ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_t.c
Revision: 3.14
Committed: Wed Jun 1 05:21:18 2011 UTC (12 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 3.13: +6 -6 lines
Log Message:
Bug fix in tree consolidation routine

File Contents

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