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.8 by greg, Sun Sep 26 15:43:26 2010 UTC vs.
Revision 2.54 by greg, Mon May 15 22:44:10 2017 UTC

# Line 2 | Line 2
2   static const char RCSid[] = "$Id$";
3   #endif
4   /*
5 < * Routines for handling BSDF data
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 "standard.h"
14 < #include "bsdf.h"
15 < #include "paths.h"
16 < #include "ezxml.h"
13 > #define _USE_MATH_DEFINES
14 > #include <stdio.h>
15 > #include <stdlib.h>
16 > #include <string.h>
17 > #include <math.h>
18   #include <ctype.h>
19 + #include "ezxml.h"
20 + #include "hilbert.h"
21 + #include "bsdf.h"
22 + #include "bsdf_m.h"
23 + #include "bsdf_t.h"
24  
25 < #define MAXLATS         46              /* maximum number of latitudes */
25 > /* English ASCII strings corresponding to ennumerated errors */
26 > const char              *SDerrorEnglish[] = {
27 >                                "No error",
28 >                                "Memory error",
29 >                                "File input/output error",
30 >                                "File format error",
31 >                                "Illegal argument",
32 >                                "Invalid data",
33 >                                "Unsupported feature",
34 >                                "Internal program error",
35 >                                "Unknown error"
36 >                        };
37  
38 < /* BSDF angle specification */
39 < typedef struct {
18 <        char    name[64];               /* basis name */
19 <        int     nangles;                /* total number of directions */
20 <        struct {
21 <                float   tmin;                   /* starting theta */
22 <                short   nphis;                  /* number of phis (0 term) */
23 <        }       lat[MAXLATS+1];         /* latitudes */
24 < } ANGLE_BASIS;
38 > /* Pointer to error list in preferred language */
39 > const char              **SDerrorList = SDerrorEnglish;
40  
41 < #define MAXABASES       7               /* limit on defined bases */
41 > /* Additional information on last error (ASCII English) */
42 > char                    SDerrorDetail[256];
43  
44 < static ANGLE_BASIS      abase_list[MAXABASES] = {
45 <        {
30 <                "LBNL/Klems Full", 145,
31 <                { {-5., 1},
32 <                {5., 8},
33 <                {15., 16},
34 <                {25., 20},
35 <                {35., 24},
36 <                {45., 24},
37 <                {55., 24},
38 <                {65., 16},
39 <                {75., 12},
40 <                {90., 0} }
41 <        }, {
42 <                "LBNL/Klems Half", 73,
43 <                { {-6.5, 1},
44 <                {6.5, 8},
45 <                {19.5, 12},
46 <                {32.5, 16},
47 <                {46.5, 20},
48 <                {61.5, 12},
49 <                {76.5, 4},
50 <                {90., 0} }
51 <        }, {
52 <                "LBNL/Klems Quarter", 41,
53 <                { {-9., 1},
54 <                {9., 8},
55 <                {27., 12},
56 <                {46., 12},
57 <                {66., 8},
58 <                {90., 0} }
59 <        }
60 < };
44 > /* Empty distribution for getCDist() calls that fail for some reason */
45 > const SDCDst            SDemptyCD;
46  
47 < static int      nabases = 3;    /* current number of defined bases */
47 > /* Cache of loaded BSDFs */
48 > struct SDCache_s        *SDcacheList = NULL;
49  
50 < #define  FEQ(a,b)       ((a)-(b) <= 1e-7 && (b)-(a) <= 1e-7)
50 > /* Retain BSDFs in cache list */
51 > int                     SDretainSet = SDretainNone;
52  
53 < // returns the name of the given tag
54 < #ifdef ezxml_name
55 < #undef ezxml_name
69 < static char *
70 < ezxml_name(ezxml_t xml)
53 > /* Report any error to the indicated stream */
54 > SDError
55 > SDreportError(SDError ec, FILE *fp)
56   {
57 <        if (xml == NULL)
58 <                return(NULL);
59 <        return(xml->name);
57 >        if (!ec)
58 >                return SDEnone;
59 >        if ((ec < SDEnone) | (ec > SDEunknown)) {
60 >                SDerrorDetail[0] = '\0';
61 >                ec = SDEunknown;
62 >        }
63 >        if (fp == NULL)
64 >                return ec;
65 >        fputs(SDerrorList[ec], fp);
66 >        if (SDerrorDetail[0]) {
67 >                fputs(": ", fp);
68 >                fputs(SDerrorDetail, fp);
69 >        }
70 >        fputc('\n', fp);
71 >        if (fp != stderr)
72 >                fflush(fp);
73 >        return ec;
74   }
76 #endif
75  
76 < // returns the given tag's character content or empty string if none
77 < #ifdef ezxml_txt
78 < #undef ezxml_txt
79 < static char *
82 < ezxml_txt(ezxml_t xml)
76 > static double
77 > to_meters(              /* return factor to convert given unit to meters */
78 >        const char *unit
79 > )
80   {
81 <        if (xml == NULL)
82 <                return("");
83 <        return(xml->txt);
81 >        if (unit == NULL) return(1.);           /* safe assumption? */
82 >        if (!strcasecmp(unit, "Meter")) return(1.);
83 >        if (!strcasecmp(unit, "Foot")) return(.3048);
84 >        if (!strcasecmp(unit, "Inch")) return(.0254);
85 >        if (!strcasecmp(unit, "Centimeter")) return(.01);
86 >        if (!strcasecmp(unit, "Millimeter")) return(.001);
87 >        sprintf(SDerrorDetail, "Unknown dimensional unit '%s'", unit);
88 >        return(-1.);
89   }
88 #endif
90  
91 <
92 < static int
93 < ab_getvec(              /* get vector for this angle basis index */
93 <        FVECT v,
94 <        int ndx,
95 <        void *p
96 < )
91 > /* Load geometric dimensions and description (if any) */
92 > static SDError
93 > SDloadGeometry(SDData *sd, ezxml_t wtl)
94   {
95 <        ANGLE_BASIS  *ab = (ANGLE_BASIS *)p;
96 <        int     li;
97 <        double  pol, azi, d;
98 <        
99 <        if ((ndx < 0) | (ndx >= ab->nangles))
100 <                return(0);
101 <        for (li = 0; ndx >= ab->lat[li].nphis; li++)
102 <                ndx -= ab->lat[li].nphis;
103 <        pol = PI/180.*0.5*(ab->lat[li].tmin + ab->lat[li+1].tmin);
104 <        azi = 2.*PI*ndx/ab->lat[li].nphis;
105 <        v[2] = d = cos(pol);
106 <        d = sqrt(1. - d*d);     /* sin(pol) */
107 <        v[0] = cos(azi)*d;
108 <        v[1] = sin(azi)*d;
109 <        return(1);
95 >        ezxml_t         node, matl, geom;
96 >        double          cfact;
97 >        const char      *fmt = NULL, *mgfstr;
98 >
99 >        SDerrorDetail[0] = '\0';
100 >        sd->matn[0] = '\0'; sd->makr[0] = '\0';
101 >        sd->dim[0] = sd->dim[1] = sd->dim[2] = 0;
102 >        matl = ezxml_child(wtl, "Material");
103 >        if (matl != NULL) {                     /* get material info. */
104 >                if ((node = ezxml_child(matl, "Name")) != NULL) {
105 >                        strncpy(sd->matn, ezxml_txt(node), SDnameLn);
106 >                        if (sd->matn[SDnameLn-1])
107 >                                strcpy(sd->matn+(SDnameLn-4), "...");
108 >                }
109 >                if ((node = ezxml_child(matl, "Manufacturer")) != NULL) {
110 >                        strncpy(sd->makr, ezxml_txt(node), SDnameLn);
111 >                        if (sd->makr[SDnameLn-1])
112 >                                strcpy(sd->makr+(SDnameLn-4), "...");
113 >                }
114 >                if ((node = ezxml_child(matl, "Width")) != NULL)
115 >                        sd->dim[0] = atof(ezxml_txt(node)) *
116 >                                        to_meters(ezxml_attr(node, "unit"));
117 >                if ((node = ezxml_child(matl, "Height")) != NULL)
118 >                        sd->dim[1] = atof(ezxml_txt(node)) *
119 >                                        to_meters(ezxml_attr(node, "unit"));
120 >                if ((node = ezxml_child(matl, "Thickness")) != NULL)
121 >                        sd->dim[2] = atof(ezxml_txt(node)) *
122 >                                        to_meters(ezxml_attr(node, "unit"));
123 >                if ((sd->dim[0] < 0) | (sd->dim[1] < 0) | (sd->dim[2] < 0)) {
124 >                        if (!SDerrorDetail[0])
125 >                                sprintf(SDerrorDetail, "Negative dimension in \"%s\"",
126 >                                                        sd->name);
127 >                        return SDEdata;
128 >                }
129 >        }
130 >        sd->mgf = NULL;
131 >        geom = ezxml_child(wtl, "Geometry");
132 >        if (geom == NULL)                       /* no actual geometry? */
133 >                return SDEnone;
134 >        fmt = ezxml_attr(geom, "format");
135 >        if (fmt != NULL && strcasecmp(fmt, "MGF")) {
136 >                sprintf(SDerrorDetail,
137 >                        "Unrecognized geometry format '%s' in \"%s\"",
138 >                                        fmt, sd->name);
139 >                return SDEsupport;
140 >        }
141 >        if ((node = ezxml_child(geom, "MGFblock")) == NULL ||
142 >                        (mgfstr = ezxml_txt(node)) == NULL)
143 >                return SDEnone;
144 >        while (isspace(*mgfstr))
145 >                ++mgfstr;
146 >        if (!*mgfstr)
147 >                return SDEnone;
148 >        cfact = to_meters(ezxml_attr(node, "unit"));
149 >        if (cfact <= 0)
150 >                return SDEformat;
151 >        sd->mgf = (char *)malloc(strlen(mgfstr)+32);
152 >        if (sd->mgf == NULL) {
153 >                strcpy(SDerrorDetail, "Out of memory in SDloadGeometry");
154 >                return SDEmemory;
155 >        }
156 >        if (cfact < 0.99 || cfact > 1.01)
157 >                sprintf(sd->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
158 >        else
159 >                strcpy(sd->mgf, mgfstr);
160 >        return SDEnone;
161   }
162  
163 <
164 < static int
165 < ab_getndx(              /* get index corresponding to the given vector */
118 <        FVECT v,
119 <        void *p
120 < )
163 > /* Load a BSDF struct from the given file (free first and keep name) */
164 > SDError
165 > SDloadFile(SDData *sd, const char *fname)
166   {
167 <        ANGLE_BASIS  *ab = (ANGLE_BASIS *)p;
168 <        int     li, ndx;
124 <        double  pol, azi, d;
167 >        SDError         lastErr;
168 >        ezxml_t         fl, wtl;
169  
170 <        if ((v[2] < -1.0) | (v[2] > 1.0))
171 <                return(-1);
172 <        pol = 180.0/PI*acos(v[2]);
173 <        azi = 180.0/PI*atan2(v[1], v[0]);
174 <        if (azi < 0.0) azi += 360.0;
175 <        for (li = 1; ab->lat[li].tmin <= pol; li++)
176 <                if (!ab->lat[li].nphis)
177 <                        return(-1);
178 <        --li;
179 <        ndx = (int)((1./360.)*azi*ab->lat[li].nphis + 0.5);
180 <        if (ndx >= ab->lat[li].nphis) ndx = 0;
181 <        while (li--)
182 <                ndx += ab->lat[li].nphis;
183 <        return(ndx);
170 >        if ((sd == NULL) | (fname == NULL || !*fname))
171 >                return SDEargument;
172 >                                /* free old data, keeping name */
173 >        SDfreeBSDF(sd);
174 >                                /* parse XML file */
175 >        fl = ezxml_parse_file(fname);
176 >        if (fl == NULL) {
177 >                sprintf(SDerrorDetail, "Cannot open BSDF \"%s\"", fname);
178 >                return SDEfile;
179 >        }
180 >        if (ezxml_error(fl)[0]) {
181 >                sprintf(SDerrorDetail, "BSDF \"%s\" %s", fname, ezxml_error(fl));
182 >                ezxml_free(fl);
183 >                return SDEformat;
184 >        }
185 >        if (strcmp(ezxml_name(fl), "WindowElement")) {
186 >                sprintf(SDerrorDetail,
187 >                        "BSDF \"%s\": top level node not 'WindowElement'",
188 >                                sd->name);
189 >                ezxml_free(fl);
190 >                return SDEformat;
191 >        }
192 >        wtl = ezxml_child(fl, "FileType");
193 >        if (wtl != NULL && strcmp(ezxml_txt(wtl), "BSDF")) {
194 >                sprintf(SDerrorDetail,
195 >                        "XML \"%s\": wrong FileType (must be 'BSDF')",
196 >                                sd->name);
197 >                ezxml_free(fl);
198 >                return SDEformat;
199 >        }
200 >        wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
201 >        if (wtl == NULL) {
202 >                sprintf(SDerrorDetail, "BSDF \"%s\": no optical layers",
203 >                                sd->name);
204 >                ezxml_free(fl);
205 >                return SDEformat;
206 >        }
207 >                                /* load geometry if present */
208 >        lastErr = SDloadGeometry(sd, wtl);
209 >        if (lastErr) {
210 >                ezxml_free(fl);
211 >                return lastErr;
212 >        }
213 >                                /* try loading variable resolution data */
214 >        lastErr = SDloadTre(sd, wtl);
215 >                                /* check our result */
216 >        if (lastErr == SDEsupport)      /* try matrix BSDF if not tree data */
217 >                lastErr = SDloadMtx(sd, wtl);
218 >                
219 >                                /* done with XML file */
220 >        ezxml_free(fl);
221 >        
222 >        if (lastErr) {          /* was there a load error? */
223 >                SDfreeBSDF(sd);
224 >                return lastErr;
225 >        }
226 >                                /* remove any insignificant components */
227 >        if (sd->rf != NULL && sd->rf->maxHemi <= .001) {
228 >                SDfreeSpectralDF(sd->rf); sd->rf = NULL;
229 >        }
230 >        if (sd->rb != NULL && sd->rb->maxHemi <= .001) {
231 >                SDfreeSpectralDF(sd->rb); sd->rb = NULL;
232 >        }
233 >        if (sd->tf != NULL && sd->tf->maxHemi <= .001) {
234 >                SDfreeSpectralDF(sd->tf); sd->tf = NULL;
235 >        }
236 >        if (sd->tb != NULL && sd->tb->maxHemi <= .001) {
237 >                SDfreeSpectralDF(sd->tb); sd->tb = NULL;
238 >        }
239 >                                /* return success */
240 >        return SDEnone;
241   }
242  
243 <
244 < static double
245 < ab_getohm(              /* get solid angle for this angle basis index */
145 <        int ndx,
146 <        void *p
147 < )
243 > /* Allocate new spectral distribution function */
244 > SDSpectralDF *
245 > SDnewSpectralDF(int nc)
246   {
247 <        ANGLE_BASIS  *ab = (ANGLE_BASIS *)p;
150 <        int     li;
151 <        double  theta, theta1;
247 >        SDSpectralDF    *df;
248          
249 <        if ((ndx < 0) | (ndx >= ab->nangles))
250 <                return(0);
251 <        for (li = 0; ndx >= ab->lat[li].nphis; li++)
156 <                ndx -= ab->lat[li].nphis;
157 <        theta1 = PI/180. * ab->lat[li+1].tmin;
158 <        if (ab->lat[li].nphis == 1) {           /* special case */
159 <                if (ab->lat[li].tmin > FTINY)
160 <                        error(USER, "unsupported BSDF coordinate system");
161 <                return(2.*PI*(1. - cos(theta1)));
249 >        if (nc <= 0) {
250 >                strcpy(SDerrorDetail, "Zero component spectral DF request");
251 >                return NULL;
252          }
253 <        theta = PI/180. * ab->lat[li].tmin;
254 <        return(2.*PI*(cos(theta) - cos(theta1))/(double)ab->lat[li].nphis);
253 >        df = (SDSpectralDF *)malloc(sizeof(SDSpectralDF) +
254 >                                        (nc-1)*sizeof(SDComponent));
255 >        if (df == NULL) {
256 >                sprintf(SDerrorDetail,
257 >                                "Cannot allocate %d component spectral DF", nc);
258 >                return NULL;
259 >        }
260 >        df->minProjSA = .0;
261 >        df->maxHemi = .0;
262 >        df->ncomp = nc;
263 >        memset(df->comp, 0, nc*sizeof(SDComponent));
264 >        return df;
265   }
266  
267 <
268 < static int
269 < ab_getvecR(             /* get reverse vector for this angle basis index */
170 <        FVECT v,
171 <        int ndx,
172 <        void *p
173 < )
267 > /* Add component(s) to spectral distribution function */
268 > SDSpectralDF *
269 > SDaddComponent(SDSpectralDF *odf, int nadd)
270   {
271 <        if (!ab_getvec(v, ndx, p))
176 <                return(0);
271 >        SDSpectralDF    *df;
272  
273 <        v[0] = -v[0];
274 <        v[1] = -v[1];
275 <        v[2] = -v[2];
276 <
277 <        return(1);
273 >        if (odf == NULL)
274 >                return SDnewSpectralDF(nadd);
275 >        if (nadd <= 0)
276 >                return odf;
277 >        df = (SDSpectralDF *)realloc(odf, sizeof(SDSpectralDF) +
278 >                                (odf->ncomp+nadd-1)*sizeof(SDComponent));
279 >        if (df == NULL) {
280 >                sprintf(SDerrorDetail,
281 >                        "Cannot add %d component(s) to spectral DF", nadd);
282 >                SDfreeSpectralDF(odf);
283 >                return NULL;
284 >        }
285 >        memset(df->comp+df->ncomp, 0, nadd*sizeof(SDComponent));
286 >        df->ncomp += nadd;
287 >        return df;
288   }
289  
290 <
291 < static int
292 < ab_getndxR(             /* get index corresponding to the reverse vector */
188 <        FVECT v,
189 <        void *p
190 < )
290 > /* Free cached cumulative distributions for BSDF component */
291 > void
292 > SDfreeCumulativeCache(SDSpectralDF *df)
293   {
294 <        FVECT  v2;
295 <        
194 <        v2[0] = -v[0];
195 <        v2[1] = -v[1];
196 <        v2[2] = -v[2];
294 >        int     n;
295 >        SDCDst  *cdp;
296  
297 <        return ab_getndx(v2, p);
297 >        if (df == NULL)
298 >                return;
299 >        for (n = df->ncomp; n-- > 0; )
300 >                while ((cdp = df->comp[n].cdList) != NULL) {
301 >                        df->comp[n].cdList = cdp->next;
302 >                        free(cdp);
303 >                }
304   }
305  
306 <
307 < static void
308 < load_angle_basis(       /* load custom BSDF angle basis */
204 <        ezxml_t wab
205 < )
306 > /* Free a spectral distribution function */
307 > void
308 > SDfreeSpectralDF(SDSpectralDF *df)
309   {
310 <        char    *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
311 <        ezxml_t wbb;
312 <        int     i;
210 <        
211 <        if (!abname || !*abname)
310 >        int     n;
311 >
312 >        if (df == NULL)
313                  return;
314 <        for (i = nabases; i--; )
315 <                if (!strcmp(abname, abase_list[i].name))
316 <                        return;         /* assume it's the same */
317 <        if (nabases >= MAXABASES)
318 <                error(INTERNAL, "too many angle bases");
218 <        strcpy(abase_list[nabases].name, abname);
219 <        abase_list[nabases].nangles = 0;
220 <        for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
221 <                        wbb != NULL; i++, wbb = wbb->next) {
222 <                if (i >= MAXLATS)
223 <                        error(INTERNAL, "too many latitudes in custom basis");
224 <                abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
225 <                                ezxml_child(ezxml_child(wbb,
226 <                                        "ThetaBounds"), "UpperTheta")));
227 <                if (!i)
228 <                        abase_list[nabases].lat[i].tmin =
229 <                                        -abase_list[nabases].lat[i+1].tmin;
230 <                else if (!FEQ(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
231 <                                        "ThetaBounds"), "LowerTheta"))),
232 <                                abase_list[nabases].lat[i].tmin))
233 <                        error(WARNING, "theta values disagree in custom basis");
234 <                abase_list[nabases].nangles +=
235 <                        abase_list[nabases].lat[i].nphis =
236 <                                atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
237 <        }
238 <        abase_list[nabases++].lat[i].nphis = 0;
314 >        SDfreeCumulativeCache(df);
315 >        for (n = df->ncomp; n-- > 0; )
316 >                if (df->comp[n].dist != NULL)
317 >                        (*df->comp[n].func->freeSC)(df->comp[n].dist);
318 >        free(df);
319   }
320  
321 <
322 < static double
323 < to_meters(              /* return factor to convert given unit to meters */
244 <        const char *unit
245 < )
321 > /* Shorten file path to useable BSDF name, removing suffix */
322 > void
323 > SDclipName(char *res, const char *fname)
324   {
325 <        if (unit == NULL) return(1.);           /* safe assumption? */
326 <        if (!strcasecmp(unit, "Meter")) return(1.);
327 <        if (!strcasecmp(unit, "Foot")) return(.3048);
328 <        if (!strcasecmp(unit, "Inch")) return(.0254);
329 <        if (!strcasecmp(unit, "Centimeter")) return(.01);
330 <        if (!strcasecmp(unit, "Millimeter")) return(.001);
331 <        sprintf(errmsg, "unknown dimensional unit '%s'", unit);
332 <        error(USER, errmsg);
325 >        const char      *cp, *dot = NULL;
326 >        
327 >        for (cp = fname; *cp; cp++)
328 >                if (*cp == '.')
329 >                        dot = cp;
330 >        if ((dot == NULL) | (dot < fname+2))
331 >                dot = cp;
332 >        if (dot - fname >= SDnameLn)
333 >                fname = dot - SDnameLn + 1;
334 >        while (fname < dot)
335 >                *res++ = *fname++;
336 >        *res = '\0';
337   }
338  
339 <
340 < static void
341 < load_geometry(          /* load geometric dimensions and description (if any) */
260 <        struct BSDF_data *dp,
261 <        ezxml_t wdb
262 < )
339 > /* Initialize an unused BSDF struct (simply clears to zeroes) */
340 > void
341 > SDclearBSDF(SDData *sd, const char *fname)
342   {
343 <        ezxml_t         geom;
265 <        double          cfact;
266 <        const char      *fmt, *mgfstr;
267 <
268 <        dp->dim[0] = dp->dim[1] = dp->dim[2] = 0;
269 <        dp->mgf = NULL;
270 <        if ((geom = ezxml_child(wdb, "Width")) != NULL)
271 <                dp->dim[0] = atof(ezxml_txt(geom)) *
272 <                                to_meters(ezxml_attr(geom, "unit"));
273 <        if ((geom = ezxml_child(wdb, "Height")) != NULL)
274 <                dp->dim[1] = atof(ezxml_txt(geom)) *
275 <                                to_meters(ezxml_attr(geom, "unit"));
276 <        if ((geom = ezxml_child(wdb, "Thickness")) != NULL)
277 <                dp->dim[2] = atof(ezxml_txt(geom)) *
278 <                                to_meters(ezxml_attr(geom, "unit"));
279 <        if ((geom = ezxml_child(wdb, "Geometry")) == NULL ||
280 <                        (mgfstr = ezxml_txt(geom)) == NULL)
343 >        if (sd == NULL)
344                  return;
345 <        if ((fmt = ezxml_attr(geom, "format")) != NULL &&
346 <                        strcasecmp(fmt, "MGF")) {
284 <                sprintf(errmsg, "unrecognized geometry format '%s'", fmt);
285 <                error(WARNING, errmsg);
345 >        memset(sd, 0, sizeof(SDData));
346 >        if (fname == NULL)
347                  return;
348 <        }
288 <        cfact = to_meters(ezxml_attr(geom, "unit"));
289 <        dp->mgf = (char *)malloc(strlen(mgfstr)+32);
290 <        if (dp->mgf == NULL)
291 <                error(SYSTEM, "out of memory in load_geometry");
292 <        if (cfact < 0.99 || cfact > 1.01)
293 <                sprintf(dp->mgf, "xf -s %.5f\n%s\nxf\n", cfact, mgfstr);
294 <        else
295 <                strcpy(dp->mgf, mgfstr);
348 >        SDclipName(sd->name, fname);
349   }
350  
351 <
352 < static void
353 < load_bsdf_data(         /* load BSDF distribution for this wavelength */
301 <        struct BSDF_data *dp,
302 <        ezxml_t wdb
303 < )
351 > /* Free data associated with BSDF struct */
352 > void
353 > SDfreeBSDF(SDData *sd)
354   {
355 <        char  *cbasis = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
306 <        char  *rbasis = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
307 <        char  *sdata;
308 <        int  i;
309 <        
310 <        if ((!cbasis || !*cbasis) | (!rbasis || !*rbasis)) {
311 <                error(WARNING, "missing column/row basis for BSDF");
355 >        if (sd == NULL)
356                  return;
357 +        if (sd->mgf != NULL) {
358 +                free(sd->mgf);
359 +                sd->mgf = NULL;
360          }
361 <        for (i = nabases; i--; )
362 <                if (!strcmp(cbasis, abase_list[i].name)) {
363 <                        dp->ninc = abase_list[i].nangles;
317 <                        dp->ib_priv = (void *)&abase_list[i];
318 <                        dp->ib_vec = ab_getvecR;
319 <                        dp->ib_ndx = ab_getndxR;
320 <                        dp->ib_ohm = ab_getohm;
321 <                        break;
322 <                }
323 <        if (i < 0) {
324 <                sprintf(errmsg, "undefined ColumnAngleBasis '%s'", cbasis);
325 <                error(WARNING, errmsg);
326 <                return;
361 >        if (sd->rf != NULL) {
362 >                SDfreeSpectralDF(sd->rf);
363 >                sd->rf = NULL;
364          }
365 <        for (i = nabases; i--; )
366 <                if (!strcmp(rbasis, abase_list[i].name)) {
367 <                        dp->nout = abase_list[i].nangles;
331 <                        dp->ob_priv = (void *)&abase_list[i];
332 <                        dp->ob_vec = ab_getvec;
333 <                        dp->ob_ndx = ab_getndx;
334 <                        dp->ob_ohm = ab_getohm;
335 <                        break;
336 <                }
337 <        if (i < 0) {
338 <                sprintf(errmsg, "undefined RowAngleBasis '%s'", cbasis);
339 <                error(WARNING, errmsg);
340 <                return;
365 >        if (sd->rb != NULL) {
366 >                SDfreeSpectralDF(sd->rb);
367 >                sd->rb = NULL;
368          }
369 <                                /* read BSDF data */
370 <        sdata  = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
371 <        if (!sdata || !*sdata) {
345 <                error(WARNING, "missing BSDF ScatteringData");
346 <                return;
369 >        if (sd->tf != NULL) {
370 >                SDfreeSpectralDF(sd->tf);
371 >                sd->tf = NULL;
372          }
373 <        dp->bsdf = (float *)malloc(sizeof(float)*dp->ninc*dp->nout);
374 <        if (dp->bsdf == NULL)
375 <                error(SYSTEM, "out of memory in load_bsdf_data");
351 <        for (i = 0; i < dp->ninc*dp->nout; i++) {
352 <                char  *sdnext = fskip(sdata);
353 <                if (sdnext == NULL) {
354 <                        error(WARNING, "bad/missing BSDF ScatteringData");
355 <                        free(dp->bsdf); dp->bsdf = NULL;
356 <                        return;
357 <                }
358 <                while (*sdnext && isspace(*sdnext))
359 <                        sdnext++;
360 <                if (*sdnext == ',') sdnext++;
361 <                dp->bsdf[i] = atof(sdata);
362 <                sdata = sdnext;
373 >        if (sd->tb != NULL) {
374 >                SDfreeSpectralDF(sd->tb);
375 >                sd->tb = NULL;
376          }
377 <        while (isspace(*sdata))
378 <                sdata++;
379 <        if (*sdata) {
380 <                sprintf(errmsg, "%d extra characters after BSDF ScatteringData",
381 <                                (int)strlen(sdata));
382 <                error(WARNING, errmsg);
370 <        }
377 >        sd->rLambFront.cieY = .0;
378 >        sd->rLambFront.spec.flags = 0;
379 >        sd->rLambBack.cieY = .0;
380 >        sd->rLambBack.spec.flags = 0;
381 >        sd->tLamb.cieY = .0;
382 >        sd->tLamb.spec.flags = 0;
383   }
384  
385 <
386 < static int
387 < check_bsdf_data(        /* check that BSDF data is sane */
376 <        struct BSDF_data *dp
377 < )
385 > /* Find writeable BSDF by name, or allocate new cache entry if absent */
386 > SDData *
387 > SDgetCache(const char *bname)
388   {
389 <        double          *omega_iarr, *omega_oarr;
390 <        double          dom, contrib, hemi_total, full_total;
381 <        int             nneg;
382 <        FVECT           v;
383 <        int             i, o;
389 >        struct SDCache_s        *sdl;
390 >        char                    sdnam[SDnameLn];
391  
392 <        if (dp == NULL || dp->bsdf == NULL)
393 <                return(0);
394 <        omega_iarr = (double *)calloc(dp->ninc, sizeof(double));
395 <        omega_oarr = (double *)calloc(dp->nout, sizeof(double));
396 <        if ((omega_iarr == NULL) | (omega_oarr == NULL))
397 <                error(SYSTEM, "out of memory in check_bsdf_data");
398 <                                        /* incoming projected solid angles */
399 <        hemi_total = .0;
393 <        for (i = dp->ninc; i--; ) {
394 <                dom = getBSDF_incohm(dp,i);
395 <                if (dom <= .0) {
396 <                        error(WARNING, "zero/negative incoming solid angle");
397 <                        continue;
392 >        if (bname == NULL)
393 >                return NULL;
394 >
395 >        SDclipName(sdnam, bname);
396 >        for (sdl = SDcacheList; sdl != NULL; sdl = sdl->next)
397 >                if (!strcmp(sdl->bsdf.name, sdnam)) {
398 >                        sdl->refcnt++;
399 >                        return &sdl->bsdf;
400                  }
401 <                if (!getBSDF_incvec(v,dp,i) || v[2] > FTINY) {
402 <                        error(WARNING, "illegal incoming BSDF direction");
403 <                        free(omega_iarr); free(omega_oarr);
404 <                        return(0);
405 <                }
406 <                hemi_total += omega_iarr[i] = dom * -v[2];
401 >
402 >        sdl = (struct SDCache_s *)calloc(1, sizeof(struct SDCache_s));
403 >        if (sdl == NULL)
404 >                return NULL;
405 >
406 >        strcpy(sdl->bsdf.name, sdnam);
407 >        sdl->next = SDcacheList;
408 >        SDcacheList = sdl;
409 >
410 >        sdl->refcnt = 1;
411 >        return &sdl->bsdf;
412 > }
413 >
414 > /* Get loaded BSDF from cache (or load and cache it on first call) */
415 > /* Report any problem to stderr and return NULL on failure */
416 > const SDData *
417 > SDcacheFile(const char *fname)
418 > {
419 >        SDData          *sd;
420 >        SDError         ec;
421 >        
422 >        if (fname == NULL || !*fname)
423 >                return NULL;
424 >        SDerrorDetail[0] = '\0';
425 >        /* PLACE MUTEX LOCK HERE FOR THREAD-SAFE */
426 >        if ((sd = SDgetCache(fname)) == NULL) {
427 >                SDreportError(SDEmemory, stderr);
428 >                return NULL;
429          }
430 <        if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
431 <                sprintf(errmsg, "incoming BSDF hemisphere off by %.1f%%",
432 <                                100.*(hemi_total/PI - 1.));
433 <                error(WARNING, errmsg);
430 >        if (!SDisLoaded(sd) && (ec = SDloadFile(sd, fname))) {
431 >                SDreportError(ec, stderr);
432 >                SDfreeCache(sd);
433 >                sd = NULL;
434          }
435 <        dom = PI / hemi_total;          /* fix normalization */
436 <        for (i = dp->ninc; i--; )
437 <                omega_iarr[i] *= dom;
414 <                                        /* outgoing projected solid angles */
415 <        hemi_total = .0;
416 <        for (o = dp->nout; o--; ) {
417 <                dom = getBSDF_outohm(dp,o);
418 <                if (dom <= .0) {
419 <                        error(WARNING, "zero/negative outgoing solid angle");
420 <                        continue;
421 <                }
422 <                if (!getBSDF_outvec(v,dp,o) || v[2] < -FTINY) {
423 <                        error(WARNING, "illegal outgoing BSDF direction");
424 <                        free(omega_iarr); free(omega_oarr);
425 <                        return(0);
426 <                }
427 <                hemi_total += omega_oarr[o] = dom * v[2];
428 <        }
429 <        if ((hemi_total > 1.02*PI) | (hemi_total < 0.98*PI)) {
430 <                sprintf(errmsg, "outgoing BSDF hemisphere off by %.1f%%",
431 <                                100.*(hemi_total/PI - 1.));
432 <                error(WARNING, errmsg);
433 <        }
434 <        dom = PI / hemi_total;          /* fix normalization */
435 <        for (o = dp->nout; o--; )
436 <                omega_oarr[o] *= dom;
437 <        nneg = 0;                       /* check outgoing totals */
438 <        for (i = 0; i < dp->ninc; i++) {
439 <                hemi_total = .0;
440 <                for (o = dp->nout; o--; ) {
441 <                        double  f = BSDF_value(dp,i,o);
442 <                        if (f >= .0)
443 <                                hemi_total += f*omega_oarr[o];
444 <                        else {
445 <                                nneg += (f < -FTINY);
446 <                                BSDF_value(dp,i,o) = .0f;
447 <                        }
448 <                }
449 <                if (hemi_total > 1.01) {
450 <                        sprintf(errmsg,
451 <                        "incoming BSDF direction %d passes %.1f%% of light",
452 <                                        i, 100.*hemi_total);
453 <                        error(WARNING, errmsg);
454 <                }
455 <        }
456 <        if (nneg) {
457 <                sprintf(errmsg, "%d negative BSDF values (ignored)", nneg);
458 <                error(WARNING, errmsg);
459 <        }
460 <        full_total = .0;                /* reverse roles and check again */
461 <        for (o = 0; o < dp->nout; o++) {
462 <                hemi_total = .0;
463 <                for (i = dp->ninc; i--; )
464 <                        hemi_total += BSDF_value(dp,i,o) * omega_iarr[i];
435 >        /* END MUTEX LOCK */
436 >        return sd;
437 > }
438  
439 <                if (hemi_total > 1.01) {
440 <                        sprintf(errmsg,
441 <                        "outgoing BSDF direction %d collects %.1f%% of light",
442 <                                        o, 100.*hemi_total);
443 <                        error(WARNING, errmsg);
439 > /* Free a BSDF from our cache (clear all if NULL) */
440 > void
441 > SDfreeCache(const SDData *sd)
442 > {
443 >        struct SDCache_s        *sdl, *sdLast = NULL;
444 >
445 >        if (sd == NULL) {               /* free entire list */
446 >                while ((sdl = SDcacheList) != NULL) {
447 >                        SDcacheList = sdl->next;
448 >                        SDfreeBSDF(&sdl->bsdf);
449 >                        free(sdl);
450                  }
451 <                full_total += hemi_total*omega_oarr[o];
451 >                return;
452          }
453 <        full_total /= PI;
454 <        if (full_total > 1.00001) {
455 <                sprintf(errmsg, "BSDF transfers %.4f%% of light",
456 <                                100.*full_total);
457 <                error(WARNING, errmsg);
453 >        for (sdl = SDcacheList; sdl != NULL; sdl = (sdLast=sdl)->next)
454 >                if (&sdl->bsdf == sd)
455 >                        break;
456 >        if (sdl == NULL || (sdl->refcnt -= (sdl->refcnt > 0)))
457 >                return;                 /* missing or still in use */
458 >                                        /* keep unreferenced data? */
459 >        if (SDisLoaded(sd) && SDretainSet) {
460 >                if (SDretainSet == SDretainAll)
461 >                        return;         /* keep everything */
462 >                                        /* else free cumulative data */
463 >                SDfreeCumulativeCache(sd->rf);
464 >                SDfreeCumulativeCache(sd->rb);
465 >                SDfreeCumulativeCache(sd->tf);
466 >                SDfreeCumulativeCache(sd->tb);
467 >                return;
468          }
469 <        free(omega_iarr); free(omega_oarr);
470 <        return(1);
469 >                                        /* remove from list and free */
470 >        if (sdLast == NULL)
471 >                SDcacheList = sdl->next;
472 >        else
473 >                sdLast->next = sdl->next;
474 >        SDfreeBSDF(&sdl->bsdf);
475 >        free(sdl);
476   }
477  
478 <
479 < struct BSDF_data *
480 < load_BSDF(              /* load BSDF data from file */
487 <        char *fname
488 < )
478 > /* Sample an individual BSDF component */
479 > SDError
480 > SDsampComponent(SDValue *sv, FVECT ioVec, double randX, SDComponent *sdc)
481   {
482 <        char                    *path;
483 <        ezxml_t                 fl, wtl, wld, wdb;
484 <        struct BSDF_data        *dp;
485 <        
486 <        path = getpath(fname, getrlibpath(), R_OK);
487 <        if (path == NULL) {
488 <                sprintf(errmsg, "cannot find BSDF file \"%s\"", fname);
489 <                error(WARNING, errmsg);
490 <                return(NULL);
482 >        float           coef[SDmaxCh];
483 >        SDError         ec;
484 >        FVECT           inVec;
485 >        const SDCDst    *cd;
486 >        double          d;
487 >        int             n;
488 >                                        /* check arguments */
489 >        if ((sv == NULL) | (ioVec == NULL) | (sdc == NULL))
490 >                return SDEargument;
491 >                                        /* get cumulative distribution */
492 >        VCOPY(inVec, ioVec);
493 >        sv->cieY = 0;
494 >        cd = (*sdc->func->getCDist)(inVec, sdc);
495 >        if (cd != NULL)
496 >                sv->cieY = cd->cTotal;
497 >        if (sv->cieY <= 1e-6) {         /* nothing to sample? */
498 >                sv->spec = c_dfcolor;
499 >                memset(ioVec, 0, sizeof(FVECT));
500 >                return SDEnone;
501          }
502 <        fl = ezxml_parse_file(path);
503 <        if (fl == NULL) {
504 <                sprintf(errmsg, "cannot open BSDF \"%s\"", path);
505 <                error(WARNING, errmsg);
506 <                return(NULL);
502 >                                        /* compute sample direction */
503 >        ec = (*sdc->func->sampCDist)(ioVec, randX, cd);
504 >        if (ec)
505 >                return ec;
506 >                                        /* get BSDF color */
507 >        n = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
508 >        if (n <= 0) {
509 >                strcpy(SDerrorDetail, "BSDF sample value error");
510 >                return SDEinternal;
511          }
512 <        if (ezxml_error(fl)[0]) {
513 <                sprintf(errmsg, "BSDF \"%s\" %s", path, ezxml_error(fl));
514 <                error(WARNING, errmsg);
515 <                ezxml_free(fl);
516 <                return(NULL);
512 >        sv->spec = sdc->cspec[0];
513 >        d = coef[0];
514 >        while (--n) {
515 >                c_cmix(&sv->spec, d, &sv->spec, coef[n], &sdc->cspec[n]);
516 >                d += coef[n];
517          }
518 <        if (strcmp(ezxml_name(fl), "WindowElement")) {
519 <                sprintf(errmsg,
520 <                        "BSDF \"%s\": top level node not 'WindowElement'",
515 <                                path);
516 <                error(WARNING, errmsg);
517 <                ezxml_free(fl);
518 <                return(NULL);
519 <        }
520 <        wtl = ezxml_child(ezxml_child(fl, "Optical"), "Layer");
521 <        load_angle_basis(ezxml_child(ezxml_child(wtl,
522 <                                "DataDefinition"), "AngleBasis"));
523 <        dp = (struct BSDF_data *)calloc(1, sizeof(struct BSDF_data));
524 <        load_geometry(dp, ezxml_child(wtl, "Material"));
525 <        for (wld = ezxml_child(wtl, "WavelengthData");
526 <                                wld != NULL; wld = wld->next) {
527 <                if (strcmp(ezxml_txt(ezxml_child(wld,"Wavelength")), "Visible"))
528 <                        continue;
529 <                wdb = ezxml_child(wld, "WavelengthDataBlock");
530 <                if (wdb == NULL) continue;
531 <                if (strcmp(ezxml_txt(ezxml_child(wdb,"WavelengthDataDirection")),
532 <                                        "Transmission Front"))
533 <                        continue;
534 <                load_bsdf_data(dp, wdb);        /* load front BTDF */
535 <                break;                          /* ignore the rest */
536 <        }
537 <        ezxml_free(fl);                         /* done with XML file */
538 <        if (!check_bsdf_data(dp)) {
539 <                sprintf(errmsg, "bad/missing BTDF data in \"%s\"", path);
540 <                error(WARNING, errmsg);
541 <                free_BSDF(dp);
542 <                dp = NULL;
543 <        }
544 <        return(dp);
518 >                                        /* make sure everything is set */
519 >        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
520 >        return SDEnone;
521   }
522  
523 + #define MS_MAXDIM       15
524  
525 + /* Convert 1-dimensional random variable to N-dimensional */
526   void
527 < free_BSDF(              /* free BSDF data structure */
550 <        struct BSDF_data *b
551 < )
527 > SDmultiSamp(double t[], int n, double randX)
528   {
529 <        if (b == NULL)
529 >        unsigned        nBits;
530 >        double          scale;
531 >        bitmask_t       ndx, coord[MS_MAXDIM];
532 >
533 >        if (n <= 0)                     /* check corner cases */
534                  return;
535 <        if (b->mgf != NULL)
536 <                free(b->mgf);
537 <        if (b->bsdf != NULL)
538 <                free(b->bsdf);
539 <        free(b);
535 >        if (randX < 0) randX = 0;
536 >        else if (randX >= 1.) randX = 0.999999999999999;
537 >        if (n == 1) {
538 >                t[0] = randX;
539 >                return;
540 >        }
541 >        while (n > MS_MAXDIM)           /* punt for higher dimensions */
542 >                t[--n] = rand()*(1./(RAND_MAX+.5));
543 >        nBits = (8*sizeof(bitmask_t) - 1) / n;
544 >        ndx = randX * (double)((bitmask_t)1 << (nBits*n));
545 >                                        /* get coordinate on Hilbert curve */
546 >        hilbert_i2c(n, nBits, ndx, coord);
547 >                                        /* convert back to [0,1) range */
548 >        scale = 1. / (double)((bitmask_t)1 << nBits);
549 >        while (n--)
550 >                t[n] = scale * ((double)coord[n] + rand()*(1./(RAND_MAX+.5)));
551   }
552  
553 + #undef MS_MAXDIM
554  
555 < int
556 < r_BSDF_incvec(          /* compute random input vector at given location */
557 <        FVECT v,
566 <        struct BSDF_data *b,
567 <        int i,
568 <        double rv,
569 <        MAT4 xm
570 < )
555 > /* Generate diffuse hemispherical sample */
556 > static void
557 > SDdiffuseSamp(FVECT outVec, int outFront, double randX)
558   {
559 <        FVECT   pert;
560 <        double  rad;
561 <        int     j;
562 <        
563 <        if (!getBSDF_incvec(v, b, i))
564 <                return(0);
565 <        rad = sqrt(getBSDF_incohm(b, i) / PI);
579 <        multisamp(pert, 3, rv);
580 <        for (j = 0; j < 3; j++)
581 <                v[j] += rad*(2.*pert[j] - 1.);
582 <        if (xm != NULL)
583 <                multv3(v, v, xm);
584 <        return(normalize(v) != 0.0);
559 >                                        /* convert to position on hemisphere */
560 >        SDmultiSamp(outVec, 2, randX);
561 >        SDsquare2disk(outVec, outVec[0], outVec[1]);
562 >        outVec[2] = 1. - outVec[0]*outVec[0] - outVec[1]*outVec[1];
563 >        outVec[2] = sqrt(outVec[2]*(outVec[2]>0));
564 >        if (!outFront)                  /* going out back? */
565 >                outVec[2] = -outVec[2];
566   }
567  
568 + /* Query projected solid angle coverage for non-diffuse BSDF direction */
569 + SDError
570 + SDsizeBSDF(double *projSA, const FVECT v1, const RREAL *v2,
571 +                                int qflags, const SDData *sd)
572 + {
573 +        SDSpectralDF    *rdf, *tdf;
574 +        SDError         ec;
575 +        int             i;
576 +                                        /* check arguments */
577 +        if ((projSA == NULL) | (v1 == NULL) | (sd == NULL))
578 +                return SDEargument;
579 +                                        /* initialize extrema */
580 +        switch (qflags) {
581 +        case SDqueryMax:
582 +                projSA[0] = .0;
583 +                break;
584 +        case SDqueryMin+SDqueryMax:
585 +                projSA[1] = .0;
586 +                /* fall through */
587 +        case SDqueryMin:
588 +                projSA[0] = 10.;
589 +                break;
590 +        case 0:
591 +                return SDEargument;
592 +        }
593 +        if (v1[2] > 0) {                /* front surface query? */
594 +                rdf = sd->rf;
595 +                tdf = (sd->tf != NULL) ? sd->tf : sd->tb;
596 +        } else {
597 +                rdf = sd->rb;
598 +                tdf = (sd->tb != NULL) ? sd->tb : sd->tf;
599 +        }
600 +        if (v2 != NULL) {               /* bidirectional? */
601 +                if (v1[2] > 0 ^ v2[2] > 0)
602 +                        rdf = NULL;
603 +                else
604 +                        tdf = NULL;
605 +        }
606 +        ec = SDEdata;                   /* run through components */
607 +        for (i = (rdf==NULL) ? 0 : rdf->ncomp; i--; ) {
608 +                ec = (*rdf->comp[i].func->queryProjSA)(projSA, v1, v2,
609 +                                                qflags, &rdf->comp[i]);
610 +                if (ec)
611 +                        return ec;
612 +        }
613 +        for (i = (tdf==NULL) ? 0 : tdf->ncomp; i--; ) {
614 +                ec = (*tdf->comp[i].func->queryProjSA)(projSA, v1, v2,
615 +                                                qflags, &tdf->comp[i]);
616 +                if (ec)
617 +                        return ec;
618 +        }
619 +        if (ec) {                       /* all diffuse? */
620 +                projSA[0] = M_PI;
621 +                if (qflags == SDqueryMin+SDqueryMax)
622 +                        projSA[1] = M_PI;
623 +        } else if (qflags == SDqueryMin+SDqueryMax && projSA[0] > projSA[1])
624 +                projSA[0] = projSA[1];
625 +        return SDEnone;
626 + }
627  
628 < int
629 < r_BSDF_outvec(          /* compute random output vector at given location */
630 <        FVECT v,
591 <        struct BSDF_data *b,
592 <        int o,
593 <        double rv,
594 <        MAT4 xm
595 < )
628 > /* Return BSDF for the given incident and scattered ray vectors */
629 > SDError
630 > SDevalBSDF(SDValue *sv, const FVECT outVec, const FVECT inVec, const SDData *sd)
631   {
632 <        FVECT   pert;
633 <        double  rad;
634 <        int     j;
635 <        
636 <        if (!getBSDF_outvec(v, b, o))
637 <                return(0);
638 <        rad = sqrt(getBSDF_outohm(b, o) / PI);
639 <        multisamp(pert, 3, rv);
640 <        for (j = 0; j < 3; j++)
641 <                v[j] += rad*(2.*pert[j] - 1.);
642 <        if (xm != NULL)
643 <                multv3(v, v, xm);
644 <        return(normalize(v) != 0.0);
632 >        int             inFront, outFront;
633 >        SDSpectralDF    *sdf;
634 >        float           coef[SDmaxCh];
635 >        int             nch, i;
636 >                                        /* check arguments */
637 >        if ((sv == NULL) | (outVec == NULL) | (inVec == NULL) | (sd == NULL))
638 >                return SDEargument;
639 >                                        /* whose side are we on? */
640 >        inFront = (inVec[2] > 0);
641 >        outFront = (outVec[2] > 0);
642 >                                        /* start with diffuse portion */
643 >        if (inFront & outFront) {
644 >                *sv = sd->rLambFront;
645 >                sdf = sd->rf;
646 >        } else if (!(inFront | outFront)) {
647 >                *sv = sd->rLambBack;
648 >                sdf = sd->rb;
649 >        } else if (outFront) {
650 >                *sv = sd->tLamb;
651 >                sdf = (sd->tf != NULL) ? sd->tf : sd->tb;
652 >        } else /* inFront & !outFront */ {
653 >                *sv = sd->tLamb;
654 >                sdf = (sd->tb != NULL) ? sd->tb : sd->tf;
655 >        }
656 >        sv->cieY *= 1./M_PI;
657 >                                        /* add non-diffuse components */
658 >        i = (sdf != NULL) ? sdf->ncomp : 0;
659 >        while (i-- > 0) {
660 >                nch = (*sdf->comp[i].func->getBSDFs)(coef, outVec, inVec,
661 >                                                        &sdf->comp[i]);
662 >                while (nch-- > 0) {
663 >                        c_cmix(&sv->spec, sv->cieY, &sv->spec,
664 >                                        coef[nch], &sdf->comp[i].cspec[nch]);
665 >                        sv->cieY += coef[nch];
666 >                }
667 >        }
668 >                                        /* make sure everything is set */
669 >        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
670 >        return SDEnone;
671   }
672  
673 <
674 < static int
675 < addrot(                 /* compute rotation (x,y,z) => (xp,yp,zp) */
615 <        char *xfarg[],
616 <        FVECT xp,
617 <        FVECT yp,
618 <        FVECT zp
619 < )
673 > /* Compute directional hemispherical scattering at this incident angle */
674 > double
675 > SDdirectHemi(const FVECT inVec, int sflags, const SDData *sd)
676   {
677 <        static char     bufs[3][16];
678 <        int     bn = 0;
679 <        char    **xfp = xfarg;
680 <        double  theta;
677 >        double          hsum;
678 >        SDSpectralDF    *rdf, *tdf;
679 >        const SDCDst    *cd;
680 >        int             i;
681 >                                        /* check arguments */
682 >        if ((inVec == NULL) | (sd == NULL))
683 >                return .0;
684 >                                        /* gather diffuse components */
685 >        if (inVec[2] > 0) {
686 >                hsum = sd->rLambFront.cieY;
687 >                rdf = sd->rf;
688 >                tdf = (sd->tf != NULL) ? sd->tf : sd->tb;
689 >        } else /* !inFront */ {
690 >                hsum = sd->rLambBack.cieY;
691 >                rdf = sd->rb;
692 >                tdf = (sd->tb != NULL) ? sd->tb : sd->tf;
693 >        }
694 >        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
695 >                hsum = .0;
696 >        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
697 >                hsum += sd->tLamb.cieY;
698 >                                        /* gather non-diffuse components */
699 >        i = (((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR) &
700 >                        (rdf != NULL)) ? rdf->ncomp : 0;
701 >        while (i-- > 0) {               /* non-diffuse reflection */
702 >                cd = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
703 >                if (cd != NULL)
704 >                        hsum += cd->cTotal;
705 >        }
706 >        i = (((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT) &
707 >                        (tdf != NULL)) ? tdf->ncomp : 0;
708 >        while (i-- > 0) {               /* non-diffuse transmission */
709 >                cd = (*tdf->comp[i].func->getCDist)(inVec, &tdf->comp[i]);
710 >                if (cd != NULL)
711 >                        hsum += cd->cTotal;
712 >        }
713 >        return hsum;
714 > }
715  
716 <        if (yp[2]*yp[2] + zp[2]*zp[2] < 2.*FTINY*FTINY) {
717 <                /* Special case for X' along Z-axis */
718 <                theta = -atan2(yp[0], yp[1]);
719 <                *xfp++ = "-ry";
720 <                *xfp++ = xp[2] < 0.0 ? "90" : "-90";
721 <                *xfp++ = "-rz";
722 <                sprintf(bufs[bn], "%f", theta*(180./PI));
723 <                *xfp++ = bufs[bn++];
724 <                return(xfp - xfarg);
716 > /* Sample BSDF direction based on the given random variable */
717 > SDError
718 > SDsampBSDF(SDValue *sv, FVECT ioVec, double randX, int sflags, const SDData *sd)
719 > {
720 >        SDError         ec;
721 >        FVECT           inVec;
722 >        int             inFront;
723 >        SDSpectralDF    *rdf, *tdf;
724 >        double          rdiff;
725 >        float           coef[SDmaxCh];
726 >        int             i, j, n, nr;
727 >        SDComponent     *sdc;
728 >        const SDCDst    **cdarr = NULL;
729 >                                        /* check arguments */
730 >        if ((sv == NULL) | (ioVec == NULL) | (sd == NULL) |
731 >                        (randX < 0) | (randX >= 1.))
732 >                return SDEargument;
733 >                                        /* whose side are we on? */
734 >        VCOPY(inVec, ioVec);
735 >        inFront = (inVec[2] > 0);
736 >                                        /* remember diffuse portions */
737 >        if (inFront) {
738 >                *sv = sd->rLambFront;
739 >                rdf = sd->rf;
740 >                tdf = (sd->tf != NULL) ? sd->tf : sd->tb;
741 >        } else /* !inFront */ {
742 >                *sv = sd->rLambBack;
743 >                rdf = sd->rb;
744 >                tdf = (sd->tb != NULL) ? sd->tb : sd->tf;
745          }
746 <        theta = atan2(yp[2], zp[2]);
747 <        if (!FEQ(theta,0.0)) {
748 <                *xfp++ = "-rx";
749 <                sprintf(bufs[bn], "%f", theta*(180./PI));
750 <                *xfp++ = bufs[bn++];
746 >        if ((sflags & SDsampDf+SDsampR) != SDsampDf+SDsampR)
747 >                sv->cieY = .0;
748 >        rdiff = sv->cieY;
749 >        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT)
750 >                sv->cieY += sd->tLamb.cieY;
751 >                                        /* gather non-diffuse components */
752 >        i = nr = (((sflags & SDsampSp+SDsampR) == SDsampSp+SDsampR) &
753 >                        (rdf != NULL)) ? rdf->ncomp : 0;
754 >        j = (((sflags & SDsampSp+SDsampT) == SDsampSp+SDsampT) &
755 >                        (tdf != NULL)) ? tdf->ncomp : 0;
756 >        n = i + j;
757 >        if (n > 0 && (cdarr = (const SDCDst **)malloc(n*sizeof(SDCDst *))) == NULL)
758 >                return SDEmemory;
759 >        while (j-- > 0) {               /* non-diffuse transmission */
760 >                cdarr[i+j] = (*tdf->comp[j].func->getCDist)(inVec, &tdf->comp[j]);
761 >                if (cdarr[i+j] == NULL)
762 >                        cdarr[i+j] = &SDemptyCD;
763 >                sv->cieY += cdarr[i+j]->cTotal;
764          }
765 <        theta = asin(-xp[2]);
766 <        if (!FEQ(theta,0.0)) {
767 <                *xfp++ = "-ry";
768 <                sprintf(bufs[bn], " %f", theta*(180./PI));
769 <                *xfp++ = bufs[bn++];
765 >        while (i-- > 0) {               /* non-diffuse reflection */
766 >                cdarr[i] = (*rdf->comp[i].func->getCDist)(inVec, &rdf->comp[i]);
767 >                if (cdarr[i] == NULL)
768 >                        cdarr[i] = &SDemptyCD;
769 >                sv->cieY += cdarr[i]->cTotal;
770          }
771 <        theta = atan2(xp[1], xp[0]);
772 <        if (!FEQ(theta,0.0)) {
773 <                *xfp++ = "-rz";
774 <                sprintf(bufs[bn], "%f", theta*(180./PI));
652 <                *xfp++ = bufs[bn++];
771 >        if (sv->cieY <= 1e-6) {         /* anything to sample? */
772 >                sv->cieY = .0;
773 >                memset(ioVec, 0, sizeof(FVECT));
774 >                return SDEnone;
775          }
776 <        *xfp = NULL;
777 <        return(xfp - xfarg);
776 >                                        /* scale random variable */
777 >        randX *= sv->cieY;
778 >                                        /* diffuse reflection? */
779 >        if (randX < rdiff) {
780 >                SDdiffuseSamp(ioVec, inFront, randX/rdiff);
781 >                goto done;
782 >        }
783 >        randX -= rdiff;
784 >                                        /* diffuse transmission? */
785 >        if ((sflags & SDsampDf+SDsampT) == SDsampDf+SDsampT) {
786 >                if (randX < sd->tLamb.cieY) {
787 >                        sv->spec = sd->tLamb.spec;
788 >                        SDdiffuseSamp(ioVec, !inFront, randX/sd->tLamb.cieY);
789 >                        goto done;
790 >                }
791 >                randX -= sd->tLamb.cieY;
792 >        }
793 >                                        /* else one of cumulative dist. */
794 >        for (i = 0; i < n && randX > cdarr[i]->cTotal; i++)
795 >                randX -= cdarr[i]->cTotal;
796 >        if (i >= n)
797 >                return SDEinternal;
798 >                                        /* compute sample direction */
799 >        sdc = (i < nr) ? &rdf->comp[i] : &tdf->comp[i-nr];
800 >        ec = (*sdc->func->sampCDist)(ioVec, randX/cdarr[i]->cTotal, cdarr[i]);
801 >        if (ec)
802 >                return ec;
803 >                                        /* compute color */
804 >        j = (*sdc->func->getBSDFs)(coef, ioVec, inVec, sdc);
805 >        if (j <= 0) {
806 >                sprintf(SDerrorDetail, "BSDF \"%s\" sampling value error",
807 >                                sd->name);
808 >                return SDEinternal;
809 >        }
810 >        sv->spec = sdc->cspec[0];
811 >        rdiff = coef[0];
812 >        while (--j) {
813 >                c_cmix(&sv->spec, rdiff, &sv->spec, coef[j], &sdc->cspec[j]);
814 >                rdiff += coef[j];
815 >        }
816 > done:
817 >        if (cdarr != NULL)
818 >                free(cdarr);
819 >                                        /* make sure everything is set */
820 >        c_ccvt(&sv->spec, C_CSXY+C_CSSPEC);
821 >        return SDEnone;
822   }
823  
824 + /* Compute World->BSDF transform from surface normal and up (Y) vector */
825 + SDError
826 + SDcompXform(RREAL vMtx[3][3], const FVECT sNrm, const FVECT uVec)
827 + {
828 +        if ((vMtx == NULL) | (sNrm == NULL) | (uVec == NULL))
829 +                return SDEargument;
830 +        VCOPY(vMtx[2], sNrm);
831 +        if (normalize(vMtx[2]) == 0)
832 +                return SDEargument;
833 +        fcross(vMtx[0], uVec, vMtx[2]);
834 +        if (normalize(vMtx[0]) == 0)
835 +                return SDEargument;
836 +        fcross(vMtx[1], vMtx[2], vMtx[0]);
837 +        return SDEnone;
838 + }
839  
840 < int
841 < getBSDF_xfm(            /* compute BSDF orient. -> world orient. transform */
842 <        MAT4 xm,
662 <        FVECT nrm,
663 <        UpDir ud,
664 <        char *xfbuf
665 < )
840 > /* Compute inverse transform */
841 > SDError
842 > SDinvXform(RREAL iMtx[3][3], RREAL vMtx[3][3])
843   {
844 <        char    *xfargs[7];
845 <        XF      myxf;
669 <        FVECT   updir, xdest, ydest;
670 <        int     i;
844 >        RREAL   mTmp[3][3];
845 >        double  d;
846  
847 <        updir[0] = updir[1] = updir[2] = 0.;
848 <        switch (ud) {
849 <        case UDzneg:
850 <                updir[2] = -1.;
851 <                break;
852 <        case UDyneg:
853 <                updir[1] = -1.;
854 <                break;
855 <        case UDxneg:
856 <                updir[0] = -1.;
682 <                break;
683 <        case UDxpos:
684 <                updir[0] = 1.;
685 <                break;
686 <        case UDypos:
687 <                updir[1] = 1.;
688 <                break;
689 <        case UDzpos:
690 <                updir[2] = 1.;
691 <                break;
692 <        case UDunknown:
693 <                return(0);
847 >        if ((iMtx == NULL) | (vMtx == NULL))
848 >                return SDEargument;
849 >                                        /* compute determinant */
850 >        mTmp[0][0] = vMtx[2][2]*vMtx[1][1] - vMtx[2][1]*vMtx[1][2];
851 >        mTmp[0][1] = vMtx[2][1]*vMtx[0][2] - vMtx[2][2]*vMtx[0][1];
852 >        mTmp[0][2] = vMtx[1][2]*vMtx[0][1] - vMtx[1][1]*vMtx[0][2];
853 >        d = vMtx[0][0]*mTmp[0][0] + vMtx[1][0]*mTmp[0][1] + vMtx[2][0]*mTmp[0][2];
854 >        if (d == 0) {
855 >                strcpy(SDerrorDetail, "Zero determinant in matrix inversion");
856 >                return SDEargument;
857          }
858 <        fcross(xdest, updir, nrm);
859 <        if (normalize(xdest) == 0.0)
860 <                return(0);
861 <        fcross(ydest, nrm, xdest);
862 <        xf(&myxf, addrot(xfargs, xdest, ydest, nrm), xfargs);
863 <        copymat4(xm, myxf.xfm);
864 <        if (xfbuf == NULL)
865 <                return(1);
866 <                                /* return xf arguments as well */
867 <        for (i = 0; xfargs[i] != NULL; i++) {
868 <                *xfbuf++ = ' ';
869 <                strcpy(xfbuf, xfargs[i]);
870 <                while (*xfbuf) ++xfbuf;
858 >        d = 1./d;                       /* invert matrix */
859 >        mTmp[0][0] *= d; mTmp[0][1] *= d; mTmp[0][2] *= d;
860 >        mTmp[1][0] = d*(vMtx[2][0]*vMtx[1][2] - vMtx[2][2]*vMtx[1][0]);
861 >        mTmp[1][1] = d*(vMtx[2][2]*vMtx[0][0] - vMtx[2][0]*vMtx[0][2]);
862 >        mTmp[1][2] = d*(vMtx[1][0]*vMtx[0][2] - vMtx[1][2]*vMtx[0][0]);
863 >        mTmp[2][0] = d*(vMtx[2][1]*vMtx[1][0] - vMtx[2][0]*vMtx[1][1]);
864 >        mTmp[2][1] = d*(vMtx[2][0]*vMtx[0][1] - vMtx[2][1]*vMtx[0][0]);
865 >        mTmp[2][2] = d*(vMtx[1][1]*vMtx[0][0] - vMtx[1][0]*vMtx[0][1]);
866 >        memcpy(iMtx, mTmp, sizeof(mTmp));
867 >        return SDEnone;
868 > }
869 >
870 > /* Transform and normalize direction (column) vector */
871 > SDError
872 > SDmapDir(FVECT resVec, RREAL vMtx[3][3], const FVECT inpVec)
873 > {
874 >        FVECT   vTmp;
875 >
876 >        if ((resVec == NULL) | (inpVec == NULL))
877 >                return SDEargument;
878 >        if (vMtx == NULL) {             /* assume they just want to normalize */
879 >                if (resVec != inpVec)
880 >                        VCOPY(resVec, inpVec);
881 >                return (normalize(resVec) > 0) ? SDEnone : SDEargument;
882          }
883 <        return(1);
883 >        vTmp[0] = DOT(vMtx[0], inpVec);
884 >        vTmp[1] = DOT(vMtx[1], inpVec);
885 >        vTmp[2] = DOT(vMtx[2], inpVec);
886 >        if (normalize(vTmp) == 0)
887 >                return SDEargument;
888 >        VCOPY(resVec, vTmp);
889 >        return SDEnone;
890   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines