ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/RpictSimulManager.cpp
Revision: 2.2
Committed: Sun Aug 18 00:37:13 2024 UTC (8 months, 2 weeks ago) by greg
Branch: MAIN
Changes since 2.1: +28 -30 lines
Log Message:
fix(rxpict): Fixed fill algorithm for pixel sampling

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.2 static const char RCSid[] = "$Id: RpictSimulManager.cpp,v 2.1 2024/08/14 20:05:23 greg Exp $";
3 greg 2.1 #endif
4     /*
5     * RpictSimulManager.cpp
6     *
7     * Rpict simulation manager implementation
8     *
9     * Created by Greg Ward on 07/11/2024.
10     */
11    
12     #include <ctype.h>
13     #include "platform.h"
14     #include "RpictSimulManager.h"
15     #include "depthcodec.h"
16     #include "random.h"
17    
18     /************* Imported globals from rxpmain.c *************/
19    
20     extern VIEW ourview; /* viewing parameters */
21     extern int hres, vres; /* current image resolution */
22    
23     extern int psample; /* pixel sample size */
24     extern double maxdiff; /* max. sample difference */
25     extern double dstrpix; /* square pixel distribution */
26    
27     extern double mblur; /* motion blur parameter */
28    
29     extern double dblur; /* depth-of-field blur parameter */
30    
31     // Assign a pixel value (& depth) from rendered ray value
32     bool
33     PixelAccess::SetPixel(int x, int y, const RAY *rp)
34     {
35     if (!rp) return false;
36    
37     COLOR col;
38     float zv = 0; // get depth if needed
39     if (DepthType())
40     zv = raydistance(rp);
41    
42     switch (ColorSpace()) {
43     case RDTscolor: // keeping rendered spectrum?
44     case RDTscolr:
45     return SetPixel(x, y, rp->rcol, zv);
46     case RDTrgb:
47     case RDTrgbe:
48     case RDTxyz:
49     case RDTxyze:
50     scolor_out(col, primp, rp->rcol);
51     return SetPixel(x, y, col, zv);
52     default:
53 greg 2.2 error(INTERNAL, "botched color space type in SetPixel()");
54 greg 2.1 }
55     return false;
56     }
57    
58     // Set color space after non-empty initialization
59     bool
60     PixelAccess::SetColorSpace(RenderDataType cs, RGBPRIMP pr)
61     {
62     if (!dtyp) return false;
63    
64     if (!(cs = RDTcolorT(cs)))
65     cs = RDTcolorT(dtyp);
66     else if (RDTcommonE(cs) ^ RDTcommonE(dtyp))
67     return false;
68    
69     if (NCSAMP == 3) {
70     if (cs == RDTscolr) cs = RDTrgbe;
71     else if (cs == RDTscolor) cs = RDTrgb;
72     }
73     switch (cs) {
74     case RDTxyze:
75     case RDTxyz:
76     primp = xyzprims;
77     break;
78     case RDTrgbe:
79     case RDTrgb:
80     primp = pr ? pr : stdprims;
81     break;
82 greg 2.2 case RDTscolr:
83     case RDTscolor:
84 greg 2.1 primp = NULL;
85     break;
86 greg 2.2 default:
87     error(INTERNAL, "botched color space type in SetColorSpace()");
88 greg 2.1 }
89     dtyp = RDTnewCT(dtyp, cs);
90     return true;
91     }
92    
93     /*
94     * Set up rendering frame (call after octree loaded)
95     * Overall dimensions may be adjusted for view,
96     * optional pixel aspect ratio and tile grid
97     * Increments frameNo if >0
98     */
99     bool
100     RpictSimulManager::NewFrame(const VIEW &v, int xydim[2], double *ap, const int *tgrid)
101     {
102     double pasp = 1.;
103    
104     if (!xydim) return false;
105     if (!ap) ap = &pasp;
106     pvw = vw; // save previous view for motion blur
107     vw = v;
108     const char * verr = setview(&vw);
109     if (verr) {
110     error(WARNING, verr);
111     vw = pvw;
112     return false;
113     }
114     const double va = viewaspect(&vw);
115     normaspect(va, ap, &xydim[0], &xydim[1]);
116     // set up tiling?
117     if (tgrid && (tgrid[0] > 0) & (tgrid[1] > 0) & (tgrid[0]*tgrid[1] > 1)) {
118     if ((8*tgrid[0] >= xydim[0]) | (8*tgrid[1] >= xydim[1])) {
119     error(WARNING, "Excessive tiling for image size");
120     return false;
121     }
122     xydim[0] -= xydim[0] % (tgsize[0] = tgrid[0]);
123     xydim[1] -= xydim[1] % (tgsize[1] = tgrid[1]);
124     *ap = va * xydim[0] / xydim[1];
125     } else
126     tgsize[0] = tgsize[1] = 1;
127    
128     if (vw.vaft > FTINY) rtFlags |= RTlimDist;
129     else rtFlags &= ~RTlimDist;
130     hvres[0] = xydim[0]; hvres[1] = xydim[1];
131     thvres[0] = hvres[0]/tgsize[0]; // presumed tile width
132     thvres[1] = hvres[1]/tgsize[1]; // ...and height
133     frameNo += (frameNo > 0); // caller may override after
134     return true;
135     }
136    
137     // Call-back for rendered pixel
138     int
139     RpictSimulManager::RtCall(RAY *r, void *cd)
140     {
141     RpictSimulManager * rsp = (RpictSimulManager *)cd;
142 greg 2.2 const int ty = (r->rno-1) / rsp->TWidth();
143     const int tx = r->rno-1 - (RNUMBER)ty*rsp->TWidth();
144 greg 2.1
145     if (ty >= rsp->THeight()) {
146     error(INTERNAL, "bad pixel calculation position in RtCall()");
147     return -1;
148     }
149     if (!rsp->doneMap.TestAndSet(tx, ty)) {
150     error(WARNING, "duplicate pixel calculation");
151     return 0;
152     }
153     return rsp->pacc.SetPixel(tx, ty, r);
154     }
155    
156     // Set up the specified tile (or entire image if NULL)
157     bool
158     RpictSimulManager::SetTile(const int ti[2])
159     {
160     tvw = vw; ptvw = pvw;
161    
162     if (ti) {
163     if ((ti[0] < 0) | (ti[0] >= tgsize[0]) |
164     (ti[1] < 0) | (ti[1] >= tgsize[1])) {
165     error(INTERNAL, "illegal tile specification in SetTile()");
166     return false;
167     }
168     const char * verr = cropview(&tvw,
169     (double)ti[0]/tgsize[0],
170     (double)ti[1]/tgsize[1],
171     (ti[0]+1.)/tgsize[0],
172     (ti[1]+1.)/tgsize[1]);
173     if (verr) {
174     sprintf(errmsg, "crop failure @ tile (%d,%d)/(%d,%d): %s",
175     ti[0], ti[1], tgsize[0], tgsize[1], verr);
176     error(USER, errmsg);
177     return false;
178     } // previous tile view for blur
179     if (!ptvw.type | (mblur <= FTINY) ||
180     cropview(&ptvw, (double)ti[0]/tgsize[0],
181     (double)ti[1]/tgsize[1],
182     (ti[0]+1.)/tgsize[0],
183     (ti[1]+1.)/tgsize[1]))
184     ptvw.type = 0;
185    
186     } else if ((tgsize[0] > 1) | (tgsize[1] > 1)) {
187     error(INTERNAL, "missing tile specification in SetTile()");
188     return false;
189     }
190     return doneMap.NewBitMap(TWidth(), THeight());
191     }
192    
193     #define pixjitter() (.5+dstrpix*(.5-frandom()))
194    
195     // Send the indicated pixel to ray tracer
196     bool
197     RpictSimulManager::ComputePixel(int x, int y)
198     {
199     static const SCOLOR scBlack = {0};
200     int i;
201     FVECT rodir[2];
202     double hpos = (x+pixjitter())/TWidth();
203     double vpos = (y+pixjitter())/THeight();
204     double dlim = viewray(rodir[0], rodir[1], &tvw, hpos, vpos);
205     if (dlim < -FTINY) { // off view?
206     pacc.SetPixel(x, y, scBlack);
207     doneMap.Set(x, y);
208     return true;
209     }
210     if (ptvw.type) { // add motion blur if requested
211     FVECT rorg2, rdir2;
212     double dlim2 = viewray(rorg2, rdir2, &ptvw, hpos, vpos);
213     if (dlim2 >= -FTINY) {
214     const double d = mblur*(.5-frandom());
215     dlim = (1.-d)*dlim + d*dlim2;
216     for (i = 3; i--; ) {
217     rodir[0][i] = (1.-d)*rodir[0][i] + d*rorg2[i];
218     rodir[1][i] = (1.-d)*rodir[1][i] + d*rdir2[i];
219     }
220     if (normalize(rodir[1]) == 0)
221     return false;
222     }
223     }
224     // depth-of-field blur if any
225     if (!jitteraperture(rodir[0], rodir[1], &tvw, dblur))
226     return false;
227     // include aft clipping distance?
228     for (i = (dlim > FTINY)*3; i--; )
229     rodir[1][i] *= dlim;
230    
231 greg 2.2 return EnqueueRay(rodir[0], rodir[1], (RNUMBER)y*TWidth()+x+1);
232 greg 2.1 }
233    
234     // Check if neighbor differences are below pixel sampling threshold
235     bool
236     RpictSimulManager::BelowSampThresh(int x, int y, const int noff[4][2]) const
237     {
238     SCOLOR pval[4];
239     float dist[4];
240     int i, j;
241    
242     for (i = 4; i--; ) { // get pixels from tile store
243     int px = x + noff[i][0];
244     int py = y + noff[i][1];
245     if (!doneMap.Check(px, py) ||
246     !pacc.GetPixel(px, py, pval[i], &dist[i]))
247     return false;
248     }
249     const bool spectr = (pacc.NC() > 3);
250     for (i = 4; --i; ) // do pairwise comparisons
251     for (j = i; j--; ) {
252     if (pacc.DepthType() &&
253     (dist[i] - dist[j] > maxdiff*dist[j]) |
254     (dist[j] - dist[i] > maxdiff*dist[i]))
255     return false;
256     if (spectr ? sbigsdiff(pval[i], pval[j], maxdiff) :
257     bigdiff(pval[i], pval[j], maxdiff))
258     return false;
259     }
260     return true; // linear interpolation OK
261     }
262    
263     // Fill an interior square patch with interpolated values
264     void
265 greg 2.2 RpictSimulManager::FillSquare(const int x, const int y, const int noff[4][2])
266 greg 2.1 {
267     SCOLOR pval[4];
268     float dist[4];
269     int i, j;
270     // assumes 4 corners are valid!
271     for (i = 4; i--; )
272     pacc.GetPixel(x+noff[i][0], y+noff[i][1], pval[i], &dist[i]);
273    
274     i = abs(noff[1][0]-noff[0][0]);
275 greg 2.2 j = abs(noff[1][1]-noff[0][1]); // i==j for diamond fill
276     const int slen = (i > j) ? i : j;
277 greg 2.1 const bool spectr = (pacc.NC() > 3);
278 greg 2.2 for (i = slen+1 + (i==j)*slen; i--; ) {
279     const double c1 = (i>slen ? i-slen-.5 : (double)i)/slen;
280     for (j = slen + (i<=slen); j--; ) {
281     const double c2 = (j + (i>slen)*.5)/slen;
282 greg 2.1 const int px = int(x + (1.-c1)*(1.-c2)*noff[0][0] +
283     c1*(1.-c2)*noff[1][0] +
284     (1.-c1)*c2*noff[2][0] +
285     c1*c2*noff[3][0] + .5);
286     const int py = int(y + (1.-c1)*(1.-c2)*noff[0][1] +
287     c1*(1.-c2)*noff[1][1] +
288     (1.-c1)*c2*noff[2][1] +
289     c1*c2*noff[3][1] + .5);
290     if (!doneMap.TestAndSet(px, py))
291     continue;
292     float zval = 0;
293     if (pacc.DepthType())
294     zval = (1.-c1)*(1.-c2)*dist[0] + c1*(1.-c2)*dist[1] +
295     (1.-c1)*c2*dist[2] + c1*c2*dist[3];
296     if (spectr) { // XXX assumes pacc.NC() == NCSAMP
297     SCOLOR ipval, tpval;
298     copyscolor(ipval, pval[0]);
299     scalescolor(ipval, (1.-c1)*(1.-c2));
300     copyscolor(tpval, pval[1]);
301     scalescolor(tpval, c1*(1.-c2));
302     saddscolor(ipval, tpval);
303     copyscolor(tpval, pval[2]);
304     scalescolor(tpval, (1.-c1)*c2);
305     saddscolor(ipval, tpval);
306     copyscolor(tpval, pval[3]);
307     scalescolor(tpval, c1*c2);
308     saddscolor(ipval, tpval);
309     pacc.SetPixel(px, py, ipval, zval);
310     } else { // tristimulus interpolation
311     COLOR ipval, tpval;
312     copycolor(ipval, pval[0]);
313     scalecolor(ipval, (1.-c1)*(1.-c2));
314     copycolor(tpval, pval[1]);
315     scalecolor(tpval, c1*(1.-c2));
316     addcolor(ipval, tpval);
317     copycolor(tpval, pval[2]);
318     scalecolor(tpval, (1.-c1)*c2);
319     addcolor(ipval, tpval);
320     copycolor(tpval, pval[3]);
321     scalecolor(tpval, c1*c2);
322     addcolor(ipval, tpval);
323     pacc.SetPixel(px, py, ipval, zval);
324     }
325     }
326     }
327     }
328    
329     // helper function to set up quincunx sampling
330     static void
331     SetQuincunx(ABitMap2 *bmp2, int noff[4][2], const int spc, const bool odd)
332     {
333     for (int y = 0; y < bmp2->Height(); y += spc>>1)
334 greg 2.2 for (int x = (odd^(y&1))*(spc>>1); x < bmp2->Width(); x += spc)
335 greg 2.1 bmp2->Set(x, y);
336     // order neighbors CCW
337     if (odd) {
338     noff[0][0] = spc>>1; noff[0][1] = 0;
339     noff[1][0] = 0; noff[1][1] = spc>>1;
340     noff[2][0] = -(spc>>1); noff[2][1] = 0;
341     noff[3][0] = 0; noff[3][1] = -(spc>>1);
342     } else {
343     noff[0][0] = spc>>1; noff[0][1] = spc>>1;
344     noff[1][0] = -(spc>>1); noff[1][1] = spc>>1;
345     noff[2][0] = -(spc>>1); noff[2][1] = -(spc>>1);
346     noff[3][0] = spc>>1; noff[3][1] = -(spc>>1);
347     }
348     }
349    
350     // Render (or finish rendering) current tile
351     bool
352     RpictSimulManager::RenderRect()
353     {
354     if (!tvw.type || !Ready()) {
355     error(INTERNAL, "need octree and view for RenderRect()");
356     return false;
357     }
358     ABitMap2 doneSamples = doneMap;
359     int sp2 = ceil(log2((TWidth()>THeight() ? TWidth() : THeight()) - 1.));
360     int layer = 0;
361     int x, y;
362     fprintf(stderr, "Rendering %dx%d tile with psample=%d, maxdiff=%.3f ...\n",
363     TWidth(), THeight(), psample, maxdiff);
364     while (sp2 > 0) {
365     ABitMap2 sampMap(TWidth(), THeight());
366     int noff[4][2];
367     if ((prCB != NULL) & (barPix == NULL))
368     (*prCB)(100.*doneMap.SumTotal()/doneMap.Width()/doneMap.Height());
369     SetQuincunx(&sampMap, noff, 1<<sp2, layer&1);
370     sampMap -= doneSamples; // avoid resampling pixels
371     // Are we into adaptive sampling realm?
372     if (noff[0][0]*noff[0][0] + noff[0][1]*noff[0][1] < psample*psample) {
373 greg 2.2 if (FlushQueue() < 0) // need results to check thresholds
374 greg 2.1 return false;
375     ABitMap2 fillMap = sampMap;
376     for (x = y = 0; sampMap.Find(&x, &y); x++)
377     if (BelowSampThresh(x, y, noff))
378     sampMap.Reset(x, y);
379     // spread sampling to neighbors...
380     const ABitMap2 origSampMap = sampMap;
381 greg 2.2 for (x = 4; x--; ) {
382 greg 2.1 ABitMap2 stamp = origSampMap;
383 greg 2.2 stamp.Shift(noff[x][0], noff[x][1]);
384 greg 2.1 sampMap |= stamp;
385     } // ...but don't resample what's done
386     sampMap -= doneSamples;
387     // interpolate smooth regions
388     fillMap -= sampMap;
389     for (x = y = 0; fillMap.Find(&x, &y); x++)
390     FillSquare(x, y, noff);
391     doneSamples |= doneMap;
392     } // compute required ray samples
393     for (x = y = 0; sampMap.Find(&x, &y); x++)
394     if (!ComputePixel(x, y))
395     return false;
396     doneSamples |= sampMap; // samples now done or at least queued
397     fprintf(stderr, "Sampled %ld pixels at (sp2,layer)=(%d,%d)\n",
398     (long)sampMap.SumTotal(), sp2, layer);
399     fprintf(stderr, "\t%ld pixels (%.3f%%) completed (+%ld in process)\n",
400     (long)doneMap.SumTotal(), 100.*doneMap.SumTotal()/doneMap.Width()/doneMap.Height(),
401     (long)(doneSamples.SumTotal()-doneMap.SumTotal()));
402     sp2 -= layer++ & 1; // next denser sampling
403     }
404     if (FlushQueue() < 0) // make sure we got everyone
405     return false;
406     x = y = 0;
407     if (doneMap.Find(&x, &y, false)) {
408     sprintf(errmsg, "missed %ld tile pixels, e.g. (%d,%d)",
409     (long)doneMap.Width()*doneMap.Height() -
410     doneMap.SumTotal(), x, y);
411     error(WARNING, errmsg);
412     }
413     if ((prCB != NULL) & (barPix == NULL))
414     (*prCB)(100.);
415     return true;
416     }
417    
418     /*
419     * Render the specified tile in frame
420     * Tile pixels are contiguous unless ystride != 0
421     * Tiles numbered from upper-left at (0,0)
422     * Pixel type influenced by this->prims assignment
423     */
424     bool
425     RpictSimulManager::RenderTile(COLORV *rp, int ystride, float *zp, const int *tile)
426     {
427     if (!rp | (GetWidth() <= 0) | (GetHeight() <= 0) | !vw.type)
428     return false;
429     if (!ystride) // contiguous rows?
430     ystride = TWidth();
431     pacc.Init(rp, ystride, zp);
432     if (prims == xyzprims)
433     pacc.SetColorSpace(RDTxyz);
434     else if (prims)
435     pacc.SetColorSpace(RDTrgb, prims);
436    
437     return SetTile(tile) && RenderRect();
438     }
439    
440     // Same but store as common-exponent COLR or SCOLR
441     bool
442     RpictSimulManager::RenderTile(COLRV *bp, int ystride, float *zp, const int *tile)
443     {
444     if (!bp | (GetWidth() <= 0) | (GetHeight() <= 0) | !vw.type)
445     return false;
446     if (!ystride) // contiguous rows?
447     ystride = TWidth();
448     pacc.Init(bp, ystride, zp);
449     if (prims == xyzprims)
450     pacc.SetColorSpace(RDTxyze);
451     else if (prims)
452     pacc.SetColorSpace(RDTrgbe, prims);
453    
454     return SetTile(tile) && RenderRect();
455     }
456    
457     // Same but also use 16-bit encoded depth buffer
458     bool
459     RpictSimulManager::RenderTile(COLRV *bp, int ystride, short *dp, const int *tile)
460     {
461     if (!bp | (GetWidth() <= 0) | (GetHeight() <= 0) | !vw.type)
462     return false;
463     if (!ystride) // contiguous rows?
464     ystride = TWidth();
465     pacc.Init(bp, ystride, dp);
466     if (prims == xyzprims)
467     pacc.SetColorSpace(RDTxyze);
468     else if (prims)
469     pacc.SetColorSpace(RDTrgbe, prims);
470    
471     return SetTile(tile) && RenderRect();
472     }
473    
474     // Allocate a new render bar
475     void
476     RpictSimulManager::NewBar(int ht)
477     {
478     delete [] barPix;
479     delete [] barDepth;
480     if (ht > GetHeight()) ht = GetHeight();
481     if ((ht <= 0) | (GetWidth() <= 0)) {
482     doneMap.NewBitMap(0,0);
483     pacc.Init();
484     barPix = NULL; barDepth = NULL;
485     return;
486     }
487     thvres[0] = GetWidth();
488     thvres[1] = ht;
489     const int NC = prims ? 3 : NCSAMP;
490     barPix = new COLORV [ht*thvres[0]*NC];
491     barDepth = new float [ht*thvres[0]];
492     pacc.Init(barPix + (ht-1)*thvres[0]*NC,
493     -thvres[0], barDepth + (ht-1)*thvres[0]);
494     if (prims == xyzprims)
495     pacc.SetColorSpace(RDTxyz);
496     else if (prims)
497     pacc.SetColorSpace(RDTrgb, prims);
498    
499     doneMap.NewBitMap(TWidth(), THeight());
500     }
501    
502     // Shift render bar area the specified amount down the frame
503     bool
504     RpictSimulManager::LowerBar(int v)
505     {
506     if (v <= 0) return !v;
507     if (!barPix | !barDepth | (v > THeight()) | !tvw.type)
508     return false;
509 greg 2.2 tvw.voff -= double(v)/THeight();
510     ptvw.voff -= double(v)/THeight();
511 greg 2.1 if (v == THeight()) {
512     doneMap.ClearBitMap();
513     return true;
514     }
515     const int NC = pacc.NC();
516     doneMap.Shift(0, v, false); // lift finished pixel samples
517     memmove(barPix, barPix + NC*TWidth()*v,
518     sizeof(COLORV)*NC*TWidth()*(THeight()-v));
519     memmove(barDepth, barDepth + TWidth()*v,
520     sizeof(float)*TWidth()*(THeight()-v));
521     return true;
522     }
523    
524     // Continue rendering from the specified position
525     bool
526     RpictSimulManager::RenderBelow(int ytop, const int vstep, FILE *pfp, const int dt, FILE *dfp)
527     {
528     if (ytop <= 0)
529     return true;
530     ptvw = pvw; // set starting bar's view
531     tvw = vw;
532     const char * verr = cropview(&tvw, 0., double(ytop-THeight())/GetHeight(),
533     1., double(ytop)/GetHeight());
534     if (verr) {
535     sprintf(errmsg, "illegal render bar below y=%d: %s", ytop, verr);
536     error(INTERNAL, errmsg);
537     return false;
538     }
539     if (!ptvw.type | (mblur <= FTINY) ||
540     cropview(&ptvw, 0., double(ytop-THeight())/GetHeight(),
541     1., double(ytop)/GetHeight()))
542     ptvw.type = 0;
543     // set up spectral sampling
544     if (setspectrsamp(CNDX, WLPART) <= 0) {
545     error(USER, "unsupported spectral sampling");
546     return false;
547     }
548     COLORV ** parr = NULL; // set up tiny source drawing
549     float ** zarr = NULL;
550     if (!ptvw.type && directvis && dblur <= FTINY) {
551     parr = new COLORV * [THeight()];
552     zarr = new float * [THeight()];
553     for (int n = THeight(); n-- > 0; ) {
554     parr[THeight()-1-n] = barPix + pacc.NC()*TWidth()*n;
555     zarr[THeight()-1-n] = barDepth + TWidth()*n;
556     }
557     ourview = vw; hres = GetWidth(); vres = GetHeight();
558     init_drawsources(psample);
559     }
560     int lastOut = ytop; // render down frame
561     while (ytop > 0) {
562 greg 2.2 fprintf(stderr, "At y=%d, source drawing %s...\n", ytop, parr ? "ON" : "OFF");
563 greg 2.1 if (ytop < THeight()) // mark what we won't do as finished
564     doneMap.ClearRect(0, 0, TWidth(), THeight()-ytop, true);
565     if (prCB)
566     (*prCB)(100.*(GetHeight()-ytop)/GetHeight());
567     if (!RenderRect()) // render this bar
568     return false;
569     int nlines = lastOut - ytop + THeight();
570     if (nlines > ytop)
571     nlines = ytop;
572     else if (parr) // drawing sources?
573     drawsources(parr, prims, zarr,
574     0, hres, lastOut-nlines, nlines);
575    
576     if (dfp) { // write out depth scanlines?
577     const float * dp = barDepth + TWidth()*(ytop-lastOut);
578     if (RDTdepthT(dt) == RDTdshort) {
579     for (int n = TWidth()*nlines; n-- > 0; dp++)
580     if (putint(depth2code(*dp, pacc.refDepth), 2, dfp) == EOF)
581     error(SYSTEM, "cannot write 16-bit depth buffer");
582     } else if (putbinary(dp, sizeof(float), TWidth()*nlines, dfp)
583     != TWidth()*nlines)
584     error(SYSTEM, "cannot write raw depth buffer");
585     }
586     COLORV * bpos = barPix + pacc.NC()*TWidth()*(ytop-lastOut);
587     while (nlines-- > 0) { // write pixel scanlines
588     switch (RDTcolorT(dt)) {
589     case RDTrgbe:
590     case RDTxyze:
591     if (fwritescan((COLOR *)bpos, TWidth(), pfp) < 0)
592     error(SYSTEM, "cannot write RGBE/XYZE output");
593     break;
594     case RDTscolr:
595     if (fwritesscan(bpos, pacc.NC(), TWidth(), pfp) < 0)
596     error(SYSTEM, "cannot write SCOLOR output");
597     break;
598     case RDTrgb:
599     case RDTxyz:
600     case RDTscolor:
601     if (putbinary(bpos, sizeof(COLORV)*pacc.NC(), TWidth(), pfp)
602     != TWidth())
603     error(SYSTEM, "cannot write SCOLOR output");
604     break;
605     default:
606 greg 2.2 error(INTERNAL, "botched output color type in RenderBelow()");
607 greg 2.1 break;
608     }
609     bpos += pacc.NC()*TWidth();
610     --lastOut;
611     } // flush each scan bar
612     if (fflush(pfp) == EOF || (dfp && fflush(dfp) == EOF))
613     error(SYSTEM, "output write error");
614     // advance down the frame
615     if (lastOut > 0 && !LowerBar(vstep))
616     return false;
617     ytop -= vstep;
618     }
619     delete [] parr;
620     delete [] zarr;
621     if (prCB)
622     (*prCB)(100.);
623     return true;
624     }
625    
626     /*
627     * Render and write a frame to the named file
628     * Include any header lines set prior to call
629     * Picture file must not already exist
630 greg 2.2 * Write pixels to stdout if !pfname
631     * Write depth to a command if dfname[0]=='!'
632 greg 2.1 */
633     RenderDataType
634     RpictSimulManager::RenderFrame(const char *pfname, RenderDataType dt, const char *dfname)
635     {
636     int fd = 1;
637     FILE * pfp = NULL;
638     FILE * dfp = NULL;
639    
640     if (!RDTcolorT(dt))
641 greg 2.2 error(INTERNAL, "botched color output type in RenderFrame()");
642 greg 2.1 if (NCSAMP == 3) {
643     if (RDTcolorT(dt) == RDTscolr)
644     dt = RDTnewCT(dt, prims==xyzprims ? RDTxyze : RDTrgbe);
645     else if (RDTcolorT(dt) == RDTscolor)
646     dt = RDTnewCT(dt, prims==xyzprims ? RDTxyz : RDTrgb);
647     }
648     if (!RDTdepthT(dt) ^ !dfname)
649     error(INTERNAL, "depth output requires file name and type in RenderFrame()");
650     if (pfname) { // open picture output file
651     if (pfname[0] == '!') {
652     error(INTERNAL, "writing picture to a command not supported");
653     return RDTnone;
654     }
655     fd = open(pfname, O_WRONLY|O_CREAT|O_EXCL, 0666);
656     }
657     if (fd < 0) {
658     if ((frameNo <= 0) | (errno != EEXIST)) {
659     sprintf(errmsg, "cannot open picture file '%s'", pfname);
660     error(SYSTEM, errmsg);
661     }
662     return RDTnone; // expected in parallel sequence
663     }
664     if (fd == 1)
665     pfp = stdout;
666     else if (!(pfp = fdopen(fd, "w")))
667     error(SYSTEM, "failure calling fdopen()");
668     SET_FILE_BINARY(pfp); // write picture header
669     if ((pfp != stdout) | (frameNo <= 1)) {
670     newheader("RADIANCE", pfp);
671     fputs(GetHeader(), pfp);
672     }
673     fputs(VIEWSTR, pfp); fprintview(&vw, pfp); fputc('\n', pfp);
674     if (frameNo > 0)
675     fprintf(pfp, "FRAME=%d\n", frameNo);
676     double pasp = viewaspect(&vw) * GetWidth() / GetHeight();
677 greg 2.2 if ((0.99 > pasp) | (pasp > 1.01))
678 greg 2.1 fputaspect(pasp, pfp);
679     fputnow(pfp);
680     switch (RDTcolorT(dt)) { // set primaries and picture format
681     case RDTrgbe:
682     if (!prims | (prims == xyzprims)) prims = stdprims;
683     fputprims(prims, pfp);
684     fputformat(COLRFMT, pfp);
685     break;
686     case RDTxyze:
687     prims = xyzprims;
688     fputformat(CIEFMT, pfp);
689     break;
690     case RDTscolr:
691     prims = NULL;
692     fputwlsplit(WLPART, pfp);
693     fputncomp(NCSAMP, pfp);
694     fputformat(SPECFMT, pfp);
695     break;
696     case RDTrgb:
697     if (!prims | (prims == xyzprims)) prims = stdprims;
698     fputprims(prims, pfp);
699     fputncomp(3, pfp);
700     fputendian(pfp);
701     fputformat("float", pfp);
702     break;
703     case RDTxyz:
704     prims = xyzprims;
705     fputprims(prims, pfp);
706     fputncomp(3, pfp);
707     fputendian(pfp);
708     fputformat("float", pfp);
709     break;
710     case RDTscolor:
711     prims = NULL;
712     fputwlsplit(WLPART, pfp);
713     fputncomp(NCSAMP, pfp);
714     fputendian(pfp);
715     fputformat("float", pfp);
716     break;
717     default:;
718     }
719     fputc('\n', pfp); // end picture header
720     fprtresolu(GetWidth(), GetHeight(), pfp);
721     if (dfname) {
722     if (dfname[0] == '!')
723     dfp = popen(dfname+1, "w");
724     else
725     dfp = fopen(dfname, "w");
726     if (!dfp) {
727     sprintf(errmsg, "cannot open depth output '%s'", dfname);
728     error(SYSTEM, errmsg);
729     return RDTnone;
730     }
731     SET_FILE_BINARY(dfp);
732     }
733     if (RDTdepthT(dt) == RDTdshort) { // write header for 16-bit depth?
734     newheader("RADIANCE", dfp);
735     fputs(GetHeader(), dfp);
736     fputs(VIEWSTR, dfp); fprintview(&vw, dfp); fputc('\n', dfp);
737     fputs(DEPTHSTR, dfp); fputs(dunit, dfp); fputc('\n', dfp);
738     fputformat(DEPTH16FMT, dfp);
739     fputc('\n', dfp); // end-of-info
740     fprtresolu(GetWidth(), GetHeight(), dfp);
741     }
742     const int bheight = (psample > 1) ? int(2*psample+.99) : 4;
743     const int vstep = bheight >> (psample > 1);
744    
745     NewBar(bheight); // render frame if we can
746     if (!RenderBelow(GetHeight(), vstep, pfp, dt, dfp)) {
747     fclose(pfp);
748     if (dfp) (dfname[0] == '!') ? pclose(dfp) : fclose(dfp);
749     Cleanup();
750     return RDTnone;
751     }
752     NewBar(); // clean up and return
753     if (pfp != stdout)
754     fclose(pfp);
755     if (dfp) {
756     if (dfname[0] == '!') {
757     int status = pclose(dfp);
758     if (status) {
759     sprintf(errmsg, "depth output (%s) error status: %d",
760     dfname, status);
761     error(USER, errmsg);
762     return RDTnone;
763     }
764     } else
765     fclose(dfp);
766     }
767     return dt;
768     }
769    
770     // passed struct for header line callback
771     struct HeaderInfo {
772     char fmt[MAXFMTLEN];
773     char depth_unit[32];
774     int ncomp;
775     RGBPRIMS prims;
776     VIEW vw;
777     bool gotWL;
778     bool gotprims;
779     bool gotview;
780     bool endianMatch;
781    
782     HeaderInfo() {
783     strcpy(fmt, "MISSING");
784     depth_unit[0] = '\0';
785     ncomp = 3;
786     vw = stdview;
787     gotWL = false;
788     gotprims = false;
789     gotview = false;
790     endianMatch = true;
791     }
792     };
793    
794     // helper function checks header line and records req. info.
795     static int
796     head_check(char *s, void *p)
797     {
798     HeaderInfo * hp = (HeaderInfo *)p;
799     int rval;
800    
801     if (isncomp(s)) {
802     hp->ncomp = ncompval(s);
803     return 1;
804     }
805     if (iswlsplit(s)) {
806     hp->gotWL = wlsplitval(WLPART, s);
807     return 1;
808     }
809     if (isprims(s)) {
810     hp->gotprims = primsval(hp->prims, s);
811     return 1;
812     }
813     if (isview(s)) {
814     hp->gotview |= (sscanview(&hp->vw, s) > 0);
815     return 1;
816     }
817     if (!strncmp(s, DEPTHSTR, LDEPTHSTR)) {
818     strlcpy(hp->depth_unit, s+LDEPTHSTR, sizeof(hp->depth_unit));
819     char * cp = hp->depth_unit;
820     while (*cp) cp++;
821     while (cp > hp->depth_unit && isspace(cp[-1])) cp--;
822     *cp = '\0';
823     return 1;
824     }
825     if ((rval = isbigendian(s)) >= 0) {
826     hp->endianMatch = (rval == nativebigendian());
827     return 1;
828     }
829     if (formatval(hp->fmt, s))
830     return 1;
831     return 0;
832     }
833    
834     // Resume partially finished rendering
835     // Picture file must exist
836     RenderDataType
837     RpictSimulManager::ResumeFrame(const char *pfname, const char *dfname)
838     {
839     if (!pfname || pfname[0] == '!')
840     return RDTnone;
841    
842     RenderDataType dt = RDTnone;
843     FILE * dfp = NULL;
844     FILE * pfp = fopen(pfname, "r+");
845     if (!pfp) {
846     sprintf(errmsg, "cannot reopen output picture '%s'", pfname);
847     error(SYSTEM, errmsg);
848     return RDTnone;
849     }
850     SET_FILE_BINARY(pfp);
851     HeaderInfo hinfo; // read header information & dimensions
852     RESOLU res;
853     if (getheader(pfp, head_check, &hinfo) < 0) {
854     fclose(pfp);
855     return RDTnone;
856     }
857     if (!fgetsresolu(&res, pfp) || res.rt != PIXSTANDARD) {
858     sprintf(errmsg, "missing/bad resolution for '%s'", pfname);
859     error(USER, errmsg);
860     fclose(pfp);
861     return RDTnone;
862     }
863     if (!hinfo.gotview) {
864     sprintf(errmsg, "missing view for '%s'", pfname);
865     error(USER, errmsg);
866     fclose(pfp);
867     return RDTnone;
868     }
869     if (hinfo.ncomp < 3) {
870     sprintf(errmsg, "bad # components (%d) in '%s'", hinfo.ncomp, pfname);
871     error(USER, errmsg);
872     fclose(pfp);
873     return RDTnone;
874     }
875     int bytesPer = 0; // complicated part to set rendering/output space
876     if (!strcmp(hinfo.fmt, COLRFMT)) {
877     prims = hinfo.prims;
878     int n = 8*hinfo.gotprims;
879     while (n--)
880     if (!FABSEQ(hinfo.prims[0][n], stdprims[0][n]))
881     break;
882     if (n < 0)
883     prims = stdprims;
884     dt = RDTnewCT(dt, RDTrgbe);
885     } else if (!strcmp(hinfo.fmt, CIEFMT)) {
886     prims = xyzprims;
887     dt = RDTnewCT(dt, RDTxyze);
888     } else if (!strcmp(hinfo.fmt, SPECFMT)) {
889     if ((hinfo.ncomp <= 3) | (hinfo.ncomp > MAXCSAMP)) {
890     sprintf(errmsg, "incompatible sample count (%d) in '%s'",
891     hinfo.ncomp, pfname);
892     error(USER, errmsg);
893     fclose(pfp);
894     return RDTnone;
895     }
896     NCSAMP = hinfo.ncomp; // overrides global setting
897     prims = NULL;
898     dt = RDTnewCT(dt, RDTscolr);
899     bytesPer = hinfo.ncomp + 1; // XXX assumes no compression
900     } else if (!strcmp(hinfo.fmt, "float")) {
901     if (!hinfo.endianMatch) {
902     sprintf(errmsg, "incompatible byte ordering in '%s'", pfname);
903     error(USER, errmsg);
904     fclose(pfp);
905     return RDTnone;
906     }
907     if (hinfo.ncomp == 3) {
908     prims = hinfo.prims; // custom primaries?
909     int n = 8*hinfo.gotprims;
910     while (n--)
911     if (!FABSEQ(hinfo.prims[0][n], stdprims[0][n]))
912     break;
913     if (n < 0) // standard primaries?
914     prims = stdprims;
915     else if (hinfo.gotprims) { // or check if XYZ
916     for (n = 8; n--; )
917     if (!FABSEQ(prims[0][n], xyzprims[0][n]))
918     break;
919     if (n < 0)
920     prims = xyzprims;
921     }
922     if (prims == xyzprims)
923     dt = RDTnewCT(dt, RDTxyz);
924     else
925     dt = RDTnewCT(dt, RDTrgb);
926     } else {
927     NCSAMP = hinfo.ncomp; // overrides global setting
928     prims = NULL;
929     dt = RDTnewCT(dt, RDTscolor);
930     }
931     bytesPer = sizeof(float)*hinfo.ncomp;
932     } else {
933     sprintf(errmsg, "unknown format (%s) for '%s'", hinfo.fmt, pfname);
934     error(USER, errmsg);
935     fclose(pfp);
936     return RDTnone;
937     }
938     vw.type = 0; // set up new (unreferenced) frame
939     frameNo = 0;
940     int hvdim[2] = {res.xr, res.yr};
941     double noAdj = 0;
942     if (!NewFrame(hinfo.vw, hvdim, &noAdj) ||
943     (hvdim[0] != res.xr) | (hvdim[1] != res.yr)) {
944     fclose(pfp);
945     return RDTnone;
946     }
947     long dataStart = ftell(pfp); // picture starting point
948     if (dataStart < 0) {
949     sprintf(errmsg, "cannot seek on '%s'", pfname);
950     error(SYSTEM, errmsg);
951     fclose(pfp);
952     return RDTnone;
953     }
954     long doneScans = 0;
955     if (bytesPer) { // fixed-width records?
956     fseek(pfp, 0, SEEK_END);
957     long dataEnd = ftell(pfp);
958     doneScans = (dataEnd - dataStart)/(bytesPer*GetWidth());
959     if (dataEnd-dataStart > bytesPer*GetWidth()*doneScans)
960     fseek(pfp, dataStart + bytesPer*GetWidth()*doneScans, SEEK_SET);
961     } else { // else get compressed scanlines
962     COLR * scan = (COLR *)tempbuffer(sizeof(COLR)*GetWidth());
963     while (freadcolrs(scan, GetWidth(), pfp) >= 0)
964     ++doneScans;
965     if (!feof(pfp)) {
966     sprintf(errmsg, "error reading compressed scanline from '%s'", pfname);
967     error(USER, errmsg);
968     fclose(pfp);
969     return RDTnone;
970     }
971     }
972     if (doneScans >= GetHeight()) { // nothing left to do?
973     sprintf(errmsg, "output file '%s' is already complete", pfname);
974     error(WARNING, errmsg);
975     fclose(pfp);
976     return dt;
977     }
978     if (!doneScans) {
979     sprintf(errmsg, "restarting empty frame '%s'", pfname);
980     error(WARNING, errmsg);
981     }
982     if (dfname) { // append depth file, too?
983     if (dfname[0] == '!') {
984     error(USER, "depth data cannot be reloaded from command");
985     fclose(pfp);
986     return RDTnone;
987     }
988     dfp = fopen(dfname, "a");
989     if (!dfp) {
990     sprintf(errmsg, "cannot reopen depth file '%s'", dfname);
991     error(SYSTEM, errmsg);
992     fclose(pfp);
993     return RDTnone;
994     }
995     SET_FILE_BINARY(dfp);
996     const long dflen = ftell(dfp);
997     if (dflen != sizeof(float)*GetWidth()*doneScans) {
998     fclose(dfp);
999     dfp = fopen(dfname, "r+");
1000     if (!dfp) return RDTnone; // WTH?
1001     SET_FILE_BINARY(dfp);
1002     }
1003     if (dflen < sizeof(float)*GetWidth()*doneScans) {
1004     HeaderInfo dinfo;
1005     if (getheader(dfp, head_check, &dinfo) < 0)
1006     sprintf(errmsg, "bad header in encoded depth file '%s'",
1007     dfname);
1008     else if (strcmp(dinfo.fmt, DEPTH16FMT))
1009     sprintf(errmsg, "wrong format (%s) for depth file '%s'",
1010     dinfo.fmt, dfname);
1011     else if (!SetReferenceDepth(dinfo.depth_unit))
1012     sprintf(errmsg, "bad/missing reference depth (%s) in '%s'",
1013     dinfo.depth_unit, dfname);
1014     else if (!fscnresolu(hvdim, hvdim+1, dfp) ||
1015     (hvdim[0] != GetWidth()) | (hvdim[1] != GetHeight()))
1016     sprintf(errmsg, "bad/mismatched resolution in '%s'",
1017     dfname);
1018     else
1019     errmsg[0] = '\0';
1020    
1021     if (errmsg[0]) {
1022     error(USER, errmsg);
1023     fclose(dfp);
1024     fclose(pfp);
1025     return RDTnone;
1026     }
1027     const long dStart = ftell(dfp);
1028     if (dflen-dStart < 2*GetWidth()*doneScans) {
1029     sprintf(errmsg, "missing %ld depths in '%s'",
1030     (long)GetWidth()*doneScans - (dflen-dStart)/2,
1031     dfname);
1032     error(WARNING, errmsg);
1033     }
1034     fseek(dfp, dStart + 2*GetWidth()*doneScans, SEEK_SET);
1035     dt = RDTnewDT(dt, RDTdshort);
1036     } else {
1037     if (dflen > sizeof(float)*GetWidth()*doneScans)
1038     fseek(dfp, sizeof(float)*GetWidth()*doneScans, SEEK_SET);
1039     dt = RDTnewDT(dt, RDTdfloat);
1040     }
1041     }
1042     int bheight = (psample > 1) ? int(2*psample+.99) : 4;
1043     if (bheight > GetHeight()-doneScans)
1044     bheight = GetHeight()-doneScans;
1045     int vstep = bheight >> (psample > 1);
1046     vstep += !vstep;
1047    
1048     NewBar(bheight); // render remainder if we can
1049     if (!RenderBelow(GetHeight()-doneScans, vstep, pfp, dt, dfp)) {
1050     fclose(pfp);
1051     if (dfp) fclose(dfp);
1052     Cleanup();
1053     return RDTnone;
1054     }
1055     NewBar(); // close up and return success
1056     fclose(pfp);
1057     if (dfp) fclose(dfp);
1058     return dt;
1059     }