Debian Codegraph @

modules/lightmapper_rd/lm_compute.glsl

raw
1 #[versions]
2
3 primary = "#define MODE_DIRECT_LIGHT";
4 secondary = "#define MODE_BOUNCE_LIGHT";
5 dilate = "#define MODE_DILATE";
6 unocclude = "#define MODE_UNOCCLUDE";
7 light_probes = "#define MODE_LIGHT_PROBES";
8 denoise = "#define MODE_DENOISE";
9 pack_coeffs = "#define MODE_PACK_L1_COEFFS";
10
11 #[compute]
12
13 #version 450
14
15 #VERSION_DEFINES
16
17 #extension GL_EXT_samplerless_texture_functions : enable
18
19 // One 2D local group focusing in one layer at a time, though all
20 // in parallel (no barriers) makes more sense than a 3D local group
21 // as this can take more advantage of the cache for each group.
22
23 #ifdef MODE_LIGHT_PROBES
24
25 layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
26
27 #else
28
29 layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
30
31 #endif
32
33 #include "lm_common_inc.glsl"
34
35 #ifdef MODE_LIGHT_PROBES
36
37 layout(set = 1, binding = 0, std430) restrict buffer LightProbeData {
38 vec4 data[];
39 }
40 light_probes;
41
42 layout(set = 1, binding = 1) uniform texture2DArray source_light;
43 layout(set = 1, binding = 2) uniform texture2D environment;
44 #endif
45
46 #ifdef MODE_UNOCCLUDE
47
48 layout(rgba32f, set = 1, binding = 0) uniform restrict image2DArray position;
49 layout(rgba32f, set = 1, binding = 1) uniform restrict image2DArray unocclude;
50
51 #endif
52
53 #if defined(MODE_DIRECT_LIGHT) || defined(MODE_BOUNCE_LIGHT)
54
55 layout(rgba16f, set = 1, binding = 0) uniform restrict writeonly image2DArray dest_light;
56 layout(set = 1, binding = 1) uniform texture2DArray source_light;
57 layout(set = 1, binding = 2) uniform texture2DArray source_position;
58 layout(set = 1, binding = 3) uniform texture2DArray source_normal;
59 layout(rgba16f, set = 1, binding = 4) uniform restrict image2DArray accum_light;
60
61 #endif
62
63 #if defined(MODE_DIRECT_LIGHT) && defined(USE_SHADOWMASK)
64 layout(rgba8, set = 1, binding = 5) uniform restrict writeonly image2DArray shadowmask;
65 #elif defined(MODE_BOUNCE_LIGHT)
66 layout(set = 1, binding = 5) uniform texture2D environment;
67 #endif
68
69 #if defined(MODE_DILATE) || defined(MODE_DENOISE) || defined(MODE_PACK_L1_COEFFS)
70 layout(rgba16f, set = 1, binding = 0) uniform restrict writeonly image2DArray dest_light;
71 layout(set = 1, binding = 1) uniform texture2DArray source_light;
72 #endif
73
74 #ifdef MODE_DENOISE
75 layout(set = 1, binding = 2) uniform texture2DArray source_normal;
76 layout(set = 1, binding = 3) uniform texture2DArray unocclude_mask;
77 layout(set = 1, binding = 4) uniform DenoiseParams {
78 float spatial_bandwidth;
79 float light_bandwidth;
80 float albedo_bandwidth;
81 float normal_bandwidth;
82
83 int half_search_window;
84 float filter_strength;
85 uint slice_count;
86 }
87 denoise_params;
88 #endif
89
90 layout(push_constant, std430) uniform Params {
91 uint atlas_slice;
92 uint ray_count;
93 uint ray_from;
94 uint ray_to;
95
96 ivec2 region_ofs;
97 uint probe_count;
98 uint denoiser_range;
99 }
100 params;
101
102 //check it, but also return distance and barycentric coords (for uv lookup)
103 bool ray_hits_triangle(vec3 from, vec3 dir, float max_dist, vec3 p0, vec3 p1, vec3 p2, out float r_distance, out vec3 r_barycentric) {
104 const float EPSILON = 0.00001;
105 const vec3 e0 = p1 - p0;
106 const vec3 e1 = p0 - p2;
107 vec3 triangle_normal = cross(e1, e0);
108
109 float n_dot_dir = dot(triangle_normal, dir);
110
111 if (abs(n_dot_dir) < EPSILON) {
112 return false;
113 }
114
115 const vec3 e2 = (p0 - from) / n_dot_dir;
116 const vec3 i = cross(dir, e2);
117
118 r_barycentric.y = dot(i, e1);
119 r_barycentric.z = dot(i, e0);
120 r_barycentric.x = 1.0 - (r_barycentric.z + r_barycentric.y);
121 r_distance = dot(triangle_normal, e2);
122
123 return (r_distance > bake_params.bias) && (r_distance < max_dist) && all(greaterThanEqual(r_barycentric, vec3(0.0)));
124 }
125
126 const uint RAY_MISS = 0;
127 const uint RAY_FRONT = 1;
128 const uint RAY_BACK = 2;
129 const uint RAY_ANY = 3;
130
131 bool ray_box_test(vec3 p_from, vec3 p_inv_dir, vec3 p_box_min, vec3 p_box_max) {
132 vec3 t0 = (p_box_min - p_from) * p_inv_dir;
133 vec3 t1 = (p_box_max - p_from) * p_inv_dir;
134 vec3 tmin = min(t0, t1), tmax = max(t0, t1);
135 return max(tmin.x, max(tmin.y, tmin.z)) <= min(tmax.x, min(tmax.y, tmax.z));
136 }
137
138 #if CLUSTER_SIZE > 32
139 #define CLUSTER_TRIANGLE_ITERATION
140 #endif
141
142 uint trace_ray(vec3 p_from, vec3 p_to, bool p_any_hit, out float r_distance, out vec3 r_normal, out uint r_triangle, out vec3 r_barycentric) {
143 // World coordinates.
144 vec3 rel = p_to - p_from;
145 float rel_len = length(rel);
146 vec3 dir = normalize(rel);
147 vec3 inv_dir = 1.0 / dir;
148
149 // Cell coordinates.
150 vec3 from_cell = (p_from - bake_params.to_cell_offset) * bake_params.to_cell_size;
151 vec3 to_cell = (p_to - bake_params.to_cell_offset) * bake_params.to_cell_size;
152
153 // Prepare DDA.
154 vec3 rel_cell = to_cell - from_cell;
155 ivec3 icell = ivec3(from_cell);
156 ivec3 iendcell = ivec3(to_cell);
157 vec3 dir_cell = normalize(rel_cell);
158 vec3 delta = min(abs(1.0 / dir_cell), bake_params.grid_size); // Use bake_params.grid_size as max to prevent infinity values.
159 ivec3 step = ivec3(sign(rel_cell));
160 const vec3 init_next_cell = vec3(icell) + max(vec3(0), sign(step));
161 vec3 t_max = mix(vec3(0), (init_next_cell - from_cell) / dir_cell, notEqual(step, vec3(0))); // Distance to next boundary.
162
163 uint iters = 0;
164 while (all(greaterThanEqual(icell, ivec3(0))) && all(lessThan(icell, ivec3(bake_params.grid_size))) && (iters < 1000)) {
165 uvec2 cell_data = texelFetch(grid, icell, 0).xy;
166 uint triangle_count = cell_data.x;
167 if (triangle_count > 0) {
168 uint hit = RAY_MISS;
169 float best_distance = 1e20;
170 uint cluster_start = cluster_indices.data[cell_data.y * 2];
171 uint cell_triangle_start = cluster_indices.data[cell_data.y * 2 + 1];
172 uint cluster_count = (triangle_count + CLUSTER_SIZE - 1) / CLUSTER_SIZE;
173 uint cluster_base_index = 0;
174 while (cluster_base_index < cluster_count) {
175 // To minimize divergence, all Ray-AABB tests on the clusters contained in the cell are performed
176 // before checking against the triangles. We do this 32 clusters at a time and store the intersected
177 // clusters on each bit of the 32-bit integer.
178 uint cluster_test_count = min(32, cluster_count - cluster_base_index);
179 uint cluster_hits = 0;
180 for (uint i = 0; i < cluster_test_count; i++) {
181 uint cluster_index = cluster_start + cluster_base_index + i;
182 ClusterAABB cluster_aabb = cluster_aabbs.data[cluster_index];
183 if (ray_box_test(p_from, inv_dir, cluster_aabb.min_bounds, cluster_aabb.max_bounds)) {
184 cluster_hits |= (1 << i);
185 }
186 }
187
188 // Check the triangles in any of the clusters that were intersected by toggling off the bits in the
189 // 32-bit integer counter until no bits are left.
190 while (cluster_hits > 0) {
191 uint cluster_index = findLSB(cluster_hits);
192 cluster_hits &= ~(1 << cluster_index);
193 cluster_index += cluster_base_index;
194
195 // Do the same divergence execution trick with triangles as well.
196 uint triangle_base_index = 0;
197 #ifdef CLUSTER_TRIANGLE_ITERATION
198 while (triangle_base_index < triangle_count)
199 #endif
200 {
201 uint triangle_start_index = cell_triangle_start + cluster_index * CLUSTER_SIZE + triangle_base_index;
202 uint triangle_test_count = min(CLUSTER_SIZE, triangle_count - triangle_base_index);
203 uint triangle_hits = 0;
204 for (uint i = 0; i < triangle_test_count; i++) {
205 uint triangle_index = triangle_indices.data[triangle_start_index + i];
206 if (ray_box_test(p_from, inv_dir, triangles.data[triangle_index].min_bounds, triangles.data[triangle_index].max_bounds)) {
207 triangle_hits |= (1 << i);
208 }
209 }
210
211 while (triangle_hits > 0) {
212 uint cluster_triangle_index = findLSB(triangle_hits);
213 triangle_hits &= ~(1 << cluster_triangle_index);
214 cluster_triangle_index += triangle_start_index;
215
216 uint triangle_index = triangle_indices.data[cluster_triangle_index];
217 Triangle triangle = triangles.data[triangle_index];
218
219 // Gather the triangle vertex positions.
220 vec3 vtx0 = vertices.data[triangle.indices.x].position;
221 vec3 vtx1 = vertices.data[triangle.indices.y].position;
222 vec3 vtx2 = vertices.data[triangle.indices.z].position;
223 vec3 normal = -normalize(cross((vtx0 - vtx1), (vtx0 - vtx2)));
224 bool backface = dot(normal, dir) >= 0.0;
225 float distance;
226 vec3 barycentric;
227 if (ray_hits_triangle(p_from, dir, rel_len, vtx0, vtx1, vtx2, distance, barycentric)) {
228 if (p_any_hit) {
229 // Return early if any hit was requested.
230 return RAY_ANY;
231 }
232 vec3 position = p_from + dir * distance;
233 vec3 hit_cell = (position - bake_params.to_cell_offset) * bake_params.to_cell_size;
234 if (icell != ivec3(hit_cell)) {
235 // It's possible for the ray to hit a triangle in a position outside the bounds of the cell
236 // if it's large enough to cover multiple ones. The hit must be ignored if this is the case.
237 continue;
238 }
239
240 if (!backface) {
241 // The case of meshes having both a front and back face in the same plane is more common than
242 // expected, so if this is a front-face, bias it closer to the ray origin, so it always wins
243 // over the back-face.
244 distance = max(bake_params.bias, distance - bake_params.bias);
245 }
246
247 if (distance < best_distance) {
248 switch (triangle.cull_mode) {
249 case CULL_DISABLED:
250 backface = false;
251 break;
252 case CULL_FRONT:
253 backface = !backface;
254 break;
255 case CULL_BACK: // Default behavior.
256 break;
257 }
258
259 hit = backface ? RAY_BACK : RAY_FRONT;
260 best_distance = distance;
261 r_distance = distance;
262 r_normal = normal;
263 r_triangle = triangle_index;
264 r_barycentric = barycentric;
265 }
266 }
267 }
268
269 #ifdef CLUSTER_TRIANGLE_ITERATION
270 triangle_base_index += CLUSTER_SIZE;
271 #endif
272 }
273 }
274
275 cluster_base_index += 32;
276 }
277
278 if (hit != RAY_MISS) {
279 return hit;
280 }
281 }
282
283 if (icell == iendcell) {
284 break;
285 }
286
287 // There should be only one axis updated at a time for DDA to work properly.
288 if (t_max.x < t_max.y && t_max.x < t_max.z) {
289 icell.x += step.x;
290 t_max.x += delta.x;
291 } else if (t_max.y < t_max.z) {
292 icell.y += step.y;
293 t_max.y += delta.y;
294 } else {
295 icell.z += step.z;
296 t_max.z += delta.z;
297 }
298 iters++;
299 }
300
301 return RAY_MISS;
302 }
303
304 uint trace_ray_closest_hit_triangle(vec3 p_from, vec3 p_to, out uint r_triangle, out vec3 r_barycentric) {
305 float distance;
306 vec3 normal;
307 return trace_ray(p_from, p_to, false, distance, normal, r_triangle, r_barycentric);
308 }
309
310 uint trace_ray_closest_hit_triangle_albedo_alpha(vec3 p_from, vec3 p_to, out vec4 albedo_alpha, out vec3 hit_position) {
311 float distance;
312 vec3 normal;
313 uint tidx;
314 vec3 barycentric;
315
316 uint ret = trace_ray(p_from, p_to, false, distance, normal, tidx, barycentric);
317 if (ret != RAY_MISS) {
318 Vertex vert0 = vertices.data[triangles.data[tidx].indices.x];
319 Vertex vert1 = vertices.data[triangles.data[tidx].indices.y];
320 Vertex vert2 = vertices.data[triangles.data[tidx].indices.z];
321
322 vec3 uvw = vec3(barycentric.x * vert0.uv + barycentric.y * vert1.uv + barycentric.z * vert2.uv, float(triangles.data[tidx].slice));
323
324 albedo_alpha = textureLod(sampler2DArray(albedo_tex, linear_sampler), uvw, 0);
325 hit_position = barycentric.x * vert0.position + barycentric.y * vert1.position + barycentric.z * vert2.position;
326 }
327
328 return ret;
329 }
330
331 uint trace_ray_closest_hit_distance(vec3 p_from, vec3 p_to, out float r_distance, out vec3 r_normal) {
332 uint triangle;
333 vec3 barycentric;
334 return trace_ray(p_from, p_to, false, r_distance, r_normal, triangle, barycentric);
335 }
336
337 uint trace_ray_any_hit(vec3 p_from, vec3 p_to) {
338 float distance;
339 vec3 normal;
340 uint triangle;
341 vec3 barycentric;
342 return trace_ray(p_from, p_to, true, distance, normal, triangle, barycentric);
343 }
344
345 // https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/
346 uint hash(uint value) {
347 uint state = value * 747796405u + 2891336453u;
348 uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
349 return (word >> 22u) ^ word;
350 }
351
352 uint random_seed(ivec3 seed) {
353 return hash(seed.x ^ hash(seed.y ^ hash(seed.z)));
354 }
355
356 // generates a random value in range [0.0, 1.0)
357 float randomize(inout uint value) {
358 value = hash(value);
359 return float(value / 4294967296.0);
360 }
361
362 const float PI = 3.14159265f;
363
364 // http://www.realtimerendering.com/raytracinggems/unofficial_RayTracingGems_v1.4.pdf (chapter 15)
365 vec3 generate_hemisphere_cosine_weighted_direction(inout uint noise) {
366 float noise1 = randomize(noise);
367 float noise2 = randomize(noise) * 2.0 * PI;
368
369 return vec3(sqrt(noise1) * cos(noise2), sqrt(noise1) * sin(noise2), sqrt(1.0 - noise1));
370 }
371
372 // Distribution generation adapted from "Generating uniformly distributed numbers on a sphere"
373 // <http://corysimon.github.io/articles/uniformdistn-on-sphere/>
374 vec3 generate_sphere_uniform_direction(inout uint noise) {
375 float theta = 2.0 * PI * randomize(noise);
376 float phi = acos(1.0 - 2.0 * randomize(noise));
377 return vec3(sin(phi) * cos(theta), sin(phi) * sin(theta), cos(phi));
378 }
379
380 vec3 generate_ray_dir_from_normal(vec3 normal, inout uint noise) {
381 vec3 v0 = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
382 vec3 tangent = normalize(cross(v0, normal));
383 vec3 bitangent = normalize(cross(tangent, normal));
384 mat3 normal_mat = mat3(tangent, bitangent, normal);
385 return normal_mat * generate_hemisphere_cosine_weighted_direction(noise);
386 }
387
388 #if defined(MODE_DIRECT_LIGHT) || defined(MODE_BOUNCE_LIGHT) || defined(MODE_LIGHT_PROBES)
389
390 float get_omni_attenuation(float distance, float inv_range, float decay) {
391 float nd = distance * inv_range;
392 nd *= nd;
393 nd *= nd; // nd^4
394 nd = max(1.0 - nd, 0.0);
395 nd *= nd; // nd^2
396 return nd * pow(max(distance, 0.0001), -decay);
397 }
398
399 const int AA_SAMPLES = 16;
400
401 const vec2 halton_map[AA_SAMPLES] = vec2[](
402 vec2(0.5, 0.33333333),
403 vec2(0.25, 0.66666667),
404 vec2(0.75, 0.11111111),
405 vec2(0.125, 0.44444444),
406 vec2(0.625, 0.77777778),
407 vec2(0.375, 0.22222222),
408 vec2(0.875, 0.55555556),
409 vec2(0.0625, 0.88888889),
410 vec2(0.5625, 0.03703704),
411 vec2(0.3125, 0.37037037),
412 vec2(0.8125, 0.7037037),
413 vec2(0.1875, 0.14814815),
414 vec2(0.6875, 0.48148148),
415 vec2(0.4375, 0.81481481),
416 vec2(0.9375, 0.25925926),
417 vec2(0.03125, 0.59259259));
418
419 vec2 get_vogel_disk(float p_i, float p_rotation, float p_sample_count_sqrt) {
420 const float golden_angle = 2.4;
421
422 float r = sqrt(p_i + 0.5) / p_sample_count_sqrt;
423 float theta = p_i * golden_angle + p_rotation;
424
425 return vec2(cos(theta), sin(theta)) * r;
426 }
427
428 void trace_direct_light(vec3 p_position, vec3 p_normal, uint p_light_index, bool p_soft_shadowing, out vec3 r_light, out vec3 r_light_dir, inout uint r_noise, float p_texel_size, out float r_shadow) {
429 const float EPSILON = 0.00001;
430
431 r_light = vec3(0.0f);
432 r_shadow = 0.0f;
433
434 vec3 light_pos;
435 float dist;
436 float attenuation;
437 float soft_shadowing_disk_size;
438 Light light_data = lights.data[p_light_index];
439 if (light_data.type == LIGHT_TYPE_DIRECTIONAL) {
440 vec3 light_vec = light_data.direction;
441 light_pos = p_position - light_vec * length(bake_params.world_size);
442 r_light_dir = normalize(light_pos - p_position);
443 dist = length(bake_params.world_size);
444 attenuation = 1.0;
445 soft_shadowing_disk_size = light_data.size;
446 } else {
447 light_pos = light_data.position;
448 r_light_dir = normalize(light_pos - p_position);
449 dist = distance(p_position, light_pos);
450 if (dist > light_data.range) {
451 return;
452 }
453
454 soft_shadowing_disk_size = light_data.size / dist;
455
456 attenuation = get_omni_attenuation(dist, 1.0 / light_data.range, light_data.attenuation);
457
458 if (light_data.type == LIGHT_TYPE_SPOT) {
459 vec3 rel = normalize(p_position - light_pos);
460 float cos_spot_angle = light_data.cos_spot_angle;
461 float cos_angle = dot(rel, light_data.direction);
462
463 if (cos_angle < cos_spot_angle) {
464 return;
465 }
466
467 float scos = max(cos_angle, cos_spot_angle);
468 float spot_rim = max(0.0001, (1.0 - scos) / (1.0 - cos_spot_angle));
469 attenuation *= 1.0 - pow(spot_rim, light_data.inv_spot_attenuation);
470 }
471 }
472
473 attenuation *= max(0.0, dot(p_normal, r_light_dir));
474 if (attenuation <= 0.0001) {
475 return;
476 }
477
478 float penumbra = 0.0;
479 vec3 penumbra_color = vec3(0.0);
480 if (p_soft_shadowing) {
481 const bool use_soft_shadows = (light_data.size > 0.0);
482 const uint ray_count = AA_SAMPLES;
483 const uint total_ray_count = use_soft_shadows ? params.ray_count : ray_count;
484 const uint shadowing_rays_check_penumbra_denom = 2;
485 const uint shadowing_ray_count = max(1, params.ray_count / ray_count);
486 const float shadowing_ray_count_sqrt = sqrt(float(total_ray_count));
487
488 // Setup tangent pass to calculate AA samples over the current texel.
489 vec3 aux = p_normal.y < 0.777 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
490 vec3 tangent = normalize(cross(p_normal, aux));
491 vec3 bitan = normalize(cross(p_normal, tangent));
492
493 // Setup light tangent pass to calculate samples over disk aligned towards the light
494 vec3 light_to_point = -r_light_dir;
495 vec3 light_aux = light_to_point.y < 0.777 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
496 vec3 light_to_point_tan = normalize(cross(light_to_point, light_aux));
497 vec3 light_to_point_bitan = normalize(cross(light_to_point, light_to_point_tan));
498
499 float aa_power = 0.0;
500 for (uint i = 0; i < ray_count; i++) {
501 // Create a random sample within the texel.
502 vec2 disk_sample = (halton_map[i] - vec2(0.5)) * p_texel_size * light_data.shadow_blur;
503 // Align the sample to world space.
504 vec3 disk_aligned = (disk_sample.x * tangent + disk_sample.y * bitan);
505 vec3 origin = p_position - disk_aligned;
506 vec3 light_dir = normalize(light_pos - origin);
507
508 float power = 0.0;
509 vec3 light_color = vec3(0.0);
510 uint power_accm = 0;
511 vec3 prev_pos = origin;
512 if (use_soft_shadows) {
513 uint soft_shadow_hits = 0;
514 for (uint j = 0; j < shadowing_ray_count; j++) {
515 origin = prev_pos;
516 // Optimization:
517 // Once already traced an important proportion of rays, if all are hits or misses,
518 // assume we're not in the penumbra so we can infer the rest would have the same result.
519 if (j == shadowing_ray_count / shadowing_rays_check_penumbra_denom) {
520 if (soft_shadow_hits == j) {
521 // Assume totally lit
522 soft_shadow_hits = shadowing_ray_count;
523 break;
524 } else if (soft_shadow_hits == 0) {
525 // Assume totally dark
526 soft_shadow_hits = 0;
527 break;
528 }
529 }
530
531 float a = randomize(r_noise) * 2.0 * PI;
532 float vogel_index = float(total_ray_count - 1 - (i * shadowing_ray_count + j)); // Start from (total_ray_count - 1) so we check the outer points first.
533 vec2 light_disk_sample = get_vogel_disk(vogel_index, a, shadowing_ray_count_sqrt) * soft_shadowing_disk_size * light_data.shadow_blur;
534 vec3 light_disk_to_point = normalize(light_to_point + light_disk_sample.x * light_to_point_tan + light_disk_sample.y * light_to_point_bitan);
535 float sample_penumbra = 0.0;
536 vec3 sample_penumbra_color = light_data.color.rgb;
537 bool sample_did_hit = false;
538
539 for (uint iter = 0; iter < bake_params.transparency_rays; iter++) {
540 vec4 hit_albedo = vec4(1.0);
541 vec3 hit_position;
542 // Offset the ray origin for AA, offset the light position for soft shadows.
543 uint ret = trace_ray_closest_hit_triangle_albedo_alpha(origin - light_disk_to_point * (bake_params.bias + length(disk_sample)), p_position - light_disk_to_point * dist, hit_albedo, hit_position);
544 if (ret == RAY_MISS) {
545 if (!sample_did_hit) {
546 sample_penumbra = 1.0;
547 }
548 soft_shadow_hits += 1;
549 break;
550 } else if (ret == RAY_FRONT || ret == RAY_BACK) {
551 bool contribute = ret == RAY_FRONT || !sample_did_hit;
552 if (!sample_did_hit) {
553 sample_penumbra = 1.0;
554 sample_did_hit = true;
555 }
556
557 soft_shadow_hits += 1;
558
559 if (contribute) {
560 sample_penumbra_color = mix(sample_penumbra_color, sample_penumbra_color * hit_albedo.rgb, hit_albedo.a);
561 sample_penumbra *= 1.0 - hit_albedo.a;
562 }
563 origin = hit_position + r_light_dir * bake_params.bias;
564
565 if (sample_penumbra - EPSILON <= 0) {
566 break;
567 }
568 }
569 }
570
571 power += sample_penumbra;
572 light_color += sample_penumbra_color;
573 power_accm++;
574 }
575
576 } else { // No soft shadows (size == 0).
577 float sample_penumbra = 0.0;
578 vec3 sample_penumbra_color = light_data.color.rgb;
579 bool sample_did_hit = false;
580 for (uint iter = 0; iter < bake_params.transparency_rays; iter++) {
581 vec4 hit_albedo = vec4(1.0);
582 vec3 hit_position;
583 // Offset the ray origin for AA, offset the light position for soft shadows.
584 uint ret = trace_ray_closest_hit_triangle_albedo_alpha(origin + light_dir * (bake_params.bias + length(disk_sample)), light_pos, hit_albedo, hit_position);
585 if (ret == RAY_MISS) {
586 if (!sample_did_hit) {
587 sample_penumbra = 1.0;
588 }
589 break;
590 } else if (ret == RAY_FRONT || ret == RAY_BACK) {
591 bool contribute = ret == RAY_FRONT || !sample_did_hit;
592 if (!sample_did_hit) {
593 sample_penumbra = 1.0;
594 sample_did_hit = true;
595 }
596
597 if (contribute) {
598 sample_penumbra_color = mix(sample_penumbra_color, sample_penumbra_color * hit_albedo.rgb, hit_albedo.a);
599 sample_penumbra *= 1.0 - hit_albedo.a;
600 }
601 origin = hit_position + r_light_dir * bake_params.bias;
602
603 if (sample_penumbra - EPSILON <= 0) {
604 break;
605 }
606 }
607 }
608 power = sample_penumbra;
609 light_color = sample_penumbra_color;
610 power_accm = 1;
611 }
612 aa_power += power / float(power_accm);
613 penumbra_color += light_color / float(power_accm);
614 }
615 penumbra = aa_power / ray_count;
616 penumbra_color /= ray_count;
617 } else { // No soft shadows and anti-aliasing (disabled via parameter).
618 bool did_hit = false;
619 penumbra = 0.0;
620 penumbra_color = light_data.color.rgb;
621 for (uint iter = 0; iter < bake_params.transparency_rays; iter++) {
622 vec4 hit_albedo = vec4(1.0);
623 vec3 hit_position;
624 uint ret = trace_ray_closest_hit_triangle_albedo_alpha(p_position + r_light_dir * bake_params.bias, light_pos, hit_albedo, hit_position);
625 if (ret == RAY_MISS) {
626 if (!did_hit) {
627 penumbra = 1.0;
628 }
629 break;
630 } else if (ret == RAY_FRONT || ret == RAY_BACK) {
631 bool contribute = (ret == RAY_FRONT || !did_hit);
632 if (!did_hit) {
633 penumbra = 1.0;
634 did_hit = true;
635 }
636
637 if (contribute) {
638 penumbra_color = mix(penumbra_color, penumbra_color * hit_albedo.rgb, hit_albedo.a);
639 penumbra *= 1.0 - hit_albedo.a;
640 }
641
642 p_position = hit_position + r_light_dir * bake_params.bias;
643
644 if (penumbra - EPSILON <= 0) {
645 break;
646 }
647 }
648 }
649
650 penumbra = clamp(penumbra, 0.0, 1.0);
651 }
652
653 r_shadow = penumbra;
654 r_light = light_data.energy * attenuation * penumbra * penumbra_color;
655 }
656
657 #endif
658
659 #if defined(MODE_BOUNCE_LIGHT) || defined(MODE_LIGHT_PROBES)
660
661 vec3 trace_environment_color(vec3 ray_dir) {
662 vec3 sky_dir = normalize(mat3(bake_params.env_transform) * ray_dir);
663 vec2 st = vec2(atan(sky_dir.x, sky_dir.z), acos(sky_dir.y));
664 if (st.x < 0.0) {
665 st.x += PI * 2.0;
666 }
667
668 return textureLod(sampler2D(environment, linear_sampler), st / vec2(PI * 2.0, PI), 0.0).rgb;
669 }
670
671 vec3 trace_indirect_light(vec3 p_position, vec3 p_ray_dir, inout uint r_noise, float p_texel_size) {
672 // The lower limit considers the case where the lightmapper might have bounces disabled but light probes are requested.
673 vec3 position = p_position;
674 vec3 ray_dir = p_ray_dir;
675 uint max_depth = max(bake_params.bounces, 1);
676 uint transparency_rays_left = bake_params.transparency_rays;
677 vec3 throughput = vec3(1.0);
678 vec3 light = vec3(0.0);
679 for (uint depth = 0; depth < max_depth; depth++) {
680 uint tidx;
681 vec3 barycentric;
682 uint trace_result = trace_ray_closest_hit_triangle(position + ray_dir * bake_params.bias, position + ray_dir * length(bake_params.world_size), tidx, barycentric);
683 if (trace_result == RAY_FRONT) {
684 Vertex vert0 = vertices.data[triangles.data[tidx].indices.x];
685 Vertex vert1 = vertices.data[triangles.data[tidx].indices.y];
686 Vertex vert2 = vertices.data[triangles.data[tidx].indices.z];
687 vec3 uvw = vec3(barycentric.x * vert0.uv + barycentric.y * vert1.uv + barycentric.z * vert2.uv, float(triangles.data[tidx].slice));
688 position = barycentric.x * vert0.position + barycentric.y * vert1.position + barycentric.z * vert2.position;
689
690 vec3 prev_normal = ray_dir;
691
692 vec3 norm0 = vec3(vert0.normal_xy, vert0.normal_z);
693 vec3 norm1 = vec3(vert1.normal_xy, vert1.normal_z);
694 vec3 norm2 = vec3(vert2.normal_xy, vert2.normal_z);
695 vec3 normal = barycentric.x * norm0 + barycentric.y * norm1 + barycentric.z * norm2;
696
697 vec3 direct_light = vec3(0.0f);
698 #ifdef USE_LIGHT_TEXTURE_FOR_BOUNCES
699 direct_light += textureLod(sampler2DArray(source_light, linear_sampler), uvw, 0.0).rgb;
700 #else
701 // Trace the lights directly. Significantly more expensive but more accurate in scenarios
702 // where the lightmap texture isn't reliable.
703 for (uint i = 0; i < bake_params.light_count; i++) {
704 vec3 light;
705 vec3 light_dir;
706 float shadow;
707 trace_direct_light(position, normal, i, false, light, light_dir, r_noise, p_texel_size, shadow);
708 direct_light += light * lights.data[i].indirect_energy;
709 }
710
711 direct_light *= bake_params.exposure_normalization;
712 #endif
713
714 vec4 albedo_alpha = textureLod(sampler2DArray(albedo_tex, linear_sampler), uvw, 0).rgba;
715 vec3 emissive = textureLod(sampler2DArray(emission_tex, linear_sampler), uvw, 0).rgb;
716 emissive *= bake_params.exposure_normalization;
717
718 light += throughput * emissive * albedo_alpha.a;
719 throughput = mix(throughput, throughput * albedo_alpha.rgb, albedo_alpha.a);
720 light += throughput * direct_light * bake_params.bounce_indirect_energy * albedo_alpha.a;
721
722 if (albedo_alpha.a < 1.0) {
723 transparency_rays_left -= 1;
724 depth -= 1;
725 if (transparency_rays_left <= 0) {
726 break;
727 }
728
729 // Either bounce off the transparent surface or keep going forward.
730 float pa = albedo_alpha.a * albedo_alpha.a;
731 if (randomize(r_noise) > pa) {
732 normal = prev_normal;
733 }
734
735 position += normal * bake_params.bias;
736 }
737
738 // Use Russian Roulette to determine a probability to terminate the bounce earlier as an optimization.
739 // <https://computergraphics.stackexchange.com/questions/2316/is-russian-roulette-really-the-answer>
740 float p = max(max(throughput.x, throughput.y), throughput.z);
741 if (randomize(r_noise) > p) {
742 break;
743 }
744
745 // Boost the throughput from the probability of the ray being terminated early.
746 throughput *= 1.0 / p;
747
748 // Generate a new ray direction for the next bounce from this surface's normal.
749 ray_dir = generate_ray_dir_from_normal(normal, r_noise);
750 } else if (trace_result == RAY_MISS) {
751 // Look for the environment color and stop bouncing.
752 light += throughput * trace_environment_color(ray_dir);
753 break;
754 } else if (trace_result == RAY_BACK) {
755 Vertex vert0 = vertices.data[triangles.data[tidx].indices.x];
756 Vertex vert1 = vertices.data[triangles.data[tidx].indices.y];
757 Vertex vert2 = vertices.data[triangles.data[tidx].indices.z];
758 vec3 uvw = vec3(barycentric.x * vert0.uv + barycentric.y * vert1.uv + barycentric.z * vert2.uv, float(triangles.data[tidx].slice));
759 position = barycentric.x * vert0.position + barycentric.y * vert1.position + barycentric.z * vert2.position;
760
761 vec4 albedo_alpha = textureLod(sampler2DArray(albedo_tex, linear_sampler), uvw, 0).rgba;
762
763 if (albedo_alpha.a > 1.0) {
764 break;
765 }
766
767 transparency_rays_left -= 1;
768 depth -= 1;
769 if (transparency_rays_left <= 0) {
770 break;
771 }
772
773 vec3 norm0 = vec3(vert0.normal_xy, vert0.normal_z);
774 vec3 norm1 = vec3(vert1.normal_xy, vert1.normal_z);
775 vec3 norm2 = vec3(vert2.normal_xy, vert2.normal_z);
776 vec3 normal = barycentric.x * norm0 + barycentric.y * norm1 + barycentric.z * norm2;
777
778 vec3 direct_light = vec3(0.0f);
779 #ifdef USE_LIGHT_TEXTURE_FOR_BOUNCES
780 direct_light += textureLod(sampler2DArray(source_light, linear_sampler), uvw, 0.0).rgb;
781 #else
782 // Trace the lights directly. Significantly more expensive but more accurate in scenarios
783 // where the lightmap texture isn't reliable.
784 for (uint i = 0; i < bake_params.light_count; i++) {
785 vec3 light;
786 vec3 light_dir;
787 float shadow;
788 trace_direct_light(position, normal, i, false, light, light_dir, r_noise, p_texel_size, shadow);
789 direct_light += light * lights.data[i].indirect_energy;
790 }
791
792 direct_light *= bake_params.exposure_normalization;
793 #endif
794
795 vec3 emissive = textureLod(sampler2DArray(emission_tex, linear_sampler), uvw, 0).rgb;
796 emissive *= bake_params.exposure_normalization;
797
798 light += throughput * emissive * albedo_alpha.a;
799 throughput = mix(mix(throughput, throughput * albedo_alpha.rgb, albedo_alpha.a), vec3(0.0), albedo_alpha.a);
800 light += throughput * direct_light * bake_params.bounce_indirect_energy * albedo_alpha.a;
801
802 position += ray_dir * bake_params.bias;
803 }
804 }
805
806 return light;
807 }
808
809 #endif
810
811 void main() {
812 // Check if invocation is out of bounds.
813 #ifdef MODE_LIGHT_PROBES
814 int probe_index = int(gl_GlobalInvocationID.x);
815 if (probe_index >= params.probe_count) {
816 return;
817 }
818
819 #else
820 ivec2 atlas_pos = ivec2(gl_GlobalInvocationID.xy) + params.region_ofs;
821 if (any(greaterThanEqual(atlas_pos, bake_params.atlas_size))) {
822 return;
823 }
824 #endif
825
826 #ifdef MODE_DIRECT_LIGHT
827 vec3 normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
828 if (length(normal) < 0.5) {
829 return; //empty texel, no process
830 }
831 vec3 position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
832 vec4 neighbor_position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos + ivec2(1, 0), params.atlas_slice), 0).xyzw;
833
834 if (neighbor_position.w < 0.001) {
835 // Empty texel, try again.
836 neighbor_position.xyz = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos + ivec2(-1, 0), params.atlas_slice), 0).xyz;
837 }
838 float texel_size_world_space = distance(position, neighbor_position.xyz) * bake_params.supersampling_factor;
839
840 vec3 light_for_texture = vec3(0.0);
841 vec3 light_for_bounces = vec3(0.0);
842
843 #ifdef USE_SHADOWMASK
844 float shadowmask_value = 0.0f;
845 #endif
846
847 #ifdef USE_SH_LIGHTMAPS
848 vec4 sh_accum[4] = vec4[](
849 vec4(0.0, 0.0, 0.0, 1.0),
850 vec4(0.0, 0.0, 0.0, 1.0),
851 vec4(0.0, 0.0, 0.0, 1.0),
852 vec4(0.0, 0.0, 0.0, 1.0));
853 #endif
854
855 // Use atlas position and a prime number as the seed.
856 uint noise = random_seed(ivec3(atlas_pos, 43573547));
857 for (uint i = 0; i < bake_params.light_count; i++) {
858 vec3 light;
859 vec3 light_dir;
860 float shadow;
861 trace_direct_light(position, normal, i, true, light, light_dir, noise, texel_size_world_space, shadow);
862
863 if (lights.data[i].static_bake) {
864 light_for_texture += light;
865
866 #ifdef USE_SH_LIGHTMAPS
867 // For L0, light needs to be attenuated by dot(normal, light_dir) else it is oversaturated when sampled later.
868 // For L1, light can't be attenuated by dot(normal, light_dir) since when sampling later, the dot product is done.
869 // The output of trace_direct_light() is already attenuated by dot(normal, light_dir).
870 // So L0 and L1 has the following relationship: L1 = L0 / dot(normal, light_dir).
871
872 // For L1 packing to work, there needs to be a defined ratio (4) between L0 and L1 values.
873 // This ratio is achieved with two coefficients c_l0 and c_l1, and ensuring that
874 // 4 = (c_l0 * LO) / (c_l1 * L1)
875
876 // For direct lights to look right, its effective "energy" needs to be 1 since it is not being integrated
877 // unlike indirect lighting.
878 // This binds c_l0 and c_l1 to the following relationship: 1 = c_l0 + c_l1
879
880 float attenuation = dot(normal, light_dir);
881
882 if (attenuation <= 0.0001) {
883 continue;
884 }
885
886 float c_l0 = 1 / (1 + 4 * attenuation);
887 float c_l1 = 1 - c_l0;
888 float c[4] = float[](
889 c_l0, //l0
890 c_l1 / attenuation * light_dir.y, //l1n1
891 c_l1 / attenuation * light_dir.z, //l1n0
892 c_l1 / attenuation * light_dir.x //l1p1
893 );
894
895 for (uint j = 0; j < 4; j++) {
896 sh_accum[j].rgb += light * c[j] * bake_params.exposure_normalization;
897 }
898 #endif
899 }
900
901 light_for_bounces += light * lights.data[i].indirect_energy;
902
903 #ifdef USE_SHADOWMASK
904 if (lights.data[i].type == LIGHT_TYPE_DIRECTIONAL && i == bake_params.shadowmask_light_idx) {
905 shadowmask_value = max(shadowmask_value, shadow);
906 }
907 #endif
908 }
909
910 light_for_bounces *= bake_params.exposure_normalization;
911 imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice), vec4(light_for_bounces, 1.0));
912
913 #ifdef USE_SH_LIGHTMAPS
914 // Keep for adding at the end.
915 imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 0), sh_accum[0]);
916 imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 1), sh_accum[1]);
917 imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 2), sh_accum[2]);
918 imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 3), sh_accum[3]);
919 #else
920 light_for_texture *= bake_params.exposure_normalization;
921 imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice), vec4(light_for_texture, 1.0));
922 #endif
923
924 #ifdef USE_SHADOWMASK
925 imageStore(shadowmask, ivec3(atlas_pos, params.atlas_slice), vec4(shadowmask_value, shadowmask_value, shadowmask_value, 1.0));
926 #endif
927
928 #endif
929
930 #ifdef MODE_BOUNCE_LIGHT
931
932 #ifdef USE_SH_LIGHTMAPS
933 vec4 sh_accum[4] = vec4[](
934 vec4(0.0, 0.0, 0.0, 1.0),
935 vec4(0.0, 0.0, 0.0, 1.0),
936 vec4(0.0, 0.0, 0.0, 1.0),
937 vec4(0.0, 0.0, 0.0, 1.0));
938 #else
939 vec3 light_accum = vec3(0.0);
940 #endif
941
942 // Retrieve starting normal and position.
943 vec3 normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
944 if (length(normal) < 0.5) {
945 // The pixel is empty, skip processing it.
946 return;
947 }
948
949 vec3 position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
950 int neighbor_offset = atlas_pos.x < bake_params.atlas_size.x - 1 ? 1 : -1;
951 vec3 neighbor_position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos + ivec2(neighbor_offset, 0), params.atlas_slice), 0).xyz;
952 float texel_size_world_space = distance(position, neighbor_position);
953 uint noise = random_seed(ivec3(params.ray_from, atlas_pos));
954 for (uint i = params.ray_from; i < params.ray_to; i++) {
955 vec3 ray_dir = generate_ray_dir_from_normal(normal, noise);
956 vec3 light = trace_indirect_light(position, ray_dir, noise, texel_size_world_space);
957
958 #ifdef USE_SH_LIGHTMAPS
959 // These coefficients include the factored out SH evaluation, diffuse convolution, and final application, as well as the BRDF 1/PI and the spherical monte carlo factor.
960 // LO: 1/(2*sqrtPI) * 1/(2*sqrtPI) * PI * PI * 1/PI = 0.25
961 // L1: sqrt(3/(4*pi)) * sqrt(3/(4*pi)) * (PI*2/3) * (2 * PI) * 1/PI = 1.0
962 // Note: This only works because we aren't scaling, rotating, or combing harmonics, we are just directing applying them in the shader.
963
964 float c[4] = float[](
965 0.25, //l0
966 ray_dir.y, //l1n1
967 ray_dir.z, //l1n0
968 ray_dir.x //l1p1
969 );
970
971 for (uint j = 0; j < 4; j++) {
972 sh_accum[j].rgb += light * c[j];
973 }
974 #else
975 light_accum += light;
976 #endif
977 }
978
979 // Add the averaged result to the accumulated light texture.
980 #ifdef USE_SH_LIGHTMAPS
981 for (int i = 0; i < 4; i++) {
982 vec4 accum = imageLoad(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + i));
983 accum.rgb += sh_accum[i].rgb / float(params.ray_count);
984 imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + i), accum);
985 }
986 #else
987 vec4 accum = imageLoad(accum_light, ivec3(atlas_pos, params.atlas_slice));
988 accum.rgb += light_accum / float(params.ray_count);
989 imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice), accum);
990 #endif
991
992 #endif
993
994 #ifdef MODE_UNOCCLUDE
995
996 //texel_size = 0.5;
997 //compute tangents
998
999 vec4 position_alpha = imageLoad(position, ivec3(atlas_pos, params.atlas_slice));
1000 if (position_alpha.a < 0.5) {
1001 return;
1002 }
1003
1004 vec3 vertex_pos = position_alpha.xyz;
1005 vec4 normal_tsize = imageLoad(unocclude, ivec3(atlas_pos, params.atlas_slice));
1006
1007 vec3 face_normal = normal_tsize.xyz;
1008 float texel_size = normal_tsize.w;
1009
1010 vec3 v0 = abs(face_normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
1011 vec3 tangent = normalize(cross(v0, face_normal));
1012 vec3 bitangent = normalize(cross(tangent, face_normal));
1013 vec3 base_pos = vertex_pos + face_normal * bake_params.bias; // Raise a bit.
1014
1015 vec3 rays[4] = vec3[](tangent, bitangent, -tangent, -bitangent);
1016 float min_d = 1e20;
1017 float unocclude_mask = 0.0;
1018
1019 for (int i = 0; i < 4; i++) {
1020 vec3 ray_to = base_pos + rays[i] * texel_size * params.denoiser_range;
1021 float d;
1022 vec3 norm;
1023
1024 if (trace_ray_closest_hit_distance(base_pos, ray_to, d, norm) == RAY_BACK) {
1025 unocclude_mask = 1.0;
1026 if (d <= texel_size && d < min_d) {
1027 // This bias needs to be greater than the regular bias, because otherwise later, rays will go the other side when pointing back.
1028 vertex_pos = base_pos + rays[i] * d + norm * bake_params.bias * 10.0;
1029 min_d = d;
1030 }
1031 }
1032 }
1033
1034 position_alpha.xyz = vertex_pos;
1035
1036 imageStore(position, ivec3(atlas_pos, params.atlas_slice), position_alpha);
1037 imageStore(unocclude, ivec3(atlas_pos, params.atlas_slice), vec4(unocclude_mask, 0, 0, 0));
1038
1039 #endif
1040
1041 #ifdef MODE_LIGHT_PROBES
1042
1043 vec3 position = probe_positions.data[probe_index].xyz;
1044
1045 vec4 probe_sh_accum[9] = vec4[](
1046 vec4(0.0),
1047 vec4(0.0),
1048 vec4(0.0),
1049 vec4(0.0),
1050 vec4(0.0),
1051 vec4(0.0),
1052 vec4(0.0),
1053 vec4(0.0),
1054 vec4(0.0));
1055
1056 uint noise = random_seed(ivec3(params.ray_from, probe_index, 49502741 /* some prime */));
1057 for (uint i = params.ray_from; i < params.ray_to; i++) {
1058 vec3 ray_dir = generate_sphere_uniform_direction(noise);
1059 vec3 light = trace_indirect_light(position, ray_dir, noise, 0.0);
1060
1061 float c[9] = float[](
1062 0.282095, //l0
1063 0.488603 * ray_dir.y, //l1n1
1064 0.488603 * ray_dir.z, //l1n0
1065 0.488603 * ray_dir.x, //l1p1
1066 1.092548 * ray_dir.x * ray_dir.y, //l2n2
1067 1.092548 * ray_dir.y * ray_dir.z, //l2n1
1068 0.315392 * (3.0 * ray_dir.z * ray_dir.z - 1.0), //l20
1069 1.092548 * ray_dir.x * ray_dir.z, //l2p1
1070 0.546274 * (ray_dir.x * ray_dir.x - ray_dir.y * ray_dir.y) //l2p2
1071 );
1072
1073 for (uint j = 0; j < 9; j++) {
1074 probe_sh_accum[j].rgb += light * c[j];
1075 }
1076 }
1077
1078 if (params.ray_from > 0) {
1079 for (uint j = 0; j < 9; j++) { //accum from existing
1080 probe_sh_accum[j] += light_probes.data[probe_index * 9 + j];
1081 }
1082 }
1083
1084 if (params.ray_to == params.ray_count) {
1085 for (uint j = 0; j < 9; j++) { //accum from existing
1086 probe_sh_accum[j] *= 4.0 / float(params.ray_count);
1087 }
1088 }
1089
1090 for (uint j = 0; j < 9; j++) { //accum from existing
1091 light_probes.data[probe_index * 9 + j] = probe_sh_accum[j];
1092 }
1093
1094 #endif
1095
1096 #ifdef MODE_DILATE
1097
1098 const int max_radius = int(4.0 * bake_params.supersampling_factor);
1099 const ivec2 directions[8] = ivec2[8](ivec2(-1, 0), ivec2(0, 1), ivec2(1, 0), ivec2(0, -1), ivec2(-1, -1), ivec2(-1, 1), ivec2(1, -1), ivec2(1, 1));
1100
1101 vec4 texel_color = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0);
1102
1103 for (int radius = 1; radius <= max_radius; radius++) {
1104 for (uint i = 0; i < 8; i++) {
1105 const ivec2 sample_pos = atlas_pos + directions[i] * radius;
1106 // Texture bounds check for robustness.
1107 if (any(lessThan(sample_pos, ivec2(0))) ||
1108 any(greaterThanEqual(sample_pos, textureSize(source_light, 0).xy))) {
1109 continue;
1110 }
1111
1112 vec4 neighbor_color = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(sample_pos, params.atlas_slice), 0);
1113 if (neighbor_color.a > 0.5) {
1114 texel_color = neighbor_color;
1115 break;
1116 }
1117 }
1118
1119 if (texel_color.a > 0.5) {
1120 break;
1121 }
1122 }
1123
1124 imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice), texel_color);
1125
1126 #endif
1127
1128 #ifdef MODE_DENOISE
1129 // Joint Non-local means (JNLM) denoiser.
1130 //
1131 // Based on YoctoImageDenoiser's JNLM implementation with corrections from "Nonlinearly Weighted First-order Regression for Denoising Monte Carlo Renderings".
1132 //
1133 // <https://github.com/ManuelPrandini/YoctoImageDenoiser/blob/06e19489dd64e47792acffde536393802ba48607/libs/yocto_extension/yocto_extension.cpp#L207>
1134 // <https://benedikt-bitterli.me/nfor/nfor.pdf>
1135 //
1136 // MIT License
1137 //
1138 // Copyright (c) 2020 ManuelPrandini
1139 //
1140 // Permission is hereby granted, free of charge, to any person obtaining a copy
1141 // of this software and associated documentation files (the "Software"), to deal
1142 // in the Software without restriction, including without limitation the rights
1143 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1144 // copies of the Software, and to permit persons to whom the Software is
1145 // furnished to do so, subject to the following conditions:
1146 //
1147 // The above copyright notice and this permission notice shall be included in all
1148 // copies or substantial portions of the Software.
1149 //
1150 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1151 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1152 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1153 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1154 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1155 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1156 // SOFTWARE.
1157 //
1158 // Most of the constants below have been hand-picked to fit the common scenarios lightmaps
1159 // are generated with, but they can be altered freely to experiment and achieve better results.
1160
1161 // Half the size of the patch window around each pixel that is weighted to compute the denoised pixel.
1162 // A value of 1 represents a 3x3 window, a value of 2 a 5x5 window, etc.
1163 const int HALF_PATCH_WINDOW = 3;
1164
1165 // Half the size of the search window around each pixel that is denoised and weighted to compute the denoised pixel.
1166 const int HALF_SEARCH_WINDOW = denoise_params.half_search_window;
1167
1168 // For all of the following sigma values, smaller values will give less weight to pixels that have a bigger distance
1169 // in the feature being evaluated. Therefore, smaller values are likely to cause more noise to appear, but will also
1170 // cause less features to be erased in the process.
1171
1172 // Controls how much the spatial distance of the pixels influences the denoising weight.
1173 const float SIGMA_SPATIAL = denoise_params.spatial_bandwidth;
1174
1175 // Controls how much the light color distance of the pixels influences the denoising weight.
1176 const float SIGMA_LIGHT = denoise_params.light_bandwidth;
1177
1178 // Controls how much the albedo color distance of the pixels influences the denoising weight.
1179 const float SIGMA_ALBEDO = denoise_params.albedo_bandwidth;
1180
1181 // Controls how much the normal vector distance of the pixels influences the denoising weight.
1182 const float SIGMA_NORMAL = denoise_params.normal_bandwidth;
1183
1184 // Strength of the filter. The original paper recommends values around 10 to 15 times the Sigma parameter.
1185 const float FILTER_VALUE = denoise_params.filter_strength * SIGMA_LIGHT;
1186
1187 // Formula constants.
1188 const int PATCH_WINDOW_DIMENSION = (HALF_PATCH_WINDOW * 2 + 1);
1189 const int PATCH_WINDOW_DIMENSION_SQUARE = (PATCH_WINDOW_DIMENSION * PATCH_WINDOW_DIMENSION);
1190 const float TWO_SIGMA_SPATIAL_SQUARE = 2.0f * SIGMA_SPATIAL * SIGMA_SPATIAL;
1191 const float TWO_SIGMA_LIGHT_SQUARE = 2.0f * SIGMA_LIGHT * SIGMA_LIGHT;
1192 const float TWO_SIGMA_ALBEDO_SQUARE = 2.0f * SIGMA_ALBEDO * SIGMA_ALBEDO;
1193 const float TWO_SIGMA_NORMAL_SQUARE = 2.0f * SIGMA_NORMAL * SIGMA_NORMAL;
1194 const float FILTER_SQUARE_TWO_SIGMA_LIGHT_SQUARE = FILTER_VALUE * FILTER_VALUE * TWO_SIGMA_LIGHT_SQUARE;
1195 const float EPSILON = 1e-6f;
1196
1197 const uint slice_count = denoise_params.slice_count;
1198 const uint slice_base = params.atlas_slice * slice_count;
1199 const bool is_directional = (slice_count == 4);
1200
1201 for (uint i = 0; i < slice_count; i++) {
1202 uint lightmap_slice = slice_base + i;
1203 vec3 denoised_rgb = vec3(0.0f);
1204 vec4 input_light = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos, lightmap_slice), 0);
1205 vec3 input_albedo = texelFetch(sampler2DArray(albedo_tex, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).rgb;
1206 vec3 input_normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
1207 if (length(input_normal) > EPSILON) {
1208 // Compute the denoised pixel if the normal is valid.
1209 float sum_weights = 0.0f;
1210 vec3 input_rgb = input_light.rgb;
1211 for (int search_y = -HALF_SEARCH_WINDOW; search_y <= HALF_SEARCH_WINDOW; search_y++) {
1212 for (int search_x = -HALF_SEARCH_WINDOW; search_x <= HALF_SEARCH_WINDOW; search_x++) {
1213 ivec2 search_pos = atlas_pos + ivec2(search_x, search_y);
1214 vec3 search_rgb = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(search_pos, lightmap_slice), 0).rgb;
1215 vec3 search_albedo = texelFetch(sampler2DArray(albedo_tex, linear_sampler), ivec3(search_pos, params.atlas_slice), 0).rgb;
1216 vec3 search_normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(search_pos, params.atlas_slice), 0).xyz;
1217 float search_occlusion = texelFetch(sampler2DArray(unocclude_mask, linear_sampler), ivec3(search_pos, params.atlas_slice), 0).r;
1218 float patch_square_dist = 0.0f;
1219 for (int offset_y = -HALF_PATCH_WINDOW; offset_y <= HALF_PATCH_WINDOW; offset_y++) {
1220 for (int offset_x = -HALF_PATCH_WINDOW; offset_x <= HALF_PATCH_WINDOW; offset_x++) {
1221 ivec2 offset_input_pos = atlas_pos + ivec2(offset_x, offset_y);
1222 ivec2 offset_search_pos = search_pos + ivec2(offset_x, offset_y);
1223 vec3 offset_input_rgb = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(offset_input_pos, slice_base), 0).rgb;
1224 vec3 offset_search_rgb = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(offset_search_pos, slice_base), 0).rgb;
1225 vec3 offset_delta_rgb = offset_input_rgb - offset_search_rgb;
1226
1227 if (is_directional) {
1228 // Since L0 data is 1/4 the value of a regular lightmap,
1229 // we have to multiply it by 4.
1230 offset_delta_rgb *= 4.0;
1231 }
1232
1233 patch_square_dist += dot(offset_delta_rgb, offset_delta_rgb) - TWO_SIGMA_LIGHT_SQUARE;
1234 }
1235 }
1236
1237 patch_square_dist = max(0.0f, patch_square_dist / (3.0f * PATCH_WINDOW_DIMENSION_SQUARE));
1238
1239 float weight = 1.0f;
1240
1241 // Ignore weight if search position is out of bounds.
1242 weight *= step(0, search_pos.x) * step(search_pos.x, bake_params.atlas_size.x - 1);
1243 weight *= step(0, search_pos.y) * step(search_pos.y, bake_params.atlas_size.y - 1);
1244
1245 // Ignore weight if normal is zero length.
1246 weight *= step(EPSILON, length(search_normal));
1247
1248 // Weight with pixel distance.
1249 vec2 pixel_delta = vec2(search_x, search_y);
1250 float pixel_square_dist = dot(pixel_delta, pixel_delta);
1251 weight *= exp(-pixel_square_dist / TWO_SIGMA_SPATIAL_SQUARE);
1252
1253 // Weight with patch.
1254 weight *= exp(-patch_square_dist / FILTER_SQUARE_TWO_SIGMA_LIGHT_SQUARE);
1255
1256 // Weight with albedo.
1257 vec3 albedo_delta = input_albedo - search_albedo;
1258 float albedo_square_dist = dot(albedo_delta, albedo_delta);
1259 weight *= exp(-albedo_square_dist / TWO_SIGMA_ALBEDO_SQUARE);
1260
1261 // Weight with normal.
1262 vec3 normal_delta = input_normal - search_normal;
1263 float normal_square_dist = dot(normal_delta, normal_delta);
1264 weight *= exp(-normal_square_dist / TWO_SIGMA_NORMAL_SQUARE);
1265
1266 // Weight with occlusion.
1267 weight *= 1.0 - search_occlusion;
1268
1269 denoised_rgb += weight * search_rgb;
1270 sum_weights += weight;
1271 }
1272 }
1273
1274 // Avoid division by zero if no weights were accumulated.
1275 denoised_rgb = sum_weights > EPSILON ? denoised_rgb / sum_weights : input_rgb;
1276 } else {
1277 // Ignore pixels where the normal is empty, just copy the light color.
1278 denoised_rgb = input_light.rgb;
1279 }
1280
1281 imageStore(dest_light, ivec3(atlas_pos, lightmap_slice), vec4(denoised_rgb, input_light.a));
1282 }
1283 #endif
1284
1285 #ifdef MODE_PACK_L1_COEFFS
1286 vec4 base_coeff = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos, params.atlas_slice * 4), 0);
1287 imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice * 4), base_coeff);
1288
1289 for (int i = 1; i < 4; i++) {
1290 vec4 c = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos, params.atlas_slice * 4 + i), 0);
1291 c.rgb /= (base_coeff.rgb * 8.0 + vec3(1e-6f));
1292 c.rgb = clamp(c.rgb + vec3(0.5), vec3(0.0), vec3(1.0));
1293
1294 imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice * 4 + i), c);
1295 }
1296 #endif
1297 }