Cycles: Automatically detect HDRI resolution by default and use non-square sampling map
[blender.git] / intern / cycles / kernel / kernel_light.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 /* Light Sample result */
20
21 typedef struct LightSample {
22         float3 P;                       /* position on light, or direction for distant light */
23         float3 Ng;                      /* normal on light */
24         float3 D;                       /* direction from shading point to light */
25         float t;                        /* distance to light (FLT_MAX for distant light) */
26         float u, v;                     /* parametric coordinate on primitive */
27         float pdf;                      /* light sampling probability density function */
28         float eval_fac;         /* intensity multiplier */
29         int object;                     /* object id for triangle/curve lights */
30         int prim;                       /* primitive id for triangle/curve lights */
31         int shader;                     /* shader id */
32         int lamp;                       /* lamp id */
33         LightType type;         /* type of light */
34 } LightSample;
35
36 /* Area light sampling */
37
38 /* Uses the following paper:
39  *
40  * Carlos Urena et al.
41  * An Area-Preserving Parametrization for Spherical Rectangles.
42  *
43  * https://www.solidangle.com/research/egsr2013_spherical_rectangle.pdf
44  *
45  * Note: light_p is modified when sample_coord is true.
46  */
47 ccl_device_inline float area_light_sample(float3 P,
48                                           float3 *light_p,
49                                           float3 axisu, float3 axisv,
50                                           float randu, float randv,
51                                           bool sample_coord)
52 {
53         /* In our name system we're using P for the center,
54          * which is o in the paper.
55          */
56
57         float3 corner = *light_p - axisu * 0.5f - axisv * 0.5f;
58         float axisu_len, axisv_len;
59         /* Compute local reference system R. */
60         float3 x = normalize_len(axisu, &axisu_len);
61         float3 y = normalize_len(axisv, &axisv_len);
62         float3 z = cross(x, y);
63         /* Compute rectangle coords in local reference system. */
64         float3 dir = corner - P;
65         float z0 = dot(dir, z);
66         /* Flip 'z' to make it point against Q. */
67         if(z0 > 0.0f) {
68                 z *= -1.0f;
69                 z0 *= -1.0f;
70         }
71         float x0 = dot(dir, x);
72         float y0 = dot(dir, y);
73         float x1 = x0 + axisu_len;
74         float y1 = y0 + axisv_len;
75         /* Create vectors to four vertices. */
76         float3 v00 = make_float3(x0, y0, z0);
77         float3 v01 = make_float3(x0, y1, z0);
78         float3 v10 = make_float3(x1, y0, z0);
79         float3 v11 = make_float3(x1, y1, z0);
80         /* Compute normals to edges. */
81         float3 n0 = normalize(cross(v00, v10));
82         float3 n1 = normalize(cross(v10, v11));
83         float3 n2 = normalize(cross(v11, v01));
84         float3 n3 = normalize(cross(v01, v00));
85         /* Compute internal angles (gamma_i). */
86         float g0 = safe_acosf(-dot(n0, n1));
87         float g1 = safe_acosf(-dot(n1, n2));
88         float g2 = safe_acosf(-dot(n2, n3));
89         float g3 = safe_acosf(-dot(n3, n0));
90         /* Compute predefined constants. */
91         float b0 = n0.z;
92         float b1 = n2.z;
93         float b0sq = b0 * b0;
94         float k = M_2PI_F - g2 - g3;
95         /* Compute solid angle from internal angles. */
96         float S = g0 + g1 - k;
97
98         if(sample_coord) {
99                 /* Compute cu. */
100                 float au = randu * S + k;
101                 float fu = (cosf(au) * b0 - b1) / sinf(au);
102                 float cu = 1.0f / sqrtf(fu * fu + b0sq) * (fu > 0.0f ? 1.0f : -1.0f);
103                 cu = clamp(cu, -1.0f, 1.0f);
104                 /* Compute xu. */
105                 float xu = -(cu * z0) / max(sqrtf(1.0f - cu * cu), 1e-7f);
106                 xu = clamp(xu, x0, x1);
107                 /* Compute yv. */
108                 float z0sq = z0 * z0;
109                 float y0sq = y0 * y0;
110                 float y1sq = y1 * y1;
111                 float d = sqrtf(xu * xu + z0sq);
112                 float h0 = y0 / sqrtf(d * d + y0sq);
113                 float h1 = y1 / sqrtf(d * d + y1sq);
114                 float hv = h0 + randv * (h1 - h0), hv2 = hv * hv;
115                 float yv = (hv2 < 1.0f - 1e-6f) ? (hv * d) / sqrtf(1.0f - hv2) : y1;
116
117                 /* Transform (xu, yv, z0) to world coords. */
118                 *light_p = P + xu * x + yv * y + z0 * z;
119         }
120
121         /* return pdf */
122         if(S != 0.0f)
123                 return 1.0f / S;
124         else
125                 return 0.0f;
126 }
127
128 /* Background Light */
129
130 #ifdef __BACKGROUND_MIS__
131
132 /* TODO(sergey): In theory it should be all fine to use noinline for all
133  * devices, but we're so close to the release so better not screw things
134  * up for CPU at least.
135  */
136 #ifdef __KERNEL_GPU__
137 ccl_device_noinline
138 #else
139 ccl_device
140 #endif
141 float3 background_map_sample(KernelGlobals *kg, float randu, float randv, float *pdf)
142 {
143         /* for the following, the CDF values are actually a pair of floats, with the
144          * function value as X and the actual CDF as Y.  The last entry's function
145          * value is the CDF total. */
146         int res_x = kernel_data.integrator.pdf_background_res_x;
147         int res_y = kernel_data.integrator.pdf_background_res_y;
148         int cdf_width = res_x + 1;
149
150         /* this is basically std::lower_bound as used by pbrt */
151         int first = 0;
152         int count = res_y;
153
154         while(count > 0) {
155                 int step = count >> 1;
156                 int middle = first + step;
157
158                 if(kernel_tex_fetch(__light_background_marginal_cdf, middle).y < randv) {
159                         first = middle + 1;
160                         count -= step + 1;
161                 }
162                 else
163                         count = step;
164         }
165
166         int index_v = max(0, first - 1);
167         kernel_assert(index_v >= 0 && index_v < res_y);
168
169         float2 cdf_v = kernel_tex_fetch(__light_background_marginal_cdf, index_v);
170         float2 cdf_next_v = kernel_tex_fetch(__light_background_marginal_cdf, index_v + 1);
171         float2 cdf_last_v = kernel_tex_fetch(__light_background_marginal_cdf, res_y);
172
173         /* importance-sampled V direction */
174         float dv = inverse_lerp(cdf_v.y, cdf_next_v.y, randv);
175         float v = (index_v + dv) / res_y;
176
177         /* this is basically std::lower_bound as used by pbrt */
178         first = 0;
179         count = res_x;
180         while(count > 0) {
181                 int step = count >> 1;
182                 int middle = first + step;
183
184                 if(kernel_tex_fetch(__light_background_conditional_cdf, index_v * cdf_width + middle).y < randu) {
185                         first = middle + 1;
186                         count -= step + 1;
187                 }
188                 else
189                         count = step;
190         }
191
192         int index_u = max(0, first - 1);
193         kernel_assert(index_u >= 0 && index_u < res_x);
194
195         float2 cdf_u = kernel_tex_fetch(__light_background_conditional_cdf, index_v * cdf_width + index_u);
196         float2 cdf_next_u = kernel_tex_fetch(__light_background_conditional_cdf, index_v * cdf_width + index_u + 1);
197         float2 cdf_last_u = kernel_tex_fetch(__light_background_conditional_cdf, index_v * cdf_width + res_x);
198
199         /* importance-sampled U direction */
200         float du = inverse_lerp(cdf_u.y, cdf_next_u.y, randu);
201         float u = (index_u + du) / res_x;
202
203         /* compute pdf */
204         float denom = cdf_last_u.x * cdf_last_v.x;
205         float sin_theta = sinf(M_PI_F * v);
206
207         if(sin_theta == 0.0f || denom == 0.0f)
208                 *pdf = 0.0f;
209         else
210                 *pdf = (cdf_u.x * cdf_v.x)/(M_2PI_F * M_PI_F * sin_theta * denom);
211
212         /* compute direction */
213         return equirectangular_to_direction(u, v);
214 }
215
216 /* TODO(sergey): Same as above, after the release we should consider using
217  * 'noinline' for all devices.
218  */
219 #ifdef __KERNEL_GPU__
220 ccl_device_noinline
221 #else
222 ccl_device
223 #endif
224 float background_map_pdf(KernelGlobals *kg, float3 direction)
225 {
226         float2 uv = direction_to_equirectangular(direction);
227         int res_x = kernel_data.integrator.pdf_background_res_x;
228         int res_y = kernel_data.integrator.pdf_background_res_y;
229         int cdf_width = res_x + 1;
230
231         float sin_theta = sinf(uv.y * M_PI_F);
232
233         if(sin_theta == 0.0f)
234                 return 0.0f;
235
236         int index_u = clamp(float_to_int(uv.x * res_x), 0, res_x - 1);
237         int index_v = clamp(float_to_int(uv.y * res_y), 0, res_y - 1);
238
239         /* pdfs in V direction */
240         float2 cdf_last_u = kernel_tex_fetch(__light_background_conditional_cdf, index_v * cdf_width + res_x);
241         float2 cdf_last_v = kernel_tex_fetch(__light_background_marginal_cdf, res_y);
242
243         float denom = cdf_last_u.x * cdf_last_v.x;
244
245         if(denom == 0.0f)
246                 return 0.0f;
247
248         /* pdfs in U direction */
249         float2 cdf_u = kernel_tex_fetch(__light_background_conditional_cdf, index_v * cdf_width + index_u);
250         float2 cdf_v = kernel_tex_fetch(__light_background_marginal_cdf, index_v);
251
252         return (cdf_u.x * cdf_v.x)/(M_2PI_F * M_PI_F * sin_theta * denom);
253 }
254
255 ccl_device_inline bool background_portal_data_fetch_and_check_side(KernelGlobals *kg,
256                                                                    float3 P,
257                                                                    int index,
258                                                                    float3 *lightpos,
259                                                                    float3 *dir)
260 {
261         int portal = kernel_data.integrator.portal_offset + index;
262         const ccl_global KernelLight *klight = &kernel_tex_fetch(__lights, portal);
263
264         *lightpos = make_float3(klight->co[0], klight->co[1], klight->co[2]);
265         *dir = make_float3(klight->area.dir[0], klight->area.dir[1], klight->area.dir[2]);
266
267         /* Check whether portal is on the right side. */
268         if(dot(*dir, P - *lightpos) > 1e-4f)
269                 return true;
270
271         return false;
272 }
273
274 ccl_device_inline float background_portal_pdf(KernelGlobals *kg,
275                                               float3 P,
276                                               float3 direction,
277                                               int ignore_portal,
278                                               bool *is_possible)
279 {
280         float portal_pdf = 0.0f;
281
282         int num_possible = 0;
283         for(int p = 0; p < kernel_data.integrator.num_portals; p++) {
284                 if(p == ignore_portal)
285                         continue;
286
287                 float3 lightpos, dir;
288                 if(!background_portal_data_fetch_and_check_side(kg, P, p, &lightpos, &dir))
289                         continue;
290
291                 /* There's a portal that could be sampled from this position. */
292                 if(is_possible) {
293                         *is_possible = true;
294                 }
295                 num_possible++;
296
297                 int portal = kernel_data.integrator.portal_offset + p;
298                 const ccl_global KernelLight *klight = &kernel_tex_fetch(__lights, portal);
299                 float3 axisu = make_float3(klight->area.axisu[0], klight->area.axisu[1], klight->area.axisu[2]);
300                 float3 axisv = make_float3(klight->area.axisv[0], klight->area.axisv[1], klight->area.axisv[2]);
301
302                 if(!ray_quad_intersect(P, direction, 1e-4f, FLT_MAX, lightpos, axisu, axisv, dir, NULL, NULL, NULL, NULL))
303                         continue;
304
305                 portal_pdf += area_light_sample(P, &lightpos, axisu, axisv, 0.0f, 0.0f, false);
306         }
307
308         if(ignore_portal >= 0) {
309                 /* We have skipped a portal that could be sampled as well. */
310                 num_possible++;
311         }
312
313         return (num_possible > 0)? portal_pdf / num_possible: 0.0f;
314 }
315
316 ccl_device int background_num_possible_portals(KernelGlobals *kg, float3 P)
317 {
318         int num_possible_portals = 0;
319         for(int p = 0; p < kernel_data.integrator.num_portals; p++) {
320                 float3 lightpos, dir;
321                 if(background_portal_data_fetch_and_check_side(kg, P, p, &lightpos, &dir))
322                         num_possible_portals++;
323         }
324         return num_possible_portals;
325 }
326
327 ccl_device float3 background_portal_sample(KernelGlobals *kg,
328                                            float3 P,
329                                            float randu,
330                                            float randv,
331                                            int num_possible,
332                                            int *sampled_portal,
333                                            float *pdf)
334 {
335         /* Pick a portal, then re-normalize randv. */
336         randv *= num_possible;
337         int portal = (int)randv;
338         randv -= portal;
339
340         /* TODO(sergey): Some smarter way of finding portal to sample
341          * is welcome.
342          */
343         for(int p = 0; p < kernel_data.integrator.num_portals; p++) {
344                 /* Search for the sampled portal. */
345                 float3 lightpos, dir;
346                 if(!background_portal_data_fetch_and_check_side(kg, P, p, &lightpos, &dir))
347                         continue;
348
349                 if(portal == 0) {
350                         /* p is the portal to be sampled. */
351                         int portal = kernel_data.integrator.portal_offset + p;
352                         const ccl_global KernelLight *klight = &kernel_tex_fetch(__lights, portal);
353                         float3 axisu = make_float3(klight->area.axisu[0], klight->area.axisu[1], klight->area.axisu[2]);
354                         float3 axisv = make_float3(klight->area.axisv[0], klight->area.axisv[1], klight->area.axisv[2]);
355
356                         *pdf = area_light_sample(P, &lightpos,
357                                                  axisu, axisv,
358                                                  randu, randv,
359                                                  true);
360
361                         *pdf /= num_possible;
362                         *sampled_portal = p;
363                         return normalize(lightpos - P);
364                 }
365
366                 portal--;
367         }
368
369         return make_float3(0.0f, 0.0f, 0.0f);
370 }
371
372 ccl_device_inline float3 background_light_sample(KernelGlobals *kg,
373                                                  float3 P,
374                                                  float randu, float randv,
375                                                  float *pdf)
376 {
377         /* Probability of sampling portals instead of the map. */
378         float portal_sampling_pdf = kernel_data.integrator.portal_pdf;
379
380         /* Check if there are portals in the scene which we can sample. */
381         if(portal_sampling_pdf > 0.0f) {
382                 int num_portals = background_num_possible_portals(kg, P);
383                 if(num_portals > 0) {
384                         if(portal_sampling_pdf == 1.0f || randu < portal_sampling_pdf) {
385                                 if(portal_sampling_pdf < 1.0f) {
386                                         randu /= portal_sampling_pdf;
387                                 }
388                                 int portal;
389                                 float3 D = background_portal_sample(kg, P, randu, randv, num_portals, &portal, pdf);
390                                 if(num_portals > 1) {
391                                         /* Ignore the chosen portal, its pdf is already included. */
392                                         *pdf += background_portal_pdf(kg, P, D, portal, NULL);
393                                 }
394                                 /* We could also have sampled the map, so combine with MIS. */
395                                 if(portal_sampling_pdf < 1.0f) {
396                                         float cdf_pdf = background_map_pdf(kg, D);
397                                         *pdf = (portal_sampling_pdf * (*pdf)
398                                              + (1.0f - portal_sampling_pdf) * cdf_pdf);
399                                 }
400                                 return D;
401                         }
402                         else {
403                                 /* Sample map, but with nonzero portal_sampling_pdf for MIS. */
404                                 randu = (randu - portal_sampling_pdf) / (1.0f - portal_sampling_pdf);
405                         }
406                 }
407                 else {
408                         /* We can't sample a portal.
409                          * Check if we can sample the map instead.
410                          */
411                         if(portal_sampling_pdf == 1.0f) {
412                                 /* Use uniform as a fallback if we can't sample the map. */
413                                 *pdf = 1.0f / M_4PI_F;
414                                 return sample_uniform_sphere(randu, randv);
415                         }
416                         else {
417                                 portal_sampling_pdf = 0.0f;
418                         }
419                 }
420         }
421
422         float3 D = background_map_sample(kg, randu, randv, pdf);
423         /* Use MIS if portals could be sampled as well. */
424         if(portal_sampling_pdf > 0.0f) {
425                 float portal_pdf = background_portal_pdf(kg, P, D, -1, NULL);
426                 *pdf = (portal_sampling_pdf * portal_pdf
427                      + (1.0f - portal_sampling_pdf) * (*pdf));
428         }
429         return D;
430 }
431
432 ccl_device float background_light_pdf(KernelGlobals *kg, float3 P, float3 direction)
433 {
434         /* Probability of sampling portals instead of the map. */
435         float portal_sampling_pdf = kernel_data.integrator.portal_pdf;
436
437         float portal_pdf = 0.0f, map_pdf = 0.0f;
438         if(portal_sampling_pdf > 0.0f) {
439                 /* Evaluate PDF of sampling this direction by portal sampling. */
440                 bool is_possible = false;
441                 portal_pdf = background_portal_pdf(kg, P, direction, -1, &is_possible) * portal_sampling_pdf;
442                 if(!is_possible) {
443                         /* Portal sampling is not possible here because all portals point to the wrong side.
444                          * If map sampling is possible, it would be used instead, otherwise fallback sampling is used. */
445                         if(portal_sampling_pdf == 1.0f) {
446                                 return kernel_data.integrator.pdf_lights / M_4PI_F;
447                         }
448                         else {
449                                 /* Force map sampling. */
450                                 portal_sampling_pdf = 0.0f;
451                         }
452                 }
453         }
454         if(portal_sampling_pdf < 1.0f) {
455                 /* Evaluate PDF of sampling this direction by map sampling. */
456                 map_pdf = background_map_pdf(kg, direction) * (1.0f - portal_sampling_pdf);
457         }
458         return (portal_pdf + map_pdf) * kernel_data.integrator.pdf_lights;
459 }
460 #endif
461
462 /* Regular Light */
463
464 ccl_device float3 disk_light_sample(float3 v, float randu, float randv)
465 {
466         float3 ru, rv;
467
468         make_orthonormals(v, &ru, &rv);
469         to_unit_disk(&randu, &randv);
470
471         return ru*randu + rv*randv;
472 }
473
474 ccl_device float3 distant_light_sample(float3 D, float radius, float randu, float randv)
475 {
476         return normalize(D + disk_light_sample(D, randu, randv)*radius);
477 }
478
479 ccl_device float3 sphere_light_sample(float3 P, float3 center, float radius, float randu, float randv)
480 {
481         return disk_light_sample(normalize(P - center), randu, randv)*radius;
482 }
483
484 ccl_device float spot_light_attenuation(float3 dir, float spot_angle, float spot_smooth, LightSample *ls)
485 {
486         float3 I = ls->Ng;
487
488         float attenuation = dot(dir, I);
489
490         if(attenuation <= spot_angle) {
491                 attenuation = 0.0f;
492         }
493         else {
494                 float t = attenuation - spot_angle;
495
496                 if(t < spot_smooth && spot_smooth != 0.0f)
497                         attenuation *= smoothstepf(t/spot_smooth);
498         }
499
500         return attenuation;
501 }
502
503 ccl_device float lamp_light_pdf(KernelGlobals *kg, const float3 Ng, const float3 I, float t)
504 {
505         float cos_pi = dot(Ng, I);
506
507         if(cos_pi <= 0.0f)
508                 return 0.0f;
509         
510         return t*t/cos_pi;
511 }
512
513 ccl_device_inline bool lamp_light_sample(KernelGlobals *kg,
514                                          int lamp,
515                                          float randu, float randv,
516                                          float3 P,
517                                          LightSample *ls)
518 {
519         const ccl_global KernelLight *klight = &kernel_tex_fetch(__lights, lamp);
520         LightType type = (LightType)klight->type;
521         ls->type = type;
522         ls->shader = klight->shader_id;
523         ls->object = PRIM_NONE;
524         ls->prim = PRIM_NONE;
525         ls->lamp = lamp;
526         ls->u = randu;
527         ls->v = randv;
528
529         if(type == LIGHT_DISTANT) {
530                 /* distant light */
531                 float3 lightD = make_float3(klight->co[0], klight->co[1], klight->co[2]);
532                 float3 D = lightD;
533                 float radius = klight->distant.radius;
534                 float invarea = klight->distant.invarea;
535
536                 if(radius > 0.0f)
537                         D = distant_light_sample(D, radius, randu, randv);
538
539                 ls->P = D;
540                 ls->Ng = D;
541                 ls->D = -D;
542                 ls->t = FLT_MAX;
543
544                 float costheta = dot(lightD, D);
545                 ls->pdf = invarea/(costheta*costheta*costheta);
546                 ls->eval_fac = ls->pdf;
547         }
548 #ifdef __BACKGROUND_MIS__
549         else if(type == LIGHT_BACKGROUND) {
550                 /* infinite area light (e.g. light dome or env light) */
551                 float3 D = -background_light_sample(kg, P, randu, randv, &ls->pdf);
552
553                 ls->P = D;
554                 ls->Ng = D;
555                 ls->D = -D;
556                 ls->t = FLT_MAX;
557                 ls->eval_fac = 1.0f;
558         }
559 #endif
560         else {
561                 ls->P = make_float3(klight->co[0], klight->co[1], klight->co[2]);
562
563                 if(type == LIGHT_POINT || type == LIGHT_SPOT) {
564                         float radius = klight->spot.radius;
565
566                         if(radius > 0.0f)
567                                 /* sphere light */
568                                 ls->P += sphere_light_sample(P, ls->P, radius, randu, randv);
569
570                         ls->D = normalize_len(ls->P - P, &ls->t);
571                         ls->Ng = -ls->D;
572
573                         float invarea = klight->spot.invarea;
574                         ls->eval_fac = (0.25f*M_1_PI_F)*invarea;
575                         ls->pdf = invarea;
576
577                         if(type == LIGHT_SPOT) {
578                                 /* spot light attenuation */
579                                 float3 dir = make_float3(klight->spot.dir[0],
580                                          klight->spot.dir[1],
581                                                          klight->spot.dir[2]);
582                                 ls->eval_fac *= spot_light_attenuation(dir,
583                                                                        klight->spot.spot_angle,
584                                                                        klight->spot.spot_smooth,
585                                                                        ls);
586                                 if(ls->eval_fac == 0.0f) {
587                                         return false;
588                                 }
589                         }
590                         float2 uv = map_to_sphere(ls->Ng);
591                         ls->u = uv.x;
592                         ls->v = uv.y;
593
594                         ls->pdf *= lamp_light_pdf(kg, ls->Ng, -ls->D, ls->t);
595                 }
596                 else {
597                         /* area light */
598                         float3 axisu = make_float3(klight->area.axisu[0],
599                                                    klight->area.axisu[1],
600                                                    klight->area.axisu[2]);
601                         float3 axisv = make_float3(klight->area.axisv[0],
602                                                    klight->area.axisv[1],
603                                                    klight->area.axisv[2]);
604                         float3 D = make_float3(klight->area.dir[0],
605                                                klight->area.dir[1],
606                                                klight->area.dir[2]);
607
608                         if(dot(ls->P - P, D) > 0.0f) {
609                                 return false;
610                         }
611
612                         float3 inplane = ls->P;
613                         ls->pdf = area_light_sample(P, &ls->P,
614                                                   axisu, axisv,
615                                                   randu, randv,
616                                                   true);
617
618                         inplane = ls->P - inplane;
619                         ls->u = dot(inplane, axisu) * (1.0f / dot(axisu, axisu)) + 0.5f;
620                         ls->v = dot(inplane, axisv) * (1.0f / dot(axisv, axisv)) + 0.5f;
621
622                         ls->Ng = D;
623                         ls->D = normalize_len(ls->P - P, &ls->t);
624
625                         float invarea = klight->area.invarea;
626                         ls->eval_fac = 0.25f*invarea;
627                 }
628         }
629
630         ls->pdf *= kernel_data.integrator.pdf_lights;
631
632         return (ls->pdf > 0.0f);
633 }
634
635 ccl_device bool lamp_light_eval(KernelGlobals *kg, int lamp, float3 P, float3 D, float t, LightSample *ls)
636 {
637         const ccl_global KernelLight *klight = &kernel_tex_fetch(__lights, lamp);
638         LightType type = (LightType)klight->type;
639         ls->type = type;
640         ls->shader = klight->shader_id;
641         ls->object = PRIM_NONE;
642         ls->prim = PRIM_NONE;
643         ls->lamp = lamp;
644         /* todo: missing texture coordinates */
645         ls->u = 0.0f;
646         ls->v = 0.0f;
647
648         if(!(ls->shader & SHADER_USE_MIS))
649                 return false;
650
651         if(type == LIGHT_DISTANT) {
652                 /* distant light */
653                 float radius = klight->distant.radius;
654
655                 if(radius == 0.0f)
656                         return false;
657                 if(t != FLT_MAX)
658                         return false;
659
660                 /* a distant light is infinitely far away, but equivalent to a disk
661                  * shaped light exactly 1 unit away from the current shading point.
662                  *
663                  *     radius              t^2/cos(theta)
664                  *  <---------->           t = sqrt(1^2 + tan(theta)^2)
665                  *       tan(th)           area = radius*radius*pi
666                  *       <----->
667                  *        \    |           (1 + tan(theta)^2)/cos(theta)
668                  *         \   |           (1 + tan(acos(cos(theta)))^2)/cos(theta)
669                  *       t  \th| 1         simplifies to
670                  *           \-|           1/(cos(theta)^3)
671                  *            \|           magic!
672                  *             P
673                  */
674
675                 float3 lightD = make_float3(klight->co[0], klight->co[1], klight->co[2]);
676                 float costheta = dot(-lightD, D);
677                 float cosangle = klight->distant.cosangle;
678
679                 if(costheta < cosangle)
680                         return false;
681
682                 ls->P = -D;
683                 ls->Ng = -D;
684                 ls->D = D;
685                 ls->t = FLT_MAX;
686
687                 /* compute pdf */
688                 float invarea = klight->distant.invarea;
689                 ls->pdf = invarea/(costheta*costheta*costheta);
690                 ls->eval_fac = ls->pdf;
691         }
692         else if(type == LIGHT_POINT || type == LIGHT_SPOT) {
693                 float3 lightP = make_float3(klight->co[0], klight->co[1], klight->co[2]);
694
695                 float radius = klight->spot.radius;
696
697                 /* sphere light */
698                 if(radius == 0.0f)
699                         return false;
700
701                 if(!ray_aligned_disk_intersect(P, D, t,
702                                                lightP, radius, &ls->P, &ls->t))
703                 {
704                         return false;
705                 }
706
707                 ls->Ng = -D;
708                 ls->D = D;
709
710                 float invarea = klight->spot.invarea;
711                 ls->eval_fac = (0.25f*M_1_PI_F)*invarea;
712                 ls->pdf = invarea;
713
714                 if(type == LIGHT_SPOT) {
715                         /* spot light attenuation */
716                         float3 dir = make_float3(klight->spot.dir[0],
717                                                  klight->spot.dir[1],
718                                                  klight->spot.dir[2]);
719                         ls->eval_fac *= spot_light_attenuation(dir,
720                                                                klight->spot.spot_angle,
721                                                                klight->spot.spot_smooth,
722                                                                ls);
723
724                         if(ls->eval_fac == 0.0f)
725                                 return false;
726                 }
727                 float2 uv = map_to_sphere(ls->Ng);
728                 ls->u = uv.x;
729                 ls->v = uv.y;
730
731                 /* compute pdf */
732                 if(ls->t != FLT_MAX)
733                         ls->pdf *= lamp_light_pdf(kg, ls->Ng, -ls->D, ls->t);
734         }
735         else if(type == LIGHT_AREA) {
736                 /* area light */
737                 float invarea = klight->area.invarea;
738                 if(invarea == 0.0f)
739                         return false;
740
741                 float3 axisu = make_float3(klight->area.axisu[0],
742                                            klight->area.axisu[1],
743                                            klight->area.axisu[2]);
744                 float3 axisv = make_float3(klight->area.axisv[0],
745                                            klight->area.axisv[1],
746                                            klight->area.axisv[2]);
747                 float3 Ng = make_float3(klight->area.dir[0],
748                                         klight->area.dir[1],
749                                         klight->area.dir[2]);
750
751                 /* one sided */
752                 if(dot(D, Ng) >= 0.0f)
753                         return false;
754
755                 float3 light_P = make_float3(klight->co[0], klight->co[1], klight->co[2]);
756
757                 if(!ray_quad_intersect(P, D, 0.0f, t, light_P,
758                                        axisu, axisv, Ng,
759                                        &ls->P, &ls->t,
760                                        &ls->u, &ls->v))
761                 {
762                         return false;
763                 }
764
765                 ls->D = D;
766                 ls->Ng = Ng;
767                 ls->pdf = area_light_sample(P, &light_P, axisu, axisv, 0, 0, false);
768                 ls->eval_fac = 0.25f*invarea;
769         }
770         else {
771                 return false;
772         }
773
774         ls->pdf *= kernel_data.integrator.pdf_lights;
775
776         return true;
777 }
778
779 /* Triangle Light */
780
781 /* returns true if the triangle is has motion blur or an instancing transform applied */
782 ccl_device_inline bool triangle_world_space_vertices(KernelGlobals *kg, int object, int prim, float time, float3 V[3])
783 {
784         bool has_motion = false;
785         const int object_flag = kernel_tex_fetch(__object_flag, object);
786
787         if(object_flag & SD_OBJECT_HAS_VERTEX_MOTION && time >= 0.0f) {
788                 motion_triangle_vertices(kg, object, prim, time, V);
789                 has_motion = true;
790         }
791         else {
792                 triangle_vertices(kg, prim, V);
793         }
794
795 #ifdef __INSTANCING__
796         if(!(object_flag & SD_OBJECT_TRANSFORM_APPLIED)) {
797 #  ifdef __OBJECT_MOTION__
798                 float object_time = (time >= 0.0f) ? time : 0.5f;
799                 Transform tfm = object_fetch_transform_motion_test(kg, object, object_time, NULL);
800 #  else
801                 Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
802 #  endif
803                 V[0] = transform_point(&tfm, V[0]);
804                 V[1] = transform_point(&tfm, V[1]);
805                 V[2] = transform_point(&tfm, V[2]);
806                 has_motion = true;
807         }
808 #endif
809         return has_motion;
810 }
811
812 ccl_device_inline float triangle_light_pdf_area(KernelGlobals *kg, const float3 Ng, const float3 I, float t)
813 {
814         float pdf = kernel_data.integrator.pdf_triangles;
815         float cos_pi = fabsf(dot(Ng, I));
816
817         if(cos_pi == 0.0f)
818                 return 0.0f;
819
820         return t*t*pdf/cos_pi;
821 }
822
823 ccl_device_forceinline float triangle_light_pdf(KernelGlobals *kg, ShaderData *sd, float t)
824 {
825         /* A naive heuristic to decide between costly solid angle sampling
826          * and simple area sampling, comparing the distance to the triangle plane
827          * to the length of the edges of the triangle. */
828
829         float3 V[3];
830         bool has_motion = triangle_world_space_vertices(kg, sd->object, sd->prim, sd->time, V);
831
832         const float3 e0 = V[1] - V[0];
833         const float3 e1 = V[2] - V[0];
834         const float3 e2 = V[2] - V[1];
835         const float longest_edge_squared = max(len_squared(e0), max(len_squared(e1), len_squared(e2)));
836         const float3 N = cross(e0, e1);
837         const float distance_to_plane = fabsf(dot(N, sd->I * t))/dot(N, N);
838
839         if(longest_edge_squared > distance_to_plane*distance_to_plane) {
840                 /* sd contains the point on the light source
841                  * calculate Px, the point that we're shading */
842                 const float3 Px = sd->P + sd->I * t;
843                 const float3 v0_p = V[0] - Px;
844                 const float3 v1_p = V[1] - Px;
845                 const float3 v2_p = V[2] - Px;
846
847                 const float3 u01 = safe_normalize(cross(v0_p, v1_p));
848                 const float3 u02 = safe_normalize(cross(v0_p, v2_p));
849                 const float3 u12 = safe_normalize(cross(v1_p, v2_p));
850
851                 const float alpha = fast_acosf(dot(u02, u01));
852                 const float beta = fast_acosf(-dot(u01, u12));
853                 const float gamma = fast_acosf(dot(u02, u12));
854                 const float solid_angle =  alpha + beta + gamma - M_PI_F;
855
856                 /* pdf_triangles is calculated over triangle area, but we're not sampling over its area */
857                 if(UNLIKELY(solid_angle == 0.0f)) {
858                         return 0.0f;
859                 }
860                 else {
861                         float area = 1.0f;
862                         if(has_motion) {
863                                 /* get the center frame vertices, this is what the PDF was calculated from */
864                                 triangle_world_space_vertices(kg, sd->object, sd->prim, -1.0f, V);
865                                 area = triangle_area(V[0], V[1], V[2]);
866                         }
867                         else {
868                                 area = 0.5f * len(N);
869                         }
870                         const float pdf = area * kernel_data.integrator.pdf_triangles;
871                         return pdf / solid_angle;
872                 }
873         }
874         else {
875                 float pdf = triangle_light_pdf_area(kg, sd->Ng, sd->I, t);
876                 if(has_motion) {
877                         const float     area = 0.5f * len(N);
878                         if(UNLIKELY(area == 0.0f)) {
879                                 return 0.0f;
880                         }
881                         /* scale the PDF.
882                          * area = the area the sample was taken from
883                          * area_pre = the are from which pdf_triangles was calculated from */
884                         triangle_world_space_vertices(kg, sd->object, sd->prim, -1.0f, V);
885                         const float area_pre = triangle_area(V[0], V[1], V[2]);
886                         pdf = pdf * area_pre / area;
887                 }
888                 return pdf;
889         }
890 }
891
892 ccl_device_forceinline void triangle_light_sample(KernelGlobals *kg, int prim, int object,
893         float randu, float randv, float time, LightSample *ls, const float3 P)
894 {
895         /* A naive heuristic to decide between costly solid angle sampling
896          * and simple area sampling, comparing the distance to the triangle plane
897          * to the length of the edges of the triangle. */
898
899         float3 V[3];
900         bool has_motion = triangle_world_space_vertices(kg, object, prim, time, V);
901
902         const float3 e0 = V[1] - V[0];
903         const float3 e1 = V[2] - V[0];
904         const float3 e2 = V[2] - V[1];
905         const float longest_edge_squared = max(len_squared(e0), max(len_squared(e1), len_squared(e2)));
906         const float3 N0 = cross(e0, e1);
907         float Nl = 0.0f;
908         ls->Ng = safe_normalize_len(N0, &Nl);
909         float area = 0.5f * Nl;
910
911         /* flip normal if necessary */
912         const int object_flag = kernel_tex_fetch(__object_flag, object);
913         if(object_flag & SD_OBJECT_NEGATIVE_SCALE_APPLIED) {
914                 ls->Ng = -ls->Ng;
915         }
916         ls->eval_fac = 1.0f;
917         ls->shader = kernel_tex_fetch(__tri_shader, prim);
918         ls->object = object;
919         ls->prim = prim;
920         ls->lamp = LAMP_NONE;
921         ls->shader |= SHADER_USE_MIS;
922         ls->type = LIGHT_TRIANGLE;
923
924         float distance_to_plane = fabsf(dot(N0, V[0] - P)/dot(N0, N0));
925
926         if(longest_edge_squared > distance_to_plane*distance_to_plane) {
927                 /* see James Arvo, "Stratified Sampling of Spherical Triangles"
928                  * http://www.graphics.cornell.edu/pubs/1995/Arv95c.pdf */
929
930                 /* project the triangle to the unit sphere
931                  * and calculate its edges and angles */
932                 const float3 v0_p = V[0] - P;
933                 const float3 v1_p = V[1] - P;
934                 const float3 v2_p = V[2] - P;
935
936                 const float3 u01 = safe_normalize(cross(v0_p, v1_p));
937                 const float3 u02 = safe_normalize(cross(v0_p, v2_p));
938                 const float3 u12 = safe_normalize(cross(v1_p, v2_p));
939
940                 const float3 A = safe_normalize(v0_p);
941                 const float3 B = safe_normalize(v1_p);
942                 const float3 C = safe_normalize(v2_p);
943
944                 const float cos_alpha = dot(u02, u01);
945                 const float cos_beta = -dot(u01, u12);
946                 const float cos_gamma = dot(u02, u12);
947
948                 /* calculate dihedral angles */
949                 const float alpha = fast_acosf(cos_alpha);
950                 const float beta = fast_acosf(cos_beta);
951                 const float gamma = fast_acosf(cos_gamma);
952                 /* the area of the unit spherical triangle = solid angle */
953                 const float solid_angle =  alpha + beta + gamma - M_PI_F;
954
955                 /* precompute a few things
956                  * these could be re-used to take several samples
957                  * as they are independent of randu/randv */
958                 const float cos_c = dot(A, B);
959                 const float sin_alpha = fast_sinf(alpha);
960                 const float product = sin_alpha * cos_c;
961
962                 /* Select a random sub-area of the spherical triangle
963                  * and calculate the third vertex C_ of that new triangle */
964                 const float phi = randu * solid_angle - alpha;
965                 float s, t;
966                 fast_sincosf(phi, &s, &t);
967                 const float u = t - cos_alpha;
968                 const float v = s + product;
969
970                 const float3 U = safe_normalize(C - dot(C, A) * A);
971
972                 float q = 1.0f;
973                 const float det = ((v * s + u * t) * sin_alpha);
974                 if(det != 0.0f) {
975                         q = ((v * t - u * s) * cos_alpha - v) / det;
976                 }
977                 const float temp = max(1.0f - q*q, 0.0f);
978
979                 const float3 C_ = safe_normalize(q * A + sqrtf(temp) * U);
980
981                 /* Finally, select a random point along the edge of the new triangle
982                  * That point on the spherical triangle is the sampled ray direction */
983                 const float z = 1.0f - randv * (1.0f - dot(C_, B));
984                 ls->D = z * B + safe_sqrtf(1.0f - z*z) * safe_normalize(C_ - dot(C_, B) * B);
985
986                 /* calculate intersection with the planar triangle */
987                 if(!ray_triangle_intersect(P, ls->D, FLT_MAX,
988 #if defined(__KERNEL_SSE2__) && defined(__KERNEL_SSE__)
989                                            (ssef*)V,
990 #else
991                                            V[0], V[1], V[2],
992 #endif
993                                            &ls->u, &ls->v, &ls->t)) {
994                         ls->pdf = 0.0f;
995                         return;
996                 }
997
998                 ls->P = P + ls->D * ls->t;
999
1000                 /* pdf_triangles is calculated over triangle area, but we're sampling over solid angle */
1001                 if(UNLIKELY(solid_angle == 0.0f)) {
1002                         ls->pdf = 0.0f;
1003                         return;
1004                 }
1005                 else {
1006                         if(has_motion) {
1007                                 /* get the center frame vertices, this is what the PDF was calculated from */
1008                                 triangle_world_space_vertices(kg, object, prim, -1.0f, V);
1009                                 area = triangle_area(V[0], V[1], V[2]);
1010                         }
1011                         const float pdf = area * kernel_data.integrator.pdf_triangles;
1012                         ls->pdf = pdf / solid_angle;
1013                 }
1014         }
1015         else {
1016                 /* compute random point in triangle */
1017                 randu = sqrtf(randu);
1018
1019                 const float u = 1.0f - randu;
1020                 const float v = randv*randu;
1021                 const float t = 1.0f - u - v;
1022                 ls->P = u * V[0] + v * V[1] + t * V[2];
1023                 /* compute incoming direction, distance and pdf */
1024                 ls->D = normalize_len(ls->P - P, &ls->t);
1025                 ls->pdf = triangle_light_pdf_area(kg, ls->Ng, -ls->D, ls->t);
1026                 if(has_motion && area != 0.0f) {
1027                         /* scale the PDF.
1028                          * area = the area the sample was taken from
1029                          * area_pre = the are from which pdf_triangles was calculated from */
1030                         triangle_world_space_vertices(kg, object, prim, -1.0f, V);
1031                         const float area_pre = triangle_area(V[0], V[1], V[2]);
1032                         ls->pdf = ls->pdf * area_pre / area;
1033                 }
1034                 ls->u = u;
1035                 ls->v = v;
1036         }
1037 }
1038
1039 /* Light Distribution */
1040
1041 ccl_device int light_distribution_sample(KernelGlobals *kg, float *randu)
1042 {
1043         /* This is basically std::upper_bound as used by pbrt, to find a point light or
1044          * triangle to emit from, proportional to area. a good improvement would be to
1045          * also sample proportional to power, though it's not so well defined with
1046          * arbitrary shaders. */
1047         int first = 0;
1048         int len = kernel_data.integrator.num_distribution + 1;
1049         float r = *randu;
1050
1051         while(len > 0) {
1052                 int half_len = len >> 1;
1053                 int middle = first + half_len;
1054
1055                 if(r < kernel_tex_fetch(__light_distribution, middle).totarea) {
1056                         len = half_len;
1057                 }
1058                 else {
1059                         first = middle + 1;
1060                         len = len - half_len - 1;
1061                 }
1062         }
1063
1064         /* Clamping should not be needed but float rounding errors seem to
1065          * make this fail on rare occasions. */
1066         int index = clamp(first-1, 0, kernel_data.integrator.num_distribution-1);
1067
1068         /* Rescale to reuse random number. this helps the 2D samples within
1069          * each area light be stratified as well. */
1070         float distr_min = kernel_tex_fetch(__light_distribution, index).totarea;
1071         float distr_max = kernel_tex_fetch(__light_distribution, index+1).totarea;
1072         *randu = (r - distr_min)/(distr_max - distr_min);
1073
1074         return index;
1075 }
1076
1077 /* Generic Light */
1078
1079 ccl_device bool light_select_reached_max_bounces(KernelGlobals *kg, int index, int bounce)
1080 {
1081         return (bounce > kernel_tex_fetch(__lights, index).max_bounces);
1082 }
1083
1084 ccl_device_noinline bool light_sample(KernelGlobals *kg,
1085                                       float randu,
1086                                       float randv,
1087                                       float time,
1088                                       float3 P,
1089                                       int bounce,
1090                                       LightSample *ls)
1091 {
1092         /* sample index */
1093         int index = light_distribution_sample(kg, &randu);
1094
1095         /* fetch light data */
1096         const ccl_global KernelLightDistribution *kdistribution = &kernel_tex_fetch(__light_distribution, index);
1097         int prim = kdistribution->prim;
1098
1099         if(prim >= 0) {
1100                 int object = kdistribution->mesh_light.object_id;
1101                 int shader_flag = kdistribution->mesh_light.shader_flag;
1102
1103                 triangle_light_sample(kg, prim, object, randu, randv, time, ls, P);
1104                 ls->shader |= shader_flag;
1105                 return (ls->pdf > 0.0f);
1106         }
1107         else {
1108                 int lamp = -prim-1;
1109
1110                 if(UNLIKELY(light_select_reached_max_bounces(kg, lamp, bounce))) {
1111                         return false;
1112                 }
1113
1114                 return lamp_light_sample(kg, lamp, randu, randv, P, ls);
1115         }
1116 }
1117
1118 ccl_device int light_select_num_samples(KernelGlobals *kg, int index)
1119 {
1120         return kernel_tex_fetch(__lights, index).samples;
1121 }
1122
1123 CCL_NAMESPACE_END