ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.9
Committed: Wed Jun 1 16:11:01 2005 UTC (18 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.8: +11 -2 lines
Log Message:
Added RAYPATH directory searching to rtcontrib -f option

File Contents

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