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

Comparing ray/src/common/bsdf.c (file contents):
Revision 2.1 by greg, Wed Jun 17 20:41:47 2009 UTC vs.
Revision 2.22 by greg, Tue Apr 19 21:31:22 2011 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines