ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambcomp.c
Revision: 2.63
Committed: Thu Jun 19 16:26:55 2014 UTC (9 years, 10 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad4R2
Changes since 2.62: +2 -2 lines
Log Message:
Officially replaced ambient calculation with new Hessian-based error control

File Contents

# Content
1 #ifndef lint
2 static const char RCSid[] = "$Id: ambcomp.c,v 2.62 2014/05/19 20:23:48 greg Exp $";
3 #endif
4 /*
5 * Routines to compute "ambient" values using Monte Carlo
6 *
7 * Hessian calculations based on "Practical Hessian-Based Error Control
8 * for Irradiance Caching" by Schwarzhaupt, Wann Jensen, & Jarosz
9 * from ACM SIGGRAPH Asia 2012 conference proceedings.
10 *
11 * Added book-keeping optimization to avoid calculations that would
12 * cancel due to traversal both directions on edges that are adjacent
13 * to same-valued triangles. This cuts about half of Hessian math.
14 *
15 * Declarations of external symbols in ambient.h
16 */
17
18 #include "copyright.h"
19
20 #include "ray.h"
21 #include "ambient.h"
22 #include "random.h"
23
24 #ifndef OLDAMB
25
26 extern void SDsquare2disk(double ds[2], double seedx, double seedy);
27
28 typedef struct {
29 COLOR v; /* hemisphere sample value */
30 float d; /* reciprocal distance (1/rt) */
31 FVECT p; /* intersection point */
32 } AMBSAMP; /* sample value */
33
34 typedef struct {
35 RAY *rp; /* originating ray sample */
36 int ns; /* number of samples per axis */
37 int sampOK; /* acquired full sample set? */
38 COLOR acoef; /* division contribution coefficient */
39 double acol[3]; /* accumulated color */
40 FVECT ux, uy; /* tangent axis unit vectors */
41 AMBSAMP sa[1]; /* sample array (extends struct) */
42 } AMBHEMI; /* ambient sample hemisphere */
43
44 #define AI(h,i,j) ((i)*(h)->ns + (j))
45 #define ambsam(h,i,j) (h)->sa[AI(h,i,j)]
46
47 typedef struct {
48 FVECT r_i, r_i1, e_i, rcp, rI2_eJ2;
49 double I1, I2;
50 } FFTRI; /* vectors and coefficients for Hessian calculation */
51
52
53 static int
54 ambsample( /* initial ambient division sample */
55 AMBHEMI *hp,
56 int i,
57 int j,
58 int n
59 )
60 {
61 AMBSAMP *ap = &ambsam(hp,i,j);
62 RAY ar;
63 int hlist[3], ii;
64 double spt[2], zd;
65 /* generate hemispherical sample */
66 /* ambient coefficient for weight */
67 if (ambacc > FTINY)
68 setcolor(ar.rcoef, AVGREFL, AVGREFL, AVGREFL);
69 else
70 copycolor(ar.rcoef, hp->acoef);
71 if (rayorigin(&ar, AMBIENT, hp->rp, ar.rcoef) < 0)
72 return(0);
73 if (ambacc > FTINY) {
74 multcolor(ar.rcoef, hp->acoef);
75 scalecolor(ar.rcoef, 1./AVGREFL);
76 }
77 hlist[0] = hp->rp->rno;
78 hlist[1] = j;
79 hlist[2] = i;
80 multisamp(spt, 2, urand(ilhash(hlist,3)+n));
81 if (!n) { /* avoid border samples for n==0 */
82 if ((spt[0] < 0.1) | (spt[0] >= 0.9))
83 spt[0] = 0.1 + 0.8*frandom();
84 if ((spt[1] < 0.1) | (spt[1] >= 0.9))
85 spt[1] = 0.1 + 0.8*frandom();
86 }
87 SDsquare2disk(spt, (j+spt[1])/hp->ns, (i+spt[0])/hp->ns);
88 zd = sqrt(1. - spt[0]*spt[0] - spt[1]*spt[1]);
89 for (ii = 3; ii--; )
90 ar.rdir[ii] = spt[0]*hp->ux[ii] +
91 spt[1]*hp->uy[ii] +
92 zd*hp->rp->ron[ii];
93 checknorm(ar.rdir);
94 dimlist[ndims++] = AI(hp,i,j) + 90171;
95 rayvalue(&ar); /* evaluate ray */
96 ndims--;
97 if (ar.rt <= FTINY)
98 return(0); /* should never happen */
99 multcolor(ar.rcol, ar.rcoef); /* apply coefficient */
100 if (ar.rt*ap->d < 1.0) /* new/closer distance? */
101 ap->d = 1.0/ar.rt;
102 if (!n) { /* record first vertex & value */
103 if (ar.rt > 10.0*thescene.cusize)
104 ar.rt = 10.0*thescene.cusize;
105 VSUM(ap->p, ar.rorg, ar.rdir, ar.rt);
106 copycolor(ap->v, ar.rcol);
107 } else { /* else update recorded value */
108 hp->acol[RED] -= colval(ap->v,RED);
109 hp->acol[GRN] -= colval(ap->v,GRN);
110 hp->acol[BLU] -= colval(ap->v,BLU);
111 zd = 1.0/(double)(n+1);
112 scalecolor(ar.rcol, zd);
113 zd *= (double)n;
114 scalecolor(ap->v, zd);
115 addcolor(ap->v, ar.rcol);
116 }
117 addcolor(hp->acol, ap->v); /* add to our sum */
118 return(1);
119 }
120
121
122 /* Estimate errors based on ambient division differences */
123 static float *
124 getambdiffs(AMBHEMI *hp)
125 {
126 float *earr = (float *)calloc(hp->ns*hp->ns, sizeof(float));
127 float *ep;
128 AMBSAMP *ap;
129 double b, d2;
130 int i, j;
131
132 if (earr == NULL) /* out of memory? */
133 return(NULL);
134 /* compute squared neighbor diffs */
135 for (ap = hp->sa, ep = earr, i = 0; i < hp->ns; i++)
136 for (j = 0; j < hp->ns; j++, ap++, ep++) {
137 b = bright(ap[0].v);
138 if (i) { /* from above */
139 d2 = b - bright(ap[-hp->ns].v);
140 d2 *= d2;
141 ep[0] += d2;
142 ep[-hp->ns] += d2;
143 }
144 if (!j) continue;
145 /* from behind */
146 d2 = b - bright(ap[-1].v);
147 d2 *= d2;
148 ep[0] += d2;
149 ep[-1] += d2;
150 if (!i) continue;
151 /* diagonal */
152 d2 = b - bright(ap[-hp->ns-1].v);
153 d2 *= d2;
154 ep[0] += d2;
155 ep[-hp->ns-1] += d2;
156 }
157 /* correct for number of neighbors */
158 earr[0] *= 8./3.;
159 earr[hp->ns-1] *= 8./3.;
160 earr[(hp->ns-1)*hp->ns] *= 8./3.;
161 earr[(hp->ns-1)*hp->ns + hp->ns-1] *= 8./3.;
162 for (i = 1; i < hp->ns-1; i++) {
163 earr[i*hp->ns] *= 8./5.;
164 earr[i*hp->ns + hp->ns-1] *= 8./5.;
165 }
166 for (j = 1; j < hp->ns-1; j++) {
167 earr[j] *= 8./5.;
168 earr[(hp->ns-1)*hp->ns + j] *= 8./5.;
169 }
170 return(earr);
171 }
172
173
174 /* Perform super-sampling on hemisphere (introduces bias) */
175 static void
176 ambsupersamp(AMBHEMI *hp, int cnt)
177 {
178 float *earr = getambdiffs(hp);
179 double e2rem = 0;
180 AMBSAMP *ap;
181 RAY ar;
182 float *ep;
183 int i, j, n, nss;
184
185 if (earr == NULL) /* just skip calc. if no memory */
186 return;
187 /* accumulate estimated variances */
188 for (ep = earr + hp->ns*hp->ns; ep > earr; )
189 e2rem += *--ep;
190 ep = earr; /* perform super-sampling */
191 for (ap = hp->sa, i = 0; i < hp->ns; i++)
192 for (j = 0; j < hp->ns; j++, ap++) {
193 if (e2rem <= FTINY)
194 goto done; /* nothing left to do */
195 nss = *ep/e2rem*cnt + frandom();
196 for (n = 1; n <= nss && ambsample(hp,i,j,n); n++)
197 --cnt;
198 e2rem -= *ep++; /* update remainder */
199 }
200 done:
201 free(earr);
202 }
203
204
205 static AMBHEMI *
206 samp_hemi( /* sample indirect hemisphere */
207 COLOR rcol,
208 RAY *r,
209 double wt
210 )
211 {
212 AMBHEMI *hp;
213 double d;
214 int n, i, j;
215 /* set number of divisions */
216 if (ambacc <= FTINY &&
217 wt > (d = 0.8*intens(rcol)*r->rweight/(ambdiv*minweight)))
218 wt = d; /* avoid ray termination */
219 n = sqrt(ambdiv * wt) + 0.5;
220 i = 1 + 5*(ambacc > FTINY); /* minimum number of samples */
221 if (n < i)
222 n = i;
223 /* allocate sampling array */
224 hp = (AMBHEMI *)malloc(sizeof(AMBHEMI) + sizeof(AMBSAMP)*(n*n - 1));
225 if (hp == NULL)
226 error(SYSTEM, "out of memory in samp_hemi");
227 hp->rp = r;
228 hp->ns = n;
229 hp->acol[RED] = hp->acol[GRN] = hp->acol[BLU] = 0.0;
230 memset(hp->sa, 0, sizeof(AMBSAMP)*n*n);
231 hp->sampOK = 0;
232 /* assign coefficient */
233 copycolor(hp->acoef, rcol);
234 d = 1.0/(n*n);
235 scalecolor(hp->acoef, d);
236 /* make tangent plane axes */
237 hp->uy[0] = 0.5 - frandom();
238 hp->uy[1] = 0.5 - frandom();
239 hp->uy[2] = 0.5 - frandom();
240 for (i = 3; i--; )
241 if ((-0.6 < r->ron[i]) & (r->ron[i] < 0.6))
242 break;
243 if (i < 0)
244 error(CONSISTENCY, "bad ray direction in samp_hemi");
245 hp->uy[i] = 1.0;
246 VCROSS(hp->ux, hp->uy, r->ron);
247 normalize(hp->ux);
248 VCROSS(hp->uy, r->ron, hp->ux);
249 /* sample divisions */
250 for (i = hp->ns; i--; )
251 for (j = hp->ns; j--; )
252 hp->sampOK += ambsample(hp, i, j, 0);
253 copycolor(rcol, hp->acol);
254 if (!hp->sampOK) { /* utter failure? */
255 free(hp);
256 return(NULL);
257 }
258 if (hp->sampOK < hp->ns*hp->ns) {
259 hp->sampOK *= -1; /* soft failure */
260 return(hp);
261 }
262 n = ambssamp*wt + 0.5;
263 if (n > 8) { /* perform super-sampling? */
264 ambsupersamp(hp, n);
265 copycolor(rcol, hp->acol);
266 }
267 return(hp); /* all is well */
268 }
269
270
271 /* Return brightness of farthest ambient sample */
272 static double
273 back_ambval(AMBHEMI *hp, const int n1, const int n2, const int n3)
274 {
275 if (hp->sa[n1].d <= hp->sa[n2].d) {
276 if (hp->sa[n1].d <= hp->sa[n3].d)
277 return(colval(hp->sa[n1].v,CIEY));
278 return(colval(hp->sa[n3].v,CIEY));
279 }
280 if (hp->sa[n2].d <= hp->sa[n3].d)
281 return(colval(hp->sa[n2].v,CIEY));
282 return(colval(hp->sa[n3].v,CIEY));
283 }
284
285
286 /* Compute vectors and coefficients for Hessian/gradient calcs */
287 static void
288 comp_fftri(FFTRI *ftp, AMBHEMI *hp, const int n0, const int n1)
289 {
290 double rdot_cp, dot_e, dot_er, rdot_r, rdot_r1, J2;
291 int ii;
292
293 VSUB(ftp->r_i, hp->sa[n0].p, hp->rp->rop);
294 VSUB(ftp->r_i1, hp->sa[n1].p, hp->rp->rop);
295 VSUB(ftp->e_i, hp->sa[n1].p, hp->sa[n0].p);
296 VCROSS(ftp->rcp, ftp->r_i, ftp->r_i1);
297 rdot_cp = 1.0/DOT(ftp->rcp,ftp->rcp);
298 dot_e = DOT(ftp->e_i,ftp->e_i);
299 dot_er = DOT(ftp->e_i, ftp->r_i);
300 rdot_r = 1.0/DOT(ftp->r_i,ftp->r_i);
301 rdot_r1 = 1.0/DOT(ftp->r_i1,ftp->r_i1);
302 ftp->I1 = acos( DOT(ftp->r_i, ftp->r_i1) * sqrt(rdot_r*rdot_r1) ) *
303 sqrt( rdot_cp );
304 ftp->I2 = ( DOT(ftp->e_i, ftp->r_i1)*rdot_r1 - dot_er*rdot_r +
305 dot_e*ftp->I1 )*0.5*rdot_cp;
306 J2 = ( 0.5*(rdot_r - rdot_r1) - dot_er*ftp->I2 ) / dot_e;
307 for (ii = 3; ii--; )
308 ftp->rI2_eJ2[ii] = ftp->I2*ftp->r_i[ii] + J2*ftp->e_i[ii];
309 }
310
311
312 /* Compose 3x3 matrix from two vectors */
313 static void
314 compose_matrix(FVECT mat[3], FVECT va, FVECT vb)
315 {
316 mat[0][0] = 2.0*va[0]*vb[0];
317 mat[1][1] = 2.0*va[1]*vb[1];
318 mat[2][2] = 2.0*va[2]*vb[2];
319 mat[0][1] = mat[1][0] = va[0]*vb[1] + va[1]*vb[0];
320 mat[0][2] = mat[2][0] = va[0]*vb[2] + va[2]*vb[0];
321 mat[1][2] = mat[2][1] = va[1]*vb[2] + va[2]*vb[1];
322 }
323
324
325 /* Compute partial 3x3 Hessian matrix for edge */
326 static void
327 comp_hessian(FVECT hess[3], FFTRI *ftp, FVECT nrm)
328 {
329 FVECT ncp;
330 FVECT m1[3], m2[3], m3[3], m4[3];
331 double d1, d2, d3, d4;
332 double I3, J3, K3;
333 int i, j;
334 /* compute intermediate coefficients */
335 d1 = 1.0/DOT(ftp->r_i,ftp->r_i);
336 d2 = 1.0/DOT(ftp->r_i1,ftp->r_i1);
337 d3 = 1.0/DOT(ftp->e_i,ftp->e_i);
338 d4 = DOT(ftp->e_i, ftp->r_i);
339 I3 = ( DOT(ftp->e_i, ftp->r_i1)*d2*d2 - d4*d1*d1 + 3.0/d3*ftp->I2 )
340 / ( 4.0*DOT(ftp->rcp,ftp->rcp) );
341 J3 = 0.25*d3*(d1*d1 - d2*d2) - d4*d3*I3;
342 K3 = d3*(ftp->I2 - I3/d1 - 2.0*d4*J3);
343 /* intermediate matrices */
344 VCROSS(ncp, nrm, ftp->e_i);
345 compose_matrix(m1, ncp, ftp->rI2_eJ2);
346 compose_matrix(m2, ftp->r_i, ftp->r_i);
347 compose_matrix(m3, ftp->e_i, ftp->e_i);
348 compose_matrix(m4, ftp->r_i, ftp->e_i);
349 d1 = DOT(nrm, ftp->rcp);
350 d2 = -d1*ftp->I2;
351 d1 *= 2.0;
352 for (i = 3; i--; ) /* final matrix sum */
353 for (j = 3; j--; ) {
354 hess[i][j] = m1[i][j] + d1*( I3*m2[i][j] + K3*m3[i][j] +
355 2.0*J3*m4[i][j] );
356 hess[i][j] += d2*(i==j);
357 hess[i][j] *= -1.0/PI;
358 }
359 }
360
361
362 /* Reverse hessian calculation result for edge in other direction */
363 static void
364 rev_hessian(FVECT hess[3])
365 {
366 int i;
367
368 for (i = 3; i--; ) {
369 hess[i][0] = -hess[i][0];
370 hess[i][1] = -hess[i][1];
371 hess[i][2] = -hess[i][2];
372 }
373 }
374
375
376 /* Add to radiometric Hessian from the given triangle */
377 static void
378 add2hessian(FVECT hess[3], FVECT ehess1[3],
379 FVECT ehess2[3], FVECT ehess3[3], double v)
380 {
381 int i, j;
382
383 for (i = 3; i--; )
384 for (j = 3; j--; )
385 hess[i][j] += v*( ehess1[i][j] + ehess2[i][j] + ehess3[i][j] );
386 }
387
388
389 /* Compute partial displacement form factor gradient for edge */
390 static void
391 comp_gradient(FVECT grad, FFTRI *ftp, FVECT nrm)
392 {
393 FVECT ncp;
394 double f1;
395 int i;
396
397 f1 = 2.0*DOT(nrm, ftp->rcp);
398 VCROSS(ncp, nrm, ftp->e_i);
399 for (i = 3; i--; )
400 grad[i] = (0.5/PI)*( ftp->I1*ncp[i] + f1*ftp->rI2_eJ2[i] );
401 }
402
403
404 /* Reverse gradient calculation result for edge in other direction */
405 static void
406 rev_gradient(FVECT grad)
407 {
408 grad[0] = -grad[0];
409 grad[1] = -grad[1];
410 grad[2] = -grad[2];
411 }
412
413
414 /* Add to displacement gradient from the given triangle */
415 static void
416 add2gradient(FVECT grad, FVECT egrad1, FVECT egrad2, FVECT egrad3, double v)
417 {
418 int i;
419
420 for (i = 3; i--; )
421 grad[i] += v*( egrad1[i] + egrad2[i] + egrad3[i] );
422 }
423
424
425 /* Compute anisotropic radii and eigenvector directions */
426 static void
427 eigenvectors(FVECT uv[2], float ra[2], FVECT hessian[3])
428 {
429 double hess2[2][2];
430 FVECT a, b;
431 double evalue[2], slope1, xmag1;
432 int i;
433 /* project Hessian to sample plane */
434 for (i = 3; i--; ) {
435 a[i] = DOT(hessian[i], uv[0]);
436 b[i] = DOT(hessian[i], uv[1]);
437 }
438 hess2[0][0] = DOT(uv[0], a);
439 hess2[0][1] = DOT(uv[0], b);
440 hess2[1][0] = DOT(uv[1], a);
441 hess2[1][1] = DOT(uv[1], b);
442 /* compute eigenvalue(s) */
443 i = quadratic(evalue, 1.0, -hess2[0][0]-hess2[1][1],
444 hess2[0][0]*hess2[1][1]-hess2[0][1]*hess2[1][0]);
445 if (i == 1) /* double-root (circle) */
446 evalue[1] = evalue[0];
447 if (!i || ((evalue[0] = fabs(evalue[0])) <= FTINY*FTINY) |
448 ((evalue[1] = fabs(evalue[1])) <= FTINY*FTINY) ) {
449 ra[0] = ra[1] = maxarad;
450 return;
451 }
452 if (evalue[0] > evalue[1]) {
453 ra[0] = sqrt(sqrt(4.0/evalue[0]));
454 ra[1] = sqrt(sqrt(4.0/evalue[1]));
455 slope1 = evalue[1];
456 } else {
457 ra[0] = sqrt(sqrt(4.0/evalue[1]));
458 ra[1] = sqrt(sqrt(4.0/evalue[0]));
459 slope1 = evalue[0];
460 }
461 /* compute unit eigenvectors */
462 if (fabs(hess2[0][1]) <= FTINY)
463 return; /* uv OK as is */
464 slope1 = (slope1 - hess2[0][0]) / hess2[0][1];
465 xmag1 = sqrt(1.0/(1.0 + slope1*slope1));
466 for (i = 3; i--; ) {
467 b[i] = xmag1*uv[0][i] + slope1*xmag1*uv[1][i];
468 a[i] = slope1*xmag1*uv[0][i] - xmag1*uv[1][i];
469 }
470 VCOPY(uv[0], a);
471 VCOPY(uv[1], b);
472 }
473
474
475 static void
476 ambHessian( /* anisotropic radii & pos. gradient */
477 AMBHEMI *hp,
478 FVECT uv[2], /* returned */
479 float ra[2], /* returned (optional) */
480 float pg[2] /* returned (optional) */
481 )
482 {
483 static char memerrmsg[] = "out of memory in ambHessian()";
484 FVECT (*hessrow)[3] = NULL;
485 FVECT *gradrow = NULL;
486 FVECT hessian[3];
487 FVECT gradient;
488 FFTRI fftr;
489 int i, j;
490 /* be sure to assign unit vectors */
491 VCOPY(uv[0], hp->ux);
492 VCOPY(uv[1], hp->uy);
493 /* clock-wise vertex traversal from sample POV */
494 if (ra != NULL) { /* initialize Hessian row buffer */
495 hessrow = (FVECT (*)[3])malloc(sizeof(FVECT)*3*(hp->ns-1));
496 if (hessrow == NULL)
497 error(SYSTEM, memerrmsg);
498 memset(hessian, 0, sizeof(hessian));
499 } else if (pg == NULL) /* bogus call? */
500 return;
501 if (pg != NULL) { /* initialize form factor row buffer */
502 gradrow = (FVECT *)malloc(sizeof(FVECT)*(hp->ns-1));
503 if (gradrow == NULL)
504 error(SYSTEM, memerrmsg);
505 memset(gradient, 0, sizeof(gradient));
506 }
507 /* compute first row of edges */
508 for (j = 0; j < hp->ns-1; j++) {
509 comp_fftri(&fftr, hp, AI(hp,0,j), AI(hp,0,j+1));
510 if (hessrow != NULL)
511 comp_hessian(hessrow[j], &fftr, hp->rp->ron);
512 if (gradrow != NULL)
513 comp_gradient(gradrow[j], &fftr, hp->rp->ron);
514 }
515 /* sum each row of triangles */
516 for (i = 0; i < hp->ns-1; i++) {
517 FVECT hesscol[3]; /* compute first vertical edge */
518 FVECT gradcol;
519 comp_fftri(&fftr, hp, AI(hp,i,0), AI(hp,i+1,0));
520 if (hessrow != NULL)
521 comp_hessian(hesscol, &fftr, hp->rp->ron);
522 if (gradrow != NULL)
523 comp_gradient(gradcol, &fftr, hp->rp->ron);
524 for (j = 0; j < hp->ns-1; j++) {
525 FVECT hessdia[3]; /* compute triangle contributions */
526 FVECT graddia;
527 double backg;
528 backg = back_ambval(hp, AI(hp,i,j),
529 AI(hp,i,j+1), AI(hp,i+1,j));
530 /* diagonal (inner) edge */
531 comp_fftri(&fftr, hp, AI(hp,i,j+1), AI(hp,i+1,j));
532 if (hessrow != NULL) {
533 comp_hessian(hessdia, &fftr, hp->rp->ron);
534 rev_hessian(hesscol);
535 add2hessian(hessian, hessrow[j], hessdia, hesscol, backg);
536 }
537 if (gradrow != NULL) {
538 comp_gradient(graddia, &fftr, hp->rp->ron);
539 rev_gradient(gradcol);
540 add2gradient(gradient, gradrow[j], graddia, gradcol, backg);
541 }
542 /* initialize edge in next row */
543 comp_fftri(&fftr, hp, AI(hp,i+1,j+1), AI(hp,i+1,j));
544 if (hessrow != NULL)
545 comp_hessian(hessrow[j], &fftr, hp->rp->ron);
546 if (gradrow != NULL)
547 comp_gradient(gradrow[j], &fftr, hp->rp->ron);
548 /* new column edge & paired triangle */
549 backg = back_ambval(hp, AI(hp,i+1,j+1),
550 AI(hp,i+1,j), AI(hp,i,j+1));
551 comp_fftri(&fftr, hp, AI(hp,i,j+1), AI(hp,i+1,j+1));
552 if (hessrow != NULL) {
553 comp_hessian(hesscol, &fftr, hp->rp->ron);
554 rev_hessian(hessdia);
555 add2hessian(hessian, hessrow[j], hessdia, hesscol, backg);
556 if (i < hp->ns-2)
557 rev_hessian(hessrow[j]);
558 }
559 if (gradrow != NULL) {
560 comp_gradient(gradcol, &fftr, hp->rp->ron);
561 rev_gradient(graddia);
562 add2gradient(gradient, gradrow[j], graddia, gradcol, backg);
563 if (i < hp->ns-2)
564 rev_gradient(gradrow[j]);
565 }
566 }
567 }
568 /* release row buffers */
569 if (hessrow != NULL) free(hessrow);
570 if (gradrow != NULL) free(gradrow);
571
572 if (ra != NULL) /* extract eigenvectors & radii */
573 eigenvectors(uv, ra, hessian);
574 if (pg != NULL) { /* tangential position gradient */
575 pg[0] = DOT(gradient, uv[0]);
576 pg[1] = DOT(gradient, uv[1]);
577 }
578 }
579
580
581 /* Compute direction gradient from a hemispherical sampling */
582 static void
583 ambdirgrad(AMBHEMI *hp, FVECT uv[2], float dg[2])
584 {
585 AMBSAMP *ap;
586 double dgsum[2];
587 int n;
588 FVECT vd;
589 double gfact;
590
591 dgsum[0] = dgsum[1] = 0.0; /* sum values times -tan(theta) */
592 for (ap = hp->sa, n = hp->ns*hp->ns; n--; ap++) {
593 /* use vector for azimuth + 90deg */
594 VSUB(vd, ap->p, hp->rp->rop);
595 /* brightness over cosine factor */
596 gfact = colval(ap->v,CIEY) / DOT(hp->rp->ron, vd);
597 /* sine = proj_radius/vd_length */
598 dgsum[0] -= DOT(uv[1], vd) * gfact;
599 dgsum[1] += DOT(uv[0], vd) * gfact;
600 }
601 dg[0] = dgsum[0] / (hp->ns*hp->ns);
602 dg[1] = dgsum[1] / (hp->ns*hp->ns);
603 }
604
605
606 /* Compute potential light leak direction flags for cache value */
607 static uint32
608 ambcorral(AMBHEMI *hp, FVECT uv[2], const double r0, const double r1)
609 {
610 const double max_d = 1.0/(minarad*ambacc + 0.001);
611 const double ang_res = 0.5*PI/(hp->ns-1);
612 const double ang_step = ang_res/((int)(16/PI*ang_res) + (1+FTINY));
613 double avg_d = 0;
614 uint32 flgs = 0;
615 FVECT vec;
616 double u, v;
617 double ang, a1;
618 int i, j;
619 /* don't bother for a few samples */
620 if (hp->ns < 12)
621 return(0);
622 /* check distances overhead */
623 for (i = hp->ns*3/4; i-- > hp->ns>>2; )
624 for (j = hp->ns*3/4; j-- > hp->ns>>2; )
625 avg_d += ambsam(hp,i,j).d;
626 avg_d *= 4.0/(hp->ns*hp->ns);
627 if (avg_d*r0 >= 1.0) /* ceiling too low for corral? */
628 return(0);
629 if (avg_d >= max_d) /* insurance */
630 return(0);
631 /* else circle around perimeter */
632 for (i = 0; i < hp->ns; i++)
633 for (j = 0; j < hp->ns; j += !i|(i==hp->ns-1) ? 1 : hp->ns-1) {
634 AMBSAMP *ap = &ambsam(hp,i,j);
635 if ((ap->d <= FTINY) | (ap->d >= max_d))
636 continue; /* too far or too near */
637 VSUB(vec, ap->p, hp->rp->rop);
638 u = DOT(vec, uv[0]);
639 v = DOT(vec, uv[1]);
640 if ((r0*r0*u*u + r1*r1*v*v) * ap->d*ap->d <= u*u + v*v)
641 continue; /* occluder outside ellipse */
642 ang = atan2a(v, u); /* else set direction flags */
643 for (a1 = ang-.5*ang_res; a1 <= ang+.5*ang_res; a1 += ang_step)
644 flgs |= 1L<<(int)(16/PI*(a1 + 2.*PI*(a1 < 0)));
645 }
646 /* add low-angle incident (< 20deg) */
647 if (fabs(hp->rp->rod) <= 0.342) {
648 u = -DOT(hp->rp->rdir, uv[0]);
649 v = -DOT(hp->rp->rdir, uv[1]);
650 if ((r0*r0*u*u + r1*r1*v*v) > hp->rp->rot*hp->rp->rot) {
651 ang = atan2a(v, u);
652 ang += 2.*PI*(ang < 0);
653 ang *= 16/PI;
654 if ((ang < .5) | (ang >= 31.5))
655 flgs |= 0x80000001;
656 else
657 flgs |= 3L<<(int)(ang-.5);
658 }
659 }
660 return(flgs);
661 }
662
663
664 int
665 doambient( /* compute ambient component */
666 COLOR rcol, /* input/output color */
667 RAY *r,
668 double wt,
669 FVECT uv[2], /* returned (optional) */
670 float ra[2], /* returned (optional) */
671 float pg[2], /* returned (optional) */
672 float dg[2], /* returned (optional) */
673 uint32 *crlp /* returned (optional) */
674 )
675 {
676 AMBHEMI *hp = samp_hemi(rcol, r, wt);
677 FVECT my_uv[2];
678 double d, K;
679 AMBSAMP *ap;
680 int i;
681 /* clear return values */
682 if (uv != NULL)
683 memset(uv, 0, sizeof(FVECT)*2);
684 if (ra != NULL)
685 ra[0] = ra[1] = 0.0;
686 if (pg != NULL)
687 pg[0] = pg[1] = 0.0;
688 if (dg != NULL)
689 dg[0] = dg[1] = 0.0;
690 if (crlp != NULL)
691 *crlp = 0;
692 if (hp == NULL) /* sampling falure? */
693 return(0);
694
695 if ((ra == NULL) & (pg == NULL) & (dg == NULL) ||
696 (hp->sampOK < 0) | (hp->ns < 4)) {
697 free(hp); /* Hessian not requested/possible */
698 return(-1); /* value-only return value */
699 }
700 if ((d = bright(rcol)) > FTINY) { /* normalize Y values */
701 d = 0.99*(hp->ns*hp->ns)/d;
702 K = 0.01;
703 } else { /* or fall back on geometric Hessian */
704 K = 1.0;
705 pg = NULL;
706 dg = NULL;
707 crlp = NULL;
708 }
709 ap = hp->sa; /* relative Y channel from here on... */
710 for (i = hp->ns*hp->ns; i--; ap++)
711 colval(ap->v,CIEY) = bright(ap->v)*d + K;
712
713 if (uv == NULL) /* make sure we have axis pointers */
714 uv = my_uv;
715 /* compute radii & pos. gradient */
716 ambHessian(hp, uv, ra, pg);
717
718 if (dg != NULL) /* compute direction gradient */
719 ambdirgrad(hp, uv, dg);
720
721 if (ra != NULL) { /* scale/clamp radii */
722 if (pg != NULL) {
723 if (ra[0]*(d = fabs(pg[0])) > 1.0)
724 ra[0] = 1.0/d;
725 if (ra[1]*(d = fabs(pg[1])) > 1.0)
726 ra[1] = 1.0/d;
727 if (ra[0] > ra[1])
728 ra[0] = ra[1];
729 }
730 if (ra[0] < minarad) {
731 ra[0] = minarad;
732 if (ra[1] < minarad)
733 ra[1] = minarad;
734 }
735 ra[0] *= d = 1.0/sqrt(wt);
736 if ((ra[1] *= d) > 2.0*ra[0])
737 ra[1] = 2.0*ra[0];
738 if (ra[1] > maxarad) {
739 ra[1] = maxarad;
740 if (ra[0] > maxarad)
741 ra[0] = maxarad;
742 }
743 /* flag encroached directions */
744 if ((wt >= 0.89*AVGREFL) & (crlp != NULL))
745 *crlp = ambcorral(hp, uv, ra[0]*ambacc, ra[1]*ambacc);
746 if (pg != NULL) { /* cap gradient if necessary */
747 d = pg[0]*pg[0]*ra[0]*ra[0] + pg[1]*pg[1]*ra[1]*ra[1];
748 if (d > 1.0) {
749 d = 1.0/sqrt(d);
750 pg[0] *= d;
751 pg[1] *= d;
752 }
753 }
754 }
755 free(hp); /* clean up and return */
756 return(1);
757 }
758
759
760 #else /* ! NEWAMB */
761
762
763 void
764 inithemi( /* initialize sampling hemisphere */
765 AMBHEMI *hp,
766 COLOR ac,
767 RAY *r,
768 double wt
769 )
770 {
771 double d;
772 int i;
773 /* set number of divisions */
774 if (ambacc <= FTINY &&
775 wt > (d = 0.8*intens(ac)*r->rweight/(ambdiv*minweight)))
776 wt = d; /* avoid ray termination */
777 hp->nt = sqrt(ambdiv * wt / PI) + 0.5;
778 i = ambacc > FTINY ? 3 : 1; /* minimum number of samples */
779 if (hp->nt < i)
780 hp->nt = i;
781 hp->np = PI * hp->nt + 0.5;
782 /* set number of super-samples */
783 hp->ns = ambssamp * wt + 0.5;
784 /* assign coefficient */
785 copycolor(hp->acoef, ac);
786 d = 1.0/(hp->nt*hp->np);
787 scalecolor(hp->acoef, d);
788 /* make axes */
789 VCOPY(hp->uz, r->ron);
790 hp->uy[0] = hp->uy[1] = hp->uy[2] = 0.0;
791 for (i = 0; i < 3; i++)
792 if (hp->uz[i] < 0.6 && hp->uz[i] > -0.6)
793 break;
794 if (i >= 3)
795 error(CONSISTENCY, "bad ray direction in inithemi");
796 hp->uy[i] = 1.0;
797 fcross(hp->ux, hp->uy, hp->uz);
798 normalize(hp->ux);
799 fcross(hp->uy, hp->uz, hp->ux);
800 }
801
802
803 int
804 divsample( /* sample a division */
805 AMBSAMP *dp,
806 AMBHEMI *h,
807 RAY *r
808 )
809 {
810 RAY ar;
811 int hlist[3];
812 double spt[2];
813 double xd, yd, zd;
814 double b2;
815 double phi;
816 int i;
817 /* ambient coefficient for weight */
818 if (ambacc > FTINY)
819 setcolor(ar.rcoef, AVGREFL, AVGREFL, AVGREFL);
820 else
821 copycolor(ar.rcoef, h->acoef);
822 if (rayorigin(&ar, AMBIENT, r, ar.rcoef) < 0)
823 return(-1);
824 if (ambacc > FTINY) {
825 multcolor(ar.rcoef, h->acoef);
826 scalecolor(ar.rcoef, 1./AVGREFL);
827 }
828 hlist[0] = r->rno;
829 hlist[1] = dp->t;
830 hlist[2] = dp->p;
831 multisamp(spt, 2, urand(ilhash(hlist,3)+dp->n));
832 zd = sqrt((dp->t + spt[0])/h->nt);
833 phi = 2.0*PI * (dp->p + spt[1])/h->np;
834 xd = tcos(phi) * zd;
835 yd = tsin(phi) * zd;
836 zd = sqrt(1.0 - zd*zd);
837 for (i = 0; i < 3; i++)
838 ar.rdir[i] = xd*h->ux[i] +
839 yd*h->uy[i] +
840 zd*h->uz[i];
841 checknorm(ar.rdir);
842 dimlist[ndims++] = dp->t*h->np + dp->p + 90171;
843 rayvalue(&ar);
844 ndims--;
845 multcolor(ar.rcol, ar.rcoef); /* apply coefficient */
846 addcolor(dp->v, ar.rcol);
847 /* use rt to improve gradient calc */
848 if (ar.rt > FTINY && ar.rt < FHUGE)
849 dp->r += 1.0/ar.rt;
850 /* (re)initialize error */
851 if (dp->n++) {
852 b2 = bright(dp->v)/dp->n - bright(ar.rcol);
853 b2 = b2*b2 + dp->k*((dp->n-1)*(dp->n-1));
854 dp->k = b2/(dp->n*dp->n);
855 } else
856 dp->k = 0.0;
857 return(0);
858 }
859
860
861 static int
862 ambcmp( /* decreasing order */
863 const void *p1,
864 const void *p2
865 )
866 {
867 const AMBSAMP *d1 = (const AMBSAMP *)p1;
868 const AMBSAMP *d2 = (const AMBSAMP *)p2;
869
870 if (d1->k < d2->k)
871 return(1);
872 if (d1->k > d2->k)
873 return(-1);
874 return(0);
875 }
876
877
878 static int
879 ambnorm( /* standard order */
880 const void *p1,
881 const void *p2
882 )
883 {
884 const AMBSAMP *d1 = (const AMBSAMP *)p1;
885 const AMBSAMP *d2 = (const AMBSAMP *)p2;
886 int c;
887
888 if ( (c = d1->t - d2->t) )
889 return(c);
890 return(d1->p - d2->p);
891 }
892
893
894 double
895 doambient( /* compute ambient component */
896 COLOR rcol,
897 RAY *r,
898 double wt,
899 FVECT pg,
900 FVECT dg
901 )
902 {
903 double b, d=0;
904 AMBHEMI hemi;
905 AMBSAMP *div;
906 AMBSAMP dnew;
907 double acol[3];
908 AMBSAMP *dp;
909 double arad;
910 int divcnt;
911 int i, j;
912 /* initialize hemisphere */
913 inithemi(&hemi, rcol, r, wt);
914 divcnt = hemi.nt * hemi.np;
915 /* initialize */
916 if (pg != NULL)
917 pg[0] = pg[1] = pg[2] = 0.0;
918 if (dg != NULL)
919 dg[0] = dg[1] = dg[2] = 0.0;
920 setcolor(rcol, 0.0, 0.0, 0.0);
921 if (divcnt == 0)
922 return(0.0);
923 /* allocate super-samples */
924 if (hemi.ns > 0 || pg != NULL || dg != NULL) {
925 div = (AMBSAMP *)malloc(divcnt*sizeof(AMBSAMP));
926 if (div == NULL)
927 error(SYSTEM, "out of memory in doambient");
928 } else
929 div = NULL;
930 /* sample the divisions */
931 arad = 0.0;
932 acol[0] = acol[1] = acol[2] = 0.0;
933 if ((dp = div) == NULL)
934 dp = &dnew;
935 divcnt = 0;
936 for (i = 0; i < hemi.nt; i++)
937 for (j = 0; j < hemi.np; j++) {
938 dp->t = i; dp->p = j;
939 setcolor(dp->v, 0.0, 0.0, 0.0);
940 dp->r = 0.0;
941 dp->n = 0;
942 if (divsample(dp, &hemi, r) < 0) {
943 if (div != NULL)
944 dp++;
945 continue;
946 }
947 arad += dp->r;
948 divcnt++;
949 if (div != NULL)
950 dp++;
951 else
952 addcolor(acol, dp->v);
953 }
954 if (!divcnt) {
955 if (div != NULL)
956 free((void *)div);
957 return(0.0); /* no samples taken */
958 }
959 if (divcnt < hemi.nt*hemi.np) {
960 pg = dg = NULL; /* incomplete sampling */
961 hemi.ns = 0;
962 } else if (arad > FTINY && divcnt/arad < minarad) {
963 hemi.ns = 0; /* close enough */
964 } else if (hemi.ns > 0) { /* else perform super-sampling? */
965 comperrs(div, &hemi); /* compute errors */
966 qsort(div, divcnt, sizeof(AMBSAMP), ambcmp); /* sort divs */
967 /* super-sample */
968 for (i = hemi.ns; i > 0; i--) {
969 dnew = *div;
970 if (divsample(&dnew, &hemi, r) < 0) {
971 dp++;
972 continue;
973 }
974 dp = div; /* reinsert */
975 j = divcnt < i ? divcnt : i;
976 while (--j > 0 && dnew.k < dp[1].k) {
977 *dp = *(dp+1);
978 dp++;
979 }
980 *dp = dnew;
981 }
982 if (pg != NULL || dg != NULL) /* restore order */
983 qsort(div, divcnt, sizeof(AMBSAMP), ambnorm);
984 }
985 /* compute returned values */
986 if (div != NULL) {
987 arad = 0.0; /* note: divcnt may be < nt*np */
988 for (i = hemi.nt*hemi.np, dp = div; i-- > 0; dp++) {
989 arad += dp->r;
990 if (dp->n > 1) {
991 b = 1.0/dp->n;
992 scalecolor(dp->v, b);
993 dp->r *= b;
994 dp->n = 1;
995 }
996 addcolor(acol, dp->v);
997 }
998 b = bright(acol);
999 if (b > FTINY) {
1000 b = 1.0/b; /* compute & normalize gradient(s) */
1001 if (pg != NULL) {
1002 posgradient(pg, div, &hemi);
1003 for (i = 0; i < 3; i++)
1004 pg[i] *= b;
1005 }
1006 if (dg != NULL) {
1007 dirgradient(dg, div, &hemi);
1008 for (i = 0; i < 3; i++)
1009 dg[i] *= b;
1010 }
1011 }
1012 free((void *)div);
1013 }
1014 copycolor(rcol, acol);
1015 if (arad <= FTINY)
1016 arad = maxarad;
1017 else
1018 arad = (divcnt+hemi.ns)/arad;
1019 if (pg != NULL) { /* reduce radius if gradient large */
1020 d = DOT(pg,pg);
1021 if (d*arad*arad > 1.0)
1022 arad = 1.0/sqrt(d);
1023 }
1024 if (arad < minarad) {
1025 arad = minarad;
1026 if (pg != NULL && d*arad*arad > 1.0) { /* cap gradient */
1027 d = 1.0/arad/sqrt(d);
1028 for (i = 0; i < 3; i++)
1029 pg[i] *= d;
1030 }
1031 }
1032 if ((arad /= sqrt(wt)) > maxarad)
1033 arad = maxarad;
1034 return(arad);
1035 }
1036
1037
1038 void
1039 comperrs( /* compute initial error estimates */
1040 AMBSAMP *da, /* assumes standard ordering */
1041 AMBHEMI *hp
1042 )
1043 {
1044 double b, b2;
1045 int i, j;
1046 AMBSAMP *dp;
1047 /* sum differences from neighbors */
1048 dp = da;
1049 for (i = 0; i < hp->nt; i++)
1050 for (j = 0; j < hp->np; j++) {
1051 #ifdef DEBUG
1052 if (dp->t != i || dp->p != j)
1053 error(CONSISTENCY,
1054 "division order in comperrs");
1055 #endif
1056 b = bright(dp[0].v);
1057 if (i > 0) { /* from above */
1058 b2 = bright(dp[-hp->np].v) - b;
1059 b2 *= b2 * 0.25;
1060 dp[0].k += b2;
1061 dp[-hp->np].k += b2;
1062 }
1063 if (j > 0) { /* from behind */
1064 b2 = bright(dp[-1].v) - b;
1065 b2 *= b2 * 0.25;
1066 dp[0].k += b2;
1067 dp[-1].k += b2;
1068 } else { /* around */
1069 b2 = bright(dp[hp->np-1].v) - b;
1070 b2 *= b2 * 0.25;
1071 dp[0].k += b2;
1072 dp[hp->np-1].k += b2;
1073 }
1074 dp++;
1075 }
1076 /* divide by number of neighbors */
1077 dp = da;
1078 for (j = 0; j < hp->np; j++) /* top row */
1079 (dp++)->k *= 1.0/3.0;
1080 if (hp->nt < 2)
1081 return;
1082 for (i = 1; i < hp->nt-1; i++) /* central region */
1083 for (j = 0; j < hp->np; j++)
1084 (dp++)->k *= 0.25;
1085 for (j = 0; j < hp->np; j++) /* bottom row */
1086 (dp++)->k *= 1.0/3.0;
1087 }
1088
1089
1090 void
1091 posgradient( /* compute position gradient */
1092 FVECT gv,
1093 AMBSAMP *da, /* assumes standard ordering */
1094 AMBHEMI *hp
1095 )
1096 {
1097 int i, j;
1098 double nextsine, lastsine, b, d;
1099 double mag0, mag1;
1100 double phi, cosp, sinp, xd, yd;
1101 AMBSAMP *dp;
1102
1103 xd = yd = 0.0;
1104 for (j = 0; j < hp->np; j++) {
1105 dp = da + j;
1106 mag0 = mag1 = 0.0;
1107 lastsine = 0.0;
1108 for (i = 0; i < hp->nt; i++) {
1109 #ifdef DEBUG
1110 if (dp->t != i || dp->p != j)
1111 error(CONSISTENCY,
1112 "division order in posgradient");
1113 #endif
1114 b = bright(dp->v);
1115 if (i > 0) {
1116 d = dp[-hp->np].r;
1117 if (dp[0].r > d) d = dp[0].r;
1118 /* sin(t)*cos(t)^2 */
1119 d *= lastsine * (1.0 - (double)i/hp->nt);
1120 mag0 += d*(b - bright(dp[-hp->np].v));
1121 }
1122 nextsine = sqrt((double)(i+1)/hp->nt);
1123 if (j > 0) {
1124 d = dp[-1].r;
1125 if (dp[0].r > d) d = dp[0].r;
1126 mag1 += d * (nextsine - lastsine) *
1127 (b - bright(dp[-1].v));
1128 } else {
1129 d = dp[hp->np-1].r;
1130 if (dp[0].r > d) d = dp[0].r;
1131 mag1 += d * (nextsine - lastsine) *
1132 (b - bright(dp[hp->np-1].v));
1133 }
1134 dp += hp->np;
1135 lastsine = nextsine;
1136 }
1137 mag0 *= 2.0*PI / hp->np;
1138 phi = 2.0*PI * (double)j/hp->np;
1139 cosp = tcos(phi); sinp = tsin(phi);
1140 xd += mag0*cosp - mag1*sinp;
1141 yd += mag0*sinp + mag1*cosp;
1142 }
1143 for (i = 0; i < 3; i++)
1144 gv[i] = (xd*hp->ux[i] + yd*hp->uy[i])*(hp->nt*hp->np)/PI;
1145 }
1146
1147
1148 void
1149 dirgradient( /* compute direction gradient */
1150 FVECT gv,
1151 AMBSAMP *da, /* assumes standard ordering */
1152 AMBHEMI *hp
1153 )
1154 {
1155 int i, j;
1156 double mag;
1157 double phi, xd, yd;
1158 AMBSAMP *dp;
1159
1160 xd = yd = 0.0;
1161 for (j = 0; j < hp->np; j++) {
1162 dp = da + j;
1163 mag = 0.0;
1164 for (i = 0; i < hp->nt; i++) {
1165 #ifdef DEBUG
1166 if (dp->t != i || dp->p != j)
1167 error(CONSISTENCY,
1168 "division order in dirgradient");
1169 #endif
1170 /* tan(t) */
1171 mag += bright(dp->v)/sqrt(hp->nt/(i+.5) - 1.0);
1172 dp += hp->np;
1173 }
1174 phi = 2.0*PI * (j+.5)/hp->np + PI/2.0;
1175 xd += mag * tcos(phi);
1176 yd += mag * tsin(phi);
1177 }
1178 for (i = 0; i < 3; i++)
1179 gv[i] = xd*hp->ux[i] + yd*hp->uy[i];
1180 }
1181
1182 #endif /* ! NEWAMB */