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.1 by greg, Thu Feb 2 10:41:17 1989 UTC vs.
Revision 2.24 by greg, Thu Mar 24 13:41:04 1994 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(), loadatree();
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 < 0 ? 0 : 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 + setambacc(newa)                         /* set ambient accuracy */
76 + double  newa;
77 + {
78 +        static double  oldambacc = -1.0;
79 +        AMBTREE  oldatrunk;
80  
81 +        ambacc = newa < 0.0 ? 0.0 : newa;       /* may be done already */
82 +        if (oldambacc < -FTINY)
83 +                oldambacc = ambacc;     /* do nothing first call */
84 +        if (fabs(newa - oldambacc) < 0.01)
85 +                return;                 /* insignificant -- don't bother */
86 +        if (ambacc <= FTINY)
87 +                return;                 /* cannot build new tree */
88 +                                        /* else need to rebuild tree */
89 +        copystruct(&oldatrunk, &atrunk);
90 +        atrunk.alist = NULL;
91 +        atrunk.kid = NULL;
92 +        loadatree(&oldatrunk);
93 +        oldambacc = ambacc;             /* remeber setting for next call */
94 + }
95 +
96 +
97   setambient(afile)                       /* initialize calculation */
98   char  *afile;
99   {
100 <        long  ftell();
101 <        char  **amblp;
102 <        OBJECT  obj;
103 <        AMBVAL  amb;
104 <                                        /* set up ambient set */
105 <        ambset[0] = 0;
106 <        for (amblp = amblist; *amblp != NULL; amblp++) {
107 <                if ((obj = modifier(*amblp)) == OVOID) {
108 <                        sprintf(errmsg, "unknown %s modifier \"%s\"",
109 <                                ambincl ? "include" : "exclude", *amblp);
110 <                        error(WARNING, errmsg);
111 <                        continue;
88 <                }
89 <                if (!inset(ambset, obj))
90 <                        insertelem(ambset, obj);
100 >        long  headlen;
101 >        AMBVAL  amb;
102 >                                                /* init ambient limits */
103 >        setambres(ambres);
104 >        setambacc(ambacc);
105 >        if (afile == NULL)
106 >                return;
107 >        if (ambacc <= FTINY) {
108 >                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
109 >                                afile);
110 >                error(WARNING, errmsg);
111 >                return;
112          }
113 <        maxarad = thescene.cusize / 2.0;                /* maximum radius */
114 <                                                        /* minimum radius */
115 <        minarad = ambres > 0 ? thescene.cusize/ambres : 0.0;
113 >                                                /* open ambient file */
114 >        if ((ambfp = fopen(afile, "r+")) != NULL) {
115 >                initambfile(0);
116 >                headlen = ftell(ambfp);
117 >                while (readambval(&amb, ambfp))
118 >                        avinsert(avstore(&amb));
119 >                                                /* align */
120 >                fseek(ambfp, -((ftell(ambfp)-headlen)%AMBVALSIZ), 1);
121 >        } else if ((ambfp = fopen(afile, "w+")) != NULL)
122 >                initambfile(1);
123 >        else {
124 >                sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
125 >                error(SYSTEM, errmsg);
126 >        }
127 >        nunflshed++;    /* lie */
128 >        ambsync();
129 > }
130  
131 <                                        /* open ambient file */
132 <        if (afile != NULL)
133 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
134 <                        while (fread(&amb, sizeof(AMBVAL), 1, ambfp) == 1)
135 <                                avinsert(&amb, &atrunk, thescene.cuorg,
136 <                                                thescene.cusize);
137 <                                                        /* align */
138 <                        fseek(ambfp, -(ftell(ambfp)%sizeof(AMBVAL)), 1);
139 <                } else if ((ambfp = fopen(afile, "w")) == NULL) {
140 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
141 <                                        afile);
142 <                        error(SYSTEM, errmsg);
131 >
132 > ambnotify(obj)                  /* record new modifier */
133 > OBJECT  obj;
134 > {
135 >        static int  hitlimit = 0;
136 >        register OBJREC  *o = objptr(obj);
137 >        register char  **amblp;
138 >
139 >        if (hitlimit || !ismodifier(o->otype))
140 >                return;
141 >        for (amblp = amblist; *amblp != NULL; amblp++)
142 >                if (!strcmp(o->oname, *amblp)) {
143 >                        if (ambset[0] >= MAXASET) {
144 >                                error(WARNING, "too many modifiers in ambient list");
145 >                                hitlimit++;
146 >                                return;         /* should this be fatal? */
147 >                        }
148 >                        insertelem(ambset, obj);
149 >                        return;
150                  }
151   }
152  
# Line 114 | Line 156 | COLOR  acol;
156   register RAY  *r;
157   {
158          static int  rdepth = 0;                 /* ambient recursion */
159 <        double  wsum;
159 >        double  d;
160  
119        rdepth++;                               /* increment level */
120
161          if (ambdiv <= 0)                        /* no ambient calculation */
162                  goto dumbamb;
163                                                  /* check number of bounces */
164 <        if (rdepth > ambounce)
164 >        if (rdepth >= ambounce)
165                  goto dumbamb;
166                                                  /* check ambient list */
167          if (ambincl != -1 && r->ro != NULL &&
# Line 129 | Line 169 | register RAY  *r;
169                  goto dumbamb;
170  
171          if (ambacc <= FTINY) {                  /* no ambient storage */
172 <                if (doambient(acol, r) == 0.0)
172 >                rdepth++;
173 >                d = doambient(acol, r, r->rweight, NULL, NULL);
174 >                rdepth--;
175 >                if (d == 0.0)
176                          goto dumbamb;
177 <                goto done;
177 >                return;
178          }
179                                                  /* get ambient value */
180          setcolor(acol, 0.0, 0.0, 0.0);
181 <        wsum = sumambient(acol, r, &atrunk, thescene.cuorg, thescene.cusize);
182 <        if (wsum > FTINY)
183 <                scalecolor(acol, 1.0/wsum);
184 <        else if (makeambient(acol, r) == 0.0)
185 <                goto dumbamb;
186 <        goto done;
187 <
181 >        d = sumambient(acol, r, rdepth,
182 >                        &atrunk, thescene.cuorg, thescene.cusize);
183 >        if (d > FTINY)
184 >                scalecolor(acol, 1.0/d);
185 >        else {
186 >                d = makeambient(acol, r, rdepth++);
187 >                rdepth--;
188 >        }
189 >        if (d > FTINY)
190 >                return;
191   dumbamb:                                        /* return global value */
192          copycolor(acol, ambval);
147 done:                                           /* must finish here! */
148        rdepth--;
193   }
194  
195  
196   double
197 < sumambient(acol, r, at, c0, s)          /* get interpolated ambient value */
197 > sumambient(acol, r, al, at, c0, s)      /* get interpolated ambient value */
198   COLOR  acol;
199   register RAY  *r;
200 < AMBTREE  *at;
200 > int  al;
201 > AMBTREE  *at;
202   FVECT  c0;
203 < double  s;
203 > double  s;
204   {
205 <        extern double  sqrt();
161 <        double  d, e1, e2, wt, wsum;
205 >        double  d, e1, e2, wt, wsum;
206          COLOR  ct;
207          FVECT  ck0;
208          int  i;
209          register int  j;
210 <        register AMBVAL  *av;
210 >        register AMBVAL  *av;
211                                          /* do this node */
212          wsum = 0.0;
213          for (av = at->alist; av != NULL; av = av->next) {
214                  /*
215 <                 *  Ray strength test.
215 >                 *  Ambient level test.
216                   */
217 <                if (av->lvl > r->rlvl || av->weight < r->rweight-FTINY)
217 >                if (av->lvl > al)       /* list sorted, so this works */
218 >                        break;
219 >                if (av->weight < r->rweight-FTINY)
220                          continue;
221                  /*
222                   *  Ambient radius test.
# Line 197 | Line 243 | double  s;
243                  for (j = 0; j < 3; j++)
244                          d += (r->rop[j] - av->pos[j]) *
245                                          (av->dir[j] + r->ron[j]);
246 <                if (d < -minarad)
246 >                if (d*0.5 < -minarad*ambacc-.001)
247                          continue;
248                  /*
249                   *  Jittering final test reduces image artifacts.
250                   */
251                  wt = sqrt(e1) + sqrt(e2);
252 <                if (wt > ambacc*(0.9 + 0.2*frandom()))
252 >                wt *= .9 + .2*urand(9015+samplendx);
253 >                if (wt > ambacc)
254                          continue;
255                  if (wt <= 1e-3)
256                          wt = 1e3;
257                  else
258                          wt = 1.0 / wt;
259                  wsum += wt;
260 <                copycolor(ct, av->val);
260 >                extambient(ct, av, r->rop, r->ron);
261                  scalecolor(ct, wt);
262                  addcolor(acol, ct);
263          }
# Line 221 | Line 268 | double  s;
268          for (i = 0; i < 8; i++) {
269                  for (j = 0; j < 3; j++) {
270                          ck0[j] = c0[j];
271 <                        if (1<<j & i) {
271 >                        if (1<<j & i)
272                                  ck0[j] += s;
273 <                                if (r->rop[j] < ck0[j] - OCTSCALE*s)
274 <                                        break;
275 <                        } else
276 <                                if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
230 <                                        break;
273 >                        if (r->rop[j] < ck0[j] - OCTSCALE*s)
274 >                                break;
275 >                        if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
276 >                                break;
277                  }
278                  if (j == 3)
279 <                        wsum += sumambient(acol, r, at->kid+i, ck0, s);
279 >                        wsum += sumambient(acol, r, al, at->kid+i, ck0, s);
280          }
281          return(wsum);
282   }
283  
284  
285   double
286 < makeambient(acol, r)            /* make a new ambient value */
286 > makeambient(acol, r, al)        /* make a new ambient value */
287   COLOR  acol;
288   register RAY  *r;
289 + int  al;
290   {
291 <        AMBVAL  amb;
292 <
293 <        amb.rad = doambient(acol, r);           /* compute ambient */
291 >        AMBVAL  amb;
292 >        FVECT   gp, gd;
293 >                                                /* compute weight */
294 >        amb.weight = pow(AVGREFL, (double)al);
295 >        if (r->rweight < 0.2*amb.weight)        /* heuristic */
296 >                amb.weight = r->rweight;
297 >                                                /* compute ambient */
298 >        amb.rad = doambient(acol, r, amb.weight, gp, gd);
299          if (amb.rad == 0.0)
300                  return(0.0);
301                                                  /* store it */
302          VCOPY(amb.pos, r->rop);
303          VCOPY(amb.dir, r->ron);
304 <        amb.lvl = r->rlvl;
253 <        amb.weight = r->rweight;
304 >        amb.lvl = al;
305          copycolor(amb.val, acol);
306 +        VCOPY(amb.gpos, gp);
307 +        VCOPY(amb.gdir, gd);
308                                                  /* insert into tree */
309 <        avinsert(&amb, &atrunk, thescene.cuorg, thescene.cusize);
257 <        avsave(&amb);                           /* write to file */
309 >        avsave(&amb);                           /* and save to file */
310          return(amb.rad);
311   }
312  
313  
314 < double
315 < doambient(acol, r)                      /* compute ambient component */
316 < COLOR  acol;
317 < register RAY  *r;
314 > extambient(cr, ap, pv, nv)              /* extrapolate value at pv, nv */
315 > COLOR  cr;
316 > register AMBVAL  *ap;
317 > FVECT  pv, nv;
318   {
319 <        extern int  ambcmp();
320 <        extern double  sin(), cos(), sqrt();
321 <        double  phi, xd, yd, zd;
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;
319 >        FVECT  v1, v2;
320 >        register int  i;
321 >        double  d;
322  
323 <        setcolor(acol, 0.0, 0.0, 0.0);
324 <                                        /* set number of divisions */
325 <        nt = sqrt(ambdiv * r->rweight * 0.5) + 0.5;
326 <        np = 2 * nt;
327 <        ndivs = nt * np;
328 <                                        /* check first */
329 <        if (ndivs == 0 || rayorigin(&ar, r, AMBIENT, 0.5) < 0)
330 <                return(0.0);
331 <                                        /* set number of super-samples */
332 <        ns = ambssamp * r->rweight + 0.5;
333 <        if (ns > 0) {
289 <                div = (AMBSAMP *)malloc(ndivs*sizeof(AMBSAMP));
290 <                if (div == NULL)
291 <                        error(SYSTEM, "out of memory in doambient");
323 >        d = 1.0;                        /* zeroeth order */
324 >                                        /* gradient due to translation */
325 >        for (i = 0; i < 3; i++)
326 >                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
327 >                                        /* gradient due to rotation */
328 >        VCOPY(v1, ap->dir);
329 >        fcross(v2, v1, nv);
330 >        d += DOT(ap->gdir, v2);
331 >        if (d <= 0.0) {
332 >                setcolor(cr, 0.0, 0.0, 0.0);
333 >                return;
334          }
335 <                                        /* make axes */
336 <        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 <                                xd = bright(ar.rcol);
325 <                                if (i > 0) {            /* from above */
326 <                                        yd = bright(div[ne-np].v) - xd;
327 <                                        yd *= yd * 0.25;
328 <                                        div[ne].k += yd;
329 <                                        div[ne].n++;
330 <                                        div[ne-np].k += yd;
331 <                                        div[ne-np].n++;
332 <                                }
333 <                                if (j > 0) {            /* from behind */
334 <                                        yd = bright(div[ne-1].v) - xd;
335 <                                        yd *= yd * 0.25;
336 <                                        div[ne].k += yd;
337 <                                        div[ne].n++;
338 <                                        div[ne-1].k += yd;
339 <                                        div[ne-1].n++;
340 <                                }
341 <                                if (j == np-1) {        /* around */
342 <                                        yd = bright(div[ne-(np-1)].v) - xd;
343 <                                        yd *= yd * 0.25;
344 <                                        div[ne].k += yd;
345 <                                        div[ne].n++;
346 <                                        div[ne-(np-1)].k += yd;
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 <                yd = bright(dnew.v)/dnew.n - bright(ar.rcol);
384 <                yd = yd*yd + div[0].k*(div[0].n*div[0].n);
385 <                dnew.k = yd/(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);
335 >        copycolor(cr, ap->val);
336 >        scalecolor(cr, d);
337   }
338  
339  
340 < static int
341 < ambcmp(d1, d2)                          /* decreasing order */
342 < AMBSAMP  *d1, *d2;
340 > static
341 > initambfile(creat)              /* initialize ambient file */
342 > int  creat;
343   {
344 <        if (d1->k < d2->k)
345 <                return(1);
346 <        if (d1->k > d2->k)
347 <                return(-1);
348 <        return(0);
344 >        extern char  *progname, *octname, VersionID[];
345 >
346 > #ifdef  F_SETLKW
347 >        aflock(creat ? F_WRLCK : F_RDLCK);
348 > #endif
349 > #ifdef MSDOS
350 >        setmode(fileno(ambfp), O_BINARY);
351 > #endif
352 >        setbuf(ambfp, bmalloc(BUFSIZ+8));
353 >        if (creat) {                    /* new file */
354 >                newheader("RADIANCE", ambfp);
355 >                fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
356 >                                progname, colval(ambval,RED),
357 >                                colval(ambval,GRN), colval(ambval,BLU),
358 >                                ambounce, ambacc);
359 >                fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
360 >                                ambdiv, ambssamp, ambres,
361 >                                octname==NULL ? "" : octname);
362 >                fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
363 >                fputformat(AMBFMT, ambfp);
364 >                putc('\n', ambfp);
365 >                putambmagic(ambfp);
366 >        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
367 >                error(USER, "bad ambient file");
368   }
369  
370  
371   static
372 < avsave(av)                              /* save an ambient value */
373 < AMBVAL  *av;
372 > avsave(av)                              /* insert and save an ambient value */
373 > AMBVAL  *av;
374   {
375 < #ifdef  AMBFLUSH
430 <        static int  nunflshed = 0;
431 < #endif
375 >        avinsert(avstore(av));
376          if (ambfp == NULL)
377                  return;
378 <        if (fwrite(av, sizeof(AMBVAL), 1, ambfp) != 1)
378 >        if (writambval(av, ambfp) < 0)
379                  goto writerr;
380 < #ifdef  AMBFLUSH
381 <        if (++nunflshed >= AMBFLUSH) {
438 <                if (fflush(ambfp) == EOF)
380 >        if (++nunflshed >= AMBFLUSH)
381 >                if (ambsync() == EOF)
382                          goto writerr;
440                nunflshed = 0;
441        }
442 #endif
383          return;
384   writerr:
385          error(SYSTEM, "error writing ambient file");
386   }
387  
388  
389 + static AMBVAL *
390 + avstore(aval)                           /* allocate memory and store aval */
391 + register AMBVAL  *aval;
392 + {
393 +        register AMBVAL  *av;
394 +
395 +        if ((av = newambval()) == NULL)
396 +                error(SYSTEM, "out of memory in avstore");
397 +        copystruct(av, aval);
398 +        return(av);
399 + }
400 +
401 +
402   static
403 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
404 < AMBVAL  *aval;
452 < register AMBTREE  *at;
453 < FVECT  c0;
454 < double  s;
403 > avinsert(av)                            /* insert ambient value in our tree */
404 > register AMBVAL  *av;
405   {
406 +        register AMBTREE  *at;
407 +        register AMBVAL  *ap;
408 +        AMBVAL  avh;
409          FVECT  ck0;
410 +        double  s;
411          int  branch;
458        register AMBVAL  *av;
412          register int  i;
413  
414 <        if ((av = newambval()) == NULL)
415 <                goto memerr;
416 <        bcopy(aval, av, sizeof(AMBVAL));
417 <        VCOPY(ck0, c0);
414 >        if (av->rad <= FTINY)
415 >                error(CONSISTENCY, "zero ambient radius in avinsert");
416 >        at = &atrunk;
417 >        VCOPY(ck0, thescene.cuorg);
418 >        s = thescene.cusize;
419          while (s*(OCTSCALE/2) > av->rad*ambacc) {
420                  if (at->kid == NULL)
421                          if ((at->kid = newambtree()) == NULL)
422 <                                goto memerr;
422 >                                error(SYSTEM, "out of memory in avinsert");
423                  s *= 0.5;
424                  branch = 0;
425                  for (i = 0; i < 3; i++)
# Line 475 | Line 429 | double  s;
429                          }
430                  at = at->kid + branch;
431          }
432 <        av->next = at->alist;
433 <        at->alist = av;
434 <        return;
435 < memerr:
436 <        error(SYSTEM, "out of memory in avinsert");
432 >        avh.next = at->alist;           /* order by increasing level */
433 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
434 >                if (ap->next->lvl >= av->lvl)
435 >                        break;
436 >        av->next = ap->next;
437 >        ap->next = av;
438 >        at->alist = avh.next;
439   }
440 +
441 +
442 + static
443 + loadatree(at)                           /* move tree to main store */
444 + register AMBTREE  *at;
445 + {
446 +        register AMBVAL  *av;
447 +        register int  i;
448 +                                        /* transfer values at this node */
449 +        for (av = at->alist; av != NULL; av = at->alist) {
450 +                at->alist = av->next;
451 +                avinsert(av);
452 +        }
453 +        if (at->kid == NULL)
454 +                return;
455 +        for (i = 0; i < 8; i++)         /* transfer and free children */
456 +                loadatree(at->kid+i);
457 +        freeambtree(at->kid);
458 + }
459 +
460 +
461 + #ifdef  F_SETLKW
462 +
463 + static
464 + aflock(typ)                     /* lock/unlock ambient file */
465 + int  typ;
466 + {
467 +        static struct flock  fls;       /* static so initialized to zeroes */
468 +
469 +        fls.l_type = typ;
470 +        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
471 +                error(SYSTEM, "cannot (un)lock ambient file");
472 + }
473 +
474 +
475 + int
476 + ambsync()                       /* synchronize ambient file */
477 + {
478 +        static FILE  *ambinp = NULL;
479 +        static long  lastpos = -1;
480 +        long  flen;
481 +        AMBVAL  avs;
482 +        register int  n;
483 +
484 +        if (nunflshed == 0)
485 +                return(0);
486 +        if (lastpos < 0)        /* initializing (locked in initambfile) */
487 +                goto syncend;
488 +                                /* gain exclusive access */
489 +        aflock(F_WRLCK);
490 +                                /* see if file has grown */
491 +        if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
492 +                goto seekerr;
493 +        if (n = flen - lastpos) {               /* file has grown */
494 +                if (ambinp == NULL) {           /* use duplicate filedes */
495 +                        ambinp = fdopen(dup(fileno(ambfp)), "r");
496 +                        if (ambinp == NULL)
497 +                                error(SYSTEM, "fdopen failed in ambsync");
498 +                }
499 +                if (fseek(ambinp, lastpos, 0) < 0)
500 +                        goto seekerr;
501 +                while (n >= AMBVALSIZ) {        /* load contributed values */
502 +                        readambval(&avs, ambinp);
503 +                        avinsert(avstore(&avs));
504 +                        n -= AMBVALSIZ;
505 +                }
506 +                /*** seek always as safety measure
507 +                if (n) ***/                     /* alignment */
508 +                        if (lseek(fileno(ambfp), flen-n, 0) < 0)
509 +                                goto seekerr;
510 +        }
511 + #ifdef  DEBUG
512 +        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
513 +                sprintf(errmsg, "ambient file buffer at %d rather than %d",
514 +                                ambfp->_ptr - ambfp->_base,
515 +                                nunflshed*AMBVALSIZ);
516 +                error(CONSISTENCY, errmsg);
517 +        }
518 + #endif
519 + syncend:
520 +        n = fflush(ambfp);                      /* calls write() at last */
521 +        if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
522 +                goto seekerr;
523 +        aflock(F_UNLCK);                        /* release file */
524 +        nunflshed = 0;
525 +        return(n);
526 + seekerr:
527 +        error(SYSTEM, "seek failed in ambsync");
528 + }
529 +
530 + #else
531 +
532 + int
533 + ambsync()                       /* flush ambient file */
534 + {
535 +        if (nunflshed == 0)
536 +                return(0);
537 +        nunflshed = 0;
538 +        return(fflush(ambfp));
539 + }
540 +
541 + #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines