ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.18
Committed: Fri Jun 10 20:38:38 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.17: +3 -2 lines
Log Message:
Fixed array overrun with large number of modifiers

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: rtcontrib.c,v 1.17 2005/06/10 16:42:11 greg Exp $";
3 #endif
4 /*
5 * Gather rtrace output to compute contributions from particular sources
6 */
7
8 #include "standard.h"
9 #include <ctype.h>
10 #include <signal.h>
11 #include "platform.h"
12 #include "rtprocess.h"
13 #include "selcall.h"
14 #include "color.h"
15 #include "resolu.h"
16 #include "lookup.h"
17 #include "calcomp.h"
18
19 #define MAXMODLIST 1024 /* maximum modifiers we'll track */
20
21 int treebufsiz = BUFSIZ; /* current tree buffer size */
22
23 typedef double DCOLOR[3]; /* double-precision color */
24
25 /*
26 * The modcont structure is used to accumulate ray contributions
27 * for a particular modifier, which may be subdivided into bins
28 * if binv is non-NULL. If outspec contains a %s in it, this will
29 * be replaced with the modifier name. If outspec contains a %d in it,
30 * this will be used to create one output file per bin, otherwise all bins
31 * will be written to the same file, in order. If the global outfmt
32 * is 'c', then a 4-byte RGBE pixel will be output for each bin value
33 * and the file will conform to a RADIANCE image if xres & yres are set.
34 */
35 typedef struct {
36 const char *outspec; /* output file specification */
37 const char *modname; /* modifier name */
38 EPNODE *binv; /* bin value expression */
39 int nbins; /* number of accumulation bins */
40 DCOLOR cbin[1]; /* contribution bins (extends struct) */
41 } MODCONT; /* modifier contribution */
42
43 static void mcfree(void *p) { epfree((*(MODCONT *)p).binv); free(p); }
44
45 LUTAB modconttab = LU_SINIT(NULL,mcfree); /* modifier lookup table */
46
47 /* close output stream */
48 static void closefile(void *p) { fclose((FILE *)p); }
49
50 LUTAB ofiletab = LU_SINIT(free,closefile); /* output file table */
51
52 #define OF_MODIFIER 01
53 #define OF_BIN 02
54
55 FILE *getofile(const char *ospec, const char *mname, int bn);
56 int ofname(char *oname, const char *ospec, const char *mname, int bn);
57 void printheader(FILE *fout, const char *info);
58
59 /*
60 * The rcont structure is used to manage i/o with a particular
61 * rtrace child process. Input is passed unchanged from stdin,
62 * and output is processed in input order and accumulated according
63 * to the corresponding modifier and bin number.
64 */
65 struct rtproc {
66 struct rtproc *next; /* next in list of processes */
67 SUBPROC pd; /* rtrace pipe descriptors */
68 unsigned long raynum; /* ray number for this tree */
69 int bsiz; /* ray tree buffer length */
70 char *buf; /* ray tree buffer */
71 int nbr; /* number of bytes from rtrace */
72 }; /* rtrace process buffer */
73
74 /* rtrace command and defaults */
75 char *rtargv[256+2*MAXMODLIST] = { "rtrace",
76 "-dj", ".5", "-dr", "3",
77 "-ab", "1", "-ad", "128", };
78 int rtargc = 9;
79 /* overriding rtrace options */
80 char *myrtopts[] = { "-o~~TmWdp", "-h-", "-x", "1", "-y", "0",
81 "-dt", "0", "-as", "0", "-aa", "0", NULL };
82
83 struct rtproc rt0; /* head of rtrace process list */
84
85 struct rtproc *rt_unproc = NULL; /* unprocessed ray trees */
86
87 char persistfn[] = "pfXXXXXX"; /* persist file name */
88
89 int gargc; /* global argc */
90 char **gargv; /* global argv */
91 #define progname gargv[0]
92
93 char *octree; /* global octree argument */
94
95 int inpfmt = 'a'; /* input format */
96 int outfmt = 'a'; /* output format */
97
98 int header = 1; /* output header? */
99 int xres = 0; /* horiz. output resolution */
100 int yres = 0; /* vert. output resolution */
101
102 unsigned long raysleft; /* number of rays left to trace */
103 long waitflush; /* how long until next flush */
104
105 unsigned long lastray = 0; /* last ray number sent */
106 unsigned long lastdone = 0; /* last ray processed */
107
108 int using_stdout = 0; /* are we using stdout? */
109
110 const char *modname[MAXMODLIST]; /* ordered modifier name list */
111 int nmods = 0; /* number of modifiers */
112
113 MODCONT *addmodifier(char *modn, char *outf, char *binv);
114 void addmodfile(char *fname, char *outf, char *binv);
115
116 void init(int np);
117 int done_rprocs(struct rtproc *rtp);
118 void recover_output(FILE *fin);
119 void trace_contribs(FILE *fin);
120 struct rtproc *wait_rproc(void);
121 struct rtproc *get_rproc(void);
122 void queue_raytree(struct rtproc *rtp);
123 void process_queue(void);
124
125 void put_contrib(const DCOLOR cnt, FILE *fout);
126 void add_contrib(const char *modn);
127 void done_contrib(void);
128
129 /* set input/output format */
130 static void
131 setformat(const char *fmt)
132 {
133 switch (fmt[0]) {
134 case 'f':
135 case 'd':
136 SET_FILE_BINARY(stdin);
137 /* fall through */
138 case 'a':
139 inpfmt = fmt[0];
140 break;
141 default:
142 goto fmterr;
143 }
144 switch (fmt[1]) {
145 case '\0':
146 outfmt = inpfmt;
147 return;
148 case 'a':
149 case 'f':
150 case 'd':
151 case 'c':
152 outfmt = fmt[1];
153 break;
154 default:
155 goto fmterr;
156 }
157 if (!fmt[2])
158 return;
159 fmterr:
160 sprintf(errmsg, "Illegal i/o format: -f%s", fmt);
161 error(USER, errmsg);
162 }
163
164 /* gather rays from rtrace and output contributions */
165 int
166 main(int argc, char *argv[])
167 {
168 int nprocs = 1;
169 int recover = 0;
170 char *curout = NULL;
171 char *binval = NULL;
172 char fmt[8];
173 int i, j;
174 /* global program name */
175 gargv = argv;
176 /* initialize calcomp routines */
177 esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
178 esupport &= ~(E_OUTCHAN);
179 varset("PI", ':', PI);
180 /* get our options */
181 for (i = 1; i < argc-1; i++) {
182 /* expand arguments */
183 while ((j = expandarg(&argc, &argv, i)) > 0)
184 ;
185 if (j < 0) {
186 fprintf(stderr, "%s: cannot expand '%s'",
187 argv[0], argv[i]);
188 exit(1);
189 }
190 if (argv[i][0] == '-')
191 switch (argv[i][1]) {
192 case 'r': /* recover output */
193 if (argv[i][2]) break;
194 recover++;
195 continue;
196 case 'n': /* number of processes */
197 if (argv[i][2] || i >= argc-1) break;
198 nprocs = atoi(argv[++i]);
199 if (nprocs <= 0)
200 error(USER, "illegal number of processes");
201 continue;
202 case 'h': /* output header? */
203 switch (argv[i][2]) {
204 case '\0':
205 header = !header;
206 continue;
207 case '+': case '1':
208 case 'T': case 't':
209 case 'Y': case 'y':
210 header = 1;
211 continue;
212 case '-': case '0':
213 case 'F': case 'f':
214 case 'N': case 'n':
215 header = 0;
216 continue;
217 }
218 break;
219 case 'f': /* file or i/o format */
220 if (!argv[i][2]) {
221 char *fpath;
222 if (i >= argc-1) break;
223 fpath = getpath(argv[++i],
224 getrlibpath(), R_OK);
225 if (fpath == NULL) {
226 sprintf(errmsg,
227 "cannot find file '%s'",
228 argv[i]);
229 error(USER, errmsg);
230 }
231 fcompile(fpath);
232 continue;
233 }
234 setformat(argv[i]+2);
235 continue;
236 case 'e': /* expression */
237 if (argv[i][2] || i >= argc-1) break;
238 scompile(argv[++i], NULL, 0);
239 continue;
240 case 'o': /* output file spec. */
241 if (argv[i][2] || i >= argc-1) break;
242 curout = argv[++i];
243 continue;
244 case 'x': /* horiz. output resolution */
245 if (argv[i][2] || i >= argc-1) break;
246 xres = atoi(argv[++i]);
247 continue;
248 case 'y': /* vert. output resolution */
249 if (argv[i][2] || i >= argc-1) break;
250 yres = atoi(argv[++i]);
251 continue;
252 case 'b': /* bin expression */
253 if (argv[i][2] || i >= argc-1) break;
254 binval = argv[++i];
255 continue;
256 case 'm': /* modifier name */
257 if (argv[i][2] || i >= argc-1) break;
258 rtargv[rtargc++] = "-ti";
259 rtargv[rtargc++] = argv[++i];
260 addmodifier(argv[i], curout, binval);
261 continue;
262 case 'M': /* modifier file */
263 if (argv[i][2] || i >= argc-1) break;
264 addmodfile(argv[++i], curout, binval);
265 continue;
266 }
267 rtargv[rtargc++] = argv[i]; /* assume rtrace option */
268 }
269 /* set global argument list */
270 gargc = argc; gargv = argv;
271 /* add "mandatory" rtrace settings */
272 for (j = 0; myrtopts[j] != NULL; j++)
273 rtargv[rtargc++] = myrtopts[j];
274 /* just asking for defaults? */
275 if (!strcmp(argv[i], "-defaults")) {
276 char sxres[16], syres[16];
277 char *rtpath;
278 printf("-n %-2d\t\t\t\t# number of processes\n", nprocs);
279 fflush(stdout); /* report OUR options */
280 rtargv[rtargc++] = header ? "-h+" : "-h-";
281 sprintf(fmt, "-f%c%c", inpfmt, outfmt);
282 rtargv[rtargc++] = fmt;
283 rtargv[rtargc++] = "-x";
284 sprintf(sxres, "%d", xres);
285 rtargv[rtargc++] = sxres;
286 rtargv[rtargc++] = "-y";
287 sprintf(syres, "%d", yres);
288 rtargv[rtargc++] = syres;
289 rtargv[rtargc++] = "-oTW";
290 rtargv[rtargc++] = "-defaults";
291 rtargv[rtargc] = NULL;
292 rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
293 if (rtpath == NULL) {
294 eputs(rtargv[0]);
295 eputs(": command not found\n");
296 exit(1);
297 }
298 execv(rtpath, rtargv);
299 perror(rtpath); /* execv() should not return */
300 exit(1);
301 }
302 if (nprocs > 1) { /* add persist file if parallel */
303 rtargv[rtargc++] = "-PP";
304 rtargv[rtargc++] = mktemp(persistfn);
305 }
306 /* add format string */
307 sprintf(fmt, "-f%cf", inpfmt);
308 rtargv[rtargc++] = fmt;
309 /* octree argument is last */
310 if (i <= 0 || i != argc-1 || argv[i][0] == '-')
311 error(USER, "missing octree argument");
312 rtargv[rtargc++] = octree = argv[i];
313 rtargv[rtargc] = NULL;
314 /* start rtrace & compute contributions */
315 init(nprocs);
316 if (recover) /* perform recovery if requested */
317 recover_output(stdin);
318 trace_contribs(stdin);
319 quit(0);
320 }
321
322 /* kill persistent rtrace process */
323 static void
324 killpersist(void)
325 {
326 FILE *fp = fopen(persistfn, "r");
327 int pid;
328
329 if (fp == NULL)
330 return;
331 if (fscanf(fp, "%*s %d", &pid) != 1 || kill(pid, SIGALRM) < 0)
332 unlink(persistfn);
333 fclose(fp);
334 }
335
336 /* close rtrace processes and clean up */
337 int
338 done_rprocs(struct rtproc *rtp)
339 {
340 int st0, st1 = 0;
341
342 if (rtp->next != NULL) { /* close last opened first! */
343 st1 = done_rprocs(rtp->next);
344 free((void *)rtp->next);
345 rtp->next = NULL;
346 }
347 st0 = close_process(&rtp->pd);
348 if (st0 < 0)
349 error(WARNING, "unknown return status from rtrace process");
350 else if (st0 > 0)
351 return(st0);
352 return(st1);
353 }
354
355 /* exit with status */
356 void
357 quit(int status)
358 {
359 int rtstat;
360
361 if (rt0.next != NULL) /* terminate persistent rtrace */
362 killpersist();
363 /* clean up rtrace process(es) */
364 rtstat = done_rprocs(&rt0);
365 if (status == 0)
366 status = rtstat;
367 exit(status); /* flushes all output streams */
368 }
369
370 /* start rtrace processes and initialize */
371 void
372 init(int np)
373 {
374 struct rtproc *rtp;
375 int i;
376 int maxbytes;
377 /* make sure we have something to do */
378 if (!nmods)
379 error(USER, "No modifiers specified");
380 /* assign ray variables */
381 scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
382 scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
383 /* set up signal handling */
384 signal(SIGINT, quit);
385 #ifdef SIGHUP
386 signal(SIGHUP, quit);
387 #endif
388 #ifdef SIGTERM
389 signal(SIGTERM, quit);
390 #endif
391 #ifdef SIGPIPE
392 signal(SIGPIPE, quit);
393 #endif
394 rtp = &rt0; /* start rtrace process(es) */
395 for (i = 0; i++ < np; ) {
396 errno = 0;
397 maxbytes = open_process(&rtp->pd, rtargv);
398 if (maxbytes == 0) {
399 eputs(rtargv[0]);
400 eputs(": command not found\n");
401 exit(1);
402 }
403 if (maxbytes < 0)
404 error(SYSTEM, "cannot start rtrace process");
405 if (maxbytes > treebufsiz)
406 treebufsiz = maxbytes;
407 rtp->raynum = 0;
408 rtp->bsiz = 0;
409 rtp->buf = NULL;
410 rtp->nbr = 0;
411 if (i == np) /* last process? */
412 break;
413 if (i == 1)
414 sleep(2); /* wait for persist file */
415 rtp->next = (struct rtproc *)malloc(sizeof(struct rtproc));
416 if (rtp->next == NULL)
417 error(SYSTEM, "out of memory in init");
418 rtp = rtp->next;
419 }
420 rtp->next = NULL; /* terminate list */
421 if (yres > 0) {
422 if (xres > 0)
423 raysleft = (unsigned long)xres*yres;
424 else
425 raysleft = yres;
426 } else
427 raysleft = 0;
428 waitflush = xres;
429 }
430
431 /* add modifier to our list to track */
432 MODCONT *
433 addmodifier(char *modn, char *outf, char *binv)
434 {
435 LUENT *lep = lu_find(&modconttab, modn);
436 MODCONT *mp;
437
438 if (lep->data != NULL) {
439 sprintf(errmsg, "duplicate modifier '%s'", modn);
440 error(USER, errmsg);
441 }
442 if (nmods >= MAXMODLIST)
443 error(USER, "too many modifiers");
444 modname[nmods++] = modn; /* XXX assumes static string */
445 lep->key = modn; /* XXX assumes static string */
446 mp = (MODCONT *)malloc(sizeof(MODCONT));
447 if (mp == NULL)
448 error(SYSTEM, "out of memory in addmodifier");
449 lep->data = (char *)mp;
450 mp->outspec = outf; /* XXX assumes static string */
451 mp->modname = modn; /* XXX assumes static string */
452 if (binv != NULL)
453 mp->binv = eparse(binv);
454 else
455 mp->binv = eparse("0");
456 mp->nbins = 1;
457 setcolor(mp->cbin[0], 0., 0., 0.);
458 return mp;
459 }
460
461 /* add modifiers from a file list */
462 void
463 addmodfile(char *fname, char *outf, char *binv)
464 {
465 char *mname[MAXMODLIST];
466 int i;
467 /* load the file & store strings */
468 wordfile(mname, fname);
469 for (i = 0; mname[i]; i++) /* add each one */
470 addmodifier(mname[i], outf, binv);
471 }
472
473 /* put string to stderr */
474 void
475 eputs(char *s)
476 {
477 static int midline = 0;
478
479 if (!*s) return;
480 if (!midline) {
481 fputs(progname, stderr);
482 fputs(": ", stderr);
483 }
484 fputs(s, stderr);
485 midline = s[strlen(s)-1] != '\n';
486 }
487
488 /* construct output file name and return flags whether modifier/bin present */
489 int
490 ofname(char *oname, const char *ospec, const char *mname, int bn)
491 {
492 const char *mnp = NULL;
493 const char *bnp = NULL;
494 const char *cp;
495
496 if (ospec == NULL)
497 return -1;
498 for (cp = ospec; *cp; cp++) /* check format position(s) */
499 if (*cp == '%') {
500 do
501 ++cp;
502 while (isdigit(*cp));
503 switch (*cp) {
504 case '%':
505 break;
506 case 's':
507 if (mnp != NULL)
508 return -1;
509 mnp = cp;
510 break;
511 case 'd':
512 if (bnp != NULL)
513 return -1;
514 bnp = cp;
515 break;
516 default:
517 return -1;
518 }
519 }
520 if (mnp != NULL) { /* create file name */
521 if (bnp != NULL) {
522 if (bnp > mnp)
523 sprintf(oname, ospec, mname, bn);
524 else
525 sprintf(oname, ospec, bn, mname);
526 return OF_MODIFIER|OF_BIN;
527 }
528 sprintf(oname, ospec, mname);
529 return OF_MODIFIER;
530 }
531 if (bnp != NULL) {
532 sprintf(oname, ospec, bn);
533 return OF_BIN;
534 }
535 strcpy(oname, ospec);
536 return 0;
537 }
538
539 /* write header to the given output stream */
540 void
541 printheader(FILE *fout, const char *info)
542 {
543 extern char VersionID[];
544 FILE *fin = fopen(octree, "r");
545
546 if (fin == NULL)
547 quit(1);
548 checkheader(fin, "ignore", fout); /* copy octree header */
549 fclose(fin);
550 printargs(gargc-1, gargv, fout); /* add our command */
551 fprintf(fout, "SOFTWARE= %s\n", VersionID);
552 fputnow(fout);
553 if (info != NULL) /* add extra info if given */
554 fputs(info, fout);
555 switch (outfmt) { /* add output format */
556 case 'a':
557 fputformat("ascii", fout);
558 break;
559 case 'f':
560 fputformat("float", fout);
561 break;
562 case 'd':
563 fputformat("double", fout);
564 break;
565 case 'c':
566 fputformat(COLRFMT, fout);
567 break;
568 }
569 fputc('\n', fout);
570 if (xres > 0) {
571 if (yres > 0) /* resolution string */
572 fprtresolu(xres, yres, fout);
573 fflush(fout);
574 }
575 }
576
577 /* Get output file pointer (open and write header if new) */
578 FILE *
579 getofile(const char *ospec, const char *mname, int bn)
580 {
581 int ofl;
582 char oname[1024];
583 LUENT *lep;
584
585 if (ospec == NULL) { /* use stdout? */
586 if (!using_stdout) {
587 if (outfmt != 'a')
588 SET_FILE_BINARY(stdout);
589 if (header)
590 printheader(stdout, NULL);
591 }
592 using_stdout = 1;
593 return stdout;
594 }
595 ofl = ofname(oname, ospec, mname, bn); /* get output name */
596 if (ofl < 0) {
597 sprintf(errmsg, "bad output format '%s'", ospec);
598 error(USER, errmsg);
599 }
600 lep = lu_find(&ofiletab, oname); /* look it up */
601 if (lep->key == NULL) /* new entry */
602 lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
603 if (lep->data == NULL) { /* open output file */
604 FILE *fp;
605 int i;
606 if (oname[0] == '!') /* output to command */
607 fp = popen(oname+1, "w");
608 else
609 fp = fopen(oname, "w");
610 if (fp == NULL) {
611 sprintf(errmsg, "cannot open '%s' for writing", oname);
612 error(SYSTEM, errmsg);
613 }
614 if (outfmt != 'a')
615 SET_FILE_BINARY(fp);
616 if (header) {
617 char info[512];
618 char *cp = info;
619 if (ofl & OF_MODIFIER) {
620 sprintf(cp, "MODIFIER=%s\n", mname);
621 while (*cp) ++cp;
622 }
623 if (ofl & OF_BIN) {
624 sprintf(cp, "BIN=%d\n", bn);
625 while (*cp) ++cp;
626 }
627 *cp = '\0';
628 printheader(fp, info);
629 }
630 /* play catch-up */
631 for (i = 0; i < lastdone; i++) {
632 static const DCOLOR nocontrib = BLKCOLOR;
633 put_contrib(nocontrib, fp);
634 if (outfmt == 'a')
635 putc('\n', fp);
636 }
637 if (xres > 0)
638 fflush(fp);
639 lep->data = (char *)fp;
640 }
641 return (FILE *)lep->data; /* return open file pointer */
642 }
643
644 /* read input ray into buffer */
645 int
646 getinp(char *buf, FILE *fp)
647 {
648 char *cp;
649 int i;
650
651 switch (inpfmt) {
652 case 'a':
653 cp = buf; /* make sure we get 6 floats */
654 for (i = 0; i < 6; i++) {
655 if (fgetword(cp, buf+127-cp, fp) == NULL)
656 return 0;
657 if ((cp = fskip(cp)) == NULL || *cp)
658 return 0;
659 *cp++ = ' ';
660 }
661 getc(fp); /* get/put eol */
662 *cp-- = '\0'; *cp = '\n';
663 return strlen(buf);
664 case 'f':
665 if (fread(buf, sizeof(float), 6, fp) < 6)
666 return 0;
667 return sizeof(float)*6;
668 case 'd':
669 if (fread(buf, sizeof(double), 6, fp) < 6)
670 return 0;
671 return sizeof(double)*6;
672 }
673 error(INTERNAL, "botched input format");
674 return 0; /* pro forma return */
675 }
676
677 static float rparams[9]; /* traced ray parameters */
678
679 /* return channel (ray) value */
680 double
681 chanvalue(int n)
682 {
683 if (--n < 0 || n >= 6)
684 error(USER, "illegal channel number ($N)");
685 return rparams[n+3];
686 }
687
688 /* add current ray contribution to the appropriate modifier bin */
689 void
690 add_contrib(const char *modn)
691 {
692 LUENT *le = lu_find(&modconttab, modn);
693 MODCONT *mp = (MODCONT *)le->data;
694 int bn;
695
696 if (mp == NULL) {
697 sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
698 error(USER, errmsg);
699 }
700 eclock++; /* get bin number */
701 bn = (int)(evalue(mp->binv) + .5);
702 if (bn <= 0)
703 bn = 0;
704 else if (bn > mp->nbins) { /* new bin */
705 mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
706 bn*sizeof(DCOLOR));
707 if (mp == NULL)
708 error(SYSTEM, "out of memory in add_contrib");
709 memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(bn+1-mp->nbins));
710 mp->nbins = bn+1;
711 le->data = (char *)mp;
712 }
713 addcolor(mp->cbin[bn], rparams);
714 }
715
716 /* output newline to ASCII file and/or flush as requested */
717 static int
718 puteol(const LUENT *e, void *p)
719 {
720 FILE *fp = (FILE *)e->data;
721
722 if (outfmt == 'a')
723 putc('\n', fp);
724 if (!waitflush)
725 fflush(fp);
726 if (ferror(fp)) {
727 sprintf(errmsg, "write error on file '%s'", e->key);
728 error(SYSTEM, errmsg);
729 }
730 return 0;
731 }
732
733 /* put out ray contribution to file */
734 void
735 put_contrib(const DCOLOR cnt, FILE *fout)
736 {
737 float fv[3];
738 COLR cv;
739
740 switch (outfmt) {
741 case 'a':
742 fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
743 break;
744 case 'f':
745 fv[0] = cnt[0];
746 fv[1] = cnt[1];
747 fv[2] = cnt[2];
748 fwrite(fv, sizeof(float), 3, fout);
749 break;
750 case 'd':
751 fwrite(cnt, sizeof(double), 3, fout);
752 break;
753 case 'c':
754 setcolr(cv, cnt[0], cnt[1], cnt[2]);
755 fwrite(cv, sizeof(cv), 1, fout);
756 break;
757 default:
758 error(INTERNAL, "botched output format");
759 }
760 }
761
762 /* output ray tallies and clear for next primary */
763 void
764 done_contrib(void)
765 {
766 int i, j;
767 MODCONT *mp;
768 FILE *fp;
769 /* output modifiers in order */
770 for (i = 0; i < nmods; i++) {
771 mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
772 fp = getofile(mp->outspec, mp->modname, 0);
773 put_contrib(mp->cbin[0], fp);
774 if (mp->nbins > 3 && /* minor optimization */
775 fp == getofile(mp->outspec, mp->modname, 1))
776 for (j = 1; j < mp->nbins; j++)
777 put_contrib(mp->cbin[j], fp);
778 else
779 for (j = 1; j < mp->nbins; j++)
780 put_contrib(mp->cbin[j],
781 getofile(mp->outspec, mp->modname, j));
782 /* clear for next ray tree */
783 memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
784 }
785 --waitflush; /* terminate records */
786 lu_doall(&ofiletab, puteol, NULL);
787 if (using_stdout & (outfmt == 'a'))
788 putc('\n', stdout);
789 if (!waitflush) {
790 waitflush = xres;
791 if (using_stdout)
792 fflush(stdout);
793 }
794 }
795
796 /* queue completed ray tree produced by rtrace process */
797 void
798 queue_raytree(struct rtproc *rtp)
799 {
800 struct rtproc *rtu, *rtl = NULL;
801 /* insert following ray order */
802 for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
803 if (rtp->raynum < rtu->raynum)
804 break;
805 rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
806 if (rtu == NULL)
807 error(SYSTEM, "out of memory in queue_raytree");
808 *rtu = *rtp;
809 if (rtl == NULL) {
810 rtu->next = rt_unproc;
811 rt_unproc = rtu;
812 } else {
813 rtu->next = rtl->next;
814 rtl->next = rtu;
815 }
816 rtp->raynum = 0; /* clear path for next ray tree */
817 rtp->bsiz = 0;
818 rtp->buf = NULL;
819 rtp->nbr = 0;
820 }
821
822 /* process completed ray trees from our queue */
823 void
824 process_queue(void)
825 {
826 char modname[128];
827 /* ray-ordered queue */
828 while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
829 struct rtproc *rtp = rt_unproc;
830 int n = rtp->nbr;
831 const char *cp = rtp->buf;
832 while (n > 0) { /* process rays */
833 register char *mnp = modname;
834 /* skip leading tabs */
835 while (n > 0 && *cp == '\t') {
836 cp++; n--;
837 }
838 if (!n || !(isalpha(*cp) | (*cp == '_')))
839 error(USER, "bad modifier name from rtrace");
840 /* get modifier name */
841 while (n > 0 && *cp != '\t') {
842 *mnp++ = *cp++; n--;
843 }
844 *mnp = '\0';
845 cp++; n--; /* eat following tab */
846 if (n < (int)(sizeof(float)*9))
847 error(USER, "incomplete ray value from rtrace");
848 /* add ray contribution */
849 memcpy(rparams, cp, sizeof(float)*9);
850 cp += sizeof(float)*9; n -= sizeof(float)*9;
851 add_contrib(modname);
852 }
853 done_contrib(); /* sum up contributions & output */
854 lastdone = rtp->raynum;
855 free(rtp->buf); /* free up buffer space */
856 rt_unproc = rtp->next;
857 free(rtp); /* done with this ray tree */
858 }
859 }
860
861 /* wait for rtrace process to finish with ray tree */
862 struct rtproc *
863 wait_rproc(void)
864 {
865 struct rtproc *rtfree = NULL;
866 fd_set readset, errset;
867 int nr;
868 struct rtproc *rt;
869 int n;
870
871 do {
872 nr = 0; /* prepare select call */
873 FD_ZERO(&readset); FD_ZERO(&errset); n = 0;
874 for (rt = &rt0; rt != NULL; rt = rt->next) {
875 if (rt->raynum) {
876 FD_SET(rt->pd.r, &readset);
877 ++nr;
878 }
879 FD_SET(rt->pd.r, &errset);
880 if (rt->pd.r >= n)
881 n = rt->pd.r + 1;
882 }
883 if (!nr) /* no rays pending */
884 break;
885 if (nr > 1) { /* call select for multiple proc's */
886 errno = 0;
887 if (select(n, &readset, NULL, &errset, NULL) < 0)
888 error(SYSTEM, "select call error in wait_rproc()");
889 } else
890 FD_ZERO(&errset);
891 nr = 0;
892 for (rt = &rt0; rt != NULL; rt = rt->next) {
893 if (!FD_ISSET(rt->pd.r, &readset) &&
894 !FD_ISSET(rt->pd.r, &errset))
895 continue;
896 if (rt->buf == NULL) {
897 rt->bsiz = treebufsiz;
898 rt->buf = (char *)malloc(treebufsiz);
899 } else if (rt->nbr + BUFSIZ > rt->bsiz) {
900 if (rt->bsiz + BUFSIZ <= treebufsiz)
901 rt->bsiz = treebufsiz;
902 else
903 rt->bsiz = treebufsiz += BUFSIZ;
904 rt->buf = (char *)realloc(rt->buf, rt->bsiz);
905 }
906 if (rt->buf == NULL)
907 error(SYSTEM, "out of memory in wait_rproc");
908 nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
909 if (nr <= 0)
910 error(USER, "rtrace process died");
911 rt->nbr += nr; /* advance & check */
912 if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
913 "~\t~\t", 4)) {
914 rt->nbr -= 4; /* elide terminator */
915 queue_raytree(rt);
916 rtfree = rt; /* ready for next ray */
917 }
918 }
919 } while ((rtfree == NULL) & (nr > 0)); /* repeat until ready or out */
920 return rtfree;
921 }
922
923 /* return next available rtrace process */
924 struct rtproc *
925 get_rproc(void)
926 {
927 struct rtproc *rtp;
928 /* check for idle rtrace */
929 for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
930 if (!rtp->raynum)
931 return rtp;
932 return wait_rproc(); /* need to wait for one */
933 }
934
935 /* trace ray contributions (main loop) */
936 void
937 trace_contribs(FILE *fin)
938 {
939 char inpbuf[128];
940 int iblen;
941 struct rtproc *rtp;
942 /* loop over input */
943 while ((iblen = getinp(inpbuf, fin)) > 0) {
944 if (lastray+1 < lastray) { /* counter rollover? */
945 while (wait_rproc() != NULL)
946 process_queue();
947 lastdone = lastray = 0;
948 }
949 rtp = get_rproc(); /* get avail. rtrace process */
950 rtp->raynum = ++lastray; /* assign ray to it */
951 writebuf(rtp->pd.w, inpbuf, iblen);
952 if (raysleft && !--raysleft)
953 break;
954 process_queue(); /* catch up with results */
955 }
956 while (wait_rproc() != NULL) /* process outstanding rays */
957 process_queue();
958 if (raysleft)
959 error(USER, "unexpected EOF on input");
960 lu_done(&ofiletab); /* close output files */
961 }
962
963 /* seek on the given output file */
964 static int
965 myseeko(const LUENT *e, void *p)
966 {
967 if (fseeko((FILE *)e->data, *(off_t *)p, SEEK_CUR) < 0) {
968 sprintf(errmsg, "seek error on file '%s'", e->key);
969 error(SYSTEM, errmsg);
970 }
971 }
972
973 /* recover output if possible */
974 void
975 recover_output(FILE *fin)
976 {
977 off_t lastout = -1;
978 int outvsiz;
979 char *outvfmt;
980 int i, j;
981 MODCONT *mp;
982 int ofl;
983 char oname[1024];
984 LUENT *ment, *oent;
985 FILE *fp;
986 off_t nvals;
987
988 switch (outfmt) {
989 case 'a':
990 error(USER, "cannot recover ASCII output");
991 return;
992 case 'f':
993 outvsiz = sizeof(float)*3;
994 outvfmt = "float";
995 break;
996 case 'd':
997 outvsiz = sizeof(double)*3;
998 outvfmt = "double";
999 break;
1000 case 'c':
1001 outvsiz = sizeof(COLR);
1002 outvfmt = COLRFMT;
1003 break;
1004 default:
1005 error(INTERNAL, "botched output format");
1006 return;
1007 }
1008 /* check modifier outputs */
1009 for (i = 0; i < nmods; i++) {
1010 ment = lu_find(&modconttab,modname[i]);
1011 mp = (MODCONT *)ment->data;
1012 if (mp->outspec == NULL)
1013 error(USER, "cannot recover from stdout");
1014 for (j = 0; ; j++) { /* check each bin's file */
1015 ofl = ofname(oname, mp->outspec, mp->modname, j);
1016 if (ofl < 0)
1017 error(USER, "bad output file specification");
1018 oent = lu_find(&ofiletab, oname);
1019 if (oent->data != NULL) { /* saw this one already */
1020 if (ofl & OF_BIN)
1021 continue;
1022 break;
1023 }
1024 if (oname[0] == '!')
1025 error(USER, "cannot recover from command");
1026 /* open output */
1027 fp = fopen(oname, "rb+");
1028 if (fp == NULL)
1029 break; /* must be end of modifier */
1030 nvals = lseek(fileno(fp), 0, SEEK_END);
1031 if (nvals <= 0) {
1032 lastout = 0; /* empty output, quit here */
1033 fclose(fp);
1034 break;
1035 }
1036 lseek(fileno(fp), 0, SEEK_SET);
1037 if (header) {
1038 int xr, yr;
1039 if (checkheader(fp, outvfmt, NULL) != 1) {
1040 sprintf(errmsg,
1041 "format mismatch for '%s'",
1042 oname);
1043 error(USER, errmsg);
1044 }
1045 if (xres > 0 && yres > 0 &&
1046 (!fscnresolu(&xr, &yr, fp) ||
1047 xr != xres ||
1048 yr != yres)) {
1049 sprintf(errmsg,
1050 "resolution mismatch for '%s'",
1051 oname);
1052 error(USER, errmsg);
1053 }
1054 }
1055 nvals = (nvals - (off_t)ftell(fp)) / outvsiz;
1056 if (lastout < 0 || nvals < lastout)
1057 lastout = nvals;
1058 if (oent->key == NULL) /* new entry */
1059 oent->key = strcpy((char *)
1060 malloc(strlen(oname)+1), oname);
1061 oent->data = (char *)fp;
1062 if (!(ofl & OF_BIN))
1063 break; /* no bin separation */
1064 }
1065 if (!lastout) { /* empty output */
1066 error(WARNING, "no previous data to recover");
1067 lu_done(&ofiletab); /* reclose all outputs */
1068 return;
1069 }
1070 if (j > mp->nbins) { /* preallocate modifier bins */
1071 mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
1072 (j-1)*sizeof(DCOLOR));
1073 if (mp == NULL)
1074 error(SYSTEM, "out of memory in recover_output");
1075 memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
1076 mp->nbins = j;
1077 ment->data = (char *)mp;
1078 }
1079 }
1080 if (lastout < 0) {
1081 error(WARNING, "no output files to recover");
1082 return;
1083 }
1084 /* seek on all files */
1085 nvals = lastout * outvsiz;
1086 lu_doall(&ofiletab, myseeko, &nvals);
1087 /* discard input */
1088 for (nvals = 0; nvals < lastout; nvals++)
1089 if (getinp(oname, fin) <= 0)
1090 error(USER, "unexpected EOF on input");
1091 lastray = lastdone = (unsigned long)lastout;
1092 if (raysleft)
1093 raysleft -= lastray;
1094 }