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.21 by greg, Sun Apr 17 17:45:13 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 vec, int qflags, const SDData *sd)
492 + {
493 +        SDSpectralDF    *rdf;
494 +        SDError         ec;
495 +        int             i;
496 +                                        /* check arguments */
497 +        if ((projSA == NULL) | (vec == NULL) | (sd == NULL))
498 +                return SDEargument;
499 +                                        /* initialize extrema */
500 +        switch (qflags) {
501 +        case SDqueryMax:
502 +                projSA[0] = .0;
503 +                break;
504 +        case SDqueryMin+SDqueryMax:
505 +                projSA[1] = .0;
506 +                /* fall through */
507 +        case SDqueryMin:
508 +                projSA[0] = 10.;
509 +                break;
510 +        case 0:
511 +                return SDEargument;
512 +        }
513 +        if (vec[2] > .0)                /* front surface query? */
514 +                rdf = sd->rf;
515 +        else
516 +                rdf = sd->rb;
517 +        ec = SDEdata;                   /* run through components */
518 +        for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
519 +                ec = (*rdf->comp[i].func->queryProjSA)(projSA, vec, qflags,
520 +                                                        rdf->comp[i].dist);
521 +                if (ec)
522 +                        return ec;
523 +        }
524 +        for (i = (sd->tf==NULL) ? 0 : sd->tf->ncomp; i--; ) {
525 +                ec = (*sd->tf->comp[i].func->queryProjSA)(projSA, vec, qflags,
526 +                                                        sd->tf->comp[i].dist);
527 +                if (ec)
528 +                        return ec;
529 +        }
530 +        if (ec) {                       /* all diffuse? */
531 +                projSA[0] = M_PI;
532 +                if (qflags == SDqueryMin+SDqueryMax)
533 +                        projSA[1] = M_PI;
534 +        }
535 +        return SDEnone;
536 + }
537 +
538 + /* Return BSDF for the given incident and scattered ray vectors */
539 + SDError
540 + SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
541 + {
542 +        int             inFront, outFront;
543 +        SDSpectralDF    *sdf;
544 +        float           coef[SDmaxCh];
545 +        int             nch, i;
546 +                                        /* check arguments */
547 +        if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
548 +                return SDEargument;
549 +                                        /* whose side are we on? */
550 +        inFront = (inVec[2] > .0);
551 +        outFront = (outVec[2] > .0);
552 +                                        /* start with diffuse portion */
553 +        if (inFront & outFront) {
554 +                *sv = sd->rLambFront;
555 +                sdf = sd->rf;
556 +        } else if (!(inFront | outFront)) {
557 +                *sv = sd->rLambBack;
558 +                sdf = sd->rb;
559 +        } else /* inFront ^ outFront */ {
560 +                *sv = sd->tLamb;
561 +                sdf = sd->tf;
562 +        }
563 +        sv->cieY *= 1./M_PI;
564 +                                        /* add non-diffuse components */
565 +        i = (sdf != NULL) ? sdf->ncomp : 0;
566 +        while (i-- > 0) {
567 +                nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
568 +                                                        sdf->comp[i].dist);
569 +                while (nch-- > 0) {
570 +                        c_cmix(&sv->spec, sv->cieY, &sv->spec,
571 +                                        coef[nch], &sdf->comp[i].cspec[nch]);
572 +                        sv->cieY += coef[nch];
573 +                }
574 +        }
575 +                                        /* make sure everything is set */
576 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
577 +        return SDEnone;
578 + }
579 +
580 + /* Compute directional hemispherical scattering at this incident angle */
581 + double
582 + SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
583 + {
584 +        double          hsum;
585 +        SDSpectralDF    *rdf;
586 +        const SDCDst    *cd;
587 +        int             i;
588 +                                        /* check arguments */
589 +        if ((inVec == NULL) | (sd == NULL))
590 +                return .0;
591 +                                        /* gather diffuse components */
592 +        if (inVec[2] > .0) {
593 +                hsum = sd->rLambFront.cieY;
594 +                rdf = sd->rf;
595 +        } else /* !inFront */ {
596 +                hsum = sd->rLambBack.cieY;
597 +                rdf = sd->rb;
598 +        }
599 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
600 +                hsum = .0;
601 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
602 +                hsum += sd->tLamb.cieY;
603 +                                        /* gather non-diffuse components */
604 +        i = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
605 +                        rdf != NULL) ? rdf->ncomp : 0;
606 +        while (i-- > 0) {               /* non-diffuse reflection */
607 +                cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
608 +                if (cd != NULL)
609 +                        hsum += cd->cTotal;
610 +        }
611 +        i = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
612 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
613 +        while (i-- > 0) {               /* non-diffuse transmission */
614 +                cd = (*sd->tf->comp[i].func->getCDist)(inVec, &sd->tf->comp[i]);
615 +                if (cd != NULL)
616 +                        hsum += cd->cTotal;
617 +        }
618 +        return hsum;
619 + }
620 +
621 + /* Sample BSDF direction based on the given random variable */
622 + SDError
623 + SDsampBSDF(SDValue *sv, FVECT outVec, const FVECT inVec,
624 +                        double randX, int sflags, const SDData *sd)
625 + {
626 +        SDError         ec;
627 +        int             inFront;
628 +        SDSpectralDF    *rdf;
629 +        double          rdiff;
630 +        float           coef[SDmaxCh];
631 +        int             i, j, n, nr;
632 +        SDComponent     *sdc;
633 +        const SDCDst    **cdarr = NULL;
634 +                                        /* check arguments */
635 +        if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL) |
636 +                        (randX < .0) | (randX >= 1.))
637 +                return SDEargument;
638 +                                        /* whose side are we on? */
639 +        inFront = (inVec[2] > .0);
640 +                                        /* remember diffuse portions */
641 +        if (inFront) {
642 +                *sv = sd->rLambFront;
643 +                rdf = sd->rf;
644 +        } else /* !inFront */ {
645 +                *sv = sd->rLambBack;
646 +                rdf = sd->rb;
647 +        }
648 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
649 +                sv->cieY = .0;
650 +        rdiff = sv->cieY;
651 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
652 +                sv->cieY += sd->tLamb.cieY;
653 +                                        /* gather non-diffuse components */
654 +        i = nr = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
655 +                        rdf != NULL) ? rdf->ncomp : 0;
656 +        j = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
657 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
658 +        n = i + j;
659 +        if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
660 +                return SDEmemory;
661 +        while (j-- > 0) {               /* non-diffuse transmission */
662 +                cdarr[i+j] = (*sd->tf->comp[j].func->getCDist)(inVec, &sd->tf->comp[j]);
663 +                if (cdarr[i+j] == NULL) {
664 +                        free(cdarr);
665 +                        return SDEmemory;
666 +                }
667 +                sv->cieY += cdarr[i+j]->cTotal;
668 +        }
669 +        while (i-- > 0) {               /* non-diffuse reflection */
670 +                cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
671 +                if (cdarr[i] == NULL) {
672 +                        free(cdarr);
673 +                        return SDEmemory;
674 +                }
675 +                sv->cieY += cdarr[i]->cTotal;
676 +        }
677 +        if (sv->cieY <= 1e-7) {         /* anything to sample? */
678 +                sv->cieY = .0;
679 +                memset(outVec, 0, 3*sizeof(double));
680 +                return SDEnone;
681 +        }
682 +                                        /* scale random variable */
683 +        randX *= sv->cieY;
684 +                                        /* diffuse reflection? */
685 +        if (randX < rdiff) {
686 +                SDdiffuseSamp(outVec, inFront, randX/rdiff);
687 +                goto done;
688 +        }
689 +        randX -= rdiff;
690 +                                        /* diffuse transmission? */
691 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
692 +                if (randX < sd->tLamb.cieY) {
693 +                        sv->spec = sd->tLamb.spec;
694 +                        SDdiffuseSamp(outVec, !inFront, randX/sd->tLamb.cieY);
695 +                        goto done;
696 +                }
697 +                randX -= sd->tLamb.cieY;
698 +        }
699 +                                        /* else one of cumulative dist. */
700 +        for (i = 0; i < n && randX < cdarr[i]->cTotal; i++)
701 +                randX -= cdarr[i]->cTotal;
702 +        if (i >= n)
703 +                return SDEinternal;
704 +                                        /* compute sample direction */
705 +        sdc = (i < nr) ? &rdf->comp[i] : &sd->tf->comp[i-nr];
706 +        ec = (*sdc->func->sampCDist)(outVec, randX/cdarr[i]->cTotal, cdarr[i]);
707 +        if (ec)
708 +                return ec;
709 +                                        /* compute color */
710 +        j = (*sdc->func->getBSDFs)(coef, outVec, inVec, sdc->dist);
711 +        if (j <= 0) {
712 +                sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
713 +                                sd->name);
714 +                return SDEinternal;
715 +        }
716 +        sv->spec = sdc->cspec[0];
717 +        rdiff = coef[0];
718 +        while (--j) {
719 +                c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
720 +                rdiff += coef[j];
721 +        }
722 + done:
723 +        if (cdarr != NULL)
724 +                free(cdarr);
725 +                                        /* make sure everything is set */
726 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
727 +        return SDEnone;
728 + }
729 +
730 + /* Compute World->BSDF transform from surface normal and up (Y) vector */
731 + SDError
732 + SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
733 + {
734 +        if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
735 +                return SDEargument;
736 +        VCOPY(vMtx[2], sNrm);
737 +        if (normalize(vMtx[2]) == .0)
738 +                return SDEargument;
739 +        fcross(vMtx[0], uVec, vMtx[2]);
740 +        if (normalize(vMtx[0]) == .0)
741 +                return SDEargument;
742 +        fcross(vMtx[1], vMtx[2], vMtx[0]);
743 +        return SDEnone;
744 + }
745 +
746 + /* Compute inverse transform */
747 + SDError
748 + SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
749 + {
750 +        RREAL   mTmp[3][3];
751 +        double  d;
752 +
753 +        if ((iMtx == NULL) | (vMtx == NULL))
754 +                return SDEargument;
755 +                                        /* compute determinant */
756 +        mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
757 +        mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
758 +        mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
759 +        d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
760 +        if (d == .0) {
761 +                strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
762 +                return SDEargument;
763 +        }
764 +        d = 1./d;                       /* invert matrix */
765 +        mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
766 +        mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
767 +        mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
768 +        mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
769 +        mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
770 +        mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
771 +        mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
772 +        memcpy(iMtx, mTmp, sizeof(mTmp));
773 +        return SDEnone;
774 + }
775 +
776 + /* Transform and normalize direction (column) vector */
777 + SDError
778 + SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
779 + {
780 +        FVECT   vTmp;
781 +
782 +        if ((resVec == NULL) | (inpVec == NULL))
783 +                return SDEargument;
784 +        if (vMtx == NULL) {             /* assume they just want to normalize */
785 +                if (resVec != inpVec)
786 +                        VCOPY(resVec, inpVec);
787 +                return (normalize(resVec) > .0) ? SDEnone : SDEargument;
788 +        }
789 +        vTmp[0] = DOT(vMtx[0], inpVec);
790 +        vTmp[1] = DOT(vMtx[1], inpVec);
791 +        vTmp[2] = DOT(vMtx[2], inpVec);
792 +        if (normalize(vTmp) == .0)
793 +                return SDEargument;
794 +        VCOPY(resVec, vTmp);
795 +        return SDEnone;
796 + }
797 +
798 + /*################################################################*/
799 + /*######### DEPRECATED ROUTINES AWAITING PERMANENT REMOVAL #######*/
800 +
801 + /*
802   * Routines for handling BSDF data
803   */
804  
805   #include "standard.h"
9 #include "bsdf.h"
806   #include "paths.h"
11 #include "ezxml.h"
807   #include <ctype.h>
808  
809   #define MAXLATS         46              /* maximum number of latitudes */
# Line 23 | Line 818 | typedef struct {
818          }       lat[MAXLATS+1];         /* latitudes */
819   } ANGLE_BASIS;
820  
821 < #define MAXABASES       3               /* limit on defined bases */
821 > #define MAXABASES       7               /* limit on defined bases */
822  
823   static ANGLE_BASIS      abase_list[MAXABASES] = {
824          {
# Line 61 | Line 856 | static ANGLE_BASIS     abase_list[MAXABASES] = {
856  
857   static int      nabases = 3;    /* current number of defined bases */
858  
859 + #define  FEQ(a,b)       ((a)-(b) <= 1e-6 && (b)-(a) <= 1e-6)
860  
861   static int
862 + fequal(double a, double b)
863 + {
864 +        if (b != .0)
865 +                a = a/b - 1.;
866 +        return((a <= 1e-6) & (a >= -1e-6));
867 + }
868 +
869 + /* Returns the name of the given tag */
870 + #ifdef ezxml_name
871 + #undef ezxml_name
872 + static char *
873 + ezxml_name(ezxml_t xml)
874 + {
875 +        if (xml == NULL)
876 +                return(NULL);
877 +        return(xml->name);
878 + }
879 + #endif
880 +
881 + /* Returns the given tag's character content or empty string if none */
882 + #ifdef ezxml_txt
883 + #undef ezxml_txt
884 + static char *
885 + ezxml_txt(ezxml_t xml)
886 + {
887 +        if (xml == NULL)
888 +                return("");
889 +        return(xml->txt);
890 + }
891 + #endif
892 +
893 +
894 + static int
895   ab_getvec(              /* get vector for this angle basis index */
896          FVECT v,
897          int ndx,
# Line 71 | Line 900 | ab_getvec(             /* get vector for this angle basis index *
900   {
901          ANGLE_BASIS  *ab = (ANGLE_BASIS *)p;
902          int     li;
903 <        double  alt, azi, d;
903 >        double  pol, azi, d;
904          
905          if ((ndx < 0) | (ndx >= ab->nangles))
906                  return(0);
907          for (li = 0; ndx >= ab->lat[li].nphis; li++)
908                  ndx -= ab->lat[li].nphis;
909 <        alt = PI/180.*0.5*(ab->lat[li].tmin + ab->lat[li+1].tmin);
909 >        pol = PI/180.*0.5*(ab->lat[li].tmin + ab->lat[li+1].tmin);
910          azi = 2.*PI*ndx/ab->lat[li].nphis;
911 <        v[2] = d = cos(alt);
912 <        d = sqrt(1. - d*d);     /* sin(alt) */
911 >        v[2] = d = cos(pol);
912 >        d = sqrt(1. - d*d);     /* sin(pol) */
913          v[0] = cos(azi)*d;
914          v[1] = sin(azi)*d;
915          return(1);
# Line 95 | Line 924 | ab_getndx(             /* get index corresponding to the given ve
924   {
925          ANGLE_BASIS  *ab = (ANGLE_BASIS *)p;
926          int     li, ndx;
927 <        double  alt, azi, d;
927 >        double  pol, azi, d;
928  
929          if ((v[2] < -1.0) | (v[2] > 1.0))
930                  return(-1);
931 <        alt = 180.0/PI*acos(v[2]);
931 >        pol = 180.0/PI*acos(v[2]);
932          azi = 180.0/PI*atan2(v[1], v[0]);
933          if (azi < 0.0) azi += 360.0;
934 <        for (li = 1; ab->lat[li].tmin <= alt; li++)
934 >        for (li = 1; ab->lat[li].tmin <= pol; li++)
935                  if (!ab->lat[li].nphis)
936                          return(-1);
937          --li;
# Line 174 | Line 1003 | ab_getndxR(            /* get index corresponding to the reverse
1003  
1004  
1005   static void
1006 + load_angle_basis(       /* load custom BSDF angle basis */
1007 +        ezxml_t wab
1008 + )
1009 + {
1010 +        char    *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
1011 +        ezxml_t wbb;
1012 +        int     i;
1013 +        
1014 +        if (!abname || !*abname)
1015 +                return;
1016 +        for (i = nabases; i--; )
1017 +                if (!strcasecmp(abname, abase_list[i].name))
1018 +                        return;         /* assume it's the same */
1019 +        if (nabases >= MAXABASES)
1020 +                error(INTERNAL, "too many angle bases");
1021 +        strcpy(abase_list[nabases].name, abname);
1022 +        abase_list[nabases].nangles = 0;
1023 +        for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
1024 +                        wbb != NULL; i++, wbb = wbb->next) {
1025 +                if (i >= MAXLATS)
1026 +                        error(INTERNAL, "too many latitudes in custom basis");
1027 +                abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
1028 +                                ezxml_child(ezxml_child(wbb,
1029 +                                        "ThetaBounds"), "UpperTheta")));
1030 +                if (!i)
1031 +                        abase_list[nabases].lat[i].tmin =
1032 +                                        -abase_list[nabases].lat[i+1].tmin;
1033 +                else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
1034 +                                        "ThetaBounds"), "LowerTheta"))),
1035 +                                abase_list[nabases].lat[i].tmin))
1036 +                        error(WARNING, "theta values disagree in custom basis");
1037 +                abase_list[nabases].nangles +=
1038 +                        abase_list[nabases].lat[i].nphis =
1039 +                                atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
1040 +        }
1041 +        abase_list[nabases++].lat[i].nphis = 0;
1042 + }
1043 +
1044 +
1045 + static void
1046 + load_geometry(          /* load geometric dimensions and description (if any) */
1047 +        struct BSDF_data *dp,
1048 +        ezxml_t wdb
1049 + )
1050 + {
1051 +        ezxml_t         geom;
1052 +        double          cfact;
1053 +        const char      *fmt, *mgfstr;
1054 +
1055 +        dp->dim[0] = dp->dim[1] = dp->dim[2] = 0;
1056 +        dp->mgf = NULL;
1057 +        if ((geom = ezxml_child(wdb, "Width")) != NULL)
1058 +                dp->dim[0] = atof(ezxml_txt(geom)) *
1059 +                                to_meters(ezxml_attr(geom, "unit"));
1060 +        if ((geom = ezxml_child(wdb, "Height")) != NULL)
1061 +                dp->dim[1] = atof(ezxml_txt(geom)) *
1062 +                                to_meters(ezxml_attr(geom, "unit"));
1063 +        if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
1064 +                dp->dim[2] = atof(ezxml_txt(geom)) *
1065 +                                to_meters(ezxml_attr(geom, "unit"));
1066 +        if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
1067 +                        (mgfstr = ezxml_txt(geom)) == NULL)
1068 +                return;
1069 +        if ((fmt = ezxml_attr(geom, "format")) != NULL &&
1070 +                        strcasecmp(fmt, "MGF")) {
1071 +                sprintf(errmsg, "unrecognized geometry format '%s'", fmt);
1072 +                error(WARNING, errmsg);
1073 +                return;
1074 +        }
1075 +        cfact = to_meters(ezxml_attr(geom, "unit"));
1076 +        dp->mgf = (char *)malloc(strlen(mgfstr)+32);
1077 +        if (dp->mgf == NULL)
1078 +                error(SYSTEM, "out of memory in load_geometry");
1079 +        if (cfact < 0.99 || cfact > 1.01)
1080 +                sprintf(dp->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
1081 +        else
1082 +                strcpy(dp->mgf, mgfstr);
1083 + }
1084 +
1085 +
1086 + static void
1087   load_bsdf_data(         /* load BSDF distribution for this wavelength */
1088          struct BSDF_data *dp,
1089          ezxml_t wdb
# Line 184 | Line 1094 | load_bsdf_data(                /* load BSDF distribution for this wa
1094          char  *sdata;
1095          int  i;
1096          
1097 <        if ((cbasis == NULL) | (rbasis == NULL)) {
1097 >        if ((!cbasis || !*cbasis) | (!rbasis || !*rbasis)) {
1098                  error(WARNING, "missing column/row basis for BSDF");
1099                  return;
1100          }
191        /* XXX need to add routines for loading in foreign bases */
1101          for (i = nabases; i--; )
1102 <                if (!strcmp(cbasis, abase_list[i].name)) {
1102 >                if (!strcasecmp(cbasis, abase_list[i].name)) {
1103                          dp->ninc = abase_list[i].nangles;
1104                          dp->ib_priv = (void *)&abase_list[i];
1105                          dp->ib_vec = ab_getvecR;
# Line 199 | Line 1108 | load_bsdf_data(                /* load BSDF distribution for this wa
1108                          break;
1109                  }
1110          if (i < 0) {
1111 <                sprintf(errmsg, "unsupported ColumnAngleBasis '%s'", cbasis);
1111 >                sprintf(errmsg, "undefined ColumnAngleBasis '%s'", cbasis);
1112                  error(WARNING, errmsg);
1113                  return;
1114          }
1115          for (i = nabases; i--; )
1116 <                if (!strcmp(rbasis, abase_list[i].name)) {
1116 >                if (!strcasecmp(rbasis, abase_list[i].name)) {
1117                          dp->nout = abase_list[i].nangles;
1118                          dp->ob_priv = (void *)&abase_list[i];
1119                          dp->ob_vec = ab_getvec;
# Line 213 | Line 1122 | load_bsdf_data(                /* load BSDF distribution for this wa
1122                          break;
1123                  }
1124          if (i < 0) {
1125 <                sprintf(errmsg, "unsupported RowAngleBasis '%s'", cbasis);
1125 >                sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1126                  error(WARNING, errmsg);
1127                  return;
1128          }
1129                                  /* read BSDF data */
1130          sdata  = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
1131 <        if (sdata == NULL) {
1131 >        if (!sdata || !*sdata) {
1132                  error(WARNING, "missing BSDF ScatteringData");
1133                  return;
1134          }
# Line 243 | Line 1152 | load_bsdf_data(                /* load BSDF distribution for this wa
1152                  sdata++;
1153          if (*sdata) {
1154                  sprintf(errmsg, "%d extra characters after BSDF ScatteringData",
1155 <                                strlen(sdata));
1155 >                                (int)strlen(sdata));
1156                  error(WARNING, errmsg);
1157          }
1158   }
# Line 254 | Line 1163 | check_bsdf_data(       /* check that BSDF data is sane */
1163          struct BSDF_data *dp
1164   )
1165   {
1166 <        double *        omega_arr;
1167 <        double          dom, hemi_total;
1166 >        double          *omega_iarr, *omega_oarr;
1167 >        double          dom, contrib, hemi_total, full_total;
1168          int             nneg;
1169 +        FVECT           v;
1170          int             i, o;
1171  
1172          if (dp == NULL || dp->bsdf == NULL)
1173                  return(0);
1174 <        omega_arr = (double *)calloc(dp->nout, sizeof(double));
1175 <        if (omega_arr == NULL)
1174 >        omega_iarr = (double *)calloc(dp->ninc, sizeof(double));
1175 >        omega_oarr = (double *)calloc(dp->nout, sizeof(double));
1176 >        if ((omega_iarr == NULL) | (omega_oarr == NULL))
1177                  error(SYSTEM, "out of memory in check_bsdf_data");
1178 +                                        /* incoming projected solid angles */
1179          hemi_total = .0;
1180 +        for (i = dp->ninc; i--; ) {
1181 +                dom = getBSDF_incohm(dp,i);
1182 +                if (dom <= .0) {
1183 +                        error(WARNING, "zero/negative incoming solid angle");
1184 +                        continue;
1185 +                }
1186 +                if (!getBSDF_incvec(v,dp,i) || v[2] > FTINY) {
1187 +                        error(WARNING, "illegal incoming BSDF direction");
1188 +                        free(omega_iarr); free(omega_oarr);
1189 +                        return(0);
1190 +                }
1191 +                hemi_total += omega_iarr[i] = dom * -v[2];
1192 +        }
1193 +        if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1194 +                sprintf(errmsg, "incoming BSDF hemisphere off by %.1f%%",
1195 +                                100.*(hemi_total/PI - 1.));
1196 +                error(WARNING, errmsg);
1197 +        }
1198 +        dom = PI / hemi_total;          /* fix normalization */
1199 +        for (i = dp->ninc; i--; )
1200 +                omega_iarr[i] *= dom;
1201 +                                        /* outgoing projected solid angles */
1202 +        hemi_total = .0;
1203          for (o = dp->nout; o--; ) {
269                FVECT   v;
1204                  dom = getBSDF_outohm(dp,o);
1205                  if (dom <= .0) {
1206 <                        error(WARNING, "zero/negative solid angle");
1206 >                        error(WARNING, "zero/negative outgoing solid angle");
1207                          continue;
1208                  }
1209                  if (!getBSDF_outvec(v,dp,o) || v[2] < -FTINY) {
1210                          error(WARNING, "illegal outgoing BSDF direction");
1211 <                        free(omega_arr);
1211 >                        free(omega_iarr); free(omega_oarr);
1212                          return(0);
1213                  }
1214 <                hemi_total += omega_arr[o] = dom*v[2];
1214 >                hemi_total += omega_oarr[o] = dom * v[2];
1215          }
1216          if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
1217                  sprintf(errmsg, "outgoing BSDF hemisphere off by %.1f%%",
1218                                  100.*(hemi_total/PI - 1.));
1219                  error(WARNING, errmsg);
1220          }
1221 <        dom = PI / hemi_total;          /* normalize solid angles */
1221 >        dom = PI / hemi_total;          /* fix normalization */
1222          for (o = dp->nout; o--; )
1223 <                omega_arr[o] *= dom;
1224 <        nneg = 0;
1225 <        for (i = dp->ninc; i--; ) {
1223 >                omega_oarr[o] *= dom;
1224 >        nneg = 0;                       /* check outgoing totals */
1225 >        for (i = 0; i < dp->ninc; i++) {
1226                  hemi_total = .0;
1227                  for (o = dp->nout; o--; ) {
1228                          double  f = BSDF_value(dp,i,o);
1229 <                        if (f > .0)
1230 <                                hemi_total += f*omega_arr[o];
1231 <                        else if (f < -FTINY)
1232 <                                ++nneg;
1229 >                        if (f >= .0)
1230 >                                hemi_total += f*omega_oarr[o];
1231 >                        else {
1232 >                                nneg += (f < -FTINY);
1233 >                                BSDF_value(dp,i,o) = .0f;
1234 >                        }
1235                  }
1236 <                if (hemi_total > 1.02) {
1237 <                        sprintf(errmsg, "BSDF direction passes %.1f%% of light",
1238 <                                        100.*hemi_total);
1236 >                if (hemi_total > 1.01) {
1237 >                        sprintf(errmsg,
1238 >                        "incoming BSDF direction %d passes %.1f%% of light",
1239 >                                        i, 100.*hemi_total);
1240                          error(WARNING, errmsg);
1241                  }
1242          }
1243 <        free(omega_arr);
1244 <        if (nneg > 0) {
308 <                sprintf(errmsg, "%d negative BSDF values", nneg);
1243 >        if (nneg) {
1244 >                sprintf(errmsg, "%d negative BSDF values (ignored)", nneg);
1245                  error(WARNING, errmsg);
310                return(0);
1246          }
1247 +        full_total = .0;                /* reverse roles and check again */
1248 +        for (o = 0; o < dp->nout; o++) {
1249 +                hemi_total = .0;
1250 +                for (i = dp->ninc; i--; )
1251 +                        hemi_total += BSDF_value(dp,i,o) * omega_iarr[i];
1252 +
1253 +                if (hemi_total > 1.01) {
1254 +                        sprintf(errmsg,
1255 +                        "outgoing BSDF direction %d collects %.1f%% of light",
1256 +                                        o, 100.*hemi_total);
1257 +                        error(WARNING, errmsg);
1258 +                }
1259 +                full_total += hemi_total*omega_oarr[o];
1260 +        }
1261 +        full_total /= PI;
1262 +        if (full_total > 1.00001) {
1263 +                sprintf(errmsg, "BSDF transfers %.4f%% of light",
1264 +                                100.*full_total);
1265 +                error(WARNING, errmsg);
1266 +        }
1267 +        free(omega_iarr); free(omega_oarr);
1268          return(1);
1269   }
1270  
1271 +
1272   struct BSDF_data *
1273   load_BSDF(              /* load BSDF data from file */
1274          char *fname
# Line 348 | Line 1305 | load_BSDF(             /* load BSDF data from file */
1305                  return(NULL);
1306          }
1307          wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
1308 +        if (strcasecmp(ezxml_txt(ezxml_child(ezxml_child(wtl,
1309 +                        "DataDefinition"), "IncidentDataStructure")),
1310 +                        "Columns")) {
1311 +                sprintf(errmsg,
1312 +                        "BSDF \"%s\": unsupported IncidentDataStructure",
1313 +                                path);
1314 +                error(WARNING, errmsg);
1315 +                ezxml_free(fl);
1316 +                return(NULL);
1317 +        }              
1318 +        load_angle_basis(ezxml_child(ezxml_child(wtl,
1319 +                                "DataDefinition"), "AngleBasis"));
1320          dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
1321 +        load_geometry(dp, ezxml_child(wtl, "Material"));
1322          for (wld = ezxml_child(wtl, "WavelengthData");
1323                                  wld != NULL; wld = wld->next) {
1324 <                if (strcmp(ezxml_txt(ezxml_child(wld,"Wavelength")), "Visible"))
1324 >                if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1325 >                                "Visible"))
1326                          continue;
1327 <                wdb = ezxml_child(wld, "WavelengthDataBlock");
1328 <                if (wdb == NULL) continue;
1329 <                if (strcmp(ezxml_txt(ezxml_child(wdb,"WavelengthDataDirection")),
1327 >                for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1328 >                                wdb != NULL; wdb = wdb->next)
1329 >                        if (!strcasecmp(ezxml_txt(ezxml_child(wdb,
1330 >                                        "WavelengthDataDirection")),
1331                                          "Transmission Front"))
1332 <                        continue;
1333 <                load_bsdf_data(dp, wdb);        /* load front BTDF */
1334 <                break;                          /* ignore the rest */
1332 >                                break;
1333 >                if (wdb != NULL) {              /* load front BTDF */
1334 >                        load_bsdf_data(dp, wdb);
1335 >                        break;                  /* ignore the rest */
1336 >                }
1337          }
1338          ezxml_free(fl);                         /* done with XML file */
1339          if (!check_bsdf_data(dp)) {
# Line 379 | Line 1353 | free_BSDF(             /* free BSDF data structure */
1353   {
1354          if (b == NULL)
1355                  return;
1356 +        if (b->mgf != NULL)
1357 +                free(b->mgf);
1358          if (b->bsdf != NULL)
1359                  free(b->bsdf);
1360          free(b);
# Line 435 | Line 1411 | r_BSDF_outvec(         /* compute random output vector at giv
1411   }
1412  
1413  
438 #define  FEQ(a,b)       ((a)-(b) <= 1e-7 && (b)-(a) <= 1e-7)
439
1414   static int
1415   addrot(                 /* compute rotation (x,y,z) => (xp,yp,zp) */
1416          char *xfarg[],
# Line 487 | Line 1461 | int
1461   getBSDF_xfm(            /* compute BSDF orient. -> world orient. transform */
1462          MAT4 xm,
1463          FVECT nrm,
1464 <        UpDir ud
1464 >        UpDir ud,
1465 >        char *xfbuf
1466   )
1467   {
1468          char    *xfargs[7];
1469          XF      myxf;
1470          FVECT   updir, xdest, ydest;
1471 +        int     i;
1472  
1473          updir[0] = updir[1] = updir[2] = 0.;
1474          switch (ud) {
# Line 523 | Line 1499 | getBSDF_xfm(           /* compute BSDF orient. -> world orient.
1499          fcross(ydest, nrm, xdest);
1500          xf(&myxf, addrot(xfargs, xdest, ydest, nrm), xfargs);
1501          copymat4(xm, myxf.xfm);
1502 +        if (xfbuf == NULL)
1503 +                return(1);
1504 +                                /* return xf arguments as well */
1505 +        for (i = 0; xfargs[i] != NULL; i++) {
1506 +                *xfbuf++ = ' ';
1507 +                strcpy(xfbuf, xfargs[i]);
1508 +                while (*xfbuf) ++xfbuf;
1509 +        }
1510          return(1);
1511   }
1512 +
1513 + /*######### END DEPRECATED ROUTINES #######*/
1514 + /*################################################################*/

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines