ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
Revision: 1.25
Committed: Tue Sep 13 22:58:22 2005 UTC (18 years, 7 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 1.24: +8 -1 lines
Log Message:
Added check for no arguments

File Contents

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