ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.19
Committed: Fri Jun 10 20:44:00 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.18: +6 -2 lines
Log Message:
Fixe in rtcontrib -M option

File Contents

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