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.14 by greg, Fri Jun 7 10:04:29 1991 UTC vs.
Revision 2.83 by greg, Sat Apr 26 05:15:17 2014 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines