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 2.42 by greg, Thu Jan 2 09:37:13 1997 UTC vs.
Revision 2.84 by greg, Sat Apr 26 15:54:43 2014 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines