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.37 by greg, Tue May 28 14:24:44 1996 UTC vs.
Revision 2.70 by greg, Thu Sep 22 02:15:56 2011 UTC

# Line 1 | Line 1
1 /* Copyright (c) 1995 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   #ifndef  OCTSCALE
22   #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
23   #endif
24  
25 typedef struct ambtree {
26        AMBVAL  *alist;         /* ambient value list */
27        struct ambtree  *kid;   /* 8 child nodes */
28 }  AMBTREE;                     /* ambient octree */
29
30 extern CUBE  thescene;          /* contains space boundaries */
31
25   extern char  *shm_boundary;     /* memory sharing boundary */
26  
27 < #define  MAXASET        511     /* maximum number of elements in ambient set */
27 > #ifndef  MAXASET
28 > #define  MAXASET        4095    /* 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 43 | Line 38 | static FILE  *ambfp = NULL;    /* ambient file pointer */
38   static int  nunflshed = 0;      /* number of unflushed ambient values */
39  
40   #ifndef SORT_THRESH
41 < #ifdef BIGMEM
47 < #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
48 < #else
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*256)
48 > #define SORT_INTVL      (SORT_THRESH<<1)
49   #endif
50   #ifndef MAX_SORT_INTVL
51 < #define MAX_SORT_INTVL  (SORT_INTVL<<4)
51 > #define MAX_SORT_INTVL  (SORT_INTVL<<6)
52   #endif
53  
54 < static COLOR  avsum = BLKCOLOR;         /* computed ambient value sum */
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          /*
# Line 69 | Line 67 | static long  sortintvl = SORT_INTVL;   /* time until nex
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 < extern long  ftell(), lseek();
82 < static int  initambfile(), avsave(), avinsert(), sortambvals();
83 < static AMBVAL  *avstore();
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 > 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 < 0 ? 0 : ar;               /* may be done already */
107                                                  /* set min & max radii */
# Line 105 | Line 121 | int  ar;
121   }
122  
123  
124 < setambacc(newa)                         /* set ambient accuracy */
125 < double  newa;
124 > extern void
125 > setambacc(                              /* set ambient accuracy */
126 >        double  newa
127 > )
128   {
129          double  ambdiff;
130  
# Line 118 | Line 136 | double  newa;
136   }
137  
138  
139 < setambient(afile)                       /* initialize calculation */
140 < char  *afile;
139 > extern void
140 > setambient(void)                                /* initialize calculation */
141   {
142 <        long  pos, flen;
142 >        int     readonly = 0;
143 >        long    flen;
144          AMBVAL  amb;
145 +                                                /* make sure we're fresh */
146 +        ambdone();
147                                                  /* init ambient limits */
148          setambres(ambres);
149          setambacc(ambacc);
150 <        if (afile == NULL)
150 >        if (ambfile == NULL || !ambfile[0])
151                  return;
152          if (ambacc <= FTINY) {
153                  sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
154 <                                afile);
154 >                                ambfile);
155                  error(WARNING, errmsg);
156                  return;
157          }
158                                                  /* open ambient file */
159 <        if ((ambfp = fopen(afile, "r+")) != NULL) {
160 <                initambfile(0);
161 <                pos = 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 >                lastpos = ftell(ambfp);
164                  while (readambval(&amb, ambfp))
165                          avinsert(avstore(&amb));
166 <                                                /* align */
167 <                pos += (long)nambvals*AMBVALSIZ;
168 <                flen = lseek(fileno(ambfp), 0L, 2);
169 <                if (flen != pos) {
170 <                        error(WARNING,
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 >                lastpos += (long)nambvals*AMBVALSIZ;
178 >                flen = lseek(fileno(ambfp), (off_t)0, SEEK_END);
179 >                if (flen != lastpos) {
180 >                        sprintf(errmsg,
181                          "ignoring last %ld values in ambient file (corrupted)",
182 <                                        (flen - pos)/AMBVALSIZ);
183 <                        fseek(ambfp, pos, 0);
184 <                        ftruncate(fileno(ambfp), pos);
182 >                                        (flen - lastpos)/AMBVALSIZ);
183 >                        error(WARNING, errmsg);
184 >                        fseek(ambfp, lastpos, SEEK_SET);
185 > #ifndef _WIN32 /* XXX we need a replacement for that one */
186 >                        ftruncate(fileno(ambfp), (off_t)lastpos);
187 > #endif
188                  }
189 <                nambshare = nambvals;
190 <        } else if ((ambfp = fopen(afile, "w+")) != NULL)
191 <                initambfile(1);
192 <        else {
193 <                sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
189 >        } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
190 >                initambfile(1);                 /* else create new file */
191 >                fflush(ambfp);
192 >                lastpos = ftell(ambfp);
193 >        } else {
194 >                sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
195                  error(SYSTEM, errmsg);
196          }
197 <        nunflshed++;    /* lie */
198 <        ambsync();
197 > #ifdef  F_SETLKW
198 >        aflock(F_UNLCK);                        /* release file */
199 > #endif
200   }
201  
202  
203 < ambnotify(obj)                  /* record new modifier */
204 < OBJECT  obj;
203 > extern void
204 > ambdone(void)                   /* close ambient file and free memory */
205   {
206 +        if (ambfp != NULL) {            /* close ambient file */
207 +                ambsync();
208 +                fclose(ambfp);
209 +                ambfp = NULL;
210 +                if (ambinp != NULL) {  
211 +                        fclose(ambinp);
212 +                        ambinp = NULL;
213 +                }
214 +                lastpos = -1;
215 +        }
216 +                                        /* free ambient tree */
217 +        unloadatree(&atrunk, free);
218 +                                        /* reset state variables */
219 +        avsum = 0.;
220 +        navsum = 0;
221 +        nambvals = 0;
222 +        nambshare = 0;
223 +        ambclock = 0;
224 +        lastsort = 0;
225 +        sortintvl = SORT_INTVL;
226 + }
227 +
228 +
229 + extern void
230 + ambnotify(                      /* record new modifier */
231 +        OBJECT  obj
232 + )
233 + {
234          static int  hitlimit = 0;
235 <        register OBJREC  *o = objptr(obj);
236 <        register char  **amblp;
235 >        OBJREC   *o;
236 >        char  **amblp;
237  
238 +        if (obj == OVOID) {             /* starting over */
239 +                ambset[0] = 0;
240 +                hitlimit = 0;
241 +                return;
242 +        }
243 +        o = objptr(obj);
244          if (hitlimit || !ismodifier(o->otype))
245                  return;
246          for (amblp = amblist; *amblp != NULL; amblp++)
# Line 184 | Line 256 | OBJECT obj;
256   }
257  
258  
259 < ambient(acol, r, nrm)           /* compute ambient component for ray */
260 < COLOR  acol;
261 < register RAY  *r;
262 < FVECT  nrm;
259 > extern void
260 > multambient(            /* compute ambient component & multiply by coef. */
261 >        COLOR  aval,
262 >        RAY  *r,
263 >        FVECT  nrm
264 > )
265   {
266          static int  rdepth = 0;                 /* ambient recursion */
267 <        double  d;
267 >        COLOR   acol;
268 >        double  d, l;
269  
270          if (ambdiv <= 0)                        /* no ambient calculation */
271                  goto dumbamb;
# Line 203 | Line 278 | FVECT  nrm;
278                  goto dumbamb;
279  
280          if (ambacc <= FTINY) {                  /* no ambient storage */
281 +                copycolor(acol, aval);
282                  rdepth++;
283                  d = doambient(acol, r, r->rweight, NULL, NULL);
284                  rdepth--;
285                  if (d <= FTINY)
286                          goto dumbamb;
287 +                copycolor(aval, acol);
288                  return;
289          }
290 <                                                /* resort memory? */
291 <        sortambvals(0);
292 <                                                /* get ambient value */
290 >
291 >        if (tracktime)                          /* sort to minimize thrashing */
292 >                sortambvals(0);
293 >                                                /* interpolate ambient value */
294          setcolor(acol, 0.0, 0.0, 0.0);
295          d = sumambient(acol, r, nrm, rdepth,
296                          &atrunk, thescene.cuorg, thescene.cusize);
297          if (d > FTINY) {
298 <                scalecolor(acol, 1.0/d);
298 >                d = 1.0/d;
299 >                scalecolor(acol, d);
300 >                multcolor(aval, acol);
301                  return;
302          }
303          rdepth++;                               /* need to cache new value */
304          d = makeambient(acol, r, nrm, rdepth-1);
305          rdepth--;
306 <        if (d > FTINY)
306 >        if (d > FTINY) {
307 >                multcolor(aval, acol);          /* got new value */
308                  return;
309 +        }
310   dumbamb:                                        /* return global value */
311 <        copycolor(acol, ambval);
312 <        if (ambvwt <= 0 | nambvals == 0)
311 >        if ((ambvwt <= 0) | (navsum == 0)) {
312 >                multcolor(aval, ambval);
313                  return;
314 <        scalecolor(acol, (double)ambvwt);
315 <        addcolor(acol, avsum);                  /* average in computations */
316 <        d = 1.0/(ambvwt+nambvals);
317 <        scalecolor(acol, d);
314 >        }
315 >        l = bright(ambval);                     /* average in computations */
316 >        if (l > FTINY) {
317 >                d = (log(l)*(double)ambvwt + avsum) /
318 >                                (double)(ambvwt + navsum);
319 >                d = exp(d) / l;
320 >                scalecolor(aval, d);
321 >                multcolor(aval, ambval);        /* apply color of ambval */
322 >        } else {
323 >                d = exp( avsum / (double)navsum );
324 >                scalecolor(aval, d);            /* neutral color */
325 >        }
326   }
327  
328  
329 < double
330 < sumambient(acol, r, rn, al, at, c0, s)  /* get interpolated ambient value */
331 < COLOR  acol;
332 < register RAY  *r;
333 < FVECT  rn;
334 < int  al;
335 < AMBTREE  *at;
336 < FVECT  c0;
337 < double  s;
329 > extern double
330 > sumambient(     /* get interpolated ambient value */
331 >        COLOR  acol,
332 >        RAY  *r,
333 >        FVECT  rn,
334 >        int  al,
335 >        AMBTREE  *at,
336 >        FVECT  c0,
337 >        double  s
338 > )
339   {
340          double  d, e1, e2, wt, wsum;
341          COLOR  ct;
342          FVECT  ck0;
343          int  i;
344 <        register int  j;
345 <        register AMBVAL  *av;
344 >        int  j;
345 >        AMBVAL   *av;
346  
347          wsum = 0.0;
348                                          /* do this node */
349          for (av = at->alist; av != NULL; av = av->next) {
350 +                double  rn_dot = -2.0;
351                  if (tracktime)
352 <                        av->latick = ambclock++;
352 >                        av->latick = ambclock;
353                  /*
354                   *  Ambient level test.
355                   */
356                  if (av->lvl > al)       /* list sorted, so this works */
357                          break;
358 <                if (av->weight < r->rweight-FTINY)
358 >                if (av->weight < 0.9*r->rweight)
359                          continue;
360                  /*
361                   *  Ambient radius test.
362                   */
363 <                d = av->pos[0] - r->rop[0];
364 <                e1 = d * d;
273 <                d = av->pos[1] - r->rop[1];
274 <                e1 += d * d;
275 <                d = av->pos[2] - r->rop[2];
276 <                e1 += d * d;
277 <                e1 /= av->rad * av->rad;
363 >                VSUB(ck0, av->pos, r->rop);
364 >                e1 = DOT(ck0, ck0) / (av->rad * av->rad);
365                  if (e1 > ambacc*ambacc*1.21)
366                          continue;
367                  /*
368 <                 *  Normal direction test.
368 >                 *  Direction test using closest normal.
369                   */
370 <                e2 = (1.0 - DOT(av->dir, r->ron)) * r->rweight;
371 <                if (e2 < 0.0) e2 = 0.0;
372 <                if (e1 + e2 > ambacc*ambacc*1.21)
370 >                d = DOT(av->dir, r->ron);
371 >                if (rn != r->ron) {
372 >                        rn_dot = DOT(av->dir, rn);
373 >                        if (rn_dot > 1.0-FTINY)
374 >                                rn_dot = 1.0-FTINY;
375 >                        if (rn_dot >= d-FTINY) {
376 >                                d = rn_dot;
377 >                                rn_dot = -2.0;
378 >                        }
379 >                }
380 >                e2 = (1.0 - d) * r->rweight;
381 >                if (e2 < 0.0)
382 >                        e2 = 0.0;
383 >                else if (e1 + e2 > ambacc*ambacc*1.21)
384                          continue;
385                  /*
386                   *  Ray behind test.
# Line 296 | Line 394 | double s;
394                  /*
395                   *  Jittering final test reduces image artifacts.
396                   */
397 <                wt = sqrt(e1) + sqrt(e2);
397 >                e1 = sqrt(e1);
398 >                e2 = sqrt(e2);
399 >                wt = e1 + e2;
400                  if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
401                          continue;
402 +                /*
403 +                 *  Recompute directional error using perturbed normal
404 +                 */
405 +                if (rn_dot > 0.0) {
406 +                        e2 = sqrt((1.0 - rn_dot)*r->rweight);
407 +                        wt = e1 + e2;
408 +                }
409                  if (wt <= 1e-3)
410                          wt = 1e3;
411                  else
# Line 323 | Line 430 | double s;
430                                  break;
431                  }
432                  if (j == 3)
433 <                        wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
433 >                        wsum += sumambient(acol, r, rn, al,
434 >                                                at->kid+i, ck0, s);
435          }
436          return(wsum);
437   }
438  
439  
440 < double
441 < makeambient(acol, r, rn, al)    /* make a new ambient value */
442 < COLOR  acol;
443 < register RAY  *r;
444 < FVECT  rn;
445 < int  al;
440 > extern double
441 > makeambient(            /* make a new ambient value for storage */
442 >        COLOR  acol,
443 >        RAY  *r,
444 >        FVECT  rn,
445 >        int  al
446 > )
447   {
448          AMBVAL  amb;
449          FVECT   gp, gd;
450 <                                                /* compute weight */
451 <        amb.weight = pow(AVGREFL, (double)al);
452 <        if (r->rweight < 0.1*amb.weight)        /* heuristic */
453 <                amb.weight = r->rweight;
450 >        int     i;
451 >
452 >        amb.weight = 1.0;                       /* compute weight */
453 >        for (i = al; i-- > 0; )
454 >                amb.weight *= AVGREFL;
455 >        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
456 >                amb.weight = 1.25*r->rweight;
457 >        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
458                                                  /* compute ambient */
459          amb.rad = doambient(acol, r, amb.weight, gp, gd);
460 <        if (amb.rad <= FTINY)
460 >        if (amb.rad <= FTINY) {
461 >                setcolor(acol, 0.0, 0.0, 0.0);
462                  return(0.0);
463 <                                                /* store it */
463 >        }
464 >        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
465 >                                                /* store value */
466          VCOPY(amb.pos, r->rop);
467          VCOPY(amb.dir, r->ron);
468          amb.lvl = al;
# Line 361 | Line 477 | int  al;
477   }
478  
479  
480 < extambient(cr, ap, pv, nv)              /* extrapolate value at pv, nv */
481 < COLOR  cr;
482 < register AMBVAL  *ap;
483 < FVECT  pv, nv;
480 > extern void
481 > extambient(             /* extrapolate value at pv, nv */
482 >        COLOR  cr,
483 >        AMBVAL   *ap,
484 >        FVECT  pv,
485 >        FVECT  nv
486 > )
487   {
488 <        FVECT  v1, v2;
489 <        register int  i;
488 >        FVECT  v1;
489 >        int  i;
490          double  d;
491  
492          d = 1.0;                        /* zeroeth order */
# Line 375 | Line 494 | FVECT  pv, nv;
494          for (i = 0; i < 3; i++)
495                  d += ap->gpos[i]*(pv[i]-ap->pos[i]);
496                                          /* gradient due to rotation */
497 <        VCOPY(v1, ap->dir);
498 <        fcross(v2, v1, nv);
380 <        d += DOT(ap->gdir, v2);
497 >        VCROSS(v1, ap->dir, nv);
498 >        d += DOT(ap->gdir, v1);
499          if (d <= 0.0) {
500                  setcolor(cr, 0.0, 0.0, 0.0);
501                  return;
# Line 387 | Line 505 | FVECT  pv, nv;
505   }
506  
507  
508 < static
509 < initambfile(creat)              /* initialize ambient file */
510 < int  creat;
508 > static void
509 > initambfile(            /* initialize ambient file */
510 >        int  cre8
511 > )
512   {
513 <        extern char  *progname, *octname, VersionID[];
513 >        extern char  *progname, *octname;
514 >        static char  *mybuf = NULL;
515  
516   #ifdef  F_SETLKW
517 <        aflock(creat ? F_WRLCK : F_RDLCK);
517 >        aflock(cre8 ? F_WRLCK : F_RDLCK);
518   #endif
519 < #ifdef MSDOS
520 <        setmode(fileno(ambfp), O_BINARY);
521 < #endif
522 <        setbuf(ambfp, bmalloc(BUFSIZ+8));
523 <        if (creat) {                    /* new file */
519 >        SET_FILE_BINARY(ambfp);
520 >        if (mybuf == NULL)
521 >                mybuf = (char *)bmalloc(BUFSIZ+8);
522 >        setbuf(ambfp, mybuf);
523 >        if (cre8) {                     /* new file */
524                  newheader("RADIANCE", ambfp);
525 <                fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
525 >                fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
526                                  progname, colval(ambval,RED),
527                                  colval(ambval,GRN), colval(ambval,BLU),
528 <                                ambounce, ambacc);
529 <                fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
530 <                                ambdiv, ambssamp, ambres,
531 <                                octname==NULL ? "" : octname);
528 >                                ambvwt, ambounce, ambacc);
529 >                fprintf(ambfp, "-ad %d -as %d -ar %d ",
530 >                                ambdiv, ambssamp, ambres);
531 >                if (octname != NULL)
532 >                        fputs(octname, ambfp);
533 >                fputc('\n', ambfp);
534                  fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
535 +                fputnow(ambfp);
536                  fputformat(AMBFMT, ambfp);
537 <                putc('\n', ambfp);
537 >                fputc('\n', ambfp);
538                  putambmagic(ambfp);
539          } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
540                  error(USER, "bad ambient file");
541   }
542  
543  
544 < static
545 < avsave(av)                              /* insert and save an ambient value */
546 < AMBVAL  *av;
544 > static void
545 > avsave(                         /* insert and save an ambient value */
546 >        AMBVAL  *av
547 > )
548   {
549          avinsert(avstore(av));
550          if (ambfp == NULL)
# Line 432 | Line 556 | AMBVAL *av;
556                          goto writerr;
557          return;
558   writerr:
559 <        error(SYSTEM, "error writing ambient file");
559 >        error(SYSTEM, "error writing to ambient file");
560   }
561  
562  
563   static AMBVAL *
564 < avstore(aval)                           /* allocate memory and store aval */
565 < register AMBVAL  *aval;
564 > avstore(                                /* allocate memory and store aval */
565 >        AMBVAL  *aval
566 > )
567   {
568 <        register AMBVAL  *av;
568 >        AMBVAL  *av;
569 >        double  d;
570  
571          if ((av = newambval()) == NULL)
572                  error(SYSTEM, "out of memory in avstore");
573 <        copystruct(av, aval);
573 >        *av = *aval;
574          av->latick = ambclock;
575          av->next = NULL;
450        addcolor(avsum, av->val);       /* add to sum for averaging */
576          nambvals++;
577 +        d = bright(av->val);
578 +        if (d > FTINY) {                /* add to log sum for averaging */
579 +                avsum += log(d);
580 +                navsum++;
581 +        }
582          return(av);
583   }
584  
# Line 458 | Line 588 | register AMBVAL  *aval;
588   static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
589  
590  
591 < static
592 < AMBTREE *
463 < newambtree()                            /* allocate 8 ambient tree structs */
591 > static AMBTREE *
592 > newambtree(void)                                /* allocate 8 ambient tree structs */
593   {
594 <        register AMBTREE  *atp, *upperlim;
594 >        AMBTREE  *atp, *upperlim;
595  
596          if (atfreelist == NULL) {       /* get more nodes */
597 <                atfreelist = (AMBTREE *)bmalloc(ATALLOCSZ*8*sizeof(AMBTREE));
597 >                atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
598                  if (atfreelist == NULL)
599                          return(NULL);
600                                          /* link new free list */
# Line 476 | Line 605 | newambtree()                           /* allocate 8 ambient tree structs */
605          }
606          atp = atfreelist;
607          atfreelist = atp->kid;
608 <        bzero((char *)atp, 8*sizeof(AMBTREE));
608 >        memset((char *)atp, '\0', 8*sizeof(AMBTREE));
609          return(atp);
610   }
611  
612  
613 < static
614 < freeambtree(atp)                        /* free 8 ambient tree structs */
615 < AMBTREE  *atp;
613 > static void
614 > freeambtree(                    /* free 8 ambient tree structs */
615 >        AMBTREE  *atp
616 > )
617   {
618          atp->kid = atfreelist;
619          atfreelist = atp;
620   }
621  
622  
623 < static
624 < avinsert(av)                            /* insert ambient value in our tree */
625 < register AMBVAL  *av;
623 > static void
624 > avinsert(                               /* insert ambient value in our tree */
625 >        void *av
626 > )
627   {
628 <        register AMBTREE  *at;
629 <        register AMBVAL  *ap;
628 >        AMBTREE  *at;
629 >        AMBVAL  *ap;
630          AMBVAL  avh;
631          FVECT  ck0;
632          double  s;
633          int  branch;
634 <        register int  i;
634 >        int  i;
635  
636 <        if (av->rad <= FTINY)
636 >        if (((AMBVAL*)av)->rad <= FTINY)
637                  error(CONSISTENCY, "zero ambient radius in avinsert");
638          at = &atrunk;
639          VCOPY(ck0, thescene.cuorg);
640          s = thescene.cusize;
641 <        while (s*(OCTSCALE/2) > av->rad*ambacc) {
641 >        while (s*(OCTSCALE/2) > ((AMBVAL*)av)->rad*ambacc) {
642                  if (at->kid == NULL)
643                          if ((at->kid = newambtree()) == NULL)
644                                  error(SYSTEM, "out of memory in avinsert");
645                  s *= 0.5;
646                  branch = 0;
647                  for (i = 0; i < 3; i++)
648 <                        if (av->pos[i] > ck0[i] + s) {
648 >                        if (((AMBVAL*)av)->pos[i] > ck0[i] + s) {
649                                  ck0[i] += s;
650                                  branch |= 1 << i;
651                          }
# Line 522 | Line 653 | register AMBVAL         *av;
653          }
654          avh.next = at->alist;           /* order by increasing level */
655          for (ap = &avh; ap->next != NULL; ap = ap->next)
656 <                if (ap->next->lvl >= av->lvl)
656 >                if (ap->next->lvl >= ((AMBVAL*)av)->lvl)
657                          break;
658 <        av->next = ap->next;
659 <        ap->next = av;
658 >        ((AMBVAL*)av)->next = ap->next;
659 >        ap->next = (AMBVAL*)av;
660          at->alist = avh.next;
661   }
662  
663  
664 < static
665 < unloadatree(at, f)                      /* unload an ambient value tree */
666 < register AMBTREE  *at;
667 < int     (*f)();
664 > static void
665 > unloadatree(                    /* unload an ambient value tree */
666 >        AMBTREE  *at,
667 >        unloadtf_t *f
668 > )
669   {
670 <        register AMBVAL  *av;
671 <        register int  i;
670 >        AMBVAL  *av;
671 >        int  i;
672                                          /* transfer values at this node */
673          for (av = at->alist; av != NULL; av = at->alist) {
674                  at->alist = av->next;
# Line 551 | Line 683 | int    (*f)();
683   }
684  
685  
686 < static AMBVAL   **avlist1, **avlist2;   /* ambient value lists for sorting */
686 > static struct avl {
687 >        AMBVAL  *p;
688 >        unsigned long   t;
689 > }       *avlist1;                       /* ambient value list with ticks */
690 > static AMBVAL   **avlist2;              /* memory positions for sorting */
691   static int      i_avlist;               /* index for lists */
692  
693 + static int alatcmp(const void *av1, const void *av2);
694  
695 < static
696 < av2list(av)
697 < AMBVAL  *av;
695 > static void
696 > av2list(
697 >        void *av
698 > )
699   {
700   #ifdef DEBUG
701          if (i_avlist >= nambvals)
702                  error(CONSISTENCY, "too many ambient values in av2list1");
703   #endif
704 <        avlist1[i_avlist] = avlist2[i_avlist] = av;
705 <        i_avlist++;
704 >        avlist1[i_avlist].p = avlist2[i_avlist] = (AMBVAL*)av;
705 >        avlist1[i_avlist++].t = ((AMBVAL*)av)->latick;
706   }
707  
708  
709   static int
710 < alatcmp(avp1, avp2)                     /* compare ambient values for MRA */
711 < AMBVAL  **avp1, **avp2;
710 > alatcmp(                        /* compare ambient values for MRA */
711 >        const void *av1,
712 >        const void *av2
713 > )
714   {
715 <        return((**avp2).latick - (**avp1).latick);
715 >        long  lc = ((struct avl *)av2)->t - ((struct avl *)av1)->t;
716 >        return(lc<0 ? -1 : lc>0 ? 1 : 0);
717   }
718  
719  
720 + /* GW NOTE 2002/10/3:
721 + * I used to compare AMBVAL pointers, but found that this was the
722 + * cause of a serious consistency error with gcc, since the optimizer
723 + * uses some dangerous trick in pointer subtraction that
724 + * assumes pointers differ by exact struct size increments.
725 + */
726   static int
727 < aposcmp(avp1, avp2)                     /* compare ambient value positions */
728 < AMBVAL  **avp1, **avp2;
727 > aposcmp(                        /* compare ambient value positions */
728 >        const void      *avp1,
729 >        const void      *avp2
730 > )
731   {
732 <        return(*avp1 - *avp2);
732 >        long    diff = *(char * const *)avp1 - *(char * const *)avp2;
733 >        if (diff < 0)
734 >                return(-1);
735 >        return(diff > 0);
736   }
737  
738 <
587 < #ifdef DEBUG
738 > #if 1
739   static int
740 < avlmemi(avaddr)                         /* find list position from address */
741 < AMBVAL  *avaddr;
740 > avlmemi(                                /* find list position from address */
741 >        AMBVAL  *avaddr
742 > )
743   {
744 <        register AMBVAL  **avlpp;
744 >        AMBVAL  **avlpp;
745  
746          avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
747                          nambvals, sizeof(AMBVAL *), aposcmp);
# Line 603 | Line 755 | AMBVAL *avaddr;
755   #endif
756  
757  
758 < static
759 < sortambvals(always)                     /* resort ambient values */
760 < int     always;
758 > static void
759 > sortambvals(                    /* resort ambient values */
760 >        int     always
761 > )
762   {
763          AMBTREE  oldatrunk;
764          AMBVAL  tav, *tap, *pnext;
765 <        register int    i, j;
765 >        int     i, j;
766                                          /* see if it's time yet */
767 <        if (!always && (ambclock < lastsort+sortintvl ||
767 >        if (!always && (ambclock++ < lastsort+sortintvl ||
768                          nambvals < SORT_THRESH))
769                  return;
770          /*
# Line 630 | Line 783 | int    always;
783           * tree will be rebuilt with the new accuracy parameter.
784           */
785          if (tracktime) {                /* allocate pointer arrays to sort */
633                avlist1 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
786                  avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
787 <        } else
788 <                avlist1 = avlist2 = NULL;
789 <        if (avlist2 == NULL) {          /* no time tracking -- rebuild tree? */
790 <                if (avlist1 != NULL)
791 <                        free((char *)avlist1);
787 >                avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
788 >        } else {
789 >                avlist2 = NULL;
790 >                avlist1 = NULL;
791 >        }
792 >        if (avlist1 == NULL) {          /* no time tracking -- rebuild tree? */
793 >                if (avlist2 != NULL)
794 >                        free((void *)avlist2);
795                  if (always) {           /* rebuild without sorting */
796 <                        copystruct(&oldatrunk, &atrunk);
796 >                        oldatrunk = atrunk;
797                          atrunk.alist = NULL;
798                          atrunk.kid = NULL;
799                          unloadatree(&oldatrunk, avinsert);
# Line 663 | Line 818 | int    always;
818                  if (i_avlist < nambvals)
819                          error(CONSISTENCY, "missing ambient values in sortambvals");
820   #endif
821 <                qsort((char *)avlist1, nambvals, sizeof(AMBVAL *), alatcmp);
821 >                qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
822                  qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
823                  for (i = 0; i < nambvals; i++) {
824 <                        if (avlist1[i] == NULL)
824 >                        if (avlist1[i].p == NULL)
825                                  continue;
826                          tap = avlist2[i];
827 <                        copystruct(&tav, tap);
828 <                        for (j = i; (pnext = avlist1[j]) != tap;
827 >                        tav = *tap;
828 >                        for (j = i; (pnext = avlist1[j].p) != tap;
829                                          j = avlmemi(pnext)) {
830 <                                copystruct(avlist2[j], pnext);
830 >                                *(avlist2[j]) = *pnext;
831                                  avinsert(avlist2[j]);
832 <                                avlist1[j] = NULL;
832 >                                avlist1[j].p = NULL;
833                          }
834 <                        copystruct(avlist2[j], &tav);
834 >                        *(avlist2[j]) = tav;
835                          avinsert(avlist2[j]);
836 <                        avlist1[j] = NULL;
836 >                        avlist1[j].p = NULL;
837                  }
838 <                free((char *)avlist1);
839 <                free((char *)avlist2);
838 >                free((void *)avlist1);
839 >                free((void *)avlist2);
840                                                  /* compute new sort interval */
841                  sortintvl = ambclock - lastsort;
842                  if (sortintvl >= MAX_SORT_INTVL/2)
# Line 700 | Line 855 | int    always;
855  
856   #ifdef  F_SETLKW
857  
858 < static
859 < aflock(typ)                     /* lock/unlock ambient file */
860 < int  typ;
858 > static void
859 > aflock(                 /* lock/unlock ambient file */
860 >        int  typ
861 > )
862   {
863          static struct flock  fls;       /* static so initialized to zeroes */
864  
865 +        if (typ == fls.l_type)          /* already called? */
866 +                return;
867          fls.l_type = typ;
868          if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
869                  error(SYSTEM, "cannot (un)lock ambient file");
870   }
871  
872  
873 < int
874 < ambsync()                       /* synchronize ambient file */
873 > extern int
874 > ambsync(void)                   /* synchronize ambient file */
875   {
718        static FILE  *ambinp = NULL;
719        static long  lastpos = -1;
876          long  flen;
877          AMBVAL  avs;
878 <        register int  n;
878 >        int  n;
879  
880 <        if (nunflshed == 0)
880 >        if (ambfp == NULL)      /* no ambient file? */
881                  return(0);
882 <        if (lastpos < 0)        /* initializing (locked in initambfile) */
883 <                goto syncend;
728 <                                /* gain exclusive access */
729 <        aflock(F_WRLCK);
882 >                                /* gain appropriate access */
883 >        aflock(nunflshed ? F_WRLCK : F_RDLCK);
884                                  /* see if file has grown */
885 <        if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
885 >        if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
886                  goto seekerr;
887 <        if (n = flen - lastpos) {               /* file has grown */
887 >        if ((n = flen - lastpos) > 0) {         /* file has grown */
888                  if (ambinp == NULL) {           /* use duplicate filedes */
889                          ambinp = fdopen(dup(fileno(ambfp)), "r");
890                          if (ambinp == NULL)
891                                  error(SYSTEM, "fdopen failed in ambsync");
892                  }
893 <                if (fseek(ambinp, lastpos, 0) < 0)
893 >                if (fseek(ambinp, lastpos, SEEK_SET) < 0)
894                          goto seekerr;
895                  while (n >= AMBVALSIZ) {        /* load contributed values */
896                          if (!readambval(&avs, ambinp)) {
897                                  sprintf(errmsg,
898 <                                "ambient file corrupted near character %ld",
899 <                                                flen - n);
898 >                        "ambient file \"%s\" corrupted near character %ld",
899 >                                                ambfile, flen - n);
900                                  error(WARNING, errmsg);
901                                  break;
902                          }
903                          avinsert(avstore(&avs));
904                          n -= AMBVALSIZ;
905                  }
906 +                lastpos = flen - n;
907                  /*** seek always as safety measure
908                  if (n) ***/                     /* alignment */
909 <                        if (lseek(fileno(ambfp), flen-n, 0) < 0)
909 >                        if (lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
910                                  goto seekerr;
911          }
757 #ifdef  DEBUG
758        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
759                sprintf(errmsg, "ambient file buffer at %d rather than %d",
760                                ambfp->_ptr - ambfp->_base,
761                                nunflshed*AMBVALSIZ);
762                error(CONSISTENCY, errmsg);
763        }
764 #endif
765 syncend:
912          n = fflush(ambfp);                      /* calls write() at last */
913 <        if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
913 >        if (n != EOF)
914 >                lastpos += (long)nunflshed*AMBVALSIZ;
915 >        else if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
916                  goto seekerr;
917 +                
918          aflock(F_UNLCK);                        /* release file */
919          nunflshed = 0;
920          return(n);
921   seekerr:
922          error(SYSTEM, "seek failed in ambsync");
923 +        return -1; /* pro forma return */
924   }
925  
926   #else
927  
928 < int
929 < ambsync()                       /* flush ambient file */
928 > extern int
929 > ambsync(void)                   /* flush ambient file */
930   {
931 <        if (nunflshed == 0)
931 >        if (ambfp == NULL)
932                  return(0);
933          nunflshed = 0;
934          return(fflush(ambfp));

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines