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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines