ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/util/rtcontrib.c
(Generate patch)

Comparing ray/src/util/rtcontrib.c (file contents):
Revision 1.1 by greg, Wed May 25 04:45:22 2005 UTC vs.
Revision 1.59 by greg, Sun Oct 10 01:26:51 2010 UTC

# Line 5 | Line 5 | static const char RCSid[] = "$Id$";
5   * Gather rtrace output to compute contributions from particular sources
6   */
7  
8 + #include  "standard.h"
9   #include  <ctype.h>
10 < #include  "rtio.h"
10 < #include  "rterror.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  "random.h"
18   #include  "calcomp.h"
19  
20 < #ifdef getc_unlocked            /* avoid horrendous overhead of flockfile */
21 < #undef getc
21 < #undef putc
22 < #define getc    getc_unlocked
23 < #define putc    putc_unlocked
24 < #define ferror  ferror_unlocked
20 > #ifndef MAXMODLIST
21 > #define MAXMODLIST      1024            /* maximum modifiers we'll track */
22   #endif
23  
24 < #define MAXMODLIST      1024            /* maximum modifiers we'll track */
24 > size_t  treebufsiz = BUFSIZ;            /* current tree buffer size */
25  
26 < int     treebufsiz = BUFSIZ;            /* current tree buffer size */
26 > typedef double  DCOLOR[3];              /* double-precision color */
27  
28   /*
29 < * The modcont structure is used to accumulate ray contributions
29 > * The MODCONT structure is used to accumulate ray contributions
30   * for a particular modifier, which may be subdivided into bins
31 < * if binv is non-NULL.  If outspec contains a %s in it, this will
31 > * if binv evaluates > 0.  If outspec contains a %s in it, this will
32   * be replaced with the modifier name.  If outspec contains a %d in it,
33   * this will be used to create one output file per bin, otherwise all bins
34   * will be written to the same file, in order.  If the global outfmt
# Line 43 | Line 40 | typedef struct {
40          const char      *modname;       /* modifier name */
41          EPNODE          *binv;          /* bin value expression */
42          int             nbins;          /* number of accumulation bins */
43 <        COLOR           cbin[1];        /* contribution bins (extends struct) */
43 >        DCOLOR          cbin[1];        /* contribution bins (extends struct) */
44   } MODCONT;                      /* modifier contribution */
45  
46   static void mcfree(void *p) { epfree((*(MODCONT *)p).binv); free(p); }
47  
48   LUTAB   modconttab = LU_SINIT(NULL,mcfree);     /* modifier lookup table */
49  
50 < /* close output stream */
51 < static void closefile(void *p) { fclose((FILE *)p); }
50 > /*
51 > * The STREAMOUT structure holds an open FILE pointer and a count of
52 > * the number of RGB triplets per record, or 0 if unknown.
53 > */
54 > typedef struct {
55 >        FILE            *ofp;           /* output file pointer */
56 >        int             outpipe;        /* output is to a pipe */
57 >        int             reclen;         /* triplets/record */
58 >        int             xr, yr;         /* output resolution for picture */
59 > } STREAMOUT;
60  
61 < LUTAB   ofiletab = LU_SINIT(free,closefile);    /* output file table */
61 > /* close output stream and free record */
62 > static void
63 > closestream(void *p)
64 > {
65 >        STREAMOUT       *sop = (STREAMOUT *)p;
66 >        int             status;
67 >        if (sop->outpipe)
68 >                status = pclose(sop->ofp);
69 >        else
70 >                status = fclose(sop->ofp);
71 >        if (status)
72 >                error(SYSTEM, "error closing output stream");
73 >        free(p);
74 > }
75  
76 < FILE *getofile(const char *ospec, const char *mname, int bn);
76 > LUTAB   ofiletab = LU_SINIT(free,closestream);  /* output file table */
77  
78 + #define OF_MODIFIER     01
79 + #define OF_BIN          02
80 +
81 + STREAMOUT *getostream(const char *ospec, const char *mname, int bn, int noopen);
82 + int ofname(char *oname, const char *ospec, const char *mname, int bn);
83 + void printheader(FILE *fout, const char *info);
84 + void printresolu(FILE *fout, int xr, int yr);
85 +
86   /*
87   * The rcont structure is used to manage i/o with a particular
88   * rtrace child process.  Input is passed unchanged from stdin,
# Line 66 | Line 92 | FILE *getofile(const char *ospec, const char *mname, i
92   struct rtproc {
93          struct rtproc   *next;          /* next in list of processes */
94          SUBPROC         pd;             /* rtrace pipe descriptors */
95 <        unsigned long   raynum;         /* ray number for this buffer */
96 <        int             bsiz;           /* rtrace buffer length */
97 <        char            *buf;           /* rtrace i/o buffer */
98 <        char            *bpos;          /* current buffer position */
99 < };                              /* rtrace process */
95 >        unsigned long   raynum;         /* ray number for this tree */
96 >        size_t          bsiz;           /* ray tree buffer length */
97 >        char            *buf;           /* ray tree buffer */
98 >        size_t          nbr;            /* number of bytes from rtrace */
99 > };                              /* rtrace process buffer */
100  
101                                          /* rtrace command and defaults */
102 < char            *rtargv[256] = { "rtrace", "-dj", ".5", "-dr", "3",
103 <                                "-ab", "1", "-ad", "512", };
102 > char            *rtargv[256+2*MAXMODLIST] = { "rtrace",
103 >                                "-dj", ".9", "-dr", "3",
104 >                                "-ab", "1", "-ad", "350", };
105 >
106   int  rtargc = 9;
107                                          /* overriding rtrace options */
108 < char            *myrtopts[] = { "-o-TmWdp", "-h-",
109 <                                "-x", "1", "-y", "0", NULL };
108 > char            *myrtopts[] = { "-h-", "-x", "1", "-y", "0",
109 >                                "-dt", "0", "-as", "0", "-aa", "0", NULL };
110  
111 + #define RTCOEFF         "-o~~TmWdp"     /* compute coefficients only */
112 + #define RTCONTRIB       "-o~~TmVdp"     /* compute ray contributions */
113 +
114   struct rtproc   rt0;                    /* head of rtrace process list */
115  
116   struct rtproc   *rt_unproc = NULL;      /* unprocessed ray trees */
117  
118 < char    persistfn[] = "pfXXXXXX";       /* persist file name */
119 < char    fmt[8];                         /* rtrace i/o format */
118 > #define PERSIST_NONE    0               /* no persist file */
119 > #define PERSIST_SINGLE  1               /* user set -P persist */
120 > #define PERSIST_PARALL  2               /* user set -PP persist */
121 > #define PERSIST_OURS    3               /* -PP persist belongs to us */
122 > int     persist_state = PERSIST_NONE;   /* persist file state */
123 > char    persistfn[] = "pfXXXXXX";       /* our persist file name, if set */
124  
125   int             gargc;                  /* global argc */
126   char            **gargv;                /* global argv */
# Line 97 | Line 132 | int            inpfmt = 'a';           /* input format */
132   int             outfmt = 'a';           /* output format */
133  
134   int             header = 1;             /* output header? */
135 + int             force_open = 0;         /* truncate existing output? */
136 + int             recover = 0;            /* recover previous output? */
137 + int             accumulate = 1;         /* input rays per output record */
138   int             xres = 0;               /* horiz. output resolution */
139   int             yres = 0;               /* vert. output resolution */
140  
141 < long            raysleft;               /* number of rays left to trace */
141 > int             account;                /* current accumulation count */
142 > unsigned long   raysleft;               /* number of rays left to trace */
143   long            waitflush;              /* how long until next flush */
144  
145   unsigned long   lastray = 0;            /* last ray number sent */
146   unsigned long   lastdone = 0;           /* last ray processed */
147  
148 + int             using_stdout = 0;       /* are we using stdout? */
149 +
150   const char      *modname[MAXMODLIST];   /* ordered modifier name list */
151   int             nmods = 0;              /* number of modifiers */
152  
153 < MODCONT *addmodifier(char *modn, char *outf, char *binv);
153 > #define queue_length()          (lastray - lastdone)
154  
155 < int done_rprocs(struct rtproc *rtp);
155 > MODCONT *growmodifier(MODCONT *mp, int nb);
156 > MODCONT *addmodifier(char *modn, char *outf, char *binv, int bincnt);
157 > void addmodfile(char *fname, char *outf, char *binv, int bincnt);
158 >
159   void init(int np);
160 < void tracecontribs(FILE *fp);
160 > int done_rprocs(struct rtproc *rtp);
161 > void reload_output(void);
162 > void recover_output(FILE *fin);
163 > void trace_contribs(FILE *fin);
164   struct rtproc *wait_rproc(void);
165   struct rtproc *get_rproc(void);
166 < void process_rays(struct rtproc *rtp);
166 > void queue_raytree(struct rtproc *rtp);
167 > void process_queue(void);
168  
169 < void add_contrib(const char *modn, float rayval[7]);
170 < void done_contrib(void);
169 > void put_contrib(const DCOLOR cnt, FILE *fout);
170 > void add_contrib(const char *modn);
171 > void done_contrib(int navg);
172  
173 + /* return number of open rtrace processes */
174 + static int
175 + nrtprocs(void)
176 + {
177 +        int     nrtp = 0;
178 +        struct rtproc   *rtp;
179 +
180 +        for (rtp = &rt0; rtp != NULL; rtp = rtp->next)
181 +                nrtp += rtp->pd.running;
182 +        return(nrtp);
183 + }
184 +
185   /* set input/output format */
186   static void
187   setformat(const char *fmt)
188   {
189          switch (fmt[0]) {
129        case 'a':
190          case 'f':
191          case 'd':
192 +                SET_FILE_BINARY(stdin);
193 +                /* fall through */
194 +        case 'a':
195                  inpfmt = fmt[0];
196                  break;
197          default:
# Line 158 | Line 221 | fmterr:
221   int
222   main(int argc, char *argv[])
223   {
224 +        int     contrib = 0;
225          int     nprocs = 1;
226          char    *curout = NULL;
227          char    *binval = NULL;
228 <        int     i;
229 <                                /* set global argument list */
230 <        gargc = argc;
228 >        int     bincnt = 0;
229 >        char    fmt[8];
230 >        int     i, j;
231 >                                /* need at least one argument */
232 >        if (argc < 2) {
233 >                fprintf(stderr,
234 > "Usage: %s [-n nprocs][-V][-r][-e expr][-f source][-o ospec][-b binv] {-m mod | -M file} [rtrace options] octree\n",
235 >                        argv[0]);
236 >                exit(1);
237 >        }
238 >                                /* global program name */
239          gargv = argv;
240 <                                /* set up calcomp functions */
240 >                                /* initialize calcomp routines */
241          esupport |= E_VARIABLE|E_FUNCTION|E_INCHAN|E_RCONST|E_REDEFW;
242          esupport &= ~(E_OUTCHAN);
243 +        varset("PI", ':', PI);
244                                  /* get our options */
245 <        for (i = 1; i < argc && argv[i][0] == '-'; i++) {
246 <                switch (argv[i][1]) {
247 <                case 'n':                       /* number of processes */
248 <                        if (argv[i][2] || i >= argc-1) break;
249 <                        nprocs = atoi(argv[++i]);
250 <                        if (nprocs <= 0)
251 <                                error(USER, "illegal number of processes");
252 <                        continue;
253 <                case 'h':                       /* output header? */
254 <                        switch (argv[i][2]) {
255 <                        case '\0':
256 <                                header = !header;
245 >        for (i = 1; i < argc-1; i++) {
246 >                                                /* expand arguments */
247 >                while ((j = expandarg(&argc, &argv, i)) > 0)
248 >                        ;
249 >                if (j < 0) {
250 >                        fprintf(stderr, "%s: cannot expand '%s'\n",
251 >                                        argv[0], argv[i]);
252 >                        exit(1);
253 >                }
254 >                if (argv[i][0] == '-')
255 >                        switch (argv[i][1]) {
256 >                        case 'n':               /* number of processes */
257 >                                if (argv[i][2] || i >= argc-2) break;
258 >                                nprocs = atoi(argv[++i]);
259 >                                if (nprocs <= 0)
260 >                                        error(USER, "illegal number of processes");
261                                  continue;
262 <                        case '+': case '1': case 'T': case 't':
263 <                                header = 1;
262 >                        case 'V':               /* output contributions */
263 >                                switch (argv[i][2]) {
264 >                                case '\0':
265 >                                        contrib = !contrib;
266 >                                        continue;
267 >                                case '+': case '1':
268 >                                case 'T': case 't':
269 >                                case 'Y': case 'y':
270 >                                        contrib = 1;
271 >                                        continue;
272 >                                case '-': case '0':
273 >                                case 'F': case 'f':
274 >                                case 'N': case 'n':
275 >                                        contrib = 0;
276 >                                        continue;
277 >                                }
278 >                                break;
279 >                        case 'c':               /* input rays per output */
280 >                                if (argv[i][2] || i >= argc-2) break;
281 >                                accumulate = atoi(argv[++i]);
282                                  continue;
283 <                        case '-': case '0': case 'F': case 'f':
284 <                                header = 0;
283 >                        case 'r':               /* recover output */
284 >                                if (argv[i][2]) break;
285 >                                recover = 1;
286                                  continue;
287 <                        }
288 <                        break;
289 <                case 'f':                       /* file or i/o format */
290 <                        if (!argv[i][2]) {
291 <                                if (i >= argc-1) break;
292 <                                fcompile(argv[++i]);
287 >                        case 'h':               /* output header? */
288 >                                switch (argv[i][2]) {
289 >                                case '\0':
290 >                                        header = !header;
291 >                                        continue;
292 >                                case '+': case '1':
293 >                                case 'T': case 't':
294 >                                case 'Y': case 'y':
295 >                                        header = 1;
296 >                                        continue;
297 >                                case '-': case '0':
298 >                                case 'F': case 'f':
299 >                                case 'N': case 'n':
300 >                                        header = 0;
301 >                                        continue;
302 >                                }
303 >                                break;
304 >                        case 'f':               /* file or force or format */
305 >                                if (!argv[i][2]) {
306 >                                        char    *fpath;
307 >                                        if (i >= argc-2) break;
308 >                                        fpath = getpath(argv[++i],
309 >                                                        getrlibpath(), R_OK);
310 >                                        if (fpath == NULL) {
311 >                                                sprintf(errmsg,
312 >                                                        "cannot find file '%s'",
313 >                                                                argv[i]);
314 >                                                error(USER, errmsg);
315 >                                        }
316 >                                        fcompile(fpath);
317 >                                        continue;
318 >                                }
319 >                                if (argv[i][2] == 'o') {
320 >                                        force_open = 1;
321 >                                        continue;
322 >                                }
323 >                                setformat(argv[i]+2);
324                                  continue;
325 +                        case 'e':               /* expression */
326 +                                if (argv[i][2] || i >= argc-2) break;
327 +                                scompile(argv[++i], NULL, 0);
328 +                                continue;
329 +                        case 'o':               /* output file spec. */
330 +                                if (argv[i][2] || i >= argc-2) break;
331 +                                curout = argv[++i];
332 +                                continue;
333 +                        case 'x':               /* horiz. output resolution */
334 +                                if (argv[i][2] || i >= argc-2) break;
335 +                                xres = atoi(argv[++i]);
336 +                                continue;
337 +                        case 'y':               /* vert. output resolution */
338 +                                if (argv[i][2] || i >= argc-2) break;
339 +                                yres = atoi(argv[++i]);
340 +                                continue;
341 +                        case 'b':               /* bin expression/count */
342 +                                if (i >= argc-2) break;
343 +                                if (argv[i][2] == 'n') {
344 +                                        bincnt = (int)(eval(argv[++i]) + .5);
345 +                                        continue;
346 +                                }
347 +                                if (argv[i][2]) break;
348 +                                binval = argv[++i];
349 +                                continue;
350 +                        case 'm':               /* modifier name */
351 +                                if (argv[i][2] || i >= argc-2) break;
352 +                                rtargv[rtargc++] = "-ti";
353 +                                rtargv[rtargc++] = argv[++i];
354 +                                addmodifier(argv[i], curout, binval, bincnt);
355 +                                continue;
356 +                        case 'M':               /* modifier file */
357 +                                if (argv[i][2] || i >= argc-2) break;
358 +                                rtargv[rtargc++] = "-tI";
359 +                                rtargv[rtargc++] = argv[++i];
360 +                                addmodfile(argv[i], curout, binval, bincnt);
361 +                                continue;
362 +                        case 'P':               /* persist file */
363 +                                if (i >= argc-2) break;
364 +                                persist_state = (argv[i][2] == 'P') ?
365 +                                                PERSIST_PARALL : PERSIST_SINGLE;
366 +                                rtargv[rtargc++] = argv[i];
367 +                                rtargv[rtargc++] = argv[++i];
368 +                                continue;
369                          }
370 <                        setformat(argv[i]+2);
200 <                        continue;
201 <                case 'e':                       /* expression */
202 <                        if (argv[i][2] || i >= argc-1) break;
203 <                        scompile(argv[++i], NULL, 0);
204 <                        continue;
205 <                case 'o':                       /* output file spec. */
206 <                        if (argv[i][2] || i >= argc-1) break;
207 <                        curout = argv[++i];
208 <                        continue;
209 <                case 'x':                       /* horiz. output resolution */
210 <                        if (argv[i][2] || i >= argc-1) break;
211 <                        xres = atoi(argv[++i]);
212 <                        continue;
213 <                case 'y':                       /* vert. output resolution */
214 <                        if (argv[i][2] || i >= argc-1) break;
215 <                        yres = atoi(argv[++i]);
216 <                        continue;
217 <                case 'l':                       /* limit distance? */
218 <                        if (argv[i][2] != 'd') break;
219 <                        rtargv[rtargc++] = argv[i];
220 <                        continue;
221 <                case 'b':                       /* bin expression */
222 <                        if (argv[i][2] || i >= argc-1) break;
223 <                        binval = argv[++i];
224 <                        continue;
225 <                case 'm':                       /* modifier name */
226 <                        if (argv[i][2] || i >= argc-1) break;
227 <                        rtargv[rtargc++] = "-ti";
228 <                        rtargv[rtargc++] = argv[++i];
229 <                        addmodifier(argv[i], curout, binval);
230 <                        continue;
231 <                }
232 <                break;          /* break into rtrace options */
370 >                rtargv[rtargc++] = argv[i];     /* assume rtrace option */
371          }
372 <        for ( ; i < argc; i++)  /* transfer rtrace-specific options */
373 <                rtargv[rtargc++] = argv[i];
374 <        if (!strcmp(rtargv[--rtargc], "-defaults"))
375 <                nprocs = 0;
238 <        if (nprocs > 1) {       /* add persist file if parallel invocation */
239 <                rtargv[rtargc++] = "-PP";
240 <                rtargv[rtargc++] = mktemp(persistfn);
241 <        }
372 >        if (accumulate <= 0)    /* no output flushing for single record */
373 >                xres = yres = 0;
374 >                                /* set global argument list */
375 >        gargc = argc; gargv = argv;
376                                  /* add "mandatory" rtrace settings */
377 <        for (i = 0; myrtopts[i] != NULL; i++)
378 <                rtargv[rtargc++] = myrtopts[i];
379 <        if (!nprocs) {          /* just asking for defaults? */
380 <                char    sxres[16], syres[16];
377 >        for (j = 0; myrtopts[j] != NULL; j++)
378 >                rtargv[rtargc++] = myrtopts[j];
379 >        rtargv[rtargc++] = contrib ? RTCONTRIB : RTCOEFF;
380 >                                /* just asking for defaults? */
381 >        if (!strcmp(argv[i], "-defaults")) {
382 >                char    nps[8], sxres[16], syres[16];
383                  char    *rtpath;
384 <                printf("-n  1\t\t\t\t# number of processes\n", nprocs);
384 >                printf("-c %-5d\t\t\t# accumulated rays per record\n",
385 >                                accumulate);
386 >                printf("-V%c\t\t\t\t# output %s\n", contrib ? '+' : '-',
387 >                                contrib ? "contributions" : "coefficients");
388                  fflush(stdout);                 /* report OUR options */
389 +                rtargv[rtargc++] = "-n";
390 +                sprintf(nps, "%d", nprocs);
391 +                rtargv[rtargc++] = nps;
392                  rtargv[rtargc++] = header ? "-h+" : "-h-";
393                  sprintf(fmt, "-f%c%c", inpfmt, outfmt);
394                  rtargv[rtargc++] = fmt;
# Line 256 | Line 398 | main(int argc, char *argv[])
398                  rtargv[rtargc++] = "-y";
399                  sprintf(syres, "%d", yres);
400                  rtargv[rtargc++] = syres;
259                rtargv[rtargc++] = "-oW";
401                  rtargv[rtargc++] = "-defaults";
402                  rtargv[rtargc] = NULL;
403                  rtpath = getpath(rtargv[0], getenv("PATH"), X_OK);
# Line 269 | Line 410 | main(int argc, char *argv[])
410                  perror(rtpath); /* execv() should not return */
411                  exit(1);
412          }
413 <        if (!nmods)
414 <                error(USER, "No modifiers specified");
415 <        if (argc < 2 || argv[argc-1][0] == '-')
416 <                error(USER, "missing octree argument");
413 >        if (nprocs > 1) {       /* add persist file if parallel */
414 >                if (persist_state == PERSIST_SINGLE)
415 >                        error(USER, "use -PP option for multiple processes");
416 >                if (persist_state == PERSIST_NONE) {
417 >                        rtargv[rtargc++] = "-PP";
418 >                        rtargv[rtargc++] = mktemp(persistfn);
419 >                        persist_state = PERSIST_OURS;
420 >                }
421 >        }
422                                  /* add format string */
423          sprintf(fmt, "-f%cf", inpfmt);
424          rtargv[rtargc++] = fmt;
425                                  /* octree argument is last */
426 <        rtargv[rtargc++] = octree = argv[argc-1];
426 >        if (i <= 0 || i != argc-1 || argv[i][0] == '-')
427 >                error(USER, "missing octree argument");
428 >        rtargv[rtargc++] = octree = argv[i];
429          rtargv[rtargc] = NULL;
430 <                                /* start rtrace & sum contributions */
430 >                                /* start rtrace & recover if requested */
431          init(nprocs);
432 <        tracecontribs(stdin);
432 >                                /* compute contributions */
433 >        trace_contribs(stdin);
434 >                                /* clean up */
435          quit(0);
436   }
437  
438 + #ifndef SIGALRM
439 + #define SIGALRM SIGTERM
440 + #endif
441   /* kill persistent rtrace process */
442   static void
443   killpersist(void)
444   {
445          FILE    *fp = fopen(persistfn, "r");
446 <        int     pid;
446 >        RT_PID  pid;
447  
448          if (fp == NULL)
449                  return;
# Line 324 | Line 477 | quit(int status)
477   {
478          int     rtstat;
479  
480 <        if (rt0.next != NULL)           /* terminate persistent rtrace */
480 >        if (persist_state == PERSIST_OURS)  /* terminate waiting rtrace */
481                  killpersist();
482                                          /* clean up rtrace process(es) */
483          rtstat = done_rprocs(&rt0);
# Line 333 | Line 486 | quit(int status)
486          exit(status);                   /* flushes all output streams */
487   }
488  
489 < /* start rtrace and initialize buffers */
489 > /* start rtrace processes and initialize */
490   void
491   init(int np)
492   {
493          struct rtproc   *rtp;
494          int     i;
495          int     maxbytes;
496 +                                        /* make sure we have something to do */
497 +        if (!nmods)
498 +                error(USER, "No modifiers specified");
499                                          /* assign ray variables */
500          scompile("Dx=$1;Dy=$2;Dz=$3;", NULL, 0);
501          scompile("Px=$4;Py=$5;Pz=$6;", NULL, 0);
502                                          /* set up signal handling */
503 < #ifdef SIGPIPE /* not present on Windows */
503 >        signal(SIGINT, quit);
504 > #ifdef SIGHUP
505 >        signal(SIGHUP, quit);
506 > #endif
507 > #ifdef SIGTERM
508 >        signal(SIGTERM, quit);
509 > #endif
510 > #ifdef SIGPIPE
511          signal(SIGPIPE, quit);
512   #endif
513          rtp = &rt0;                     /* start rtrace process(es) */
# Line 360 | Line 523 | init(int np)
523                          error(SYSTEM, "cannot start rtrace process");
524                  if (maxbytes > treebufsiz)
525                          treebufsiz = maxbytes;
526 +                rtp->raynum = 0;
527                  rtp->bsiz = 0;
528                  rtp->buf = NULL;
529 <                rtp->raynum = 0;
529 >                rtp->nbr = 0;
530                  if (i == np)            /* last process? */
531                          break;
532                  if (i == 1)
# Line 375 | Line 539 | init(int np)
539          rtp->next = NULL;               /* terminate list */
540          if (yres > 0) {
541                  if (xres > 0)
542 <                        raysleft = xres*yres;
542 >                        raysleft = (unsigned long)xres*yres;
543                  else
544                          raysleft = yres;
545          } else
546                  raysleft = 0;
547 <        waitflush = xres;
547 >        if ((account = accumulate) > 0)
548 >                raysleft *= accumulate;
549 >        waitflush = (yres > 0) & (xres > 1) ? 0 : xres;
550 >        if (!recover)
551 >                return;
552 >                                        /* recover previous values */
553 >        if (accumulate <= 0)
554 >                reload_output();
555 >        else
556 >                recover_output(stdin);
557   }
558  
559 + /* grow modifier to accommodate more bins */
560 + MODCONT *
561 + growmodifier(MODCONT *mp, int nb)
562 + {
563 +        if (nb <= mp->nbins)
564 +                return mp;
565 +        mp = (MODCONT *)realloc(mp, sizeof(MODCONT) + sizeof(DCOLOR)*(nb-1));
566 +        if (mp == NULL)
567 +                error(SYSTEM, "out of memory in growmodifier");
568 +        memset(mp->cbin+mp->nbins, 0, sizeof(DCOLOR)*(nb-mp->nbins));
569 +        mp->nbins = nb;
570 +        return mp;
571 + }
572 +
573   /* add modifier to our list to track */
574   MODCONT *
575 < addmodifier(char *modn, char *outf, char *binv)
575 > addmodifier(char *modn, char *outf, char *binv, int bincnt)
576   {
577          LUENT   *lep = lu_find(&modconttab, modn);
578          MODCONT *mp;
579 +        int     i;
580          
581          if (lep->data != NULL) {
582                  sprintf(errmsg, "duplicate modifier '%s'", modn);
583                  error(USER, errmsg);
584          }
585          if (nmods >= MAXMODLIST)
586 <                error(USER, "too many modifiers");
586 >                error(INTERNAL, "too many modifiers");
587          modname[nmods++] = modn;        /* XXX assumes static string */
588          lep->key = modn;                /* XXX assumes static string */
589          mp = (MODCONT *)malloc(sizeof(MODCONT));
590          if (mp == NULL)
591                  error(SYSTEM, "out of memory in addmodifier");
404        lep->data = (char *)mp;
592          mp->outspec = outf;             /* XXX assumes static string */
593          mp->modname = modn;             /* XXX assumes static string */
594 <        if (binv != NULL)
595 <                mp->binv = eparse(binv);
596 <        else
597 <                mp->binv = eparse("0");
598 <        mp->nbins = 1;
594 >        if (binv == NULL)
595 >                binv = "0";             /* use single bin if unspecified */
596 >        mp->binv = eparse(binv);
597 >        if (mp->binv->type == NUM) {    /* check value if constant */
598 >                bincnt = (int)(evalue(mp->binv) + 1.5);
599 >                if (bincnt != 1) {
600 >                        sprintf(errmsg, "illegal non-zero constant for bin (%s)",
601 >                                        binv);
602 >                        error(USER, errmsg);
603 >                }
604 >        }
605 >        mp->nbins = 1;                  /* initialize results holder */
606          setcolor(mp->cbin[0], 0., 0., 0.);
607 +        if (bincnt > 1)
608 +                mp = growmodifier(mp, bincnt);
609 +        lep->data = (char *)mp;
610 +                                        /* allocate output streams */
611 +        for (i = bincnt; i-- > 0; )
612 +                getostream(mp->outspec, mp->modname, i, 1);
613          return mp;
614   }
615  
616 + /* add modifiers from a file list */
617 + void
618 + addmodfile(char *fname, char *outf, char *binv, int bincnt)
619 + {
620 +        char    *mname[MAXMODLIST];
621 +        int     i;
622 +                                        /* find the file & store strings */
623 +        if (wordfile(mname, getpath(fname, getrlibpath(), R_OK)) < 0) {
624 +                sprintf(errmsg, "cannot find modifier file '%s'", fname);
625 +                error(SYSTEM, errmsg);
626 +        }
627 +        for (i = 0; mname[i]; i++)      /* add each one */
628 +                addmodifier(mname[i], outf, binv, bincnt);
629 + }
630 +
631   /* put string to stderr */
632   void
633   eputs(char  *s)
# Line 428 | Line 643 | eputs(char  *s)
643          midline = s[strlen(s)-1] != '\n';
644   }
645  
646 + /* construct output file name and return flags whether modifier/bin present */
647 + int
648 + ofname(char *oname, const char *ospec, const char *mname, int bn)
649 + {
650 +        const char      *mnp = NULL;
651 +        const char      *bnp = NULL;
652 +        const char      *cp;
653 +        
654 +        if (ospec == NULL)
655 +                return -1;
656 +        for (cp = ospec; *cp; cp++)             /* check format position(s) */
657 +                if (*cp == '%') {
658 +                        do
659 +                                ++cp;
660 +                        while (isdigit(*cp));
661 +                        switch (*cp) {
662 +                        case '%':
663 +                                break;
664 +                        case 's':
665 +                                if (mnp != NULL)
666 +                                        return -1;
667 +                                mnp = cp;
668 +                                break;
669 +                        case 'd':
670 +                        case 'i':
671 +                        case 'o':
672 +                        case 'x':
673 +                        case 'X':
674 +                                if (bnp != NULL)
675 +                                        return -1;
676 +                                bnp = cp;
677 +                                break;
678 +                        default:
679 +                                return -1;
680 +                        }
681 +                }
682 +        if (mnp != NULL) {                      /* create file name */
683 +                if (bnp != NULL) {
684 +                        if (bnp > mnp)
685 +                                sprintf(oname, ospec, mname, bn);
686 +                        else
687 +                                sprintf(oname, ospec, bn, mname);
688 +                        return OF_MODIFIER|OF_BIN;
689 +                }
690 +                sprintf(oname, ospec, mname);
691 +                return OF_MODIFIER;
692 +        }
693 +        if (bnp != NULL) {
694 +                sprintf(oname, ospec, bn);
695 +                return OF_BIN;
696 +        }
697 +        strcpy(oname, ospec);
698 +        return 0;
699 + }
700 +
701   /* write header to the given output stream */
702   void
703 < printheader(FILE *fout)
703 > printheader(FILE *fout, const char *info)
704   {
705          extern char     VersionID[];
706          FILE            *fin = fopen(octree, "r");
707          
708          if (fin == NULL)
709                  quit(1);
710 <        getheader(fin, (gethfunc *)fputs, fout);        /* copy octree header */
710 >        checkheader(fin, "ignore", fout);       /* copy octree header */
711          fclose(fin);
712          printargs(gargc-1, gargv, fout);        /* add our command */
713          fprintf(fout, "SOFTWARE= %s\n", VersionID);
714          fputnow(fout);
715 +        if (info != NULL)                       /* add extra info if given */
716 +                fputs(info, fout);
717          switch (outfmt) {                       /* add output format */
718          case 'a':
719                  fputformat("ascii", fout);
# Line 457 | Line 729 | printheader(FILE *fout)
729                  break;
730          }
731          fputc('\n', fout);
460        if (xres > 0) {
461                if (yres > 0)                   /* resolution string */
462                        fprtresolu(xres, yres, fout);
463                fflush(fout);
464        }
732   }
733  
734 < /* Get output file pointer (open and write header if new) */
735 < FILE *
736 < getofile(const char *ospec, const char *mname, int bn)
734 > /* write resolution string to given output stream */
735 > void
736 > printresolu(FILE *fout, int xr, int yr)
737   {
738 <        static int      using_stdout = 0;
739 <        const char      *mnp = NULL;
740 <        const char      *bnp = NULL;
741 <        const char      *cp;
742 <        char            ofname[1024];
743 <        LUENT           *lep;
738 >        if ((xr > 0) & (yr > 0))        /* resolution string */
739 >                fprtresolu(xr, yr, fout);
740 > }
741 >
742 > /* Get output stream pointer (open and write header if new and noopen==0) */
743 > STREAMOUT *
744 > getostream(const char *ospec, const char *mname, int bn, int noopen)
745 > {
746 >        static const DCOLOR     nocontrib = BLKCOLOR;
747 >        static STREAMOUT        stdos;
748 >        int                     ofl;
749 >        char                    oname[1024];
750 >        LUENT                   *lep;
751 >        STREAMOUT               *sop;
752          
753          if (ospec == NULL) {                    /* use stdout? */
754 <                if (!using_stdout && header)
755 <                        printheader(stdout);
756 <                using_stdout = 1;
757 <                return stdout;
754 >                if (!noopen && !using_stdout) {
755 >                        if (outfmt != 'a')
756 >                                SET_FILE_BINARY(stdout);
757 >                        if (header)
758 >                                printheader(stdout, NULL);
759 >                        printresolu(stdout, xres, yres);
760 >                        if (waitflush > 0)
761 >                                fflush(stdout);
762 >                        stdos.xr = xres; stdos.yr = yres;
763 >                        using_stdout = 1;
764 >                }
765 >                stdos.ofp = stdout;
766 >                stdos.reclen += noopen;
767 >                return &stdos;
768          }
769 <        for (cp = ospec; *cp; cp++)             /* check format position(s) */
770 <                if (*cp == '%') {
771 <                        do
772 <                                ++cp;
773 <                        while (isdigit(*cp));
774 <                        switch (*cp) {
775 <                        case '%':
776 <                                break;
777 <                        case 's':
778 <                                if (mnp != NULL)
779 <                                        goto badspec;
780 <                                mnp = cp;
781 <                                break;
782 <                        case 'd':
783 <                                if (bnp != NULL)
784 <                                        goto badspec;
785 <                                bnp = cp;
786 <                                break;
787 <                        default:
788 <                                goto badspec;
769 >        ofl = ofname(oname, ospec, mname, bn);  /* get output name */
770 >        if (ofl < 0) {
771 >                sprintf(errmsg, "bad output format '%s'", ospec);
772 >                error(USER, errmsg);
773 >        }
774 >        lep = lu_find(&ofiletab, oname);        /* look it up */
775 >        if (lep->key == NULL)                   /* new entry */
776 >                lep->key = strcpy((char *)malloc(strlen(oname)+1), oname);
777 >        sop = (STREAMOUT *)lep->data;
778 >        if (sop == NULL) {                      /* allocate stream */
779 >                sop = (STREAMOUT *)malloc(sizeof(STREAMOUT));
780 >                if (sop == NULL)
781 >                        error(SYSTEM, "out of memory in getostream");
782 >                sop->outpipe = oname[0] == '!';
783 >                sop->reclen = 0;
784 >                sop->ofp = NULL;                /* open iff noopen==0 */
785 >                sop->xr = xres; sop->yr = yres;
786 >                lep->data = (char *)sop;
787 >                if (!sop->outpipe & !force_open & !recover &&
788 >                                access(oname, F_OK) == 0) {
789 >                        errno = EEXIST;         /* file exists */
790 >                        goto openerr;
791 >                }
792 >        }
793 >        if (!noopen && sop->ofp == NULL) {      /* open output stream */
794 >                long            i;
795 >                if (oname[0] == '!')            /* output to command */
796 >                        sop->ofp = popen(oname+1, "w");
797 >                else                            /* else open file */
798 >                        sop->ofp = fopen(oname, "w");
799 >                if (sop->ofp == NULL)
800 >                        goto openerr;
801 >                if (outfmt != 'a')
802 >                        SET_FILE_BINARY(sop->ofp);
803 >                if (header) {
804 >                        char    info[512];
805 >                        char    *cp = info;
806 >                        if (ofl & OF_MODIFIER || sop->reclen == 1) {
807 >                                sprintf(cp, "MODIFIER=%s\n", mname);
808 >                                while (*cp) ++cp;
809                          }
810 +                        if (ofl & OF_BIN) {
811 +                                sprintf(cp, "BIN=%d\n", bn);
812 +                                while (*cp) ++cp;
813 +                        }
814 +                        *cp = '\0';
815 +                        printheader(sop->ofp, info);
816                  }
817 <        if (mnp != NULL) {                      /* create file name */
818 <                if (bnp != NULL) {
508 <                        if (bnp > mnp)
509 <                                sprintf(ofname, ospec, mname, bn);
510 <                        else
511 <                                sprintf(ofname, ospec, bn, mname);
512 <                } else
513 <                        sprintf(ofname, ospec, mname);
514 <        } else if (bnp != NULL)
515 <                sprintf(ofname, ospec, bn);
516 <        else
517 <                strcpy(ofname, ospec);
518 <        lep = lu_find(&ofiletab, ofname);       /* look it up */
519 <        if (lep->key == NULL)                   /* new entry */
520 <                lep->key = strcpy((char *)malloc(strlen(ofname)+1), ofname);
521 <        if (lep->data == NULL) {                /* open output file */
522 <                lep->data = (char *)fopen(ofname, "w");
523 <                if (lep->data == NULL) {
524 <                        sprintf(errmsg, "cannot open '%s' for writing", ofname);
525 <                        error(SYSTEM, errmsg);
817 >                if (accumulate > 0) {           /* global resolution */
818 >                        sop->xr = xres; sop->yr = yres;
819                  }
820 <                if (header)
821 <                        printheader((FILE *)lep->data);
820 >                printresolu(sop->ofp, sop->xr, sop->yr);
821 >                                                /* play catch-up */
822 >                for (i = accumulate > 0 ? lastdone/accumulate : 0; i--; ) {
823 >                        int     j = sop->reclen;
824 >                        if (j <= 0) j = 1;
825 >                        while (j--)
826 >                                put_contrib(nocontrib, sop->ofp);
827 >                        if (outfmt == 'a')
828 >                                putc('\n', sop->ofp);
829 >                }
830 >                if (waitflush > 0)
831 >                        fflush(sop->ofp);
832          }
833 <        return (FILE *)lep->data;               /* return open file pointer */
834 < badspec:
835 <        sprintf(errmsg, "bad output format '%s'", ospec);
836 <        error(USER, errmsg);
837 <        return NULL;            /* pro forma return */
833 >        sop->reclen += noopen;                  /* add to length if noopen */
834 >        return sop;                             /* return output stream */
835 > openerr:
836 >        sprintf(errmsg, "cannot open '%s' for writing", oname);
837 >        error(SYSTEM, errmsg);
838 >        return NULL;    /* pro forma return */
839   }
840  
841   /* read input ray into buffer */
842   int
843   getinp(char *buf, FILE *fp)
844   {
845 +        double  dv[3], *dvp;
846 +        float   *fvp;
847 +        char    *cp;
848 +        int     i;
849 +
850          switch (inpfmt) {
851          case 'a':
852 <                if (fgets(buf, 128, fp) == NULL)
853 <                        return 0;
852 >                cp = buf;               /* make sure we get 6 floats */
853 >                for (i = 0; i < 6; i++) {
854 >                        if (fgetword(cp, buf+127-cp, fp) == NULL)
855 >                                return -1;
856 >                        if (i >= 3)
857 >                                dv[i-3] = atof(cp);
858 >                        if ((cp = fskip(cp)) == NULL || *cp)
859 >                                return -1;
860 >                        *cp++ = ' ';
861 >                }
862 >                getc(fp);               /* get/put eol */
863 >                *cp-- = '\0'; *cp = '\n';
864 >                if (DOT(dv,dv) <= FTINY*FTINY)
865 >                        return 0;       /* dummy ray */
866                  return strlen(buf);
867          case 'f':
868                  if (fread(buf, sizeof(float), 6, fp) < 6)
869 <                        return 0;
869 >                        return -1;
870 >                fvp = (float *)buf + 3;
871 >                if (DOT(fvp,fvp) <= FTINY*FTINY)
872 >                        return 0;       /* dummy ray */
873                  return sizeof(float)*6;
874          case 'd':
875                  if (fread(buf, sizeof(double), 6, fp) < 6)
876 <                        return 0;
876 >                        return -1;
877 >                dvp = (double *)buf + 3;
878 >                if (DOT(dvp,dvp) <= FTINY*FTINY)
879 >                        return 0;       /* dummy ray */
880                  return sizeof(double)*6;
881          }
882          error(INTERNAL, "botched input format");
883 <        return 0;       /* pro forma return */
883 >        return -1;      /* pro forma return */
884   }
885  
886 < static const float      *rparams = NULL;        /* ray parameter pointer */
886 > static float    rparams[9];             /* traced ray parameters */
887  
888   /* return channel (ray) value */
889   double
# Line 564 | Line 891 | chanvalue(int n)
891   {
892          if (--n < 0 || n >= 6)
893                  error(USER, "illegal channel number ($N)");
894 <        if (rparams == NULL)
568 <                error(USER, "illegal use of $N in constant expression");
569 <        return rparams[n];
894 >        return rparams[n+3];
895   }
896  
897 < /* add ray contribution to the appropriate modifier bin */
897 > /* add current ray contribution to the appropriate modifier bin */
898   void
899 < add_contrib(const char *modn, float rayval[9])
899 > add_contrib(const char *modn)
900   {
901          LUENT   *le = lu_find(&modconttab, modn);
902          MODCONT *mp = (MODCONT *)le->data;
# Line 581 | Line 906 | add_contrib(const char *modn, float rayval[9])
906                  sprintf(errmsg, "unexpected modifier '%s' from rtrace", modn);
907                  error(USER, errmsg);
908          }
909 <        rparams = rayval + 3;           /* for chanvalue */
585 <        eclock++;
909 >        eclock++;                       /* get bin number */
910          bn = (int)(evalue(mp->binv) + .5);
911          if (bn <= 0)
912                  bn = 0;
913 <        else if (bn > mp->nbins) {      /* new bin */
914 <                mp = (MODCONT *)realloc(mp, sizeof(MODCONT) +
915 <                                                bn*sizeof(COLOR));
592 <                if (mp == NULL)
593 <                        error(SYSTEM, "out of memory in add_contrib");
594 <                memset(mp->cbin+mp->nbins, 0, sizeof(COLOR)*(bn+1-mp->nbins));
595 <                mp->nbins = bn+1;
596 <                le->data = (char *)mp;
597 <        }
598 <        addcolor(mp->cbin[bn], rayval);
599 <        rparams = NULL;
913 >        else if (bn >= mp->nbins)       /* new bin */
914 >                le->data = (char *)(mp = growmodifier(mp, bn+1));
915 >        addcolor(mp->cbin[bn], rparams);
916   }
917  
918   /* output newline to ASCII file and/or flush as requested */
919   static int
920   puteol(const LUENT *e, void *p)
921   {
922 <        FILE    *fp = (FILE *)e->data;
922 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
923  
924          if (outfmt == 'a')
925 <                putc('\n', fp);
925 >                putc('\n', sop->ofp);
926          if (!waitflush)
927 <                fflush(fp);
928 <        if (ferror(fp)) {
927 >                fflush(sop->ofp);
928 >        if (ferror(sop->ofp)) {
929                  sprintf(errmsg, "write error on file '%s'", e->key);
930                  error(SYSTEM, errmsg);
931          }
932          return 0;
933   }
934  
935 < /* output ray tallies and clear for next primary */
935 > /* put out ray contribution to file */
936   void
937 < done_contrib(void)
937 > put_contrib(const DCOLOR cnt, FILE *fout)
938   {
939 <        int     i, j;
624 <        MODCONT *mp;
625 <        FILE    *fout;
626 <        double  dv[3];
939 >        float   fv[3];
940          COLR    cv;
941 +
942 +        switch (outfmt) {
943 +        case 'a':
944 +                fprintf(fout, "%.6e\t%.6e\t%.6e\t", cnt[0], cnt[1], cnt[2]);
945 +                break;
946 +        case 'f':
947 +                copycolor(fv, cnt);
948 +                fwrite(fv, sizeof(float), 3, fout);
949 +                break;
950 +        case 'd':
951 +                fwrite(cnt, sizeof(double), 3, fout);
952 +                break;
953 +        case 'c':
954 +                setcolr(cv, cnt[0], cnt[1], cnt[2]);
955 +                fwrite(cv, sizeof(cv), 1, fout);
956 +                break;
957 +        default:
958 +                error(INTERNAL, "botched output format");
959 +        }
960 + }
961 +
962 + /* output ray tallies and clear for next accumulation */
963 + void
964 + done_contrib(int navg)
965 + {
966 +        double          sf = 1.;
967 +        int             i, j;
968 +        MODCONT         *mp;
969 +        STREAMOUT       *sop;
970 +                                                /* set average scaling */
971 +        if (navg > 1)
972 +                sf = 1. / (double)navg;
973                                                  /* output modifiers in order */
974          for (i = 0; i < nmods; i++) {
975                  mp = (MODCONT *)lu_find(&modconttab,modname[i])->data;
976 <                for (j = 0; j < mp->nbins; j++) {
977 <                        fout = getofile(mp->outspec, mp->modname, j);
978 <                        switch (outfmt) {
979 <                        case 'a':
980 <                                fprintf(fout, "%.6e\t%.6e\t%.6e\t",
981 <                                                mp->cbin[j][RED],
982 <                                                mp->cbin[j][GRN],
983 <                                                mp->cbin[j][BLU]);
984 <                                break;
985 <                        case 'f':
986 <                                fwrite(mp->cbin[j], sizeof(float), 3, fout);
987 <                                break;
988 <                        case 'd':
989 <                                dv[0] = mp->cbin[j][0];
990 <                                dv[1] = mp->cbin[j][1];
646 <                                dv[2] = mp->cbin[j][2];
647 <                                fwrite(dv, sizeof(double), 3, fout);
648 <                                break;
649 <                        case 'c':
650 <                                setcolr(cv, mp->cbin[j][RED],
651 <                                        mp->cbin[j][GRN], mp->cbin[j][BLU]);
652 <                                fwrite(cv, sizeof(COLR), 1, fout);
653 <                                break;
654 <                        default:
655 <                                error(INTERNAL, "botched output format");
656 <                        }
657 <                }
658 <                                                /* clear for next ray tree */
659 <                memset(mp->cbin, 0, sizeof(COLOR)*mp->nbins);
976 >                if (navg > 1)                   /* average scaling */
977 >                        for (j = mp->nbins; j--; )
978 >                                scalecolor(mp->cbin[j], sf);
979 >                sop = getostream(mp->outspec, mp->modname, 0,0);
980 >                put_contrib(mp->cbin[0], sop->ofp);
981 >                if (mp->nbins > 3 &&            /* minor optimization */
982 >                                sop == getostream(mp->outspec, mp->modname, 1,0))
983 >                        for (j = 1; j < mp->nbins; j++)
984 >                                put_contrib(mp->cbin[j], sop->ofp);
985 >                else
986 >                        for (j = 1; j < mp->nbins; j++)
987 >                                put_contrib(mp->cbin[j],
988 >                                    getostream(mp->outspec,mp->modname,j,0)->ofp);
989 >                                                /* clear for next time */
990 >                memset(mp->cbin, 0, sizeof(DCOLOR)*mp->nbins);
991          }
992          --waitflush;                            /* terminate records */
993          lu_doall(&ofiletab, puteol, NULL);
994 <        if (!waitflush)
995 <                waitflush = xres;
994 >        if (using_stdout & (outfmt == 'a'))
995 >                putc('\n', stdout);
996 >        if (!waitflush) {
997 >                waitflush = (yres > 0) & (xres > 1) ? 0 : xres;
998 >                if (using_stdout)
999 >                        fflush(stdout);
1000 >        }
1001   }
1002  
1003 < /* process (or save) ray tree produced by rtrace process */
1003 > /* queue completed ray tree produced by rtrace process */
1004   void
1005 < process_rays(struct rtproc *rtp)
1005 > queue_raytree(struct rtproc *rtp)
1006   {
1007 <        struct rtproc   *rtu;
1008 <                                        /* check if time to process it */
1009 <        if (rtp->raynum == lastdone+1) {
1010 <                int             n = rtp->bpos - rtp->buf;
1007 >        struct rtproc   *rtu, *rtl = NULL;
1008 >                                        /* insert following ray order */
1009 >        for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
1010 >                if (rtp->raynum < rtu->raynum)
1011 >                        break;
1012 >        rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
1013 >        if (rtu == NULL)
1014 >                error(SYSTEM, "out of memory in queue_raytree");
1015 >        *rtu = *rtp;
1016 >        if (rtl == NULL) {
1017 >                rtu->next = rt_unproc;
1018 >                rt_unproc = rtu;
1019 >        } else {
1020 >                rtu->next = rtl->next;
1021 >                rtl->next = rtu;
1022 >        }
1023 >        rtp->raynum = 0;                /* clear path for next ray tree */
1024 >        rtp->bsiz = 0;
1025 >        rtp->buf = NULL;
1026 >        rtp->nbr = 0;
1027 > }
1028 >
1029 > /* process completed ray trees from our queue */
1030 > void
1031 > process_queue(void)
1032 > {
1033 >        char    modname[128];
1034 >                                        /* ray-ordered queue */
1035 >        while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
1036 >                struct rtproc   *rtp = rt_unproc;
1037 >                int             n = rtp->nbr;
1038                  const char      *cp = rtp->buf;
1039                  while (n > 0) {         /* process rays */
1040 <                        char    matname[128];
678 <                        char    *mnp = matname;
1040 >                        register char   *mnp = modname;
1041                                          /* skip leading tabs */
1042                          while (n > 0 && *cp == '\t') {
1043                                  cp++; n--;
1044                          }
1045 <                                        /* get material name */
1046 <                        while (n > 0 && *cp != '\t') {
1045 >                        if (!n || !(isalpha(*cp) | (*cp == '_')))
1046 >                                error(USER, "bad modifier name from rtrace");
1047 >                                        /* get modifier name */
1048 >                        while (n > 1 && *cp != '\t') {
1049 >                                if (mnp - modname >= sizeof(modname)-2)
1050 >                                        error(INTERNAL, "modifier name too long");
1051                                  *mnp++ = *cp++; n--;
1052                          }
687                        if (!n)
688                                error(USER, "botched modifer name from rtrace");
1053                          *mnp = '\0';
1054 <                        cp++; n--;      /* skip terminating tab */
1054 >                        cp++; n--;      /* eat following tab */
1055                          if (n < (int)(sizeof(float)*9))
1056                                  error(USER, "incomplete ray value from rtrace");
1057                                          /* add ray contribution */
1058 <                        add_contrib(matname, (float *)cp);
1058 >                        memcpy(rparams, cp, sizeof(float)*9);
1059                          cp += sizeof(float)*9; n -= sizeof(float)*9;
1060 +                        add_contrib(modname);
1061                  }
1062 <                done_contrib();         /* sum up contributions & output */
1062 >                                        /* time to produce record? */
1063 >                if (account > 0 && !--account)
1064 >                        done_contrib(account = accumulate);
1065                  lastdone = rtp->raynum;
1066 <                free(rtp->buf);
1067 <                                        /* catch up with unprocessed list */
1068 <                while (rt_unproc != NULL && rt_unproc->raynum == lastdone+1) {
1069 <                        process_rays(rt_unproc);
703 <                        rt_unproc = (rtu=rt_unproc)->next;
704 <                        free(rtu);
705 <                }
706 <        } else {                        /* else insert in unprocessed list */
707 <                struct rtproc   *rtl = NULL;
708 <                for (rtu = rt_unproc; rtu != NULL; rtu = (rtl=rtu)->next)
709 <                        if (rtp->raynum < rtu->raynum)
710 <                                break;
711 <                rtu = (struct rtproc *)malloc(sizeof(struct rtproc));
712 <                if (rtu == NULL)
713 <                        error(SYSTEM, "out of memory in process_rays");
714 <                *rtu = *rtp;
715 <                if (rtl == NULL) {
716 <                        rtu->next = rt_unproc;
717 <                        rt_unproc = rtu;
718 <                } else {
719 <                        rtu->next = rtl->next;
720 <                        rtl->next = rtu;
721 <                }
1066 >                if (rtp->buf != NULL)   /* free up buffer space */
1067 >                        free(rtp->buf);
1068 >                rt_unproc = rtp->next;
1069 >                free(rtp);              /* done with this ray tree */
1070          }
723        rtp->raynum = 0;                /* clear path for next ray tree */
724        rtp->bsiz = 0;
725        rtp->buf = NULL;
1071   }
1072  
1073   /* wait for rtrace process to finish with ray tree */
# Line 731 | Line 1076 | wait_rproc(void)
1076   {
1077          struct rtproc   *rtfree = NULL;
1078          fd_set          readset, errset;
1079 <        int             nr;
1079 >        ssize_t         nr;
1080          struct rtproc   *rt;
1081          int             n;
1082          
# Line 763 | Line 1108 | wait_rproc(void)
1108                          if (rt->buf == NULL) {
1109                                  rt->bsiz = treebufsiz;
1110                                  rt->buf = (char *)malloc(treebufsiz);
1111 <                        } else if (rt->bpos + BUFSIZ > rt->buf + rt->bsiz) {
1111 >                        } else if (rt->nbr + BUFSIZ > rt->bsiz) {
1112                                  if (rt->bsiz + BUFSIZ <= treebufsiz)
1113                                          rt->bsiz = treebufsiz;
1114                                  else
1115 <                                        rt->bsiz = treebufsiz += BUFSIZ;
1115 >                                        treebufsiz = rt->bsiz += BUFSIZ;
1116                                  rt->buf = (char *)realloc(rt->buf, rt->bsiz);
1117                          }
1118                          if (rt->buf == NULL)
1119                                  error(SYSTEM, "out of memory in wait_rproc");
1120 <                        nr = read(rt->pd.r, rt->bpos,
1121 <                                        rt->buf + rt->bsiz - rt->bpos);
777 <                        if (!nr)
1120 >                        nr = read(rt->pd.r, rt->buf+rt->nbr, rt->bsiz-rt->nbr);
1121 >                        if (nr <= 0)
1122                                  error(USER, "rtrace process died");
1123 <                        rt->bpos += nr;         /* advance buffer & check */
1124 <                        if (rt->bpos[-1] == '\t' && rt->bpos[-2] == '-') {
1125 <                                rt->bpos -= 2;  /* elide terminator */
1126 <                                process_rays(rt);
1123 >                        rt->nbr += nr;          /* advance & check */
1124 >                        if (rt->nbr >= 4 && !memcmp(rt->buf+rt->nbr-4,
1125 >                                                        "~\t~\t", 4)) {
1126 >                                rt->nbr -= 4;   /* elide terminator */
1127 >                                queue_raytree(rt);
1128                                  rtfree = rt;    /* ready for next ray */
1129                          }
1130                  }
# Line 801 | Line 1146 | get_rproc(void)
1146  
1147   /* trace ray contributions (main loop) */
1148   void
1149 < tracecontribs(FILE *fin)
1149 > trace_contribs(FILE *fin)
1150   {
1151 +        static int      ignore_warning_given = 0;
1152          char            inpbuf[128];
1153          int             iblen;
1154          struct rtproc   *rtp;
1155                                                  /* loop over input */
1156 <        while ((iblen = getinp(inpbuf, fin)) > 0) {
1157 <                if (lastray+1 < lastray) {      /* counter rollover? */
1156 >        while ((iblen = getinp(inpbuf, fin)) >= 0) {
1157 >                if (!iblen && accumulate != 1) {
1158 >                        if (!ignore_warning_given++)
1159 >                                error(WARNING,
1160 >                                "dummy ray(s) ignored during accumulation\n");
1161 >                        continue;
1162 >                }
1163 >                if (!iblen ||                   /* need flush/reset? */
1164 >                                queue_length() > 10*nrtprocs() ||
1165 >                                lastray+1 < lastray) {
1166                          while (wait_rproc() != NULL)
1167 <                                ;
1168 <                        lastdone = lastray = 0;
1167 >                                process_queue();
1168 >                        if (lastray+1 < lastray)
1169 >                                lastdone = lastray = 0;
1170                  }
1171                  rtp = get_rproc();              /* get avail. rtrace process */
1172 <                rtp->raynum = ++lastray;        /* assign this ray to it */
1173 <                writebuf(rtp->pd.w, inpbuf, iblen);
1174 <                if (!--raysleft)
1175 <                        break;                  /* explicit EOF */
1172 >                rtp->raynum = ++lastray;        /* assign ray */
1173 >                if (iblen) {                    /* trace ray if valid */
1174 >                        writebuf(rtp->pd.w, inpbuf, iblen);
1175 >                } else {                        /* else bypass dummy ray */
1176 >                        queue_raytree(rtp);     /* queue empty ray/record */
1177 >                        if ((yres <= 0) | (xres <= 0))
1178 >                                waitflush = 1;  /* flush right after */
1179 >                }
1180 >                process_queue();                /* catch up with results */
1181 >                if (raysleft && !--raysleft)
1182 >                        break;                  /* preemptive EOI */
1183          }
1184          while (wait_rproc() != NULL)            /* process outstanding rays */
1185 <                ;
1185 >                process_queue();
1186 >        if (accumulate <= 0)
1187 >                done_contrib(0);                /* output tallies */
1188 >        else if (account < accumulate) {
1189 >                error(WARNING, "partial accumulation in final record");
1190 >                done_contrib(accumulate - account);
1191 >        }
1192 >        if (raysleft)
1193 >                error(USER, "unexpected EOF on input");
1194 >        lu_done(&ofiletab);                     /* close output files */
1195 > }
1196 >
1197 > /* get ray contribution from previous file */
1198 > static int
1199 > get_contrib(DCOLOR cnt, FILE *finp)
1200 > {
1201 >        COLOR   fv;
1202 >        COLR    cv;
1203 >
1204 >        switch (outfmt) {
1205 >        case 'a':
1206 >                return(fscanf(finp,"%lf %lf %lf",&cnt[0],&cnt[1],&cnt[2]) == 3);
1207 >        case 'f':
1208 >                if (fread(fv, sizeof(fv[0]), 3, finp) != 3)
1209 >                        return(0);
1210 >                copycolor(cnt, fv);
1211 >                return(1);
1212 >        case 'd':
1213 >                return(fread(cnt, sizeof(cnt[0]), 3, finp) == 3);
1214 >        case 'c':
1215 >                if (fread(cv, sizeof(cv), 1, finp) != 1)
1216 >                        return(0);
1217 >                colr_color(fv, cv);
1218 >                copycolor(cnt, fv);
1219 >                return(1);
1220 >        default:
1221 >                error(INTERNAL, "botched output format");
1222 >        }
1223 >        return(0);      /* pro forma return */
1224 > }
1225 >
1226 > /* close output file opened for input */
1227 > static int
1228 > myclose(const LUENT *e, void *p)
1229 > {
1230 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1231 >        
1232 >        if (sop->ofp == NULL)
1233 >                return(0);
1234 >        fclose(sop->ofp);
1235 >        sop->ofp = NULL;
1236 >        return(0);
1237 > }
1238 >
1239 > /* load previously accumulated values */
1240 > void
1241 > reload_output(void)
1242 > {
1243 >        int             i, j;
1244 >        MODCONT         *mp;
1245 >        int             ofl;
1246 >        char            oname[1024];
1247 >        char            *fmode = "rb";
1248 >        char            *outvfmt;
1249 >        LUENT           *ment, *oent;
1250 >        int             xr, yr;
1251 >        STREAMOUT       sout;
1252 >        DCOLOR          rgbv;
1253 >
1254 >        switch (outfmt) {
1255 >        case 'a':
1256 >                outvfmt = "ascii";
1257 >                fmode = "r";
1258 >                break;
1259 >        case 'f':
1260 >                outvfmt = "float";
1261 >                break;
1262 >        case 'd':
1263 >                outvfmt = "double";
1264 >                break;
1265 >        case 'c':
1266 >                outvfmt = COLRFMT;
1267 >                break;
1268 >        default:
1269 >                error(INTERNAL, "botched output format");
1270 >                return;
1271 >        }
1272 >                                                /* reload modifier values */
1273 >        for (i = 0; i < nmods; i++) {
1274 >                ment = lu_find(&modconttab,modname[i]);
1275 >                mp = (MODCONT *)ment->data;
1276 >                if (mp->outspec == NULL)
1277 >                        error(USER, "cannot reload from stdout");
1278 >                if (mp->outspec[0] == '!')
1279 >                        error(USER, "cannot reload from command");
1280 >                for (j = 0; ; j++) {            /* load each modifier bin */
1281 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1282 >                        if (ofl < 0)
1283 >                                error(USER, "bad output file specification");
1284 >                        oent = lu_find(&ofiletab, oname);
1285 >                        if (oent->data != NULL) {
1286 >                                sout = *(STREAMOUT *)oent->data;
1287 >                        } else {
1288 >                                sout.reclen = 0;
1289 >                                sout.outpipe = 0;
1290 >                                sout.xr = xres; sout.yr = yres;
1291 >                                sout.ofp = NULL;
1292 >                        }
1293 >                        if (sout.ofp == NULL) { /* open output as input */
1294 >                                sout.ofp = fopen(oname, fmode);
1295 >                                if (sout.ofp == NULL) {
1296 >                                        if (j)
1297 >                                                break;  /* assume end of modifier */
1298 >                                        sprintf(errmsg, "missing reload file '%s'",
1299 >                                                        oname);
1300 >                                        error(WARNING, errmsg);
1301 >                                        break;
1302 >                                }
1303 >                                if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1304 >                                        sprintf(errmsg, "format mismatch for '%s'",
1305 >                                                        oname);
1306 >                                        error(USER, errmsg);
1307 >                                }
1308 >                                if ((sout.xr > 0) & (sout.yr > 0) &&
1309 >                                                (!fscnresolu(&xr, &yr, sout.ofp) ||
1310 >                                                        (xr != sout.xr) |
1311 >                                                        (yr != sout.yr))) {
1312 >                                        sprintf(errmsg, "resolution mismatch for '%s'",
1313 >                                                        oname);
1314 >                                        error(USER, errmsg);
1315 >                                }
1316 >                        }
1317 >                                                        /* read in RGB value */
1318 >                        if (!get_contrib(rgbv, sout.ofp)) {
1319 >                                if (!j) {
1320 >                                        fclose(sout.ofp);
1321 >                                        break;          /* ignore empty file */
1322 >                                }
1323 >                                if (j < mp->nbins) {
1324 >                                        sprintf(errmsg, "missing data in '%s'",
1325 >                                                        oname);
1326 >                                        error(USER, errmsg);
1327 >                                }
1328 >                                break;
1329 >                        }
1330 >                        if (j >= mp->nbins)             /* grow modifier size */
1331 >                                ment->data = (char *)(mp = growmodifier(mp, j+1));
1332 >                        copycolor(mp->cbin[j], rgbv);
1333 >                        if (oent->key == NULL)          /* new file entry */
1334 >                                oent->key = strcpy((char *)
1335 >                                                malloc(strlen(oname)+1), oname);
1336 >                        if (oent->data == NULL)
1337 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1338 >                        *(STREAMOUT *)oent->data = sout;
1339 >                }
1340 >        }
1341 >        lu_doall(&ofiletab, myclose, NULL);     /* close all files */
1342 > }
1343 >
1344 > /* seek on the given output file */
1345 > static int
1346 > myseeko(const LUENT *e, void *p)
1347 > {
1348 >        STREAMOUT       *sop = (STREAMOUT *)e->data;
1349 >        off_t           nbytes = *(off_t *)p;
1350 >        
1351 >        if (sop->reclen > 1)
1352 >                nbytes = nbytes * sop->reclen;
1353 >        if (fseeko(sop->ofp, nbytes, SEEK_CUR) < 0) {
1354 >                sprintf(errmsg, "seek error on file '%s'", e->key);
1355 >                error(SYSTEM, errmsg);
1356 >        }
1357 >        return 0;
1358 > }
1359 >
1360 > /* recover output if possible */
1361 > void
1362 > recover_output(FILE *fin)
1363 > {
1364 >        off_t           lastout = -1;
1365 >        int             outvsiz, recsiz;
1366 >        char            *outvfmt;
1367 >        int             i, j;
1368 >        MODCONT         *mp;
1369 >        int             ofl;
1370 >        char            oname[1024];
1371 >        LUENT           *ment, *oent;
1372 >        STREAMOUT       sout;
1373 >        off_t           nvals;
1374 >        int             xr, yr;
1375 >
1376 >        switch (outfmt) {
1377 >        case 'a':
1378 >                error(USER, "cannot recover ASCII output");
1379 >                return;
1380 >        case 'f':
1381 >                outvsiz = sizeof(float)*3;
1382 >                outvfmt = "float";
1383 >                break;
1384 >        case 'd':
1385 >                outvsiz = sizeof(double)*3;
1386 >                outvfmt = "double";
1387 >                break;
1388 >        case 'c':
1389 >                outvsiz = sizeof(COLR);
1390 >                outvfmt = COLRFMT;
1391 >                break;
1392 >        default:
1393 >                error(INTERNAL, "botched output format");
1394 >                return;
1395 >        }
1396 >                                                /* check modifier outputs */
1397 >        for (i = 0; i < nmods; i++) {
1398 >                ment = lu_find(&modconttab,modname[i]);
1399 >                mp = (MODCONT *)ment->data;
1400 >                if (mp->outspec == NULL)
1401 >                        error(USER, "cannot recover from stdout");
1402 >                if (mp->outspec[0] == '!')
1403 >                        error(USER, "cannot recover from command");
1404 >                for (j = 0; ; j++) {            /* check each bin's file */
1405 >                        ofl = ofname(oname, mp->outspec, mp->modname, j);
1406 >                        if (ofl < 0)
1407 >                                error(USER, "bad output file specification");
1408 >                        oent = lu_find(&ofiletab, oname);
1409 >                        if (oent->data != NULL) {
1410 >                                sout = *(STREAMOUT *)oent->data;
1411 >                        } else {
1412 >                                sout.reclen = 0;
1413 >                                sout.outpipe = 0;
1414 >                                sout.ofp = NULL;
1415 >                        }
1416 >                        if (sout.ofp != NULL) { /* already open? */
1417 >                                if (ofl & OF_BIN)
1418 >                                        continue;
1419 >                                break;
1420 >                        }
1421 >                                                /* open output */
1422 >                        sout.ofp = fopen(oname, "rb+");
1423 >                        if (sout.ofp == NULL) {
1424 >                                if (j)
1425 >                                        break;  /* assume end of modifier */
1426 >                                sprintf(errmsg, "missing recover file '%s'",
1427 >                                                oname);
1428 >                                error(WARNING, errmsg);
1429 >                                break;
1430 >                        }
1431 >                        nvals = lseek(fileno(sout.ofp), 0, SEEK_END);
1432 >                        if (nvals <= 0) {
1433 >                                lastout = 0;    /* empty output, quit here */
1434 >                                fclose(sout.ofp);
1435 >                                break;
1436 >                        }
1437 >                        if (!sout.reclen) {
1438 >                                if (!(ofl & OF_BIN)) {
1439 >                                        sprintf(errmsg,
1440 >                                                "need -bn to recover file '%s'",
1441 >                                                        oname);
1442 >                                        error(USER, errmsg);
1443 >                                }
1444 >                                recsiz = outvsiz;
1445 >                        } else
1446 >                                recsiz = outvsiz * sout.reclen;
1447 >
1448 >                        lseek(fileno(sout.ofp), 0, SEEK_SET);
1449 >                        if (header && checkheader(sout.ofp, outvfmt, NULL) != 1) {
1450 >                                sprintf(errmsg, "format mismatch for '%s'",
1451 >                                                oname);
1452 >                                error(USER, errmsg);
1453 >                        }
1454 >                        sout.xr = xres; sout.yr = yres;
1455 >                        if ((sout.xr > 0) & (sout.yr > 0) &&
1456 >                                        (!fscnresolu(&xr, &yr, sout.ofp) ||
1457 >                                                (xr != sout.xr) |
1458 >                                                (yr != sout.yr))) {
1459 >                                sprintf(errmsg, "resolution mismatch for '%s'",
1460 >                                                oname);
1461 >                                error(USER, errmsg);
1462 >                        }
1463 >                        nvals = (nvals - (off_t)ftell(sout.ofp)) / recsiz;
1464 >                        if ((lastout < 0) | (nvals < lastout))
1465 >                                lastout = nvals;
1466 >                        if (oent->key == NULL)  /* new entry */
1467 >                                oent->key = strcpy((char *)
1468 >                                                malloc(strlen(oname)+1), oname);
1469 >                        if (oent->data == NULL)
1470 >                                oent->data = (char *)malloc(sizeof(STREAMOUT));
1471 >                        *(STREAMOUT *)oent->data = sout;
1472 >                        if (!(ofl & OF_BIN))
1473 >                                break;          /* no bin separation */
1474 >                }
1475 >                if (!lastout) {                 /* empty output */
1476 >                        error(WARNING, "no previous data to recover");
1477 >                        lu_done(&ofiletab);     /* reclose all outputs */
1478 >                        return;
1479 >                }
1480 >                if (j > mp->nbins)              /* reallocate modifier bins */
1481 >                        ment->data = (char *)(mp = growmodifier(mp, j));
1482 >        }
1483 >        if (lastout < 0) {
1484 >                error(WARNING, "no output files to recover");
1485 >                return;
1486 >        }
1487 >        if (raysleft && lastout >= raysleft/accumulate) {
1488 >                error(WARNING, "output appears to be complete");
1489 >                /* XXX should read & discard input? */
1490 >                quit(0);
1491 >        }
1492 >                                                /* seek on all files */
1493 >        nvals = lastout * outvsiz;
1494 >        lu_doall(&ofiletab, myseeko, &nvals);
1495 >                                                /* skip repeated input */
1496 >        for (nvals = 0; nvals < lastout; nvals++)
1497 >                if (getinp(oname, fin) < 0)
1498 >                        error(USER, "unexpected EOF on input");
1499 >        lastray = lastdone = (unsigned long)lastout * accumulate;
1500 >        if (raysleft)
1501 >                raysleft -= lastray;
1502   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines