ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
(Generate patch)

Comparing ray/src/rt/ambient.c (file contents):
Revision 2.16 by greg, Fri Jan 22 09:51:13 1993 UTC vs.
Revision 2.37 by greg, Tue May 28 14:24:44 1996 UTC

# Line 1 | Line 1
1 < /* Copyright (c) 1993 Regents of the University of California */
1 > /* Copyright (c) 1995 Regents of the University of California */
2  
3   #ifndef lint
4   static char SCCSid[] = "$SunId$ LBL";
# Line 18 | Line 18 | static char SCCSid[] = "$SunId$ LBL";
18  
19   #include  "random.h"
20  
21 < #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
21 > #ifndef  OCTSCALE
22 > #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
23 > #endif
24  
25   typedef struct ambtree {
26          AMBVAL  *alist;         /* ambient value list */
# Line 27 | Line 29 | typedef struct ambtree {
29  
30   extern CUBE  thescene;          /* contains space boundaries */
31  
32 + extern char  *shm_boundary;     /* memory sharing boundary */
33 +
34   #define  MAXASET        511     /* maximum number of elements in ambient set */
35   OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
36  
# Line 35 | Line 39 | double minarad;                /* minimum ambient radius */
39  
40   static AMBTREE  atrunk;         /* our ambient trunk node */
41  
38 static char  *ambfname = NULL;  /* ambient file name */
42   static FILE  *ambfp = NULL;     /* ambient file pointer */
43   static int  nunflshed = 0;      /* number of unflushed ambient values */
44  
45 + #ifndef SORT_THRESH
46 + #ifdef BIGMEM
47 + #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
48 + #else
49 + #define SORT_THRESH     ((3L<<20)/sizeof(AMBVAL))
50 + #endif
51 + #endif
52 + #ifndef SORT_INTVL
53 + #define SORT_INTVL      (SORT_THRESH*256)
54 + #endif
55 + #ifndef MAX_SORT_INTVL
56 + #define MAX_SORT_INTVL  (SORT_INTVL<<4)
57 + #endif
58 +
59 + static COLOR  avsum = BLKCOLOR;         /* computed ambient value sum */
60 + static unsigned int  nambvals = 0;      /* total number of indirect values */
61 + static unsigned int  nambshare = 0;     /* number of values from file */
62 + static unsigned long  ambclock = 0;     /* ambient access clock */
63 + static unsigned long  lastsort = 0;     /* time of last value sort */
64 + static long  sortintvl = SORT_INTVL;    /* time until next sort */
65 +
66 + #define MAXACLOCK       (1L<<30)        /* clock turnover value */
67 +        /*
68 +         * Track access times unless we are sharing ambient values
69 +         * through memory on a multiprocessor, when we want to avoid
70 +         * claiming our own memory (copy on write).  Go ahead anyway
71 +         * if more than two thirds of our values are unshared.
72 +         */
73 + #define tracktime       (shm_boundary == NULL || nambvals > 3*nambshare)
74 +
75   #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
76  
77   #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
78  
46 #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
47
79   extern long  ftell(), lseek();
80 < static int  initambfile(), avsave(), avinsert();
80 > static int  initambfile(), avsave(), avinsert(), sortambvals();
81 > static AMBVAL  *avstore();
82 > #ifdef  F_SETLKW
83 > static  aflock();
84 > #endif
85  
86  
87   setambres(ar)                           /* set ambient resolution */
88   int  ar;
89   {
90 +        ambres = ar < 0 ? 0 : ar;               /* may be done already */
91                                                  /* set min & max radii */
92          if (ar <= 0) {
93 <                minarad = 0.0;
93 >                minarad = 0;
94                  maxarad = thescene.cusize / 2.0;
95          } else {
96                  minarad = thescene.cusize / ar;
97 <                maxarad = 16.0 * minarad;               /* heuristic */
97 >                maxarad = 64 * minarad;                 /* heuristic */
98                  if (maxarad > thescene.cusize / 2.0)
99                          maxarad = thescene.cusize / 2.0;
100          }
101 <        if (maxarad <= FTINY)
102 <                maxarad = .001;
101 >        if (minarad <= FTINY)
102 >                minarad = 10*FTINY;
103 >        if (maxarad <= minarad)
104 >                maxarad = 64 * minarad;
105   }
106  
107  
108 + setambacc(newa)                         /* set ambient accuracy */
109 + double  newa;
110 + {
111 +        double  ambdiff;
112 +
113 +        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 + }
119 +
120 +
121   setambient(afile)                       /* initialize calculation */
122   char  *afile;
123   {
124 <        long  headlen;
124 >        long  pos, flen;
125          AMBVAL  amb;
126                                                  /* init ambient limits */
127          setambres(ambres);
128 +        setambacc(ambacc);
129 +        if (afile == NULL)
130 +                return;
131 +        if (ambacc <= FTINY) {
132 +                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
133 +                                afile);
134 +                error(WARNING, errmsg);
135 +                return;
136 +        }
137                                                  /* open ambient file */
138 <        if ((ambfname = afile) != NULL) {
139 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
140 <                        initambfile(0);
141 <                        headlen = ftell(ambfp);
142 <                        while (readambval(&amb, ambfp))
143 <                                avinsert(&amb, &atrunk, thescene.cuorg,
144 <                                                thescene.cusize);
145 <                                                        /* align */
146 <                        fseek(ambfp, -((ftell(ambfp)-headlen)%AMBVALSIZ), 1);
147 <                } else if ((ambfp = fopen(afile, "w+")) != NULL)
148 <                        initambfile(1);
149 <                else {
150 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
151 <                                        afile);
92 <                        error(SYSTEM, errmsg);
138 >        if ((ambfp = fopen(afile, "r+")) != NULL) {
139 >                initambfile(0);
140 >                pos = ftell(ambfp);
141 >                while (readambval(&amb, ambfp))
142 >                        avinsert(avstore(&amb));
143 >                                                /* align */
144 >                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 <                nunflshed++;    /* lie */
154 <                ambsync();
153 >                nambshare = nambvals;
154 >        } 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          }
160 +        nunflshed++;    /* lie */
161 +        ambsync();
162   }
163  
164  
# Line 119 | Line 184 | OBJECT obj;
184   }
185  
186  
187 < ambient(acol, r)                /* compute ambient component for ray */
187 > ambient(acol, r, nrm)           /* compute ambient component for ray */
188   COLOR  acol;
189   register RAY  *r;
190 + FVECT  nrm;
191   {
192          static int  rdepth = 0;                 /* ambient recursion */
193          double  d;
# Line 140 | Line 206 | register RAY  *r;
206                  rdepth++;
207                  d = doambient(acol, r, r->rweight, NULL, NULL);
208                  rdepth--;
209 <                if (d == 0.0)
209 >                if (d <= FTINY)
210                          goto dumbamb;
211                  return;
212          }
213 +                                                /* resort memory? */
214 +        sortambvals(0);
215                                                  /* get ambient value */
216          setcolor(acol, 0.0, 0.0, 0.0);
217 <        d = sumambient(acol, r, rdepth,
217 >        d = sumambient(acol, r, nrm, rdepth,
218                          &atrunk, thescene.cuorg, thescene.cusize);
219 <        if (d > FTINY)
219 >        if (d > FTINY) {
220                  scalecolor(acol, 1.0/d);
221 <        else {
154 <                d = makeambient(acol, r, rdepth++);
155 <                rdepth--;
221 >                return;
222          }
223 +        rdepth++;                               /* need to cache new value */
224 +        d = makeambient(acol, r, nrm, rdepth-1);
225 +        rdepth--;
226          if (d > FTINY)
227                  return;
228   dumbamb:                                        /* return global value */
229          copycolor(acol, ambval);
230 +        if (ambvwt <= 0 | nambvals == 0)
231 +                return;
232 +        scalecolor(acol, (double)ambvwt);
233 +        addcolor(acol, avsum);                  /* average in computations */
234 +        d = 1.0/(ambvwt+nambvals);
235 +        scalecolor(acol, d);
236   }
237  
238  
239   double
240 < sumambient(acol, r, al, at, c0, s)      /* get interpolated ambient value */
240 > sumambient(acol, r, rn, al, at, c0, s)  /* get interpolated ambient value */
241   COLOR  acol;
242   register RAY  *r;
243 + FVECT  rn;
244   int  al;
245   AMBTREE  *at;
246   FVECT  c0;
# Line 176 | Line 252 | double s;
252          int  i;
253          register int  j;
254          register AMBVAL  *av;
255 <                                        /* do this node */
255 >
256          wsum = 0.0;
257 +                                        /* do this node */
258          for (av = at->alist; av != NULL; av = av->next) {
259 +                if (tracktime)
260 +                        av->latick = ambclock++;
261                  /*
262                   *  Ambient level test.
263                   */
264 <                if (av->lvl > al || av->weight < r->rweight-FTINY)
264 >                if (av->lvl > al)       /* list sorted, so this works */
265 >                        break;
266 >                if (av->weight < r->rweight-FTINY)
267                          continue;
268                  /*
269                   *  Ambient radius test.
270                   */
271 <                e1 = 0.0;
272 <                for (j = 0; j < 3; j++) {
273 <                        d = av->pos[j] - r->rop[j];
274 <                        e1 += d * d;
275 <                }
271 >                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                  e1 /= av->rad * av->rad;
278                  if (e1 > ambacc*ambacc*1.21)
279                          continue;
# Line 215 | Line 297 | double s;
297                   *  Jittering final test reduces image artifacts.
298                   */
299                  wt = sqrt(e1) + sqrt(e2);
300 <                wt *= .9 + .2*urand(9015+samplendx);
219 <                if (wt > ambacc)
300 >                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
301                          continue;
302                  if (wt <= 1e-3)
303                          wt = 1e3;
304                  else
305                          wt = 1.0 / wt;
306                  wsum += wt;
307 <                extambient(ct, av, r->rop, r->ron);
307 >                extambient(ct, av, r->rop, rn);
308                  scalecolor(ct, wt);
309                  addcolor(acol, ct);
310          }
# Line 242 | Line 323 | double s;
323                                  break;
324                  }
325                  if (j == 3)
326 <                        wsum += sumambient(acol, r, al, at->kid+i, ck0, s);
326 >                        wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
327          }
328          return(wsum);
329   }
330  
331  
332   double
333 < makeambient(acol, r, al)        /* make a new ambient value */
333 > makeambient(acol, r, rn, al)    /* make a new ambient value */
334   COLOR  acol;
335   register RAY  *r;
336 + FVECT  rn;
337   int  al;
338   {
339          AMBVAL  amb;
340          FVECT   gp, gd;
341                                                  /* compute weight */
342          amb.weight = pow(AVGREFL, (double)al);
343 <        if (r->rweight < 0.2*amb.weight)        /* heuristic */
343 >        if (r->rweight < 0.1*amb.weight)        /* heuristic */
344                  amb.weight = r->rweight;
345                                                  /* compute ambient */
346          amb.rad = doambient(acol, r, amb.weight, gp, gd);
347 <        if (amb.rad == 0.0)
347 >        if (amb.rad <= FTINY)
348                  return(0.0);
349                                                  /* store it */
350          VCOPY(amb.pos, r->rop);
# Line 273 | Line 355 | int  al;
355          VCOPY(amb.gdir, gd);
356                                                  /* insert into tree */
357          avsave(&amb);                           /* and save to file */
358 +        if (rn != r->ron)
359 +                extambient(acol, &amb, r->rop, rn);     /* texture */
360          return(amb.rad);
361   }
362  
# Line 309 | Line 393 | int  creat;
393   {
394          extern char  *progname, *octname, VersionID[];
395  
396 + #ifdef  F_SETLKW
397 +        aflock(creat ? F_WRLCK : F_RDLCK);
398 + #endif
399   #ifdef MSDOS
400          setmode(fileno(ambfp), O_BINARY);
401   #endif
402 <        setbuf(ambfp, bmalloc(BUFSIZ));
402 >        setbuf(ambfp, bmalloc(BUFSIZ+8));
403          if (creat) {                    /* new file */
404 +                newheader("RADIANCE", ambfp);
405                  fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
406                                  progname, colval(ambval,RED),
407                                  colval(ambval,GRN), colval(ambval,BLU),
# Line 325 | Line 413 | int  creat;
413                  fputformat(AMBFMT, ambfp);
414                  putc('\n', ambfp);
415                  putambmagic(ambfp);
416 <        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp)) {
417 <                sprintf(errmsg, "bad ambient file \"%s\"", ambfname);
330 <                error(USER, errmsg);
331 <        }
416 >        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
417 >                error(USER, "bad ambient file");
418   }
419  
420  
# Line 336 | Line 422 | static
422   avsave(av)                              /* insert and save an ambient value */
423   AMBVAL  *av;
424   {
425 <        avinsert(av, &atrunk, thescene.cuorg, thescene.cusize);
425 >        avinsert(avstore(av));
426          if (ambfp == NULL)
427                  return;
428          if (writambval(av, ambfp) < 0)
# Line 346 | Line 432 | AMBVAL *av;
432                          goto writerr;
433          return;
434   writerr:
435 <        sprintf(errmsg, "error writing ambient file \"%s\"", ambfname);
350 <        error(SYSTEM, errmsg);
435 >        error(SYSTEM, "error writing ambient file");
436   }
437  
438  
439 + 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 +        av->latick = ambclock;
449 +        av->next = NULL;
450 +        addcolor(avsum, av->val);       /* add to sum for averaging */
451 +        nambvals++;
452 +        return(av);
453 + }
454 +
455 +
456 + #define ATALLOCSZ       512             /* #/8 trees to allocate at once */
457 +
458 + static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
459 +
460 +
461   static
462 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
463 < AMBVAL  *aval;
357 < register AMBTREE  *at;
358 < FVECT  c0;
359 < double  s;
462 > 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 + avinsert(av)                            /* insert ambient value in our tree */
495 + register AMBVAL  *av;
496 + {
497 +        register AMBTREE  *at;
498 +        register AMBVAL  *ap;
499 +        AMBVAL  avh;
500          FVECT  ck0;
501 +        double  s;
502          int  branch;
363        register AMBVAL  *av;
503          register int  i;
504  
505 <        if ((av = newambval()) == NULL)
506 <                goto memerr;
507 <        copystruct(av, aval);
508 <        VCOPY(ck0, c0);
505 >        if (av->rad <= FTINY)
506 >                error(CONSISTENCY, "zero ambient radius in avinsert");
507 >        at = &atrunk;
508 >        VCOPY(ck0, thescene.cuorg);
509 >        s = thescene.cusize;
510          while (s*(OCTSCALE/2) > av->rad*ambacc) {
511                  if (at->kid == NULL)
512                          if ((at->kid = newambtree()) == NULL)
513 <                                goto memerr;
513 >                                error(SYSTEM, "out of memory in avinsert");
514                  s *= 0.5;
515                  branch = 0;
516                  for (i = 0; i < 3; i++)
# Line 380 | Line 520 | double s;
520                          }
521                  at = at->kid + branch;
522          }
523 <        av->next = at->alist;
524 <        at->alist = av;
525 <        return;
526 < memerr:
527 <        error(SYSTEM, "out of memory in avinsert");
523 >        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   }
531  
532  
533 < #ifdef  NIX
533 > static
534 > unloadatree(at, f)                      /* unload an ambient value tree */
535 > register AMBTREE  *at;
536 > int     (*f)();
537 > {
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 >                (*f)(av);
544 >        }
545 >        if (at->kid == NULL)
546 >                return;
547 >        for (i = 0; i < 8; i++)         /* transfer and free children */
548 >                unloadatree(at->kid+i, f);
549 >        freeambtree(at->kid);
550 >        at->kid = NULL;
551 > }
552  
553 < int
554 < ambsync()                       /* flush ambient file */
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 <        if (nunflshed == 0)
563 <                return(0);
564 <        nunflshed = 0;
565 <        return(fflush(ambfp));
562 > #ifdef DEBUG
563 >        if (i_avlist >= nambvals)
564 >                error(CONSISTENCY, "too many ambient values in av2list1");
565 > #endif
566 >        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 + #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 + 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 +                                        /* see if it's time yet */
614 +        if (!always && (ambclock < lastsort+sortintvl ||
615 +                        nambvals < SORT_THRESH))
616 +                return;
617 +        /*
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 +        if (tracktime) {                /* allocate pointer arrays to sort */
633 +                avlist1 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
634 +                avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
635 +        } else
636 +                avlist1 = avlist2 = NULL;
637 +        if (avlist2 == NULL) {          /* no time tracking -- rebuild tree? */
638 +                if (avlist1 != NULL)
639 +                        free((char *)avlist1);
640 +                if (always) {           /* rebuild without sorting */
641 +                        copystruct(&oldatrunk, &atrunk);
642 +                        atrunk.alist = NULL;
643 +                        atrunk.kid = NULL;
644 +                        unloadatree(&oldatrunk, avinsert);
645 +                }
646 +        } 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 +                 * everyone at least twice, and this is an expensive process
653 +                 * when we're thrashing, which is when we need to do it.
654 +                 */
655 + #ifdef DEBUG
656 +                sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
657 +                                nambvals, ambclock);
658 +                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 +                qsort((char *)avlist1, nambvals, sizeof(AMBVAL *), alatcmp);
667 +                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
668 +                for (i = 0; i < nambvals; i++) {
669 +                        if (avlist1[i] == NULL)
670 +                                continue;
671 +                        tap = avlist2[i];
672 +                        copystruct(&tav, tap);
673 +                        for (j = i; (pnext = avlist1[j]) != tap;
674 +                                        j = avlmemi(pnext)) {
675 +                                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 +                                                /* compute new sort interval */
686 +                sortintvl = ambclock - lastsort;
687 +                if (sortintvl >= MAX_SORT_INTVL/2)
688 +                        sortintvl = MAX_SORT_INTVL;
689 +                else
690 +                        sortintvl <<= 1;        /* wait twice as long next */
691 + #ifdef DEBUG
692 +                eputs("done\n");
693 + #endif
694 +        }
695 +        if (ambclock >= MAXACLOCK)
696 +                ambclock = MAXACLOCK/2;
697 +        lastsort = ambclock;
698 + }
699 +
700 +
701 + #ifdef  F_SETLKW
702 +
703 + 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   int
716   ambsync()                       /* synchronize ambient file */
717   {
718          static FILE  *ambinp = NULL;
719          static long  lastpos = -1;
409        struct flock  fls;
720          long  flen;
721          AMBVAL  avs;
722          register int  n;
723  
724          if (nunflshed == 0)
725                  return(0);
726 <                                /* gain exclusive access */
417 <        fls.l_type = F_WRLCK;
418 <        fls.l_whence = 0;
419 <        fls.l_start = 0L;
420 <        fls.l_len = 0L;
421 <        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
422 <                error(SYSTEM, "cannot lock ambient file");
423 <        if (lastpos < 0)        /* initializing */
726 >        if (lastpos < 0)        /* initializing (locked in initambfile) */
727                  goto syncend;
728 +                                /* gain exclusive access */
729 +        aflock(F_WRLCK);
730                                  /* see if file has grown */
731          if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
732 <                error(SYSTEM, "cannot seek on ambient file");
732 >                goto seekerr;
733          if (n = flen - lastpos) {               /* file has grown */
734 <                if (ambinp == NULL) {
735 <                        ambinp = fopen(ambfname, "r");
734 >                if (ambinp == NULL) {           /* use duplicate filedes */
735 >                        ambinp = fdopen(dup(fileno(ambfp)), "r");
736                          if (ambinp == NULL)
737 <                                error(SYSTEM, "fopen failed in ambsync");
737 >                                error(SYSTEM, "fdopen failed in ambsync");
738                  }
739                  if (fseek(ambinp, lastpos, 0) < 0)
740 <                        error(SYSTEM, "fseek failed in ambsync");
740 >                        goto seekerr;
741                  while (n >= AMBVALSIZ) {        /* load contributed values */
742 <                        readambval(&avs, ambinp);
743 <                        avinsert(&avs,&atrunk,thescene.cuorg,thescene.cusize);
742 >                        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 >                        avinsert(avstore(&avs));
750                          n -= AMBVALSIZ;
751                  }
752 <                if (n)                          /* alignment */
753 <                        lseek(fileno(ambfp), flen-n, 0);
752 >                /*** seek always as safety measure
753 >                if (n) ***/                     /* alignment */
754 >                        if (lseek(fileno(ambfp), flen-n, 0) < 0)
755 >                                goto seekerr;
756          }
757 + #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   syncend:
766          n = fflush(ambfp);                      /* calls write() at last */
767 <        lastpos = lseek(fileno(ambfp), 0L, 1);
768 <        fls.l_type = F_UNLCK;                   /* release file */
769 <        fcntl(fileno(ambfp), F_SETLKW, &fls);
767 >        if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
768 >                goto seekerr;
769 >        aflock(F_UNLCK);                        /* release file */
770          nunflshed = 0;
771          return(n);
772 + seekerr:
773 +        error(SYSTEM, "seek failed in ambsync");
774 + }
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   }
786  
787   #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines