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.6 by greg, Tue Aug 8 17:31:23 1989 UTC vs.
Revision 2.42 by greg, Thu Jan 2 09:37:13 1997 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines