ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.105
Committed: Tue Jan 9 05:01:15 2018 UTC (6 years, 4 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad5R2
Changes since 2.104: +5 -2 lines
Log Message:
Made proximity test (plugaleak) more robust with transparent surfaces, etc.

File Contents

# User Rev Content
1 greg 2.105 static const char RCSid[] = "$Id: ambient.c,v 2.104 2017/01/27 22:00:49 greg Exp $";
2 greg 1.1 /*
3     * ambient.c - routines dealing with ambient (inter-reflected) component.
4 greg 2.47 *
5     * Declarations of external symbols in ambient.h
6     */
7    
8 greg 2.48 #include "copyright.h"
9 greg 1.1
10 schorsch 2.52 #include <string.h>
11    
12 schorsch 2.50 #include "platform.h"
13 greg 1.1 #include "ray.h"
14 greg 1.8 #include "otypes.h"
15 greg 2.105 #include "otspecial.h"
16 schorsch 2.56 #include "resolu.h"
17 greg 1.14 #include "ambient.h"
18 greg 2.105 #include "source.h"
19 greg 1.1 #include "random.h"
20 greg 2.94 #include "pmapamb.h"
21 greg 1.1
22 greg 2.32 #ifndef OCTSCALE
23 greg 2.29 #define OCTSCALE 1.0 /* ceil((valid rad.)/(cube size)) */
24 greg 2.32 #endif
25 greg 1.1
26 greg 2.27 extern char *shm_boundary; /* memory sharing boundary */
27 greg 2.26
28 greg 2.57 #ifndef MAXASET
29 greg 2.67 #define MAXASET 4095 /* maximum number of elements in ambient set */
30 greg 2.57 #endif
31 greg 2.12 OBJECT ambset[MAXASET+1]={0}; /* ambient include/exclude set */
32 greg 1.1
33 greg 2.12 double maxarad; /* maximum ambient radius */
34     double minarad; /* minimum ambient radius */
35 greg 1.1
36 greg 2.12 static AMBTREE atrunk; /* our ambient trunk node */
37 greg 1.1
38     static FILE *ambfp = NULL; /* ambient file pointer */
39 greg 2.16 static int nunflshed = 0; /* number of unflushed ambient values */
40 greg 1.1
41 greg 2.26 #ifndef SORT_THRESH
42 greg 2.49 #ifdef SMLMEM
43 greg 2.71 #define SORT_THRESH ((16L<<20)/sizeof(AMBVAL))
44 greg 2.49 #else
45 greg 2.71 #define SORT_THRESH ((64L<<20)/sizeof(AMBVAL))
46 greg 2.26 #endif
47     #endif
48     #ifndef SORT_INTVL
49 greg 2.41 #define SORT_INTVL (SORT_THRESH<<1)
50 greg 2.26 #endif
51 greg 2.28 #ifndef MAX_SORT_INTVL
52 greg 2.41 #define MAX_SORT_INTVL (SORT_INTVL<<6)
53 greg 2.28 #endif
54 greg 2.26
55 greg 2.74
56 gregl 2.43 static double avsum = 0.; /* computed ambient value sum (log) */
57     static unsigned int navsum = 0; /* number of values in avsum */
58 greg 2.35 static unsigned int nambvals = 0; /* total number of indirect values */
59     static unsigned int nambshare = 0; /* number of values from file */
60 greg 2.27 static unsigned long ambclock = 0; /* ambient access clock */
61     static unsigned long lastsort = 0; /* time of last value sort */
62 greg 2.26 static long sortintvl = SORT_INTVL; /* time until next sort */
63 greg 2.47 static FILE *ambinp = NULL; /* auxiliary file for input */
64     static long lastpos = -1; /* last flush position */
65 greg 2.26
66     #define MAXACLOCK (1L<<30) /* clock turnover value */
67 greg 2.27 /*
68     * Track access times unless we are sharing ambient values
69     * through memory on a multiprocessor, when we want to avoid
70 greg 2.35 * claiming our own memory (copy on write). Go ahead anyway
71     * if more than two thirds of our values are unshared.
72 gregl 2.43 * Compile with -Dtracktime=0 to turn this code off.
73 greg 2.27 */
74 gregl 2.43 #ifndef tracktime
75 greg 2.35 #define tracktime (shm_boundary == NULL || nambvals > 3*nambshare)
76 gregl 2.43 #endif
77 greg 2.26
78 greg 2.12 #define AMBFLUSH (BUFSIZ/AMBVALSIZ)
79 greg 2.6
80 greg 2.47 #define newambval() (AMBVAL *)malloc(sizeof(AMBVAL))
81 greg 1.1
82 schorsch 2.56 static void initambfile(int creat);
83     static void avsave(AMBVAL *av);
84     static AMBVAL *avstore(AMBVAL *aval);
85     static AMBTREE *newambtree(void);
86     static void freeambtree(AMBTREE *atp);
87    
88 greg 2.71 typedef void unloadtf_t(AMBVAL *);
89 schorsch 2.56 static unloadtf_t avinsert;
90     static unloadtf_t av2list;
91 greg 2.71 static unloadtf_t avfree;
92 schorsch 2.56 static void unloadatree(AMBTREE *at, unloadtf_t *f);
93    
94     static int aposcmp(const void *avp1, const void *avp2);
95     static int avlmemi(AMBVAL *avaddr);
96     static void sortambvals(int always);
97    
98 greg 2.19 #ifdef F_SETLKW
99 schorsch 2.56 static void aflock(int typ);
100 greg 2.19 #endif
101 greg 1.1
102 greg 2.7
103 greg 2.71 void
104 schorsch 2.56 setambres( /* set ambient resolution */
105     int ar
106     )
107 greg 2.3 {
108 greg 2.21 ambres = ar < 0 ? 0 : ar; /* may be done already */
109 greg 2.3 /* set min & max radii */
110     if (ar <= 0) {
111 greg 2.25 minarad = 0;
112 greg 2.89 maxarad = thescene.cusize*0.2;
113 greg 2.3 } else {
114     minarad = thescene.cusize / ar;
115 greg 2.83 maxarad = 64.0 * minarad; /* heuristic */
116 greg 2.89 if (maxarad > thescene.cusize*0.2)
117     maxarad = thescene.cusize*0.2;
118 greg 2.3 }
119 greg 2.25 if (minarad <= FTINY)
120 greg 2.83 minarad = 10.0*FTINY;
121 greg 2.25 if (maxarad <= minarad)
122 greg 2.83 maxarad = 64.0 * minarad;
123 greg 2.3 }
124    
125    
126 greg 2.71 void
127 schorsch 2.56 setambacc( /* set ambient accuracy */
128     double newa
129     )
130 greg 2.20 {
131 greg 2.84 static double olda; /* remember previous setting here */
132 greg 2.82
133     newa *= (newa > 0);
134     if (fabs(newa - olda) >= .05*(newa + olda)) {
135 greg 2.84 ambacc = newa;
136 greg 2.74 if (nambvals > 0)
137     sortambvals(1); /* rebuild tree */
138     }
139 greg 2.20 }
140    
141    
142 greg 2.71 void
143 schorsch 2.56 setambient(void) /* initialize calculation */
144 greg 1.1 {
145 gwlarson 2.46 int readonly = 0;
146 greg 2.66 long flen;
147 greg 2.12 AMBVAL amb;
148 greg 2.47 /* make sure we're fresh */
149     ambdone();
150 greg 2.3 /* init ambient limits */
151     setambres(ambres);
152 greg 2.82 setambacc(ambacc);
153 greg 2.47 if (ambfile == NULL || !ambfile[0])
154 greg 2.19 return;
155 greg 2.20 if (ambacc <= FTINY) {
156 greg 2.21 sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
157 greg 2.47 ambfile);
158 greg 2.20 error(WARNING, errmsg);
159     return;
160     }
161 greg 2.3 /* open ambient file */
162 greg 2.47 if ((ambfp = fopen(ambfile, "r+")) == NULL)
163     readonly = (ambfp = fopen(ambfile, "r")) != NULL;
164 gwlarson 2.46 if (ambfp != NULL) {
165     initambfile(0); /* file exists */
166 greg 2.66 lastpos = ftell(ambfp);
167 greg 2.19 while (readambval(&amb, ambfp))
168 greg 2.88 avstore(&amb);
169 gwlarson 2.46 nambshare = nambvals; /* share loaded values */
170     if (readonly) {
171     sprintf(errmsg,
172     "loaded %u values from read-only ambient file",
173     nambvals);
174     error(WARNING, errmsg);
175     fclose(ambfp); /* close file so no writes */
176     ambfp = NULL;
177     return; /* avoid ambsync() */
178     }
179     /* align file pointer */
180 greg 2.66 lastpos += (long)nambvals*AMBVALSIZ;
181 greg 2.55 flen = lseek(fileno(ambfp), (off_t)0, SEEK_END);
182 greg 2.66 if (flen != lastpos) {
183 greg 2.42 sprintf(errmsg,
184 greg 2.37 "ignoring last %ld values in ambient file (corrupted)",
185 greg 2.66 (flen - lastpos)/AMBVALSIZ);
186 greg 2.42 error(WARNING, errmsg);
187 greg 2.66 fseek(ambfp, lastpos, SEEK_SET);
188     ftruncate(fileno(ambfp), (off_t)lastpos);
189 greg 2.37 }
190 greg 2.47 } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
191 gwlarson 2.46 initambfile(1); /* else create new file */
192 greg 2.68 fflush(ambfp);
193 greg 2.66 lastpos = ftell(ambfp);
194 gwlarson 2.46 } else {
195 greg 2.47 sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
196 greg 2.19 error(SYSTEM, errmsg);
197 greg 2.16 }
198 greg 2.68 #ifdef F_SETLKW
199     aflock(F_UNLCK); /* release file */
200     #endif
201 greg 1.8 }
202    
203    
204 greg 2.71 void
205 schorsch 2.56 ambdone(void) /* close ambient file and free memory */
206 greg 2.47 {
207     if (ambfp != NULL) { /* close ambient file */
208     ambsync();
209     fclose(ambfp);
210     ambfp = NULL;
211     if (ambinp != NULL) {
212     fclose(ambinp);
213     ambinp = NULL;
214     }
215     lastpos = -1;
216     }
217     /* free ambient tree */
218 greg 2.99 unloadatree(&atrunk, avfree);
219 greg 2.47 /* reset state variables */
220     avsum = 0.;
221     navsum = 0;
222     nambvals = 0;
223     nambshare = 0;
224     ambclock = 0;
225     lastsort = 0;
226     sortintvl = SORT_INTVL;
227     }
228    
229    
230 greg 2.71 void
231 schorsch 2.56 ambnotify( /* record new modifier */
232     OBJECT obj
233     )
234 greg 1.8 {
235 greg 1.11 static int hitlimit = 0;
236 greg 2.70 OBJREC *o;
237     char **amblp;
238 greg 1.8
239 greg 2.47 if (obj == OVOID) { /* starting over */
240     ambset[0] = 0;
241     hitlimit = 0;
242     return;
243     }
244     o = objptr(obj);
245 greg 1.11 if (hitlimit || !ismodifier(o->otype))
246 greg 1.8 return;
247     for (amblp = amblist; *amblp != NULL; amblp++)
248     if (!strcmp(o->oname, *amblp)) {
249 greg 1.11 if (ambset[0] >= MAXASET) {
250     error(WARNING, "too many modifiers in ambient list");
251     hitlimit++;
252     return; /* should this be fatal? */
253     }
254 greg 1.8 insertelem(ambset, obj);
255     return;
256 greg 1.1 }
257     }
258    
259 greg 2.71 /************ THE FOLLOWING ROUTINES DIFFER BETWEEN NEW & OLD ***************/
260    
261 greg 2.91 #ifndef OLDAMB
262 greg 2.71
263 greg 2.72 #define tfunc(lwr, x, upr) (((x)-(lwr))/((upr)-(lwr)))
264 greg 1.1
265 greg 2.86 static int plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang);
266 greg 2.72 static double sumambient(COLOR acol, RAY *r, FVECT rn, int al,
267     AMBTREE *at, FVECT c0, double s);
268     static int makeambient(COLOR acol, RAY *r, FVECT rn, int al);
269 greg 2.92 static int extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
270 greg 2.72 FVECT uvw[3]);
271 greg 2.71
272     void
273     multambient( /* compute ambient component & multiply by coef. */
274     COLOR aval,
275     RAY *r,
276     FVECT nrm
277     )
278     {
279     static int rdepth = 0; /* ambient recursion */
280 greg 2.94 COLOR acol, caustic;
281 greg 2.103 int i, ok;
282 greg 2.71 double d, l;
283    
284 greg 2.94 /* PMAP: Factor in ambient from photon map, if enabled and ray is
285     * ambient. Return as all ambient components accounted for, else
286     * continue. */
287     if (ambPmap(aval, r, rdepth))
288     return;
289    
290     /* PMAP: Factor in specular-diffuse ambient (caustics) from photon
291     * map, if enabled and ray is primary, else caustic is zero. Continue
292     * with RADIANCE ambient calculation */
293     copycolor(caustic, aval);
294     ambPmapCaustic(caustic, r, rdepth);
295    
296 greg 2.71 if (ambdiv <= 0) /* no ambient calculation */
297     goto dumbamb;
298     /* check number of bounces */
299     if (rdepth >= ambounce)
300     goto dumbamb;
301     /* check ambient list */
302     if (ambincl != -1 && r->ro != NULL &&
303     ambincl != inset(ambset, r->ro->omod))
304     goto dumbamb;
305    
306     if (ambacc <= FTINY) { /* no ambient storage */
307 greg 2.103 FVECT uvd[2];
308     float dgrad[2], *dgp = NULL;
309    
310     if (nrm != r->ron && DOT(nrm,r->ron) < 0.9999)
311     dgp = dgrad; /* compute rotational grad. */
312 greg 2.71 copycolor(acol, aval);
313     rdepth++;
314 greg 2.86 ok = doambient(acol, r, r->rweight,
315 greg 2.103 uvd, NULL, NULL, dgp, NULL);
316 greg 2.71 rdepth--;
317     if (!ok)
318     goto dumbamb;
319 greg 2.103 if ((ok > 0) & (dgp != NULL)) { /* apply texture */
320     FVECT v1;
321     VCROSS(v1, r->ron, nrm);
322     d = 1.0;
323     for (i = 3; i--; )
324     d += v1[i] * (dgp[0]*uvd[0][i] + dgp[1]*uvd[1][i]);
325     if (d >= 0.05)
326     scalecolor(acol, d);
327     }
328 greg 2.71 copycolor(aval, acol);
329 greg 2.94
330     /* PMAP: add in caustic */
331     addcolor(aval, caustic);
332 greg 2.71 return;
333     }
334    
335     if (tracktime) /* sort to minimize thrashing */
336     sortambvals(0);
337     /* interpolate ambient value */
338     setcolor(acol, 0.0, 0.0, 0.0);
339     d = sumambient(acol, r, nrm, rdepth,
340     &atrunk, thescene.cuorg, thescene.cusize);
341 greg 2.94
342 greg 2.71 if (d > FTINY) {
343     d = 1.0/d;
344     scalecolor(acol, d);
345     multcolor(aval, acol);
346 greg 2.94
347     /* PMAP: add in caustic */
348     addcolor(aval, caustic);
349 greg 2.71 return;
350     }
351 greg 2.94
352 greg 2.71 rdepth++; /* need to cache new value */
353     ok = makeambient(acol, r, nrm, rdepth-1);
354     rdepth--;
355 greg 2.94
356 greg 2.71 if (ok) {
357 greg 2.73 multcolor(aval, acol); /* computed new value */
358 greg 2.94
359     /* PMAP: add in caustic */
360     addcolor(aval, caustic);
361 greg 2.71 return;
362     }
363 greg 2.94
364 greg 2.71 dumbamb: /* return global value */
365     if ((ambvwt <= 0) | (navsum == 0)) {
366     multcolor(aval, ambval);
367 greg 2.94
368     /* PMAP: add in caustic */
369     addcolor(aval, caustic);
370 greg 2.71 return;
371     }
372 greg 2.94
373     l = bright(ambval); /* average in computations */
374 greg 2.71 if (l > FTINY) {
375     d = (log(l)*(double)ambvwt + avsum) /
376     (double)(ambvwt + navsum);
377     d = exp(d) / l;
378     scalecolor(aval, d);
379     multcolor(aval, ambval); /* apply color of ambval */
380     } else {
381     d = exp( avsum / (double)navsum );
382     scalecolor(aval, d); /* neutral color */
383     }
384     }
385    
386    
387 greg 2.86 /* Plug a potential leak where ambient cache value is occluded */
388     static int
389     plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang)
390     {
391     const double cost70sq = 0.1169778; /* cos(70deg)^2 */
392     RAY rtst;
393     FVECT vdif;
394     double normdot, ndotd, nadotd;
395     double a, b, c, t[2];
396    
397     ang += 2.*PI*(ang < 0); /* check direction flags */
398     if ( !(ap->corral>>(int)(ang*(16./PI)) & 1) )
399     return(0);
400     /*
401     * Generate test ray, targeting 20 degrees above sample point plane
402     * along surface normal from cache position. This should be high
403     * enough to miss local geometry we don't really care about.
404     */
405     VSUB(vdif, ap->pos, r->rop);
406     normdot = DOT(anorm, r->ron);
407     ndotd = DOT(vdif, r->ron);
408     nadotd = DOT(vdif, anorm);
409     a = normdot*normdot - cost70sq;
410     b = 2.0*(normdot*ndotd - nadotd*cost70sq);
411     c = ndotd*ndotd - DOT(vdif,vdif)*cost70sq;
412     if (quadratic(t, a, b, c) != 2)
413     return(1); /* should rarely happen */
414     if (t[1] <= FTINY)
415     return(0); /* should fail behind test */
416     rayorigin(&rtst, SHADOW, r, NULL);
417     VSUM(rtst.rdir, vdif, anorm, t[1]); /* further dist. > plane */
418     rtst.rmax = normalize(rtst.rdir); /* short ray test */
419     while (localhit(&rtst, &thescene)) { /* check for occluder */
420 greg 2.105 OBJREC *m = findmaterial(rtst.ro);
421     if (m != NULL && !istransp(m->otype) && !isBSDFproxy(m) &&
422 greg 2.86 (rtst.clipset == NULL ||
423     !inset(rtst.clipset, rtst.ro->omod)))
424     return(1); /* plug light leak */
425     VCOPY(rtst.rorg, rtst.rop); /* skip invisible surface */
426     rtst.rmax -= rtst.rot;
427     rayclear(&rtst);
428     }
429     return(0); /* seems we're OK */
430     }
431    
432    
433     static double
434 greg 2.72 sumambient( /* get interpolated ambient value */
435 greg 2.71 COLOR acol,
436     RAY *r,
437     FVECT rn,
438     int al,
439     AMBTREE *at,
440     FVECT c0,
441     double s
442     )
443 greg 2.80 { /* initial limit is 10 degrees plus ambacc radians */
444     const double minangle = 10.0 * PI/180.;
445 greg 2.84 double maxangle = minangle + ambacc;
446 greg 2.71 double wsum = 0.0;
447     FVECT ck0;
448     int i, j;
449     AMBVAL *av;
450 greg 2.83
451     if (at->kid != NULL) { /* sum children first */
452     s *= 0.5;
453     for (i = 0; i < 8; i++) {
454     for (j = 0; j < 3; j++) {
455     ck0[j] = c0[j];
456     if (1<<j & i)
457     ck0[j] += s;
458     if (r->rop[j] < ck0[j] - OCTSCALE*s)
459     break;
460     if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
461     break;
462     }
463     if (j == 3)
464     wsum += sumambient(acol, r, rn, al,
465     at->kid+i, ck0, s);
466     }
467     /* good enough? */
468 greg 2.84 if (wsum >= 0.05 && s > minarad*10.0)
469 greg 2.83 return(wsum);
470     }
471 greg 2.84 /* adjust maximum angle */
472     if (at->alist != NULL && (at->alist->lvl <= al) & (r->rweight < 0.6))
473     maxangle = (maxangle - PI/2.)*pow(r->rweight,0.13) + PI/2.;
474 greg 2.71 /* sum this node */
475     for (av = at->alist; av != NULL; av = av->next) {
476 greg 2.86 double u, v, d, delta_r2, delta_t2;
477 greg 2.71 COLOR ct;
478     FVECT uvw[3];
479     /* record access */
480     if (tracktime)
481     av->latick = ambclock;
482     /*
483 greg 2.72 * Ambient level test
484 greg 2.71 */
485 greg 2.87 if (av->lvl > al || /* list sorted, so this works */
486     (av->lvl == al) & (av->weight < 0.9*r->rweight))
487 greg 2.71 break;
488     /*
489 greg 2.72 * Direction test using unperturbed normal
490 greg 2.71 */
491     decodedir(uvw[2], av->ndir);
492     d = DOT(uvw[2], r->ron);
493     if (d <= 0.0) /* >= 90 degrees */
494     continue;
495     delta_r2 = 2.0 - 2.0*d; /* approx. radians^2 */
496     if (delta_r2 >= maxangle*maxangle)
497     continue;
498     /*
499 greg 2.81 * Modified ray behind test
500     */
501 greg 2.85 VSUB(ck0, r->rop, av->pos);
502 greg 2.81 d = DOT(ck0, uvw[2]);
503 greg 2.84 if (d < -minarad*ambacc-.001)
504 greg 2.81 continue;
505     d /= av->rad[0];
506     delta_t2 = d*d;
507 greg 2.84 if (delta_t2 >= ambacc*ambacc)
508 greg 2.81 continue;
509     /*
510 greg 2.72 * Elliptical radii test based on Hessian
511 greg 2.71 */
512     decodedir(uvw[0], av->udir);
513     VCROSS(uvw[1], uvw[2], uvw[0]);
514 greg 2.86 d = (u = DOT(ck0, uvw[0])) / av->rad[0];
515 greg 2.81 delta_t2 += d*d;
516 greg 2.86 d = (v = DOT(ck0, uvw[1])) / av->rad[1];
517 greg 2.71 delta_t2 += d*d;
518 greg 2.84 if (delta_t2 >= ambacc*ambacc)
519 greg 2.71 continue;
520     /*
521 greg 2.86 * Test for potential light leak
522     */
523     if (av->corral && plugaleak(r, av, uvw[2], atan2a(v,u)))
524     continue;
525     /*
526 greg 2.72 * Extrapolate value and compute final weight (hat function)
527 greg 2.71 */
528 greg 2.92 if (!extambient(ct, av, r->rop, rn, uvw))
529     continue;
530 greg 2.71 d = tfunc(maxangle, sqrt(delta_r2), 0.0) *
531 greg 2.84 tfunc(ambacc, sqrt(delta_t2), 0.0);
532 greg 2.71 scalecolor(ct, d);
533     addcolor(acol, ct);
534 greg 2.72 wsum += d;
535 greg 2.71 }
536     return(wsum);
537     }
538    
539    
540 greg 2.86 static int
541 greg 2.71 makeambient( /* make a new ambient value for storage */
542     COLOR acol,
543     RAY *r,
544     FVECT rn,
545     int al
546     )
547     {
548     AMBVAL amb;
549 greg 2.72 FVECT uvw[3];
550 greg 2.71 int i;
551    
552     amb.weight = 1.0; /* compute weight */
553     for (i = al; i-- > 0; )
554     amb.weight *= AVGREFL;
555     if (r->rweight < 0.1*amb.weight) /* heuristic override */
556     amb.weight = 1.25*r->rweight;
557     setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
558     /* compute ambient */
559 greg 2.86 i = doambient(acol, r, amb.weight,
560     uvw, amb.rad, amb.gpos, amb.gdir, &amb.corral);
561 greg 2.71 scalecolor(acol, 1./AVGREFL); /* undo assumed reflectance */
562 greg 2.76 if (i <= 0 || amb.rad[0] <= FTINY) /* no Hessian or zero radius */
563 greg 2.73 return(i);
564 greg 2.71 /* store value */
565     VCOPY(amb.pos, r->rop);
566     amb.ndir = encodedir(r->ron);
567 greg 2.72 amb.udir = encodedir(uvw[0]);
568 greg 2.71 amb.lvl = al;
569     copycolor(amb.val, acol);
570     /* insert into tree */
571     avsave(&amb); /* and save to file */
572 greg 2.72 if (rn != r->ron) { /* texture */
573     VCOPY(uvw[2], r->ron);
574     extambient(acol, &amb, r->rop, rn, uvw);
575     }
576 greg 2.71 return(1);
577     }
578    
579    
580 greg 2.92 static int
581 greg 2.71 extambient( /* extrapolate value at pv, nv */
582     COLOR cr,
583     AMBVAL *ap,
584     FVECT pv,
585 greg 2.72 FVECT nv,
586     FVECT uvw[3]
587 greg 2.71 )
588     {
589 greg 2.93 const double min_d = 0.05;
590 greg 2.72 static FVECT my_uvw[3];
591     FVECT v1;
592     int i;
593     double d = 1.0; /* zeroeth order */
594    
595     if (uvw == NULL) { /* need local coordinates? */
596     decodedir(my_uvw[2], ap->ndir);
597     decodedir(my_uvw[0], ap->udir);
598     VCROSS(my_uvw[1], my_uvw[2], my_uvw[0]);
599     uvw = my_uvw;
600     }
601 greg 2.71 for (i = 3; i--; ) /* gradient due to translation */
602     d += (pv[i] - ap->pos[i]) *
603     (ap->gpos[0]*uvw[0][i] + ap->gpos[1]*uvw[1][i]);
604    
605     VCROSS(v1, uvw[2], nv); /* gradient due to rotation */
606     for (i = 3; i--; )
607     d += v1[i] * (ap->gdir[0]*uvw[0][i] + ap->gdir[1]*uvw[1][i]);
608    
609 greg 2.93 if (d < min_d) /* should not use if we can avoid it */
610     d = min_d;
611 greg 2.71 copycolor(cr, ap->val);
612     scalecolor(cr, d);
613 greg 2.93 return(d > min_d);
614 greg 2.71 }
615    
616    
617     static void
618     avinsert( /* insert ambient value in our tree */
619     AMBVAL *av
620     )
621     {
622     AMBTREE *at;
623     AMBVAL *ap;
624     AMBVAL avh;
625     FVECT ck0;
626     double s;
627     int branch;
628     int i;
629    
630     if (av->rad[0] <= FTINY)
631     error(CONSISTENCY, "zero ambient radius in avinsert");
632     at = &atrunk;
633     VCOPY(ck0, thescene.cuorg);
634     s = thescene.cusize;
635 greg 2.84 while (s*(OCTSCALE/2) > av->rad[1]*ambacc) {
636 greg 2.71 if (at->kid == NULL)
637     if ((at->kid = newambtree()) == NULL)
638     error(SYSTEM, "out of memory in avinsert");
639     s *= 0.5;
640     branch = 0;
641     for (i = 0; i < 3; i++)
642     if (av->pos[i] > ck0[i] + s) {
643     ck0[i] += s;
644     branch |= 1 << i;
645     }
646     at = at->kid + branch;
647     }
648     avh.next = at->alist; /* order by increasing level */
649     for (ap = &avh; ap->next != NULL; ap = ap->next)
650 greg 2.87 if ( ap->next->lvl > av->lvl ||
651     (ap->next->lvl == av->lvl) &
652     (ap->next->weight <= av->weight) )
653 greg 2.71 break;
654     av->next = ap->next;
655     ap->next = (AMBVAL*)av;
656     at->alist = avh.next;
657     }
658    
659    
660     #else /* ! NEWAMB */
661    
662 greg 2.72 static double sumambient(COLOR acol, RAY *r, FVECT rn, int al,
663     AMBTREE *at, FVECT c0, double s);
664     static double makeambient(COLOR acol, RAY *r, FVECT rn, int al);
665     static void extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv);
666    
667 greg 2.71
668     void
669 greg 2.58 multambient( /* compute ambient component & multiply by coef. */
670     COLOR aval,
671 greg 2.70 RAY *r,
672 schorsch 2.56 FVECT nrm
673     )
674 greg 1.1 {
675     static int rdepth = 0; /* ambient recursion */
676 greg 2.94 COLOR acol, caustic;
677 gregl 2.43 double d, l;
678 greg 1.1
679 greg 2.94 /* PMAP: Factor in ambient from global photon map (if enabled) and return
680     * as all ambient components accounted for */
681 rschregle 2.95 if (ambPmap(aval, r, rdepth))
682 greg 2.94 return;
683    
684     /* PMAP: Otherwise factor in ambient from caustic photon map
685 rschregle 2.96 * (ambPmapCaustic() returns zero if caustic photons disabled) and
686 greg 2.94 * continue with RADIANCE ambient calculation */
687     copycolor(caustic, aval);
688 rschregle 2.95 ambPmapCaustic(caustic, r, rdepth);
689 greg 2.94
690 greg 1.1 if (ambdiv <= 0) /* no ambient calculation */
691     goto dumbamb;
692     /* check number of bounces */
693 greg 1.16 if (rdepth >= ambounce)
694 greg 1.1 goto dumbamb;
695     /* check ambient list */
696     if (ambincl != -1 && r->ro != NULL &&
697     ambincl != inset(ambset, r->ro->omod))
698     goto dumbamb;
699    
700     if (ambacc <= FTINY) { /* no ambient storage */
701 greg 2.61 copycolor(acol, aval);
702 greg 1.16 rdepth++;
703 greg 2.61 d = doambient(acol, r, r->rweight, NULL, NULL);
704 greg 1.16 rdepth--;
705 greg 2.32 if (d <= FTINY)
706 greg 1.1 goto dumbamb;
707 greg 2.94 copycolor(aval, acol);
708    
709     /* PMAP: add in caustic */
710     addcolor(aval, caustic);
711 greg 1.16 return;
712 greg 1.1 }
713 greg 2.40
714     if (tracktime) /* sort to minimize thrashing */
715     sortambvals(0);
716 greg 2.61 /* interpolate ambient value */
717 greg 1.1 setcolor(acol, 0.0, 0.0, 0.0);
718 greg 2.61 d = sumambient(acol, r, nrm, rdepth,
719 greg 1.16 &atrunk, thescene.cuorg, thescene.cusize);
720 greg 2.94
721 greg 2.32 if (d > FTINY) {
722 greg 2.61 d = 1.0/d;
723     scalecolor(acol, d);
724 greg 2.58 multcolor(aval, acol);
725 greg 2.94
726     /* PMAP: add in caustic */
727     addcolor(aval, caustic);
728 greg 2.32 return;
729 greg 1.16 }
730 greg 2.94
731 greg 2.33 rdepth++; /* need to cache new value */
732 greg 2.61 d = makeambient(acol, r, nrm, rdepth-1);
733 greg 2.32 rdepth--;
734 greg 2.94
735 greg 2.58 if (d > FTINY) {
736     multcolor(aval, acol); /* got new value */
737 greg 2.94
738     /* PMAP: add in caustic */
739     addcolor(aval, caustic);
740 greg 1.16 return;
741 greg 2.58 }
742 greg 2.94
743 greg 1.1 dumbamb: /* return global value */
744 greg 2.58 if ((ambvwt <= 0) | (navsum == 0)) {
745     multcolor(aval, ambval);
746 greg 2.94
747     /* PMAP: add in caustic */
748     addcolor(aval, caustic);
749 greg 2.32 return;
750 greg 2.58 }
751 greg 2.94
752 gregl 2.43 l = bright(ambval); /* average in computations */
753     if (l > FTINY) {
754     d = (log(l)*(double)ambvwt + avsum) /
755     (double)(ambvwt + navsum);
756     d = exp(d) / l;
757 greg 2.58 scalecolor(aval, d);
758     multcolor(aval, ambval); /* apply color of ambval */
759 gregl 2.43 } else {
760     d = exp( avsum / (double)navsum );
761 greg 2.58 scalecolor(aval, d); /* neutral color */
762 gregl 2.43 }
763 greg 1.1 }
764    
765    
766 greg 2.72 static double
767 schorsch 2.56 sumambient( /* get interpolated ambient value */
768     COLOR acol,
769 greg 2.70 RAY *r,
770 schorsch 2.56 FVECT rn,
771     int al,
772     AMBTREE *at,
773     FVECT c0,
774     double s
775     )
776 greg 1.1 {
777 greg 2.12 double d, e1, e2, wt, wsum;
778 greg 1.1 COLOR ct;
779     FVECT ck0;
780     int i;
781 greg 2.70 int j;
782     AMBVAL *av;
783 greg 2.29
784     wsum = 0.0;
785 greg 1.7 /* do this node */
786 greg 1.1 for (av = at->alist; av != NULL; av = av->next) {
787 greg 2.47 double rn_dot = -2.0;
788 greg 2.26 if (tracktime)
789 greg 2.40 av->latick = ambclock;
790 greg 1.1 /*
791 greg 1.16 * Ambient level test.
792 greg 1.1 */
793 greg 2.87 if (av->lvl > al || /* list sorted, so this works */
794     (av->lvl == al) & (av->weight < 0.9*r->rweight))
795 greg 2.23 break;
796 greg 1.1 /*
797     * Ambient radius test.
798     */
799 greg 2.70 VSUB(ck0, av->pos, r->rop);
800     e1 = DOT(ck0, ck0) / (av->rad * av->rad);
801 greg 1.1 if (e1 > ambacc*ambacc*1.21)
802     continue;
803     /*
804 greg 2.47 * Direction test using closest normal.
805 greg 1.1 */
806 greg 2.47 d = DOT(av->dir, r->ron);
807     if (rn != r->ron) {
808     rn_dot = DOT(av->dir, rn);
809     if (rn_dot > 1.0-FTINY)
810     rn_dot = 1.0-FTINY;
811     if (rn_dot >= d-FTINY) {
812     d = rn_dot;
813     rn_dot = -2.0;
814     }
815     }
816     e2 = (1.0 - d) * r->rweight;
817 greg 2.70 if (e2 < 0.0)
818     e2 = 0.0;
819     else if (e1 + e2 > ambacc*ambacc*1.21)
820 greg 1.1 continue;
821     /*
822     * Ray behind test.
823     */
824     d = 0.0;
825     for (j = 0; j < 3; j++)
826     d += (r->rop[j] - av->pos[j]) *
827     (av->dir[j] + r->ron[j]);
828 greg 1.18 if (d*0.5 < -minarad*ambacc-.001)
829 greg 1.1 continue;
830     /*
831     * Jittering final test reduces image artifacts.
832     */
833 greg 2.47 e1 = sqrt(e1);
834     e2 = sqrt(e2);
835     wt = e1 + e2;
836 greg 2.31 if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
837 greg 1.1 continue;
838 greg 2.47 /*
839     * Recompute directional error using perturbed normal
840     */
841     if (rn_dot > 0.0) {
842     e2 = sqrt((1.0 - rn_dot)*r->rweight);
843     wt = e1 + e2;
844     }
845 greg 1.1 if (wt <= 1e-3)
846     wt = 1e3;
847     else
848     wt = 1.0 / wt;
849     wsum += wt;
850 greg 2.34 extambient(ct, av, r->rop, rn);
851 greg 1.1 scalecolor(ct, wt);
852     addcolor(acol, ct);
853 greg 1.7 }
854     if (at->kid == NULL)
855     return(wsum);
856     /* do children */
857     s *= 0.5;
858     for (i = 0; i < 8; i++) {
859     for (j = 0; j < 3; j++) {
860     ck0[j] = c0[j];
861     if (1<<j & i)
862     ck0[j] += s;
863     if (r->rop[j] < ck0[j] - OCTSCALE*s)
864     break;
865     if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
866     break;
867     }
868     if (j == 3)
869 greg 2.61 wsum += sumambient(acol, r, rn, al,
870 greg 2.59 at->kid+i, ck0, s);
871 greg 1.1 }
872     return(wsum);
873     }
874    
875    
876 greg 2.72 static double
877 greg 2.61 makeambient( /* make a new ambient value for storage */
878 schorsch 2.56 COLOR acol,
879 greg 2.58 RAY *r,
880 schorsch 2.56 FVECT rn,
881     int al
882     )
883 greg 1.1 {
884 greg 2.12 AMBVAL amb;
885 greg 1.14 FVECT gp, gd;
886 greg 2.60 int i;
887    
888 greg 2.61 amb.weight = 1.0; /* compute weight */
889     for (i = al; i-- > 0; )
890 greg 2.60 amb.weight *= AVGREFL;
891 greg 2.61 if (r->rweight < 0.1*amb.weight) /* heuristic override */
892 greg 2.62 amb.weight = 1.25*r->rweight;
893 greg 2.61 setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
894 greg 1.16 /* compute ambient */
895 greg 2.61 amb.rad = doambient(acol, r, amb.weight, gp, gd);
896     if (amb.rad <= FTINY) {
897     setcolor(acol, 0.0, 0.0, 0.0);
898 greg 1.1 return(0.0);
899 greg 2.61 }
900     scalecolor(acol, 1./AVGREFL); /* undo assumed reflectance */
901     /* store value */
902 greg 1.1 VCOPY(amb.pos, r->rop);
903     VCOPY(amb.dir, r->ron);
904 greg 1.16 amb.lvl = al;
905 greg 1.1 copycolor(amb.val, acol);
906 greg 1.14 VCOPY(amb.gpos, gp);
907     VCOPY(amb.gdir, gd);
908 greg 1.1 /* insert into tree */
909 greg 2.7 avsave(&amb); /* and save to file */
910 greg 2.34 if (rn != r->ron)
911     extambient(acol, &amb, r->rop, rn); /* texture */
912 greg 1.1 return(amb.rad);
913 greg 1.15 }
914    
915    
916 greg 2.72 static void
917 schorsch 2.56 extambient( /* extrapolate value at pv, nv */
918     COLOR cr,
919 greg 2.70 AMBVAL *ap,
920 schorsch 2.56 FVECT pv,
921     FVECT nv
922     )
923 greg 1.15 {
924 gwlarson 2.45 FVECT v1;
925 greg 2.70 int i;
926 greg 2.12 double d;
927 greg 1.15
928     d = 1.0; /* zeroeth order */
929     /* gradient due to translation */
930     for (i = 0; i < 3; i++)
931     d += ap->gpos[i]*(pv[i]-ap->pos[i]);
932     /* gradient due to rotation */
933 gwlarson 2.45 VCROSS(v1, ap->dir, nv);
934     d += DOT(ap->gdir, v1);
935 greg 1.15 if (d <= 0.0) {
936     setcolor(cr, 0.0, 0.0, 0.0);
937     return;
938     }
939     copycolor(cr, ap->val);
940     scalecolor(cr, d);
941 greg 1.1 }
942    
943    
944 greg 2.47 static void
945 greg 2.71 avinsert( /* insert ambient value in our tree */
946     AMBVAL *av
947     )
948     {
949     AMBTREE *at;
950     AMBVAL *ap;
951     AMBVAL avh;
952     FVECT ck0;
953     double s;
954     int branch;
955     int i;
956    
957     if (av->rad <= FTINY)
958     error(CONSISTENCY, "zero ambient radius in avinsert");
959     at = &atrunk;
960     VCOPY(ck0, thescene.cuorg);
961     s = thescene.cusize;
962     while (s*(OCTSCALE/2) > av->rad*ambacc) {
963     if (at->kid == NULL)
964     if ((at->kid = newambtree()) == NULL)
965     error(SYSTEM, "out of memory in avinsert");
966     s *= 0.5;
967     branch = 0;
968     for (i = 0; i < 3; i++)
969     if (av->pos[i] > ck0[i] + s) {
970     ck0[i] += s;
971     branch |= 1 << i;
972     }
973     at = at->kid + branch;
974     }
975     avh.next = at->alist; /* order by increasing level */
976     for (ap = &avh; ap->next != NULL; ap = ap->next)
977 greg 2.87 if ( ap->next->lvl > av->lvl ||
978     (ap->next->lvl == av->lvl) &
979     (ap->next->weight <= av->weight) )
980 greg 2.71 break;
981     av->next = ap->next;
982     ap->next = (AMBVAL*)av;
983     at->alist = avh.next;
984     }
985    
986     #endif /* ! NEWAMB */
987    
988     /************* FOLLOWING ROUTINES SAME FOR NEW & OLD METHODS ***************/
989    
990     static void
991 schorsch 2.56 initambfile( /* initialize ambient file */
992 greg 2.68 int cre8
993 schorsch 2.56 )
994 greg 2.9 {
995 greg 2.47 extern char *progname, *octname;
996     static char *mybuf = NULL;
997 greg 2.9
998 greg 2.19 #ifdef F_SETLKW
999 greg 2.69 aflock(cre8 ? F_WRLCK : F_RDLCK);
1000 greg 2.19 #endif
1001 schorsch 2.50 SET_FILE_BINARY(ambfp);
1002 greg 2.47 if (mybuf == NULL)
1003     mybuf = (char *)bmalloc(BUFSIZ+8);
1004     setbuf(ambfp, mybuf);
1005 greg 2.68 if (cre8) { /* new file */
1006 greg 2.24 newheader("RADIANCE", ambfp);
1007 greg 2.41 fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
1008 greg 2.9 progname, colval(ambval,RED),
1009     colval(ambval,GRN), colval(ambval,BLU),
1010 greg 2.41 ambvwt, ambounce, ambacc);
1011 greg 2.47 fprintf(ambfp, "-ad %d -as %d -ar %d ",
1012     ambdiv, ambssamp, ambres);
1013     if (octname != NULL)
1014 greg 2.68 fputs(octname, ambfp);
1015     fputc('\n', ambfp);
1016 greg 2.9 fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
1017 greg 2.47 fputnow(ambfp);
1018 greg 2.9 fputformat(AMBFMT, ambfp);
1019 greg 2.68 fputc('\n', ambfp);
1020 greg 2.9 putambmagic(ambfp);
1021 greg 2.17 } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
1022     error(USER, "bad ambient file");
1023 greg 2.9 }
1024    
1025    
1026 greg 2.47 static void
1027 schorsch 2.56 avsave( /* insert and save an ambient value */
1028     AMBVAL *av
1029     )
1030 greg 1.1 {
1031 greg 2.88 avstore(av);
1032 greg 1.1 if (ambfp == NULL)
1033     return;
1034 greg 2.5 if (writambval(av, ambfp) < 0)
1035 greg 1.1 goto writerr;
1036 greg 2.16 if (++nunflshed >= AMBFLUSH)
1037 greg 2.7 if (ambsync() == EOF)
1038 greg 1.1 goto writerr;
1039     return;
1040     writerr:
1041 greg 2.47 error(SYSTEM, "error writing to ambient file");
1042 greg 1.1 }
1043    
1044    
1045 greg 2.20 static AMBVAL *
1046 greg 2.88 avstore( /* allocate memory and save aval */
1047 greg 2.70 AMBVAL *aval
1048 schorsch 2.56 )
1049 greg 2.20 {
1050 greg 2.70 AMBVAL *av;
1051 gregl 2.43 double d;
1052 greg 2.20
1053     if ((av = newambval()) == NULL)
1054     error(SYSTEM, "out of memory in avstore");
1055 schorsch 2.53 *av = *aval;
1056 greg 2.26 av->latick = ambclock;
1057     av->next = NULL;
1058     nambvals++;
1059 gregl 2.43 d = bright(av->val);
1060     if (d > FTINY) { /* add to log sum for averaging */
1061     avsum += log(d);
1062     navsum++;
1063     }
1064 greg 2.88 avinsert(av); /* insert in our cache tree */
1065 greg 2.20 return(av);
1066     }
1067    
1068    
1069 greg 2.26 #define ATALLOCSZ 512 /* #/8 trees to allocate at once */
1070    
1071     static AMBTREE *atfreelist = NULL; /* free ambient tree structures */
1072    
1073    
1074 greg 2.47 static AMBTREE *
1075 schorsch 2.56 newambtree(void) /* allocate 8 ambient tree structs */
1076 greg 2.26 {
1077 greg 2.70 AMBTREE *atp, *upperlim;
1078 greg 2.26
1079     if (atfreelist == NULL) { /* get more nodes */
1080 greg 2.47 atfreelist = (AMBTREE *)malloc(ATALLOCSZ*8*sizeof(AMBTREE));
1081 greg 2.26 if (atfreelist == NULL)
1082     return(NULL);
1083     /* link new free list */
1084     upperlim = atfreelist + 8*(ATALLOCSZ-1);
1085     for (atp = atfreelist; atp < upperlim; atp += 8)
1086     atp->kid = atp + 8;
1087     atp->kid = NULL;
1088     }
1089     atp = atfreelist;
1090     atfreelist = atp->kid;
1091 greg 2.102 memset(atp, 0, 8*sizeof(AMBTREE));
1092 greg 2.26 return(atp);
1093     }
1094    
1095    
1096 greg 2.47 static void
1097 schorsch 2.56 freeambtree( /* free 8 ambient tree structs */
1098     AMBTREE *atp
1099     )
1100 greg 2.26 {
1101 greg 2.100 atp->kid = atfreelist;
1102 greg 2.26 atfreelist = atp;
1103     }
1104    
1105    
1106 greg 2.47 static void
1107 schorsch 2.56 unloadatree( /* unload an ambient value tree */
1108 greg 2.70 AMBTREE *at,
1109 schorsch 2.56 unloadtf_t *f
1110     )
1111 greg 2.20 {
1112 greg 2.70 AMBVAL *av;
1113     int i;
1114 greg 2.20 /* transfer values at this node */
1115     for (av = at->alist; av != NULL; av = at->alist) {
1116     at->alist = av->next;
1117 greg 2.102 av->next = NULL;
1118 greg 2.26 (*f)(av);
1119 greg 2.20 }
1120 greg 2.21 if (at->kid == NULL)
1121     return;
1122 greg 2.20 for (i = 0; i < 8; i++) /* transfer and free children */
1123 greg 2.26 unloadatree(at->kid+i, f);
1124 greg 2.20 freeambtree(at->kid);
1125 greg 2.26 at->kid = NULL;
1126     }
1127    
1128    
1129 greg 2.39 static struct avl {
1130     AMBVAL *p;
1131     unsigned long t;
1132     } *avlist1; /* ambient value list with ticks */
1133     static AMBVAL **avlist2; /* memory positions for sorting */
1134 greg 2.26 static int i_avlist; /* index for lists */
1135    
1136 schorsch 2.56 static int alatcmp(const void *av1, const void *av2);
1137 greg 2.26
1138 schorsch 2.56 static void
1139 greg 2.71 avfree(AMBVAL *av)
1140     {
1141     free(av);
1142     }
1143    
1144     static void
1145 schorsch 2.56 av2list(
1146 greg 2.71 AMBVAL *av
1147 schorsch 2.56 )
1148 greg 2.26 {
1149 greg 2.27 #ifdef DEBUG
1150 greg 2.26 if (i_avlist >= nambvals)
1151     error(CONSISTENCY, "too many ambient values in av2list1");
1152 greg 2.27 #endif
1153 schorsch 2.56 avlist1[i_avlist].p = avlist2[i_avlist] = (AMBVAL*)av;
1154 greg 2.71 avlist1[i_avlist++].t = av->latick;
1155 greg 2.26 }
1156    
1157    
1158     static int
1159 schorsch 2.56 alatcmp( /* compare ambient values for MRA */
1160     const void *av1,
1161     const void *av2
1162     )
1163 greg 2.26 {
1164 greg 2.70 long lc = ((struct avl *)av2)->t - ((struct avl *)av1)->t;
1165 greg 2.38 return(lc<0 ? -1 : lc>0 ? 1 : 0);
1166 greg 2.26 }
1167    
1168    
1169 greg 2.47 /* GW NOTE 2002/10/3:
1170     * I used to compare AMBVAL pointers, but found that this was the
1171     * cause of a serious consistency error with gcc, since the optimizer
1172     * uses some dangerous trick in pointer subtraction that
1173     * assumes pointers differ by exact struct size increments.
1174     */
1175 greg 2.26 static int
1176 schorsch 2.56 aposcmp( /* compare ambient value positions */
1177     const void *avp1,
1178     const void *avp2
1179     )
1180 greg 2.26 {
1181 greg 2.70 long diff = *(char * const *)avp1 - *(char * const *)avp2;
1182 greg 2.47 if (diff < 0)
1183     return(-1);
1184     return(diff > 0);
1185 greg 2.26 }
1186    
1187 greg 2.71
1188 greg 2.27 static int
1189 schorsch 2.56 avlmemi( /* find list position from address */
1190     AMBVAL *avaddr
1191     )
1192 greg 2.27 {
1193 greg 2.70 AMBVAL **avlpp;
1194 greg 2.27
1195 greg 2.102 avlpp = (AMBVAL **)bsearch(&avaddr, avlist2,
1196     nambvals, sizeof(AMBVAL *), aposcmp);
1197 greg 2.27 if (avlpp == NULL)
1198     error(CONSISTENCY, "address not found in avlmemi");
1199     return(avlpp - avlist2);
1200     }
1201    
1202    
1203 greg 2.47 static void
1204 schorsch 2.56 sortambvals( /* resort ambient values */
1205     int always
1206     )
1207 greg 2.26 {
1208     AMBTREE oldatrunk;
1209     AMBVAL tav, *tap, *pnext;
1210 greg 2.70 int i, j;
1211 greg 2.28 /* see if it's time yet */
1212 greg 2.40 if (!always && (ambclock++ < lastsort+sortintvl ||
1213 greg 2.28 nambvals < SORT_THRESH))
1214     return;
1215 greg 2.26 /*
1216     * The idea here is to minimize memory thrashing
1217     * in VM systems by improving reference locality.
1218     * We do this by periodically sorting our stored ambient
1219     * values in memory in order of most recently to least
1220     * recently accessed. This ordering was chosen so that new
1221     * ambient values (which tend to be less important) go into
1222     * higher memory with the infrequently accessed values.
1223     * Since we expect our values to need sorting less
1224     * frequently as the process continues, we double our
1225     * waiting interval after each call.
1226     * This routine is also called by setambacc() with
1227     * the "always" parameter set to 1 so that the ambient
1228     * tree will be rebuilt with the new accuracy parameter.
1229     */
1230 greg 2.27 if (tracktime) { /* allocate pointer arrays to sort */
1231 greg 2.26 avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
1232 greg 2.39 avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
1233     } else {
1234     avlist2 = NULL;
1235     avlist1 = NULL;
1236     }
1237     if (avlist1 == NULL) { /* no time tracking -- rebuild tree? */
1238     if (avlist2 != NULL)
1239 greg 2.102 free(avlist2);
1240 greg 2.27 if (always) { /* rebuild without sorting */
1241 schorsch 2.53 oldatrunk = atrunk;
1242 greg 2.27 atrunk.alist = NULL;
1243     atrunk.kid = NULL;
1244 greg 2.99 unloadatree(&oldatrunk, avinsert);
1245 greg 2.27 }
1246 greg 2.26 } else { /* sort memory by last access time */
1247     /*
1248     * Sorting memory is tricky because it isn't contiguous.
1249     * We have to sort an array of pointers by MRA and also
1250     * by memory position. We then copy values in "loops"
1251     * to minimize memory hits. Nevertheless, we will visit
1252 greg 2.27 * everyone at least twice, and this is an expensive process
1253 greg 2.26 * when we're thrashing, which is when we need to do it.
1254     */
1255 greg 2.27 #ifdef DEBUG
1256 greg 2.29 sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
1257     nambvals, ambclock);
1258 greg 2.27 eputs(errmsg);
1259     #endif
1260     i_avlist = 0;
1261 greg 2.99 unloadatree(&atrunk, av2list); /* empty current tree */
1262 greg 2.27 #ifdef DEBUG
1263     if (i_avlist < nambvals)
1264     error(CONSISTENCY, "missing ambient values in sortambvals");
1265     #endif
1266 greg 2.102 qsort(avlist1, nambvals, sizeof(struct avl), alatcmp);
1267     qsort(avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
1268 greg 2.26 for (i = 0; i < nambvals; i++) {
1269 greg 2.39 if (avlist1[i].p == NULL)
1270 greg 2.26 continue;
1271     tap = avlist2[i];
1272 schorsch 2.53 tav = *tap;
1273 greg 2.39 for (j = i; (pnext = avlist1[j].p) != tap;
1274 greg 2.27 j = avlmemi(pnext)) {
1275 schorsch 2.53 *(avlist2[j]) = *pnext;
1276 greg 2.26 avinsert(avlist2[j]);
1277 greg 2.39 avlist1[j].p = NULL;
1278 greg 2.26 }
1279 schorsch 2.53 *(avlist2[j]) = tav;
1280 greg 2.26 avinsert(avlist2[j]);
1281 greg 2.39 avlist1[j].p = NULL;
1282 greg 2.26 }
1283 greg 2.102 free(avlist1);
1284     free(avlist2);
1285 greg 2.28 /* compute new sort interval */
1286     sortintvl = ambclock - lastsort;
1287 greg 2.32 if (sortintvl >= MAX_SORT_INTVL/2)
1288 greg 2.28 sortintvl = MAX_SORT_INTVL;
1289     else
1290 greg 2.26 sortintvl <<= 1; /* wait twice as long next */
1291 greg 2.27 #ifdef DEBUG
1292     eputs("done\n");
1293     #endif
1294 greg 2.26 }
1295     if (ambclock >= MAXACLOCK)
1296     ambclock = MAXACLOCK/2;
1297     lastsort = ambclock;
1298 greg 2.20 }
1299    
1300    
1301 greg 2.18 #ifdef F_SETLKW
1302 greg 2.10
1303 greg 2.47 static void
1304 schorsch 2.56 aflock( /* lock/unlock ambient file */
1305     int typ
1306     )
1307 greg 2.19 {
1308     static struct flock fls; /* static so initialized to zeroes */
1309    
1310 greg 2.66 if (typ == fls.l_type) /* already called? */
1311     return;
1312 greg 2.19 fls.l_type = typ;
1313     if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
1314     error(SYSTEM, "cannot (un)lock ambient file");
1315     }
1316    
1317    
1318 greg 2.71 int
1319 schorsch 2.56 ambsync(void) /* synchronize ambient file */
1320 greg 2.7 {
1321 greg 2.15 long flen;
1322 greg 2.12 AMBVAL avs;
1323 greg 2.70 int n;
1324 greg 2.16
1325 greg 2.65 if (ambfp == NULL) /* no ambient file? */
1326     return(0);
1327 greg 2.63 /* gain appropriate access */
1328     aflock(nunflshed ? F_WRLCK : F_RDLCK);
1329 greg 2.7 /* see if file has grown */
1330 greg 2.55 if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
1331 greg 2.21 goto seekerr;
1332 greg 2.68 if ((n = flen - lastpos) > 0) { /* file has grown */
1333 greg 2.104 if (ambinp == NULL) { /* get new file pointer */
1334     ambinp = fopen(ambfile, "rb");
1335 greg 2.14 if (ambinp == NULL)
1336 greg 2.104 error(SYSTEM, "fopen failed in ambsync");
1337 greg 2.14 }
1338 greg 2.66 if (fseek(ambinp, lastpos, SEEK_SET) < 0)
1339 greg 2.21 goto seekerr;
1340 greg 2.15 while (n >= AMBVALSIZ) { /* load contributed values */
1341 greg 2.37 if (!readambval(&avs, ambinp)) {
1342     sprintf(errmsg,
1343 greg 2.47 "ambient file \"%s\" corrupted near character %ld",
1344     ambfile, flen - n);
1345 greg 2.37 error(WARNING, errmsg);
1346     break;
1347     }
1348 greg 2.88 avstore(&avs);
1349 greg 2.15 n -= AMBVALSIZ;
1350     }
1351 greg 2.104 lastpos = flen - n; /* check alignment */
1352     if (n && lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1353     goto seekerr;
1354 greg 2.7 }
1355     n = fflush(ambfp); /* calls write() at last */
1356 greg 2.104 lastpos += (long)nunflshed*AMBVALSIZ;
1357 greg 2.19 aflock(F_UNLCK); /* release file */
1358 greg 2.16 nunflshed = 0;
1359 greg 2.7 return(n);
1360 greg 2.21 seekerr:
1361     error(SYSTEM, "seek failed in ambsync");
1362 greg 2.104 return(EOF); /* pro forma return */
1363 greg 2.18 }
1364    
1365 greg 2.71 #else /* ! F_SETLKW */
1366 greg 2.18
1367 greg 2.71 int
1368 schorsch 2.56 ambsync(void) /* flush ambient file */
1369 greg 2.18 {
1370 greg 2.65 if (ambfp == NULL)
1371     return(0);
1372 greg 2.18 nunflshed = 0;
1373     return(fflush(ambfp));
1374 greg 1.1 }
1375 greg 2.10
1376 greg 2.71 #endif /* ! F_SETLKW */