ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.56
Committed: Tue Mar 30 16:13:00 2004 UTC (20 years, 1 month ago) by schorsch
Content type: text/plain
Branch: MAIN
CVS Tags: rad3R6, rad3R6P1
Changes since 2.55: +120 -83 lines
Log Message:
Continued ANSIfication. There are only bits and pieces left now.

File Contents

# User Rev Content
1 greg 1.1 #ifndef lint
2 schorsch 2.56 static const char RCSid[] = "$Id: ambient.c,v 2.55 2003/10/20 16:01:55 greg Exp $";
3 greg 1.1 #endif
4     /*
5     * ambient.c - routines dealing with ambient (inter-reflected) component.
6 greg 2.47 *
7     * Declarations of external symbols in ambient.h
8     */
9    
10 greg 2.48 #include "copyright.h"
11 greg 1.1
12 schorsch 2.52 #include <string.h>
13    
14 schorsch 2.50 #include "platform.h"
15 greg 1.1 #include "ray.h"
16 greg 1.8 #include "otypes.h"
17 schorsch 2.56 #include "resolu.h"
18 greg 1.14 #include "ambient.h"
19 greg 1.1 #include "random.h"
20    
21 greg 2.32 #ifndef OCTSCALE
22 greg 2.29 #define OCTSCALE 1.0 /* ceil((valid rad.)/(cube size)) */
23 greg 2.32 #endif
24 greg 1.1
25 greg 2.27 extern char *shm_boundary; /* memory sharing boundary */
26 greg 2.26
27 greg 2.12 #define MAXASET 511 /* maximum number of elements in ambient set */
28     OBJECT ambset[MAXASET+1]={0}; /* ambient include/exclude set */
29 greg 1.1
30 greg 2.12 double maxarad; /* maximum ambient radius */
31     double minarad; /* minimum ambient radius */
32 greg 1.1
33 greg 2.12 static AMBTREE atrunk; /* our ambient trunk node */
34 greg 1.1
35     static FILE *ambfp = NULL; /* ambient file pointer */
36 greg 2.16 static int nunflshed = 0; /* number of unflushed ambient values */
37 greg 1.1
38 greg 2.26 #ifndef SORT_THRESH
39 greg 2.49 #ifdef SMLMEM
40     #define SORT_THRESH ((3L<<20)/sizeof(AMBVAL))
41     #else
42 greg 2.27 #define SORT_THRESH ((9L<<20)/sizeof(AMBVAL))
43 greg 2.26 #endif
44     #endif
45     #ifndef SORT_INTVL
46 greg 2.41 #define SORT_INTVL (SORT_THRESH<<1)
47 greg 2.26 #endif
48 greg 2.28 #ifndef MAX_SORT_INTVL
49 greg 2.41 #define MAX_SORT_INTVL (SORT_INTVL<<6)
50 greg 2.28 #endif
51 greg 2.26
52 gregl 2.43 static double avsum = 0.; /* computed ambient value sum (log) */
53     static unsigned int navsum = 0; /* number of values in avsum */
54 greg 2.35 static unsigned int nambvals = 0; /* total number of indirect values */
55     static unsigned int nambshare = 0; /* number of values from file */
56 greg 2.27 static unsigned long ambclock = 0; /* ambient access clock */
57     static unsigned long lastsort = 0; /* time of last value sort */
58 greg 2.26 static long sortintvl = SORT_INTVL; /* time until next sort */
59 greg 2.47 static FILE *ambinp = NULL; /* auxiliary file for input */
60     static long lastpos = -1; /* last flush position */
61 greg 2.26
62     #define MAXACLOCK (1L<<30) /* clock turnover value */
63 greg 2.27 /*
64     * Track access times unless we are sharing ambient values
65     * through memory on a multiprocessor, when we want to avoid
66 greg 2.35 * claiming our own memory (copy on write). Go ahead anyway
67     * if more than two thirds of our values are unshared.
68 gregl 2.43 * Compile with -Dtracktime=0 to turn this code off.
69 greg 2.27 */
70 gregl 2.43 #ifndef tracktime
71 greg 2.35 #define tracktime (shm_boundary == NULL || nambvals > 3*nambshare)
72 gregl 2.43 #endif
73 greg 2.26
74 greg 2.12 #define AMBFLUSH (BUFSIZ/AMBVALSIZ)
75 greg 2.6
76 greg 2.47 #define newambval() (AMBVAL *)malloc(sizeof(AMBVAL))
77     #define freeav(av) free((void *)av);
78 greg 1.1
79 schorsch 2.56 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     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 greg 2.19 #ifdef F_SETLKW
95 schorsch 2.56 static void aflock(int typ);
96 greg 2.19 #endif
97 greg 1.1
98 greg 2.7
99 schorsch 2.56 extern void
100     setambres( /* set ambient resolution */
101     int ar
102     )
103 greg 2.3 {
104 greg 2.21 ambres = ar < 0 ? 0 : ar; /* may be done already */
105 greg 2.3 /* set min & max radii */
106     if (ar <= 0) {
107 greg 2.25 minarad = 0;
108 greg 2.3 maxarad = thescene.cusize / 2.0;
109     } else {
110     minarad = thescene.cusize / ar;
111 greg 2.30 maxarad = 64 * minarad; /* heuristic */
112 greg 2.3 if (maxarad > thescene.cusize / 2.0)
113     maxarad = thescene.cusize / 2.0;
114     }
115 greg 2.25 if (minarad <= FTINY)
116     minarad = 10*FTINY;
117     if (maxarad <= minarad)
118     maxarad = 64 * minarad;
119 greg 2.3 }
120    
121    
122 schorsch 2.56 extern void
123     setambacc( /* set ambient accuracy */
124     double newa
125     )
126 greg 2.20 {
127 greg 2.33 double ambdiff;
128 greg 2.20
129 greg 2.33 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 greg 2.20 }
135    
136    
137 schorsch 2.56 extern void
138     setambient(void) /* initialize calculation */
139 greg 1.1 {
140 gwlarson 2.46 int readonly = 0;
141 greg 2.37 long pos, flen;
142 greg 2.12 AMBVAL amb;
143 greg 2.47 /* make sure we're fresh */
144     ambdone();
145 greg 2.3 /* init ambient limits */
146     setambres(ambres);
147 greg 2.21 setambacc(ambacc);
148 greg 2.47 if (ambfile == NULL || !ambfile[0])
149 greg 2.19 return;
150 greg 2.20 if (ambacc <= FTINY) {
151 greg 2.21 sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
152 greg 2.47 ambfile);
153 greg 2.20 error(WARNING, errmsg);
154     return;
155     }
156 greg 2.3 /* open ambient file */
157 greg 2.47 if ((ambfp = fopen(ambfile, "r+")) == NULL)
158     readonly = (ambfp = fopen(ambfile, "r")) != NULL;
159 gwlarson 2.46 if (ambfp != NULL) {
160     initambfile(0); /* file exists */
161 greg 2.37 pos = ftell(ambfp);
162 greg 2.19 while (readambval(&amb, ambfp))
163 greg 2.21 avinsert(avstore(&amb));
164 gwlarson 2.46 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     fclose(ambfp); /* close file so no writes */
171     ambfp = NULL;
172     return; /* avoid ambsync() */
173     }
174     /* align file pointer */
175 greg 2.37 pos += (long)nambvals*AMBVALSIZ;
176 greg 2.55 flen = lseek(fileno(ambfp), (off_t)0, SEEK_END);
177 greg 2.37 if (flen != pos) {
178 greg 2.42 sprintf(errmsg,
179 greg 2.37 "ignoring last %ld values in ambient file (corrupted)",
180     (flen - pos)/AMBVALSIZ);
181 greg 2.42 error(WARNING, errmsg);
182 greg 2.37 fseek(ambfp, pos, 0);
183 schorsch 2.51 #ifndef _WIN32 /* XXX we need a replacement for that one */
184 greg 2.47 ftruncate(fileno(ambfp), (off_t)pos);
185 schorsch 2.51 #endif
186 greg 2.37 }
187 greg 2.47 } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
188 gwlarson 2.46 initambfile(1); /* else create new file */
189     } else {
190 greg 2.47 sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
191 greg 2.19 error(SYSTEM, errmsg);
192 greg 2.16 }
193 greg 2.19 nunflshed++; /* lie */
194     ambsync();
195 greg 1.8 }
196    
197    
198 schorsch 2.56 extern void
199     ambdone(void) /* close ambient file and free memory */
200 greg 2.47 {
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 schorsch 2.56 extern void
225     ambnotify( /* record new modifier */
226     OBJECT obj
227     )
228 greg 1.8 {
229 greg 1.11 static int hitlimit = 0;
230 greg 2.47 register OBJREC *o;
231 greg 1.8 register char **amblp;
232    
233 greg 2.47 if (obj == OVOID) { /* starting over */
234     ambset[0] = 0;
235     hitlimit = 0;
236     return;
237     }
238     o = objptr(obj);
239 greg 1.11 if (hitlimit || !ismodifier(o->otype))
240 greg 1.8 return;
241     for (amblp = amblist; *amblp != NULL; amblp++)
242     if (!strcmp(o->oname, *amblp)) {
243 greg 1.11 if (ambset[0] >= MAXASET) {
244     error(WARNING, "too many modifiers in ambient list");
245     hitlimit++;
246     return; /* should this be fatal? */
247     }
248 greg 1.8 insertelem(ambset, obj);
249     return;
250 greg 1.1 }
251     }
252    
253    
254 schorsch 2.56 extern void
255     ambient( /* compute ambient component for ray */
256     COLOR acol,
257     register RAY *r,
258     FVECT nrm
259     )
260 greg 1.1 {
261     static int rdepth = 0; /* ambient recursion */
262 gregl 2.43 double d, l;
263 greg 1.1
264     if (ambdiv <= 0) /* no ambient calculation */
265     goto dumbamb;
266     /* check number of bounces */
267 greg 1.16 if (rdepth >= ambounce)
268 greg 1.1 goto dumbamb;
269     /* check ambient list */
270     if (ambincl != -1 && r->ro != NULL &&
271     ambincl != inset(ambset, r->ro->omod))
272     goto dumbamb;
273    
274     if (ambacc <= FTINY) { /* no ambient storage */
275 greg 1.16 rdepth++;
276     d = doambient(acol, r, r->rweight, NULL, NULL);
277     rdepth--;
278 greg 2.32 if (d <= FTINY)
279 greg 1.1 goto dumbamb;
280 greg 1.16 return;
281 greg 1.1 }
282 greg 2.40
283     if (tracktime) /* sort to minimize thrashing */
284     sortambvals(0);
285 greg 1.1 /* get ambient value */
286     setcolor(acol, 0.0, 0.0, 0.0);
287 greg 2.34 d = sumambient(acol, r, nrm, rdepth,
288 greg 1.16 &atrunk, thescene.cuorg, thescene.cusize);
289 greg 2.32 if (d > FTINY) {
290 greg 1.16 scalecolor(acol, 1.0/d);
291 greg 2.32 return;
292 greg 1.16 }
293 greg 2.33 rdepth++; /* need to cache new value */
294 greg 2.34 d = makeambient(acol, r, nrm, rdepth-1);
295 greg 2.32 rdepth--;
296 greg 1.16 if (d > FTINY)
297     return;
298 greg 1.1 dumbamb: /* return global value */
299     copycolor(acol, ambval);
300 schorsch 2.54 if ((ambvwt <= 0) | (navsum == 0))
301 greg 2.32 return;
302 gregl 2.43 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 greg 1.1 }
313    
314    
315 schorsch 2.56 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 greg 1.1 {
326 greg 2.12 double d, e1, e2, wt, wsum;
327 greg 1.1 COLOR ct;
328     FVECT ck0;
329     int i;
330     register int j;
331 greg 2.12 register AMBVAL *av;
332 greg 2.29
333     wsum = 0.0;
334 greg 1.7 /* do this node */
335 greg 1.1 for (av = at->alist; av != NULL; av = av->next) {
336 greg 2.47 double rn_dot = -2.0;
337 greg 2.26 if (tracktime)
338 greg 2.40 av->latick = ambclock;
339 greg 1.1 /*
340 greg 1.16 * Ambient level test.
341 greg 1.1 */
342 greg 2.23 if (av->lvl > al) /* list sorted, so this works */
343     break;
344     if (av->weight < r->rweight-FTINY)
345 greg 1.1 continue;
346     /*
347     * Ambient radius test.
348     */
349 greg 2.29 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 greg 1.1 e1 /= av->rad * av->rad;
356     if (e1 > ambacc*ambacc*1.21)
357     continue;
358     /*
359 greg 2.47 * Direction test using closest normal.
360 greg 1.1 */
361 greg 2.47 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 greg 1.1 if (e2 < 0.0) e2 = 0.0;
373     if (e1 + e2 > ambacc*ambacc*1.21)
374     continue;
375     /*
376     * Ray behind test.
377     */
378     d = 0.0;
379     for (j = 0; j < 3; j++)
380     d += (r->rop[j] - av->pos[j]) *
381     (av->dir[j] + r->ron[j]);
382 greg 1.18 if (d*0.5 < -minarad*ambacc-.001)
383 greg 1.1 continue;
384     /*
385     * Jittering final test reduces image artifacts.
386     */
387 greg 2.47 e1 = sqrt(e1);
388     e2 = sqrt(e2);
389     wt = e1 + e2;
390 greg 2.31 if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
391 greg 1.1 continue;
392 greg 2.47 /*
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 greg 1.1 if (wt <= 1e-3)
400     wt = 1e3;
401     else
402     wt = 1.0 / wt;
403     wsum += wt;
404 greg 2.34 extambient(ct, av, r->rop, rn);
405 greg 1.1 scalecolor(ct, wt);
406     addcolor(acol, ct);
407 greg 1.7 }
408     if (at->kid == NULL)
409     return(wsum);
410     /* do children */
411     s *= 0.5;
412     for (i = 0; i < 8; i++) {
413     for (j = 0; j < 3; j++) {
414     ck0[j] = c0[j];
415     if (1<<j & i)
416     ck0[j] += s;
417     if (r->rop[j] < ck0[j] - OCTSCALE*s)
418     break;
419     if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
420     break;
421     }
422     if (j == 3)
423 greg 2.34 wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
424 greg 1.1 }
425     return(wsum);
426     }
427    
428    
429 schorsch 2.56 extern double
430     makeambient( /* make a new ambient value */
431     COLOR acol,
432     register RAY *r,
433     FVECT rn,
434     int al
435     )
436 greg 1.1 {
437 greg 2.12 AMBVAL amb;
438 greg 1.14 FVECT gp, gd;
439 greg 1.16 /* compute weight */
440     amb.weight = pow(AVGREFL, (double)al);
441 greg 2.33 if (r->rweight < 0.1*amb.weight) /* heuristic */
442 greg 1.16 amb.weight = r->rweight;
443     /* compute ambient */
444     amb.rad = doambient(acol, r, amb.weight, gp, gd);
445 greg 2.33 if (amb.rad <= FTINY)
446 greg 1.1 return(0.0);
447     /* store it */
448     VCOPY(amb.pos, r->rop);
449     VCOPY(amb.dir, r->ron);
450 greg 1.16 amb.lvl = al;
451 greg 1.1 copycolor(amb.val, acol);
452 greg 1.14 VCOPY(amb.gpos, gp);
453     VCOPY(amb.gdir, gd);
454 greg 1.1 /* insert into tree */
455 greg 2.7 avsave(&amb); /* and save to file */
456 greg 2.34 if (rn != r->ron)
457     extambient(acol, &amb, r->rop, rn); /* texture */
458 greg 1.1 return(amb.rad);
459 greg 1.15 }
460    
461    
462 schorsch 2.56 extern void
463     extambient( /* extrapolate value at pv, nv */
464     COLOR cr,
465     register AMBVAL *ap,
466     FVECT pv,
467     FVECT nv
468     )
469 greg 1.15 {
470 gwlarson 2.45 FVECT v1;
471 greg 1.15 register int i;
472 greg 2.12 double d;
473 greg 1.15
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 gwlarson 2.45 VCROSS(v1, ap->dir, nv);
480     d += DOT(ap->gdir, v1);
481 greg 1.15 if (d <= 0.0) {
482     setcolor(cr, 0.0, 0.0, 0.0);
483     return;
484     }
485     copycolor(cr, ap->val);
486     scalecolor(cr, d);
487 greg 1.1 }
488    
489    
490 greg 2.47 static void
491 schorsch 2.56 initambfile( /* initialize ambient file */
492     int creat
493     )
494 greg 2.9 {
495 greg 2.47 extern char *progname, *octname;
496     static char *mybuf = NULL;
497 greg 2.9
498 greg 2.19 #ifdef F_SETLKW
499     aflock(creat ? F_WRLCK : F_RDLCK);
500     #endif
501 schorsch 2.50 SET_FILE_BINARY(ambfp);
502 greg 2.47 if (mybuf == NULL)
503     mybuf = (char *)bmalloc(BUFSIZ+8);
504     setbuf(ambfp, mybuf);
505 greg 2.9 if (creat) { /* new file */
506 greg 2.24 newheader("RADIANCE", ambfp);
507 greg 2.41 fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
508 greg 2.9 progname, colval(ambval,RED),
509     colval(ambval,GRN), colval(ambval,BLU),
510 greg 2.41 ambvwt, ambounce, ambacc);
511 greg 2.47 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 greg 2.9 fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
518 greg 2.47 fputnow(ambfp);
519 greg 2.9 fputformat(AMBFMT, ambfp);
520     putc('\n', ambfp);
521     putambmagic(ambfp);
522 greg 2.17 } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
523     error(USER, "bad ambient file");
524 greg 2.9 }
525    
526    
527 greg 2.47 static void
528 schorsch 2.56 avsave( /* insert and save an ambient value */
529     AMBVAL *av
530     )
531 greg 1.1 {
532 greg 2.21 avinsert(avstore(av));
533 greg 1.1 if (ambfp == NULL)
534     return;
535 greg 2.5 if (writambval(av, ambfp) < 0)
536 greg 1.1 goto writerr;
537 greg 2.16 if (++nunflshed >= AMBFLUSH)
538 greg 2.7 if (ambsync() == EOF)
539 greg 1.1 goto writerr;
540     return;
541     writerr:
542 greg 2.47 error(SYSTEM, "error writing to ambient file");
543 greg 1.1 }
544    
545    
546 greg 2.20 static AMBVAL *
547 schorsch 2.56 avstore( /* allocate memory and store aval */
548     register AMBVAL *aval
549     )
550 greg 2.20 {
551     register AMBVAL *av;
552 gregl 2.43 double d;
553 greg 2.20
554     if ((av = newambval()) == NULL)
555     error(SYSTEM, "out of memory in avstore");
556 schorsch 2.53 *av = *aval;
557 greg 2.26 av->latick = ambclock;
558     av->next = NULL;
559     nambvals++;
560 gregl 2.43 d = bright(av->val);
561     if (d > FTINY) { /* add to log sum for averaging */
562     avsum += log(d);
563     navsum++;
564     }
565 greg 2.20 return(av);
566     }
567    
568    
569 greg 2.26 #define ATALLOCSZ 512 /* #/8 trees to allocate at once */
570    
571     static AMBTREE *atfreelist = NULL; /* free ambient tree structures */
572    
573    
574 greg 2.47 static AMBTREE *
575 schorsch 2.56 newambtree(void) /* allocate 8 ambient tree structs */
576 greg 2.26 {
577     register AMBTREE *atp, *upperlim;
578    
579     if (atfreelist == NULL) { /* get more nodes */
580 greg 2.47 atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
581 greg 2.26 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 schorsch 2.52 memset((char *)atp, '\0', 8*sizeof(AMBTREE));
592 greg 2.26 return(atp);
593     }
594    
595    
596 greg 2.47 static void
597 schorsch 2.56 freeambtree( /* free 8 ambient tree structs */
598     AMBTREE *atp
599     )
600 greg 2.26 {
601     atp->kid = atfreelist;
602     atfreelist = atp;
603     }
604    
605    
606 greg 2.47 static void
607 schorsch 2.56 avinsert( /* insert ambient value in our tree */
608     void *av
609     )
610 greg 1.1 {
611 greg 2.21 register AMBTREE *at;
612 greg 2.23 register AMBVAL *ap;
613     AMBVAL avh;
614 greg 1.1 FVECT ck0;
615 greg 2.21 double s;
616 greg 1.1 int branch;
617     register int i;
618    
619 schorsch 2.56 if (((AMBVAL*)av)->rad <= FTINY)
620 greg 2.20 error(CONSISTENCY, "zero ambient radius in avinsert");
621 greg 2.21 at = &atrunk;
622     VCOPY(ck0, thescene.cuorg);
623     s = thescene.cusize;
624 schorsch 2.56 while (s*(OCTSCALE/2) > ((AMBVAL*)av)->rad*ambacc) {
625 greg 1.1 if (at->kid == NULL)
626     if ((at->kid = newambtree()) == NULL)
627 greg 2.20 error(SYSTEM, "out of memory in avinsert");
628 greg 1.1 s *= 0.5;
629     branch = 0;
630     for (i = 0; i < 3; i++)
631 schorsch 2.56 if (((AMBVAL*)av)->pos[i] > ck0[i] + s) {
632 greg 1.1 ck0[i] += s;
633     branch |= 1 << i;
634     }
635     at = at->kid + branch;
636     }
637 greg 2.23 avh.next = at->alist; /* order by increasing level */
638     for (ap = &avh; ap->next != NULL; ap = ap->next)
639 schorsch 2.56 if (ap->next->lvl >= ((AMBVAL*)av)->lvl)
640 greg 2.23 break;
641 schorsch 2.56 ((AMBVAL*)av)->next = ap->next;
642     ap->next = (AMBVAL*)av;
643 greg 2.23 at->alist = avh.next;
644 greg 2.7 }
645    
646    
647 greg 2.47 static void
648 schorsch 2.56 unloadatree( /* unload an ambient value tree */
649     register AMBTREE *at,
650     unloadtf_t *f
651     )
652 greg 2.20 {
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 greg 2.26 (*f)(av);
659 greg 2.20 }
660 greg 2.21 if (at->kid == NULL)
661     return;
662 greg 2.20 for (i = 0; i < 8; i++) /* transfer and free children */
663 greg 2.26 unloadatree(at->kid+i, f);
664 greg 2.20 freeambtree(at->kid);
665 greg 2.26 at->kid = NULL;
666     }
667    
668    
669 greg 2.39 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 greg 2.26 static int i_avlist; /* index for lists */
675    
676 schorsch 2.56 static int alatcmp(const void *av1, const void *av2);
677 greg 2.26
678 schorsch 2.56 static void
679     av2list(
680     void *av
681     )
682 greg 2.26 {
683 greg 2.27 #ifdef DEBUG
684 greg 2.26 if (i_avlist >= nambvals)
685     error(CONSISTENCY, "too many ambient values in av2list1");
686 greg 2.27 #endif
687 schorsch 2.56 avlist1[i_avlist].p = avlist2[i_avlist] = (AMBVAL*)av;
688     avlist1[i_avlist++].t = ((AMBVAL*)av)->latick;
689 greg 2.26 }
690    
691    
692     static int
693 schorsch 2.56 alatcmp( /* compare ambient values for MRA */
694     const void *av1,
695     const void *av2
696     )
697 greg 2.26 {
698 schorsch 2.56 register long lc = ((struct avl *)av2)->t - ((struct avl *)av1)->t;
699 greg 2.38 return(lc<0 ? -1 : lc>0 ? 1 : 0);
700 greg 2.26 }
701    
702    
703 greg 2.47 /* 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 greg 2.26 static int
710 schorsch 2.56 aposcmp( /* compare ambient value positions */
711     const void *avp1,
712     const void *avp2
713     )
714 greg 2.26 {
715 greg 2.47 register long diff = *(char * const *)avp1 - *(char * const *)avp2;
716     if (diff < 0)
717     return(-1);
718     return(diff > 0);
719 greg 2.26 }
720    
721 greg 2.39 #if 1
722 greg 2.27 static int
723 schorsch 2.56 avlmemi( /* find list position from address */
724     AMBVAL *avaddr
725     )
726 greg 2.27 {
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 greg 2.47 static void
742 schorsch 2.56 sortambvals( /* resort ambient values */
743     int always
744     )
745 greg 2.26 {
746     AMBTREE oldatrunk;
747     AMBVAL tav, *tap, *pnext;
748     register int i, j;
749 greg 2.28 /* see if it's time yet */
750 greg 2.40 if (!always && (ambclock++ < lastsort+sortintvl ||
751 greg 2.28 nambvals < SORT_THRESH))
752     return;
753 greg 2.26 /*
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 greg 2.27 if (tracktime) { /* allocate pointer arrays to sort */
769 greg 2.26 avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
770 greg 2.39 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 greg 2.47 free((void *)avlist2);
778 greg 2.27 if (always) { /* rebuild without sorting */
779 schorsch 2.53 oldatrunk = atrunk;
780 greg 2.27 atrunk.alist = NULL;
781     atrunk.kid = NULL;
782     unloadatree(&oldatrunk, avinsert);
783     }
784 greg 2.26 } 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 greg 2.27 * everyone at least twice, and this is an expensive process
791 greg 2.26 * when we're thrashing, which is when we need to do it.
792     */
793 greg 2.27 #ifdef DEBUG
794 greg 2.29 sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
795     nambvals, ambclock);
796 greg 2.27 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 greg 2.39 qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
805 greg 2.26 qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
806     for (i = 0; i < nambvals; i++) {
807 greg 2.39 if (avlist1[i].p == NULL)
808 greg 2.26 continue;
809     tap = avlist2[i];
810 schorsch 2.53 tav = *tap;
811 greg 2.39 for (j = i; (pnext = avlist1[j].p) != tap;
812 greg 2.27 j = avlmemi(pnext)) {
813 schorsch 2.53 *(avlist2[j]) = *pnext;
814 greg 2.26 avinsert(avlist2[j]);
815 greg 2.39 avlist1[j].p = NULL;
816 greg 2.26 }
817 schorsch 2.53 *(avlist2[j]) = tav;
818 greg 2.26 avinsert(avlist2[j]);
819 greg 2.39 avlist1[j].p = NULL;
820 greg 2.26 }
821 greg 2.47 free((void *)avlist1);
822     free((void *)avlist2);
823 greg 2.28 /* compute new sort interval */
824     sortintvl = ambclock - lastsort;
825 greg 2.32 if (sortintvl >= MAX_SORT_INTVL/2)
826 greg 2.28 sortintvl = MAX_SORT_INTVL;
827     else
828 greg 2.26 sortintvl <<= 1; /* wait twice as long next */
829 greg 2.27 #ifdef DEBUG
830     eputs("done\n");
831     #endif
832 greg 2.26 }
833     if (ambclock >= MAXACLOCK)
834     ambclock = MAXACLOCK/2;
835     lastsort = ambclock;
836 greg 2.20 }
837    
838    
839 greg 2.18 #ifdef F_SETLKW
840 greg 2.10
841 greg 2.47 static void
842 schorsch 2.56 aflock( /* lock/unlock ambient file */
843     int typ
844     )
845 greg 2.19 {
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 schorsch 2.56 extern int
855     ambsync(void) /* synchronize ambient file */
856 greg 2.7 {
857 greg 2.15 long flen;
858 greg 2.12 AMBVAL avs;
859 greg 2.7 register int n;
860 greg 2.16
861     if (nunflshed == 0)
862     return(0);
863 greg 2.19 if (lastpos < 0) /* initializing (locked in initambfile) */
864     goto syncend;
865 greg 2.7 /* gain exclusive access */
866 greg 2.19 aflock(F_WRLCK);
867 greg 2.7 /* see if file has grown */
868 greg 2.55 if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
869 greg 2.21 goto seekerr;
870 schorsch 2.54 if ( (n = flen - lastpos) ) { /* file has grown */
871 greg 2.17 if (ambinp == NULL) { /* use duplicate filedes */
872     ambinp = fdopen(dup(fileno(ambfp)), "r");
873 greg 2.14 if (ambinp == NULL)
874 greg 2.17 error(SYSTEM, "fdopen failed in ambsync");
875 greg 2.14 }
876 greg 2.15 if (fseek(ambinp, lastpos, 0) < 0)
877 greg 2.21 goto seekerr;
878 greg 2.15 while (n >= AMBVALSIZ) { /* load contributed values */
879 greg 2.37 if (!readambval(&avs, ambinp)) {
880     sprintf(errmsg,
881 greg 2.47 "ambient file \"%s\" corrupted near character %ld",
882     ambfile, flen - n);
883 greg 2.37 error(WARNING, errmsg);
884     break;
885     }
886 greg 2.21 avinsert(avstore(&avs));
887 greg 2.15 n -= AMBVALSIZ;
888     }
889 greg 2.22 /*** seek always as safety measure
890     if (n) ***/ /* alignment */
891 greg 2.55 if (lseek(fileno(ambfp), (off_t)(flen-n), SEEK_SET) < 0)
892 greg 2.21 goto seekerr;
893 greg 2.7 }
894 greg 2.21 #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 greg 2.15 syncend:
903 greg 2.7 n = fflush(ambfp); /* calls write() at last */
904 greg 2.55 if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
905 greg 2.21 goto seekerr;
906 greg 2.19 aflock(F_UNLCK); /* release file */
907 greg 2.16 nunflshed = 0;
908 greg 2.7 return(n);
909 greg 2.21 seekerr:
910     error(SYSTEM, "seek failed in ambsync");
911 schorsch 2.56 return -1; /* pro forma return */
912 greg 2.18 }
913    
914     #else
915    
916 schorsch 2.56 extern int
917     ambsync(void) /* flush ambient file */
918 greg 2.18 {
919     if (nunflshed == 0)
920     return(0);
921     nunflshed = 0;
922     return(fflush(ambfp));
923 greg 1.1 }
924 greg 2.10
925     #endif