8e9fc7436942067cbff00bc07fa37ff8904a1e0c
[blender-staging.git] / intern / cycles / kernel / kernel_path.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 #ifdef __OSL__
18 #include "osl_shader.h"
19 #endif
20
21 #include "kernel_random.h"
22 #include "kernel_projection.h"
23 #include "kernel_montecarlo.h"
24 #include "kernel_differential.h"
25 #include "kernel_camera.h"
26
27 #include "geom/geom.h"
28
29 #include "kernel_accumulate.h"
30 #include "kernel_shader.h"
31 #include "kernel_light.h"
32 #include "kernel_passes.h"
33
34 #ifdef __SUBSURFACE__
35 #include "kernel_subsurface.h"
36 #endif
37
38 #ifdef __VOLUME__
39 #include "kernel_volume.h"
40 #endif
41
42 #include "kernel_path_state.h"
43 #include "kernel_shadow.h"
44 #include "kernel_emission.h"
45 #include "kernel_path_surface.h"
46 #include "kernel_path_volume.h"
47
48 CCL_NAMESPACE_BEGIN
49
50 ccl_device void kernel_path_indirect(KernelGlobals *kg, RNG *rng, Ray ray,
51         float3 throughput, int num_samples, PathState state, PathRadiance *L)
52 {
53         /* path iteration */
54         for(;;) {
55                 /* intersect scene */
56                 Intersection isect;
57                 uint visibility = path_state_ray_visibility(kg, &state);
58                 bool hit = scene_intersect(kg, &ray, visibility, &isect, NULL, 0.0f, 0.0f);
59
60 #ifdef __LAMP_MIS__
61                 if(kernel_data.integrator.use_lamp_mis && !(state.flag & PATH_RAY_CAMERA)) {
62                         /* ray starting from previous non-transparent bounce */
63                         Ray light_ray;
64
65                         light_ray.P = ray.P - state.ray_t*ray.D;
66                         state.ray_t += isect.t;
67                         light_ray.D = ray.D;
68                         light_ray.t = state.ray_t;
69                         light_ray.time = ray.time;
70                         light_ray.dD = ray.dD;
71                         light_ray.dP = ray.dP;
72
73                         /* intersect with lamp */
74                         float3 emission;
75
76                         if(indirect_lamp_emission(kg, &state, &light_ray, &emission))
77                                 path_radiance_accum_emission(L, throughput, emission, state.bounce);
78                 }
79 #endif
80
81 #ifdef __VOLUME__
82                 /* volume attenuation, emission, scatter */
83                 if(state.volume_stack[0].shader != SHADER_NONE) {
84                         Ray volume_ray = ray;
85                         volume_ray.t = (hit)? isect.t: FLT_MAX;
86
87                         bool heterogeneous = volume_stack_is_heterogeneous(kg, state.volume_stack);
88
89 #ifdef __VOLUME_DECOUPLED__
90                         int sampling_method = volume_stack_sampling_method(kg, state.volume_stack);
91                         bool decoupled = kernel_volume_use_decoupled(kg, heterogeneous, false, sampling_method);
92
93                         if(decoupled) {
94                                 /* cache steps along volume for repeated sampling */
95                                 VolumeSegment volume_segment;
96                                 ShaderData volume_sd;
97
98                                 shader_setup_from_volume(kg, &volume_sd, &volume_ray, state.bounce, state.transparent_bounce);
99                                 kernel_volume_decoupled_record(kg, &state,
100                                         &volume_ray, &volume_sd, &volume_segment, heterogeneous);
101                                 
102                                 volume_segment.sampling_method = sampling_method;
103
104                                 /* emission */
105                                 if(volume_segment.closure_flag & SD_EMISSION)
106                                         path_radiance_accum_emission(L, throughput, volume_segment.accum_emission, state.bounce);
107
108                                 /* scattering */
109                                 VolumeIntegrateResult result = VOLUME_PATH_ATTENUATED;
110
111                                 if(volume_segment.closure_flag & SD_SCATTER) {
112                                         bool all = kernel_data.integrator.sample_all_lights_indirect;
113
114                                         /* direct light sampling */
115                                         kernel_branched_path_volume_connect_light(kg, rng, &volume_sd,
116                                                 throughput, &state, L, 1.0f, all, &volume_ray, &volume_segment);
117
118                                         /* indirect sample. if we use distance sampling and take just
119                                          * one sample for direct and indirect light, we could share
120                                          * this computation, but makes code a bit complex */
121                                         float rphase = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_PHASE);
122                                         float rscatter = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_SCATTER_DISTANCE);
123
124                                         result = kernel_volume_decoupled_scatter(kg,
125                                                 &state, &volume_ray, &volume_sd, &throughput,
126                                                 rphase, rscatter, &volume_segment, NULL, true);
127                                 }
128
129                                 if(result != VOLUME_PATH_SCATTERED)
130                                         throughput *= volume_segment.accum_transmittance;
131
132                                 /* free cached steps */
133                                 kernel_volume_decoupled_free(kg, &volume_segment);
134
135                                 if(result == VOLUME_PATH_SCATTERED) {
136                                         if(kernel_path_volume_bounce(kg, rng, &volume_sd, &throughput, &state, L, &ray))
137                                                 continue;
138                                         else
139                                                 break;
140                                 }
141                         }
142                         else
143 #endif
144                         {
145                                 /* integrate along volume segment with distance sampling */
146                                 ShaderData volume_sd;
147                                 VolumeIntegrateResult result = kernel_volume_integrate(
148                                         kg, &state, &volume_sd, &volume_ray, L, &throughput, rng, heterogeneous);
149
150 #ifdef __VOLUME_SCATTER__
151                                 if(result == VOLUME_PATH_SCATTERED) {
152                                         /* direct lighting */
153                                         kernel_path_volume_connect_light(kg, rng, &volume_sd, throughput, &state, L);
154
155                                         /* indirect light bounce */
156                                         if(kernel_path_volume_bounce(kg, rng, &volume_sd, &throughput, &state, L, &ray))
157                                                 continue;
158                                         else
159                                                 break;
160                                 }
161 #endif
162                         }
163                 }
164 #endif
165
166                 if(!hit) {
167 #ifdef __BACKGROUND__
168                         /* sample background shader */
169                         float3 L_background = indirect_background(kg, &state, &ray);
170                         path_radiance_accum_background(L, throughput, L_background, state.bounce);
171 #endif
172
173                         break;
174                 }
175
176                 /* setup shading */
177                 ShaderData sd;
178                 shader_setup_from_ray(kg, &sd, &isect, &ray, state.bounce, state.transparent_bounce);
179                 float rbsdf = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_BSDF);
180                 shader_eval_surface(kg, &sd, rbsdf, state.flag, SHADER_CONTEXT_INDIRECT);
181 #ifdef __BRANCHED_PATH__
182                 shader_merge_closures(&sd);
183 #endif
184
185                 /* blurring of bsdf after bounces, for rays that have a small likelihood
186                  * of following this particular path (diffuse, rough glossy) */
187                 if(kernel_data.integrator.filter_glossy != FLT_MAX) {
188                         float blur_pdf = kernel_data.integrator.filter_glossy*state.min_ray_pdf;
189
190                         if(blur_pdf < 1.0f) {
191                                 float blur_roughness = sqrtf(1.0f - blur_pdf)*0.5f;
192                                 shader_bsdf_blur(kg, &sd, blur_roughness);
193                         }
194                 }
195
196 #ifdef __EMISSION__
197                 /* emission */
198                 if(sd.flag & SD_EMISSION) {
199                         float3 emission = indirect_primitive_emission(kg, &sd, isect.t, state.flag, state.ray_pdf);
200                         path_radiance_accum_emission(L, throughput, emission, state.bounce);
201                 }
202 #endif
203
204                 /* path termination. this is a strange place to put the termination, it's
205                  * mainly due to the mixed in MIS that we use. gives too many unneeded
206                  * shader evaluations, only need emission if we are going to terminate */
207                 float probability = path_state_terminate_probability(kg, &state, throughput*num_samples);
208
209                 if(probability == 0.0f) {
210                         break;
211                 }
212                 else if(probability != 1.0f) {
213                         float terminate = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_TERMINATE);
214
215                         if(terminate >= probability)
216                                 break;
217
218                         throughput /= probability;
219                 }
220
221 #ifdef __AO__
222                 /* ambient occlusion */
223                 if(kernel_data.integrator.use_ambient_occlusion || (sd.flag & SD_AO)) {
224                         float bsdf_u, bsdf_v;
225                         path_state_rng_2D(kg, rng, &state, PRNG_BSDF_U, &bsdf_u, &bsdf_v);
226
227                         float ao_factor = kernel_data.background.ao_factor;
228                         float3 ao_N;
229                         float3 ao_bsdf = shader_bsdf_ao(kg, &sd, ao_factor, &ao_N);
230                         float3 ao_D;
231                         float ao_pdf;
232                         float3 ao_alpha = make_float3(0.0f, 0.0f, 0.0f);
233
234                         sample_cos_hemisphere(ao_N, bsdf_u, bsdf_v, &ao_D, &ao_pdf);
235
236                         if(dot(sd.Ng, ao_D) > 0.0f && ao_pdf != 0.0f) {
237                                 Ray light_ray;
238                                 float3 ao_shadow;
239
240                                 light_ray.P = ray_offset(sd.P, sd.Ng);
241                                 light_ray.D = ao_D;
242                                 light_ray.t = kernel_data.background.ao_distance;
243 #ifdef __OBJECT_MOTION__
244                                 light_ray.time = sd.time;
245 #endif
246                                 light_ray.dP = sd.dP;
247                                 light_ray.dD = differential3_zero();
248
249                                 if(!shadow_blocked(kg, &state, &light_ray, &ao_shadow))
250                                         path_radiance_accum_ao(L, throughput, ao_alpha, ao_bsdf, ao_shadow, state.bounce);
251                         }
252                 }
253 #endif
254
255 #ifdef __SUBSURFACE__
256                 /* bssrdf scatter to a different location on the same object, replacing
257                  * the closures with a diffuse BSDF */
258                 if(sd.flag & SD_BSSRDF) {
259                         float bssrdf_probability;
260                         ShaderClosure *sc = subsurface_scatter_pick_closure(kg, &sd, &bssrdf_probability);
261
262                         /* modify throughput for picking bssrdf or bsdf */
263                         throughput *= bssrdf_probability;
264
265                         /* do bssrdf scatter step if we picked a bssrdf closure */
266                         if(sc) {
267                                 uint lcg_state = lcg_state_init(rng, &state, 0x68bc21eb);
268
269                                 float bssrdf_u, bssrdf_v;
270                                 path_state_rng_2D(kg, rng, &state, PRNG_BSDF_U, &bssrdf_u, &bssrdf_v);
271                                 subsurface_scatter_step(kg, &sd, state.flag, sc, &lcg_state, bssrdf_u, bssrdf_v, false);
272
273                                 state.flag |= PATH_RAY_BSSRDF_ANCESTOR;
274                         }
275                 }
276 #endif
277
278 #if defined(__EMISSION__) && defined(__BRANCHED_PATH__)
279                 if(kernel_data.integrator.use_direct_light) {
280                         bool all = kernel_data.integrator.sample_all_lights_indirect;
281                         kernel_branched_path_surface_connect_light(kg, rng, &sd, &state, throughput, 1.0f, L, all);
282                 }
283 #endif
284
285                 if(!kernel_path_surface_bounce(kg, rng, &sd, &throughput, &state, L, &ray))
286                         break;
287         }
288 }
289
290 ccl_device void kernel_path_ao(KernelGlobals *kg, ShaderData *sd, PathRadiance *L, PathState *state, RNG *rng, float3 throughput)
291 {
292         /* todo: solve correlation */
293         float bsdf_u, bsdf_v;
294
295         path_state_rng_2D(kg, rng, state, PRNG_BSDF_U, &bsdf_u, &bsdf_v);
296
297         float ao_factor = kernel_data.background.ao_factor;
298         float3 ao_N;
299         float3 ao_bsdf = shader_bsdf_ao(kg, sd, ao_factor, &ao_N);
300         float3 ao_D;
301         float ao_pdf;
302         float3 ao_alpha = shader_bsdf_alpha(kg, sd);
303
304         sample_cos_hemisphere(ao_N, bsdf_u, bsdf_v, &ao_D, &ao_pdf);
305
306         if(dot(sd->Ng, ao_D) > 0.0f && ao_pdf != 0.0f) {
307                 Ray light_ray;
308                 float3 ao_shadow;
309
310                 light_ray.P = ray_offset(sd->P, sd->Ng);
311                 light_ray.D = ao_D;
312                 light_ray.t = kernel_data.background.ao_distance;
313 #ifdef __OBJECT_MOTION__
314                 light_ray.time = sd->time;
315 #endif
316                 light_ray.dP = sd->dP;
317                 light_ray.dD = differential3_zero();
318
319                 if(!shadow_blocked(kg, state, &light_ray, &ao_shadow))
320                         path_radiance_accum_ao(L, throughput, ao_alpha, ao_bsdf, ao_shadow, state->bounce);
321         }
322 }
323
324 ccl_device void kernel_branched_path_ao(KernelGlobals *kg, ShaderData *sd, PathRadiance *L, PathState *state, RNG *rng, float3 throughput)
325 {
326         int num_samples = kernel_data.integrator.ao_samples;
327         float num_samples_inv = 1.0f/num_samples;
328         float ao_factor = kernel_data.background.ao_factor;
329         float3 ao_N;
330         float3 ao_bsdf = shader_bsdf_ao(kg, sd, ao_factor, &ao_N);
331         float3 ao_alpha = shader_bsdf_alpha(kg, sd);
332
333         for(int j = 0; j < num_samples; j++) {
334                 float bsdf_u, bsdf_v;
335                 path_branched_rng_2D(kg, rng, state, j, num_samples, PRNG_BSDF_U, &bsdf_u, &bsdf_v);
336
337                 float3 ao_D;
338                 float ao_pdf;
339
340                 sample_cos_hemisphere(ao_N, bsdf_u, bsdf_v, &ao_D, &ao_pdf);
341
342                 if(dot(sd->Ng, ao_D) > 0.0f && ao_pdf != 0.0f) {
343                         Ray light_ray;
344                         float3 ao_shadow;
345
346                         light_ray.P = ray_offset(sd->P, sd->Ng);
347                         light_ray.D = ao_D;
348                         light_ray.t = kernel_data.background.ao_distance;
349 #ifdef __OBJECT_MOTION__
350                         light_ray.time = sd->time;
351 #endif
352                         light_ray.dP = sd->dP;
353                         light_ray.dD = differential3_zero();
354
355                         if(!shadow_blocked(kg, state, &light_ray, &ao_shadow))
356                                 path_radiance_accum_ao(L, throughput*num_samples_inv, ao_alpha, ao_bsdf, ao_shadow, state->bounce);
357                 }
358         }
359 }
360
361 #ifdef __SUBSURFACE__
362 ccl_device bool kernel_path_subsurface_scatter(KernelGlobals *kg, ShaderData *sd, PathRadiance *L, PathState *state, RNG *rng, Ray *ray, float3 *throughput)
363 {
364         float bssrdf_probability;
365         ShaderClosure *sc = subsurface_scatter_pick_closure(kg, sd, &bssrdf_probability);
366
367         /* modify throughput for picking bssrdf or bsdf */
368         *throughput *= bssrdf_probability;
369
370         /* do bssrdf scatter step if we picked a bssrdf closure */
371         if(sc) {
372                 uint lcg_state = lcg_state_init(rng, state, 0x68bc21eb);
373
374                 ShaderData bssrdf_sd[BSSRDF_MAX_HITS];
375                 float bssrdf_u, bssrdf_v;
376                 path_state_rng_2D(kg, rng, state, PRNG_BSDF_U, &bssrdf_u, &bssrdf_v);
377                 int num_hits = subsurface_scatter_multi_step(kg, sd, bssrdf_sd, state->flag, sc, &lcg_state, bssrdf_u, bssrdf_v, false);
378
379                 /* compute lighting with the BSDF closure */
380                 for(int hit = 0; hit < num_hits; hit++) {
381                         float3 tp = *throughput;
382                         PathState hit_state = *state;
383                         Ray hit_ray = *ray;
384
385                         hit_state.flag |= PATH_RAY_BSSRDF_ANCESTOR;
386                         hit_state.rng_offset += PRNG_BOUNCE_NUM;
387                         
388                         kernel_path_surface_connect_light(kg, rng, &bssrdf_sd[hit], tp, state, L);
389
390                         if(kernel_path_surface_bounce(kg, rng, &bssrdf_sd[hit], &tp, &hit_state, L, &hit_ray)) {
391 #ifdef __LAMP_MIS__
392                                 hit_state.ray_t = 0.0f;
393 #endif
394
395                                 kernel_path_indirect(kg, rng, hit_ray, tp, state->num_samples, hit_state, L);
396
397                                 /* for render passes, sum and reset indirect light pass variables
398                                  * for the next samples */
399                                 path_radiance_sum_indirect(L);
400                                 path_radiance_reset_indirect(L);
401                         }
402                 }
403                 return true;
404         }
405         return false;
406 }
407 #endif
408
409 ccl_device float4 kernel_path_integrate(KernelGlobals *kg, RNG *rng, int sample, Ray ray, ccl_global float *buffer)
410 {
411         /* initialize */
412         PathRadiance L;
413         float3 throughput = make_float3(1.0f, 1.0f, 1.0f);
414         float L_transparent = 0.0f;
415
416         path_radiance_init(&L, kernel_data.film.use_light_pass);
417
418         PathState state;
419         path_state_init(kg, &state, rng, sample);
420
421         /* path iteration */
422         for(;;) {
423                 /* intersect scene */
424                 Intersection isect;
425                 uint visibility = path_state_ray_visibility(kg, &state);
426
427 #ifdef __HAIR__
428                 float difl = 0.0f, extmax = 0.0f;
429                 uint lcg_state = 0;
430
431                 if(kernel_data.bvh.have_curves) {
432                         if((kernel_data.cam.resolution == 1) && (state.flag & PATH_RAY_CAMERA)) {       
433                                 float3 pixdiff = ray.dD.dx + ray.dD.dy;
434                                 /*pixdiff = pixdiff - dot(pixdiff, ray.D)*ray.D;*/
435                                 difl = kernel_data.curve.minimum_width * len(pixdiff) * 0.5f;
436                         }
437
438                         extmax = kernel_data.curve.maximum_width;
439                         lcg_state = lcg_state_init(rng, &state, 0x51633e2d);
440                 }
441
442                 bool hit = scene_intersect(kg, &ray, visibility, &isect, &lcg_state, difl, extmax);
443 #else
444                 bool hit = scene_intersect(kg, &ray, visibility, &isect, NULL, 0.0f, 0.0f);
445 #endif
446
447 #ifdef __LAMP_MIS__
448                 if(kernel_data.integrator.use_lamp_mis && !(state.flag & PATH_RAY_CAMERA)) {
449                         /* ray starting from previous non-transparent bounce */
450                         Ray light_ray;
451
452                         light_ray.P = ray.P - state.ray_t*ray.D;
453                         state.ray_t += isect.t;
454                         light_ray.D = ray.D;
455                         light_ray.t = state.ray_t;
456                         light_ray.time = ray.time;
457                         light_ray.dD = ray.dD;
458                         light_ray.dP = ray.dP;
459
460                         /* intersect with lamp */
461                         float3 emission;
462
463                         if(indirect_lamp_emission(kg, &state, &light_ray, &emission))
464                                 path_radiance_accum_emission(&L, throughput, emission, state.bounce);
465                 }
466 #endif
467
468 #ifdef __VOLUME__
469                 /* volume attenuation, emission, scatter */
470                 if(state.volume_stack[0].shader != SHADER_NONE) {
471                         Ray volume_ray = ray;
472                         volume_ray.t = (hit)? isect.t: FLT_MAX;
473
474                         bool heterogeneous = volume_stack_is_heterogeneous(kg, state.volume_stack);
475
476 #ifdef __VOLUME_DECOUPLED__
477                         int sampling_method = volume_stack_sampling_method(kg, state.volume_stack);
478                         bool decoupled = kernel_volume_use_decoupled(kg, heterogeneous, true, sampling_method);
479
480                         if(decoupled) {
481                                 /* cache steps along volume for repeated sampling */
482                                 VolumeSegment volume_segment;
483                                 ShaderData volume_sd;
484
485                                 shader_setup_from_volume(kg, &volume_sd, &volume_ray, state.bounce, state.transparent_bounce);
486                                 kernel_volume_decoupled_record(kg, &state,
487                                         &volume_ray, &volume_sd, &volume_segment, heterogeneous);
488
489                                 volume_segment.sampling_method = sampling_method;
490
491                                 /* emission */
492                                 if(volume_segment.closure_flag & SD_EMISSION)
493                                         path_radiance_accum_emission(&L, throughput, volume_segment.accum_emission, state.bounce);
494
495                                 /* scattering */
496                                 VolumeIntegrateResult result = VOLUME_PATH_ATTENUATED;
497
498                                 if(volume_segment.closure_flag & SD_SCATTER) {
499                                         bool all = false;
500
501                                         /* direct light sampling */
502                                         kernel_branched_path_volume_connect_light(kg, rng, &volume_sd,
503                                                 throughput, &state, &L, 1.0f, all, &volume_ray, &volume_segment);
504
505                                         /* indirect sample. if we use distance sampling and take just
506                                          * one sample for direct and indirect light, we could share
507                                          * this computation, but makes code a bit complex */
508                                         float rphase = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_PHASE);
509                                         float rscatter = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_SCATTER_DISTANCE);
510
511                                         result = kernel_volume_decoupled_scatter(kg,
512                                                 &state, &volume_ray, &volume_sd, &throughput,
513                                                 rphase, rscatter, &volume_segment, NULL, true);
514                                 }
515
516                                 if(result != VOLUME_PATH_SCATTERED)
517                                         throughput *= volume_segment.accum_transmittance;
518
519                                 /* free cached steps */
520                                 kernel_volume_decoupled_free(kg, &volume_segment);
521
522                                 if(result == VOLUME_PATH_SCATTERED) {
523                                         if(kernel_path_volume_bounce(kg, rng, &volume_sd, &throughput, &state, &L, &ray))
524                                                 continue;
525                                         else
526                                                 break;
527                                 }
528                         }
529                         else 
530 #endif
531                         {
532                                 /* integrate along volume segment with distance sampling */
533                                 ShaderData volume_sd;
534                                 VolumeIntegrateResult result = kernel_volume_integrate(
535                                         kg, &state, &volume_sd, &volume_ray, &L, &throughput, rng, heterogeneous);
536
537 #ifdef __VOLUME_SCATTER__
538                                 if(result == VOLUME_PATH_SCATTERED) {
539                                         /* direct lighting */
540                                         kernel_path_volume_connect_light(kg, rng, &volume_sd, throughput, &state, &L);
541
542                                         /* indirect light bounce */
543                                         if(kernel_path_volume_bounce(kg, rng, &volume_sd, &throughput, &state, &L, &ray))
544                                                 continue;
545                                         else
546                                                 break;
547                                 }
548 #endif
549                         }
550                 }
551 #endif
552
553                 if(!hit) {
554                         /* eval background shader if nothing hit */
555                         if(kernel_data.background.transparent && (state.flag & PATH_RAY_CAMERA)) {
556                                 L_transparent += average(throughput);
557
558 #ifdef __PASSES__
559                                 if(!(kernel_data.film.pass_flag & PASS_BACKGROUND))
560 #endif
561                                         break;
562                         }
563
564 #ifdef __BACKGROUND__
565                         /* sample background shader */
566                         float3 L_background = indirect_background(kg, &state, &ray);
567                         path_radiance_accum_background(&L, throughput, L_background, state.bounce);
568 #endif
569
570                         break;
571                 }
572
573                 /* setup shading */
574                 ShaderData sd;
575                 shader_setup_from_ray(kg, &sd, &isect, &ray, state.bounce, state.transparent_bounce);
576                 float rbsdf = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_BSDF);
577                 shader_eval_surface(kg, &sd, rbsdf, state.flag, SHADER_CONTEXT_MAIN);
578
579                 /* holdout */
580 #ifdef __HOLDOUT__
581                 if((sd.flag & (SD_HOLDOUT|SD_HOLDOUT_MASK)) && (state.flag & PATH_RAY_CAMERA)) {
582                         if(kernel_data.background.transparent) {
583                                 float3 holdout_weight;
584                                 
585                                 if(sd.flag & SD_HOLDOUT_MASK)
586                                         holdout_weight = make_float3(1.0f, 1.0f, 1.0f);
587                                 else
588                                         holdout_weight = shader_holdout_eval(kg, &sd);
589
590                                 /* any throughput is ok, should all be identical here */
591                                 L_transparent += average(holdout_weight*throughput);
592                         }
593
594                         if(sd.flag & SD_HOLDOUT_MASK)
595                                 break;
596                 }
597 #endif
598
599                 /* holdout mask objects do not write data passes */
600                 kernel_write_data_passes(kg, buffer, &L, &sd, sample, &state, throughput);
601
602                 /* blurring of bsdf after bounces, for rays that have a small likelihood
603                  * of following this particular path (diffuse, rough glossy) */
604                 if(kernel_data.integrator.filter_glossy != FLT_MAX) {
605                         float blur_pdf = kernel_data.integrator.filter_glossy*state.min_ray_pdf;
606
607                         if(blur_pdf < 1.0f) {
608                                 float blur_roughness = sqrtf(1.0f - blur_pdf)*0.5f;
609                                 shader_bsdf_blur(kg, &sd, blur_roughness);
610                         }
611                 }
612
613 #ifdef __EMISSION__
614                 /* emission */
615                 if(sd.flag & SD_EMISSION) {
616                         /* todo: is isect.t wrong here for transparent surfaces? */
617                         float3 emission = indirect_primitive_emission(kg, &sd, isect.t, state.flag, state.ray_pdf);
618                         path_radiance_accum_emission(&L, throughput, emission, state.bounce);
619                 }
620 #endif
621
622                 /* path termination. this is a strange place to put the termination, it's
623                  * mainly due to the mixed in MIS that we use. gives too many unneeded
624                  * shader evaluations, only need emission if we are going to terminate */
625                 float probability = path_state_terminate_probability(kg, &state, throughput);
626
627                 if(probability == 0.0f) {
628                         break;
629                 }
630                 else if(probability != 1.0f) {
631                         float terminate = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_TERMINATE);
632
633                         if(terminate >= probability)
634                                 break;
635
636                         throughput /= probability;
637                 }
638
639 #ifdef __AO__
640                 /* ambient occlusion */
641                 if(kernel_data.integrator.use_ambient_occlusion || (sd.flag & SD_AO)) {
642                         kernel_path_ao(kg, &sd, &L, &state, rng, throughput);
643                 }
644 #endif
645
646 #ifdef __SUBSURFACE__
647                 /* bssrdf scatter to a different location on the same object, replacing
648                  * the closures with a diffuse BSDF */
649                 if(sd.flag & SD_BSSRDF) {
650                         if(kernel_path_subsurface_scatter(kg, &sd, &L, &state, rng, &ray, &throughput))
651                                 break;
652                 }
653 #endif
654
655                 /* direct lighting */
656                 kernel_path_surface_connect_light(kg, rng, &sd, throughput, &state, &L);
657
658                 /* compute direct lighting and next bounce */
659                 if(!kernel_path_surface_bounce(kg, rng, &sd, &throughput, &state, &L, &ray))
660                         break;
661         }
662
663         float3 L_sum = path_radiance_clamp_and_sum(kg, &L);
664
665         kernel_write_light_passes(kg, buffer, &L, sample);
666
667         return make_float4(L_sum.x, L_sum.y, L_sum.z, 1.0f - L_transparent);
668 }
669
670 #ifdef __BRANCHED_PATH__
671
672 /* branched path tracing: bounce off surface and integrate indirect light */
673 ccl_device_noinline void kernel_branched_path_surface_indirect_light(KernelGlobals *kg,
674         RNG *rng, ShaderData *sd, float3 throughput, float num_samples_adjust,
675         PathState *state, PathRadiance *L)
676 {
677         for(int i = 0; i< sd->num_closure; i++) {
678                 const ShaderClosure *sc = &sd->closure[i];
679
680                 if(!CLOSURE_IS_BSDF(sc->type))
681                         continue;
682                 /* transparency is not handled here, but in outer loop */
683                 if(sc->type == CLOSURE_BSDF_TRANSPARENT_ID)
684                         continue;
685
686                 int num_samples;
687
688                 if(CLOSURE_IS_BSDF_DIFFUSE(sc->type))
689                         num_samples = kernel_data.integrator.diffuse_samples;
690                 else if(CLOSURE_IS_BSDF_BSSRDF(sc->type))
691                         num_samples = 1;
692                 else if(CLOSURE_IS_BSDF_GLOSSY(sc->type))
693                         num_samples = kernel_data.integrator.glossy_samples;
694                 else
695                         num_samples = kernel_data.integrator.transmission_samples;
696
697                 num_samples = ceil_to_int(num_samples_adjust*num_samples);
698
699                 float num_samples_inv = num_samples_adjust/num_samples;
700                 RNG bsdf_rng = cmj_hash(*rng, i);
701
702                 for(int j = 0; j < num_samples; j++) {
703                         PathState ps = *state;
704                         float3 tp = throughput;
705                         Ray bsdf_ray;
706
707                         if(!kernel_branched_path_surface_bounce(kg, &bsdf_rng, sd, sc, j, num_samples, &tp, &ps, L, &bsdf_ray))
708                                 continue;
709
710                         kernel_path_indirect(kg, rng, bsdf_ray, tp*num_samples_inv, num_samples, ps, L);
711
712                         /* for render passes, sum and reset indirect light pass variables
713                          * for the next samples */
714                         path_radiance_sum_indirect(L);
715                         path_radiance_reset_indirect(L);
716                 }
717         }
718 }
719
720 #ifdef __SUBSURFACE__
721 ccl_device void kernel_branched_path_subsurface_scatter(KernelGlobals *kg, ShaderData *sd, PathRadiance *L, PathState *state, RNG *rng, float3 throughput)
722 {
723         for(int i = 0; i< sd->num_closure; i++) {
724                 ShaderClosure *sc = &sd->closure[i];
725
726                 if(!CLOSURE_IS_BSSRDF(sc->type))
727                         continue;
728
729                 /* set up random number generator */
730                 uint lcg_state = lcg_state_init(rng, state, 0x68bc21eb);
731                 int num_samples = kernel_data.integrator.subsurface_samples;
732                 float num_samples_inv = 1.0f/num_samples;
733                 RNG bssrdf_rng = cmj_hash(*rng, i);
734
735                 state->flag |= PATH_RAY_BSSRDF_ANCESTOR;
736
737                 /* do subsurface scatter step with copy of shader data, this will
738                  * replace the BSSRDF with a diffuse BSDF closure */
739                 for(int j = 0; j < num_samples; j++) {
740                         ShaderData bssrdf_sd[BSSRDF_MAX_HITS];
741                         float bssrdf_u, bssrdf_v;
742                         path_branched_rng_2D(kg, &bssrdf_rng, state, j, num_samples, PRNG_BSDF_U, &bssrdf_u, &bssrdf_v);
743                         int num_hits = subsurface_scatter_multi_step(kg, sd, bssrdf_sd, state->flag, sc, &lcg_state, bssrdf_u, bssrdf_v, true);
744
745                         /* compute lighting with the BSDF closure */
746                         for(int hit = 0; hit < num_hits; hit++) {
747                                 PathState hit_state = *state;
748
749                                 path_state_branch(&hit_state, j, num_samples);
750
751 #if defined(__EMISSION__) && defined(__BRANCHED_PATH__)
752                                 /* direct light */
753                                 if(kernel_data.integrator.use_direct_light) {
754                                         bool all = kernel_data.integrator.sample_all_lights_direct;
755                                         kernel_branched_path_surface_connect_light(kg, rng,
756                                                 &bssrdf_sd[hit], &hit_state, throughput, num_samples_inv, L, all);
757                                 }
758 #endif
759
760                                 /* indirect light */
761                                 kernel_branched_path_surface_indirect_light(kg, rng,
762                                         &bssrdf_sd[hit], throughput, num_samples_inv,
763                                         &hit_state, L);
764                         }
765                 }
766
767                 state->flag &= ~PATH_RAY_BSSRDF_ANCESTOR;
768         }
769 }
770 #endif
771
772 ccl_device float4 kernel_branched_path_integrate(KernelGlobals *kg, RNG *rng, int sample, Ray ray, ccl_global float *buffer)
773 {
774         /* initialize */
775         PathRadiance L;
776         float3 throughput = make_float3(1.0f, 1.0f, 1.0f);
777         float L_transparent = 0.0f;
778
779         path_radiance_init(&L, kernel_data.film.use_light_pass);
780
781         PathState state;
782         path_state_init(kg, &state, rng, sample);
783
784         for(;;) {
785                 /* intersect scene */
786                 Intersection isect;
787                 uint visibility = path_state_ray_visibility(kg, &state);
788
789 #ifdef __HAIR__
790                 float difl = 0.0f, extmax = 0.0f;
791                 uint lcg_state = 0;
792
793                 if(kernel_data.bvh.have_curves) {
794                         if((kernel_data.cam.resolution == 1) && (state.flag & PATH_RAY_CAMERA)) {       
795                                 float3 pixdiff = ray.dD.dx + ray.dD.dy;
796                                 /*pixdiff = pixdiff - dot(pixdiff, ray.D)*ray.D;*/
797                                 difl = kernel_data.curve.minimum_width * len(pixdiff) * 0.5f;
798                         }
799
800                         extmax = kernel_data.curve.maximum_width;
801                         lcg_state = lcg_state_init(rng, &state, 0x51633e2d);
802                 }
803
804                 bool hit = scene_intersect(kg, &ray, visibility, &isect, &lcg_state, difl, extmax);
805 #else
806                 bool hit = scene_intersect(kg, &ray, visibility, &isect, NULL, 0.0f, 0.0f);
807 #endif
808
809 #ifdef __VOLUME__
810                 /* volume attenuation, emission, scatter */
811                 if(state.volume_stack[0].shader != SHADER_NONE) {
812                         Ray volume_ray = ray;
813                         volume_ray.t = (hit)? isect.t: FLT_MAX;
814                         
815                         bool heterogeneous = volume_stack_is_heterogeneous(kg, state.volume_stack);
816
817 #ifdef __VOLUME_DECOUPLED__
818                         /* decoupled ray marching only supported on CPU */
819
820                         /* cache steps along volume for repeated sampling */
821                         VolumeSegment volume_segment;
822                         ShaderData volume_sd;
823
824                         shader_setup_from_volume(kg, &volume_sd, &volume_ray, state.bounce, state.transparent_bounce);
825                         kernel_volume_decoupled_record(kg, &state,
826                                 &volume_ray, &volume_sd, &volume_segment, heterogeneous);
827
828                         /* direct light sampling */
829                         if(volume_segment.closure_flag & SD_SCATTER) {
830                                 volume_segment.sampling_method = volume_stack_sampling_method(kg, state.volume_stack);
831
832                                 bool all = kernel_data.integrator.sample_all_lights_direct;
833
834                                 kernel_branched_path_volume_connect_light(kg, rng, &volume_sd,
835                                         throughput, &state, &L, 1.0f, all, &volume_ray, &volume_segment);
836
837                                 /* indirect light sampling */
838                                 int num_samples = kernel_data.integrator.volume_samples;
839                                 float num_samples_inv = 1.0f/num_samples;
840
841                                 for(int j = 0; j < num_samples; j++) {
842                                         /* workaround to fix correlation bug in T38710, can find better solution
843                                          * in random number generator later, for now this is done here to not impact
844                                          * performance of rendering without volumes */
845                                         RNG tmp_rng = cmj_hash(*rng, state.rng_offset);
846
847                                         PathState ps = state;
848                                         Ray pray = ray;
849                                         float3 tp = throughput;
850
851                                         /* branch RNG state */
852                                         path_state_branch(&ps, j, num_samples);
853
854                                         /* scatter sample. if we use distance sampling and take just one
855                                          * sample for direct and indirect light, we could share this
856                                          * computation, but makes code a bit complex */
857                                         float rphase = path_state_rng_1D_for_decision(kg, &tmp_rng, &ps, PRNG_PHASE);
858                                         float rscatter = path_state_rng_1D_for_decision(kg, &tmp_rng, &ps, PRNG_SCATTER_DISTANCE);
859
860                                         VolumeIntegrateResult result = kernel_volume_decoupled_scatter(kg,
861                                                 &ps, &pray, &volume_sd, &tp, rphase, rscatter, &volume_segment, NULL, false);
862                                                 
863                                         (void)result;
864                                         kernel_assert(result == VOLUME_PATH_SCATTERED);
865
866                                         if(kernel_path_volume_bounce(kg, rng, &volume_sd, &tp, &ps, &L, &pray)) {
867                                                 kernel_path_indirect(kg, rng, pray, tp*num_samples_inv, num_samples, ps, &L);
868
869                                                 /* for render passes, sum and reset indirect light pass variables
870                                                  * for the next samples */
871                                                 path_radiance_sum_indirect(&L);
872                                                 path_radiance_reset_indirect(&L);
873                                         }
874                                 }
875                         }
876
877                         /* emission and transmittance */
878                         if(volume_segment.closure_flag & SD_EMISSION)
879                                 path_radiance_accum_emission(&L, throughput, volume_segment.accum_emission, state.bounce);
880                         throughput *= volume_segment.accum_transmittance;
881
882                         /* free cached steps */
883                         kernel_volume_decoupled_free(kg, &volume_segment);
884 #else
885                         /* GPU: no decoupled ray marching, scatter probalistically */
886                         int num_samples = kernel_data.integrator.volume_samples;
887                         float num_samples_inv = 1.0f/num_samples;
888
889                         /* todo: we should cache the shader evaluations from stepping
890                          * through the volume, for now we redo them multiple times */
891
892                         for(int j = 0; j < num_samples; j++) {
893                                 PathState ps = state;
894                                 Ray pray = ray;
895                                 ShaderData volume_sd;
896                                 float3 tp = throughput * num_samples_inv;
897
898                                 /* branch RNG state */
899                                 path_state_branch(&ps, j, num_samples);
900
901                                 VolumeIntegrateResult result = kernel_volume_integrate(
902                                         kg, &ps, &volume_sd, &volume_ray, &L, &tp, rng, heterogeneous);
903                                 
904 #ifdef __VOLUME_SCATTER__
905                                 if(result == VOLUME_PATH_SCATTERED) {
906                                         /* todo: support equiangular, MIS and all light sampling.
907                                          * alternatively get decoupled ray marching working on the GPU */
908                                         kernel_path_volume_connect_light(kg, rng, &volume_sd, tp, &state, &L);
909
910                                         if(kernel_path_volume_bounce(kg, rng, &volume_sd, &tp, &ps, &L, &pray)) {
911                                                 kernel_path_indirect(kg, rng, pray, tp, num_samples, ps, &L);
912
913                                                 /* for render passes, sum and reset indirect light pass variables
914                                                  * for the next samples */
915                                                 path_radiance_sum_indirect(&L);
916                                                 path_radiance_reset_indirect(&L);
917                                         }
918                                 }
919 #endif
920                         }
921
922                         /* todo: avoid this calculation using decoupled ray marching */
923                         kernel_volume_shadow(kg, &state, &volume_ray, &throughput);
924 #endif
925                 }
926 #endif
927
928                 if(!hit) {
929                         /* eval background shader if nothing hit */
930                         if(kernel_data.background.transparent) {
931                                 L_transparent += average(throughput);
932
933 #ifdef __PASSES__
934                                 if(!(kernel_data.film.pass_flag & PASS_BACKGROUND))
935 #endif
936                                         break;
937                         }
938
939 #ifdef __BACKGROUND__
940                         /* sample background shader */
941                         float3 L_background = indirect_background(kg, &state, &ray);
942                         path_radiance_accum_background(&L, throughput, L_background, state.bounce);
943 #endif
944
945                         break;
946                 }
947
948                 /* setup shading */
949                 ShaderData sd;
950                 shader_setup_from_ray(kg, &sd, &isect, &ray, state.bounce, state.transparent_bounce);
951                 shader_eval_surface(kg, &sd, 0.0f, state.flag, SHADER_CONTEXT_MAIN);
952                 shader_merge_closures(&sd);
953
954                 /* holdout */
955 #ifdef __HOLDOUT__
956                 if(sd.flag & (SD_HOLDOUT|SD_HOLDOUT_MASK)) {
957                         if(kernel_data.background.transparent) {
958                                 float3 holdout_weight;
959                                 
960                                 if(sd.flag & SD_HOLDOUT_MASK)
961                                         holdout_weight = make_float3(1.0f, 1.0f, 1.0f);
962                                 else
963                                         holdout_weight = shader_holdout_eval(kg, &sd);
964
965                                 /* any throughput is ok, should all be identical here */
966                                 L_transparent += average(holdout_weight*throughput);
967                         }
968
969                         if(sd.flag & SD_HOLDOUT_MASK)
970                                 break;
971                 }
972 #endif
973
974                 /* holdout mask objects do not write data passes */
975                 kernel_write_data_passes(kg, buffer, &L, &sd, sample, &state, throughput);
976
977 #ifdef __EMISSION__
978                 /* emission */
979                 if(sd.flag & SD_EMISSION) {
980                         float3 emission = indirect_primitive_emission(kg, &sd, isect.t, state.flag, state.ray_pdf);
981                         path_radiance_accum_emission(&L, throughput, emission, state.bounce);
982                 }
983 #endif
984
985                 /* transparency termination */
986                 if(state.flag & PATH_RAY_TRANSPARENT) {
987                         /* path termination. this is a strange place to put the termination, it's
988                          * mainly due to the mixed in MIS that we use. gives too many unneeded
989                          * shader evaluations, only need emission if we are going to terminate */
990                         float probability = path_state_terminate_probability(kg, &state, throughput);
991
992                         if(probability == 0.0f) {
993                                 break;
994                         }
995                         else if(probability != 1.0f) {
996                                 float terminate = path_state_rng_1D_for_decision(kg, rng, &state, PRNG_TERMINATE);
997
998                                 if(terminate >= probability)
999                                         break;
1000
1001                                 throughput /= probability;
1002                         }
1003                 }
1004
1005 #ifdef __AO__
1006                 /* ambient occlusion */
1007                 if(kernel_data.integrator.use_ambient_occlusion || (sd.flag & SD_AO)) {
1008                         kernel_branched_path_ao(kg, &sd, &L, &state, rng, throughput);
1009                 }
1010 #endif
1011
1012 #ifdef __SUBSURFACE__
1013                 /* bssrdf scatter to a different location on the same object */
1014                 if(sd.flag & SD_BSSRDF) {
1015                         kernel_branched_path_subsurface_scatter(kg, &sd, &L, &state, rng, throughput);
1016                 }
1017 #endif
1018
1019                 if(!(sd.flag & SD_HAS_ONLY_VOLUME)) {
1020                         PathState hit_state = state;
1021
1022 #ifdef __EMISSION__
1023                         /* direct light */
1024                         if(kernel_data.integrator.use_direct_light) {
1025                                 bool all = kernel_data.integrator.sample_all_lights_direct;
1026                                 kernel_branched_path_surface_connect_light(kg, rng,
1027                                         &sd, &hit_state, throughput, 1.0f, &L, all);
1028                         }
1029 #endif
1030
1031                         /* indirect light */
1032                         kernel_branched_path_surface_indirect_light(kg, rng,
1033                                 &sd, throughput, 1.0f, &hit_state, &L);
1034
1035                         /* continue in case of transparency */
1036                         throughput *= shader_bsdf_transparency(kg, &sd);
1037
1038                         if(is_zero(throughput))
1039                                 break;
1040                 }
1041
1042                 path_state_next(kg, &state, LABEL_TRANSPARENT);
1043                 ray.P = ray_offset(sd.P, -sd.Ng);
1044                 ray.t -= sd.ray_length; /* clipping works through transparent */
1045
1046
1047 #ifdef __RAY_DIFFERENTIALS__
1048                 ray.dP = sd.dP;
1049                 ray.dD.dx = -sd.dI.dx;
1050                 ray.dD.dy = -sd.dI.dy;
1051 #endif
1052
1053 #ifdef __VOLUME__
1054                 /* enter/exit volume */
1055                 kernel_volume_stack_enter_exit(kg, &sd, state.volume_stack);
1056 #endif
1057         }
1058
1059         float3 L_sum = path_radiance_clamp_and_sum(kg, &L);
1060
1061         kernel_write_light_passes(kg, buffer, &L, sample);
1062
1063         return make_float4(L_sum.x, L_sum.y, L_sum.z, 1.0f - L_transparent);
1064 }
1065
1066 #endif
1067
1068 ccl_device_inline void kernel_path_trace_setup(KernelGlobals *kg, ccl_global uint *rng_state, int sample, int x, int y, RNG *rng, Ray *ray)
1069 {
1070         float filter_u;
1071         float filter_v;
1072
1073         int num_samples = kernel_data.integrator.aa_samples;
1074
1075         path_rng_init(kg, rng_state, sample, num_samples, rng, x, y, &filter_u, &filter_v);
1076
1077         /* sample camera ray */
1078
1079         float lens_u = 0.0f, lens_v = 0.0f;
1080
1081         if(kernel_data.cam.aperturesize > 0.0f)
1082                 path_rng_2D(kg, rng, sample, num_samples, PRNG_LENS_U, &lens_u, &lens_v);
1083
1084         float time = 0.0f;
1085
1086 #ifdef __CAMERA_MOTION__
1087         if(kernel_data.cam.shuttertime != -1.0f)
1088                 time = path_rng_1D(kg, rng, sample, num_samples, PRNG_TIME);
1089 #endif
1090
1091         camera_sample(kg, x, y, filter_u, filter_v, lens_u, lens_v, time, ray);
1092 }
1093
1094 ccl_device void kernel_path_trace(KernelGlobals *kg,
1095         ccl_global float *buffer, ccl_global uint *rng_state,
1096         int sample, int x, int y, int offset, int stride)
1097 {
1098         /* buffer offset */
1099         int index = offset + x + y*stride;
1100         int pass_stride = kernel_data.film.pass_stride;
1101
1102         rng_state += index;
1103         buffer += index*pass_stride;
1104
1105         /* initialize random numbers and ray */
1106         RNG rng;
1107         Ray ray;
1108
1109         kernel_path_trace_setup(kg, rng_state, sample, x, y, &rng, &ray);
1110
1111         /* integrate */
1112         float4 L;
1113
1114         if(ray.t != 0.0f)
1115                 L = kernel_path_integrate(kg, &rng, sample, ray, buffer);
1116         else
1117                 L = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
1118
1119         /* accumulate result in output buffer */
1120         kernel_write_pass_float4(buffer, sample, L);
1121
1122         path_rng_end(kg, rng_state, rng);
1123 }
1124
1125 #ifdef __BRANCHED_PATH__
1126 ccl_device void kernel_branched_path_trace(KernelGlobals *kg,
1127         ccl_global float *buffer, ccl_global uint *rng_state,
1128         int sample, int x, int y, int offset, int stride)
1129 {
1130         /* buffer offset */
1131         int index = offset + x + y*stride;
1132         int pass_stride = kernel_data.film.pass_stride;
1133
1134         rng_state += index;
1135         buffer += index*pass_stride;
1136
1137         /* initialize random numbers and ray */
1138         RNG rng;
1139         Ray ray;
1140
1141         kernel_path_trace_setup(kg, rng_state, sample, x, y, &rng, &ray);
1142
1143         /* integrate */
1144         float4 L;
1145
1146         if(ray.t != 0.0f)
1147                 L = kernel_branched_path_integrate(kg, &rng, sample, ray, buffer);
1148         else
1149                 L = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
1150
1151         /* accumulate result in output buffer */
1152         kernel_write_pass_float4(buffer, sample, L);
1153
1154         path_rng_end(kg, rng_state, rng);
1155 }
1156 #endif
1157
1158 CCL_NAMESPACE_END
1159