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 2.20 by greg, Thu Aug 5 10:02:00 1993 UTC vs.
Revision 2.59 by greg, Wed May 25 18:06:22 2005 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines