ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/pmapcontrib.c
Revision: 2.5
Committed: Wed May 20 12:58:31 2015 UTC (9 years ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.4: +26 -27 lines
Log Message:
Added appropriate setting of ray parameters for bin rcontrib evaluation

File Contents

# Content
1 /*
2 ==================================================================
3 Photon map support for light source contributions
4
5 Roland Schregle (roland.schregle@{hslu.ch, gmail.com})
6 (c) Lucerne University of Applied Sciences and Arts,
7 supported by the Swiss National Science Foundation (SNSF, #147053)
8 ==================================================================
9
10 $Id: pmapcontrib.c,v 2.4 2015/05/08 13:20:23 rschregle Exp $
11 */
12
13
14 #include "pmapcontrib.h"
15 #include "pmap.h"
16 #include "pmapmat.h"
17 #include "pmapsrc.h"
18 #include "pmaprand.h"
19 #include "pmapio.h"
20 #include "pmapdiag.h"
21 #include "rcontrib.h"
22 #include "otypes.h"
23
24
25
26 static void setPmapContribParams (PhotonMap *pmap, LUTAB *srcContrib)
27 /* Set parameters for light source contributions */
28 {
29 /* Set light source modifier list and appropriate callback to extract
30 * their contributions from the photon map */
31 if (pmap) {
32 pmap -> srcContrib = srcContrib;
33 pmap -> lookup = photonContrib;
34 /* Ensure we get all requested photon contribs during lookups */
35 pmap -> gatherTolerance = 1.0;
36 }
37 }
38
39
40
41 static void checkPmapContribs (const PhotonMap *pmap, LUTAB *srcContrib)
42 /* Check modifiers for light source contributions */
43 {
44 const PhotonPrimary *primary = pmap -> primary;
45 OBJREC *srcMod;
46 unsigned long i, found = 0;
47
48 /* Make sure at least one of the modifiers is actually in the pmap,
49 * otherwise findPhotons() winds up in an infinite loop! */
50 for (i = pmap -> primarySize; i; --i, ++primary) {
51 if (primary -> srcIdx < 0 || primary -> srcIdx >= nsources)
52 error(INTERNAL, "invalid light source index in photon map");
53
54 srcMod = objptr(source [primary -> srcIdx].so -> omod);
55 if ((MODCONT*)lu_find(srcContrib, srcMod -> oname) -> data)
56 ++found;
57 }
58
59 if (!found)
60 error(USER, "modifiers not in photon map");
61 }
62
63
64
65 void initPmapContrib (LUTAB *srcContrib, unsigned numSrcContrib)
66 {
67 unsigned t;
68
69 for (t = 0; t < NUM_PMAP_TYPES; t++)
70 if (photonMaps [t] && t != PMAP_TYPE_CONTRIB) {
71 sprintf(errmsg, "%s photon map does not support contributions",
72 pmapName [t]);
73 error(USER, errmsg);
74 }
75
76 /* Get params */
77 setPmapContribParams(contribPmap, srcContrib);
78
79 if (contribPhotonMapping) {
80 if (contribPmap -> maxGather < numSrcContrib) {
81 /* Adjust density estimate bandwidth if lower than modifier
82 * count, otherwise contributions are missing */
83 error(WARNING, "contrib density estimate bandwidth too low, "
84 "adjusting to modifier count");
85 contribPmap -> maxGather = numSrcContrib;
86 }
87
88 /* Sanity check */
89 checkPmapContribs(contribPmap, srcContrib);
90 }
91 }
92
93
94
95 void photonContrib (PhotonMap *pmap, RAY *ray, COLOR irrad)
96 /* Sum up light source contributions from photons in pmap->srcContrib */
97 {
98 unsigned i;
99 PhotonSQNode *sq;
100 float r, invArea;
101 RREAL rayCoeff [3];
102
103 setcolor(irrad, 0, 0, 0);
104
105 if (!pmap -> maxGather)
106 return;
107
108 /* Ignore sources */
109 if (ray -> ro)
110 if (islight(objptr(ray -> ro -> omod) -> otype))
111 return;
112
113 /* Get cumulative path
114 * coefficient up to photon lookup point */
115 raycontrib(rayCoeff, ray, PRIMARY);
116
117 /* Lookup photons */
118 pmap -> squeueEnd = 0;
119 findPhotons(pmap, ray);
120
121 /* Need at least 2 photons */
122 if (pmap -> squeueEnd < 2) {
123 #ifdef PMAP_NONEFOUND
124 sprintf(errmsg, "no photons found on %s at (%.3f, %.3f, %.3f)",
125 ray -> ro ? ray -> ro -> oname : "<null>",
126 ray -> rop [0], ray -> rop [1], ray -> rop [2]);
127 error(WARNING, errmsg);
128 #endif
129
130 return;
131 }
132
133 /* Average (squared) radius between furthest two photons to improve
134 * accuracy and get inverse search area 1 / (PI * r^2), with extra
135 * normalisation factor 1 / PI for ambient calculation */
136 sq = pmap -> squeue + 1;
137 r = max(sq -> dist, (sq + 1) -> dist);
138 r = 0.25 * (pmap -> maxDist + r + 2 * sqrt(pmap -> maxDist * r));
139 invArea = 1 / (PI * PI * r);
140
141 /* Skip the extra photon */
142 for (i = 1 ; i < pmap -> squeueEnd; i++, sq++) {
143 COLOR flux;
144
145 /* Get photon's contribution to density estimate */
146 getPhotonFlux(sq -> photon, flux);
147 scalecolor(flux, invArea);
148 #ifdef PMAP_EPANECHNIKOV
149 /* Apply Epanechnikov kernel to photon flux (dists are squared) */
150 scalecolor(flux, 2 * (1 - sq -> dist / r));
151 #endif
152 addcolor(irrad, flux);
153
154 if (pmap -> srcContrib) {
155 const PhotonPrimary *primary = pmap -> primary +
156 sq -> photon -> primary;
157 SRCREC *sp = &source[primary -> srcIdx];
158 OBJREC *srcMod = objptr(sp -> so -> omod);
159 MODCONT *srcContrib = (MODCONT*)lu_find(pmap -> srcContrib,
160 srcMod -> oname) -> data;
161
162 if (srcContrib) {
163 /* Photon's emitting light source has modifier whose
164 * contributions are sought */
165 double srcBinReal;
166 int srcBin;
167 RAY srcRay;
168
169 if (srcContrib -> binv -> type != NUM) {
170 /* Use intersection function to set shadow ray parameters
171 */
172 rayorigin(&srcRay, SHADOW, NULL, NULL);
173 srcRay.rsrc = primary -> srcIdx;
174 VCOPY(srcRay.rorg, primary -> pos);
175 VCOPY(srcRay.rdir, primary -> dir);
176 if (!(source [primary -> srcIdx].sflags & SDISTANT ?
177 sourcehit(&srcRay) :
178 (*ofun[sp -> so -> otype].funp)(sp -> so, &srcRay)))
179 continue; /* XXX shouldn't happen! */
180 worldfunc(RCCONTEXT, &srcRay);
181 set_eparams((char *)srcContrib -> params);
182 }
183 if ((srcBinReal = evalue(srcContrib -> binv)) < -.5)
184 continue; /* silently ignore negative bins */
185
186 if ((srcBin = srcBinReal + .5) >= srcContrib -> nbins) {
187 error(WARNING, "bad bin number (ignored)");
188 continue;
189 }
190
191 if (!contrib) {
192 /* Ray coefficient mode; normalise by light source radiance
193 * after applying distrib pattern */
194 int j;
195 raytexture(ray, srcMod -> omod);
196 setcolor(ray -> rcol, srcMod -> oargs.farg [0],
197 srcMod -> oargs.farg [1], srcMod -> oargs.farg [2]);
198 multcolor(ray -> rcol, ray -> pcol);
199 for (j = 0; j < 3; j++)
200 flux [j] = ray -> rcol [j] ? flux [j] / ray -> rcol [j]
201 : 0;
202 }
203
204 multcolor(flux, rayCoeff);
205 addcolor(srcContrib -> cbin [srcBin], flux);
206 }
207 else fprintf(stderr, "Skipped contrib from %s\n", srcMod -> oname);
208 }
209 }
210
211 return;
212 }
213
214
215
216 void distribPhotonContrib (PhotonMap* pm)
217 {
218 EmissionMap emap;
219 char errmsg2 [128];
220 unsigned srcIdx;
221 double *srcFlux; /* Emitted flux per light source */
222 const double srcDistribTarget = /* Target photon count per source */
223 nsources ? (double)pm -> distribTarget / nsources : 0;
224
225 if (!pm)
226 error(USER, "no photon map defined");
227
228 if (!nsources)
229 error(USER, "no light sources");
230
231 /* Allocate photon flux per light source; this differs for every
232 * source as all sources contribute the same number of distributed
233 * photons (srcDistribTarget), hence the number of photons emitted per
234 * source does not correlate with its emitted flux. The resulting flux
235 * per photon is therefore adjusted individually for each source. */
236 if (!(srcFlux = calloc(nsources, sizeof(double))))
237 error(SYSTEM, "cannot allocate source flux");
238
239 /* ================================================================
240 * INITIALISASHUNN - Set up emisshunn and scattering funcs
241 * ================================================================ */
242 emap.samples = NULL;
243 emap.src = NULL;
244 emap.maxPartitions = MAXSPART;
245 emap.partitions = (unsigned char*)malloc(emap.maxPartitions >> 1);
246 if (!emap.partitions)
247 error(USER, "can't allocate source partitions");
248
249 initPhotonMap(pm, PMAP_TYPE_CONTRIB);
250 initPhotonEmissionFuncs();
251 initPhotonScatterFuncs();
252
253 /* Get photon ports if specified */
254 if (ambincl == 1)
255 getPhotonPorts();
256
257 /* Get photon sensor modifiers */
258 getPhotonSensors(photonSensorList);
259
260 /* Seed RNGs for photon distribution */
261 pmapSeed(randSeed, partState);
262 pmapSeed(randSeed, emitState);
263 pmapSeed(randSeed, cntState);
264 pmapSeed(randSeed, mediumState);
265 pmapSeed(randSeed, scatterState);
266 pmapSeed(randSeed, rouletteState);
267
268 /* Record start time and enable progress report signal handler */
269 repStartTime = time(NULL);
270 #ifdef SIGCONT
271 signal(SIGCONT, pmapDistribReport);
272 #endif
273
274 for (srcIdx = 0; srcIdx < nsources; srcIdx++) {
275 unsigned portCnt = 0, passCnt = 0, prePassCnt = 0;
276 double srcNumEmit = 0; /* # photons to emit from source */
277 unsigned long srcNumDistrib = pm -> heapEnd; /* # photons stored */
278
279 srcFlux [srcIdx] = repProgress = 0;
280 emap.src = source + srcIdx;
281
282 if (photonRepTime)
283 eputs("\n");
284
285 /* =============================================================
286 * FLUX INTEGRATION - Get total flux emitted from light source
287 * ============================================================= */
288 do {
289 emap.port = emap.src -> sflags & SDISTANT
290 ? photonPorts + portCnt : NULL;
291 photonPartition [emap.src -> so -> otype] (&emap);
292
293 if (photonRepTime) {
294 sprintf(errmsg, "Integrating flux from source %s (mod %s) ",
295 source [srcIdx].so -> oname,
296 objptr(source [srcIdx].so -> omod) -> oname);
297
298 if (emap.port) {
299 sprintf(errmsg2, "via port %s ",
300 photonPorts [portCnt].so -> oname);
301 strcat(errmsg, errmsg2);
302 }
303
304 sprintf(errmsg2, "(%lu partitions)...\n",
305 emap.numPartitions);
306 strcat(errmsg, errmsg2);
307 eputs(errmsg);
308 fflush(stderr);
309 }
310
311 for (emap.partitionCnt = 0;
312 emap.partitionCnt < emap.numPartitions;
313 emap.partitionCnt++) {
314 initPhotonEmission(&emap, pdfSamples);
315 srcFlux [srcIdx] += colorAvg(emap.partFlux);
316 }
317
318 portCnt++;
319 } while (portCnt < numPhotonPorts);
320
321 if (srcFlux [srcIdx] < FTINY) {
322 sprintf(errmsg, "source %s has zero emission",
323 source [srcIdx].so -> oname);
324 error(WARNING, errmsg);
325 }
326 else {
327 /* ==========================================================
328 * 2-PASS PHOTON DISTRIBUTION
329 * Pass 1 (pre): emit fraction of target photon count
330 * Pass 2 (main): based on outcome of pass 1, estimate
331 * remaining number of photons to emit to
332 * approximate target count
333 * ========================================================== */
334 do {
335 if (!passCnt) {
336 /* INIT PASS 1 */
337 if (++prePassCnt > maxPreDistrib) {
338 /* Warn if no photons contributed after sufficient
339 * iterations */
340 sprintf(errmsg, "too many prepasses, no photons "
341 "from source %s", source [srcIdx].so -> oname);
342 error(WARNING, errmsg);
343 break;
344 }
345
346 /* Num to emit is fraction of target count */
347 srcNumEmit = preDistrib * srcDistribTarget;
348 }
349
350 else {
351 /* INIT PASS 2 */
352 /* Based on the outcome of the predistribution we can now
353 * figure out how many more photons we have to emit from
354 * the current source to meet the target count,
355 * srcDistribTarget. This value is clamped to 0 in case
356 * the target has already been exceeded in pass 1.
357 * srcNumEmit and srcNumDistrib is the number of photons
358 * emitted and distributed (stored) from the current
359 * source in pass 1, respectively. */
360 srcNumDistrib = pm -> heapEnd - srcNumDistrib;
361 srcNumEmit *= srcNumDistrib
362 ? max(srcDistribTarget/srcNumDistrib, 1) - 1
363 : 0;
364
365 if (!srcNumEmit)
366 /* No photons left to distribute in main pass */
367 break;
368 }
369
370 /* Set completion count for progress report */
371 repComplete = srcNumEmit + repProgress;
372 portCnt = 0;
373
374 do {
375 emap.port = emap.src -> sflags & SDISTANT
376 ? photonPorts + portCnt : NULL;
377 photonPartition [emap.src -> so -> otype] (&emap);
378
379 if (photonRepTime) {
380 if (!passCnt)
381 sprintf(errmsg, "PREPASS %d on source %s (mod %s) ",
382 prePassCnt, source [srcIdx].so -> oname,
383 objptr(source[srcIdx].so->omod) -> oname);
384 else
385 sprintf(errmsg, "MAIN PASS on source %s (mod %s) ",
386 source [srcIdx].so -> oname,
387 objptr(source[srcIdx].so->omod) -> oname);
388
389 if (emap.port) {
390 sprintf(errmsg2, "via port %s ",
391 photonPorts [portCnt].so -> oname);
392 strcat(errmsg, errmsg2);
393 }
394
395 sprintf(errmsg2, "(%lu partitions)...\n",
396 emap.numPartitions);
397 strcat(errmsg, errmsg2);
398 eputs(errmsg);
399 fflush(stderr);
400 }
401
402 for (emap.partitionCnt = 0;
403 emap.partitionCnt < emap.numPartitions;
404 emap.partitionCnt++) {
405 double partNumEmit;
406 unsigned long partEmitCnt;
407
408 /* Get photon origin within current source partishunn
409 * and build emission map */
410 photonOrigin [emap.src -> so -> otype] (&emap);
411 initPhotonEmission(&emap, pdfSamples);
412
413 /* Number of photons to emit from ziss partishunn;
414 * scale according to its normalised contribushunn to
415 * the emitted source flux */
416 partNumEmit = srcNumEmit * colorAvg(emap.partFlux) /
417 srcFlux [srcIdx];
418 partEmitCnt = (unsigned long)partNumEmit;
419
420 /* Probabilistically account for fractional photons */
421 if (pmapRandom(cntState) < partNumEmit - partEmitCnt)
422 partEmitCnt++;
423
424 /* Integer counter avoids FP rounding errors */
425 while (partEmitCnt--) {
426 RAY photonRay;
427
428 /* Emit photon according to PDF (if any), allocate
429 * associated primary ray, and trace through scene
430 * until absorbed/leaked */
431 emitPhoton(&emap, &photonRay);
432 addPhotonPrimary(pm, &photonRay);
433 tracePhoton(&photonRay);
434
435 /* Record progress */
436 repProgress++;
437
438 if (photonRepTime > 0 &&
439 time(NULL) >= repLastTime + photonRepTime)
440 pmapDistribReport();
441 #ifdef SIGCONT
442 else signal(SIGCONT, pmapDistribReport);
443 #endif
444 }
445 }
446
447 portCnt++;
448 } while (portCnt < numPhotonPorts);
449
450 if (pm -> heapEnd == srcNumDistrib)
451 /* Double preDistrib in case no photons were stored
452 * for this source and redo pass 1 */
453 preDistrib *= 2;
454 else {
455 /* Now do pass 2 */
456 passCnt++;
457 if (photonRepTime)
458 eputs("\n");
459 }
460 } while (passCnt < 2);
461
462 /* Flux per photon emitted from this source; repProgress is the
463 * number of emitted photons after both passes */
464 srcFlux [srcIdx] = repProgress ? srcFlux [srcIdx] / repProgress
465 : 0;
466 }
467 }
468
469 /* ================================================================
470 * POST-DISTRIBUTION - Set photon flux and build kd-tree, etc.
471 * ================================================================ */
472 #ifdef SIGCONT
473 signal(SIGCONT, SIG_DFL);
474 #endif
475 free(emap.samples);
476
477 if (!pm -> heapEnd)
478 error(USER, "empty photon map");
479
480 /* Check for valid primary photon rays */
481 if (!pm -> primary)
482 error(INTERNAL, "no primary rays in contribution photon map");
483
484 if (pm -> primary [pm -> primaryEnd].srcIdx < 0)
485 /* Last primary ray is unused, so decrement counter */
486 pm -> primaryEnd--;
487
488 if (photonRepTime) {
489 eputs("\nBuilding contrib photon heap...\n");
490 fflush(stderr);
491 }
492
493 balancePhotons(pm, srcFlux);
494 }