ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_t.c
Revision: 3.16
Committed: Sun Jun 5 20:27:14 2011 UTC (12 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 3.15: +20 -13 lines
Log Message:
Fixed comments and potential bug in BSDF tree traversal

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: bsdf_t.c,v 3.15 2011/06/03 18:12:58 greg Exp $";
3 #endif
4 /*
5 * bsdf_t.c
6 *
7 * Definitions for variable-resolution BSDF trees
8 *
9 * Created by Greg Ward on 2/2/11.
10 *
11 */
12
13 #include "rtio.h"
14 #include <stdlib.h>
15 #include <math.h>
16 #include <ctype.h>
17 #include "ezxml.h"
18 #include "bsdf.h"
19 #include "bsdf_t.h"
20 #include "hilbert.h"
21
22 /* Callback function type for SDtraverseTre() */
23 typedef int SDtreCallback(float val, const double *cmin,
24 double csiz, void *cptr);
25
26 /* reference width maximum (1.0) */
27 static const unsigned iwbits = sizeof(unsigned)*4;
28 static const unsigned iwmax = (1<<(sizeof(unsigned)*4))-1;
29 /* maximum cumulative value */
30 static const unsigned cumlmax = ~0;
31 /* constant z-vector */
32 static const FVECT zvec = {.0, .0, 1.};
33
34 /* Struct used for our distribution-building callback */
35 typedef struct {
36 int nic; /* number of input coordinates */
37 unsigned alen; /* current array length */
38 unsigned nall; /* number of allocated entries */
39 unsigned wmin; /* minimum square size so far */
40 unsigned wmax; /* maximum square size */
41 struct outdir_s {
42 unsigned hent; /* entering Hilbert index */
43 int wid; /* this square size */
44 float bsdf; /* BSDF for this square */
45 } *darr; /* output direction array */
46 } SDdistScaffold;
47
48 /* Allocate a new scattering distribution node */
49 static SDNode *
50 SDnewNode(int nd, int lg)
51 {
52 SDNode *st;
53
54 if (nd <= 0) {
55 strcpy(SDerrorDetail, "Zero dimension BSDF node request");
56 return NULL;
57 }
58 if (nd > SD_MAXDIM) {
59 sprintf(SDerrorDetail, "Illegal BSDF dimension (%d > %d)",
60 nd, SD_MAXDIM);
61 return NULL;
62 }
63 if (lg < 0) {
64 st = (SDNode *)malloc(sizeof(SDNode) +
65 sizeof(st->u.t[0])*((1<<nd) - 1));
66 if (st == NULL) {
67 sprintf(SDerrorDetail,
68 "Cannot allocate %d branch BSDF tree", 1<<nd);
69 return NULL;
70 }
71 memset(st->u.t, 0, sizeof(st->u.t[0])<<nd);
72 } else {
73 st = (SDNode *)malloc(sizeof(SDNode) +
74 sizeof(st->u.v[0])*((1 << nd*lg) - 1));
75 if (st == NULL) {
76 sprintf(SDerrorDetail,
77 "Cannot allocate %d BSDF leaves", 1 << nd*lg);
78 return NULL;
79 }
80 }
81 st->ndim = nd;
82 st->log2GR = lg;
83 return st;
84 }
85
86 /* Free an SD tree */
87 static void
88 SDfreeTre(SDNode *st)
89 {
90 int n;
91
92 if (st == NULL)
93 return;
94 for (n = (st->log2GR < 0) << st->ndim; n--; )
95 SDfreeTre(st->u.t[n]);
96 free(st);
97 }
98
99 /* Free a variable-resolution BSDF */
100 static void
101 SDFreeBTre(void *p)
102 {
103 SDTre *sdt = (SDTre *)p;
104
105 if (sdt == NULL)
106 return;
107 SDfreeTre(sdt->st);
108 free(sdt);
109 }
110
111 /* Fill branch's worth of grid values from subtree */
112 static void
113 fill_grid_branch(float *dptr, const float *sptr, int nd, int shft)
114 {
115 unsigned n = 1 << (shft-1);
116
117 if (!--nd) { /* end on the line */
118 memcpy(dptr, sptr, sizeof(*dptr)*n);
119 return;
120 }
121 while (n--) /* recurse on each slice */
122 fill_grid_branch(dptr + (n << shft*nd),
123 sptr + (n << (shft-1)*nd), nd, shft);
124 }
125
126 /* Get pointer at appropriate offset for the given branch */
127 static float *
128 grid_branch_start(SDNode *st, int n)
129 {
130 unsigned skipsiz = 1 << (st->log2GR - 1);
131 float *vptr = st->u.v;
132 int i;
133
134 for (i = st->ndim; i--; skipsiz <<= st->log2GR)
135 if (1<<i & n)
136 vptr += skipsiz;
137 return vptr;
138 }
139
140 /* Simplify (consolidate) a tree by flattening uniform depth regions */
141 static SDNode *
142 SDsimplifyTre(SDNode *st)
143 {
144 int match, n;
145
146 if (st == NULL) /* check for invalid tree */
147 return NULL;
148 if (st->log2GR >= 0) /* grid just returns unaltered */
149 return st;
150 match = 1; /* check if grids below match */
151 for (n = 0; n < 1<<st->ndim; n++) {
152 if ((st->u.t[n] = SDsimplifyTre(st->u.t[n])) == NULL)
153 return NULL; /* propogate error up call stack */
154 match &= (st->u.t[n]->log2GR == st->u.t[0]->log2GR);
155 }
156 if (match && (match = st->u.t[0]->log2GR) >= 0) {
157 SDNode *stn = SDnewNode(st->ndim, match + 1);
158 if (stn == NULL) /* out of memory? */
159 return st;
160 /* transfer values to new grid */
161 for (n = 1 << st->ndim; n--; )
162 fill_grid_branch(grid_branch_start(stn, n),
163 st->u.t[n]->u.v, stn->ndim, stn->log2GR);
164 SDfreeTre(st); /* free old tree */
165 st = stn; /* return new one */
166 }
167 return st;
168 }
169
170 /* Find smallest leaf in tree */
171 static double
172 SDsmallestLeaf(const SDNode *st)
173 {
174 if (st->log2GR < 0) { /* tree branches */
175 double lmin = 1.;
176 int n;
177 for (n = 1<<st->ndim; n--; ) {
178 double lsiz = SDsmallestLeaf(st->u.t[n]);
179 if (lsiz < lmin)
180 lmin = lsiz;
181 }
182 return .5*lmin;
183 }
184 /* leaf grid width */
185 return 1. / (double)(1 << st->log2GR);
186 }
187
188 /* Add up N-dimensional hypercube array values over the given box */
189 static double
190 SDiterSum(const float *va, int nd, int shft, const int *imin, const int *imax)
191 {
192 const unsigned skipsiz = 1 << --nd*shft;
193 double sum = .0;
194 int i;
195
196 va += *imin * skipsiz;
197
198 if (skipsiz == 1)
199 for (i = *imin; i < *imax; i++)
200 sum += *va++;
201 else
202 for (i = *imin; i < *imax; i++, va += skipsiz)
203 sum += SDiterSum(va, nd, shft, imin+1, imax+1);
204 return sum;
205 }
206
207 /* Average BSDF leaves over an orthotope defined by the unit hypercube */
208 static double
209 SDavgTreBox(const SDNode *st, const double *bmin, const double *bmax)
210 {
211 unsigned n;
212 int i;
213
214 if (!st)
215 return .0;
216 /* check box limits */
217 for (i = st->ndim; i--; ) {
218 if (bmin[i] >= 1.)
219 return .0;
220 if (bmax[i] <= 0)
221 return .0;
222 if (bmin[i] >= bmax[i])
223 return .0;
224 }
225 if (st->log2GR < 0) { /* iterate on subtree */
226 double sum = .0, wsum = 1e-20;
227 double sbmin[SD_MAXDIM], sbmax[SD_MAXDIM], w;
228 for (n = 1 << st->ndim; n--; ) {
229 w = 1.;
230 for (i = st->ndim; i--; ) {
231 sbmin[i] = 2.*bmin[i];
232 sbmax[i] = 2.*bmax[i];
233 if (n & 1<<i) {
234 sbmin[i] -= 1.;
235 sbmax[i] -= 1.;
236 }
237 if (sbmin[i] < .0) sbmin[i] = .0;
238 if (sbmax[i] > 1.) sbmax[i] = 1.;
239 if (sbmin[i] >= sbmax[i]) {
240 w = .0;
241 break;
242 }
243 w *= sbmax[i] - sbmin[i];
244 }
245 if (w > 1e-10) {
246 sum += w * SDavgTreBox(st->u.t[n], sbmin, sbmax);
247 wsum += w;
248 }
249 }
250 return sum / wsum;
251 } else { /* iterate over leaves */
252 int imin[SD_MAXDIM], imax[SD_MAXDIM];
253
254 n = 1;
255 for (i = st->ndim; i--; ) {
256 imin[i] = (bmin[i] <= 0) ? 0 :
257 (int)((1 << st->log2GR)*bmin[i]);
258 imax[i] = (bmax[i] >= 1.) ? (1 << st->log2GR) :
259 (int)((1 << st->log2GR)*bmax[i] + .999999);
260 n *= imax[i] - imin[i];
261 }
262 if (n)
263 return SDiterSum(st->u.v, st->ndim,
264 st->log2GR, imin, imax) / (double)n;
265 }
266 return .0;
267 }
268
269 /* Recursive call for SDtraverseTre() */
270 static int
271 SDdotravTre(const SDNode *st, const double *pos, int cmask,
272 SDtreCallback *cf, void *cptr,
273 const double *cmin, double csiz)
274 {
275 int rv, rval = 0;
276 double bmin[SD_MAXDIM];
277 int i, n;
278 /* in branches? */
279 if (st->log2GR < 0) {
280 unsigned skipmask = 0;
281 csiz *= .5;
282 for (i = st->ndim; i--; )
283 if (1<<i & cmask)
284 if (pos[i] < cmin[i] + csiz)
285 for (n = 1 << st->ndim; n--; ) {
286 if (n & 1<<i)
287 skipmask |= 1<<n;
288 }
289 else
290 for (n = 1 << st->ndim; n--; ) {
291 if (!(n & 1<<i))
292 skipmask |= 1<<n;
293 }
294 for (n = 1 << st->ndim; n--; ) {
295 if (1<<n & skipmask)
296 continue;
297 for (i = st->ndim; i--; )
298 if (1<<i & n)
299 bmin[i] = cmin[i] + csiz;
300 else
301 bmin[i] = cmin[i];
302
303 rval += rv = SDdotravTre(st->u.t[n], pos, cmask,
304 cf, cptr, bmin, csiz);
305 if (rv < 0)
306 return rv;
307 }
308 } else { /* else traverse leaves */
309 int clim[SD_MAXDIM][2];
310 int cpos[SD_MAXDIM];
311
312 if (st->log2GR == 0) /* short cut */
313 return (*cf)(st->u.v[0], cmin, csiz, cptr);
314
315 csiz /= (double)(1 << st->log2GR);
316 /* assign coord. ranges */
317 for (i = st->ndim; i--; )
318 if (1<<i & cmask) {
319 clim[i][0] = (pos[i] - cmin[i])/csiz;
320 /* check overflow from f.p. error */
321 clim[i][0] -= clim[i][0] >> st->log2GR;
322 clim[i][1] = clim[i][0] + 1;
323 } else {
324 clim[i][0] = 0;
325 clim[i][1] = 1 << st->log2GR;
326 }
327 #if (SD_MAXDIM == 4)
328 bmin[0] = cmin[0] + csiz*clim[0][0];
329 for (cpos[0] = clim[0][0]; cpos[0] < clim[0][1]; cpos[0]++) {
330 bmin[1] = cmin[1] + csiz*clim[1][0];
331 for (cpos[1] = clim[1][0]; cpos[1] < clim[1][1]; cpos[1]++) {
332 bmin[2] = cmin[2] + csiz*clim[2][0];
333 if (st->ndim == 3) {
334 cpos[2] = clim[2][0];
335 n = cpos[0];
336 for (i = 1; i < 3; i++)
337 n = (n << st->log2GR) + cpos[i];
338 for ( ; cpos[2] < clim[2][1]; cpos[2]++) {
339 rval += rv = (*cf)(st->u.v[n++], bmin, csiz, cptr);
340 if (rv < 0)
341 return rv;
342 bmin[2] += csiz;
343 }
344 } else {
345 for (cpos[2] = clim[2][0]; cpos[2] < clim[2][1]; cpos[2]++) {
346 bmin[3] = cmin[3] + csiz*(cpos[3] = clim[3][0]);
347 n = cpos[0];
348 for (i = 1; i < 4; i++)
349 n = (n << st->log2GR) + cpos[i];
350 for ( ; cpos[3] < clim[3][1]; cpos[3]++) {
351 rval += rv = (*cf)(st->u.v[n++], bmin, csiz, cptr);
352 if (rv < 0)
353 return rv;
354 bmin[3] += csiz;
355 }
356 bmin[2] += csiz;
357 }
358 }
359 bmin[1] += csiz;
360 }
361 bmin[0] += csiz;
362 }
363 #else
364 _!_ "broken code segment!"
365 #endif
366 }
367 return rval;
368 }
369
370 /* Traverse a tree, visiting nodes in a slice that fits partial position */
371 static int
372 SDtraverseTre(const SDNode *st, const double *pos, int cmask,
373 SDtreCallback *cf, void *cptr)
374 {
375 static double czero[SD_MAXDIM];
376 int i;
377 /* check arguments */
378 if ((st == NULL) | (cf == NULL))
379 return -1;
380 for (i = st->ndim; i--; )
381 if (1<<i & cmask && (pos[i] < 0) | (pos[i] >= 1.))
382 return -1;
383
384 return SDdotravTre(st, pos, cmask, cf, cptr, czero, 1.);
385 }
386
387 /* Look up tree value at the given grid position */
388 static float
389 SDlookupTre(const SDNode *st, const double *pos, double *hcube)
390 {
391 double spos[SD_MAXDIM];
392 int i, n, t;
393 /* initialize voxel return */
394 if (hcube) {
395 hcube[i = st->ndim] = 1.;
396 while (i--)
397 hcube[i] = .0;
398 }
399 /* climb the tree */
400 while (st->log2GR < 0) {
401 n = 0; /* move to appropriate branch */
402 if (hcube) hcube[st->ndim] *= .5;
403 for (i = st->ndim; i--; ) {
404 spos[i] = 2.*pos[i];
405 t = (spos[i] >= 1.);
406 n |= t<<i;
407 spos[i] -= (double)t;
408 if (hcube) hcube[i] += (double)t * hcube[st->ndim];
409 }
410 st = st->u.t[n]; /* avoids tail recursion */
411 pos = spos;
412 }
413 if (st->log2GR == 0) /* short cut */
414 return st->u.v[0];
415 n = t = 0; /* find grid array index */
416 for (i = st->ndim; i--; ) {
417 n += (int)((1<<st->log2GR)*pos[i]) << t;
418 t += st->log2GR;
419 }
420 if (hcube) { /* compute final hypercube */
421 hcube[st->ndim] /= (double)(1<<st->log2GR);
422 for (i = st->ndim; i--; )
423 hcube[i] += floor((1<<st->log2GR)*pos[i])*hcube[st->ndim];
424 }
425 return st->u.v[n]; /* no interpolation */
426 }
427
428 /* Query BSDF value and sample hypercube for the given vectors */
429 static float
430 SDqueryTre(const SDTre *sdt, const FVECT outVec, const FVECT inVec, double *hc)
431 {
432 FVECT rOutVec;
433 double gridPos[4];
434
435 switch (sdt->sidef) { /* whose side are you on? */
436 case SD_UFRONT:
437 if ((outVec[2] < 0) | (inVec[2] < 0))
438 return -1.;
439 break;
440 case SD_UBACK:
441 if ((outVec[2] > 0) | (inVec[2] > 0))
442 return -1.;
443 break;
444 case SD_XMIT:
445 if ((outVec[2] > 0) == (inVec[2] > 0))
446 return -1.;
447 break;
448 default:
449 return -1.;
450 }
451 /* convert vector coordinates */
452 if (sdt->st->ndim == 3) {
453 spinvector(rOutVec, outVec, zvec, -atan2(-inVec[1],-inVec[0]));
454 gridPos[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
455 SDdisk2square(gridPos+1, rOutVec[0], rOutVec[1]);
456 } else if (sdt->st->ndim == 4) {
457 SDdisk2square(gridPos, -inVec[0], -inVec[1]);
458 SDdisk2square(gridPos+2, outVec[0], outVec[1]);
459 } else
460 return -1.; /* should be internal error */
461
462 return SDlookupTre(sdt->st, gridPos, hc);
463 }
464
465 /* Compute non-diffuse component for variable-resolution BSDF */
466 static int
467 SDgetTreBSDF(float coef[SDmaxCh], const FVECT outVec,
468 const FVECT inVec, SDComponent *sdc)
469 {
470 /* check arguments */
471 if ((coef == NULL) | (outVec == NULL) | (inVec == NULL) | (sdc == NULL)
472 || sdc->dist == NULL)
473 return 0;
474 /* get nearest BSDF value */
475 coef[0] = SDqueryTre((SDTre *)sdc->dist, outVec, inVec, NULL);
476 return (coef[0] >= 0); /* monochromatic for now */
477 }
478
479 /* Callback to build cumulative distribution using SDtraverseTre() */
480 static int
481 build_scaffold(float val, const double *cmin, double csiz, void *cptr)
482 {
483 SDdistScaffold *sp = (SDdistScaffold *)cptr;
484 int wid = csiz*(double)iwmax + .5;
485 bitmask_t bmin[2], bmax[2];
486
487 cmin += sp->nic; /* skip to output coords */
488 if (wid < sp->wmin) /* new minimum width? */
489 sp->wmin = wid;
490 if (wid > sp->wmax) /* new maximum? */
491 sp->wmax = wid;
492 if (sp->alen >= sp->nall) { /* need more space? */
493 struct outdir_s *ndarr;
494 sp->nall += 1024;
495 ndarr = (struct outdir_s *)realloc(sp->darr,
496 sizeof(struct outdir_s)*sp->nall);
497 if (ndarr == NULL) {
498 sprintf(SDerrorDetail,
499 "Cannot grow scaffold to %u entries", sp->nall);
500 return -1; /* abort build */
501 }
502 sp->darr = ndarr;
503 }
504 /* find Hilbert entry index */
505 bmin[0] = cmin[0]*(double)iwmax + .5;
506 bmin[1] = cmin[1]*(double)iwmax + .5;
507 bmax[0] = bmin[0] + wid-1;
508 bmax[1] = bmin[1] + wid-1;
509 hilbert_box_vtx(2, sizeof(bitmask_t), iwbits, 1, bmin, bmax);
510 sp->darr[sp->alen].hent = hilbert_c2i(2, iwbits, bmin);
511 sp->darr[sp->alen].wid = wid;
512 sp->darr[sp->alen].bsdf = val;
513 sp->alen++; /* on to the next entry */
514 return 0;
515 }
516
517 /* Scaffold comparison function for qsort -- ascending Hilbert index */
518 static int
519 sscmp(const void *p1, const void *p2)
520 {
521 unsigned h1 = (*(const struct outdir_s *)p1).hent;
522 unsigned h2 = (*(const struct outdir_s *)p2).hent;
523
524 if (h1 > h2)
525 return 1;
526 if (h1 < h2)
527 return -1;
528 return 0;
529 }
530
531 /* Create a new cumulative distribution for the given input direction */
532 static SDTreCDst *
533 make_cdist(const SDTre *sdt, const double *pos)
534 {
535 SDdistScaffold myScaffold;
536 SDTreCDst *cd;
537 struct outdir_s *sp;
538 double scale, cursum;
539 int i;
540 /* initialize scaffold */
541 myScaffold.wmin = iwmax;
542 myScaffold.wmax = 0;
543 myScaffold.nic = sdt->st->ndim - 2;
544 myScaffold.alen = 0;
545 myScaffold.nall = 512;
546 myScaffold.darr = (struct outdir_s *)malloc(sizeof(struct outdir_s) *
547 myScaffold.nall);
548 if (myScaffold.darr == NULL)
549 return NULL;
550 /* grow the distribution */
551 if (SDtraverseTre(sdt->st, pos, (1<<myScaffold.nic)-1,
552 &build_scaffold, &myScaffold) < 0) {
553 free(myScaffold.darr);
554 return NULL;
555 }
556 /* allocate result holder */
557 cd = (SDTreCDst *)malloc(sizeof(SDTreCDst) +
558 sizeof(cd->carr[0])*myScaffold.alen);
559 if (cd == NULL) {
560 sprintf(SDerrorDetail,
561 "Cannot allocate %u entry cumulative distribution",
562 myScaffold.alen);
563 free(myScaffold.darr);
564 return NULL;
565 }
566 cd->isodist = (myScaffold.nic == 1);
567 /* sort the distribution */
568 qsort(myScaffold.darr, cd->calen = myScaffold.alen,
569 sizeof(struct outdir_s), &sscmp);
570
571 /* record input range */
572 scale = myScaffold.wmin / (double)iwmax;
573 for (i = myScaffold.nic; i--; ) {
574 cd->clim[i][0] = floor(pos[i]/scale) * scale;
575 cd->clim[i][1] = cd->clim[i][0] + scale;
576 }
577 if (cd->isodist) { /* avoid issue in SDqueryTreProjSA() */
578 cd->clim[1][0] = cd->clim[0][0];
579 cd->clim[1][1] = cd->clim[0][1];
580 }
581 cd->max_psa = myScaffold.wmax / (double)iwmax;
582 cd->max_psa *= cd->max_psa * M_PI;
583 cd->sidef = sdt->sidef;
584 cd->cTotal = 1e-20; /* compute directional total */
585 sp = myScaffold.darr;
586 for (i = myScaffold.alen; i--; sp++)
587 cd->cTotal += sp->bsdf * (double)sp->wid * sp->wid;
588 cursum = .0; /* go back and get cumulative values */
589 scale = (double)cumlmax / cd->cTotal;
590 sp = myScaffold.darr;
591 for (i = 0; i < cd->calen; i++, sp++) {
592 cd->carr[i].hndx = sp->hent;
593 cd->carr[i].cuml = scale*cursum + .5;
594 cursum += sp->bsdf * (double)sp->wid * sp->wid;
595 }
596 cd->carr[i].hndx = ~0; /* make final entry */
597 cd->carr[i].cuml = cumlmax;
598 cd->cTotal *= M_PI/(double)iwmax/iwmax;
599 /* all done, clean up and return */
600 free(myScaffold.darr);
601 return cd;
602 }
603
604 /* Find or allocate a cumulative distribution for the given incoming vector */
605 const SDCDst *
606 SDgetTreCDist(const FVECT inVec, SDComponent *sdc)
607 {
608 const SDTre *sdt;
609 double inCoord[2];
610 int vflags;
611 int i;
612 SDTreCDst *cd, *cdlast;
613 /* check arguments */
614 if ((inVec == NULL) | (sdc == NULL) ||
615 (sdt = (SDTre *)sdc->dist) == NULL)
616 return NULL;
617 if (sdt->st->ndim == 3) /* isotropic BSDF? */
618 inCoord[0] = .5 - .5*sqrt(inVec[0]*inVec[0] + inVec[1]*inVec[1]);
619 else if (sdt->st->ndim == 4)
620 SDdisk2square(inCoord, -inVec[0], -inVec[1]);
621 else
622 return NULL; /* should be internal error */
623 cdlast = NULL; /* check for direction in cache list */
624 for (cd = (SDTreCDst *)sdc->cdList; cd != NULL;
625 cdlast = cd, cd = (SDTreCDst *)cd->next) {
626 for (i = sdt->st->ndim - 2; i--; )
627 if ((cd->clim[i][0] > inCoord[i]) |
628 (inCoord[i] >= cd->clim[i][1]))
629 break;
630 if (i < 0)
631 break; /* means we have a match */
632 }
633 if (cd == NULL) /* need to create new entry? */
634 cdlast = cd = make_cdist(sdt, inCoord);
635 if (cdlast != NULL) { /* move entry to head of cache list */
636 cdlast->next = cd->next;
637 cd->next = sdc->cdList;
638 sdc->cdList = (SDCDst *)cd;
639 }
640 return (SDCDst *)cd; /* ready to go */
641 }
642
643 /* Query solid angle for vector(s) */
644 static SDError
645 SDqueryTreProjSA(double *psa, const FVECT v1, const RREAL *v2,
646 int qflags, SDComponent *sdc)
647 {
648 double myPSA[2];
649 /* check arguments */
650 if ((psa == NULL) | (v1 == NULL) | (sdc == NULL) ||
651 sdc->dist == NULL)
652 return SDEargument;
653 /* get projected solid angle(s) */
654 if (v2 != NULL) {
655 const SDTre *sdt = (SDTre *)sdc->dist;
656 double hcube[SD_MAXDIM];
657 if (SDqueryTre(sdt, v1, v2, hcube) < 0) {
658 strcpy(SDerrorDetail, "Bad call to SDqueryTreProjSA");
659 return SDEinternal;
660 }
661 myPSA[0] = hcube[sdt->st->ndim];
662 myPSA[1] = myPSA[0] *= myPSA[0] * M_PI;
663 } else {
664 const SDTreCDst *cd = (const SDTreCDst *)SDgetTreCDist(v1, sdc);
665 if (cd == NULL)
666 return SDEmemory;
667 myPSA[0] = M_PI * (cd->clim[0][1] - cd->clim[0][0]) *
668 (cd->clim[1][1] - cd->clim[1][0]);
669 myPSA[1] = cd->max_psa;
670 }
671 switch (qflags) { /* record based on flag settings */
672 case SDqueryVal:
673 *psa = myPSA[0];
674 break;
675 case SDqueryMax:
676 if (myPSA[1] > *psa)
677 *psa = myPSA[1];
678 break;
679 case SDqueryMin+SDqueryMax:
680 if (myPSA[1] > psa[1])
681 psa[1] = myPSA[1];
682 /* fall through */
683 case SDqueryMin:
684 if (myPSA[0] < psa[0])
685 psa[0] = myPSA[0];
686 break;
687 }
688 return SDEnone;
689 }
690
691 /* Sample cumulative distribution */
692 static SDError
693 SDsampTreCDist(FVECT ioVec, double randX, const SDCDst *cdp)
694 {
695 const unsigned nBitsC = 4*sizeof(bitmask_t);
696 const unsigned nExtraBits = 8*(sizeof(bitmask_t)-sizeof(unsigned));
697 const SDTreCDst *cd = (const SDTreCDst *)cdp;
698 const unsigned target = randX*cumlmax;
699 bitmask_t hndx, hcoord[2];
700 double gpos[3], rotangle;
701 int i, iupper, ilower;
702 /* check arguments */
703 if ((ioVec == NULL) | (cd == NULL))
704 return SDEargument;
705 if (ioVec[2] > 0) {
706 if (!(cd->sidef & SD_UFRONT))
707 return SDEargument;
708 } else if (!(cd->sidef & SD_UBACK))
709 return SDEargument;
710 /* binary search to find position */
711 ilower = 0; iupper = cd->calen;
712 while ((i = (iupper + ilower) >> 1) != ilower)
713 if ((long)target >= (long)cd->carr[i].cuml)
714 ilower = i;
715 else
716 iupper = i;
717 /* localize random position */
718 randX = (randX*cumlmax - cd->carr[ilower].cuml) /
719 (double)(cd->carr[iupper].cuml - cd->carr[ilower].cuml);
720 /* index in longer Hilbert curve */
721 hndx = (randX*cd->carr[iupper].hndx + (1.-randX)*cd->carr[ilower].hndx)
722 * (double)((bitmask_t)1 << nExtraBits);
723 /* convert Hilbert index to vector */
724 hilbert_i2c(2, nBitsC, hndx, hcoord);
725 for (i = 2; i--; )
726 gpos[i] = ((double)hcoord[i] + rand()*(1./(RAND_MAX+.5))) /
727 (double)((bitmask_t)1 << nBitsC);
728 SDsquare2disk(gpos, gpos[0], gpos[1]);
729 /* compute Z-coordinate */
730 gpos[2] = 1. - gpos[0]*gpos[0] - gpos[1]*gpos[1];
731 if (gpos[2] > 0) /* paranoia, I hope */
732 gpos[2] = sqrt(gpos[2]);
733 /* emit from back? */
734 if (ioVec[2] > 0 ^ cd->sidef != SD_XMIT)
735 gpos[2] = -gpos[2];
736 if (cd->isodist) { /* rotate isotropic result */
737 rotangle = atan2(-ioVec[1],-ioVec[0]);
738 VCOPY(ioVec, gpos);
739 spinvector(ioVec, ioVec, zvec, rotangle);
740 } else
741 VCOPY(ioVec, gpos);
742 return SDEnone;
743 }
744
745 /* Advance pointer to the next non-white character in the string (or nul) */
746 static int
747 next_token(char **spp)
748 {
749 while (isspace(**spp))
750 ++*spp;
751 return **spp;
752 }
753
754 /* Advance pointer past matching token (or any token if c==0) */
755 #define eat_token(spp,c) (next_token(spp)==(c) ^ !(c) ? *(*(spp))++ : 0)
756
757 /* Count words from this point in string to '}' */
758 static int
759 count_values(char *cp)
760 {
761 int n = 0;
762
763 while (next_token(&cp) != '}' && *cp) {
764 while (!isspace(*cp) & (*cp != ',') & (*cp != '}'))
765 if (!*++cp)
766 break;
767 ++n;
768 eat_token(&cp, ',');
769 }
770 return n;
771 }
772
773 /* Load an array of real numbers, returning total */
774 static int
775 load_values(char **spp, float *va, int n)
776 {
777 float *v = va;
778 char *svnext;
779
780 while (n-- > 0 && (svnext = fskip(*spp)) != NULL) {
781 *v++ = atof(*spp);
782 *spp = svnext;
783 eat_token(spp, ',');
784 }
785 return v - va;
786 }
787
788 /* Load BSDF tree data */
789 static SDNode *
790 load_tree_data(char **spp, int nd)
791 {
792 SDNode *st;
793 int n;
794
795 if (!eat_token(spp, '{')) {
796 strcpy(SDerrorDetail, "Missing '{' in tensor tree");
797 return NULL;
798 }
799 if (next_token(spp) == '{') { /* tree branches */
800 st = SDnewNode(nd, -1);
801 if (st == NULL)
802 return NULL;
803 for (n = 0; n < 1<<nd; n++)
804 if ((st->u.t[n] = load_tree_data(spp, nd)) == NULL) {
805 SDfreeTre(st);
806 return NULL;
807 }
808 } else { /* else load value grid */
809 int bsiz;
810 n = count_values(*spp); /* see how big the grid is */
811 for (bsiz = 0; bsiz < 8*sizeof(size_t); bsiz += nd)
812 if (1<<bsiz == n)
813 break;
814 if (bsiz >= 8*sizeof(size_t)) {
815 strcpy(SDerrorDetail, "Illegal value count in tensor tree");
816 return NULL;
817 }
818 st = SDnewNode(nd, bsiz/nd);
819 if (st == NULL)
820 return NULL;
821 if (load_values(spp, st->u.v, n) != n) {
822 strcpy(SDerrorDetail, "Real format error in tensor tree");
823 SDfreeTre(st);
824 return NULL;
825 }
826 }
827 if (!eat_token(spp, '}')) {
828 strcpy(SDerrorDetail, "Missing '}' in tensor tree");
829 SDfreeTre(st);
830 return NULL;
831 }
832 eat_token(spp, ',');
833 return st;
834 }
835
836 /* Compute min. proj. solid angle and max. direct hemispherical scattering */
837 static SDError
838 get_extrema(SDSpectralDF *df)
839 {
840 SDNode *st = (*(SDTre *)df->comp[0].dist).st;
841 double stepWidth, dhemi, bmin[4], bmax[4];
842
843 stepWidth = SDsmallestLeaf(st);
844 df->minProjSA = M_PI*stepWidth*stepWidth;
845 if (stepWidth < .03125)
846 stepWidth = .03125; /* 1/32 resolution good enough */
847 df->maxHemi = .0;
848 if (st->ndim == 3) { /* isotropic BSDF */
849 bmin[1] = bmin[2] = .0;
850 bmax[1] = bmax[2] = 1.;
851 for (bmin[0] = .0; bmin[0] < .5-FTINY; bmin[0] += stepWidth) {
852 bmax[0] = bmin[0] + stepWidth;
853 dhemi = SDavgTreBox(st, bmin, bmax);
854 if (dhemi > df->maxHemi)
855 df->maxHemi = dhemi;
856 }
857 } else if (st->ndim == 4) { /* anisotropic BSDF */
858 bmin[2] = bmin[3] = .0;
859 bmax[2] = bmax[3] = 1.;
860 for (bmin[0] = .0; bmin[0] < 1.-FTINY; bmin[0] += stepWidth) {
861 bmax[0] = bmin[0] + stepWidth;
862 for (bmin[1] = .0; bmin[1] < 1.-FTINY; bmin[1] += stepWidth) {
863 bmax[1] = bmin[1] + stepWidth;
864 dhemi = SDavgTreBox(st, bmin, bmax);
865 if (dhemi > df->maxHemi)
866 df->maxHemi = dhemi;
867 }
868 }
869 } else
870 return SDEinternal;
871 /* correct hemispherical value */
872 df->maxHemi *= M_PI;
873 return SDEnone;
874 }
875
876 /* Load BSDF distribution for this wavelength */
877 static SDError
878 load_bsdf_data(SDData *sd, ezxml_t wdb, int ndim)
879 {
880 SDSpectralDF *df;
881 SDTre *sdt;
882 char *sdata;
883 int i;
884 /* allocate BSDF component */
885 sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
886 if (!sdata)
887 return SDEnone;
888 /*
889 * Remember that front and back are reversed from WINDOW 6 orientations
890 */
891 if (!strcasecmp(sdata, "Transmission")) {
892 if (sd->tf != NULL)
893 SDfreeSpectralDF(sd->tf);
894 if ((sd->tf = SDnewSpectralDF(1)) == NULL)
895 return SDEmemory;
896 df = sd->tf;
897 } else if (!strcasecmp(sdata, "Reflection Front")) {
898 if (sd->rb != NULL) /* note back-front reversal */
899 SDfreeSpectralDF(sd->rb);
900 if ((sd->rb = SDnewSpectralDF(1)) == NULL)
901 return SDEmemory;
902 df = sd->rb;
903 } else if (!strcasecmp(sdata, "Reflection Back")) {
904 if (sd->rf != NULL) /* note front-back reversal */
905 SDfreeSpectralDF(sd->rf);
906 if ((sd->rf = SDnewSpectralDF(1)) == NULL)
907 return SDEmemory;
908 df = sd->rf;
909 } else
910 return SDEnone;
911 /* XXX should also check "ScatteringDataType" for consistency? */
912 /* get angle bases */
913 sdata = ezxml_txt(ezxml_child(wdb,"AngleBasis"));
914 if (!sdata || strcasecmp(sdata, "LBNL/Shirley-Chiu")) {
915 sprintf(SDerrorDetail, "%s angle basis for BSDF '%s'",
916 !sdata ? "Missing" : "Unsupported", sd->name);
917 return !sdata ? SDEformat : SDEsupport;
918 }
919 /* allocate BSDF tree */
920 sdt = (SDTre *)malloc(sizeof(SDTre));
921 if (sdt == NULL)
922 return SDEmemory;
923 if (df == sd->rf)
924 sdt->sidef = SD_UFRONT;
925 else if (df == sd->rb)
926 sdt->sidef = SD_UBACK;
927 else
928 sdt->sidef = SD_XMIT;
929 sdt->st = NULL;
930 df->comp[0].cspec[0] = c_dfcolor; /* XXX monochrome for now */
931 df->comp[0].dist = sdt;
932 df->comp[0].func = &SDhandleTre;
933 /* read BSDF data */
934 sdata = ezxml_txt(ezxml_child(wdb, "ScatteringData"));
935 if (!sdata || !next_token(&sdata)) {
936 sprintf(SDerrorDetail, "Missing BSDF ScatteringData in '%s'",
937 sd->name);
938 return SDEformat;
939 }
940 sdt->st = load_tree_data(&sdata, ndim);
941 if (sdt->st == NULL)
942 return SDEformat;
943 if (next_token(&sdata)) { /* check for unconsumed characters */
944 sprintf(SDerrorDetail,
945 "Extra characters at end of ScatteringData in '%s'",
946 sd->name);
947 return SDEformat;
948 }
949 /* flatten branches where possible */
950 sdt->st = SDsimplifyTre(sdt->st);
951 if (sdt->st == NULL)
952 return SDEinternal;
953 return get_extrema(df); /* compute global quantities */
954 }
955
956 /* Find minimum value in tree */
957 static float
958 SDgetTreMin(const SDNode *st)
959 {
960 float vmin = FHUGE;
961 int n;
962
963 if (st->log2GR < 0) {
964 for (n = 1<<st->ndim; n--; ) {
965 float v = SDgetTreMin(st->u.t[n]);
966 if (v < vmin)
967 vmin = v;
968 }
969 } else {
970 for (n = 1<<(st->ndim*st->log2GR); n--; )
971 if (st->u.v[n] < vmin)
972 vmin = st->u.v[n];
973 }
974 return vmin;
975 }
976
977 /* Subtract the given value from all tree nodes */
978 static void
979 SDsubtractTreVal(SDNode *st, float val)
980 {
981 int n;
982
983 if (st->log2GR < 0) {
984 for (n = 1<<st->ndim; n--; )
985 SDsubtractTreVal(st->u.t[n], val);
986 } else {
987 for (n = 1<<(st->ndim*st->log2GR); n--; )
988 if ((st->u.v[n] -= val) < 0)
989 st->u.v[n] = .0f;
990 }
991 }
992
993 /* Subtract minimum value from BSDF */
994 static double
995 subtract_min(SDNode *st)
996 {
997 float vmin;
998 /* be sure to skip unused portion */
999 if (st->ndim == 3) {
1000 int n;
1001 vmin = 1./M_PI;
1002 if (st->log2GR < 0) {
1003 for (n = 0; n < 8; n += 2) {
1004 float v = SDgetTreMin(st->u.t[n]);
1005 if (v < vmin)
1006 vmin = v;
1007 }
1008 } else if (st->log2GR) {
1009 for (n = 1 << (3*st->log2GR - 1); n--; )
1010 if (st->u.v[n] < vmin)
1011 vmin = st->u.v[n];
1012 } else
1013 vmin = st->u.v[0];
1014 } else /* anisotropic covers entire tree */
1015 vmin = SDgetTreMin(st);
1016
1017 if (vmin <= FTINY)
1018 return .0;
1019
1020 SDsubtractTreVal(st, vmin);
1021
1022 return M_PI * vmin; /* return hemispherical value */
1023 }
1024
1025 /* Extract and separate diffuse portion of BSDF */
1026 static void
1027 extract_diffuse(SDValue *dv, SDSpectralDF *df)
1028 {
1029 int n;
1030
1031 if (df == NULL || df->ncomp <= 0) {
1032 dv->spec = c_dfcolor;
1033 dv->cieY = .0;
1034 return;
1035 }
1036 dv->spec = df->comp[0].cspec[0];
1037 dv->cieY = subtract_min((*(SDTre *)df->comp[0].dist).st);
1038 /* in case of multiple components */
1039 for (n = df->ncomp; --n; ) {
1040 double ymin = subtract_min((*(SDTre *)df->comp[n].dist).st);
1041 c_cmix(&dv->spec, dv->cieY, &dv->spec, ymin, &df->comp[n].cspec[0]);
1042 dv->cieY += ymin;
1043 }
1044 df->maxHemi -= dv->cieY; /* adjust maximum hemispherical */
1045 /* make sure everything is set */
1046 c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
1047 }
1048
1049 /* Load a variable-resolution BSDF tree from an open XML file */
1050 SDError
1051 SDloadTre(SDData *sd, ezxml_t wtl)
1052 {
1053 SDError ec;
1054 ezxml_t wld, wdb;
1055 int rank;
1056 char *txt;
1057 /* basic checks and tensor rank */
1058 txt = ezxml_txt(ezxml_child(ezxml_child(wtl,
1059 "DataDefinition"), "IncidentDataStructure"));
1060 if (txt == NULL || !*txt) {
1061 sprintf(SDerrorDetail,
1062 "BSDF \"%s\": missing IncidentDataStructure",
1063 sd->name);
1064 return SDEformat;
1065 }
1066 if (!strcasecmp(txt, "TensorTree3"))
1067 rank = 3;
1068 else if (!strcasecmp(txt, "TensorTree4"))
1069 rank = 4;
1070 else {
1071 sprintf(SDerrorDetail,
1072 "BSDF \"%s\": unsupported IncidentDataStructure",
1073 sd->name);
1074 return SDEsupport;
1075 }
1076 /* load BSDF components */
1077 for (wld = ezxml_child(wtl, "WavelengthData");
1078 wld != NULL; wld = wld->next) {
1079 if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1080 "Visible"))
1081 continue; /* just visible for now */
1082 for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1083 wdb != NULL; wdb = wdb->next)
1084 if ((ec = load_bsdf_data(sd, wdb, rank)) != SDEnone)
1085 return ec;
1086 }
1087 /* separate diffuse components */
1088 extract_diffuse(&sd->rLambFront, sd->rf);
1089 extract_diffuse(&sd->rLambBack, sd->rb);
1090 extract_diffuse(&sd->tLamb, sd->tf);
1091 /* return success */
1092 return SDEnone;
1093 }
1094
1095 /* Variable resolution BSDF methods */
1096 SDFunc SDhandleTre = {
1097 &SDgetTreBSDF,
1098 &SDqueryTreProjSA,
1099 &SDgetTreCDist,
1100 &SDsampTreCDist,
1101 &SDFreeBTre,
1102 };