ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.29
Committed: Wed Oct 5 05:20:21 2005 UTC (18 years, 6 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.28: +17 -2 lines
Log Message:
Bug fix for some systems where rtrace process gets stuck for unknown reasons

File Contents

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