ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.5
Committed: Thu May 26 21:35:35 2005 UTC (18 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.4: +10 -9 lines
Log Message:
Minor code tweaks

File Contents

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