ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.103
Committed: Tue Nov 1 20:39:39 2016 UTC (7 years, 6 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.102: +17 -3 lines
Log Message:
Added code to handle textures (normal perturbations) with -aa 0

File Contents

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