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.7 by greg, Tue Sep 7 23:10:50 2010 UTC vs.
Revision 2.26 by greg, Mon Apr 25 15:48:05 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 ioVec, double randX, SDComponent *sdc)
409 + {
410 +        float           coef[SDmaxCh];
411 +        SDError         ec;
412 +        FVECT           inVec;
413 +        const SDCDst    *cd;
414 +        double          d;
415 +        int             n;
416 +                                        /* check arguments */
417 +        if ((sv == NULL) | (ioVec == NULL) | (sdc == NULL))
418 +                return SDEargument;
419 +                                        /* get cumulative distribution */
420 +        VCOPY(inVec, ioVec);
421 +        cd = (*sdc->func->getCDist)(inVec, sdc);
422 +        if (cd == NULL)
423 +                return SDEmemory;
424 +        if (cd->cTotal <= 1e-7) {       /* anything to sample? */
425 +                sv->spec = c_dfcolor;
426 +                sv->cieY = .0;
427 +                memset(ioVec, 0, 3*sizeof(double));
428 +                return SDEnone;
429 +        }
430 +        sv->cieY = cd->cTotal;
431 +                                        /* compute sample direction */
432 +        ec = (*sdc->func->sampCDist)(ioVec, randX, cd);
433 +        if (ec)
434 +                return ec;
435 +                                        /* get BSDF color */
436 +        n = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
437 +        if (n <= 0) {
438 +                strcpy(SDerrorDetail, "BSDF sample value error");
439 +                return SDEinternal;
440 +        }
441 +        sv->spec = sdc->cspec[0];
442 +        d = coef[0];
443 +        while (--n) {
444 +                c_cmix(&sv->spec, d, &sv->spec, coef[n], &sdc->cspec[n]);
445 +                d += coef[n];
446 +        }
447 +                                        /* make sure everything is set */
448 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
449 +        return SDEnone;
450 + }
451 +
452 + #define MS_MAXDIM       15
453 +
454 + /* Convert 1-dimensional random variable to N-dimensional */
455 + void
456 + SDmultiSamp(double t[], int n, double randX)
457 + {
458 +        unsigned        nBits;
459 +        double          scale;
460 +        bitmask_t       ndx, coord[MS_MAXDIM];
461 +        
462 +        while (n > MS_MAXDIM)           /* punt for higher dimensions */
463 +                t[--n] = rand()*(1./(RAND_MAX+.5));
464 +        nBits = (8*sizeof(bitmask_t) - 1) / n;
465 +        ndx = randX * (double)((bitmask_t)1 << (nBits*n));
466 +                                        /* get coordinate on Hilbert curve */
467 +        hilbert_i2c(n, nBits, ndx, coord);
468 +                                        /* convert back to [0,1) range */
469 +        scale = 1. / (double)((bitmask_t)1 << nBits);
470 +        while (n--)
471 +                t[n] = scale * ((double)coord[n] + rand()*(1./(RAND_MAX+.5)));
472 + }
473 +
474 + #undef MS_MAXDIM
475 +
476 + /* Generate diffuse hemispherical sample */
477 + static void
478 + SDdiffuseSamp(FVECT outVec, int outFront, double randX)
479 + {
480 +                                        /* convert to position on hemisphere */
481 +        SDmultiSamp(outVec, 2, randX);
482 +        SDsquare2disk(outVec, outVec[0], outVec[1]);
483 +        outVec[2] = 1. - outVec[0]*outVec[0] - outVec[1]*outVec[1];
484 +        if (outVec[2] > 0)              /* a bit of paranoia */
485 +                outVec[2] = sqrt(outVec[2]);
486 +        if (!outFront)                  /* going out back? */
487 +                outVec[2] = -outVec[2];
488 + }
489 +
490 + /* Query projected solid angle coverage for non-diffuse BSDF direction */
491 + SDError
492 + SDsizeBSDF(double *projSA, const FVECT v1, const RREAL *v2,
493 +                                int qflags, const SDData *sd)
494 + {
495 +        SDSpectralDF    *rdf, *tdf;
496 +        SDError         ec;
497 +        int             i;
498 +                                        /* check arguments */
499 +        if ((projSA == NULL) | (v1 == NULL) | (sd == NULL))
500 +                return SDEargument;
501 +                                        /* initialize extrema */
502 +        switch (qflags) {
503 +        case SDqueryMax:
504 +                projSA[0] = .0;
505 +                break;
506 +        case SDqueryMin+SDqueryMax:
507 +                projSA[1] = .0;
508 +                /* fall through */
509 +        case SDqueryMin:
510 +                projSA[0] = 10.;
511 +                break;
512 +        case 0:
513 +                return SDEargument;
514 +        }
515 +        if (v1[2] > 0)                  /* front surface query? */
516 +                rdf = sd->rf;
517 +        else
518 +                rdf = sd->rb;
519 +        tdf = sd->tf;
520 +        if (v2 != NULL)                 /* bidirectional? */
521 +                if (v1[2] > 0 ^ v2[2] > 0)
522 +                        rdf = NULL;
523 +                else
524 +                        tdf = NULL;
525 +        ec = SDEdata;                   /* run through components */
526 +        for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
527 +                ec = (*rdf->comp[i].func->queryProjSA)(projSA, v1, v2,
528 +                                                qflags, &rdf->comp[i]);
529 +                if (ec)
530 +                        return ec;
531 +        }
532 +        for (i = (tdf==NULL) ? 0 : tdf->ncomp; i--; ) {
533 +                ec = (*tdf->comp[i].func->queryProjSA)(projSA, v1, v2,
534 +                                                qflags, &tdf->comp[i]);
535 +                if (ec)
536 +                        return ec;
537 +        }
538 +        if (ec) {                       /* all diffuse? */
539 +                projSA[0] = M_PI;
540 +                if (qflags == SDqueryMin+SDqueryMax)
541 +                        projSA[1] = M_PI;
542 +        }
543 +        return SDEnone;
544 + }
545 +
546 + /* Return BSDF for the given incident and scattered ray vectors */
547 + SDError
548 + SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
549 + {
550 +        int             inFront, outFront;
551 +        SDSpectralDF    *sdf;
552 +        float           coef[SDmaxCh];
553 +        int             nch, i;
554 +                                        /* check arguments */
555 +        if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
556 +                return SDEargument;
557 +                                        /* whose side are we on? */
558 +        inFront = (inVec[2] > 0);
559 +        outFront = (outVec[2] > 0);
560 +                                        /* start with diffuse portion */
561 +        if (inFront & outFront) {
562 +                *sv = sd->rLambFront;
563 +                sdf = sd->rf;
564 +        } else if (!(inFront | outFront)) {
565 +                *sv = sd->rLambBack;
566 +                sdf = sd->rb;
567 +        } else /* inFront ^ outFront */ {
568 +                *sv = sd->tLamb;
569 +                sdf = sd->tf;
570 +        }
571 +        sv->cieY *= 1./M_PI;
572 +                                        /* add non-diffuse components */
573 +        i = (sdf != NULL) ? sdf->ncomp : 0;
574 +        while (i-- > 0) {
575 +                nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
576 +                                                        &sdf->comp[i]);
577 +                while (nch-- > 0) {
578 +                        c_cmix(&sv->spec, sv->cieY, &sv->spec,
579 +                                        coef[nch], &sdf->comp[i].cspec[nch]);
580 +                        sv->cieY += coef[nch];
581 +                }
582 +        }
583 +                                        /* make sure everything is set */
584 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
585 +        return SDEnone;
586 + }
587 +
588 + /* Compute directional hemispherical scattering at this incident angle */
589 + double
590 + SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
591 + {
592 +        double          hsum;
593 +        SDSpectralDF    *rdf;
594 +        const SDCDst    *cd;
595 +        int             i;
596 +                                        /* check arguments */
597 +        if ((inVec == NULL) | (sd == NULL))
598 +                return .0;
599 +                                        /* gather diffuse components */
600 +        if (inVec[2] > 0) {
601 +                hsum = sd->rLambFront.cieY;
602 +                rdf = sd->rf;
603 +        } else /* !inFront */ {
604 +                hsum = sd->rLambBack.cieY;
605 +                rdf = sd->rb;
606 +        }
607 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
608 +                hsum = .0;
609 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
610 +                hsum += sd->tLamb.cieY;
611 +                                        /* gather non-diffuse components */
612 +        i = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
613 +                        rdf != NULL) ? rdf->ncomp : 0;
614 +        while (i-- > 0) {               /* non-diffuse reflection */
615 +                cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
616 +                if (cd != NULL)
617 +                        hsum += cd->cTotal;
618 +        }
619 +        i = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
620 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
621 +        while (i-- > 0) {               /* non-diffuse transmission */
622 +                cd = (*sd->tf->comp[i].func->getCDist)(inVec, &sd->tf->comp[i]);
623 +                if (cd != NULL)
624 +                        hsum += cd->cTotal;
625 +        }
626 +        return hsum;
627 + }
628 +
629 + /* Sample BSDF direction based on the given random variable */
630 + SDError
631 + SDsampBSDF(SDValue *sv, FVECT ioVec, double randX, int sflags, const SDData *sd)
632 + {
633 +        SDError         ec;
634 +        FVECT           inVec;
635 +        int             inFront;
636 +        SDSpectralDF    *rdf;
637 +        double          rdiff;
638 +        float           coef[SDmaxCh];
639 +        int             i, j, n, nr;
640 +        SDComponent     *sdc;
641 +        const SDCDst    **cdarr = NULL;
642 +                                        /* check arguments */
643 +        if ((sv == NULL) | (ioVec == NULL) | (sd == NULL) |
644 +                        (randX < 0) | (randX >= 1.))
645 +                return SDEargument;
646 +                                        /* whose side are we on? */
647 +        VCOPY(inVec, ioVec);
648 +        inFront = (inVec[2] > 0);
649 +                                        /* remember diffuse portions */
650 +        if (inFront) {
651 +                *sv = sd->rLambFront;
652 +                rdf = sd->rf;
653 +        } else /* !inFront */ {
654 +                *sv = sd->rLambBack;
655 +                rdf = sd->rb;
656 +        }
657 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
658 +                sv->cieY = .0;
659 +        rdiff = sv->cieY;
660 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
661 +                sv->cieY += sd->tLamb.cieY;
662 +                                        /* gather non-diffuse components */
663 +        i = nr = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
664 +                        rdf != NULL) ? rdf->ncomp : 0;
665 +        j = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
666 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
667 +        n = i + j;
668 +        if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
669 +                return SDEmemory;
670 +        while (j-- > 0) {               /* non-diffuse transmission */
671 +                cdarr[i+j] = (*sd->tf->comp[j].func->getCDist)(inVec, &sd->tf->comp[j]);
672 +                if (cdarr[i+j] == NULL) {
673 +                        free(cdarr);
674 +                        return SDEmemory;
675 +                }
676 +                sv->cieY += cdarr[i+j]->cTotal;
677 +        }
678 +        while (i-- > 0) {               /* non-diffuse reflection */
679 +                cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
680 +                if (cdarr[i] == NULL) {
681 +                        free(cdarr);
682 +                        return SDEmemory;
683 +                }
684 +                sv->cieY += cdarr[i]->cTotal;
685 +        }
686 +        if (sv->cieY <= 1e-7) {         /* anything to sample? */
687 +                sv->cieY = .0;
688 +                memset(ioVec, 0, 3*sizeof(double));
689 +                return SDEnone;
690 +        }
691 +                                        /* scale random variable */
692 +        randX *= sv->cieY;
693 +                                        /* diffuse reflection? */
694 +        if (randX < rdiff) {
695 +                SDdiffuseSamp(ioVec, inFront, randX/rdiff);
696 +                goto done;
697 +        }
698 +        randX -= rdiff;
699 +                                        /* diffuse transmission? */
700 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
701 +                if (randX < sd->tLamb.cieY) {
702 +                        sv->spec = sd->tLamb.spec;
703 +                        SDdiffuseSamp(ioVec, !inFront, randX/sd->tLamb.cieY);
704 +                        goto done;
705 +                }
706 +                randX -= sd->tLamb.cieY;
707 +        }
708 +                                        /* else one of cumulative dist. */
709 +        for (i = 0; i < n && randX < cdarr[i]->cTotal; i++)
710 +                randX -= cdarr[i]->cTotal;
711 +        if (i >= n)
712 +                return SDEinternal;
713 +                                        /* compute sample direction */
714 +        sdc = (i < nr) ? &rdf->comp[i] : &sd->tf->comp[i-nr];
715 +        ec = (*sdc->func->sampCDist)(ioVec, randX/cdarr[i]->cTotal, cdarr[i]);
716 +        if (ec)
717 +                return ec;
718 +                                        /* compute color */
719 +        j = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
720 +        if (j <= 0) {
721 +                sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
722 +                                sd->name);
723 +                return SDEinternal;
724 +        }
725 +        sv->spec = sdc->cspec[0];
726 +        rdiff = coef[0];
727 +        while (--j) {
728 +                c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
729 +                rdiff += coef[j];
730 +        }
731 + done:
732 +        if (cdarr != NULL)
733 +                free(cdarr);
734 +                                        /* make sure everything is set */
735 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
736 +        return SDEnone;
737 + }
738 +
739 + /* Compute World->BSDF transform from surface normal and up (Y) vector */
740 + SDError
741 + SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
742 + {
743 +        if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
744 +                return SDEargument;
745 +        VCOPY(vMtx[2], sNrm);
746 +        if (normalize(vMtx[2]) == 0)
747 +                return SDEargument;
748 +        fcross(vMtx[0], uVec, vMtx[2]);
749 +        if (normalize(vMtx[0]) == 0)
750 +                return SDEargument;
751 +        fcross(vMtx[1], vMtx[2], vMtx[0]);
752 +        return SDEnone;
753 + }
754 +
755 + /* Compute inverse transform */
756 + SDError
757 + SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
758 + {
759 +        RREAL   mTmp[3][3];
760 +        double  d;
761 +
762 +        if ((iMtx == NULL) | (vMtx == NULL))
763 +                return SDEargument;
764 +                                        /* compute determinant */
765 +        mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
766 +        mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
767 +        mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
768 +        d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
769 +        if (d == 0) {
770 +                strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
771 +                return SDEargument;
772 +        }
773 +        d = 1./d;                       /* invert matrix */
774 +        mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
775 +        mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
776 +        mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
777 +        mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
778 +        mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
779 +        mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
780 +        mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
781 +        memcpy(iMtx, mTmp, sizeof(mTmp));
782 +        return SDEnone;
783 + }
784 +
785 + /* Transform and normalize direction (column) vector */
786 + SDError
787 + SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
788 + {
789 +        FVECT   vTmp;
790 +
791 +        if ((resVec == NULL) | (inpVec == NULL))
792 +                return SDEargument;
793 +        if (vMtx == NULL) {             /* assume they just want to normalize */
794 +                if (resVec != inpVec)
795 +                        VCOPY(resVec, inpVec);
796 +                return (normalize(resVec) > 0) ? SDEnone : SDEargument;
797 +        }
798 +        vTmp[0] = DOT(vMtx[0], inpVec);
799 +        vTmp[1] = DOT(vMtx[1], inpVec);
800 +        vTmp[2] = DOT(vMtx[2], inpVec);
801 +        if (normalize(vTmp) == 0)
802 +                return SDEargument;
803 +        VCOPY(resVec, vTmp);
804 +        return SDEnone;
805 + }
806 +
807 + /*################################################################*/
808 + /*######### DEPRECATED ROUTINES AWAITING PERMANENT REMOVAL #######*/
809 +
810 + /*
811   * Routines for handling BSDF data
812   */
813  
814   #include "standard.h"
9 #include "bsdf.h"
815   #include "paths.h"
11 #include "ezxml.h"
816   #include <ctype.h>
817  
818   #define MAXLATS         46              /* maximum number of latitudes */
# Line 61 | Line 865 | static ANGLE_BASIS     abase_list[MAXABASES] = {
865  
866   static int      nabases = 3;    /* current number of defined bases */
867  
868 < #define  FEQ(a,b)       ((a)-(b) <= 1e-7 && (b)-(a) <= 1e-7)
868 > #define  FEQ(a,b)       ((a)-(b) <= 1e-6 && (b)-(a) <= 1e-6)
869  
870 < // returns the name of the given tag
870 > static int
871 > fequal(double a, double b)
872 > {
873 >        if (b != 0)
874 >                a = a/b - 1.;
875 >        return((a <= 1e-6) & (a >= -1e-6));
876 > }
877 >
878 > /* Returns the name of the given tag */
879   #ifdef ezxml_name
880   #undef ezxml_name
881   static char *
# Line 75 | Line 887 | ezxml_name(ezxml_t xml)
887   }
888   #endif
889  
890 < // returns the given tag's character content or empty string if none
890 > /* Returns the given tag's character content or empty string if none */
891   #ifdef ezxml_txt
892   #undef ezxml_txt
893   static char *
# Line 211 | Line 1023 | load_angle_basis(      /* load custom BSDF angle basis */
1023          if (!abname || !*abname)
1024                  return;
1025          for (i = nabases; i--; )
1026 <                if (!strcmp(abname, abase_list[i].name))
1026 >                if (!strcasecmp(abname, abase_list[i].name))
1027                          return;         /* assume it's the same */
1028          if (nabases >= MAXABASES)
1029                  error(INTERNAL, "too many angle bases");
# Line 227 | Line 1039 | load_angle_basis(      /* load custom BSDF angle basis */
1039                  if (!i)
1040                          abase_list[nabases].lat[i].tmin =
1041                                          -abase_list[nabases].lat[i+1].tmin;
1042 <                else if (!FEQ(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
1042 >                else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
1043                                          "ThetaBounds"), "LowerTheta"))),
1044                                  abase_list[nabases].lat[i].tmin))
1045                          error(WARNING, "theta values disagree in custom basis");
# Line 239 | Line 1051 | load_angle_basis(      /* load custom BSDF angle basis */
1051   }
1052  
1053  
242 static double
243 to_meters(              /* return factor to convert given unit to meters */
244        const char *unit
245 )
246 {
247        if (unit == NULL) return(1.);           /* safe assumption? */
248        if (!strcasecmp(unit, "Meter")) return(1.);
249        if (!strcasecmp(unit, "Foot")) return(.3048);
250        if (!strcasecmp(unit, "Inch")) return(.0254);
251        if (!strcasecmp(unit, "Centimeter")) return(.01);
252        sprintf(errmsg, "unknown dimensional unit '%s'", unit);
253        error(USER, errmsg);
254 }
255
256
1054   static void
1055   load_geometry(          /* load geometric dimensions and description (if any) */
1056          struct BSDF_data *dp,
# Line 311 | Line 1108 | load_bsdf_data(                /* load BSDF distribution for this wa
1108                  return;
1109          }
1110          for (i = nabases; i--; )
1111 <                if (!strcmp(cbasis, abase_list[i].name)) {
1111 >                if (!strcasecmp(cbasis, abase_list[i].name)) {
1112                          dp->ninc = abase_list[i].nangles;
1113                          dp->ib_priv = (void *)&abase_list[i];
1114                          dp->ib_vec = ab_getvecR;
# Line 325 | Line 1122 | load_bsdf_data(                /* load BSDF distribution for this wa
1122                  return;
1123          }
1124          for (i = nabases; i--; )
1125 <                if (!strcmp(rbasis, abase_list[i].name)) {
1125 >                if (!strcasecmp(rbasis, abase_list[i].name)) {
1126                          dp->nout = abase_list[i].nangles;
1127                          dp->ob_priv = (void *)&abase_list[i];
1128                          dp->ob_vec = ab_getvec;
# Line 334 | Line 1131 | load_bsdf_data(                /* load BSDF distribution for this wa
1131                          break;
1132                  }
1133          if (i < 0) {
1134 <                sprintf(errmsg, "undefined RowAngleBasis '%s'", cbasis);
1134 >                sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1135                  error(WARNING, errmsg);
1136                  return;
1137          }
# Line 391 | Line 1188 | check_bsdf_data(       /* check that BSDF data is sane */
1188          hemi_total = .0;
1189          for (i = dp->ninc; i--; ) {
1190                  dom = getBSDF_incohm(dp,i);
1191 <                if (dom <= .0) {
1191 >                if (dom <= 0) {
1192                          error(WARNING, "zero/negative incoming solid angle");
1193                          continue;
1194                  }
# Line 414 | Line 1211 | check_bsdf_data(       /* check that BSDF data is sane */
1211          hemi_total = .0;
1212          for (o = dp->nout; o--; ) {
1213                  dom = getBSDF_outohm(dp,o);
1214 <                if (dom <= .0) {
1214 >                if (dom <= 0) {
1215                          error(WARNING, "zero/negative outgoing solid angle");
1216                          continue;
1217                  }
# Line 438 | Line 1235 | check_bsdf_data(       /* check that BSDF data is sane */
1235                  hemi_total = .0;
1236                  for (o = dp->nout; o--; ) {
1237                          double  f = BSDF_value(dp,i,o);
1238 <                        if (f >= .0)
1238 >                        if (f >= 0)
1239                                  hemi_total += f*omega_oarr[o];
1240                          else {
1241                                  nneg += (f < -FTINY);
1242                                  BSDF_value(dp,i,o) = .0f;
1243                          }
1244                  }
1245 <                if (hemi_total > 1.02) {
1245 >                if (hemi_total > 1.01) {
1246                          sprintf(errmsg,
1247                          "incoming BSDF direction %d passes %.1f%% of light",
1248                                          i, 100.*hemi_total);
# Line 462 | Line 1259 | check_bsdf_data(       /* check that BSDF data is sane */
1259                  for (i = dp->ninc; i--; )
1260                          hemi_total += BSDF_value(dp,i,o) * omega_iarr[i];
1261  
1262 <                if (hemi_total > 1.02) {
1262 >                if (hemi_total > 1.01) {
1263                          sprintf(errmsg,
1264                          "outgoing BSDF direction %d collects %.1f%% of light",
1265                                          o, 100.*hemi_total);
# Line 471 | Line 1268 | check_bsdf_data(       /* check that BSDF data is sane */
1268                  full_total += hemi_total*omega_oarr[o];
1269          }
1270          full_total /= PI;
1271 <        if (full_total > 1.02) {
1272 <                sprintf(errmsg, "BSDF transfers %.1f%% of light",
1271 >        if (full_total > 1.00001) {
1272 >                sprintf(errmsg, "BSDF transfers %.4f%% of light",
1273                                  100.*full_total);
1274                  error(WARNING, errmsg);
1275          }
# Line 517 | Line 1314 | load_BSDF(             /* load BSDF data from file */
1314                  return(NULL);
1315          }
1316          wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
1317 +        if (strcasecmp(ezxml_txt(ezxml_child(ezxml_child(wtl,
1318 +                        "DataDefinition"), "IncidentDataStructure")),
1319 +                        "Columns")) {
1320 +                sprintf(errmsg,
1321 +                        "BSDF \"%s\": unsupported IncidentDataStructure",
1322 +                                path);
1323 +                error(WARNING, errmsg);
1324 +                ezxml_free(fl);
1325 +                return(NULL);
1326 +        }              
1327          load_angle_basis(ezxml_child(ezxml_child(wtl,
1328                                  "DataDefinition"), "AngleBasis"));
1329          dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
1330          load_geometry(dp, ezxml_child(wtl, "Material"));
1331          for (wld = ezxml_child(wtl, "WavelengthData");
1332                                  wld != NULL; wld = wld->next) {
1333 <                if (strcmp(ezxml_txt(ezxml_child(wld,"Wavelength")), "Visible"))
1333 >                if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1334 >                                "Visible"))
1335                          continue;
1336 <                wdb = ezxml_child(wld, "WavelengthDataBlock");
1337 <                if (wdb == NULL) continue;
1338 <                if (strcmp(ezxml_txt(ezxml_child(wdb,"WavelengthDataDirection")),
1336 >                for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1337 >                                wdb != NULL; wdb = wdb->next)
1338 >                        if (!strcasecmp(ezxml_txt(ezxml_child(wdb,
1339 >                                        "WavelengthDataDirection")),
1340                                          "Transmission Front"))
1341 <                        continue;
1342 <                load_bsdf_data(dp, wdb);        /* load front BTDF */
1343 <                break;                          /* ignore the rest */
1341 >                                break;
1342 >                if (wdb != NULL) {              /* load front BTDF */
1343 >                        load_bsdf_data(dp, wdb);
1344 >                        break;                  /* ignore the rest */
1345 >                }
1346          }
1347          ezxml_free(fl);                         /* done with XML file */
1348          if (!check_bsdf_data(dp)) {
# Line 707 | Line 1518 | getBSDF_xfm(           /* compute BSDF orient. -> world orient.
1518          }
1519          return(1);
1520   }
1521 +
1522 + /*######### END DEPRECATED ROUTINES #######*/
1523 + /*################################################################*/

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines