ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf.c
Revision: 2.25
Committed: Sun Apr 24 20:16:52 2011 UTC (13 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.24: +6 -6 lines
Log Message:
Bug fixes to last change

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.25 static const char RCSid[] = "$Id: bsdf.c,v 2.24 2011/04/24 19:39:21 greg Exp $";
3 greg 2.1 #endif
4     /*
5 greg 2.15 * bsdf.c
6     *
7     * Definitions for bidirectional scattering distribution functions.
8     *
9     * Created by Greg Ward on 1/10/11.
10     *
11     */
12    
13     #include <stdio.h>
14     #include <stdlib.h>
15     #include <math.h>
16     #include "ezxml.h"
17     #include "hilbert.h"
18     #include "bsdf.h"
19     #include "bsdf_m.h"
20     #include "bsdf_t.h"
21    
22     /* English ASCII strings corresponding to ennumerated errors */
23     const char *SDerrorEnglish[] = {
24     "No error",
25     "Memory error",
26     "File input/output error",
27     "File format error",
28     "Illegal argument",
29     "Invalid data",
30     "Unsupported feature",
31     "Internal program error",
32     "Unknown error"
33     };
34    
35     /* Additional information on last error (ASCII English) */
36     char SDerrorDetail[256];
37    
38     /* Cache of loaded BSDFs */
39     struct SDCache_s *SDcacheList = NULL;
40    
41     /* Retain BSDFs in cache list */
42     int SDretainSet = SDretainNone;
43    
44     /* Report any error to the indicated stream (in English) */
45     SDError
46     SDreportEnglish(SDError ec, FILE *fp)
47     {
48 greg 2.21 if (!ec)
49     return SDEnone;
50     if ((ec < SDEnone) | (ec > SDEunknown)) {
51     SDerrorDetail[0] = '\0';
52     ec = SDEunknown;
53     }
54 greg 2.15 if (fp == NULL)
55     return ec;
56     fputs(SDerrorEnglish[ec], fp);
57     if (SDerrorDetail[0]) {
58     fputs(": ", fp);
59     fputs(SDerrorDetail, fp);
60     }
61     fputc('\n', fp);
62     if (fp != stderr)
63     fflush(fp);
64     return ec;
65     }
66    
67     static double
68     to_meters( /* return factor to convert given unit to meters */
69     const char *unit
70     )
71     {
72     if (unit == NULL) return(1.); /* safe assumption? */
73     if (!strcasecmp(unit, "Meter")) return(1.);
74     if (!strcasecmp(unit, "Foot")) return(.3048);
75     if (!strcasecmp(unit, "Inch")) return(.0254);
76     if (!strcasecmp(unit, "Centimeter")) return(.01);
77     if (!strcasecmp(unit, "Millimeter")) return(.001);
78     sprintf(SDerrorDetail, "Unknown dimensional unit '%s'", unit);
79     return(-1.);
80     }
81    
82     /* Load geometric dimensions and description (if any) */
83     static SDError
84 greg 2.16 SDloadGeometry(SDData *sd, ezxml_t wdb)
85 greg 2.15 {
86     ezxml_t geom;
87     double cfact;
88     const char *fmt, *mgfstr;
89    
90 greg 2.16 if (wdb == NULL) /* no geometry section? */
91     return SDEnone;
92     sd->dim[0] = sd->dim[1] = sd->dim[2] = .0;
93 greg 2.15 if ((geom = ezxml_child(wdb, "Width")) != NULL)
94 greg 2.16 sd->dim[0] = atof(ezxml_txt(geom)) *
95 greg 2.15 to_meters(ezxml_attr(geom, "unit"));
96     if ((geom = ezxml_child(wdb, "Height")) != NULL)
97 greg 2.16 sd->dim[1] = atof(ezxml_txt(geom)) *
98 greg 2.15 to_meters(ezxml_attr(geom, "unit"));
99     if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
100 greg 2.16 sd->dim[2] = atof(ezxml_txt(geom)) *
101 greg 2.15 to_meters(ezxml_attr(geom, "unit"));
102 greg 2.23 if ((sd->dim[0] < 0) | (sd->dim[1] < 0) | (sd->dim[2] < 0)) {
103 greg 2.17 sprintf(SDerrorDetail, "Negative size in \"%s\"", sd->name);
104 greg 2.15 return SDEdata;
105 greg 2.17 }
106 greg 2.15 if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
107     (mgfstr = ezxml_txt(geom)) == NULL)
108     return SDEnone;
109     if ((fmt = ezxml_attr(geom, "format")) != NULL &&
110     strcasecmp(fmt, "MGF")) {
111     sprintf(SDerrorDetail,
112     "Unrecognized geometry format '%s' in \"%s\"",
113 greg 2.16 fmt, sd->name);
114 greg 2.15 return SDEsupport;
115     }
116     cfact = to_meters(ezxml_attr(geom, "unit"));
117 greg 2.16 sd->mgf = (char *)malloc(strlen(mgfstr)+32);
118     if (sd->mgf == NULL) {
119 greg 2.15 strcpy(SDerrorDetail, "Out of memory in SDloadGeometry");
120     return SDEmemory;
121     }
122     if (cfact < 0.99 || cfact > 1.01)
123 greg 2.16 sprintf(sd->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
124 greg 2.15 else
125 greg 2.16 strcpy(sd->mgf, mgfstr);
126 greg 2.15 return SDEnone;
127     }
128    
129     /* Load a BSDF struct from the given file (free first and keep name) */
130     SDError
131     SDloadFile(SDData *sd, const char *fname)
132     {
133     SDError lastErr;
134 greg 2.16 ezxml_t fl, wtl;
135 greg 2.15
136     if ((sd == NULL) | (fname == NULL || !*fname))
137     return SDEargument;
138     /* free old data, keeping name */
139     SDfreeBSDF(sd);
140     /* parse XML file */
141     fl = ezxml_parse_file(fname);
142     if (fl == NULL) {
143     sprintf(SDerrorDetail, "Cannot open BSDF \"%s\"", fname);
144     return SDEfile;
145     }
146     if (ezxml_error(fl)[0]) {
147     sprintf(SDerrorDetail, "BSDF \"%s\" %s", fname, ezxml_error(fl));
148     ezxml_free(fl);
149     return SDEformat;
150     }
151 greg 2.16 if (strcmp(ezxml_name(fl), "WindowElement")) {
152     sprintf(SDerrorDetail,
153     "BSDF \"%s\": top level node not 'WindowElement'",
154     sd->name);
155     ezxml_free(fl);
156     return SDEformat;
157     }
158     wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
159     if (wtl == NULL) {
160     sprintf(SDerrorDetail, "BSDF \"%s\": no optical layer'",
161     sd->name);
162     ezxml_free(fl);
163     return SDEformat;
164     }
165 greg 2.15 /* load geometry if present */
166 greg 2.16 lastErr = SDloadGeometry(sd, ezxml_child(wtl, "Material"));
167     if (lastErr)
168 greg 2.15 return lastErr;
169     /* try loading variable resolution data */
170 greg 2.16 lastErr = SDloadTre(sd, wtl);
171 greg 2.15 /* check our result */
172     switch (lastErr) {
173     case SDEformat:
174     case SDEdata:
175     case SDEsupport: /* possibly we just tried the wrong format */
176 greg 2.16 lastErr = SDloadMtx(sd, wtl);
177 greg 2.15 break;
178     default: /* variable res. OK else serious error */
179     break;
180     }
181     /* done with XML file */
182     ezxml_free(fl);
183 greg 2.16
184     if (lastErr) { /* was there a load error? */
185     SDfreeBSDF(sd);
186     return lastErr;
187     }
188     /* remove any insignificant components */
189     if (sd->rf != NULL && sd->rf->maxHemi <= .001) {
190     SDfreeSpectralDF(sd->rf); sd->rf = NULL;
191     }
192     if (sd->rb != NULL && sd->rb->maxHemi <= .001) {
193     SDfreeSpectralDF(sd->rb); sd->rb = NULL;
194     }
195     if (sd->tf != NULL && sd->tf->maxHemi <= .001) {
196     SDfreeSpectralDF(sd->tf); sd->tf = NULL;
197     }
198     /* return success */
199     return SDEnone;
200 greg 2.15 }
201    
202     /* Allocate new spectral distribution function */
203     SDSpectralDF *
204     SDnewSpectralDF(int nc)
205     {
206     SDSpectralDF *df;
207    
208     if (nc <= 0) {
209     strcpy(SDerrorDetail, "Zero component spectral DF request");
210     return NULL;
211     }
212     df = (SDSpectralDF *)malloc(sizeof(SDSpectralDF) +
213     (nc-1)*sizeof(SDComponent));
214     if (df == NULL) {
215     sprintf(SDerrorDetail,
216     "Cannot allocate %d component spectral DF", nc);
217     return NULL;
218     }
219     df->minProjSA = .0;
220     df->maxHemi = .0;
221     df->ncomp = nc;
222     memset(df->comp, 0, nc*sizeof(SDComponent));
223     return df;
224     }
225    
226     /* Free cached cumulative distributions for BSDF component */
227     void
228     SDfreeCumulativeCache(SDSpectralDF *df)
229     {
230     int n;
231     SDCDst *cdp;
232    
233     if (df == NULL)
234     return;
235     for (n = df->ncomp; n-- > 0; )
236     while ((cdp = df->comp[n].cdList) != NULL) {
237     df->comp[n].cdList = cdp->next;
238     free(cdp);
239     }
240     }
241    
242     /* Free a spectral distribution function */
243     void
244     SDfreeSpectralDF(SDSpectralDF *df)
245     {
246     int n;
247    
248     if (df == NULL)
249     return;
250     SDfreeCumulativeCache(df);
251     for (n = df->ncomp; n-- > 0; )
252     (*df->comp[n].func->freeSC)(df->comp[n].dist);
253     free(df);
254     }
255    
256     /* Shorten file path to useable BSDF name, removing suffix */
257     void
258 greg 2.16 SDclipName(char *res, const char *fname)
259 greg 2.15 {
260     const char *cp, *dot = NULL;
261    
262     for (cp = fname; *cp; cp++)
263     if (*cp == '.')
264     dot = cp;
265     if ((dot == NULL) | (dot < fname+2))
266     dot = cp;
267     if (dot - fname >= SDnameLn)
268     fname = dot - SDnameLn + 1;
269     while (fname < dot)
270     *res++ = *fname++;
271     *res = '\0';
272     }
273    
274     /* Initialize an unused BSDF struct (simply clears to zeroes) */
275     void
276 greg 2.20 SDclearBSDF(SDData *sd, const char *fname)
277 greg 2.15 {
278 greg 2.20 if (sd == NULL)
279     return;
280     memset(sd, 0, sizeof(SDData));
281     if (fname == NULL)
282     return;
283     SDclipName(sd->name, fname);
284 greg 2.15 }
285    
286     /* Free data associated with BSDF struct */
287     void
288     SDfreeBSDF(SDData *sd)
289     {
290     if (sd == NULL)
291     return;
292     if (sd->mgf != NULL) {
293     free(sd->mgf);
294     sd->mgf = NULL;
295     }
296     if (sd->rf != NULL) {
297     SDfreeSpectralDF(sd->rf);
298     sd->rf = NULL;
299     }
300     if (sd->rb != NULL) {
301     SDfreeSpectralDF(sd->rb);
302     sd->rb = NULL;
303     }
304     if (sd->tf != NULL) {
305     SDfreeSpectralDF(sd->tf);
306     sd->tf = NULL;
307     }
308     sd->rLambFront.cieY = .0;
309 greg 2.16 sd->rLambFront.spec.flags = 0;
310 greg 2.15 sd->rLambBack.cieY = .0;
311 greg 2.16 sd->rLambBack.spec.flags = 0;
312 greg 2.15 sd->tLamb.cieY = .0;
313 greg 2.16 sd->tLamb.spec.flags = 0;
314 greg 2.15 }
315    
316     /* Find writeable BSDF by name, or allocate new cache entry if absent */
317     SDData *
318     SDgetCache(const char *bname)
319     {
320     struct SDCache_s *sdl;
321     char sdnam[SDnameLn];
322    
323     if (bname == NULL)
324     return NULL;
325    
326     SDclipName(sdnam, bname);
327     for (sdl = SDcacheList; sdl != NULL; sdl = sdl->next)
328     if (!strcmp(sdl->bsdf.name, sdnam)) {
329     sdl->refcnt++;
330     return &sdl->bsdf;
331     }
332    
333     sdl = (struct SDCache_s *)calloc(1, sizeof(struct SDCache_s));
334     if (sdl == NULL)
335     return NULL;
336    
337     strcpy(sdl->bsdf.name, sdnam);
338     sdl->next = SDcacheList;
339     SDcacheList = sdl;
340    
341 greg 2.21 sdl->refcnt = 1;
342 greg 2.15 return &sdl->bsdf;
343     }
344    
345     /* Get loaded BSDF from cache (or load and cache it on first call) */
346     /* Report any problem to stderr and return NULL on failure */
347     const SDData *
348     SDcacheFile(const char *fname)
349     {
350     SDData *sd;
351     SDError ec;
352    
353     if (fname == NULL || !*fname)
354     return NULL;
355     SDerrorDetail[0] = '\0';
356     if ((sd = SDgetCache(fname)) == NULL) {
357     SDreportEnglish(SDEmemory, stderr);
358     return NULL;
359     }
360     if (!SDisLoaded(sd) && (ec = SDloadFile(sd, fname))) {
361     SDreportEnglish(ec, stderr);
362     SDfreeCache(sd);
363     return NULL;
364     }
365     return sd;
366     }
367    
368     /* Free a BSDF from our cache (clear all if NULL) */
369     void
370     SDfreeCache(const SDData *sd)
371     {
372     struct SDCache_s *sdl, *sdLast = NULL;
373    
374     if (sd == NULL) { /* free entire list */
375     while ((sdl = SDcacheList) != NULL) {
376     SDcacheList = sdl->next;
377     SDfreeBSDF(&sdl->bsdf);
378     free(sdl);
379     }
380     return;
381     }
382     for (sdl = SDcacheList; sdl != NULL; sdl = (sdLast=sdl)->next)
383     if (&sdl->bsdf == sd)
384     break;
385 greg 2.21 if (sdl == NULL || (sdl->refcnt -= (sdl->refcnt > 0)))
386 greg 2.15 return; /* missing or still in use */
387     /* keep unreferenced data? */
388     if (SDisLoaded(sd) && SDretainSet) {
389     if (SDretainSet == SDretainAll)
390     return; /* keep everything */
391     /* else free cumulative data */
392     SDfreeCumulativeCache(sd->rf);
393     SDfreeCumulativeCache(sd->rb);
394     SDfreeCumulativeCache(sd->tf);
395     return;
396     }
397     /* remove from list and free */
398     if (sdLast == NULL)
399     SDcacheList = sdl->next;
400     else
401     sdLast->next = sdl->next;
402     SDfreeBSDF(&sdl->bsdf);
403     free(sdl);
404     }
405    
406     /* Sample an individual BSDF component */
407     SDError
408 greg 2.24 SDsampComponent(SDValue *sv, FVECT ioVec, double randX, SDComponent *sdc)
409 greg 2.15 {
410     float coef[SDmaxCh];
411     SDError ec;
412 greg 2.24 FVECT inVec;
413 greg 2.15 const SDCDst *cd;
414     double d;
415     int n;
416     /* check arguments */
417 greg 2.24 if ((sv == NULL) | (ioVec == NULL) | (sdc == NULL))
418 greg 2.15 return SDEargument;
419     /* get cumulative distribution */
420 greg 2.24 VCOPY(inVec, ioVec);
421 greg 2.15 cd = (*sdc->func->getCDist)(inVec, sdc);
422     if (cd == NULL)
423     return SDEmemory;
424     if (cd->cTotal <= 1e-7) { /* anything to sample? */
425     sv->spec = c_dfcolor;
426     sv->cieY = .0;
427 greg 2.24 memset(ioVec, 0, 3*sizeof(double));
428 greg 2.15 return SDEnone;
429     }
430     sv->cieY = cd->cTotal;
431     /* compute sample direction */
432 greg 2.24 ec = (*sdc->func->sampCDist)(ioVec, randX, cd);
433 greg 2.15 if (ec)
434     return ec;
435     /* get BSDF color */
436 greg 2.25 n = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
437 greg 2.15 if (n <= 0) {
438     strcpy(SDerrorDetail, "BSDF sample value error");
439     return SDEinternal;
440     }
441     sv->spec = sdc->cspec[0];
442     d = coef[0];
443     while (--n) {
444     c_cmix(&sv->spec, d, &sv->spec, coef[n], &sdc->cspec[n]);
445     d += coef[n];
446     }
447     /* make sure everything is set */
448     c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
449     return SDEnone;
450     }
451    
452     #define MS_MAXDIM 15
453    
454     /* Convert 1-dimensional random variable to N-dimensional */
455     void
456     SDmultiSamp(double t[], int n, double randX)
457     {
458     unsigned nBits;
459     double scale;
460     bitmask_t ndx, coord[MS_MAXDIM];
461    
462     while (n > MS_MAXDIM) /* punt for higher dimensions */
463 greg 2.19 t[--n] = rand()*(1./(RAND_MAX+.5));
464 greg 2.15 nBits = (8*sizeof(bitmask_t) - 1) / n;
465     ndx = randX * (double)((bitmask_t)1 << (nBits*n));
466     /* get coordinate on Hilbert curve */
467     hilbert_i2c(n, nBits, ndx, coord);
468     /* convert back to [0,1) range */
469     scale = 1. / (double)((bitmask_t)1 << nBits);
470     while (n--)
471 greg 2.19 t[n] = scale * ((double)coord[n] + rand()*(1./(RAND_MAX+.5)));
472 greg 2.15 }
473    
474     #undef MS_MAXDIM
475    
476     /* Generate diffuse hemispherical sample */
477     static void
478     SDdiffuseSamp(FVECT outVec, int outFront, double randX)
479     {
480     /* convert to position on hemisphere */
481     SDmultiSamp(outVec, 2, randX);
482     SDsquare2disk(outVec, outVec[0], outVec[1]);
483     outVec[2] = 1. - outVec[0]*outVec[0] - outVec[1]*outVec[1];
484 greg 2.23 if (outVec[2] > 0) /* a bit of paranoia */
485 greg 2.15 outVec[2] = sqrt(outVec[2]);
486     if (!outFront) /* going out back? */
487     outVec[2] = -outVec[2];
488     }
489    
490     /* Query projected solid angle coverage for non-diffuse BSDF direction */
491     SDError
492 greg 2.22 SDsizeBSDF(double *projSA, const FVECT v1, const RREAL *v2,
493     int qflags, const SDData *sd)
494 greg 2.15 {
495 greg 2.23 SDSpectralDF *rdf, *tdf;
496 greg 2.15 SDError ec;
497     int i;
498     /* check arguments */
499 greg 2.22 if ((projSA == NULL) | (v1 == NULL))
500 greg 2.15 return SDEargument;
501     /* initialize extrema */
502 greg 2.17 switch (qflags) {
503 greg 2.15 case SDqueryMax:
504     projSA[0] = .0;
505     break;
506     case SDqueryMin+SDqueryMax:
507     projSA[1] = .0;
508     /* fall through */
509     case SDqueryMin:
510     projSA[0] = 10.;
511     break;
512     case 0:
513     return SDEargument;
514     }
515 greg 2.23 if (v1[2] > 0) /* front surface query? */
516 greg 2.15 rdf = sd->rf;
517     else
518     rdf = sd->rb;
519 greg 2.23 tdf = NULL; /* transmitted component? */
520     if (v2 != NULL && v1[2] > 0 ^ v2[2] > 0) {
521     rdf = NULL;
522     tdf = sd->tf;
523     }
524 greg 2.15 ec = SDEdata; /* run through components */
525     for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
526 greg 2.22 ec = (*rdf->comp[i].func->queryProjSA)(projSA, v1, v2,
527 greg 2.25 qflags, &rdf->comp[i]);
528 greg 2.15 if (ec)
529     return ec;
530     }
531 greg 2.23 for (i = (tdf==NULL) ? 0 : tdf->ncomp; i--; ) {
532     ec = (*tdf->comp[i].func->queryProjSA)(projSA, v1, v2,
533 greg 2.25 qflags, &tdf->comp[i]);
534 greg 2.15 if (ec)
535     return ec;
536     }
537 greg 2.17 if (ec) { /* all diffuse? */
538     projSA[0] = M_PI;
539     if (qflags == SDqueryMin+SDqueryMax)
540     projSA[1] = M_PI;
541     }
542     return SDEnone;
543 greg 2.15 }
544    
545     /* Return BSDF for the given incident and scattered ray vectors */
546     SDError
547     SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
548     {
549     int inFront, outFront;
550     SDSpectralDF *sdf;
551     float coef[SDmaxCh];
552     int nch, i;
553     /* check arguments */
554     if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
555     return SDEargument;
556     /* whose side are we on? */
557 greg 2.23 inFront = (inVec[2] > 0);
558     outFront = (outVec[2] > 0);
559 greg 2.15 /* start with diffuse portion */
560     if (inFront & outFront) {
561     *sv = sd->rLambFront;
562     sdf = sd->rf;
563     } else if (!(inFront | outFront)) {
564     *sv = sd->rLambBack;
565     sdf = sd->rb;
566     } else /* inFront ^ outFront */ {
567     *sv = sd->tLamb;
568     sdf = sd->tf;
569     }
570     sv->cieY *= 1./M_PI;
571     /* add non-diffuse components */
572     i = (sdf != NULL) ? sdf->ncomp : 0;
573     while (i-- > 0) {
574     nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
575 greg 2.25 &sdf->comp[i]);
576 greg 2.15 while (nch-- > 0) {
577     c_cmix(&sv->spec, sv->cieY, &sv->spec,
578     coef[nch], &sdf->comp[i].cspec[nch]);
579     sv->cieY += coef[nch];
580     }
581     }
582     /* make sure everything is set */
583     c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
584     return SDEnone;
585     }
586    
587     /* Compute directional hemispherical scattering at this incident angle */
588     double
589     SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
590     {
591     double hsum;
592     SDSpectralDF *rdf;
593     const SDCDst *cd;
594     int i;
595     /* check arguments */
596     if ((inVec == NULL) | (sd == NULL))
597     return .0;
598     /* gather diffuse components */
599 greg 2.23 if (inVec[2] > 0) {
600 greg 2.15 hsum = sd->rLambFront.cieY;
601     rdf = sd->rf;
602     } else /* !inFront */ {
603     hsum = sd->rLambBack.cieY;
604     rdf = sd->rb;
605     }
606     if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
607     hsum = .0;
608     if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
609     hsum += sd->tLamb.cieY;
610     /* gather non-diffuse components */
611     i = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
612     rdf != NULL) ? rdf->ncomp : 0;
613     while (i-- > 0) { /* non-diffuse reflection */
614     cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
615     if (cd != NULL)
616     hsum += cd->cTotal;
617     }
618     i = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
619     sd->tf != NULL) ? sd->tf->ncomp : 0;
620     while (i-- > 0) { /* non-diffuse transmission */
621     cd = (*sd->tf->comp[i].func->getCDist)(inVec, &sd->tf->comp[i]);
622     if (cd != NULL)
623     hsum += cd->cTotal;
624     }
625     return hsum;
626     }
627    
628     /* Sample BSDF direction based on the given random variable */
629     SDError
630 greg 2.24 SDsampBSDF(SDValue *sv, FVECT ioVec, double randX, int sflags, const SDData *sd)
631 greg 2.15 {
632     SDError ec;
633 greg 2.24 FVECT inVec;
634 greg 2.15 int inFront;
635     SDSpectralDF *rdf;
636     double rdiff;
637     float coef[SDmaxCh];
638     int i, j, n, nr;
639     SDComponent *sdc;
640     const SDCDst **cdarr = NULL;
641     /* check arguments */
642 greg 2.24 if ((sv == NULL) | (ioVec == NULL) | (sd == NULL) |
643 greg 2.23 (randX < 0) | (randX >= 1.))
644 greg 2.15 return SDEargument;
645     /* whose side are we on? */
646 greg 2.24 VCOPY(inVec, ioVec);
647 greg 2.23 inFront = (inVec[2] > 0);
648 greg 2.15 /* remember diffuse portions */
649     if (inFront) {
650     *sv = sd->rLambFront;
651     rdf = sd->rf;
652     } else /* !inFront */ {
653     *sv = sd->rLambBack;
654     rdf = sd->rb;
655     }
656     if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
657     sv->cieY = .0;
658     rdiff = sv->cieY;
659     if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
660     sv->cieY += sd->tLamb.cieY;
661     /* gather non-diffuse components */
662     i = nr = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
663     rdf != NULL) ? rdf->ncomp : 0;
664     j = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
665     sd->tf != NULL) ? sd->tf->ncomp : 0;
666     n = i + j;
667     if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
668     return SDEmemory;
669     while (j-- > 0) { /* non-diffuse transmission */
670     cdarr[i+j] = (*sd->tf->comp[j].func->getCDist)(inVec, &sd->tf->comp[j]);
671     if (cdarr[i+j] == NULL) {
672     free(cdarr);
673     return SDEmemory;
674     }
675     sv->cieY += cdarr[i+j]->cTotal;
676     }
677     while (i-- > 0) { /* non-diffuse reflection */
678     cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
679     if (cdarr[i] == NULL) {
680     free(cdarr);
681     return SDEmemory;
682     }
683     sv->cieY += cdarr[i]->cTotal;
684     }
685     if (sv->cieY <= 1e-7) { /* anything to sample? */
686     sv->cieY = .0;
687 greg 2.24 memset(ioVec, 0, 3*sizeof(double));
688 greg 2.15 return SDEnone;
689     }
690     /* scale random variable */
691     randX *= sv->cieY;
692     /* diffuse reflection? */
693     if (randX < rdiff) {
694 greg 2.24 SDdiffuseSamp(ioVec, inFront, randX/rdiff);
695 greg 2.15 goto done;
696     }
697     randX -= rdiff;
698     /* diffuse transmission? */
699     if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
700     if (randX < sd->tLamb.cieY) {
701     sv->spec = sd->tLamb.spec;
702 greg 2.24 SDdiffuseSamp(ioVec, !inFront, randX/sd->tLamb.cieY);
703 greg 2.15 goto done;
704     }
705     randX -= sd->tLamb.cieY;
706     }
707     /* else one of cumulative dist. */
708     for (i = 0; i < n && randX < cdarr[i]->cTotal; i++)
709     randX -= cdarr[i]->cTotal;
710     if (i >= n)
711     return SDEinternal;
712     /* compute sample direction */
713     sdc = (i < nr) ? &rdf->comp[i] : &sd->tf->comp[i-nr];
714 greg 2.24 ec = (*sdc->func->sampCDist)(ioVec, randX/cdarr[i]->cTotal, cdarr[i]);
715 greg 2.15 if (ec)
716     return ec;
717     /* compute color */
718 greg 2.25 j = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
719 greg 2.15 if (j <= 0) {
720     sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
721     sd->name);
722     return SDEinternal;
723     }
724     sv->spec = sdc->cspec[0];
725     rdiff = coef[0];
726     while (--j) {
727     c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
728     rdiff += coef[j];
729     }
730     done:
731     if (cdarr != NULL)
732     free(cdarr);
733     /* make sure everything is set */
734     c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
735     return SDEnone;
736     }
737    
738     /* Compute World->BSDF transform from surface normal and up (Y) vector */
739     SDError
740     SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
741     {
742     if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
743     return SDEargument;
744     VCOPY(vMtx[2], sNrm);
745 greg 2.23 if (normalize(vMtx[2]) == 0)
746 greg 2.15 return SDEargument;
747     fcross(vMtx[0], uVec, vMtx[2]);
748 greg 2.23 if (normalize(vMtx[0]) == 0)
749 greg 2.15 return SDEargument;
750     fcross(vMtx[1], vMtx[2], vMtx[0]);
751     return SDEnone;
752     }
753    
754     /* Compute inverse transform */
755     SDError
756     SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
757     {
758     RREAL mTmp[3][3];
759     double d;
760    
761     if ((iMtx == NULL) | (vMtx == NULL))
762     return SDEargument;
763     /* compute determinant */
764     mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
765     mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
766     mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
767     d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
768 greg 2.23 if (d == 0) {
769 greg 2.15 strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
770     return SDEargument;
771     }
772     d = 1./d; /* invert matrix */
773     mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
774     mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
775     mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
776     mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
777     mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
778     mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
779     mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
780     memcpy(iMtx, mTmp, sizeof(mTmp));
781     return SDEnone;
782     }
783    
784     /* Transform and normalize direction (column) vector */
785     SDError
786     SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
787     {
788     FVECT vTmp;
789    
790     if ((resVec == NULL) | (inpVec == NULL))
791     return SDEargument;
792     if (vMtx == NULL) { /* assume they just want to normalize */
793     if (resVec != inpVec)
794     VCOPY(resVec, inpVec);
795 greg 2.23 return (normalize(resVec) > 0) ? SDEnone : SDEargument;
796 greg 2.15 }
797     vTmp[0] = DOT(vMtx[0], inpVec);
798     vTmp[1] = DOT(vMtx[1], inpVec);
799     vTmp[2] = DOT(vMtx[2], inpVec);
800 greg 2.23 if (normalize(vTmp) == 0)
801 greg 2.15 return SDEargument;
802     VCOPY(resVec, vTmp);
803     return SDEnone;
804     }
805    
806     /*################################################################*/
807     /*######### DEPRECATED ROUTINES AWAITING PERMANENT REMOVAL #######*/
808    
809     /*
810 greg 2.1 * Routines for handling BSDF data
811     */
812    
813     #include "standard.h"
814     #include "paths.h"
815     #include <ctype.h>
816    
817     #define MAXLATS 46 /* maximum number of latitudes */
818    
819     /* BSDF angle specification */
820     typedef struct {
821     char name[64]; /* basis name */
822     int nangles; /* total number of directions */
823     struct {
824     float tmin; /* starting theta */
825     short nphis; /* number of phis (0 term) */
826     } lat[MAXLATS+1]; /* latitudes */
827     } ANGLE_BASIS;
828    
829 greg 2.4 #define MAXABASES 7 /* limit on defined bases */
830 greg 2.1
831     static ANGLE_BASIS abase_list[MAXABASES] = {
832     {
833     "LBNL/Klems Full", 145,
834     { {-5., 1},
835     {5., 8},
836     {15., 16},
837     {25., 20},
838     {35., 24},
839     {45., 24},
840     {55., 24},
841     {65., 16},
842     {75., 12},
843     {90., 0} }
844     }, {
845     "LBNL/Klems Half", 73,
846     { {-6.5, 1},
847     {6.5, 8},
848     {19.5, 12},
849     {32.5, 16},
850     {46.5, 20},
851     {61.5, 12},
852     {76.5, 4},
853     {90., 0} }
854     }, {
855     "LBNL/Klems Quarter", 41,
856     { {-9., 1},
857     {9., 8},
858     {27., 12},
859     {46., 12},
860     {66., 8},
861     {90., 0} }
862     }
863     };
864    
865     static int nabases = 3; /* current number of defined bases */
866    
867 greg 2.9 #define FEQ(a,b) ((a)-(b) <= 1e-6 && (b)-(a) <= 1e-6)
868    
869     static int
870     fequal(double a, double b)
871     {
872 greg 2.23 if (b != 0)
873 greg 2.9 a = a/b - 1.;
874     return((a <= 1e-6) & (a >= -1e-6));
875     }
876 greg 2.3
877 greg 2.14 /* Returns the name of the given tag */
878 greg 2.3 #ifdef ezxml_name
879     #undef ezxml_name
880     static char *
881     ezxml_name(ezxml_t xml)
882     {
883     if (xml == NULL)
884     return(NULL);
885     return(xml->name);
886     }
887     #endif
888    
889 greg 2.14 /* Returns the given tag's character content or empty string if none */
890 greg 2.3 #ifdef ezxml_txt
891     #undef ezxml_txt
892     static char *
893     ezxml_txt(ezxml_t xml)
894     {
895     if (xml == NULL)
896     return("");
897     return(xml->txt);
898     }
899     #endif
900    
901 greg 2.1
902     static int
903     ab_getvec( /* get vector for this angle basis index */
904     FVECT v,
905     int ndx,
906     void *p
907     )
908     {
909     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
910     int li;
911 greg 2.2 double pol, azi, d;
912 greg 2.1
913     if ((ndx < 0) | (ndx >= ab->nangles))
914     return(0);
915     for (li = 0; ndx >= ab->lat[li].nphis; li++)
916     ndx -= ab->lat[li].nphis;
917 greg 2.2 pol = PI/180.*0.5*(ab->lat[li].tmin + ab->lat[li+1].tmin);
918 greg 2.1 azi = 2.*PI*ndx/ab->lat[li].nphis;
919 greg 2.2 v[2] = d = cos(pol);
920     d = sqrt(1. - d*d); /* sin(pol) */
921 greg 2.1 v[0] = cos(azi)*d;
922     v[1] = sin(azi)*d;
923     return(1);
924     }
925    
926    
927     static int
928     ab_getndx( /* get index corresponding to the given vector */
929     FVECT v,
930     void *p
931     )
932     {
933     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
934     int li, ndx;
935 greg 2.2 double pol, azi, d;
936 greg 2.1
937     if ((v[2] < -1.0) | (v[2] > 1.0))
938     return(-1);
939 greg 2.2 pol = 180.0/PI*acos(v[2]);
940 greg 2.1 azi = 180.0/PI*atan2(v[1], v[0]);
941     if (azi < 0.0) azi += 360.0;
942 greg 2.2 for (li = 1; ab->lat[li].tmin <= pol; li++)
943 greg 2.1 if (!ab->lat[li].nphis)
944     return(-1);
945     --li;
946     ndx = (int)((1./360.)*azi*ab->lat[li].nphis + 0.5);
947     if (ndx >= ab->lat[li].nphis) ndx = 0;
948     while (li--)
949     ndx += ab->lat[li].nphis;
950     return(ndx);
951     }
952    
953    
954     static double
955     ab_getohm( /* get solid angle for this angle basis index */
956     int ndx,
957     void *p
958     )
959     {
960     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
961     int li;
962     double theta, theta1;
963    
964     if ((ndx < 0) | (ndx >= ab->nangles))
965     return(0);
966     for (li = 0; ndx >= ab->lat[li].nphis; li++)
967     ndx -= ab->lat[li].nphis;
968     theta1 = PI/180. * ab->lat[li+1].tmin;
969     if (ab->lat[li].nphis == 1) { /* special case */
970     if (ab->lat[li].tmin > FTINY)
971     error(USER, "unsupported BSDF coordinate system");
972     return(2.*PI*(1. - cos(theta1)));
973     }
974     theta = PI/180. * ab->lat[li].tmin;
975     return(2.*PI*(cos(theta) - cos(theta1))/(double)ab->lat[li].nphis);
976     }
977    
978    
979     static int
980     ab_getvecR( /* get reverse vector for this angle basis index */
981     FVECT v,
982     int ndx,
983     void *p
984     )
985     {
986     if (!ab_getvec(v, ndx, p))
987     return(0);
988    
989     v[0] = -v[0];
990     v[1] = -v[1];
991     v[2] = -v[2];
992    
993     return(1);
994     }
995    
996    
997     static int
998     ab_getndxR( /* get index corresponding to the reverse vector */
999     FVECT v,
1000     void *p
1001     )
1002     {
1003     FVECT v2;
1004    
1005     v2[0] = -v[0];
1006     v2[1] = -v[1];
1007     v2[2] = -v[2];
1008    
1009     return ab_getndx(v2, p);
1010     }
1011    
1012    
1013     static void
1014 greg 2.4 load_angle_basis( /* load custom BSDF angle basis */
1015 greg 2.3 ezxml_t wab
1016     )
1017     {
1018     char *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
1019     ezxml_t wbb;
1020     int i;
1021    
1022 greg 2.4 if (!abname || !*abname)
1023 greg 2.3 return;
1024     for (i = nabases; i--; )
1025 greg 2.12 if (!strcasecmp(abname, abase_list[i].name))
1026 greg 2.4 return; /* assume it's the same */
1027 greg 2.3 if (nabases >= MAXABASES)
1028     error(INTERNAL, "too many angle bases");
1029     strcpy(abase_list[nabases].name, abname);
1030     abase_list[nabases].nangles = 0;
1031     for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
1032     wbb != NULL; i++, wbb = wbb->next) {
1033     if (i >= MAXLATS)
1034     error(INTERNAL, "too many latitudes in custom basis");
1035     abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
1036     ezxml_child(ezxml_child(wbb,
1037     "ThetaBounds"), "UpperTheta")));
1038     if (!i)
1039     abase_list[nabases].lat[i].tmin =
1040     -abase_list[nabases].lat[i+1].tmin;
1041 greg 2.9 else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
1042 greg 2.3 "ThetaBounds"), "LowerTheta"))),
1043     abase_list[nabases].lat[i].tmin))
1044     error(WARNING, "theta values disagree in custom basis");
1045     abase_list[nabases].nangles +=
1046     abase_list[nabases].lat[i].nphis =
1047     atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
1048     }
1049     abase_list[nabases++].lat[i].nphis = 0;
1050     }
1051    
1052    
1053 greg 2.6 static void
1054     load_geometry( /* load geometric dimensions and description (if any) */
1055     struct BSDF_data *dp,
1056     ezxml_t wdb
1057     )
1058     {
1059     ezxml_t geom;
1060     double cfact;
1061     const char *fmt, *mgfstr;
1062    
1063     dp->dim[0] = dp->dim[1] = dp->dim[2] = 0;
1064     dp->mgf = NULL;
1065     if ((geom = ezxml_child(wdb, "Width")) != NULL)
1066     dp->dim[0] = atof(ezxml_txt(geom)) *
1067     to_meters(ezxml_attr(geom, "unit"));
1068     if ((geom = ezxml_child(wdb, "Height")) != NULL)
1069     dp->dim[1] = atof(ezxml_txt(geom)) *
1070     to_meters(ezxml_attr(geom, "unit"));
1071     if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
1072     dp->dim[2] = atof(ezxml_txt(geom)) *
1073     to_meters(ezxml_attr(geom, "unit"));
1074     if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
1075     (mgfstr = ezxml_txt(geom)) == NULL)
1076     return;
1077     if ((fmt = ezxml_attr(geom, "format")) != NULL &&
1078     strcasecmp(fmt, "MGF")) {
1079     sprintf(errmsg, "unrecognized geometry format '%s'", fmt);
1080     error(WARNING, errmsg);
1081     return;
1082     }
1083     cfact = to_meters(ezxml_attr(geom, "unit"));
1084     dp->mgf = (char *)malloc(strlen(mgfstr)+32);
1085     if (dp->mgf == NULL)
1086     error(SYSTEM, "out of memory in load_geometry");
1087     if (cfact < 0.99 || cfact > 1.01)
1088     sprintf(dp->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
1089     else
1090     strcpy(dp->mgf, mgfstr);
1091     }
1092    
1093    
1094 greg 2.3 static void
1095 greg 2.1 load_bsdf_data( /* load BSDF distribution for this wavelength */
1096     struct BSDF_data *dp,
1097     ezxml_t wdb
1098     )
1099     {
1100     char *cbasis = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
1101     char *rbasis = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
1102     char *sdata;
1103     int i;
1104    
1105 greg 2.4 if ((!cbasis || !*cbasis) | (!rbasis || !*rbasis)) {
1106 greg 2.1 error(WARNING, "missing column/row basis for BSDF");
1107     return;
1108     }
1109     for (i = nabases; i--; )
1110 greg 2.12 if (!strcasecmp(cbasis, abase_list[i].name)) {
1111 greg 2.1 dp->ninc = abase_list[i].nangles;
1112     dp->ib_priv = (void *)&abase_list[i];
1113     dp->ib_vec = ab_getvecR;
1114     dp->ib_ndx = ab_getndxR;
1115     dp->ib_ohm = ab_getohm;
1116     break;
1117     }
1118     if (i < 0) {
1119 greg 2.4 sprintf(errmsg, "undefined ColumnAngleBasis '%s'", cbasis);
1120 greg 2.1 error(WARNING, errmsg);
1121     return;
1122     }
1123     for (i = nabases; i--; )
1124 greg 2.12 if (!strcasecmp(rbasis, abase_list[i].name)) {
1125 greg 2.1 dp->nout = abase_list[i].nangles;
1126     dp->ob_priv = (void *)&abase_list[i];
1127     dp->ob_vec = ab_getvec;
1128     dp->ob_ndx = ab_getndx;
1129     dp->ob_ohm = ab_getohm;
1130     break;
1131     }
1132     if (i < 0) {
1133 greg 2.16 sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1134 greg 2.1 error(WARNING, errmsg);
1135     return;
1136     }
1137     /* read BSDF data */
1138     sdata = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
1139 greg 2.4 if (!sdata || !*sdata) {
1140 greg 2.1 error(WARNING, "missing BSDF ScatteringData");
1141     return;
1142     }
1143     dp->bsdf = (float *)malloc(sizeof(float)*dp->ninc*dp->nout);
1144     if (dp->bsdf == NULL)
1145     error(SYSTEM, "out of memory in load_bsdf_data");
1146     for (i = 0; i < dp->ninc*dp->nout; i++) {
1147     char *sdnext = fskip(sdata);
1148     if (sdnext == NULL) {
1149     error(WARNING, "bad/missing BSDF ScatteringData");
1150     free(dp->bsdf); dp->bsdf = NULL;
1151     return;
1152     }
1153     while (*sdnext && isspace(*sdnext))
1154     sdnext++;
1155     if (*sdnext == ',') sdnext++;
1156     dp->bsdf[i] = atof(sdata);
1157     sdata = sdnext;
1158     }
1159     while (isspace(*sdata))
1160     sdata++;
1161     if (*sdata) {
1162     sprintf(errmsg, "%d extra characters after BSDF ScatteringData",
1163 greg 2.5 (int)strlen(sdata));
1164 greg 2.1 error(WARNING, errmsg);
1165     }
1166     }
1167    
1168    
1169     static int
1170     check_bsdf_data( /* check that BSDF data is sane */
1171     struct BSDF_data *dp
1172     )
1173     {
1174 greg 2.2 double *omega_iarr, *omega_oarr;
1175 greg 2.7 double dom, contrib, hemi_total, full_total;
1176 greg 2.1 int nneg;
1177 greg 2.2 FVECT v;
1178 greg 2.1 int i, o;
1179    
1180     if (dp == NULL || dp->bsdf == NULL)
1181     return(0);
1182 greg 2.2 omega_iarr = (double *)calloc(dp->ninc, sizeof(double));
1183     omega_oarr = (double *)calloc(dp->nout, sizeof(double));
1184     if ((omega_iarr == NULL) | (omega_oarr == NULL))
1185 greg 2.1 error(SYSTEM, "out of memory in check_bsdf_data");
1186 greg 2.2 /* incoming projected solid angles */
1187     hemi_total = .0;
1188     for (i = dp->ninc; i--; ) {
1189     dom = getBSDF_incohm(dp,i);
1190 greg 2.23 if (dom <= 0) {
1191 greg 2.2 error(WARNING, "zero/negative incoming solid angle");
1192     continue;
1193     }
1194     if (!getBSDF_incvec(v,dp,i) || v[2] > FTINY) {
1195     error(WARNING, "illegal incoming BSDF direction");
1196     free(omega_iarr); free(omega_oarr);
1197     return(0);
1198     }
1199     hemi_total += omega_iarr[i] = dom * -v[2];
1200     }
1201     if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1202     sprintf(errmsg, "incoming BSDF hemisphere off by %.1f%%",
1203     100.*(hemi_total/PI - 1.));
1204     error(WARNING, errmsg);
1205     }
1206     dom = PI / hemi_total; /* fix normalization */
1207     for (i = dp->ninc; i--; )
1208     omega_iarr[i] *= dom;
1209     /* outgoing projected solid angles */
1210 greg 2.1 hemi_total = .0;
1211     for (o = dp->nout; o--; ) {
1212     dom = getBSDF_outohm(dp,o);
1213 greg 2.23 if (dom <= 0) {
1214 greg 2.2 error(WARNING, "zero/negative outgoing solid angle");
1215 greg 2.1 continue;
1216     }
1217     if (!getBSDF_outvec(v,dp,o) || v[2] < -FTINY) {
1218     error(WARNING, "illegal outgoing BSDF direction");
1219 greg 2.2 free(omega_iarr); free(omega_oarr);
1220 greg 2.1 return(0);
1221     }
1222 greg 2.2 hemi_total += omega_oarr[o] = dom * v[2];
1223 greg 2.1 }
1224     if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1225     sprintf(errmsg, "outgoing BSDF hemisphere off by %.1f%%",
1226     100.*(hemi_total/PI - 1.));
1227     error(WARNING, errmsg);
1228     }
1229 greg 2.2 dom = PI / hemi_total; /* fix normalization */
1230 greg 2.1 for (o = dp->nout; o--; )
1231 greg 2.2 omega_oarr[o] *= dom;
1232     nneg = 0; /* check outgoing totals */
1233     for (i = 0; i < dp->ninc; i++) {
1234 greg 2.1 hemi_total = .0;
1235     for (o = dp->nout; o--; ) {
1236     double f = BSDF_value(dp,i,o);
1237 greg 2.23 if (f >= 0)
1238 greg 2.2 hemi_total += f*omega_oarr[o];
1239     else {
1240     nneg += (f < -FTINY);
1241     BSDF_value(dp,i,o) = .0f;
1242     }
1243 greg 2.1 }
1244 greg 2.8 if (hemi_total > 1.01) {
1245 greg 2.2 sprintf(errmsg,
1246     "incoming BSDF direction %d passes %.1f%% of light",
1247     i, 100.*hemi_total);
1248 greg 2.1 error(WARNING, errmsg);
1249     }
1250     }
1251 greg 2.2 if (nneg) {
1252     sprintf(errmsg, "%d negative BSDF values (ignored)", nneg);
1253 greg 2.1 error(WARNING, errmsg);
1254     }
1255 greg 2.7 full_total = .0; /* reverse roles and check again */
1256 greg 2.2 for (o = 0; o < dp->nout; o++) {
1257     hemi_total = .0;
1258     for (i = dp->ninc; i--; )
1259     hemi_total += BSDF_value(dp,i,o) * omega_iarr[i];
1260    
1261 greg 2.8 if (hemi_total > 1.01) {
1262 greg 2.2 sprintf(errmsg,
1263     "outgoing BSDF direction %d collects %.1f%% of light",
1264     o, 100.*hemi_total);
1265     error(WARNING, errmsg);
1266     }
1267 greg 2.7 full_total += hemi_total*omega_oarr[o];
1268     }
1269     full_total /= PI;
1270 greg 2.8 if (full_total > 1.00001) {
1271     sprintf(errmsg, "BSDF transfers %.4f%% of light",
1272 greg 2.7 100.*full_total);
1273     error(WARNING, errmsg);
1274 greg 2.2 }
1275     free(omega_iarr); free(omega_oarr);
1276 greg 2.1 return(1);
1277     }
1278    
1279 greg 2.6
1280 greg 2.1 struct BSDF_data *
1281     load_BSDF( /* load BSDF data from file */
1282     char *fname
1283     )
1284     {
1285     char *path;
1286     ezxml_t fl, wtl, wld, wdb;
1287     struct BSDF_data *dp;
1288    
1289     path = getpath(fname, getrlibpath(), R_OK);
1290     if (path == NULL) {
1291     sprintf(errmsg, "cannot find BSDF file \"%s\"", fname);
1292     error(WARNING, errmsg);
1293     return(NULL);
1294     }
1295     fl = ezxml_parse_file(path);
1296     if (fl == NULL) {
1297     sprintf(errmsg, "cannot open BSDF \"%s\"", path);
1298     error(WARNING, errmsg);
1299     return(NULL);
1300     }
1301     if (ezxml_error(fl)[0]) {
1302     sprintf(errmsg, "BSDF \"%s\" %s", path, ezxml_error(fl));
1303     error(WARNING, errmsg);
1304     ezxml_free(fl);
1305     return(NULL);
1306     }
1307     if (strcmp(ezxml_name(fl), "WindowElement")) {
1308     sprintf(errmsg,
1309     "BSDF \"%s\": top level node not 'WindowElement'",
1310     path);
1311     error(WARNING, errmsg);
1312     ezxml_free(fl);
1313     return(NULL);
1314     }
1315     wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
1316 greg 2.10 if (strcasecmp(ezxml_txt(ezxml_child(ezxml_child(wtl,
1317     "DataDefinition"), "IncidentDataStructure")),
1318     "Columns")) {
1319     sprintf(errmsg,
1320     "BSDF \"%s\": unsupported IncidentDataStructure",
1321     path);
1322     error(WARNING, errmsg);
1323     ezxml_free(fl);
1324     return(NULL);
1325     }
1326 greg 2.3 load_angle_basis(ezxml_child(ezxml_child(wtl,
1327     "DataDefinition"), "AngleBasis"));
1328 greg 2.1 dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
1329 greg 2.6 load_geometry(dp, ezxml_child(wtl, "Material"));
1330 greg 2.1 for (wld = ezxml_child(wtl, "WavelengthData");
1331     wld != NULL; wld = wld->next) {
1332 greg 2.13 if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1333     "Visible"))
1334 greg 2.1 continue;
1335 greg 2.13 for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1336     wdb != NULL; wdb = wdb->next)
1337     if (!strcasecmp(ezxml_txt(ezxml_child(wdb,
1338     "WavelengthDataDirection")),
1339 greg 2.1 "Transmission Front"))
1340 greg 2.13 break;
1341     if (wdb != NULL) { /* load front BTDF */
1342     load_bsdf_data(dp, wdb);
1343     break; /* ignore the rest */
1344     }
1345 greg 2.1 }
1346     ezxml_free(fl); /* done with XML file */
1347     if (!check_bsdf_data(dp)) {
1348     sprintf(errmsg, "bad/missing BTDF data in \"%s\"", path);
1349     error(WARNING, errmsg);
1350     free_BSDF(dp);
1351     dp = NULL;
1352     }
1353     return(dp);
1354     }
1355    
1356    
1357     void
1358     free_BSDF( /* free BSDF data structure */
1359     struct BSDF_data *b
1360     )
1361     {
1362     if (b == NULL)
1363     return;
1364 greg 2.6 if (b->mgf != NULL)
1365     free(b->mgf);
1366 greg 2.1 if (b->bsdf != NULL)
1367     free(b->bsdf);
1368     free(b);
1369     }
1370    
1371    
1372     int
1373     r_BSDF_incvec( /* compute random input vector at given location */
1374     FVECT v,
1375     struct BSDF_data *b,
1376     int i,
1377     double rv,
1378     MAT4 xm
1379     )
1380     {
1381     FVECT pert;
1382     double rad;
1383     int j;
1384    
1385     if (!getBSDF_incvec(v, b, i))
1386     return(0);
1387     rad = sqrt(getBSDF_incohm(b, i) / PI);
1388     multisamp(pert, 3, rv);
1389     for (j = 0; j < 3; j++)
1390     v[j] += rad*(2.*pert[j] - 1.);
1391     if (xm != NULL)
1392     multv3(v, v, xm);
1393     return(normalize(v) != 0.0);
1394     }
1395    
1396    
1397     int
1398     r_BSDF_outvec( /* compute random output vector at given location */
1399     FVECT v,
1400     struct BSDF_data *b,
1401     int o,
1402     double rv,
1403     MAT4 xm
1404     )
1405     {
1406     FVECT pert;
1407     double rad;
1408     int j;
1409    
1410     if (!getBSDF_outvec(v, b, o))
1411     return(0);
1412     rad = sqrt(getBSDF_outohm(b, o) / PI);
1413     multisamp(pert, 3, rv);
1414     for (j = 0; j < 3; j++)
1415     v[j] += rad*(2.*pert[j] - 1.);
1416     if (xm != NULL)
1417     multv3(v, v, xm);
1418     return(normalize(v) != 0.0);
1419     }
1420    
1421    
1422     static int
1423     addrot( /* compute rotation (x,y,z) => (xp,yp,zp) */
1424     char *xfarg[],
1425     FVECT xp,
1426     FVECT yp,
1427     FVECT zp
1428     )
1429     {
1430     static char bufs[3][16];
1431     int bn = 0;
1432     char **xfp = xfarg;
1433     double theta;
1434    
1435     if (yp[2]*yp[2] + zp[2]*zp[2] < 2.*FTINY*FTINY) {
1436     /* Special case for X' along Z-axis */
1437     theta = -atan2(yp[0], yp[1]);
1438     *xfp++ = "-ry";
1439     *xfp++ = xp[2] < 0.0 ? "90" : "-90";
1440     *xfp++ = "-rz";
1441     sprintf(bufs[bn], "%f", theta*(180./PI));
1442     *xfp++ = bufs[bn++];
1443     return(xfp - xfarg);
1444     }
1445     theta = atan2(yp[2], zp[2]);
1446     if (!FEQ(theta,0.0)) {
1447     *xfp++ = "-rx";
1448     sprintf(bufs[bn], "%f", theta*(180./PI));
1449     *xfp++ = bufs[bn++];
1450     }
1451     theta = asin(-xp[2]);
1452     if (!FEQ(theta,0.0)) {
1453     *xfp++ = "-ry";
1454     sprintf(bufs[bn], " %f", theta*(180./PI));
1455     *xfp++ = bufs[bn++];
1456     }
1457     theta = atan2(xp[1], xp[0]);
1458     if (!FEQ(theta,0.0)) {
1459     *xfp++ = "-rz";
1460     sprintf(bufs[bn], "%f", theta*(180./PI));
1461     *xfp++ = bufs[bn++];
1462     }
1463     *xfp = NULL;
1464     return(xfp - xfarg);
1465     }
1466    
1467    
1468     int
1469     getBSDF_xfm( /* compute BSDF orient. -> world orient. transform */
1470     MAT4 xm,
1471     FVECT nrm,
1472 greg 2.6 UpDir ud,
1473     char *xfbuf
1474 greg 2.1 )
1475     {
1476     char *xfargs[7];
1477     XF myxf;
1478     FVECT updir, xdest, ydest;
1479 greg 2.6 int i;
1480 greg 2.1
1481     updir[0] = updir[1] = updir[2] = 0.;
1482     switch (ud) {
1483     case UDzneg:
1484     updir[2] = -1.;
1485     break;
1486     case UDyneg:
1487     updir[1] = -1.;
1488     break;
1489     case UDxneg:
1490     updir[0] = -1.;
1491     break;
1492     case UDxpos:
1493     updir[0] = 1.;
1494     break;
1495     case UDypos:
1496     updir[1] = 1.;
1497     break;
1498     case UDzpos:
1499     updir[2] = 1.;
1500     break;
1501     case UDunknown:
1502     return(0);
1503     }
1504     fcross(xdest, updir, nrm);
1505     if (normalize(xdest) == 0.0)
1506     return(0);
1507     fcross(ydest, nrm, xdest);
1508     xf(&myxf, addrot(xfargs, xdest, ydest, nrm), xfargs);
1509     copymat4(xm, myxf.xfm);
1510 greg 2.6 if (xfbuf == NULL)
1511     return(1);
1512     /* return xf arguments as well */
1513     for (i = 0; xfargs[i] != NULL; i++) {
1514     *xfbuf++ = ' ';
1515     strcpy(xfbuf, xfargs[i]);
1516     while (*xfbuf) ++xfbuf;
1517     }
1518 greg 2.1 return(1);
1519     }
1520 greg 2.15
1521     /*######### END DEPRECATED ROUTINES #######*/
1522     /*################################################################*/