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.11 by greg, Fri Sep 7 08:17:42 1990 UTC vs.
Revision 2.33 by greg, Tue Oct 24 13:33:23 1995 UTC

# Line 1 | Line 1
1 < /* Copyright (c) 1986 Regents of the University of California */
1 > /* Copyright (c) 1995 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"
# Line 19 | Line 14 | static char SCCSid[] = "$SunId$ LBL";
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 > #ifndef  OCTSCALE
22 > #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
23 > #endif
24 > #ifndef  AMBVWT
25 > #define  AMBVWT         250     /* relative ambient value weight (# calcs) */
26 > #endif
27  
28 + typedef struct ambtree {
29 +        AMBVAL  *alist;         /* ambient value list */
30 +        struct ambtree  *kid;   /* 8 child nodes */
31 + }  AMBTREE;                     /* ambient octree */
32 +
33   extern CUBE  thescene;          /* contains space boundaries */
34  
35 < extern COLOR  ambval;           /* global ambient component */
29 < extern double  ambacc;          /* ambient accuracy */
30 < extern int  ambres;             /* ambient resolution */
31 < 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 */
35 > extern char  *shm_boundary;     /* memory sharing boundary */
36  
37 < #define  MAXASET        511     /* maximum number of elements in ambient set */
38 < OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
37 > #define  MAXASET        511     /* maximum number of elements in ambient set */
38 > OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
39  
40 < double  maxarad;                /* maximum ambient radius */
41 < double  minarad;                /* minimum ambient radius */
40 > double  maxarad;                /* maximum ambient radius */
41 > double  minarad;                /* minimum ambient radius */
42  
43 < typedef struct ambval {
44 <        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 */
43 > static AMBTREE  atrunk;         /* our ambient trunk node */
44  
45 < typedef struct ambtree {
46 <        AMBVAL  *alist;         /* ambient value list */
55 <        struct ambtree  *kid;   /* 8 child nodes */
56 < }  AMBTREE;                     /* ambient octree */
45 > static FILE  *ambfp = NULL;     /* ambient file pointer */
46 > static int  nunflshed = 0;      /* number of unflushed ambient values */
47  
48 < typedef struct {
49 <        float  k;               /* error contribution per sample */
50 <        COLOR  v;               /* ray sum */
51 <        int  n;                 /* number of samples */
52 <        short  t, p;            /* theta, phi indices */
53 < }  AMBSAMP;                     /* ambient sample */
48 > #ifndef SORT_THRESH
49 > #ifdef BIGMEM
50 > #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
51 > #else
52 > #define SORT_THRESH     ((3L<<20)/sizeof(AMBVAL))
53 > #endif
54 > #endif
55 > #ifndef SORT_INTVL
56 > #define SORT_INTVL      (SORT_THRESH*256)
57 > #endif
58 > #ifndef MAX_SORT_INTVL
59 > #define MAX_SORT_INTVL  (SORT_INTVL<<4)
60 > #endif
61  
62 < static AMBTREE  atrunk;         /* our ambient trunk node */
62 > static COLOR  avsum = BLKCOLOR;         /* computed ambient value sum */
63 > static unsigned int  nambvals = 0;      /* number of computed ambient values */
64 > static unsigned long  ambclock = 0;     /* ambient access clock */
65 > static unsigned long  lastsort = 0;     /* time of last value sort */
66 > static long  sortintvl = SORT_INTVL;    /* time until next sort */
67  
68 < static FILE  *ambfp = NULL;     /* ambient file pointer */
68 > #define MAXACLOCK       (1L<<30)        /* clock turnover value */
69 >        /*
70 >         * Track access times unless we are sharing ambient values
71 >         * through memory on a multiprocessor, when we want to avoid
72 >         * claiming our own memory (copy on write).
73 >         */
74 > #define tracktime       (shm_boundary == NULL || ambfp == NULL)
75  
76 < #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
76 > #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
77  
78 < #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
78 > #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
79  
80 < double  sumambient(), doambient(), makeambient();
80 > extern long  ftell(), lseek();
81 > static int  initambfile(), avsave(), avinsert(), sortambvals();
82 > static AMBVAL  *avstore();
83 > #ifdef  F_SETLKW
84 > static  aflock();
85 > #endif
86  
87  
88 < setambient(afile)                       /* initialize calculation */
89 < char  *afile;
88 > setambres(ar)                           /* set ambient resolution */
89 > int  ar;
90   {
91 <        long  ftell();
92 <        AMBVAL  amb;
91 >        ambres = ar < 0 ? 0 : ar;               /* may be done already */
92 >                                                /* set min & max radii */
93 >        if (ar <= 0) {
94 >                minarad = 0;
95 >                maxarad = thescene.cusize / 2.0;
96 >        } else {
97 >                minarad = thescene.cusize / ar;
98 >                maxarad = 64 * minarad;                 /* heuristic */
99 >                if (maxarad > thescene.cusize / 2.0)
100 >                        maxarad = thescene.cusize / 2.0;
101 >        }
102 >        if (minarad <= FTINY)
103 >                minarad = 10*FTINY;
104 >        if (maxarad <= minarad)
105 >                maxarad = 64 * minarad;
106 > }
107  
82        maxarad = thescene.cusize / 2.0;                /* maximum radius */
83                                                        /* minimum radius */
84        minarad = ambres > 0 ? thescene.cusize/ambres : 0.0;
108  
109 <                                        /* open ambient file */
110 <        if (afile != NULL)
111 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
112 <                        while (fread((char *)&amb,sizeof(AMBVAL),1,ambfp) == 1)
113 <                                avinsert(&amb, &atrunk, thescene.cuorg,
114 <                                                thescene.cusize);
115 <                                                        /* align */
116 <                        fseek(ambfp, -(ftell(ambfp)%sizeof(AMBVAL)), 1);
117 <                } else if ((ambfp = fopen(afile, "w")) == NULL) {
118 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
96 <                                        afile);
97 <                        error(SYSTEM, errmsg);
98 <                }
109 > setambacc(newa)                         /* set ambient accuracy */
110 > double  newa;
111 > {
112 >        double  ambdiff;
113 >
114 >        if (newa < 0.0)
115 >                newa = 0.0;
116 >        ambdiff = fabs(newa - ambacc);
117 >        if (ambdiff >= .01 && (ambacc = newa) > FTINY && nambvals > 0)
118 >                sortambvals(1);                 /* rebuild tree */
119   }
120  
121  
122 + setambient(afile)                       /* initialize calculation */
123 + char  *afile;
124 + {
125 +        long  headlen;
126 +        AMBVAL  amb;
127 +                                                /* init ambient limits */
128 +        setambres(ambres);
129 +        setambacc(ambacc);
130 +        if (afile == NULL)
131 +                return;
132 +        if (ambacc <= FTINY) {
133 +                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
134 +                                afile);
135 +                error(WARNING, errmsg);
136 +                return;
137 +        }
138 +                                                /* open ambient file */
139 +        if ((ambfp = fopen(afile, "r+")) != NULL) {
140 +                initambfile(0);
141 +                headlen = ftell(ambfp);
142 +                while (readambval(&amb, ambfp))
143 +                        avinsert(avstore(&amb));
144 +                                                /* align */
145 +                fseek(ambfp, -((ftell(ambfp)-headlen)%AMBVALSIZ), 1);
146 +        } else if ((ambfp = fopen(afile, "w+")) != NULL)
147 +                initambfile(1);
148 +        else {
149 +                sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
150 +                error(SYSTEM, errmsg);
151 +        }
152 +        nunflshed++;    /* lie */
153 +        ambsync();
154 + }
155 +
156 +
157   ambnotify(obj)                  /* record new modifier */
158 < OBJECT  obj;
158 > OBJECT  obj;
159   {
160          static int  hitlimit = 0;
161 <        register OBJREC  *o = objptr(obj);
161 >        register OBJREC  *o = objptr(obj);
162          register char  **amblp;
163  
164          if (hitlimit || !ismodifier(o->otype))
# Line 126 | Line 181 | COLOR  acol;
181   register RAY  *r;
182   {
183          static int  rdepth = 0;                 /* ambient recursion */
184 <        double  wsum;
184 >        double  d;
185  
131        rdepth++;                               /* increment level */
132
186          if (ambdiv <= 0)                        /* no ambient calculation */
187                  goto dumbamb;
188                                                  /* check number of bounces */
189 <        if (rdepth > ambounce)
189 >        if (rdepth >= ambounce)
190                  goto dumbamb;
191                                                  /* check ambient list */
192          if (ambincl != -1 && r->ro != NULL &&
# Line 141 | Line 194 | register RAY  *r;
194                  goto dumbamb;
195  
196          if (ambacc <= FTINY) {                  /* no ambient storage */
197 <                if (doambient(acol, r) == 0.0)
197 >                rdepth++;
198 >                d = doambient(acol, r, r->rweight, NULL, NULL);
199 >                rdepth--;
200 >                if (d <= FTINY)
201                          goto dumbamb;
202 <                goto done;
202 >                return;
203          }
204 +                                                /* resort memory? */
205 +        sortambvals(0);
206                                                  /* get ambient value */
207          setcolor(acol, 0.0, 0.0, 0.0);
208 <        wsum = sumambient(acol, r, &atrunk, thescene.cuorg, thescene.cusize);
209 <        if (wsum > FTINY)
210 <                scalecolor(acol, 1.0/wsum);
211 <        else if (makeambient(acol, r) == 0.0)
212 <                goto dumbamb;
213 <        goto done;
214 <
208 >        d = sumambient(acol, r, rdepth,
209 >                        &atrunk, thescene.cuorg, thescene.cusize);
210 >        if (d > FTINY) {
211 >                scalecolor(acol, 1.0/d);
212 >                return;
213 >        }
214 >        rdepth++;                               /* need to cache new value */
215 >        d = makeambient(acol, r, rdepth-1);
216 >        rdepth--;
217 >        if (d > FTINY)
218 >                return;
219   dumbamb:                                        /* return global value */
220          copycolor(acol, ambval);
221 < done:                                           /* must finish here! */
222 <        rdepth--;
221 > #if  AMBVWT
222 >        if (nambvals == 0)
223 >                return;
224 >        scalecolor(acol, (double)AMBVWT);
225 >        addcolor(acol, avsum);                  /* average in computations */
226 >        d = 1.0/(AMBVWT+nambvals);
227 >        scalecolor(acol, d);
228 > #endif
229   }
230  
231  
232   double
233 < sumambient(acol, r, at, c0, s)          /* get interpolated ambient value */
233 > sumambient(acol, r, al, at, c0, s)      /* get interpolated ambient value */
234   COLOR  acol;
235   register RAY  *r;
236 < AMBTREE  *at;
236 > int  al;
237 > AMBTREE  *at;
238   FVECT  c0;
239 < double  s;
239 > double  s;
240   {
241 <        extern double  sqrt();
173 <        double  d, e1, e2, wt, wsum;
241 >        double  d, e1, e2, wt, wsum;
242          COLOR  ct;
243          FVECT  ck0;
244          int  i;
245          register int  j;
246 <        register AMBVAL  *av;
247 <                                        /* do this node */
246 >        register AMBVAL  *av;
247 >
248          wsum = 0.0;
249 +                                        /* do this node */
250          for (av = at->alist; av != NULL; av = av->next) {
251 +                if (tracktime)
252 +                        av->latick = ambclock++;
253                  /*
254 <                 *  Ray strength test.
254 >                 *  Ambient level test.
255                   */
256 <                if (av->lvl > r->rlvl || av->weight < r->rweight-FTINY)
256 >                if (av->lvl > al)       /* list sorted, so this works */
257 >                        break;
258 >                if (av->weight < r->rweight-FTINY)
259                          continue;
260                  /*
261                   *  Ambient radius test.
262                   */
263 <                e1 = 0.0;
264 <                for (j = 0; j < 3; j++) {
265 <                        d = av->pos[j] - r->rop[j];
266 <                        e1 += d * d;
267 <                }
263 >                d = av->pos[0] - r->rop[0];
264 >                e1 = d * d;
265 >                d = av->pos[1] - r->rop[1];
266 >                e1 += d * d;
267 >                d = av->pos[2] - r->rop[2];
268 >                e1 += d * d;
269                  e1 /= av->rad * av->rad;
270                  if (e1 > ambacc*ambacc*1.21)
271                          continue;
# Line 209 | Line 283 | double  s;
283                  for (j = 0; j < 3; j++)
284                          d += (r->rop[j] - av->pos[j]) *
285                                          (av->dir[j] + r->ron[j]);
286 <                if (d < -minarad)
286 >                if (d*0.5 < -minarad*ambacc-.001)
287                          continue;
288                  /*
289                   *  Jittering final test reduces image artifacts.
290                   */
291                  wt = sqrt(e1) + sqrt(e2);
292 <                wt *= .9 + .2*frandom();
219 <                if (wt > ambacc)
292 >                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
293                          continue;
294                  if (wt <= 1e-3)
295                          wt = 1e3;
296                  else
297                          wt = 1.0 / wt;
298                  wsum += wt;
299 <                copycolor(ct, av->val);
299 >                extambient(ct, av, r->rop, r->ron);
300                  scalecolor(ct, wt);
301                  addcolor(acol, ct);
302          }
# Line 242 | Line 315 | double  s;
315                                  break;
316                  }
317                  if (j == 3)
318 <                        wsum += sumambient(acol, r, at->kid+i, ck0, s);
318 >                        wsum += sumambient(acol, r, al, at->kid+i, ck0, s);
319          }
320          return(wsum);
321   }
322  
323  
324   double
325 < makeambient(acol, r)            /* make a new ambient value */
325 > makeambient(acol, r, al)        /* make a new ambient value */
326   COLOR  acol;
327   register RAY  *r;
328 + int  al;
329   {
330 <        AMBVAL  amb;
331 <
332 <        amb.rad = doambient(acol, r);           /* compute ambient */
333 <        if (amb.rad == 0.0)
330 >        AMBVAL  amb;
331 >        FVECT   gp, gd;
332 >                                                /* compute weight */
333 >        amb.weight = pow(AVGREFL, (double)al);
334 >        if (r->rweight < 0.1*amb.weight)        /* heuristic */
335 >                amb.weight = r->rweight;
336 >                                                /* compute ambient */
337 >        amb.rad = doambient(acol, r, amb.weight, gp, gd);
338 >        if (amb.rad <= FTINY)
339                  return(0.0);
340                                                  /* store it */
341          VCOPY(amb.pos, r->rop);
342          VCOPY(amb.dir, r->ron);
343 <        amb.lvl = r->rlvl;
265 <        amb.weight = r->rweight;
343 >        amb.lvl = al;
344          copycolor(amb.val, acol);
345 +        VCOPY(amb.gpos, gp);
346 +        VCOPY(amb.gdir, gd);
347                                                  /* insert into tree */
348 <        avinsert(&amb, &atrunk, thescene.cuorg, thescene.cusize);
269 <        avsave(&amb);                           /* write to file */
348 >        avsave(&amb);                           /* and save to file */
349          return(amb.rad);
350   }
351  
352  
353 < double
354 < doambient(acol, r)                      /* compute ambient component */
355 < COLOR  acol;
356 < register RAY  *r;
353 > extambient(cr, ap, pv, nv)              /* extrapolate value at pv, nv */
354 > COLOR  cr;
355 > register AMBVAL  *ap;
356 > FVECT  pv, nv;
357   {
358 <        extern int  ambcmp();
359 <        extern double  sin(), cos(), sqrt();
360 <        double  phi, xd, yd, zd;
282 <        double  b, b2;
283 <        register AMBSAMP  *div;
284 <        AMBSAMP  dnew;
285 <        RAY  ar;
286 <        FVECT  ux, uy;
287 <        double  arad;
288 <        int  ndivs, nt, np, ns, ne, i, j;
289 <        register int  k;
358 >        FVECT  v1, v2;
359 >        register int  i;
360 >        double  d;
361  
362 <        setcolor(acol, 0.0, 0.0, 0.0);
363 <                                        /* set number of divisions */
364 <        nt = sqrt(ambdiv * r->rweight * 0.5) + 0.5;
365 <        np = 2 * nt;
366 <        ndivs = nt * np;
367 <                                        /* check first */
368 <        if (ndivs == 0 || rayorigin(&ar, r, AMBIENT, 0.5) < 0)
369 <                return(0.0);
370 <                                        /* set number of super-samples */
371 <        ns = ambssamp * r->rweight + 0.5;
372 <        if (ns > 0) {
302 <                div = (AMBSAMP *)malloc(ndivs*sizeof(AMBSAMP));
303 <                if (div == NULL)
304 <                        error(SYSTEM, "out of memory in doambient");
362 >        d = 1.0;                        /* zeroeth order */
363 >                                        /* gradient due to translation */
364 >        for (i = 0; i < 3; i++)
365 >                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
366 >                                        /* gradient due to rotation */
367 >        VCOPY(v1, ap->dir);
368 >        fcross(v2, v1, nv);
369 >        d += DOT(ap->gdir, v2);
370 >        if (d <= 0.0) {
371 >                setcolor(cr, 0.0, 0.0, 0.0);
372 >                return;
373          }
374 <                                        /* make axes */
375 <        uy[0] = uy[1] = uy[2] = 0.0;
308 <        for (k = 0; k < 3; k++)
309 <                if (r->ron[k] < 0.6 && r->ron[k] > -0.6)
310 <                        break;
311 <        uy[k] = 1.0;
312 <        fcross(ux, r->ron, uy);
313 <        normalize(ux);
314 <        fcross(uy, ux, r->ron);
315 <                                                /* sample divisions */
316 <        arad = 0.0;
317 <        ne = 0;
318 <        for (i = 0; i < nt; i++)
319 <                for (j = 0; j < np; j++) {
320 <                        rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
321 <                        zd = sqrt((i+frandom())/nt);
322 <                        phi = 2.0*PI * (j+frandom())/np;
323 <                        xd = cos(phi) * zd;
324 <                        yd = sin(phi) * zd;
325 <                        zd = sqrt(1.0 - zd*zd);
326 <                        for (k = 0; k < 3; k++)
327 <                                ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
328 <                        rayvalue(&ar);
329 <                        if (ar.rot < FHUGE)
330 <                                arad += 1.0 / ar.rot;
331 <                        if (ns > 0) {                   /* save division */
332 <                                div[ne].k = 0.0;
333 <                                copycolor(div[ne].v, ar.rcol);
334 <                                div[ne].n = 0;
335 <                                div[ne].t = i; div[ne].p = j;
336 <                                                        /* sum errors */
337 <                                b = bright(ar.rcol);
338 <                                if (i > 0) {            /* from above */
339 <                                        b2 = bright(div[ne-np].v) - b;
340 <                                        b2 *= b2 * 0.25;
341 <                                        div[ne].k += b2;
342 <                                        div[ne].n++;
343 <                                        div[ne-np].k += b2;
344 <                                        div[ne-np].n++;
345 <                                }
346 <                                if (j > 0) {            /* from behind */
347 <                                        b2 = bright(div[ne-1].v) - b;
348 <                                        b2 *= b2 * 0.25;
349 <                                        div[ne].k += b2;
350 <                                        div[ne].n++;
351 <                                        div[ne-1].k += b2;
352 <                                        div[ne-1].n++;
353 <                                }
354 <                                if (j == np-1) {        /* around */
355 <                                        b2 = bright(div[ne-(np-1)].v) - b;
356 <                                        b2 *= b2 * 0.25;
357 <                                        div[ne].k += b2;
358 <                                        div[ne].n++;
359 <                                        div[ne-(np-1)].k += b2;
360 <                                        div[ne-(np-1)].n++;
361 <                                }
362 <                                ne++;
363 <                        } else
364 <                                addcolor(acol, ar.rcol);
365 <                }
366 <        for (k = 0; k < ne; k++) {              /* compute errors */
367 <                if (div[k].n > 1)
368 <                        div[k].k /= div[k].n;
369 <                div[k].n = 1;
370 <        }
371 <                                                /* sort the divisions */
372 <        qsort(div, ne, sizeof(AMBSAMP), ambcmp);
373 <                                                /* skim excess */
374 <        while (ne > ns) {
375 <                ne--;
376 <                addcolor(acol, div[ne].v);
377 <        }
378 <                                                /* super-sample */
379 <        for (i = ns; i > 0; i--) {
380 <                rayorigin(&ar, r, AMBIENT, 0.5);        /* pretested */
381 <                zd = sqrt((div[0].t+frandom())/nt);
382 <                phi = 2.0*PI * (div[0].p+frandom())/np;
383 <                xd = cos(phi) * zd;
384 <                yd = sin(phi) * zd;
385 <                zd = sqrt(1.0 - zd*zd);
386 <                for (k = 0; k < 3; k++)
387 <                        ar.rdir[k] = xd*ux[k]+yd*uy[k]+zd*r->ron[k];
388 <                rayvalue(&ar);
389 <                if (ar.rot < FHUGE)
390 <                        arad += 1.0 / ar.rot;
391 <                                                /* recompute error */
392 <                copycolor(dnew.v, div[0].v);
393 <                addcolor(dnew.v, ar.rcol);
394 <                dnew.n = div[0].n + 1;
395 <                dnew.t = div[0].t; dnew.p = div[0].p;
396 <                b2 = bright(dnew.v)/dnew.n - bright(ar.rcol);
397 <                b2 = b2*b2 + div[0].k*(div[0].n*div[0].n);
398 <                dnew.k = b2/(dnew.n*dnew.n);
399 <                                                /* reinsert */
400 <                for (k = 0; k < ne-1 && dnew.k < div[k+1].k; k++)
401 <                        copystruct(&div[k], &div[k+1]);
402 <                copystruct(&div[k], &dnew);
403 <
404 <                if (ne >= i) {          /* extract darkest division */
405 <                        ne--;
406 <                        if (div[ne].n > 1)
407 <                                scalecolor(div[ne].v, 1.0/div[ne].n);
408 <                        addcolor(acol, div[ne].v);
409 <                }
410 <        }
411 <        scalecolor(acol, 1.0/ndivs);
412 <        if (arad <= FTINY)
413 <                arad = FHUGE;
414 <        else
415 <                arad = (ndivs+ns) / arad / sqrt(r->rweight);
416 <        if (arad > maxarad)
417 <                arad = maxarad;
418 <        else if (arad < minarad)
419 <                arad = minarad;
420 <        if (ns > 0)
421 <                free((char *)div);
422 <        return(arad);
374 >        copycolor(cr, ap->val);
375 >        scalecolor(cr, d);
376   }
377  
378  
379 < static int
380 < ambcmp(d1, d2)                          /* decreasing order */
381 < AMBSAMP  *d1, *d2;
379 > static
380 > initambfile(creat)              /* initialize ambient file */
381 > int  creat;
382   {
383 <        if (d1->k < d2->k)
384 <                return(1);
385 <        if (d1->k > d2->k)
386 <                return(-1);
387 <        return(0);
383 >        extern char  *progname, *octname, VersionID[];
384 >
385 > #ifdef  F_SETLKW
386 >        aflock(creat ? F_WRLCK : F_RDLCK);
387 > #endif
388 > #ifdef MSDOS
389 >        setmode(fileno(ambfp), O_BINARY);
390 > #endif
391 >        setbuf(ambfp, bmalloc(BUFSIZ+8));
392 >        if (creat) {                    /* new file */
393 >                newheader("RADIANCE", ambfp);
394 >                fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
395 >                                progname, colval(ambval,RED),
396 >                                colval(ambval,GRN), colval(ambval,BLU),
397 >                                ambounce, ambacc);
398 >                fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
399 >                                ambdiv, ambssamp, ambres,
400 >                                octname==NULL ? "" : octname);
401 >                fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
402 >                fputformat(AMBFMT, ambfp);
403 >                putc('\n', ambfp);
404 >                putambmagic(ambfp);
405 >        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
406 >                error(USER, "bad ambient file");
407   }
408  
409  
410   static
411 < avsave(av)                              /* save an ambient value */
412 < AMBVAL  *av;
411 > avsave(av)                              /* insert and save an ambient value */
412 > AMBVAL  *av;
413   {
414 < #ifdef  AMBFLUSH
443 <        static int  nunflshed = 0;
444 < #endif
414 >        avinsert(avstore(av));
415          if (ambfp == NULL)
416                  return;
417 <        if (fwrite((char *)av, sizeof(AMBVAL), 1, ambfp) != 1)
417 >        if (writambval(av, ambfp) < 0)
418                  goto writerr;
419 < #ifdef  AMBFLUSH
420 <        if (++nunflshed >= AMBFLUSH) {
451 <                if (fflush(ambfp) == EOF)
419 >        if (++nunflshed >= AMBFLUSH)
420 >                if (ambsync() == EOF)
421                          goto writerr;
453                nunflshed = 0;
454        }
455 #endif
422          return;
423   writerr:
424          error(SYSTEM, "error writing ambient file");
425   }
426  
427  
428 + static AMBVAL *
429 + avstore(aval)                           /* allocate memory and store aval */
430 + register AMBVAL  *aval;
431 + {
432 +        register AMBVAL  *av;
433 +
434 +        if ((av = newambval()) == NULL)
435 +                error(SYSTEM, "out of memory in avstore");
436 +        copystruct(av, aval);
437 +        av->latick = ambclock;
438 +        av->next = NULL;
439 +        addcolor(avsum, av->val);       /* add to sum for averaging */
440 +        nambvals++;
441 +        return(av);
442 + }
443 +
444 +
445 + #define ATALLOCSZ       512             /* #/8 trees to allocate at once */
446 +
447 + static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
448 +
449 +
450   static
451 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
452 < AMBVAL  *aval;
465 < register AMBTREE  *at;
466 < FVECT  c0;
467 < double  s;
451 > AMBTREE *
452 > newambtree()                            /* allocate 8 ambient tree structs */
453   {
454 +        register AMBTREE  *atp, *upperlim;
455 +
456 +        if (atfreelist == NULL) {       /* get more nodes */
457 +                atfreelist = (AMBTREE *)bmalloc(ATALLOCSZ*8*sizeof(AMBTREE));
458 +                if (atfreelist == NULL)
459 +                        return(NULL);
460 +                                        /* link new free list */
461 +                upperlim = atfreelist + 8*(ATALLOCSZ-1);
462 +                for (atp = atfreelist; atp < upperlim; atp += 8)
463 +                        atp->kid = atp + 8;
464 +                atp->kid = NULL;
465 +        }
466 +        atp = atfreelist;
467 +        atfreelist = atp->kid;
468 +        bzero((char *)atp, 8*sizeof(AMBTREE));
469 +        return(atp);
470 + }
471 +
472 +
473 + static
474 + freeambtree(atp)                        /* free 8 ambient tree structs */
475 + AMBTREE  *atp;
476 + {
477 +        atp->kid = atfreelist;
478 +        atfreelist = atp;
479 + }
480 +
481 +
482 + static
483 + avinsert(av)                            /* insert ambient value in our tree */
484 + register AMBVAL  *av;
485 + {
486 +        register AMBTREE  *at;
487 +        register AMBVAL  *ap;
488 +        AMBVAL  avh;
489          FVECT  ck0;
490 +        double  s;
491          int  branch;
471        register AMBVAL  *av;
492          register int  i;
493  
494 <        if ((av = newambval()) == NULL)
495 <                goto memerr;
496 <        copystruct(av, aval);
497 <        VCOPY(ck0, c0);
494 >        if (av->rad <= FTINY)
495 >                error(CONSISTENCY, "zero ambient radius in avinsert");
496 >        at = &atrunk;
497 >        VCOPY(ck0, thescene.cuorg);
498 >        s = thescene.cusize;
499          while (s*(OCTSCALE/2) > av->rad*ambacc) {
500                  if (at->kid == NULL)
501                          if ((at->kid = newambtree()) == NULL)
502 <                                goto memerr;
502 >                                error(SYSTEM, "out of memory in avinsert");
503                  s *= 0.5;
504                  branch = 0;
505                  for (i = 0; i < 3; i++)
# Line 488 | Line 509 | double  s;
509                          }
510                  at = at->kid + branch;
511          }
512 <        av->next = at->alist;
513 <        at->alist = av;
514 <        return;
515 < memerr:
516 <        error(SYSTEM, "out of memory in avinsert");
512 >        avh.next = at->alist;           /* order by increasing level */
513 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
514 >                if (ap->next->lvl >= av->lvl)
515 >                        break;
516 >        av->next = ap->next;
517 >        ap->next = av;
518 >        at->alist = avh.next;
519   }
520 +
521 +
522 + static
523 + unloadatree(at, f)                      /* unload an ambient value tree */
524 + register AMBTREE  *at;
525 + int     (*f)();
526 + {
527 +        register AMBVAL  *av;
528 +        register int  i;
529 +                                        /* transfer values at this node */
530 +        for (av = at->alist; av != NULL; av = at->alist) {
531 +                at->alist = av->next;
532 +                (*f)(av);
533 +        }
534 +        if (at->kid == NULL)
535 +                return;
536 +        for (i = 0; i < 8; i++)         /* transfer and free children */
537 +                unloadatree(at->kid+i, f);
538 +        freeambtree(at->kid);
539 +        at->kid = NULL;
540 + }
541 +
542 +
543 + static AMBVAL   **avlist1, **avlist2;   /* ambient value lists for sorting */
544 + static int      i_avlist;               /* index for lists */
545 +
546 +
547 + static
548 + av2list(av)
549 + AMBVAL  *av;
550 + {
551 + #ifdef DEBUG
552 +        if (i_avlist >= nambvals)
553 +                error(CONSISTENCY, "too many ambient values in av2list1");
554 + #endif
555 +        avlist1[i_avlist] = avlist2[i_avlist] = av;
556 +        i_avlist++;
557 + }
558 +
559 +
560 + static int
561 + alatcmp(avp1, avp2)                     /* compare ambient values for MRA */
562 + AMBVAL  **avp1, **avp2;
563 + {
564 +        return((**avp2).latick - (**avp1).latick);
565 + }
566 +
567 +
568 + static int
569 + aposcmp(avp1, avp2)                     /* compare ambient value positions */
570 + AMBVAL  **avp1, **avp2;
571 + {
572 +        return(*avp1 - *avp2);
573 + }
574 +
575 +
576 + #ifdef DEBUG
577 + static int
578 + avlmemi(avaddr)                         /* find list position from address */
579 + AMBVAL  *avaddr;
580 + {
581 +        register AMBVAL  **avlpp;
582 +
583 +        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
584 +                        nambvals, sizeof(AMBVAL *), aposcmp);
585 +        if (avlpp == NULL)
586 +                error(CONSISTENCY, "address not found in avlmemi");
587 +        return(avlpp - avlist2);
588 + }
589 + #else
590 + #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
591 +                                nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
592 + #endif
593 +
594 +
595 + static
596 + sortambvals(always)                     /* resort ambient values */
597 + int     always;
598 + {
599 +        AMBTREE  oldatrunk;
600 +        AMBVAL  tav, *tap, *pnext;
601 +        register int    i, j;
602 +                                        /* see if it's time yet */
603 +        if (!always && (ambclock < lastsort+sortintvl ||
604 +                        nambvals < SORT_THRESH))
605 +                return;
606 +        /*
607 +         * The idea here is to minimize memory thrashing
608 +         * in VM systems by improving reference locality.
609 +         * We do this by periodically sorting our stored ambient
610 +         * values in memory in order of most recently to least
611 +         * recently accessed.  This ordering was chosen so that new
612 +         * ambient values (which tend to be less important) go into
613 +         * higher memory with the infrequently accessed values.
614 +         *      Since we expect our values to need sorting less
615 +         * frequently as the process continues, we double our
616 +         * waiting interval after each call.
617 +         *      This routine is also called by setambacc() with
618 +         * the "always" parameter set to 1 so that the ambient
619 +         * tree will be rebuilt with the new accuracy parameter.
620 +         */
621 +        if (tracktime) {                /* allocate pointer arrays to sort */
622 +                avlist1 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
623 +                avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
624 +        } else
625 +                avlist1 = avlist2 = NULL;
626 +        if (avlist2 == NULL) {          /* no time tracking -- rebuild tree? */
627 +                if (avlist1 != NULL)
628 +                        free((char *)avlist1);
629 +                if (always) {           /* rebuild without sorting */
630 +                        copystruct(&oldatrunk, &atrunk);
631 +                        atrunk.alist = NULL;
632 +                        atrunk.kid = NULL;
633 +                        unloadatree(&oldatrunk, avinsert);
634 +                }
635 +        } else {                        /* sort memory by last access time */
636 +                /*
637 +                 * Sorting memory is tricky because it isn't contiguous.
638 +                 * We have to sort an array of pointers by MRA and also
639 +                 * by memory position.  We then copy values in "loops"
640 +                 * to minimize memory hits.  Nevertheless, we will visit
641 +                 * everyone at least twice, and this is an expensive process
642 +                 * when we're thrashing, which is when we need to do it.
643 +                 */
644 + #ifdef DEBUG
645 +                sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
646 +                                nambvals, ambclock);
647 +                eputs(errmsg);
648 + #endif
649 +                i_avlist = 0;
650 +                unloadatree(&atrunk, av2list);  /* empty current tree */
651 + #ifdef DEBUG
652 +                if (i_avlist < nambvals)
653 +                        error(CONSISTENCY, "missing ambient values in sortambvals");
654 + #endif
655 +                qsort((char *)avlist1, nambvals, sizeof(AMBVAL *), alatcmp);
656 +                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
657 +                for (i = 0; i < nambvals; i++) {
658 +                        if (avlist1[i] == NULL)
659 +                                continue;
660 +                        tap = avlist2[i];
661 +                        copystruct(&tav, tap);
662 +                        for (j = i; (pnext = avlist1[j]) != tap;
663 +                                        j = avlmemi(pnext)) {
664 +                                copystruct(avlist2[j], pnext);
665 +                                avinsert(avlist2[j]);
666 +                                avlist1[j] = NULL;
667 +                        }
668 +                        copystruct(avlist2[j], &tav);
669 +                        avinsert(avlist2[j]);
670 +                        avlist1[j] = NULL;
671 +                }
672 +                free((char *)avlist1);
673 +                free((char *)avlist2);
674 +                                                /* compute new sort interval */
675 +                sortintvl = ambclock - lastsort;
676 +                if (sortintvl >= MAX_SORT_INTVL/2)
677 +                        sortintvl = MAX_SORT_INTVL;
678 +                else
679 +                        sortintvl <<= 1;        /* wait twice as long next */
680 + #ifdef DEBUG
681 +                eputs("done\n");
682 + #endif
683 +        }
684 +        if (ambclock >= MAXACLOCK)
685 +                ambclock = MAXACLOCK/2;
686 +        lastsort = ambclock;
687 + }
688 +
689 +
690 + #ifdef  F_SETLKW
691 +
692 + static
693 + aflock(typ)                     /* lock/unlock ambient file */
694 + int  typ;
695 + {
696 +        static struct flock  fls;       /* static so initialized to zeroes */
697 +
698 +        fls.l_type = typ;
699 +        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
700 +                error(SYSTEM, "cannot (un)lock ambient file");
701 + }
702 +
703 +
704 + int
705 + ambsync()                       /* synchronize ambient file */
706 + {
707 +        static FILE  *ambinp = NULL;
708 +        static long  lastpos = -1;
709 +        long  flen;
710 +        AMBVAL  avs;
711 +        register int  n;
712 +
713 +        if (nunflshed == 0)
714 +                return(0);
715 +        if (lastpos < 0)        /* initializing (locked in initambfile) */
716 +                goto syncend;
717 +                                /* gain exclusive access */
718 +        aflock(F_WRLCK);
719 +                                /* see if file has grown */
720 +        if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
721 +                goto seekerr;
722 +        if (n = flen - lastpos) {               /* file has grown */
723 +                if (ambinp == NULL) {           /* use duplicate filedes */
724 +                        ambinp = fdopen(dup(fileno(ambfp)), "r");
725 +                        if (ambinp == NULL)
726 +                                error(SYSTEM, "fdopen failed in ambsync");
727 +                }
728 +                if (fseek(ambinp, lastpos, 0) < 0)
729 +                        goto seekerr;
730 +                while (n >= AMBVALSIZ) {        /* load contributed values */
731 +                        readambval(&avs, ambinp);
732 +                        avinsert(avstore(&avs));
733 +                        n -= AMBVALSIZ;
734 +                }
735 +                /*** seek always as safety measure
736 +                if (n) ***/                     /* alignment */
737 +                        if (lseek(fileno(ambfp), flen-n, 0) < 0)
738 +                                goto seekerr;
739 +        }
740 + #ifdef  DEBUG
741 +        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
742 +                sprintf(errmsg, "ambient file buffer at %d rather than %d",
743 +                                ambfp->_ptr - ambfp->_base,
744 +                                nunflshed*AMBVALSIZ);
745 +                error(CONSISTENCY, errmsg);
746 +        }
747 + #endif
748 + syncend:
749 +        n = fflush(ambfp);                      /* calls write() at last */
750 +        if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
751 +                goto seekerr;
752 +        aflock(F_UNLCK);                        /* release file */
753 +        nunflshed = 0;
754 +        return(n);
755 + seekerr:
756 +        error(SYSTEM, "seek failed in ambsync");
757 + }
758 +
759 + #else
760 +
761 + int
762 + ambsync()                       /* flush ambient file */
763 + {
764 +        if (nunflshed == 0)
765 +                return(0);
766 +        nunflshed = 0;
767 +        return(fflush(ambfp));
768 + }
769 +
770 + #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines