Cycles CUDA: reduce stack memory by reusing ShaderData.
[blender.git] / intern / cycles / kernel / kernel_path_branched.h
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 CCL_NAMESPACE_BEGIN
18
19 #ifdef __BRANCHED_PATH__
20
21 ccl_device void kernel_branched_path_ao(KernelGlobals *kg,
22                                         ShaderData *sd,
23                                         ShaderData *emission_sd,
24                                         PathRadiance *L,
25                                         PathState *state,
26                                         RNG *rng,
27                                         float3 throughput)
28 {
29         int num_samples = kernel_data.integrator.ao_samples;
30         float num_samples_inv = 1.0f/num_samples;
31         float ao_factor = kernel_data.background.ao_factor;
32         float3 ao_N;
33         float3 ao_bsdf = shader_bsdf_ao(kg, sd, ao_factor, &ao_N);
34         float3 ao_alpha = shader_bsdf_alpha(kg, sd);
35
36         for(int j = 0; j < num_samples; j++) {
37                 float bsdf_u, bsdf_v;
38                 path_branched_rng_2D(kg, rng, state, j, num_samples, PRNG_BSDF_U, &bsdf_u, &bsdf_v);
39
40                 float3 ao_D;
41                 float ao_pdf;
42
43                 sample_cos_hemisphere(ao_N, bsdf_u, bsdf_v, &ao_D, &ao_pdf);
44
45                 if(dot(ccl_fetch(sd, Ng), ao_D) > 0.0f && ao_pdf != 0.0f) {
46                         Ray light_ray;
47                         float3 ao_shadow;
48
49                         light_ray.P = ray_offset(ccl_fetch(sd, P), ccl_fetch(sd, Ng));
50                         light_ray.D = ao_D;
51                         light_ray.t = kernel_data.background.ao_distance;
52 #ifdef __OBJECT_MOTION__
53                         light_ray.time = ccl_fetch(sd, time);
54 #endif
55                         light_ray.dP = ccl_fetch(sd, dP);
56                         light_ray.dD = differential3_zero();
57
58                         if(!shadow_blocked(kg, emission_sd, state, &light_ray, &ao_shadow))
59                                 path_radiance_accum_ao(L, throughput*num_samples_inv, ao_alpha, ao_bsdf, ao_shadow, state->bounce);
60                 }
61         }
62 }
63
64
65 /* bounce off surface and integrate indirect light */
66 ccl_device_noinline void kernel_branched_path_surface_indirect_light(KernelGlobals *kg,
67         RNG *rng, ShaderData *sd, ShaderData *emission_sd, float3 throughput,
68         float num_samples_adjust, PathState *state, PathRadiance *L)
69 {
70         for(int i = 0; i < ccl_fetch(sd, num_closure); i++) {
71                 const ShaderClosure *sc = &ccl_fetch(sd, closure)[i];
72
73                 if(!CLOSURE_IS_BSDF(sc->type))
74                         continue;
75                 /* transparency is not handled here, but in outer loop */
76                 if(sc->type == CLOSURE_BSDF_TRANSPARENT_ID)
77                         continue;
78
79                 int num_samples;
80
81                 if(CLOSURE_IS_BSDF_DIFFUSE(sc->type))
82                         num_samples = kernel_data.integrator.diffuse_samples;
83                 else if(CLOSURE_IS_BSDF_BSSRDF(sc->type))
84                         num_samples = 1;
85                 else if(CLOSURE_IS_BSDF_GLOSSY(sc->type))
86                         num_samples = kernel_data.integrator.glossy_samples;
87                 else
88                         num_samples = kernel_data.integrator.transmission_samples;
89
90                 num_samples = ceil_to_int(num_samples_adjust*num_samples);
91
92                 float num_samples_inv = num_samples_adjust/num_samples;
93                 RNG bsdf_rng = cmj_hash(*rng, i);
94
95                 for(int j = 0; j < num_samples; j++) {
96                         PathState ps = *state;
97                         float3 tp = throughput;
98                         Ray bsdf_ray;
99
100                         if(!kernel_branched_path_surface_bounce(kg,
101                                                                 &bsdf_rng,
102                                                                 sd,
103                                                                 sc,
104                                                                 j,
105                                                                 num_samples,
106                                                                 &tp,
107                                                                 &ps,
108                                                                 L,
109                                                                 &bsdf_ray))
110                         {
111                                 continue;
112                         }
113
114                         kernel_path_indirect(kg,
115                                              emission_sd,
116                                              rng,
117                                              &bsdf_ray,
118                                              tp*num_samples_inv,
119                                              num_samples,
120                                              &ps,
121                                              L);
122
123                         /* for render passes, sum and reset indirect light pass variables
124                          * for the next samples */
125                         path_radiance_sum_indirect(L);
126                         path_radiance_reset_indirect(L);
127                 }
128         }
129 }
130
131 #ifdef __SUBSURFACE__
132 ccl_device void kernel_branched_path_subsurface_scatter(KernelGlobals *kg,
133                                                         ShaderData *sd,
134                                                         ShaderData *emission_sd,
135                                                         PathRadiance *L,
136                                                         PathState *state,
137                                                         RNG *rng,
138                                                         Ray *ray,
139                                                         float3 throughput)
140 {
141         for(int i = 0; i < ccl_fetch(sd, num_closure); i++) {
142                 ShaderClosure *sc = &ccl_fetch(sd, closure)[i];
143
144                 if(!CLOSURE_IS_BSSRDF(sc->type))
145                         continue;
146
147                 /* set up random number generator */
148                 uint lcg_state = lcg_state_init(rng, state, 0x68bc21eb);
149                 int num_samples = kernel_data.integrator.subsurface_samples;
150                 float num_samples_inv = 1.0f/num_samples;
151                 RNG bssrdf_rng = cmj_hash(*rng, i);
152
153                 /* do subsurface scatter step with copy of shader data, this will
154                  * replace the BSSRDF with a diffuse BSDF closure */
155                 for(int j = 0; j < num_samples; j++) {
156                         SubsurfaceIntersection ss_isect;
157                         float bssrdf_u, bssrdf_v;
158                         path_branched_rng_2D(kg, &bssrdf_rng, state, j, num_samples, PRNG_BSDF_U, &bssrdf_u, &bssrdf_v);
159                         int num_hits = subsurface_scatter_multi_intersect(kg,
160                                                                           &ss_isect,
161                                                                           sd,
162                                                                           sc,
163                                                                           &lcg_state,
164                                                                           bssrdf_u, bssrdf_v,
165                                                                           true);
166 #ifdef __VOLUME__
167                         Ray volume_ray = *ray;
168                         bool need_update_volume_stack = kernel_data.integrator.use_volumes &&
169                                                         ccl_fetch(sd, flag) & SD_OBJECT_INTERSECTS_VOLUME;
170 #endif
171
172                         /* compute lighting with the BSDF closure */
173                         for(int hit = 0; hit < num_hits; hit++) {
174                                 ShaderData bssrdf_sd = *sd;
175                                 subsurface_scatter_multi_setup(kg,
176                                                                &ss_isect,
177                                                                hit,
178                                                                &bssrdf_sd,
179                                                                state,
180                                                                state->flag,
181                                                                sc,
182                                                                true);
183
184                                 PathState hit_state = *state;
185
186                                 path_state_branch(&hit_state, j, num_samples);
187
188 #ifdef __VOLUME__
189                                 if(need_update_volume_stack) {
190                                         /* Setup ray from previous surface point to the new one. */
191                                         float3 P = ray_offset(bssrdf_sd.P, -bssrdf_sd.Ng);
192                                         volume_ray.D = normalize_len(P - volume_ray.P,
193                                                                      &volume_ray.t);
194
195                                         kernel_volume_stack_update_for_subsurface(
196                                             kg,
197                                             emission_sd,
198                                             &volume_ray,
199                                             hit_state.volume_stack);
200                                 }
201 #endif
202
203 #ifdef __EMISSION__
204                                 /* direct light */
205                                 if(kernel_data.integrator.use_direct_light) {
206                                         int all = kernel_data.integrator.sample_all_lights_direct;
207                                         kernel_branched_path_surface_connect_light(
208                                                 kg,
209                                                 rng,
210                                                 &bssrdf_sd,
211                                                 emission_sd,
212                                                 &hit_state,
213                                                 throughput,
214                                                 num_samples_inv,
215                                                 L,
216                                                 all);
217                                 }
218 #endif
219
220                                 /* indirect light */
221                                 kernel_branched_path_surface_indirect_light(
222                                         kg,
223                                         rng,
224                                         &bssrdf_sd,
225                                         emission_sd,
226                                         throughput,
227                                         num_samples_inv,
228                                         &hit_state,
229                                         L);
230                         }
231                 }
232         }
233 }
234 #endif
235
236 ccl_device float4 kernel_branched_path_integrate(KernelGlobals *kg, RNG *rng, int sample, Ray ray, ccl_global float *buffer)
237 {
238         /* initialize */
239         PathRadiance L;
240         float3 throughput = make_float3(1.0f, 1.0f, 1.0f);
241         float L_transparent = 0.0f;
242
243         path_radiance_init(&L, kernel_data.film.use_light_pass);
244
245         /* shader data memory used for both volumes and surfaces, saves stack space */
246         ShaderData sd;
247         /* shader data used by emission, shadows, volume stacks */
248         ShaderData emission_sd;
249
250         PathState state;
251         path_state_init(kg, &emission_sd, &state, rng, sample, &ray);
252
253 #ifdef __KERNEL_DEBUG__
254         DebugData debug_data;
255         debug_data_init(&debug_data);
256 #endif
257
258         /* Main Loop
259          * Here we only handle transparency intersections from the camera ray.
260          * Indirect bounces are handled in kernel_branched_path_surface_indirect_light().
261          */
262         for(;;) {
263                 /* intersect scene */
264                 Intersection isect;
265                 uint visibility = path_state_ray_visibility(kg, &state);
266
267 #ifdef __HAIR__
268                 float difl = 0.0f, extmax = 0.0f;
269                 uint lcg_state = 0;
270
271                 if(kernel_data.bvh.have_curves) {
272                         if(kernel_data.cam.resolution == 1) {
273                                 float3 pixdiff = ray.dD.dx + ray.dD.dy;
274                                 /*pixdiff = pixdiff - dot(pixdiff, ray.D)*ray.D;*/
275                                 difl = kernel_data.curve.minimum_width * len(pixdiff) * 0.5f;
276                         }
277
278                         extmax = kernel_data.curve.maximum_width;
279                         lcg_state = lcg_state_init(rng, &state, 0x51633e2d);
280                 }
281
282                 bool hit = scene_intersect(kg, &ray, visibility, &isect, &lcg_state, difl, extmax);
283 #else
284                 bool hit = scene_intersect(kg, &ray, visibility, &isect, NULL, 0.0f, 0.0f);
285 #endif
286
287 #ifdef __KERNEL_DEBUG__
288                 debug_data.num_bvh_traversal_steps += isect.num_traversal_steps;
289                 debug_data.num_bvh_traversed_instances += isect.num_traversed_instances;
290                 debug_data.num_ray_bounces++;
291 #endif
292
293 #ifdef __VOLUME__
294                 /* volume attenuation, emission, scatter */
295                 if(state.volume_stack[0].shader != SHADER_NONE) {
296                         Ray volume_ray = ray;
297                         volume_ray.t = (hit)? isect.t: FLT_MAX;
298                         
299                         bool heterogeneous = volume_stack_is_heterogeneous(kg, state.volume_stack);
300
301 #ifdef __VOLUME_DECOUPLED__
302                         /* decoupled ray marching only supported on CPU */
303
304                         /* cache steps along volume for repeated sampling */
305                         VolumeSegment volume_segment;
306
307                         shader_setup_from_volume(kg, &sd, &volume_ray);
308                         kernel_volume_decoupled_record(kg, &state,
309                                 &volume_ray, &sd, &volume_segment, heterogeneous);
310
311                         /* direct light sampling */
312                         if(volume_segment.closure_flag & SD_SCATTER) {
313                                 volume_segment.sampling_method = volume_stack_sampling_method(kg, state.volume_stack);
314
315                                 int all = kernel_data.integrator.sample_all_lights_direct;
316
317                                 kernel_branched_path_volume_connect_light(kg, rng, &sd,
318                                         &emission_sd, throughput, &state, &L, all,
319                                         &volume_ray, &volume_segment);
320
321                                 /* indirect light sampling */
322                                 int num_samples = kernel_data.integrator.volume_samples;
323                                 float num_samples_inv = 1.0f/num_samples;
324
325                                 for(int j = 0; j < num_samples; j++) {
326                                         /* workaround to fix correlation bug in T38710, can find better solution
327                                          * in random number generator later, for now this is done here to not impact
328                                          * performance of rendering without volumes */
329                                         RNG tmp_rng = cmj_hash(*rng, state.rng_offset);
330
331                                         PathState ps = state;
332                                         Ray pray = ray;
333                                         float3 tp = throughput;
334
335                                         /* branch RNG state */
336                                         path_state_branch(&ps, j, num_samples);
337
338                                         /* scatter sample. if we use distance sampling and take just one
339                                          * sample for direct and indirect light, we could share this
340                                          * computation, but makes code a bit complex */
341                                         float rphase = path_state_rng_1D_for_decision(kg, &tmp_rng, &ps, PRNG_PHASE);
342                                         float rscatter = path_state_rng_1D_for_decision(kg, &tmp_rng, &ps, PRNG_SCATTER_DISTANCE);
343
344                                         VolumeIntegrateResult result = kernel_volume_decoupled_scatter(kg,
345                                                 &ps, &pray, &sd, &tp, rphase, rscatter, &volume_segment, NULL, false);
346
347                                         (void)result;
348                                         kernel_assert(result == VOLUME_PATH_SCATTERED);
349
350                                         if(kernel_path_volume_bounce(kg,
351                                                                      rng,
352                                                                      &sd,
353                                                                      &tp,
354                                                                      &ps,
355                                                                      &L,
356                                                                      &pray))
357                                         {
358                                                 kernel_path_indirect(kg,
359                                                                      &emission_sd,
360                                                                      rng,
361                                                                      &pray,
362                                                                      tp*num_samples_inv,
363                                                                      num_samples,
364                                                                      &ps,
365                                                                      &L);
366
367                                                 /* for render passes, sum and reset indirect light pass variables
368                                                  * for the next samples */
369                                                 path_radiance_sum_indirect(&L);
370                                                 path_radiance_reset_indirect(&L);
371                                         }
372                                 }
373                         }
374
375                         /* emission and transmittance */
376                         if(volume_segment.closure_flag & SD_EMISSION)
377                                 path_radiance_accum_emission(&L, throughput, volume_segment.accum_emission, state.bounce);
378                         throughput *= volume_segment.accum_transmittance;
379
380                         /* free cached steps */
381                         kernel_volume_decoupled_free(kg, &volume_segment);
382 #else
383                         /* GPU: no decoupled ray marching, scatter probalistically */
384                         int num_samples = kernel_data.integrator.volume_samples;
385                         float num_samples_inv = 1.0f/num_samples;
386
387                         /* todo: we should cache the shader evaluations from stepping
388                          * through the volume, for now we redo them multiple times */
389
390                         for(int j = 0; j < num_samples; j++) {
391                                 PathState ps = state;
392                                 Ray pray = ray;
393                                 float3 tp = throughput * num_samples_inv;
394
395                                 /* branch RNG state */
396                                 path_state_branch(&ps, j, num_samples);
397
398                                 VolumeIntegrateResult result = kernel_volume_integrate(
399                                         kg, &ps, &sd, &volume_ray, &L, &tp, rng, heterogeneous);
400
401 #ifdef __VOLUME_SCATTER__
402                                 if(result == VOLUME_PATH_SCATTERED) {
403                                         /* todo: support equiangular, MIS and all light sampling.
404                                          * alternatively get decoupled ray marching working on the GPU */
405                                         kernel_path_volume_connect_light(kg, rng, &sd, &emission_sd, tp, &state, &L);
406
407                                         if(kernel_path_volume_bounce(kg,
408                                                                      rng,
409                                                                      &sd,
410                                                                      &tp,
411                                                                      &ps,
412                                                                      &L,
413                                                                      &pray))
414                                         {
415                                                 kernel_path_indirect(kg,
416                                                                      &emission_sd,
417                                                                      rng,
418                                                                      &pray,
419                                                                      tp,
420                                                                      num_samples,
421                                                                      &ps,
422                                                                      &L);
423
424                                                 /* for render passes, sum and reset indirect light pass variables
425                                                  * for the next samples */
426                                                 path_radiance_sum_indirect(&L);
427                                                 path_radiance_reset_indirect(&L);
428                                         }
429                                 }
430 #endif
431                         }
432
433                         /* todo: avoid this calculation using decoupled ray marching */
434                         kernel_volume_shadow(kg, &emission_sd, &state, &volume_ray, &throughput);
435 #endif
436                 }
437 #endif
438
439                 if(!hit) {
440                         /* eval background shader if nothing hit */
441                         if(kernel_data.background.transparent) {
442                                 L_transparent += average(throughput);
443
444 #ifdef __PASSES__
445                                 if(!(kernel_data.film.pass_flag & PASS_BACKGROUND))
446 #endif
447                                         break;
448                         }
449
450 #ifdef __BACKGROUND__
451                         /* sample background shader */
452                         float3 L_background = indirect_background(kg, &emission_sd, &state, &ray);
453                         path_radiance_accum_background(&L, throughput, L_background, state.bounce);
454 #endif
455
456                         break;
457                 }
458
459                 /* setup shading */
460                 shader_setup_from_ray(kg, &sd, &isect, &ray);
461                 shader_eval_surface(kg, &sd, &state, 0.0f, state.flag, SHADER_CONTEXT_MAIN);
462                 shader_merge_closures(&sd);
463
464                 /* holdout */
465 #ifdef __HOLDOUT__
466                 if(sd.flag & (SD_HOLDOUT|SD_HOLDOUT_MASK)) {
467                         if(kernel_data.background.transparent) {
468                                 float3 holdout_weight;
469                                 
470                                 if(sd.flag & SD_HOLDOUT_MASK)
471                                         holdout_weight = make_float3(1.0f, 1.0f, 1.0f);
472                                 else
473                                         holdout_weight = shader_holdout_eval(kg, &sd);
474
475                                 /* any throughput is ok, should all be identical here */
476                                 L_transparent += average(holdout_weight*throughput);
477                         }
478
479                         if(sd.flag & SD_HOLDOUT_MASK)
480                                 break;
481                 }
482 #endif
483
484                 /* holdout mask objects do not write data passes */
485                 kernel_write_data_passes(kg, buffer, &L, &sd, sample, &state, throughput);
486
487 #ifdef __EMISSION__
488                 /* emission */
489                 if(sd.flag & SD_EMISSION) {
490                         float3 emission = indirect_primitive_emission(kg, &sd, isect.t, state.flag, state.ray_pdf);
491                         path_radiance_accum_emission(&L, throughput, emission, state.bounce);
492                 }
493 #endif
494
495                 /* transparency termination */
496                 if(state.flag & PATH_RAY_TRANSPARENT) {
497                         /* path termination. this is a strange place to put the termination, it's
498                          * mainly due to the mixed in MIS that we use. gives too many unneeded
499                          * shader evaluations, only need emission if we are going to terminate */
500                         float probability = path_state_terminate_probability(kg, &state, throughput);
501
502                         if(probability == 0.0f) {
503                                 break;
504                         }
505                         else if(probability != 1.0f) {
506                                 float terminate = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_TERMINATE);
507
508                                 if(terminate >= probability)
509                                         break;
510
511                                 throughput /= probability;
512                         }
513                 }
514
515 #ifdef __AO__
516                 /* ambient occlusion */
517                 if(kernel_data.integrator.use_ambient_occlusion || (sd.flag & SD_AO)) {
518                         kernel_branched_path_ao(kg, &sd, &emission_sd, &L, &state, rng, throughput);
519                 }
520 #endif
521
522 #ifdef __SUBSURFACE__
523                 /* bssrdf scatter to a different location on the same object */
524                 if(sd.flag & SD_BSSRDF) {
525                         kernel_branched_path_subsurface_scatter(kg, &sd, &emission_sd, &L, &state,
526                                                                 rng, &ray, throughput);
527                 }
528 #endif
529
530                 if(!(sd.flag & SD_HAS_ONLY_VOLUME)) {
531                         PathState hit_state = state;
532
533 #ifdef __EMISSION__
534                         /* direct light */
535                         if(kernel_data.integrator.use_direct_light) {
536                                 int all = kernel_data.integrator.sample_all_lights_direct;
537                                 kernel_branched_path_surface_connect_light(kg, rng,
538                                         &sd, &emission_sd, &hit_state, throughput, 1.0f, &L, all);
539                         }
540 #endif
541
542                         /* indirect light */
543                         kernel_branched_path_surface_indirect_light(kg, rng,
544                                 &sd, &emission_sd, throughput, 1.0f, &hit_state, &L);
545
546                         /* continue in case of transparency */
547                         throughput *= shader_bsdf_transparency(kg, &sd);
548
549                         if(is_zero(throughput))
550                                 break;
551                 }
552
553                 /* Update Path State */
554                 state.flag |= PATH_RAY_TRANSPARENT;
555                 state.transparent_bounce++;
556
557                 ray.P = ray_offset(sd.P, -sd.Ng);
558                 ray.t -= sd.ray_length; /* clipping works through transparent */
559
560
561 #ifdef __RAY_DIFFERENTIALS__
562                 ray.dP = sd.dP;
563                 ray.dD.dx = -sd.dI.dx;
564                 ray.dD.dy = -sd.dI.dy;
565 #endif
566
567 #ifdef __VOLUME__
568                 /* enter/exit volume */
569                 kernel_volume_stack_enter_exit(kg, &sd, state.volume_stack);
570 #endif
571         }
572
573         float3 L_sum = path_radiance_clamp_and_sum(kg, &L);
574
575         kernel_write_light_passes(kg, buffer, &L, sample);
576
577 #ifdef __KERNEL_DEBUG__
578         kernel_write_debug_passes(kg, buffer, &state, &debug_data, sample);
579 #endif
580
581         return make_float4(L_sum.x, L_sum.y, L_sum.z, 1.0f - L_transparent);
582 }
583
584 ccl_device void kernel_branched_path_trace(KernelGlobals *kg,
585         ccl_global float *buffer, ccl_global uint *rng_state,
586         int sample, int x, int y, int offset, int stride)
587 {
588         /* buffer offset */
589         int index = offset + x + y*stride;
590         int pass_stride = kernel_data.film.pass_stride;
591
592         rng_state += index;
593         buffer += index*pass_stride;
594
595         /* initialize random numbers and ray */
596         RNG rng;
597         Ray ray;
598
599         kernel_path_trace_setup(kg, rng_state, sample, x, y, &rng, &ray);
600
601         /* integrate */
602         float4 L;
603
604         if(ray.t != 0.0f)
605                 L = kernel_branched_path_integrate(kg, &rng, sample, ray, buffer);
606         else
607                 L = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
608
609         /* accumulate result in output buffer */
610         kernel_write_pass_float4(buffer, sample, L);
611
612         path_rng_end(kg, rng_state, rng);
613 }
614
615 #endif  /* __BRANCHED_PATH__ */
616
617 CCL_NAMESPACE_END
618