ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf.c
Revision: 2.42
Committed: Sun Sep 2 15:33:15 2012 UTC (11 years, 8 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.41: +39 -19 lines
Log Message:
Fixes to reciprocity for tensor tree representation

File Contents

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