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.85 by greg, Tue May 6 17:15:11 2014 UTC vs.
Revision 2.110 by greg, Fri Feb 19 22:05:46 2021 UTC

# Line 1 | Line 1
1 #ifndef lint
1   static const char       RCSid[] = "$Id$";
3 #endif
2   /*
3   *  ambient.c - routines dealing with ambient (inter-reflected) component.
4   *
# Line 14 | Line 12 | static const char      RCSid[] = "$Id$";
12   #include  "platform.h"
13   #include  "ray.h"
14   #include  "otypes.h"
15 + #include  "otspecial.h"
16   #include  "resolu.h"
17   #include  "ambient.h"
18   #include  "random.h"
19 + #include  "pmapamb.h"
20  
21   #ifndef  OCTSCALE
22   #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
# Line 77 | Line 77 | static long  lastpos = -1;             /* last flush position */
77   #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
78  
79   #define  newambval()    (AMBVAL *)malloc(sizeof(AMBVAL))
80 #define  freeav(av)     free((void *)av);
80  
81 + #define  tfunc(lwr, x, upr)     (((x)-(lwr))/((upr)-(lwr)))
82 +
83   static void initambfile(int creat);
84   static void avsave(AMBVAL *av);
85   static AMBVAL *avstore(AMBVAL  *aval);
# Line 95 | Line 96 | static int aposcmp(const void *avp1, const void *avp2)
96   static int avlmemi(AMBVAL *avaddr);
97   static void sortambvals(int always);
98  
99 + static int      plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang);
100 + static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
101 +                                AMBTREE *at, FVECT c0, double s);
102 + static int      makeambient(COLOR acol, RAY *r, FVECT rn, int al);
103 + static int      extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
104 +                                FVECT uvw[3]);
105 +
106   #ifdef  F_SETLKW
107   static void aflock(int  typ);
108   #endif
# Line 109 | Line 117 | setambres(                             /* set ambient resolution */
117                                                  /* set min & max radii */
118          if (ar <= 0) {
119                  minarad = 0;
120 <                maxarad = thescene.cusize*0.5;
120 >                maxarad = thescene.cusize*0.2;
121          } else {
122                  minarad = thescene.cusize / ar;
123                  maxarad = 64.0 * minarad;               /* heuristic */
124 <                if (maxarad > thescene.cusize*0.5)
125 <                        maxarad = thescene.cusize*0.5;
124 >                if (maxarad > thescene.cusize*0.2)
125 >                        maxarad = thescene.cusize*0.2;
126          }
127          if (minarad <= FTINY)
128                  minarad = 10.0*FTINY;
# Line 133 | Line 141 | setambacc(                             /* set ambient accuracy */
141          newa *= (newa > 0);
142          if (fabs(newa - olda) >= .05*(newa + olda)) {
143                  ambacc = newa;
144 <                if (nambvals > 0)
144 >                if (ambacc > FTINY && nambvals > 0)
145                          sortambvals(1);         /* rebuild tree */
146          }
147   }
# Line 165 | Line 173 | setambient(void)                               /* initialize calculation */
173                  initambfile(0);                 /* file exists */
174                  lastpos = ftell(ambfp);
175                  while (readambval(&amb, ambfp))
176 <                        avinsert(avstore(&amb));
176 >                        avstore(&amb);
177                  nambshare = nambvals;           /* share loaded values */
178                  if (readonly) {
179                          sprintf(errmsg,
# Line 185 | Line 193 | setambient(void)                               /* initialize calculation */
193                                          (flen - lastpos)/AMBVALSIZ);
194                          error(WARNING, errmsg);
195                          fseek(ambfp, lastpos, SEEK_SET);
188 #ifndef _WIN32 /* XXX we need a replacement for that one */
196                          ftruncate(fileno(ambfp), (off_t)lastpos);
190 #endif
197                  }
198          } else if ((ambfp = fopen(ambfile, "w+")) != NULL) {
199                  initambfile(1);                 /* else create new file */
# Line 197 | Line 203 | setambient(void)                               /* initialize calculation */
203                  sprintf(errmsg, "cannot open ambient file \"%s\"", ambfile);
204                  error(SYSTEM, errmsg);
205          }
200 #ifdef getc_unlocked
201        flockfile(ambfp);                       /* application-level lock */
202 #endif
206   #ifdef  F_SETLKW
207          aflock(F_UNLCK);                        /* release file */
208   #endif
# Line 220 | Line 223 | ambdone(void)                  /* close ambient file and free memory
223                  lastpos = -1;
224          }
225                                          /* free ambient tree */
226 <        unloadatree(&atrunk, &avfree);
226 >        unloadatree(&atrunk, avfree);
227                                          /* reset state variables */
228          avsum = 0.;
229          navsum = 0;
# Line 261 | Line 264 | ambnotify(                     /* record new modifier */
264                  }
265   }
266  
264 /************ THE FOLLOWING ROUTINES DIFFER BETWEEN NEW & OLD ***************/
267  
266 #ifdef NEWAMB
267
268 #define tfunc(lwr, x, upr)      (((x)-(lwr))/((upr)-(lwr)))
269
270 static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
271                                AMBTREE *at, FVECT c0, double s);
272 static int      makeambient(COLOR acol, RAY *r, FVECT rn, int al);
273 static void     extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv,
274                                FVECT uvw[3]);
275
268   void
269   multambient(            /* compute ambient component & multiply by coef. */
270          COLOR  aval,
# Line 281 | Line 273 | multambient(           /* compute ambient component & multiply
273   )
274   {
275          static int  rdepth = 0;                 /* ambient recursion */
276 <        COLOR   acol;
277 <        int     ok;
276 >        COLOR   acol, caustic;
277 >        int     i, ok;
278          double  d, l;
279  
280 +        /* PMAP: Factor in ambient from photon map, if enabled and ray is
281 +         * ambient. Return as all ambient components accounted for, else
282 +         * continue. */
283 +        if (ambPmap(aval, r, rdepth))
284 +                return;
285 +
286 +        /* PMAP: Factor in specular-diffuse ambient (caustics) from photon
287 +         * map, if enabled and ray is primary, else caustic is zero.  Continue
288 +         * with RADIANCE ambient calculation */
289 +        copycolor(caustic, aval);
290 +        ambPmapCaustic(caustic, r, rdepth);
291 +        
292          if (ambdiv <= 0)                        /* no ambient calculation */
293                  goto dumbamb;
294                                                  /* check number of bounces */
# Line 296 | Line 300 | multambient(           /* compute ambient component & multiply
300                  goto dumbamb;
301  
302          if (ambacc <= FTINY) {                  /* no ambient storage */
303 +                FVECT   uvd[2];
304 +                float   dgrad[2], *dgp = NULL;
305 +
306 +                if (nrm != r->ron && DOT(nrm,r->ron) < 0.9999)
307 +                        dgp = dgrad;            /* compute rotational grad. */
308                  copycolor(acol, aval);
309                  rdepth++;
310 <                ok = doambient(acol, r, r->rweight, NULL, NULL, NULL, NULL);
310 >                ok = doambient(acol, r, r->rweight,
311 >                                uvd, NULL, NULL, dgp, NULL);
312                  rdepth--;
313                  if (!ok)
314                          goto dumbamb;
315 +                if ((ok > 0) & (dgp != NULL)) { /* apply texture */
316 +                        FVECT   v1;
317 +                        VCROSS(v1, r->ron, nrm);
318 +                        d = 1.0;
319 +                        for (i = 3; i--; )
320 +                                d += v1[i] * (dgp[0]*uvd[0][i] + dgp[1]*uvd[1][i]);
321 +                        if (d >= 0.05)
322 +                                scalecolor(acol, d);
323 +                }
324                  copycolor(aval, acol);
325 +
326 +                /* PMAP: add in caustic */
327 +                addcolor(aval, caustic);
328                  return;
329          }
330  
# Line 312 | Line 334 | multambient(           /* compute ambient component & multiply
334          setcolor(acol, 0.0, 0.0, 0.0);
335          d = sumambient(acol, r, nrm, rdepth,
336                          &atrunk, thescene.cuorg, thescene.cusize);
337 +                        
338          if (d > FTINY) {
339                  d = 1.0/d;
340                  scalecolor(acol, d);
341                  multcolor(aval, acol);
342 +
343 +                /* PMAP: add in caustic */
344 +                addcolor(aval, caustic);
345                  return;
346          }
347 +        
348          rdepth++;                               /* need to cache new value */
349          ok = makeambient(acol, r, nrm, rdepth-1);
350          rdepth--;
351 +        
352          if (ok) {
353                  multcolor(aval, acol);          /* computed new value */
354 +
355 +                /* PMAP: add in caustic */
356 +                addcolor(aval, caustic);
357                  return;
358          }
359 +        
360   dumbamb:                                        /* return global value */
361          if ((ambvwt <= 0) | (navsum == 0)) {
362                  multcolor(aval, ambval);
363 +                
364 +                /* PMAP: add in caustic */
365 +                addcolor(aval, caustic);
366                  return;
367          }
368 <        l = bright(ambval);                     /* average in computations */
368 >        
369 >        l = bright(ambval);                     /* average in computations */  
370          if (l > FTINY) {
371                  d = (log(l)*(double)ambvwt + avsum) /
372                                  (double)(ambvwt + navsum);
# Line 344 | Line 380 | dumbamb:                                       /* return global value */
380   }
381  
382  
383 < double
383 > /* Plug a potential leak where ambient cache value is occluded */
384 > static int
385 > plugaleak(RAY *r, AMBVAL *ap, FVECT anorm, double ang)
386 > {
387 >        const double    cost70sq = 0.1169778;   /* cos(70deg)^2 */
388 >        RAY             rtst;
389 >        FVECT           vdif;
390 >        double          normdot, ndotd, nadotd;
391 >        double          a, b, c, t[2];
392 >
393 >        ang += 2.*PI*(ang < 0);                 /* check direction flags */
394 >        if ( !(ap->corral>>(int)(ang*(16./PI)) & 1) )
395 >                return(0);
396 >        /*
397 >         * Generate test ray, targeting 20 degrees above sample point plane
398 >         * along surface normal from cache position.  This should be high
399 >         * enough to miss local geometry we don't really care about.
400 >         */
401 >        VSUB(vdif, ap->pos, r->rop);
402 >        normdot = DOT(anorm, r->ron);
403 >        ndotd = DOT(vdif, r->ron);
404 >        nadotd = DOT(vdif, anorm);
405 >        a = normdot*normdot - cost70sq;
406 >        b = 2.0*(normdot*ndotd - nadotd*cost70sq);
407 >        c = ndotd*ndotd - DOT(vdif,vdif)*cost70sq;
408 >        if (quadratic(t, a, b, c) != 2)
409 >                return(1);                      /* should rarely happen */
410 >        if (t[1] <= FTINY)
411 >                return(0);                      /* should fail behind test */
412 >        rayorigin(&rtst, SHADOW, r, NULL);
413 >        VSUM(rtst.rdir, vdif, anorm, t[1]);     /* further dist. > plane */
414 >        rtst.rmax = normalize(rtst.rdir);       /* short ray test */
415 >        while (localhit(&rtst, &thescene)) {    /* check for occluder */
416 >                OBJREC  *m = findmaterial(rtst.ro);
417 >                if (m != NULL && !istransp(m->otype) && !isBSDFproxy(m) &&
418 >                                (rtst.clipset == NULL ||
419 >                                        !inset(rtst.clipset, rtst.ro->omod)))
420 >                        return(1);              /* plug light leak */
421 >                VCOPY(rtst.rorg, rtst.rop);     /* skip invisible surface */
422 >                rtst.rmax -= rtst.rot;
423 >                rayclear(&rtst);
424 >        }
425 >        return(0);                              /* seems we're OK */
426 > }
427 >
428 >
429 > static double
430   sumambient(             /* get interpolated ambient value */
431          COLOR  acol,
432          RAY  *r,
# Line 387 | Line 469 | sumambient(            /* get interpolated ambient value */
469                  maxangle = (maxangle - PI/2.)*pow(r->rweight,0.13) + PI/2.;
470                                          /* sum this node */
471          for (av = at->alist; av != NULL; av = av->next) {
472 <                double  d, delta_r2, delta_t2;
472 >                double  u, v, d, delta_r2, delta_t2;
473                  COLOR   ct;
474                  FVECT   uvw[3];
475                                          /* record access */
# Line 396 | Line 478 | sumambient(            /* get interpolated ambient value */
478                  /*
479                   *  Ambient level test
480                   */
481 <                if (av->lvl > al)       /* list sorted, so this works */
481 >                if (av->lvl > al ||     /* list sorted, so this works */
482 >                                (av->lvl == al) & (av->weight < 0.9*r->rweight))
483                          break;
401                if (av->weight < 0.9*r->rweight)
402                        continue;
484                  /*
485                   *  Direction test using unperturbed normal
486                   */
# Line 426 | Line 507 | sumambient(            /* get interpolated ambient value */
507                   */
508                  decodedir(uvw[0], av->udir);
509                  VCROSS(uvw[1], uvw[2], uvw[0]);
510 <                d = DOT(ck0, uvw[0]) / av->rad[0];
510 >                d = (u = DOT(ck0, uvw[0])) / av->rad[0];
511                  delta_t2 += d*d;
512 <                d = DOT(ck0, uvw[1]) / av->rad[1];
512 >                d = (v = DOT(ck0, uvw[1])) / av->rad[1];
513                  delta_t2 += d*d;
514                  if (delta_t2 >= ambacc*ambacc)
515                          continue;
516                  /*
517 +                 *  Test for potential light leak
518 +                 */
519 +                if (av->corral && plugaleak(r, av, uvw[2], atan2a(v,u)))
520 +                        continue;
521 +                /*
522                   *  Extrapolate value and compute final weight (hat function)
523                   */
524 <                extambient(ct, av, r->rop, rn, uvw);
524 >                if (!extambient(ct, av, r->rop, rn, uvw))
525 >                        continue;
526                  d = tfunc(maxangle, sqrt(delta_r2), 0.0) *
527                          tfunc(ambacc, sqrt(delta_t2), 0.0);
528                  scalecolor(ct, d);
# Line 446 | Line 533 | sumambient(            /* get interpolated ambient value */
533   }
534  
535  
536 < int
536 > static int
537   makeambient(            /* make a new ambient value for storage */
538          COLOR  acol,
539          RAY  *r,
# Line 465 | Line 552 | makeambient(           /* make a new ambient value for storage
552                  amb.weight = 1.25*r->rweight;
553          setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
554                                                  /* compute ambient */
555 <        i = doambient(acol, r, amb.weight, uvw, amb.rad, amb.gpos, amb.gdir);
555 >        i = doambient(acol, r, amb.weight,
556 >                        uvw, amb.rad, amb.gpos, amb.gdir, &amb.corral);
557          scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
558          if (i <= 0 || amb.rad[0] <= FTINY)      /* no Hessian or zero radius */
559                  return(i);
# Line 485 | Line 573 | makeambient(           /* make a new ambient value for storage
573   }
574  
575  
576 < void
576 > static int
577   extambient(             /* extrapolate value at pv, nv */
578          COLOR  cr,
579          AMBVAL   *ap,
# Line 494 | Line 582 | extambient(            /* extrapolate value at pv, nv */
582          FVECT  uvw[3]
583   )
584   {
585 +        const double    min_d = 0.05;
586 +        const double    max_d = 20.;
587          static FVECT    my_uvw[3];
588          FVECT           v1;
589          int             i;
# Line 513 | Line 603 | extambient(            /* extrapolate value at pv, nv */
603          for (i = 3; i--; )
604                  d += v1[i] * (ap->gdir[0]*uvw[0][i] + ap->gdir[1]*uvw[1][i]);
605          
606 <        if (d <= 0.0) {
607 <                setcolor(cr, 0.0, 0.0, 0.0);
608 <                return;
609 <        }
606 >        if (d < min_d)                  /* clamp min/max scaling */
607 >                d = min_d;
608 >        else if (d > max_d)
609 >                d = max_d;
610          copycolor(cr, ap->val);
611          scalecolor(cr, d);
612 +        return(d > min_d);
613   }
614  
615  
# Line 555 | Line 646 | avinsert(                              /* insert ambient value in our tree */
646          }
647          avh.next = at->alist;           /* order by increasing level */
648          for (ap = &avh; ap->next != NULL; ap = ap->next)
649 <                if (ap->next->lvl >= av->lvl)
649 >                if ( ap->next->lvl > av->lvl ||
650 >                                (ap->next->lvl == av->lvl) &
651 >                                (ap->next->weight <= av->weight) )
652                          break;
653          av->next = ap->next;
654          ap->next = (AMBVAL*)av;
# Line 563 | Line 656 | avinsert(                              /* insert ambient value in our tree */
656   }
657  
658  
566 #else /* ! NEWAMB */
567
568 static double   sumambient(COLOR acol, RAY *r, FVECT rn, int al,
569                                AMBTREE *at, FVECT c0, double s);
570 static double   makeambient(COLOR acol, RAY *r, FVECT rn, int al);
571 static void     extambient(COLOR cr, AMBVAL *ap, FVECT pv, FVECT nv);
572
573
574 void
575 multambient(            /* compute ambient component & multiply by coef. */
576        COLOR  aval,
577        RAY  *r,
578        FVECT  nrm
579 )
580 {
581        static int  rdepth = 0;                 /* ambient recursion */
582        COLOR   acol;
583        double  d, l;
584
585        if (ambdiv <= 0)                        /* no ambient calculation */
586                goto dumbamb;
587                                                /* check number of bounces */
588        if (rdepth >= ambounce)
589                goto dumbamb;
590                                                /* check ambient list */
591        if (ambincl != -1 && r->ro != NULL &&
592                        ambincl != inset(ambset, r->ro->omod))
593                goto dumbamb;
594
595        if (ambacc <= FTINY) {                  /* no ambient storage */
596                copycolor(acol, aval);
597                rdepth++;
598                d = doambient(acol, r, r->rweight, NULL, NULL);
599                rdepth--;
600                if (d <= FTINY)
601                        goto dumbamb;
602                copycolor(aval, acol);
603                return;
604        }
605
606        if (tracktime)                          /* sort to minimize thrashing */
607                sortambvals(0);
608                                                /* interpolate ambient value */
609        setcolor(acol, 0.0, 0.0, 0.0);
610        d = sumambient(acol, r, nrm, rdepth,
611                        &atrunk, thescene.cuorg, thescene.cusize);
612        if (d > FTINY) {
613                d = 1.0/d;
614                scalecolor(acol, d);
615                multcolor(aval, acol);
616                return;
617        }
618        rdepth++;                               /* need to cache new value */
619        d = makeambient(acol, r, nrm, rdepth-1);
620        rdepth--;
621        if (d > FTINY) {
622                multcolor(aval, acol);          /* got new value */
623                return;
624        }
625 dumbamb:                                        /* return global value */
626        if ((ambvwt <= 0) | (navsum == 0)) {
627                multcolor(aval, ambval);
628                return;
629        }
630        l = bright(ambval);                     /* average in computations */
631        if (l > FTINY) {
632                d = (log(l)*(double)ambvwt + avsum) /
633                                (double)(ambvwt + navsum);
634                d = exp(d) / l;
635                scalecolor(aval, d);
636                multcolor(aval, ambval);        /* apply color of ambval */
637        } else {
638                d = exp( avsum / (double)navsum );
639                scalecolor(aval, d);            /* neutral color */
640        }
641 }
642
643
644 static double
645 sumambient(     /* get interpolated ambient value */
646        COLOR  acol,
647        RAY  *r,
648        FVECT  rn,
649        int  al,
650        AMBTREE  *at,
651        FVECT  c0,
652        double  s
653 )
654 {
655        double  d, e1, e2, wt, wsum;
656        COLOR  ct;
657        FVECT  ck0;
658        int  i;
659        int  j;
660        AMBVAL   *av;
661
662        wsum = 0.0;
663                                        /* do this node */
664        for (av = at->alist; av != NULL; av = av->next) {
665                double  rn_dot = -2.0;
666                if (tracktime)
667                        av->latick = ambclock;
668                /*
669                 *  Ambient level test.
670                 */
671                if (av->lvl > al)       /* list sorted, so this works */
672                        break;
673                if (av->weight < 0.9*r->rweight)
674                        continue;
675                /*
676                 *  Ambient radius test.
677                 */
678                VSUB(ck0, av->pos, r->rop);
679                e1 = DOT(ck0, ck0) / (av->rad * av->rad);
680                if (e1 > ambacc*ambacc*1.21)
681                        continue;
682                /*
683                 *  Direction test using closest normal.
684                 */
685                d = DOT(av->dir, r->ron);
686                if (rn != r->ron) {
687                        rn_dot = DOT(av->dir, rn);
688                        if (rn_dot > 1.0-FTINY)
689                                rn_dot = 1.0-FTINY;
690                        if (rn_dot >= d-FTINY) {
691                                d = rn_dot;
692                                rn_dot = -2.0;
693                        }
694                }
695                e2 = (1.0 - d) * r->rweight;
696                if (e2 < 0.0)
697                        e2 = 0.0;
698                else if (e1 + e2 > ambacc*ambacc*1.21)
699                        continue;
700                /*
701                 *  Ray behind test.
702                 */
703                d = 0.0;
704                for (j = 0; j < 3; j++)
705                        d += (r->rop[j] - av->pos[j]) *
706                                        (av->dir[j] + r->ron[j]);
707                if (d*0.5 < -minarad*ambacc-.001)
708                        continue;
709                /*
710                 *  Jittering final test reduces image artifacts.
711                 */
712                e1 = sqrt(e1);
713                e2 = sqrt(e2);
714                wt = e1 + e2;
715                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
716                        continue;
717                /*
718                 *  Recompute directional error using perturbed normal
719                 */
720                if (rn_dot > 0.0) {
721                        e2 = sqrt((1.0 - rn_dot)*r->rweight);
722                        wt = e1 + e2;
723                }
724                if (wt <= 1e-3)
725                        wt = 1e3;
726                else
727                        wt = 1.0 / wt;
728                wsum += wt;
729                extambient(ct, av, r->rop, rn);
730                scalecolor(ct, wt);
731                addcolor(acol, ct);
732        }
733        if (at->kid == NULL)
734                return(wsum);
735                                        /* do children */
736        s *= 0.5;
737        for (i = 0; i < 8; i++) {
738                for (j = 0; j < 3; j++) {
739                        ck0[j] = c0[j];
740                        if (1<<j & i)
741                                ck0[j] += s;
742                        if (r->rop[j] < ck0[j] - OCTSCALE*s)
743                                break;
744                        if (r->rop[j] > ck0[j] + (1.0+OCTSCALE)*s)
745                                break;
746                }
747                if (j == 3)
748                        wsum += sumambient(acol, r, rn, al,
749                                                at->kid+i, ck0, s);
750        }
751        return(wsum);
752 }
753
754
755 static double
756 makeambient(            /* make a new ambient value for storage */
757        COLOR  acol,
758        RAY  *r,
759        FVECT  rn,
760        int  al
761 )
762 {
763        AMBVAL  amb;
764        FVECT   gp, gd;
765        int     i;
766
767        amb.weight = 1.0;                       /* compute weight */
768        for (i = al; i-- > 0; )
769                amb.weight *= AVGREFL;
770        if (r->rweight < 0.1*amb.weight)        /* heuristic override */
771                amb.weight = 1.25*r->rweight;
772        setcolor(acol, AVGREFL, AVGREFL, AVGREFL);
773                                                /* compute ambient */
774        amb.rad = doambient(acol, r, amb.weight, gp, gd);
775        if (amb.rad <= FTINY) {
776                setcolor(acol, 0.0, 0.0, 0.0);
777                return(0.0);
778        }
779        scalecolor(acol, 1./AVGREFL);           /* undo assumed reflectance */
780                                                /* store value */
781        VCOPY(amb.pos, r->rop);
782        VCOPY(amb.dir, r->ron);
783        amb.lvl = al;
784        copycolor(amb.val, acol);
785        VCOPY(amb.gpos, gp);
786        VCOPY(amb.gdir, gd);
787                                                /* insert into tree */
788        avsave(&amb);                           /* and save to file */
789        if (rn != r->ron)
790                extambient(acol, &amb, r->rop, rn);     /* texture */
791        return(amb.rad);
792 }
793
794
659   static void
796 extambient(             /* extrapolate value at pv, nv */
797        COLOR  cr,
798        AMBVAL   *ap,
799        FVECT  pv,
800        FVECT  nv
801 )
802 {
803        FVECT  v1;
804        int  i;
805        double  d;
806
807        d = 1.0;                        /* zeroeth order */
808                                        /* gradient due to translation */
809        for (i = 0; i < 3; i++)
810                d += ap->gpos[i]*(pv[i]-ap->pos[i]);
811                                        /* gradient due to rotation */
812        VCROSS(v1, ap->dir, nv);
813        d += DOT(ap->gdir, v1);
814        if (d <= 0.0) {
815                setcolor(cr, 0.0, 0.0, 0.0);
816                return;
817        }
818        copycolor(cr, ap->val);
819        scalecolor(cr, d);
820 }
821
822
823 static void
824 avinsert(                               /* insert ambient value in our tree */
825        AMBVAL *av
826 )
827 {
828        AMBTREE  *at;
829        AMBVAL  *ap;
830        AMBVAL  avh;
831        FVECT  ck0;
832        double  s;
833        int  branch;
834        int  i;
835
836        if (av->rad <= FTINY)
837                error(CONSISTENCY, "zero ambient radius in avinsert");
838        at = &atrunk;
839        VCOPY(ck0, thescene.cuorg);
840        s = thescene.cusize;
841        while (s*(OCTSCALE/2) > av->rad*ambacc) {
842                if (at->kid == NULL)
843                        if ((at->kid = newambtree()) == NULL)
844                                error(SYSTEM, "out of memory in avinsert");
845                s *= 0.5;
846                branch = 0;
847                for (i = 0; i < 3; i++)
848                        if (av->pos[i] > ck0[i] + s) {
849                                ck0[i] += s;
850                                branch |= 1 << i;
851                        }
852                at = at->kid + branch;
853        }
854        avh.next = at->alist;           /* order by increasing level */
855        for (ap = &avh; ap->next != NULL; ap = ap->next)
856                if (ap->next->lvl >= av->lvl)
857                        break;
858        av->next = ap->next;
859        ap->next = (AMBVAL*)av;
860        at->alist = avh.next;
861 }
862
863 #endif  /* ! NEWAMB */
864
865 /************* FOLLOWING ROUTINES SAME FOR NEW & OLD METHODS ***************/
866
867 static void
660   initambfile(            /* initialize ambient file */
661          int  cre8
662   )
# Line 905 | Line 697 | avsave(                                /* insert and save an ambient value */
697          AMBVAL  *av
698   )
699   {
700 <        avinsert(avstore(av));
700 >        avstore(av);
701          if (ambfp == NULL)
702                  return;
703          if (writambval(av, ambfp) < 0)
# Line 920 | Line 712 | writerr:
712  
713  
714   static AMBVAL *
715 < avstore(                                /* allocate memory and store aval */
715 > avstore(                                /* allocate memory and save aval */
716          AMBVAL  *aval
717   )
718   {
# Line 938 | Line 730 | avstore(                               /* allocate memory and store aval */
730                  avsum += log(d);
731                  navsum++;
732          }
733 +        avinsert(av);                   /* insert in our cache tree */
734          return(av);
735   }
736  
# Line 964 | Line 757 | newambtree(void)                               /* allocate 8 ambient tree structs
757          }
758          atp = atfreelist;
759          atfreelist = atp->kid;
760 <        memset((char *)atp, '\0', 8*sizeof(AMBTREE));
760 >        memset(atp, 0, 8*sizeof(AMBTREE));
761          return(atp);
762   }
763  
# Line 990 | Line 783 | unloadatree(                   /* unload an ambient value tree */
783                                          /* transfer values at this node */
784          for (av = at->alist; av != NULL; av = at->alist) {
785                  at->alist = av->next;
786 +                av->next = NULL;
787                  (*f)(av);
788          }
789          if (at->kid == NULL)
# Line 1067 | Line 861 | avlmemi(                               /* find list position from address */
861   {
862          AMBVAL  **avlpp;
863  
864 <        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
865 <                        nambvals, sizeof(AMBVAL *), &aposcmp);
864 >        avlpp = (AMBVAL **)bsearch(&avaddr, avlist2,
865 >                        nambvals, sizeof(AMBVAL *), aposcmp);
866          if (avlpp == NULL)
867                  error(CONSISTENCY, "address not found in avlmemi");
868          return(avlpp - avlist2);
# Line 1111 | Line 905 | sortambvals(                   /* resort ambient values */
905          }
906          if (avlist1 == NULL) {          /* no time tracking -- rebuild tree? */
907                  if (avlist2 != NULL)
908 <                        free((void *)avlist2);
908 >                        free(avlist2);
909                  if (always) {           /* rebuild without sorting */
910                          oldatrunk = atrunk;
911                          atrunk.alist = NULL;
912                          atrunk.kid = NULL;
913 <                        unloadatree(&oldatrunk, &avinsert);
913 >                        unloadatree(&oldatrunk, avinsert);
914                  }
915          } else {                        /* sort memory by last access time */
916                  /*
# Line 1133 | Line 927 | sortambvals(                   /* resort ambient values */
927                  eputs(errmsg);
928   #endif
929                  i_avlist = 0;
930 <                unloadatree(&atrunk, &av2list); /* empty current tree */
930 >                unloadatree(&atrunk, av2list);  /* empty current tree */
931   #ifdef DEBUG
932                  if (i_avlist < nambvals)
933                          error(CONSISTENCY, "missing ambient values in sortambvals");
934   #endif
935 <                qsort((char *)avlist1, nambvals, sizeof(struct avl), &alatcmp);
936 <                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), &aposcmp);
935 >                qsort(avlist1, nambvals, sizeof(struct avl), alatcmp);
936 >                qsort(avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
937                  for (i = 0; i < nambvals; i++) {
938                          if (avlist1[i].p == NULL)
939                                  continue;
# Line 1155 | Line 949 | sortambvals(                   /* resort ambient values */
949                          avinsert(avlist2[j]);
950                          avlist1[j].p = NULL;
951                  }
952 <                free((void *)avlist1);
953 <                free((void *)avlist2);
952 >                free(avlist1);
953 >                free(avlist2);
954                                                  /* compute new sort interval */
955                  sortintvl = ambclock - lastsort;
956                  if (sortintvl >= MAX_SORT_INTVL/2)
# Line 1184 | Line 978 | aflock(                        /* lock/unlock ambient file */
978  
979          if (typ == fls.l_type)          /* already called? */
980                  return;
981 +
982          fls.l_type = typ;
983 <        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
984 <                error(SYSTEM, "cannot (un)lock ambient file");
983 >        do
984 >                if (fcntl(fileno(ambfp), F_SETLKW, &fls) != -1)
985 >                        return;
986 >        while (errno == EINTR);
987 >        
988 >        error(SYSTEM, "cannot (un)lock ambient file");
989   }
990  
991  
# Line 1205 | Line 1004 | ambsync(void)                  /* synchronize ambient file */
1004          if ((flen = lseek(fileno(ambfp), (off_t)0, SEEK_END)) < 0)
1005                  goto seekerr;
1006          if ((n = flen - lastpos) > 0) {         /* file has grown */
1007 <                if (ambinp == NULL) {           /* use duplicate filedes */
1008 <                        ambinp = fdopen(dup(fileno(ambfp)), "r");
1007 >                if (ambinp == NULL) {           /* get new file pointer */
1008 >                        ambinp = fopen(ambfile, "rb");
1009                          if (ambinp == NULL)
1010 <                                error(SYSTEM, "fdopen failed in ambsync");
1010 >                                error(SYSTEM, "fopen failed in ambsync");
1011                  }
1012                  if (fseek(ambinp, lastpos, SEEK_SET) < 0)
1013                          goto seekerr;
# Line 1220 | Line 1019 | ambsync(void)                  /* synchronize ambient file */
1019                                  error(WARNING, errmsg);
1020                                  break;
1021                          }
1022 <                        avinsert(avstore(&avs));
1022 >                        avstore(&avs);
1023                          n -= AMBVALSIZ;
1024                  }
1025 <                lastpos = flen - n;
1026 <                /*** seek always as safety measure
1027 <                if (n) ***/                     /* alignment */
1229 <                        if (lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1230 <                                goto seekerr;
1025 >                lastpos = flen - n;             /* check alignment */
1026 >                if (n && lseek(fileno(ambfp), (off_t)lastpos, SEEK_SET) < 0)
1027 >                        goto seekerr;
1028          }
1029          n = fflush(ambfp);                      /* calls write() at last */
1030 <        if (n != EOF)
1234 <                lastpos += (long)nunflshed*AMBVALSIZ;
1235 <        else if ((lastpos = lseek(fileno(ambfp), (off_t)0, SEEK_CUR)) < 0)
1236 <                goto seekerr;
1237 <                
1030 >        lastpos += (long)nunflshed*AMBVALSIZ;
1031          aflock(F_UNLCK);                        /* release file */
1032          nunflshed = 0;
1033          return(n);
1034   seekerr:
1035          error(SYSTEM, "seek failed in ambsync");
1036 <        return -1; /* pro forma return */
1036 >        return(EOF);    /* pro forma return */
1037   }
1038  
1039   #else   /* ! F_SETLKW */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines