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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines