ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/RpictSimulManager.cpp
Revision: 2.10
Committed: Sun Aug 25 17:24:48 2024 UTC (8 months, 1 week ago) by greg
Branch: MAIN
Changes since 2.9: +31 -46 lines
Log Message:
perf(rxpict): Further improvements to sampling pattern

File Contents

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