ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.98
Committed: Sun Aug 23 00:17:12 2015 UTC (8 years, 8 months ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad5R0
Changes since 2.97: +1 -4 lines
Log Message:
Minor tweaks & performance improvements for rcontrib file locking

File Contents

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