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

Comparing ray/src/rt/ambient.c (file contents):
Revision 1.12 by greg, Wed May 22 12:44:39 1991 UTC vs.
Revision 2.65 by greg, Sat Sep 15 02:47:30 2007 UTC

# Line 1 | Line 1
1 /* Copyright (c) 1986 Regents of the University of California */
2
1   #ifndef lint
2 < static char SCCSid[] = "$SunId$ LBL";
2 > static const char       RCSid[] = "$Id$";
3   #endif
6
4   /*
5   *  ambient.c - routines dealing with ambient (inter-reflected) component.
6   *
7 < *  The macro AMBFLUSH (if defined) is the number of ambient values
11 < *      to wait before flushing to the ambient file.
12 < *
13 < *     5/9/86
7 > *  Declarations of external symbols in ambient.h
8   */
9  
10 < #include  "ray.h"
10 > #include "copyright.h"
11  
12 < #include  "octree.h"
12 > #include <string.h>
13  
14 + #include  "platform.h"
15 + #include  "ray.h"
16   #include  "otypes.h"
17 <
17 > #include  "resolu.h"
18 > #include  "ambient.h"
19   #include  "random.h"
20  
21 < #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
21 > #ifndef  OCTSCALE
22 > #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
23 > #endif
24  
25 < extern CUBE  thescene;          /* contains space boundaries */
25 > extern char  *shm_boundary;     /* memory sharing boundary */
26  
27 < extern COLOR  ambval;           /* global ambient component */
28 < extern double  ambacc;          /* ambient accuracy */
29 < extern int  ambres;             /* ambient resolution */
30 < extern int  ambdiv;             /* number of divisions for calculation */
32 < extern int  ambssamp;           /* number of super-samples */
33 < extern int  ambounce;           /* number of ambient bounces */
34 < extern char  *amblist[];        /* ambient include/exclude list */
35 < extern int  ambincl;            /* include == 1, exclude == 0 */
27 > #ifndef  MAXASET
28 > #define  MAXASET        2047    /* maximum number of elements in ambient set */
29 > #endif
30 > OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
31  
32 < #define  MAXASET        511     /* maximum number of elements in ambient set */
33 < OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
32 > double  maxarad;                /* maximum ambient radius */
33 > double  minarad;                /* minimum ambient radius */
34  
35 < double  maxarad;                /* maximum ambient radius */
41 < double  minarad;                /* minimum ambient radius */
35 > static AMBTREE  atrunk;         /* our ambient trunk node */
36  
37 < typedef struct ambval {
38 <        FVECT  pos;             /* position in space */
45 <        FVECT  dir;             /* normal direction */
46 <        int  lvl;               /* recursion level of parent ray */
47 <        float  weight;          /* weight of parent ray */
48 <        COLOR  val;             /* computed ambient value */
49 <        float  rad;             /* validity radius */
50 <        struct ambval  *next;   /* next in list */
51 < }  AMBVAL;                      /* ambient value */
37 > static FILE  *ambfp = NULL;     /* ambient file pointer */
38 > static int  nunflshed = 0;      /* number of unflushed ambient values */
39  
40 < typedef struct ambtree {
41 <        AMBVAL  *alist;         /* ambient value list */
42 <        struct ambtree  *kid;   /* 8 child nodes */
43 < }  AMBTREE;                     /* ambient octree */
40 > #ifndef SORT_THRESH
41 > #ifdef SMLMEM
42 > #define SORT_THRESH     ((3L<<20)/sizeof(AMBVAL))
43 > #else
44 > #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
45 > #endif
46 > #endif
47 > #ifndef SORT_INTVL
48 > #define SORT_INTVL      (SORT_THRESH<<1)
49 > #endif
50 > #ifndef MAX_SORT_INTVL
51 > #define MAX_SORT_INTVL  (SORT_INTVL<<6)
52 > #endif
53  
54 < typedef struct {
55 <        float  k;               /* error contribution per sample */
56 <        COLOR  v;               /* ray sum */
57 <        int  n;                 /* number of samples */
58 <        short  t, p;            /* theta, phi indices */
59 < }  AMBSAMP;                     /* ambient sample */
54 > static double  avsum = 0.;              /* computed ambient value sum (log) */
55 > static unsigned int  navsum = 0;        /* number of values in avsum */
56 > static unsigned int  nambvals = 0;      /* total number of indirect values */
57 > static unsigned int  nambshare = 0;     /* number of values from file */
58 > static unsigned long  ambclock = 0;     /* ambient access clock */
59 > static unsigned long  lastsort = 0;     /* time of last value sort */
60 > static long  sortintvl = SORT_INTVL;    /* time until next sort */
61 > static FILE  *ambinp = NULL;            /* auxiliary file for input */
62 > static long  lastpos = -1;              /* last flush position */
63  
64 < static AMBTREE  atrunk;         /* our ambient trunk node */
64 > #define MAXACLOCK       (1L<<30)        /* clock turnover value */
65 >        /*
66 >         * Track access times unless we are sharing ambient values
67 >         * through memory on a multiprocessor, when we want to avoid
68 >         * claiming our own memory (copy on write).  Go ahead anyway
69 >         * if more than two thirds of our values are unshared.
70 >         * Compile with -Dtracktime=0 to turn this code off.
71 >         */
72 > #ifndef tracktime
73 > #define tracktime       (shm_boundary == NULL || nambvals > 3*nambshare)
74 > #endif
75  
76 < static FILE  *ambfp = NULL;     /* ambient file pointer */
76 > #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
77  
78 < #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
78 > #define  newambval()    (AMBVAL *)malloc(sizeof(AMBVAL))
79 > #define  freeav(av)     free((void *)av);
80  
81 < #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
81 > static void initambfile(int creat);
82 > static void avsave(AMBVAL *av);
83 > static AMBVAL *avstore(AMBVAL  *aval);
84 > static AMBTREE *newambtree(void);
85 > static void freeambtree(AMBTREE  *atp);
86  
87 < double  sumambient(), doambient(), makeambient();
87 > typedef void unloadtf_t(void *);
88 > static unloadtf_t avinsert;
89 > static unloadtf_t av2list;
90 > static void unloadatree(AMBTREE  *at, unloadtf_t *f);
91  
92 + static int aposcmp(const void *avp1, const void *avp2);
93 + static int avlmemi(AMBVAL *avaddr);
94 + static void sortambvals(int always);
95  
96 < setambient(afile)                       /* initialize calculation */
97 < char  *afile;
96 > #ifdef  F_SETLKW
97 > static void aflock(int  typ);
98 > #endif
99 >
100 >
101 > extern void
102 > setambres(                              /* set ambient resolution */
103 >        int  ar
104 > )
105   {
106 <        long  ftell();
107 <        AMBVAL  amb;
106 >        ambres = ar < 0 ? 0 : ar;               /* may be done already */
107 >                                                /* set min & max radii */
108 >        if (ar <= 0) {
109 >                minarad = 0;
110 >                maxarad = thescene.cusize / 2.0;
111 >        } else {
112 >                minarad = thescene.cusize / ar;
113 >                maxarad = 64 * minarad;                 /* heuristic */
114 >                if (maxarad > thescene.cusize / 2.0)
115 >                        maxarad = thescene.cusize / 2.0;
116 >        }
117 >        if (minarad <= FTINY)
118 >                minarad = 10*FTINY;
119 >        if (maxarad <= minarad)
120 >                maxarad = 64 * minarad;
121 > }
122  
82        maxarad = thescene.cusize / 2.0;                /* maximum radius */
83                                                        /* minimum radius */
84        minarad = ambres > 0 ? thescene.cusize/ambres : 0.0;
123  
124 <                                        /* open ambient file */
125 <        if (afile != NULL)
126 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
127 <                        while (fread((char *)&amb,sizeof(AMBVAL),1,ambfp) == 1)
128 <                                avinsert(&amb, &atrunk, thescene.cuorg,
129 <                                                thescene.cusize);
130 <                                                        /* align */
131 <                        fseek(ambfp, -(ftell(ambfp)%sizeof(AMBVAL)), 1);
132 <                } else if ((ambfp = fopen(afile, "w")) == NULL) {
133 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
134 <                                        afile);
135 <                        error(SYSTEM, errmsg);
124 > extern void
125 > setambacc(                              /* set ambient accuracy */
126 >        double  newa
127 > )
128 > {
129 >        double  ambdiff;
130 >
131 >        if (newa < 0.0)
132 >                newa = 0.0;
133 >        ambdiff = fabs(newa - ambacc);
134 >        if (ambdiff >= .01 && (ambacc = newa) > FTINY && nambvals > 0)
135 >                sortambvals(1);                 /* rebuild tree */
136 > }
137 >
138 >
139 > extern void
140 > setambient(void)                                /* initialize calculation */
141 > {
142 >        int     readonly = 0;
143 >        long  pos, flen;
144 >        AMBVAL  amb;
145 >                                                /* make sure we're fresh */
146 >        ambdone();
147 >                                                /* init ambient limits */
148 >        setambres(ambres);
149 >        setambacc(ambacc);
150 >        if (ambfile == NULL || !ambfile[0])
151 >                return;
152 >        if (ambacc <= FTINY) {
153 >                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
154 >                                ambfile);
155 >                error(WARNING, errmsg);
156 >                return;
157 >        }
158 >                                                /* open ambient file */
159 >        if ((ambfp = fopen(ambfile, "r+")) == NULL)
160 >                readonly = (ambfp = fopen(ambfile, "r")) != NULL;
161 >        if (ambfp != NULL) {
162 >                initambfile(0);                 /* file exists */
163 >                pos = ftell(ambfp);
164 >                while (readambval(&amb, ambfp))
165 >                        avinsert(avstore(&amb));
166 >                nambshare = nambvals;           /* share loaded values */
167 >                if (readonly) {
168 >                        sprintf(errmsg,
169 >                                "loaded %u values from read-only ambient file",
170 >                                        nambvals);
171 >                        error(WARNING, errmsg);
172 >                        fclose(ambfp);          /* close file so no writes */
173 >                        ambfp = NULL;
174 >                        return;                 /* avoid ambsync() */
175                  }
176 +                                                /* align file pointer */
177 +                pos += (long)nambvals*AMBVALSIZ;
178 +                flen = lseek(fileno(ambfp), (off_t)0, SEEK_END);
179 +                if (flen != pos) {
180 +                        sprintf(errmsg,
181 +                        "ignoring last %ld values in ambient file (corrupted)",
182 +                                        (flen - pos)/AMBVALSIZ);
183 +                        error(WARNING, errmsg);
184 +                        fseek(ambfp, pos, 0);
185 + #ifndef _WIN32 /* XXX we need a replacement for that one */
186 +                        ftruncate(fileno(ambfp), (off_t)pos);
187 + #endif
188 +                }
189 +        } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
190 +                initambfile(1);                 /* else create new file */
191 +        } else {
192 +                sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
193 +                error(SYSTEM, errmsg);
194 +        }
195 +        ambsync();                      /* load previous values */
196   }
197  
198  
199 < ambnotify(obj)                  /* record new modifier */
200 < OBJECT  obj;
199 > extern void
200 > ambdone(void)                   /* close ambient file and free memory */
201   {
202 +        if (ambfp != NULL) {            /* close ambient file */
203 +                ambsync();
204 +                fclose(ambfp);
205 +                ambfp = NULL;
206 +                if (ambinp != NULL) {  
207 +                        fclose(ambinp);
208 +                        ambinp = NULL;
209 +                }
210 +                lastpos = -1;
211 +        }
212 +                                        /* free ambient tree */
213 +        unloadatree(&atrunk, free);
214 +                                        /* reset state variables */
215 +        avsum = 0.;
216 +        navsum = 0;
217 +        nambvals = 0;
218 +        nambshare = 0;
219 +        ambclock = 0;
220 +        lastsort = 0;
221 +        sortintvl = SORT_INTVL;
222 + }
223 +
224 +
225 + extern void
226 + ambnotify(                      /* record new modifier */
227 +        OBJECT  obj
228 + )
229 + {
230          static int  hitlimit = 0;
231 <        register OBJREC  *o = objptr(obj);
231 >        register OBJREC  *o;
232          register char  **amblp;
233  
234 +        if (obj == OVOID) {             /* starting over */
235 +                ambset[0] = 0;
236 +                hitlimit = 0;
237 +                return;
238 +        }
239 +        o = objptr(obj);
240          if (hitlimit || !ismodifier(o->otype))
241                  return;
242          for (amblp = amblist; *amblp != NULL; amblp++)
# Line 121 | Line 252 | OBJECT  obj;
252   }
253  
254  
255 < ambient(acol, r)                /* compute ambient component for ray */
256 < COLOR  acol;
257 < register RAY  *r;
255 > extern void
256 > multambient(            /* compute ambient component & multiply by coef. */
257 >        COLOR  aval,
258 >        register RAY  *r,
259 >        FVECT  nrm
260 > )
261   {
262          static int  rdepth = 0;                 /* ambient recursion */
263 <        double  wsum;
263 >        COLOR   acol;
264 >        double  d, l;
265  
131        rdepth++;                               /* increment level */
132
266          if (ambdiv <= 0)                        /* no ambient calculation */
267                  goto dumbamb;
268                                                  /* check number of bounces */
269 <        if (rdepth > ambounce)
269 >        if (rdepth >= ambounce)
270                  goto dumbamb;
271                                                  /* check ambient list */
272          if (ambincl != -1 && r->ro != NULL &&
# Line 141 | Line 274 | register RAY  *r;
274                  goto dumbamb;
275  
276          if (ambacc <= FTINY) {                  /* no ambient storage */
277 <                if (doambient(acol, r) == 0.0)
277 >                copycolor(acol, aval);
278 >                rdepth++;
279 >                d = doambient(acol, r, r->rweight, NULL, NULL);
280 >                rdepth--;
281 >                if (d <= FTINY)
282                          goto dumbamb;
283 <                goto done;
283 >                copycolor(aval, acol);
284 >                return;
285          }
148                                                /* get ambient value */
149        setcolor(acol, 0.0, 0.0, 0.0);
150        wsum = sumambient(acol, r, &atrunk, thescene.cuorg, thescene.cusize);
151        if (wsum > FTINY)
152                scalecolor(acol, 1.0/wsum);
153        else if (makeambient(acol, r) == 0.0)
154                goto dumbamb;
155        goto done;
286  
287 < dumbamb:                                        /* return global value */
288 <        copycolor(acol, ambval);
289 < done:                                           /* must finish here! */
287 >        if (tracktime)                          /* sort to minimize thrashing */
288 >                sortambvals(0);
289 >                                                /* interpolate ambient value */
290 >        setcolor(acol, 0.0, 0.0, 0.0);
291 >        d = sumambient(acol, r, nrm, rdepth,
292 >                        &atrunk, thescene.cuorg, thescene.cusize);
293 >        if (d > FTINY) {
294 >                d = 1.0/d;
295 >                scalecolor(acol, d);
296 >                multcolor(aval, acol);
297 >                return;
298 >        }
299 >        rdepth++;                               /* need to cache new value */
300 >        d = makeambient(acol, r, nrm, rdepth-1);
301          rdepth--;
302 +        if (d > FTINY) {
303 +                multcolor(aval, acol);          /* got new value */
304 +                return;
305 +        }
306 + dumbamb:                                        /* return global value */
307 +        if ((ambvwt <= 0) | (navsum == 0)) {
308 +                multcolor(aval, ambval);
309 +                return;
310 +        }
311 +        l = bright(ambval);                     /* average in computations */
312 +        if (l > FTINY) {
313 +                d = (log(l)*(double)ambvwt + avsum) /
314 +                                (double)(ambvwt + navsum);
315 +                d = exp(d) / l;
316 +                scalecolor(aval, d);
317 +                multcolor(aval, ambval);        /* apply color of ambval */
318 +        } else {
319 +                d = exp( avsum / (double)navsum );
320 +                scalecolor(aval, d);            /* neutral color */
321 +        }
322   }
323  
324  
325 < double
326 < sumambient(acol, r, at, c0, s)          /* get interpolated ambient value */
327 < COLOR  acol;
328 < register RAY  *r;
329 < AMBTREE  *at;
330 < FVECT  c0;
331 < double  s;
325 > extern double
326 > sumambient(     /* get interpolated ambient value */
327 >        COLOR  acol,
328 >        register RAY  *r,
329 >        FVECT  rn,
330 >        int  al,
331 >        AMBTREE  *at,
332 >        FVECT  c0,
333 >        double  s
334 > )
335   {
336 <        extern double  sqrt();
173 <        double  d, e1, e2, wt, wsum;
336 >        double  d, e1, e2, wt, wsum;
337          COLOR  ct;
338          FVECT  ck0;
339          int  i;
340          register int  j;
341 <        register AMBVAL  *av;
342 <                                        /* do this node */
341 >        register AMBVAL  *av;
342 >
343          wsum = 0.0;
344 +                                        /* do this node */
345          for (av = at->alist; av != NULL; av = av->next) {
346 +                double  rn_dot = -2.0;
347 +                if (tracktime)
348 +                        av->latick = ambclock;
349                  /*
350 <                 *  Ray strength test.
350 >                 *  Ambient level test.
351                   */
352 <                if (av->lvl > r->rlvl || av->weight < r->rweight-FTINY)
352 >                if (av->lvl > al)       /* list sorted, so this works */
353 >                        break;
354 >                if (av->weight < 0.9*r->rweight)
355                          continue;
356                  /*
357                   *  Ambient radius test.
358                   */
359 <                e1 = 0.0;
360 <                for (j = 0; j < 3; j++) {
361 <                        d = av->pos[j] - r->rop[j];
362 <                        e1 += d * d;
363 <                }
359 >                d = av->pos[0] - r->rop[0];
360 >                e1 = d * d;
361 >                d = av->pos[1] - r->rop[1];
362 >                e1 += d * d;
363 >                d = av->pos[2] - r->rop[2];
364 >                e1 += d * d;
365                  e1 /= av->rad * av->rad;
366                  if (e1 > ambacc*ambacc*1.21)
367                          continue;
368                  /*
369 <                 *  Normal direction test.
369 >                 *  Direction test using closest normal.
370                   */
371 <                e2 = (1.0 - DOT(av->dir, r->ron)) * r->rweight;
371 >                d = DOT(av->dir, r->ron);
372 >                if (rn != r->ron) {
373 >                        rn_dot = DOT(av->dir, rn);
374 >                        if (rn_dot > 1.0-FTINY)
375 >                                rn_dot = 1.0-FTINY;
376 >                        if (rn_dot >= d-FTINY) {
377 >                                d = rn_dot;
378 >                                rn_dot = -2.0;
379 >                        }
380 >                }
381 >                e2 = (1.0 - d) * r->rweight;
382                  if (e2 < 0.0) e2 = 0.0;
383                  if (e1 + e2 > ambacc*ambacc*1.21)
384                          continue;
# Line 209 | Line 389 | double  s;
389                  for (j = 0; j < 3; j++)
390                          d += (r->rop[j] - av->pos[j]) *
391                                          (av->dir[j] + r->ron[j]);
392 <                if (d < -minarad)
392 >                if (d*0.5 < -minarad*ambacc-.001)
393                          continue;
394                  /*
395                   *  Jittering final test reduces image artifacts.
396                   */
397 <                wt = sqrt(e1) + sqrt(e2);
398 <                wt *= .9 + .2*frandom();
399 <                if (wt > ambacc)
397 >                e1 = sqrt(e1);
398 >                e2 = sqrt(e2);
399 >                wt = e1 + e2;
400 >                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
401                          continue;
402 +                /*
403 +                 *  Recompute directional error using perturbed normal
404 +                 */
405 +                if (rn_dot > 0.0) {
406 +                        e2 = sqrt((1.0 - rn_dot)*r->rweight);
407 +                        wt = e1 + e2;
408 +                }
409                  if (wt <= 1e-3)
410                          wt = 1e3;
411                  else
412                          wt = 1.0 / wt;
413                  wsum += wt;
414 <                copycolor(ct, av->val);
414 >                extambient(ct, av, r->rop, rn);
415                  scalecolor(ct, wt);
416                  addcolor(acol, ct);
417          }
# Line 242 | Line 430 | double  s;
430                                  break;
431                  }
432                  if (j == 3)
433 <                        wsum += sumambient(acol, r, at->kid+i, ck0, s);
433 >                        wsum += sumambient(acol, r, rn, al,
434 >                                                at->kid+i, ck0, s);
435          }
436          return(wsum);
437   }
438  
439  
440 < double
441 < makeambient(acol, r)            /* make a new ambient value */
442 < COLOR  acol;
443 < register RAY  *r;
440 > extern double
441 > makeambient(            /* make a new ambient value for storage */
442 >        COLOR  acol,
443 >        RAY  *r,
444 >        FVECT  rn,
445 >        int  al
446 > )
447   {
448 <        AMBVAL  amb;
448 >        AMBVAL  amb;
449 >        FVECT   gp, gd;
450 >        int     i;
451  
452 <        amb.rad = doambient(acol, r);           /* compute ambient */
453 <        if (amb.rad == 0.0)
452 >        amb.weight = 1.0;                       /* compute weight */
453 >        for (i = al; i-- > 0; )
454 >                amb.weight *= AVGREFL;
455 >        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
456 >                amb.weight = 1.25*r->rweight;
457 >        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
458 >                                                /* compute ambient */
459 >        amb.rad = doambient(acol, r, amb.weight, gp, gd);
460 >        if (amb.rad <= FTINY) {
461 >                setcolor(acol, 0.0, 0.0, 0.0);
462                  return(0.0);
463 <                                                /* store it */
463 >        }
464 >        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
465 >                                                /* store value */
466          VCOPY(amb.pos, r->rop);
467          VCOPY(amb.dir, r->ron);
468 <        amb.lvl = r->rlvl;
265 <        amb.weight = r->rweight;
468 >        amb.lvl = al;
469          copycolor(amb.val, acol);
470 +        VCOPY(amb.gpos, gp);
471 +        VCOPY(amb.gdir, gd);
472                                                  /* insert into tree */
473 <        avinsert(&amb, &atrunk, thescene.cuorg, thescene.cusize);
474 <        avsave(&amb);                           /* write to file */
473 >        avsave(&amb);                           /* and save to file */
474 >        if (rn != r->ron)
475 >                extambient(acol, &amb, r->rop, rn);     /* texture */
476          return(amb.rad);
477   }
478  
479  
480 < double
481 < doambient(acol, r)                      /* compute ambient component */
482 < COLOR  acol;
483 < register RAY  *r;
480 > extern void
481 > extambient(             /* extrapolate value at pv, nv */
482 >        COLOR  cr,
483 >        register AMBVAL  *ap,
484 >        FVECT  pv,
485 >        FVECT  nv
486 > )
487   {
488 <        extern int  ambcmp();
489 <        extern double  sin(), cos(), sqrt();
490 <        int  hlist[4];
282 <        double  phi, xd, yd, zd;
283 <        double  b, b2;
284 <        register AMBSAMP  *div;
285 <        AMBSAMP  dnew;
286 <        RAY  ar;
287 <        FVECT  ux, uy;
288 <        double  arad;
289 <        int  ndivs, nt, np, ns, ne, i, j;
290 <        register int  k;
488 >        FVECT  v1;
489 >        register int  i;
490 >        double  d;
491  
492 <        setcolor(acol, 0.0, 0.0, 0.0);
493 <                                        /* set number of divisions */
494 <        nt = sqrt(ambdiv * r->rweight * 0.5) + 0.5;
495 <        np = 2 * nt;
496 <        ndivs = nt * np;
497 <                                        /* check first */
498 <        if (ndivs == 0 || rayorigin(&ar, r, AMBIENT, 0.5) < 0)
499 <                return(0.0);
500 <                                        /* set number of super-samples */
501 <        ns = ambssamp * r->rweight + 0.5;
302 <        if (ns > 0) {
303 <                div = (AMBSAMP *)malloc(ndivs*sizeof(AMBSAMP));
304 <                if (div == NULL)
305 <                        error(SYSTEM, "out of memory in doambient");
492 >        d = 1.0;                        /* zeroeth order */
493 >                                        /* gradient due to translation */
494 >        for (i = 0; i < 3; i++)
495 >                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
496 >                                        /* gradient due to rotation */
497 >        VCROSS(v1, ap->dir, nv);
498 >        d += DOT(ap->gdir, v1);
499 >        if (d <= 0.0) {
500 >                setcolor(cr, 0.0, 0.0, 0.0);
501 >                return;
502          }
503 <                                        /* make axes */
504 <        uy[0] = uy[1] = uy[2] = 0.0;
309 <        for (k = 0; k < 3; k++)
310 <                if (r->ron[k] < 0.6 && r->ron[k] > -0.6)
311 <                        break;
312 <        uy[k] = 1.0;
313 <        fcross(ux, r->ron, uy);
314 <        normalize(ux);
315 <        fcross(uy, ux, r->ron);
316 <                                        /* set up urand */
317 <        hlist[0] = r->rno;
318 <                                                /* sample divisions */
319 <        arad = 0.0;
320 <        ne = 0;
321 <        for (i = 0; i < nt; i++) {
322 <                hlist[1] = i;
323 <                for (j = 0; j < np; j++) {
324 <                        rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
325 <                        hlist[2] = j;
326 <                        hlist[3] = 0;
327 <                        zd = sqrt((i+urand(ilhash(hlist,4)))/nt);
328 <                        hlist[3] = 1;
329 <                        phi = 2.0*PI * (j+urand(ilhash(hlist,4)))/np;
330 <                        xd = cos(phi) * zd;
331 <                        yd = sin(phi) * zd;
332 <                        zd = sqrt(1.0 - zd*zd);
333 <                        for (k = 0; k < 3; k++)
334 <                                ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
335 <                        dimlist[ndims++] = i*np + j + 38813;
336 <                        rayvalue(&ar);
337 <                        ndims--;
338 <                        if (ar.rot < FHUGE)
339 <                                arad += 1.0 / ar.rot;
340 <                        if (ns > 0) {                   /* save division */
341 <                                div[ne].k = 0.0;
342 <                                copycolor(div[ne].v, ar.rcol);
343 <                                div[ne].n = 0;
344 <                                div[ne].t = i; div[ne].p = j;
345 <                                                        /* sum errors */
346 <                                b = bright(ar.rcol);
347 <                                if (i > 0) {            /* from above */
348 <                                        b2 = bright(div[ne-np].v) - b;
349 <                                        b2 *= b2 * 0.25;
350 <                                        div[ne].k += b2;
351 <                                        div[ne].n++;
352 <                                        div[ne-np].k += b2;
353 <                                        div[ne-np].n++;
354 <                                }
355 <                                if (j > 0) {            /* from behind */
356 <                                        b2 = bright(div[ne-1].v) - b;
357 <                                        b2 *= b2 * 0.25;
358 <                                        div[ne].k += b2;
359 <                                        div[ne].n++;
360 <                                        div[ne-1].k += b2;
361 <                                        div[ne-1].n++;
362 <                                }
363 <                                if (j == np-1) {        /* around */
364 <                                        b2 = bright(div[ne-(np-1)].v) - b;
365 <                                        b2 *= b2 * 0.25;
366 <                                        div[ne].k += b2;
367 <                                        div[ne].n++;
368 <                                        div[ne-(np-1)].k += b2;
369 <                                        div[ne-(np-1)].n++;
370 <                                }
371 <                                ne++;
372 <                        } else
373 <                                addcolor(acol, ar.rcol);
374 <                }
375 <        }
376 <        for (k = 0; k < ne; k++) {              /* compute errors */
377 <                if (div[k].n > 1)
378 <                        div[k].k /= div[k].n;
379 <                div[k].n = 1;
380 <        }
381 <                                                /* sort the divisions */
382 <        qsort(div, ne, sizeof(AMBSAMP), ambcmp);
383 <                                                /* skim excess */
384 <        while (ne > ns) {
385 <                ne--;
386 <                addcolor(acol, div[ne].v);
387 <        }
388 <                                                /* super-sample */
389 <        for (i = ns; i > 0; i--) {
390 <                rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
391 <                hlist[1] = div[0].t;
392 <                hlist[2] = div[0].p;
393 <                hlist[3] = 0;
394 <                zd = sqrt((div[0].t+urand(ilhash(hlist,4)+div[0].n))/nt);
395 <                hlist[3] = 1;
396 <                phi = 2.0*PI * (div[0].p+urand(ilhash(hlist,4)+div[0].n))/np;
397 <                xd = cos(phi) * zd;
398 <                yd = sin(phi) * zd;
399 <                zd = sqrt(1.0 - zd*zd);
400 <                for (k = 0; k < 3; k++)
401 <                        ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
402 <                dimlist[ndims++] = div[0].t*np + div[0].p + 38813;
403 <                rayvalue(&ar);
404 <                ndims--;
405 <                rayvalue(&ar);
406 <                if (ar.rot < FHUGE)
407 <                        arad += 1.0 / ar.rot;
408 <                                                /* recompute error */
409 <                copycolor(dnew.v, div[0].v);
410 <                addcolor(dnew.v, ar.rcol);
411 <                dnew.n = div[0].n + 1;
412 <                dnew.t = div[0].t; dnew.p = div[0].p;
413 <                b2 = bright(dnew.v)/dnew.n - bright(ar.rcol);
414 <                b2 = b2*b2 + div[0].k*(div[0].n*div[0].n);
415 <                dnew.k = b2/(dnew.n*dnew.n);
416 <                                                /* reinsert */
417 <                for (k = 0; k < ne-1 && dnew.k < div[k+1].k; k++)
418 <                        copystruct(&div[k], &div[k+1]);
419 <                copystruct(&div[k], &dnew);
420 <
421 <                if (ne >= i) {          /* extract darkest division */
422 <                        ne--;
423 <                        if (div[ne].n > 1)
424 <                                scalecolor(div[ne].v, 1.0/div[ne].n);
425 <                        addcolor(acol, div[ne].v);
426 <                }
427 <        }
428 <        scalecolor(acol, 1.0/ndivs);
429 <        if (arad <= FTINY)
430 <                arad = FHUGE;
431 <        else
432 <                arad = (ndivs+ns) / arad / sqrt(r->rweight);
433 <        if (arad > maxarad)
434 <                arad = maxarad;
435 <        else if (arad < minarad)
436 <                arad = minarad;
437 <        if (ns > 0)
438 <                free((char *)div);
439 <        return(arad);
503 >        copycolor(cr, ap->val);
504 >        scalecolor(cr, d);
505   }
506  
507  
508 < static int
509 < ambcmp(d1, d2)                          /* decreasing order */
510 < AMBSAMP  *d1, *d2;
508 > static void
509 > initambfile(            /* initialize ambient file */
510 >        int  creat
511 > )
512   {
513 <        if (d1->k < d2->k)
514 <                return(1);
515 <        if (d1->k > d2->k)
516 <                return(-1);
517 <        return(0);
513 >        extern char  *progname, *octname;
514 >        static char  *mybuf = NULL;
515 >
516 > #ifdef  F_SETLKW
517 >        aflock(creat ? F_WRLCK : F_RDLCK);
518 > #endif
519 >        SET_FILE_BINARY(ambfp);
520 >        if (mybuf == NULL)
521 >                mybuf = (char *)bmalloc(BUFSIZ+8);
522 >        setbuf(ambfp, mybuf);
523 >        if (creat) {                    /* new file */
524 >                newheader("RADIANCE", ambfp);
525 >                fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
526 >                                progname, colval(ambval,RED),
527 >                                colval(ambval,GRN), colval(ambval,BLU),
528 >                                ambvwt, ambounce, ambacc);
529 >                fprintf(ambfp, "-ad %d -as %d -ar %d ",
530 >                                ambdiv, ambssamp, ambres);
531 >                if (octname != NULL)
532 >                        printargs(1, &octname, ambfp);
533 >                else
534 >                        fputc('\n', ambfp);
535 >                fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
536 >                fputnow(ambfp);
537 >                fputformat(AMBFMT, ambfp);
538 >                putc('\n', ambfp);
539 >                putambmagic(ambfp);
540 >        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
541 >                error(USER, "bad ambient file");
542   }
543  
544  
545 < static
546 < avsave(av)                              /* save an ambient value */
547 < AMBVAL  *av;
545 > static void
546 > avsave(                         /* insert and save an ambient value */
547 >        AMBVAL  *av
548 > )
549   {
550 < #ifdef  AMBFLUSH
460 <        static int  nunflshed = 0;
461 < #endif
550 >        avinsert(avstore(av));
551          if (ambfp == NULL)
552                  return;
553 <        if (fwrite((char *)av, sizeof(AMBVAL), 1, ambfp) != 1)
553 >        if (writambval(av, ambfp) < 0)
554                  goto writerr;
555 < #ifdef  AMBFLUSH
556 <        if (++nunflshed >= AMBFLUSH) {
468 <                if (fflush(ambfp) == EOF)
555 >        if (++nunflshed >= AMBFLUSH)
556 >                if (ambsync() == EOF)
557                          goto writerr;
470                nunflshed = 0;
471        }
472 #endif
558          return;
559   writerr:
560 <        error(SYSTEM, "error writing ambient file");
560 >        error(SYSTEM, "error writing to ambient file");
561   }
562  
563  
564 < static
565 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
566 < AMBVAL  *aval;
567 < register AMBTREE  *at;
483 < FVECT  c0;
484 < double  s;
564 > static AMBVAL *
565 > avstore(                                /* allocate memory and store aval */
566 >        register AMBVAL  *aval
567 > )
568   {
569 +        register AMBVAL  *av;
570 +        double  d;
571 +
572 +        if ((av = newambval()) == NULL)
573 +                error(SYSTEM, "out of memory in avstore");
574 +        *av = *aval;
575 +        av->latick = ambclock;
576 +        av->next = NULL;
577 +        nambvals++;
578 +        d = bright(av->val);
579 +        if (d > FTINY) {                /* add to log sum for averaging */
580 +                avsum += log(d);
581 +                navsum++;
582 +        }
583 +        return(av);
584 + }
585 +
586 +
587 + #define ATALLOCSZ       512             /* #/8 trees to allocate at once */
588 +
589 + static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
590 +
591 +
592 + static AMBTREE *
593 + newambtree(void)                                /* allocate 8 ambient tree structs */
594 + {
595 +        register AMBTREE  *atp, *upperlim;
596 +
597 +        if (atfreelist == NULL) {       /* get more nodes */
598 +                atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
599 +                if (atfreelist == NULL)
600 +                        return(NULL);
601 +                                        /* link new free list */
602 +                upperlim = atfreelist + 8*(ATALLOCSZ-1);
603 +                for (atp = atfreelist; atp < upperlim; atp += 8)
604 +                        atp->kid = atp + 8;
605 +                atp->kid = NULL;
606 +        }
607 +        atp = atfreelist;
608 +        atfreelist = atp->kid;
609 +        memset((char *)atp, '\0', 8*sizeof(AMBTREE));
610 +        return(atp);
611 + }
612 +
613 +
614 + static void
615 + freeambtree(                    /* free 8 ambient tree structs */
616 +        AMBTREE  *atp
617 + )
618 + {
619 +        atp->kid = atfreelist;
620 +        atfreelist = atp;
621 + }
622 +
623 +
624 + static void
625 + avinsert(                               /* insert ambient value in our tree */
626 +        void *av
627 + )
628 + {
629 +        register AMBTREE  *at;
630 +        register AMBVAL  *ap;
631 +        AMBVAL  avh;
632          FVECT  ck0;
633 +        double  s;
634          int  branch;
488        register AMBVAL  *av;
635          register int  i;
636  
637 <        if ((av = newambval()) == NULL)
638 <                goto memerr;
639 <        copystruct(av, aval);
640 <        VCOPY(ck0, c0);
641 <        while (s*(OCTSCALE/2) > av->rad*ambacc) {
637 >        if (((AMBVAL*)av)->rad <= FTINY)
638 >                error(CONSISTENCY, "zero ambient radius in avinsert");
639 >        at = &atrunk;
640 >        VCOPY(ck0, thescene.cuorg);
641 >        s = thescene.cusize;
642 >        while (s*(OCTSCALE/2) > ((AMBVAL*)av)->rad*ambacc) {
643                  if (at->kid == NULL)
644                          if ((at->kid = newambtree()) == NULL)
645 <                                goto memerr;
645 >                                error(SYSTEM, "out of memory in avinsert");
646                  s *= 0.5;
647                  branch = 0;
648                  for (i = 0; i < 3; i++)
649 <                        if (av->pos[i] > ck0[i] + s) {
649 >                        if (((AMBVAL*)av)->pos[i] > ck0[i] + s) {
650                                  ck0[i] += s;
651                                  branch |= 1 << i;
652                          }
653                  at = at->kid + branch;
654          }
655 <        av->next = at->alist;
656 <        at->alist = av;
657 <        return;
658 < memerr:
659 <        error(SYSTEM, "out of memory in avinsert");
655 >        avh.next = at->alist;           /* order by increasing level */
656 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
657 >                if (ap->next->lvl >= ((AMBVAL*)av)->lvl)
658 >                        break;
659 >        ((AMBVAL*)av)->next = ap->next;
660 >        ap->next = (AMBVAL*)av;
661 >        at->alist = avh.next;
662   }
663 +
664 +
665 + static void
666 + unloadatree(                    /* unload an ambient value tree */
667 +        register AMBTREE  *at,
668 +        unloadtf_t *f
669 + )
670 + {
671 +        register AMBVAL  *av;
672 +        register int  i;
673 +                                        /* transfer values at this node */
674 +        for (av = at->alist; av != NULL; av = at->alist) {
675 +                at->alist = av->next;
676 +                (*f)(av);
677 +        }
678 +        if (at->kid == NULL)
679 +                return;
680 +        for (i = 0; i < 8; i++)         /* transfer and free children */
681 +                unloadatree(at->kid+i, f);
682 +        freeambtree(at->kid);
683 +        at->kid = NULL;
684 + }
685 +
686 +
687 + static struct avl {
688 +        AMBVAL  *p;
689 +        unsigned long   t;
690 + }       *avlist1;                       /* ambient value list with ticks */
691 + static AMBVAL   **avlist2;              /* memory positions for sorting */
692 + static int      i_avlist;               /* index for lists */
693 +
694 + static int alatcmp(const void *av1, const void *av2);
695 +
696 + static void
697 + av2list(
698 +        void *av
699 + )
700 + {
701 + #ifdef DEBUG
702 +        if (i_avlist >= nambvals)
703 +                error(CONSISTENCY, "too many ambient values in av2list1");
704 + #endif
705 +        avlist1[i_avlist].p = avlist2[i_avlist] = (AMBVAL*)av;
706 +        avlist1[i_avlist++].t = ((AMBVAL*)av)->latick;
707 + }
708 +
709 +
710 + static int
711 + alatcmp(                        /* compare ambient values for MRA */
712 +        const void *av1,
713 +        const void *av2
714 + )
715 + {
716 +        register long  lc = ((struct avl *)av2)->t - ((struct avl *)av1)->t;
717 +        return(lc<0 ? -1 : lc>0 ? 1 : 0);
718 + }
719 +
720 +
721 + /* GW NOTE 2002/10/3:
722 + * I used to compare AMBVAL pointers, but found that this was the
723 + * cause of a serious consistency error with gcc, since the optimizer
724 + * uses some dangerous trick in pointer subtraction that
725 + * assumes pointers differ by exact struct size increments.
726 + */
727 + static int
728 + aposcmp(                        /* compare ambient value positions */
729 +        const void      *avp1,
730 +        const void      *avp2
731 + )
732 + {
733 +        register long   diff = *(char * const *)avp1 - *(char * const *)avp2;
734 +        if (diff < 0)
735 +                return(-1);
736 +        return(diff > 0);
737 + }
738 +
739 + #if 1
740 + static int
741 + avlmemi(                                /* find list position from address */
742 +        AMBVAL  *avaddr
743 + )
744 + {
745 +        register AMBVAL  **avlpp;
746 +
747 +        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
748 +                        nambvals, sizeof(AMBVAL *), aposcmp);
749 +        if (avlpp == NULL)
750 +                error(CONSISTENCY, "address not found in avlmemi");
751 +        return(avlpp - avlist2);
752 + }
753 + #else
754 + #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
755 +                                nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
756 + #endif
757 +
758 +
759 + static void
760 + sortambvals(                    /* resort ambient values */
761 +        int     always
762 + )
763 + {
764 +        AMBTREE  oldatrunk;
765 +        AMBVAL  tav, *tap, *pnext;
766 +        register int    i, j;
767 +                                        /* see if it's time yet */
768 +        if (!always && (ambclock++ < lastsort+sortintvl ||
769 +                        nambvals < SORT_THRESH))
770 +                return;
771 +        /*
772 +         * The idea here is to minimize memory thrashing
773 +         * in VM systems by improving reference locality.
774 +         * We do this by periodically sorting our stored ambient
775 +         * values in memory in order of most recently to least
776 +         * recently accessed.  This ordering was chosen so that new
777 +         * ambient values (which tend to be less important) go into
778 +         * higher memory with the infrequently accessed values.
779 +         *      Since we expect our values to need sorting less
780 +         * frequently as the process continues, we double our
781 +         * waiting interval after each call.
782 +         *      This routine is also called by setambacc() with
783 +         * the "always" parameter set to 1 so that the ambient
784 +         * tree will be rebuilt with the new accuracy parameter.
785 +         */
786 +        if (tracktime) {                /* allocate pointer arrays to sort */
787 +                avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
788 +                avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
789 +        } else {
790 +                avlist2 = NULL;
791 +                avlist1 = NULL;
792 +        }
793 +        if (avlist1 == NULL) {          /* no time tracking -- rebuild tree? */
794 +                if (avlist2 != NULL)
795 +                        free((void *)avlist2);
796 +                if (always) {           /* rebuild without sorting */
797 +                        oldatrunk = atrunk;
798 +                        atrunk.alist = NULL;
799 +                        atrunk.kid = NULL;
800 +                        unloadatree(&oldatrunk, avinsert);
801 +                }
802 +        } else {                        /* sort memory by last access time */
803 +                /*
804 +                 * Sorting memory is tricky because it isn't contiguous.
805 +                 * We have to sort an array of pointers by MRA and also
806 +                 * by memory position.  We then copy values in "loops"
807 +                 * to minimize memory hits.  Nevertheless, we will visit
808 +                 * everyone at least twice, and this is an expensive process
809 +                 * when we're thrashing, which is when we need to do it.
810 +                 */
811 + #ifdef DEBUG
812 +                sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
813 +                                nambvals, ambclock);
814 +                eputs(errmsg);
815 + #endif
816 +                i_avlist = 0;
817 +                unloadatree(&atrunk, av2list);  /* empty current tree */
818 + #ifdef DEBUG
819 +                if (i_avlist < nambvals)
820 +                        error(CONSISTENCY, "missing ambient values in sortambvals");
821 + #endif
822 +                qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
823 +                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
824 +                for (i = 0; i < nambvals; i++) {
825 +                        if (avlist1[i].p == NULL)
826 +                                continue;
827 +                        tap = avlist2[i];
828 +                        tav = *tap;
829 +                        for (j = i; (pnext = avlist1[j].p) != tap;
830 +                                        j = avlmemi(pnext)) {
831 +                                *(avlist2[j]) = *pnext;
832 +                                avinsert(avlist2[j]);
833 +                                avlist1[j].p = NULL;
834 +                        }
835 +                        *(avlist2[j]) = tav;
836 +                        avinsert(avlist2[j]);
837 +                        avlist1[j].p = NULL;
838 +                }
839 +                free((void *)avlist1);
840 +                free((void *)avlist2);
841 +                                                /* compute new sort interval */
842 +                sortintvl = ambclock - lastsort;
843 +                if (sortintvl >= MAX_SORT_INTVL/2)
844 +                        sortintvl = MAX_SORT_INTVL;
845 +                else
846 +                        sortintvl <<= 1;        /* wait twice as long next */
847 + #ifdef DEBUG
848 +                eputs("done\n");
849 + #endif
850 +        }
851 +        if (ambclock >= MAXACLOCK)
852 +                ambclock = MAXACLOCK/2;
853 +        lastsort = ambclock;
854 + }
855 +
856 +
857 + #ifdef  F_SETLKW
858 +
859 + static void
860 + aflock(                 /* lock/unlock ambient file */
861 +        int  typ
862 + )
863 + {
864 +        static struct flock  fls;       /* static so initialized to zeroes */
865 +
866 +        fls.l_type = typ;
867 +        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
868 +                error(SYSTEM, "cannot (un)lock ambient file");
869 + }
870 +
871 +
872 + extern int
873 + ambsync(void)                   /* synchronize ambient file */
874 + {
875 +        long  flen;
876 +        AMBVAL  avs;
877 +        register int  n;
878 +
879 +        if (ambfp == NULL)      /* no ambient file? */
880 +                return(0);
881 +        if (lastpos < 0)        /* initializing (locked in initambfile) */
882 +                goto syncend;
883 +                                /* gain appropriate access */
884 +        aflock(nunflshed ? F_WRLCK : F_RDLCK);
885 +                                /* see if file has grown */
886 +        if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
887 +                goto seekerr;
888 +        if ( (n = flen - lastpos) ) {           /* file has grown */
889 +                if (ambinp == NULL) {           /* use duplicate filedes */
890 +                        ambinp = fdopen(dup(fileno(ambfp)), "r");
891 +                        if (ambinp == NULL)
892 +                                error(SYSTEM, "fdopen failed in ambsync");
893 +                }
894 +                if (fseek(ambinp, lastpos, 0) < 0)
895 +                        goto seekerr;
896 +                while (n >= AMBVALSIZ) {        /* load contributed values */
897 +                        if (!readambval(&avs, ambinp)) {
898 +                                sprintf(errmsg,
899 +                        "ambient file \"%s\" corrupted near character %ld",
900 +                                                ambfile, flen - n);
901 +                                error(WARNING, errmsg);
902 +                                break;
903 +                        }
904 +                        avinsert(avstore(&avs));
905 +                        n -= AMBVALSIZ;
906 +                }
907 +                lastpos = flen - n;
908 +                /*** seek always as safety measure
909 +                if (n) ***/                     /* alignment */
910 +                        if (lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
911 +                                goto seekerr;
912 +        }
913 + #ifdef  DEBUG
914 +        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
915 +                sprintf(errmsg, "ambient file buffer at %d rather than %d",
916 +                                ambfp->_ptr - ambfp->_base,
917 +                                nunflshed*AMBVALSIZ);
918 +                error(CONSISTENCY, errmsg);
919 +        }
920 + #endif
921 + syncend:
922 +        n = fflush(ambfp);                      /* calls write() at last */
923 +        if ((n == EOF) | (lastpos < 0)) {
924 +                if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
925 +                        goto seekerr;
926 +        } else
927 +                lastpos += (long)nunflshed*AMBVALSIZ;
928 +        aflock(F_UNLCK);                        /* release file */
929 +        nunflshed = 0;
930 +        return(n);
931 + seekerr:
932 +        error(SYSTEM, "seek failed in ambsync");
933 +        return -1; /* pro forma return */
934 + }
935 +
936 + #else
937 +
938 + extern int
939 + ambsync(void)                   /* flush ambient file */
940 + {
941 +        if (ambfp == NULL)
942 +                return(0);
943 +        nunflshed = 0;
944 +        return(fflush(ambfp));
945 + }
946 +
947 + #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines