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 2.8 by gwlarson, Wed Dec 16 18:14:57 1998 UTC vs.
Revision 2.92 by greg, Fri Apr 5 01:10:26 2024 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines