lm_compute.glsl 36 KB

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