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.10 by greg, Tue Jun 26 09:00:07 1990 UTC vs.
Revision 2.71 by greg, Fri Apr 11 20:31:37 2014 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines