ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/rxpiece.cpp
Revision: 2.7
Committed: Wed Nov 6 18:28:52 2024 UTC (5 months, 3 weeks ago) by greg
Branch: MAIN
Changes since 2.6: +15 -11 lines
Log Message:
perf(rxtrace,rxpict,rxpiece,rxcontrib): Improved exit strategy in children

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.7 static const char RCSid[] = "$Id: rxpiece.cpp,v 2.6 2024/10/31 19:22:36 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * rxpiece.cpp - main for rxpiece tile rendering program
6     */
7    
8     #include "copyright.h"
9    
10     #include <time.h>
11     #include <signal.h>
12     #include <sys/mman.h>
13     #include <unistd.h>
14    
15     #include "platform.h"
16     #include "RpictSimulManager.h"
17 greg 2.5 #include "ambient.h"
18     #include "pmapray.h"
19 greg 2.1 #include "random.h"
20    
21     extern char *progname; /* argv[0] */
22     const char *sigerr[NSIG]; /* signal error messages */
23    
24     VIEW ourview = STDVIEW; /* global view parameters */
25     int hresolu = 1024; /* horizontal resolution */
26     int vresolu = 1024; /* vertical resolution */
27     double pixaspect = 1.0; /* pixel aspect ratio */
28     int hres, vres; /* current image resolution for srcdraw.c */
29    
30     int tileGrid[2] = {5,5}; // tile subdivisions
31    
32     int psample = 4; /* pixel sample size */
33     double maxdiff = .05; /* max. difference for interpolation */
34     double dstrpix = 0.67; /* square pixel distribution */
35    
36     double mblur = 0.; /* motion blur parameter (unused) */
37    
38     double dblur = 0.; /* depth-of-field blur parameter */
39    
40 greg 2.7 int nproc = 1; /* number of processes to run (-1 in child) */
41 greg 2.1
42     RpictSimulManager myRPmanager; // global simulation manager
43    
44     static void onsig(int signo);
45     static void onalrm(int signo);
46     static void sigdie(int signo, const char *msg);
47     static void printdefaults(void);
48     static RenderDataType rpiece(char *pout, RenderDataType dt, char *zout);
49    
50     /* rxpiece additional features */
51     #define RXPIECE_FEATURES "Recovery\nIrradianceCalc\nViewTypes=v,l,a,h,s,c\n" \
52     "ParticipatingMedia=Mist\n" \
53     "HessianAmbientCache\nAmbientAveraging\nAmbientValueSharing\n" \
54     "PixelJitter\nPixelSampling\nPixelDepthOfField\n" \
55     "SmallSourceDrawing\n" \
56     "AdaptiveShadowTesting\nOutputs=v,l\n" \
57     "OutputCS=RGB,XYZ,prims,spec\n"
58    
59    
60 greg 2.7 // Exit program
61 greg 2.1 void
62     quit(int code) /* quit program */
63     {
64 greg 2.7 if (nproc < 0) {
65     ray_pnprocs = -1; // hack to avoid cleanup in child
66     _exit(code);
67     }
68     exit(code); // parent still frees everything (*yawn*)
69 greg 2.1 }
70    
71    
72     int
73     main(int argc, char *argv[])
74     {
75     #define check(ol,al) if (argv[i][ol] || \
76     badarg(argc-i-1,argv+i+1,al)) \
77     goto badopt
78     #define check_bool(olen,var) switch (argv[i][olen]) { \
79     case '\0': var = !var; break; \
80     case 'y': case 'Y': case 't': case 'T': \
81     case '+': case '1': var = 1; break; \
82     case 'n': case 'N': case 'f': case 'F': \
83     case '-': case '0': var = 0; break; \
84     default: goto badopt; }
85     RGBPRIMS our_prims; /* private output color primitives */
86     RenderDataType dtype = RDTrgbe; // output data flags
87     char *outfile = NULL;
88     char *zfile = NULL;
89     int outfmt = 'c';
90     int rval;
91     int i;
92     /* global program name */
93     progname = argv[0];
94     /* feature check only? */
95     strcat(RFeatureList, RXPIECE_FEATURES);
96     if (argc > 1 && !strcmp(argv[1], "-features"))
97     return feature_status(argc-2, argv+2);
98     /* option city */
99     for (i = 1; i < argc; i++) {
100     /* expand arguments */
101     while ((rval = expandarg(&argc, &argv, i)) > 0)
102     ;
103     if (rval < 0) {
104     sprintf(errmsg, "cannot expand '%s'", argv[i]);
105     error(SYSTEM, errmsg);
106     }
107     if (argv[i] == NULL || argv[i][0] != '-')
108     break; /* break from options */
109     if (!strcmp(argv[i], "-version")) {
110     puts(VersionID);
111     quit(0);
112     }
113     if (!strcmp(argv[i], "-defaults") ||
114     !strcmp(argv[i], "-help")) {
115     printdefaults();
116     quit(0);
117     }
118     rval = getrenderopt(argc-i, argv+i);
119     if (rval >= 0) {
120     i += rval;
121     continue;
122     }
123     rval = getviewopt(&ourview, argc-i, argv+i);
124     if (rval >= 0) {
125     i += rval;
126     continue;
127     }
128     /* rxpiece options */
129     switch (argv[i][1]) {
130     case 'v': /* view file */
131     if (argv[i][2] != 'f')
132     goto badopt;
133     check(3,"s");
134     rval = viewfile(argv[++i], &ourview, NULL);
135     if (rval < 0) {
136     sprintf(errmsg,
137     "cannot open view file \"%s\"",
138     argv[i]);
139     error(SYSTEM, errmsg);
140     } else if (rval == 0) {
141     sprintf(errmsg,
142     "bad view file \"%s\"",
143     argv[i]);
144     error(USER, errmsg);
145     }
146     break;
147     case 'n': /* number of processes */
148     check(2,"i");
149     nproc = atoi(argv[++i]);
150     if (nproc < 0 && (nproc += RadSimulManager::GetNCores()) <= 0)
151     nproc = 1;
152     break;
153     case 'f': /* output format */
154     if ((argv[i][2] != 'c') & (argv[i][2] != 'f')
155     || argv[i][3])
156     goto badopt;
157     outfmt = argv[i][2];
158     break;
159     case 'p': /* pixel */
160     switch (argv[i][2]) {
161     case 's': /* sample */
162     check(3,"i");
163     psample = atoi(argv[++i]);
164     if (psample < 1) psample = 1;
165     break;
166     case 't': /* threshold */
167     check(3,"f");
168     maxdiff = atof(argv[++i]);
169     break;
170     case 'j': /* jitter */
171     check(3,"f");
172     dstrpix = atof(argv[++i]);
173     break;
174     case 'a': /* aspect */
175     check(3,"f");
176     pixaspect = atof(argv[++i]);
177     break;
178     case 'd': /* aperture */
179     check(3,"f");
180     dblur = atof(argv[++i]);
181     dblur *= (dblur > 0);
182     break;
183     case 'R': /* standard RGB output */
184     if (strcmp(argv[i]+2, "RGB"))
185     goto badopt;
186     myRPmanager.prims = stdprims;
187     dtype = RDTnewCT(dtype, RDTrgbe);
188     break;
189     case 'X': /* XYZ output */
190     if (strcmp(argv[i]+2, "XYZ"))
191     goto badopt;
192     myRPmanager.prims = xyzprims;
193     dtype = RDTnewCT(dtype, RDTxyze);
194     break;
195     case 'c': /* chromaticities */
196     check(3,"ffffffff");
197     rval = 0;
198     for (int j = 0; j < 8; j++) {
199     our_prims[0][j] = atof(argv[++i]);
200     rval |= fabs(our_prims[0][j]-stdprims[0][j]) > .001;
201     }
202     if (rval) {
203     if (!colorprimsOK(our_prims))
204     error(USER, "illegal primary chromaticities");
205     myRPmanager.prims = our_prims;
206     } else
207     myRPmanager.prims = stdprims;
208     dtype = RDTnewCT(dtype, RDTrgbe);
209     break;
210     default:
211     goto badopt;
212     }
213     break;
214     case 'd': /* reference depth */
215     if (argv[i][2] || !myRPmanager.SetReferenceDepth(argv[++i]))
216     goto badopt;
217     dtype = RDTnewDT(dtype, RDTdshort);
218     break;
219     case 'x': /* x resolution */
220     check(2,"i");
221     hresolu = atoi(argv[++i]);
222     break;
223     case 'y': /* y resolution */
224     check(2,"i");
225     vresolu = atoi(argv[++i]);
226     break;
227     case 'X': /* horizontal tile subdivisions */
228     check(2,"i");
229     tileGrid[0] = atoi(argv[++i]);
230     break;
231     case 'Y': /* vertical tile subdivisions */
232     check(2,"i");
233     tileGrid[1] = atoi(argv[++i]);
234     break;
235     case 'o': /* output file */
236     check(2,"s");
237     outfile = argv[++i];
238     break;
239     case 'z': /* z file */
240     check(2,"s");
241     zfile = argv[++i];
242     break;
243     #if MAXCSAMP>3
244     case 'c': /* output spectral results */
245     if (argv[i][2] != 'o')
246     goto badopt;
247     rval = (myRPmanager.prims == NULL);
248     check_bool(3,rval);
249     if (rval)
250     myRPmanager.prims = NULL;
251     else if (myRPmanager.prims == NULL)
252     myRPmanager.prims = stdprims;
253     dtype = RDTnewCT(dtype, rval ? RDTscolr : RDTrgbe);
254     break;
255     #endif
256     case 'w': /* warnings */
257     rval = erract[WARNING].pf != NULL;
258     check_bool(2,rval);
259     if (rval) erract[WARNING].pf = wputs;
260     else erract[WARNING].pf = NULL;
261     break;
262     default:
263     goto badopt;
264     }
265     }
266     if (maxdiff <= FTINY) /* check for useless sampling */
267     psample = 1;
268     if (outfile == NULL)
269     error(USER, "missing output file (-o option)");
270     if (zfile == NULL) /* set up depth output */
271     dtype = RDTnewDT(dtype, RDTnone);
272     else if (!RDTdepthT(dtype))
273     dtype = RDTnewDT(dtype, RDTdfloat);
274     /* check pixel output type */
275     if ((myRPmanager.prims == NULL) & (NCSAMP == 3)) {
276     myRPmanager.prims = stdprims;
277     dtype = RDTnewCT(dtype, RDTrgbe);
278     }
279     if (outfmt == 'f')
280     switch (RDTcolorT(dtype)) {
281     case RDTrgbe:
282     dtype = RDTnewCT(dtype, RDTrgb);
283     break;
284     case RDTxyze:
285     dtype = RDTnewCT(dtype, RDTxyz);
286     break;
287     case RDTscolr:
288     dtype = RDTnewCT(dtype, RDTscolor);
289     break;
290     case RDTrgb:
291     case RDTxyz:
292     case RDTscolor:
293     break;
294     default:
295     error(INTERNAL, "botched color output type");
296     }
297     /* set up signal handling */
298     sigdie(SIGINT, "Interrupt");
299     sigdie(SIGHUP, "Hangup");
300     sigdie(SIGTERM, "Terminate");
301     sigdie(SIGPIPE, "Broken pipe");
302     signal(SIGALRM, onalrm); // used to gracefully terminate
303     #ifdef SIGXCPU
304     sigdie(SIGXCPU, "CPU limit exceeded");
305     sigdie(SIGXFSZ, "File size exceeded");
306     #endif
307     #ifdef NICE
308     nice(NICE); /* lower priority */
309     #endif
310     if (i < argc-1)
311     goto badopt;
312     // load octree
313     if (!myRPmanager.LoadOctree(argv[i]))
314     error(USER, "missing octree argument");
315     // add new header info
316     myRPmanager.AddHeader(i, argv);
317     {
318     char buf[128] = "SOFTWARE= ";
319     strcpy(buf+10, VersionID);
320     myRPmanager.AddHeader(buf);
321     }
322     // render tiles
323     dtype = rpiece(outfile, dtype, zfile);
324    
325 greg 2.7 ambsync(); // flush ambient cache
326    
327     ray_done_pmap(); /* PMAP: free photon maps */
328    
329 greg 2.5 quit(dtype==RDTnone); // status is 1 on failure
330 greg 2.1
331     badopt:
332     sprintf(errmsg, "command line error at '%s'", argv[i]);
333     error(USER, errmsg);
334     return 1; /* pro forma return */
335    
336     #undef check
337     #undef check_bool
338     }
339    
340    
341     void
342     wputs( /* warning output function */
343     const char *s
344     )
345     {
346 greg 2.6 if (!erract[WARNING].pf)
347     return; // warnings were disabled!
348 greg 2.1 int lasterrno = errno;
349     eputs(s);
350     errno = lasterrno;
351     }
352    
353    
354     void
355     eputs( /* put string to stderr */
356     const char *s
357     )
358     {
359     static int midline = 0;
360    
361     if (!*s)
362     return;
363     if (!midline++) {
364     fputs(progname, stderr);
365     fputs(": ", stderr);
366     }
367     fputs(s, stderr);
368     if (s[strlen(s)-1] == '\n') {
369     fflush(stderr);
370     midline = 0;
371     }
372     }
373    
374    
375     static void
376     onsig( /* fatal signal */
377     int signo
378     )
379     {
380     static int gotsig = 0;
381    
382     if (gotsig++) /* two signals and we're gone! */
383     _exit(signo);
384    
385     alarm(30); /* allow 30 seconds to clean up */
386     signal(SIGALRM, SIG_DFL); /* make certain we do die */
387     eputs("signal - ");
388     eputs(sigerr[signo]);
389     eputs("\n");
390     quit(3);
391     }
392    
393    
394     static bool gotALRM = false; // flag for ALRM signal
395    
396     static void
397     onalrm(int signo)
398     {
399     gotALRM = true;
400     }
401    
402    
403     static void
404     sigdie( /* set fatal signal */
405     int signo,
406     const char *msg
407     )
408     {
409     if (signal(signo, onsig) == SIG_IGN)
410     signal(signo, SIG_IGN);
411     sigerr[signo] = msg;
412     }
413    
414    
415     static void
416     printdefaults(void) /* print default values to stdout */
417     {
418     printf("-n %-2d\t\t\t\t# number of rendering processes\n", nproc);
419     printf("-vt%c\t\t\t\t# view type %s\n", ourview.type,
420     ourview.type==VT_PER ? "perspective" :
421     ourview.type==VT_PAR ? "parallel" :
422     ourview.type==VT_HEM ? "hemispherical" :
423     ourview.type==VT_ANG ? "angular" :
424     ourview.type==VT_CYL ? "cylindrical" :
425     ourview.type==VT_PLS ? "planisphere" :
426     "unknown");
427     printf("-vp %f %f %f\t# view point\n",
428     ourview.vp[0], ourview.vp[1], ourview.vp[2]);
429     printf("-vd %f %f %f\t# view direction\n",
430     ourview.vdir[0], ourview.vdir[1], ourview.vdir[2]);
431     printf("-vu %f %f %f\t# view up\n",
432     ourview.vup[0], ourview.vup[1], ourview.vup[2]);
433     printf("-vh %f\t\t\t# view horizontal size\n", ourview.horiz);
434     printf("-vv %f\t\t\t# view vertical size\n", ourview.vert);
435     printf("-vo %f\t\t\t# view fore clipping plane\n", ourview.vfore);
436     printf("-va %f\t\t\t# view aft clipping plane\n", ourview.vaft);
437     printf("-vs %f\t\t\t# view shift\n", ourview.hoff);
438     printf("-vl %f\t\t\t# view lift\n", ourview.voff);
439     printf("-x %-9d\t\t\t# x resolution\n", hresolu);
440     printf("-y %-9d\t\t\t# y resolution\n", vresolu);
441     printf("-X %-9d\t\t\t# horizontal tile divisions\n", tileGrid[0]);
442     printf("-Y %-9d\t\t\t# vertical tile divisions\n", tileGrid[1]);
443     if (myRPmanager.prims == stdprims)
444     printf("-pRGB\t\t\t\t# standard RGB color output\n");
445     else if (myRPmanager.prims == xyzprims)
446     printf("-pXYZ\t\t\t\t# CIE XYZ color output\n");
447     else if (myRPmanager.prims != NULL)
448     printf("-pc %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f\t# output color primaries and white point\n",
449     myRPmanager.prims[RED][0], myRPmanager.prims[RED][1],
450     myRPmanager.prims[GRN][0], myRPmanager.prims[GRN][1],
451     myRPmanager.prims[BLU][0], myRPmanager.prims[BLU][1],
452     myRPmanager.prims[WHT][0], myRPmanager.prims[WHT][1]);
453     if (NCSAMP > 3)
454     printf(myRPmanager.prims != NULL ? "-co-\t\t\t\t# output tristimulus colors\n" :
455     "-co+\t\t\t\t# output spectral values\n");
456     printf("-pa %f\t\t\t# pixel aspect ratio\n", pixaspect);
457     printf("-pj %f\t\t\t# pixel jitter\n", dstrpix);
458     printf("-pd %f\t\t\t# pixel depth-of-field\n", dblur);
459     printf("-ps %-9d\t\t\t# pixel sample\n", psample);
460     printf("-pt %f\t\t\t# pixel threshold\n", maxdiff);
461     printf(erract[WARNING].pf != NULL ?
462     "-w+\t\t\t\t# warning messages on\n" :
463     "-w-\t\t\t\t# warning messages off\n");
464     print_rdefaults();
465     }
466    
467    
468     // Struct for tracking tiles being rendered in mapped file / shared memory
469     struct TileProg {
470     short status; // 0==Unstarted, -1==InProgress, 1==Done
471     pid_t pID; // process operating on tile
472     } *tprog = NULL; // shared tile progress array
473    
474     #define tile_p(ti) (tprog + (ti)[1]*tileGrid[0] + (ti)[0])
475    
476     // Return true if tile is renderable
477     static bool
478     renderable_tile(TileProg *tp)
479     {
480     if (tp->status < 0 && kill(tp->pID, 0) < 0)
481     tp->status = 0; // dead process - reset
482    
483     return !tp->status;
484     }
485    
486    
487     // handle multi-processing if requested, return true if all done
488     static bool
489     children_finished()
490     {
491     if (nproc <= 1) // single process -> run in parent
492     return false;
493     int cnt = 0; // else count ready-to-go tiles
494     int ti[2];
495     for (ti[1] = 0; ti[1] < tileGrid[1]; ti[1]++)
496     for (ti[0] = 0; ti[0] < tileGrid[0]; ti[0]++)
497     cnt += renderable_tile(tile_p(ti));
498 greg 2.2 if (!cnt)
499     return false; // parent can do nothing
500 greg 2.1 if (cnt < nproc) {
501     sprintf(errmsg, "only %d renderable tiles, reducing process count", cnt);
502     error(WARNING, errmsg);
503     if ((nproc = cnt) == 1)
504     return false; // back to single process
505     }
506     cow_memshare(); // else we'll be sharing memory
507     fflush(NULL); // and forking children
508     pid_t cpid; // create nproc children
509     for (cnt = nproc; cnt && (cpid = fork()) != 0; cnt--)
510     if (cpid < 0)
511     error(SYSTEM, "fork error!");
512    
513     if (cpid == 0) { // children render tiles
514     sleep(nproc - cnt); // avoid race conditions
515 greg 2.7 nproc = -1; // flag as child
516 greg 2.1 return false;
517     }
518     cow_doneshare(); // parent frees memory and waits
519     signal(SIGALRM, SIG_IGN);
520     myRPmanager.Cleanup(true);
521     int nfailed = 0;
522     int status;
523     for (cnt = nproc; cnt && wait(&status) > 0; cnt--)
524     if (status) {
525     sprintf(errmsg, "child exited with status %d", status);
526     error(WARNING, errmsg);
527     if (!nfailed++ & (cnt > 1)) {
528     kill(0, SIGALRM);
529     error(WARNING, "waiting for other tiles to finish...");
530     }
531     }
532     if (cnt) {
533     sprintf(errmsg, "lost track of %d children", cnt);
534     error(WARNING, errmsg);
535     }
536     if (nfailed) {
537     sprintf(errmsg, "%d tiles were not completed", nfailed);
538     error(USER, errmsg);
539     }
540     return true; // all done!
541     }
542    
543     // return next renderable tile, false if everything is done
544     static bool
545     nexttile(int ti[2])
546     {
547     static pid_t ourpID = 0;
548     static short * tlist = NULL;
549     static int tlen = 0;
550     static int tnext = 0;
551    
552     if (gotALRM) { // pre-empting new work?
553     if (tlist) {
554     sprintf(errmsg, "process %d got alarm, exiting", ourpID);
555     CHECK(tnext<tlen, WARNING, errmsg);
556     free(tlist); tlist = NULL;
557     }
558     return false;
559     }
560     if (!tlist) { // initialize random tile list
561     ABitMap2 todoMap(tileGrid[0], tileGrid[1]);
562     tlen = 0;
563     for (ti[1] = 0; ti[1] < tileGrid[1]; ti[1]++)
564     for (ti[0] = 0; ti[0] < tileGrid[0]; ti[0]++)
565     if (renderable_tile(tile_p(ti))) {
566     todoMap.Set(ti[0], ti[1]);
567     tlen++;
568     }
569     if (!tlen)
570     return false; // nothing to do!
571     tlist = (short *)malloc(sizeof(short)*2*tlen);
572     CHECK(!tlist, SYSTEM, "out of memory in nexttile()");
573     tlen = 0; // assign entries
574     for (ti[0] = ti[1] = 0; todoMap.Find(&ti[0], &ti[1]); ti[0]++) {
575     tlist[2*tlen] = ti[0];
576     tlist[2*tlen+1] = ti[1];
577     tlen++;
578     }
579     // shuffle order w/ Fisher-Yates
580     for (int i = 0; i < tlen-1; i++) {
581     const int ix = irandom(tlen-i) + i;
582     ti[0] = tlist[2*i];
583     ti[1] = tlist[2*i+1];
584     tlist[2*i] = tlist[2*ix];
585     tlist[2*i+1] = tlist[2*ix+1];
586     tlist[2*ix] = ti[0];
587     tlist[2*ix+1] = ti[1];
588     }
589     ourpID = getpid(); // save time on system calls
590     }
591     while (tnext < tlen) { // find first available
592     ti[0] = tlist[2*tnext];
593     ti[1] = tlist[2*tnext+1];
594     tnext++; // take if still unclaimed
595     if (renderable_tile(tile_p(ti))) {
596     tile_p(ti)->status = -1;
597     tile_p(ti)->pID = ourpID;
598     return true;
599     }
600     }
601     free(tlist); tlist = NULL; // exhausted our list?
602     return false;
603     }
604    
605    
606     // Principal function for rpiece
607     static RenderDataType
608     rpiece(char *pout, RenderDataType dt, char *zout)
609     {
610     if (zout && *zout == '!')
611     error(USER, "cannot send depth to a command");
612    
613     const bool newOutput = (access(pout, F_OK) < 0);
614     FILE *pdfp[2];
615 greg 2.4 if (newOutput) { // new output file?
616     CHECK((tileGrid[0] <= 1) & (tileGrid[1] <= 1),
617     USER, "bad tiling specification");
618     } else {
619 greg 2.1 dt = myRPmanager.ReopenOutput(pdfp, pout, zout);
620     if (dt == RDTnone)
621 greg 2.7 return RDTnone;
622 greg 2.1 if (!fscnresolu(&hresolu, &vresolu, pdfp[0]))
623     error(USER, "missing picture resolution");
624 greg 2.2 pixaspect = .0; // need to leave this as is
625 greg 2.1 myRPmanager.NewHeader(pout); // get prev. header info
626     const char * tval = myRPmanager.GetHeadStr("TILED=");
627     if (tval) sscanf(tval, "%d %d", &tileGrid[0], &tileGrid[1]);
628 greg 2.4 CHECK(myRPmanager.GetView()==NULL,
629     USER, "missing view in picture file");
630 greg 2.1 ourview = *myRPmanager.GetView();
631     }
632     int hvdim[2] = {hresolu, vresolu}; // set up tiled frame
633     if (!myRPmanager.NewFrame(ourview, hvdim, &pixaspect, tileGrid))
634     error(USER, "tiling setup error in rpiece");
635    
636     if ((hvdim[0] != hresolu) | (hvdim[1] != vresolu)) {
637     if (!newOutput)
638     error(USER, "unexpected output size adjustment");
639     sprintf(errmsg, "resolution adjusted from %dx%d to %dx%d",
640     hresolu, vresolu, hvdim[0], hvdim[1]);
641     error(WARNING, errmsg);
642     hresolu = hvdim[0];
643     vresolu = hvdim[1];
644     }
645     if (newOutput){ // open new output here
646     char buf[64];
647     sprintf(buf, "TILED= %d %d\n", tileGrid[0], tileGrid[1]);
648     myRPmanager.AddHeader(buf);
649     dt = myRPmanager.NewOutput(pdfp, pout, dt, zout);
650     if (dt == RDTnone)
651 greg 2.7 return RDTnone;
652 greg 2.1 fprtresolu(hresolu, vresolu, pdfp[0]);
653 greg 2.5 fflush(pdfp[0]);
654     if (RDTdepthT(dt) == RDTdshort) {
655 greg 2.1 fprtresolu(hresolu, vresolu, pdfp[1]);
656 greg 2.5 fflush(pdfp[1]);
657     }
658     } else if (RDTdepthT(dt) == RDTdshort &&
659     (!fscnresolu(&hvdim[0], &hvdim[1], pdfp[1]) ||
660     (hvdim[0] != hresolu) | (hvdim[1] != vresolu)))
661     error(USER, "mismatched depth file resolution");
662 greg 2.1 // prepare (flat) pixel buffer
663     const long pdata_beg = ftell(pdfp[0]);
664     const size_t pixSiz = (RDTcolorT(dt)==RDTrgbe)|(RDTcolorT(dt)==RDTxyze) ? sizeof(COLR)
665     : (RDTcolorT(dt)==RDTrgb)|(RDTcolorT(dt)==RDTxyz) ? sizeof(COLORV)*3
666     : RDTcolorT(dt)==RDTscolr ? LSCOLR : sizeof(COLORV)*NCSAMP;
667     size_t pmlen = pdata_beg + pixSiz*hresolu*vresolu;
668     // put tile progress array at end
669     if (pmlen&7) pmlen += 8 - (pmlen&7); // 8-byte alignment to be safe
670     pmlen += sizeof(TileProg)*tileGrid[0]*tileGrid[1];
671     // map picture file to memory
672 greg 2.4 if (newOutput && ftruncate(fileno(pdfp[0]), pmlen) < 0)
673 greg 2.1 error(SYSTEM, "cannot extend picture buffer");
674     uby8 * pixMap = (uby8 *)mmap(NULL, pmlen, PROT_READ|PROT_WRITE,
675     MAP_SHARED, fileno(pdfp[0]), 0);
676     if ((void *)pixMap == MAP_FAILED)
677     error(SYSTEM, "cannot map picture file into memory");
678     // map depth buffer to memory
679     const long zdata_beg = RDTdepthT(dt) ? ftell(pdfp[1]) : 0L;
680     const size_t zdpSiz = RDTdepthT(dt)==RDTdshort ? sizeof(short) :
681     RDTdepthT(dt)==RDTdfloat ? sizeof(float) : 0;
682     const size_t zmlen = zdata_beg + zdpSiz*hresolu*vresolu;
683     uby8 * zdMap = NULL;
684     if (RDTdepthT(dt)) {
685 greg 2.4 if (newOutput && ftruncate(fileno(pdfp[1]), zmlen) < 0)
686 greg 2.1 error(SYSTEM, "cannot extend depth buffer");
687     zdMap = (uby8 *)mmap(NULL, zmlen, PROT_READ|PROT_WRITE,
688     MAP_SHARED, fileno(pdfp[1]), 0);
689     if ((void *)zdMap == MAP_FAILED)
690     error(SYSTEM, "cannot map depth file into memory");
691     }
692     fclose(pdfp[0]); // done with file pointers
693     if (RDTdepthT(dt)) fclose(pdfp[1]);
694     // point to tile progress array
695     tprog = (TileProg *)(pixMap + pmlen - sizeof(TileProg)*tileGrid[0]*tileGrid[1]);
696    
697     if (children_finished()) // work done in children?
698     return dt;
699    
700 greg 2.2 int ndone = 0; // else render tiles
701     int ti[2];
702 greg 2.1 while (nexttile(ti)) {
703     const int offset = (tileGrid[1]-1-ti[1])*myRPmanager.GetWidth()*myRPmanager.THeight() +
704     (myRPmanager.THeight()-1)*myRPmanager.GetWidth() +
705     ti[0]*myRPmanager.TWidth();
706     uby8 * pptr = pixMap + pdata_beg + pixSiz*offset;
707     uby8 * zptr = zdMap + zdata_beg + zdpSiz*offset;
708     bool ok = false;
709     switch (RDTcommonE(dt)<<1 | (RDTdepthT(dt)==RDTdshort)) {
710     case 2: // common-exponent color, float/no depth
711     ok = myRPmanager.RenderTile((COLRV *)pptr, -myRPmanager.GetWidth(),
712     (float *)zptr, ti);
713     break;
714     case 0: // float color, float/no depth
715     ok = myRPmanager.RenderTile((COLORV *)pptr, -myRPmanager.GetWidth(),
716     (float *)zptr, ti);
717     break;
718     case 3: // common-exponent color, encoded depth
719     ok = myRPmanager.RenderTile((COLRV *)pptr, -myRPmanager.GetWidth(),
720     (short *)zptr, ti);
721     break;
722     case 1: // float color, encoded depth
723     ok = myRPmanager.RenderTile((COLORV *)pptr, -myRPmanager.GetWidth(),
724     (short *)zptr, ti);
725     break;
726     }
727     if (!ok) { // got an error
728     sprintf(errmsg, "error rendering tile (%d,%d)/(%d,%d)",
729     ti[0], ti[1], tileGrid[0], tileGrid[1]);
730     error(USER, errmsg);
731     }
732     tile_p(ti)->status = 1; // mark tile completed
733 greg 2.3 ndone++;
734 greg 2.1 }
735 greg 2.2 if (!ndone)
736     error(WARNING, "no tiles need rendering, exit");
737 greg 2.1 /*
738     munmap(pixMap, pmlen); // technically unnecessary...
739     if (zdMap) munmap(zdMap, zmlen);
740     */
741     return dt; // we're done here
742     }