ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf.c
Revision: 2.40
Committed: Mon Mar 5 15:27:08 2012 UTC (12 years, 2 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.39: +5 -3 lines
Log Message:
Tweak on last change to recording name & manufacturer

File Contents

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