ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.12
Committed: Fri Jun 3 14:29:42 2005 UTC (18 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.11: +11 -3 lines
Log Message:
Minor optimization to reduce calls to getofile()

File Contents

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