lm_compute.glsl 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. #[versions]
  2. primary = "#define MODE_DIRECT_LIGHT";
  3. secondary = "#define MODE_BOUNCE_LIGHT";
  4. dilate = "#define MODE_DILATE";
  5. unocclude = "#define MODE_UNOCCLUDE";
  6. light_probes = "#define MODE_LIGHT_PROBES";
  7. denoise = "#define MODE_DENOISE";
  8. #[compute]
  9. #version 450
  10. #VERSION_DEFINES
  11. // One 2D local group focusing in one layer at a time, though all
  12. // in parallel (no barriers) makes more sense than a 3D local group
  13. // as this can take more advantage of the cache for each group.
  14. #ifdef MODE_LIGHT_PROBES
  15. layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
  16. #else
  17. layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
  18. #endif
  19. #include "lm_common_inc.glsl"
  20. #ifdef MODE_LIGHT_PROBES
  21. layout(set = 1, binding = 0, std430) restrict buffer LightProbeData {
  22. vec4 data[];
  23. }
  24. light_probes;
  25. layout(set = 1, binding = 1) uniform texture2DArray source_light;
  26. layout(set = 1, binding = 2) uniform texture2D environment;
  27. #endif
  28. #ifdef MODE_UNOCCLUDE
  29. layout(rgba32f, set = 1, binding = 0) uniform restrict image2DArray position;
  30. layout(rgba32f, set = 1, binding = 1) uniform restrict readonly image2DArray unocclude;
  31. #endif
  32. #if defined(MODE_DIRECT_LIGHT) || defined(MODE_BOUNCE_LIGHT)
  33. layout(rgba16f, set = 1, binding = 0) uniform restrict writeonly image2DArray dest_light;
  34. layout(set = 1, binding = 1) uniform texture2DArray source_light;
  35. layout(set = 1, binding = 2) uniform texture2DArray source_position;
  36. layout(set = 1, binding = 3) uniform texture2DArray source_normal;
  37. layout(rgba16f, set = 1, binding = 4) uniform restrict image2DArray accum_light;
  38. #endif
  39. #ifdef MODE_BOUNCE_LIGHT
  40. layout(set = 1, binding = 5) uniform texture2D environment;
  41. #endif
  42. #if defined(MODE_DILATE) || defined(MODE_DENOISE)
  43. layout(rgba16f, set = 1, binding = 0) uniform restrict writeonly image2DArray dest_light;
  44. layout(set = 1, binding = 1) uniform texture2DArray source_light;
  45. #endif
  46. #ifdef MODE_DENOISE
  47. layout(set = 1, binding = 2) uniform texture2DArray source_normal;
  48. layout(set = 1, binding = 3) uniform DenoiseParams {
  49. float spatial_bandwidth;
  50. float light_bandwidth;
  51. float albedo_bandwidth;
  52. float normal_bandwidth;
  53. float filter_strength;
  54. }
  55. denoise_params;
  56. #endif
  57. layout(push_constant, std430) uniform Params {
  58. uint atlas_slice;
  59. uint ray_count;
  60. uint ray_from;
  61. uint ray_to;
  62. ivec2 region_ofs;
  63. uint probe_count;
  64. }
  65. params;
  66. //check it, but also return distance and barycentric coords (for uv lookup)
  67. 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) {
  68. const float EPSILON = 0.00001;
  69. const vec3 e0 = p1 - p0;
  70. const vec3 e1 = p0 - p2;
  71. vec3 triangle_normal = cross(e1, e0);
  72. float n_dot_dir = dot(triangle_normal, dir);
  73. if (abs(n_dot_dir) < EPSILON) {
  74. return false;
  75. }
  76. const vec3 e2 = (p0 - from) / n_dot_dir;
  77. const vec3 i = cross(dir, e2);
  78. r_barycentric.y = dot(i, e1);
  79. r_barycentric.z = dot(i, e0);
  80. r_barycentric.x = 1.0 - (r_barycentric.z + r_barycentric.y);
  81. r_distance = dot(triangle_normal, e2);
  82. return (r_distance > bake_params.bias) && (r_distance < max_dist) && all(greaterThanEqual(r_barycentric, vec3(0.0)));
  83. }
  84. const uint RAY_MISS = 0;
  85. const uint RAY_FRONT = 1;
  86. const uint RAY_BACK = 2;
  87. const uint RAY_ANY = 3;
  88. bool ray_box_test(vec3 p_from, vec3 p_inv_dir, vec3 p_box_min, vec3 p_box_max) {
  89. vec3 t0 = (p_box_min - p_from) * p_inv_dir;
  90. vec3 t1 = (p_box_max - p_from) * p_inv_dir;
  91. vec3 tmin = min(t0, t1), tmax = max(t0, t1);
  92. return max(tmin.x, max(tmin.y, tmin.z)) <= min(tmax.x, min(tmax.y, tmax.z));
  93. }
  94. #if CLUSTER_SIZE > 32
  95. #define CLUSTER_TRIANGLE_ITERATION
  96. #endif
  97. 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) {
  98. // World coordinates.
  99. vec3 rel = p_to - p_from;
  100. float rel_len = length(rel);
  101. vec3 dir = normalize(rel);
  102. vec3 inv_dir = 1.0 / dir;
  103. // Cell coordinates.
  104. vec3 from_cell = (p_from - bake_params.to_cell_offset) * bake_params.to_cell_size;
  105. vec3 to_cell = (p_to - bake_params.to_cell_offset) * bake_params.to_cell_size;
  106. // Prepare DDA.
  107. vec3 rel_cell = to_cell - from_cell;
  108. ivec3 icell = ivec3(from_cell);
  109. ivec3 iendcell = ivec3(to_cell);
  110. vec3 dir_cell = normalize(rel_cell);
  111. vec3 delta = min(abs(1.0 / dir_cell), bake_params.grid_size); // Use bake_params.grid_size as max to prevent infinity values.
  112. ivec3 step = ivec3(sign(rel_cell));
  113. vec3 side = (sign(rel_cell) * (vec3(icell) - from_cell) + (sign(rel_cell) * 0.5) + 0.5) * delta;
  114. uint iters = 0;
  115. while (all(greaterThanEqual(icell, ivec3(0))) && all(lessThan(icell, ivec3(bake_params.grid_size))) && (iters < 1000)) {
  116. uvec2 cell_data = texelFetch(usampler3D(grid, linear_sampler), icell, 0).xy;
  117. uint triangle_count = cell_data.x;
  118. if (triangle_count > 0) {
  119. uint hit = RAY_MISS;
  120. float best_distance = 1e20;
  121. uint cluster_start = cluster_indices.data[cell_data.y * 2];
  122. uint cell_triangle_start = cluster_indices.data[cell_data.y * 2 + 1];
  123. uint cluster_count = (triangle_count + CLUSTER_SIZE - 1) / CLUSTER_SIZE;
  124. uint cluster_base_index = 0;
  125. while (cluster_base_index < cluster_count) {
  126. // To minimize divergence, all Ray-AABB tests on the clusters contained in the cell are performed
  127. // before checking against the triangles. We do this 32 clusters at a time and store the intersected
  128. // clusters on each bit of the 32-bit integer.
  129. uint cluster_test_count = min(32, cluster_count - cluster_base_index);
  130. uint cluster_hits = 0;
  131. for (uint i = 0; i < cluster_test_count; i++) {
  132. uint cluster_index = cluster_start + cluster_base_index + i;
  133. ClusterAABB cluster_aabb = cluster_aabbs.data[cluster_index];
  134. if (ray_box_test(p_from, inv_dir, cluster_aabb.min_bounds, cluster_aabb.max_bounds)) {
  135. cluster_hits |= (1 << i);
  136. }
  137. }
  138. // Check the triangles in any of the clusters that were intersected by toggling off the bits in the
  139. // 32-bit integer counter until no bits are left.
  140. while (cluster_hits > 0) {
  141. uint cluster_index = findLSB(cluster_hits);
  142. cluster_hits &= ~(1 << cluster_index);
  143. cluster_index += cluster_base_index;
  144. // Do the same divergence execution trick with triangles as well.
  145. uint triangle_base_index = 0;
  146. #ifdef CLUSTER_TRIANGLE_ITERATION
  147. while (triangle_base_index < triangle_count)
  148. #endif
  149. {
  150. uint triangle_start_index = cell_triangle_start + cluster_index * CLUSTER_SIZE + triangle_base_index;
  151. uint triangle_test_count = min(CLUSTER_SIZE, triangle_count - triangle_base_index);
  152. uint triangle_hits = 0;
  153. for (uint i = 0; i < triangle_test_count; i++) {
  154. uint triangle_index = triangle_indices.data[triangle_start_index + i];
  155. if (ray_box_test(p_from, inv_dir, triangles.data[triangle_index].min_bounds, triangles.data[triangle_index].max_bounds)) {
  156. triangle_hits |= (1 << i);
  157. }
  158. }
  159. while (triangle_hits > 0) {
  160. uint cluster_triangle_index = findLSB(triangle_hits);
  161. triangle_hits &= ~(1 << cluster_triangle_index);
  162. cluster_triangle_index += triangle_start_index;
  163. uint triangle_index = triangle_indices.data[cluster_triangle_index];
  164. Triangle triangle = triangles.data[triangle_index];
  165. // Gather the triangle vertex positions.
  166. vec3 vtx0 = vertices.data[triangle.indices.x].position;
  167. vec3 vtx1 = vertices.data[triangle.indices.y].position;
  168. vec3 vtx2 = vertices.data[triangle.indices.z].position;
  169. vec3 normal = -normalize(cross((vtx0 - vtx1), (vtx0 - vtx2)));
  170. bool backface = dot(normal, dir) >= 0.0;
  171. float distance;
  172. vec3 barycentric;
  173. if (ray_hits_triangle(p_from, dir, rel_len, vtx0, vtx1, vtx2, distance, barycentric)) {
  174. if (p_any_hit) {
  175. // Return early if any hit was requested.
  176. return RAY_ANY;
  177. }
  178. vec3 position = p_from + dir * distance;
  179. vec3 hit_cell = (position - bake_params.to_cell_offset) * bake_params.to_cell_size;
  180. if (icell != ivec3(hit_cell)) {
  181. // It's possible for the ray to hit a triangle in a position outside the bounds of the cell
  182. // if it's large enough to cover multiple ones. The hit must be ignored if this is the case.
  183. continue;
  184. }
  185. if (!backface) {
  186. // The case of meshes having both a front and back face in the same plane is more common than
  187. // expected, so if this is a front-face, bias it closer to the ray origin, so it always wins
  188. // over the back-face.
  189. distance = max(bake_params.bias, distance - bake_params.bias);
  190. }
  191. if (distance < best_distance) {
  192. hit = backface ? RAY_BACK : RAY_FRONT;
  193. best_distance = distance;
  194. r_distance = distance;
  195. r_normal = normal;
  196. r_triangle = triangle_index;
  197. r_barycentric = barycentric;
  198. }
  199. }
  200. }
  201. #ifdef CLUSTER_TRIANGLE_ITERATION
  202. triangle_base_index += CLUSTER_SIZE;
  203. #endif
  204. }
  205. }
  206. cluster_base_index += 32;
  207. }
  208. if (hit != RAY_MISS) {
  209. return hit;
  210. }
  211. }
  212. if (icell == iendcell) {
  213. break;
  214. }
  215. bvec3 mask = lessThanEqual(side.xyz, min(side.yzx, side.zxy));
  216. side += vec3(mask) * delta;
  217. icell += ivec3(vec3(mask)) * step;
  218. iters++;
  219. }
  220. return RAY_MISS;
  221. }
  222. uint trace_ray_closest_hit_triangle(vec3 p_from, vec3 p_to, out uint r_triangle, out vec3 r_barycentric) {
  223. float distance;
  224. vec3 normal;
  225. return trace_ray(p_from, p_to, false, distance, normal, r_triangle, r_barycentric);
  226. }
  227. uint trace_ray_closest_hit_distance(vec3 p_from, vec3 p_to, out float r_distance, out vec3 r_normal) {
  228. uint triangle;
  229. vec3 barycentric;
  230. return trace_ray(p_from, p_to, false, r_distance, r_normal, triangle, barycentric);
  231. }
  232. uint trace_ray_any_hit(vec3 p_from, vec3 p_to) {
  233. float distance;
  234. vec3 normal;
  235. uint triangle;
  236. vec3 barycentric;
  237. return trace_ray(p_from, p_to, true, distance, normal, triangle, barycentric);
  238. }
  239. // https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/
  240. uint hash(uint value) {
  241. uint state = value * 747796405u + 2891336453u;
  242. uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
  243. return (word >> 22u) ^ word;
  244. }
  245. uint random_seed(ivec3 seed) {
  246. return hash(seed.x ^ hash(seed.y ^ hash(seed.z)));
  247. }
  248. // generates a random value in range [0.0, 1.0)
  249. float randomize(inout uint value) {
  250. value = hash(value);
  251. return float(value / 4294967296.0);
  252. }
  253. const float PI = 3.14159265f;
  254. // http://www.realtimerendering.com/raytracinggems/unofficial_RayTracingGems_v1.4.pdf (chapter 15)
  255. vec3 generate_hemisphere_cosine_weighted_direction(inout uint noise) {
  256. float noise1 = randomize(noise);
  257. float noise2 = randomize(noise) * 2.0 * PI;
  258. return vec3(sqrt(noise1) * cos(noise2), sqrt(noise1) * sin(noise2), sqrt(1.0 - noise1));
  259. }
  260. // Distribution generation adapted from "Generating uniformly distributed numbers on a sphere"
  261. // <http://corysimon.github.io/articles/uniformdistn-on-sphere/>
  262. vec3 generate_sphere_uniform_direction(inout uint noise) {
  263. float theta = 2.0 * PI * randomize(noise);
  264. float phi = acos(1.0 - 2.0 * randomize(noise));
  265. return vec3(sin(phi) * cos(theta), sin(phi) * sin(theta), cos(phi));
  266. }
  267. vec3 generate_ray_dir_from_normal(vec3 normal, inout uint noise) {
  268. vec3 v0 = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
  269. vec3 tangent = normalize(cross(v0, normal));
  270. vec3 bitangent = normalize(cross(tangent, normal));
  271. mat3 normal_mat = mat3(tangent, bitangent, normal);
  272. return normal_mat * generate_hemisphere_cosine_weighted_direction(noise);
  273. }
  274. #if defined(MODE_DIRECT_LIGHT) || defined(MODE_BOUNCE_LIGHT) || defined(MODE_LIGHT_PROBES)
  275. float get_omni_attenuation(float distance, float inv_range, float decay) {
  276. float nd = distance * inv_range;
  277. nd *= nd;
  278. nd *= nd; // nd^4
  279. nd = max(1.0 - nd, 0.0);
  280. nd *= nd; // nd^2
  281. return nd * pow(max(distance, 0.0001), -decay);
  282. }
  283. 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) {
  284. r_light = vec3(0.0f);
  285. vec3 light_pos;
  286. float dist;
  287. float attenuation;
  288. float soft_shadowing_disk_size;
  289. Light light_data = lights.data[p_light_index];
  290. if (light_data.type == LIGHT_TYPE_DIRECTIONAL) {
  291. vec3 light_vec = light_data.direction;
  292. light_pos = p_position - light_vec * length(bake_params.world_size);
  293. r_light_dir = normalize(light_pos - p_position);
  294. dist = length(bake_params.world_size);
  295. attenuation = 1.0;
  296. soft_shadowing_disk_size = light_data.size;
  297. } else {
  298. light_pos = light_data.position;
  299. r_light_dir = normalize(light_pos - p_position);
  300. dist = distance(p_position, light_pos);
  301. if (dist > light_data.range) {
  302. return;
  303. }
  304. soft_shadowing_disk_size = light_data.size / dist;
  305. attenuation = get_omni_attenuation(dist, 1.0 / light_data.range, light_data.attenuation);
  306. if (light_data.type == LIGHT_TYPE_SPOT) {
  307. vec3 rel = normalize(p_position - light_pos);
  308. float cos_spot_angle = light_data.cos_spot_angle;
  309. float cos_angle = dot(rel, light_data.direction);
  310. if (cos_angle < cos_spot_angle) {
  311. return;
  312. }
  313. float scos = max(cos_angle, cos_spot_angle);
  314. float spot_rim = max(0.0001, (1.0 - scos) / (1.0 - cos_spot_angle));
  315. attenuation *= 1.0 - pow(spot_rim, light_data.inv_spot_attenuation);
  316. }
  317. }
  318. attenuation *= max(0.0, dot(p_normal, r_light_dir));
  319. if (attenuation <= 0.0001) {
  320. return;
  321. }
  322. float penumbra = 0.0;
  323. if ((light_data.size > 0.0) && p_soft_shadowing) {
  324. vec3 light_to_point = -r_light_dir;
  325. vec3 aux = light_to_point.y < 0.777 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
  326. vec3 light_to_point_tan = normalize(cross(light_to_point, aux));
  327. vec3 light_to_point_bitan = normalize(cross(light_to_point, light_to_point_tan));
  328. const uint shadowing_rays_check_penumbra_denom = 2;
  329. uint shadowing_ray_count = p_soft_shadowing ? params.ray_count : 1;
  330. uint hits = 0;
  331. vec3 light_disk_to_point = light_to_point;
  332. for (uint j = 0; j < shadowing_ray_count; j++) {
  333. // Optimization:
  334. // Once already traced an important proportion of rays, if all are hits or misses,
  335. // assume we're not in the penumbra so we can infer the rest would have the same result
  336. if (p_soft_shadowing) {
  337. if (j == shadowing_ray_count / shadowing_rays_check_penumbra_denom) {
  338. if (hits == j) {
  339. // Assume totally lit
  340. hits = shadowing_ray_count;
  341. break;
  342. } else if (hits == 0) {
  343. // Assume totally dark
  344. hits = 0;
  345. break;
  346. }
  347. }
  348. }
  349. float r = randomize(r_noise);
  350. float a = randomize(r_noise) * 2.0 * PI;
  351. vec2 disk_sample = (r * vec2(cos(a), sin(a))) * soft_shadowing_disk_size * light_data.shadow_blur;
  352. light_disk_to_point = normalize(light_to_point + disk_sample.x * light_to_point_tan + disk_sample.y * light_to_point_bitan);
  353. if (trace_ray_any_hit(p_position - light_disk_to_point * bake_params.bias, p_position - light_disk_to_point * dist) == RAY_MISS) {
  354. hits++;
  355. }
  356. }
  357. penumbra = float(hits) / float(shadowing_ray_count);
  358. } else {
  359. if (trace_ray_any_hit(p_position + r_light_dir * bake_params.bias, light_pos) == RAY_MISS) {
  360. penumbra = 1.0;
  361. }
  362. }
  363. r_light = light_data.color * light_data.energy * attenuation * penumbra;
  364. }
  365. #endif
  366. #if defined(MODE_BOUNCE_LIGHT) || defined(MODE_LIGHT_PROBES)
  367. vec3 trace_environment_color(vec3 ray_dir) {
  368. vec3 sky_dir = normalize(mat3(bake_params.env_transform) * ray_dir);
  369. vec2 st = vec2(atan(sky_dir.x, sky_dir.z), acos(sky_dir.y));
  370. if (st.x < 0.0) {
  371. st.x += PI * 2.0;
  372. }
  373. return textureLod(sampler2D(environment, linear_sampler), st / vec2(PI * 2.0, PI), 0.0).rgb;
  374. }
  375. vec3 trace_indirect_light(vec3 p_position, vec3 p_ray_dir, inout uint r_noise) {
  376. // The lower limit considers the case where the lightmapper might have bounces disabled but light probes are requested.
  377. vec3 position = p_position;
  378. vec3 ray_dir = p_ray_dir;
  379. uint max_depth = max(bake_params.bounces, 1);
  380. vec3 throughput = vec3(1.0);
  381. vec3 light = vec3(0.0);
  382. for (uint depth = 0; depth < max_depth; depth++) {
  383. uint tidx;
  384. vec3 barycentric;
  385. uint trace_result = trace_ray_closest_hit_triangle(position + ray_dir * bake_params.bias, position + ray_dir * length(bake_params.world_size), tidx, barycentric);
  386. if (trace_result == RAY_FRONT) {
  387. Vertex vert0 = vertices.data[triangles.data[tidx].indices.x];
  388. Vertex vert1 = vertices.data[triangles.data[tidx].indices.y];
  389. Vertex vert2 = vertices.data[triangles.data[tidx].indices.z];
  390. vec3 uvw = vec3(barycentric.x * vert0.uv + barycentric.y * vert1.uv + barycentric.z * vert2.uv, float(triangles.data[tidx].slice));
  391. position = barycentric.x * vert0.position + barycentric.y * vert1.position + barycentric.z * vert2.position;
  392. vec3 norm0 = vec3(vert0.normal_xy, vert0.normal_z);
  393. vec3 norm1 = vec3(vert1.normal_xy, vert1.normal_z);
  394. vec3 norm2 = vec3(vert2.normal_xy, vert2.normal_z);
  395. vec3 normal = barycentric.x * norm0 + barycentric.y * norm1 + barycentric.z * norm2;
  396. vec3 direct_light = vec3(0.0f);
  397. #ifdef USE_LIGHT_TEXTURE_FOR_BOUNCES
  398. direct_light += textureLod(sampler2DArray(source_light, linear_sampler), uvw, 0.0).rgb;
  399. #else
  400. // Trace the lights directly. Significantly more expensive but more accurate in scenarios
  401. // where the lightmap texture isn't reliable.
  402. for (uint i = 0; i < bake_params.light_count; i++) {
  403. vec3 light;
  404. vec3 light_dir;
  405. trace_direct_light(position, normal, i, false, light, light_dir, r_noise);
  406. direct_light += light * lights.data[i].indirect_energy;
  407. }
  408. direct_light *= bake_params.exposure_normalization;
  409. #endif
  410. vec3 albedo = textureLod(sampler2DArray(albedo_tex, linear_sampler), uvw, 0).rgb;
  411. vec3 emissive = textureLod(sampler2DArray(emission_tex, linear_sampler), uvw, 0).rgb;
  412. emissive *= bake_params.exposure_normalization;
  413. light += throughput * emissive;
  414. throughput *= albedo;
  415. light += throughput * direct_light * bake_params.bounce_indirect_energy;
  416. // Use Russian Roulette to determine a probability to terminate the bounce earlier as an optimization.
  417. // <https://computergraphics.stackexchange.com/questions/2316/is-russian-roulette-really-the-answer>
  418. float p = max(max(throughput.x, throughput.y), throughput.z);
  419. if (randomize(r_noise) > p) {
  420. break;
  421. }
  422. // Boost the throughput from the probability of the ray being terminated early.
  423. throughput *= 1.0 / p;
  424. // Generate a new ray direction for the next bounce from this surface's normal.
  425. ray_dir = generate_ray_dir_from_normal(normal, r_noise);
  426. } else if (trace_result == RAY_MISS) {
  427. // Look for the environment color and stop bouncing.
  428. light += throughput * trace_environment_color(ray_dir);
  429. break;
  430. } else {
  431. // Ignore any other trace results.
  432. break;
  433. }
  434. }
  435. return light;
  436. }
  437. #endif
  438. void main() {
  439. // Check if invocation is out of bounds.
  440. #ifdef MODE_LIGHT_PROBES
  441. int probe_index = int(gl_GlobalInvocationID.x);
  442. if (probe_index >= params.probe_count) {
  443. return;
  444. }
  445. #else
  446. ivec2 atlas_pos = ivec2(gl_GlobalInvocationID.xy) + params.region_ofs;
  447. if (any(greaterThanEqual(atlas_pos, bake_params.atlas_size))) {
  448. return;
  449. }
  450. #endif
  451. #ifdef MODE_DIRECT_LIGHT
  452. vec3 normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
  453. if (length(normal) < 0.5) {
  454. return; //empty texel, no process
  455. }
  456. vec3 position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
  457. vec3 light_for_texture = vec3(0.0);
  458. vec3 light_for_bounces = vec3(0.0);
  459. #ifdef USE_SH_LIGHTMAPS
  460. vec4 sh_accum[4] = vec4[](
  461. vec4(0.0, 0.0, 0.0, 1.0),
  462. vec4(0.0, 0.0, 0.0, 1.0),
  463. vec4(0.0, 0.0, 0.0, 1.0),
  464. vec4(0.0, 0.0, 0.0, 1.0));
  465. #endif
  466. // Use atlas position and a prime number as the seed.
  467. uint noise = random_seed(ivec3(atlas_pos, 43573547));
  468. for (uint i = 0; i < bake_params.light_count; i++) {
  469. vec3 light;
  470. vec3 light_dir;
  471. trace_direct_light(position, normal, i, true, light, light_dir, noise);
  472. if (lights.data[i].static_bake) {
  473. light_for_texture += light;
  474. #ifdef USE_SH_LIGHTMAPS
  475. float c[4] = float[](
  476. 0.282095, //l0
  477. 0.488603 * light_dir.y, //l1n1
  478. 0.488603 * light_dir.z, //l1n0
  479. 0.488603 * light_dir.x //l1p1
  480. );
  481. for (uint j = 0; j < 4; j++) {
  482. sh_accum[j].rgb += light * c[j] * 8.0;
  483. }
  484. #endif
  485. }
  486. light_for_bounces += light * lights.data[i].indirect_energy;
  487. }
  488. light_for_bounces *= bake_params.exposure_normalization;
  489. imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice), vec4(light_for_bounces, 1.0));
  490. #ifdef USE_SH_LIGHTMAPS
  491. // Keep for adding at the end.
  492. imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 0), sh_accum[0]);
  493. imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 1), sh_accum[1]);
  494. imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 2), sh_accum[2]);
  495. imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + 3), sh_accum[3]);
  496. #else
  497. light_for_texture *= bake_params.exposure_normalization;
  498. imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice), vec4(light_for_texture, 1.0));
  499. #endif
  500. #endif
  501. #ifdef MODE_BOUNCE_LIGHT
  502. #ifdef USE_SH_LIGHTMAPS
  503. vec4 sh_accum[4] = vec4[](
  504. vec4(0.0, 0.0, 0.0, 1.0),
  505. vec4(0.0, 0.0, 0.0, 1.0),
  506. vec4(0.0, 0.0, 0.0, 1.0),
  507. vec4(0.0, 0.0, 0.0, 1.0));
  508. #else
  509. vec3 light_accum = vec3(0.0);
  510. #endif
  511. // Retrieve starting normal and position.
  512. vec3 normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
  513. if (length(normal) < 0.5) {
  514. // The pixel is empty, skip processing it.
  515. return;
  516. }
  517. vec3 position = texelFetch(sampler2DArray(source_position, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
  518. uint noise = random_seed(ivec3(params.ray_from, atlas_pos));
  519. for (uint i = params.ray_from; i < params.ray_to; i++) {
  520. vec3 ray_dir = generate_ray_dir_from_normal(normal, noise);
  521. vec3 light = trace_indirect_light(position, ray_dir, noise);
  522. #ifdef USE_SH_LIGHTMAPS
  523. float c[4] = float[](
  524. 0.282095, //l0
  525. 0.488603 * ray_dir.y, //l1n1
  526. 0.488603 * ray_dir.z, //l1n0
  527. 0.488603 * ray_dir.x //l1p1
  528. );
  529. for (uint j = 0; j < 4; j++) {
  530. sh_accum[j].rgb += light * c[j] * 8.0;
  531. }
  532. #else
  533. light_accum += light;
  534. #endif
  535. }
  536. // Add the averaged result to the accumulated light texture.
  537. #ifdef USE_SH_LIGHTMAPS
  538. for (int i = 0; i < 4; i++) {
  539. vec4 accum = imageLoad(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + i));
  540. accum.rgb += sh_accum[i].rgb / float(params.ray_count);
  541. imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice * 4 + i), accum);
  542. }
  543. #else
  544. vec4 accum = imageLoad(accum_light, ivec3(atlas_pos, params.atlas_slice));
  545. accum.rgb += light_accum / float(params.ray_count);
  546. imageStore(accum_light, ivec3(atlas_pos, params.atlas_slice), accum);
  547. #endif
  548. #endif
  549. #ifdef MODE_UNOCCLUDE
  550. //texel_size = 0.5;
  551. //compute tangents
  552. vec4 position_alpha = imageLoad(position, ivec3(atlas_pos, params.atlas_slice));
  553. if (position_alpha.a < 0.5) {
  554. return;
  555. }
  556. vec3 vertex_pos = position_alpha.xyz;
  557. vec4 normal_tsize = imageLoad(unocclude, ivec3(atlas_pos, params.atlas_slice));
  558. vec3 face_normal = normal_tsize.xyz;
  559. float texel_size = normal_tsize.w;
  560. vec3 v0 = abs(face_normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
  561. vec3 tangent = normalize(cross(v0, face_normal));
  562. vec3 bitangent = normalize(cross(tangent, face_normal));
  563. vec3 base_pos = vertex_pos + face_normal * bake_params.bias; // Raise a bit.
  564. vec3 rays[4] = vec3[](tangent, bitangent, -tangent, -bitangent);
  565. float min_d = 1e20;
  566. for (int i = 0; i < 4; i++) {
  567. vec3 ray_to = base_pos + rays[i] * texel_size;
  568. float d;
  569. vec3 norm;
  570. if (trace_ray_closest_hit_distance(base_pos, ray_to, d, norm) == RAY_BACK) {
  571. if (d < min_d) {
  572. // This bias needs to be greater than the regular bias, because otherwise later, rays will go the other side when pointing back.
  573. vertex_pos = base_pos + rays[i] * d + norm * bake_params.bias * 10.0;
  574. min_d = d;
  575. }
  576. }
  577. }
  578. position_alpha.xyz = vertex_pos;
  579. imageStore(position, ivec3(atlas_pos, params.atlas_slice), position_alpha);
  580. #endif
  581. #ifdef MODE_LIGHT_PROBES
  582. vec3 position = probe_positions.data[probe_index].xyz;
  583. vec4 probe_sh_accum[9] = vec4[](
  584. vec4(0.0),
  585. vec4(0.0),
  586. vec4(0.0),
  587. vec4(0.0),
  588. vec4(0.0),
  589. vec4(0.0),
  590. vec4(0.0),
  591. vec4(0.0),
  592. vec4(0.0));
  593. uint noise = random_seed(ivec3(params.ray_from, probe_index, 49502741 /* some prime */));
  594. for (uint i = params.ray_from; i < params.ray_to; i++) {
  595. vec3 ray_dir = generate_sphere_uniform_direction(noise);
  596. vec3 light = trace_indirect_light(position, ray_dir, noise);
  597. float c[9] = float[](
  598. 0.282095, //l0
  599. 0.488603 * ray_dir.y, //l1n1
  600. 0.488603 * ray_dir.z, //l1n0
  601. 0.488603 * ray_dir.x, //l1p1
  602. 1.092548 * ray_dir.x * ray_dir.y, //l2n2
  603. 1.092548 * ray_dir.y * ray_dir.z, //l2n1
  604. //0.315392 * (ray_dir.x * ray_dir.x + ray_dir.y * ray_dir.y + 2.0 * ray_dir.z * ray_dir.z), //l20
  605. 0.315392 * (3.0 * ray_dir.z * ray_dir.z - 1.0), //l20
  606. 1.092548 * ray_dir.x * ray_dir.z, //l2p1
  607. 0.546274 * (ray_dir.x * ray_dir.x - ray_dir.y * ray_dir.y) //l2p2
  608. );
  609. for (uint j = 0; j < 9; j++) {
  610. probe_sh_accum[j].rgb += light * c[j];
  611. }
  612. }
  613. if (params.ray_from > 0) {
  614. for (uint j = 0; j < 9; j++) { //accum from existing
  615. probe_sh_accum[j] += light_probes.data[probe_index * 9 + j];
  616. }
  617. }
  618. if (params.ray_to == params.ray_count) {
  619. for (uint j = 0; j < 9; j++) { //accum from existing
  620. probe_sh_accum[j] *= 4.0 / float(params.ray_count);
  621. }
  622. }
  623. for (uint j = 0; j < 9; j++) { //accum from existing
  624. light_probes.data[probe_index * 9 + j] = probe_sh_accum[j];
  625. }
  626. #endif
  627. #ifdef MODE_DILATE
  628. vec4 c = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0);
  629. //sides first, as they are closer
  630. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, 0), params.atlas_slice), 0);
  631. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, 1), params.atlas_slice), 0);
  632. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, 0), params.atlas_slice), 0);
  633. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, -1), params.atlas_slice), 0);
  634. //endpoints second
  635. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, -1), params.atlas_slice), 0);
  636. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, 1), params.atlas_slice), 0);
  637. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, -1), params.atlas_slice), 0);
  638. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, 1), params.atlas_slice), 0);
  639. //far sides third
  640. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, 0), params.atlas_slice), 0);
  641. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, 2), params.atlas_slice), 0);
  642. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, 0), params.atlas_slice), 0);
  643. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(0, -2), params.atlas_slice), 0);
  644. //far-mid endpoints
  645. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, -1), params.atlas_slice), 0);
  646. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, 1), params.atlas_slice), 0);
  647. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, -1), params.atlas_slice), 0);
  648. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, 1), params.atlas_slice), 0);
  649. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, -2), params.atlas_slice), 0);
  650. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-1, 2), params.atlas_slice), 0);
  651. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, -2), params.atlas_slice), 0);
  652. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(1, 2), params.atlas_slice), 0);
  653. //far endpoints
  654. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, -2), params.atlas_slice), 0);
  655. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(-2, 2), params.atlas_slice), 0);
  656. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, -2), params.atlas_slice), 0);
  657. c = c.a > 0.5 ? c : texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos + ivec2(2, 2), params.atlas_slice), 0);
  658. imageStore(dest_light, ivec3(atlas_pos, params.atlas_slice), c);
  659. #endif
  660. #ifdef MODE_DENOISE
  661. // Joint Non-local means (JNLM) denoiser.
  662. //
  663. // Based on YoctoImageDenoiser's JNLM implementation with corrections from "Nonlinearly Weighted First-order Regression for Denoising Monte Carlo Renderings".
  664. //
  665. // <https://github.com/ManuelPrandini/YoctoImageDenoiser/blob/06e19489dd64e47792acffde536393802ba48607/libs/yocto_extension/yocto_extension.cpp#L207>
  666. // <https://benedikt-bitterli.me/nfor/nfor.pdf>
  667. //
  668. // MIT License
  669. //
  670. // Copyright (c) 2020 ManuelPrandini
  671. //
  672. // Permission is hereby granted, free of charge, to any person obtaining a copy
  673. // of this software and associated documentation files (the "Software"), to deal
  674. // in the Software without restriction, including without limitation the rights
  675. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  676. // copies of the Software, and to permit persons to whom the Software is
  677. // furnished to do so, subject to the following conditions:
  678. //
  679. // The above copyright notice and this permission notice shall be included in all
  680. // copies or substantial portions of the Software.
  681. //
  682. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  683. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  684. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  685. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  686. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  687. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  688. // SOFTWARE.
  689. //
  690. // Most of the constants below have been hand-picked to fit the common scenarios lightmaps
  691. // are generated with, but they can be altered freely to experiment and achieve better results.
  692. // Half the size of the patch window around each pixel that is weighted to compute the denoised pixel.
  693. // A value of 1 represents a 3x3 window, a value of 2 a 5x5 window, etc.
  694. const int HALF_PATCH_WINDOW = 4;
  695. // Half the size of the search window around each pixel that is denoised and weighted to compute the denoised pixel.
  696. const int HALF_SEARCH_WINDOW = 10;
  697. // For all of the following sigma values, smaller values will give less weight to pixels that have a bigger distance
  698. // in the feature being evaluated. Therefore, smaller values are likely to cause more noise to appear, but will also
  699. // cause less features to be erased in the process.
  700. // Controls how much the spatial distance of the pixels influences the denoising weight.
  701. const float SIGMA_SPATIAL = denoise_params.spatial_bandwidth;
  702. // Controls how much the light color distance of the pixels influences the denoising weight.
  703. const float SIGMA_LIGHT = denoise_params.light_bandwidth;
  704. // Controls how much the albedo color distance of the pixels influences the denoising weight.
  705. const float SIGMA_ALBEDO = denoise_params.albedo_bandwidth;
  706. // Controls how much the normal vector distance of the pixels influences the denoising weight.
  707. const float SIGMA_NORMAL = denoise_params.normal_bandwidth;
  708. // Strength of the filter. The original paper recommends values around 10 to 15 times the Sigma parameter.
  709. const float FILTER_VALUE = denoise_params.filter_strength * SIGMA_LIGHT;
  710. // Formula constants.
  711. const int PATCH_WINDOW_DIMENSION = (HALF_PATCH_WINDOW * 2 + 1);
  712. const int PATCH_WINDOW_DIMENSION_SQUARE = (PATCH_WINDOW_DIMENSION * PATCH_WINDOW_DIMENSION);
  713. const float TWO_SIGMA_SPATIAL_SQUARE = 2.0f * SIGMA_SPATIAL * SIGMA_SPATIAL;
  714. const float TWO_SIGMA_LIGHT_SQUARE = 2.0f * SIGMA_LIGHT * SIGMA_LIGHT;
  715. const float TWO_SIGMA_ALBEDO_SQUARE = 2.0f * SIGMA_ALBEDO * SIGMA_ALBEDO;
  716. const float TWO_SIGMA_NORMAL_SQUARE = 2.0f * SIGMA_NORMAL * SIGMA_NORMAL;
  717. const float FILTER_SQUARE_TWO_SIGMA_LIGHT_SQUARE = FILTER_VALUE * FILTER_VALUE * TWO_SIGMA_LIGHT_SQUARE;
  718. const float EPSILON = 1e-6f;
  719. #ifdef USE_SH_LIGHTMAPS
  720. const uint slice_count = 4;
  721. const uint slice_base = params.atlas_slice * slice_count;
  722. #else
  723. const uint slice_count = 1;
  724. const uint slice_base = params.atlas_slice;
  725. #endif
  726. for (uint i = 0; i < slice_count; i++) {
  727. uint lightmap_slice = slice_base + i;
  728. vec3 denoised_rgb = vec3(0.0f);
  729. vec4 input_light = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(atlas_pos, lightmap_slice), 0);
  730. vec3 input_albedo = texelFetch(sampler2DArray(albedo_tex, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).rgb;
  731. vec3 input_normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(atlas_pos, params.atlas_slice), 0).xyz;
  732. if (length(input_normal) > EPSILON) {
  733. // Compute the denoised pixel if the normal is valid.
  734. float sum_weights = 0.0f;
  735. vec3 input_rgb = input_light.rgb;
  736. for (int search_y = -HALF_SEARCH_WINDOW; search_y <= HALF_SEARCH_WINDOW; search_y++) {
  737. for (int search_x = -HALF_SEARCH_WINDOW; search_x <= HALF_SEARCH_WINDOW; search_x++) {
  738. ivec2 search_pos = atlas_pos + ivec2(search_x, search_y);
  739. vec3 search_rgb = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(search_pos, lightmap_slice), 0).rgb;
  740. vec3 search_albedo = texelFetch(sampler2DArray(albedo_tex, linear_sampler), ivec3(search_pos, params.atlas_slice), 0).rgb;
  741. vec3 search_normal = texelFetch(sampler2DArray(source_normal, linear_sampler), ivec3(search_pos, params.atlas_slice), 0).xyz;
  742. float patch_square_dist = 0.0f;
  743. for (int offset_y = -HALF_PATCH_WINDOW; offset_y <= HALF_PATCH_WINDOW; offset_y++) {
  744. for (int offset_x = -HALF_PATCH_WINDOW; offset_x <= HALF_PATCH_WINDOW; offset_x++) {
  745. ivec2 offset_input_pos = atlas_pos + ivec2(offset_x, offset_y);
  746. ivec2 offset_search_pos = search_pos + ivec2(offset_x, offset_y);
  747. vec3 offset_input_rgb = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(offset_input_pos, lightmap_slice), 0).rgb;
  748. vec3 offset_search_rgb = texelFetch(sampler2DArray(source_light, linear_sampler), ivec3(offset_search_pos, lightmap_slice), 0).rgb;
  749. vec3 offset_delta_rgb = offset_input_rgb - offset_search_rgb;
  750. patch_square_dist += dot(offset_delta_rgb, offset_delta_rgb) - TWO_SIGMA_LIGHT_SQUARE;
  751. }
  752. }
  753. patch_square_dist = max(0.0f, patch_square_dist / (3.0f * PATCH_WINDOW_DIMENSION_SQUARE));
  754. float weight = 1.0f;
  755. // Ignore weight if search position is out of bounds.
  756. weight *= step(0, search_pos.x) * step(search_pos.x, bake_params.atlas_size.x - 1);
  757. weight *= step(0, search_pos.y) * step(search_pos.y, bake_params.atlas_size.y - 1);
  758. // Ignore weight if normal is zero length.
  759. weight *= step(EPSILON, length(search_normal));
  760. // Weight with pixel distance.
  761. vec2 pixel_delta = vec2(search_x, search_y);
  762. float pixel_square_dist = dot(pixel_delta, pixel_delta);
  763. weight *= exp(-pixel_square_dist / TWO_SIGMA_SPATIAL_SQUARE);
  764. // Weight with patch.
  765. weight *= exp(-patch_square_dist / FILTER_SQUARE_TWO_SIGMA_LIGHT_SQUARE);
  766. // Weight with albedo.
  767. vec3 albedo_delta = input_albedo - search_albedo;
  768. float albedo_square_dist = dot(albedo_delta, albedo_delta);
  769. weight *= exp(-albedo_square_dist / TWO_SIGMA_ALBEDO_SQUARE);
  770. // Weight with normal.
  771. vec3 normal_delta = input_normal - search_normal;
  772. float normal_square_dist = dot(normal_delta, normal_delta);
  773. weight *= exp(-normal_square_dist / TWO_SIGMA_NORMAL_SQUARE);
  774. denoised_rgb += weight * search_rgb;
  775. sum_weights += weight;
  776. }
  777. }
  778. denoised_rgb /= sum_weights;
  779. } else {
  780. // Ignore pixels where the normal is empty, just copy the light color.
  781. denoised_rgb = input_light.rgb;
  782. }
  783. imageStore(dest_light, ivec3(atlas_pos, lightmap_slice), vec4(denoised_rgb, input_light.a));
  784. }
  785. #endif
  786. }