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.3 by greg, Fri May 26 17:58:01 1989 UTC vs.
Revision 2.20 by greg, Thu Aug 5 10:02:00 1993 UTC

# Line 1 | Line 1
1 < /* Copyright (c) 1986 Regents of the University of California */
1 > /* Copyright (c) 1993 Regents of the University of California */
2  
3   #ifndef lint
4   static char SCCSid[] = "$SunId$ LBL";
# Line 6 | Line 6 | static char SCCSid[] = "$SunId$ LBL";
6  
7   /*
8   *  ambient.c - routines dealing with ambient (inter-reflected) component.
9 *
10 *  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
9   */
10  
11   #include  "ray.h"
12  
13   #include  "octree.h"
14  
15 + #include  "otypes.h"
16 +
17 + #include  "ambient.h"
18 +
19   #include  "random.h"
20  
21 < #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
21 > #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
22  
23 + typedef struct ambtree {
24 +        AMBVAL  *alist;         /* ambient value list */
25 +        struct ambtree  *kid;   /* 8 child nodes */
26 + }  AMBTREE;                     /* ambient octree */
27 +
28   extern CUBE  thescene;          /* contains space boundaries */
29  
30 < extern COLOR  ambval;           /* global ambient component */
31 < extern double  ambacc;          /* ambient accuracy */
28 < extern int  ambres;             /* ambient resolution */
29 < extern int  ambdiv;             /* number of divisions for calculation */
30 < extern int  ambssamp;           /* number of super-samples */
31 < extern int  ambounce;           /* number of ambient bounces */
32 < extern char  *amblist[];        /* ambient include/exclude list */
33 < extern int  ambincl;            /* include == 1, exclude == 0 */
30 > #define  MAXASET        511     /* maximum number of elements in ambient set */
31 > OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
32  
33 < OBJECT  ambset[128];            /* ambient include/exclude set */
33 > double  maxarad;                /* maximum ambient radius */
34 > double  minarad;                /* minimum ambient radius */
35  
36 < double  maxarad;                /* maximum ambient radius */
38 < double  minarad;                /* minimum ambient radius */
36 > static AMBTREE  atrunk;         /* our ambient trunk node */
37  
38 < typedef struct ambval {
39 <        FVECT  pos;             /* position in space */
42 <        FVECT  dir;             /* normal direction */
43 <        int  lvl;               /* recursion level of parent ray */
44 <        float  weight;          /* weight of parent ray */
45 <        COLOR  val;             /* computed ambient value */
46 <        float  rad;             /* validity radius */
47 <        struct ambval  *next;   /* next in list */
48 < }  AMBVAL;                      /* ambient value */
38 > static FILE  *ambfp = NULL;     /* ambient file pointer */
39 > static int  nunflshed = 0;      /* number of unflushed ambient values */
40  
41 < typedef struct ambtree {
51 <        AMBVAL  *alist;         /* ambient value list */
52 <        struct ambtree  *kid;   /* 8 child nodes */
53 < }  AMBTREE;                     /* ambient octree */
41 > #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
42  
43 < typedef struct {
56 <        float  k;               /* error contribution per sample */
57 <        COLOR  v;               /* ray sum */
58 <        int  n;                 /* number of samples */
59 <        short  t, p;            /* theta, phi indices */
60 < }  AMBSAMP;                     /* ambient sample */
43 > #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
44  
45 < static AMBTREE  atrunk;         /* our ambient trunk node */
45 > #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
46 > #define  freeambtree(t) free((char *)(t))
47  
48 < static FILE  *ambfp = NULL;     /* ambient file pointer */
48 > extern long  ftell(), lseek();
49 > static int  initambfile(), avsave(), avinsert(), loadtree();
50 > static AMBVAL  *avstore();
51 > #ifdef  F_SETLKW
52 > static  aflock();
53 > #endif
54  
66 #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
55  
56 < #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
56 > setambres(ar)                           /* set ambient resolution */
57 > int  ar;
58 > {
59 >        ambres = ar;                    /* may be done already */
60 >                                                /* set min & max radii */
61 >        if (ar <= 0) {
62 >                minarad = 0.0;
63 >                maxarad = thescene.cusize / 2.0;
64 >        } else {
65 >                minarad = thescene.cusize / ar;
66 >                maxarad = 16.0 * minarad;               /* heuristic */
67 >                if (maxarad > thescene.cusize / 2.0)
68 >                        maxarad = thescene.cusize / 2.0;
69 >        }
70 >        if (maxarad <= FTINY)
71 >                maxarad = .001;
72 > }
73  
70 double  sumambient(), doambient(), makeambient();
74  
75 + resetambacc(newa)                       /* change ambient accuracy setting */
76 + double  newa;
77 + {
78 +        AMBTREE  oldatrunk;
79  
80 +        if (fabs(newa - ambacc) < 0.01)
81 +                return;                 /* insignificant -- don't bother */
82 +        ambacc = newa;
83 +        if (ambacc <= FTINY)
84 +                return;                 /* cannot build new tree */
85 +                                        /* else need to rebuild tree */
86 +        copystruct(&oldatrunk, &atrunk);
87 +        atrunk.alist = NULL;
88 +        atrunk.kid = NULL;
89 +        loadtree(&oldatrunk);
90 + }
91 +
92 +
93   setambient(afile)                       /* initialize calculation */
94   char  *afile;
95   {
96 <        long  ftell();
97 <        char  **amblp;
98 <        OBJECT  obj;
99 <        AMBVAL  amb;
100 <                                        /* set up ambient set */
101 <        ambset[0] = 0;
102 <        for (amblp = amblist; *amblp != NULL; amblp++) {
103 <                if ((obj = modifier(*amblp)) == OVOID) {
104 <                        sprintf(errmsg, "unknown %s modifier \"%s\"",
105 <                                ambincl ? "include" : "exclude", *amblp);
106 <                        error(WARNING, errmsg);
87 <                        continue;
88 <                }
89 <                if (!inset(ambset, obj))
90 <                        insertelem(ambset, obj);
96 >        long  headlen;
97 >        AMBVAL  amb;
98 >                                                /* init ambient limits */
99 >        setambres(ambres);
100 >        if (afile == NULL)
101 >                return;
102 >        if (ambacc <= FTINY) {
103 >                sprintf(errmsg, "zero ambient accuracy so \"%s\" not loaded",
104 >                                afile);
105 >                error(WARNING, errmsg);
106 >                return;
107          }
108 <        maxarad = thescene.cusize / 2.0;                /* maximum radius */
109 <                                                        /* minimum radius */
110 <        minarad = ambres > 0 ? thescene.cusize/ambres : 0.0;
108 >                                                /* open ambient file */
109 >        if ((ambfp = fopen(afile, "r+")) != NULL) {
110 >                initambfile(0);
111 >                headlen = ftell(ambfp);
112 >                while (readambval(&amb, ambfp))
113 >                        avinsert(avstore(&amb), &atrunk,
114 >                                        thescene.cuorg, thescene.cusize);
115 >                                                /* align */
116 >                fseek(ambfp, -((ftell(ambfp)-headlen)%AMBVALSIZ), 1);
117 >        } else if ((ambfp = fopen(afile, "w+")) != NULL)
118 >                initambfile(1);
119 >        else {
120 >                sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
121 >                error(SYSTEM, errmsg);
122 >        }
123 >        nunflshed++;    /* lie */
124 >        ambsync();
125 > }
126  
127 <                                        /* open ambient file */
128 <        if (afile != NULL)
129 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
130 <                        while (fread(&amb, sizeof(AMBVAL), 1, ambfp) == 1)
131 <                                avinsert(&amb, &atrunk, thescene.cuorg,
132 <                                                thescene.cusize);
133 <                                                        /* align */
134 <                        fseek(ambfp, -(ftell(ambfp)%sizeof(AMBVAL)), 1);
135 <                } else if ((ambfp = fopen(afile, "w")) == NULL) {
136 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
137 <                                        afile);
138 <                        error(SYSTEM, errmsg);
127 >
128 > ambnotify(obj)                  /* record new modifier */
129 > OBJECT  obj;
130 > {
131 >        static int  hitlimit = 0;
132 >        register OBJREC  *o = objptr(obj);
133 >        register char  **amblp;
134 >
135 >        if (hitlimit || !ismodifier(o->otype))
136 >                return;
137 >        for (amblp = amblist; *amblp != NULL; amblp++)
138 >                if (!strcmp(o->oname, *amblp)) {
139 >                        if (ambset[0] >= MAXASET) {
140 >                                error(WARNING, "too many modifiers in ambient list");
141 >                                hitlimit++;
142 >                                return;         /* should this be fatal? */
143 >                        }
144 >                        insertelem(ambset, obj);
145 >                        return;
146                  }
147   }
148  
# Line 114 | Line 152 | COLOR  acol;
152   register RAY  *r;
153   {
154          static int  rdepth = 0;                 /* ambient recursion */
155 <        double  wsum;
155 >        double  d;
156  
119        rdepth++;                               /* increment level */
120
157          if (ambdiv <= 0)                        /* no ambient calculation */
158                  goto dumbamb;
159                                                  /* check number of bounces */
160 <        if (rdepth > ambounce)
160 >        if (rdepth >= ambounce)
161                  goto dumbamb;
162                                                  /* check ambient list */
163          if (ambincl != -1 && r->ro != NULL &&
# Line 129 | Line 165 | register RAY  *r;
165                  goto dumbamb;
166  
167          if (ambacc <= FTINY) {                  /* no ambient storage */
168 <                if (doambient(acol, r) == 0.0)
168 >                rdepth++;
169 >                d = doambient(acol, r, r->rweight, NULL, NULL);
170 >                rdepth--;
171 >                if (d == 0.0)
172                          goto dumbamb;
173 <                goto done;
173 >                return;
174          }
175                                                  /* get ambient value */
176          setcolor(acol, 0.0, 0.0, 0.0);
177 <        wsum = sumambient(acol, r, &atrunk, thescene.cuorg, thescene.cusize);
178 <        if (wsum > FTINY)
179 <                scalecolor(acol, 1.0/wsum);
180 <        else if (makeambient(acol, r) == 0.0)
181 <                goto dumbamb;
182 <        goto done;
183 <
177 >        d = sumambient(acol, r, rdepth,
178 >                        &atrunk, thescene.cuorg, thescene.cusize);
179 >        if (d > FTINY)
180 >                scalecolor(acol, 1.0/d);
181 >        else {
182 >                d = makeambient(acol, r, rdepth++);
183 >                rdepth--;
184 >        }
185 >        if (d > FTINY)
186 >                return;
187   dumbamb:                                        /* return global value */
188          copycolor(acol, ambval);
147 done:                                           /* must finish here! */
148        rdepth--;
189   }
190  
191  
192   double
193 < sumambient(acol, r, at, c0, s)          /* get interpolated ambient value */
193 > sumambient(acol, r, al, at, c0, s)      /* get interpolated ambient value */
194   COLOR  acol;
195   register RAY  *r;
196 < AMBTREE  *at;
196 > int  al;
197 > AMBTREE  *at;
198   FVECT  c0;
199 < double  s;
199 > double  s;
200   {
201 <        extern double  sqrt();
161 <        double  d, e1, e2, wt, wsum;
201 >        double  d, e1, e2, wt, wsum;
202          COLOR  ct;
203          FVECT  ck0;
204          int  i;
205          register int  j;
206 <        register AMBVAL  *av;
206 >        register AMBVAL  *av;
207                                          /* do this node */
208          wsum = 0.0;
209          for (av = at->alist; av != NULL; av = av->next) {
210                  /*
211 <                 *  Ray strength test.
211 >                 *  Ambient level test.
212                   */
213 <                if (av->lvl > r->rlvl || av->weight < r->rweight-FTINY)
213 >                if (av->lvl > al || av->weight < r->rweight-FTINY)
214                          continue;
215                  /*
216                   *  Ambient radius test.
# Line 197 | Line 237 | double  s;
237                  for (j = 0; j < 3; j++)
238                          d += (r->rop[j] - av->pos[j]) *
239                                          (av->dir[j] + r->ron[j]);
240 <                if (d < -minarad)
240 >                if (d*0.5 < -minarad*ambacc-.001)
241                          continue;
242                  /*
243                   *  Jittering final test reduces image artifacts.
244                   */
245                  wt = sqrt(e1) + sqrt(e2);
246 <                if (wt > ambacc*(0.9 + 0.2*frandom()))
246 >                wt *= .9 + .2*urand(9015+samplendx);
247 >                if (wt > ambacc)
248                          continue;
249                  if (wt <= 1e-3)
250                          wt = 1e3;
251                  else
252                          wt = 1.0 / wt;
253                  wsum += wt;
254 <                copycolor(ct, av->val);
254 >                extambient(ct, av, r->rop, r->ron);
255                  scalecolor(ct, wt);
256                  addcolor(acol, ct);
257          }
# Line 229 | Line 270 | double  s;
270                                  break;
271                  }
272                  if (j == 3)
273 <                        wsum += sumambient(acol, r, at->kid+i, ck0, s);
273 >                        wsum += sumambient(acol, r, al, at->kid+i, ck0, s);
274          }
275          return(wsum);
276   }
277  
278  
279   double
280 < makeambient(acol, r)            /* make a new ambient value */
280 > makeambient(acol, r, al)        /* make a new ambient value */
281   COLOR  acol;
282   register RAY  *r;
283 + int  al;
284   {
285 <        AMBVAL  amb;
286 <
287 <        amb.rad = doambient(acol, r);           /* compute ambient */
285 >        AMBVAL  amb;
286 >        FVECT   gp, gd;
287 >                                                /* compute weight */
288 >        amb.weight = pow(AVGREFL, (double)al);
289 >        if (r->rweight < 0.2*amb.weight)        /* heuristic */
290 >                amb.weight = r->rweight;
291 >                                                /* compute ambient */
292 >        amb.rad = doambient(acol, r, amb.weight, gp, gd);
293          if (amb.rad == 0.0)
294                  return(0.0);
295                                                  /* store it */
296          VCOPY(amb.pos, r->rop);
297          VCOPY(amb.dir, r->ron);
298 <        amb.lvl = r->rlvl;
252 <        amb.weight = r->rweight;
298 >        amb.lvl = al;
299          copycolor(amb.val, acol);
300 +        VCOPY(amb.gpos, gp);
301 +        VCOPY(amb.gdir, gd);
302                                                  /* insert into tree */
303 <        avinsert(&amb, &atrunk, thescene.cuorg, thescene.cusize);
256 <        avsave(&amb);                           /* write to file */
303 >        avsave(&amb);                           /* and save to file */
304          return(amb.rad);
305   }
306  
307  
308 < double
309 < doambient(acol, r)                      /* compute ambient component */
310 < COLOR  acol;
311 < register RAY  *r;
308 > extambient(cr, ap, pv, nv)              /* extrapolate value at pv, nv */
309 > COLOR  cr;
310 > register AMBVAL  *ap;
311 > FVECT  pv, nv;
312   {
313 <        extern int  ambcmp();
314 <        extern double  sin(), cos(), sqrt();
315 <        double  phi, xd, yd, zd;
269 <        double  b, b2;
270 <        register AMBSAMP  *div;
271 <        AMBSAMP  dnew;
272 <        RAY  ar;
273 <        FVECT  ux, uy;
274 <        double  arad;
275 <        int  ndivs, nt, np, ns, ne, i, j;
276 <        register int  k;
313 >        FVECT  v1, v2;
314 >        register int  i;
315 >        double  d;
316  
317 <        setcolor(acol, 0.0, 0.0, 0.0);
318 <                                        /* set number of divisions */
319 <        nt = sqrt(ambdiv * r->rweight * 0.5) + 0.5;
320 <        np = 2 * nt;
321 <        ndivs = nt * np;
322 <                                        /* check first */
323 <        if (ndivs == 0 || rayorigin(&ar, r, AMBIENT, 0.5) < 0)
324 <                return(0.0);
325 <                                        /* set number of super-samples */
326 <        ns = ambssamp * r->rweight + 0.5;
327 <        if (ns > 0) {
289 <                div = (AMBSAMP *)malloc(ndivs*sizeof(AMBSAMP));
290 <                if (div == NULL)
291 <                        error(SYSTEM, "out of memory in doambient");
317 >        d = 1.0;                        /* zeroeth order */
318 >                                        /* gradient due to translation */
319 >        for (i = 0; i < 3; i++)
320 >                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
321 >                                        /* gradient due to rotation */
322 >        VCOPY(v1, ap->dir);
323 >        fcross(v2, v1, nv);
324 >        d += DOT(ap->gdir, v2);
325 >        if (d <= 0.0) {
326 >                setcolor(cr, 0.0, 0.0, 0.0);
327 >                return;
328          }
329 <                                        /* make axes */
330 <        uy[0] = uy[1] = uy[2] = 0.0;
295 <        for (k = 0; k < 3; k++)
296 <                if (r->ron[k] < 0.6 && r->ron[k] > -0.6)
297 <                        break;
298 <        uy[k] = 1.0;
299 <        fcross(ux, r->ron, uy);
300 <        normalize(ux);
301 <        fcross(uy, ux, r->ron);
302 <                                                /* sample divisions */
303 <        arad = 0.0;
304 <        ne = 0;
305 <        for (i = 0; i < nt; i++)
306 <                for (j = 0; j < np; j++) {
307 <                        rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
308 <                        zd = sqrt((i+frandom())/nt);
309 <                        phi = 2.0*PI * (j+frandom())/np;
310 <                        xd = cos(phi) * zd;
311 <                        yd = sin(phi) * zd;
312 <                        zd = sqrt(1.0 - zd*zd);
313 <                        for (k = 0; k < 3; k++)
314 <                                ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
315 <                        rayvalue(&ar);
316 <                        if (ar.rot < FHUGE)
317 <                                arad += 1.0 / ar.rot;
318 <                        if (ns > 0) {                   /* save division */
319 <                                div[ne].k = 0.0;
320 <                                copycolor(div[ne].v, ar.rcol);
321 <                                div[ne].n = 0;
322 <                                div[ne].t = i; div[ne].p = j;
323 <                                                        /* sum errors */
324 <                                b = bright(ar.rcol);
325 <                                if (i > 0) {            /* from above */
326 <                                        b2 = bright(div[ne-np].v) - b;
327 <                                        b2 *= b2 * 0.25;
328 <                                        div[ne].k += b2;
329 <                                        div[ne].n++;
330 <                                        div[ne-np].k += b2;
331 <                                        div[ne-np].n++;
332 <                                }
333 <                                if (j > 0) {            /* from behind */
334 <                                        b2 = bright(div[ne-1].v) - b;
335 <                                        b2 *= b2 * 0.25;
336 <                                        div[ne].k += b2;
337 <                                        div[ne].n++;
338 <                                        div[ne-1].k += b2;
339 <                                        div[ne-1].n++;
340 <                                }
341 <                                if (j == np-1) {        /* around */
342 <                                        b2 = bright(div[ne-(np-1)].v) - b;
343 <                                        b2 *= b2 * 0.25;
344 <                                        div[ne].k += b2;
345 <                                        div[ne].n++;
346 <                                        div[ne-(np-1)].k += b2;
347 <                                        div[ne-(np-1)].n++;
348 <                                }
349 <                                ne++;
350 <                        } else
351 <                                addcolor(acol, ar.rcol);
352 <                }
353 <        for (k = 0; k < ne; k++) {              /* compute errors */
354 <                if (div[k].n > 1)
355 <                        div[k].k /= div[k].n;
356 <                div[k].n = 1;
357 <        }
358 <                                                /* sort the divisions */
359 <        qsort(div, ne, sizeof(AMBSAMP), ambcmp);
360 <                                                /* skim excess */
361 <        while (ne > ns) {
362 <                ne--;
363 <                addcolor(acol, div[ne].v);
364 <        }
365 <                                                /* super-sample */
366 <        for (i = ns; i > 0; i--) {
367 <                rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
368 <                zd = sqrt((div[0].t+frandom())/nt);
369 <                phi = 2.0*PI * (div[0].p+frandom())/np;
370 <                xd = cos(phi) * zd;
371 <                yd = sin(phi) * zd;
372 <                zd = sqrt(1.0 - zd*zd);
373 <                for (k = 0; k < 3; k++)
374 <                        ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
375 <                rayvalue(&ar);
376 <                if (ar.rot < FHUGE)
377 <                        arad += 1.0 / ar.rot;
378 <                                                /* recompute error */
379 <                copycolor(dnew.v, div[0].v);
380 <                addcolor(dnew.v, ar.rcol);
381 <                dnew.n = div[0].n + 1;
382 <                dnew.t = div[0].t; dnew.p = div[0].p;
383 <                b2 = bright(dnew.v)/dnew.n - bright(ar.rcol);
384 <                b2 = b2*b2 + div[0].k*(div[0].n*div[0].n);
385 <                dnew.k = b2/(dnew.n*dnew.n);
386 <                                                /* reinsert */
387 <                for (k = 0; k < ne-1 && dnew.k < div[k+1].k; k++)
388 <                        bcopy(&div[k+1], &div[k], sizeof(AMBSAMP));
389 <                bcopy(&dnew, &div[k], sizeof(AMBSAMP));
390 <
391 <                if (ne >= i) {          /* extract darkest division */
392 <                        ne--;
393 <                        if (div[ne].n > 1)
394 <                                scalecolor(div[ne].v, 1.0/div[ne].n);
395 <                        addcolor(acol, div[ne].v);
396 <                }
397 <        }
398 <        scalecolor(acol, 1.0/ndivs);
399 <        if (arad <= FTINY)
400 <                arad = FHUGE;
401 <        else
402 <                arad = (ndivs+ns) / arad / sqrt(r->rweight);
403 <        if (arad > maxarad)
404 <                arad = maxarad;
405 <        else if (arad < minarad)
406 <                arad = minarad;
407 <        if (ns > 0)
408 <                free((char *)div);
409 <        return(arad);
329 >        copycolor(cr, ap->val);
330 >        scalecolor(cr, d);
331   }
332  
333  
334 < static int
335 < ambcmp(d1, d2)                          /* decreasing order */
336 < AMBSAMP  *d1, *d2;
334 > static
335 > initambfile(creat)              /* initialize ambient file */
336 > int  creat;
337   {
338 <        if (d1->k < d2->k)
339 <                return(1);
340 <        if (d1->k > d2->k)
341 <                return(-1);
342 <        return(0);
338 >        extern char  *progname, *octname, VersionID[];
339 >
340 > #ifdef  F_SETLKW
341 >        aflock(creat ? F_WRLCK : F_RDLCK);
342 > #endif
343 > #ifdef MSDOS
344 >        setmode(fileno(ambfp), O_BINARY);
345 > #endif
346 >        setbuf(ambfp, bmalloc(BUFSIZ));
347 >        if (creat) {                    /* new file */
348 >                fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
349 >                                progname, colval(ambval,RED),
350 >                                colval(ambval,GRN), colval(ambval,BLU),
351 >                                ambounce, ambacc);
352 >                fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
353 >                                ambdiv, ambssamp, ambres,
354 >                                octname==NULL ? "" : octname);
355 >                fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
356 >                fputformat(AMBFMT, ambfp);
357 >                putc('\n', ambfp);
358 >                putambmagic(ambfp);
359 >        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
360 >                error(USER, "bad ambient file");
361   }
362  
363  
364   static
365 < avsave(av)                              /* save an ambient value */
366 < AMBVAL  *av;
365 > avsave(av)                              /* insert and save an ambient value */
366 > AMBVAL  *av;
367   {
368 < #ifdef  AMBFLUSH
430 <        static int  nunflshed = 0;
431 < #endif
368 >        avinsert(avstore(av), &atrunk, thescene.cuorg, thescene.cusize);
369          if (ambfp == NULL)
370                  return;
371 <        if (fwrite(av, sizeof(AMBVAL), 1, ambfp) != 1)
371 >        if (writambval(av, ambfp) < 0)
372                  goto writerr;
373 < #ifdef  AMBFLUSH
374 <        if (++nunflshed >= AMBFLUSH) {
438 <                if (fflush(ambfp) == EOF)
373 >        if (++nunflshed >= AMBFLUSH)
374 >                if (ambsync() == EOF)
375                          goto writerr;
440                nunflshed = 0;
441        }
442 #endif
376          return;
377   writerr:
378          error(SYSTEM, "error writing ambient file");
379   }
380  
381  
382 + static AMBVAL *
383 + avstore(aval)                           /* allocate memory and store aval */
384 + register AMBVAL  *aval;
385 + {
386 +        register AMBVAL  *av;
387 +
388 +        if ((av = newambval()) == NULL)
389 +                error(SYSTEM, "out of memory in avstore");
390 +        copystruct(av, aval);
391 +        return(av);
392 + }
393 +
394 +
395   static
396 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
397 < AMBVAL  *aval;
396 > avinsert(av, at, c0, s)                 /* insert ambient value in a tree */
397 > register AMBVAL  *av;
398   register AMBTREE  *at;
399   FVECT  c0;
400 < double  s;
400 > double  s;
401   {
402          FVECT  ck0;
403          int  branch;
458        register AMBVAL  *av;
404          register int  i;
405  
406 <        if ((av = newambval()) == NULL)
407 <                goto memerr;
463 <        bcopy(aval, av, sizeof(AMBVAL));
406 >        if (av->rad <= FTINY)
407 >                error(CONSISTENCY, "zero ambient radius in avinsert");
408          VCOPY(ck0, c0);
409          while (s*(OCTSCALE/2) > av->rad*ambacc) {
410                  if (at->kid == NULL)
411                          if ((at->kid = newambtree()) == NULL)
412 <                                goto memerr;
412 >                                error(SYSTEM, "out of memory in avinsert");
413                  s *= 0.5;
414                  branch = 0;
415                  for (i = 0; i < 3; i++)
# Line 477 | Line 421 | double  s;
421          }
422          av->next = at->alist;
423          at->alist = av;
480        return;
481 memerr:
482        error(SYSTEM, "out of memory in avinsert");
424   }
425 +
426 +
427 + static
428 + loadtree(at)                            /* move tree to main store */
429 + register AMBTREE  *at;
430 + {
431 +        register AMBVAL  *av;
432 +        register int  i;
433 +                                        /* transfer values at this node */
434 +        for (av = at->alist; av != NULL; av = at->alist) {
435 +                at->alist = av->next;
436 +                avinsert(av, &atrunk, thescene.cuorg, thescene.cusize);
437 +        }
438 +        for (i = 0; i < 8; i++)         /* transfer and free children */
439 +                loadtree(at->kid+i);
440 +        freeambtree(at->kid);
441 + }
442 +
443 +
444 + #ifdef  F_SETLKW
445 +
446 + static
447 + aflock(typ)                     /* lock/unlock ambient file */
448 + int  typ;
449 + {
450 +        static struct flock  fls;       /* static so initialized to zeroes */
451 +
452 +        fls.l_type = typ;
453 +        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
454 +                error(SYSTEM, "cannot (un)lock ambient file");
455 + }
456 +
457 +
458 + int
459 + ambsync()                       /* synchronize ambient file */
460 + {
461 +        static FILE  *ambinp = NULL;
462 +        static long  lastpos = -1;
463 +        long  flen;
464 +        AMBVAL  avs;
465 +        register int  n;
466 +
467 +        if (nunflshed == 0)
468 +                return(0);
469 +        if (lastpos < 0)        /* initializing (locked in initambfile) */
470 +                goto syncend;
471 +                                /* gain exclusive access */
472 +        aflock(F_WRLCK);
473 +                                /* see if file has grown */
474 +        if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
475 +                error(SYSTEM, "cannot seek on ambient file");
476 +        if (n = flen - lastpos) {               /* file has grown */
477 +                if (ambinp == NULL) {           /* use duplicate filedes */
478 +                        ambinp = fdopen(dup(fileno(ambfp)), "r");
479 +                        if (ambinp == NULL)
480 +                                error(SYSTEM, "fdopen failed in ambsync");
481 +                }
482 +                if (fseek(ambinp, lastpos, 0) < 0)
483 +                        error(SYSTEM, "fseek failed in ambsync");
484 +                while (n >= AMBVALSIZ) {        /* load contributed values */
485 +                        readambval(&avs, ambinp);
486 +                        avinsert(avstore(&avs), &atrunk,
487 +                                        thescene.cuorg, thescene.cusize);
488 +                        n -= AMBVALSIZ;
489 +                }
490 +                if (n)                          /* alignment */
491 +                        lseek(fileno(ambfp), flen-n, 0);
492 +        }
493 + syncend:
494 +        n = fflush(ambfp);                      /* calls write() at last */
495 +        lastpos = lseek(fileno(ambfp), 0L, 1);
496 +        aflock(F_UNLCK);                        /* release file */
497 +        nunflshed = 0;
498 +        return(n);
499 + }
500 +
501 + #else
502 +
503 + int
504 + ambsync()                       /* flush ambient file */
505 + {
506 +        if (nunflshed == 0)
507 +                return(0);
508 +        nunflshed = 0;
509 +        return(fflush(ambfp));
510 + }
511 +
512 + #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines