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

Comparing ray/src/rt/ambient.c (file contents):
Revision 1.2 by greg, Tue Feb 21 14:34:08 1989 UTC vs.
Revision 2.101 by schorsch, Sun Mar 6 01:13:17 2016 UTC

# Line 1 | Line 1
1 < /* Copyright (c) 1986 Regents of the University of California */
2 <
3 < #ifndef lint
4 < static char SCCSid[] = "$SunId$ LBL";
5 < #endif
6 <
1 > static const char       RCSid[] = "$Id$";
2   /*
3   *  ambient.c - routines dealing with ambient (inter-reflected) component.
4   *
5 < *  The macro AMBFLUSH (if defined) is the number of ambient values
11 < *      to wait before flushing to the ambient file.
12 < *
13 < *     5/9/86
5 > *  Declarations of external symbols in ambient.h
6   */
7  
8 < #include  "ray.h"
8 > #include "copyright.h"
9  
10 < #include  "octree.h"
10 > #include <string.h>
11  
12 + #include  "platform.h"
13 + #include  "ray.h"
14 + #include  "otypes.h"
15 + #include  "resolu.h"
16 + #include  "ambient.h"
17   #include  "random.h"
18 + #include  "pmapamb.h"
19  
20 < #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
20 > #ifndef  OCTSCALE
21 > #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
22 > #endif
23  
24 < extern CUBE  thescene;          /* contains space boundaries */
24 > extern char  *shm_boundary;     /* memory sharing boundary */
25  
26 < extern COLOR  ambval;           /* global ambient component */
27 < extern double  ambacc;          /* ambient accuracy */
28 < extern int  ambres;             /* ambient resolution */
29 < extern int  ambdiv;             /* number of divisions for calculation */
30 < extern int  ambssamp;           /* number of super-samples */
31 < extern int  ambounce;           /* number of ambient bounces */
32 < extern char  *amblist[];        /* ambient include/exclude list */
33 < extern int  ambincl;            /* include == 1, exclude == 0 */
26 > #ifndef  MAXASET
27 > #define  MAXASET        4095    /* maximum number of elements in ambient set */
28 > #endif
29 > OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
30  
31 < OBJECT  ambset[128];            /* ambient include/exclude set */
31 > double  maxarad;                /* maximum ambient radius */
32 > double  minarad;                /* minimum ambient radius */
33  
34 < double  maxarad;                /* maximum ambient radius */
38 < double  minarad;                /* minimum ambient radius */
34 > static AMBTREE  atrunk;         /* our ambient trunk node */
35  
36 < typedef struct ambval {
37 <        FVECT  pos;             /* position in space */
42 <        FVECT  dir;             /* normal direction */
43 <        int  lvl;               /* recursion level of parent ray */
44 <        float  weight;          /* weight of parent ray */
45 <        COLOR  val;             /* computed ambient value */
46 <        float  rad;             /* validity radius */
47 <        struct ambval  *next;   /* next in list */
48 < }  AMBVAL;                      /* ambient value */
36 > static FILE  *ambfp = NULL;     /* ambient file pointer */
37 > static int  nunflshed = 0;      /* number of unflushed ambient values */
38  
39 < typedef struct ambtree {
40 <        AMBVAL  *alist;         /* ambient value list */
41 <        struct ambtree  *kid;   /* 8 child nodes */
42 < }  AMBTREE;                     /* ambient octree */
39 > #ifndef SORT_THRESH
40 > #ifdef SMLMEM
41 > #define SORT_THRESH     ((16L<<20)/sizeof(AMBVAL))
42 > #else
43 > #define SORT_THRESH     ((64L<<20)/sizeof(AMBVAL))
44 > #endif
45 > #endif
46 > #ifndef SORT_INTVL
47 > #define SORT_INTVL      (SORT_THRESH<<1)
48 > #endif
49 > #ifndef MAX_SORT_INTVL
50 > #define MAX_SORT_INTVL  (SORT_INTVL<<6)
51 > #endif
52  
55 typedef struct {
56        float  k;               /* error contribution per sample */
57        COLOR  v;               /* ray sum */
58        int  n;                 /* number of samples */
59        short  t, p;            /* theta, phi indices */
60 }  AMBSAMP;                     /* ambient sample */
53  
54 < static AMBTREE  atrunk;         /* our ambient trunk node */
54 > static double  avsum = 0.;              /* computed ambient value sum (log) */
55 > static unsigned int  navsum = 0;        /* number of values in avsum */
56 > static unsigned int  nambvals = 0;      /* total number of indirect values */
57 > static unsigned int  nambshare = 0;     /* number of values from file */
58 > static unsigned long  ambclock = 0;     /* ambient access clock */
59 > static unsigned long  lastsort = 0;     /* time of last value sort */
60 > static long  sortintvl = SORT_INTVL;    /* time until next sort */
61 > static FILE  *ambinp = NULL;            /* auxiliary file for input */
62 > static long  lastpos = -1;              /* last flush position */
63  
64 < static FILE  *ambfp = NULL;     /* ambient file pointer */
64 > #define MAXACLOCK       (1L<<30)        /* clock turnover value */
65 >        /*
66 >         * Track access times unless we are sharing ambient values
67 >         * through memory on a multiprocessor, when we want to avoid
68 >         * claiming our own memory (copy on write).  Go ahead anyway
69 >         * if more than two thirds of our values are unshared.
70 >         * Compile with -Dtracktime=0 to turn this code off.
71 >         */
72 > #ifndef tracktime
73 > #define tracktime       (shm_boundary == NULL || nambvals > 3*nambshare)
74 > #endif
75  
76 < #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
76 > #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
77  
78 < #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
78 > #define  newambval()    (AMBVAL *)malloc(sizeof(AMBVAL))
79 > #define  freeav(av)     free((void *)av);
80  
81 < double  sumambient(), doambient(), makeambient();
81 > static void initambfile(int creat);
82 > static void avsave(AMBVAL *av);
83 > static AMBVAL *avstore(AMBVAL  *aval);
84 > static AMBTREE *newambtree(void);
85 > static void freeambtree(AMBTREE  *atp);
86  
87 + typedef void unloadtf_t(AMBVAL *);
88 + static unloadtf_t avinsert;
89 + static unloadtf_t av2list;
90 + static unloadtf_t avfree;
91 + static void unloadatree(AMBTREE  *at, unloadtf_t *f);
92  
93 < setambient(afile)                       /* initialize calculation */
94 < char  *afile;
93 > static int aposcmp(const void *avp1, const void *avp2);
94 > static int avlmemi(AMBVAL *avaddr);
95 > static void sortambvals(int always);
96 >
97 > #ifdef  F_SETLKW
98 > static void aflock(int  typ);
99 > #endif
100 >
101 >
102 > void
103 > setambres(                              /* set ambient resolution */
104 >        int  ar
105 > )
106   {
107 <        long  ftell();
108 <        char  **amblp;
109 <        OBJECT  obj;
110 <        AMBVAL  amb;
111 <                                        /* set up ambient set */
112 <        ambset[0] = 0;
113 <        for (amblp = amblist; *amblp != NULL; amblp++) {
114 <                if ((obj = modifier(*amblp)) == OVOID) {
115 <                        sprintf(errmsg, "unknown %s modifier \"%s\"",
116 <                                ambincl ? "include" : "exclude", *amblp);
107 >        ambres = ar < 0 ? 0 : ar;               /* may be done already */
108 >                                                /* set min & max radii */
109 >        if (ar <= 0) {
110 >                minarad = 0;
111 >                maxarad = thescene.cusize*0.2;
112 >        } else {
113 >                minarad = thescene.cusize / ar;
114 >                maxarad = 64.0 * minarad;               /* heuristic */
115 >                if (maxarad > thescene.cusize*0.2)
116 >                        maxarad = thescene.cusize*0.2;
117 >        }
118 >        if (minarad <= FTINY)
119 >                minarad = 10.0*FTINY;
120 >        if (maxarad <= minarad)
121 >                maxarad = 64.0 * minarad;
122 > }
123 >
124 >
125 > void
126 > setambacc(                              /* set ambient accuracy */
127 >        double  newa
128 > )
129 > {
130 >        static double   olda;           /* remember previous setting here */
131 >        
132 >        newa *= (newa > 0);
133 >        if (fabs(newa - olda) >= .05*(newa + olda)) {
134 >                ambacc = newa;
135 >                if (nambvals > 0)
136 >                        sortambvals(1);         /* rebuild tree */
137 >        }
138 > }
139 >
140 >
141 > void
142 > setambient(void)                                /* initialize calculation */
143 > {
144 >        int     readonly = 0;
145 >        long    flen;
146 >        AMBVAL  amb;
147 >                                                /* make sure we're fresh */
148 >        ambdone();
149 >                                                /* init ambient limits */
150 >        setambres(ambres);
151 >        setambacc(ambacc);
152 >        if (ambfile == NULL || !ambfile[0])
153 >                return;
154 >        if (ambacc <= FTINY) {
155 >                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
156 >                                ambfile);
157 >                error(WARNING, errmsg);
158 >                return;
159 >        }
160 >                                                /* open ambient file */
161 >        if ((ambfp = fopen(ambfile, "r+")) == NULL)
162 >                readonly = (ambfp = fopen(ambfile, "r")) != NULL;
163 >        if (ambfp != NULL) {
164 >                initambfile(0);                 /* file exists */
165 >                lastpos = ftell(ambfp);
166 >                while (readambval(&amb, ambfp))
167 >                        avstore(&amb);
168 >                nambshare = nambvals;           /* share loaded values */
169 >                if (readonly) {
170 >                        sprintf(errmsg,
171 >                                "loaded %u values from read-only ambient file",
172 >                                        nambvals);
173                          error(WARNING, errmsg);
174 <                        continue;
174 >                        fclose(ambfp);          /* close file so no writes */
175 >                        ambfp = NULL;
176 >                        return;                 /* avoid ambsync() */
177                  }
178 <                if (!inset(ambset, obj))
179 <                        insertelem(ambset, obj);
178 >                                                /* align file pointer */
179 >                lastpos += (long)nambvals*AMBVALSIZ;
180 >                flen = lseek(fileno(ambfp), (off_t)0, SEEK_END);
181 >                if (flen != lastpos) {
182 >                        sprintf(errmsg,
183 >                        "ignoring last %ld values in ambient file (corrupted)",
184 >                                        (flen - lastpos)/AMBVALSIZ);
185 >                        error(WARNING, errmsg);
186 >                        fseek(ambfp, lastpos, SEEK_SET);
187 >                        ftruncate(fileno(ambfp), (off_t)lastpos);
188 >                }
189 >        } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
190 >                initambfile(1);                 /* else create new file */
191 >                fflush(ambfp);
192 >                lastpos = ftell(ambfp);
193 >        } else {
194 >                sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
195 >                error(SYSTEM, errmsg);
196          }
197 <        maxarad = thescene.cusize / 2.0;                /* maximum radius */
198 <                                                        /* minimum radius */
199 <        minarad = ambres > 0 ? thescene.cusize/ambres : 0.0;
197 > #ifdef  F_SETLKW
198 >        aflock(F_UNLCK);                        /* release file */
199 > #endif
200 > }
201  
202 <                                        /* open ambient file */
203 <        if (afile != NULL)
204 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
205 <                        while (fread(&amb, sizeof(AMBVAL), 1, ambfp) == 1)
206 <                                avinsert(&amb, &atrunk, thescene.cuorg,
207 <                                                thescene.cusize);
208 <                                                        /* align */
209 <                        fseek(ambfp, -(ftell(ambfp)%sizeof(AMBVAL)), 1);
210 <                } else if ((ambfp = fopen(afile, "w")) == NULL) {
211 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
212 <                                        afile);
107 <                        error(SYSTEM, errmsg);
202 >
203 > void
204 > ambdone(void)                   /* close ambient file and free memory */
205 > {
206 >        if (ambfp != NULL) {            /* close ambient file */
207 >                ambsync();
208 >                fclose(ambfp);
209 >                ambfp = NULL;
210 >                if (ambinp != NULL) {  
211 >                        fclose(ambinp);
212 >                        ambinp = NULL;
213                  }
214 +                lastpos = -1;
215 +        }
216 +                                        /* free ambient tree */
217 +        unloadatree(&atrunk, avfree);
218 +                                        /* reset state variables */
219 +        avsum = 0.;
220 +        navsum = 0;
221 +        nambvals = 0;
222 +        nambshare = 0;
223 +        ambclock = 0;
224 +        lastsort = 0;
225 +        sortintvl = SORT_INTVL;
226   }
227  
228  
229 < ambient(acol, r)                /* compute ambient component for ray */
230 < COLOR  acol;
231 < register RAY  *r;
229 > void
230 > ambnotify(                      /* record new modifier */
231 >        OBJECT  obj
232 > )
233   {
234 +        static int  hitlimit = 0;
235 +        OBJREC   *o;
236 +        char  **amblp;
237 +
238 +        if (obj == OVOID) {             /* starting over */
239 +                ambset[0] = 0;
240 +                hitlimit = 0;
241 +                return;
242 +        }
243 +        o = objptr(obj);
244 +        if (hitlimit || !ismodifier(o->otype))
245 +                return;
246 +        for (amblp = amblist; *amblp != NULL; amblp++)
247 +                if (!strcmp(o->oname, *amblp)) {
248 +                        if (ambset[0] >= MAXASET) {
249 +                                error(WARNING, "too many modifiers in ambient list");
250 +                                hitlimit++;
251 +                                return;         /* should this be fatal? */
252 +                        }
253 +                        insertelem(ambset, obj);
254 +                        return;
255 +                }
256 + }
257 +
258 + /************ THE FOLLOWING ROUTINES DIFFER BETWEEN NEW & OLD ***************/
259 +
260 + #ifndef OLDAMB
261 +
262 + #define tfunc(lwr, x, upr)      (((x)-(lwr))/((upr)-(lwr)))
263 +
264 + static int      plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang);
265 + static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
266 +                                AMBTREE *at, FVECT c0, double s);
267 + static int      makeambient(COLOR acol, RAY *r, FVECT rn, int al);
268 + static int      extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
269 +                                FVECT uvw[3]);
270 +
271 + void
272 + multambient(            /* compute ambient component & multiply by coef. */
273 +        COLOR  aval,
274 +        RAY  *r,
275 +        FVECT  nrm
276 + )
277 + {
278          static int  rdepth = 0;                 /* ambient recursion */
279 <        double  wsum;
279 >        COLOR   acol, caustic;
280 >        int     ok;
281 >        double  d, l;
282  
283 <        rdepth++;                               /* increment level */
283 >        /* PMAP: Factor in ambient from photon map, if enabled and ray is
284 >         * ambient. Return as all ambient components accounted for, else
285 >         * continue. */
286 >        if (ambPmap(aval, r, rdepth))
287 >                return;
288  
289 +        /* PMAP: Factor in specular-diffuse ambient (caustics) from photon
290 +         * map, if enabled and ray is primary, else caustic is zero.  Continue
291 +         * with RADIANCE ambient calculation */
292 +        copycolor(caustic, aval);
293 +        ambPmapCaustic(caustic, r, rdepth);
294 +        
295          if (ambdiv <= 0)                        /* no ambient calculation */
296                  goto dumbamb;
297                                                  /* check number of bounces */
298 <        if (rdepth > ambounce)
298 >        if (rdepth >= ambounce)
299                  goto dumbamb;
300                                                  /* check ambient list */
301          if (ambincl != -1 && r->ro != NULL &&
# Line 129 | Line 303 | register RAY  *r;
303                  goto dumbamb;
304  
305          if (ambacc <= FTINY) {                  /* no ambient storage */
306 <                if (doambient(acol, r) == 0.0)
306 >                copycolor(acol, aval);
307 >                rdepth++;
308 >                ok = doambient(acol, r, r->rweight,
309 >                                NULL, NULL, NULL, NULL, NULL);
310 >                rdepth--;
311 >                if (!ok)
312                          goto dumbamb;
313 <                goto done;
313 >                copycolor(aval, acol);
314 >
315 >                /* PMAP: add in caustic */
316 >                addcolor(aval, caustic);
317 >                return;
318          }
319 <                                                /* get ambient value */
319 >
320 >        if (tracktime)                          /* sort to minimize thrashing */
321 >                sortambvals(0);
322 >                                                /* interpolate ambient value */
323          setcolor(acol, 0.0, 0.0, 0.0);
324 <        wsum = sumambient(acol, r, &atrunk, thescene.cuorg, thescene.cusize);
325 <        if (wsum > FTINY)
326 <                scalecolor(acol, 1.0/wsum);
327 <        else if (makeambient(acol, r) == 0.0)
328 <                goto dumbamb;
329 <        goto done;
324 >        d = sumambient(acol, r, nrm, rdepth,
325 >                        &atrunk, thescene.cuorg, thescene.cusize);
326 >                        
327 >        if (d > FTINY) {
328 >                d = 1.0/d;
329 >                scalecolor(acol, d);
330 >                multcolor(aval, acol);
331  
332 +                /* PMAP: add in caustic */
333 +                addcolor(aval, caustic);
334 +                return;
335 +        }
336 +        
337 +        rdepth++;                               /* need to cache new value */
338 +        ok = makeambient(acol, r, nrm, rdepth-1);
339 +        rdepth--;
340 +        
341 +        if (ok) {
342 +                multcolor(aval, acol);          /* computed new value */
343 +
344 +                /* PMAP: add in caustic */
345 +                addcolor(aval, caustic);
346 +                return;
347 +        }
348 +        
349   dumbamb:                                        /* return global value */
350 <        copycolor(acol, ambval);
351 < done:                                           /* must finish here! */
350 >        if ((ambvwt <= 0) | (navsum == 0)) {
351 >                multcolor(aval, ambval);
352 >                
353 >                /* PMAP: add in caustic */
354 >                addcolor(aval, caustic);
355 >                return;
356 >        }
357 >        
358 >        l = bright(ambval);                     /* average in computations */  
359 >        if (l > FTINY) {
360 >                d = (log(l)*(double)ambvwt + avsum) /
361 >                                (double)(ambvwt + navsum);
362 >                d = exp(d) / l;
363 >                scalecolor(aval, d);
364 >                multcolor(aval, ambval);        /* apply color of ambval */
365 >        } else {
366 >                d = exp( avsum / (double)navsum );
367 >                scalecolor(aval, d);            /* neutral color */
368 >        }
369 > }
370 >
371 >
372 > /* Plug a potential leak where ambient cache value is occluded */
373 > static int
374 > plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang)
375 > {
376 >        const double    cost70sq = 0.1169778;   /* cos(70deg)^2 */
377 >        RAY             rtst;
378 >        FVECT           vdif;
379 >        double          normdot, ndotd, nadotd;
380 >        double          a, b, c, t[2];
381 >
382 >        ang += 2.*PI*(ang < 0);                 /* check direction flags */
383 >        if ( !(ap->corral>>(int)(ang*(16./PI)) & 1) )
384 >                return(0);
385 >        /*
386 >         * Generate test ray, targeting 20 degrees above sample point plane
387 >         * along surface normal from cache position.  This should be high
388 >         * enough to miss local geometry we don't really care about.
389 >         */
390 >        VSUB(vdif, ap->pos, r->rop);
391 >        normdot = DOT(anorm, r->ron);
392 >        ndotd = DOT(vdif, r->ron);
393 >        nadotd = DOT(vdif, anorm);
394 >        a = normdot*normdot - cost70sq;
395 >        b = 2.0*(normdot*ndotd - nadotd*cost70sq);
396 >        c = ndotd*ndotd - DOT(vdif,vdif)*cost70sq;
397 >        if (quadratic(t, a, b, c) != 2)
398 >                return(1);                      /* should rarely happen */
399 >        if (t[1] <= FTINY)
400 >                return(0);                      /* should fail behind test */
401 >        rayorigin(&rtst, SHADOW, r, NULL);
402 >        VSUM(rtst.rdir, vdif, anorm, t[1]);     /* further dist. > plane */
403 >        rtst.rmax = normalize(rtst.rdir);       /* short ray test */
404 >        while (localhit(&rtst, &thescene)) {    /* check for occluder */
405 >                if (rtst.ro->omod != OVOID &&
406 >                                (rtst.clipset == NULL ||
407 >                                        !inset(rtst.clipset, rtst.ro->omod)))
408 >                        return(1);              /* plug light leak */
409 >                VCOPY(rtst.rorg, rtst.rop);     /* skip invisible surface */
410 >                rtst.rmax -= rtst.rot;
411 >                rayclear(&rtst);
412 >        }
413 >        return(0);                              /* seems we're OK */
414 > }
415 >
416 >
417 > static double
418 > sumambient(             /* get interpolated ambient value */
419 >        COLOR  acol,
420 >        RAY  *r,
421 >        FVECT  rn,
422 >        int  al,
423 >        AMBTREE  *at,
424 >        FVECT  c0,
425 >        double  s
426 > )
427 > {                       /* initial limit is 10 degrees plus ambacc radians */
428 >        const double    minangle = 10.0 * PI/180.;
429 >        double          maxangle = minangle + ambacc;
430 >        double          wsum = 0.0;
431 >        FVECT           ck0;
432 >        int             i, j;
433 >        AMBVAL          *av;
434 >
435 >        if (at->kid != NULL) {          /* sum children first */                                
436 >                s *= 0.5;
437 >                for (i = 0; i < 8; i++) {
438 >                        for (j = 0; j < 3; j++) {
439 >                                ck0[j] = c0[j];
440 >                                if (1<<j & i)
441 >                                        ck0[j] += s;
442 >                                if (r->rop[j] < ck0[j] - OCTSCALE*s)
443 >                                        break;
444 >                                if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
445 >                                        break;
446 >                        }
447 >                        if (j == 3)
448 >                                wsum += sumambient(acol, r, rn, al,
449 >                                                        at->kid+i, ck0, s);
450 >                }
451 >                                        /* good enough? */
452 >                if (wsum >= 0.05 && s > minarad*10.0)
453 >                        return(wsum);
454 >        }
455 >                                        /* adjust maximum angle */
456 >        if (at->alist != NULL && (at->alist->lvl <= al) & (r->rweight < 0.6))
457 >                maxangle = (maxangle - PI/2.)*pow(r->rweight,0.13) + PI/2.;
458 >                                        /* sum this node */
459 >        for (av = at->alist; av != NULL; av = av->next) {
460 >                double  u, v, d, delta_r2, delta_t2;
461 >                COLOR   ct;
462 >                FVECT   uvw[3];
463 >                                        /* record access */
464 >                if (tracktime)
465 >                        av->latick = ambclock;
466 >                /*
467 >                 *  Ambient level test
468 >                 */
469 >                if (av->lvl > al ||     /* list sorted, so this works */
470 >                                (av->lvl == al) & (av->weight < 0.9*r->rweight))
471 >                        break;
472 >                /*
473 >                 *  Direction test using unperturbed normal
474 >                 */
475 >                decodedir(uvw[2], av->ndir);
476 >                d = DOT(uvw[2], r->ron);
477 >                if (d <= 0.0)           /* >= 90 degrees */
478 >                        continue;
479 >                delta_r2 = 2.0 - 2.0*d; /* approx. radians^2 */
480 >                if (delta_r2 >= maxangle*maxangle)
481 >                        continue;
482 >                /*
483 >                 *  Modified ray behind test
484 >                 */
485 >                VSUB(ck0, r->rop, av->pos);
486 >                d = DOT(ck0, uvw[2]);
487 >                if (d < -minarad*ambacc-.001)
488 >                        continue;
489 >                d /= av->rad[0];
490 >                delta_t2 = d*d;
491 >                if (delta_t2 >= ambacc*ambacc)
492 >                        continue;
493 >                /*
494 >                 *  Elliptical radii test based on Hessian
495 >                 */
496 >                decodedir(uvw[0], av->udir);
497 >                VCROSS(uvw[1], uvw[2], uvw[0]);
498 >                d = (u = DOT(ck0, uvw[0])) / av->rad[0];
499 >                delta_t2 += d*d;
500 >                d = (v = DOT(ck0, uvw[1])) / av->rad[1];
501 >                delta_t2 += d*d;
502 >                if (delta_t2 >= ambacc*ambacc)
503 >                        continue;
504 >                /*
505 >                 *  Test for potential light leak
506 >                 */
507 >                if (av->corral && plugaleak(r, av, uvw[2], atan2a(v,u)))
508 >                        continue;
509 >                /*
510 >                 *  Extrapolate value and compute final weight (hat function)
511 >                 */
512 >                if (!extambient(ct, av, r->rop, rn, uvw))
513 >                        continue;
514 >                d = tfunc(maxangle, sqrt(delta_r2), 0.0) *
515 >                        tfunc(ambacc, sqrt(delta_t2), 0.0);
516 >                scalecolor(ct, d);
517 >                addcolor(acol, ct);
518 >                wsum += d;
519 >        }
520 >        return(wsum);
521 > }
522 >
523 >
524 > static int
525 > makeambient(            /* make a new ambient value for storage */
526 >        COLOR  acol,
527 >        RAY  *r,
528 >        FVECT  rn,
529 >        int  al
530 > )
531 > {
532 >        AMBVAL  amb;
533 >        FVECT   uvw[3];
534 >        int     i;
535 >
536 >        amb.weight = 1.0;                       /* compute weight */
537 >        for (i = al; i-- > 0; )
538 >                amb.weight *= AVGREFL;
539 >        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
540 >                amb.weight = 1.25*r->rweight;
541 >        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
542 >                                                /* compute ambient */
543 >        i = doambient(acol, r, amb.weight,
544 >                        uvw, amb.rad, amb.gpos, amb.gdir, &amb.corral);
545 >        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
546 >        if (i <= 0 || amb.rad[0] <= FTINY)      /* no Hessian or zero radius */
547 >                return(i);
548 >                                                /* store value */
549 >        VCOPY(amb.pos, r->rop);
550 >        amb.ndir = encodedir(r->ron);
551 >        amb.udir = encodedir(uvw[0]);
552 >        amb.lvl = al;
553 >        copycolor(amb.val, acol);
554 >                                                /* insert into tree */
555 >        avsave(&amb);                           /* and save to file */
556 >        if (rn != r->ron) {                     /* texture */
557 >                VCOPY(uvw[2], r->ron);
558 >                extambient(acol, &amb, r->rop, rn, uvw);
559 >        }
560 >        return(1);
561 > }
562 >
563 >
564 > static int
565 > extambient(             /* extrapolate value at pv, nv */
566 >        COLOR  cr,
567 >        AMBVAL   *ap,
568 >        FVECT  pv,
569 >        FVECT  nv,
570 >        FVECT  uvw[3]
571 > )
572 > {
573 >        const double    min_d = 0.05;
574 >        static FVECT    my_uvw[3];
575 >        FVECT           v1;
576 >        int             i;
577 >        double          d = 1.0;        /* zeroeth order */
578 >
579 >        if (uvw == NULL) {              /* need local coordinates? */
580 >                decodedir(my_uvw[2], ap->ndir);
581 >                decodedir(my_uvw[0], ap->udir);
582 >                VCROSS(my_uvw[1], my_uvw[2], my_uvw[0]);
583 >                uvw = my_uvw;
584 >        }
585 >        for (i = 3; i--; )              /* gradient due to translation */
586 >                d += (pv[i] - ap->pos[i]) *
587 >                        (ap->gpos[0]*uvw[0][i] + ap->gpos[1]*uvw[1][i]);
588 >
589 >        VCROSS(v1, uvw[2], nv);         /* gradient due to rotation */
590 >        for (i = 3; i--; )
591 >                d += v1[i] * (ap->gdir[0]*uvw[0][i] + ap->gdir[1]*uvw[1][i]);
592 >        
593 >        if (d < min_d)                  /* should not use if we can avoid it */
594 >                d = min_d;
595 >        copycolor(cr, ap->val);
596 >        scalecolor(cr, d);
597 >        return(d > min_d);
598 > }
599 >
600 >
601 > static void
602 > avinsert(                               /* insert ambient value in our tree */
603 >        AMBVAL *av
604 > )
605 > {
606 >        AMBTREE  *at;
607 >        AMBVAL  *ap;
608 >        AMBVAL  avh;
609 >        FVECT  ck0;
610 >        double  s;
611 >        int  branch;
612 >        int  i;
613 >
614 >        if (av->rad[0] <= FTINY)
615 >                error(CONSISTENCY, "zero ambient radius in avinsert");
616 >        at = &atrunk;
617 >        VCOPY(ck0, thescene.cuorg);
618 >        s = thescene.cusize;
619 >        while (s*(OCTSCALE/2) > av->rad[1]*ambacc) {
620 >                if (at->kid == NULL)
621 >                        if ((at->kid = newambtree()) == NULL)
622 >                                error(SYSTEM, "out of memory in avinsert");
623 >                s *= 0.5;
624 >                branch = 0;
625 >                for (i = 0; i < 3; i++)
626 >                        if (av->pos[i] > ck0[i] + s) {
627 >                                ck0[i] += s;
628 >                                branch |= 1 << i;
629 >                        }
630 >                at = at->kid + branch;
631 >        }
632 >        avh.next = at->alist;           /* order by increasing level */
633 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
634 >                if ( ap->next->lvl > av->lvl ||
635 >                                (ap->next->lvl == av->lvl) &
636 >                                (ap->next->weight <= av->weight) )
637 >                        break;
638 >        av->next = ap->next;
639 >        ap->next = (AMBVAL*)av;
640 >        at->alist = avh.next;
641 > }
642 >
643 >
644 > #else /* ! NEWAMB */
645 >
646 > static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
647 >                                AMBTREE *at, FVECT c0, double s);
648 > static double   makeambient(COLOR acol, RAY *r, FVECT rn, int al);
649 > static void     extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv);
650 >
651 >
652 > void
653 > multambient(            /* compute ambient component & multiply by coef. */
654 >        COLOR  aval,
655 >        RAY  *r,
656 >        FVECT  nrm
657 > )
658 > {
659 >        static int  rdepth = 0;                 /* ambient recursion */
660 >        COLOR   acol, caustic;
661 >        double  d, l;
662 >
663 >        /* PMAP: Factor in ambient from global photon map (if enabled) and return
664 >         * as all ambient components accounted for */
665 >        if (ambPmap(aval, r, rdepth))
666 >                return;
667 >
668 >        /* PMAP: Otherwise factor in ambient from caustic photon map
669 >         * (ambPmapCaustic() returns zero if caustic photons disabled) and
670 >         * continue with RADIANCE ambient calculation */
671 >        copycolor(caustic, aval);
672 >        ambPmapCaustic(caustic, r, rdepth);
673 >        
674 >        if (ambdiv <= 0)                        /* no ambient calculation */
675 >                goto dumbamb;
676 >                                                /* check number of bounces */
677 >        if (rdepth >= ambounce)
678 >                goto dumbamb;
679 >                                                /* check ambient list */
680 >        if (ambincl != -1 && r->ro != NULL &&
681 >                        ambincl != inset(ambset, r->ro->omod))
682 >                goto dumbamb;
683 >
684 >        if (ambacc <= FTINY) {                  /* no ambient storage */
685 >                copycolor(acol, aval);
686 >                rdepth++;
687 >                d = doambient(acol, r, r->rweight, NULL, NULL);
688 >                rdepth--;
689 >                if (d <= FTINY)
690 >                        goto dumbamb;
691 >                copycolor(aval, acol);          
692 >        
693 >           /* PMAP: add in caustic */
694 >                addcolor(aval, caustic);        
695 >                return;
696 >        }
697 >
698 >        if (tracktime)                          /* sort to minimize thrashing */
699 >                sortambvals(0);
700 >                                                /* interpolate ambient value */
701 >        setcolor(acol, 0.0, 0.0, 0.0);
702 >        d = sumambient(acol, r, nrm, rdepth,
703 >                        &atrunk, thescene.cuorg, thescene.cusize);
704 >                        
705 >        if (d > FTINY) {
706 >                d = 1.0/d;
707 >                scalecolor(acol, d);
708 >                multcolor(aval, acol);
709 >                
710 >                /* PMAP: add in caustic */
711 >                addcolor(aval, caustic);        
712 >                return;
713 >        }
714 >        
715 >        rdepth++;                               /* need to cache new value */
716 >        d = makeambient(acol, r, nrm, rdepth-1);
717          rdepth--;
718 +        
719 +        if (d > FTINY) {
720 +                multcolor(aval, acol);          /* got new value */
721 +
722 +                /* PMAP: add in caustic */
723 +                addcolor(aval, caustic);                        
724 +                return;
725 +        }
726 +        
727 + dumbamb:                                        /* return global value */
728 +        if ((ambvwt <= 0) | (navsum == 0)) {
729 +                multcolor(aval, ambval);
730 +
731 +                /* PMAP: add in caustic */
732 +                addcolor(aval, caustic);        
733 +                return;
734 +        }
735 +        
736 +        l = bright(ambval);                     /* average in computations */
737 +        if (l > FTINY) {
738 +                d = (log(l)*(double)ambvwt + avsum) /
739 +                                (double)(ambvwt + navsum);
740 +                d = exp(d) / l;
741 +                scalecolor(aval, d);
742 +                multcolor(aval, ambval);        /* apply color of ambval */
743 +        } else {
744 +                d = exp( avsum / (double)navsum );
745 +                scalecolor(aval, d);            /* neutral color */
746 +        }
747   }
748  
749  
750 < double
751 < sumambient(acol, r, at, c0, s)          /* get interpolated ambient value */
752 < COLOR  acol;
753 < register RAY  *r;
754 < AMBTREE  *at;
755 < FVECT  c0;
756 < double  s;
750 > static double
751 > sumambient(     /* get interpolated ambient value */
752 >        COLOR  acol,
753 >        RAY  *r,
754 >        FVECT  rn,
755 >        int  al,
756 >        AMBTREE  *at,
757 >        FVECT  c0,
758 >        double  s
759 > )
760   {
761 <        extern double  sqrt();
161 <        double  d, e1, e2, wt, wsum;
761 >        double  d, e1, e2, wt, wsum;
762          COLOR  ct;
763          FVECT  ck0;
764          int  i;
765 <        register int  j;
766 <        register AMBVAL  *av;
767 <                                        /* do this node */
765 >        int  j;
766 >        AMBVAL   *av;
767 >
768          wsum = 0.0;
769 +                                        /* do this node */
770          for (av = at->alist; av != NULL; av = av->next) {
771 +                double  rn_dot = -2.0;
772 +                if (tracktime)
773 +                        av->latick = ambclock;
774                  /*
775 <                 *  Ray strength test.
775 >                 *  Ambient level test.
776                   */
777 <                if (av->lvl > r->rlvl || av->weight < r->rweight-FTINY)
778 <                        continue;
777 >                if (av->lvl > al ||     /* list sorted, so this works */
778 >                                (av->lvl == al) & (av->weight < 0.9*r->rweight))
779 >                        break;
780                  /*
781                   *  Ambient radius test.
782                   */
783 <                e1 = 0.0;
784 <                for (j = 0; j < 3; j++) {
180 <                        d = av->pos[j] - r->rop[j];
181 <                        e1 += d * d;
182 <                }
183 <                e1 /= av->rad * av->rad;
783 >                VSUB(ck0, av->pos, r->rop);
784 >                e1 = DOT(ck0, ck0) / (av->rad * av->rad);
785                  if (e1 > ambacc*ambacc*1.21)
786                          continue;
787                  /*
788 <                 *  Normal direction test.
788 >                 *  Direction test using closest normal.
789                   */
790 <                e2 = (1.0 - DOT(av->dir, r->ron)) * r->rweight;
791 <                if (e2 < 0.0) e2 = 0.0;
792 <                if (e1 + e2 > ambacc*ambacc*1.21)
790 >                d = DOT(av->dir, r->ron);
791 >                if (rn != r->ron) {
792 >                        rn_dot = DOT(av->dir, rn);
793 >                        if (rn_dot > 1.0-FTINY)
794 >                                rn_dot = 1.0-FTINY;
795 >                        if (rn_dot >= d-FTINY) {
796 >                                d = rn_dot;
797 >                                rn_dot = -2.0;
798 >                        }
799 >                }
800 >                e2 = (1.0 - d) * r->rweight;
801 >                if (e2 < 0.0)
802 >                        e2 = 0.0;
803 >                else if (e1 + e2 > ambacc*ambacc*1.21)
804                          continue;
805                  /*
806                   *  Ray behind test.
# Line 197 | Line 809 | double  s;
809                  for (j = 0; j < 3; j++)
810                          d += (r->rop[j] - av->pos[j]) *
811                                          (av->dir[j] + r->ron[j]);
812 <                if (d < -minarad)
812 >                if (d*0.5 < -minarad*ambacc-.001)
813                          continue;
814                  /*
815                   *  Jittering final test reduces image artifacts.
816                   */
817 <                wt = sqrt(e1) + sqrt(e2);
818 <                if (wt > ambacc*(0.9 + 0.2*frandom()))
817 >                e1 = sqrt(e1);
818 >                e2 = sqrt(e2);
819 >                wt = e1 + e2;
820 >                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
821                          continue;
822 +                /*
823 +                 *  Recompute directional error using perturbed normal
824 +                 */
825 +                if (rn_dot > 0.0) {
826 +                        e2 = sqrt((1.0 - rn_dot)*r->rweight);
827 +                        wt = e1 + e2;
828 +                }
829                  if (wt <= 1e-3)
830                          wt = 1e3;
831                  else
832                          wt = 1.0 / wt;
833                  wsum += wt;
834 <                copycolor(ct, av->val);
834 >                extambient(ct, av, r->rop, rn);
835                  scalecolor(ct, wt);
836                  addcolor(acol, ct);
837          }
# Line 229 | Line 850 | double  s;
850                                  break;
851                  }
852                  if (j == 3)
853 <                        wsum += sumambient(acol, r, at->kid+i, ck0, s);
853 >                        wsum += sumambient(acol, r, rn, al,
854 >                                                at->kid+i, ck0, s);
855          }
856          return(wsum);
857   }
858  
859  
860 < double
861 < makeambient(acol, r)            /* make a new ambient value */
862 < COLOR  acol;
863 < register RAY  *r;
860 > static double
861 > makeambient(            /* make a new ambient value for storage */
862 >        COLOR  acol,
863 >        RAY  *r,
864 >        FVECT  rn,
865 >        int  al
866 > )
867   {
868 <        AMBVAL  amb;
868 >        AMBVAL  amb;
869 >        FVECT   gp, gd;
870 >        int     i;
871  
872 <        amb.rad = doambient(acol, r);           /* compute ambient */
873 <        if (amb.rad == 0.0)
872 >        amb.weight = 1.0;                       /* compute weight */
873 >        for (i = al; i-- > 0; )
874 >                amb.weight *= AVGREFL;
875 >        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
876 >                amb.weight = 1.25*r->rweight;
877 >        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
878 >                                                /* compute ambient */
879 >        amb.rad = doambient(acol, r, amb.weight, gp, gd);
880 >        if (amb.rad <= FTINY) {
881 >                setcolor(acol, 0.0, 0.0, 0.0);
882                  return(0.0);
883 <                                                /* store it */
883 >        }
884 >        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
885 >                                                /* store value */
886          VCOPY(amb.pos, r->rop);
887          VCOPY(amb.dir, r->ron);
888 <        amb.lvl = r->rlvl;
252 <        amb.weight = r->rweight;
888 >        amb.lvl = al;
889          copycolor(amb.val, acol);
890 +        VCOPY(amb.gpos, gp);
891 +        VCOPY(amb.gdir, gd);
892                                                  /* insert into tree */
893 <        avinsert(&amb, &atrunk, thescene.cuorg, thescene.cusize);
894 <        avsave(&amb);                           /* write to file */
893 >        avsave(&amb);                           /* and save to file */
894 >        if (rn != r->ron)
895 >                extambient(acol, &amb, r->rop, rn);     /* texture */
896          return(amb.rad);
897   }
898  
899  
900 < double
901 < doambient(acol, r)                      /* compute ambient component */
902 < COLOR  acol;
903 < register RAY  *r;
900 > static void
901 > extambient(             /* extrapolate value at pv, nv */
902 >        COLOR  cr,
903 >        AMBVAL   *ap,
904 >        FVECT  pv,
905 >        FVECT  nv
906 > )
907   {
908 <        extern int  ambcmp();
909 <        extern double  sin(), cos(), sqrt();
910 <        double  phi, xd, yd, zd;
269 <        register AMBSAMP  *div;
270 <        AMBSAMP  dnew;
271 <        RAY  ar;
272 <        FVECT  ux, uy;
273 <        double  arad;
274 <        int  ndivs, nt, np, ns, ne, i, j;
275 <        register int  k;
908 >        FVECT  v1;
909 >        int  i;
910 >        double  d;
911  
912 <        setcolor(acol, 0.0, 0.0, 0.0);
913 <                                        /* set number of divisions */
914 <        nt = sqrt(ambdiv * r->rweight * 0.5) + 0.5;
915 <        np = 2 * nt;
916 <        ndivs = nt * np;
917 <                                        /* check first */
918 <        if (ndivs == 0 || rayorigin(&ar, r, AMBIENT, 0.5) < 0)
919 <                return(0.0);
920 <                                        /* set number of super-samples */
921 <        ns = ambssamp * r->rweight + 0.5;
287 <        if (ns > 0) {
288 <                div = (AMBSAMP *)malloc(ndivs*sizeof(AMBSAMP));
289 <                if (div == NULL)
290 <                        error(SYSTEM, "out of memory in doambient");
912 >        d = 1.0;                        /* zeroeth order */
913 >                                        /* gradient due to translation */
914 >        for (i = 0; i < 3; i++)
915 >                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
916 >                                        /* gradient due to rotation */
917 >        VCROSS(v1, ap->dir, nv);
918 >        d += DOT(ap->gdir, v1);
919 >        if (d <= 0.0) {
920 >                setcolor(cr, 0.0, 0.0, 0.0);
921 >                return;
922          }
923 <                                        /* make axes */
924 <        uy[0] = uy[1] = uy[2] = 0.0;
925 <        for (k = 0; k < 3; k++)
926 <                if (r->ron[k] < 0.6 && r->ron[k] > -0.6)
923 >        copycolor(cr, ap->val);
924 >        scalecolor(cr, d);
925 > }
926 >
927 >
928 > static void
929 > avinsert(                               /* insert ambient value in our tree */
930 >        AMBVAL *av
931 > )
932 > {
933 >        AMBTREE  *at;
934 >        AMBVAL  *ap;
935 >        AMBVAL  avh;
936 >        FVECT  ck0;
937 >        double  s;
938 >        int  branch;
939 >        int  i;
940 >
941 >        if (av->rad <= FTINY)
942 >                error(CONSISTENCY, "zero ambient radius in avinsert");
943 >        at = &atrunk;
944 >        VCOPY(ck0, thescene.cuorg);
945 >        s = thescene.cusize;
946 >        while (s*(OCTSCALE/2) > av->rad*ambacc) {
947 >                if (at->kid == NULL)
948 >                        if ((at->kid = newambtree()) == NULL)
949 >                                error(SYSTEM, "out of memory in avinsert");
950 >                s *= 0.5;
951 >                branch = 0;
952 >                for (i = 0; i < 3; i++)
953 >                        if (av->pos[i] > ck0[i] + s) {
954 >                                ck0[i] += s;
955 >                                branch |= 1 << i;
956 >                        }
957 >                at = at->kid + branch;
958 >        }
959 >        avh.next = at->alist;           /* order by increasing level */
960 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
961 >                if ( ap->next->lvl > av->lvl ||
962 >                                (ap->next->lvl == av->lvl) &
963 >                                (ap->next->weight <= av->weight) )
964                          break;
965 <        uy[k] = 1.0;
966 <        fcross(ux, r->ron, uy);
967 <        normalize(ux);
968 <        fcross(uy, ux, r->ron);
969 <                                                /* sample divisions */
970 <        arad = 0.0;
971 <        ne = 0;
972 <        for (i = 0; i < nt; i++)
973 <                for (j = 0; j < np; j++) {
974 <                        rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
975 <                        zd = sqrt((i+frandom())/nt);
976 <                        phi = 2.0*PI * (j+frandom())/np;
977 <                        xd = cos(phi) * zd;
978 <                        yd = sin(phi) * zd;
979 <                        zd = sqrt(1.0 - zd*zd);
980 <                        for (k = 0; k < 3; k++)
981 <                                ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
982 <                        rayvalue(&ar);
983 <                        if (ar.rot < FHUGE)
984 <                                arad += 1.0 / ar.rot;
985 <                        if (ns > 0) {                   /* save division */
986 <                                div[ne].k = 0.0;
987 <                                copycolor(div[ne].v, ar.rcol);
988 <                                div[ne].n = 0;
989 <                                div[ne].t = i; div[ne].p = j;
990 <                                                        /* sum errors */
991 <                                xd = bright(ar.rcol);
992 <                                if (i > 0) {            /* from above */
993 <                                        yd = bright(div[ne-np].v) - xd;
994 <                                        yd *= yd * 0.25;
995 <                                        div[ne].k += yd;
996 <                                        div[ne].n++;
997 <                                        div[ne-np].k += yd;
998 <                                        div[ne-np].n++;
999 <                                }
1000 <                                if (j > 0) {            /* from behind */
1001 <                                        yd = bright(div[ne-1].v) - xd;
1002 <                                        yd *= yd * 0.25;
1003 <                                        div[ne].k += yd;
1004 <                                        div[ne].n++;
1005 <                                        div[ne-1].k += yd;
1006 <                                        div[ne-1].n++;
1007 <                                }
1008 <                                if (j == np-1) {        /* around */
1009 <                                        yd = bright(div[ne-(np-1)].v) - xd;
1010 <                                        yd *= yd * 0.25;
1011 <                                        div[ne].k += yd;
1012 <                                        div[ne].n++;
1013 <                                        div[ne-(np-1)].k += yd;
1014 <                                        div[ne-(np-1)].n++;
1015 <                                }
1016 <                                ne++;
1017 <                        } else
1018 <                                addcolor(acol, ar.rcol);
1019 <                }
1020 <        for (k = 0; k < ne; k++) {              /* compute errors */
1021 <                if (div[k].n > 1)
1022 <                        div[k].k /= div[k].n;
1023 <                div[k].n = 1;
965 >        av->next = ap->next;
966 >        ap->next = (AMBVAL*)av;
967 >        at->alist = avh.next;
968 > }
969 >
970 > #endif  /* ! NEWAMB */
971 >
972 > /************* FOLLOWING ROUTINES SAME FOR NEW & OLD METHODS ***************/
973 >
974 > static void
975 > initambfile(            /* initialize ambient file */
976 >        int  cre8
977 > )
978 > {
979 >        extern char  *progname, *octname;
980 >        static char  *mybuf = NULL;
981 >
982 > #ifdef  F_SETLKW
983 >        aflock(cre8 ? F_WRLCK : F_RDLCK);
984 > #endif
985 >        SET_FILE_BINARY(ambfp);
986 >        if (mybuf == NULL)
987 >                mybuf = (char *)bmalloc(BUFSIZ+8);
988 >        setbuf(ambfp, mybuf);
989 >        if (cre8) {                     /* new file */
990 >                newheader("RADIANCE", ambfp);
991 >                fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
992 >                                progname, colval(ambval,RED),
993 >                                colval(ambval,GRN), colval(ambval,BLU),
994 >                                ambvwt, ambounce, ambacc);
995 >                fprintf(ambfp, "-ad %d -as %d -ar %d ",
996 >                                ambdiv, ambssamp, ambres);
997 >                if (octname != NULL)
998 >                        fputs(octname, ambfp);
999 >                fputc('\n', ambfp);
1000 >                fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
1001 >                fputnow(ambfp);
1002 >                fputformat(AMBFMT, ambfp);
1003 >                fputc('\n', ambfp);
1004 >                putambmagic(ambfp);
1005 >        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
1006 >                error(USER, "bad ambient file");
1007 > }
1008 >
1009 >
1010 > static void
1011 > avsave(                         /* insert and save an ambient value */
1012 >        AMBVAL  *av
1013 > )
1014 > {
1015 >        avstore(av);
1016 >        if (ambfp == NULL)
1017 >                return;
1018 >        if (writambval(av, ambfp) < 0)
1019 >                goto writerr;
1020 >        if (++nunflshed >= AMBFLUSH)
1021 >                if (ambsync() == EOF)
1022 >                        goto writerr;
1023 >        return;
1024 > writerr:
1025 >        error(SYSTEM, "error writing to ambient file");
1026 > }
1027 >
1028 >
1029 > static AMBVAL *
1030 > avstore(                                /* allocate memory and save aval */
1031 >        AMBVAL  *aval
1032 > )
1033 > {
1034 >        AMBVAL  *av;
1035 >        double  d;
1036 >
1037 >        if ((av = newambval()) == NULL)
1038 >                error(SYSTEM, "out of memory in avstore");
1039 >        *av = *aval;
1040 >        av->latick = ambclock;
1041 >        av->next = NULL;
1042 >        nambvals++;
1043 >        d = bright(av->val);
1044 >        if (d > FTINY) {                /* add to log sum for averaging */
1045 >                avsum += log(d);
1046 >                navsum++;
1047          }
1048 <                                                /* sort the divisions */
1049 <        qsort(div, ne, sizeof(AMBSAMP), ambcmp);
1050 <                                                /* skim excess */
1051 <        while (ne > ns) {
1052 <                ne--;
1053 <                addcolor(acol, div[ne].v);
1048 >        avinsert(av);                   /* insert in our cache tree */
1049 >        return(av);
1050 > }
1051 >
1052 >
1053 > #define ATALLOCSZ       512             /* #/8 trees to allocate at once */
1054 >
1055 > static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
1056 >
1057 >
1058 > static AMBTREE *
1059 > newambtree(void)                                /* allocate 8 ambient tree structs */
1060 > {
1061 >        AMBTREE  *atp, *upperlim;
1062 >
1063 >        if (atfreelist == NULL) {       /* get more nodes */
1064 >                atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
1065 >                if (atfreelist == NULL)
1066 >                        return(NULL);
1067 >                                        /* link new free list */
1068 >                upperlim = atfreelist + 8*(ATALLOCSZ-1);
1069 >                for (atp = atfreelist; atp < upperlim; atp += 8)
1070 >                        atp->kid = atp + 8;
1071 >                atp->kid = NULL;
1072          }
1073 <                                                /* super-sample */
1074 <        for (i = ns; i > 0; i--) {
1075 <                rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
1076 <                zd = sqrt((div[0].t+frandom())/nt);
1077 <                phi = 2.0*PI * (div[0].p+frandom())/np;
369 <                xd = cos(phi) * zd;
370 <                yd = sin(phi) * zd;
371 <                zd = sqrt(1.0 - zd*zd);
372 <                for (k = 0; k < 3; k++)
373 <                        ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
374 <                rayvalue(&ar);
375 <                if (ar.rot < FHUGE)
376 <                        arad += 1.0 / ar.rot;
377 <                                                /* recompute error */
378 <                copycolor(dnew.v, div[0].v);
379 <                addcolor(dnew.v, ar.rcol);
380 <                dnew.n = div[0].n + 1;
381 <                dnew.t = div[0].t; dnew.p = div[0].p;
382 <                yd = bright(dnew.v)/dnew.n - bright(ar.rcol);
383 <                yd = yd*yd + div[0].k*(div[0].n*div[0].n);
384 <                dnew.k = yd/(dnew.n*dnew.n);
385 <                                                /* reinsert */
386 <                for (k = 0; k < ne-1 && dnew.k < div[k+1].k; k++)
387 <                        bcopy(&div[k+1], &div[k], sizeof(AMBSAMP));
388 <                bcopy(&dnew, &div[k], sizeof(AMBSAMP));
1073 >        atp = atfreelist;
1074 >        atfreelist = atp->kid;
1075 >        memset((char *)atp, '\0', 8*sizeof(AMBTREE));
1076 >        return(atp);
1077 > }
1078  
1079 <                if (ne >= i) {          /* extract darkest division */
1080 <                        ne--;
1081 <                        if (div[ne].n > 1)
1082 <                                scalecolor(div[ne].v, 1.0/div[ne].n);
1083 <                        addcolor(acol, div[ne].v);
1084 <                }
1079 >
1080 > static void
1081 > freeambtree(                    /* free 8 ambient tree structs */
1082 >        AMBTREE  *atp
1083 > )
1084 > {
1085 >        atp->kid = atfreelist;
1086 >        atfreelist = atp;
1087 > }
1088 >
1089 >
1090 > static void
1091 > unloadatree(                    /* unload an ambient value tree */
1092 >        AMBTREE  *at,
1093 >        unloadtf_t *f
1094 > )
1095 > {
1096 >        AMBVAL  *av;
1097 >        int  i;
1098 >                                        /* transfer values at this node */
1099 >        for (av = at->alist; av != NULL; av = at->alist) {
1100 >                at->alist = av->next;
1101 >                (*f)(av);
1102          }
1103 <        scalecolor(acol, 1.0/ndivs);
1104 <        if (arad <= FTINY)
1105 <                arad = FHUGE;
1106 <        else
1107 <                arad = (ndivs+ns) / arad / sqrt(r->rweight);
1108 <        if (arad > maxarad)
403 <                arad = maxarad;
404 <        else if (arad < minarad)
405 <                arad = minarad;
406 <        if (ns > 0)
407 <                free((char *)div);
408 <        return(arad);
1103 >        if (at->kid == NULL)
1104 >                return;
1105 >        for (i = 0; i < 8; i++)         /* transfer and free children */
1106 >                unloadatree(at->kid+i, f);
1107 >        freeambtree(at->kid);
1108 >        at->kid = NULL;
1109   }
1110  
1111  
1112 + static struct avl {
1113 +        AMBVAL  *p;
1114 +        unsigned long   t;
1115 + }       *avlist1;                       /* ambient value list with ticks */
1116 + static AMBVAL   **avlist2;              /* memory positions for sorting */
1117 + static int      i_avlist;               /* index for lists */
1118 +
1119 + static int alatcmp(const void *av1, const void *av2);
1120 +
1121 + static void
1122 + avfree(AMBVAL *av)
1123 + {
1124 +        free(av);
1125 + }
1126 +
1127 + static void
1128 + av2list(
1129 +        AMBVAL *av
1130 + )
1131 + {
1132 + #ifdef DEBUG
1133 +        if (i_avlist >= nambvals)
1134 +                error(CONSISTENCY, "too many ambient values in av2list1");
1135 + #endif
1136 +        avlist1[i_avlist].p = avlist2[i_avlist] = (AMBVAL*)av;
1137 +        avlist1[i_avlist++].t = av->latick;
1138 + }
1139 +
1140 +
1141   static int
1142 < ambcmp(d1, d2)                          /* decreasing order */
1143 < AMBSAMP  *d1, *d2;
1142 > alatcmp(                        /* compare ambient values for MRA */
1143 >        const void *av1,
1144 >        const void *av2
1145 > )
1146   {
1147 <        if (d1->k < d2->k)
1148 <                return(1);
1149 <        if (d1->k > d2->k)
1147 >        long  lc = ((struct avl *)av2)->t - ((struct avl *)av1)->t;
1148 >        return(lc<0 ? -1 : lc>0 ? 1 : 0);
1149 > }
1150 >
1151 >
1152 > /* GW NOTE 2002/10/3:
1153 > * I used to compare AMBVAL pointers, but found that this was the
1154 > * cause of a serious consistency error with gcc, since the optimizer
1155 > * uses some dangerous trick in pointer subtraction that
1156 > * assumes pointers differ by exact struct size increments.
1157 > */
1158 > static int
1159 > aposcmp(                        /* compare ambient value positions */
1160 >        const void      *avp1,
1161 >        const void      *avp2
1162 > )
1163 > {
1164 >        long    diff = *(char * const *)avp1 - *(char * const *)avp2;
1165 >        if (diff < 0)
1166                  return(-1);
1167 <        return(0);
1167 >        return(diff > 0);
1168   }
1169  
1170  
1171 < static
1172 < avsave(av)                              /* save an ambient value */
1173 < AMBVAL  *av;
1171 > static int
1172 > avlmemi(                                /* find list position from address */
1173 >        AMBVAL  *avaddr
1174 > )
1175   {
1176 < #ifdef  AMBFLUSH
1177 <        static int  nunflshed = 0;
1178 < #endif
1179 <        if (ambfp == NULL)
1176 >        AMBVAL  **avlpp;
1177 >
1178 >        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
1179 >                        nambvals, sizeof(AMBVAL *), &aposcmp);
1180 >        if (avlpp == NULL)
1181 >                error(CONSISTENCY, "address not found in avlmemi");
1182 >        return(avlpp - avlist2);
1183 > }
1184 >
1185 >
1186 > static void
1187 > sortambvals(                    /* resort ambient values */
1188 >        int     always
1189 > )
1190 > {
1191 >        AMBTREE  oldatrunk;
1192 >        AMBVAL  tav, *tap, *pnext;
1193 >        int     i, j;
1194 >                                        /* see if it's time yet */
1195 >        if (!always && (ambclock++ < lastsort+sortintvl ||
1196 >                        nambvals < SORT_THRESH))
1197                  return;
1198 <        if (fwrite(av, sizeof(AMBVAL), 1, ambfp) != 1)
1199 <                goto writerr;
1200 < #ifdef  AMBFLUSH
1201 <        if (++nunflshed >= AMBFLUSH) {
1202 <                if (fflush(ambfp) == EOF)
1203 <                        goto writerr;
1204 <                nunflshed = 0;
1198 >        /*
1199 >         * The idea here is to minimize memory thrashing
1200 >         * in VM systems by improving reference locality.
1201 >         * We do this by periodically sorting our stored ambient
1202 >         * values in memory in order of most recently to least
1203 >         * recently accessed.  This ordering was chosen so that new
1204 >         * ambient values (which tend to be less important) go into
1205 >         * higher memory with the infrequently accessed values.
1206 >         *      Since we expect our values to need sorting less
1207 >         * frequently as the process continues, we double our
1208 >         * waiting interval after each call.
1209 >         *      This routine is also called by setambacc() with
1210 >         * the "always" parameter set to 1 so that the ambient
1211 >         * tree will be rebuilt with the new accuracy parameter.
1212 >         */
1213 >        if (tracktime) {                /* allocate pointer arrays to sort */
1214 >                avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
1215 >                avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
1216 >        } else {
1217 >                avlist2 = NULL;
1218 >                avlist1 = NULL;
1219          }
1220 +        if (avlist1 == NULL) {          /* no time tracking -- rebuild tree? */
1221 +                if (avlist2 != NULL)
1222 +                        free((void *)avlist2);
1223 +                if (always) {           /* rebuild without sorting */
1224 +                        oldatrunk = atrunk;
1225 +                        atrunk.alist = NULL;
1226 +                        atrunk.kid = NULL;
1227 +                        unloadatree(&oldatrunk, avinsert);
1228 +                }
1229 +        } else {                        /* sort memory by last access time */
1230 +                /*
1231 +                 * Sorting memory is tricky because it isn't contiguous.
1232 +                 * We have to sort an array of pointers by MRA and also
1233 +                 * by memory position.  We then copy values in "loops"
1234 +                 * to minimize memory hits.  Nevertheless, we will visit
1235 +                 * everyone at least twice, and this is an expensive process
1236 +                 * when we're thrashing, which is when we need to do it.
1237 +                 */
1238 + #ifdef DEBUG
1239 +                sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
1240 +                                nambvals, ambclock);
1241 +                eputs(errmsg);
1242   #endif
1243 <        return;
1244 < writerr:
1245 <        error(SYSTEM, "error writing ambient file");
1243 >                i_avlist = 0;
1244 >                unloadatree(&atrunk, av2list);  /* empty current tree */
1245 > #ifdef DEBUG
1246 >                if (i_avlist < nambvals)
1247 >                        error(CONSISTENCY, "missing ambient values in sortambvals");
1248 > #endif
1249 >                qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
1250 >                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
1251 >                for (i = 0; i < nambvals; i++) {
1252 >                        if (avlist1[i].p == NULL)
1253 >                                continue;
1254 >                        tap = avlist2[i];
1255 >                        tav = *tap;
1256 >                        for (j = i; (pnext = avlist1[j].p) != tap;
1257 >                                        j = avlmemi(pnext)) {
1258 >                                *(avlist2[j]) = *pnext;
1259 >                                avinsert(avlist2[j]);
1260 >                                avlist1[j].p = NULL;
1261 >                        }
1262 >                        *(avlist2[j]) = tav;
1263 >                        avinsert(avlist2[j]);
1264 >                        avlist1[j].p = NULL;
1265 >                }
1266 >                free((void *)avlist1);
1267 >                free((void *)avlist2);
1268 >                                                /* compute new sort interval */
1269 >                sortintvl = ambclock - lastsort;
1270 >                if (sortintvl >= MAX_SORT_INTVL/2)
1271 >                        sortintvl = MAX_SORT_INTVL;
1272 >                else
1273 >                        sortintvl <<= 1;        /* wait twice as long next */
1274 > #ifdef DEBUG
1275 >                eputs("done\n");
1276 > #endif
1277 >        }
1278 >        if (ambclock >= MAXACLOCK)
1279 >                ambclock = MAXACLOCK/2;
1280 >        lastsort = ambclock;
1281   }
1282  
1283  
1284 < static
1285 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
1286 < AMBVAL  *aval;
1287 < register AMBTREE  *at;
1288 < FVECT  c0;
1289 < double  s;
1284 > #ifdef  F_SETLKW
1285 >
1286 > static void
1287 > aflock(                 /* lock/unlock ambient file */
1288 >        int  typ
1289 > )
1290   {
1291 <        FVECT  ck0;
456 <        int  branch;
457 <        register AMBVAL  *av;
458 <        register int  i;
1291 >        static struct flock  fls;       /* static so initialized to zeroes */
1292  
1293 <        if ((av = newambval()) == NULL)
1294 <                goto memerr;
1295 <        bcopy(aval, av, sizeof(AMBVAL));
1296 <        VCOPY(ck0, c0);
1297 <        while (s*(OCTSCALE/2) > av->rad*ambacc) {
1298 <                if (at->kid == NULL)
1299 <                        if ((at->kid = newambtree()) == NULL)
1300 <                                goto memerr;
1301 <                s *= 0.5;
1302 <                branch = 0;
1303 <                for (i = 0; i < 3; i++)
1304 <                        if (av->pos[i] > ck0[i] + s) {
1305 <                                ck0[i] += s;
1306 <                                branch |= 1 << i;
1293 >        if (typ == fls.l_type)          /* already called? */
1294 >                return;
1295 >        fls.l_type = typ;
1296 >        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
1297 >                error(SYSTEM, "cannot (un)lock ambient file");
1298 > }
1299 >
1300 >
1301 > int
1302 > ambsync(void)                   /* synchronize ambient file */
1303 > {
1304 >        long  flen;
1305 >        AMBVAL  avs;
1306 >        int  n;
1307 >
1308 >        if (ambfp == NULL)      /* no ambient file? */
1309 >                return(0);
1310 >                                /* gain appropriate access */
1311 >        aflock(nunflshed ? F_WRLCK : F_RDLCK);
1312 >                                /* see if file has grown */
1313 >        if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
1314 >                goto seekerr;
1315 >        if ((n = flen - lastpos) > 0) {         /* file has grown */
1316 >                if (ambinp == NULL) {           /* use duplicate filedes */
1317 >                        ambinp = fdopen(dup(fileno(ambfp)), "r");
1318 >                        if (ambinp == NULL)
1319 >                                error(SYSTEM, "fdopen failed in ambsync");
1320 >                }
1321 >                if (fseek(ambinp, lastpos, SEEK_SET) < 0)
1322 >                        goto seekerr;
1323 >                while (n >= AMBVALSIZ) {        /* load contributed values */
1324 >                        if (!readambval(&avs, ambinp)) {
1325 >                                sprintf(errmsg,
1326 >                        "ambient file \"%s\" corrupted near character %ld",
1327 >                                                ambfile, flen - n);
1328 >                                error(WARNING, errmsg);
1329 >                                break;
1330                          }
1331 <                at = at->kid + branch;
1331 >                        avstore(&avs);
1332 >                        n -= AMBVALSIZ;
1333 >                }
1334 >                lastpos = flen - n;
1335 >                /*** seek always as safety measure
1336 >                if (n) ***/                     /* alignment */
1337 >                        if (lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1338 >                                goto seekerr;
1339          }
1340 <        av->next = at->alist;
1341 <        at->alist = av;
1342 <        return;
1343 < memerr:
1344 <        error(SYSTEM, "out of memory in avinsert");
1340 >        n = fflush(ambfp);                      /* calls write() at last */
1341 >        if (n != EOF)
1342 >                lastpos += (long)nunflshed*AMBVALSIZ;
1343 >        else if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
1344 >                goto seekerr;
1345 >                
1346 >        aflock(F_UNLCK);                        /* release file */
1347 >        nunflshed = 0;
1348 >        return(n);
1349 > seekerr:
1350 >        error(SYSTEM, "seek failed in ambsync");
1351 >        return -1; /* pro forma return */
1352   }
1353 +
1354 + #else   /* ! F_SETLKW */
1355 +
1356 + int
1357 + ambsync(void)                   /* flush ambient file */
1358 + {
1359 +        if (ambfp == NULL)
1360 +                return(0);
1361 +        nunflshed = 0;
1362 +        return(fflush(ambfp));
1363 + }
1364 +
1365 + #endif  /* ! F_SETLKW */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines