ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/bsdf_m.c
Revision: 3.5
Committed: Sat Feb 19 23:42:09 2011 UTC (13 years, 2 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 3.4: +53 -66 lines
Log Message:
Fixes to BSDF including blurring of angle boundaries

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: bsdf_m.c,v 3.4 2011/02/19 01:48:59 greg Exp $";
3 #endif
4 /*
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 #include "rtio.h"
15 #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->ib_ohm != dp->ob_ohm) | (dp->ib_priv != dp->ob_priv)) {
350 double ohm;
351 for (i = dp->ninc; i--; )
352 if ((ohm = mBSDF_incohm(dp,i)) < df->minProjSA)
353 df->minProjSA = ohm;
354 }
355 return (df->maxHemi <= 1.01);
356 }
357
358 /* load BSDF distribution for this wavelength */
359 static int
360 load_bsdf_data(SDData *sd, ezxml_t wdb, int rowinc)
361 {
362 SDSpectralDF *df;
363 SDMat *dp;
364 char *sdata;
365 int inbi, outbi;
366 int i;
367 /* allocate BSDF component */
368 sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
369 if (!strcasecmp(sdata, "Transmission Front")) {
370 if (sd->tf != NULL)
371 SDfreeSpectralDF(sd->tf);
372 if ((sd->tf = SDnewSpectralDF(1)) == NULL)
373 return RC_MEMERR;
374 df = sd->tf;
375 } else if (!strcasecmp(sdata, "Reflection Front")) {
376 if (sd->rf != NULL)
377 SDfreeSpectralDF(sd->rf);
378 if ((sd->rf = SDnewSpectralDF(1)) == NULL)
379 return RC_MEMERR;
380 df = sd->rf;
381 } else if (!strcasecmp(sdata, "Reflection Back")) {
382 if (sd->rb != NULL)
383 SDfreeSpectralDF(sd->rb);
384 if ((sd->rb = SDnewSpectralDF(1)) == NULL)
385 return RC_MEMERR;
386 df = sd->rb;
387 } else
388 return RC_FAIL;
389 /* XXX should also check "ScatteringDataType" for consistency? */
390 /* get angle bases */
391 sdata = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
392 if (!sdata || !*sdata) {
393 sprintf(SDerrorDetail, "Missing column basis for BSDF '%s'",
394 sd->name);
395 return RC_FORMERR;
396 }
397 for (inbi = nabases; inbi--; )
398 if (!strcasecmp(sdata, abase_list[inbi].name))
399 break;
400 if (inbi < 0) {
401 sprintf(SDerrorDetail, "Undefined ColumnAngleBasis '%s'", sdata);
402 return RC_FORMERR;
403 }
404 sdata = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
405 if (!sdata || !*sdata) {
406 sprintf(SDerrorDetail, "Missing row basis for BSDF '%s'",
407 sd->name);
408 return RC_FORMERR;
409 }
410 for (outbi = nabases; outbi--; )
411 if (!strcasecmp(sdata, abase_list[outbi].name))
412 break;
413 if (outbi < 0) {
414 sprintf(SDerrorDetail, "Undefined RowAngleBasis '%s'", sdata);
415 return RC_FORMERR;
416 }
417 /* allocate BSDF matrix */
418 dp = SDnewMatrix(abase_list[inbi].nangles, abase_list[outbi].nangles);
419 if (dp == NULL)
420 return RC_MEMERR;
421 dp->ib_priv = &abase_list[inbi];
422 dp->ob_priv = &abase_list[outbi];
423 if (df == sd->tf) {
424 dp->ib_vec = &ab_getvecR;
425 dp->ib_ndx = &ab_getndxR;
426 dp->ob_vec = &ab_getvec;
427 dp->ob_ndx = &ab_getndx;
428 } else if (df == sd->rf) {
429 dp->ib_vec = &ab_getvec;
430 dp->ib_ndx = &ab_getndx;
431 dp->ob_vec = &ab_getvec;
432 dp->ob_ndx = &ab_getndx;
433 } else /* df == sd->rb */ {
434 dp->ib_vec = &ab_getvecR;
435 dp->ib_ndx = &ab_getndxR;
436 dp->ob_vec = &ab_getvecR;
437 dp->ob_ndx = &ab_getndxR;
438 }
439 dp->ib_ohm = &ab_getohm;
440 dp->ob_ohm = &ab_getohm;
441 df->comp[0].cspec[0] = c_dfcolor; /* XXX monochrome for now */
442 df->comp[0].dist = dp;
443 df->comp[0].func = &SDhandleMtx;
444 /* read BSDF data */
445 sdata = ezxml_txt(ezxml_child(wdb,"ScatteringData"));
446 if (!sdata || !*sdata) {
447 sprintf(SDerrorDetail, "Missing BSDF ScatteringData in '%s'",
448 sd->name);
449 return RC_FORMERR;
450 }
451 for (i = 0; i < dp->ninc*dp->nout; i++) {
452 char *sdnext = fskip(sdata);
453 if (sdnext == NULL) {
454 sprintf(SDerrorDetail,
455 "Bad/missing BSDF ScatteringData in '%s'",
456 sd->name);
457 return RC_FORMERR;
458 }
459 while (*sdnext && isspace(*sdnext))
460 sdnext++;
461 if (*sdnext == ',') sdnext++;
462 if (rowinc) {
463 int r = i/dp->nout;
464 int c = i - c*dp->nout;
465 mBSDF_value(dp,r,c) = atof(sdata);
466 } else
467 dp->bsdf[i] = atof(sdata);
468 sdata = sdnext;
469 }
470 return get_extrema(df);
471 }
472
473 /* Subtract minimum (diffuse) scattering amount from BSDF */
474 static double
475 subtract_min(SDMat *sm)
476 {
477 float minv = sm->bsdf[0];
478 int n = sm->ninc*sm->nout;
479 int i;
480
481 for (i = n; --i; )
482 if (sm->bsdf[i] < minv)
483 minv = sm->bsdf[i];
484 for (i = n; i--; )
485 sm->bsdf[i] -= minv;
486
487 return minv*M_PI; /* be sure to include multiplier */
488 }
489
490 /* Extract and separate diffuse portion of BSDF */
491 static void
492 extract_diffuse(SDValue *dv, SDSpectralDF *df)
493 {
494 int n;
495
496 if (df == NULL || df->ncomp <= 0) {
497 dv->spec = c_dfcolor;
498 dv->cieY = .0;
499 return;
500 }
501 dv->spec = df->comp[0].cspec[0];
502 dv->cieY = subtract_min((SDMat *)df->comp[0].dist);
503 /* in case of multiple components */
504 for (n = df->ncomp; --n; ) {
505 double ymin = subtract_min((SDMat *)df->comp[n].dist);
506 c_cmix(&dv->spec, dv->cieY, &dv->spec, ymin, &df->comp[n].cspec[0]);
507 dv->cieY += ymin;
508 }
509 df->maxHemi -= dv->cieY; /* adjust minimum hemispherical */
510 /* make sure everything is set */
511 c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
512 }
513
514 /* Load a BSDF matrix from an open XML file */
515 SDError
516 SDloadMtx(SDData *sd, ezxml_t wtl)
517 {
518 ezxml_t wld, wdb;
519 int rowIn;
520 struct BSDF_data *dp;
521 char *txt;
522 int rval;
523
524 txt = ezxml_txt(ezxml_child(ezxml_child(wtl,
525 "DataDefinition"), "IncidentDataStructure"));
526 if (txt == NULL || !*txt) {
527 sprintf(SDerrorDetail,
528 "BSDF \"%s\": missing IncidentDataStructure",
529 sd->name);
530 return SDEformat;
531 }
532 if (!strcasecmp(txt, "Rows"))
533 rowIn = 1;
534 else if (!strcasecmp(txt, "Columns"))
535 rowIn = 0;
536 else {
537 sprintf(SDerrorDetail,
538 "BSDF \"%s\": unsupported IncidentDataStructure",
539 sd->name);
540 return SDEsupport;
541 }
542 /* get angle basis */
543 rval = load_angle_basis(ezxml_child(ezxml_child(wtl,
544 "DataDefinition"), "AngleBasis"));
545 if (rval < 0)
546 return convert_errcode(rval);
547 /* load BSDF components */
548 for (wld = ezxml_child(wtl, "WavelengthData");
549 wld != NULL; wld = wld->next) {
550 if (strcasecmp(ezxml_txt(ezxml_child(wld,"Wavelength")),
551 "Visible"))
552 continue; /* just visible for now */
553 for (wdb = ezxml_child(wld, "WavelengthDataBlock");
554 wdb != NULL; wdb = wdb->next)
555 if ((rval = load_bsdf_data(sd, wdb, rowIn)) < 0)
556 return convert_errcode(rval);
557 }
558 /* separate diffuse components */
559 extract_diffuse(&sd->rLambFront, sd->rf);
560 extract_diffuse(&sd->rLambBack, sd->rb);
561 extract_diffuse(&sd->tLamb, sd->tf);
562 /* return success */
563 return SDEnone;
564 }
565
566 /* Get Matrix BSDF value */
567 static int
568 SDgetMtxBSDF(float coef[SDmaxCh], const FVECT outVec,
569 const FVECT inVec, const void *dist)
570 {
571 const SDMat *dp = (const SDMat *)dist;
572 int i_ndx, o_ndx;
573 /* get angle indices */
574 i_ndx = mBSDF_incndx(dp, inVec);
575 o_ndx = mBSDF_outndx(dp, outVec);
576 /* try reciprocity if necessary */
577 if ((i_ndx < 0) & (o_ndx < 0)) {
578 i_ndx = mBSDF_incndx(dp, outVec);
579 o_ndx = mBSDF_outndx(dp, inVec);
580 }
581 if ((i_ndx < 0) | (o_ndx < 0))
582 return 0; /* nothing from this component */
583 coef[0] = mBSDF_value(dp, i_ndx, o_ndx);
584 return 1; /* XXX monochrome for now */
585 }
586
587 /* Query solid angle for vector */
588 static SDError
589 SDqueryMtxProjSA(double *psa, const FVECT vec, int qflags, const void *dist)
590 {
591 const SDMat *dp = (const SDMat *)dist;
592 double inc_psa, out_psa;
593 /* check arguments */
594 if ((psa == NULL) | (vec == NULL) | (dp == NULL))
595 return SDEargument;
596 /* get projected solid angles */
597 inc_psa = mBSDF_incohm(dp, mBSDF_incndx(dp, vec));
598 out_psa = mBSDF_outohm(dp, mBSDF_outndx(dp, vec));
599
600 switch (qflags) { /* record based on flag settings */
601 case SDqueryVal:
602 psa[0] = .0;
603 /* fall through */
604 case SDqueryMax:
605 if (inc_psa > psa[0])
606 psa[0] = inc_psa;
607 if (out_psa > psa[0])
608 psa[0] = out_psa;
609 break;
610 case SDqueryMin+SDqueryMax:
611 if (inc_psa > psa[0])
612 psa[1] = inc_psa;
613 if (out_psa > psa[0])
614 psa[1] = out_psa;
615 /* fall through */
616 case SDqueryMin:
617 if ((inc_psa > .0) & (inc_psa < psa[0]))
618 psa[0] = inc_psa;
619 if ((out_psa > .0) & (out_psa < psa[0]))
620 psa[0] = out_psa;
621 break;
622 }
623 /* make sure it's legal */
624 return (psa[0] <= .0) ? SDEinternal : SDEnone;
625 }
626
627 /* Compute new cumulative distribution from BSDF */
628 static int
629 make_cdist(SDMatCDst *cd, const FVECT inVec, SDMat *dp, int rev)
630 {
631 const unsigned maxval = ~0;
632 double *cmtab, scale;
633 int o;
634
635 cmtab = (double *)malloc((cd->calen+1)*sizeof(double));
636 if (cmtab == NULL)
637 return 0;
638 cmtab[0] = .0;
639 for (o = 0; o < cd->calen; o++) {
640 if (rev)
641 cmtab[o+1] = mBSDF_value(dp, o, cd->indx) *
642 (*dp->ib_ohm)(o, dp->ib_priv);
643 else
644 cmtab[o+1] = mBSDF_value(dp, cd->indx, o) *
645 (*dp->ob_ohm)(o, dp->ob_priv);
646 cmtab[o+1] += cmtab[o];
647 }
648 cd->cTotal = cmtab[cd->calen];
649 scale = (double)maxval / cd->cTotal;
650 cd->carr[0] = 0;
651 for (o = 1; o < cd->calen; o++)
652 cd->carr[o] = scale*cmtab[o] + .5;
653 cd->carr[cd->calen] = maxval;
654 free(cmtab);
655 return 1;
656 }
657
658 /* Get cumulative distribution for matrix BSDF */
659 static const SDCDst *
660 SDgetMtxCDist(const FVECT inVec, SDComponent *sdc)
661 {
662 SDMat *dp = (SDMat *)sdc->dist;
663 int reverse;
664 SDMatCDst myCD;
665 SDMatCDst *cd, *cdlast;
666 /* check arguments */
667 if ((inVec == NULL) | (dp == NULL))
668 return NULL;
669 memset(&myCD, 0, sizeof(myCD));
670 myCD.indx = mBSDF_incndx(dp, inVec);
671 if (myCD.indx >= 0) {
672 myCD.ob_priv = dp->ob_priv;
673 myCD.ob_vec = dp->ob_vec;
674 myCD.calen = dp->nout;
675 reverse = 0;
676 } else { /* try reciprocity */
677 myCD.indx = mBSDF_outndx(dp, inVec);
678 if (myCD.indx < 0)
679 return NULL;
680 myCD.ob_priv = dp->ib_priv;
681 myCD.ob_vec = dp->ib_vec;
682 myCD.calen = dp->ninc;
683 reverse = 1;
684 }
685 cdlast = NULL; /* check for it in cache list */
686 for (cd = (SDMatCDst *)sdc->cdList;
687 cd != NULL; cd = (SDMatCDst *)cd->next) {
688 if (cd->indx == myCD.indx && (cd->calen == myCD.calen) &
689 (cd->ob_priv == myCD.ob_priv) &
690 (cd->ob_vec == myCD.ob_vec))
691 break;
692 cdlast = cd;
693 }
694 if (cd == NULL) { /* need to allocate new entry */
695 cd = (SDMatCDst *)malloc(sizeof(SDMatCDst) +
696 myCD.calen*sizeof(myCD.carr[0]));
697 if (cd == NULL)
698 return NULL;
699 *cd = myCD; /* compute cumulative distribution */
700 if (!make_cdist(cd, inVec, dp, reverse)) {
701 free(cd);
702 return NULL;
703 }
704 cdlast = cd;
705 }
706 if (cdlast != NULL) { /* move entry to head of cache list */
707 cdlast->next = cd->next;
708 cd->next = sdc->cdList;
709 sdc->cdList = (SDCDst *)cd;
710 }
711 return (SDCDst *)cd; /* ready to go */
712 }
713
714 /* Sample cumulative distribution */
715 static SDError
716 SDsampMtxCDist(FVECT outVec, double randX, const SDCDst *cdp)
717 {
718 const unsigned maxval = ~0;
719 const SDMatCDst *mcd = (const SDMatCDst *)cdp;
720 const unsigned target = randX*maxval;
721 int i, iupper, ilower;
722 /* check arguments */
723 if ((outVec == NULL) | (mcd == NULL))
724 return SDEargument;
725 /* binary search to find index */
726 ilower = 0; iupper = mcd->calen;
727 while ((i = (iupper + ilower) >> 1) != ilower)
728 if ((long)target >= (long)mcd->carr[i])
729 ilower = i;
730 else
731 iupper = i;
732 /* localize random position */
733 randX = (randX*maxval - mcd->carr[ilower]) /
734 (double)(mcd->carr[iupper] - mcd->carr[ilower]);
735 /* convert index to vector */
736 if ((*mcd->ob_vec)(outVec, i, randX, mcd->ob_priv))
737 return SDEnone;
738 strcpy(SDerrorDetail, "BSDF sampling fault");
739 return SDEinternal;
740 }
741
742 /* Fixed resolution BSDF methods */
743 SDFunc SDhandleMtx = {
744 &SDgetMtxBSDF,
745 &SDqueryMtxProjSA,
746 &SDgetMtxCDist,
747 &SDsampMtxCDist,
748 &SDfreeMatrix,
749 };