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.9 by greg, Mon Jan 3 19:27:00 2011 UTC vs.
Revision 2.31 by greg, Fri Jun 10 01:11:26 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 + #define _USE_MATH_DEFINES
14 + #include <stdio.h>
15 + #include <stdlib.h>
16 + #include <string.h>
17 + #include <math.h>
18 + #include "ezxml.h"
19 + #include "hilbert.h"
20 + #include "bsdf.h"
21 + #include "bsdf_m.h"
22 + #include "bsdf_t.h"
23 +
24 + /* English ASCII strings corresponding to ennumerated errors */
25 + const char              *SDerrorEnglish[] = {
26 +                                "No error",
27 +                                "Memory error",
28 +                                "File input/output error",
29 +                                "File format error",
30 +                                "Illegal argument",
31 +                                "Invalid data",
32 +                                "Unsupported feature",
33 +                                "Internal program error",
34 +                                "Unknown error"
35 +                        };
36 +
37 + /* Additional information on last error (ASCII English) */
38 + char                    SDerrorDetail[256];
39 +
40 + /* Cache of loaded BSDFs */
41 + struct SDCache_s        *SDcacheList = NULL;
42 +
43 + /* Retain BSDFs in cache list */
44 + int                     SDretainSet = SDretainNone;
45 +
46 + /* Report any error to the indicated stream (in English) */
47 + SDError
48 + SDreportEnglish(SDError ec, FILE *fp)
49 + {
50 +        if (!ec)
51 +                return SDEnone;
52 +        if ((ec < SDEnone) | (ec > SDEunknown)) {
53 +                SDerrorDetail[0] = '\0';
54 +                ec = SDEunknown;
55 +        }
56 +        if (fp == NULL)
57 +                return ec;
58 +        fputs(SDerrorEnglish[ec], fp);
59 +        if (SDerrorDetail[0]) {
60 +                fputs(": ", fp);
61 +                fputs(SDerrorDetail, fp);
62 +        }
63 +        fputc('\n', fp);
64 +        if (fp != stderr)
65 +                fflush(fp);
66 +        return ec;
67 + }
68 +
69 + static double
70 + to_meters(              /* return factor to convert given unit to meters */
71 +        const char *unit
72 + )
73 + {
74 +        if (unit == NULL) return(1.);           /* safe assumption? */
75 +        if (!strcasecmp(unit, "Meter")) return(1.);
76 +        if (!strcasecmp(unit, "Foot")) return(.3048);
77 +        if (!strcasecmp(unit, "Inch")) return(.0254);
78 +        if (!strcasecmp(unit, "Centimeter")) return(.01);
79 +        if (!strcasecmp(unit, "Millimeter")) return(.001);
80 +        sprintf(SDerrorDetail, "Unknown dimensional unit '%s'", unit);
81 +        return(-1.);
82 + }
83 +
84 + /* Load geometric dimensions and description (if any) */
85 + static SDError
86 + SDloadGeometry(SDData *sd, ezxml_t wdb)
87 + {
88 +        ezxml_t         geom;
89 +        double          cfact;
90 +        const char      *fmt, *mgfstr;
91 +
92 +        if (wdb == NULL)                /* no geometry section? */
93 +                return SDEnone;
94 +        sd->dim[0] = sd->dim[1] = sd->dim[2] = .0;
95 +        if ((geom = ezxml_child(wdb, "Width")) != NULL)
96 +                sd->dim[0] = atof(ezxml_txt(geom)) *
97 +                                to_meters(ezxml_attr(geom, "unit"));
98 +        if ((geom = ezxml_child(wdb, "Height")) != NULL)
99 +                sd->dim[1] = atof(ezxml_txt(geom)) *
100 +                                to_meters(ezxml_attr(geom, "unit"));
101 +        if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
102 +                sd->dim[2] = atof(ezxml_txt(geom)) *
103 +                                to_meters(ezxml_attr(geom, "unit"));
104 +        if ((sd->dim[0] < 0) | (sd->dim[1] < 0) | (sd->dim[2] < 0)) {
105 +                sprintf(SDerrorDetail, "Negative size in \"%s\"", sd->name);
106 +                return SDEdata;
107 +        }
108 +        if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
109 +                        (mgfstr = ezxml_txt(geom)) == NULL)
110 +                return SDEnone;
111 +        if ((fmt = ezxml_attr(geom, "format")) != NULL &&
112 +                        strcasecmp(fmt, "MGF")) {
113 +                sprintf(SDerrorDetail,
114 +                        "Unrecognized geometry format '%s' in \"%s\"",
115 +                                        fmt, sd->name);
116 +                return SDEsupport;
117 +        }
118 +        cfact = to_meters(ezxml_attr(geom, "unit"));
119 +        sd->mgf = (char *)malloc(strlen(mgfstr)+32);
120 +        if (sd->mgf == NULL) {
121 +                strcpy(SDerrorDetail, "Out of memory in SDloadGeometry");
122 +                return SDEmemory;
123 +        }
124 +        if (cfact < 0.99 || cfact > 1.01)
125 +                sprintf(sd->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
126 +        else
127 +                strcpy(sd->mgf, mgfstr);
128 +        return SDEnone;
129 + }
130 +
131 + /* Load a BSDF struct from the given file (free first and keep name) */
132 + SDError
133 + SDloadFile(SDData *sd, const char *fname)
134 + {
135 +        SDError         lastErr;
136 +        ezxml_t         fl, wtl;
137 +
138 +        if ((sd == NULL) | (fname == NULL || !*fname))
139 +                return SDEargument;
140 +                                /* free old data, keeping name */
141 +        SDfreeBSDF(sd);
142 +                                /* parse XML file */
143 +        fl = ezxml_parse_file(fname);
144 +        if (fl == NULL) {
145 +                sprintf(SDerrorDetail, "Cannot open BSDF \"%s\"", fname);
146 +                return SDEfile;
147 +        }
148 +        if (ezxml_error(fl)[0]) {
149 +                sprintf(SDerrorDetail, "BSDF \"%s\" %s", fname, ezxml_error(fl));
150 +                ezxml_free(fl);
151 +                return SDEformat;
152 +        }
153 +        if (strcmp(ezxml_name(fl), "WindowElement")) {
154 +                sprintf(SDerrorDetail,
155 +                        "BSDF \"%s\": top level node not 'WindowElement'",
156 +                                sd->name);
157 +                ezxml_free(fl);
158 +                return SDEformat;
159 +        }
160 +        wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
161 +        if (wtl == NULL) {
162 +                sprintf(SDerrorDetail, "BSDF \"%s\": no optical layer'",
163 +                                sd->name);
164 +                ezxml_free(fl);
165 +                return SDEformat;
166 +        }
167 +                                /* load geometry if present */
168 +        lastErr = SDloadGeometry(sd, ezxml_child(wtl, "Material"));
169 +        if (lastErr)
170 +                return lastErr;
171 +                                /* try loading variable resolution data */
172 +        lastErr = SDloadTre(sd, wtl);
173 +                                /* check our result */
174 +        if (lastErr == SDEsupport)      /* try matrix BSDF if not tree data */
175 +                lastErr = SDloadMtx(sd, wtl);
176 +                
177 +                                /* done with XML file */
178 +        ezxml_free(fl);
179 +        
180 +        if (lastErr) {          /* was there a load error? */
181 +                SDfreeBSDF(sd);
182 +                return lastErr;
183 +        }
184 +                                /* remove any insignificant components */
185 +        if (sd->rf != NULL && sd->rf->maxHemi <= .001) {
186 +                SDfreeSpectralDF(sd->rf); sd->rf = NULL;
187 +        }
188 +        if (sd->rb != NULL && sd->rb->maxHemi <= .001) {
189 +                SDfreeSpectralDF(sd->rb); sd->rb = NULL;
190 +        }
191 +        if (sd->tf != NULL && sd->tf->maxHemi <= .001) {
192 +                SDfreeSpectralDF(sd->tf); sd->tf = NULL;
193 +        }
194 +                                /* return success */
195 +        return SDEnone;
196 + }
197 +
198 + /* Allocate new spectral distribution function */
199 + SDSpectralDF *
200 + SDnewSpectralDF(int nc)
201 + {
202 +        SDSpectralDF    *df;
203 +        
204 +        if (nc <= 0) {
205 +                strcpy(SDerrorDetail, "Zero component spectral DF request");
206 +                return NULL;
207 +        }
208 +        df = (SDSpectralDF *)malloc(sizeof(SDSpectralDF) +
209 +                                        (nc-1)*sizeof(SDComponent));
210 +        if (df == NULL) {
211 +                sprintf(SDerrorDetail,
212 +                                "Cannot allocate %d component spectral DF", nc);
213 +                return NULL;
214 +        }
215 +        df->minProjSA = .0;
216 +        df->maxHemi = .0;
217 +        df->ncomp = nc;
218 +        memset(df->comp, 0, nc*sizeof(SDComponent));
219 +        return df;
220 + }
221 +
222 + /* Free cached cumulative distributions for BSDF component */
223 + void
224 + SDfreeCumulativeCache(SDSpectralDF *df)
225 + {
226 +        int     n;
227 +        SDCDst  *cdp;
228 +
229 +        if (df == NULL)
230 +                return;
231 +        for (n = df->ncomp; n-- > 0; )
232 +                while ((cdp = df->comp[n].cdList) != NULL) {
233 +                        df->comp[n].cdList = cdp->next;
234 +                        free(cdp);
235 +                }
236 + }
237 +
238 + /* Free a spectral distribution function */
239 + void
240 + SDfreeSpectralDF(SDSpectralDF *df)
241 + {
242 +        int     n;
243 +
244 +        if (df == NULL)
245 +                return;
246 +        SDfreeCumulativeCache(df);
247 +        for (n = df->ncomp; n-- > 0; )
248 +                (*df->comp[n].func->freeSC)(df->comp[n].dist);
249 +        free(df);
250 + }
251 +
252 + /* Shorten file path to useable BSDF name, removing suffix */
253 + void
254 + SDclipName(char *res, const char *fname)
255 + {
256 +        const char      *cp, *dot = NULL;
257 +        
258 +        for (cp = fname; *cp; cp++)
259 +                if (*cp == '.')
260 +                        dot = cp;
261 +        if ((dot == NULL) | (dot < fname+2))
262 +                dot = cp;
263 +        if (dot - fname >= SDnameLn)
264 +                fname = dot - SDnameLn + 1;
265 +        while (fname < dot)
266 +                *res++ = *fname++;
267 +        *res = '\0';
268 + }
269 +
270 + /* Initialize an unused BSDF struct (simply clears to zeroes) */
271 + void
272 + SDclearBSDF(SDData *sd, const char *fname)
273 + {
274 +        if (sd == NULL)
275 +                return;
276 +        memset(sd, 0, sizeof(SDData));
277 +        if (fname == NULL)
278 +                return;
279 +        SDclipName(sd->name, fname);
280 + }
281 +
282 + /* Free data associated with BSDF struct */
283 + void
284 + SDfreeBSDF(SDData *sd)
285 + {
286 +        if (sd == NULL)
287 +                return;
288 +        if (sd->mgf != NULL) {
289 +                free(sd->mgf);
290 +                sd->mgf = NULL;
291 +        }
292 +        if (sd->rf != NULL) {
293 +                SDfreeSpectralDF(sd->rf);
294 +                sd->rf = NULL;
295 +        }
296 +        if (sd->rb != NULL) {
297 +                SDfreeSpectralDF(sd->rb);
298 +                sd->rb = NULL;
299 +        }
300 +        if (sd->tf != NULL) {
301 +                SDfreeSpectralDF(sd->tf);
302 +                sd->tf = NULL;
303 +        }
304 +        sd->rLambFront.cieY = .0;
305 +        sd->rLambFront.spec.flags = 0;
306 +        sd->rLambBack.cieY = .0;
307 +        sd->rLambBack.spec.flags = 0;
308 +        sd->tLamb.cieY = .0;
309 +        sd->tLamb.spec.flags = 0;
310 + }
311 +
312 + /* Find writeable BSDF by name, or allocate new cache entry if absent */
313 + SDData *
314 + SDgetCache(const char *bname)
315 + {
316 +        struct SDCache_s        *sdl;
317 +        char                    sdnam[SDnameLn];
318 +
319 +        if (bname == NULL)
320 +                return NULL;
321 +
322 +        SDclipName(sdnam, bname);
323 +        for (sdl = SDcacheList; sdl != NULL; sdl = sdl->next)
324 +                if (!strcmp(sdl->bsdf.name, sdnam)) {
325 +                        sdl->refcnt++;
326 +                        return &sdl->bsdf;
327 +                }
328 +
329 +        sdl = (struct SDCache_s *)calloc(1, sizeof(struct SDCache_s));
330 +        if (sdl == NULL)
331 +                return NULL;
332 +
333 +        strcpy(sdl->bsdf.name, sdnam);
334 +        sdl->next = SDcacheList;
335 +        SDcacheList = sdl;
336 +
337 +        sdl->refcnt = 1;
338 +        return &sdl->bsdf;
339 + }
340 +
341 + /* Get loaded BSDF from cache (or load and cache it on first call) */
342 + /* Report any problem to stderr and return NULL on failure */
343 + const SDData *
344 + SDcacheFile(const char *fname)
345 + {
346 +        SDData          *sd;
347 +        SDError         ec;
348 +        
349 +        if (fname == NULL || !*fname)
350 +                return NULL;
351 +        SDerrorDetail[0] = '\0';
352 +        if ((sd = SDgetCache(fname)) == NULL) {
353 +                SDreportEnglish(SDEmemory, stderr);
354 +                return NULL;
355 +        }
356 +        if (!SDisLoaded(sd) && (ec = SDloadFile(sd, fname))) {
357 +                SDreportEnglish(ec, stderr);
358 +                SDfreeCache(sd);
359 +                return NULL;
360 +        }
361 +        return sd;
362 + }
363 +
364 + /* Free a BSDF from our cache (clear all if NULL) */
365 + void
366 + SDfreeCache(const SDData *sd)
367 + {
368 +        struct SDCache_s        *sdl, *sdLast = NULL;
369 +
370 +        if (sd == NULL) {               /* free entire list */
371 +                while ((sdl = SDcacheList) != NULL) {
372 +                        SDcacheList = sdl->next;
373 +                        SDfreeBSDF(&sdl->bsdf);
374 +                        free(sdl);
375 +                }
376 +                return;
377 +        }
378 +        for (sdl = SDcacheList; sdl != NULL; sdl = (sdLast=sdl)->next)
379 +                if (&sdl->bsdf == sd)
380 +                        break;
381 +        if (sdl == NULL || (sdl->refcnt -= (sdl->refcnt > 0)))
382 +                return;                 /* missing or still in use */
383 +                                        /* keep unreferenced data? */
384 +        if (SDisLoaded(sd) && SDretainSet) {
385 +                if (SDretainSet == SDretainAll)
386 +                        return;         /* keep everything */
387 +                                        /* else free cumulative data */
388 +                SDfreeCumulativeCache(sd->rf);
389 +                SDfreeCumulativeCache(sd->rb);
390 +                SDfreeCumulativeCache(sd->tf);
391 +                return;
392 +        }
393 +                                        /* remove from list and free */
394 +        if (sdLast == NULL)
395 +                SDcacheList = sdl->next;
396 +        else
397 +                sdLast->next = sdl->next;
398 +        SDfreeBSDF(&sdl->bsdf);
399 +        free(sdl);
400 + }
401 +
402 + /* Sample an individual BSDF component */
403 + SDError
404 + SDsampComponent(SDValue *sv, FVECT ioVec, double randX, SDComponent *sdc)
405 + {
406 +        float           coef[SDmaxCh];
407 +        SDError         ec;
408 +        FVECT           inVec;
409 +        const SDCDst    *cd;
410 +        double          d;
411 +        int             n;
412 +                                        /* check arguments */
413 +        if ((sv == NULL) | (ioVec == NULL) | (sdc == NULL))
414 +                return SDEargument;
415 +                                        /* get cumulative distribution */
416 +        VCOPY(inVec, ioVec);
417 +        cd = (*sdc->func->getCDist)(inVec, sdc);
418 +        if (cd == NULL)
419 +                return SDEmemory;
420 +        if (cd->cTotal <= 1e-7) {       /* anything to sample? */
421 +                sv->spec = c_dfcolor;
422 +                sv->cieY = .0;
423 +                memset(ioVec, 0, 3*sizeof(double));
424 +                return SDEnone;
425 +        }
426 +        sv->cieY = cd->cTotal;
427 +                                        /* compute sample direction */
428 +        ec = (*sdc->func->sampCDist)(ioVec, randX, cd);
429 +        if (ec)
430 +                return ec;
431 +                                        /* get BSDF color */
432 +        n = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
433 +        if (n <= 0) {
434 +                strcpy(SDerrorDetail, "BSDF sample value error");
435 +                return SDEinternal;
436 +        }
437 +        sv->spec = sdc->cspec[0];
438 +        d = coef[0];
439 +        while (--n) {
440 +                c_cmix(&sv->spec, d, &sv->spec, coef[n], &sdc->cspec[n]);
441 +                d += coef[n];
442 +        }
443 +                                        /* make sure everything is set */
444 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
445 +        return SDEnone;
446 + }
447 +
448 + #define MS_MAXDIM       15
449 +
450 + /* Convert 1-dimensional random variable to N-dimensional */
451 + void
452 + SDmultiSamp(double t[], int n, double randX)
453 + {
454 +        unsigned        nBits;
455 +        double          scale;
456 +        bitmask_t       ndx, coord[MS_MAXDIM];
457 +        
458 +        while (n > MS_MAXDIM)           /* punt for higher dimensions */
459 +                t[--n] = rand()*(1./(RAND_MAX+.5));
460 +        nBits = (8*sizeof(bitmask_t) - 1) / n;
461 +        ndx = randX * (double)((bitmask_t)1 << (nBits*n));
462 +                                        /* get coordinate on Hilbert curve */
463 +        hilbert_i2c(n, nBits, ndx, coord);
464 +                                        /* convert back to [0,1) range */
465 +        scale = 1. / (double)((bitmask_t)1 << nBits);
466 +        while (n--)
467 +                t[n] = scale * ((double)coord[n] + rand()*(1./(RAND_MAX+.5)));
468 + }
469 +
470 + #undef MS_MAXDIM
471 +
472 + /* Generate diffuse hemispherical sample */
473 + static void
474 + SDdiffuseSamp(FVECT outVec, int outFront, double randX)
475 + {
476 +                                        /* convert to position on hemisphere */
477 +        SDmultiSamp(outVec, 2, randX);
478 +        SDsquare2disk(outVec, outVec[0], outVec[1]);
479 +        outVec[2] = 1. - outVec[0]*outVec[0] - outVec[1]*outVec[1];
480 +        if (outVec[2] > 0)              /* a bit of paranoia */
481 +                outVec[2] = sqrt(outVec[2]);
482 +        if (!outFront)                  /* going out back? */
483 +                outVec[2] = -outVec[2];
484 + }
485 +
486 + /* Query projected solid angle coverage for non-diffuse BSDF direction */
487 + SDError
488 + SDsizeBSDF(double *projSA, const FVECT v1, const RREAL *v2,
489 +                                int qflags, const SDData *sd)
490 + {
491 +        SDSpectralDF    *rdf, *tdf;
492 +        SDError         ec;
493 +        int             i;
494 +                                        /* check arguments */
495 +        if ((projSA == NULL) | (v1 == NULL) | (sd == NULL))
496 +                return SDEargument;
497 +                                        /* initialize extrema */
498 +        switch (qflags) {
499 +        case SDqueryMax:
500 +                projSA[0] = .0;
501 +                break;
502 +        case SDqueryMin+SDqueryMax:
503 +                projSA[1] = .0;
504 +                /* fall through */
505 +        case SDqueryMin:
506 +                projSA[0] = 10.;
507 +                break;
508 +        case 0:
509 +                return SDEargument;
510 +        }
511 +        if (v1[2] > 0)                  /* front surface query? */
512 +                rdf = sd->rf;
513 +        else
514 +                rdf = sd->rb;
515 +        tdf = sd->tf;
516 +        if (v2 != NULL)                 /* bidirectional? */
517 +                if (v1[2] > 0 ^ v2[2] > 0)
518 +                        rdf = NULL;
519 +                else
520 +                        tdf = NULL;
521 +        ec = SDEdata;                   /* run through components */
522 +        for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
523 +                ec = (*rdf->comp[i].func->queryProjSA)(projSA, v1, v2,
524 +                                                qflags, &rdf->comp[i]);
525 +                if (ec)
526 +                        return ec;
527 +        }
528 +        for (i = (tdf==NULL) ? 0 : tdf->ncomp; i--; ) {
529 +                ec = (*tdf->comp[i].func->queryProjSA)(projSA, v1, v2,
530 +                                                qflags, &tdf->comp[i]);
531 +                if (ec)
532 +                        return ec;
533 +        }
534 +        if (ec) {                       /* all diffuse? */
535 +                projSA[0] = M_PI;
536 +                if (qflags == SDqueryMin+SDqueryMax)
537 +                        projSA[1] = M_PI;
538 +        }
539 +        return SDEnone;
540 + }
541 +
542 + /* Return BSDF for the given incident and scattered ray vectors */
543 + SDError
544 + SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
545 + {
546 +        int             inFront, outFront;
547 +        SDSpectralDF    *sdf;
548 +        float           coef[SDmaxCh];
549 +        int             nch, i;
550 +                                        /* check arguments */
551 +        if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
552 +                return SDEargument;
553 +                                        /* whose side are we on? */
554 +        inFront = (inVec[2] > 0);
555 +        outFront = (outVec[2] > 0);
556 +                                        /* start with diffuse portion */
557 +        if (inFront & outFront) {
558 +                *sv = sd->rLambFront;
559 +                sdf = sd->rf;
560 +        } else if (!(inFront | outFront)) {
561 +                *sv = sd->rLambBack;
562 +                sdf = sd->rb;
563 +        } else /* inFront ^ outFront */ {
564 +                *sv = sd->tLamb;
565 +                sdf = sd->tf;
566 +        }
567 +        sv->cieY *= 1./M_PI;
568 +                                        /* add non-diffuse components */
569 +        i = (sdf != NULL) ? sdf->ncomp : 0;
570 +        while (i-- > 0) {
571 +                nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
572 +                                                        &sdf->comp[i]);
573 +                while (nch-- > 0) {
574 +                        c_cmix(&sv->spec, sv->cieY, &sv->spec,
575 +                                        coef[nch], &sdf->comp[i].cspec[nch]);
576 +                        sv->cieY += coef[nch];
577 +                }
578 +        }
579 +                                        /* make sure everything is set */
580 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
581 +        return SDEnone;
582 + }
583 +
584 + /* Compute directional hemispherical scattering at this incident angle */
585 + double
586 + SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
587 + {
588 +        double          hsum;
589 +        SDSpectralDF    *rdf;
590 +        const SDCDst    *cd;
591 +        int             i;
592 +                                        /* check arguments */
593 +        if ((inVec == NULL) | (sd == NULL))
594 +                return .0;
595 +                                        /* gather diffuse components */
596 +        if (inVec[2] > 0) {
597 +                hsum = sd->rLambFront.cieY;
598 +                rdf = sd->rf;
599 +        } else /* !inFront */ {
600 +                hsum = sd->rLambBack.cieY;
601 +                rdf = sd->rb;
602 +        }
603 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
604 +                hsum = .0;
605 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
606 +                hsum += sd->tLamb.cieY;
607 +                                        /* gather non-diffuse components */
608 +        i = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
609 +                        rdf != NULL) ? rdf->ncomp : 0;
610 +        while (i-- > 0) {               /* non-diffuse reflection */
611 +                cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
612 +                if (cd != NULL)
613 +                        hsum += cd->cTotal;
614 +        }
615 +        i = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
616 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
617 +        while (i-- > 0) {               /* non-diffuse transmission */
618 +                cd = (*sd->tf->comp[i].func->getCDist)(inVec, &sd->tf->comp[i]);
619 +                if (cd != NULL)
620 +                        hsum += cd->cTotal;
621 +        }
622 +        return hsum;
623 + }
624 +
625 + /* Sample BSDF direction based on the given random variable */
626 + SDError
627 + SDsampBSDF(SDValue *sv, FVECT ioVec, double randX, int sflags, const SDData *sd)
628 + {
629 +        SDError         ec;
630 +        FVECT           inVec;
631 +        int             inFront;
632 +        SDSpectralDF    *rdf;
633 +        double          rdiff;
634 +        float           coef[SDmaxCh];
635 +        int             i, j, n, nr;
636 +        SDComponent     *sdc;
637 +        const SDCDst    **cdarr = NULL;
638 +                                        /* check arguments */
639 +        if ((sv == NULL) | (ioVec == NULL) | (sd == NULL) |
640 +                        (randX < 0) | (randX >= 1.))
641 +                return SDEargument;
642 +                                        /* whose side are we on? */
643 +        VCOPY(inVec, ioVec);
644 +        inFront = (inVec[2] > 0);
645 +                                        /* remember diffuse portions */
646 +        if (inFront) {
647 +                *sv = sd->rLambFront;
648 +                rdf = sd->rf;
649 +        } else /* !inFront */ {
650 +                *sv = sd->rLambBack;
651 +                rdf = sd->rb;
652 +        }
653 +        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
654 +                sv->cieY = .0;
655 +        rdiff = sv->cieY;
656 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
657 +                sv->cieY += sd->tLamb.cieY;
658 +                                        /* gather non-diffuse components */
659 +        i = nr = ((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR &&
660 +                        rdf != NULL) ? rdf->ncomp : 0;
661 +        j = ((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT &&
662 +                        sd->tf != NULL) ? sd->tf->ncomp : 0;
663 +        n = i + j;
664 +        if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
665 +                return SDEmemory;
666 +        while (j-- > 0) {               /* non-diffuse transmission */
667 +                cdarr[i+j] = (*sd->tf->comp[j].func->getCDist)(inVec, &sd->tf->comp[j]);
668 +                if (cdarr[i+j] == NULL) {
669 +                        free(cdarr);
670 +                        return SDEmemory;
671 +                }
672 +                sv->cieY += cdarr[i+j]->cTotal;
673 +        }
674 +        while (i-- > 0) {               /* non-diffuse reflection */
675 +                cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
676 +                if (cdarr[i] == NULL) {
677 +                        free(cdarr);
678 +                        return SDEmemory;
679 +                }
680 +                sv->cieY += cdarr[i]->cTotal;
681 +        }
682 +        if (sv->cieY <= 1e-7) {         /* anything to sample? */
683 +                sv->cieY = .0;
684 +                memset(ioVec, 0, 3*sizeof(double));
685 +                return SDEnone;
686 +        }
687 +                                        /* scale random variable */
688 +        randX *= sv->cieY;
689 +                                        /* diffuse reflection? */
690 +        if (randX < rdiff) {
691 +                SDdiffuseSamp(ioVec, inFront, randX/rdiff);
692 +                goto done;
693 +        }
694 +        randX -= rdiff;
695 +                                        /* diffuse transmission? */
696 +        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
697 +                if (randX < sd->tLamb.cieY) {
698 +                        sv->spec = sd->tLamb.spec;
699 +                        SDdiffuseSamp(ioVec, !inFront, randX/sd->tLamb.cieY);
700 +                        goto done;
701 +                }
702 +                randX -= sd->tLamb.cieY;
703 +        }
704 +                                        /* else one of cumulative dist. */
705 +        for (i = 0; i < n && randX < cdarr[i]->cTotal; i++)
706 +                randX -= cdarr[i]->cTotal;
707 +        if (i >= n)
708 +                return SDEinternal;
709 +                                        /* compute sample direction */
710 +        sdc = (i < nr) ? &rdf->comp[i] : &sd->tf->comp[i-nr];
711 +        ec = (*sdc->func->sampCDist)(ioVec, randX/cdarr[i]->cTotal, cdarr[i]);
712 +        if (ec)
713 +                return ec;
714 +                                        /* compute color */
715 +        j = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
716 +        if (j <= 0) {
717 +                sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
718 +                                sd->name);
719 +                return SDEinternal;
720 +        }
721 +        sv->spec = sdc->cspec[0];
722 +        rdiff = coef[0];
723 +        while (--j) {
724 +                c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
725 +                rdiff += coef[j];
726 +        }
727 + done:
728 +        if (cdarr != NULL)
729 +                free(cdarr);
730 +                                        /* make sure everything is set */
731 +        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
732 +        return SDEnone;
733 + }
734 +
735 + /* Compute World->BSDF transform from surface normal and up (Y) vector */
736 + SDError
737 + SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
738 + {
739 +        if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
740 +                return SDEargument;
741 +        VCOPY(vMtx[2], sNrm);
742 +        if (normalize(vMtx[2]) == 0)
743 +                return SDEargument;
744 +        fcross(vMtx[0], uVec, vMtx[2]);
745 +        if (normalize(vMtx[0]) == 0)
746 +                return SDEargument;
747 +        fcross(vMtx[1], vMtx[2], vMtx[0]);
748 +        return SDEnone;
749 + }
750 +
751 + /* Compute inverse transform */
752 + SDError
753 + SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
754 + {
755 +        RREAL   mTmp[3][3];
756 +        double  d;
757 +
758 +        if ((iMtx == NULL) | (vMtx == NULL))
759 +                return SDEargument;
760 +                                        /* compute determinant */
761 +        mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
762 +        mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
763 +        mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
764 +        d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
765 +        if (d == 0) {
766 +                strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
767 +                return SDEargument;
768 +        }
769 +        d = 1./d;                       /* invert matrix */
770 +        mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
771 +        mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
772 +        mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
773 +        mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
774 +        mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
775 +        mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
776 +        mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
777 +        memcpy(iMtx, mTmp, sizeof(mTmp));
778 +        return SDEnone;
779 + }
780 +
781 + /* Transform and normalize direction (column) vector */
782 + SDError
783 + SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
784 + {
785 +        FVECT   vTmp;
786 +
787 +        if ((resVec == NULL) | (inpVec == NULL))
788 +                return SDEargument;
789 +        if (vMtx == NULL) {             /* assume they just want to normalize */
790 +                if (resVec != inpVec)
791 +                        VCOPY(resVec, inpVec);
792 +                return (normalize(resVec) > 0) ? SDEnone : SDEargument;
793 +        }
794 +        vTmp[0] = DOT(vMtx[0], inpVec);
795 +        vTmp[1] = DOT(vMtx[1], inpVec);
796 +        vTmp[2] = DOT(vMtx[2], inpVec);
797 +        if (normalize(vTmp) == 0)
798 +                return SDEargument;
799 +        VCOPY(resVec, vTmp);
800 +        return SDEnone;
801 + }
802 +
803 + /*################################################################*/
804 + /*######### DEPRECATED ROUTINES AWAITING PERMANENT REMOVAL #######*/
805 +
806 + /*
807   * Routines for handling BSDF data
808   */
809  
810   #include "standard.h"
9 #include "bsdf.h"
811   #include "paths.h"
11 #include "ezxml.h"
812   #include <ctype.h>
813  
814   #define MAXLATS         46              /* maximum number of latitudes */
# Line 66 | Line 866 | static int     nabases = 3;    /* current number of defined b
866   static int
867   fequal(double a, double b)
868   {
869 <        if (b != .0)
869 >        if (b != 0)
870                  a = a/b - 1.;
871          return((a <= 1e-6) & (a >= -1e-6));
872   }
873  
874 < // returns the name of the given tag
874 > /* Returns the name of the given tag */
875   #ifdef ezxml_name
876   #undef ezxml_name
877   static char *
# Line 83 | Line 883 | ezxml_name(ezxml_t xml)
883   }
884   #endif
885  
886 < // returns the given tag's character content or empty string if none
886 > /* Returns the given tag's character content or empty string if none */
887   #ifdef ezxml_txt
888   #undef ezxml_txt
889   static char *
# Line 219 | Line 1019 | load_angle_basis(      /* load custom BSDF angle basis */
1019          if (!abname || !*abname)
1020                  return;
1021          for (i = nabases; i--; )
1022 <                if (!strcmp(abname, abase_list[i].name))
1022 >                if (!strcasecmp(abname, abase_list[i].name))
1023                          return;         /* assume it's the same */
1024          if (nabases >= MAXABASES)
1025                  error(INTERNAL, "too many angle bases");
# Line 247 | Line 1047 | load_angle_basis(      /* load custom BSDF angle basis */
1047   }
1048  
1049  
250 static double
251 to_meters(              /* return factor to convert given unit to meters */
252        const char *unit
253 )
254 {
255        if (unit == NULL) return(1.);           /* safe assumption? */
256        if (!strcasecmp(unit, "Meter")) return(1.);
257        if (!strcasecmp(unit, "Foot")) return(.3048);
258        if (!strcasecmp(unit, "Inch")) return(.0254);
259        if (!strcasecmp(unit, "Centimeter")) return(.01);
260        if (!strcasecmp(unit, "Millimeter")) return(.001);
261        sprintf(errmsg, "unknown dimensional unit '%s'", unit);
262        error(USER, errmsg);
263 }
264
265
1050   static void
1051   load_geometry(          /* load geometric dimensions and description (if any) */
1052          struct BSDF_data *dp,
# Line 320 | Line 1104 | load_bsdf_data(                /* load BSDF distribution for this wa
1104                  return;
1105          }
1106          for (i = nabases; i--; )
1107 <                if (!strcmp(cbasis, abase_list[i].name)) {
1107 >                if (!strcasecmp(cbasis, abase_list[i].name)) {
1108                          dp->ninc = abase_list[i].nangles;
1109                          dp->ib_priv = (void *)&abase_list[i];
1110                          dp->ib_vec = ab_getvecR;
# Line 334 | Line 1118 | load_bsdf_data(                /* load BSDF distribution for this wa
1118                  return;
1119          }
1120          for (i = nabases; i--; )
1121 <                if (!strcmp(rbasis, abase_list[i].name)) {
1121 >                if (!strcasecmp(rbasis, abase_list[i].name)) {
1122                          dp->nout = abase_list[i].nangles;
1123                          dp->ob_priv = (void *)&abase_list[i];
1124                          dp->ob_vec = ab_getvec;
# Line 343 | Line 1127 | load_bsdf_data(                /* load BSDF distribution for this wa
1127                          break;
1128                  }
1129          if (i < 0) {
1130 <                sprintf(errmsg, "undefined RowAngleBasis '%s'", cbasis);
1130 >                sprintf(errmsg, "undefined RowAngleBasis '%s'", rbasis);
1131                  error(WARNING, errmsg);
1132                  return;
1133          }
# Line 400 | Line 1184 | check_bsdf_data(       /* check that BSDF data is sane */
1184          hemi_total = .0;
1185          for (i = dp->ninc; i--; ) {
1186                  dom = getBSDF_incohm(dp,i);
1187 <                if (dom <= .0) {
1187 >                if (dom <= 0) {
1188                          error(WARNING, "zero/negative incoming solid angle");
1189                          continue;
1190                  }
# Line 423 | Line 1207 | check_bsdf_data(       /* check that BSDF data is sane */
1207          hemi_total = .0;
1208          for (o = dp->nout; o--; ) {
1209                  dom = getBSDF_outohm(dp,o);
1210 <                if (dom <= .0) {
1210 >                if (dom <= 0) {
1211                          error(WARNING, "zero/negative outgoing solid angle");
1212                          continue;
1213                  }
# Line 447 | Line 1231 | check_bsdf_data(       /* check that BSDF data is sane */
1231                  hemi_total = .0;
1232                  for (o = dp->nout; o--; ) {
1233                          double  f = BSDF_value(dp,i,o);
1234 <                        if (f >= .0)
1234 >                        if (f >= 0)
1235                                  hemi_total += f*omega_oarr[o];
1236                          else {
1237                                  nneg += (f < -FTINY);
# Line 526 | Line 1310 | load_BSDF(             /* load BSDF data from file */
1310                  return(NULL);
1311          }
1312          wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
1313 +        if (strcasecmp(ezxml_txt(ezxml_child(ezxml_child(wtl,
1314 +                        "DataDefinition"), "IncidentDataStructure")),
1315 +                        "Columns")) {
1316 +                sprintf(errmsg,
1317 +                        "BSDF \"%s\": unsupported IncidentDataStructure",
1318 +                                path);
1319 +                error(WARNING, errmsg);
1320 +                ezxml_free(fl);
1321 +                return(NULL);
1322 +        }              
1323          load_angle_basis(ezxml_child(ezxml_child(wtl,
1324                                  "DataDefinition"), "AngleBasis"));
1325          dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
1326          load_geometry(dp, ezxml_child(wtl, "Material"));
1327          for (wld = ezxml_child(wtl, "WavelengthData");
1328                                  wld != NULL; wld = wld->next) {
1329 <                if (strcmp(ezxml_txt(ezxml_child(wld,"Wavelength")), "Visible"))
1329 >                if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
1330 >                                "Visible"))
1331                          continue;
1332 <                wdb = ezxml_child(wld, "WavelengthDataBlock");
1333 <                if (wdb == NULL) continue;
1334 <                if (strcmp(ezxml_txt(ezxml_child(wdb,"WavelengthDataDirection")),
1332 >                for (wdb = ezxml_child(wld, "WavelengthDataBlock");
1333 >                                wdb != NULL; wdb = wdb->next)
1334 >                        if (!strcasecmp(ezxml_txt(ezxml_child(wdb,
1335 >                                        "WavelengthDataDirection")),
1336                                          "Transmission Front"))
1337 <                        continue;
1338 <                load_bsdf_data(dp, wdb);        /* load front BTDF */
1339 <                break;                          /* ignore the rest */
1337 >                                break;
1338 >                if (wdb != NULL) {              /* load front BTDF */
1339 >                        load_bsdf_data(dp, wdb);
1340 >                        break;                  /* ignore the rest */
1341 >                }
1342          }
1343          ezxml_free(fl);                         /* done with XML file */
1344          if (!check_bsdf_data(dp)) {
# Line 716 | Line 1514 | getBSDF_xfm(           /* compute BSDF orient. -> world orient.
1514          }
1515          return(1);
1516   }
1517 +
1518 + /*######### END DEPRECATED ROUTINES #######*/
1519 + /*################################################################*/

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines