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

Comparing ray/src/rt/pmapcontrib.c (file contents):
Revision 2.12 by rschregle, Tue May 17 17:39:47 2016 UTC vs.
Revision 2.17 by rschregle, Tue Mar 20 19:55:33 2018 UTC

# Line 4 | Line 4 | static const char RCSid[] = "$Id$";
4  
5   /*
6     ======================================================================
7 <   Photon map support for light source contributions
7 >   Photon map for light source contributions
8  
9     Roland Schregle (roland.schregle@{hslu.ch, gmail.com})
10     (c) Lucerne University of Applied Sciences and Arts,
# Line 23 | Line 23 | static const char RCSid[] = "$Id$";
23   #include "pmapdiag.h"
24   #include "rcontrib.h"
25   #include "otypes.h"
26 < #include <sys/mman.h>
27 < #include <sys/wait.h>
26 > #if NIX
27 >   #include <sys/mman.h>
28 >   #include <sys/wait.h>  
29 > #endif
30  
31  
30
31 static void setPmapContribParams (PhotonMap *pmap, LUTAB *srcContrib)
32 /* Set parameters for light source contributions */
33 {
34   /* Set light source modifier list and appropriate callback to extract
35    * their contributions from the photon map */
36   if (pmap) {
37      pmap -> srcContrib = srcContrib;
38      pmap -> lookup = photonContrib;
39      /* Ensure we get all requested photon contribs during lookups */
40      pmap -> gatherTolerance = 1.0;
41   }
42 }
43
44
45
46 static void checkPmapContribs (const PhotonMap *pmap, LUTAB *srcContrib)
47 /* Check modifiers for light source contributions */
48 {
49   const PhotonPrimary  *primary = pmap -> primaries;
50   PhotonPrimaryIdx     i, found = 0;
51   OBJREC *srcMod;
52  
53   /* Make sure at least one of the modifiers is actually in the pmap,
54    * otherwise findPhotons() winds up in an infinite loop! */
55   for (i = pmap -> numPrimary; i; --i, ++primary) {
56      if (primary -> srcIdx < 0 || primary -> srcIdx >= nsources)
57         error(INTERNAL, "invalid light source index in photon map");
58        
59      srcMod = findmaterial(source [primary -> srcIdx].so);
60      if ((MODCONT*)lu_find(srcContrib, srcMod -> oname) -> data)
61         ++found;
62   }
63  
64   if (!found)
65      error(USER, "modifiers not in photon map");
66 }
67
68  
69
70 void initPmapContrib (LUTAB *srcContrib, unsigned numSrcContrib)
71 {
72   unsigned t;
73  
74   for (t = 0; t < NUM_PMAP_TYPES; t++)
75      if (photonMaps [t] && t != PMAP_TYPE_CONTRIB) {
76         sprintf(errmsg, "%s photon map does not support contributions",
77                 pmapName [t]);
78         error(USER, errmsg);
79      }
80  
81   /* Get params */
82   setPmapContribParams(contribPmap, srcContrib);
83  
84   if (contribPhotonMapping) {
85      if (contribPmap -> maxGather < numSrcContrib) {
86         /* Adjust density estimate bandwidth if lower than modifier
87          * count, otherwise contributions are missing */
88         error(WARNING, "contrib density estimate bandwidth too low, "
89                        "adjusting to modifier count");
90         contribPmap -> maxGather = numSrcContrib;
91      }
92      
93      /* Sanity check */
94      checkPmapContribs(contribPmap, srcContrib);
95   }
96 }
97
98
99
32   static PhotonPrimaryIdx newPhotonPrimary (PhotonMap *pmap,
33                                            const RAY *primRay,
34                                            FILE *primHeap)
# Line 111 | Line 43 | static PhotonPrimaryIdx newPhotonPrimary (PhotonMap *p
43        return 0;
44        
45     /* Check if last primary ray has spawned photons (srcIdx >= 0, see
46 <    * newPhoton()), in which case we write it to the primary heap file
47 <    * before overwriting it */
46 >    * newPhoton()), in which case we save it to the primary heap file
47 >    * before clobbering it */
48     if (pmap -> lastPrimary.srcIdx >= 0) {
49        if (!fwrite(&pmap -> lastPrimary, sizeof(PhotonPrimary), 1, primHeap))
50           error(SYSTEM, "failed writing photon primary in newPhotonPrimary");
# Line 128 | Line 60 | static PhotonPrimaryIdx newPhotonPrimary (PhotonMap *p
60      
61     if (primRay) {
62        FVECT dvec;
63 <      
63 >
64 > #ifdef PMAP_PRIMARYDIR            
65        /* Reverse incident direction to point to light source */
66        dvec [0] = -primRay -> rdir [0];
67        dvec [1] = -primRay -> rdir [1];
68        dvec [2] = -primRay -> rdir [2];
69        pmap -> lastPrimary.dir = encodedir(dvec);
70 + #endif      
71   #ifdef PMAP_PRIMARYPOS      
72        VCOPY(pmap -> lastPrimary.pos, primRay -> rop);
73   #endif      
# Line 144 | Line 78 | static PhotonPrimaryIdx newPhotonPrimary (PhotonMap *p
78  
79  
80  
81 < #ifdef DEBUG_PMAP_CONTRIB
81 > #ifdef DEBUG_PMAP
82   static int checkPrimaryHeap (FILE *file)
83   /* Check heap for ordered primaries */
84   {
# Line 184 | Line 118 | static int checkPrimaryHeap (FILE *file)
118  
119  
120   static PhotonPrimaryIdx buildPrimaries (PhotonMap *pmap, FILE **primaryHeap,
121 +                                        char **primaryHeapFname,
122                                          PhotonPrimaryIdx *primaryOfs,
123                                          unsigned numHeaps)
124   /* Consolidate per-subprocess photon primary heaps into the primary array
# Line 201 | Line 136 | static PhotonPrimaryIdx buildPrimaries (PhotonMap *pma
136     for (heap = 0; heap < numHeaps; heap++) {
137        primaryOfs [heap] = pmap -> numPrimary;
138        
139 <      if (fseek(primaryHeap [heap], 0, SEEK_END))
139 >      if (fseek(primaryHeap [heap], 0, SEEK_END) < 0)
140           error(SYSTEM, "failed photon primary seek in buildPrimaries");
141        pmap -> numPrimary += heapLen = ftell(primaryHeap [heap]) /
142                                        sizeof(PhotonPrimary);      
# Line 217 | Line 152 | static PhotonPrimaryIdx buildPrimaries (PhotonMap *pma
152                  heapLen, primaryHeap [heap]) != heapLen)
153           error(SYSTEM, "failed reading photon primaries in buildPrimaries");
154        
155 <      fclose(primaryHeap [heap]);      
155 >      fclose(primaryHeap [heap]);
156 >      unlink(primaryHeapFname [heap]);
157     }
158    
159     return pmap -> numPrimary;
# Line 236 | Line 172 | typedef  unsigned long  PhotonContribCnt;
172  
173  
174  
175 +
176 +
177 +
178   void distribPhotonContrib (PhotonMap* pm, unsigned numProc)
179   {
180     EmissionMap       emap;
181 <   char              errmsg2 [128], shmFname [255];
181 >   char              errmsg2 [128], shmFname [PMAP_TMPFNLEN];
182     unsigned          srcIdx, proc;
183     int               shmFile, stat, pid;
184     double            *srcFlux,         /* Emitted flux per light source */
185                       srcDistribTarget; /* Target photon count per source */
186     PhotonContribCnt  *photonCnt;       /* Photon emission counter array */
187 <   const unsigned    photonCntSize = sizeof(PhotonContribCnt) *
187 >   unsigned          photonCntSize = sizeof(PhotonContribCnt) *
188                                       PHOTONCNT_NUMEMIT(nsources);
189 <   FILE              *primaryHeap [numProc];
190 <   PhotonPrimaryIdx  primaryOfs [numProc];
189 >   FILE              **primaryHeap = NULL;
190 >   char              **primaryHeapFname = NULL;
191 >   PhotonPrimaryIdx  *primaryOfs = NULL;
192                                      
193     if (!pm)
194        error(USER, "no photon map defined in distribPhotonContrib");
# Line 285 | Line 225 | void distribPhotonContrib (PhotonMap* pm, unsigned num
225    
226     /* Per-subprocess / per-source target counts */
227     pm -> distribTarget /= numProc;
228 <   srcDistribTarget = nsources ? (double)pm -> distribTarget / nsources : 0;
228 >   srcDistribTarget = nsources ? (double)pm -> distribTarget / nsources : 0;  
229    
230 <   /* Get photon ports if specified */
231 <   if (ambincl == 1)
232 <      getPhotonPorts();
230 >   if (!pm -> distribTarget)
231 >      error(INTERNAL, "no photons to distribute in distribPhotonContrib");
232 >  
233 >   /* Get photon ports from modifier list */
234 >   getPhotonPorts(photonPortList);
235        
236     /* Get photon sensor modifiers */
237     getPhotonSensors(photonSensorList);      
238 <  
238 >
239 > #if NIX  
240     /* Set up shared mem for photon counters (zeroed by ftruncate) */
241 < #if 0  
299 <   snprintf(shmFname, 255, PMAP_SHMFNAME, getpid());
300 <   shmFile = shm_open(shmFname, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
301 < #else
302 <   strcpy(shmFname, PMAP_SHMFNAME);
241 >   strcpy(shmFname, PMAP_TMPFNAME);
242     shmFile = mkstemp(shmFname);
304 #endif        
243    
244     if (shmFile < 0 || ftruncate(shmFile, photonCntSize) < 0)
245        error(SYSTEM, "failed shared mem init in distribPhotonContrib");
# Line 311 | Line 249 | void distribPhotonContrib (PhotonMap* pm, unsigned num
249                      
250     if (photonCnt == MAP_FAILED)
251        error(SYSTEM, "failed shared mem mapping in distribPhotonContrib");
252 + #else
253 +   /* Allocate photon counters statically on Windoze */
254 +   if (!(photonCnt = malloc(photonCntSize)))
255 +      error(SYSTEM, "failed trivial malloc in distribPhotonContrib");
256 +  
257 +   for (srcIdx = 0; srcIdx < PHOTONCNT_NUMEMIT(nsources); srcIdx++)
258 +      photonCnt [srcIdx] = 0;
259 + #endif /* NIX */
260  
261 +   if (verbose) {
262 +      sprintf(errmsg, "\nIntegrating flux from %d sources", nsources);
263 +
264 +      if (photonPorts) {
265 +         sprintf(errmsg2, " via %d ports", numPhotonPorts);
266 +         strcat(errmsg, errmsg2);
267 +      }
268 +
269 +      strcat(errmsg, "\n");
270 +      eputs(errmsg);
271 +   }
272 +
273     /* =============================================================
274 <    * FLUX INTEGRATION - Get total flux emitted from light source
274 >    * FLUX INTEGRATION - Get total flux emitted from sources/ports
275      * ============================================================= */  
276     for (srcIdx = 0; srcIdx < nsources; srcIdx++) {
277 <      unsigned portCnt = 0;
320 <      
277 >      unsigned portCnt = 0;      
278        srcFlux [srcIdx] = 0;
279        emap.src = source + srcIdx;
280        
324      if (photonRepTime)
325         eputs("\n");
326
281        do {  /* Need at least one iteration if no ports! */      
282           emap.port = emap.src -> sflags & SDISTANT ? photonPorts + portCnt
283                                                     : NULL;
284           photonPartition [emap.src -> so -> otype] (&emap);
285 <        
286 <         if (photonRepTime) {
287 <            sprintf(errmsg, "Integrating flux from source %s (mod %s) ",
288 <                    source [srcIdx].so -> oname,
289 <                    objptr(source [srcIdx].so -> omod) -> oname);
336 <                    
285 >
286 >         if (verbose) {
287 >            sprintf(errmsg, "\tIntegrating flux from source %s ",
288 >                    source [srcIdx].so -> oname);
289 >
290              if (emap.port) {
291                 sprintf(errmsg2, "via port %s ",
292                         photonPorts [portCnt].so -> oname);
293                 strcat(errmsg, errmsg2);
294              }
295 <            
296 <            sprintf(errmsg2, "(%lu partitions)...\n", emap.numPartitions);
295 >
296 >            sprintf(errmsg2, "(%lu partitions)\n", emap.numPartitions);
297              strcat(errmsg, errmsg2);
298              eputs(errmsg);
299 + #if NIX            
300              fflush(stderr);
301 <         }
301 > #endif            
302 >         }                    
303          
304           for (emap.partitionCnt = 0; emap.partitionCnt < emap.numPartitions;
305                emap.partitionCnt++) {
# Line 361 | Line 316 | void distribPhotonContrib (PhotonMap* pm, unsigned num
316           error(WARNING, errmsg);
317        }
318     }  
319 <
320 <   if (photonRepTime)
321 <      eputs("\n");
322 <
323 <   /* Init per-subprocess primary heap files */
324 <   for (proc = 0; proc < numProc; proc++)
325 <      if (!(primaryHeap [proc] = tmpfile()))
319 >  
320 >   /* Allocate & init per-subprocess primary heap files */
321 >   primaryHeap = calloc(numProc, sizeof(FILE*));
322 >   primaryHeapFname = calloc(numProc, sizeof(char*));
323 >   primaryOfs = calloc(numProc, sizeof(PhotonPrimaryIdx));
324 >   if (!primaryHeap || !primaryHeapFname || !primaryOfs)
325 >      error(SYSTEM, "failed primary heap allocation in "
326 >            "distribPhotonContrib");
327 >      
328 >   for (proc = 0; proc < numProc; proc++) {
329 >      primaryHeapFname [proc] = malloc(PMAP_TMPFNLEN);
330 >      if (!primaryHeapFname [proc])
331 >         error(SYSTEM, "failed primary heap file allocation in "
332 >               "distribPhotonContrib");
333 >              
334 >      mktemp(strcpy(primaryHeapFname [proc], PMAP_TMPFNAME));
335 >      if (!(primaryHeap [proc] = fopen(primaryHeapFname [proc], "w+b")))
336           error(SYSTEM, "failed opening primary heap file in "
337                 "distribPhotonContrib");
338 +   }              
339 +
340 +   /* Record start time for progress reports */
341 +   repStartTime = time(NULL);
342 +
343 +   if (verbose) {
344 +      sprintf(errmsg, "\nPhoton distribution @ %d procs\n", numProc);
345 +      eputs(errmsg);
346 +   }
347                
348     /* MAIN LOOP */
349     for (proc = 0; proc < numProc; proc++) {
350 + #if NIX          
351        if (!(pid = fork())) {
352 <         /* SUBPROCESS ENTERS HERE;
353 <          * all opened and memory mapped files are inherited */
354 <          
352 >         /* SUBPROCESS ENTERS HERE; opened and mmapped files inherited */
353 > #else
354 >      if (1) {
355 >         /* No subprocess under Windoze */
356 > #endif  
357           /* Local photon counters for this subprocess */
358           unsigned long  lastNumPhotons = 0, localNumEmitted = 0;
359 <         double         photonFluxSum = 0;   /* Running photon flux sum */
359 >         double         photonFluxSum = 0;   /* Accum. photon flux */
360  
361           /* Seed RNGs from PID for decorellated photon distribution */
362           pmapSeed(randSeed + proc, partState);
363 <         pmapSeed(randSeed + proc, emitState);
364 <         pmapSeed(randSeed + proc, cntState);
365 <         pmapSeed(randSeed + proc, mediumState);
366 <         pmapSeed(randSeed + proc, scatterState);
367 <         pmapSeed(randSeed + proc, rouletteState);
363 >         pmapSeed(randSeed + (proc + 1) % numProc, emitState);
364 >         pmapSeed(randSeed + (proc + 2) % numProc, cntState);
365 >         pmapSeed(randSeed + (proc + 3) % numProc, mediumState);
366 >         pmapSeed(randSeed + (proc + 4) % numProc, scatterState);
367 >         pmapSeed(randSeed + (proc + 5) % numProc, rouletteState);
368 >
369 > #ifdef PMAP_SIGUSR                      
370 >   double partNumEmit;
371 >   unsigned long partEmitCnt;
372 >   double srcPhotonFlux, avgPhotonFlux;
373 >   unsigned       portCnt, passCnt, prePassCnt;
374 >   float          srcPreDistrib;
375 >   double         srcNumEmit;     /* # to emit from source */
376 >   unsigned long  srcNumDistrib;  /* # stored */
377 >
378 >   void sigUsrDiags()
379 >   /* Loop diags via SIGUSR1 */
380 >   {
381 >      sprintf(errmsg,
382 >              "********************* Proc %d Diags *********************\n"
383 >              "srcIdx = %d (%s)\nportCnt = %d (%s)\npassCnt = %d\n"
384 >              "srcFlux = %f\nsrcPhotonFlux = %f\navgPhotonFlux = %f\n"
385 >              "partNumEmit = %f\npartEmitCnt = %lu\n\n",
386 >              proc, srcIdx, findmaterial(source [srcIdx].so) -> oname,
387 >              portCnt, photonPorts [portCnt].so -> oname,
388 >              passCnt, srcFlux [srcIdx], srcPhotonFlux, avgPhotonFlux,
389 >              partNumEmit, partEmitCnt);
390 >      eputs(errmsg);
391 >      fflush(stderr);
392 >   }
393 > #endif
394          
395 + #if PMAP_SIGUSR
396 +         signal(SIGUSR1, sigUsrDiags);
397 + #endif        
398 +        
399 +         /* Output child process PID after random delay to prevent corrupted
400 +          * console output due to race condition */
401 +         usleep(1e6 * pmapRandom(rouletteState));
402 +         fprintf(stderr, "Proc %d: PID = %d\n", proc, getpid());
403 +         /* Allow time for debugger to attach to child process */
404 +         sleep(10);
405 +
406           /* =============================================================
407            * 2-PASS PHOTON DISTRIBUTION
408            * Pass 1 (pre):  emit fraction of target photon count
# Line 397 | Line 411 | void distribPhotonContrib (PhotonMap* pm, unsigned num
411            *                count
412            * ============================================================= */        
413           for (srcIdx = 0; srcIdx < nsources; srcIdx++) {
414 + #ifndef PMAP_SIGUSR        
415              unsigned       portCnt, passCnt = 0, prePassCnt = 0;
416              float          srcPreDistrib = preDistrib;
417              double         srcNumEmit = 0;       /* # to emit from source */
418              unsigned long  srcNumDistrib = pm -> numPhotons;  /* # stored */
419 + #else
420 +            passCnt = prePassCnt = 0;
421 +            srcPreDistrib = preDistrib;
422 +            srcNumEmit = 0;       /* # to emit from source */
423 +            srcNumDistrib = pm -> numPhotons;  /* # stored */
424 + #endif            
425  
426              if (srcFlux [srcIdx] < FTINY)
427                 continue;
# Line 410 | Line 431 | void distribPhotonContrib (PhotonMap* pm, unsigned num
431                    /* INIT PASS 1 */
432                    if (++prePassCnt > maxPreDistrib) {
433                       /* Warn if no photons contributed after sufficient
434 <                      * iterations */
435 <                     sprintf(errmsg, "proc %d, source %s: "
436 <                             "too many prepasses, skipped",
437 <                             proc, source [srcIdx].so -> oname);
438 <                     error(WARNING, errmsg);
434 >                      * iterations; only output from subprocess 0 to reduce
435 >                      * console clutter */
436 >                     if (!proc) {
437 >                        sprintf(errmsg,
438 >                                "source %s: too many prepasses, skipped",
439 >                                source [srcIdx].so -> oname);
440 >                        error(WARNING, errmsg);
441 >                     }
442 >
443                       break;
444                    }
445                    
# Line 423 | Line 448 | void distribPhotonContrib (PhotonMap* pm, unsigned num
448                 }
449                 else {
450                    /* INIT PASS 2 */
451 + #ifndef PMAP_SIGUSR
452                    double srcPhotonFlux, avgPhotonFlux;
453 + #endif
454                    
455                    /* Based on the outcome of the predistribution we can now
456                     * figure out how many more photons we have to emit from
# Line 445 | Line 472 | void distribPhotonContrib (PhotonMap* pm, unsigned num
472                    srcPhotonFlux = srcFlux [srcIdx] / srcNumEmit;
473                    avgPhotonFlux = photonFluxSum / (srcIdx + 1);
474                    
475 <                  if (avgPhotonFlux > 0 &&
475 >                  if (avgPhotonFlux > FTINY &&
476                        srcPhotonFlux / avgPhotonFlux < FTINY) {
477                       /* Skip source if its photon flux is grossly below the
478 <                      * running average, indicating negligible contribs at
479 <                      * the expense of excessive distribution time */
480 <                     sprintf(errmsg, "proc %d, source %s: "
481 <                             "itsy bitsy photon flux, skipped",
482 <                             proc, source [srcIdx].so -> oname);
483 <                     error(WARNING, errmsg);
484 <                     srcNumEmit = 0;
478 >                      * running average, indicating negligible contributions
479 >                      * at the expense of excessive distribution time; only
480 >                      * output from subproc 0 to reduce console clutter */
481 >                     if (!proc) {
482 >                        sprintf(errmsg,
483 >                                "source %s: itsy bitsy photon flux, skipped",
484 >                                source [srcIdx].so -> oname);                    
485 >                        error(WARNING, errmsg);
486 >                     }
487 >
488 >                     srcNumEmit = 0;   /* Or just break??? */
489                    }
490                          
491                    /* Update sum of photon flux per light source */
492                    photonFluxSum += srcPhotonFlux;
493                 }
494 <              
494 >                              
495                 portCnt = 0;
496                 do {    /* Need at least one iteration if no ports! */
497                    emap.src = source + srcIdx;
498                    emap.port = emap.src -> sflags & SDISTANT
499                                ? photonPorts + portCnt : NULL;
500                    photonPartition [emap.src -> so -> otype] (&emap);
501 <                  
502 <                  if (photonRepTime && !proc) {
501 >
502 >                  if (verbose && !proc) {
503 >                     /* Output from subproc 0 only to avoid race condition
504 >                      * on console I/O */
505                       if (!passCnt)
506 <                        sprintf(errmsg, "PREPASS %d on source %s (mod %s) ",
507 <                                prePassCnt, source [srcIdx].so -> oname,
475 <                                objptr(source[srcIdx].so->omod) -> oname);
506 >                        sprintf(errmsg, "\tPREPASS %d on source %s ",
507 >                                prePassCnt, source [srcIdx].so -> oname);
508                       else
509 <                        sprintf(errmsg, "MAIN PASS on source %s (mod %s) ",
510 <                                source [srcIdx].so -> oname,
511 <                                objptr(source[srcIdx].so->omod) -> oname);
480 <                            
509 >                        sprintf(errmsg, "\tMAIN PASS on source %s ",
510 >                                source [srcIdx].so -> oname);
511 >
512                       if (emap.port) {
513                          sprintf(errmsg2, "via port %s ",
514                                  photonPorts [portCnt].so -> oname);
515                          strcat(errmsg, errmsg2);
516                       }
517 <                    
517 >
518                       sprintf(errmsg2, "(%lu partitions)\n",
519                               emap.numPartitions);
520 <                     strcat(errmsg, errmsg2);
520 >                     strcat(errmsg, errmsg2);                    
521                       eputs(errmsg);
522 + #if NIX                    
523                       fflush(stderr);
524 <                  }
524 > #endif                    
525 >                  }                
526                    
527                    for (emap.partitionCnt = 0; emap.partitionCnt < emap.numPartitions;
528                         emap.partitionCnt++) {
529 + #ifndef PMAP_SIGUSR                      
530                       double partNumEmit;
531                       unsigned long partEmitCnt;
532 + #endif
533                      
534                       /* Get photon origin within current source partishunn
535                        * and build emission map */
# Line 513 | Line 548 | void distribPhotonContrib (PhotonMap* pm, unsigned num
548                          partEmitCnt++;
549                          
550                       /* Update local and shared global emission counter */
516                     localNumEmitted += partEmitCnt;                                    
551                       photonCnt [PHOTONCNT_NUMEMIT(srcIdx)] += partEmitCnt;
552 +                     localNumEmitted += partEmitCnt;                                    
553                      
554 <                     /* Integer counter avoids FP rounding errors */
554 >                     /* Integer counter avoids FP rounding errors during
555 >                      * iteration */
556                       while (partEmitCnt--) {
557                          RAY photonRay;
558                      
# Line 525 | Line 561 | void distribPhotonContrib (PhotonMap* pm, unsigned num
561                           * until absorbed/leaked; emitPhoton() sets the
562                           * emitting light source index in photonRay */
563                          emitPhoton(&emap, &photonRay);
564 + #if 1
565 +                        if (emap.port)
566 +                           /* !!!  PHOTON PORT REJECTION SAMPLING HACK: set
567 +                            * !!!  photon port as fake hit object for
568 +                            * !!!  primary ray to check for intersection in
569 +                            * !!!  tracePhoton() */                        
570 +                           photonRay.ro = emap.port -> so;
571 + #endif
572                          newPhotonPrimary(pm, &photonRay, primaryHeap[proc]);
573                          /* Set subprocess index in photonRay for post-
574                           * distrib primary index linearisation; this is
# Line 538 | Line 582 | void distribPhotonContrib (PhotonMap* pm, unsigned num
582                       photonCnt [PHOTONCNT_NUMPHOT] += pm -> numPhotons -
583                                                        lastNumPhotons;
584                       lastNumPhotons = pm -> numPhotons;
585 + #if !NIX
586 +                     /* Synchronous progress report on Windoze */
587 +                     if (!proc && photonRepTime > 0 &&
588 +                           time(NULL) >= repLastTime + photonRepTime) {
589 +                        unsigned s;                        
590 +                        repComplete = pm -> distribTarget * numProc;
591 +                        repProgress = photonCnt [PHOTONCNT_NUMPHOT];
592 +                        
593 +                        for (repEmitted = 0, s = 0; s < nsources; s++)
594 +                           repEmitted += photonCnt [PHOTONCNT_NUMEMIT(s)];
595 +
596 +                        pmapDistribReport();
597 +                     }
598 + #endif
599                    }
600  
601                    portCnt++;
602                 } while (portCnt < numPhotonPorts);                  
603  
604 <               if (pm -> numPhotons == srcNumDistrib)
604 >               if (pm -> numPhotons == srcNumDistrib) {
605                    /* Double predistrib factor in case no photons were stored
606                     * for this source and redo pass 1 */
607                    srcPreDistrib *= 2;
608 +               }
609                 else {
610                    /* Now do pass 2 */
611                    passCnt++;
553 /*                if (photonRepTime)
554                     eputs("\n"); */
612                 }
613              }
614           }
615                          
616           /* Flush heap buffa one final time to prevent data corruption */
617 <         flushPhotonHeap(pm);
561 <         fclose(pm -> heap);
562 <        
617 >         flushPhotonHeap(pm);        
618           /* Flush final photon primary to primary heap file */
619           newPhotonPrimary(pm, NULL, primaryHeap [proc]);
620 <         fclose(primaryHeap [proc]);
620 >         /* Heap files closed automatically on exit
621 >            fclose(pm -> heap);
622 >            fclose(primaryHeap [proc]); */
623                    
624   #ifdef DEBUG_PMAP
625 <         sprintf(errmsg, "Proc %d exited with total %ld photons\n", proc,
625 >         sprintf(errmsg, "Proc %d total %ld photons\n", proc,
626                   pm -> numPhotons);
627           eputs(errmsg);
628 +         fflush(stderr);
629   #endif
630  
631 + #ifdef PMAP_SIGUSR
632 +         signal(SIGUSR1, SIG_DFL);
633 + #endif
634 +
635 + #if NIX
636 +         /* Terminate subprocess */
637           exit(0);
638 + #endif
639        }
640        else if (pid < 0)
641           error(SYSTEM, "failed to fork subprocess in distribPhotonContrib");
642     }
643  
644 + #if NIX
645     /* PARENT PROCESS CONTINUES HERE */
580   /* Record start time and enable progress report signal handler */
581   repStartTime = time(NULL);
646   #ifdef SIGCONT
647 +   /* Enable progress report signal handler */
648     signal(SIGCONT, pmapDistribReport);
649   #endif
585 /*
586   if (photonRepTime)
587      eputs("\n"); */
588  
650     /* Wait for subprocesses to complete while reporting progress */
651     proc = numProc;
652     while (proc) {
# Line 599 | Line 660 | void distribPhotonContrib (PhotonMap* pm, unsigned num
660        
661        /* Nod off for a bit and update progress  */
662        sleep(1);
663 <      
664 <      /* Update progress report from shared subprocess counters */
663 >
664 >      /* Asynchronous progress report from shared subprocess counters */      
665        repComplete = pm -> distribTarget * numProc;
666 <      repProgress = photonCnt [PHOTONCNT_NUMPHOT];
666 >      repProgress = photonCnt [PHOTONCNT_NUMPHOT];      
667 >      
668        for (repEmitted = 0, srcIdx = 0; srcIdx < nsources; srcIdx++)
669           repEmitted += photonCnt [PHOTONCNT_NUMEMIT(srcIdx)];
670  
# Line 615 | Line 677 | void distribPhotonContrib (PhotonMap* pm, unsigned num
677        else signal(SIGCONT, pmapDistribReport);
678   #endif
679     }
680 + #endif /* NIX */
681  
682     /* ================================================================
683      * POST-DISTRIBUTION - Set photon flux and build kd-tree, etc.
684      * ================================================================ */
685   #ifdef SIGCONT    
686 +   /* Reset signal handler */
687     signal(SIGCONT, SIG_DFL);
688   #endif  
689     free(emap.samples);
690  
691     if (!pm -> numPhotons)
692 <      error(USER, "empty photon map");
692 >      error(USER, "empty contribution photon map");
693  
694     /* Load per-subprocess primary rays into pm -> primary array */
695 <   pm -> numPrimary = buildPrimaries(pm, primaryHeap, primaryOfs, numProc);
695 >   /* Dumb compilers apparently need the char** cast */
696 >   pm -> numPrimary = buildPrimaries(pm, primaryHeap,
697 >                                     (char**)primaryHeapFname,
698 >                                     primaryOfs, numProc);
699     if (!pm -> numPrimary)
700        error(INTERNAL, "no primary rays in contribution photon map");
701    
702     /* Set photon flux per source */
703     for (srcIdx = 0; srcIdx < nsources; srcIdx++)
704        srcFlux [srcIdx] /= photonCnt [PHOTONCNT_NUMEMIT(srcIdx)];
705 <
705 > #if NIX
706     /* Photon counters no longer needed, unmap shared memory */
707     munmap(photonCnt, sizeof(*photonCnt));
708     close(shmFile);
642 #if 0  
643   shm_unlink(shmFname);
644 #else
709     unlink(shmFname);
710 + #else
711 +   free(photonCnt);  
712   #endif      
713    
714 <   if (photonRepTime) {
715 <      eputs("\nBuilding contrib photon map...\n");
714 >   if (verbose) {
715 >      eputs("\nBuilding contribution photon map...\n");
716 > #if NIX      
717        fflush(stderr);
718 + #endif      
719     }
720    
721     /* Build underlying data structure; heap is destroyed */
722 <   buildPhotonMap(pm, srcFlux, primaryOfs, numProc);  
655 < }
656 <
657 <
658 <
659 < void photonContrib (PhotonMap *pmap, RAY *ray, COLOR irrad)
660 < /* Sum up light source contributions from photons in pmap->srcContrib */
661 < {
662 <   unsigned                i;
663 <   PhotonSearchQueueNode   *sqn;
664 <   float                   r, invArea;
665 <   RREAL                   rayCoeff [3];
666 <   Photon                  *photon;
667 <   static char             warn = 1;
668 <
669 <   setcolor(irrad, 0, 0, 0);
670 <
671 <   if (!pmap -> maxGather)
672 <      return;
673 <      
674 <   /* Ignore sources */
675 <   if (ray -> ro && islight(objptr(ray -> ro -> omod) -> otype))
676 <      return;
677 <
678 <   /* Get cumulative path coefficient up to photon lookup point */
679 <   raycontrib(rayCoeff, ray, PRIMARY);
680 <
681 <   /* Lookup photons */
682 <   pmap -> squeue.tail = 0;
683 <   findPhotons(pmap, ray);
722 >   buildPhotonMap(pm, srcFlux, primaryOfs, numProc);
723    
724 <   /* Need at least 2 photons */
725 <   if (pmap -> squeue.tail < 2) {
726 < #ifdef PMAP_NONEFOUND
688 <      sprintf(errmsg, "no photons found on %s at (%.3f, %.3f, %.3f)",
689 <              ray -> ro ? ray -> ro -> oname : "<null>",
690 <              ray -> rop [0], ray -> rop [1], ray -> rop [2]);
691 <      error(WARNING, errmsg);
692 < #endif
724 >   /* Free per-subprocess primary heap files */
725 >   for (proc = 0; proc < numProc; proc++)
726 >      free(primaryHeapFname [proc]);
727        
728 <      return;
729 <   }
730 <
697 <   /* Average (squared) radius between furthest two photons to improve
698 <    * accuracy and get inverse search area 1 / (PI * r^2), with extra
699 <    * normalisation factor 1 / PI for ambient calculation */
700 <   sqn = pmap -> squeue.node + 1;
701 <   r = max(sqn -> dist2, (sqn + 1) -> dist2);
702 <   r = 0.25 * (pmap -> maxDist2 + r + 2 * sqrt(pmap -> maxDist2 * r));  
703 <   invArea = 1 / (PI * PI * r);
728 >   free(primaryHeapFname);
729 >   free(primaryHeap);
730 >   free(primaryOfs);
731    
732 <   /* Skip the extra photon */
733 <   for (i = 1 ; i < pmap -> squeue.tail; i++, sqn++) {        
707 <      COLOR flux;
708 <      
709 <      /* Get photon's contribution to density estimate */
710 <      photon = getNearestPhoton(&pmap -> squeue, sqn -> idx);
711 <      getPhotonFlux(photon, flux);
712 <      scalecolor(flux, invArea);      
713 < #ifdef PMAP_EPANECHNIKOV
714 <      /* Apply Epanechnikov kernel to photon flux based on photon distance */
715 <      scalecolor(flux, 2 * (1 - sqn -> dist2 / r));
716 < #endif
717 <      addcolor(irrad, flux);
718 <      
719 <      if (pmap -> srcContrib) {      
720 <         const PhotonPrimary  *primary = pmap -> primaries +
721 <                                         photon -> primary;
722 <         const SRCREC         *sp = &source [primary -> srcIdx];
723 <         OBJREC               *srcMod = findmaterial(sp -> so);
724 <         MODCONT *srcContrib = (MODCONT*)lu_find(pmap -> srcContrib,
725 <                                                 srcMod -> oname) -> data;
726 <         double   srcBinReal;
727 <         int      srcBin;
728 <         RAY      srcRay;                                                
729 <                                                
730 <         if (!srcContrib)
731 <            continue;
732 <
733 <         /* Photon's emitting light source has modifier whose contributions
734 <          * are sought */
735 <         if (srcContrib -> binv -> type != NUM) {
736 <            /* Use intersection function to set shadow ray parameters if
737 <             * it's not simply a constant */
738 <            rayorigin(&srcRay, SHADOW, NULL, NULL);
739 <            srcRay.rsrc = primary -> srcIdx;
740 < #ifdef PMAP_PRIMARYPOS
741 <            VCOPY(srcRay.rorg, primary -> pos);
742 < #else
743 <            /* No primary hitpoints; set dummy ray origin and warn once */
744 <            srcRay.rorg [0] = srcRay.rorg [1] = srcRay.rorg [2] = 0;
745 <            if (warn) {
746 <               error(WARNING, "no photon primary hitpoints for bin evaluation;"
747 <                     " using dummy (0,0,0) !");
748 <               warn = 0;
749 <            }
750 < #endif          
751 <            decodedir(srcRay.rdir, primary -> dir);
752 <
753 <            if (!(sp->sflags & SDISTANT
754 <                  ? sourcehit(&srcRay)
755 <                  : (*ofun[sp -> so -> otype].funp)(sp -> so, &srcRay)))
756 <               continue;                /* XXX shouldn't happen! */
757 <
758 <            worldfunc(RCCONTEXT, &srcRay);
759 <            set_eparams((char *)srcContrib -> params);
760 <         }
761 <
762 <         if ((srcBinReal = evalue(srcContrib -> binv)) < -.5)
763 <            continue;           /* silently ignore negative bins */
764 <  
765 <         if ((srcBin = srcBinReal + .5) >= srcContrib -> nbins) {
766 <            error(WARNING, "bad bin number (ignored)");
767 <            continue;
768 <         }
769 <            
770 <         if (!contrib) {
771 <            /* Ray coefficient mode; normalise by light source radiance
772 <             * after applying distrib pattern */
773 <            int j;
774 <            
775 <            raytexture(ray, srcMod -> omod);
776 <            setcolor(ray -> rcol, srcMod -> oargs.farg [0],
777 <                     srcMod -> oargs.farg [1], srcMod -> oargs.farg [2]);
778 <            multcolor(ray -> rcol, ray -> pcol);
779 <            for (j = 0; j < 3; j++)
780 <               flux [j] = ray -> rcol [j] ? flux [j] / ray -> rcol [j] : 0;
781 <         }
782 <                    
783 <         multcolor(flux, rayCoeff);
784 <         addcolor(srcContrib -> cbin [srcBin], flux);
785 <      }
786 <   }
787 <        
788 <   return;
732 >   if (verbose)
733 >      eputs("\n");
734   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines