ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.37
Committed: Tue May 28 14:24:44 1996 UTC (27 years, 11 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.36: +18 -4 lines
Log Message:
added check for ambient value validity, ambvalOK(), called by readambval()

File Contents

# User Rev Content
1 greg 2.27 /* Copyright (c) 1995 Regents of the University of California */
2 greg 1.1
3     #ifndef lint
4     static char SCCSid[] = "$SunId$ LBL";
5     #endif
6    
7     /*
8     * ambient.c - routines dealing with ambient (inter-reflected) component.
9     */
10    
11     #include "ray.h"
12    
13     #include "octree.h"
14    
15 greg 1.8 #include "otypes.h"
16    
17 greg 1.14 #include "ambient.h"
18    
19 greg 1.1 #include "random.h"
20    
21 greg 2.32 #ifndef OCTSCALE
22 greg 2.29 #define OCTSCALE 1.0 /* ceil((valid rad.)/(cube size)) */
23 greg 2.32 #endif
24 greg 1.1
25 greg 1.14 typedef struct ambtree {
26 greg 2.12 AMBVAL *alist; /* ambient value list */
27     struct ambtree *kid; /* 8 child nodes */
28 greg 1.14 } AMBTREE; /* ambient octree */
29    
30 greg 1.1 extern CUBE thescene; /* contains space boundaries */
31    
32 greg 2.27 extern char *shm_boundary; /* memory sharing boundary */
33 greg 2.26
34 greg 2.12 #define MAXASET 511 /* maximum number of elements in ambient set */
35     OBJECT ambset[MAXASET+1]={0}; /* ambient include/exclude set */
36 greg 1.1
37 greg 2.12 double maxarad; /* maximum ambient radius */
38     double minarad; /* minimum ambient radius */
39 greg 1.1
40 greg 2.12 static AMBTREE atrunk; /* our ambient trunk node */
41 greg 1.1
42     static FILE *ambfp = NULL; /* ambient file pointer */
43 greg 2.16 static int nunflshed = 0; /* number of unflushed ambient values */
44 greg 1.1
45 greg 2.26 #ifndef SORT_THRESH
46     #ifdef BIGMEM
47 greg 2.27 #define SORT_THRESH ((9L<<20)/sizeof(AMBVAL))
48 greg 2.26 #else
49 greg 2.27 #define SORT_THRESH ((3L<<20)/sizeof(AMBVAL))
50 greg 2.26 #endif
51     #endif
52     #ifndef SORT_INTVL
53 greg 2.29 #define SORT_INTVL (SORT_THRESH*256)
54 greg 2.26 #endif
55 greg 2.28 #ifndef MAX_SORT_INTVL
56 greg 2.29 #define MAX_SORT_INTVL (SORT_INTVL<<4)
57 greg 2.28 #endif
58 greg 2.26
59 greg 2.32 static COLOR avsum = BLKCOLOR; /* computed ambient value sum */
60 greg 2.35 static unsigned int nambvals = 0; /* total number of indirect values */
61     static unsigned int nambshare = 0; /* number of values from file */
62 greg 2.27 static unsigned long ambclock = 0; /* ambient access clock */
63     static unsigned long lastsort = 0; /* time of last value sort */
64 greg 2.26 static long sortintvl = SORT_INTVL; /* time until next sort */
65    
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 greg 2.27 */
73 greg 2.35 #define tracktime (shm_boundary == NULL || nambvals > 3*nambshare)
74 greg 2.26
75 greg 2.12 #define AMBFLUSH (BUFSIZ/AMBVALSIZ)
76 greg 2.6
77 greg 2.12 #define newambval() (AMBVAL *)bmalloc(sizeof(AMBVAL))
78 greg 1.1
79 greg 2.7 extern long ftell(), lseek();
80 greg 2.26 static int initambfile(), avsave(), avinsert(), sortambvals();
81 greg 2.20 static AMBVAL *avstore();
82 greg 2.19 #ifdef F_SETLKW
83     static aflock();
84     #endif
85 greg 1.1
86 greg 2.7
87 greg 2.3 setambres(ar) /* set ambient resolution */
88     int ar;
89     {
90 greg 2.21 ambres = ar < 0 ? 0 : ar; /* may be done already */
91 greg 2.3 /* set min & max radii */
92     if (ar <= 0) {
93 greg 2.25 minarad = 0;
94 greg 2.3 maxarad = thescene.cusize / 2.0;
95     } else {
96     minarad = thescene.cusize / ar;
97 greg 2.30 maxarad = 64 * minarad; /* heuristic */
98 greg 2.3 if (maxarad > thescene.cusize / 2.0)
99     maxarad = thescene.cusize / 2.0;
100     }
101 greg 2.25 if (minarad <= FTINY)
102     minarad = 10*FTINY;
103     if (maxarad <= minarad)
104     maxarad = 64 * minarad;
105 greg 2.3 }
106    
107    
108 greg 2.21 setambacc(newa) /* set ambient accuracy */
109 greg 2.20 double newa;
110     {
111 greg 2.33 double ambdiff;
112 greg 2.20
113 greg 2.33 if (newa < 0.0)
114     newa = 0.0;
115     ambdiff = fabs(newa - ambacc);
116     if (ambdiff >= .01 && (ambacc = newa) > FTINY && nambvals > 0)
117     sortambvals(1); /* rebuild tree */
118 greg 2.20 }
119    
120    
121 greg 1.1 setambient(afile) /* initialize calculation */
122     char *afile;
123     {
124 greg 2.37 long pos, flen;
125 greg 2.12 AMBVAL amb;
126 greg 2.3 /* init ambient limits */
127     setambres(ambres);
128 greg 2.21 setambacc(ambacc);
129 greg 2.19 if (afile == NULL)
130     return;
131 greg 2.20 if (ambacc <= FTINY) {
132 greg 2.21 sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
133 greg 2.20 afile);
134     error(WARNING, errmsg);
135     return;
136     }
137 greg 2.3 /* open ambient file */
138 greg 2.19 if ((ambfp = fopen(afile, "r+")) != NULL) {
139     initambfile(0);
140 greg 2.37 pos = ftell(ambfp);
141 greg 2.19 while (readambval(&amb, ambfp))
142 greg 2.21 avinsert(avstore(&amb));
143 greg 2.19 /* align */
144 greg 2.37 pos += (long)nambvals*AMBVALSIZ;
145     flen = lseek(fileno(ambfp), 0L, 2);
146     if (flen != pos) {
147     error(WARNING,
148     "ignoring last %ld values in ambient file (corrupted)",
149     (flen - pos)/AMBVALSIZ);
150     fseek(ambfp, pos, 0);
151     ftruncate(fileno(ambfp), pos);
152     }
153 greg 2.35 nambshare = nambvals;
154 greg 2.19 } else if ((ambfp = fopen(afile, "w+")) != NULL)
155     initambfile(1);
156     else {
157     sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
158     error(SYSTEM, errmsg);
159 greg 2.16 }
160 greg 2.19 nunflshed++; /* lie */
161     ambsync();
162 greg 1.8 }
163    
164    
165     ambnotify(obj) /* record new modifier */
166 greg 2.12 OBJECT obj;
167 greg 1.8 {
168 greg 1.11 static int hitlimit = 0;
169 greg 2.12 register OBJREC *o = objptr(obj);
170 greg 1.8 register char **amblp;
171    
172 greg 1.11 if (hitlimit || !ismodifier(o->otype))
173 greg 1.8 return;
174     for (amblp = amblist; *amblp != NULL; amblp++)
175     if (!strcmp(o->oname, *amblp)) {
176 greg 1.11 if (ambset[0] >= MAXASET) {
177     error(WARNING, "too many modifiers in ambient list");
178     hitlimit++;
179     return; /* should this be fatal? */
180     }
181 greg 1.8 insertelem(ambset, obj);
182     return;
183 greg 1.1 }
184     }
185    
186    
187 greg 2.34 ambient(acol, r, nrm) /* compute ambient component for ray */
188 greg 1.1 COLOR acol;
189     register RAY *r;
190 greg 2.34 FVECT nrm;
191 greg 1.1 {
192     static int rdepth = 0; /* ambient recursion */
193 greg 2.12 double d;
194 greg 1.1
195     if (ambdiv <= 0) /* no ambient calculation */
196     goto dumbamb;
197     /* check number of bounces */
198 greg 1.16 if (rdepth >= ambounce)
199 greg 1.1 goto dumbamb;
200     /* check ambient list */
201     if (ambincl != -1 && r->ro != NULL &&
202     ambincl != inset(ambset, r->ro->omod))
203     goto dumbamb;
204    
205     if (ambacc <= FTINY) { /* no ambient storage */
206 greg 1.16 rdepth++;
207     d = doambient(acol, r, r->rweight, NULL, NULL);
208     rdepth--;
209 greg 2.32 if (d <= FTINY)
210 greg 1.1 goto dumbamb;
211 greg 1.16 return;
212 greg 1.1 }
213 greg 2.27 /* resort memory? */
214 greg 2.28 sortambvals(0);
215 greg 1.1 /* get ambient value */
216     setcolor(acol, 0.0, 0.0, 0.0);
217 greg 2.34 d = sumambient(acol, r, nrm, rdepth,
218 greg 1.16 &atrunk, thescene.cuorg, thescene.cusize);
219 greg 2.32 if (d > FTINY) {
220 greg 1.16 scalecolor(acol, 1.0/d);
221 greg 2.32 return;
222 greg 1.16 }
223 greg 2.33 rdepth++; /* need to cache new value */
224 greg 2.34 d = makeambient(acol, r, nrm, rdepth-1);
225 greg 2.32 rdepth--;
226 greg 1.16 if (d > FTINY)
227     return;
228 greg 1.1 dumbamb: /* return global value */
229     copycolor(acol, ambval);
230 greg 2.36 if (ambvwt <= 0 | nambvals == 0)
231 greg 2.32 return;
232 greg 2.36 scalecolor(acol, (double)ambvwt);
233 greg 2.32 addcolor(acol, avsum); /* average in computations */
234 greg 2.36 d = 1.0/(ambvwt+nambvals);
235 greg 2.32 scalecolor(acol, d);
236 greg 1.1 }
237    
238    
239     double
240 greg 2.34 sumambient(acol, r, rn, al, at, c0, s) /* get interpolated ambient value */
241 greg 1.1 COLOR acol;
242     register RAY *r;
243 greg 2.34 FVECT rn;
244 greg 1.16 int al;
245 greg 2.12 AMBTREE *at;
246 greg 1.1 FVECT c0;
247 greg 2.12 double s;
248 greg 1.1 {
249 greg 2.12 double d, e1, e2, wt, wsum;
250 greg 1.1 COLOR ct;
251     FVECT ck0;
252     int i;
253     register int j;
254 greg 2.12 register AMBVAL *av;
255 greg 2.29
256     wsum = 0.0;
257 greg 1.7 /* do this node */
258 greg 1.1 for (av = at->alist; av != NULL; av = av->next) {
259 greg 2.26 if (tracktime)
260     av->latick = ambclock++;
261 greg 1.1 /*
262 greg 1.16 * Ambient level test.
263 greg 1.1 */
264 greg 2.23 if (av->lvl > al) /* list sorted, so this works */
265     break;
266     if (av->weight < r->rweight-FTINY)
267 greg 1.1 continue;
268     /*
269     * Ambient radius test.
270     */
271 greg 2.29 d = av->pos[0] - r->rop[0];
272     e1 = d * d;
273     d = av->pos[1] - r->rop[1];
274     e1 += d * d;
275     d = av->pos[2] - r->rop[2];
276     e1 += d * d;
277 greg 1.1 e1 /= av->rad * av->rad;
278     if (e1 > ambacc*ambacc*1.21)
279     continue;
280     /*
281     * Normal direction test.
282     */
283     e2 = (1.0 - DOT(av->dir, r->ron)) * r->rweight;
284     if (e2 < 0.0) e2 = 0.0;
285     if (e1 + e2 > ambacc*ambacc*1.21)
286     continue;
287     /*
288     * Ray behind test.
289     */
290     d = 0.0;
291     for (j = 0; j < 3; j++)
292     d += (r->rop[j] - av->pos[j]) *
293     (av->dir[j] + r->ron[j]);
294 greg 1.18 if (d*0.5 < -minarad*ambacc-.001)
295 greg 1.1 continue;
296     /*
297     * Jittering final test reduces image artifacts.
298     */
299     wt = sqrt(e1) + sqrt(e2);
300 greg 2.31 if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
301 greg 1.1 continue;
302     if (wt <= 1e-3)
303     wt = 1e3;
304     else
305     wt = 1.0 / wt;
306     wsum += wt;
307 greg 2.34 extambient(ct, av, r->rop, rn);
308 greg 1.1 scalecolor(ct, wt);
309     addcolor(acol, ct);
310 greg 1.7 }
311     if (at->kid == NULL)
312     return(wsum);
313     /* do children */
314     s *= 0.5;
315     for (i = 0; i < 8; i++) {
316     for (j = 0; j < 3; j++) {
317     ck0[j] = c0[j];
318     if (1<<j & i)
319     ck0[j] += s;
320     if (r->rop[j] < ck0[j] - OCTSCALE*s)
321     break;
322     if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
323     break;
324     }
325     if (j == 3)
326 greg 2.34 wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
327 greg 1.1 }
328     return(wsum);
329     }
330    
331    
332     double
333 greg 2.34 makeambient(acol, r, rn, al) /* make a new ambient value */
334 greg 1.1 COLOR acol;
335     register RAY *r;
336 greg 2.34 FVECT rn;
337 greg 1.16 int al;
338 greg 1.1 {
339 greg 2.12 AMBVAL amb;
340 greg 1.14 FVECT gp, gd;
341 greg 1.16 /* compute weight */
342     amb.weight = pow(AVGREFL, (double)al);
343 greg 2.33 if (r->rweight < 0.1*amb.weight) /* heuristic */
344 greg 1.16 amb.weight = r->rweight;
345     /* compute ambient */
346     amb.rad = doambient(acol, r, amb.weight, gp, gd);
347 greg 2.33 if (amb.rad <= FTINY)
348 greg 1.1 return(0.0);
349     /* store it */
350     VCOPY(amb.pos, r->rop);
351     VCOPY(amb.dir, r->ron);
352 greg 1.16 amb.lvl = al;
353 greg 1.1 copycolor(amb.val, acol);
354 greg 1.14 VCOPY(amb.gpos, gp);
355     VCOPY(amb.gdir, gd);
356 greg 1.1 /* insert into tree */
357 greg 2.7 avsave(&amb); /* and save to file */
358 greg 2.34 if (rn != r->ron)
359     extambient(acol, &amb, r->rop, rn); /* texture */
360 greg 1.1 return(amb.rad);
361 greg 1.15 }
362    
363    
364     extambient(cr, ap, pv, nv) /* extrapolate value at pv, nv */
365     COLOR cr;
366 greg 2.12 register AMBVAL *ap;
367 greg 1.15 FVECT pv, nv;
368     {
369     FVECT v1, v2;
370     register int i;
371 greg 2.12 double d;
372 greg 1.15
373     d = 1.0; /* zeroeth order */
374     /* gradient due to translation */
375     for (i = 0; i < 3; i++)
376     d += ap->gpos[i]*(pv[i]-ap->pos[i]);
377     /* gradient due to rotation */
378     VCOPY(v1, ap->dir);
379     fcross(v2, v1, nv);
380     d += DOT(ap->gdir, v2);
381     if (d <= 0.0) {
382     setcolor(cr, 0.0, 0.0, 0.0);
383     return;
384     }
385     copycolor(cr, ap->val);
386     scalecolor(cr, d);
387 greg 1.1 }
388    
389    
390     static
391 greg 2.9 initambfile(creat) /* initialize ambient file */
392     int creat;
393     {
394     extern char *progname, *octname, VersionID[];
395    
396 greg 2.19 #ifdef F_SETLKW
397     aflock(creat ? F_WRLCK : F_RDLCK);
398     #endif
399 greg 2.12 #ifdef MSDOS
400     setmode(fileno(ambfp), O_BINARY);
401     #endif
402 greg 2.21 setbuf(ambfp, bmalloc(BUFSIZ+8));
403 greg 2.9 if (creat) { /* new file */
404 greg 2.24 newheader("RADIANCE", ambfp);
405 greg 2.9 fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
406     progname, colval(ambval,RED),
407     colval(ambval,GRN), colval(ambval,BLU),
408     ambounce, ambacc);
409     fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
410     ambdiv, ambssamp, ambres,
411     octname==NULL ? "" : octname);
412     fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
413     fputformat(AMBFMT, ambfp);
414     putc('\n', ambfp);
415     putambmagic(ambfp);
416 greg 2.17 } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
417     error(USER, "bad ambient file");
418 greg 2.9 }
419    
420    
421     static
422 greg 2.7 avsave(av) /* insert and save an ambient value */
423 greg 2.12 AMBVAL *av;
424 greg 1.1 {
425 greg 2.21 avinsert(avstore(av));
426 greg 1.1 if (ambfp == NULL)
427     return;
428 greg 2.5 if (writambval(av, ambfp) < 0)
429 greg 1.1 goto writerr;
430 greg 2.16 if (++nunflshed >= AMBFLUSH)
431 greg 2.7 if (ambsync() == EOF)
432 greg 1.1 goto writerr;
433     return;
434     writerr:
435 greg 2.17 error(SYSTEM, "error writing ambient file");
436 greg 1.1 }
437    
438    
439 greg 2.20 static AMBVAL *
440     avstore(aval) /* allocate memory and store aval */
441     register AMBVAL *aval;
442     {
443     register AMBVAL *av;
444    
445     if ((av = newambval()) == NULL)
446     error(SYSTEM, "out of memory in avstore");
447     copystruct(av, aval);
448 greg 2.26 av->latick = ambclock;
449     av->next = NULL;
450 greg 2.32 addcolor(avsum, av->val); /* add to sum for averaging */
451 greg 2.26 nambvals++;
452 greg 2.20 return(av);
453     }
454    
455    
456 greg 2.26 #define ATALLOCSZ 512 /* #/8 trees to allocate at once */
457    
458     static AMBTREE *atfreelist = NULL; /* free ambient tree structures */
459    
460    
461 greg 1.1 static
462 greg 2.26 AMBTREE *
463     newambtree() /* allocate 8 ambient tree structs */
464     {
465     register AMBTREE *atp, *upperlim;
466    
467     if (atfreelist == NULL) { /* get more nodes */
468     atfreelist = (AMBTREE *)bmalloc(ATALLOCSZ*8*sizeof(AMBTREE));
469     if (atfreelist == NULL)
470     return(NULL);
471     /* link new free list */
472     upperlim = atfreelist + 8*(ATALLOCSZ-1);
473     for (atp = atfreelist; atp < upperlim; atp += 8)
474     atp->kid = atp + 8;
475     atp->kid = NULL;
476     }
477     atp = atfreelist;
478     atfreelist = atp->kid;
479     bzero((char *)atp, 8*sizeof(AMBTREE));
480     return(atp);
481     }
482    
483    
484     static
485     freeambtree(atp) /* free 8 ambient tree structs */
486     AMBTREE *atp;
487     {
488     atp->kid = atfreelist;
489     atfreelist = atp;
490     }
491    
492    
493     static
494 greg 2.21 avinsert(av) /* insert ambient value in our tree */
495 greg 2.20 register AMBVAL *av;
496 greg 1.1 {
497 greg 2.21 register AMBTREE *at;
498 greg 2.23 register AMBVAL *ap;
499     AMBVAL avh;
500 greg 1.1 FVECT ck0;
501 greg 2.21 double s;
502 greg 1.1 int branch;
503     register int i;
504    
505 greg 2.20 if (av->rad <= FTINY)
506     error(CONSISTENCY, "zero ambient radius in avinsert");
507 greg 2.21 at = &atrunk;
508     VCOPY(ck0, thescene.cuorg);
509     s = thescene.cusize;
510 greg 1.1 while (s*(OCTSCALE/2) > av->rad*ambacc) {
511     if (at->kid == NULL)
512     if ((at->kid = newambtree()) == NULL)
513 greg 2.20 error(SYSTEM, "out of memory in avinsert");
514 greg 1.1 s *= 0.5;
515     branch = 0;
516     for (i = 0; i < 3; i++)
517     if (av->pos[i] > ck0[i] + s) {
518     ck0[i] += s;
519     branch |= 1 << i;
520     }
521     at = at->kid + branch;
522     }
523 greg 2.23 avh.next = at->alist; /* order by increasing level */
524     for (ap = &avh; ap->next != NULL; ap = ap->next)
525     if (ap->next->lvl >= av->lvl)
526     break;
527     av->next = ap->next;
528     ap->next = av;
529     at->alist = avh.next;
530 greg 2.7 }
531    
532    
533 greg 2.20 static
534 greg 2.26 unloadatree(at, f) /* unload an ambient value tree */
535 greg 2.20 register AMBTREE *at;
536 greg 2.26 int (*f)();
537 greg 2.20 {
538     register AMBVAL *av;
539     register int i;
540     /* transfer values at this node */
541     for (av = at->alist; av != NULL; av = at->alist) {
542     at->alist = av->next;
543 greg 2.26 (*f)(av);
544 greg 2.20 }
545 greg 2.21 if (at->kid == NULL)
546     return;
547 greg 2.20 for (i = 0; i < 8; i++) /* transfer and free children */
548 greg 2.26 unloadatree(at->kid+i, f);
549 greg 2.20 freeambtree(at->kid);
550 greg 2.26 at->kid = NULL;
551     }
552    
553    
554     static AMBVAL **avlist1, **avlist2; /* ambient value lists for sorting */
555     static int i_avlist; /* index for lists */
556    
557    
558     static
559     av2list(av)
560     AMBVAL *av;
561     {
562 greg 2.27 #ifdef DEBUG
563 greg 2.26 if (i_avlist >= nambvals)
564     error(CONSISTENCY, "too many ambient values in av2list1");
565 greg 2.27 #endif
566 greg 2.26 avlist1[i_avlist] = avlist2[i_avlist] = av;
567     i_avlist++;
568     }
569    
570    
571     static int
572     alatcmp(avp1, avp2) /* compare ambient values for MRA */
573     AMBVAL **avp1, **avp2;
574     {
575     return((**avp2).latick - (**avp1).latick);
576     }
577    
578    
579     static int
580     aposcmp(avp1, avp2) /* compare ambient value positions */
581     AMBVAL **avp1, **avp2;
582     {
583     return(*avp1 - *avp2);
584     }
585    
586    
587 greg 2.27 #ifdef DEBUG
588     static int
589     avlmemi(avaddr) /* find list position from address */
590     AMBVAL *avaddr;
591     {
592     register AMBVAL **avlpp;
593    
594     avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
595     nambvals, sizeof(AMBVAL *), aposcmp);
596     if (avlpp == NULL)
597     error(CONSISTENCY, "address not found in avlmemi");
598     return(avlpp - avlist2);
599     }
600     #else
601     #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
602     nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
603     #endif
604    
605    
606 greg 2.26 static
607     sortambvals(always) /* resort ambient values */
608     int always;
609     {
610     AMBTREE oldatrunk;
611     AMBVAL tav, *tap, *pnext;
612     register int i, j;
613 greg 2.28 /* see if it's time yet */
614     if (!always && (ambclock < lastsort+sortintvl ||
615     nambvals < SORT_THRESH))
616     return;
617 greg 2.26 /*
618     * The idea here is to minimize memory thrashing
619     * in VM systems by improving reference locality.
620     * We do this by periodically sorting our stored ambient
621     * values in memory in order of most recently to least
622     * recently accessed. This ordering was chosen so that new
623     * ambient values (which tend to be less important) go into
624     * higher memory with the infrequently accessed values.
625     * Since we expect our values to need sorting less
626     * frequently as the process continues, we double our
627     * waiting interval after each call.
628     * This routine is also called by setambacc() with
629     * the "always" parameter set to 1 so that the ambient
630     * tree will be rebuilt with the new accuracy parameter.
631     */
632 greg 2.27 if (tracktime) { /* allocate pointer arrays to sort */
633 greg 2.26 avlist1 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
634     avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
635     } else
636     avlist1 = avlist2 = NULL;
637 greg 2.27 if (avlist2 == NULL) { /* no time tracking -- rebuild tree? */
638 greg 2.26 if (avlist1 != NULL)
639     free((char *)avlist1);
640 greg 2.27 if (always) { /* rebuild without sorting */
641     copystruct(&oldatrunk, &atrunk);
642     atrunk.alist = NULL;
643     atrunk.kid = NULL;
644     unloadatree(&oldatrunk, avinsert);
645     }
646 greg 2.26 } else { /* sort memory by last access time */
647     /*
648     * Sorting memory is tricky because it isn't contiguous.
649     * We have to sort an array of pointers by MRA and also
650     * by memory position. We then copy values in "loops"
651     * to minimize memory hits. Nevertheless, we will visit
652 greg 2.27 * everyone at least twice, and this is an expensive process
653 greg 2.26 * when we're thrashing, which is when we need to do it.
654     */
655 greg 2.27 #ifdef DEBUG
656 greg 2.29 sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
657     nambvals, ambclock);
658 greg 2.27 eputs(errmsg);
659     #endif
660     i_avlist = 0;
661     unloadatree(&atrunk, av2list); /* empty current tree */
662     #ifdef DEBUG
663     if (i_avlist < nambvals)
664     error(CONSISTENCY, "missing ambient values in sortambvals");
665     #endif
666 greg 2.26 qsort((char *)avlist1, nambvals, sizeof(AMBVAL *), alatcmp);
667     qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
668     for (i = 0; i < nambvals; i++) {
669 greg 2.27 if (avlist1[i] == NULL)
670 greg 2.26 continue;
671     tap = avlist2[i];
672     copystruct(&tav, tap);
673     for (j = i; (pnext = avlist1[j]) != tap;
674 greg 2.27 j = avlmemi(pnext)) {
675 greg 2.26 copystruct(avlist2[j], pnext);
676     avinsert(avlist2[j]);
677     avlist1[j] = NULL;
678     }
679     copystruct(avlist2[j], &tav);
680     avinsert(avlist2[j]);
681     avlist1[j] = NULL;
682     }
683     free((char *)avlist1);
684     free((char *)avlist2);
685 greg 2.28 /* compute new sort interval */
686     sortintvl = ambclock - lastsort;
687 greg 2.32 if (sortintvl >= MAX_SORT_INTVL/2)
688 greg 2.28 sortintvl = MAX_SORT_INTVL;
689     else
690 greg 2.26 sortintvl <<= 1; /* wait twice as long next */
691 greg 2.27 #ifdef DEBUG
692     eputs("done\n");
693     #endif
694 greg 2.26 }
695     if (ambclock >= MAXACLOCK)
696     ambclock = MAXACLOCK/2;
697     lastsort = ambclock;
698 greg 2.20 }
699    
700    
701 greg 2.18 #ifdef F_SETLKW
702 greg 2.10
703 greg 2.19 static
704     aflock(typ) /* lock/unlock ambient file */
705     int typ;
706     {
707     static struct flock fls; /* static so initialized to zeroes */
708    
709     fls.l_type = typ;
710     if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
711     error(SYSTEM, "cannot (un)lock ambient file");
712     }
713    
714    
715 greg 2.16 int
716 greg 2.7 ambsync() /* synchronize ambient file */
717     {
718     static FILE *ambinp = NULL;
719 greg 2.15 static long lastpos = -1;
720     long flen;
721 greg 2.12 AMBVAL avs;
722 greg 2.7 register int n;
723 greg 2.16
724     if (nunflshed == 0)
725     return(0);
726 greg 2.19 if (lastpos < 0) /* initializing (locked in initambfile) */
727     goto syncend;
728 greg 2.7 /* gain exclusive access */
729 greg 2.19 aflock(F_WRLCK);
730 greg 2.7 /* see if file has grown */
731 greg 2.15 if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
732 greg 2.21 goto seekerr;
733 greg 2.15 if (n = flen - lastpos) { /* file has grown */
734 greg 2.17 if (ambinp == NULL) { /* use duplicate filedes */
735     ambinp = fdopen(dup(fileno(ambfp)), "r");
736 greg 2.14 if (ambinp == NULL)
737 greg 2.17 error(SYSTEM, "fdopen failed in ambsync");
738 greg 2.14 }
739 greg 2.15 if (fseek(ambinp, lastpos, 0) < 0)
740 greg 2.21 goto seekerr;
741 greg 2.15 while (n >= AMBVALSIZ) { /* load contributed values */
742 greg 2.37 if (!readambval(&avs, ambinp)) {
743     sprintf(errmsg,
744     "ambient file corrupted near character %ld",
745     flen - n);
746     error(WARNING, errmsg);
747     break;
748     }
749 greg 2.21 avinsert(avstore(&avs));
750 greg 2.15 n -= AMBVALSIZ;
751     }
752 greg 2.22 /*** seek always as safety measure
753     if (n) ***/ /* alignment */
754 greg 2.21 if (lseek(fileno(ambfp), flen-n, 0) < 0)
755     goto seekerr;
756 greg 2.7 }
757 greg 2.21 #ifdef DEBUG
758     if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
759     sprintf(errmsg, "ambient file buffer at %d rather than %d",
760     ambfp->_ptr - ambfp->_base,
761     nunflshed*AMBVALSIZ);
762     error(CONSISTENCY, errmsg);
763     }
764     #endif
765 greg 2.15 syncend:
766 greg 2.7 n = fflush(ambfp); /* calls write() at last */
767 greg 2.21 if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
768     goto seekerr;
769 greg 2.19 aflock(F_UNLCK); /* release file */
770 greg 2.16 nunflshed = 0;
771 greg 2.7 return(n);
772 greg 2.21 seekerr:
773     error(SYSTEM, "seek failed in ambsync");
774 greg 2.18 }
775    
776     #else
777    
778     int
779     ambsync() /* flush ambient file */
780     {
781     if (nunflshed == 0)
782     return(0);
783     nunflshed = 0;
784     return(fflush(ambfp));
785 greg 1.1 }
786 greg 2.10
787     #endif