ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambcomp.c
(Generate patch)

Comparing ray/src/rt/ambcomp.c (file contents):
Revision 1.13 by greg, Thu Aug 22 11:56:58 1991 UTC vs.
Revision 2.98 by greg, Thu Apr 24 01:43:58 2025 UTC

# Line 1 | Line 1
1 /* Copyright (c) 1991 Regents of the University of California */
2
1   #ifndef lint
2 < static char SCCSid[] = "$SunId$ LBL";
2 > static const char       RCSid[] = "$Id$";
3   #endif
6
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  "ray.h"
18 > #include "copyright.h"
19  
20 + #include  "ray.h"
21   #include  "ambient.h"
14
22   #include  "random.h"
23  
24 + #ifndef MINADIV
25 + #define MINADIV         7       /* minimum # divisions in each dimension */
26 + #endif
27 +
28   typedef struct {
29 <        short  t, p;            /* theta, phi indices */
30 <        COLOR  v;               /* value sum */
31 <        float  r;               /* 1/distance sum */
32 <        float  k;               /* variance for this division */
22 <        int  n;                 /* number of subsamples */
23 < }  AMBSAMP;             /* ambient sample division */
29 >        FVECT   p;              /* intersection point */
30 >        float   d;              /* reciprocal distance */
31 >        SCOLOR  v;              /* hemisphere sample value */
32 > } AMBSAMP;              /* sample value */
33  
34   typedef struct {
35 <        FVECT  ux, uy, uz;      /* x, y and z axis directions */
36 <        short  nt, np;          /* number of theta and phi directions */
35 >        RAY     *rp;            /* originating ray sample */
36 >        int     ns;             /* number of samples per axis */
37 >        int     sampOK;         /* acquired full sample set? */
38 >        int     atyp;           /* RAMBIENT or TAMBIENT */
39 >        SCOLOR  acoef;          /* division contribution coefficient */
40 >        SCOLOR  acol;           /* accumulated color */
41 >        FVECT   onrm;           /* oriented unperturbed surface normal */
42 >        FVECT   ux, uy;         /* tangent axis unit vectors */
43 >        AMBSAMP sa[1];          /* sample array (extends struct) */
44   }  AMBHEMI;             /* ambient sample hemisphere */
45  
46 < extern double  sin(), cos(), sqrt();
46 > #define AI(h,i,j)       ((i)*(h)->ns + (j))
47 > #define ambsam(h,i,j)   (h)->sa[AI(h,i,j)]
48  
49 + typedef struct {
50 +        FVECT   r_i, r_i1, e_i, rcp, rI2_eJ2;
51 +        double  I1, I2;
52 + } FFTRI;                /* vectors and coefficients for Hessian calculation */
53  
54 +
55   static int
56 < ambcmp(d1, d2)                          /* decreasing order */
57 < AMBSAMP  *d1, *d2;
56 > ambcollision(                           /* proposed direciton collides? */
57 >        AMBHEMI *hp,
58 >        int     i,
59 >        int     j,
60 >        FVECT   dv
61 > )
62   {
63 <        if (d1->k < d2->k)
64 <                return(1);
65 <        if (d1->k > d2->k)
66 <                return(-1);
67 <        return(0);
63 >        double  cos_thresh;
64 >        int     ii, jj;
65 >                                        /* min. spacing = 1/4th division */
66 >        cos_thresh = (PI/4.)/(double)hp->ns;
67 >        if (cos_thresh > 7.*PI/180.)    /* 7 degrees is enough in any case */
68 >                cos_thresh = 7.*PI/180.;
69 >        cos_thresh = 1. - .5*cos_thresh*cos_thresh;
70 >                                        /* check existing neighbors */
71 >        for (ii = i-1; ii <= i+1; ii++) {
72 >                if (ii < 0) continue;
73 >                if (ii >= hp->ns) break;
74 >                for (jj = j-1; jj <= j+1; jj++) {
75 >                        AMBSAMP *ap;
76 >                        FVECT   avec;
77 >                        double  dprod;
78 >                        if (jj < 0) continue;
79 >                        if (jj >= hp->ns) break;
80 >                        if ((ii==i) & (jj==j)) continue;
81 >                        ap = &ambsam(hp,ii,jj);
82 >                        if (ap->d <= .5/FHUGE)
83 >                                continue;       /* no one home */
84 >                        VSUB(avec, ap->p, hp->rp->rop);
85 >                        dprod = DOT(avec, dv);
86 >                        if (dprod >= cos_thresh*VLEN(avec))
87 >                                return(1);      /* collision */
88 >                }
89 >        }
90 >        return(0);                      /* nothing to worry about */
91   }
92  
93  
94   static int
95 < ambnorm(d1, d2)                         /* standard order */
96 < AMBSAMP  *d1, *d2;
95 > ambsample(                              /* initial ambient division sample */
96 >        AMBHEMI *hp,
97 >        int     i,
98 >        int     j,
99 >        int     n
100 > )
101   {
102 <        register int  c;
102 >        AMBSAMP *ap = &ambsam(hp,i,j);
103 >        RAY     ar;
104 >        int     hlist[3], ii;
105 >        double  ss[2];
106 >        RREAL   spt[2];
107 >        double  zd;
108 >                                        /* generate hemispherical sample */
109 >                                        /* ambient coefficient for weight */
110 >        if (ambacc > FTINY)
111 >                setscolor(ar.rcoef, AVGREFL, AVGREFL, AVGREFL);
112 >        else
113 >                copyscolor(ar.rcoef, hp->acoef);
114 >        if (rayorigin(&ar, hp->atyp, hp->rp, ar.rcoef) < 0)
115 >                return(0);
116 >        if (ambacc > FTINY) {
117 >                smultscolor(ar.rcoef, hp->acoef);
118 >                scalescolor(ar.rcoef, 1./AVGREFL);
119 >        }
120 >        hlist[0] = hp->rp->rno;
121 >        hlist[1] = AI(hp,i,j);
122 >        hlist[2] = samplendx;
123 >        multisamp(ss, 2, urand(ilhash(hlist,3)+n));
124 > resample:
125 >        square2disk(spt, (j+ss[1])/hp->ns, (i+ss[0])/hp->ns);
126 >        zd = sqrt(1. - spt[0]*spt[0] - spt[1]*spt[1]);
127 >        for (ii = 3; ii--; )
128 >                ar.rdir[ii] =   spt[0]*hp->ux[ii] +
129 >                                spt[1]*hp->uy[ii] +
130 >                                zd*hp->onrm[ii];
131 >        checknorm(ar.rdir);
132 >                                        /* avoid coincident samples? */
133 >        if (!n & (ambacc > FTINY) & (hp->ns >= 4) &&
134 >                        ambcollision(hp, i, j, ar.rdir)) {
135 >                ss[0] = frandom(); ss[1] = frandom();
136 >                goto resample;          /* reject this sample */
137 >        }
138 >        dimlist[ndims++] = AI(hp,i,j) + 90171;
139 >        rayvalue(&ar);                  /* evaluate ray */
140 >        ndims--;
141 >        zd = raydistance(&ar);
142 >        if (zd <= FTINY)
143 >                return(0);              /* should never happen */
144 >        smultscolor(ar.rcol, ar.rcoef); /* apply coefficient */
145 >        if (zd*ap->d < 1.0)             /* new/closer distance? */
146 >                ap->d = 1.0/zd;
147 >        if (!n) {                       /* record first vertex & value */
148 >                if (zd > 10.0*thescene.cusize + 1000.)
149 >                        zd = 10.0*thescene.cusize + 1000.;
150 >                VSUM(ap->p, ar.rorg, ar.rdir, zd);
151 >                copyscolor(ap->v, ar.rcol);
152 >        } else {                        /* else update recorded value */
153 >                sopscolor(hp->acol, -=, ap->v);
154 >                zd = 1.0/(double)(n+1);
155 >                scalescolor(ar.rcol, zd);
156 >                zd *= (double)n;
157 >                scalescolor(ap->v, zd);
158 >                saddscolor(ap->v, ar.rcol);
159 >        }
160 >        saddscolor(hp->acol, ap->v);    /* add to our sum */
161 >        return(1);
162 > }
163  
164 <        if (c = d1->t - d2->t)
165 <                return(c);
166 <        return(d1->p - d2->p);
164 >
165 > /* Estimate variance based on ambient division differences */
166 > static float *
167 > getambdiffs(AMBHEMI *hp)
168 > {
169 >        const double    normf = 1./(pbright(hp->acoef) + FTINY);
170 >        float   *earr = (float *)calloc(2*hp->ns*hp->ns, sizeof(float));
171 >        float   *ep;
172 >        AMBSAMP *ap;
173 >        double  b, b1, d2;
174 >        int     i, j;
175 >
176 >        if (earr == NULL)               /* out of memory? */
177 >                return(NULL);
178 >                                        /* sum squared neighbor diffs */
179 >        ap = hp->sa;
180 >        ep = earr + hp->ns*hp->ns;      /* original estimates to scratch */
181 >        for (i = 0; i < hp->ns; i++)
182 >            for (j = 0; j < hp->ns; j++, ap++, ep++) {
183 >                b = pbright(ap[0].v);
184 >                if (i) {                /* from above */
185 >                        b1 = pbright(ap[-hp->ns].v);
186 >                        d2 = b - b1;
187 >                        d2 *= d2*normf/(b + b1 + FTINY);
188 >                        ep[0] += d2;
189 >                        ep[-hp->ns] += d2;
190 >                }
191 >                if (!j) continue;
192 >                                        /* from behind */
193 >                b1 = pbright(ap[-1].v);
194 >                d2 = b - b1;
195 >                d2 *= d2*normf/(b + b1 + FTINY);
196 >                ep[0] += d2;
197 >                ep[-1] += d2;
198 >                if (!i) continue;
199 >                                        /* diagonal */
200 >                b1 = pbright(ap[-hp->ns-1].v);
201 >                d2 = b - b1;
202 >                d2 *= d2*normf/(b + b1 + FTINY);
203 >                ep[0] += d2;
204 >                ep[-hp->ns-1] += d2;
205 >            }
206 >                                        /* correct for number of neighbors */
207 >        ep = earr + hp->ns*hp->ns;
208 >        ep[0] *= 6./3.;
209 >        ep[hp->ns-1] *= 6./3.;
210 >        ep[(hp->ns-1)*hp->ns] *= 6./3.;
211 >        ep[(hp->ns-1)*hp->ns + hp->ns-1] *= 6./3.;
212 >        for (i = 1; i < hp->ns-1; i++) {
213 >                ep[i*hp->ns] *= 6./5.;
214 >                ep[i*hp->ns + hp->ns-1] *= 6./5.;
215 >        }
216 >        for (j = 1; j < hp->ns-1; j++) {
217 >                ep[j] *= 6./5.;
218 >                ep[(hp->ns-1)*hp->ns + j] *= 6./5.;
219 >        }
220 >                                        /* blur final map to reduce bias */
221 >        for (i = 0; i < hp->ns-1; i++) {
222 >            float  *ep2;
223 >            ep = earr + i*hp->ns;
224 >            ep2 = ep + hp->ns*hp->ns;
225 >            for (j = 0; j < hp->ns-1; j++, ep++, ep2++) {
226 >                ep[0] += .5*ep2[0] + .125*(ep2[1] + ep2[hp->ns]);
227 >                ep[1] += .125*ep2[0];
228 >                ep[hp->ns] += .125*ep2[0];
229 >            }
230 >        }
231 >        return(earr);
232   }
233  
234  
235 < divsample(dp, h, r)                     /* sample a division */
236 < register AMBSAMP  *dp;
237 < AMBHEMI  *h;
60 < RAY  *r;
235 > /* Perform super-sampling on hemisphere (introduces bias) */
236 > static void
237 > ambsupersamp(AMBHEMI *hp, int cnt)
238   {
239 <        RAY  ar;
240 <        int  hlist[3];
241 <        double  spt[2];
242 <        double  xd, yd, zd;
66 <        double  b2;
67 <        double  phi;
68 <        register int  i;
239 >        float   *earr = getambdiffs(hp);
240 >        double  e2rem = 0;
241 >        float   *ep;
242 >        int     i, j, n, nss;
243  
244 <        if (rayorigin(&ar, r, AMBIENT, AVGREFL) < 0)
245 <                return(-1);
246 <        hlist[0] = r->rno;
247 <        hlist[1] = dp->t;
248 <        hlist[2] = dp->p;
249 <        multisamp(spt, 2, urand(ilhash(hlist,3)+dp->n));
250 <        zd = sqrt((dp->t + spt[0])/h->nt);
251 <        phi = 2.0*PI * (dp->p + spt[1])/h->np;
252 <        xd = cos(phi) * zd;
253 <        yd = sin(phi) * zd;
254 <        zd = sqrt(1.0 - zd*zd);
255 <        for (i = 0; i < 3; i++)
256 <                ar.rdir[i] =    xd*h->ux[i] +
257 <                                yd*h->uy[i] +
258 <                                zd*h->uz[i];
259 <        dimlist[ndims++] = dp->t*h->np + dp->p + 90171;
260 <        rayvalue(&ar);
87 <        ndims--;
88 <        addcolor(dp->v, ar.rcol);
89 <        if (ar.rt > FTINY && ar.rt < FHUGE)
90 <                dp->r += 1.0/ar.rt;
91 <                                        /* (re)initialize error */
92 <        if (dp->n++) {
93 <                b2 = bright(dp->v)/dp->n - bright(ar.rcol);
94 <                b2 = b2*b2 + dp->k*((dp->n-1)*(dp->n-1));
95 <                dp->k = b2/(dp->n*dp->n);
96 <        } else
97 <                dp->k = 0.0;
98 <        return(0);
244 >        if (earr == NULL)               /* just skip calc. if no memory */
245 >                return;
246 >                                        /* accumulate estimated variances */
247 >        for (ep = earr + hp->ns*hp->ns; ep > earr; )
248 >                e2rem += *--ep;
249 >        ep = earr;                      /* perform super-sampling */
250 >        for (i = 0; i < hp->ns; i++)
251 >            for (j = 0; j < hp->ns; j++) {
252 >                if (e2rem <= FTINY)
253 >                        goto done;      /* nothing left to do */
254 >                nss = *ep/e2rem*cnt + frandom();
255 >                for (n = 1; n <= nss && ambsample(hp,i,j,n); n++)
256 >                        if (!--cnt) goto done;
257 >                e2rem -= *ep++;         /* update remainder */
258 >        }
259 > done:
260 >        free(earr);
261   }
262  
263  
264 < double
265 < doambient(acol, r, wt, pg, dg)          /* compute ambient component */
266 < COLOR  acol;
267 < RAY  *r;
268 < double  wt;
269 < FVECT  pg, dg;
264 > static AMBHEMI *
265 > samp_hemi(                              /* sample indirect hemisphere */
266 >        SCOLOR  rcol,
267 >        RAY     *r,
268 >        double  wt
269 > )
270   {
271 <        double  b, d;
272 <        AMBHEMI  hemi;
273 <        AMBSAMP  *div;
274 <        AMBSAMP  dnew;
275 <        register AMBSAMP  *dp;
276 <        double  arad;
277 <        int  ndivs, ns;
278 <        register int  i, j;
279 <                                        /* initialize color */
280 <        setcolor(acol, 0.0, 0.0, 0.0);
281 <                                        /* initialize hemisphere */
282 <        inithemi(&hemi, r, wt);
283 <        ndivs = hemi.nt * hemi.np;
284 <        if (ndivs == 0)
285 <                return(0.0);
286 <                                        /* set number of super-samples */
287 <        ns = ambssamp * wt + 0.5;
288 <        if (ns > 0 || pg != NULL || dg != NULL) {
289 <                div = (AMBSAMP *)malloc(ndivs*sizeof(AMBSAMP));
290 <                if (div == NULL)
291 <                        error(SYSTEM, "out of memory in doambient");
292 <        } else
293 <                div = NULL;
294 <                                        /* sample the divisions */
295 <        arad = 0.0;
296 <        if ((dp = div) == NULL)
297 <                dp = &dnew;
298 <        for (i = 0; i < hemi.nt; i++)
299 <                for (j = 0; j < hemi.np; j++) {
300 <                        dp->t = i; dp->p = j;
139 <                        setcolor(dp->v, 0.0, 0.0, 0.0);
140 <                        dp->r = 0.0;
141 <                        dp->n = 0;
142 <                        if (divsample(dp, &hemi, r) < 0)
143 <                                goto oopsy;
144 <                        if (div != NULL)
145 <                                dp++;
146 <                        else {
147 <                                addcolor(acol, dp->v);
148 <                                arad += dp->r;
149 <                        }
150 <                }
151 <        if (ns > 0) {                   /* perform super-sampling */
152 <                comperrs(div, &hemi);                   /* compute errors */
153 <                qsort(div, ndivs, sizeof(AMBSAMP), ambcmp);     /* sort divs */
154 <                                                /* super-sample */
155 <                for (i = ns; i > 0; i--) {
156 <                        copystruct(&dnew, div);
157 <                        if (divsample(&dnew, &hemi, r) < 0)
158 <                                goto oopsy;
159 <                                                        /* reinsert */
160 <                        dp = div;
161 <                        j = ndivs < i ? ndivs : i;
162 <                        while (--j > 0 && dnew.k < dp[1].k) {
163 <                                copystruct(dp, dp+1);
164 <                                dp++;
165 <                        }
166 <                        copystruct(dp, &dnew);
167 <                }
168 <                if (pg != NULL || dg != NULL)   /* restore order */
169 <                        qsort(div, ndivs, sizeof(AMBSAMP), ambnorm);
271 >        int     backside = (wt < 0);
272 >        AMBHEMI *hp;
273 >        double  d;
274 >        int     n, i, j;
275 >                                        /* insignificance check */
276 >        d = sintens(rcol);
277 >        if (d <= FTINY)
278 >                return(NULL);
279 >                                        /* set number of divisions */
280 >        if (backside) wt = -wt;
281 >        if (ambacc <= FTINY &&
282 >                        wt > (d *= 0.8*r->rweight/(ambdiv*minweight + 1e-20)))
283 >                wt = d;                 /* avoid ray termination */
284 >        n = sqrt(ambdiv * wt) + 0.5;
285 >        i = 1 + (MINADIV-1)*(ambacc > FTINY);
286 >        if (n < i)                      /* use minimum number of samples? */
287 >                n = i;
288 >                                        /* allocate sampling array */
289 >        hp = (AMBHEMI *)malloc(sizeof(AMBHEMI) + sizeof(AMBSAMP)*(n*n - 1));
290 >        if (hp == NULL)
291 >                error(SYSTEM, "out of memory in samp_hemi");
292 >
293 >        if (backside) {
294 >                hp->atyp = TAMBIENT;
295 >                hp->onrm[0] = -r->ron[0];
296 >                hp->onrm[1] = -r->ron[1];
297 >                hp->onrm[2] = -r->ron[2];
298 >        } else {
299 >                hp->atyp = RAMBIENT;
300 >                VCOPY(hp->onrm, r->ron);
301          }
302 <                                        /* compute returned values */
303 <        if (div != NULL) {
304 <                for (i = ndivs, dp = div; i-- > 0; dp++) {
305 <                        arad += dp->r;
306 <                        if (dp->n > 1) {
307 <                                b = 1.0/dp->n;
308 <                                scalecolor(dp->v, b);
309 <                                dp->r *= b;
310 <                                dp->n = 1;
311 <                        }
312 <                        addcolor(acol, dp->v);
313 <                }
314 <                b = bright(acol);
315 <                if (b > FTINY) {
316 <                        b = ndivs/b;
317 <                        if (pg != NULL) {
318 <                                posgradient(pg, div, &hemi);
319 <                                for (i = 0; i < 3; i++)
320 <                                        pg[i] *= b;
321 <                        }
322 <                        if (dg != NULL) {
192 <                                dirgradient(dg, div, &hemi);
193 <                                for (i = 0; i < 3; i++)
194 <                                        dg[i] *= b;
195 <                        }
196 <                } else {
197 <                        if (pg != NULL)
198 <                                for (i = 0; i < 3; i++)
199 <                                        pg[i] = 0.0;
200 <                        if (dg != NULL)
201 <                                for (i = 0; i < 3; i++)
202 <                                        dg[i] = 0.0;
203 <                }
204 <                free((char *)div);
302 >        hp->rp = r;
303 >        hp->ns = n;
304 >        scolorblack(hp->acol);
305 >        memset(hp->sa, 0, sizeof(AMBSAMP)*n*n);
306 >        hp->sampOK = 0;
307 >                                        /* assign coefficient */
308 >        copyscolor(hp->acoef, rcol);
309 >        d = 1.0/(n*n);
310 >        scalescolor(hp->acoef, d);
311 >                                        /* make tangent plane axes */
312 >        if (!getperpendicular(hp->ux, hp->onrm, 1))
313 >                error(CONSISTENCY, "bad ray direction in samp_hemi");
314 >        VCROSS(hp->uy, hp->onrm, hp->ux);
315 >                                        /* sample divisions */
316 >        for (i = hp->ns; i--; )
317 >            for (j = hp->ns; j--; )
318 >                hp->sampOK += ambsample(hp, i, j, 0);
319 >        copyscolor(rcol, hp->acol);
320 >        if (!hp->sampOK) {              /* utter failure? */
321 >                free(hp);
322 >                return(NULL);
323          }
324 <        b = 1.0/ndivs;
325 <        scalecolor(acol, b);
326 <        if (arad <= FTINY)
209 <                arad = FHUGE;
210 <        else
211 <                arad = (ndivs+ns)/arad;
212 <        if (arad > maxarad)
213 <                arad = maxarad;
214 <        else if (arad < minarad)
215 <                arad = minarad;
216 <        arad /= sqrt(wt);
217 <        if (pg != NULL) {               /* clip pos. gradient if too large */
218 <                d = 4.0*DOT(pg,pg)*arad*arad;
219 <                if (d > 1.0) {
220 <                        d = 1.0/sqrt(d);
221 <                        for (i = 0; i < 3; i++)
222 <                                pg[i] *= d;
223 <                }
324 >        if (hp->sampOK < hp->ns*hp->ns) {
325 >                hp->sampOK *= -1;       /* soft failure */
326 >                return(hp);
327          }
328 <        return(arad);
329 < oopsy:
330 <        if (div != NULL)
331 <                free((char *)div);
332 <        return(0.0);
328 >        if (hp->sampOK <= MINADIV*MINADIV)
329 >                return(hp);             /* don't bother super-sampling */
330 >        n = ambssamp*wt + 0.5;
331 >        if (n >= 4*hp->ns) {            /* perform super-sampling? */
332 >                ambsupersamp(hp, n);
333 >                copyscolor(rcol, hp->acol);
334 >        }
335 >        return(hp);                     /* all is well */
336   }
337  
338  
339 < inithemi(hp, r, wt)             /* initialize sampling hemisphere */
340 < register AMBHEMI  *hp;
341 < RAY  *r;
236 < double  wt;
339 > /* Return brightness of farthest ambient sample */
340 > static double
341 > back_ambval(AMBHEMI *hp, const int n1, const int n2, const int n3)
342   {
343 <        register int  i;
344 <                                        /* set number of divisions */
345 <        hp->nt = sqrt(ambdiv * wt / PI) + 0.5;
346 <        hp->np = PI * hp->nt;
347 <                                        /* make axes */
348 <        VCOPY(hp->uz, r->ron);
349 <        hp->uy[0] = hp->uy[1] = hp->uy[2] = 0.0;
350 <        for (i = 0; i < 3; i++)
246 <                if (hp->uz[i] < 0.6 && hp->uz[i] > -0.6)
247 <                        break;
248 <        if (i >= 3)
249 <                error(CONSISTENCY, "bad ray direction in inithemi");
250 <        hp->uy[i] = 1.0;
251 <        fcross(hp->ux, hp->uy, hp->uz);
252 <        normalize(hp->ux);
253 <        fcross(hp->uy, hp->uz, hp->ux);
343 >        if (hp->sa[n1].d <= hp->sa[n2].d) {
344 >                if (hp->sa[n1].d <= hp->sa[n3].d)
345 >                        return(hp->sa[n1].v[0]);
346 >                return(hp->sa[n3].v[0]);
347 >        }
348 >        if (hp->sa[n2].d <= hp->sa[n3].d)
349 >                return(hp->sa[n2].v[0]);
350 >        return(hp->sa[n3].v[0]);
351   }
352  
353  
354 < comperrs(da, hp)                /* compute initial error estimates */
355 < AMBSAMP  *da;           /* assumes standard ordering */
356 < register AMBHEMI  *hp;
354 > /* Compute vectors and coefficients for Hessian/gradient calcs */
355 > static void
356 > comp_fftri(FFTRI *ftp, AMBHEMI *hp, const int n0, const int n1)
357   {
358 <        double  b, b2;
359 <        int  i, j;
360 <        register AMBSAMP  *dp;
361 <                                /* sum differences from neighbors */
362 <        dp = da;
363 <        for (i = 0; i < hp->nt; i++)
364 <                for (j = 0; j < hp->np; j++) {
365 < #ifdef  DEBUG
366 <                        if (dp->t != i || dp->p != j)
367 <                                error(CONSISTENCY,
368 <                                        "division order in comperrs");
369 < #endif
370 <                        b = bright(dp[0].v);
371 <                        if (i > 0) {            /* from above */
372 <                                b2 = bright(dp[-hp->np].v) - b;
373 <                                b2 *= b2 * 0.25;
374 <                                dp[0].k += b2;
375 <                                dp[-hp->np].k += b2;
376 <                        }
280 <                        if (j > 0) {            /* from behind */
281 <                                b2 = bright(dp[-1].v) - b;
282 <                                b2 *= b2 * 0.25;
283 <                                dp[0].k += b2;
284 <                                dp[-1].k += b2;
285 <                        } else {                /* around */
286 <                                b2 = bright(dp[hp->np-1].v) - b;
287 <                                b2 *= b2 * 0.25;
288 <                                dp[0].k += b2;
289 <                                dp[hp->np-1].k += b2;
290 <                        }
291 <                        dp++;
292 <                }
293 <                                /* divide by number of neighbors */
294 <        dp = da;
295 <        for (j = 0; j < hp->np; j++)            /* top row */
296 <                (dp++)->k *= 1.0/3.0;
297 <        if (hp->nt < 2)
298 <                return;
299 <        for (i = 1; i < hp->nt-1; i++)          /* central region */
300 <                for (j = 0; j < hp->np; j++)
301 <                        (dp++)->k *= 0.25;
302 <        for (j = 0; j < hp->np; j++)            /* bottom row */
303 <                (dp++)->k *= 1.0/3.0;
358 >        double  rdot_cp, dot_e, dot_er, rdot_r, rdot_r1, J2;
359 >        int     ii;
360 >
361 >        VSUB(ftp->r_i, hp->sa[n0].p, hp->rp->rop);
362 >        VSUB(ftp->r_i1, hp->sa[n1].p, hp->rp->rop);
363 >        VSUB(ftp->e_i, hp->sa[n1].p, hp->sa[n0].p);
364 >        VCROSS(ftp->rcp, ftp->r_i, ftp->r_i1);
365 >        rdot_cp = 1.0/DOT(ftp->rcp,ftp->rcp);
366 >        dot_e = DOT(ftp->e_i,ftp->e_i);
367 >        dot_er = DOT(ftp->e_i, ftp->r_i);
368 >        rdot_r = 1.0/DOT(ftp->r_i,ftp->r_i);
369 >        rdot_r1 = 1.0/DOT(ftp->r_i1,ftp->r_i1);
370 >        ftp->I1 = acos( DOT(ftp->r_i, ftp->r_i1) * sqrt(rdot_r*rdot_r1) ) *
371 >                        sqrt( rdot_cp );
372 >        ftp->I2 = ( DOT(ftp->e_i, ftp->r_i1)*rdot_r1 - dot_er*rdot_r +
373 >                        dot_e*ftp->I1 )*0.5*rdot_cp;
374 >        J2 =  ( 0.5*(rdot_r - rdot_r1) - dot_er*ftp->I2 ) / dot_e;
375 >        for (ii = 3; ii--; )
376 >                ftp->rI2_eJ2[ii] = ftp->I2*ftp->r_i[ii] + J2*ftp->e_i[ii];
377   }
378  
379  
380 < posgradient(gv, da, hp)                         /* compute position gradient */
381 < FVECT  gv;
382 < AMBSAMP  *da;                   /* assumes standard ordering */
310 < AMBHEMI  *hp;
380 > /* Compose 3x3 matrix from two vectors */
381 > static void
382 > compose_matrix(FVECT mat[3], FVECT va, FVECT vb)
383   {
384 <        register int  i, j;
385 <        double  b, d;
386 <        double  mag0, mag1;
387 <        double  phi, cosp, sinp, xd, yd;
388 <        register AMBSAMP  *dp;
384 >        mat[0][0] = 2.0*va[0]*vb[0];
385 >        mat[1][1] = 2.0*va[1]*vb[1];
386 >        mat[2][2] = 2.0*va[2]*vb[2];
387 >        mat[0][1] = mat[1][0] = va[0]*vb[1] + va[1]*vb[0];
388 >        mat[0][2] = mat[2][0] = va[0]*vb[2] + va[2]*vb[0];
389 >        mat[1][2] = mat[2][1] = va[1]*vb[2] + va[2]*vb[1];
390 > }
391  
392 <        xd = yd = 0.0;
393 <        for (j = 0; j < hp->np; j++) {
394 <                dp = da + j;
395 <                mag0 = mag1 = 0.0;
396 <                for (i = 0; i < hp->nt; i++) {
397 < #ifdef  DEBUG
398 <                        if (dp->t != i || dp->p != j)
399 <                                error(CONSISTENCY,
400 <                                        "division order in posgradient");
401 < #endif
402 <                        b = bright(dp->v);
403 <                        if (i > 0) {
404 <                                d = dp[-hp->np].r;
405 <                                if (dp[0].r > d) d = dp[0].r;
406 <                                d *= 1.0 - sqrt((double)i/hp->nt);
407 <                                mag0 += d*(b - bright(dp[-hp->np].v));
408 <                        }
409 <                        if (j > 0) {
410 <                                d = dp[-1].r;
411 <                                if (dp[0].r > d) d = dp[0].r;
412 <                                mag1 += d*(b - bright(dp[-1].v));
413 <                        } else {
414 <                                d = dp[hp->np-1].r;
415 <                                if (dp[0].r > d) d = dp[0].r;
416 <                                mag1 += d*(b - bright(dp[hp->np-1].v));
417 <                        }
418 <                        dp += hp->np;
392 >
393 > /* Compute partial 3x3 Hessian matrix for edge */
394 > static void
395 > comp_hessian(FVECT hess[3], FFTRI *ftp, FVECT nrm)
396 > {
397 >        FVECT   ncp;
398 >        FVECT   m1[3], m2[3], m3[3], m4[3];
399 >        double  d1, d2, d3, d4;
400 >        double  I3, J3, K3;
401 >        int     i, j;
402 >                                        /* compute intermediate coefficients */
403 >        d1 = 1.0/DOT(ftp->r_i,ftp->r_i);
404 >        d2 = 1.0/DOT(ftp->r_i1,ftp->r_i1);
405 >        d3 = 1.0/DOT(ftp->e_i,ftp->e_i);
406 >        d4 = DOT(ftp->e_i, ftp->r_i);
407 >        I3 = ( DOT(ftp->e_i, ftp->r_i1)*d2*d2 - d4*d1*d1 + 3.0/d3*ftp->I2 )
408 >                        / ( 4.0*DOT(ftp->rcp,ftp->rcp) );
409 >        J3 = 0.25*d3*(d1*d1 - d2*d2) - d4*d3*I3;
410 >        K3 = d3*(ftp->I2 - I3/d1 - 2.0*d4*J3);
411 >                                        /* intermediate matrices */
412 >        VCROSS(ncp, nrm, ftp->e_i);
413 >        compose_matrix(m1, ncp, ftp->rI2_eJ2);
414 >        compose_matrix(m2, ftp->r_i, ftp->r_i);
415 >        compose_matrix(m3, ftp->e_i, ftp->e_i);
416 >        compose_matrix(m4, ftp->r_i, ftp->e_i);
417 >        d1 = DOT(nrm, ftp->rcp);
418 >        d2 = -d1*ftp->I2;
419 >        d1 *= 2.0;
420 >        for (i = 3; i--; )              /* final matrix sum */
421 >            for (j = 3; j--; ) {
422 >                hess[i][j] = m1[i][j] + d1*( I3*m2[i][j] + K3*m3[i][j] +
423 >                                                2.0*J3*m4[i][j] );
424 >                hess[i][j] += d2*(i==j);
425 >                hess[i][j] *= -1.0/PI;
426 >            }
427 > }
428 >
429 >
430 > /* Reverse hessian calculation result for edge in other direction */
431 > static void
432 > rev_hessian(FVECT hess[3])
433 > {
434 >        int     i;
435 >
436 >        for (i = 3; i--; ) {
437 >                hess[i][0] = -hess[i][0];
438 >                hess[i][1] = -hess[i][1];
439 >                hess[i][2] = -hess[i][2];
440 >        }
441 > }
442 >
443 >
444 > /* Add to radiometric Hessian from the given triangle */
445 > static void
446 > add2hessian(FVECT hess[3], FVECT ehess1[3],
447 >                FVECT ehess2[3], FVECT ehess3[3], double v)
448 > {
449 >        int     i, j;
450 >
451 >        for (i = 3; i--; )
452 >            for (j = 3; j--; )
453 >                hess[i][j] += v*( ehess1[i][j] + ehess2[i][j] + ehess3[i][j] );
454 > }
455 >
456 >
457 > /* Compute partial displacement form factor gradient for edge */
458 > static void
459 > comp_gradient(FVECT grad, FFTRI *ftp, FVECT nrm)
460 > {
461 >        FVECT   ncp;
462 >        double  f1;
463 >        int     i;
464 >
465 >        f1 = 2.0*DOT(nrm, ftp->rcp);
466 >        VCROSS(ncp, nrm, ftp->e_i);
467 >        for (i = 3; i--; )
468 >                grad[i] = (0.5/PI)*( ftp->I1*ncp[i] + f1*ftp->rI2_eJ2[i] );
469 > }
470 >
471 >
472 > /* Reverse gradient calculation result for edge in other direction */
473 > static void
474 > rev_gradient(FVECT grad)
475 > {
476 >        grad[0] = -grad[0];
477 >        grad[1] = -grad[1];
478 >        grad[2] = -grad[2];
479 > }
480 >
481 >
482 > /* Add to displacement gradient from the given triangle */
483 > static void
484 > add2gradient(FVECT grad, FVECT egrad1, FVECT egrad2, FVECT egrad3, double v)
485 > {
486 >        int     i;
487 >
488 >        for (i = 3; i--; )
489 >                grad[i] += v*( egrad1[i] + egrad2[i] + egrad3[i] );
490 > }
491 >
492 >
493 > /* Compute anisotropic radii and eigenvector directions */
494 > static void
495 > eigenvectors(FVECT uv[2], float ra[2], FVECT hessian[3])
496 > {
497 >        double  hess2[2][2];
498 >        FVECT   a, b;
499 >        double  evalue[2], slope1, xmag1;
500 >        int     i;
501 >                                        /* project Hessian to sample plane */
502 >        for (i = 3; i--; ) {
503 >                a[i] = DOT(hessian[i], uv[0]);
504 >                b[i] = DOT(hessian[i], uv[1]);
505 >        }
506 >        hess2[0][0] = DOT(uv[0], a);
507 >        hess2[0][1] = DOT(uv[0], b);
508 >        hess2[1][0] = DOT(uv[1], a);
509 >        hess2[1][1] = DOT(uv[1], b);
510 >                                        /* compute eigenvalue(s) */
511 >        i = quadratic(evalue, 1.0, -hess2[0][0]-hess2[1][1],
512 >                        hess2[0][0]*hess2[1][1]-hess2[0][1]*hess2[1][0]);
513 >        if (i == 1)                     /* double-root (circle) */
514 >                evalue[1] = evalue[0];
515 >        if (!i || ((evalue[0] = fabs(evalue[0])) <= FTINY*FTINY) |
516 >                        ((evalue[1] = fabs(evalue[1])) <= FTINY*FTINY) ) {
517 >                ra[0] = ra[1] = maxarad;
518 >                return;
519 >        }
520 >        if (evalue[0] > evalue[1]) {
521 >                ra[0] = sqrt(sqrt(4.0/evalue[0]));
522 >                ra[1] = sqrt(sqrt(4.0/evalue[1]));
523 >                slope1 = evalue[1];
524 >        } else {
525 >                ra[0] = sqrt(sqrt(4.0/evalue[1]));
526 >                ra[1] = sqrt(sqrt(4.0/evalue[0]));
527 >                slope1 = evalue[0];
528 >        }
529 >                                        /* compute unit eigenvectors */
530 >        if (fabs(hess2[0][1]) <= FTINY)
531 >                return;                 /* uv OK as is */
532 >        slope1 = (slope1 - hess2[0][0]) / hess2[0][1];
533 >        xmag1 = sqrt(1.0/(1.0 + slope1*slope1));
534 >        for (i = 3; i--; ) {
535 >                b[i] = xmag1*uv[0][i] + slope1*xmag1*uv[1][i];
536 >                a[i] = slope1*xmag1*uv[0][i] - xmag1*uv[1][i];
537 >        }
538 >        VCOPY(uv[0], a);
539 >        VCOPY(uv[1], b);
540 > }
541 >
542 >
543 > static void
544 > ambHessian(                             /* anisotropic radii & pos. gradient */
545 >        AMBHEMI *hp,
546 >        FVECT   uv[2],                  /* returned */
547 >        float   ra[2],                  /* returned (optional) */
548 >        float   pg[2]                   /* returned (optional) */
549 > )
550 > {
551 >        static char     memerrmsg[] = "out of memory in ambHessian()";
552 >        FVECT           (*hessrow)[3] = NULL;
553 >        FVECT           *gradrow = NULL;
554 >        FVECT           hessian[3];
555 >        FVECT           gradient;
556 >        FFTRI           fftr;
557 >        int             i, j;
558 >                                        /* be sure to assign unit vectors */
559 >        VCOPY(uv[0], hp->ux);
560 >        VCOPY(uv[1], hp->uy);
561 >                        /* clock-wise vertex traversal from sample POV */
562 >        if (ra != NULL) {               /* initialize Hessian row buffer */
563 >                hessrow = (FVECT (*)[3])malloc(sizeof(FVECT)*3*(hp->ns-1));
564 >                if (hessrow == NULL)
565 >                        error(SYSTEM, memerrmsg);
566 >                memset(hessian, 0, sizeof(hessian));
567 >        } else if (pg == NULL)          /* bogus call? */
568 >                return;
569 >        if (pg != NULL) {               /* initialize form factor row buffer */
570 >                gradrow = (FVECT *)malloc(sizeof(FVECT)*(hp->ns-1));
571 >                if (gradrow == NULL)
572 >                        error(SYSTEM, memerrmsg);
573 >                memset(gradient, 0, sizeof(gradient));
574 >        }
575 >                                        /* compute first row of edges */
576 >        for (j = 0; j < hp->ns-1; j++) {
577 >                comp_fftri(&fftr, hp, AI(hp,0,j), AI(hp,0,j+1));
578 >                if (hessrow != NULL)
579 >                        comp_hessian(hessrow[j], &fftr, hp->onrm);
580 >                if (gradrow != NULL)
581 >                        comp_gradient(gradrow[j], &fftr, hp->onrm);
582 >        }
583 >                                        /* sum each row of triangles */
584 >        for (i = 0; i < hp->ns-1; i++) {
585 >            FVECT       hesscol[3];     /* compute first vertical edge */
586 >            FVECT       gradcol;
587 >            comp_fftri(&fftr, hp, AI(hp,i,0), AI(hp,i+1,0));
588 >            if (hessrow != NULL)
589 >                comp_hessian(hesscol, &fftr, hp->onrm);
590 >            if (gradrow != NULL)
591 >                comp_gradient(gradcol, &fftr, hp->onrm);
592 >            for (j = 0; j < hp->ns-1; j++) {
593 >                FVECT   hessdia[3];     /* compute triangle contributions */
594 >                FVECT   graddia;
595 >                double  backg;
596 >                backg = back_ambval(hp, AI(hp,i,j),
597 >                                        AI(hp,i,j+1), AI(hp,i+1,j));
598 >                                        /* diagonal (inner) edge */
599 >                comp_fftri(&fftr, hp, AI(hp,i,j+1), AI(hp,i+1,j));
600 >                if (hessrow != NULL) {
601 >                    comp_hessian(hessdia, &fftr, hp->onrm);
602 >                    rev_hessian(hesscol);
603 >                    add2hessian(hessian, hessrow[j], hessdia, hesscol, backg);
604                  }
605 <                if (hp->nt > 1) {
606 <                        mag0 /= (double)hp->np;
607 <                        mag1 /= (double)hp->nt;
605 >                if (gradrow != NULL) {
606 >                    comp_gradient(graddia, &fftr, hp->onrm);
607 >                    rev_gradient(gradcol);
608 >                    add2gradient(gradient, gradrow[j], graddia, gradcol, backg);
609                  }
610 <                phi = 2.0*PI * (double)j/hp->np;
611 <                cosp = cos(phi); sinp = sin(phi);
612 <                xd += mag0*cosp - mag1*sinp;
613 <                yd += mag0*sinp + mag1*cosp;
610 >                                        /* initialize edge in next row */
611 >                comp_fftri(&fftr, hp, AI(hp,i+1,j+1), AI(hp,i+1,j));
612 >                if (hessrow != NULL)
613 >                    comp_hessian(hessrow[j], &fftr, hp->onrm);
614 >                if (gradrow != NULL)
615 >                    comp_gradient(gradrow[j], &fftr, hp->onrm);
616 >                                        /* new column edge & paired triangle */
617 >                backg = back_ambval(hp, AI(hp,i+1,j+1),
618 >                                        AI(hp,i+1,j), AI(hp,i,j+1));
619 >                comp_fftri(&fftr, hp, AI(hp,i,j+1), AI(hp,i+1,j+1));
620 >                if (hessrow != NULL) {
621 >                    comp_hessian(hesscol, &fftr, hp->onrm);
622 >                    rev_hessian(hessdia);
623 >                    add2hessian(hessian, hessrow[j], hessdia, hesscol, backg);
624 >                    if (i < hp->ns-2)
625 >                        rev_hessian(hessrow[j]);
626 >                }
627 >                if (gradrow != NULL) {
628 >                    comp_gradient(gradcol, &fftr, hp->onrm);
629 >                    rev_gradient(graddia);
630 >                    add2gradient(gradient, gradrow[j], graddia, gradcol, backg);
631 >                    if (i < hp->ns-2)
632 >                        rev_gradient(gradrow[j]);
633 >                }
634 >            }
635          }
636 <        for (i = 0; i < 3; i++)
637 <                gv[i] = (xd*hp->ux[i] + yd*hp->uy[i])/PI;
636 >                                        /* release row buffers */
637 >        if (hessrow != NULL) free(hessrow);
638 >        if (gradrow != NULL) free(gradrow);
639 >        
640 >        if (ra != NULL)                 /* extract eigenvectors & radii */
641 >                eigenvectors(uv, ra, hessian);
642 >        if (pg != NULL) {               /* tangential position gradient */
643 >                pg[0] = DOT(gradient, uv[0]);
644 >                pg[1] = DOT(gradient, uv[1]);
645 >        }
646   }
647  
648  
649 < dirgradient(gv, da, hp)                         /* compute direction gradient */
650 < FVECT  gv;
651 < AMBSAMP  *da;                   /* assumes standard ordering */
363 < AMBHEMI  *hp;
649 > /* Compute direction gradient from a hemispherical sampling */
650 > static void
651 > ambdirgrad(AMBHEMI *hp, FVECT uv[2], float dg[2])
652   {
653 <        register int  i, j;
654 <        double  mag;
655 <        double  phi, xd, yd;
656 <        register AMBSAMP  *dp;
653 >        AMBSAMP *ap;
654 >        double  dgsum[2];
655 >        int     n;
656 >        FVECT   vd;
657 >        double  gfact;
658  
659 <        xd = yd = 0.0;
660 <        for (j = 0; j < hp->np; j++) {
661 <                dp = da + j;
662 <                mag = 0.0;
663 <                for (i = 0; i < hp->nt; i++) {
664 < #ifdef  DEBUG
665 <                        if (dp->t != i || dp->p != j)
666 <                                error(CONSISTENCY,
667 <                                        "division order in dirgradient");
668 < #endif
669 <                        mag += sqrt((i+.5)/hp->nt)*bright(dp->v);
670 <                        dp += hp->np;
659 >        dgsum[0] = dgsum[1] = 0.0;      /* sum values times -tan(theta) */
660 >        for (ap = hp->sa, n = hp->ns*hp->ns; n--; ap++) {
661 >                                        /* use vector for azimuth + 90deg */
662 >                VSUB(vd, ap->p, hp->rp->rop);
663 >                                        /* brightness over cosine factor */
664 >                gfact = ap->v[0] / DOT(hp->onrm, vd);
665 >                                        /* sine = proj_radius/vd_length */
666 >                dgsum[0] -= DOT(uv[1], vd) * gfact;
667 >                dgsum[1] += DOT(uv[0], vd) * gfact;
668 >        }
669 >        dg[0] = dgsum[0] / (hp->ns*hp->ns);
670 >        dg[1] = dgsum[1] / (hp->ns*hp->ns);
671 > }
672 >
673 >
674 > /* Compute potential light leak direction flags for cache value */
675 > static uint32
676 > ambcorral(AMBHEMI *hp, FVECT uv[2], const double r0, const double r1)
677 > {
678 >        const double    max_d = 1.0/(minarad*ambacc + 0.001);
679 >        const double    ang_res = 0.5*PI/hp->ns;
680 >        const double    ang_step = ang_res/((int)(16/PI*ang_res) + 1.01);
681 >        double          avg_d = 0;
682 >        uint32          flgs = 0;
683 >        FVECT           vec;
684 >        double          u, v;
685 >        double          ang, a1;
686 >        int             i, j;
687 >                                        /* don't bother for a few samples */
688 >        if (hp->ns < 8)
689 >                return(0);
690 >                                        /* check distances overhead */
691 >        for (i = hp->ns*3/4; i-- > hp->ns>>2; )
692 >            for (j = hp->ns*3/4; j-- > hp->ns>>2; )
693 >                avg_d += ambsam(hp,i,j).d;
694 >        avg_d *= 4.0/(hp->ns*hp->ns);
695 >        if (avg_d*r0 >= 1.0)            /* ceiling too low for corral? */
696 >                return(0);
697 >        if (avg_d >= max_d)             /* insurance */
698 >                return(0);
699 >                                        /* else circle around perimeter */
700 >        for (i = 0; i < hp->ns; i++)
701 >            for (j = 0; j < hp->ns; j += !i|(i==hp->ns-1) ? 1 : hp->ns-1) {
702 >                AMBSAMP *ap = &ambsam(hp,i,j);
703 >                if ((ap->d <= FTINY) | (ap->d >= max_d))
704 >                        continue;       /* too far or too near */
705 >                VSUB(vec, ap->p, hp->rp->rop);
706 >                u = DOT(vec, uv[0]);
707 >                v = DOT(vec, uv[1]);
708 >                if ((r0*r0*u*u + r1*r1*v*v) * ap->d*ap->d <= u*u + v*v)
709 >                        continue;       /* occluder outside ellipse */
710 >                ang = atan2a(v, u);     /* else set direction flags */
711 >                for (a1 = ang-ang_res; a1 <= ang+ang_res; a1 += ang_step)
712 >                        flgs |= 1L<<(int)(16/PI*(a1 + 2.*PI*(a1 < 0)));
713 >            }
714 >        return(flgs);
715 > }
716 >
717 >
718 > int
719 > doambient(                              /* compute ambient component */
720 >        SCOLOR  rcol,                   /* input/output color */
721 >        RAY     *r,
722 >        double  wt,                     /* negative for back side */
723 >        FVECT   uv[2],                  /* returned (optional) */
724 >        float   ra[2],                  /* returned (optional) */
725 >        float   pg[2],                  /* returned (optional) */
726 >        float   dg[2],                  /* returned (optional) */
727 >        uint32  *crlp                   /* returned (optional) */
728 > )
729 > {
730 >        AMBHEMI *hp = samp_hemi(rcol, r, wt);
731 >        FVECT   my_uv[2];
732 >        double  d, K;
733 >        AMBSAMP *ap;
734 >        int     i;
735 >                                        /* clear return values */
736 >        if (uv != NULL)
737 >                memset(uv, 0, sizeof(FVECT)*2);
738 >        if (ra != NULL)
739 >                ra[0] = ra[1] = 0.0;
740 >        if (pg != NULL)
741 >                pg[0] = pg[1] = 0.0;
742 >        if (dg != NULL)
743 >                dg[0] = dg[1] = 0.0;
744 >        if (crlp != NULL)
745 >                *crlp = 0;
746 >        if (hp == NULL)                 /* sampling falure? */
747 >                return(0);
748 >
749 >        if ((ra == NULL) & (pg == NULL) & (dg == NULL) ||
750 >                        (hp->sampOK < 0) | (hp->ns < MINADIV)) {
751 >                free(hp);               /* Hessian not requested/possible */
752 >                return(-1);             /* value-only return value */
753 >        }
754 >        if ((d = scolor_mean(rcol)) > FTINY) {
755 >                d = 0.99*(hp->ns*hp->ns)/d;     /* normalize avg. values */
756 >                K = 0.01;
757 >        } else {                        /* or fall back on geometric Hessian */
758 >                K = 1.0;
759 >                pg = NULL;
760 >                dg = NULL;
761 >                crlp = NULL;
762 >        }
763 >        ap = hp->sa;                    /* single channel from here on... */
764 >        for (i = hp->ns*hp->ns; i--; ap++)
765 >                ap->v[0] = scolor_mean(ap->v)*d + K;
766 >
767 >        if (uv == NULL)                 /* make sure we have axis pointers */
768 >                uv = my_uv;
769 >                                        /* compute radii & pos. gradient */
770 >        ambHessian(hp, uv, ra, pg);
771 >
772 >        if (dg != NULL)                 /* compute direction gradient */
773 >                ambdirgrad(hp, uv, dg);
774 >
775 >        if (ra != NULL) {               /* scale/clamp radii */
776 >                if (pg != NULL) {
777 >                        if (ra[0]*(d = fabs(pg[0])) > 1.0)
778 >                                ra[0] = 1.0/d;
779 >                        if (ra[1]*(d = fabs(pg[1])) > 1.0)
780 >                                ra[1] = 1.0/d;
781 >                        if (ra[0] > ra[1])
782 >                                ra[0] = ra[1];
783                  }
784 <                phi = 2.0*PI * (j+.5)/hp->np + PI/2.0;
785 <                xd += mag * cos(phi);
786 <                yd += mag * sin(phi);
784 >                if (ra[0] < minarad) {
785 >                        ra[0] = minarad;
786 >                        if (ra[1] < minarad)
787 >                                ra[1] = minarad;
788 >                }
789 >                ra[0] *= d = 1.0/sqrt(fabs(wt));
790 >                if ((ra[1] *= d) > 2.0*ra[0])
791 >                        ra[1] = 2.0*ra[0];
792 >                if (ra[1] > maxarad) {
793 >                        ra[1] = maxarad;
794 >                        if (ra[0] > maxarad)
795 >                                ra[0] = maxarad;
796 >                }
797 >                                        /* flag encroached directions */
798 >                if (crlp != NULL)       /* XXX doesn't update with changes to ambacc */
799 >                        *crlp = ambcorral(hp, uv, ra[0]*ambacc, ra[1]*ambacc);
800 >                if (pg != NULL) {       /* cap gradient if necessary */
801 >                        d = pg[0]*pg[0]*ra[0]*ra[0] + pg[1]*pg[1]*ra[1]*ra[1];
802 >                        if (d > 1.0) {
803 >                                d = 1.0/sqrt(d);
804 >                                pg[0] *= d;
805 >                                pg[1] *= d;
806 >                        }
807 >                }
808          }
809 <        for (i = 0; i < 3; i++)
810 <                gv[i] = (xd*hp->ux[i] + yd*hp->uy[i])*PI/(hp->nt*hp->np);
809 >        free(hp);                       /* clean up and return */
810 >        return(1);
811   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines