ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_m.c
Revision: 3.4
Committed: Sat Feb 19 01:48:59 2011 UTC (13 years, 2 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 3.3: +16 -43 lines
Log Message:
Minor changes and fixes -- first working version of BSDF material

File Contents

# User Rev Content
1 greg 3.2 #ifndef lint
2 greg 3.4 static const char RCSid[] = "$Id: bsdf_m.c,v 3.3 2011/02/18 02:41:55 greg Exp $";
3 greg 3.2 #endif
4 greg 3.1 /*
5     * bsdf_m.c
6     *
7     * Definitions supporting BSDF matrices
8     *
9     * Created by Greg Ward on 2/2/11.
10     * Copyright 2011 Anyhere Software. All rights reserved.
11     *
12     */
13    
14 greg 3.3 #include "rtio.h"
15 greg 3.1 #include <stdlib.h>
16     #include <math.h>
17     #include <ctype.h>
18     #include "ezxml.h"
19     #include "bsdf.h"
20     #include "bsdf_m.h"
21    
22     /* Function return codes */
23     #define RC_GOOD 1
24     #define RC_FAIL 0
25     #define RC_FORMERR (-1)
26     #define RC_DATERR (-2)
27     #define RC_UNSUPP (-3)
28     #define RC_INTERR (-4)
29     #define RC_MEMERR (-5)
30    
31     #define MAXLATS 46 /* maximum number of latitudes */
32    
33     /* BSDF angle specification */
34     typedef struct {
35     char name[64]; /* basis name */
36     int nangles; /* total number of directions */
37     struct {
38     float tmin; /* starting theta */
39     int nphis; /* number of phis (0 term) */
40     } lat[MAXLATS+1]; /* latitudes */
41     } ANGLE_BASIS;
42    
43     #define MAXABASES 7 /* limit on defined bases */
44    
45     static ANGLE_BASIS abase_list[MAXABASES] = {
46     {
47     "LBNL/Klems Full", 145,
48     { {-5., 1},
49     {5., 8},
50     {15., 16},
51     {25., 20},
52     {35., 24},
53     {45., 24},
54     {55., 24},
55     {65., 16},
56     {75., 12},
57     {90., 0} }
58     }, {
59     "LBNL/Klems Half", 73,
60     { {-6.5, 1},
61     {6.5, 8},
62     {19.5, 12},
63     {32.5, 16},
64     {46.5, 20},
65     {61.5, 12},
66     {76.5, 4},
67     {90., 0} }
68     }, {
69     "LBNL/Klems Quarter", 41,
70     { {-9., 1},
71     {9., 8},
72     {27., 12},
73     {46., 12},
74     {66., 8},
75     {90., 0} }
76     }
77     };
78    
79     static int nabases = 3; /* current number of defined bases */
80    
81     static int
82     fequal(double a, double b)
83     {
84     if (b != .0)
85     a = a/b - 1.;
86     return (a <= 1e-6) & (a >= -1e-6);
87     }
88    
89     /* returns the name of the given tag */
90     #ifdef ezxml_name
91     #undef ezxml_name
92     static char *
93     ezxml_name(ezxml_t xml)
94     {
95     if (xml == NULL)
96     return NULL;
97     return xml->name;
98     }
99     #endif
100    
101     /* returns the given tag's character content or empty string if none */
102     #ifdef ezxml_txt
103     #undef ezxml_txt
104     static char *
105     ezxml_txt(ezxml_t xml)
106     {
107     if (xml == NULL)
108     return "";
109     return xml->txt;
110     }
111     #endif
112    
113     /* Convert error to standard BSDF code */
114     static SDError
115     convert_errcode(int ec)
116     {
117     switch (ec) {
118     case RC_GOOD:
119     return SDEnone;
120     case RC_FORMERR:
121     return SDEformat;
122     case RC_DATERR:
123     return SDEdata;
124     case RC_UNSUPP:
125     return SDEsupport;
126     case RC_INTERR:
127     return SDEinternal;
128     case RC_MEMERR:
129     return SDEmemory;
130     }
131     return SDEunknown;
132     }
133    
134     /* Allocate a BSDF matrix of the given size */
135     static SDMat *
136     SDnewMatrix(int ni, int no)
137     {
138     SDMat *sm;
139    
140     if ((ni <= 0) | (no <= 0)) {
141     strcpy(SDerrorDetail, "Empty BSDF matrix request");
142     return NULL;
143     }
144     sm = (SDMat *)malloc(sizeof(SDMat) + (ni*no - 1)*sizeof(float));
145     if (sm == NULL) {
146     sprintf(SDerrorDetail, "Cannot allocate %dx%d BSDF matrix",
147     ni, no);
148     return NULL;
149     }
150     memset(sm, 0, sizeof(SDMat)-sizeof(float));
151     sm->ninc = ni;
152     sm->nout = no;
153    
154     return sm;
155     }
156    
157     /* Free a BSDF matrix */
158     #define SDfreeMatrix free
159    
160     /* get vector for this angle basis index */
161     static int
162     ab_getvec(FVECT v, int ndx, double randX, void *p)
163     {
164     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
165     double rx[2];
166     int li;
167     double pol, azi, d;
168    
169     if ((ndx < 0) | (ndx >= ab->nangles))
170     return RC_FAIL;
171     for (li = 0; ndx >= ab->lat[li].nphis; li++)
172     ndx -= ab->lat[li].nphis;
173     SDmultiSamp(rx, 2, randX);
174     pol = M_PI/180.*( (1.-rx[0])*ab->lat[li].tmin +
175     rx[0]*ab->lat[li+1].tmin );
176     azi = 2.*M_PI*(ndx + rx[1] - .5)/ab->lat[li].nphis;
177     v[2] = d = cos(pol);
178     d = sqrt(1. - d*d); /* sin(pol) */
179     v[0] = cos(azi)*d;
180     v[1] = sin(azi)*d;
181     return RC_GOOD;
182     }
183    
184     /* get index corresponding to the given vector */
185     static int
186     ab_getndx(const FVECT v, void *p)
187     {
188     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
189     int li, ndx;
190     double pol, azi, d;
191    
192     if (v == NULL)
193     return -1;
194     if ((v[2] < .0) | (v[2] > 1.0))
195     return -1;
196     pol = 180.0/M_PI*acos(v[2]);
197     azi = 180.0/M_PI*atan2(v[1], v[0]);
198     if (azi < 0.0) azi += 360.0;
199     for (li = 1; ab->lat[li].tmin <= pol; li++)
200     if (!ab->lat[li].nphis)
201     return -1;
202     --li;
203     ndx = (int)((1./360.)*azi*ab->lat[li].nphis + 0.5);
204     if (ndx >= ab->lat[li].nphis) ndx = 0;
205     while (li--)
206     ndx += ab->lat[li].nphis;
207     return ndx;
208     }
209    
210     /* compute square of real value */
211     static double sq(double x) { return x*x; }
212    
213     /* get projected solid angle for this angle basis index */
214     static double
215     ab_getohm(int ndx, void *p)
216     {
217     static int last_li = -1;
218     static double last_ohm;
219     ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
220     int li;
221     double theta, theta1;
222    
223     if ((ndx < 0) | (ndx >= ab->nangles))
224     return -1.;
225     for (li = 0; ndx >= ab->lat[li].nphis; li++)
226     ndx -= ab->lat[li].nphis;
227     if (li == last_li) /* cached latitude? */
228     return last_ohm;
229     last_li = li;
230     theta1 = M_PI/180. * ab->lat[li+1].tmin;
231     if (ab->lat[li].nphis == 1) /* special case */
232     return last_ohm = M_PI*(1. - sq(cos(theta1)));
233     theta = M_PI/180. * ab->lat[li].tmin;
234     return last_ohm = M_PI*(sq(cos(theta)) - sq(cos(theta1))) /
235     (double)ab->lat[li].nphis;
236     }
237    
238     /* get reverse vector for this angle basis index */
239     static int
240     ab_getvecR(FVECT v, int ndx, double randX, void *p)
241     {
242     int na = (*(ANGLE_BASIS *)p).nangles;
243    
244     if (!ab_getvec(v, ndx, randX, p))
245     return RC_FAIL;
246    
247     v[0] = -v[0];
248     v[1] = -v[1];
249     v[2] = -v[2];
250    
251     return RC_GOOD;
252     }
253    
254     /* get index corresponding to the reverse vector */
255     static int
256     ab_getndxR(const FVECT v, void *p)
257     {
258     FVECT v2;
259    
260     v2[0] = -v[0];
261     v2[1] = -v[1];
262     v2[2] = -v[2];
263    
264     return ab_getndx(v2, p);
265     }
266    
267     /* load custom BSDF angle basis */
268     static int
269     load_angle_basis(ezxml_t wab)
270     {
271     char *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
272     ezxml_t wbb;
273     int i;
274    
275     if (!abname || !*abname)
276     return RC_FAIL;
277     for (i = nabases; i--; )
278     if (!strcasecmp(abname, abase_list[i].name))
279     return RC_GOOD; /* assume it's the same */
280     if (nabases >= MAXABASES) {
281     sprintf(SDerrorDetail, "Out of angle bases reading '%s'",
282     abname);
283     return RC_INTERR;
284     }
285     strcpy(abase_list[nabases].name, abname);
286     abase_list[nabases].nangles = 0;
287     for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
288     wbb != NULL; i++, wbb = wbb->next) {
289     if (i >= MAXLATS) {
290     sprintf(SDerrorDetail, "Too many latitudes for '%s'",
291     abname);
292     return RC_INTERR;
293     }
294     abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
295     ezxml_child(ezxml_child(wbb,
296     "ThetaBounds"), "UpperTheta")));
297     if (!i)
298     abase_list[nabases].lat[i].tmin =
299     -abase_list[nabases].lat[i+1].tmin;
300     else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
301     "ThetaBounds"), "LowerTheta"))),
302     abase_list[nabases].lat[i].tmin)) {
303     sprintf(SDerrorDetail, "Theta values disagree in '%s'",
304     abname);
305     return RC_DATERR;
306     }
307     abase_list[nabases].nangles +=
308     abase_list[nabases].lat[i].nphis =
309     atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
310     if (abase_list[nabases].lat[i].nphis <= 0 ||
311     (abase_list[nabases].lat[i].nphis == 1 &&
312     abase_list[nabases].lat[i].tmin > FTINY)) {
313     sprintf(SDerrorDetail, "Illegal phi count in '%s'",
314     abname);
315     return RC_DATERR;
316     }
317     }
318     abase_list[nabases++].lat[i].nphis = 0;
319     return RC_GOOD;
320     }
321    
322     /* compute min. proj. solid angle and max. direct hemispherical scattering */
323     static int
324     get_extrema(SDSpectralDF *df)
325     {
326     SDMat *dp = (SDMat *)df->comp[0].dist;
327     double *ohma;
328     int i, o;
329     /* initialize extrema */
330     df->minProjSA = M_PI;
331     df->maxHemi = .0;
332     ohma = (double *)malloc(dp->nout*sizeof(double));
333     if (ohma == NULL)
334     return RC_MEMERR;
335     /* get outgoing solid angles */
336     for (o = dp->nout; o--; )
337     if ((ohma[o] = mBSDF_outohm(dp,o)) < df->minProjSA)
338     df->minProjSA = ohma[o];
339     /* compute hemispherical sums */
340     for (i = dp->ninc; i--; ) {
341     double hemi = .0;
342     for (o = dp->nout; o--; )
343     hemi += ohma[o] * mBSDF_value(dp, i, o);
344     if (hemi > df->maxHemi)
345     df->maxHemi = hemi;
346     }
347     free(ohma);
348     /* need incoming solid angles, too? */
349     if (dp->ninc < dp->nout || dp->ib_ohm != dp->ob_ohm ||
350     dp->ib_priv != dp->ob_priv) {
351     double ohm;
352     for (i = dp->ninc; i--; )
353     if ((ohm = mBSDF_incohm(dp,i)) < df->minProjSA)
354     df->minProjSA = ohm;
355     }
356     return (df->maxHemi <= 1.01);
357     }
358    
359     /* load BSDF distribution for this wavelength */
360     static int
361     load_bsdf_data(SDData *sd, ezxml_t wdb, int rowinc)
362     {
363     SDSpectralDF *df;
364     SDMat *dp;
365     char *sdata;
366     int inbi, outbi;
367     int i;
368     /* allocate BSDF component */
369     sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
370     if (!strcasecmp(sdata, "Transmission Front")) {
371     if (sd->tf != NULL)
372     SDfreeSpectralDF(sd->tf);
373     if ((sd->tf = SDnewSpectralDF(1)) == NULL)
374     return RC_MEMERR;
375     df = sd->tf;
376     } else if (!strcasecmp(sdata, "Reflection Front")) {
377     if (sd->rf != NULL)
378     SDfreeSpectralDF(sd->rf);
379     if ((sd->rf = SDnewSpectralDF(1)) == NULL)
380     return RC_MEMERR;
381     df = sd->rf;
382     } else if (!strcasecmp(sdata, "Reflection Back")) {
383     if (sd->rb != NULL)
384     SDfreeSpectralDF(sd->rb);
385     if ((sd->rb = SDnewSpectralDF(1)) == NULL)
386     return RC_MEMERR;
387     df = sd->rb;
388     } else
389     return RC_FAIL;
390 greg 3.4 /* XXX should also check "ScatteringDataType" for consistency? */
391 greg 3.1 /* get angle bases */
392     sdata = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
393     if (!sdata || !*sdata) {
394     sprintf(SDerrorDetail, "Missing column basis for BSDF '%s'",
395     sd->name);
396     return RC_FORMERR;
397     }
398     for (inbi = nabases; inbi--; )
399 greg 3.4 if (!strcasecmp(sdata, abase_list[inbi].name))
400 greg 3.1 break;
401     if (inbi < 0) {
402 greg 3.4 sprintf(SDerrorDetail, "Undefined ColumnAngleBasis '%s'", sdata);
403 greg 3.1 return RC_FORMERR;
404     }
405     sdata = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
406     if (!sdata || !*sdata) {
407     sprintf(SDerrorDetail, "Missing row basis for BSDF '%s'",
408     sd->name);
409     return RC_FORMERR;
410     }
411     for (outbi = nabases; outbi--; )
412 greg 3.4 if (!strcasecmp(sdata, abase_list[outbi].name))
413 greg 3.1 break;
414     if (outbi < 0) {
415 greg 3.4 sprintf(SDerrorDetail, "Undefined RowAngleBasis '%s'", sdata);
416 greg 3.1 return RC_FORMERR;
417     }
418     /* allocate BSDF matrix */
419     dp = SDnewMatrix(abase_list[inbi].nangles, abase_list[outbi].nangles);
420     if (dp == NULL)
421     return RC_MEMERR;
422     dp->ib_priv = (void *)&abase_list[inbi];
423     dp->ob_priv = (void *)&abase_list[outbi];
424     if (df == sd->tf) {
425     dp->ib_vec = ab_getvecR;
426     dp->ib_ndx = ab_getndxR;
427     dp->ob_vec = ab_getvec;
428     dp->ob_ndx = ab_getndx;
429     } else if (df == sd->rf) {
430     dp->ib_vec = ab_getvec;
431     dp->ib_ndx = ab_getndx;
432     dp->ob_vec = ab_getvec;
433     dp->ob_ndx = ab_getndx;
434     } else /* df == sd->rb */ {
435     dp->ib_vec = ab_getvecR;
436     dp->ib_ndx = ab_getndxR;
437     dp->ob_vec = ab_getvecR;
438     dp->ob_ndx = ab_getndxR;
439     }
440     dp->ib_ohm = ab_getohm;
441     dp->ob_ohm = ab_getohm;
442     df->comp[0].cspec[0] = c_dfcolor; /* XXX monochrome for now */
443     df->comp[0].dist = dp;
444     df->comp[0].func = &SDhandleMtx;
445     /* read BSDF data */
446     sdata = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
447     if (!sdata || !*sdata) {
448     sprintf(SDerrorDetail, "Missing BSDF ScatteringData in '%s'",
449     sd->name);
450     return RC_FORMERR;
451     }
452     for (i = 0; i < dp->ninc*dp->nout; i++) {
453 greg 3.3 char *sdnext = fskip(sdata);
454 greg 3.1 if (sdnext == NULL) {
455     sprintf(SDerrorDetail,
456     "Bad/missing BSDF ScatteringData in '%s'",
457     sd->name);
458     return RC_FORMERR;
459     }
460     while (*sdnext && isspace(*sdnext))
461     sdnext++;
462     if (*sdnext == ',') sdnext++;
463     if (rowinc) {
464     int r = i/dp->nout;
465     int c = i - c*dp->nout;
466     mBSDF_value(dp,r,c) = atof(sdata);
467     } else
468     dp->bsdf[i] = atof(sdata);
469     sdata = sdnext;
470     }
471     return get_extrema(df);
472     }
473    
474     /* Subtract minimum (diffuse) scattering amount from BSDF */
475     static double
476     subtract_min(SDMat *sm)
477     {
478     float minv = sm->bsdf[0];
479     int n = sm->ninc*sm->nout;
480     int i;
481    
482     for (i = n; --i; )
483     if (sm->bsdf[i] < minv)
484     minv = sm->bsdf[i];
485     for (i = n; i--; )
486     sm->bsdf[i] -= minv;
487    
488     return minv*M_PI; /* be sure to include multiplier */
489     }
490    
491     /* Extract and separate diffuse portion of BSDF */
492     static void
493     extract_diffuse(SDValue *dv, SDSpectralDF *df)
494     {
495     int n;
496    
497     if (df == NULL || df->ncomp <= 0) {
498     dv->spec = c_dfcolor;
499     dv->cieY = .0;
500     return;
501     }
502     dv->spec = df->comp[0].cspec[0];
503     dv->cieY = subtract_min((SDMat *)df->comp[0].dist);
504     /* in case of multiple components */
505     for (n = df->ncomp; --n; ) {
506     double ymin = subtract_min((SDMat *)df->comp[n].dist);
507     c_cmix(&dv->spec, dv->cieY, &dv->spec, ymin, &df->comp[n].cspec[0]);
508     dv->cieY += ymin;
509     }
510 greg 3.4 df->maxHemi -= dv->cieY; /* adjust minimum hemispherical */
511     /* make sure everything is set */
512 greg 3.1 c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
513     }
514    
515     /* Load a BSDF matrix from an open XML file */
516     SDError
517 greg 3.4 SDloadMtx(SDData *sd, ezxml_t wtl)
518 greg 3.1 {
519 greg 3.4 ezxml_t wld, wdb;
520 greg 3.1 int rowIn;
521     struct BSDF_data *dp;
522     char *txt;
523     int rval;
524    
525 greg 3.4 txt = ezxml_txt(ezxml_child(ezxml_child(wtl,
526     "DataDefinition"), "IncidentDataStructure"));
527     if (txt == NULL || !*txt) {
528 greg 3.1 sprintf(SDerrorDetail,
529 greg 3.4 "BSDF \"%s\": missing IncidentDataStructure",
530 greg 3.1 sd->name);
531     return SDEformat;
532     }
533     if (!strcasecmp(txt, "Rows"))
534     rowIn = 1;
535     else if (!strcasecmp(txt, "Columns"))
536     rowIn = 0;
537     else {
538     sprintf(SDerrorDetail,
539     "BSDF \"%s\": unsupported IncidentDataStructure",
540     sd->name);
541     return SDEsupport;
542     }
543     /* get angle basis */
544     rval = load_angle_basis(ezxml_child(ezxml_child(wtl,
545     "DataDefinition"), "AngleBasis"));
546     if (rval < 0)
547 greg 3.4 return convert_errcode(rval);
548 greg 3.1 /* load BSDF components */
549     for (wld = ezxml_child(wtl, "WavelengthData");
550     wld != NULL; wld = wld->next) {
551     if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
552     "Visible"))
553     continue; /* just visible for now */
554     for (wdb = ezxml_child(wld, "WavelengthDataBlock");
555     wdb != NULL; wdb = wdb->next)
556     if ((rval = load_bsdf_data(sd, wdb, rowIn)) < 0)
557 greg 3.4 return convert_errcode(rval);
558 greg 3.1 }
559     /* separate diffuse components */
560     extract_diffuse(&sd->rLambFront, sd->rf);
561     extract_diffuse(&sd->rLambBack, sd->rb);
562     extract_diffuse(&sd->tLamb, sd->tf);
563     /* return success */
564     return SDEnone;
565     }
566    
567     /* Get Matrix BSDF value */
568     static int
569     SDgetMtxBSDF(float coef[SDmaxCh], const FVECT outVec,
570     const FVECT inVec, const void *dist)
571     {
572     const SDMat *dp = (const SDMat *)dist;
573     int i_ndx, o_ndx;
574     /* get angle indices */
575     i_ndx = mBSDF_incndx(dp, inVec);
576     o_ndx = mBSDF_outndx(dp, outVec);
577     /* try reciprocity if necessary */
578     if ((i_ndx < 0) & (o_ndx < 0)) {
579     i_ndx = mBSDF_incndx(dp, outVec);
580     o_ndx = mBSDF_outndx(dp, inVec);
581     }
582     if ((i_ndx < 0) | (o_ndx < 0))
583     return 0; /* nothing from this component */
584     coef[0] = mBSDF_value(dp, i_ndx, o_ndx);
585     return 1; /* XXX monochrome for now */
586     }
587    
588     /* Query solid angle for vector */
589     static SDError
590     SDqueryMtxProjSA(double *psa, const FVECT vec, int qflags, const void *dist)
591     {
592     const SDMat *dp = (const SDMat *)dist;
593    
594     if (!(qflags & SDqueryInc+SDqueryOut))
595     return SDEargument;
596     if (qflags & SDqueryInc) {
597     double inc_psa = mBSDF_incohm(dp, mBSDF_incndx(dp, vec));
598     if (inc_psa < .0)
599     return SDEinternal;
600     switch (qflags & SDqueryMin+SDqueryMax) {
601     case SDqueryMax:
602     if (inc_psa > psa[0])
603     psa[0] = inc_psa;
604     break;
605     case SDqueryMin+SDqueryMax:
606     if (inc_psa > psa[1])
607     psa[1] = inc_psa;
608     /* fall through */
609     case SDqueryMin:
610     if (inc_psa < psa[0])
611     psa[0] = inc_psa;
612     break;
613     case 0:
614     psa[0] = inc_psa;
615     break;
616     }
617     }
618     if (qflags & SDqueryOut) {
619     double out_psa = mBSDF_outohm(dp, mBSDF_outndx(dp, vec));
620     if (out_psa < .0)
621     return SDEinternal;
622     switch (qflags & SDqueryMin+SDqueryMax) {
623     case SDqueryMax:
624     if (out_psa > psa[0])
625     psa[0] = out_psa;
626     break;
627     case SDqueryMin+SDqueryMax:
628     if (out_psa > psa[1])
629     psa[1] = out_psa;
630     /* fall through */
631     case SDqueryMin:
632     if (out_psa < psa[0])
633     psa[0] = out_psa;
634     break;
635     case 0:
636     psa[(qflags&SDqueryInc)!=0] = out_psa;
637     break;
638     }
639     }
640     return SDEnone;
641     }
642    
643     /* Compute new cumulative distribution from BSDF */
644     static int
645     make_cdist(SDMatCDst *cd, const FVECT inVec, SDMat *dp, int rev)
646     {
647     const unsigned maxval = ~0;
648     double *cmtab, scale;
649     int o;
650    
651     cmtab = (double *)malloc((cd->calen+1)*sizeof(double));
652     if (cmtab == NULL)
653     return 0;
654     cmtab[0] = .0;
655     for (o = 0; o < cd->calen; o++) {
656     if (rev)
657     cmtab[o+1] = mBSDF_value(dp, o, cd->indx) *
658     (*dp->ib_ohm)(o, dp->ib_priv);
659     else
660     cmtab[o+1] = mBSDF_value(dp, cd->indx, o) *
661     (*dp->ob_ohm)(o, dp->ob_priv);
662     cmtab[o+1] += cmtab[o];
663     }
664     cd->cTotal = cmtab[cd->calen];
665     scale = (double)maxval / cd->cTotal;
666     cd->carr[0] = 0;
667     for (o = 1; o < cd->calen; o++)
668     cd->carr[o] = scale*cmtab[o] + .5;
669     cd->carr[cd->calen] = maxval;
670     free(cmtab);
671     return 1;
672     }
673    
674     /* Get cumulative distribution for matrix BSDF */
675     static const SDCDst *
676     SDgetMtxCDist(const FVECT inVec, SDComponent *sdc)
677     {
678     SDMat *dp = (SDMat *)sdc->dist;
679     int reverse;
680     SDMatCDst myCD;
681     SDMatCDst *cd, *cdlast;
682    
683     if (dp == NULL)
684     return NULL;
685     memset(&myCD, 0, sizeof(myCD));
686     myCD.indx = mBSDF_incndx(dp, inVec);
687     if (myCD.indx >= 0) {
688     myCD.ob_priv = dp->ob_priv;
689     myCD.ob_vec = dp->ob_vec;
690     myCD.calen = dp->nout;
691     reverse = 0;
692     } else { /* try reciprocity */
693     myCD.indx = mBSDF_outndx(dp, inVec);
694     if (myCD.indx < 0)
695     return NULL;
696     myCD.ob_priv = dp->ib_priv;
697     myCD.ob_vec = dp->ib_vec;
698     myCD.calen = dp->ninc;
699     reverse = 1;
700     }
701     cdlast = NULL; /* check for it in cache list */
702     for (cd = (SDMatCDst *)sdc->cdList;
703     cd != NULL; cd = (SDMatCDst *)cd->next) {
704     if (cd->indx == myCD.indx && (cd->calen == myCD.calen) &
705     (cd->ob_priv == myCD.ob_priv) &
706     (cd->ob_vec == myCD.ob_vec))
707     break;
708     cdlast = cd;
709     }
710     if (cd == NULL) { /* need to allocate new entry */
711     cd = (SDMatCDst *)malloc(sizeof(SDMatCDst) +
712     myCD.calen*sizeof(myCD.carr[0]));
713     if (cd == NULL)
714     return NULL;
715     *cd = myCD; /* compute cumulative distribution */
716     if (!make_cdist(cd, inVec, dp, reverse)) {
717     free(cd);
718     return NULL;
719     }
720     cdlast = cd;
721     }
722     if (cdlast != NULL) { /* move entry to head of cache list */
723     cdlast->next = cd->next;
724     cd->next = sdc->cdList;
725     sdc->cdList = (SDCDst *)cd;
726     }
727     return (SDCDst *)cd; /* ready to go */
728     }
729    
730     /* Sample cumulative distribution */
731     static SDError
732     SDsampMtxCDist(FVECT outVec, double randX, const SDCDst *cdp)
733     {
734     const unsigned maxval = ~0;
735     const SDMatCDst *mcd = (const SDMatCDst *)cdp;
736     const unsigned target = randX*maxval;
737     int i, iupper, ilower;
738     /* binary search to find index */
739     ilower = 0; iupper = mcd->calen;
740     while ((i = (iupper + ilower) >> 1) != ilower)
741     if ((long)target >= (long)mcd->carr[i])
742     ilower = i;
743     else
744     iupper = i;
745     /* localize random position */
746     randX = (randX*maxval - mcd->carr[ilower]) /
747     (double)(mcd->carr[iupper] - mcd->carr[ilower]);
748     /* convert index to vector */
749     if ((*mcd->ob_vec)(outVec, i, randX, mcd->ob_priv))
750     return SDEnone;
751     strcpy(SDerrorDetail, "BSDF sampling fault");
752     return SDEinternal;
753     }
754    
755     /* Fixed resolution BSDF methods */
756     SDFunc SDhandleMtx = {
757     &SDgetMtxBSDF,
758     &SDqueryMtxProjSA,
759     &SDgetMtxCDist,
760     &SDsampMtxCDist,
761     &SDfreeMatrix,
762     };