ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
(Generate patch)

Comparing ray/src/rt/ambient.c (file contents):
Revision 1.3 by greg, Fri May 26 17:58:01 1989 UTC vs.
Revision 2.50 by schorsch, Thu Jun 5 19:29:34 2003 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines