ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_t.c
(Generate patch)

Comparing ray/src/common/bsdf_t.c (file contents):
Revision 3.6 by greg, Sun Apr 24 19:39:21 2011 UTC vs.
Revision 3.16 by greg, Sun Jun 5 20:27:14 2011 UTC

# Line 24 | Line 24 | typedef int    SDtreCallback(float val, const double *cmi
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 {
31        int             wmin;           /* minimum square size so far */
32        int             wmax;           /* maximum square size */
36          int             nic;            /* number of input coordinates */
37 <        int             alen;           /* current array length */
38 <        int             nall;           /* number of allocated entries */
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 */
# Line 57 | Line 62 | SDnewNode(int nd, int lg)
62          }
63          if (lg < 0) {
64                  st = (SDNode *)malloc(sizeof(SDNode) +
65 <                                ((1<<nd) - 1)*sizeof(st->u.t[0]));
66 <                if (st != NULL)
62 <                        memset(st->u.t, 0, sizeof(st->u.t[0])<<nd);
63 <        } else
64 <                st = (SDNode *)malloc(sizeof(SDNode) +
65 <                                ((1 << nd*lg) - 1)*sizeof(st->u.v[0]));
66 <                
67 <        if (st == NULL) {
68 <                if (lg < 0)
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 <                else
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;
78 >                        return NULL;
79 >                }
80          }
81          st->ndim = nd;
82          st->log2GR = lg;
# Line 82 | Line 87 | SDnewNode(int nd, int lg)
87   static void
88   SDfreeTre(SDNode *st)
89   {
90 <        int     i;
90 >        int     n;
91  
92          if (st == NULL)
93                  return;
94 <        for (i = (st->log2GR < 0) << st->ndim; i--; )
95 <                SDfreeTre(st->u.t[i]);
96 <        free((void *)st);
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 */
# Line 103 | Line 108 | SDFreeBTre(void *p)
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 siz, const int *imin, const int *imax)
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;
111        unsigned        skipsiz = 1;
194          int             i;
195 <        
196 <        for (i = nd; --i > 0; )
197 <                skipsiz *= siz;
195 >
196 >        va += *imin * skipsiz;
197 >
198          if (skipsiz == 1)
199                  for (i = *imin; i < *imax; i++)
200 <                        sum += va[i];
200 >                        sum += *va++;
201          else
202 <                for (i = *imin; i < *imax; i++)
203 <                        sum += SDiterSum(va + i*skipsiz,
122 <                                        nd-1, siz, imin+1, imax+1);
202 >                for (i = *imin; i < *imax; i++, va += skipsiz)
203 >                        sum += SDiterSum(va, nd, shft, imin+1, imax+1);
204          return sum;
205   }
206  
# Line 127 | Line 208 | SDiterSum(const float *va, int nd, int siz, const int
208   static double
209   SDavgTreBox(const SDNode *st, const double *bmin, const double *bmax)
210   {
130        int             imin[SD_MAXDIM], imax[SD_MAXDIM];
211          unsigned        n;
212          int             i;
213  
# Line 137 | Line 217 | SDavgTreBox(const SDNode *st, const double *bmin, cons
217          for (i = st->ndim; i--; ) {
218                  if (bmin[i] >= 1.)
219                          return .0;
220 <                if (bmax[i] <= .0)
220 >                if (bmax[i] <= 0)
221                          return .0;
222                  if (bmin[i] >= bmax[i])
223                          return .0;
# Line 145 | Line 225 | SDavgTreBox(const SDNode *st, const double *bmin, cons
225          if (st->log2GR < 0) {           /* iterate on subtree */
226                  double          sum = .0, wsum = 1e-20;
227                  double          sbmin[SD_MAXDIM], sbmax[SD_MAXDIM], w;
148
228                  for (n = 1 << st->ndim; n--; ) {
229                          w = 1.;
230                          for (i = st->ndim; i--; ) {
# Line 157 | Line 236 | SDavgTreBox(const SDNode *st, const double *bmin, cons
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) {
# Line 165 | Line 248 | SDavgTreBox(const SDNode *st, const double *bmin, cons
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 <        n = 1;                          /* iterate over leaves */
170 <        for (i = st->ndim; i--; ) {
171 <                imin[i] = (bmin[i] <= .0) ? 0
172 <                                : (int)((1 << st->log2GR)*bmin[i]);
173 <                imax[i] = (bmax[i] >= 1.) ? (1 << st->log2GR)
174 <                                : (int)((1 << st->log2GR)*bmax[i] + .999999);
175 <                n *= imax[i] - imin[i];
176 <        }
177 <        if (!n)
178 <                return .0;
179 <        
180 <        return SDiterSum(st->u.v, st->ndim, 1 << st->log2GR, imin, imax) /
181 <                        (double)n;
266 >        return .0;
267   }
268  
269   /* Recursive call for SDtraverseTre() */
# Line 193 | Line 278 | SDdotravTre(const SDNode *st, const double *pos, int c
278                                          /* in branches? */
279          if (st->log2GR < 0) {
280                  unsigned        skipmask = 0;
196
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--; )
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--; )
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;
# Line 238 | Line 324 | SDdotravTre(const SDNode *st, const double *pos, int c
324                                  clim[i][0] = 0;
325                                  clim[i][1] = 1 << st->log2GR;
326                          }
241                                        /* fill in unused dimensions */
242                for (i = SD_MAXDIM; i-- > st->ndim; ) {
243                        clim[i][0] = 0; clim[i][1] = 1;
244                }
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 <                        for (cpos[2] = clim[2][0]; cpos[2] < clim[2][1]; cpos[2]++) {
334 <                            bmin[3] = cmin[3] + csiz*(cpos[3] = clim[3][0]);
333 >                        if (st->ndim == 3) {
334 >                            cpos[2] = clim[2][0];
335                              n = cpos[0];
336 <                            for (i = 1; i < st->ndim; i++)
336 >                            for (i = 1; i < 3; i++)
337                                  n = (n << st->log2GR) + cpos[i];
338 <                            for ( ; cpos[3] < clim[3][1]; cpos[3]++) {
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[3] += csiz;
342 >                                bmin[2] += csiz;
343                              }
344 <                            bmin[2] += csiz;
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                      }
# Line 334 | Line 429 | SDlookupTre(const SDNode *st, const double *pos, doubl
429   static float
430   SDqueryTre(const SDTre *sdt, const FVECT outVec, const FVECT inVec, double *hc)
431   {
337        static const FVECT      zvec = {.0, .0, 1.};
432          FVECT                   rOutVec;
433          double                  gridPos[4];
434 <                                        /* check transmission */
435 <        if (!sdt->isxmit ^ outVec[2] > 0 ^ inVec[2] > 0)
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]));
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) {
# Line 383 | Line 491 | build_scaffold(float val, const double *cmin, double c
491                  sp->wmax = wid;
492          if (sp->alen >= sp->nall) {     /* need more space? */
493                  struct outdir_s *ndarr;
494 <                sp->nall += 8192;
494 >                sp->nall += 1024;
495                  ndarr = (struct outdir_s *)realloc(sp->darr,
496                                          sizeof(struct outdir_s)*sp->nall);
497 <                if (ndarr == NULL)
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;
508 <        bmax[1] = bmin[1] + wid;
509 <        hilbert_box_vtx(2, sizeof(bitmask_t), sizeof(unsigned)*4,
510 <                                                        1, bmin, bmax);
400 <        sp->darr[sp->alen].hent = hilbert_c2i(2, sizeof(unsigned)*4, bmin);
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 */
# Line 408 | Line 518 | build_scaffold(float val, const double *cmin, double c
518   static int
519   sscmp(const void *p1, const void *p2)
520   {
521 <        return (int)((*(const struct outdir_s *)p1).hent -
522 <                        (*(const struct outdir_s *)p2).hent);
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   {
419        const unsigned  cumlmax = ~0;
535          SDdistScaffold  myScaffold;
536          SDTreCDst       *cd;
537          struct outdir_s *sp;
# Line 427 | Line 542 | make_cdist(const SDTre *sdt, const double *pos)
542          myScaffold.wmax = 0;
543          myScaffold.nic = sdt->st->ndim - 2;
544          myScaffold.alen = 0;
545 <        myScaffold.nall = 8192;
545 >        myScaffold.nall = 512;
546          myScaffold.darr = (struct outdir_s *)malloc(sizeof(struct outdir_s) *
547                                                          myScaffold.nall);
548          if (myScaffold.darr == NULL)
# Line 442 | Line 557 | make_cdist(const SDTre *sdt, const double *pos)
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 = (double)myScaffold.wmin / iwmax;
572 >        scale = myScaffold.wmin / (double)iwmax;
573          for (i = myScaffold.nic; i--; ) {
574 <                cd->clim[i][0] = floor(pos[i]/scale + .5) * scale;
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->isxmit = sdt->isxmit;
583 >        cd->sidef = sdt->sidef;
584          cd->cTotal = 1e-20;             /* compute directional total */
585          sp = myScaffold.darr;
586          for (i = myScaffold.alen; i--; sp++)
# Line 466 | Line 589 | make_cdist(const SDTre *sdt, const double *pos)
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          }
# Line 531 | Line 655 | SDqueryTreProjSA(double *psa, const FVECT v1, const RR
655                  const SDTre     *sdt = (SDTre *)sdc->dist;
656                  double          hcube[SD_MAXDIM];
657                  if (SDqueryTre(sdt, v1, v2, hcube) < 0) {
658 <                        if (qflags == SDqueryVal)
659 <                                *psa = M_PI;
536 <                        return SDEnone;
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;
# Line 571 | Line 694 | SDsampTreCDist(FVECT ioVec, double randX, const SDCDst
694   {
695          const unsigned  nBitsC = 4*sizeof(bitmask_t);
696          const unsigned  nExtraBits = 8*(sizeof(bitmask_t)-sizeof(unsigned));
574        const unsigned  maxval = ~0;
697          const SDTreCDst *cd = (const SDTreCDst *)cdp;
698 <        const unsigned  target = randX*maxval;
698 >        const unsigned  target = randX*cumlmax;
699          bitmask_t       hndx, hcoord[2];
700 <        double          gpos[3];
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)
# Line 588 | Line 715 | SDsampTreCDist(FVECT ioVec, double randX, const SDCDst
715                  else
716                          iupper = i;
717                                          /* localize random position */
718 <        randX = (randX*maxval - cd->carr[ilower].cuml) /
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)
# Line 599 | Line 726 | SDsampTreCDist(FVECT ioVec, double randX, const SDCDst
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 <        if (ioVec[2] > 0 ^ !cd->isxmit)
733 >                                        /* emit from back? */
734 >        if (ioVec[2] > 0 ^ cd->sidef != SD_XMIT)
735                  gpos[2] = -gpos[2];
736 <        VCOPY(ioVec, gpos);
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 <        return SDEsupport;
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 */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines