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.50 by schorsch, Thu Jun 5 19:29:34 2003 UTC vs.
Revision 2.101 by schorsch, Sun Mar 6 01:13:17 2016 UTC

# Line 1 | Line 1
1 #ifndef lint
1   static const char       RCSid[] = "$Id$";
3 #endif
2   /*
3   *  ambient.c - routines dealing with ambient (inter-reflected) component.
4   *
# Line 9 | Line 7 | static const char      RCSid[] = "$Id$";
7  
8   #include "copyright.h"
9  
10 + #include <string.h>
11 +
12   #include  "platform.h"
13   #include  "ray.h"
14   #include  "otypes.h"
15 + #include  "resolu.h"
16   #include  "ambient.h"
17   #include  "random.h"
18 + #include  "pmapamb.h"
19  
20   #ifndef  OCTSCALE
21   #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
# Line 21 | Line 23 | static const char      RCSid[] = "$Id$";
23  
24   extern char  *shm_boundary;     /* memory sharing boundary */
25  
26 < #define  MAXASET        511     /* maximum number of elements in ambient set */
26 > #ifndef  MAXASET
27 > #define  MAXASET        4095    /* maximum number of elements in ambient set */
28 > #endif
29   OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
30  
31   double  maxarad;                /* maximum ambient radius */
# Line 34 | Line 38 | static int  nunflshed = 0;     /* number of unflushed ambi
38  
39   #ifndef SORT_THRESH
40   #ifdef SMLMEM
41 < #define SORT_THRESH     ((3L<<20)/sizeof(AMBVAL))
41 > #define SORT_THRESH     ((16L<<20)/sizeof(AMBVAL))
42   #else
43 < #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
43 > #define SORT_THRESH     ((64L<<20)/sizeof(AMBVAL))
44   #endif
45   #endif
46   #ifndef SORT_INTVL
# Line 46 | Line 50 | static int  nunflshed = 0;     /* number of unflushed ambi
50   #define MAX_SORT_INTVL  (SORT_INTVL<<6)
51   #endif
52  
53 +
54   static double  avsum = 0.;              /* computed ambient value sum (log) */
55   static unsigned int  navsum = 0;        /* number of values in avsum */
56   static unsigned int  nambvals = 0;      /* total number of indirect values */
# Line 73 | Line 78 | static long  lastpos = -1;             /* last flush position */
78   #define  newambval()    (AMBVAL *)malloc(sizeof(AMBVAL))
79   #define  freeav(av)     free((void *)av);
80  
81 < static void  initambfile(), avsave(), avinsert(), sortambvals(), unloadatree();
82 < static int  avlmemi();
83 < static AMBVAL  *avstore();
81 > static void initambfile(int creat);
82 > static void avsave(AMBVAL *av);
83 > static AMBVAL *avstore(AMBVAL  *aval);
84 > static AMBTREE *newambtree(void);
85 > static void freeambtree(AMBTREE  *atp);
86 >
87 > typedef void unloadtf_t(AMBVAL *);
88 > static unloadtf_t avinsert;
89 > static unloadtf_t av2list;
90 > static unloadtf_t avfree;
91 > static void unloadatree(AMBTREE  *at, unloadtf_t *f);
92 >
93 > static int aposcmp(const void *avp1, const void *avp2);
94 > static int avlmemi(AMBVAL *avaddr);
95 > static void sortambvals(int always);
96 >
97   #ifdef  F_SETLKW
98 < static void  aflock();
98 > static void aflock(int  typ);
99   #endif
100  
101  
102   void
103 < setambres(ar)                           /* set ambient resolution */
104 < int  ar;
103 > setambres(                              /* set ambient resolution */
104 >        int  ar
105 > )
106   {
107          ambres = ar < 0 ? 0 : ar;               /* may be done already */
108                                                  /* set min & max radii */
109          if (ar <= 0) {
110                  minarad = 0;
111 <                maxarad = thescene.cusize / 2.0;
111 >                maxarad = thescene.cusize*0.2;
112          } else {
113                  minarad = thescene.cusize / ar;
114 <                maxarad = 64 * minarad;                 /* heuristic */
115 <                if (maxarad > thescene.cusize / 2.0)
116 <                        maxarad = thescene.cusize / 2.0;
114 >                maxarad = 64.0 * minarad;               /* heuristic */
115 >                if (maxarad > thescene.cusize*0.2)
116 >                        maxarad = thescene.cusize*0.2;
117          }
118          if (minarad <= FTINY)
119 <                minarad = 10*FTINY;
119 >                minarad = 10.0*FTINY;
120          if (maxarad <= minarad)
121 <                maxarad = 64 * minarad;
121 >                maxarad = 64.0 * minarad;
122   }
123  
124  
125   void
126 < setambacc(newa)                         /* set ambient accuracy */
127 < double  newa;
126 > setambacc(                              /* set ambient accuracy */
127 >        double  newa
128 > )
129   {
130 <        double  ambdiff;
131 <
132 <        if (newa < 0.0)
133 <                newa = 0.0;
134 <        ambdiff = fabs(newa - ambacc);
135 <        if (ambdiff >= .01 && (ambacc = newa) > FTINY && nambvals > 0)
136 <                sortambvals(1);                 /* rebuild tree */
130 >        static double   olda;           /* remember previous setting here */
131 >        
132 >        newa *= (newa > 0);
133 >        if (fabs(newa - olda) >= .05*(newa + olda)) {
134 >                ambacc = newa;
135 >                if (nambvals > 0)
136 >                        sortambvals(1);         /* rebuild tree */
137 >        }
138   }
139  
140  
141   void
142 < setambient()                            /* initialize calculation */
142 > setambient(void)                                /* initialize calculation */
143   {
144          int     readonly = 0;
145 <        long  pos, flen;
145 >        long    flen;
146          AMBVAL  amb;
147                                                  /* make sure we're fresh */
148          ambdone();
# Line 141 | Line 162 | setambient()                           /* initialize calculation */
162                  readonly = (ambfp = fopen(ambfile, "r")) != NULL;
163          if (ambfp != NULL) {
164                  initambfile(0);                 /* file exists */
165 <                pos = ftell(ambfp);
165 >                lastpos = ftell(ambfp);
166                  while (readambval(&amb, ambfp))
167 <                        avinsert(avstore(&amb));
167 >                        avstore(&amb);
168                  nambshare = nambvals;           /* share loaded values */
169                  if (readonly) {
170                          sprintf(errmsg,
# Line 155 | Line 176 | setambient()                           /* initialize calculation */
176                          return;                 /* avoid ambsync() */
177                  }
178                                                  /* align file pointer */
179 <                pos += (long)nambvals*AMBVALSIZ;
180 <                flen = lseek(fileno(ambfp), (off_t)0L, 2);
181 <                if (flen != pos) {
179 >                lastpos += (long)nambvals*AMBVALSIZ;
180 >                flen = lseek(fileno(ambfp), (off_t)0, SEEK_END);
181 >                if (flen != lastpos) {
182                          sprintf(errmsg,
183                          "ignoring last %ld values in ambient file (corrupted)",
184 <                                        (flen - pos)/AMBVALSIZ);
184 >                                        (flen - lastpos)/AMBVALSIZ);
185                          error(WARNING, errmsg);
186 <                        fseek(ambfp, pos, 0);
187 <                        ftruncate(fileno(ambfp), (off_t)pos);
186 >                        fseek(ambfp, lastpos, SEEK_SET);
187 >                        ftruncate(fileno(ambfp), (off_t)lastpos);
188                  }
189          } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
190                  initambfile(1);                 /* else create new file */
191 +                fflush(ambfp);
192 +                lastpos = ftell(ambfp);
193          } else {
194                  sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
195                  error(SYSTEM, errmsg);
196          }
197 <        nunflshed++;    /* lie */
198 <        ambsync();
197 > #ifdef  F_SETLKW
198 >        aflock(F_UNLCK);                        /* release file */
199 > #endif
200   }
201  
202  
203   void
204 < ambdone()                       /* close ambient file and free memory */
204 > ambdone(void)                   /* close ambient file and free memory */
205   {
206          if (ambfp != NULL) {            /* close ambient file */
207                  ambsync();
# Line 190 | Line 214 | ambdone()                      /* close ambient file and free memory */
214                  lastpos = -1;
215          }
216                                          /* free ambient tree */
217 <        unloadatree(&atrunk, free);
217 >        unloadatree(&atrunk, avfree);
218                                          /* reset state variables */
219          avsum = 0.;
220          navsum = 0;
# Line 203 | Line 227 | ambdone()                      /* close ambient file and free memory */
227  
228  
229   void
230 < ambnotify(obj)                  /* record new modifier */
231 < OBJECT  obj;
230 > ambnotify(                      /* record new modifier */
231 >        OBJECT  obj
232 > )
233   {
234          static int  hitlimit = 0;
235 <        register OBJREC  *o;
236 <        register char  **amblp;
235 >        OBJREC   *o;
236 >        char  **amblp;
237  
238          if (obj == OVOID) {             /* starting over */
239                  ambset[0] = 0;
# Line 230 | Line 255 | OBJECT obj;
255                  }
256   }
257  
258 + /************ THE FOLLOWING ROUTINES DIFFER BETWEEN NEW & OLD ***************/
259  
260 + #ifndef OLDAMB
261 +
262 + #define tfunc(lwr, x, upr)      (((x)-(lwr))/((upr)-(lwr)))
263 +
264 + static int      plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang);
265 + static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
266 +                                AMBTREE *at, FVECT c0, double s);
267 + static int      makeambient(COLOR acol, RAY *r, FVECT rn, int al);
268 + static int      extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
269 +                                FVECT uvw[3]);
270 +
271   void
272 < ambient(acol, r, nrm)           /* compute ambient component for ray */
273 < COLOR  acol;
274 < register RAY  *r;
275 < FVECT  nrm;
272 > multambient(            /* compute ambient component & multiply by coef. */
273 >        COLOR  aval,
274 >        RAY  *r,
275 >        FVECT  nrm
276 > )
277   {
278          static int  rdepth = 0;                 /* ambient recursion */
279 +        COLOR   acol, caustic;
280 +        int     ok;
281          double  d, l;
282  
283 +        /* PMAP: Factor in ambient from photon map, if enabled and ray is
284 +         * ambient. Return as all ambient components accounted for, else
285 +         * continue. */
286 +        if (ambPmap(aval, r, rdepth))
287 +                return;
288 +
289 +        /* PMAP: Factor in specular-diffuse ambient (caustics) from photon
290 +         * map, if enabled and ray is primary, else caustic is zero.  Continue
291 +         * with RADIANCE ambient calculation */
292 +        copycolor(caustic, aval);
293 +        ambPmapCaustic(caustic, r, rdepth);
294 +        
295          if (ambdiv <= 0)                        /* no ambient calculation */
296                  goto dumbamb;
297                                                  /* check number of bounces */
# Line 251 | Line 303 | FVECT  nrm;
303                  goto dumbamb;
304  
305          if (ambacc <= FTINY) {                  /* no ambient storage */
306 +                copycolor(acol, aval);
307                  rdepth++;
308 +                ok = doambient(acol, r, r->rweight,
309 +                                NULL, NULL, NULL, NULL, NULL);
310 +                rdepth--;
311 +                if (!ok)
312 +                        goto dumbamb;
313 +                copycolor(aval, acol);
314 +
315 +                /* PMAP: add in caustic */
316 +                addcolor(aval, caustic);
317 +                return;
318 +        }
319 +
320 +        if (tracktime)                          /* sort to minimize thrashing */
321 +                sortambvals(0);
322 +                                                /* interpolate ambient value */
323 +        setcolor(acol, 0.0, 0.0, 0.0);
324 +        d = sumambient(acol, r, nrm, rdepth,
325 +                        &atrunk, thescene.cuorg, thescene.cusize);
326 +                        
327 +        if (d > FTINY) {
328 +                d = 1.0/d;
329 +                scalecolor(acol, d);
330 +                multcolor(aval, acol);
331 +
332 +                /* PMAP: add in caustic */
333 +                addcolor(aval, caustic);
334 +                return;
335 +        }
336 +        
337 +        rdepth++;                               /* need to cache new value */
338 +        ok = makeambient(acol, r, nrm, rdepth-1);
339 +        rdepth--;
340 +        
341 +        if (ok) {
342 +                multcolor(aval, acol);          /* computed new value */
343 +
344 +                /* PMAP: add in caustic */
345 +                addcolor(aval, caustic);
346 +                return;
347 +        }
348 +        
349 + dumbamb:                                        /* return global value */
350 +        if ((ambvwt <= 0) | (navsum == 0)) {
351 +                multcolor(aval, ambval);
352 +                
353 +                /* PMAP: add in caustic */
354 +                addcolor(aval, caustic);
355 +                return;
356 +        }
357 +        
358 +        l = bright(ambval);                     /* average in computations */  
359 +        if (l > FTINY) {
360 +                d = (log(l)*(double)ambvwt + avsum) /
361 +                                (double)(ambvwt + navsum);
362 +                d = exp(d) / l;
363 +                scalecolor(aval, d);
364 +                multcolor(aval, ambval);        /* apply color of ambval */
365 +        } else {
366 +                d = exp( avsum / (double)navsum );
367 +                scalecolor(aval, d);            /* neutral color */
368 +        }
369 + }
370 +
371 +
372 + /* Plug a potential leak where ambient cache value is occluded */
373 + static int
374 + plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang)
375 + {
376 +        const double    cost70sq = 0.1169778;   /* cos(70deg)^2 */
377 +        RAY             rtst;
378 +        FVECT           vdif;
379 +        double          normdot, ndotd, nadotd;
380 +        double          a, b, c, t[2];
381 +
382 +        ang += 2.*PI*(ang < 0);                 /* check direction flags */
383 +        if ( !(ap->corral>>(int)(ang*(16./PI)) & 1) )
384 +                return(0);
385 +        /*
386 +         * Generate test ray, targeting 20 degrees above sample point plane
387 +         * along surface normal from cache position.  This should be high
388 +         * enough to miss local geometry we don't really care about.
389 +         */
390 +        VSUB(vdif, ap->pos, r->rop);
391 +        normdot = DOT(anorm, r->ron);
392 +        ndotd = DOT(vdif, r->ron);
393 +        nadotd = DOT(vdif, anorm);
394 +        a = normdot*normdot - cost70sq;
395 +        b = 2.0*(normdot*ndotd - nadotd*cost70sq);
396 +        c = ndotd*ndotd - DOT(vdif,vdif)*cost70sq;
397 +        if (quadratic(t, a, b, c) != 2)
398 +                return(1);                      /* should rarely happen */
399 +        if (t[1] <= FTINY)
400 +                return(0);                      /* should fail behind test */
401 +        rayorigin(&rtst, SHADOW, r, NULL);
402 +        VSUM(rtst.rdir, vdif, anorm, t[1]);     /* further dist. > plane */
403 +        rtst.rmax = normalize(rtst.rdir);       /* short ray test */
404 +        while (localhit(&rtst, &thescene)) {    /* check for occluder */
405 +                if (rtst.ro->omod != OVOID &&
406 +                                (rtst.clipset == NULL ||
407 +                                        !inset(rtst.clipset, rtst.ro->omod)))
408 +                        return(1);              /* plug light leak */
409 +                VCOPY(rtst.rorg, rtst.rop);     /* skip invisible surface */
410 +                rtst.rmax -= rtst.rot;
411 +                rayclear(&rtst);
412 +        }
413 +        return(0);                              /* seems we're OK */
414 + }
415 +
416 +
417 + static double
418 + sumambient(             /* get interpolated ambient value */
419 +        COLOR  acol,
420 +        RAY  *r,
421 +        FVECT  rn,
422 +        int  al,
423 +        AMBTREE  *at,
424 +        FVECT  c0,
425 +        double  s
426 + )
427 + {                       /* initial limit is 10 degrees plus ambacc radians */
428 +        const double    minangle = 10.0 * PI/180.;
429 +        double          maxangle = minangle + ambacc;
430 +        double          wsum = 0.0;
431 +        FVECT           ck0;
432 +        int             i, j;
433 +        AMBVAL          *av;
434 +
435 +        if (at->kid != NULL) {          /* sum children first */                                
436 +                s *= 0.5;
437 +                for (i = 0; i < 8; i++) {
438 +                        for (j = 0; j < 3; j++) {
439 +                                ck0[j] = c0[j];
440 +                                if (1<<j & i)
441 +                                        ck0[j] += s;
442 +                                if (r->rop[j] < ck0[j] - OCTSCALE*s)
443 +                                        break;
444 +                                if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
445 +                                        break;
446 +                        }
447 +                        if (j == 3)
448 +                                wsum += sumambient(acol, r, rn, al,
449 +                                                        at->kid+i, ck0, s);
450 +                }
451 +                                        /* good enough? */
452 +                if (wsum >= 0.05 && s > minarad*10.0)
453 +                        return(wsum);
454 +        }
455 +                                        /* adjust maximum angle */
456 +        if (at->alist != NULL && (at->alist->lvl <= al) & (r->rweight < 0.6))
457 +                maxangle = (maxangle - PI/2.)*pow(r->rweight,0.13) + PI/2.;
458 +                                        /* sum this node */
459 +        for (av = at->alist; av != NULL; av = av->next) {
460 +                double  u, v, d, delta_r2, delta_t2;
461 +                COLOR   ct;
462 +                FVECT   uvw[3];
463 +                                        /* record access */
464 +                if (tracktime)
465 +                        av->latick = ambclock;
466 +                /*
467 +                 *  Ambient level test
468 +                 */
469 +                if (av->lvl > al ||     /* list sorted, so this works */
470 +                                (av->lvl == al) & (av->weight < 0.9*r->rweight))
471 +                        break;
472 +                /*
473 +                 *  Direction test using unperturbed normal
474 +                 */
475 +                decodedir(uvw[2], av->ndir);
476 +                d = DOT(uvw[2], r->ron);
477 +                if (d <= 0.0)           /* >= 90 degrees */
478 +                        continue;
479 +                delta_r2 = 2.0 - 2.0*d; /* approx. radians^2 */
480 +                if (delta_r2 >= maxangle*maxangle)
481 +                        continue;
482 +                /*
483 +                 *  Modified ray behind test
484 +                 */
485 +                VSUB(ck0, r->rop, av->pos);
486 +                d = DOT(ck0, uvw[2]);
487 +                if (d < -minarad*ambacc-.001)
488 +                        continue;
489 +                d /= av->rad[0];
490 +                delta_t2 = d*d;
491 +                if (delta_t2 >= ambacc*ambacc)
492 +                        continue;
493 +                /*
494 +                 *  Elliptical radii test based on Hessian
495 +                 */
496 +                decodedir(uvw[0], av->udir);
497 +                VCROSS(uvw[1], uvw[2], uvw[0]);
498 +                d = (u = DOT(ck0, uvw[0])) / av->rad[0];
499 +                delta_t2 += d*d;
500 +                d = (v = DOT(ck0, uvw[1])) / av->rad[1];
501 +                delta_t2 += d*d;
502 +                if (delta_t2 >= ambacc*ambacc)
503 +                        continue;
504 +                /*
505 +                 *  Test for potential light leak
506 +                 */
507 +                if (av->corral && plugaleak(r, av, uvw[2], atan2a(v,u)))
508 +                        continue;
509 +                /*
510 +                 *  Extrapolate value and compute final weight (hat function)
511 +                 */
512 +                if (!extambient(ct, av, r->rop, rn, uvw))
513 +                        continue;
514 +                d = tfunc(maxangle, sqrt(delta_r2), 0.0) *
515 +                        tfunc(ambacc, sqrt(delta_t2), 0.0);
516 +                scalecolor(ct, d);
517 +                addcolor(acol, ct);
518 +                wsum += d;
519 +        }
520 +        return(wsum);
521 + }
522 +
523 +
524 + static int
525 + makeambient(            /* make a new ambient value for storage */
526 +        COLOR  acol,
527 +        RAY  *r,
528 +        FVECT  rn,
529 +        int  al
530 + )
531 + {
532 +        AMBVAL  amb;
533 +        FVECT   uvw[3];
534 +        int     i;
535 +
536 +        amb.weight = 1.0;                       /* compute weight */
537 +        for (i = al; i-- > 0; )
538 +                amb.weight *= AVGREFL;
539 +        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
540 +                amb.weight = 1.25*r->rweight;
541 +        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
542 +                                                /* compute ambient */
543 +        i = doambient(acol, r, amb.weight,
544 +                        uvw, amb.rad, amb.gpos, amb.gdir, &amb.corral);
545 +        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
546 +        if (i <= 0 || amb.rad[0] <= FTINY)      /* no Hessian or zero radius */
547 +                return(i);
548 +                                                /* store value */
549 +        VCOPY(amb.pos, r->rop);
550 +        amb.ndir = encodedir(r->ron);
551 +        amb.udir = encodedir(uvw[0]);
552 +        amb.lvl = al;
553 +        copycolor(amb.val, acol);
554 +                                                /* insert into tree */
555 +        avsave(&amb);                           /* and save to file */
556 +        if (rn != r->ron) {                     /* texture */
557 +                VCOPY(uvw[2], r->ron);
558 +                extambient(acol, &amb, r->rop, rn, uvw);
559 +        }
560 +        return(1);
561 + }
562 +
563 +
564 + static int
565 + extambient(             /* extrapolate value at pv, nv */
566 +        COLOR  cr,
567 +        AMBVAL   *ap,
568 +        FVECT  pv,
569 +        FVECT  nv,
570 +        FVECT  uvw[3]
571 + )
572 + {
573 +        const double    min_d = 0.05;
574 +        static FVECT    my_uvw[3];
575 +        FVECT           v1;
576 +        int             i;
577 +        double          d = 1.0;        /* zeroeth order */
578 +
579 +        if (uvw == NULL) {              /* need local coordinates? */
580 +                decodedir(my_uvw[2], ap->ndir);
581 +                decodedir(my_uvw[0], ap->udir);
582 +                VCROSS(my_uvw[1], my_uvw[2], my_uvw[0]);
583 +                uvw = my_uvw;
584 +        }
585 +        for (i = 3; i--; )              /* gradient due to translation */
586 +                d += (pv[i] - ap->pos[i]) *
587 +                        (ap->gpos[0]*uvw[0][i] + ap->gpos[1]*uvw[1][i]);
588 +
589 +        VCROSS(v1, uvw[2], nv);         /* gradient due to rotation */
590 +        for (i = 3; i--; )
591 +                d += v1[i] * (ap->gdir[0]*uvw[0][i] + ap->gdir[1]*uvw[1][i]);
592 +        
593 +        if (d < min_d)                  /* should not use if we can avoid it */
594 +                d = min_d;
595 +        copycolor(cr, ap->val);
596 +        scalecolor(cr, d);
597 +        return(d > min_d);
598 + }
599 +
600 +
601 + static void
602 + avinsert(                               /* insert ambient value in our tree */
603 +        AMBVAL *av
604 + )
605 + {
606 +        AMBTREE  *at;
607 +        AMBVAL  *ap;
608 +        AMBVAL  avh;
609 +        FVECT  ck0;
610 +        double  s;
611 +        int  branch;
612 +        int  i;
613 +
614 +        if (av->rad[0] <= FTINY)
615 +                error(CONSISTENCY, "zero ambient radius in avinsert");
616 +        at = &atrunk;
617 +        VCOPY(ck0, thescene.cuorg);
618 +        s = thescene.cusize;
619 +        while (s*(OCTSCALE/2) > av->rad[1]*ambacc) {
620 +                if (at->kid == NULL)
621 +                        if ((at->kid = newambtree()) == NULL)
622 +                                error(SYSTEM, "out of memory in avinsert");
623 +                s *= 0.5;
624 +                branch = 0;
625 +                for (i = 0; i < 3; i++)
626 +                        if (av->pos[i] > ck0[i] + s) {
627 +                                ck0[i] += s;
628 +                                branch |= 1 << i;
629 +                        }
630 +                at = at->kid + branch;
631 +        }
632 +        avh.next = at->alist;           /* order by increasing level */
633 +        for (ap = &avh; ap->next != NULL; ap = ap->next)
634 +                if ( ap->next->lvl > av->lvl ||
635 +                                (ap->next->lvl == av->lvl) &
636 +                                (ap->next->weight <= av->weight) )
637 +                        break;
638 +        av->next = ap->next;
639 +        ap->next = (AMBVAL*)av;
640 +        at->alist = avh.next;
641 + }
642 +
643 +
644 + #else /* ! NEWAMB */
645 +
646 + static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
647 +                                AMBTREE *at, FVECT c0, double s);
648 + static double   makeambient(COLOR acol, RAY *r, FVECT rn, int al);
649 + static void     extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv);
650 +
651 +
652 + void
653 + multambient(            /* compute ambient component & multiply by coef. */
654 +        COLOR  aval,
655 +        RAY  *r,
656 +        FVECT  nrm
657 + )
658 + {
659 +        static int  rdepth = 0;                 /* ambient recursion */
660 +        COLOR   acol, caustic;
661 +        double  d, l;
662 +
663 +        /* PMAP: Factor in ambient from global photon map (if enabled) and return
664 +         * as all ambient components accounted for */
665 +        if (ambPmap(aval, r, rdepth))
666 +                return;
667 +
668 +        /* PMAP: Otherwise factor in ambient from caustic photon map
669 +         * (ambPmapCaustic() returns zero if caustic photons disabled) and
670 +         * continue with RADIANCE ambient calculation */
671 +        copycolor(caustic, aval);
672 +        ambPmapCaustic(caustic, r, rdepth);
673 +        
674 +        if (ambdiv <= 0)                        /* no ambient calculation */
675 +                goto dumbamb;
676 +                                                /* check number of bounces */
677 +        if (rdepth >= ambounce)
678 +                goto dumbamb;
679 +                                                /* check ambient list */
680 +        if (ambincl != -1 && r->ro != NULL &&
681 +                        ambincl != inset(ambset, r->ro->omod))
682 +                goto dumbamb;
683 +
684 +        if (ambacc <= FTINY) {                  /* no ambient storage */
685 +                copycolor(acol, aval);
686 +                rdepth++;
687                  d = doambient(acol, r, r->rweight, NULL, NULL);
688                  rdepth--;
689                  if (d <= FTINY)
690                          goto dumbamb;
691 +                copycolor(aval, acol);          
692 +        
693 +           /* PMAP: add in caustic */
694 +                addcolor(aval, caustic);        
695                  return;
696          }
697  
698          if (tracktime)                          /* sort to minimize thrashing */
699                  sortambvals(0);
700 <                                                /* get ambient value */
700 >                                                /* interpolate ambient value */
701          setcolor(acol, 0.0, 0.0, 0.0);
702          d = sumambient(acol, r, nrm, rdepth,
703                          &atrunk, thescene.cuorg, thescene.cusize);
704 +                        
705          if (d > FTINY) {
706 <                scalecolor(acol, 1.0/d);
706 >                d = 1.0/d;
707 >                scalecolor(acol, d);
708 >                multcolor(aval, acol);
709 >                
710 >                /* PMAP: add in caustic */
711 >                addcolor(aval, caustic);        
712                  return;
713          }
714 +        
715          rdepth++;                               /* need to cache new value */
716          d = makeambient(acol, r, nrm, rdepth-1);
717          rdepth--;
718 <        if (d > FTINY)
718 >        
719 >        if (d > FTINY) {
720 >                multcolor(aval, acol);          /* got new value */
721 >
722 >                /* PMAP: add in caustic */
723 >                addcolor(aval, caustic);                        
724                  return;
725 +        }
726 +        
727   dumbamb:                                        /* return global value */
728 <        copycolor(acol, ambval);
729 <        if (ambvwt <= 0 | navsum == 0)
728 >        if ((ambvwt <= 0) | (navsum == 0)) {
729 >                multcolor(aval, ambval);
730 >
731 >                /* PMAP: add in caustic */
732 >                addcolor(aval, caustic);        
733                  return;
734 +        }
735 +        
736          l = bright(ambval);                     /* average in computations */
737          if (l > FTINY) {
738                  d = (log(l)*(double)ambvwt + avsum) /
739                                  (double)(ambvwt + navsum);
740                  d = exp(d) / l;
741 <                scalecolor(acol, d);            /* apply color of ambval */
741 >                scalecolor(aval, d);
742 >                multcolor(aval, ambval);        /* apply color of ambval */
743          } else {
744                  d = exp( avsum / (double)navsum );
745 <                setcolor(acol, d, d, d);        /* neutral color */
745 >                scalecolor(aval, d);            /* neutral color */
746          }
747   }
748  
749  
750 < double
751 < sumambient(acol, r, rn, al, at, c0, s)  /* get interpolated ambient value */
752 < COLOR  acol;
753 < register RAY  *r;
754 < FVECT  rn;
755 < int  al;
756 < AMBTREE  *at;
757 < FVECT  c0;
758 < double  s;
750 > static double
751 > sumambient(     /* get interpolated ambient value */
752 >        COLOR  acol,
753 >        RAY  *r,
754 >        FVECT  rn,
755 >        int  al,
756 >        AMBTREE  *at,
757 >        FVECT  c0,
758 >        double  s
759 > )
760   {
761          double  d, e1, e2, wt, wsum;
762          COLOR  ct;
763          FVECT  ck0;
764          int  i;
765 <        register int  j;
766 <        register AMBVAL  *av;
765 >        int  j;
766 >        AMBVAL   *av;
767  
768          wsum = 0.0;
769                                          /* do this node */
# Line 317 | Line 774 | double s;
774                  /*
775                   *  Ambient level test.
776                   */
777 <                if (av->lvl > al)       /* list sorted, so this works */
777 >                if (av->lvl > al ||     /* list sorted, so this works */
778 >                                (av->lvl == al) & (av->weight < 0.9*r->rweight))
779                          break;
322                if (av->weight < r->rweight-FTINY)
323                        continue;
780                  /*
781                   *  Ambient radius test.
782                   */
783 <                d = av->pos[0] - r->rop[0];
784 <                e1 = d * d;
329 <                d = av->pos[1] - r->rop[1];
330 <                e1 += d * d;
331 <                d = av->pos[2] - r->rop[2];
332 <                e1 += d * d;
333 <                e1 /= av->rad * av->rad;
783 >                VSUB(ck0, av->pos, r->rop);
784 >                e1 = DOT(ck0, ck0) / (av->rad * av->rad);
785                  if (e1 > ambacc*ambacc*1.21)
786                          continue;
787                  /*
# Line 347 | Line 798 | double s;
798                          }
799                  }
800                  e2 = (1.0 - d) * r->rweight;
801 <                if (e2 < 0.0) e2 = 0.0;
802 <                if (e1 + e2 > ambacc*ambacc*1.21)
801 >                if (e2 < 0.0)
802 >                        e2 = 0.0;
803 >                else if (e1 + e2 > ambacc*ambacc*1.21)
804                          continue;
805                  /*
806                   *  Ray behind test.
# Line 398 | Line 850 | double s;
850                                  break;
851                  }
852                  if (j == 3)
853 <                        wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
853 >                        wsum += sumambient(acol, r, rn, al,
854 >                                                at->kid+i, ck0, s);
855          }
856          return(wsum);
857   }
858  
859  
860 < double
861 < makeambient(acol, r, rn, al)    /* make a new ambient value */
862 < COLOR  acol;
863 < register RAY  *r;
864 < FVECT  rn;
865 < int  al;
860 > static double
861 > makeambient(            /* make a new ambient value for storage */
862 >        COLOR  acol,
863 >        RAY  *r,
864 >        FVECT  rn,
865 >        int  al
866 > )
867   {
868          AMBVAL  amb;
869          FVECT   gp, gd;
870 <                                                /* compute weight */
871 <        amb.weight = pow(AVGREFL, (double)al);
872 <        if (r->rweight < 0.1*amb.weight)        /* heuristic */
873 <                amb.weight = r->rweight;
870 >        int     i;
871 >
872 >        amb.weight = 1.0;                       /* compute weight */
873 >        for (i = al; i-- > 0; )
874 >                amb.weight *= AVGREFL;
875 >        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
876 >                amb.weight = 1.25*r->rweight;
877 >        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
878                                                  /* compute ambient */
879          amb.rad = doambient(acol, r, amb.weight, gp, gd);
880 <        if (amb.rad <= FTINY)
880 >        if (amb.rad <= FTINY) {
881 >                setcolor(acol, 0.0, 0.0, 0.0);
882                  return(0.0);
883 <                                                /* store it */
883 >        }
884 >        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
885 >                                                /* store value */
886          VCOPY(amb.pos, r->rop);
887          VCOPY(amb.dir, r->ron);
888          amb.lvl = al;
# Line 436 | Line 897 | int  al;
897   }
898  
899  
900 < void
901 < extambient(cr, ap, pv, nv)              /* extrapolate value at pv, nv */
902 < COLOR  cr;
903 < register AMBVAL  *ap;
904 < FVECT  pv, nv;
900 > static void
901 > extambient(             /* extrapolate value at pv, nv */
902 >        COLOR  cr,
903 >        AMBVAL   *ap,
904 >        FVECT  pv,
905 >        FVECT  nv
906 > )
907   {
908          FVECT  v1;
909 <        register int  i;
909 >        int  i;
910          double  d;
911  
912          d = 1.0;                        /* zeroeth order */
# Line 463 | Line 926 | FVECT  pv, nv;
926  
927  
928   static void
929 < initambfile(creat)              /* initialize ambient file */
930 < int  creat;
929 > avinsert(                               /* insert ambient value in our tree */
930 >        AMBVAL *av
931 > )
932   {
933 +        AMBTREE  *at;
934 +        AMBVAL  *ap;
935 +        AMBVAL  avh;
936 +        FVECT  ck0;
937 +        double  s;
938 +        int  branch;
939 +        int  i;
940 +
941 +        if (av->rad <= FTINY)
942 +                error(CONSISTENCY, "zero ambient radius in avinsert");
943 +        at = &atrunk;
944 +        VCOPY(ck0, thescene.cuorg);
945 +        s = thescene.cusize;
946 +        while (s*(OCTSCALE/2) > av->rad*ambacc) {
947 +                if (at->kid == NULL)
948 +                        if ((at->kid = newambtree()) == NULL)
949 +                                error(SYSTEM, "out of memory in avinsert");
950 +                s *= 0.5;
951 +                branch = 0;
952 +                for (i = 0; i < 3; i++)
953 +                        if (av->pos[i] > ck0[i] + s) {
954 +                                ck0[i] += s;
955 +                                branch |= 1 << i;
956 +                        }
957 +                at = at->kid + branch;
958 +        }
959 +        avh.next = at->alist;           /* order by increasing level */
960 +        for (ap = &avh; ap->next != NULL; ap = ap->next)
961 +                if ( ap->next->lvl > av->lvl ||
962 +                                (ap->next->lvl == av->lvl) &
963 +                                (ap->next->weight <= av->weight) )
964 +                        break;
965 +        av->next = ap->next;
966 +        ap->next = (AMBVAL*)av;
967 +        at->alist = avh.next;
968 + }
969 +
970 + #endif  /* ! NEWAMB */
971 +
972 + /************* FOLLOWING ROUTINES SAME FOR NEW & OLD METHODS ***************/
973 +
974 + static void
975 + initambfile(            /* initialize ambient file */
976 +        int  cre8
977 + )
978 + {
979          extern char  *progname, *octname;
980          static char  *mybuf = NULL;
981  
982   #ifdef  F_SETLKW
983 <        aflock(creat ? F_WRLCK : F_RDLCK);
983 >        aflock(cre8 ? F_WRLCK : F_RDLCK);
984   #endif
985          SET_FILE_BINARY(ambfp);
986          if (mybuf == NULL)
987                  mybuf = (char *)bmalloc(BUFSIZ+8);
988          setbuf(ambfp, mybuf);
989 <        if (creat) {                    /* new file */
989 >        if (cre8) {                     /* new file */
990                  newheader("RADIANCE", ambfp);
991                  fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
992                                  progname, colval(ambval,RED),
# Line 485 | Line 995 | int  creat;
995                  fprintf(ambfp, "-ad %d -as %d -ar %d ",
996                                  ambdiv, ambssamp, ambres);
997                  if (octname != NULL)
998 <                        printargs(1, &octname, ambfp);
999 <                else
490 <                        fputc('\n', ambfp);
998 >                        fputs(octname, ambfp);
999 >                fputc('\n', ambfp);
1000                  fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
1001                  fputnow(ambfp);
1002                  fputformat(AMBFMT, ambfp);
1003 <                putc('\n', ambfp);
1003 >                fputc('\n', ambfp);
1004                  putambmagic(ambfp);
1005          } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
1006                  error(USER, "bad ambient file");
# Line 499 | Line 1008 | int  creat;
1008  
1009  
1010   static void
1011 < avsave(av)                              /* insert and save an ambient value */
1012 < AMBVAL  *av;
1011 > avsave(                         /* insert and save an ambient value */
1012 >        AMBVAL  *av
1013 > )
1014   {
1015 <        avinsert(avstore(av));
1015 >        avstore(av);
1016          if (ambfp == NULL)
1017                  return;
1018          if (writambval(av, ambfp) < 0)
# Line 517 | Line 1027 | writerr:
1027  
1028  
1029   static AMBVAL *
1030 < avstore(aval)                           /* allocate memory and store aval */
1031 < register AMBVAL  *aval;
1030 > avstore(                                /* allocate memory and save aval */
1031 >        AMBVAL  *aval
1032 > )
1033   {
1034 <        register AMBVAL  *av;
1034 >        AMBVAL  *av;
1035          double  d;
1036  
1037          if ((av = newambval()) == NULL)
1038                  error(SYSTEM, "out of memory in avstore");
1039 <        copystruct(av, aval);
1039 >        *av = *aval;
1040          av->latick = ambclock;
1041          av->next = NULL;
1042          nambvals++;
# Line 534 | Line 1045 | register AMBVAL  *aval;
1045                  avsum += log(d);
1046                  navsum++;
1047          }
1048 +        avinsert(av);                   /* insert in our cache tree */
1049          return(av);
1050   }
1051  
# Line 544 | Line 1056 | static AMBTREE  *atfreelist = NULL;    /* free ambient tr
1056  
1057  
1058   static AMBTREE *
1059 < newambtree()                            /* allocate 8 ambient tree structs */
1059 > newambtree(void)                                /* allocate 8 ambient tree structs */
1060   {
1061 <        register AMBTREE  *atp, *upperlim;
1061 >        AMBTREE  *atp, *upperlim;
1062  
1063          if (atfreelist == NULL) {       /* get more nodes */
1064                  atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
# Line 560 | Line 1072 | newambtree()                           /* allocate 8 ambient tree structs */
1072          }
1073          atp = atfreelist;
1074          atfreelist = atp->kid;
1075 <        bzero((char *)atp, 8*sizeof(AMBTREE));
1075 >        memset((char *)atp, '\0', 8*sizeof(AMBTREE));
1076          return(atp);
1077   }
1078  
1079  
1080   static void
1081 < freeambtree(atp)                        /* free 8 ambient tree structs */
1082 < AMBTREE  *atp;
1081 > freeambtree(                    /* free 8 ambient tree structs */
1082 >        AMBTREE  *atp
1083 > )
1084   {
1085          atp->kid = atfreelist;
1086          atfreelist = atp;
# Line 575 | Line 1088 | AMBTREE  *atp;
1088  
1089  
1090   static void
1091 < avinsert(av)                            /* insert ambient value in our tree */
1092 < register AMBVAL  *av;
1091 > unloadatree(                    /* unload an ambient value tree */
1092 >        AMBTREE  *at,
1093 >        unloadtf_t *f
1094 > )
1095   {
1096 <        register AMBTREE  *at;
1097 <        register AMBVAL  *ap;
583 <        AMBVAL  avh;
584 <        FVECT  ck0;
585 <        double  s;
586 <        int  branch;
587 <        register int  i;
588 <
589 <        if (av->rad <= FTINY)
590 <                error(CONSISTENCY, "zero ambient radius in avinsert");
591 <        at = &atrunk;
592 <        VCOPY(ck0, thescene.cuorg);
593 <        s = thescene.cusize;
594 <        while (s*(OCTSCALE/2) > av->rad*ambacc) {
595 <                if (at->kid == NULL)
596 <                        if ((at->kid = newambtree()) == NULL)
597 <                                error(SYSTEM, "out of memory in avinsert");
598 <                s *= 0.5;
599 <                branch = 0;
600 <                for (i = 0; i < 3; i++)
601 <                        if (av->pos[i] > ck0[i] + s) {
602 <                                ck0[i] += s;
603 <                                branch |= 1 << i;
604 <                        }
605 <                at = at->kid + branch;
606 <        }
607 <        avh.next = at->alist;           /* order by increasing level */
608 <        for (ap = &avh; ap->next != NULL; ap = ap->next)
609 <                if (ap->next->lvl >= av->lvl)
610 <                        break;
611 <        av->next = ap->next;
612 <        ap->next = av;
613 <        at->alist = avh.next;
614 < }
615 <
616 <
617 < static void
618 < unloadatree(at, f)                      /* unload an ambient value tree */
619 < register AMBTREE  *at;
620 < void    (*f)();
621 < {
622 <        register AMBVAL  *av;
623 <        register int  i;
1096 >        AMBVAL  *av;
1097 >        int  i;
1098                                          /* transfer values at this node */
1099          for (av = at->alist; av != NULL; av = at->alist) {
1100                  at->alist = av->next;
# Line 642 | Line 1116 | static struct avl {
1116   static AMBVAL   **avlist2;              /* memory positions for sorting */
1117   static int      i_avlist;               /* index for lists */
1118  
1119 + static int alatcmp(const void *av1, const void *av2);
1120  
1121 < static int
1122 < av2list(av)
648 < register AMBVAL *av;
1121 > static void
1122 > avfree(AMBVAL *av)
1123   {
1124 +        free(av);
1125 + }
1126 +
1127 + static void
1128 + av2list(
1129 +        AMBVAL *av
1130 + )
1131 + {
1132   #ifdef DEBUG
1133          if (i_avlist >= nambvals)
1134                  error(CONSISTENCY, "too many ambient values in av2list1");
1135   #endif
1136 <        avlist1[i_avlist].p = avlist2[i_avlist] = av;
1136 >        avlist1[i_avlist].p = avlist2[i_avlist] = (AMBVAL*)av;
1137          avlist1[i_avlist++].t = av->latick;
1138   }
1139  
1140  
1141   static int
1142 < alatcmp(av1, av2)                       /* compare ambient values for MRA */
1143 < struct avl      *av1, *av2;
1142 > alatcmp(                        /* compare ambient values for MRA */
1143 >        const void *av1,
1144 >        const void *av2
1145 > )
1146   {
1147 <        register long  lc = av2->t - av1->t;
1147 >        long  lc = ((struct avl *)av2)->t - ((struct avl *)av1)->t;
1148          return(lc<0 ? -1 : lc>0 ? 1 : 0);
1149   }
1150  
# Line 672 | Line 1156 | struct avl     *av1, *av2;
1156   * assumes pointers differ by exact struct size increments.
1157   */
1158   static int
1159 < aposcmp(avp1, avp2)                     /* compare ambient value positions */
1160 < const void      *avp1, *avp2;
1159 > aposcmp(                        /* compare ambient value positions */
1160 >        const void      *avp1,
1161 >        const void      *avp2
1162 > )
1163   {
1164 <        register long   diff = *(char * const *)avp1 - *(char * const *)avp2;
1164 >        long    diff = *(char * const *)avp1 - *(char * const *)avp2;
1165          if (diff < 0)
1166                  return(-1);
1167          return(diff > 0);
1168   }
1169  
1170 < #if 1
1170 >
1171   static int
1172 < avlmemi(avaddr)                         /* find list position from address */
1173 < AMBVAL  *avaddr;
1172 > avlmemi(                                /* find list position from address */
1173 >        AMBVAL  *avaddr
1174 > )
1175   {
1176 <        register AMBVAL  **avlpp;
1176 >        AMBVAL  **avlpp;
1177  
1178          avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
1179 <                        nambvals, sizeof(AMBVAL *), aposcmp);
1179 >                        nambvals, sizeof(AMBVAL *), &aposcmp);
1180          if (avlpp == NULL)
1181                  error(CONSISTENCY, "address not found in avlmemi");
1182          return(avlpp - avlist2);
1183   }
697 #else
698 #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
699                                nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
700 #endif
1184  
1185  
1186   static void
1187 < sortambvals(always)                     /* resort ambient values */
1188 < int     always;
1187 > sortambvals(                    /* resort ambient values */
1188 >        int     always
1189 > )
1190   {
1191          AMBTREE  oldatrunk;
1192          AMBVAL  tav, *tap, *pnext;
1193 <        register int    i, j;
1193 >        int     i, j;
1194                                          /* see if it's time yet */
1195          if (!always && (ambclock++ < lastsort+sortintvl ||
1196                          nambvals < SORT_THRESH))
# Line 737 | Line 1221 | int    always;
1221                  if (avlist2 != NULL)
1222                          free((void *)avlist2);
1223                  if (always) {           /* rebuild without sorting */
1224 <                        copystruct(&oldatrunk, &atrunk);
1224 >                        oldatrunk = atrunk;
1225                          atrunk.alist = NULL;
1226                          atrunk.kid = NULL;
1227                          unloadatree(&oldatrunk, avinsert);
# Line 768 | Line 1252 | int    always;
1252                          if (avlist1[i].p == NULL)
1253                                  continue;
1254                          tap = avlist2[i];
1255 <                        copystruct(&tav, tap);
1255 >                        tav = *tap;
1256                          for (j = i; (pnext = avlist1[j].p) != tap;
1257                                          j = avlmemi(pnext)) {
1258 <                                copystruct(avlist2[j], pnext);
1258 >                                *(avlist2[j]) = *pnext;
1259                                  avinsert(avlist2[j]);
1260                                  avlist1[j].p = NULL;
1261                          }
1262 <                        copystruct(avlist2[j], &tav);
1262 >                        *(avlist2[j]) = tav;
1263                          avinsert(avlist2[j]);
1264                          avlist1[j].p = NULL;
1265                  }
# Line 800 | Line 1284 | int    always;
1284   #ifdef  F_SETLKW
1285  
1286   static void
1287 < aflock(typ)                     /* lock/unlock ambient file */
1288 < int  typ;
1287 > aflock(                 /* lock/unlock ambient file */
1288 >        int  typ
1289 > )
1290   {
1291          static struct flock  fls;       /* static so initialized to zeroes */
1292  
1293 +        if (typ == fls.l_type)          /* already called? */
1294 +                return;
1295          fls.l_type = typ;
1296          if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
1297                  error(SYSTEM, "cannot (un)lock ambient file");
# Line 812 | Line 1299 | int  typ;
1299  
1300  
1301   int
1302 < ambsync()                       /* synchronize ambient file */
1302 > ambsync(void)                   /* synchronize ambient file */
1303   {
1304          long  flen;
1305          AMBVAL  avs;
1306 <        register int  n;
1306 >        int  n;
1307  
1308 <        if (nunflshed == 0)
1308 >        if (ambfp == NULL)      /* no ambient file? */
1309                  return(0);
1310 <        if (lastpos < 0)        /* initializing (locked in initambfile) */
1311 <                goto syncend;
825 <                                /* gain exclusive access */
826 <        aflock(F_WRLCK);
1310 >                                /* gain appropriate access */
1311 >        aflock(nunflshed ? F_WRLCK : F_RDLCK);
1312                                  /* see if file has grown */
1313 <        if ((flen = lseek(fileno(ambfp), (off_t)0L, 2)) < 0)
1313 >        if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
1314                  goto seekerr;
1315 <        if (n = flen - lastpos) {               /* file has grown */
1315 >        if ((n = flen - lastpos) > 0) {         /* file has grown */
1316                  if (ambinp == NULL) {           /* use duplicate filedes */
1317                          ambinp = fdopen(dup(fileno(ambfp)), "r");
1318                          if (ambinp == NULL)
1319                                  error(SYSTEM, "fdopen failed in ambsync");
1320                  }
1321 <                if (fseek(ambinp, lastpos, 0) < 0)
1321 >                if (fseek(ambinp, lastpos, SEEK_SET) < 0)
1322                          goto seekerr;
1323                  while (n >= AMBVALSIZ) {        /* load contributed values */
1324                          if (!readambval(&avs, ambinp)) {
# Line 843 | Line 1328 | ambsync()                      /* synchronize ambient file */
1328                                  error(WARNING, errmsg);
1329                                  break;
1330                          }
1331 <                        avinsert(avstore(&avs));
1331 >                        avstore(&avs);
1332                          n -= AMBVALSIZ;
1333                  }
1334 +                lastpos = flen - n;
1335                  /*** seek always as safety measure
1336                  if (n) ***/                     /* alignment */
1337 <                        if (lseek(fileno(ambfp), (off_t)(flen-n), 0) < 0)
1337 >                        if (lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1338                                  goto seekerr;
1339          }
854 #ifdef  DEBUG
855        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
856                sprintf(errmsg, "ambient file buffer at %d rather than %d",
857                                ambfp->_ptr - ambfp->_base,
858                                nunflshed*AMBVALSIZ);
859                error(CONSISTENCY, errmsg);
860        }
861 #endif
862 syncend:
1340          n = fflush(ambfp);                      /* calls write() at last */
1341 <        if ((lastpos = lseek(fileno(ambfp), (off_t)0L, 1)) < 0)
1341 >        if (n != EOF)
1342 >                lastpos += (long)nunflshed*AMBVALSIZ;
1343 >        else if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
1344                  goto seekerr;
1345 +                
1346          aflock(F_UNLCK);                        /* release file */
1347          nunflshed = 0;
1348          return(n);
1349   seekerr:
1350          error(SYSTEM, "seek failed in ambsync");
1351 +        return -1; /* pro forma return */
1352   }
1353  
1354 < #else
1354 > #else   /* ! F_SETLKW */
1355  
1356   int
1357 < ambsync()                       /* flush ambient file */
1357 > ambsync(void)                   /* flush ambient file */
1358   {
1359 <        if (nunflshed == 0)
1359 >        if (ambfp == NULL)
1360                  return(0);
1361          nunflshed = 0;
1362          return(fflush(ambfp));
1363   }
1364  
1365 < #endif
1365 > #endif  /* ! F_SETLKW */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines