| 1 | /**************************************************************************/ |
| 2 | /* lightmapper_rd.cpp */ |
| 3 | /**************************************************************************/ |
| 4 | /* This file is part of: */ |
| 5 | /* GODOT ENGINE */ |
| 6 | /* https://godotengine.org */ |
| 7 | /**************************************************************************/ |
| 8 | /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ |
| 9 | /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ |
| 10 | /* */ |
| 11 | /* Permission is hereby granted, free of charge, to any person obtaining */ |
| 12 | /* a copy of this software and associated documentation files (the */ |
| 13 | /* "Software"), to deal in the Software without restriction, including */ |
| 14 | /* without limitation the rights to use, copy, modify, merge, publish, */ |
| 15 | /* distribute, sublicense, and/or sell copies of the Software, and to */ |
| 16 | /* permit persons to whom the Software is furnished to do so, subject to */ |
| 17 | /* the following conditions: */ |
| 18 | /* */ |
| 19 | /* The above copyright notice and this permission notice shall be */ |
| 20 | /* included in all copies or substantial portions of the Software. */ |
| 21 | /* */ |
| 22 | /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ |
| 23 | /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ |
| 24 | /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ |
| 25 | /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ |
| 26 | /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ |
| 27 | /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ |
| 28 | /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ |
| 29 | /**************************************************************************/ |
| 30 | |
| 31 | #include "lightmapper_rd.h" |
| 32 | |
| 33 | #include "core/string/print_string.h" |
| 34 | #include "lm_blendseams.glsl.gen.h" |
| 35 | #include "lm_compute.glsl.gen.h" |
| 36 | #include "lm_raster.glsl.gen.h" |
| 37 | |
| 38 | #include "core/config/project_settings.h" |
| 39 | #include "core/io/dir_access.h" |
| 40 | #include "core/math/geometry_2d.h" |
| 41 | #include "editor/file_system/editor_paths.h" |
| 42 | #include "editor/settings/editor_settings.h" |
| 43 | #include "servers/rendering/rendering_device_binds.h" |
| 44 | #include "servers/rendering/rendering_server_globals.h" |
| 45 | |
| 46 | #if defined(VULKAN_ENABLED) |
| 47 | #include "drivers/vulkan/rendering_context_driver_vulkan.h" |
| 48 | #endif |
| 49 | #if defined(METAL_ENABLED) |
| 50 | #include "drivers/metal/rendering_context_driver_metal.h" |
| 51 | #endif |
| 52 | |
| 53 | //uncomment this if you want to see textures from all the process saved |
| 54 | //#define DEBUG_TEXTURES |
| 55 | |
| 56 | void LightmapperRD::add_mesh(const MeshData &p_mesh) { |
| 57 | ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty()); |
| 58 | ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty()); |
| 59 | ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width()); |
| 60 | ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height()); |
| 61 | ERR_FAIL_COND(p_mesh.points.is_empty()); |
| 62 | MeshInstance mi; |
| 63 | mi.data = p_mesh; |
| 64 | mesh_instances.push_back(mi); |
| 65 | } |
| 66 | |
| 67 | void LightmapperRD::add_directional_light(const String &p_name, bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_angular_distance, float p_shadow_blur) { |
| 68 | Light l; |
| 69 | l.type = LIGHT_TYPE_DIRECTIONAL; |
| 70 | l.direction[0] = p_direction.x; |
| 71 | l.direction[1] = p_direction.y; |
| 72 | l.direction[2] = p_direction.z; |
| 73 | l.color[0] = p_color.r; |
| 74 | l.color[1] = p_color.g; |
| 75 | l.color[2] = p_color.b; |
| 76 | l.energy = p_energy; |
| 77 | l.indirect_energy = p_indirect_energy; |
| 78 | l.static_bake = p_static; |
| 79 | l.size = Math::tan(Math::deg_to_rad(p_angular_distance)); |
| 80 | l.shadow_blur = p_shadow_blur; |
| 81 | lights.push_back(l); |
| 82 | |
| 83 | LightMetadata md; |
| 84 | md.name = p_name; |
| 85 | md.type = LIGHT_TYPE_DIRECTIONAL; |
| 86 | light_metadata.push_back(md); |
| 87 | } |
| 88 | |
| 89 | void LightmapperRD::add_omni_light(const String &p_name, bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_size, float p_shadow_blur) { |
| 90 | Light l; |
| 91 | l.type = LIGHT_TYPE_OMNI; |
| 92 | l.position[0] = p_position.x; |
| 93 | l.position[1] = p_position.y; |
| 94 | l.position[2] = p_position.z; |
| 95 | l.range = p_range; |
| 96 | l.attenuation = p_attenuation; |
| 97 | l.color[0] = p_color.r; |
| 98 | l.color[1] = p_color.g; |
| 99 | l.color[2] = p_color.b; |
| 100 | l.energy = p_energy; |
| 101 | l.indirect_energy = p_indirect_energy; |
| 102 | l.static_bake = p_static; |
| 103 | l.size = p_size; |
| 104 | l.shadow_blur = p_shadow_blur; |
| 105 | lights.push_back(l); |
| 106 | |
| 107 | LightMetadata md; |
| 108 | md.name = p_name; |
| 109 | md.type = LIGHT_TYPE_OMNI; |
| 110 | light_metadata.push_back(md); |
| 111 | } |
| 112 | |
| 113 | void LightmapperRD::add_spot_light(const String &p_name, bool p_static, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size, float p_shadow_blur) { |
| 114 | Light l; |
| 115 | l.type = LIGHT_TYPE_SPOT; |
| 116 | l.position[0] = p_position.x; |
| 117 | l.position[1] = p_position.y; |
| 118 | l.position[2] = p_position.z; |
| 119 | l.direction[0] = p_direction.x; |
| 120 | l.direction[1] = p_direction.y; |
| 121 | l.direction[2] = p_direction.z; |
| 122 | l.range = p_range; |
| 123 | l.attenuation = p_attenuation; |
| 124 | l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle)); |
| 125 | l.inv_spot_attenuation = 1.0f / p_spot_attenuation; |
| 126 | l.color[0] = p_color.r; |
| 127 | l.color[1] = p_color.g; |
| 128 | l.color[2] = p_color.b; |
| 129 | l.energy = p_energy; |
| 130 | l.indirect_energy = p_indirect_energy; |
| 131 | l.static_bake = p_static; |
| 132 | l.size = p_size; |
| 133 | l.shadow_blur = p_shadow_blur; |
| 134 | lights.push_back(l); |
| 135 | |
| 136 | LightMetadata md; |
| 137 | md.name = p_name; |
| 138 | md.type = LIGHT_TYPE_SPOT; |
| 139 | light_metadata.push_back(md); |
| 140 | } |
| 141 | |
| 142 | void LightmapperRD::add_probe(const Vector3 &p_position) { |
| 143 | Probe probe; |
| 144 | probe.position[0] = p_position.x; |
| 145 | probe.position[1] = p_position.y; |
| 146 | probe.position[2] = p_position.z; |
| 147 | probe.position[3] = 0; |
| 148 | probe_positions.push_back(probe); |
| 149 | } |
| 150 | |
| 151 | void LightmapperRD::_plot_triangle_into_triangle_index_list(int p_size, const Vector3i &p_ofs, const AABB &p_bounds, const Vector3 p_points[3], uint32_t p_triangle_index, LocalVector<TriangleSort> &p_triangles_sort, uint32_t p_grid_size) { |
| 152 | int half_size = p_size / 2; |
| 153 | |
| 154 | for (int i = 0; i < 8; i++) { |
| 155 | AABB aabb = p_bounds; |
| 156 | aabb.size *= 0.5; |
| 157 | Vector3i n = p_ofs; |
| 158 | |
| 159 | if (i & 1) { |
| 160 | aabb.position.x += aabb.size.x; |
| 161 | n.x += half_size; |
| 162 | } |
| 163 | if (i & 2) { |
| 164 | aabb.position.y += aabb.size.y; |
| 165 | n.y += half_size; |
| 166 | } |
| 167 | if (i & 4) { |
| 168 | aabb.position.z += aabb.size.z; |
| 169 | n.z += half_size; |
| 170 | } |
| 171 | |
| 172 | { |
| 173 | Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test |
| 174 | |
| 175 | if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) { |
| 176 | //does not fit in child, go on |
| 177 | continue; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | if (half_size == 1) { |
| 182 | //got to the end |
| 183 | TriangleSort ts; |
| 184 | ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size); |
| 185 | ts.triangle_index = p_triangle_index; |
| 186 | ts.triangle_aabb.position = p_points[0]; |
| 187 | ts.triangle_aabb.size = Vector3(); |
| 188 | ts.triangle_aabb.expand_to(p_points[1]); |
| 189 | ts.triangle_aabb.expand_to(p_points[2]); |
| 190 | p_triangles_sort.push_back(ts); |
| 191 | } else { |
| 192 | _plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, p_triangles_sort, p_grid_size); |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | void LightmapperRD::_sort_triangle_clusters(uint32_t p_cluster_size, uint32_t p_cluster_index, uint32_t p_index_start, uint32_t p_count, LocalVector<TriangleSort> &p_triangle_sort, LocalVector<ClusterAABB> &p_cluster_aabb) { |
| 198 | if (p_count == 0) { |
| 199 | return; |
| 200 | } |
| 201 | |
| 202 | // Compute AABB for all triangles in the range. |
| 203 | SortArray<TriangleSort, TriangleSortAxis<0>> triangle_sorter_x; |
| 204 | SortArray<TriangleSort, TriangleSortAxis<1>> triangle_sorter_y; |
| 205 | SortArray<TriangleSort, TriangleSortAxis<2>> triangle_sorter_z; |
| 206 | AABB cluster_aabb = p_triangle_sort[p_index_start].triangle_aabb; |
| 207 | for (uint32_t i = 1; i < p_count; i++) { |
| 208 | cluster_aabb.merge_with(p_triangle_sort[p_index_start + i].triangle_aabb); |
| 209 | } |
| 210 | |
| 211 | if (p_count > p_cluster_size) { |
| 212 | int longest_axis_index = cluster_aabb.get_longest_axis_index(); |
| 213 | switch (longest_axis_index) { |
| 214 | case 0: |
| 215 | triangle_sorter_x.sort(&p_triangle_sort[p_index_start], p_count); |
| 216 | break; |
| 217 | case 1: |
| 218 | triangle_sorter_y.sort(&p_triangle_sort[p_index_start], p_count); |
| 219 | break; |
| 220 | case 2: |
| 221 | triangle_sorter_z.sort(&p_triangle_sort[p_index_start], p_count); |
| 222 | break; |
| 223 | default: |
| 224 | DEV_ASSERT(false && "Invalid axis returned by AABB."); |
| 225 | break; |
| 226 | } |
| 227 | |
| 228 | uint32_t left_cluster_count = next_power_of_2(p_count / 2); |
| 229 | left_cluster_count = MAX(left_cluster_count, p_cluster_size); |
| 230 | left_cluster_count = MIN(left_cluster_count, p_count); |
| 231 | _sort_triangle_clusters(p_cluster_size, p_cluster_index, p_index_start, left_cluster_count, p_triangle_sort, p_cluster_aabb); |
| 232 | |
| 233 | if (left_cluster_count < p_count) { |
| 234 | uint32_t cluster_index_right = p_cluster_index + (left_cluster_count / p_cluster_size); |
| 235 | _sort_triangle_clusters(p_cluster_size, cluster_index_right, p_index_start + left_cluster_count, p_count - left_cluster_count, p_triangle_sort, p_cluster_aabb); |
| 236 | } |
| 237 | } else { |
| 238 | ClusterAABB &aabb = p_cluster_aabb[p_cluster_index]; |
| 239 | Vector3 aabb_end = cluster_aabb.get_end(); |
| 240 | aabb.min_bounds[0] = cluster_aabb.position.x; |
| 241 | aabb.min_bounds[1] = cluster_aabb.position.y; |
| 242 | aabb.min_bounds[2] = cluster_aabb.position.z; |
| 243 | aabb.max_bounds[0] = aabb_end.x; |
| 244 | aabb.max_bounds[1] = aabb_end.y; |
| 245 | aabb.max_bounds[2] = aabb_end.z; |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_size, int p_denoiser_range, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, float p_supersampling_factor, BakeStepFunc p_step_function, void *p_bake_userdata) { |
| 250 | Vector<Size2i> sizes; |
| 251 | |
| 252 | for (int m_i = 0; m_i < mesh_instances.size(); m_i++) { |
| 253 | MeshInstance &mi = mesh_instances.write[m_i]; |
| 254 | Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()); |
| 255 | sizes.push_back(s); |
| 256 | atlas_size = atlas_size.max(s + Size2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor); |
| 257 | } |
| 258 | |
| 259 | int max = nearest_power_of_2_templated(atlas_size.width); |
| 260 | max = MAX(max, nearest_power_of_2_templated(atlas_size.height)); |
| 261 | |
| 262 | if (max > p_max_texture_size) { |
| 263 | return BAKE_ERROR_TEXTURE_EXCEEDS_MAX_SIZE; |
| 264 | } |
| 265 | |
| 266 | if (p_step_function) { |
| 267 | if (p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true)) { |
| 268 | return BAKE_ERROR_USER_ABORTED; |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | atlas_size = Size2i(max, max); |
| 273 | |
| 274 | Size2i best_atlas_size; |
| 275 | int best_atlas_slices = 0; |
| 276 | int best_atlas_memory = 0x7FFFFFFF; |
| 277 | Vector<Vector3i> best_atlas_offsets; |
| 278 | |
| 279 | // Determine best texture array atlas size by bruteforce fitting. |
| 280 | while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) { |
| 281 | Vector<Vector2i> source_sizes; |
| 282 | Vector<int> source_indices; |
| 283 | source_sizes.resize(sizes.size()); |
| 284 | source_indices.resize(sizes.size()); |
| 285 | for (int i = 0; i < source_indices.size(); i++) { |
| 286 | // Add padding between lightmaps. |
| 287 | // Scale the padding if the lightmap will be downsampled at the end of the baking process |
| 288 | // Otherwise the padding would be insufficient. |
| 289 | source_sizes.write[i] = sizes[i] + Vector2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor; |
| 290 | source_indices.write[i] = i; |
| 291 | } |
| 292 | Vector<Vector3i> atlas_offsets; |
| 293 | atlas_offsets.resize(source_sizes.size()); |
| 294 | |
| 295 | // Ensure the sizes can all fit into a single atlas layer. |
| 296 | // This should always happen, and this check is only in place to prevent an infinite loop. |
| 297 | for (int i = 0; i < source_sizes.size(); i++) { |
| 298 | if (source_sizes[i] > atlas_size) { |
| 299 | return BAKE_ERROR_ATLAS_TOO_SMALL; |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | int slices = 0; |
| 304 | |
| 305 | while (source_sizes.size() > 0) { |
| 306 | Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size); |
| 307 | Vector<int> new_indices; |
| 308 | Vector<Vector2i> new_sources; |
| 309 | for (int i = 0; i < offsets.size(); i++) { |
| 310 | Vector3i ofs = offsets[i]; |
| 311 | int sidx = source_indices[i]; |
| 312 | if (ofs.z > 0) { |
| 313 | //valid |
| 314 | ofs.z = slices; |
| 315 | atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region |
| 316 | } else { |
| 317 | new_indices.push_back(sidx); |
| 318 | new_sources.push_back(source_sizes[i]); |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | source_sizes = new_sources; |
| 323 | source_indices = new_indices; |
| 324 | slices++; |
| 325 | } |
| 326 | |
| 327 | int mem_used = atlas_size.x * atlas_size.y * slices; |
| 328 | if (mem_used < best_atlas_memory) { |
| 329 | best_atlas_size = atlas_size; |
| 330 | best_atlas_offsets = atlas_offsets; |
| 331 | best_atlas_slices = slices; |
| 332 | best_atlas_memory = mem_used; |
| 333 | } |
| 334 | |
| 335 | if (atlas_size.width == atlas_size.height) { |
| 336 | atlas_size.width *= 2; |
| 337 | } else { |
| 338 | atlas_size.height *= 2; |
| 339 | } |
| 340 | } |
| 341 | atlas_size = best_atlas_size; |
| 342 | atlas_slices = best_atlas_slices; |
| 343 | |
| 344 | // apply the offsets and slice to all images, and also blit albedo and emission |
| 345 | albedo_images.resize(atlas_slices); |
| 346 | emission_images.resize(atlas_slices); |
| 347 | |
| 348 | if (p_step_function) { |
| 349 | if (p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true)) { |
| 350 | return BAKE_ERROR_USER_ABORTED; |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | for (int i = 0; i < atlas_slices; i++) { |
| 355 | Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8); |
| 356 | albedo->set_as_black(); |
| 357 | albedo_images.write[i] = albedo; |
| 358 | |
| 359 | Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH); |
| 360 | emission->set_as_black(); |
| 361 | emission_images.write[i] = emission; |
| 362 | } |
| 363 | |
| 364 | //assign uv positions |
| 365 | |
| 366 | for (int m_i = 0; m_i < mesh_instances.size(); m_i++) { |
| 367 | MeshInstance &mi = mesh_instances.write[m_i]; |
| 368 | mi.offset.x = best_atlas_offsets[m_i].x; |
| 369 | mi.offset.y = best_atlas_offsets[m_i].y; |
| 370 | mi.slice = best_atlas_offsets[m_i].z; |
| 371 | albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset); |
| 372 | emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset); |
| 373 | } |
| 374 | |
| 375 | return BAKE_OK; |
| 376 | } |
| 377 | |
| 378 | void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, uint32_t p_cluster_size, Vector<Probe> &p_probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &r_triangle_indices_buffer, RID &r_cluster_indices_buffer, RID &r_cluster_aabbs_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) { |
| 379 | HashMap<Vertex, uint32_t, VertexHash> vertex_map; |
| 380 | |
| 381 | //fill triangles array and vertex array |
| 382 | LocalVector<Triangle> triangles; |
| 383 | LocalVector<Vertex> vertex_array; |
| 384 | LocalVector<Seam> seams; |
| 385 | |
| 386 | slice_triangle_count.resize(atlas_slices); |
| 387 | slice_seam_count.resize(atlas_slices); |
| 388 | |
| 389 | for (int i = 0; i < atlas_slices; i++) { |
| 390 | slice_triangle_count.write[i] = 0; |
| 391 | slice_seam_count.write[i] = 0; |
| 392 | } |
| 393 | |
| 394 | bounds = AABB(); |
| 395 | |
| 396 | for (int m_i = 0; m_i < mesh_instances.size(); m_i++) { |
| 397 | if (p_step_function) { |
| 398 | float p = float(m_i + 1) / MAX(1, mesh_instances.size()) * 0.1; |
| 399 | p_step_function(0.3 + p, vformat(RTR("Plotting mesh into acceleration structure %d/%d"), m_i + 1, mesh_instances.size()), p_bake_userdata, false); |
| 400 | } |
| 401 | |
| 402 | HashMap<Edge, EdgeUV2, EdgeHash> edges; |
| 403 | |
| 404 | MeshInstance &mi = mesh_instances.write[m_i]; |
| 405 | |
| 406 | Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size); |
| 407 | Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size); |
| 408 | if (m_i == 0) { |
| 409 | bounds.position = mi.data.points[0]; |
| 410 | } |
| 411 | |
| 412 | for (int i = 0; i < mi.data.points.size(); i += 3) { |
| 413 | Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] }; |
| 414 | Vector2 uvs[3] = { mi.data.uv2[i + 0] * uv_scale + uv_offset, mi.data.uv2[i + 1] * uv_scale + uv_offset, mi.data.uv2[i + 2] * uv_scale + uv_offset }; |
| 415 | Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] }; |
| 416 | |
| 417 | AABB taabb; |
| 418 | Triangle t; |
| 419 | t.slice = mi.slice; |
| 420 | for (int k = 0; k < 3; k++) { |
| 421 | bounds.expand_to(vtxs[k]); |
| 422 | |
| 423 | Vertex v; |
| 424 | v.position[0] = vtxs[k].x; |
| 425 | v.position[1] = vtxs[k].y; |
| 426 | v.position[2] = vtxs[k].z; |
| 427 | v.uv[0] = uvs[k].x; |
| 428 | v.uv[1] = uvs[k].y; |
| 429 | v.normal_xy[0] = normal[k].x; |
| 430 | v.normal_xy[1] = normal[k].y; |
| 431 | v.normal_z = normal[k].z; |
| 432 | |
| 433 | uint32_t *indexptr = vertex_map.getptr(v); |
| 434 | |
| 435 | if (indexptr) { |
| 436 | t.indices[k] = *indexptr; |
| 437 | } else { |
| 438 | uint32_t new_index = vertex_map.size(); |
| 439 | t.indices[k] = new_index; |
| 440 | vertex_map[v] = new_index; |
| 441 | vertex_array.push_back(v); |
| 442 | } |
| 443 | |
| 444 | if (k == 0) { |
| 445 | taabb.position = vtxs[k]; |
| 446 | } else { |
| 447 | taabb.expand_to(vtxs[k]); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | //compute seams that will need to be blended later |
| 452 | for (int k = 0; k < 3; k++) { |
| 453 | int n = (k + 1) % 3; |
| 454 | |
| 455 | Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]); |
| 456 | Vector2i edge_indices(t.indices[k], t.indices[n]); |
| 457 | EdgeUV2 uv2(uvs[k], uvs[n], edge_indices); |
| 458 | |
| 459 | if (edge.b == edge.a) { |
| 460 | continue; //degenerate, somehow |
| 461 | } |
| 462 | if (edge.b < edge.a) { |
| 463 | SWAP(edge.a, edge.b); |
| 464 | SWAP(edge.na, edge.nb); |
| 465 | SWAP(uv2.a, uv2.b); |
| 466 | SWAP(uv2.indices.x, uv2.indices.y); |
| 467 | SWAP(edge_indices.x, edge_indices.y); |
| 468 | } |
| 469 | |
| 470 | EdgeUV2 *euv2 = edges.getptr(edge); |
| 471 | if (!euv2) { |
| 472 | edges[edge] = uv2; |
| 473 | } else { |
| 474 | if (*euv2 == uv2) { |
| 475 | continue; // seam shared UV space, no need to blend |
| 476 | } |
| 477 | if (euv2->seam_found) { |
| 478 | continue; //bad geometry |
| 479 | } |
| 480 | |
| 481 | Seam seam; |
| 482 | seam.a = edge_indices; |
| 483 | seam.b = euv2->indices; |
| 484 | seam.slice = mi.slice; |
| 485 | seams.push_back(seam); |
| 486 | slice_seam_count.write[mi.slice]++; |
| 487 | euv2->seam_found = true; |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | t.min_bounds[0] = taabb.position.x; |
| 492 | t.min_bounds[1] = taabb.position.y; |
| 493 | t.min_bounds[2] = taabb.position.z; |
| 494 | t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001); |
| 495 | t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001); |
| 496 | t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001); |
| 497 | |
| 498 | t.cull_mode = RS::CULL_MODE_BACK; |
| 499 | |
| 500 | RID material = mi.data.material[i]; |
| 501 | if (material.is_valid()) { |
| 502 | t.cull_mode = RSG::material_storage->material_get_cull_mode(material); |
| 503 | } |
| 504 | t.pad1 = 0; //make valgrind not complain |
| 505 | triangles.push_back(t); |
| 506 | slice_triangle_count.write[t.slice]++; |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | //also consider probe positions for bounds |
| 511 | for (int i = 0; i < p_probe_positions.size(); i++) { |
| 512 | Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]); |
| 513 | bounds.expand_to(pp); |
| 514 | } |
| 515 | bounds.grow_by(0.1); //grow a bit to avoid numerical error |
| 516 | |
| 517 | triangles.sort(); //sort by slice |
| 518 | seams.sort(); |
| 519 | |
| 520 | if (p_step_function) { |
| 521 | p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true); |
| 522 | } |
| 523 | |
| 524 | //fill list of triangles in grid |
| 525 | LocalVector<TriangleSort> triangle_sort; |
| 526 | for (uint32_t i = 0; i < triangles.size(); i++) { |
| 527 | const Triangle &t = triangles[i]; |
| 528 | Vector3 face[3] = { |
| 529 | Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]), |
| 530 | Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]), |
| 531 | Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2]) |
| 532 | }; |
| 533 | _plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size); |
| 534 | } |
| 535 | //sort it |
| 536 | triangle_sort.sort(); |
| 537 | |
| 538 | LocalVector<uint32_t> cluster_indices; |
| 539 | LocalVector<ClusterAABB> cluster_aabbs; |
| 540 | Vector<uint32_t> triangle_indices; |
| 541 | triangle_indices.resize(triangle_sort.size()); |
| 542 | Vector<uint32_t> grid_indices; |
| 543 | grid_indices.resize(grid_size * grid_size * grid_size * 2); |
| 544 | memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t)); |
| 545 | |
| 546 | { |
| 547 | // Fill grid with cell indices. |
| 548 | uint32_t last_cell = 0xFFFFFFFF; |
| 549 | uint32_t *giw = grid_indices.ptrw(); |
| 550 | uint32_t cluster_count = 0; |
| 551 | uint32_t solid_cell_count = 0; |
| 552 | for (uint32_t i = 0; i < triangle_sort.size(); i++) { |
| 553 | uint32_t cell = triangle_sort[i].cell_index; |
| 554 | if (cell != last_cell) { |
| 555 | giw[cell * 2 + 1] = solid_cell_count; |
| 556 | solid_cell_count++; |
| 557 | } |
| 558 | |
| 559 | if ((giw[cell * 2] % p_cluster_size) == 0) { |
| 560 | // Add an extra cluster every time the triangle counter reaches a multiple of the cluster size. |
| 561 | cluster_count++; |
| 562 | } |
| 563 | |
| 564 | giw[cell * 2]++; |
| 565 | last_cell = cell; |
| 566 | } |
| 567 | |
| 568 | // Build fixed-size triangle clusters for all the cells to speed up the traversal. A cell can hold multiple clusters that each contain a fixed |
| 569 | // amount of triangles and an AABB. The tracer will check against the AABBs first to know whether it needs to visit the cell's triangles. |
| 570 | // |
| 571 | // The building algorithm will divide the triangles recursively contained inside each cell, sorting by the longest axis of the AABB on each step. |
| 572 | // |
| 573 | // - If the amount of triangles is less or equal to the cluster size, the AABB will be stored and the algorithm stops. |
| 574 | // |
| 575 | // - The division by two is increased to the next power of two of half the amount of triangles (with cluster size as the minimum value) to |
| 576 | // ensure the first half always fills the cluster. |
| 577 | |
| 578 | cluster_indices.resize(solid_cell_count * 2); |
| 579 | cluster_aabbs.resize(cluster_count); |
| 580 | |
| 581 | uint32_t i = 0; |
| 582 | uint32_t cluster_index = 0; |
| 583 | uint32_t solid_cell_index = 0; |
| 584 | uint32_t *tiw = triangle_indices.ptrw(); |
| 585 | while (i < triangle_sort.size()) { |
| 586 | cluster_indices[solid_cell_index * 2] = cluster_index; |
| 587 | cluster_indices[solid_cell_index * 2 + 1] = i; |
| 588 | |
| 589 | uint32_t cell = triangle_sort[i].cell_index; |
| 590 | uint32_t triangle_count = giw[cell * 2]; |
| 591 | uint32_t cell_cluster_count = (triangle_count + p_cluster_size - 1) / p_cluster_size; |
| 592 | _sort_triangle_clusters(p_cluster_size, cluster_index, i, triangle_count, triangle_sort, cluster_aabbs); |
| 593 | |
| 594 | for (uint32_t j = 0; j < triangle_count; j++) { |
| 595 | tiw[i + j] = triangle_sort[i + j].triangle_index; |
| 596 | } |
| 597 | |
| 598 | i += triangle_count; |
| 599 | cluster_index += cell_cluster_count; |
| 600 | solid_cell_index++; |
| 601 | } |
| 602 | } |
| 603 | #if 0 |
| 604 | for (int i = 0; i < grid_size; i++) { |
| 605 | for (int j = 0; j < grid_size; j++) { |
| 606 | for (int k = 0; k < grid_size; k++) { |
| 607 | uint32_t index = i * (grid_size * grid_size) + j * grid_size + k; |
| 608 | grid_indices.write[index * 2] = float(i) / grid_size * 255; |
| 609 | grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255; |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | #endif |
| 614 | |
| 615 | #if 0 |
| 616 | for (int i = 0; i < grid_size; i++) { |
| 617 | Vector<uint8_t> grid_usage; |
| 618 | grid_usage.resize(grid_size * grid_size); |
| 619 | for (int j = 0; j < grid_usage.size(); j++) { |
| 620 | uint32_t ofs = i * grid_size * grid_size + j; |
| 621 | uint32_t count = grid_indices[ofs * 2]; |
| 622 | grid_usage.write[j] = count > 0 ? 255 : 0; |
| 623 | } |
| 624 | |
| 625 | Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage); |
| 626 | img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png"); |
| 627 | } |
| 628 | #endif |
| 629 | |
| 630 | /*****************************/ |
| 631 | /*** CREATE GPU STRUCTURES ***/ |
| 632 | /*****************************/ |
| 633 | |
| 634 | lights.sort(); |
| 635 | light_metadata.sort(); |
| 636 | |
| 637 | Vector<Vector2i> seam_buffer_vec; |
| 638 | seam_buffer_vec.resize(seams.size() * 2); |
| 639 | for (uint32_t i = 0; i < seams.size(); i++) { |
| 640 | seam_buffer_vec.write[i * 2 + 0] = seams[i].a; |
| 641 | seam_buffer_vec.write[i * 2 + 1] = seams[i].b; |
| 642 | } |
| 643 | |
| 644 | { //buffers |
| 645 | vertex_buffer = rd->storage_buffer_create(vertex_array.size() * sizeof(Vertex), vertex_array.span().reinterpret<uint8_t>()); |
| 646 | |
| 647 | triangle_buffer = rd->storage_buffer_create(triangles.size() * sizeof(Triangle), triangles.span().reinterpret<uint8_t>()); |
| 648 | |
| 649 | r_triangle_indices_buffer = rd->storage_buffer_create(triangle_indices.size() * sizeof(uint32_t), triangle_indices.span().reinterpret<uint8_t>()); |
| 650 | |
| 651 | r_cluster_indices_buffer = rd->storage_buffer_create(cluster_indices.size() * sizeof(uint32_t), cluster_indices.span().reinterpret<uint8_t>()); |
| 652 | |
| 653 | r_cluster_aabbs_buffer = rd->storage_buffer_create(cluster_aabbs.size() * sizeof(ClusterAABB), cluster_aabbs.span().reinterpret<uint8_t>()); |
| 654 | |
| 655 | // Even when there are no lights, the buffer must exist. |
| 656 | static const Light empty_lights[1]; |
| 657 | Span<uint8_t> lb = (lights.is_empty() ? Span(empty_lights) : lights.span()).reinterpret<uint8_t>(); |
| 658 | lights_buffer = rd->storage_buffer_create(lb.size(), lb); |
| 659 | |
| 660 | // Even when there are no seams, the buffer must exist. |
| 661 | static const Vector2i empty_seams[2]; |
| 662 | Span<uint8_t> sb = (seam_buffer_vec.is_empty() ? Span(empty_seams) : seam_buffer_vec.span()).reinterpret<uint8_t>(); |
| 663 | seams_buffer = rd->storage_buffer_create(sb.size(), sb); |
| 664 | |
| 665 | // Even when there are no probes, the buffer must exist. |
| 666 | static const Probe empty_probes[1]; |
| 667 | Span<uint8_t> pb = (p_probe_positions.is_empty() ? Span(empty_probes) : p_probe_positions.span()).reinterpret<uint8_t>(); |
| 668 | probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb); |
| 669 | } |
| 670 | |
| 671 | { //grid |
| 672 | |
| 673 | RD::TextureFormat tf; |
| 674 | tf.width = grid_size; |
| 675 | tf.height = grid_size; |
| 676 | tf.depth = grid_size; |
| 677 | tf.texture_type = RD::TEXTURE_TYPE_3D; |
| 678 | tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT; |
| 679 | |
| 680 | Vector<Vector<uint8_t>> texdata; |
| 681 | texdata.resize(1); |
| 682 | //grid and indices |
| 683 | tf.format = RD::DATA_FORMAT_R32G32_UINT; |
| 684 | texdata.write[0] = grid_indices.to_byte_array(); |
| 685 | grid_texture = rd->texture_create(tf, RD::TextureView(), texdata); |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | void LightmapperRD::_raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform) { |
| 690 | Vector<RID> framebuffers; |
| 691 | |
| 692 | for (int i = 0; i < atlas_slices; i++) { |
| 693 | RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0); |
| 694 | RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0); |
| 695 | RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0); |
| 696 | Vector<RID> fb; |
| 697 | fb.push_back(slice_pos_tex); |
| 698 | fb.push_back(slice_norm_tex); |
| 699 | fb.push_back(slice_unoc_tex); |
| 700 | fb.push_back(raster_depth_buffer); |
| 701 | framebuffers.push_back(rd->framebuffer_create(fb)); |
| 702 | } |
| 703 | |
| 704 | RD::PipelineDepthStencilState ds; |
| 705 | ds.enable_depth_test = true; |
| 706 | ds.enable_depth_write = true; |
| 707 | ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice |
| 708 | |
| 709 | RID raster_pipeline = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0); |
| 710 | RID raster_pipeline_wire; |
| 711 | { |
| 712 | RD::PipelineRasterizationState rw; |
| 713 | rw.wireframe = true; |
| 714 | raster_pipeline_wire = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, rw, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0); |
| 715 | } |
| 716 | |
| 717 | uint32_t triangle_offset = 0; |
| 718 | Vector<Color> clear_colors; |
| 719 | clear_colors.push_back(Color(0, 0, 0, 0)); |
| 720 | clear_colors.push_back(Color(0, 0, 0, 0)); |
| 721 | clear_colors.push_back(Color(0, 0, 0, 0)); |
| 722 | |
| 723 | for (int i = 0; i < atlas_slices; i++) { |
| 724 | RasterPushConstant raster_push_constant; |
| 725 | raster_push_constant.atlas_size[0] = atlas_size.x; |
| 726 | raster_push_constant.atlas_size[1] = atlas_size.y; |
| 727 | raster_push_constant.base_triangle = triangle_offset; |
| 728 | raster_push_constant.to_cell_offset[0] = bounds.position.x; |
| 729 | raster_push_constant.to_cell_offset[1] = bounds.position.y; |
| 730 | raster_push_constant.to_cell_offset[2] = bounds.position.z; |
| 731 | raster_push_constant.bias = p_bias; |
| 732 | raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size); |
| 733 | raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size); |
| 734 | raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size); |
| 735 | raster_push_constant.grid_size[0] = grid_size; |
| 736 | raster_push_constant.grid_size[1] = grid_size; |
| 737 | raster_push_constant.grid_size[2] = grid_size; |
| 738 | |
| 739 | // Half pixel offset is required so the rasterizer doesn't output face edges directly aligned into pixels. |
| 740 | // This fixes artifacts where the pixel would be traced from the edge of a face, causing half the rays to |
| 741 | // be outside of the boundaries of the geometry. See <https://github.com/godotengine/godot/issues/69126>. |
| 742 | raster_push_constant.uv_offset[0] = -0.5f / float(atlas_size.x); |
| 743 | raster_push_constant.uv_offset[1] = -0.5f / float(atlas_size.y); |
| 744 | |
| 745 | RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::DRAW_CLEAR_ALL, clear_colors, 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS); |
| 746 | //draw opaque |
| 747 | rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline); |
| 748 | rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0); |
| 749 | rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant)); |
| 750 | rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3); |
| 751 | //draw wire |
| 752 | rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire); |
| 753 | rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0); |
| 754 | rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant)); |
| 755 | rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3); |
| 756 | |
| 757 | rd->draw_list_end(); |
| 758 | |
| 759 | triangle_offset += slice_triangle_count[i]; |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | static Vector<RD::Uniform> dilate_or_denoise_common_uniforms(RID &p_source_light_tex, RID &p_dest_light_tex) { |
| 764 | Vector<RD::Uniform> uniforms; |
| 765 | { |
| 766 | RD::Uniform u; |
| 767 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 768 | u.binding = 0; |
| 769 | u.append_id(p_dest_light_tex); |
| 770 | uniforms.push_back(u); |
| 771 | } |
| 772 | { |
| 773 | RD::Uniform u; |
| 774 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 775 | u.binding = 1; |
| 776 | u.append_id(p_source_light_tex); |
| 777 | uniforms.push_back(u); |
| 778 | } |
| 779 | |
| 780 | return uniforms; |
| 781 | } |
| 782 | |
| 783 | LightmapperRD::BakeError LightmapperRD::_dilate(RenderingDevice *rd, Ref<RDShaderFile> &compute_shader, RID &compute_base_uniform_set, PushConstant &push_constant, RID &source_light_tex, RID &dest_light_tex, const Size2i &atlas_size, int atlas_slices) { |
| 784 | Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex); |
| 785 | |
| 786 | RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate")); |
| 787 | ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen |
| 788 | RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate); |
| 789 | |
| 790 | RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1); |
| 791 | |
| 792 | RD::ComputeListID compute_list = rd->compute_list_begin(); |
| 793 | rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline); |
| 794 | rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0); |
| 795 | rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1); |
| 796 | push_constant.region_ofs[0] = 0; |
| 797 | push_constant.region_ofs[1] = 0; |
| 798 | Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size |
| 799 | |
| 800 | for (int i = 0; i < atlas_slices; i++) { |
| 801 | push_constant.atlas_slice = i; |
| 802 | rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant)); |
| 803 | rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z); |
| 804 | //no barrier, let them run all together |
| 805 | } |
| 806 | rd->compute_list_end(); |
| 807 | rd->free_rid(compute_shader_dilate); |
| 808 | |
| 809 | #ifdef DEBUG_TEXTURES |
| 810 | for (int i = 0; i < atlas_slices; i++) { |
| 811 | Vector<uint8_t> s = rd->texture_get_data(source_light_tex, i); |
| 812 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); |
| 813 | img->convert(Image::FORMAT_RGBA8); |
| 814 | img->save_png("res://5_dilated_" + itos(i) + ".png"); |
| 815 | } |
| 816 | #endif |
| 817 | return BAKE_OK; |
| 818 | } |
| 819 | |
| 820 | LightmapperRD::BakeError LightmapperRD::_pack_l1(RenderingDevice *rd, Ref<RDShaderFile> &compute_shader, RID &compute_base_uniform_set, PushConstant &push_constant, RID &source_light_tex, RID &dest_light_tex, const Size2i &atlas_size, int atlas_slices) { |
| 821 | Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex); |
| 822 | |
| 823 | RID compute_shader_pack = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("pack_coeffs")); |
| 824 | ERR_FAIL_COND_V(compute_shader_pack.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen |
| 825 | RID compute_shader_pack_pipeline = rd->compute_pipeline_create(compute_shader_pack); |
| 826 | |
| 827 | RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_pack, 1); |
| 828 | |
| 829 | RD::ComputeListID compute_list = rd->compute_list_begin(); |
| 830 | rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_pack_pipeline); |
| 831 | rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0); |
| 832 | rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1); |
| 833 | push_constant.region_ofs[0] = 0; |
| 834 | push_constant.region_ofs[1] = 0; |
| 835 | Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size |
| 836 | |
| 837 | for (int i = 0; i < atlas_slices; i++) { |
| 838 | push_constant.atlas_slice = i; |
| 839 | rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant)); |
| 840 | rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z); |
| 841 | //no barrier, let them run all together |
| 842 | } |
| 843 | rd->compute_list_end(); |
| 844 | rd->free_rid(compute_shader_pack); |
| 845 | |
| 846 | return BAKE_OK; |
| 847 | } |
| 848 | |
| 849 | Error LightmapperRD::_store_pfm(RenderingDevice *p_rd, RID p_atlas_tex, int p_index, const Size2i &p_atlas_size, const String &p_name, bool p_shadowmask) { |
| 850 | Vector<uint8_t> data = p_rd->texture_get_data(p_atlas_tex, p_index); |
| 851 | Ref<Image> img = Image::create_from_data(p_atlas_size.width, p_atlas_size.height, false, p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH, data); |
| 852 | img->convert(Image::FORMAT_RGBF); |
| 853 | Vector<uint8_t> data_float = img->get_data(); |
| 854 | |
| 855 | Error err = OK; |
| 856 | Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::WRITE, &err); |
| 857 | ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save PFN at path: '%s'.", p_name)); |
| 858 | file->store_line("PF"); |
| 859 | file->store_line(vformat("%d %d", img->get_width(), img->get_height())); |
| 860 | #ifdef BIG_ENDIAN_ENABLED |
| 861 | file->store_line("1.0"); |
| 862 | #else |
| 863 | file->store_line("-1.0"); |
| 864 | #endif |
| 865 | file->store_buffer(data_float); |
| 866 | file->close(); |
| 867 | |
| 868 | return OK; |
| 869 | } |
| 870 | |
| 871 | Ref<Image> LightmapperRD::_read_pfm(const String &p_name, bool p_shadowmask) { |
| 872 | Error err = OK; |
| 873 | Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::READ, &err); |
| 874 | ERR_FAIL_COND_V_MSG(err, Ref<Image>(), vformat("Can't load PFM at path: '%s'.", p_name)); |
| 875 | ERR_FAIL_COND_V(file->get_line() != "PF", Ref<Image>()); |
| 876 | |
| 877 | Vector<String> new_size = file->get_line().split(" "); |
| 878 | ERR_FAIL_COND_V(new_size.size() != 2, Ref<Image>()); |
| 879 | int new_width = new_size[0].to_int(); |
| 880 | int new_height = new_size[1].to_int(); |
| 881 | |
| 882 | float endian = file->get_line().to_float(); |
| 883 | Vector<uint8_t> new_data = file->get_buffer(file->get_length() - file->get_position()); |
| 884 | file->close(); |
| 885 | |
| 886 | #ifdef BIG_ENDIAN_ENABLED |
| 887 | if (unlikely(endian < 0.0)) { |
| 888 | uint32_t count = new_data.size() / 4; |
| 889 | uint16_t *dst = (uint16_t *)new_data.ptrw(); |
| 890 | for (uint32_t j = 0; j < count; j++) { |
| 891 | dst[j * 4] = BSWAP32(dst[j * 4]); |
| 892 | } |
| 893 | } |
| 894 | #else |
| 895 | if (unlikely(endian > 0.0)) { |
| 896 | uint32_t count = new_data.size() / 4; |
| 897 | uint16_t *dst = (uint16_t *)new_data.ptrw(); |
| 898 | for (uint32_t j = 0; j < count; j++) { |
| 899 | dst[j * 4] = BSWAP32(dst[j * 4]); |
| 900 | } |
| 901 | } |
| 902 | #endif |
| 903 | Ref<Image> img = Image::create_from_data(new_width, new_height, false, Image::FORMAT_RGBF, new_data); |
| 904 | img->convert(p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH); |
| 905 | return img; |
| 906 | } |
| 907 | |
| 908 | LightmapperRD::BakeError LightmapperRD::_denoise_oidn(RenderingDevice *p_rd, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, bool p_shadowmask, const String &p_exe) { |
| 909 | Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); |
| 910 | |
| 911 | for (int i = 0; i < p_atlas_slices; i++) { |
| 912 | String fname_norm_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_norm_%d.pfm", i)); |
| 913 | _store_pfm(p_rd, p_source_normal_tex, i, p_atlas_size, fname_norm_in, false); |
| 914 | |
| 915 | for (int j = 0; j < (p_bake_sh ? 4 : 1); j++) { |
| 916 | int index = i * (p_bake_sh ? 4 : 1) + j; |
| 917 | String fname_light_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_light_%d.pfm", index)); |
| 918 | String fname_out = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_denoised_%d.pfm", index)); |
| 919 | |
| 920 | _store_pfm(p_rd, p_source_light_tex, index, p_atlas_size, fname_light_in, p_shadowmask); |
| 921 | |
| 922 | List<String> args; |
| 923 | args.push_back("--device"); |
| 924 | args.push_back("default"); |
| 925 | |
| 926 | args.push_back("--filter"); |
| 927 | args.push_back("RTLightmap"); |
| 928 | |
| 929 | args.push_back(p_shadowmask ? "--ldr" : "--hdr"); |
| 930 | args.push_back(fname_light_in); |
| 931 | |
| 932 | args.push_back("--nrm"); |
| 933 | args.push_back(fname_norm_in); |
| 934 | |
| 935 | args.push_back("--output"); |
| 936 | args.push_back(fname_out); |
| 937 | |
| 938 | String str; |
| 939 | int exitcode = 0; |
| 940 | |
| 941 | Error err = OS::get_singleton()->execute(p_exe, args, &str, &exitcode, true); |
| 942 | |
| 943 | da->remove(fname_light_in); |
| 944 | |
| 945 | if (err != OK || exitcode != 0) { |
| 946 | da->remove(fname_out); |
| 947 | print_verbose(str); |
| 948 | ERR_FAIL_V_MSG(BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, vformat("OIDN denoiser failed, return code: %d", exitcode)); |
| 949 | } |
| 950 | |
| 951 | Ref<Image> img = _read_pfm(fname_out, p_shadowmask); |
| 952 | da->remove(fname_out); |
| 953 | |
| 954 | ERR_FAIL_COND_V(img.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 955 | |
| 956 | Vector<uint8_t> old_data = p_rd->texture_get_data(p_source_light_tex, index); |
| 957 | Vector<uint8_t> new_data = img->get_data(); |
| 958 | img.unref(); // Avoid copy on write. |
| 959 | |
| 960 | uint32_t count = old_data.size() / 2; |
| 961 | const uint16_t *src = (const uint16_t *)old_data.ptr(); |
| 962 | uint16_t *dst = (uint16_t *)new_data.ptrw(); |
| 963 | for (uint32_t k = 0; k < count; k += 4) { |
| 964 | dst[k + 3] = src[k + 3]; |
| 965 | } |
| 966 | |
| 967 | p_rd->texture_update(p_dest_light_tex, index, new_data); |
| 968 | } |
| 969 | da->remove(fname_norm_in); |
| 970 | } |
| 971 | return BAKE_OK; |
| 972 | } |
| 973 | |
| 974 | LightmapperRD::BakeError LightmapperRD::_denoise(RenderingDevice *p_rd, Ref<RDShaderFile> &p_compute_shader, const RID &p_compute_base_uniform_set, PushConstant &p_push_constant, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, RID p_unocclude_tex, float p_denoiser_strength, int p_denoiser_range, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, BakeStepFunc p_step_function, void *p_bake_userdata) { |
| 975 | RID denoise_params_buffer = p_rd->uniform_buffer_create(sizeof(DenoiseParams)); |
| 976 | DenoiseParams denoise_params; |
| 977 | denoise_params.spatial_bandwidth = 5.0f; |
| 978 | denoise_params.light_bandwidth = p_denoiser_strength; |
| 979 | denoise_params.albedo_bandwidth = 1.0f; |
| 980 | denoise_params.normal_bandwidth = 0.1f; |
| 981 | denoise_params.filter_strength = 10.0f; |
| 982 | denoise_params.half_search_window = p_denoiser_range; |
| 983 | denoise_params.slice_count = p_bake_sh ? 4 : 1; |
| 984 | p_rd->buffer_update(denoise_params_buffer, 0, sizeof(DenoiseParams), &denoise_params); |
| 985 | |
| 986 | Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(p_source_light_tex, p_dest_light_tex); |
| 987 | { |
| 988 | RD::Uniform u; |
| 989 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 990 | u.binding = 2; |
| 991 | u.append_id(p_source_normal_tex); |
| 992 | uniforms.push_back(u); |
| 993 | } |
| 994 | { |
| 995 | RD::Uniform u; |
| 996 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 997 | u.binding = 3; |
| 998 | u.append_id(p_unocclude_tex); |
| 999 | uniforms.push_back(u); |
| 1000 | } |
| 1001 | { |
| 1002 | RD::Uniform u; |
| 1003 | u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER; |
| 1004 | u.binding = 4; |
| 1005 | u.append_id(denoise_params_buffer); |
| 1006 | uniforms.push_back(u); |
| 1007 | } |
| 1008 | |
| 1009 | RID compute_shader_denoise = p_rd->shader_create_from_spirv(p_compute_shader->get_spirv_stages("denoise")); |
| 1010 | ERR_FAIL_COND_V(compute_shader_denoise.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 1011 | |
| 1012 | RID compute_shader_denoise_pipeline = p_rd->compute_pipeline_create(compute_shader_denoise); |
| 1013 | RID denoise_uniform_set = p_rd->uniform_set_create(uniforms, compute_shader_denoise, 1); |
| 1014 | |
| 1015 | // We denoise in fixed size regions and synchronize execution to avoid GPU timeouts. |
| 1016 | // We use a region with 1/4 the amount of pixels if we're denoising SH lightmaps, as |
| 1017 | // all four of them are denoised in the shader in one dispatch. |
| 1018 | const int user_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size"))); |
| 1019 | const int max_region_size = p_bake_sh ? user_region_size / 2 : user_region_size; |
| 1020 | int x_regions = Math::division_round_up(p_atlas_size.width, max_region_size); |
| 1021 | int y_regions = Math::division_round_up(p_atlas_size.height, max_region_size); |
| 1022 | for (int s = 0; s < p_atlas_slices; s++) { |
| 1023 | p_push_constant.atlas_slice = s; |
| 1024 | |
| 1025 | for (int i = 0; i < x_regions; i++) { |
| 1026 | for (int j = 0; j < y_regions; j++) { |
| 1027 | int x = i * max_region_size; |
| 1028 | int y = j * max_region_size; |
| 1029 | int w = MIN((i + 1) * max_region_size, p_atlas_size.width) - x; |
| 1030 | int h = MIN((j + 1) * max_region_size, p_atlas_size.height) - y; |
| 1031 | p_push_constant.region_ofs[0] = x; |
| 1032 | p_push_constant.region_ofs[1] = y; |
| 1033 | |
| 1034 | RD::ComputeListID compute_list = p_rd->compute_list_begin(); |
| 1035 | p_rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_denoise_pipeline); |
| 1036 | p_rd->compute_list_bind_uniform_set(compute_list, p_compute_base_uniform_set, 0); |
| 1037 | p_rd->compute_list_bind_uniform_set(compute_list, denoise_uniform_set, 1); |
| 1038 | p_rd->compute_list_set_push_constant(compute_list, &p_push_constant, sizeof(PushConstant)); |
| 1039 | p_rd->compute_list_dispatch(compute_list, Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1); |
| 1040 | p_rd->compute_list_end(); |
| 1041 | |
| 1042 | p_rd->submit(); |
| 1043 | p_rd->sync(); |
| 1044 | } |
| 1045 | } |
| 1046 | if (p_step_function) { |
| 1047 | int percent = (s + 1) * 100 / p_atlas_slices; |
| 1048 | float p = float(s) / p_atlas_slices * 0.1; |
| 1049 | if (p_step_function(0.8 + p, vformat(RTR("Denoising %d%%"), percent), p_bake_userdata, false)) { |
| 1050 | return BAKE_ERROR_USER_ABORTED; |
| 1051 | } |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | p_rd->free_rid(compute_shader_denoise); |
| 1056 | p_rd->free_rid(denoise_params_buffer); |
| 1057 | |
| 1058 | return BAKE_OK; |
| 1059 | } |
| 1060 | |
| 1061 | LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, float p_denoiser_strength, int p_denoiser_range, int p_bounces, float p_bounce_indirect_energy, float p_bias, int p_max_texture_size, bool p_bake_sh, bool p_bake_shadowmask, bool p_texture_for_bounces, GenerateProbes p_generate_probes, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function, void *p_bake_userdata, float p_exposure_normalization, float p_supersampling_factor) { |
| 1062 | int denoiser = GLOBAL_GET("rendering/lightmapping/denoising/denoiser"); |
| 1063 | String oidn_path = EDITOR_GET("filesystem/tools/oidn/oidn_denoise_path"); |
| 1064 | |
| 1065 | if (p_use_denoiser && denoiser == 1) { |
| 1066 | // OIDN (external). |
| 1067 | Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); |
| 1068 | |
| 1069 | if (da->dir_exists(oidn_path)) { |
| 1070 | if (OS::get_singleton()->get_name() == "Windows") { |
| 1071 | oidn_path = oidn_path.path_join("oidnDenoise.exe"); |
| 1072 | } else { |
| 1073 | oidn_path = oidn_path.path_join("oidnDenoise"); |
| 1074 | } |
| 1075 | } |
| 1076 | ERR_FAIL_COND_V_MSG(oidn_path.is_empty() || !da->file_exists(oidn_path), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, "OIDN denoiser is selected in the project settings, but no or invalid OIDN executable path is configured in the editor settings."); |
| 1077 | } |
| 1078 | |
| 1079 | if (p_step_function) { |
| 1080 | p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true); |
| 1081 | } |
| 1082 | lightmap_textures.clear(); |
| 1083 | shadowmask_textures.clear(); |
| 1084 | int grid_size = 128; |
| 1085 | |
| 1086 | /* STEP 1: Fetch material textures and compute the bounds */ |
| 1087 | |
| 1088 | AABB bounds; |
| 1089 | Size2i atlas_size; |
| 1090 | int atlas_slices; |
| 1091 | Vector<Ref<Image>> albedo_images; |
| 1092 | Vector<Ref<Image>> emission_images; |
| 1093 | |
| 1094 | BakeError bake_error = _blit_meshes_into_atlas(p_max_texture_size, p_denoiser_range, albedo_images, emission_images, bounds, atlas_size, atlas_slices, p_supersampling_factor, p_step_function, p_bake_userdata); |
| 1095 | if (bake_error != BAKE_OK) { |
| 1096 | return bake_error; |
| 1097 | } |
| 1098 | |
| 1099 | // Find any directional light suitable for shadowmasking. |
| 1100 | if (p_bake_shadowmask) { |
| 1101 | bool found = false; |
| 1102 | for (int i = 0; i < lights.size(); i++) { |
| 1103 | if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) { |
| 1104 | found = true; |
| 1105 | break; |
| 1106 | } |
| 1107 | } |
| 1108 | |
| 1109 | if (!found) { |
| 1110 | p_bake_shadowmask = false; |
| 1111 | WARN_PRINT("Shadowmask disabled: no directional light with their bake mode set to dynamic exists."); |
| 1112 | } |
| 1113 | } |
| 1114 | |
| 1115 | #ifdef DEBUG_TEXTURES |
| 1116 | for (int i = 0; i < atlas_slices; i++) { |
| 1117 | albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png"); |
| 1118 | emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png"); |
| 1119 | } |
| 1120 | #endif |
| 1121 | |
| 1122 | // Attempt to create a local device by requesting it from rendering server first. |
| 1123 | // If that fails because the current renderer is not implemented on top of RD, we fall back to creating |
| 1124 | // a local rendering device manually depending on the current platform. |
| 1125 | Error err; |
| 1126 | RenderingContextDriver *rcd = nullptr; |
| 1127 | RenderingDevice *rd = RenderingServer::get_singleton()->create_local_rendering_device(); |
| 1128 | if (rd == nullptr) { |
| 1129 | #if defined(RD_ENABLED) |
| 1130 | #if defined(METAL_ENABLED) |
| 1131 | rcd = memnew(RenderingContextDriverMetal); |
| 1132 | rd = memnew(RenderingDevice); |
| 1133 | #endif |
| 1134 | #if defined(VULKAN_ENABLED) |
| 1135 | if (rcd == nullptr) { |
| 1136 | rcd = memnew(RenderingContextDriverVulkan); |
| 1137 | rd = memnew(RenderingDevice); |
| 1138 | } |
| 1139 | #endif |
| 1140 | #endif |
| 1141 | if (rcd != nullptr && rd != nullptr) { |
| 1142 | err = rcd->initialize(); |
| 1143 | if (err == OK) { |
| 1144 | err = rd->initialize(rcd); |
| 1145 | } |
| 1146 | |
| 1147 | if (err != OK) { |
| 1148 | memdelete(rd); |
| 1149 | memdelete(rcd); |
| 1150 | rd = nullptr; |
| 1151 | rcd = nullptr; |
| 1152 | } |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | ERR_FAIL_NULL_V(rd, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 1157 | |
| 1158 | RID albedo_array_tex; |
| 1159 | RID emission_array_tex; |
| 1160 | RID normal_tex; |
| 1161 | RID position_tex; |
| 1162 | RID unocclude_tex; |
| 1163 | RID light_source_tex; |
| 1164 | RID light_dest_tex; |
| 1165 | RID light_accum_tex; |
| 1166 | RID light_accum_tex2; |
| 1167 | RID light_environment_tex; |
| 1168 | RID shadowmask_tex; |
| 1169 | RID shadowmask_tex2; |
| 1170 | |
| 1171 | #define FREE_TEXTURES \ |
| 1172 | rd->free_rid(albedo_array_tex); \ |
| 1173 | rd->free_rid(emission_array_tex); \ |
| 1174 | rd->free_rid(normal_tex); \ |
| 1175 | rd->free_rid(position_tex); \ |
| 1176 | rd->free_rid(unocclude_tex); \ |
| 1177 | rd->free_rid(light_source_tex); \ |
| 1178 | rd->free_rid(light_accum_tex2); \ |
| 1179 | rd->free_rid(light_accum_tex); \ |
| 1180 | rd->free_rid(light_environment_tex); \ |
| 1181 | if (p_bake_shadowmask) { \ |
| 1182 | rd->free_rid(shadowmask_tex); \ |
| 1183 | rd->free_rid(shadowmask_tex2); \ |
| 1184 | } |
| 1185 | |
| 1186 | { // create all textures |
| 1187 | |
| 1188 | Vector<Vector<uint8_t>> albedo_data; |
| 1189 | Vector<Vector<uint8_t>> emission_data; |
| 1190 | for (int i = 0; i < atlas_slices; i++) { |
| 1191 | albedo_data.push_back(albedo_images[i]->get_data()); |
| 1192 | emission_data.push_back(emission_images[i]->get_data()); |
| 1193 | } |
| 1194 | |
| 1195 | RD::TextureFormat tf; |
| 1196 | tf.width = atlas_size.width; |
| 1197 | tf.height = atlas_size.height; |
| 1198 | tf.array_layers = atlas_slices; |
| 1199 | tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY; |
| 1200 | tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT; |
| 1201 | tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM; |
| 1202 | |
| 1203 | albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data); |
| 1204 | |
| 1205 | tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT; |
| 1206 | |
| 1207 | emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data); |
| 1208 | |
| 1209 | //this will be rastered to |
| 1210 | tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_STORAGE_BIT; |
| 1211 | normal_tex = rd->texture_create(tf, RD::TextureView()); |
| 1212 | tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; |
| 1213 | position_tex = rd->texture_create(tf, RD::TextureView()); |
| 1214 | unocclude_tex = rd->texture_create(tf, RD::TextureView()); |
| 1215 | |
| 1216 | tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT; |
| 1217 | |
| 1218 | // shadowmask |
| 1219 | if (p_bake_shadowmask) { |
| 1220 | tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM; |
| 1221 | |
| 1222 | shadowmask_tex = rd->texture_create(tf, RD::TextureView()); |
| 1223 | rd->texture_clear(shadowmask_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices); |
| 1224 | |
| 1225 | shadowmask_tex2 = rd->texture_create(tf, RD::TextureView()); |
| 1226 | rd->texture_clear(shadowmask_tex2, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices); |
| 1227 | } |
| 1228 | |
| 1229 | // lightmap |
| 1230 | tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT; |
| 1231 | |
| 1232 | light_source_tex = rd->texture_create(tf, RD::TextureView()); |
| 1233 | rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices); |
| 1234 | |
| 1235 | if (p_bake_sh) { |
| 1236 | tf.array_layers *= 4; |
| 1237 | } |
| 1238 | light_accum_tex = rd->texture_create(tf, RD::TextureView()); |
| 1239 | rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers); |
| 1240 | light_dest_tex = rd->texture_create(tf, RD::TextureView()); |
| 1241 | rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers); |
| 1242 | light_accum_tex2 = light_dest_tex; |
| 1243 | |
| 1244 | //env |
| 1245 | { |
| 1246 | Ref<Image> panorama_tex; |
| 1247 | if (p_environment_panorama.is_valid()) { |
| 1248 | panorama_tex = p_environment_panorama; |
| 1249 | panorama_tex->convert(Image::FORMAT_RGBAF); |
| 1250 | } else { |
| 1251 | panorama_tex.instantiate(); |
| 1252 | panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF); |
| 1253 | panorama_tex->fill(Color(0, 0, 0, 1)); |
| 1254 | } |
| 1255 | |
| 1256 | RD::TextureFormat tfp; |
| 1257 | tfp.width = panorama_tex->get_width(); |
| 1258 | tfp.height = panorama_tex->get_height(); |
| 1259 | tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT; |
| 1260 | tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; |
| 1261 | |
| 1262 | Vector<Vector<uint8_t>> tdata; |
| 1263 | tdata.push_back(panorama_tex->get_data()); |
| 1264 | light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata); |
| 1265 | |
| 1266 | #ifdef DEBUG_TEXTURES |
| 1267 | panorama_tex->save_exr("res://0_panorama.exr", false); |
| 1268 | #endif |
| 1269 | } |
| 1270 | } |
| 1271 | |
| 1272 | /* STEP 2: create the acceleration structure for the GPU*/ |
| 1273 | |
| 1274 | Vector<int> slice_triangle_count; |
| 1275 | RID bake_parameters_buffer; |
| 1276 | RID vertex_buffer; |
| 1277 | RID triangle_buffer; |
| 1278 | RID lights_buffer; |
| 1279 | RID triangle_indices_buffer; |
| 1280 | RID cluster_indices_buffer; |
| 1281 | RID cluster_aabbs_buffer; |
| 1282 | RID grid_texture; |
| 1283 | RID seams_buffer; |
| 1284 | RID probe_positions_buffer; |
| 1285 | |
| 1286 | Vector<int> slice_seam_count; |
| 1287 | |
| 1288 | #define FREE_BUFFERS \ |
| 1289 | rd->free_rid(bake_parameters_buffer); \ |
| 1290 | rd->free_rid(vertex_buffer); \ |
| 1291 | rd->free_rid(triangle_buffer); \ |
| 1292 | rd->free_rid(lights_buffer); \ |
| 1293 | rd->free_rid(triangle_indices_buffer); \ |
| 1294 | rd->free_rid(cluster_indices_buffer); \ |
| 1295 | rd->free_rid(cluster_aabbs_buffer); \ |
| 1296 | rd->free_rid(grid_texture); \ |
| 1297 | rd->free_rid(seams_buffer); \ |
| 1298 | rd->free_rid(probe_positions_buffer); |
| 1299 | |
| 1300 | const uint32_t cluster_size = 16; |
| 1301 | _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, cluster_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_indices_buffer, cluster_indices_buffer, cluster_aabbs_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata); |
| 1302 | |
| 1303 | // The index of the directional light used for shadowmasking. |
| 1304 | int shadowmask_light_idx = -1; |
| 1305 | |
| 1306 | // Find the directional light index in the sorted lights array. |
| 1307 | if (p_bake_shadowmask) { |
| 1308 | int shadowmask_lights_count = 0; |
| 1309 | |
| 1310 | for (int i = 0; i < lights.size(); i++) { |
| 1311 | if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) { |
| 1312 | if (shadowmask_light_idx < 0) { |
| 1313 | shadowmask_light_idx = i; |
| 1314 | } |
| 1315 | shadowmask_lights_count += 1; |
| 1316 | } |
| 1317 | } |
| 1318 | |
| 1319 | if (shadowmask_lights_count > 1) { |
| 1320 | WARN_PRINT( |
| 1321 | vformat("%d directional lights detected for shadowmask baking. Only %s will be used.", |
| 1322 | shadowmask_lights_count, light_metadata[shadowmask_light_idx].name)); |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | // Create global bake parameters buffer. |
| 1327 | BakeParameters bake_parameters; |
| 1328 | bake_parameters.world_size[0] = bounds.size.x; |
| 1329 | bake_parameters.world_size[1] = bounds.size.y; |
| 1330 | bake_parameters.world_size[2] = bounds.size.z; |
| 1331 | bake_parameters.bias = p_bias; |
| 1332 | bake_parameters.to_cell_offset[0] = bounds.position.x; |
| 1333 | bake_parameters.to_cell_offset[1] = bounds.position.y; |
| 1334 | bake_parameters.to_cell_offset[2] = bounds.position.z; |
| 1335 | bake_parameters.grid_size = grid_size; |
| 1336 | bake_parameters.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size); |
| 1337 | bake_parameters.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size); |
| 1338 | bake_parameters.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size); |
| 1339 | bake_parameters.light_count = lights.size(); |
| 1340 | bake_parameters.env_transform[0] = p_environment_transform.rows[0][0]; |
| 1341 | bake_parameters.env_transform[1] = p_environment_transform.rows[1][0]; |
| 1342 | bake_parameters.env_transform[2] = p_environment_transform.rows[2][0]; |
| 1343 | bake_parameters.env_transform[3] = 0.0f; |
| 1344 | bake_parameters.env_transform[4] = p_environment_transform.rows[0][1]; |
| 1345 | bake_parameters.env_transform[5] = p_environment_transform.rows[1][1]; |
| 1346 | bake_parameters.env_transform[6] = p_environment_transform.rows[2][1]; |
| 1347 | bake_parameters.env_transform[7] = 0.0f; |
| 1348 | bake_parameters.env_transform[8] = p_environment_transform.rows[0][2]; |
| 1349 | bake_parameters.env_transform[9] = p_environment_transform.rows[1][2]; |
| 1350 | bake_parameters.env_transform[10] = p_environment_transform.rows[2][2]; |
| 1351 | bake_parameters.env_transform[11] = 0.0f; |
| 1352 | bake_parameters.atlas_size[0] = atlas_size.width; |
| 1353 | bake_parameters.atlas_size[1] = atlas_size.height; |
| 1354 | bake_parameters.exposure_normalization = p_exposure_normalization; |
| 1355 | bake_parameters.bounces = p_bounces; |
| 1356 | bake_parameters.bounce_indirect_energy = p_bounce_indirect_energy; |
| 1357 | bake_parameters.shadowmask_light_idx = shadowmask_light_idx; |
| 1358 | // Same number of rays for transparency regardless of quality (it's more of a retry rather than shooting new ones). |
| 1359 | bake_parameters.transparency_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_transparency_rays"); |
| 1360 | bake_parameters.supersampling_factor = p_supersampling_factor; |
| 1361 | |
| 1362 | bake_parameters_buffer = rd->uniform_buffer_create(sizeof(BakeParameters)); |
| 1363 | rd->buffer_update(bake_parameters_buffer, 0, sizeof(BakeParameters), &bake_parameters); |
| 1364 | |
| 1365 | if (p_step_function) { |
| 1366 | if (p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true)) { |
| 1367 | FREE_TEXTURES |
| 1368 | FREE_BUFFERS |
| 1369 | memdelete(rd); |
| 1370 | if (rcd != nullptr) { |
| 1371 | memdelete(rcd); |
| 1372 | } |
| 1373 | return BAKE_ERROR_USER_ABORTED; |
| 1374 | } |
| 1375 | } |
| 1376 | |
| 1377 | //shaders |
| 1378 | Ref<RDShaderFile> raster_shader; |
| 1379 | raster_shader.instantiate(); |
| 1380 | err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl); |
| 1381 | if (err != OK) { |
| 1382 | raster_shader->print_errors("raster_shader"); |
| 1383 | |
| 1384 | FREE_TEXTURES |
| 1385 | FREE_BUFFERS |
| 1386 | |
| 1387 | memdelete(rd); |
| 1388 | |
| 1389 | if (rcd != nullptr) { |
| 1390 | memdelete(rcd); |
| 1391 | } |
| 1392 | } |
| 1393 | ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 1394 | |
| 1395 | RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages()); |
| 1396 | |
| 1397 | ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen |
| 1398 | |
| 1399 | RID sampler; |
| 1400 | { |
| 1401 | RD::SamplerState s; |
| 1402 | s.mag_filter = RD::SAMPLER_FILTER_LINEAR; |
| 1403 | s.min_filter = RD::SAMPLER_FILTER_LINEAR; |
| 1404 | s.max_lod = 0; |
| 1405 | |
| 1406 | sampler = rd->sampler_create(s); |
| 1407 | } |
| 1408 | |
| 1409 | Vector<RD::Uniform> base_uniforms; |
| 1410 | { |
| 1411 | { |
| 1412 | RD::Uniform u; |
| 1413 | u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER; |
| 1414 | u.binding = 0; |
| 1415 | u.append_id(bake_parameters_buffer); |
| 1416 | base_uniforms.push_back(u); |
| 1417 | } |
| 1418 | { |
| 1419 | RD::Uniform u; |
| 1420 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1421 | u.binding = 1; |
| 1422 | u.append_id(vertex_buffer); |
| 1423 | base_uniforms.push_back(u); |
| 1424 | } |
| 1425 | { |
| 1426 | RD::Uniform u; |
| 1427 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1428 | u.binding = 2; |
| 1429 | u.append_id(triangle_buffer); |
| 1430 | base_uniforms.push_back(u); |
| 1431 | } |
| 1432 | { |
| 1433 | RD::Uniform u; |
| 1434 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1435 | u.binding = 3; |
| 1436 | u.append_id(triangle_indices_buffer); |
| 1437 | base_uniforms.push_back(u); |
| 1438 | } |
| 1439 | { |
| 1440 | RD::Uniform u; |
| 1441 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1442 | u.binding = 4; |
| 1443 | u.append_id(lights_buffer); |
| 1444 | base_uniforms.push_back(u); |
| 1445 | } |
| 1446 | { |
| 1447 | RD::Uniform u; |
| 1448 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1449 | u.binding = 5; |
| 1450 | u.append_id(seams_buffer); |
| 1451 | base_uniforms.push_back(u); |
| 1452 | } |
| 1453 | { |
| 1454 | RD::Uniform u; |
| 1455 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1456 | u.binding = 6; |
| 1457 | u.append_id(probe_positions_buffer); |
| 1458 | base_uniforms.push_back(u); |
| 1459 | } |
| 1460 | { |
| 1461 | RD::Uniform u; |
| 1462 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1463 | u.binding = 7; |
| 1464 | u.append_id(grid_texture); |
| 1465 | base_uniforms.push_back(u); |
| 1466 | } |
| 1467 | { |
| 1468 | RD::Uniform u; |
| 1469 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1470 | u.binding = 8; |
| 1471 | u.append_id(albedo_array_tex); |
| 1472 | base_uniforms.push_back(u); |
| 1473 | } |
| 1474 | { |
| 1475 | RD::Uniform u; |
| 1476 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1477 | u.binding = 9; |
| 1478 | u.append_id(emission_array_tex); |
| 1479 | base_uniforms.push_back(u); |
| 1480 | } |
| 1481 | { |
| 1482 | RD::Uniform u; |
| 1483 | u.uniform_type = RD::UNIFORM_TYPE_SAMPLER; |
| 1484 | u.binding = 10; |
| 1485 | u.append_id(sampler); |
| 1486 | base_uniforms.push_back(u); |
| 1487 | } |
| 1488 | { |
| 1489 | RD::Uniform u; |
| 1490 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1491 | u.binding = 11; |
| 1492 | u.append_id(cluster_indices_buffer); |
| 1493 | base_uniforms.push_back(u); |
| 1494 | } |
| 1495 | { |
| 1496 | RD::Uniform u; |
| 1497 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1498 | u.binding = 12; |
| 1499 | u.append_id(cluster_aabbs_buffer); |
| 1500 | base_uniforms.push_back(u); |
| 1501 | } |
| 1502 | } |
| 1503 | |
| 1504 | RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0); |
| 1505 | RID raster_depth_buffer; |
| 1506 | { |
| 1507 | RD::TextureFormat tf; |
| 1508 | tf.width = atlas_size.width; |
| 1509 | tf.height = atlas_size.height; |
| 1510 | tf.depth = 1; |
| 1511 | tf.texture_type = RD::TEXTURE_TYPE_2D; |
| 1512 | tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; |
| 1513 | tf.format = RD::DATA_FORMAT_D32_SFLOAT; |
| 1514 | tf.is_discardable = true; |
| 1515 | |
| 1516 | raster_depth_buffer = rd->texture_create(tf, RD::TextureView()); |
| 1517 | } |
| 1518 | |
| 1519 | rd->submit(); |
| 1520 | rd->sync(); |
| 1521 | |
| 1522 | /* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/ |
| 1523 | |
| 1524 | _raster_geometry(rd, atlas_size, atlas_slices, grid_size, bounds, p_bias, slice_triangle_count, position_tex, unocclude_tex, normal_tex, raster_depth_buffer, rasterize_shader, raster_base_uniform); |
| 1525 | |
| 1526 | #ifdef DEBUG_TEXTURES |
| 1527 | |
| 1528 | for (int i = 0; i < atlas_slices; i++) { |
| 1529 | Vector<uint8_t> s = rd->texture_get_data(position_tex, i); |
| 1530 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s); |
| 1531 | img->save_exr("res://1_position_" + itos(i) + ".exr", false); |
| 1532 | |
| 1533 | s = rd->texture_get_data(normal_tex, i); |
| 1534 | img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); |
| 1535 | img->save_exr("res://1_normal_" + itos(i) + ".exr", false); |
| 1536 | } |
| 1537 | #endif |
| 1538 | |
| 1539 | #define FREE_RASTER_RESOURCES \ |
| 1540 | rd->free_rid(rasterize_shader); \ |
| 1541 | rd->free_rid(sampler); \ |
| 1542 | rd->free_rid(raster_depth_buffer); |
| 1543 | |
| 1544 | /* Plot direct light */ |
| 1545 | |
| 1546 | Ref<RDShaderFile> compute_shader; |
| 1547 | String defines = ""; |
| 1548 | defines += "\n#define CLUSTER_SIZE " + uitos(cluster_size) + "\n"; |
| 1549 | |
| 1550 | if (p_bake_sh) { |
| 1551 | defines += "\n#define USE_SH_LIGHTMAPS\n"; |
| 1552 | } |
| 1553 | |
| 1554 | if (p_texture_for_bounces) { |
| 1555 | defines += "\n#define USE_LIGHT_TEXTURE_FOR_BOUNCES\n"; |
| 1556 | } |
| 1557 | |
| 1558 | if (p_bake_shadowmask) { |
| 1559 | defines += "\n#define USE_SHADOWMASK\n"; |
| 1560 | } |
| 1561 | |
| 1562 | compute_shader.instantiate(); |
| 1563 | err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, defines); |
| 1564 | if (err != OK) { |
| 1565 | FREE_TEXTURES |
| 1566 | FREE_BUFFERS |
| 1567 | FREE_RASTER_RESOURCES |
| 1568 | memdelete(rd); |
| 1569 | |
| 1570 | if (rcd != nullptr) { |
| 1571 | memdelete(rcd); |
| 1572 | } |
| 1573 | |
| 1574 | compute_shader->print_errors("compute_shader"); |
| 1575 | } |
| 1576 | ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 1577 | |
| 1578 | // Unoccluder |
| 1579 | RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude")); |
| 1580 | ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen |
| 1581 | RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude); |
| 1582 | |
| 1583 | // Direct light |
| 1584 | RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary")); |
| 1585 | ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen |
| 1586 | RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary); |
| 1587 | |
| 1588 | // Indirect light |
| 1589 | RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary")); |
| 1590 | ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen |
| 1591 | RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary); |
| 1592 | |
| 1593 | // Light probes |
| 1594 | RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes")); |
| 1595 | ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen |
| 1596 | RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes); |
| 1597 | |
| 1598 | RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0); |
| 1599 | |
| 1600 | #define FREE_COMPUTE_RESOURCES \ |
| 1601 | rd->free_rid(compute_shader_unocclude); \ |
| 1602 | rd->free_rid(compute_shader_primary); \ |
| 1603 | rd->free_rid(compute_shader_secondary); \ |
| 1604 | rd->free_rid(compute_shader_light_probes); |
| 1605 | |
| 1606 | Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); |
| 1607 | rd->submit(); |
| 1608 | rd->sync(); |
| 1609 | |
| 1610 | if (p_step_function) { |
| 1611 | if (p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true)) { |
| 1612 | FREE_TEXTURES |
| 1613 | FREE_BUFFERS |
| 1614 | FREE_RASTER_RESOURCES |
| 1615 | FREE_COMPUTE_RESOURCES |
| 1616 | memdelete(rd); |
| 1617 | if (rcd != nullptr) { |
| 1618 | memdelete(rcd); |
| 1619 | } |
| 1620 | return BAKE_ERROR_USER_ABORTED; |
| 1621 | } |
| 1622 | } |
| 1623 | |
| 1624 | PushConstant push_constant; |
| 1625 | push_constant.denoiser_range = p_use_denoiser ? p_denoiser_range : 1.0; |
| 1626 | |
| 1627 | /* UNOCCLUDE */ |
| 1628 | { |
| 1629 | Vector<RD::Uniform> uniforms; |
| 1630 | { |
| 1631 | { |
| 1632 | RD::Uniform u; |
| 1633 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 1634 | u.binding = 0; |
| 1635 | u.append_id(position_tex); |
| 1636 | uniforms.push_back(u); |
| 1637 | } |
| 1638 | { |
| 1639 | RD::Uniform u; |
| 1640 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 1641 | u.binding = 1; |
| 1642 | u.append_id(unocclude_tex); |
| 1643 | uniforms.push_back(u); |
| 1644 | } |
| 1645 | } |
| 1646 | |
| 1647 | RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1); |
| 1648 | |
| 1649 | RD::ComputeListID compute_list = rd->compute_list_begin(); |
| 1650 | rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline); |
| 1651 | rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0); |
| 1652 | rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1); |
| 1653 | |
| 1654 | for (int i = 0; i < atlas_slices; i++) { |
| 1655 | push_constant.atlas_slice = i; |
| 1656 | rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant)); |
| 1657 | rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z); |
| 1658 | //no barrier, let them run all together |
| 1659 | } |
| 1660 | rd->compute_list_end(); //done |
| 1661 | } |
| 1662 | |
| 1663 | #ifdef DEBUG_TEXTURES |
| 1664 | for (int i = 0; i < atlas_slices; i++) { |
| 1665 | Vector<uint8_t> s = rd->texture_get_data(unocclude_tex, i); |
| 1666 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s); |
| 1667 | img->save_exr("res://1_unocclude_" + itos(i) + ".exr", false); |
| 1668 | } |
| 1669 | #endif |
| 1670 | |
| 1671 | if (p_step_function) { |
| 1672 | if (p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true)) { |
| 1673 | FREE_TEXTURES |
| 1674 | FREE_BUFFERS |
| 1675 | FREE_RASTER_RESOURCES |
| 1676 | FREE_COMPUTE_RESOURCES |
| 1677 | memdelete(rd); |
| 1678 | if (rcd != nullptr) { |
| 1679 | memdelete(rcd); |
| 1680 | } |
| 1681 | return BAKE_ERROR_USER_ABORTED; |
| 1682 | } |
| 1683 | } |
| 1684 | |
| 1685 | const int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size"))); |
| 1686 | const int x_regions = Math::division_round_up(atlas_size.width, max_region_size); |
| 1687 | const int y_regions = Math::division_round_up(atlas_size.height, max_region_size); |
| 1688 | |
| 1689 | // Set ray count to the quality used for direct light and bounces. |
| 1690 | switch (p_quality) { |
| 1691 | case BAKE_QUALITY_LOW: { |
| 1692 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count"); |
| 1693 | } break; |
| 1694 | case BAKE_QUALITY_MEDIUM: { |
| 1695 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count"); |
| 1696 | } break; |
| 1697 | case BAKE_QUALITY_HIGH: { |
| 1698 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count"); |
| 1699 | } break; |
| 1700 | case BAKE_QUALITY_ULTRA: { |
| 1701 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count"); |
| 1702 | } break; |
| 1703 | } |
| 1704 | |
| 1705 | push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u); |
| 1706 | |
| 1707 | /* PRIMARY (direct) LIGHT PASS */ |
| 1708 | { |
| 1709 | Vector<RD::Uniform> uniforms; |
| 1710 | { |
| 1711 | { |
| 1712 | RD::Uniform u; |
| 1713 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 1714 | u.binding = 0; |
| 1715 | u.append_id(light_source_tex); |
| 1716 | uniforms.push_back(u); |
| 1717 | } |
| 1718 | { |
| 1719 | RD::Uniform u; |
| 1720 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1721 | u.binding = 1; |
| 1722 | u.append_id(light_dest_tex); //will be unused |
| 1723 | uniforms.push_back(u); |
| 1724 | } |
| 1725 | { |
| 1726 | RD::Uniform u; |
| 1727 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1728 | u.binding = 2; |
| 1729 | u.append_id(position_tex); |
| 1730 | uniforms.push_back(u); |
| 1731 | } |
| 1732 | { |
| 1733 | RD::Uniform u; |
| 1734 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1735 | u.binding = 3; |
| 1736 | u.append_id(normal_tex); |
| 1737 | uniforms.push_back(u); |
| 1738 | } |
| 1739 | { |
| 1740 | RD::Uniform u; |
| 1741 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 1742 | u.binding = 4; |
| 1743 | u.append_id(light_accum_tex); |
| 1744 | uniforms.push_back(u); |
| 1745 | } |
| 1746 | |
| 1747 | if (p_bake_shadowmask) { |
| 1748 | RD::Uniform u; |
| 1749 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 1750 | u.binding = 5; |
| 1751 | u.append_id(shadowmask_tex); |
| 1752 | uniforms.push_back(u); |
| 1753 | } |
| 1754 | } |
| 1755 | |
| 1756 | RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1); |
| 1757 | |
| 1758 | int count = 0; |
| 1759 | for (int s = 0; s < atlas_slices; s++) { |
| 1760 | push_constant.atlas_slice = s; |
| 1761 | |
| 1762 | for (int i = 0; i < x_regions; i++) { |
| 1763 | for (int j = 0; j < y_regions; j++) { |
| 1764 | int x = i * max_region_size; |
| 1765 | int y = j * max_region_size; |
| 1766 | int w = MIN((i + 1) * max_region_size, atlas_size.width) - x; |
| 1767 | int h = MIN((j + 1) * max_region_size, atlas_size.height) - y; |
| 1768 | |
| 1769 | push_constant.region_ofs[0] = x; |
| 1770 | push_constant.region_ofs[1] = y; |
| 1771 | |
| 1772 | group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1); |
| 1773 | RD::ComputeListID compute_list = rd->compute_list_begin(); |
| 1774 | rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline); |
| 1775 | rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0); |
| 1776 | rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1); |
| 1777 | rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant)); |
| 1778 | rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z); |
| 1779 | rd->compute_list_end(); |
| 1780 | |
| 1781 | rd->submit(); |
| 1782 | rd->sync(); |
| 1783 | |
| 1784 | count++; |
| 1785 | if (p_step_function) { |
| 1786 | int total = (atlas_slices * x_regions * y_regions); |
| 1787 | int percent = count * 100 / total; |
| 1788 | float p = float(count) / total * 0.1; |
| 1789 | if (p_step_function(0.5 + p, vformat(RTR("Plot direct lighting %d%%"), percent), p_bake_userdata, false)) { |
| 1790 | FREE_TEXTURES |
| 1791 | FREE_BUFFERS |
| 1792 | FREE_RASTER_RESOURCES |
| 1793 | FREE_COMPUTE_RESOURCES |
| 1794 | memdelete(rd); |
| 1795 | if (rcd != nullptr) { |
| 1796 | memdelete(rcd); |
| 1797 | } |
| 1798 | return BAKE_ERROR_USER_ABORTED; |
| 1799 | } |
| 1800 | } |
| 1801 | } |
| 1802 | } |
| 1803 | } |
| 1804 | } |
| 1805 | |
| 1806 | #ifdef DEBUG_TEXTURES |
| 1807 | |
| 1808 | for (int i = 0; i < atlas_slices; i++) { |
| 1809 | Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i); |
| 1810 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); |
| 1811 | img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false); |
| 1812 | } |
| 1813 | |
| 1814 | if (p_bake_sh) { |
| 1815 | for (int i = 0; i < atlas_slices * 4; i++) { |
| 1816 | Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); |
| 1817 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); |
| 1818 | img->save_exr("res://2_light_primary_accum_" + itos(i) + ".exr", false); |
| 1819 | } |
| 1820 | } |
| 1821 | #endif |
| 1822 | |
| 1823 | /* SECONDARY (indirect) LIGHT PASS(ES) */ |
| 1824 | |
| 1825 | if (p_bounces > 0) { |
| 1826 | Vector<RD::Uniform> uniforms; |
| 1827 | { |
| 1828 | { |
| 1829 | // Unused. |
| 1830 | RD::Uniform u; |
| 1831 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 1832 | u.binding = 0; |
| 1833 | u.append_id(light_dest_tex); |
| 1834 | uniforms.push_back(u); |
| 1835 | } |
| 1836 | { |
| 1837 | RD::Uniform u; |
| 1838 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1839 | u.binding = 1; |
| 1840 | u.append_id(light_source_tex); |
| 1841 | uniforms.push_back(u); |
| 1842 | } |
| 1843 | { |
| 1844 | RD::Uniform u; |
| 1845 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1846 | u.binding = 2; |
| 1847 | u.append_id(position_tex); |
| 1848 | uniforms.push_back(u); |
| 1849 | } |
| 1850 | { |
| 1851 | RD::Uniform u; |
| 1852 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1853 | u.binding = 3; |
| 1854 | u.append_id(normal_tex); |
| 1855 | uniforms.push_back(u); |
| 1856 | } |
| 1857 | { |
| 1858 | RD::Uniform u; |
| 1859 | u.uniform_type = RD::UNIFORM_TYPE_IMAGE; |
| 1860 | u.binding = 4; |
| 1861 | u.append_id(light_accum_tex); |
| 1862 | uniforms.push_back(u); |
| 1863 | } |
| 1864 | { |
| 1865 | RD::Uniform u; |
| 1866 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1867 | u.binding = 5; |
| 1868 | u.append_id(light_environment_tex); |
| 1869 | uniforms.push_back(u); |
| 1870 | } |
| 1871 | } |
| 1872 | |
| 1873 | RID secondary_uniform_set; |
| 1874 | secondary_uniform_set = rd->uniform_set_create(uniforms, compute_shader_secondary, 1); |
| 1875 | |
| 1876 | const int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass"); |
| 1877 | int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays); |
| 1878 | |
| 1879 | if (p_step_function) { |
| 1880 | if (p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true)) { |
| 1881 | FREE_TEXTURES |
| 1882 | FREE_BUFFERS |
| 1883 | FREE_RASTER_RESOURCES |
| 1884 | FREE_COMPUTE_RESOURCES |
| 1885 | memdelete(rd); |
| 1886 | if (rcd != nullptr) { |
| 1887 | memdelete(rcd); |
| 1888 | } |
| 1889 | return BAKE_ERROR_USER_ABORTED; |
| 1890 | } |
| 1891 | } |
| 1892 | |
| 1893 | int count = 0; |
| 1894 | for (int s = 0; s < atlas_slices; s++) { |
| 1895 | push_constant.atlas_slice = s; |
| 1896 | |
| 1897 | for (int i = 0; i < x_regions; i++) { |
| 1898 | for (int j = 0; j < y_regions; j++) { |
| 1899 | int x = i * max_region_size; |
| 1900 | int y = j * max_region_size; |
| 1901 | int w = MIN((i + 1) * max_region_size, atlas_size.width) - x; |
| 1902 | int h = MIN((j + 1) * max_region_size, atlas_size.height) - y; |
| 1903 | |
| 1904 | push_constant.region_ofs[0] = x; |
| 1905 | push_constant.region_ofs[1] = y; |
| 1906 | |
| 1907 | group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1); |
| 1908 | |
| 1909 | for (int k = 0; k < ray_iterations; k++) { |
| 1910 | RD::ComputeListID compute_list = rd->compute_list_begin(); |
| 1911 | rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline); |
| 1912 | rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0); |
| 1913 | rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set, 1); |
| 1914 | |
| 1915 | push_constant.ray_from = k * max_rays; |
| 1916 | push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count)); |
| 1917 | rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant)); |
| 1918 | rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z); |
| 1919 | |
| 1920 | rd->compute_list_end(); |
| 1921 | rd->submit(); |
| 1922 | rd->sync(); |
| 1923 | |
| 1924 | count++; |
| 1925 | if (p_step_function) { |
| 1926 | int total = (atlas_slices * x_regions * y_regions * ray_iterations); |
| 1927 | int percent = count * 100 / total; |
| 1928 | float p = float(count) / total * 0.1; |
| 1929 | if (p_step_function(0.6 + p, vformat(RTR("Integrate indirect lighting %d%%"), percent), p_bake_userdata, false)) { |
| 1930 | FREE_TEXTURES |
| 1931 | FREE_BUFFERS |
| 1932 | FREE_RASTER_RESOURCES |
| 1933 | FREE_COMPUTE_RESOURCES |
| 1934 | memdelete(rd); |
| 1935 | if (rcd != nullptr) { |
| 1936 | memdelete(rcd); |
| 1937 | } |
| 1938 | return BAKE_ERROR_USER_ABORTED; |
| 1939 | } |
| 1940 | } |
| 1941 | } |
| 1942 | } |
| 1943 | } |
| 1944 | } |
| 1945 | } |
| 1946 | |
| 1947 | /* LIGHTPROBES */ |
| 1948 | |
| 1949 | RID light_probe_buffer; |
| 1950 | |
| 1951 | if (probe_positions.size()) { |
| 1952 | light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size()); |
| 1953 | |
| 1954 | if (p_step_function) { |
| 1955 | if (p_step_function(0.7, RTR("Baking light probes"), p_bake_userdata, true)) { |
| 1956 | FREE_TEXTURES |
| 1957 | FREE_BUFFERS |
| 1958 | FREE_RASTER_RESOURCES |
| 1959 | FREE_COMPUTE_RESOURCES |
| 1960 | if (probe_positions.size() > 0) { |
| 1961 | rd->free_rid(light_probe_buffer); |
| 1962 | } |
| 1963 | memdelete(rd); |
| 1964 | if (rcd != nullptr) { |
| 1965 | memdelete(rcd); |
| 1966 | } |
| 1967 | return BAKE_ERROR_USER_ABORTED; |
| 1968 | } |
| 1969 | } |
| 1970 | |
| 1971 | Vector<RD::Uniform> uniforms; |
| 1972 | { |
| 1973 | { |
| 1974 | RD::Uniform u; |
| 1975 | u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; |
| 1976 | u.binding = 0; |
| 1977 | u.append_id(light_probe_buffer); |
| 1978 | uniforms.push_back(u); |
| 1979 | } |
| 1980 | { |
| 1981 | RD::Uniform u; |
| 1982 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1983 | u.binding = 1; |
| 1984 | u.append_id(light_source_tex); |
| 1985 | uniforms.push_back(u); |
| 1986 | } |
| 1987 | { |
| 1988 | RD::Uniform u; |
| 1989 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 1990 | u.binding = 2; |
| 1991 | u.append_id(light_environment_tex); |
| 1992 | uniforms.push_back(u); |
| 1993 | } |
| 1994 | } |
| 1995 | RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1); |
| 1996 | |
| 1997 | switch (p_quality) { |
| 1998 | case BAKE_QUALITY_LOW: { |
| 1999 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count"); |
| 2000 | } break; |
| 2001 | case BAKE_QUALITY_MEDIUM: { |
| 2002 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count"); |
| 2003 | } break; |
| 2004 | case BAKE_QUALITY_HIGH: { |
| 2005 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count"); |
| 2006 | } break; |
| 2007 | case BAKE_QUALITY_ULTRA: { |
| 2008 | push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count"); |
| 2009 | } break; |
| 2010 | } |
| 2011 | |
| 2012 | push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u); |
| 2013 | push_constant.probe_count = probe_positions.size(); |
| 2014 | |
| 2015 | int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass"); |
| 2016 | int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays); |
| 2017 | |
| 2018 | for (int i = 0; i < ray_iterations; i++) { |
| 2019 | RD::ComputeListID compute_list = rd->compute_list_begin(); |
| 2020 | rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline); |
| 2021 | rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0); |
| 2022 | rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1); |
| 2023 | |
| 2024 | push_constant.ray_from = i * max_rays; |
| 2025 | push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count)); |
| 2026 | rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant)); |
| 2027 | rd->compute_list_dispatch(compute_list, Math::division_round_up((int)probe_positions.size(), 64), 1, 1); |
| 2028 | |
| 2029 | rd->compute_list_end(); //done |
| 2030 | rd->submit(); |
| 2031 | rd->sync(); |
| 2032 | |
| 2033 | if (p_step_function) { |
| 2034 | int percent = i * 100 / ray_iterations; |
| 2035 | float p = float(i) / ray_iterations * 0.1; |
| 2036 | if (p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false)) { |
| 2037 | FREE_TEXTURES |
| 2038 | FREE_BUFFERS |
| 2039 | FREE_RASTER_RESOURCES |
| 2040 | FREE_COMPUTE_RESOURCES |
| 2041 | if (probe_positions.size() > 0) { |
| 2042 | rd->free_rid(light_probe_buffer); |
| 2043 | } |
| 2044 | memdelete(rd); |
| 2045 | if (rcd != nullptr) { |
| 2046 | memdelete(rcd); |
| 2047 | } |
| 2048 | return BAKE_ERROR_USER_ABORTED; |
| 2049 | } |
| 2050 | } |
| 2051 | } |
| 2052 | } |
| 2053 | |
| 2054 | #if 0 |
| 2055 | for (int i = 0; i < probe_positions.size(); i++) { |
| 2056 | Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8); |
| 2057 | for (int j = 0; j < 6; j++) { |
| 2058 | Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j); |
| 2059 | Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s); |
| 2060 | img2->convert(Image::FORMAT_RGB8); |
| 2061 | img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2)); |
| 2062 | } |
| 2063 | img->save_png("res://3_light_probe_" + itos(i) + ".png"); |
| 2064 | } |
| 2065 | #endif |
| 2066 | |
| 2067 | /* DENOISE */ |
| 2068 | |
| 2069 | if (p_bake_sh) { |
| 2070 | SWAP(light_accum_tex, light_accum_tex2); |
| 2071 | BakeError error = _pack_l1(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices); |
| 2072 | if (unlikely(error != BAKE_OK)) { |
| 2073 | return error; |
| 2074 | } |
| 2075 | } |
| 2076 | |
| 2077 | if (p_use_denoiser) { |
| 2078 | if (p_step_function) { |
| 2079 | if (p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true)) { |
| 2080 | FREE_TEXTURES |
| 2081 | FREE_BUFFERS |
| 2082 | FREE_RASTER_RESOURCES |
| 2083 | FREE_COMPUTE_RESOURCES |
| 2084 | if (probe_positions.size() > 0) { |
| 2085 | rd->free_rid(light_probe_buffer); |
| 2086 | } |
| 2087 | memdelete(rd); |
| 2088 | if (rcd != nullptr) { |
| 2089 | memdelete(rcd); |
| 2090 | } |
| 2091 | return BAKE_ERROR_USER_ABORTED; |
| 2092 | } |
| 2093 | } |
| 2094 | |
| 2095 | { |
| 2096 | BakeError error; |
| 2097 | if (denoiser == 1) { |
| 2098 | // OIDN (external). |
| 2099 | error = _denoise_oidn(rd, light_accum_tex, normal_tex, light_accum_tex, atlas_size, atlas_slices, p_bake_sh, false, oidn_path); |
| 2100 | } else { |
| 2101 | // JNLM (built-in). |
| 2102 | SWAP(light_accum_tex, light_accum_tex2); |
| 2103 | error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, normal_tex, light_accum_tex, unocclude_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, p_bake_sh, p_step_function, p_bake_userdata); |
| 2104 | } |
| 2105 | if (unlikely(error != BAKE_OK)) { |
| 2106 | return error; |
| 2107 | } |
| 2108 | } |
| 2109 | |
| 2110 | if (p_bake_shadowmask) { |
| 2111 | BakeError error; |
| 2112 | if (denoiser == 1) { |
| 2113 | // OIDN (external). |
| 2114 | error = _denoise_oidn(rd, shadowmask_tex, normal_tex, shadowmask_tex, atlas_size, atlas_slices, false, true, oidn_path); |
| 2115 | } else { |
| 2116 | // JNLM (built-in). |
| 2117 | SWAP(shadowmask_tex, shadowmask_tex2); |
| 2118 | error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, normal_tex, shadowmask_tex, unocclude_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, false, p_step_function, p_bake_userdata); |
| 2119 | } |
| 2120 | if (unlikely(error != BAKE_OK)) { |
| 2121 | return error; |
| 2122 | } |
| 2123 | } |
| 2124 | } |
| 2125 | |
| 2126 | /* DILATE */ |
| 2127 | |
| 2128 | { |
| 2129 | SWAP(light_accum_tex, light_accum_tex2); |
| 2130 | BakeError error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices * (p_bake_sh ? 4 : 1)); |
| 2131 | if (unlikely(error != BAKE_OK)) { |
| 2132 | return error; |
| 2133 | } |
| 2134 | |
| 2135 | if (p_bake_shadowmask) { |
| 2136 | SWAP(shadowmask_tex, shadowmask_tex2); |
| 2137 | error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, shadowmask_tex, atlas_size, atlas_slices); |
| 2138 | if (unlikely(error != BAKE_OK)) { |
| 2139 | return error; |
| 2140 | } |
| 2141 | } |
| 2142 | } |
| 2143 | |
| 2144 | #ifdef DEBUG_TEXTURES |
| 2145 | |
| 2146 | for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { |
| 2147 | Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); |
| 2148 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); |
| 2149 | img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false); |
| 2150 | } |
| 2151 | #endif |
| 2152 | |
| 2153 | /* BLEND SEAMS */ |
| 2154 | //shaders |
| 2155 | Ref<RDShaderFile> blendseams_shader; |
| 2156 | blendseams_shader.instantiate(); |
| 2157 | err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl); |
| 2158 | if (err != OK) { |
| 2159 | FREE_TEXTURES |
| 2160 | FREE_BUFFERS |
| 2161 | FREE_RASTER_RESOURCES |
| 2162 | FREE_COMPUTE_RESOURCES |
| 2163 | memdelete(rd); |
| 2164 | |
| 2165 | if (rcd != nullptr) { |
| 2166 | memdelete(rcd); |
| 2167 | } |
| 2168 | |
| 2169 | blendseams_shader->print_errors("blendseams_shader"); |
| 2170 | } |
| 2171 | ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 2172 | |
| 2173 | RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines")); |
| 2174 | |
| 2175 | ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 2176 | |
| 2177 | RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles")); |
| 2178 | |
| 2179 | ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); |
| 2180 | |
| 2181 | #define FREE_BLENDSEAMS_RESOURCES \ |
| 2182 | rd->free_rid(blendseams_line_raster_shader); \ |
| 2183 | rd->free_rid(blendseams_triangle_raster_shader); |
| 2184 | |
| 2185 | { |
| 2186 | //pre copy |
| 2187 | for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { |
| 2188 | rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i); |
| 2189 | } |
| 2190 | |
| 2191 | Vector<RID> framebuffers; |
| 2192 | for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { |
| 2193 | RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0); |
| 2194 | Vector<RID> fb; |
| 2195 | fb.push_back(slice_tex); |
| 2196 | fb.push_back(raster_depth_buffer); |
| 2197 | framebuffers.push_back(rd->framebuffer_create(fb)); |
| 2198 | } |
| 2199 | |
| 2200 | Vector<RD::Uniform> uniforms; |
| 2201 | { |
| 2202 | { |
| 2203 | RD::Uniform u; |
| 2204 | u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; |
| 2205 | u.binding = 0; |
| 2206 | u.append_id(light_accum_tex2); |
| 2207 | uniforms.push_back(u); |
| 2208 | } |
| 2209 | } |
| 2210 | |
| 2211 | RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1); |
| 2212 | |
| 2213 | bool debug = false; |
| 2214 | RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1); |
| 2215 | bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO; |
| 2216 | bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE; |
| 2217 | |
| 2218 | RD::PipelineDepthStencilState ds; |
| 2219 | ds.enable_depth_test = true; |
| 2220 | ds.enable_depth_write = true; |
| 2221 | ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending |
| 2222 | |
| 2223 | RID blendseams_line_raster_pipeline = rd->render_pipeline_create(blendseams_line_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_LINES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0); |
| 2224 | RID blendseams_triangle_raster_pipeline = rd->render_pipeline_create(blendseams_triangle_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0); |
| 2225 | |
| 2226 | uint32_t seam_offset = 0; |
| 2227 | uint32_t triangle_offset = 0; |
| 2228 | |
| 2229 | for (int i = 0; i < atlas_slices; i++) { |
| 2230 | int subslices = (p_bake_sh ? 4 : 1); |
| 2231 | |
| 2232 | if (slice_seam_count[i] == 0) { |
| 2233 | continue; |
| 2234 | } |
| 2235 | |
| 2236 | for (int k = 0; k < subslices; k++) { |
| 2237 | RasterSeamsPushConstant seams_push_constant; |
| 2238 | seams_push_constant.slice = uint32_t(i * subslices + k); |
| 2239 | seams_push_constant.debug = debug; |
| 2240 | |
| 2241 | // Store the current subslice in the breadcrumb. |
| 2242 | RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i * subslices + k], RD::DRAW_CLEAR_DEPTH, Vector<Color>(), 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS | seams_push_constant.slice); |
| 2243 | |
| 2244 | rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0); |
| 2245 | rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1); |
| 2246 | |
| 2247 | const int uv_offset_count = 9; |
| 2248 | static const Vector3 uv_offsets[uv_offset_count] = { |
| 2249 | Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards |
| 2250 | Vector3(0, 1, 0.2), |
| 2251 | Vector3(0, -1, 0.2), |
| 2252 | Vector3(1, 0, 0.2), |
| 2253 | Vector3(-1, 0, 0.2), |
| 2254 | Vector3(-1, -1, 0.1), |
| 2255 | Vector3(1, -1, 0.1), |
| 2256 | Vector3(1, 1, 0.1), |
| 2257 | Vector3(-1, 1, 0.1), |
| 2258 | }; |
| 2259 | |
| 2260 | /* step 1 use lines to blend the edges */ |
| 2261 | { |
| 2262 | seams_push_constant.base_index = seam_offset; |
| 2263 | rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline); |
| 2264 | seams_push_constant.uv_offset[0] = (uv_offsets[0].x - 0.5f) / float(atlas_size.width); |
| 2265 | seams_push_constant.uv_offset[1] = (uv_offsets[0].y - 0.5f) / float(atlas_size.height); |
| 2266 | seams_push_constant.blend = uv_offsets[0].z; |
| 2267 | |
| 2268 | rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant)); |
| 2269 | rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4); |
| 2270 | } |
| 2271 | |
| 2272 | /* step 2 use triangles to mask the interior */ |
| 2273 | |
| 2274 | { |
| 2275 | seams_push_constant.base_index = triangle_offset; |
| 2276 | rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline); |
| 2277 | seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask |
| 2278 | |
| 2279 | rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant)); |
| 2280 | rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3); |
| 2281 | } |
| 2282 | /* step 3 blend around the triangle */ |
| 2283 | |
| 2284 | rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline); |
| 2285 | |
| 2286 | for (int j = 1; j < uv_offset_count; j++) { |
| 2287 | seams_push_constant.base_index = seam_offset; |
| 2288 | seams_push_constant.uv_offset[0] = (uv_offsets[j].x - 0.5f) / float(atlas_size.width); |
| 2289 | seams_push_constant.uv_offset[1] = (uv_offsets[j].y - 0.5f) / float(atlas_size.height); |
| 2290 | seams_push_constant.blend = uv_offsets[0].z; |
| 2291 | |
| 2292 | rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant)); |
| 2293 | rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4); |
| 2294 | } |
| 2295 | rd->draw_list_end(); |
| 2296 | } |
| 2297 | seam_offset += slice_seam_count[i]; |
| 2298 | triangle_offset += slice_triangle_count[i]; |
| 2299 | } |
| 2300 | } |
| 2301 | |
| 2302 | #ifdef DEBUG_TEXTURES |
| 2303 | |
| 2304 | for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { |
| 2305 | Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); |
| 2306 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); |
| 2307 | img->save_exr("res://5_blendseams" + itos(i) + ".exr", false); |
| 2308 | } |
| 2309 | #endif |
| 2310 | |
| 2311 | if (p_step_function) { |
| 2312 | p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true); |
| 2313 | } |
| 2314 | |
| 2315 | for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) { |
| 2316 | Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i); |
| 2317 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); |
| 2318 | img->convert(Image::FORMAT_RGBH); //remove alpha |
| 2319 | lightmap_textures.push_back(img); |
| 2320 | } |
| 2321 | |
| 2322 | if (p_bake_shadowmask) { |
| 2323 | for (int i = 0; i < atlas_slices; i++) { |
| 2324 | Vector<uint8_t> s = rd->texture_get_data(shadowmask_tex, i); |
| 2325 | Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8, s); |
| 2326 | img->convert(Image::FORMAT_R8); |
| 2327 | shadowmask_textures.push_back(img); |
| 2328 | } |
| 2329 | } |
| 2330 | |
| 2331 | if (probe_positions.size() > 0) { |
| 2332 | probe_values.resize(probe_positions.size() * 9); |
| 2333 | Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer); |
| 2334 | memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size()); |
| 2335 | rd->free_rid(light_probe_buffer); |
| 2336 | |
| 2337 | #ifdef DEBUG_TEXTURES |
| 2338 | { |
| 2339 | Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data); |
| 2340 | img2->save_exr("res://6_lightprobes.exr", false); |
| 2341 | } |
| 2342 | #endif |
| 2343 | } |
| 2344 | |
| 2345 | FREE_TEXTURES |
| 2346 | FREE_BUFFERS |
| 2347 | FREE_RASTER_RESOURCES |
| 2348 | FREE_COMPUTE_RESOURCES |
| 2349 | FREE_BLENDSEAMS_RESOURCES |
| 2350 | |
| 2351 | memdelete(rd); |
| 2352 | |
| 2353 | if (rcd != nullptr) { |
| 2354 | memdelete(rcd); |
| 2355 | } |
| 2356 | |
| 2357 | return BAKE_OK; |
| 2358 | } |
| 2359 | |
| 2360 | int LightmapperRD::get_bake_texture_count() const { |
| 2361 | return lightmap_textures.size(); |
| 2362 | } |
| 2363 | |
| 2364 | Ref<Image> LightmapperRD::get_bake_texture(int p_index) const { |
| 2365 | ERR_FAIL_INDEX_V(p_index, lightmap_textures.size(), Ref<Image>()); |
| 2366 | return lightmap_textures[p_index]; |
| 2367 | } |
| 2368 | |
| 2369 | int LightmapperRD::get_shadowmask_texture_count() const { |
| 2370 | return shadowmask_textures.size(); |
| 2371 | } |
| 2372 | |
| 2373 | Ref<Image> LightmapperRD::get_shadowmask_texture(int p_index) const { |
| 2374 | ERR_FAIL_INDEX_V(p_index, shadowmask_textures.size(), Ref<Image>()); |
| 2375 | return shadowmask_textures[p_index]; |
| 2376 | } |
| 2377 | |
| 2378 | int LightmapperRD::get_bake_mesh_count() const { |
| 2379 | return mesh_instances.size(); |
| 2380 | } |
| 2381 | |
| 2382 | Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const { |
| 2383 | ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant()); |
| 2384 | return mesh_instances[p_index].data.userdata; |
| 2385 | } |
| 2386 | |
| 2387 | Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const { |
| 2388 | ERR_FAIL_COND_V(lightmap_textures.is_empty(), Rect2()); |
| 2389 | Rect2 uv_ofs; |
| 2390 | Vector2 atlas_size = Vector2(lightmap_textures[0]->get_width(), lightmap_textures[0]->get_height()); |
| 2391 | uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size; |
| 2392 | uv_ofs.size = Vector2(mesh_instances[p_index].data.albedo_on_uv2->get_width(), mesh_instances[p_index].data.albedo_on_uv2->get_height()) / atlas_size; |
| 2393 | return uv_ofs; |
| 2394 | } |
| 2395 | |
| 2396 | int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const { |
| 2397 | ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant()); |
| 2398 | return mesh_instances[p_index].slice; |
| 2399 | } |
| 2400 | |
| 2401 | int LightmapperRD::get_bake_probe_count() const { |
| 2402 | return probe_positions.size(); |
| 2403 | } |
| 2404 | |
| 2405 | Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const { |
| 2406 | ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant()); |
| 2407 | return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]); |
| 2408 | } |
| 2409 | |
| 2410 | Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const { |
| 2411 | ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>()); |
| 2412 | Vector<Color> ret; |
| 2413 | ret.resize(9); |
| 2414 | memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9); |
| 2415 | return ret; |
| 2416 | } |
| 2417 | |
| 2418 | LightmapperRD::LightmapperRD() { |
| 2419 | } |