Debian Codegraph @

servers/rendering/renderer_scene_cull.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* renderer_scene_cull.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 "renderer_scene_cull.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/object/worker_thread_pool.h"
35 #include "rendering_light_culler.h"
36 #include "rendering_server_default.h"
37
38 #if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
39 // This is used only to obtain node paths for user-friendly physics interpolation warnings.
40 #include "scene/main/node.h"
41 #endif
42
43 /* HALTON SEQUENCE */
44
45 #ifndef _3D_DISABLED
46 static float get_halton_value(int p_index, int p_base) {
47 float f = 1;
48 float r = 0;
49 while (p_index > 0) {
50 f = f / static_cast<float>(p_base);
51 r = r + f * (p_index % p_base);
52 p_index = p_index / p_base;
53 }
54 return r * 2.0f - 1.0f;
55 }
56 #endif // _3D_DISABLED
57
58 /* EVENT QUEUING */
59
60 void RendererSceneCull::tick() {
61 if (_interpolation_data.interpolation_enabled) {
62 update_interpolation_tick(true);
63 }
64 }
65
66 void RendererSceneCull::pre_draw(bool p_will_draw) {
67 if (_interpolation_data.interpolation_enabled) {
68 update_interpolation_frame(p_will_draw);
69 }
70 }
71
72 /* CAMERA API */
73
74 RID RendererSceneCull::camera_allocate() {
75 return camera_owner.allocate_rid();
76 }
77 void RendererSceneCull::camera_initialize(RID p_rid) {
78 camera_owner.initialize_rid(p_rid);
79 }
80
81 void RendererSceneCull::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
82 Camera *camera = camera_owner.get_or_null(p_camera);
83 ERR_FAIL_NULL(camera);
84 camera->type = Camera::PERSPECTIVE;
85 camera->fov = p_fovy_degrees;
86 camera->znear = p_z_near;
87 camera->zfar = p_z_far;
88 }
89
90 void RendererSceneCull::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
91 Camera *camera = camera_owner.get_or_null(p_camera);
92 ERR_FAIL_NULL(camera);
93 camera->type = Camera::ORTHOGONAL;
94 camera->size = p_size;
95 camera->znear = p_z_near;
96 camera->zfar = p_z_far;
97 }
98
99 void RendererSceneCull::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
100 Camera *camera = camera_owner.get_or_null(p_camera);
101 ERR_FAIL_NULL(camera);
102 camera->type = Camera::FRUSTUM;
103 camera->size = p_size;
104 camera->offset = p_offset;
105 camera->znear = p_z_near;
106 camera->zfar = p_z_far;
107 }
108
109 void RendererSceneCull::camera_set_transform(RID p_camera, const Transform3D &p_transform) {
110 Camera *camera = camera_owner.get_or_null(p_camera);
111 ERR_FAIL_NULL(camera);
112
113 camera->transform = p_transform.orthonormalized();
114 }
115
116 void RendererSceneCull::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
117 Camera *camera = camera_owner.get_or_null(p_camera);
118 ERR_FAIL_NULL(camera);
119
120 camera->visible_layers = p_layers;
121 }
122
123 void RendererSceneCull::camera_set_environment(RID p_camera, RID p_env) {
124 Camera *camera = camera_owner.get_or_null(p_camera);
125 ERR_FAIL_NULL(camera);
126 camera->env = p_env;
127 }
128
129 void RendererSceneCull::camera_set_camera_attributes(RID p_camera, RID p_attributes) {
130 Camera *camera = camera_owner.get_or_null(p_camera);
131 ERR_FAIL_NULL(camera);
132 camera->attributes = p_attributes;
133 }
134
135 void RendererSceneCull::camera_set_compositor(RID p_camera, RID p_compositor) {
136 Camera *camera = camera_owner.get_or_null(p_camera);
137 ERR_FAIL_NULL(camera);
138 camera->compositor = p_compositor;
139 }
140
141 void RendererSceneCull::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
142 Camera *camera = camera_owner.get_or_null(p_camera);
143 ERR_FAIL_NULL(camera);
144 camera->vaspect = p_enable;
145 }
146
147 bool RendererSceneCull::is_camera(RID p_camera) const {
148 return camera_owner.owns(p_camera);
149 }
150
151 /* OCCLUDER API */
152
153 RID RendererSceneCull::occluder_allocate() {
154 return RendererSceneOcclusionCull::get_singleton()->occluder_allocate();
155 }
156
157 void RendererSceneCull::occluder_initialize(RID p_rid) {
158 RendererSceneOcclusionCull::get_singleton()->occluder_initialize(p_rid);
159 }
160
161 void RendererSceneCull::occluder_set_mesh(RID p_occluder, const PackedVector3Array &p_vertices, const PackedInt32Array &p_indices) {
162 RendererSceneOcclusionCull::get_singleton()->occluder_set_mesh(p_occluder, p_vertices, p_indices);
163 }
164
165 /* SCENARIO API */
166
167 void RendererSceneCull::_instance_pair(Instance *p_A, Instance *p_B) {
168 RendererSceneCull *self = (RendererSceneCull *)singleton;
169 Instance *A = p_A;
170 Instance *B = p_B;
171
172 //instance indices are designed so greater always contains lesser
173 if (A->base_type > B->base_type) {
174 SWAP(A, B); //lesser always first
175 }
176
177 if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
178 InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
179 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
180
181 if (!(light->cull_mask & A->layer_mask)) {
182 // Early return if the object's layer mask doesn't match the light's cull mask.
183 return;
184 }
185
186 geom->lights.insert(B);
187 light->geometries.insert(A);
188
189 if (geom->can_cast_shadows) {
190 light->make_shadow_dirty();
191 }
192
193 if (A->scenario && A->array_index >= 0) {
194 InstanceData &idata = A->scenario->instance_data[A->array_index];
195 idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
196 }
197
198 if (light->uses_projector) {
199 geom->projector_count++;
200 if (geom->projector_count == 1) {
201 InstanceData &idata = A->scenario->instance_data[A->array_index];
202 idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
203 }
204 }
205
206 if (light->uses_softshadow) {
207 geom->softshadow_count++;
208 if (geom->softshadow_count == 1) {
209 InstanceData &idata = A->scenario->instance_data[A->array_index];
210 idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
211 }
212 }
213
214 } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
215 if (!(A->layer_mask & RSG::light_storage->reflection_probe_get_reflection_mask(B->base))) {
216 // Early return if the object's layer mask doesn't match the reflection mask.
217 return;
218 }
219
220 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
221 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
222
223 geom->reflection_probes.insert(B);
224 reflection_probe->geometries.insert(A);
225
226 if (A->scenario && A->array_index >= 0) {
227 InstanceData &idata = A->scenario->instance_data[A->array_index];
228 idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
229 }
230
231 } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
232 InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
233 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
234
235 if (!(decal->cull_mask & A->layer_mask)) {
236 // Early return if the object's layer mask doesn't match the decal's cull mask.
237 return;
238 }
239
240 geom->decals.insert(B);
241 decal->geometries.insert(A);
242
243 if (A->scenario && A->array_index >= 0) {
244 InstanceData &idata = A->scenario->instance_data[A->array_index];
245 idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
246 }
247
248 } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
249 InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
250 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
251
252 if (A->dynamic_gi) {
253 geom->lightmap_captures.insert(B);
254 lightmap_data->geometries.insert(A);
255
256 if (A->scenario && A->array_index >= 0) {
257 InstanceData &idata = A->scenario->instance_data[A->array_index];
258 idata.flags |= InstanceData::FLAG_LIGHTMAP_CAPTURE;
259 }
260 ((RendererSceneCull *)self)->_instance_queue_update(A, false, false); //need to update capture
261 }
262
263 } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_VOXEL_GI) && B->base_type == RS::INSTANCE_VOXEL_GI && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
264 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
265 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
266
267 geom->voxel_gi_instances.insert(B);
268
269 if (A->dynamic_gi) {
270 voxel_gi->dynamic_geometries.insert(A);
271 } else {
272 voxel_gi->geometries.insert(A);
273 }
274
275 if (A->scenario && A->array_index >= 0) {
276 InstanceData &idata = A->scenario->instance_data[A->array_index];
277 idata.flags |= InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
278 }
279
280 } else if (B->base_type == RS::INSTANCE_VOXEL_GI && A->base_type == RS::INSTANCE_LIGHT) {
281 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
282 voxel_gi->lights.insert(A);
283 } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
284 InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
285
286 if ((collision->cull_mask & A->layer_mask)) {
287 RSG::particles_storage->particles_add_collision(A->base, collision->instance);
288 }
289 }
290 }
291
292 void RendererSceneCull::_instance_unpair(Instance *p_A, Instance *p_B) {
293 RendererSceneCull *self = singleton;
294 Instance *A = p_A;
295 Instance *B = p_B;
296
297 //instance indices are designed so greater always contains lesser
298 if (A->base_type > B->base_type) {
299 SWAP(A, B); //lesser always first
300 }
301
302 if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
303 InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
304 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
305
306 if (!(light->cull_mask & A->layer_mask)) {
307 // Early return if the object's layer mask doesn't match the light's cull mask.
308 return;
309 }
310
311 geom->lights.erase(B);
312 light->geometries.erase(A);
313
314 if (geom->can_cast_shadows) {
315 light->make_shadow_dirty();
316 }
317
318 if (A->scenario && A->array_index >= 0) {
319 InstanceData &idata = A->scenario->instance_data[A->array_index];
320 idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
321 }
322
323 if (light->uses_projector) {
324 #ifdef DEBUG_ENABLED
325 if (geom->projector_count == 0) {
326 ERR_PRINT("geom->projector_count==0 - BUG!");
327 }
328 #endif
329 geom->projector_count--;
330 if (geom->projector_count == 0) {
331 InstanceData &idata = A->scenario->instance_data[A->array_index];
332 idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
333 }
334 }
335
336 if (light->uses_softshadow) {
337 #ifdef DEBUG_ENABLED
338 if (geom->softshadow_count == 0) {
339 ERR_PRINT("geom->softshadow_count==0 - BUG!");
340 }
341 #endif
342 geom->softshadow_count--;
343 if (geom->softshadow_count == 0) {
344 InstanceData &idata = A->scenario->instance_data[A->array_index];
345 idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
346 }
347 }
348
349 } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
350 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
351 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
352
353 geom->reflection_probes.erase(B);
354 reflection_probe->geometries.erase(A);
355
356 if (A->scenario && A->array_index >= 0) {
357 InstanceData &idata = A->scenario->instance_data[A->array_index];
358 idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
359 }
360
361 } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
362 InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
363 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
364
365 if (!(decal->cull_mask & A->layer_mask)) {
366 // Early return if the object's layer mask doesn't match the decal's cull mask.
367 return;
368 }
369
370 geom->decals.erase(B);
371 decal->geometries.erase(A);
372
373 if (A->scenario && A->array_index >= 0) {
374 InstanceData &idata = A->scenario->instance_data[A->array_index];
375 idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
376 }
377
378 } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
379 InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
380 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
381 if (A->dynamic_gi) {
382 geom->lightmap_captures.erase(B);
383
384 if (geom->lightmap_captures.is_empty() && A->scenario && A->array_index >= 0) {
385 InstanceData &idata = A->scenario->instance_data[A->array_index];
386 idata.flags &= ~InstanceData::FLAG_LIGHTMAP_CAPTURE;
387 }
388
389 lightmap_data->geometries.erase(A);
390 self->_instance_queue_update(A, false, false); //need to update capture
391 }
392
393 } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_VOXEL_GI) && B->base_type == RS::INSTANCE_VOXEL_GI && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
394 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
395 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
396
397 geom->voxel_gi_instances.erase(B);
398 if (A->dynamic_gi) {
399 voxel_gi->dynamic_geometries.erase(A);
400 } else {
401 voxel_gi->geometries.erase(A);
402 }
403
404 if (A->scenario && A->array_index >= 0) {
405 InstanceData &idata = A->scenario->instance_data[A->array_index];
406 idata.flags |= InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
407 }
408
409 } else if (B->base_type == RS::INSTANCE_VOXEL_GI && A->base_type == RS::INSTANCE_LIGHT) {
410 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
411 voxel_gi->lights.erase(A);
412 } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
413 InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
414
415 if ((collision->cull_mask & A->layer_mask)) {
416 RSG::particles_storage->particles_remove_collision(A->base, collision->instance);
417 }
418 }
419 }
420
421 RID RendererSceneCull::scenario_allocate() {
422 return scenario_owner.allocate_rid();
423 }
424 void RendererSceneCull::scenario_initialize(RID p_rid) {
425 scenario_owner.initialize_rid(p_rid);
426
427 Scenario *scenario = scenario_owner.get_or_null(p_rid);
428 scenario->self = p_rid;
429
430 scenario->reflection_probe_shadow_atlas = RSG::light_storage->shadow_atlas_create();
431 RSG::light_storage->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
432 RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
433 RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
434 RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
435 RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
436
437 scenario->reflection_atlas = RSG::light_storage->reflection_atlas_create();
438
439 scenario->instance_aabbs.set_page_pool(&instance_aabb_page_pool);
440 scenario->instance_data.set_page_pool(&instance_data_page_pool);
441 scenario->instance_visibility.set_page_pool(&instance_visibility_data_page_pool);
442
443 RendererSceneOcclusionCull::get_singleton()->add_scenario(p_rid);
444 }
445
446 void RendererSceneCull::scenario_set_environment(RID p_scenario, RID p_environment) {
447 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
448 ERR_FAIL_NULL(scenario);
449 scenario->environment = p_environment;
450 }
451
452 void RendererSceneCull::scenario_set_camera_attributes(RID p_scenario, RID p_camera_attributes) {
453 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
454 ERR_FAIL_NULL(scenario);
455 scenario->camera_attributes = p_camera_attributes;
456 }
457
458 void RendererSceneCull::scenario_set_compositor(RID p_scenario, RID p_compositor) {
459 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
460 ERR_FAIL_NULL(scenario);
461 scenario->compositor = p_compositor;
462 }
463
464 void RendererSceneCull::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
465 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
466 ERR_FAIL_NULL(scenario);
467 scenario->fallback_environment = p_environment;
468 }
469
470 void RendererSceneCull::scenario_set_reflection_atlas_size(RID p_scenario, int p_reflection_size, int p_reflection_count) {
471 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
472 ERR_FAIL_NULL(scenario);
473 RSG::light_storage->reflection_atlas_set_size(scenario->reflection_atlas, p_reflection_size, p_reflection_count);
474 }
475
476 bool RendererSceneCull::is_scenario(RID p_scenario) const {
477 return scenario_owner.owns(p_scenario);
478 }
479
480 RID RendererSceneCull::scenario_get_environment(RID p_scenario) {
481 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
482 ERR_FAIL_NULL_V(scenario, RID());
483 return scenario->environment;
484 }
485
486 void RendererSceneCull::scenario_remove_viewport_visibility_mask(RID p_scenario, RID p_viewport) {
487 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
488 ERR_FAIL_NULL(scenario);
489 if (!scenario->viewport_visibility_masks.has(p_viewport)) {
490 return;
491 }
492
493 uint64_t mask = scenario->viewport_visibility_masks[p_viewport];
494 scenario->used_viewport_visibility_bits &= ~mask;
495 scenario->viewport_visibility_masks.erase(p_viewport);
496 }
497
498 void RendererSceneCull::scenario_add_viewport_visibility_mask(RID p_scenario, RID p_viewport) {
499 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
500 ERR_FAIL_NULL(scenario);
501 ERR_FAIL_COND(scenario->viewport_visibility_masks.has(p_viewport));
502
503 uint64_t new_mask = 1;
504 while (new_mask & scenario->used_viewport_visibility_bits) {
505 new_mask <<= 1;
506 }
507
508 if (new_mask == 0) {
509 ERR_PRINT("Only 64 viewports per scenario allowed when using visibility ranges.");
510 new_mask = ((uint64_t)1) << 63;
511 }
512
513 scenario->viewport_visibility_masks[p_viewport] = new_mask;
514 scenario->used_viewport_visibility_bits |= new_mask;
515 }
516
517 /* INSTANCING API */
518
519 void RendererSceneCull::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_dependencies) const {
520 if (p_update_aabb) {
521 p_instance->update_aabb = true;
522 }
523 if (p_update_dependencies) {
524 p_instance->update_dependencies = true;
525 }
526
527 if (p_instance->update_item.in_list()) {
528 return;
529 }
530
531 _instance_update_list.add(&p_instance->update_item);
532 }
533
534 RID RendererSceneCull::instance_allocate() {
535 return instance_owner.allocate_rid();
536 }
537 void RendererSceneCull::instance_initialize(RID p_rid) {
538 instance_owner.initialize_rid(p_rid);
539 Instance *instance = instance_owner.get_or_null(p_rid);
540 instance->self = p_rid;
541 }
542
543 void RendererSceneCull::_instance_update_mesh_instance(Instance *p_instance) const {
544 bool needs_instance = RSG::mesh_storage->mesh_needs_instance(p_instance->base, p_instance->skeleton.is_valid());
545 if (needs_instance != p_instance->mesh_instance.is_valid()) {
546 if (needs_instance) {
547 p_instance->mesh_instance = RSG::mesh_storage->mesh_instance_create(p_instance->base);
548
549 } else {
550 RSG::mesh_storage->mesh_instance_free(p_instance->mesh_instance);
551 p_instance->mesh_instance = RID();
552 }
553
554 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
555 geom->geometry_instance->set_mesh_instance(p_instance->mesh_instance);
556
557 if (p_instance->scenario && p_instance->array_index >= 0) {
558 InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
559 if (p_instance->mesh_instance.is_valid()) {
560 idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
561 } else {
562 idata.flags &= ~InstanceData::FLAG_USES_MESH_INSTANCE;
563 }
564 }
565 }
566
567 if (p_instance->mesh_instance.is_valid()) {
568 RSG::mesh_storage->mesh_instance_set_skeleton(p_instance->mesh_instance, p_instance->skeleton);
569 }
570 }
571
572 void RendererSceneCull::instance_set_base(RID p_instance, RID p_base) {
573 Instance *instance = instance_owner.get_or_null(p_instance);
574 ERR_FAIL_NULL(instance);
575
576 Scenario *scenario = instance->scenario;
577
578 if (instance->base_type != RS::INSTANCE_NONE) {
579 //free anything related to that base
580
581 if (scenario && instance->indexer_id.is_valid()) {
582 _unpair_instance(instance);
583 }
584
585 if (instance->mesh_instance.is_valid()) {
586 RSG::mesh_storage->mesh_instance_free(instance->mesh_instance);
587 instance->mesh_instance = RID();
588 // no need to set instance data flag here, as it was freed above
589 }
590
591 switch (instance->base_type) {
592 case RS::INSTANCE_MESH:
593 case RS::INSTANCE_MULTIMESH:
594 case RS::INSTANCE_PARTICLES: {
595 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
596 scene_render->geometry_instance_free(geom->geometry_instance);
597 } break;
598 case RS::INSTANCE_LIGHT: {
599 InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
600
601 if (scenario && instance->visible && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
602 scenario->dynamic_lights.erase(light->instance);
603 }
604
605 #ifdef DEBUG_ENABLED
606 if (light->geometries.size()) {
607 ERR_PRINT("BUG, indexing did not unpair geometries from light.");
608 }
609 #endif
610 if (scenario && light->D) {
611 scenario->directional_lights.erase(light->D);
612 light->D = nullptr;
613 }
614 RSG::light_storage->light_instance_free(light->instance);
615 } break;
616 case RS::INSTANCE_PARTICLES_COLLISION: {
617 InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
618 RSG::utilities->free(collision->instance);
619 } break;
620 case RS::INSTANCE_FOG_VOLUME: {
621 InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(instance->base_data);
622 scene_render->free(volume->instance);
623 } break;
624 case RS::INSTANCE_VISIBLITY_NOTIFIER: {
625 //none
626 } break;
627 case RS::INSTANCE_REFLECTION_PROBE: {
628 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
629 RSG::light_storage->reflection_probe_instance_free(reflection_probe->instance);
630 if (reflection_probe->update_list.in_list()) {
631 reflection_probe_render_list.remove(&reflection_probe->update_list);
632 }
633 } break;
634 case RS::INSTANCE_DECAL: {
635 InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
636 RSG::texture_storage->decal_instance_free(decal->instance);
637
638 } break;
639 case RS::INSTANCE_LIGHTMAP: {
640 InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(instance->base_data);
641 //erase dependencies, since no longer a lightmap
642 while (lightmap_data->users.begin()) {
643 instance_geometry_set_lightmap((*lightmap_data->users.begin())->self, RID(), Rect2(), 0);
644 }
645 RSG::light_storage->lightmap_instance_free(lightmap_data->instance);
646 } break;
647 case RS::INSTANCE_VOXEL_GI: {
648 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
649 #ifdef DEBUG_ENABLED
650 if (voxel_gi->geometries.size()) {
651 ERR_PRINT("BUG, indexing did not unpair geometries from VoxelGI.");
652 }
653 #endif
654 #ifdef DEBUG_ENABLED
655 if (voxel_gi->lights.size()) {
656 ERR_PRINT("BUG, indexing did not unpair lights from VoxelGI.");
657 }
658 #endif
659 if (voxel_gi->update_element.in_list()) {
660 voxel_gi_update_list.remove(&voxel_gi->update_element);
661 }
662
663 scene_render->free(voxel_gi->probe_instance);
664
665 } break;
666 case RS::INSTANCE_OCCLUDER: {
667 if (scenario && instance->visible) {
668 RendererSceneOcclusionCull::get_singleton()->scenario_remove_instance(instance->scenario->self, p_instance);
669 }
670 } break;
671 default: {
672 }
673 }
674
675 if (instance->base_data) {
676 memdelete(instance->base_data);
677 instance->base_data = nullptr;
678 }
679
680 instance->materials.clear();
681 }
682
683 instance->base_type = RS::INSTANCE_NONE;
684 instance->base = RID();
685
686 if (p_base.is_valid()) {
687 instance->base_type = RSG::utilities->get_base_type(p_base);
688
689 // fix up a specific malfunctioning case before the switch, so it can be handled
690 if (instance->base_type == RS::INSTANCE_NONE && RendererSceneOcclusionCull::get_singleton()->is_occluder(p_base)) {
691 instance->base_type = RS::INSTANCE_OCCLUDER;
692 }
693
694 switch (instance->base_type) {
695 case RS::INSTANCE_NONE: {
696 ERR_PRINT_ONCE("unimplemented base type encountered in renderer scene cull");
697 return;
698 }
699 case RS::INSTANCE_LIGHT: {
700 InstanceLightData *light = memnew(InstanceLightData);
701
702 if (scenario && RSG::light_storage->light_get_type(p_base) == RS::LIGHT_DIRECTIONAL) {
703 light->D = scenario->directional_lights.push_back(instance);
704 }
705
706 light->instance = RSG::light_storage->light_instance_create(p_base);
707
708 instance->base_data = light;
709 } break;
710 case RS::INSTANCE_MESH:
711 case RS::INSTANCE_MULTIMESH:
712 case RS::INSTANCE_PARTICLES: {
713 InstanceGeometryData *geom = memnew(InstanceGeometryData);
714 instance->base_data = geom;
715 geom->geometry_instance = scene_render->geometry_instance_create(p_base);
716
717 ERR_FAIL_NULL(geom->geometry_instance);
718
719 geom->geometry_instance->set_skeleton(instance->skeleton);
720 geom->geometry_instance->set_material_override(instance->material_override);
721 geom->geometry_instance->set_material_overlay(instance->material_overlay);
722 geom->geometry_instance->set_surface_materials(instance->materials);
723 geom->geometry_instance->set_transform(instance->transform, instance->aabb, instance->transformed_aabb);
724 geom->geometry_instance->set_layer_mask(instance->layer_mask);
725 geom->geometry_instance->set_pivot_data(instance->sorting_offset, instance->use_aabb_center);
726 geom->geometry_instance->set_lod_bias(instance->lod_bias);
727 geom->geometry_instance->set_transparency(instance->transparency);
728 geom->geometry_instance->set_use_baked_light(instance->baked_light);
729 geom->geometry_instance->set_use_dynamic_gi(instance->dynamic_gi);
730 geom->geometry_instance->set_use_lightmap(RID(), instance->lightmap_uv_scale, instance->lightmap_slice_index);
731 geom->geometry_instance->set_instance_shader_uniforms_offset(instance->instance_uniforms.location());
732 geom->geometry_instance->set_cast_double_sided_shadows(instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
733 if (instance->lightmap_sh.size() == 9) {
734 geom->geometry_instance->set_lightmap_capture(instance->lightmap_sh.ptr());
735 }
736
737 for (Instance *E : instance->visibility_dependencies) {
738 Instance *dep_instance = E;
739 ERR_CONTINUE(dep_instance->array_index == -1);
740 ERR_CONTINUE(dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index != -1);
741 dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = instance->array_index;
742 }
743 } break;
744 case RS::INSTANCE_PARTICLES_COLLISION: {
745 InstanceParticlesCollisionData *collision = memnew(InstanceParticlesCollisionData);
746 collision->instance = RSG::particles_storage->particles_collision_instance_create(p_base);
747 RSG::particles_storage->particles_collision_instance_set_active(collision->instance, instance->visible);
748 instance->base_data = collision;
749 } break;
750 case RS::INSTANCE_FOG_VOLUME: {
751 InstanceFogVolumeData *volume = memnew(InstanceFogVolumeData);
752 volume->instance = scene_render->fog_volume_instance_create(p_base);
753 scene_render->fog_volume_instance_set_active(volume->instance, instance->visible);
754 instance->base_data = volume;
755 } break;
756 case RS::INSTANCE_VISIBLITY_NOTIFIER: {
757 InstanceVisibilityNotifierData *vnd = memnew(InstanceVisibilityNotifierData);
758 vnd->base = p_base;
759 instance->base_data = vnd;
760 } break;
761 case RS::INSTANCE_REFLECTION_PROBE: {
762 InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
763 reflection_probe->owner = instance;
764 instance->base_data = reflection_probe;
765
766 reflection_probe->instance = RSG::light_storage->reflection_probe_instance_create(p_base);
767 } break;
768 case RS::INSTANCE_DECAL: {
769 InstanceDecalData *decal = memnew(InstanceDecalData);
770 decal->owner = instance;
771 instance->base_data = decal;
772
773 decal->instance = RSG::texture_storage->decal_instance_create(p_base);
774 RSG::texture_storage->decal_instance_set_sorting_offset(decal->instance, instance->sorting_offset);
775 } break;
776 case RS::INSTANCE_LIGHTMAP: {
777 InstanceLightmapData *lightmap_data = memnew(InstanceLightmapData);
778 instance->base_data = lightmap_data;
779 lightmap_data->instance = RSG::light_storage->lightmap_instance_create(p_base);
780 } break;
781 case RS::INSTANCE_VOXEL_GI: {
782 InstanceVoxelGIData *voxel_gi = memnew(InstanceVoxelGIData);
783 instance->base_data = voxel_gi;
784 voxel_gi->owner = instance;
785
786 if (scenario && !voxel_gi->update_element.in_list()) {
787 voxel_gi_update_list.add(&voxel_gi->update_element);
788 }
789
790 voxel_gi->probe_instance = scene_render->voxel_gi_instance_create(p_base);
791
792 } break;
793 case RS::INSTANCE_OCCLUDER: {
794 if (scenario) {
795 RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(scenario->self, p_instance, p_base, instance->transform, instance->visible);
796 }
797 } break;
798 default: {
799 }
800 }
801
802 instance->base = p_base;
803
804 if (instance->base_type == RS::INSTANCE_MESH) {
805 _instance_update_mesh_instance(instance);
806 }
807
808 //forcefully update the dependency now, so if for some reason it gets removed, we can immediately clear it
809 RSG::utilities->base_update_dependency(p_base, &instance->dependency_tracker);
810 }
811
812 _instance_queue_update(instance, true, true);
813 }
814
815 void RendererSceneCull::instance_set_scenario(RID p_instance, RID p_scenario) {
816 Instance *instance = instance_owner.get_or_null(p_instance);
817 ERR_FAIL_NULL(instance);
818
819 if (instance->scenario) {
820 instance->scenario->instances.remove(&instance->scenario_item);
821
822 if (instance->indexer_id.is_valid()) {
823 _unpair_instance(instance);
824 }
825
826 switch (instance->base_type) {
827 case RS::INSTANCE_LIGHT: {
828 InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
829 if (instance->visible && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
830 instance->scenario->dynamic_lights.erase(light->instance);
831 }
832
833 #ifdef DEBUG_ENABLED
834 if (light->geometries.size()) {
835 ERR_PRINT("BUG, indexing did not unpair geometries from light.");
836 }
837 #endif
838 if (light->D) {
839 instance->scenario->directional_lights.erase(light->D);
840 light->D = nullptr;
841 }
842 } break;
843 case RS::INSTANCE_REFLECTION_PROBE: {
844 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
845 RSG::light_storage->reflection_probe_release_atlas_index(reflection_probe->instance);
846
847 } break;
848 case RS::INSTANCE_PARTICLES_COLLISION: {
849 heightfield_particle_colliders_update_list.erase(instance);
850 } break;
851 case RS::INSTANCE_VOXEL_GI: {
852 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
853
854 #ifdef DEBUG_ENABLED
855 if (voxel_gi->geometries.size()) {
856 ERR_PRINT("BUG, indexing did not unpair geometries from VoxelGI.");
857 }
858 #endif
859 #ifdef DEBUG_ENABLED
860 if (voxel_gi->lights.size()) {
861 ERR_PRINT("BUG, indexing did not unpair lights from VoxelGI.");
862 }
863 #endif
864
865 if (voxel_gi->update_element.in_list()) {
866 voxel_gi_update_list.remove(&voxel_gi->update_element);
867 }
868 } break;
869 case RS::INSTANCE_OCCLUDER: {
870 if (instance->visible) {
871 RendererSceneOcclusionCull::get_singleton()->scenario_remove_instance(instance->scenario->self, p_instance);
872 }
873 } break;
874 default: {
875 }
876 }
877
878 instance->scenario = nullptr;
879 }
880
881 if (p_scenario.is_valid()) {
882 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
883 ERR_FAIL_NULL(scenario);
884
885 instance->scenario = scenario;
886
887 scenario->instances.add(&instance->scenario_item);
888
889 switch (instance->base_type) {
890 case RS::INSTANCE_LIGHT: {
891 InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
892
893 if (RSG::light_storage->light_get_type(instance->base) == RS::LIGHT_DIRECTIONAL) {
894 light->D = scenario->directional_lights.push_back(instance);
895 }
896 } break;
897 case RS::INSTANCE_VOXEL_GI: {
898 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
899 if (!voxel_gi->update_element.in_list()) {
900 voxel_gi_update_list.add(&voxel_gi->update_element);
901 }
902 } break;
903 case RS::INSTANCE_OCCLUDER: {
904 RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(scenario->self, p_instance, instance->base, instance->transform, instance->visible);
905 } break;
906 default: {
907 }
908 }
909
910 _instance_queue_update(instance, true, true);
911 }
912 }
913
914 void RendererSceneCull::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
915 Instance *instance = instance_owner.get_or_null(p_instance);
916 ERR_FAIL_NULL(instance);
917
918 if (instance->layer_mask == p_mask) {
919 return;
920 }
921
922 // Particles always need to be unpaired. Geometry may need to be unpaired, but only if lights or decals use pairing.
923 // Needs to happen before layer mask changes so we can avoid attempting to unpair something that was never paired.
924 if (instance->base_type == RS::INSTANCE_PARTICLES ||
925 (((geometry_instance_pair_mask & (1 << RS::INSTANCE_LIGHT)) || (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL))) && ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK))) {
926 _unpair_instance(instance);
927 singleton->_instance_queue_update(instance, false, false);
928 }
929
930 instance->layer_mask = p_mask;
931 if (instance->scenario && instance->array_index >= 0) {
932 instance->scenario->instance_data[instance->array_index].layer_mask = p_mask;
933 }
934
935 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
936 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
937 ERR_FAIL_NULL(geom->geometry_instance);
938 geom->geometry_instance->set_layer_mask(p_mask);
939
940 if (geom->can_cast_shadows) {
941 for (HashSet<RendererSceneCull::Instance *>::Iterator I = geom->lights.begin(); I != geom->lights.end(); ++I) {
942 InstanceLightData *light = static_cast<InstanceLightData *>((*I)->base_data);
943 light->make_shadow_dirty();
944 }
945 }
946 }
947 }
948
949 void RendererSceneCull::instance_set_pivot_data(RID p_instance, float p_sorting_offset, bool p_use_aabb_center) {
950 Instance *instance = instance_owner.get_or_null(p_instance);
951 ERR_FAIL_NULL(instance);
952
953 instance->sorting_offset = p_sorting_offset;
954 instance->use_aabb_center = p_use_aabb_center;
955
956 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
957 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
958 ERR_FAIL_NULL(geom->geometry_instance);
959 geom->geometry_instance->set_pivot_data(p_sorting_offset, p_use_aabb_center);
960 } else if (instance->base_type == RS::INSTANCE_DECAL && instance->base_data) {
961 InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
962 RSG::texture_storage->decal_instance_set_sorting_offset(decal->instance, instance->sorting_offset);
963 }
964 }
965
966 void RendererSceneCull::instance_geometry_set_transparency(RID p_instance, float p_transparency) {
967 Instance *instance = instance_owner.get_or_null(p_instance);
968 ERR_FAIL_NULL(instance);
969
970 instance->transparency = p_transparency;
971
972 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
973 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
974 ERR_FAIL_NULL(geom->geometry_instance);
975 geom->geometry_instance->set_transparency(p_transparency);
976 }
977 }
978
979 void RendererSceneCull::instance_set_transform(RID p_instance, const Transform3D &p_transform) {
980 Instance *instance = instance_owner.get_or_null(p_instance);
981 ERR_FAIL_NULL(instance);
982
983 if (instance->transform == p_transform) {
984 return; // Must be checked to avoid worst evil.
985 }
986
987 #ifdef DEBUG_ENABLED
988
989 for (int i = 0; i < 4; i++) {
990 const Vector3 &v = i < 3 ? p_transform.basis.rows[i] : p_transform.origin;
991 ERR_FAIL_COND(!v.is_finite());
992 }
993
994 #endif
995 instance->transform = p_transform;
996 _instance_queue_update(instance, true);
997 }
998
999 void RendererSceneCull::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
1000 Instance *instance = instance_owner.get_or_null(p_instance);
1001 ERR_FAIL_NULL(instance);
1002
1003 instance->object_id = p_id;
1004 }
1005
1006 void RendererSceneCull::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
1007 Instance *instance = instance_owner.get_or_null(p_instance);
1008 ERR_FAIL_NULL(instance);
1009
1010 if (instance->update_item.in_list()) {
1011 _update_dirty_instance(instance);
1012 }
1013
1014 if (instance->mesh_instance.is_valid()) {
1015 RSG::mesh_storage->mesh_instance_set_blend_shape_weight(instance->mesh_instance, p_shape, p_weight);
1016 }
1017
1018 _instance_queue_update(instance, false, false);
1019 }
1020
1021 void RendererSceneCull::instance_set_surface_override_material(RID p_instance, int p_surface, RID p_material) {
1022 Instance *instance = instance_owner.get_or_null(p_instance);
1023 ERR_FAIL_NULL(instance);
1024
1025 if (instance->base_type == RS::INSTANCE_MESH) {
1026 //may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case
1027 instance->materials.resize(MAX(p_surface + 1, RSG::mesh_storage->mesh_get_surface_count(instance->base)));
1028 }
1029
1030 ERR_FAIL_INDEX(p_surface, instance->materials.size());
1031
1032 instance->materials.write[p_surface] = p_material;
1033
1034 _instance_queue_update(instance, false, true);
1035 }
1036
1037 void RendererSceneCull::instance_set_visible(RID p_instance, bool p_visible) {
1038 Instance *instance = instance_owner.get_or_null(p_instance);
1039 ERR_FAIL_NULL(instance);
1040
1041 if (instance->visible == p_visible) {
1042 return;
1043 }
1044
1045 instance->visible = p_visible;
1046
1047 if (p_visible) {
1048 if (instance->scenario != nullptr) {
1049 _instance_queue_update(instance, true, false);
1050 }
1051 } else if (instance->indexer_id.is_valid()) {
1052 _unpair_instance(instance);
1053 }
1054
1055 if (instance->base_type == RS::INSTANCE_LIGHT) {
1056 InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
1057 if (instance->scenario && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
1058 if (p_visible) {
1059 instance->scenario->dynamic_lights.push_back(light->instance);
1060 } else {
1061 instance->scenario->dynamic_lights.erase(light->instance);
1062 }
1063 }
1064 }
1065
1066 if (instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
1067 InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
1068 RSG::particles_storage->particles_collision_instance_set_active(collision->instance, p_visible);
1069 }
1070
1071 if (instance->base_type == RS::INSTANCE_FOG_VOLUME) {
1072 InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(instance->base_data);
1073 scene_render->fog_volume_instance_set_active(volume->instance, p_visible);
1074 }
1075
1076 if (instance->base_type == RS::INSTANCE_OCCLUDER) {
1077 if (instance->scenario) {
1078 RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(instance->scenario->self, p_instance, instance->base, instance->transform, p_visible);
1079 }
1080 }
1081 }
1082
1083 void RendererSceneCull::instance_teleport(RID p_instance) {
1084 Instance *instance = instance_owner.get_or_null(p_instance);
1085 ERR_FAIL_NULL(instance);
1086 instance->teleported = true;
1087 }
1088
1089 void RendererSceneCull::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
1090 Instance *instance = instance_owner.get_or_null(p_instance);
1091 ERR_FAIL_NULL(instance);
1092
1093 if (p_aabb != AABB()) {
1094 // Set custom AABB
1095 if (instance->custom_aabb == nullptr) {
1096 instance->custom_aabb = memnew(AABB);
1097 }
1098 *instance->custom_aabb = p_aabb;
1099
1100 } else {
1101 // Clear custom AABB
1102 if (instance->custom_aabb != nullptr) {
1103 memdelete(instance->custom_aabb);
1104 instance->custom_aabb = nullptr;
1105 }
1106 }
1107
1108 if (instance->scenario) {
1109 _instance_queue_update(instance, true, false);
1110 }
1111 }
1112
1113 void RendererSceneCull::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
1114 Instance *instance = instance_owner.get_or_null(p_instance);
1115 ERR_FAIL_NULL(instance);
1116
1117 if (instance->skeleton == p_skeleton) {
1118 return;
1119 }
1120
1121 instance->skeleton = p_skeleton;
1122
1123 if (p_skeleton.is_valid()) {
1124 //update the dependency now, so if cleared, we remove it
1125 RSG::mesh_storage->skeleton_update_dependency(p_skeleton, &instance->dependency_tracker);
1126 }
1127
1128 _instance_queue_update(instance, true, true);
1129
1130 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1131 _instance_update_mesh_instance(instance);
1132
1133 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1134 ERR_FAIL_NULL(geom->geometry_instance);
1135 geom->geometry_instance->set_skeleton(p_skeleton);
1136 }
1137 }
1138
1139 void RendererSceneCull::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
1140 Instance *instance = instance_owner.get_or_null(p_instance);
1141 ERR_FAIL_NULL(instance);
1142
1143 instance->extra_margin = p_margin;
1144 _instance_queue_update(instance, true, false);
1145 }
1146
1147 void RendererSceneCull::instance_set_ignore_culling(RID p_instance, bool p_enabled) {
1148 Instance *instance = instance_owner.get_or_null(p_instance);
1149 ERR_FAIL_NULL(instance);
1150 instance->ignore_all_culling = p_enabled;
1151
1152 if (instance->scenario && instance->array_index >= 0) {
1153 InstanceData &idata = instance->scenario->instance_data[instance->array_index];
1154 if (instance->ignore_all_culling) {
1155 idata.flags |= InstanceData::FLAG_IGNORE_ALL_CULLING;
1156 } else {
1157 idata.flags &= ~InstanceData::FLAG_IGNORE_ALL_CULLING;
1158 }
1159 }
1160 }
1161
1162 Vector<ObjectID> RendererSceneCull::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
1163 Vector<ObjectID> instances;
1164 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
1165 ERR_FAIL_NULL_V(scenario, instances);
1166
1167 update_dirty_instances(); // check dirty instances before culling
1168
1169 struct CullAABB {
1170 Vector<ObjectID> instances;
1171 _FORCE_INLINE_ bool operator()(void *p_data) {
1172 Instance *p_instance = (Instance *)p_data;
1173 if (!p_instance->object_id.is_null()) {
1174 instances.push_back(p_instance->object_id);
1175 }
1176 return false;
1177 }
1178 };
1179
1180 CullAABB cull_aabb;
1181 scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(p_aabb, cull_aabb);
1182 scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(p_aabb, cull_aabb);
1183 return cull_aabb.instances;
1184 }
1185
1186 Vector<ObjectID> RendererSceneCull::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
1187 Vector<ObjectID> instances;
1188 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
1189 ERR_FAIL_NULL_V(scenario, instances);
1190 update_dirty_instances(); // check dirty instances before culling
1191
1192 struct CullRay {
1193 Vector<ObjectID> instances;
1194 _FORCE_INLINE_ bool operator()(void *p_data) {
1195 Instance *p_instance = (Instance *)p_data;
1196 if (!p_instance->object_id.is_null()) {
1197 instances.push_back(p_instance->object_id);
1198 }
1199 return false;
1200 }
1201 };
1202
1203 CullRay cull_ray;
1204 scenario->indexers[Scenario::INDEXER_GEOMETRY].ray_query(p_from, p_to, cull_ray);
1205 scenario->indexers[Scenario::INDEXER_VOLUMES].ray_query(p_from, p_to, cull_ray);
1206 return cull_ray.instances;
1207 }
1208
1209 Vector<ObjectID> RendererSceneCull::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
1210 Vector<ObjectID> instances;
1211 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
1212 ERR_FAIL_NULL_V(scenario, instances);
1213 update_dirty_instances(); // check dirty instances before culling
1214
1215 Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&p_convex[0], p_convex.size());
1216
1217 struct CullConvex {
1218 Vector<ObjectID> instances;
1219 _FORCE_INLINE_ bool operator()(void *p_data) {
1220 Instance *p_instance = (Instance *)p_data;
1221 if (!p_instance->object_id.is_null()) {
1222 instances.push_back(p_instance->object_id);
1223 }
1224 return false;
1225 }
1226 };
1227
1228 CullConvex cull_convex;
1229 scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
1230 scenario->indexers[Scenario::INDEXER_VOLUMES].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
1231 return cull_convex.instances;
1232 }
1233
1234 void RendererSceneCull::instance_geometry_set_flag(RID p_instance, RS::InstanceFlags p_flags, bool p_enabled) {
1235 Instance *instance = instance_owner.get_or_null(p_instance);
1236 ERR_FAIL_NULL(instance);
1237
1238 //ERR_FAIL_COND(((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK));
1239
1240 switch (p_flags) {
1241 case RS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
1242 instance->baked_light = p_enabled;
1243
1244 if (instance->scenario && instance->array_index >= 0) {
1245 InstanceData &idata = instance->scenario->instance_data[instance->array_index];
1246 if (instance->baked_light) {
1247 idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
1248 } else {
1249 idata.flags &= ~InstanceData::FLAG_USES_BAKED_LIGHT;
1250 }
1251 }
1252
1253 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1254 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1255 ERR_FAIL_NULL(geom->geometry_instance);
1256 geom->geometry_instance->set_use_baked_light(p_enabled);
1257 }
1258
1259 } break;
1260 case RS::INSTANCE_FLAG_USE_DYNAMIC_GI: {
1261 if (p_enabled == instance->dynamic_gi) {
1262 //bye, redundant
1263 return;
1264 }
1265
1266 if (instance->indexer_id.is_valid()) {
1267 _unpair_instance(instance);
1268 _instance_queue_update(instance, true, true);
1269 }
1270
1271 //once out of octree, can be changed
1272 instance->dynamic_gi = p_enabled;
1273
1274 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1275 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1276 ERR_FAIL_NULL(geom->geometry_instance);
1277 geom->geometry_instance->set_use_dynamic_gi(p_enabled);
1278 }
1279
1280 } break;
1281 case RS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
1282 instance->redraw_if_visible = p_enabled;
1283
1284 if (instance->scenario && instance->array_index >= 0) {
1285 InstanceData &idata = instance->scenario->instance_data[instance->array_index];
1286 if (instance->redraw_if_visible) {
1287 idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
1288 } else {
1289 idata.flags &= ~InstanceData::FLAG_REDRAW_IF_VISIBLE;
1290 }
1291 }
1292
1293 } break;
1294 case RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING: {
1295 instance->ignore_occlusion_culling = p_enabled;
1296
1297 if (instance->scenario && instance->array_index >= 0) {
1298 InstanceData &idata = instance->scenario->instance_data[instance->array_index];
1299 if (instance->ignore_occlusion_culling) {
1300 idata.flags |= InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
1301 } else {
1302 idata.flags &= ~InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
1303 }
1304 }
1305 } break;
1306 default: {
1307 }
1308 }
1309 }
1310
1311 void RendererSceneCull::instance_geometry_set_cast_shadows_setting(RID p_instance, RS::ShadowCastingSetting p_shadow_casting_setting) {
1312 Instance *instance = instance_owner.get_or_null(p_instance);
1313 ERR_FAIL_NULL(instance);
1314
1315 instance->cast_shadows = p_shadow_casting_setting;
1316
1317 if (instance->scenario && instance->array_index >= 0) {
1318 InstanceData &idata = instance->scenario->instance_data[instance->array_index];
1319
1320 if (instance->cast_shadows != RS::SHADOW_CASTING_SETTING_OFF) {
1321 idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
1322 } else {
1323 idata.flags &= ~InstanceData::FLAG_CAST_SHADOWS;
1324 }
1325
1326 if (instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
1327 idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
1328 } else {
1329 idata.flags &= ~InstanceData::FLAG_CAST_SHADOWS_ONLY;
1330 }
1331 }
1332
1333 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1334 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1335 ERR_FAIL_NULL(geom->geometry_instance);
1336
1337 geom->geometry_instance->set_cast_double_sided_shadows(instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
1338 }
1339
1340 _instance_queue_update(instance, false, true);
1341 }
1342
1343 void RendererSceneCull::instance_geometry_set_material_override(RID p_instance, RID p_material) {
1344 Instance *instance = instance_owner.get_or_null(p_instance);
1345 ERR_FAIL_NULL(instance);
1346
1347 instance->material_override = p_material;
1348 _instance_queue_update(instance, false, true);
1349
1350 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1351 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1352 ERR_FAIL_NULL(geom->geometry_instance);
1353 geom->geometry_instance->set_material_override(p_material);
1354 }
1355 }
1356
1357 void RendererSceneCull::instance_geometry_set_material_overlay(RID p_instance, RID p_material) {
1358 Instance *instance = instance_owner.get_or_null(p_instance);
1359 ERR_FAIL_NULL(instance);
1360
1361 instance->material_overlay = p_material;
1362 _instance_queue_update(instance, false, true);
1363
1364 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1365 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1366 ERR_FAIL_NULL(geom->geometry_instance);
1367 geom->geometry_instance->set_material_overlay(p_material);
1368 }
1369 }
1370
1371 void RendererSceneCull::instance_geometry_set_visibility_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin, RS::VisibilityRangeFadeMode p_fade_mode) {
1372 Instance *instance = instance_owner.get_or_null(p_instance);
1373 ERR_FAIL_NULL(instance);
1374
1375 instance->visibility_range_begin = p_min;
1376 instance->visibility_range_end = p_max;
1377 instance->visibility_range_begin_margin = p_min_margin;
1378 instance->visibility_range_end_margin = p_max_margin;
1379 instance->visibility_range_fade_mode = p_fade_mode;
1380
1381 _update_instance_visibility_dependencies(instance);
1382
1383 if (instance->scenario && instance->visibility_index != -1) {
1384 InstanceVisibilityData &vd = instance->scenario->instance_visibility[instance->visibility_index];
1385 vd.range_begin = instance->visibility_range_begin;
1386 vd.range_end = instance->visibility_range_end;
1387 vd.range_begin_margin = instance->visibility_range_begin_margin;
1388 vd.range_end_margin = instance->visibility_range_end_margin;
1389 vd.fade_mode = p_fade_mode;
1390 }
1391 }
1392
1393 void RendererSceneCull::instance_set_visibility_parent(RID p_instance, RID p_parent_instance) {
1394 Instance *instance = instance_owner.get_or_null(p_instance);
1395 ERR_FAIL_NULL(instance);
1396
1397 Instance *old_parent = instance->visibility_parent;
1398 if (old_parent) {
1399 old_parent->visibility_dependencies.erase(instance);
1400 instance->visibility_parent = nullptr;
1401 _update_instance_visibility_depth(old_parent);
1402 }
1403
1404 Instance *parent = instance_owner.get_or_null(p_parent_instance);
1405 ERR_FAIL_COND(p_parent_instance.is_valid() && !parent);
1406
1407 if (parent) {
1408 parent->visibility_dependencies.insert(instance);
1409 instance->visibility_parent = parent;
1410
1411 bool cycle_detected = _update_instance_visibility_depth(parent);
1412 if (cycle_detected) {
1413 ERR_PRINT("Cycle detected in the visibility dependencies tree. The latest change to visibility_parent will have no effect.");
1414 parent->visibility_dependencies.erase(instance);
1415 instance->visibility_parent = nullptr;
1416 }
1417 }
1418
1419 _update_instance_visibility_dependencies(instance);
1420 }
1421
1422 bool RendererSceneCull::_update_instance_visibility_depth(Instance *p_instance) {
1423 bool cycle_detected = false;
1424 HashSet<Instance *> traversed_nodes;
1425
1426 {
1427 Instance *instance = p_instance;
1428 while (instance) {
1429 if (!instance->visibility_dependencies.is_empty()) {
1430 uint32_t depth = 0;
1431 for (const Instance *E : instance->visibility_dependencies) {
1432 depth = MAX(depth, E->visibility_dependencies_depth);
1433 }
1434 instance->visibility_dependencies_depth = depth + 1;
1435 } else {
1436 instance->visibility_dependencies_depth = 0;
1437 }
1438
1439 if (instance->scenario && instance->visibility_index != -1) {
1440 instance->scenario->instance_visibility.move(instance->visibility_index, instance->visibility_dependencies_depth);
1441 }
1442
1443 traversed_nodes.insert(instance);
1444
1445 instance = instance->visibility_parent;
1446 if (traversed_nodes.has(instance)) {
1447 cycle_detected = true;
1448 break;
1449 }
1450 }
1451 }
1452
1453 return cycle_detected;
1454 }
1455
1456 void RendererSceneCull::_update_instance_visibility_dependencies(Instance *p_instance) const {
1457 bool is_geometry_instance = ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) && p_instance->base_data;
1458 bool has_visibility_range = p_instance->visibility_range_begin > 0.0 || p_instance->visibility_range_end > 0.0;
1459 bool needs_visibility_cull = has_visibility_range && is_geometry_instance && p_instance->array_index != -1;
1460
1461 if (!needs_visibility_cull && p_instance->visibility_index != -1) {
1462 p_instance->scenario->instance_visibility.remove_at(p_instance->visibility_index);
1463 p_instance->visibility_index = -1;
1464 } else if (needs_visibility_cull && p_instance->visibility_index == -1) {
1465 InstanceVisibilityData vd;
1466 vd.instance = p_instance;
1467 vd.range_begin = p_instance->visibility_range_begin;
1468 vd.range_end = p_instance->visibility_range_end;
1469 vd.range_begin_margin = p_instance->visibility_range_begin_margin;
1470 vd.range_end_margin = p_instance->visibility_range_end_margin;
1471 vd.position = p_instance->transformed_aabb.get_center();
1472 vd.array_index = p_instance->array_index;
1473 vd.fade_mode = p_instance->visibility_range_fade_mode;
1474
1475 p_instance->scenario->instance_visibility.insert(vd, p_instance->visibility_dependencies_depth);
1476 }
1477
1478 if (p_instance->scenario && p_instance->array_index != -1) {
1479 InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
1480 idata.visibility_index = p_instance->visibility_index;
1481
1482 if (is_geometry_instance) {
1483 if (has_visibility_range && p_instance->visibility_range_fade_mode == RS::VISIBILITY_RANGE_FADE_SELF) {
1484 bool begin_enabled = p_instance->visibility_range_begin > 0.0f;
1485 float begin_min = p_instance->visibility_range_begin - p_instance->visibility_range_begin_margin;
1486 float begin_max = p_instance->visibility_range_begin + p_instance->visibility_range_begin_margin;
1487 bool end_enabled = p_instance->visibility_range_end > 0.0f;
1488 float end_min = p_instance->visibility_range_end - p_instance->visibility_range_end_margin;
1489 float end_max = p_instance->visibility_range_end + p_instance->visibility_range_end_margin;
1490 idata.instance_geometry->set_fade_range(begin_enabled, begin_min, begin_max, end_enabled, end_min, end_max);
1491 } else {
1492 idata.instance_geometry->set_fade_range(false, 0.0f, 0.0f, false, 0.0f, 0.0f);
1493 }
1494 }
1495
1496 if ((has_visibility_range || p_instance->visibility_parent) && (p_instance->visibility_index == -1 || p_instance->visibility_dependencies_depth == 0)) {
1497 idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK;
1498 } else {
1499 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK;
1500 }
1501
1502 if (p_instance->visibility_parent) {
1503 idata.parent_array_index = p_instance->visibility_parent->array_index;
1504 } else {
1505 idata.parent_array_index = -1;
1506 if (is_geometry_instance) {
1507 idata.instance_geometry->set_parent_fade_alpha(1.0f);
1508 }
1509 }
1510 }
1511 }
1512
1513 void RendererSceneCull::instance_geometry_set_lightmap(RID p_instance, RID p_lightmap, const Rect2 &p_lightmap_uv_scale, int p_slice_index) {
1514 Instance *instance = instance_owner.get_or_null(p_instance);
1515 ERR_FAIL_NULL(instance);
1516
1517 if (instance->lightmap) {
1518 InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(((Instance *)instance->lightmap)->base_data);
1519 lightmap_data->users.erase(instance);
1520 instance->lightmap = nullptr;
1521 }
1522
1523 Instance *lightmap_instance = instance_owner.get_or_null(p_lightmap);
1524
1525 instance->lightmap = lightmap_instance;
1526 instance->lightmap_uv_scale = p_lightmap_uv_scale;
1527 instance->lightmap_slice_index = p_slice_index;
1528
1529 RID lightmap_instance_rid;
1530
1531 if (lightmap_instance) {
1532 InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(lightmap_instance->base_data);
1533 lightmap_data->users.insert(instance);
1534 lightmap_instance_rid = lightmap_data->instance;
1535 }
1536
1537 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1538 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1539 ERR_FAIL_NULL(geom->geometry_instance);
1540 geom->geometry_instance->set_use_lightmap(lightmap_instance_rid, p_lightmap_uv_scale, p_slice_index);
1541 }
1542 }
1543
1544 void RendererSceneCull::instance_geometry_set_lod_bias(RID p_instance, float p_lod_bias) {
1545 Instance *instance = instance_owner.get_or_null(p_instance);
1546 ERR_FAIL_NULL(instance);
1547
1548 instance->lod_bias = p_lod_bias;
1549
1550 if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
1551 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
1552 ERR_FAIL_NULL(geom->geometry_instance);
1553 geom->geometry_instance->set_lod_bias(p_lod_bias);
1554 }
1555 }
1556
1557 void RendererSceneCull::instance_geometry_set_shader_parameter(RID p_instance, const StringName &p_parameter, const Variant &p_value) {
1558 Instance *instance = instance_owner.get_or_null(p_instance);
1559 ERR_FAIL_NULL(instance);
1560
1561 instance->instance_uniforms.set(instance->self, p_parameter, p_value);
1562 }
1563
1564 Variant RendererSceneCull::instance_geometry_get_shader_parameter(RID p_instance, const StringName &p_parameter) const {
1565 const Instance *instance = instance_owner.get_or_null(p_instance);
1566 ERR_FAIL_NULL_V(instance, Variant());
1567
1568 return instance->instance_uniforms.get(p_parameter);
1569 }
1570
1571 Variant RendererSceneCull::instance_geometry_get_shader_parameter_default_value(RID p_instance, const StringName &p_parameter) const {
1572 const Instance *instance = instance_owner.get_or_null(p_instance);
1573 ERR_FAIL_NULL_V(instance, Variant());
1574
1575 return instance->instance_uniforms.get_default(p_parameter);
1576 }
1577
1578 void RendererSceneCull::mesh_generate_pipelines(RID p_mesh, bool p_background_compilation) {
1579 scene_render->mesh_generate_pipelines(p_mesh, p_background_compilation);
1580 }
1581
1582 uint32_t RendererSceneCull::get_pipeline_compilations(RS::PipelineSource p_source) {
1583 return scene_render->get_pipeline_compilations(p_source);
1584 }
1585
1586 void RendererSceneCull::instance_geometry_get_shader_parameter_list(RID p_instance, List<PropertyInfo> *p_parameters) const {
1587 ERR_FAIL_NULL(p_parameters);
1588 const Instance *instance = instance_owner.get_or_null(p_instance);
1589 ERR_FAIL_NULL(instance);
1590
1591 update_dirty_instances();
1592
1593 instance->instance_uniforms.get_property_list(*p_parameters);
1594 }
1595
1596 void RendererSceneCull::_update_instance(Instance *p_instance) const {
1597 p_instance->version++;
1598
1599 // When not using interpolation the transform is used straight.
1600 const Transform3D *instance_xform = &p_instance->transform;
1601
1602 // Can possibly use the most up to date current transform here when using physics interpolation ...
1603 // uncomment the next line for this..
1604 //if (_interpolation_data.interpolation_enabled && p_instance->interpolated) {
1605 // instance_xform = &p_instance->transform_curr;
1606 //}
1607 // However it does seem that using the interpolated transform (transform) works for keeping AABBs
1608 // up to date to avoid culling errors.
1609
1610 if (p_instance->base_type == RS::INSTANCE_LIGHT) {
1611 InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
1612
1613 RSG::light_storage->light_instance_set_transform(light->instance, *instance_xform);
1614 RSG::light_storage->light_instance_set_aabb(light->instance, instance_xform->xform(p_instance->aabb));
1615 light->make_shadow_dirty();
1616
1617 RS::LightBakeMode bake_mode = RSG::light_storage->light_get_bake_mode(p_instance->base);
1618 if (RSG::light_storage->light_get_type(p_instance->base) != RS::LIGHT_DIRECTIONAL && bake_mode != light->bake_mode) {
1619 if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
1620 p_instance->scenario->dynamic_lights.erase(light->instance);
1621 }
1622
1623 light->bake_mode = bake_mode;
1624
1625 if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
1626 p_instance->scenario->dynamic_lights.push_back(light->instance);
1627 }
1628 }
1629
1630 uint32_t max_sdfgi_cascade = RSG::light_storage->light_get_max_sdfgi_cascade(p_instance->base);
1631 if (light->max_sdfgi_cascade != max_sdfgi_cascade) {
1632 light->max_sdfgi_cascade = max_sdfgi_cascade; //should most likely make sdfgi dirty in scenario
1633 }
1634 light->cull_mask = RSG::light_storage->light_get_cull_mask(p_instance->base);
1635 } else if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
1636 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
1637
1638 RSG::light_storage->reflection_probe_instance_set_transform(reflection_probe->instance, *instance_xform);
1639
1640 if (p_instance->scenario && p_instance->array_index >= 0) {
1641 InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
1642 idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
1643 }
1644 } else if (p_instance->base_type == RS::INSTANCE_DECAL) {
1645 InstanceDecalData *decal = static_cast<InstanceDecalData *>(p_instance->base_data);
1646
1647 RSG::texture_storage->decal_instance_set_transform(decal->instance, *instance_xform);
1648 decal->cull_mask = RSG::texture_storage->decal_get_cull_mask(p_instance->base);
1649 } else if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
1650 InstanceLightmapData *lightmap = static_cast<InstanceLightmapData *>(p_instance->base_data);
1651
1652 RSG::light_storage->lightmap_instance_set_transform(lightmap->instance, *instance_xform);
1653 } else if (p_instance->base_type == RS::INSTANCE_VOXEL_GI) {
1654 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(p_instance->base_data);
1655
1656 scene_render->voxel_gi_instance_set_transform_to_data(voxel_gi->probe_instance, *instance_xform);
1657 } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
1658 RSG::particles_storage->particles_set_emission_transform(p_instance->base, *instance_xform);
1659 } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
1660 InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(p_instance->base_data);
1661
1662 //remove materials no longer used and un-own them
1663 if (RSG::particles_storage->particles_collision_is_heightfield(p_instance->base)) {
1664 heightfield_particle_colliders_update_list.insert(p_instance);
1665 }
1666 RSG::particles_storage->particles_collision_instance_set_transform(collision->instance, *instance_xform);
1667 collision->cull_mask = RSG::particles_storage->particles_collision_get_cull_mask(p_instance->base);
1668 } else if (p_instance->base_type == RS::INSTANCE_FOG_VOLUME) {
1669 InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(p_instance->base_data);
1670 scene_render->fog_volume_instance_set_transform(volume->instance, *instance_xform);
1671 } else if (p_instance->base_type == RS::INSTANCE_OCCLUDER) {
1672 if (p_instance->scenario) {
1673 RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(p_instance->scenario->self, p_instance->self, p_instance->base, *instance_xform, p_instance->visible);
1674 }
1675 } else if (p_instance->base_type == RS::INSTANCE_NONE) {
1676 return;
1677 }
1678
1679 if (!p_instance->aabb.has_surface()) {
1680 return;
1681 }
1682
1683 if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
1684 //if this moved, update the captured objects
1685 InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(p_instance->base_data);
1686 //erase dependencies, since no longer a lightmap
1687
1688 for (Instance *E : lightmap_data->geometries) {
1689 Instance *geom = E;
1690 _instance_queue_update(geom, true, false);
1691 }
1692 }
1693
1694 AABB new_aabb;
1695 new_aabb = instance_xform->xform(p_instance->aabb);
1696 p_instance->transformed_aabb = new_aabb;
1697
1698 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
1699 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
1700 //make sure lights are updated if it casts shadow
1701
1702 if (geom->can_cast_shadows) {
1703 for (const Instance *E : geom->lights) {
1704 InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
1705 light->make_shadow_dirty();
1706 }
1707 }
1708
1709 if (!p_instance->lightmap && geom->lightmap_captures.size()) {
1710 //affected by lightmap captures, must update capture info!
1711 _update_instance_lightmap_captures(p_instance);
1712 } else {
1713 if (!p_instance->lightmap_sh.is_empty()) {
1714 p_instance->lightmap_sh.clear(); //don't need SH
1715 p_instance->lightmap_target_sh.clear(); //don't need SH
1716 ERR_FAIL_NULL(geom->geometry_instance);
1717 geom->geometry_instance->set_lightmap_capture(nullptr);
1718 }
1719 }
1720
1721 ERR_FAIL_NULL(geom->geometry_instance);
1722
1723 geom->geometry_instance->set_transform(*instance_xform, p_instance->aabb, p_instance->transformed_aabb);
1724 if (p_instance->teleported) {
1725 geom->geometry_instance->reset_motion_vectors();
1726 }
1727 }
1728
1729 // note: we had to remove is equal approx check here, it meant that det == 0.000004 won't work, which is the case for some of our scenes.
1730 if (p_instance->scenario == nullptr || !p_instance->visible || instance_xform->basis.determinant() == 0) {
1731 p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
1732 return;
1733 }
1734
1735 //quantize to improve moving object performance
1736 AABB bvh_aabb = p_instance->transformed_aabb;
1737
1738 if (p_instance->indexer_id.is_valid() && bvh_aabb != p_instance->prev_transformed_aabb) {
1739 //assume motion, see if bounds need to be quantized
1740 AABB motion_aabb = bvh_aabb.merge(p_instance->prev_transformed_aabb);
1741 float motion_longest_axis = motion_aabb.get_longest_axis_size();
1742 float longest_axis = p_instance->transformed_aabb.get_longest_axis_size();
1743
1744 if (motion_longest_axis < longest_axis * 2) {
1745 //moved but not a lot, use motion aabb quantizing
1746 float quantize_size = Math::pow(2.0, Math::ceil(Math::log(motion_longest_axis) / Math::log(2.0))) * 0.5; //one fifth
1747 bvh_aabb.quantize(quantize_size);
1748 }
1749 }
1750
1751 if (!p_instance->indexer_id.is_valid()) {
1752 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
1753 p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].insert(bvh_aabb, p_instance);
1754 } else {
1755 p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].insert(bvh_aabb, p_instance);
1756 }
1757
1758 p_instance->array_index = p_instance->scenario->instance_data.size();
1759 InstanceData idata;
1760 idata.instance = p_instance;
1761 idata.layer_mask = p_instance->layer_mask;
1762 idata.flags = p_instance->base_type; //changing it means de-indexing, so this never needs to be changed later
1763 idata.base_rid = p_instance->base;
1764 idata.parent_array_index = p_instance->visibility_parent ? p_instance->visibility_parent->array_index : -1;
1765 idata.visibility_index = p_instance->visibility_index;
1766 idata.occlusion_timeout = 0;
1767
1768 for (Instance *E : p_instance->visibility_dependencies) {
1769 Instance *dep_instance = E;
1770 if (dep_instance->array_index != -1) {
1771 dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = p_instance->array_index;
1772 }
1773 }
1774
1775 switch (p_instance->base_type) {
1776 case RS::INSTANCE_MESH:
1777 case RS::INSTANCE_MULTIMESH:
1778 case RS::INSTANCE_PARTICLES: {
1779 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
1780 idata.instance_geometry = geom->geometry_instance;
1781 } break;
1782 case RS::INSTANCE_LIGHT: {
1783 InstanceLightData *light_data = static_cast<InstanceLightData *>(p_instance->base_data);
1784 idata.instance_data_rid = light_data->instance.get_id();
1785 light_data->uses_projector = RSG::light_storage->light_has_projector(p_instance->base);
1786 light_data->uses_softshadow = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE) > CMP_EPSILON;
1787
1788 } break;
1789 case RS::INSTANCE_REFLECTION_PROBE: {
1790 idata.instance_data_rid = static_cast<InstanceReflectionProbeData *>(p_instance->base_data)->instance.get_id();
1791 } break;
1792 case RS::INSTANCE_DECAL: {
1793 idata.instance_data_rid = static_cast<InstanceDecalData *>(p_instance->base_data)->instance.get_id();
1794 } break;
1795 case RS::INSTANCE_LIGHTMAP: {
1796 idata.instance_data_rid = static_cast<InstanceLightmapData *>(p_instance->base_data)->instance.get_id();
1797 } break;
1798 case RS::INSTANCE_VOXEL_GI: {
1799 idata.instance_data_rid = static_cast<InstanceVoxelGIData *>(p_instance->base_data)->probe_instance.get_id();
1800 } break;
1801 case RS::INSTANCE_FOG_VOLUME: {
1802 idata.instance_data_rid = static_cast<InstanceFogVolumeData *>(p_instance->base_data)->instance.get_id();
1803 } break;
1804 case RS::INSTANCE_VISIBLITY_NOTIFIER: {
1805 idata.visibility_notifier = static_cast<InstanceVisibilityNotifierData *>(p_instance->base_data);
1806 } break;
1807 default: {
1808 }
1809 }
1810
1811 if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
1812 //always dirty when added
1813 idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
1814 }
1815 if (p_instance->cast_shadows != RS::SHADOW_CASTING_SETTING_OFF) {
1816 idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
1817 }
1818 if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
1819 idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
1820 }
1821 if (p_instance->redraw_if_visible) {
1822 idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
1823 }
1824 // dirty flags should not be set here, since no pairing has happened
1825 if (p_instance->baked_light) {
1826 idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
1827 }
1828 if (p_instance->mesh_instance.is_valid()) {
1829 idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
1830 }
1831 if (p_instance->ignore_occlusion_culling) {
1832 idata.flags |= InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
1833 }
1834 if (p_instance->ignore_all_culling) {
1835 idata.flags |= InstanceData::FLAG_IGNORE_ALL_CULLING;
1836 }
1837
1838 p_instance->scenario->instance_data.push_back(idata);
1839 p_instance->scenario->instance_aabbs.push_back(InstanceBounds(p_instance->transformed_aabb));
1840 _update_instance_visibility_dependencies(p_instance);
1841 } else {
1842 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
1843 p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].update(p_instance->indexer_id, bvh_aabb);
1844 } else {
1845 p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].update(p_instance->indexer_id, bvh_aabb);
1846 }
1847 p_instance->scenario->instance_aabbs[p_instance->array_index] = InstanceBounds(p_instance->transformed_aabb);
1848 }
1849
1850 if (p_instance->visibility_index != -1) {
1851 p_instance->scenario->instance_visibility[p_instance->visibility_index].position = p_instance->transformed_aabb.get_center();
1852 }
1853
1854 //move instance and repair
1855 pair_pass++;
1856
1857 PairInstances pair;
1858
1859 pair.instance = p_instance;
1860 pair.pair_allocator = &pair_allocator;
1861 pair.pair_pass = pair_pass;
1862 pair.pair_mask = 0;
1863
1864 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
1865 pair.pair_mask |= 1 << RS::INSTANCE_LIGHT;
1866 pair.pair_mask |= 1 << RS::INSTANCE_VOXEL_GI;
1867 pair.pair_mask |= 1 << RS::INSTANCE_LIGHTMAP;
1868 if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
1869 pair.pair_mask |= 1 << RS::INSTANCE_PARTICLES_COLLISION;
1870 }
1871
1872 pair.pair_mask |= geometry_instance_pair_mask;
1873
1874 pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
1875 } else if (p_instance->base_type == RS::INSTANCE_LIGHT) {
1876 pair.pair_mask |= RS::INSTANCE_GEOMETRY_MASK;
1877 pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
1878
1879 RS::LightBakeMode bake_mode = RSG::light_storage->light_get_bake_mode(p_instance->base);
1880 if (bake_mode == RS::LIGHT_BAKE_STATIC || bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
1881 pair.pair_mask |= (1 << RS::INSTANCE_VOXEL_GI);
1882 pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
1883 }
1884 } else if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
1885 pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
1886 pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
1887 } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE)) {
1888 pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
1889 pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
1890 } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (p_instance->base_type == RS::INSTANCE_DECAL)) {
1891 pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
1892 pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
1893 } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
1894 pair.pair_mask = (1 << RS::INSTANCE_PARTICLES);
1895 pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
1896 } else if (p_instance->base_type == RS::INSTANCE_VOXEL_GI) {
1897 //lights and geometries
1898 pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT);
1899 pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
1900 pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
1901 }
1902
1903 pair.pair();
1904
1905 p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
1906 }
1907
1908 void RendererSceneCull::_unpair_instance(Instance *p_instance) {
1909 if (!p_instance->indexer_id.is_valid()) {
1910 return; //nothing to do
1911 }
1912
1913 while (p_instance->pairs.first()) {
1914 InstancePair *pair = p_instance->pairs.first()->self();
1915 Instance *other_instance = p_instance == pair->a ? pair->b : pair->a;
1916 _instance_unpair(p_instance, other_instance);
1917 pair_allocator.free(pair);
1918 }
1919
1920 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
1921 p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].remove(p_instance->indexer_id);
1922 } else {
1923 p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].remove(p_instance->indexer_id);
1924 }
1925
1926 p_instance->indexer_id = DynamicBVH::ID();
1927
1928 //replace this by last
1929 int32_t swap_with_index = p_instance->scenario->instance_data.size() - 1;
1930 if (swap_with_index != p_instance->array_index) {
1931 Instance *swapped_instance = p_instance->scenario->instance_data[swap_with_index].instance;
1932 swapped_instance->array_index = p_instance->array_index; //swap
1933 p_instance->scenario->instance_data[p_instance->array_index] = p_instance->scenario->instance_data[swap_with_index];
1934 p_instance->scenario->instance_aabbs[p_instance->array_index] = p_instance->scenario->instance_aabbs[swap_with_index];
1935
1936 if (swapped_instance->visibility_index != -1) {
1937 swapped_instance->scenario->instance_visibility[swapped_instance->visibility_index].array_index = swapped_instance->array_index;
1938 }
1939
1940 for (Instance *E : swapped_instance->visibility_dependencies) {
1941 Instance *dep_instance = E;
1942 if (dep_instance != p_instance && dep_instance->array_index != -1) {
1943 dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = swapped_instance->array_index;
1944 }
1945 }
1946 }
1947
1948 // pop last
1949 p_instance->scenario->instance_data.pop_back();
1950 p_instance->scenario->instance_aabbs.pop_back();
1951
1952 //uninitialize
1953 p_instance->array_index = -1;
1954 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
1955 // Clear these now because the InstanceData containing the dirty flags is gone
1956 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
1957 ERR_FAIL_NULL(geom->geometry_instance);
1958
1959 geom->geometry_instance->clear_light_instances();
1960 geom->geometry_instance->pair_reflection_probe_instances(nullptr, 0);
1961 geom->geometry_instance->pair_decal_instances(nullptr, 0);
1962 geom->geometry_instance->pair_voxel_gi_instances(nullptr, 0);
1963 }
1964
1965 for (Instance *E : p_instance->visibility_dependencies) {
1966 Instance *dep_instance = E;
1967 if (dep_instance->array_index != -1) {
1968 dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = -1;
1969 if ((1 << dep_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
1970 dep_instance->scenario->instance_data[dep_instance->array_index].instance_geometry->set_parent_fade_alpha(1.0f);
1971 }
1972 }
1973 }
1974
1975 _update_instance_visibility_dependencies(p_instance);
1976 }
1977
1978 void RendererSceneCull::_update_instance_aabb(Instance *p_instance) const {
1979 AABB new_aabb;
1980
1981 ERR_FAIL_COND(p_instance->base_type != RS::INSTANCE_NONE && !p_instance->base.is_valid());
1982
1983 switch (p_instance->base_type) {
1984 case RenderingServer::INSTANCE_NONE: {
1985 // do nothing
1986 } break;
1987 case RenderingServer::INSTANCE_MESH: {
1988 if (p_instance->custom_aabb) {
1989 new_aabb = *p_instance->custom_aabb;
1990 } else {
1991 new_aabb = RSG::mesh_storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
1992 }
1993
1994 } break;
1995
1996 case RenderingServer::INSTANCE_MULTIMESH: {
1997 if (p_instance->custom_aabb) {
1998 new_aabb = *p_instance->custom_aabb;
1999 } else {
2000 new_aabb = RSG::mesh_storage->multimesh_get_aabb(p_instance->base);
2001 }
2002
2003 } break;
2004 case RenderingServer::INSTANCE_PARTICLES: {
2005 if (p_instance->custom_aabb) {
2006 new_aabb = *p_instance->custom_aabb;
2007 } else {
2008 new_aabb = RSG::particles_storage->particles_get_aabb(p_instance->base);
2009 }
2010
2011 } break;
2012 case RenderingServer::INSTANCE_PARTICLES_COLLISION: {
2013 new_aabb = RSG::particles_storage->particles_collision_get_aabb(p_instance->base);
2014
2015 } break;
2016 case RenderingServer::INSTANCE_FOG_VOLUME: {
2017 new_aabb = RSG::fog->fog_volume_get_aabb(p_instance->base);
2018 } break;
2019 case RenderingServer::INSTANCE_VISIBLITY_NOTIFIER: {
2020 new_aabb = RSG::utilities->visibility_notifier_get_aabb(p_instance->base);
2021 } break;
2022 case RenderingServer::INSTANCE_LIGHT: {
2023 new_aabb = RSG::light_storage->light_get_aabb(p_instance->base);
2024
2025 } break;
2026 case RenderingServer::INSTANCE_REFLECTION_PROBE: {
2027 new_aabb = RSG::light_storage->reflection_probe_get_aabb(p_instance->base);
2028
2029 } break;
2030 case RenderingServer::INSTANCE_DECAL: {
2031 new_aabb = RSG::texture_storage->decal_get_aabb(p_instance->base);
2032
2033 } break;
2034 case RenderingServer::INSTANCE_VOXEL_GI: {
2035 new_aabb = RSG::gi->voxel_gi_get_bounds(p_instance->base);
2036
2037 } break;
2038 case RenderingServer::INSTANCE_LIGHTMAP: {
2039 new_aabb = RSG::light_storage->lightmap_get_aabb(p_instance->base);
2040
2041 } break;
2042 default: {
2043 }
2044 }
2045
2046 if (p_instance->extra_margin) {
2047 new_aabb.grow_by(p_instance->extra_margin);
2048 }
2049
2050 p_instance->aabb = new_aabb;
2051 }
2052
2053 void RendererSceneCull::_update_instance_lightmap_captures(Instance *p_instance) const {
2054 bool first_set = p_instance->lightmap_sh.is_empty();
2055 p_instance->lightmap_sh.resize(9); //using SH
2056 p_instance->lightmap_target_sh.resize(9); //using SH
2057 Color *instance_sh = p_instance->lightmap_target_sh.ptrw();
2058 bool inside = false;
2059 Color accum_sh[9];
2060 float accum_blend = 0.0;
2061
2062 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
2063 for (Instance *E : geom->lightmap_captures) {
2064 Instance *lightmap = E;
2065
2066 bool interior = RSG::light_storage->lightmap_is_interior(lightmap->base);
2067
2068 if (inside && !interior) {
2069 continue; //we are inside, ignore exteriors
2070 }
2071
2072 Transform3D to_bounds = lightmap->transform.affine_inverse();
2073 Vector3 center = p_instance->transform.xform(p_instance->aabb.get_center()); //use aabb center
2074
2075 Vector3 lm_pos = to_bounds.xform(center);
2076
2077 AABB bounds = RSG::light_storage->lightmap_get_aabb(lightmap->base);
2078 if (!bounds.has_point(lm_pos)) {
2079 continue; //not in this lightmap
2080 }
2081
2082 Color sh[9];
2083 RSG::light_storage->lightmap_tap_sh_light(lightmap->base, lm_pos, sh);
2084
2085 //rotate it
2086 Basis rot = lightmap->transform.basis.orthonormalized();
2087 for (int i = 0; i < 3; i++) {
2088 real_t csh[9];
2089 for (int j = 0; j < 9; j++) {
2090 csh[j] = sh[j][i];
2091 }
2092 rot.rotate_sh(csh);
2093 for (int j = 0; j < 9; j++) {
2094 sh[j][i] = csh[j];
2095 }
2096 }
2097
2098 Vector3 inner_pos = ((lm_pos - bounds.position) / bounds.size) * 2.0 - Vector3(1.0, 1.0, 1.0);
2099
2100 real_t blend = MAX(Math::abs(inner_pos.x), MAX(Math::abs(inner_pos.y), Math::abs(inner_pos.z)));
2101 //make blend more rounded
2102 blend = Math::lerp(inner_pos.length(), blend, blend);
2103 blend *= blend;
2104 blend = MAX(0.0, 1.0 - blend);
2105
2106 if (interior && !inside) {
2107 //do not blend, just replace
2108 for (int j = 0; j < 9; j++) {
2109 accum_sh[j] = sh[j] * blend;
2110 }
2111 accum_blend = blend;
2112 inside = true;
2113 } else {
2114 for (int j = 0; j < 9; j++) {
2115 accum_sh[j] += sh[j] * blend;
2116 }
2117 accum_blend += blend;
2118 }
2119 }
2120
2121 if (accum_blend > 0.0) {
2122 for (int j = 0; j < 9; j++) {
2123 instance_sh[j] = accum_sh[j] / accum_blend;
2124 if (first_set) {
2125 p_instance->lightmap_sh.write[j] = instance_sh[j];
2126 }
2127 }
2128 }
2129
2130 ERR_FAIL_NULL(geom->geometry_instance);
2131 geom->geometry_instance->set_lightmap_capture(p_instance->lightmap_sh.ptr());
2132 }
2133
2134 void RendererSceneCull::_light_instance_setup_directional_shadow(int p_shadow_index, Instance *p_instance, const Transform3D p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect) {
2135 // For later tight culling, the light culler needs to know the details of the directional light.
2136 light_culler->prepare_directional_light(p_instance, p_shadow_index);
2137
2138 InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
2139
2140 Transform3D light_transform = p_instance->transform;
2141 light_transform.orthonormalize(); //scale does not count on lights
2142
2143 real_t max_distance = p_cam_projection.get_z_far();
2144 real_t shadow_max = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
2145 if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
2146 max_distance = MIN(shadow_max, max_distance);
2147 }
2148 max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
2149 real_t min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
2150
2151 real_t pancake_size = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE);
2152
2153 real_t range = max_distance - min_distance;
2154
2155 int splits = 0;
2156 switch (RSG::light_storage->light_directional_get_shadow_mode(p_instance->base)) {
2157 case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
2158 splits = 1;
2159 break;
2160 case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
2161 splits = 2;
2162 break;
2163 case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
2164 splits = 4;
2165 break;
2166 }
2167
2168 real_t distances[5];
2169
2170 distances[0] = min_distance;
2171 for (int i = 0; i < splits; i++) {
2172 distances[i + 1] = min_distance + RSG::light_storage->light_get_param(p_instance->base, RS::LightParam(RS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
2173 };
2174
2175 distances[splits] = max_distance;
2176
2177 real_t texture_size = RSG::light_storage->get_directional_light_shadow_size(light->instance);
2178
2179 bool overlap = RSG::light_storage->light_directional_get_blend_splits(p_instance->base);
2180
2181 cull.shadow_count = p_shadow_index + 1;
2182 cull.shadows[p_shadow_index].cascade_count = splits;
2183 cull.shadows[p_shadow_index].light_instance = light->instance;
2184 cull.shadows[p_shadow_index].caster_mask = RSG::light_storage->light_get_shadow_caster_mask(p_instance->base);
2185
2186 for (int i = 0; i < splits; i++) {
2187 RENDER_TIMESTAMP("Cull DirectionalLight3D, Split " + itos(i));
2188
2189 // setup a camera matrix for that range!
2190 Projection camera_matrix;
2191
2192 real_t aspect = p_cam_projection.get_aspect();
2193
2194 if (p_cam_orthogonal) {
2195 Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
2196
2197 camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
2198 } else {
2199 real_t fov = p_cam_projection.get_fov(); //this is actually yfov, because set aspect tries to keep it
2200 camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
2201 }
2202
2203 //obtain the frustum endpoints
2204
2205 Vector3 endpoints[8]; // frustum plane endpoints
2206 bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
2207 ERR_CONTINUE(!res);
2208
2209 // obtain the light frustum ranges (given endpoints)
2210
2211 Transform3D transform = light_transform; //discard scale and stabilize light
2212
2213 Vector3 x_vec = transform.basis.get_column(Vector3::AXIS_X).normalized();
2214 Vector3 y_vec = transform.basis.get_column(Vector3::AXIS_Y).normalized();
2215 Vector3 z_vec = transform.basis.get_column(Vector3::AXIS_Z).normalized();
2216 //z_vec points against the camera, like in default opengl
2217
2218 real_t x_min = 0.f, x_max = 0.f;
2219 real_t y_min = 0.f, y_max = 0.f;
2220 real_t z_min = 0.f, z_max = 0.f;
2221
2222 // FIXME: z_max_cam is defined, computed, but not used below when setting up
2223 // ortho_camera. Commented out for now to fix warnings but should be investigated.
2224 real_t x_min_cam = 0.f, x_max_cam = 0.f;
2225 real_t y_min_cam = 0.f, y_max_cam = 0.f;
2226 real_t z_min_cam = 0.f;
2227 //real_t z_max_cam = 0.f;
2228
2229 //real_t bias_scale = 1.0;
2230 //real_t aspect_bias_scale = 1.0;
2231
2232 //used for culling
2233
2234 for (int j = 0; j < 8; j++) {
2235 real_t d_x = x_vec.dot(endpoints[j]);
2236 real_t d_y = y_vec.dot(endpoints[j]);
2237 real_t d_z = z_vec.dot(endpoints[j]);
2238
2239 if (j == 0 || d_x < x_min) {
2240 x_min = d_x;
2241 }
2242 if (j == 0 || d_x > x_max) {
2243 x_max = d_x;
2244 }
2245
2246 if (j == 0 || d_y < y_min) {
2247 y_min = d_y;
2248 }
2249 if (j == 0 || d_y > y_max) {
2250 y_max = d_y;
2251 }
2252
2253 if (j == 0 || d_z < z_min) {
2254 z_min = d_z;
2255 }
2256 if (j == 0 || d_z > z_max) {
2257 z_max = d_z;
2258 }
2259 }
2260
2261 real_t radius = 0;
2262 real_t soft_shadow_expand = 0;
2263 Vector3 center;
2264
2265 {
2266 //camera viewport stuff
2267
2268 for (int j = 0; j < 8; j++) {
2269 center += endpoints[j];
2270 }
2271 center /= 8.0;
2272
2273 //center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5;
2274
2275 for (int j = 0; j < 8; j++) {
2276 real_t d = center.distance_to(endpoints[j]);
2277 if (d > radius) {
2278 radius = d;
2279 }
2280 }
2281
2282 radius *= texture_size / (texture_size - 2.0); //add a texel by each side
2283
2284 z_min_cam = z_vec.dot(center) - radius;
2285
2286 {
2287 float soft_shadow_angle = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE);
2288
2289 if (soft_shadow_angle > 0.0) {
2290 float z_range = (z_vec.dot(center) + radius + pancake_size) - z_min_cam;
2291 soft_shadow_expand = Math::tan(Math::deg_to_rad(soft_shadow_angle)) * z_range;
2292
2293 x_max += soft_shadow_expand;
2294 y_max += soft_shadow_expand;
2295
2296 x_min -= soft_shadow_expand;
2297 y_min -= soft_shadow_expand;
2298 }
2299 }
2300
2301 // This trick here is what stabilizes the shadow (make potential jaggies to not move)
2302 // at the cost of some wasted resolution. Still, the quality increase is very well worth it.
2303 const real_t unit = (radius + soft_shadow_expand) * 4.0 / texture_size;
2304 x_max_cam = Math::snapped(x_vec.dot(center) + radius + soft_shadow_expand, unit);
2305 x_min_cam = Math::snapped(x_vec.dot(center) - radius - soft_shadow_expand, unit);
2306 y_max_cam = Math::snapped(y_vec.dot(center) + radius + soft_shadow_expand, unit);
2307 y_min_cam = Math::snapped(y_vec.dot(center) - radius - soft_shadow_expand, unit);
2308 }
2309
2310 //now that we know all ranges, we can proceed to make the light frustum planes, for culling octree
2311
2312 Vector<Plane> light_frustum_planes;
2313 light_frustum_planes.resize(6);
2314
2315 //right/left
2316 light_frustum_planes.write[0] = Plane(x_vec, x_max);
2317 light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
2318 //top/bottom
2319 light_frustum_planes.write[2] = Plane(y_vec, y_max);
2320 light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
2321 //near/far
2322 light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
2323 light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
2324
2325 // a pre pass will need to be needed to determine the actual z-near to be used
2326
2327 z_max = z_vec.dot(center) + radius + pancake_size;
2328
2329 {
2330 Projection ortho_camera;
2331 real_t half_x = (x_max_cam - x_min_cam) * 0.5;
2332 real_t half_y = (y_max_cam - y_min_cam) * 0.5;
2333
2334 ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
2335
2336 Vector2 uv_scale(1.0 / (x_max_cam - x_min_cam), 1.0 / (y_max_cam - y_min_cam));
2337
2338 Transform3D ortho_transform;
2339 ortho_transform.basis = transform.basis;
2340 ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
2341
2342 cull.shadows[p_shadow_index].cascades[i].frustum = Frustum(light_frustum_planes);
2343 cull.shadows[p_shadow_index].cascades[i].projection = ortho_camera;
2344 cull.shadows[p_shadow_index].cascades[i].transform = ortho_transform;
2345 cull.shadows[p_shadow_index].cascades[i].zfar = z_max - z_min_cam;
2346 cull.shadows[p_shadow_index].cascades[i].split = distances[i + 1];
2347 cull.shadows[p_shadow_index].cascades[i].shadow_texel_size = radius * 2.0 / texture_size;
2348 cull.shadows[p_shadow_index].cascades[i].bias_scale = (z_max - z_min_cam);
2349 cull.shadows[p_shadow_index].cascades[i].range_begin = z_max;
2350 cull.shadows[p_shadow_index].cascades[i].uv_scale = uv_scale;
2351 }
2352 }
2353 }
2354
2355 bool RendererSceneCull::_light_instance_update_shadow(Instance *p_instance, const Transform3D p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_shadow_atlas, Scenario *p_scenario, float p_screen_mesh_lod_threshold, uint32_t p_visible_layers) {
2356 InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
2357
2358 Transform3D light_transform = p_instance->transform;
2359 light_transform.orthonormalize(); //scale does not count on lights
2360
2361 bool animated_material_found = false;
2362
2363 switch (RSG::light_storage->light_get_type(p_instance->base)) {
2364 case RS::LIGHT_DIRECTIONAL: {
2365 } break;
2366 case RS::LIGHT_OMNI: {
2367 RS::LightOmniShadowMode shadow_mode = RSG::light_storage->light_omni_get_shadow_mode(p_instance->base);
2368
2369 if (shadow_mode == RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !RSG::light_storage->light_instances_can_render_shadow_cube()) {
2370 if (max_shadows_used + 2 > MAX_UPDATE_SHADOWS) {
2371 return true;
2372 }
2373 for (int i = 0; i < 2; i++) {
2374 //using this one ensures that raster deferred will have it
2375 RENDER_TIMESTAMP("Cull OmniLight3D Shadow Paraboloid, Half " + itos(i));
2376
2377 real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
2378
2379 real_t z = i == 0 ? -1 : 1;
2380 Vector<Plane> planes;
2381 planes.resize(6);
2382 planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
2383 planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
2384 planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
2385 planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
2386 planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
2387 planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
2388
2389 instance_shadow_cull_result.clear();
2390
2391 Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
2392
2393 struct CullConvex {
2394 PagedArray<Instance *> *result;
2395 _FORCE_INLINE_ bool operator()(void *p_data) {
2396 Instance *p_instance = (Instance *)p_data;
2397 result->push_back(p_instance);
2398 return false;
2399 }
2400 };
2401
2402 CullConvex cull_convex;
2403 cull_convex.result = &instance_shadow_cull_result;
2404
2405 p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
2406
2407 RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
2408
2409 if (!light->is_shadow_update_full()) {
2410 light_culler->cull_regular_light(instance_shadow_cull_result);
2411 }
2412
2413 for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
2414 Instance *instance = instance_shadow_cull_result[j];
2415 if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows || !(p_visible_layers & instance->layer_mask & RSG::light_storage->light_get_shadow_caster_mask(p_instance->base))) {
2416 continue;
2417 } else {
2418 if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
2419 animated_material_found = true;
2420 }
2421
2422 if (instance->mesh_instance.is_valid()) {
2423 RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
2424 }
2425 }
2426
2427 shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
2428 }
2429
2430 RSG::mesh_storage->update_mesh_instances();
2431
2432 RSG::light_storage->light_instance_set_shadow_transform(light->instance, Projection(), light_transform, radius, 0, i, 0);
2433 shadow_data.light = light->instance;
2434 shadow_data.pass = i;
2435 }
2436 } else { //shadow cube
2437
2438 if (max_shadows_used + 6 > MAX_UPDATE_SHADOWS) {
2439 return true;
2440 }
2441
2442 real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
2443 real_t z_near = MIN(0.025f, radius);
2444 Projection cm;
2445 cm.set_perspective(90, 1, z_near, radius);
2446
2447 for (int i = 0; i < 6; i++) {
2448 RENDER_TIMESTAMP("Cull OmniLight3D Shadow Cube, Side " + itos(i));
2449 //using this one ensures that raster deferred will have it
2450
2451 static const Vector3 view_normals[6] = {
2452 Vector3(+1, 0, 0),
2453 Vector3(-1, 0, 0),
2454 Vector3(0, -1, 0),
2455 Vector3(0, +1, 0),
2456 Vector3(0, 0, +1),
2457 Vector3(0, 0, -1)
2458 };
2459 static const Vector3 view_up[6] = {
2460 Vector3(0, -1, 0),
2461 Vector3(0, -1, 0),
2462 Vector3(0, 0, -1),
2463 Vector3(0, 0, +1),
2464 Vector3(0, -1, 0),
2465 Vector3(0, -1, 0)
2466 };
2467
2468 Transform3D xform = light_transform * Transform3D().looking_at(view_normals[i], view_up[i]);
2469
2470 Vector<Plane> planes = cm.get_projection_planes(xform);
2471
2472 instance_shadow_cull_result.clear();
2473
2474 Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
2475
2476 struct CullConvex {
2477 PagedArray<Instance *> *result;
2478 _FORCE_INLINE_ bool operator()(void *p_data) {
2479 Instance *p_instance = (Instance *)p_data;
2480 result->push_back(p_instance);
2481 return false;
2482 }
2483 };
2484
2485 CullConvex cull_convex;
2486 cull_convex.result = &instance_shadow_cull_result;
2487
2488 p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
2489
2490 RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
2491
2492 if (!light->is_shadow_update_full()) {
2493 light_culler->cull_regular_light(instance_shadow_cull_result);
2494 }
2495
2496 for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
2497 Instance *instance = instance_shadow_cull_result[j];
2498 if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows || !(p_visible_layers & instance->layer_mask & RSG::light_storage->light_get_shadow_caster_mask(p_instance->base))) {
2499 continue;
2500 } else {
2501 if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
2502 animated_material_found = true;
2503 }
2504 if (instance->mesh_instance.is_valid()) {
2505 RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
2506 }
2507 }
2508
2509 shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
2510 }
2511
2512 RSG::mesh_storage->update_mesh_instances();
2513 RSG::light_storage->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0);
2514
2515 shadow_data.light = light->instance;
2516 shadow_data.pass = i;
2517 }
2518
2519 //restore the regular DP matrix
2520 //RSG::light_storage->light_instance_set_shadow_transform(light->instance, Projection(), light_transform, radius, 0, 0, 0);
2521 }
2522
2523 } break;
2524 case RS::LIGHT_SPOT: {
2525 RENDER_TIMESTAMP("Cull SpotLight3D Shadow");
2526
2527 if (max_shadows_used + 1 > MAX_UPDATE_SHADOWS) {
2528 return true;
2529 }
2530
2531 real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
2532 real_t angle = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
2533 real_t z_near = MIN(0.025f, radius);
2534
2535 Projection cm;
2536 cm.set_perspective(angle * 2.0, 1.0, z_near, radius);
2537
2538 Vector<Plane> planes = cm.get_projection_planes(light_transform);
2539
2540 instance_shadow_cull_result.clear();
2541
2542 Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
2543
2544 struct CullConvex {
2545 PagedArray<Instance *> *result;
2546 _FORCE_INLINE_ bool operator()(void *p_data) {
2547 Instance *p_instance = (Instance *)p_data;
2548 result->push_back(p_instance);
2549 return false;
2550 }
2551 };
2552
2553 CullConvex cull_convex;
2554 cull_convex.result = &instance_shadow_cull_result;
2555
2556 p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
2557
2558 RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
2559
2560 if (!light->is_shadow_update_full()) {
2561 light_culler->cull_regular_light(instance_shadow_cull_result);
2562 }
2563
2564 for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
2565 Instance *instance = instance_shadow_cull_result[j];
2566 if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows || !(p_visible_layers & instance->layer_mask & RSG::light_storage->light_get_shadow_caster_mask(p_instance->base))) {
2567 continue;
2568 } else {
2569 if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
2570 animated_material_found = true;
2571 }
2572
2573 if (instance->mesh_instance.is_valid()) {
2574 RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
2575 }
2576 }
2577 shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
2578 }
2579
2580 RSG::mesh_storage->update_mesh_instances();
2581
2582 RSG::light_storage->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0);
2583 shadow_data.light = light->instance;
2584 shadow_data.pass = 0;
2585
2586 } break;
2587 }
2588
2589 return animated_material_found;
2590 }
2591
2592 void RendererSceneCull::render_camera(const Ref<RenderSceneBuffers> &p_render_buffers, RID p_camera, RID p_scenario, RID p_viewport, Size2 p_viewport_size, uint32_t p_jitter_phase_count, float p_screen_mesh_lod_threshold, RID p_shadow_atlas, Ref<XRInterface> &p_xr_interface, RenderInfo *r_render_info) {
2593 #ifndef _3D_DISABLED
2594
2595 Camera *camera = camera_owner.get_or_null(p_camera);
2596 ERR_FAIL_NULL(camera);
2597
2598 Vector2 jitter;
2599 float taa_frame_count = 0.0f;
2600 if (p_jitter_phase_count > 0) {
2601 uint32_t current_jitter_count = camera_jitter_array.size();
2602 if (p_jitter_phase_count != current_jitter_count) {
2603 // Resize the jitter array and fill it with the pre-computed Halton sequence.
2604 camera_jitter_array.resize(p_jitter_phase_count);
2605
2606 for (uint32_t i = current_jitter_count; i < p_jitter_phase_count; i++) {
2607 camera_jitter_array[i].x = get_halton_value(i, 2);
2608 camera_jitter_array[i].y = get_halton_value(i, 3);
2609 }
2610 }
2611
2612 jitter = camera_jitter_array[RSG::rasterizer->get_frame_number() % p_jitter_phase_count] / p_viewport_size;
2613 taa_frame_count = float(RSG::rasterizer->get_frame_number() % p_jitter_phase_count);
2614 }
2615
2616 RendererSceneRender::CameraData camera_data;
2617
2618 // Setup Camera(s)
2619 if (p_xr_interface.is_null()) {
2620 // Normal camera
2621 Transform3D transform = camera->transform;
2622 Projection projection;
2623 bool vaspect = camera->vaspect;
2624 bool is_orthogonal = false;
2625 bool is_frustum = false;
2626
2627 switch (camera->type) {
2628 case Camera::ORTHOGONAL: {
2629 projection.set_orthogonal(
2630 camera->size,
2631 p_viewport_size.width / (float)p_viewport_size.height,
2632 camera->znear,
2633 camera->zfar,
2634 camera->vaspect);
2635 is_orthogonal = true;
2636 } break;
2637 case Camera::PERSPECTIVE: {
2638 projection.set_perspective(
2639 camera->fov,
2640 p_viewport_size.width / (float)p_viewport_size.height,
2641 camera->znear,
2642 camera->zfar,
2643 camera->vaspect);
2644
2645 } break;
2646 case Camera::FRUSTUM: {
2647 projection.set_frustum(
2648 camera->size,
2649 p_viewport_size.width / (float)p_viewport_size.height,
2650 camera->offset,
2651 camera->znear,
2652 camera->zfar,
2653 camera->vaspect);
2654 is_frustum = true;
2655 } break;
2656 }
2657
2658 camera_data.set_camera(transform, projection, is_orthogonal, is_frustum, vaspect, jitter, taa_frame_count, camera->visible_layers);
2659 #ifndef XR_DISABLED
2660 } else {
2661 XRServer *xr_server = XRServer::get_singleton();
2662
2663 // Setup our camera for our XR interface.
2664 // We can support multiple views here each with their own camera
2665 Transform3D transforms[RendererSceneRender::MAX_RENDER_VIEWS];
2666 Projection projections[RendererSceneRender::MAX_RENDER_VIEWS];
2667
2668 uint32_t view_count = p_xr_interface->get_view_count();
2669 ERR_FAIL_COND_MSG(view_count == 0 || view_count > RendererSceneRender::MAX_RENDER_VIEWS, "Requested view count is not supported");
2670
2671 float aspect = p_viewport_size.width / (float)p_viewport_size.height;
2672
2673 Transform3D world_origin = xr_server->get_world_origin();
2674
2675 // We ignore our camera position, it will have been positioned with a slightly old tracking position.
2676 // Instead we take our origin point and have our XR interface add fresh tracking data! Whoohoo!
2677 for (uint32_t v = 0; v < view_count; v++) {
2678 transforms[v] = p_xr_interface->get_transform_for_view(v, world_origin);
2679 projections[v] = p_xr_interface->get_projection_for_view(v, aspect, camera->znear, camera->zfar);
2680 }
2681
2682 // If requested, we move the views to be rendered as if the HMD is at the XROrigin.
2683 if (unlikely(xr_server->is_camera_locked_to_origin())) {
2684 Transform3D camera_reset = p_xr_interface->get_camera_transform().affine_inverse() * xr_server->get_reference_frame().affine_inverse();
2685 for (uint32_t v = 0; v < view_count; v++) {
2686 transforms[v] *= camera_reset;
2687 }
2688 }
2689
2690 if (view_count == 1) {
2691 camera_data.set_camera(transforms[0], projections[0], false, false, camera->vaspect, jitter, p_jitter_phase_count, camera->visible_layers);
2692 } else if (view_count == 2) {
2693 camera_data.set_multiview_camera(view_count, transforms, projections, false, false, camera->vaspect, camera->visible_layers);
2694 } else {
2695 // this won't be called (see fail check above) but keeping this comment to indicate we may support more then 2 views in the future...
2696 }
2697 #endif // XR_DISABLED
2698 }
2699
2700 RID environment = _render_get_environment(p_camera, p_scenario);
2701 RID compositor = _render_get_compositor(p_camera, p_scenario);
2702
2703 RENDER_TIMESTAMP("Update Occlusion Buffer")
2704 // For now just cull on the first camera
2705 RendererSceneOcclusionCull::get_singleton()->buffer_update(p_viewport, camera_data.main_transform, camera_data.main_projection, camera_data.is_orthogonal);
2706
2707 _render_scene(&camera_data, p_render_buffers, environment, camera->attributes, compositor, camera->visible_layers, p_scenario, p_viewport, p_shadow_atlas, RID(), -1, p_screen_mesh_lod_threshold, true, r_render_info);
2708 #endif
2709 }
2710
2711 void RendererSceneCull::_visibility_cull_threaded(uint32_t p_thread, VisibilityCullData *cull_data) {
2712 uint32_t total_threads = WorkerThreadPool::get_singleton()->get_thread_count();
2713 uint32_t bin_from = p_thread * cull_data->cull_count / total_threads;
2714 uint32_t bin_to = (p_thread + 1 == total_threads) ? cull_data->cull_count : ((p_thread + 1) * cull_data->cull_count / total_threads);
2715
2716 _visibility_cull(*cull_data, cull_data->cull_offset + bin_from, cull_data->cull_offset + bin_to);
2717 }
2718
2719 void RendererSceneCull::_visibility_cull(const VisibilityCullData &cull_data, uint64_t p_from, uint64_t p_to) {
2720 Scenario *scenario = cull_data.scenario;
2721 for (unsigned int i = p_from; i < p_to; i++) {
2722 InstanceVisibilityData &vd = scenario->instance_visibility[i];
2723 InstanceData &idata = scenario->instance_data[vd.array_index];
2724
2725 if (idata.parent_array_index >= 0) {
2726 uint32_t parent_flags = scenario->instance_data[idata.parent_array_index].flags;
2727
2728 if ((parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN) || !(parent_flags & (InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE | InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN))) {
2729 idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
2730 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
2731 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
2732 continue;
2733 }
2734 }
2735
2736 int range_check = _visibility_range_check<true>(vd, cull_data.camera_position, cull_data.viewport_mask);
2737
2738 if (range_check == -1) {
2739 idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
2740 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
2741 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
2742 } else if (range_check == 1) {
2743 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
2744 idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
2745 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
2746 } else {
2747 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
2748 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
2749 if (range_check == 2) {
2750 idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
2751 } else {
2752 idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
2753 }
2754 }
2755 }
2756 }
2757
2758 template <bool p_fade_check>
2759 int RendererSceneCull::_visibility_range_check(InstanceVisibilityData &r_vis_data, const Vector3 &p_camera_pos, uint64_t p_viewport_mask) {
2760 float dist = p_camera_pos.distance_to(r_vis_data.position);
2761 const RS::VisibilityRangeFadeMode &fade_mode = r_vis_data.fade_mode;
2762
2763 float begin_offset = -r_vis_data.range_begin_margin;
2764 float end_offset = r_vis_data.range_end_margin;
2765
2766 if (fade_mode == RS::VISIBILITY_RANGE_FADE_DISABLED && !(p_viewport_mask & r_vis_data.viewport_state)) {
2767 begin_offset = -begin_offset;
2768 end_offset = -end_offset;
2769 }
2770
2771 if (r_vis_data.range_end > 0.0f && dist > r_vis_data.range_end + end_offset) {
2772 r_vis_data.viewport_state &= ~p_viewport_mask;
2773 return -1;
2774 } else if (r_vis_data.range_begin > 0.0f && dist < r_vis_data.range_begin + begin_offset) {
2775 r_vis_data.viewport_state &= ~p_viewport_mask;
2776 return 1;
2777 } else {
2778 r_vis_data.viewport_state |= p_viewport_mask;
2779 if (p_fade_check) {
2780 if (fade_mode != RS::VISIBILITY_RANGE_FADE_DISABLED) {
2781 r_vis_data.children_fade_alpha = 1.0f;
2782 if (r_vis_data.range_end > 0.0f && dist > r_vis_data.range_end - end_offset) {
2783 if (fade_mode == RS::VISIBILITY_RANGE_FADE_DEPENDENCIES) {
2784 r_vis_data.children_fade_alpha = MIN(1.0f, (dist - (r_vis_data.range_end - end_offset)) / (2.0f * r_vis_data.range_end_margin));
2785 }
2786 return 2;
2787 } else if (r_vis_data.range_begin > 0.0f && dist < r_vis_data.range_begin - begin_offset) {
2788 if (fade_mode == RS::VISIBILITY_RANGE_FADE_DEPENDENCIES) {
2789 r_vis_data.children_fade_alpha = MIN(1.0f, 1.0 - (dist - (r_vis_data.range_begin + begin_offset)) / (2.0f * r_vis_data.range_begin_margin));
2790 }
2791 return 2;
2792 }
2793 }
2794 }
2795 return 0;
2796 }
2797 }
2798
2799 bool RendererSceneCull::_visibility_parent_check(const CullData &p_cull_data, const InstanceData &p_instance_data) {
2800 if (p_instance_data.parent_array_index == -1) {
2801 return true;
2802 }
2803 const uint32_t &parent_flags = p_cull_data.scenario->instance_data[p_instance_data.parent_array_index].flags;
2804 return ((parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK) == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE) || (parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN);
2805 }
2806
2807 void RendererSceneCull::_scene_cull_threaded(uint32_t p_thread, CullData *cull_data) {
2808 uint32_t cull_total = cull_data->scenario->instance_data.size();
2809 uint32_t total_threads = WorkerThreadPool::get_singleton()->get_thread_count();
2810 uint32_t cull_from = p_thread * cull_total / total_threads;
2811 uint32_t cull_to = (p_thread + 1 == total_threads) ? cull_total : ((p_thread + 1) * cull_total / total_threads);
2812
2813 _scene_cull(*cull_data, scene_cull_result_threads[p_thread], cull_from, cull_to);
2814 }
2815
2816 void RendererSceneCull::_scene_cull(CullData &cull_data, InstanceCullResult &cull_result, uint64_t p_from, uint64_t p_to) {
2817 uint64_t frame_number = RSG::rasterizer->get_frame_number();
2818 float lightmap_probe_update_speed = RSG::light_storage->lightmap_get_probe_capture_update_speed() * RSG::rasterizer->get_frame_delta_time();
2819
2820 uint32_t sdfgi_last_light_index = 0xFFFFFFFF;
2821 uint32_t sdfgi_last_light_cascade = 0xFFFFFFFF;
2822
2823 RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
2824
2825 // Minimize allocations when picking the most relevant lights per mesh.
2826 // We need to track the score and current index of the best N lights.
2827 thread_local LocalVector<Pair<float, uint32_t>> omni_score_idx, spot_score_idx;
2828 omni_score_idx.clear();
2829 spot_score_idx.clear();
2830 uint32_t max_lights_per_mesh = scene_render->get_max_lights_per_mesh();
2831 uint32_t max_lights_total = scene_render->get_max_lights_total();
2832
2833 Transform3D inv_cam_transform = cull_data.cam_transform.inverse();
2834 float z_near = cull_data.camera_matrix->get_z_near();
2835 bool is_orthogonal = cull_data.camera_matrix->is_orthogonal();
2836
2837 for (uint64_t i = p_from; i < p_to; i++) {
2838 bool mesh_visible = false;
2839
2840 InstanceData &idata = cull_data.scenario->instance_data[i];
2841 uint32_t visibility_flags = idata.flags & (InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE | InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN | InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN);
2842 int32_t visibility_check = -1;
2843
2844 #define HIDDEN_BY_VISIBILITY_CHECKS (visibility_flags == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE || visibility_flags == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN)
2845 #define LAYER_CHECK (cull_data.visible_layers & idata.layer_mask)
2846 #define IN_FRUSTUM(f) (cull_data.scenario->instance_aabbs[i].in_frustum(f))
2847 #define VIS_RANGE_CHECK ((idata.visibility_index == -1) || _visibility_range_check<false>(cull_data.scenario->instance_visibility[idata.visibility_index], cull_data.cam_transform.origin, cull_data.visibility_viewport_mask) == 0)
2848 #define VIS_PARENT_CHECK (_visibility_parent_check(cull_data, idata))
2849 #define VIS_CHECK (visibility_check < 0 ? (visibility_check = (visibility_flags != InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK || (VIS_RANGE_CHECK && VIS_PARENT_CHECK))) : visibility_check)
2850 #define OCCLUSION_CULLED (cull_data.occlusion_buffer != nullptr && (cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_IGNORE_OCCLUSION_CULLING) == 0 && cull_data.occlusion_buffer->is_occluded(cull_data.scenario->instance_aabbs[i].bounds, cull_data.cam_transform.origin, inv_cam_transform, *cull_data.camera_matrix, z_near, is_orthogonal, cull_data.scenario->instance_data[i].occlusion_timeout))
2851
2852 if (!HIDDEN_BY_VISIBILITY_CHECKS) {
2853 if ((LAYER_CHECK && IN_FRUSTUM(cull_data.cull->frustum) && VIS_CHECK && !OCCLUSION_CULLED) || (cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_IGNORE_ALL_CULLING)) {
2854 uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
2855 if (base_type == RS::INSTANCE_LIGHT) {
2856 cull_result.lights.push_back(idata.instance);
2857 cull_result.light_instances.push_back(RID::from_uint64(idata.instance_data_rid));
2858 if (cull_data.shadow_atlas.is_valid() && RSG::light_storage->light_has_shadow(idata.base_rid)) {
2859 RSG::light_storage->light_instance_mark_visible(RID::from_uint64(idata.instance_data_rid)); //mark it visible for shadow allocation later
2860 }
2861
2862 } else if (base_type == RS::INSTANCE_REFLECTION_PROBE) {
2863 if (cull_data.render_reflection_probe != idata.instance) {
2864 //avoid entering The Matrix
2865
2866 if ((idata.flags & InstanceData::FLAG_REFLECTION_PROBE_DIRTY) || RSG::light_storage->reflection_probe_instance_needs_redraw(RID::from_uint64(idata.instance_data_rid))) {
2867 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(idata.instance->base_data);
2868 cull_data.cull->lock.lock();
2869 if (!reflection_probe->update_list.in_list()) {
2870 reflection_probe->render_step = 0;
2871 reflection_probe_render_list.add_last(&reflection_probe->update_list);
2872 }
2873 cull_data.cull->lock.unlock();
2874
2875 idata.flags &= ~InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
2876 }
2877
2878 if (RSG::light_storage->reflection_probe_instance_has_reflection(RID::from_uint64(idata.instance_data_rid))) {
2879 cull_result.reflections.push_back(RID::from_uint64(idata.instance_data_rid));
2880 }
2881 }
2882 } else if (base_type == RS::INSTANCE_DECAL) {
2883 cull_result.decals.push_back(RID::from_uint64(idata.instance_data_rid));
2884
2885 } else if (base_type == RS::INSTANCE_VOXEL_GI) {
2886 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(idata.instance->base_data);
2887 cull_data.cull->lock.lock();
2888 if (!voxel_gi->update_element.in_list()) {
2889 voxel_gi_update_list.add(&voxel_gi->update_element);
2890 }
2891 cull_data.cull->lock.unlock();
2892 cull_result.voxel_gi_instances.push_back(RID::from_uint64(idata.instance_data_rid));
2893
2894 } else if (base_type == RS::INSTANCE_LIGHTMAP) {
2895 cull_result.lightmaps.push_back(RID::from_uint64(idata.instance_data_rid));
2896 } else if (base_type == RS::INSTANCE_FOG_VOLUME) {
2897 cull_result.fog_volumes.push_back(RID::from_uint64(idata.instance_data_rid));
2898 } else if (base_type == RS::INSTANCE_VISIBLITY_NOTIFIER) {
2899 InstanceVisibilityNotifierData *vnd = idata.visibility_notifier;
2900 if (!vnd->list_element.in_list()) {
2901 visible_notifier_list_lock.lock();
2902 visible_notifier_list.add(&vnd->list_element);
2903 visible_notifier_list_lock.unlock();
2904 vnd->just_visible = true;
2905 }
2906 vnd->visible_in_frame = RSG::rasterizer->get_frame_number();
2907 } else if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && !(idata.flags & InstanceData::FLAG_CAST_SHADOWS_ONLY)) {
2908 bool keep = true;
2909
2910 if (idata.flags & InstanceData::FLAG_REDRAW_IF_VISIBLE) {
2911 RenderingServerDefault::redraw_request();
2912 }
2913
2914 if (base_type == RS::INSTANCE_MESH) {
2915 mesh_visible = true;
2916 } else if (base_type == RS::INSTANCE_PARTICLES) {
2917 //particles visible? process them
2918 if (RSG::particles_storage->particles_is_inactive(idata.base_rid)) {
2919 //but if nothing is going on, don't do it.
2920 keep = false;
2921 } else {
2922 cull_data.cull->lock.lock();
2923 RSG::particles_storage->particles_request_process(idata.base_rid);
2924 cull_data.cull->lock.unlock();
2925
2926 RS::get_singleton()->call_on_render_thread(callable_mp_static(&RendererSceneCull::_scene_particles_set_view_axis).bind(idata.base_rid, -cull_data.cam_transform.basis.get_column(2).normalized(), cull_data.cam_transform.basis.get_column(1).normalized()));
2927 //particles visible? request redraw
2928 RenderingServerDefault::redraw_request();
2929 }
2930 }
2931
2932 if (idata.parent_array_index != -1) {
2933 float fade = 1.0f;
2934 const uint32_t &parent_flags = cull_data.scenario->instance_data[idata.parent_array_index].flags;
2935 if (parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN) {
2936 const int32_t &parent_idx = cull_data.scenario->instance_data[idata.parent_array_index].visibility_index;
2937 fade = cull_data.scenario->instance_visibility[parent_idx].children_fade_alpha;
2938 }
2939 idata.instance_geometry->set_parent_fade_alpha(fade);
2940 }
2941
2942 if (geometry_instance_pair_mask & (1 << RS::INSTANCE_LIGHT) && (idata.flags & InstanceData::FLAG_GEOM_LIGHTING_DIRTY)) {
2943 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
2944 ERR_FAIL_NULL(geom->geometry_instance);
2945 // Clear any existing light instances for this mesh and find the max count per-mesh, and total (per-scene).
2946 geom->geometry_instance->clear_light_instances();
2947 if ((max_lights_per_mesh > 0) && (max_lights_total > 0)) {
2948 // For the top N lights, track the score and the index into the internal light storage array.
2949 uint32_t total_omni_count = 0, total_spot_count = 0;
2950 bool omni_needs_heap = true, spot_needs_heap = true;
2951 uint32_t omni_count = 0, spot_count = 0;
2952 omni_score_idx.clear();
2953 spot_score_idx.clear();
2954 SortArray<Pair<float, uint32_t>> heapify; // SortArray has heap functions, but no local storage.
2955 // Iterate over the lights (possibly > max_renderable_lights), keeping the closest to the mesh center.
2956 Vector3 mesh_center = idata.instance->transformed_aabb.get_center();
2957 for (const Instance *E : geom->lights) {
2958 RS::LightType light_type = RSG::light_storage->light_get_type(E->base);
2959 if (((RS::LIGHT_OMNI == light_type) && (total_omni_count++ < max_lights_total)) ||
2960 ((RS::LIGHT_SPOT == light_type) && (total_spot_count++ < max_lights_total))) {
2961 // Perform culling.
2962 if (!(RSG::light_storage->light_get_cull_mask(E->base) & idata.layer_mask)) {
2963 continue;
2964 }
2965 if ((RSG::light_storage->light_get_bake_mode(E->base) == RS::LIGHT_BAKE_STATIC) && idata.instance->lightmap) {
2966 continue;
2967 }
2968
2969 InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
2970 // Large scores are worse, so linear with distance, inverse with energy and range.
2971 Vector3 light_center = E->transformed_aabb.get_center();
2972 float light_range_energy =
2973 RSG::light_storage->light_get_param(E->base, RS::LightParam::LIGHT_PARAM_RANGE) *
2974 RSG::light_storage->light_get_param(E->base, RS::LightParam::LIGHT_PARAM_ENERGY);
2975 float light_inst_score = mesh_center.distance_to(light_center) / MAX(0.01f, light_range_energy);
2976 // Of the N lights (on a per-light-type basis, Omni or Spot) keep only the M "best" lights.
2977 // If N <= M, we can simply store the lights, but once we exceed M, we need check each new
2978 // light and see if it's score is better than the worst light stored to date. If the new
2979 // light is better, we can replace the current worst light with the new one. In order to
2980 // efficiently track our currently worst light we use a "max heap". This loosely orders
2981 // the elements in an array as a binary-tree structure, and has the properties that finding
2982 // the worst score element is O(1) (it will always be stored in element [0]), and removing
2983 // the old max and inserting a new value is O(log M).
2984 #define VERIFY_RELEVANT_LIGHT_HEAP 0
2985 #if VERIFY_RELEVANT_LIGHT_HEAP
2986 WARN_PRINT_ONCE("VERIFY_RELEVANT_LIGHT_HEAP is True");
2987 #endif
2988 switch (light_type) {
2989 case RS::LIGHT_OMNI: {
2990 if (omni_count < max_lights_per_mesh) {
2991 // We have room to just add it, and track the score and where it goes.
2992 omni_score_idx.push_back(Pair(light_inst_score, omni_count));
2993 geom->geometry_instance->pair_light_instance(light->instance, light_type, omni_count++);
2994 } else {
2995 if (omni_needs_heap) {
2996 // We need to make this a heap one time.
2997 heapify.make_heap(0, omni_count, &omni_score_idx[0]);
2998 omni_needs_heap = false;
2999 }
3000 if (light_inst_score < omni_score_idx[0].first) {
3001 #if VERIFY_RELEVANT_LIGHT_HEAP
3002 // The [0] element should have the max score.
3003 for (uint32_t vi = 1; vi < max_lights_per_mesh; ++vi) {
3004 if (omni_score_idx[vi].first > omni_score_idx[0].first) {
3005 ERR_PRINT_ONCE("Relevant Omni Light Heap Error");
3006 }
3007 }
3008 #endif
3009 uint32_t replace_index = omni_score_idx[0].second;
3010 geom->geometry_instance->pair_light_instance(light->instance, light_type, replace_index);
3011 heapify.adjust_heap(0, 0, omni_count, Pair(light_inst_score, replace_index), &omni_score_idx[0]);
3012 }
3013 }
3014 } break;
3015 case RS::LIGHT_SPOT: {
3016 if (spot_count < max_lights_per_mesh) {
3017 // We have room to just add it, and track the score and where it goes.
3018 spot_score_idx.push_back(Pair(light_inst_score, spot_count));
3019 geom->geometry_instance->pair_light_instance(light->instance, light_type, spot_count++);
3020 } else {
3021 if (spot_needs_heap) {
3022 // We need to make this a heap one time.
3023 heapify.make_heap(0, spot_count, &spot_score_idx[0]);
3024 spot_needs_heap = false;
3025 }
3026 if (light_inst_score < spot_score_idx[0].first) {
3027 #if VERIFY_RELEVANT_LIGHT_HEAP
3028 // The [0] element should have the max score.
3029 for (uint32_t vi = 1; vi < max_lights_per_mesh; ++vi) {
3030 if (spot_score_idx[vi].first > spot_score_idx[0].first) {
3031 ERR_PRINT_ONCE("Relevant Spot Light Heap Error");
3032 }
3033 }
3034 #endif
3035 uint32_t replace_index = spot_score_idx[0].second;
3036 geom->geometry_instance->pair_light_instance(light->instance, light_type, replace_index);
3037 heapify.adjust_heap(0, 0, spot_count, Pair(light_inst_score, replace_index), &spot_score_idx[0]);
3038 }
3039 }
3040 } break;
3041 default:
3042 break;
3043 }
3044 }
3045 }
3046 }
3047 idata.flags &= ~InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
3048 }
3049
3050 if (idata.flags & InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY) {
3051 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
3052
3053 ERR_FAIL_NULL(geom->geometry_instance);
3054 cull_data.cull->lock.lock();
3055 geom->geometry_instance->set_softshadow_projector_pairing(geom->softshadow_count > 0, geom->projector_count > 0);
3056 cull_data.cull->lock.unlock();
3057 idata.flags &= ~InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
3058 }
3059
3060 if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (idata.flags & InstanceData::FLAG_GEOM_REFLECTION_DIRTY)) {
3061 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
3062 uint32_t idx = 0;
3063
3064 for (const Instance *E : geom->reflection_probes) {
3065 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->base_data);
3066
3067 instance_pair_buffer[idx++] = reflection_probe->instance;
3068 if (idx == MAX_INSTANCE_PAIRS) {
3069 break;
3070 }
3071 }
3072
3073 ERR_FAIL_NULL(geom->geometry_instance);
3074 geom->geometry_instance->pair_reflection_probe_instances(instance_pair_buffer, idx);
3075 idata.flags &= ~InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
3076 }
3077
3078 if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (idata.flags & InstanceData::FLAG_GEOM_DECAL_DIRTY)) {
3079 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
3080 uint32_t idx = 0;
3081
3082 for (const Instance *E : geom->decals) {
3083 InstanceDecalData *decal = static_cast<InstanceDecalData *>(E->base_data);
3084
3085 instance_pair_buffer[idx++] = decal->instance;
3086 if (idx == MAX_INSTANCE_PAIRS) {
3087 break;
3088 }
3089 }
3090
3091 ERR_FAIL_NULL(geom->geometry_instance);
3092 geom->geometry_instance->pair_decal_instances(instance_pair_buffer, idx);
3093
3094 idata.flags &= ~InstanceData::FLAG_GEOM_DECAL_DIRTY;
3095 }
3096
3097 if (idata.flags & InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY) {
3098 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
3099 uint32_t idx = 0;
3100 for (const Instance *E : geom->voxel_gi_instances) {
3101 InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(E->base_data);
3102
3103 instance_pair_buffer[idx++] = voxel_gi->probe_instance;
3104 if (idx == MAX_INSTANCE_PAIRS) {
3105 break;
3106 }
3107 }
3108
3109 ERR_FAIL_NULL(geom->geometry_instance);
3110 geom->geometry_instance->pair_voxel_gi_instances(instance_pair_buffer, idx);
3111
3112 idata.flags &= ~InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
3113 }
3114
3115 if ((idata.flags & InstanceData::FLAG_LIGHTMAP_CAPTURE) && idata.instance->last_frame_pass != frame_number && !idata.instance->lightmap_target_sh.is_empty() && !idata.instance->lightmap_sh.is_empty()) {
3116 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
3117 Color *sh = idata.instance->lightmap_sh.ptrw();
3118 const Color *target_sh = idata.instance->lightmap_target_sh.ptr();
3119 for (uint32_t j = 0; j < 9; j++) {
3120 sh[j] = sh[j].lerp(target_sh[j], MIN(1.0, lightmap_probe_update_speed));
3121 }
3122 ERR_FAIL_NULL(geom->geometry_instance);
3123 cull_data.cull->lock.lock();
3124 geom->geometry_instance->set_lightmap_capture(sh);
3125 cull_data.cull->lock.unlock();
3126 idata.instance->last_frame_pass = frame_number;
3127 }
3128
3129 if (keep) {
3130 cull_result.geometry_instances.push_back(idata.instance_geometry);
3131 }
3132 }
3133 }
3134
3135 for (uint32_t j = 0; j < cull_data.cull->shadow_count; j++) {
3136 if (!light_culler->cull_directional_light(cull_data.scenario->instance_aabbs[i], j)) {
3137 continue;
3138 }
3139 for (uint32_t k = 0; k < cull_data.cull->shadows[j].cascade_count; k++) {
3140 if (IN_FRUSTUM(cull_data.cull->shadows[j].cascades[k].frustum) && VIS_CHECK) {
3141 uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
3142
3143 if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && idata.flags & InstanceData::FLAG_CAST_SHADOWS && (LAYER_CHECK & cull_data.cull->shadows[j].caster_mask)) {
3144 cull_result.directional_shadows[j].cascade_geometry_instances[k].push_back(idata.instance_geometry);
3145 mesh_visible = true;
3146 }
3147 }
3148 }
3149 }
3150 }
3151
3152 #undef HIDDEN_BY_VISIBILITY_CHECKS
3153 #undef LAYER_CHECK
3154 #undef IN_FRUSTUM
3155 #undef VIS_RANGE_CHECK
3156 #undef VIS_PARENT_CHECK
3157 #undef VIS_CHECK
3158 #undef OCCLUSION_CULLED
3159
3160 for (uint32_t j = 0; j < cull_data.cull->sdfgi.region_count; j++) {
3161 if (cull_data.scenario->instance_aabbs[i].in_aabb(cull_data.cull->sdfgi.region_aabb[j])) {
3162 uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
3163
3164 if (base_type == RS::INSTANCE_LIGHT) {
3165 InstanceLightData *instance_light = (InstanceLightData *)idata.instance->base_data;
3166 if (instance_light->bake_mode == RS::LIGHT_BAKE_STATIC && cull_data.cull->sdfgi.region_cascade[j] <= instance_light->max_sdfgi_cascade) {
3167 if (sdfgi_last_light_index != i || sdfgi_last_light_cascade != cull_data.cull->sdfgi.region_cascade[j]) {
3168 sdfgi_last_light_index = i;
3169 sdfgi_last_light_cascade = cull_data.cull->sdfgi.region_cascade[j];
3170 cull_result.sdfgi_cascade_lights[sdfgi_last_light_cascade].push_back(instance_light->instance);
3171 }
3172 }
3173 } else if ((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) {
3174 if (idata.flags & InstanceData::FLAG_USES_BAKED_LIGHT) {
3175 cull_result.sdfgi_region_geometry_instances[j].push_back(idata.instance_geometry);
3176 mesh_visible = true;
3177 }
3178 }
3179 }
3180 }
3181
3182 if (mesh_visible && cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_USES_MESH_INSTANCE) {
3183 cull_result.mesh_instances.push_back(cull_data.scenario->instance_data[i].instance->mesh_instance);
3184 }
3185 }
3186 }
3187
3188 void RendererSceneCull::_scene_particles_set_view_axis(RID p_particles, const Vector3 &p_axis, const Vector3 &p_up_axis) {
3189 RSG::particles_storage->particles_set_view_axis(p_particles, p_axis, p_up_axis);
3190 }
3191
3192 void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_camera_data, const Ref<RenderSceneBuffers> &p_render_buffers, RID p_environment, RID p_force_camera_attributes, RID p_compositor, uint32_t p_visible_layers, RID p_scenario, RID p_viewport, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, bool p_using_shadows, RenderingMethod::RenderInfo *r_render_info) {
3193 Instance *render_reflection_probe = instance_owner.get_or_null(p_reflection_probe); //if null, not rendering to it
3194
3195 // Prepare the light - camera volume culling system.
3196 light_culler->prepare_camera(p_camera_data->main_transform, p_camera_data->main_projection);
3197
3198 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
3199 Vector3 camera_position = p_camera_data->main_transform.origin;
3200
3201 ERR_FAIL_COND(p_render_buffers.is_null());
3202
3203 render_pass++;
3204
3205 scene_render->set_scene_pass(render_pass);
3206
3207 if (p_reflection_probe.is_null()) {
3208 //no rendering code here, this is only to set up what needs to be done, request regions, etc.
3209 scene_render->sdfgi_update(p_render_buffers, p_environment, camera_position); //update conditions for SDFGI (whether its used or not)
3210 }
3211
3212 RENDER_TIMESTAMP("Update Visibility Dependencies");
3213
3214 if (scenario->instance_visibility.get_bin_count() > 0) {
3215 if (!scenario->viewport_visibility_masks.has(p_viewport)) {
3216 scenario_add_viewport_visibility_mask(scenario->self, p_viewport);
3217 }
3218
3219 VisibilityCullData visibility_cull_data;
3220 visibility_cull_data.scenario = scenario;
3221 visibility_cull_data.viewport_mask = scenario->viewport_visibility_masks[p_viewport];
3222 visibility_cull_data.camera_position = camera_position;
3223
3224 for (int i = scenario->instance_visibility.get_bin_count() - 1; i > 0; i--) { // We skip bin 0
3225 visibility_cull_data.cull_offset = scenario->instance_visibility.get_bin_start(i);
3226 visibility_cull_data.cull_count = scenario->instance_visibility.get_bin_size(i);
3227
3228 if (visibility_cull_data.cull_count == 0) {
3229 continue;
3230 }
3231
3232 if (visibility_cull_data.cull_count > thread_cull_threshold) {
3233 WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RendererSceneCull::_visibility_cull_threaded, &visibility_cull_data, WorkerThreadPool::get_singleton()->get_thread_count(), -1, true, SNAME("VisibilityCullInstances"));
3234 WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
3235 } else {
3236 _visibility_cull(visibility_cull_data, visibility_cull_data.cull_offset, visibility_cull_data.cull_offset + visibility_cull_data.cull_count);
3237 }
3238 }
3239 }
3240
3241 RENDER_TIMESTAMP("Cull 3D Scene");
3242
3243 //rasterizer->set_camera(p_camera_data->main_transform, p_camera_data.main_projection, p_camera_data.is_orthogonal);
3244
3245 /* STEP 2 - CULL */
3246
3247 Vector<Plane> planes = p_camera_data->main_projection.get_projection_planes(p_camera_data->main_transform);
3248 cull.frustum = Frustum(planes);
3249
3250 Vector<RID> directional_lights;
3251 // directional lights
3252 {
3253 cull.shadow_count = 0;
3254
3255 Vector<Instance *> lights_with_shadow;
3256
3257 for (Instance *E : scenario->directional_lights) {
3258 if (!E->visible || !(E->layer_mask & p_visible_layers)) {
3259 continue;
3260 }
3261
3262 if (directional_lights.size() >= RendererSceneRender::MAX_DIRECTIONAL_LIGHTS) {
3263 break;
3264 }
3265
3266 InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
3267
3268 //check shadow..
3269
3270 if (light) {
3271 if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::light_storage->light_has_shadow(E->base) && !(RSG::light_storage->light_get_type(E->base) == RS::LIGHT_DIRECTIONAL && RSG::light_storage->light_directional_get_sky_mode(E->base) == RS::LIGHT_DIRECTIONAL_SKY_MODE_SKY_ONLY)) {
3272 lights_with_shadow.push_back(E);
3273 }
3274 //add to list
3275 directional_lights.push_back(light->instance);
3276 }
3277 }
3278
3279 RSG::light_storage->set_directional_shadow_count(lights_with_shadow.size());
3280
3281 for (int i = 0; i < lights_with_shadow.size(); i++) {
3282 _light_instance_setup_directional_shadow(i, lights_with_shadow[i], p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect);
3283 }
3284 }
3285
3286 { //sdfgi
3287 cull.sdfgi.region_count = 0;
3288
3289 if (p_reflection_probe.is_null()) {
3290 cull.sdfgi.cascade_light_count = 0;
3291
3292 uint32_t prev_cascade = 0xFFFFFFFF;
3293 uint32_t pending_region_count = scene_render->sdfgi_get_pending_region_count(p_render_buffers);
3294
3295 for (uint32_t i = 0; i < pending_region_count; i++) {
3296 cull.sdfgi.region_aabb[i] = scene_render->sdfgi_get_pending_region_bounds(p_render_buffers, i);
3297 uint32_t region_cascade = scene_render->sdfgi_get_pending_region_cascade(p_render_buffers, i);
3298 cull.sdfgi.region_cascade[i] = region_cascade;
3299
3300 if (region_cascade != prev_cascade) {
3301 cull.sdfgi.cascade_light_index[cull.sdfgi.cascade_light_count] = region_cascade;
3302 cull.sdfgi.cascade_light_count++;
3303 prev_cascade = region_cascade;
3304 }
3305 }
3306
3307 cull.sdfgi.region_count = pending_region_count;
3308 }
3309 }
3310
3311 scene_cull_result.clear();
3312
3313 {
3314 uint64_t cull_from = 0;
3315 uint64_t cull_to = scenario->instance_data.size();
3316
3317 CullData cull_data;
3318
3319 //prepare for eventual thread usage
3320 cull_data.cull = &cull;
3321 cull_data.scenario = scenario;
3322 cull_data.shadow_atlas = p_shadow_atlas;
3323 cull_data.cam_transform = p_camera_data->main_transform;
3324 cull_data.visible_layers = p_visible_layers;
3325 cull_data.render_reflection_probe = render_reflection_probe;
3326 cull_data.occlusion_buffer = RendererSceneOcclusionCull::get_singleton()->buffer_get_ptr(p_viewport);
3327 cull_data.camera_matrix = &p_camera_data->main_projection;
3328 cull_data.visibility_viewport_mask = scenario->viewport_visibility_masks.has(p_viewport) ? scenario->viewport_visibility_masks[p_viewport] : 0;
3329 //#define DEBUG_CULL_TIME
3330 #ifdef DEBUG_CULL_TIME
3331 uint64_t time_from = OS::get_singleton()->get_ticks_usec();
3332 #endif
3333
3334 if (cull_to > thread_cull_threshold) {
3335 //multiple threads
3336 for (InstanceCullResult &thread : scene_cull_result_threads) {
3337 thread.clear();
3338 }
3339
3340 WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RendererSceneCull::_scene_cull_threaded, &cull_data, scene_cull_result_threads.size(), -1, true, SNAME("RenderCullInstances"));
3341 WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
3342
3343 for (InstanceCullResult &thread : scene_cull_result_threads) {
3344 scene_cull_result.append_from(thread);
3345 }
3346
3347 } else {
3348 //single threaded
3349 _scene_cull(cull_data, scene_cull_result, cull_from, cull_to);
3350 }
3351
3352 #ifdef DEBUG_CULL_TIME
3353 static float time_avg = 0;
3354 static uint32_t time_count = 0;
3355 time_avg += double(OS::get_singleton()->get_ticks_usec() - time_from) / 1000.0;
3356 time_count++;
3357 print_line("time taken: " + rtos(time_avg / time_count));
3358 #endif
3359
3360 if (scene_cull_result.mesh_instances.size()) {
3361 for (uint64_t i = 0; i < scene_cull_result.mesh_instances.size(); i++) {
3362 RSG::mesh_storage->mesh_instance_check_for_update(scene_cull_result.mesh_instances[i]);
3363 }
3364 RSG::mesh_storage->update_mesh_instances();
3365 }
3366 }
3367
3368 //render shadows
3369
3370 max_shadows_used = 0;
3371
3372 if (p_using_shadows) { //setup shadow maps
3373
3374 // Directional Shadows
3375
3376 for (uint32_t i = 0; i < cull.shadow_count; i++) {
3377 for (uint32_t j = 0; j < cull.shadows[i].cascade_count; j++) {
3378 const Cull::Shadow::Cascade &c = cull.shadows[i].cascades[j];
3379 // print_line("shadow " + itos(i) + " cascade " + itos(j) + " elements: " + itos(c.cull_result.size()));
3380 RSG::light_storage->light_instance_set_shadow_transform(cull.shadows[i].light_instance, c.projection, c.transform, c.zfar, c.split, j, c.shadow_texel_size, c.bias_scale, c.range_begin, c.uv_scale);
3381 if (max_shadows_used == MAX_UPDATE_SHADOWS) {
3382 continue;
3383 }
3384 render_shadow_data[max_shadows_used].light = cull.shadows[i].light_instance;
3385 render_shadow_data[max_shadows_used].pass = j;
3386 render_shadow_data[max_shadows_used].instances.merge_unordered(scene_cull_result.directional_shadows[i].cascade_geometry_instances[j]);
3387 max_shadows_used++;
3388 }
3389 }
3390
3391 // Positional Shadows
3392 for (uint32_t i = 0; i < (uint32_t)scene_cull_result.lights.size(); i++) {
3393 Instance *ins = scene_cull_result.lights[i];
3394
3395 if (!p_shadow_atlas.is_valid()) {
3396 continue;
3397 }
3398
3399 InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
3400
3401 if (!RSG::light_storage->light_instance_is_shadow_visible_at_position(light->instance, camera_position)) {
3402 continue;
3403 }
3404
3405 float coverage = 0.f;
3406
3407 { //compute coverage
3408
3409 Transform3D cam_xf = p_camera_data->main_transform;
3410 float zn = p_camera_data->main_projection.get_z_near();
3411 Plane p(-cam_xf.basis.get_column(2), cam_xf.origin + cam_xf.basis.get_column(2) * -zn); //camera near plane
3412
3413 // near plane half width and height
3414 Vector2 vp_half_extents = p_camera_data->main_projection.get_viewport_half_extents();
3415
3416 switch (RSG::light_storage->light_get_type(ins->base)) {
3417 case RS::LIGHT_OMNI: {
3418 float radius = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
3419
3420 //get two points parallel to near plane
3421 Vector3 points[2] = {
3422 ins->transform.origin,
3423 ins->transform.origin + cam_xf.basis.get_column(0) * radius
3424 };
3425
3426 if (!p_camera_data->is_orthogonal) {
3427 //if using perspetive, map them to near plane
3428 for (int j = 0; j < 2; j++) {
3429 if (p.distance_to(points[j]) < 0) {
3430 points[j].z = -zn; //small hack to keep size constant when hitting the screen
3431 }
3432
3433 p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
3434 }
3435 }
3436
3437 float screen_diameter = points[0].distance_to(points[1]) * 2;
3438 coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
3439 } break;
3440 case RS::LIGHT_SPOT: {
3441 float radius = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
3442 float angle = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_SPOT_ANGLE);
3443
3444 float w = radius * Math::sin(Math::deg_to_rad(angle));
3445 float d = radius * Math::cos(Math::deg_to_rad(angle));
3446
3447 Vector3 base = ins->transform.origin - ins->transform.basis.get_column(2).normalized() * d;
3448
3449 Vector3 points[2] = {
3450 base,
3451 base + cam_xf.basis.get_column(0) * w
3452 };
3453
3454 if (!p_camera_data->is_orthogonal) {
3455 //if using perspetive, map them to near plane
3456 for (int j = 0; j < 2; j++) {
3457 if (p.distance_to(points[j]) < 0) {
3458 points[j].z = -zn; //small hack to keep size constant when hitting the screen
3459 }
3460
3461 p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
3462 }
3463 }
3464
3465 float screen_diameter = points[0].distance_to(points[1]) * 2;
3466 coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
3467
3468 } break;
3469 default: {
3470 ERR_PRINT("Invalid Light Type");
3471 }
3472 }
3473 }
3474
3475 // We can detect whether multiple cameras are hitting this light, whether or not the shadow is dirty,
3476 // so that we can turn off tighter caster culling.
3477 light->detect_light_intersects_multiple_cameras(Engine::get_singleton()->get_frames_drawn());
3478
3479 if (light->is_shadow_dirty()) {
3480 // Dirty shadows have no need to be drawn if
3481 // the light volume doesn't intersect the camera frustum.
3482
3483 // Returns false if the entire light can be culled.
3484 bool allow_redraw = light_culler->prepare_regular_light(*ins);
3485
3486 // Directional lights aren't handled here, _light_instance_update_shadow is called from elsewhere.
3487 // Checking for this in case this changes, as this is assumed.
3488 DEV_CHECK_ONCE(RSG::light_storage->light_get_type(ins->base) != RS::LIGHT_DIRECTIONAL);
3489
3490 // Tighter caster culling to the camera frustum should work correctly with multiple viewports + cameras.
3491 // The first camera will cull tightly, but if the light is present on more than 1 camera, the second will
3492 // do a full render, and mark the light as non-dirty.
3493 // There is however a cost to tighter shadow culling in this situation (2 shadow updates in 1 frame),
3494 // so we should detect this and switch off tighter caster culling automatically.
3495 // This is done in the logic for `decrement_shadow_dirty()`.
3496 if (allow_redraw) {
3497 light->last_version++;
3498 light->decrement_shadow_dirty();
3499 }
3500 }
3501
3502 bool redraw = RSG::light_storage->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
3503
3504 if (redraw && max_shadows_used < MAX_UPDATE_SHADOWS) {
3505 //must redraw!
3506 RENDER_TIMESTAMP("> Render Light3D " + itos(i));
3507 if (_light_instance_update_shadow(ins, p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect, p_shadow_atlas, scenario, p_screen_mesh_lod_threshold, p_visible_layers)) {
3508 light->make_shadow_dirty();
3509 }
3510 RENDER_TIMESTAMP("< Render Light3D " + itos(i));
3511 } else {
3512 if (redraw) {
3513 light->make_shadow_dirty();
3514 }
3515 }
3516 }
3517 }
3518
3519 //render SDFGI
3520
3521 {
3522 // Q: Should this whole block be skipped if we're rendering our reflection probe?
3523
3524 sdfgi_update_data.update_static = false;
3525
3526 if (cull.sdfgi.region_count > 0) {
3527 //update regions
3528 for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
3529 render_sdfgi_data[i].instances.merge_unordered(scene_cull_result.sdfgi_region_geometry_instances[i]);
3530 render_sdfgi_data[i].region = i;
3531 }
3532 //check if static lights were culled
3533 bool static_lights_culled = false;
3534 for (uint32_t i = 0; i < cull.sdfgi.cascade_light_count; i++) {
3535 if (scene_cull_result.sdfgi_cascade_lights[i].size()) {
3536 static_lights_culled = true;
3537 break;
3538 }
3539 }
3540
3541 if (static_lights_culled) {
3542 sdfgi_update_data.static_cascade_count = cull.sdfgi.cascade_light_count;
3543 sdfgi_update_data.static_cascade_indices = cull.sdfgi.cascade_light_index;
3544 sdfgi_update_data.static_positional_lights = scene_cull_result.sdfgi_cascade_lights;
3545 sdfgi_update_data.update_static = true;
3546 }
3547 }
3548
3549 if (p_reflection_probe.is_null()) {
3550 sdfgi_update_data.directional_lights = &directional_lights;
3551 sdfgi_update_data.positional_light_instances = scenario->dynamic_lights.ptr();
3552 sdfgi_update_data.positional_light_count = scenario->dynamic_lights.size();
3553 }
3554 }
3555
3556 //append the directional lights to the lights culled
3557 for (int i = 0; i < directional_lights.size(); i++) {
3558 scene_cull_result.light_instances.push_back(directional_lights[i]);
3559 }
3560
3561 RID camera_attributes;
3562 if (p_force_camera_attributes.is_valid()) {
3563 camera_attributes = p_force_camera_attributes;
3564 } else {
3565 camera_attributes = scenario->camera_attributes;
3566 }
3567
3568 /* PROCESS GEOMETRY AND DRAW SCENE */
3569
3570 RID occluders_tex;
3571 const RendererSceneRender::CameraData *prev_camera_data = p_camera_data;
3572 if (p_viewport.is_valid()) {
3573 occluders_tex = RSG::viewport->viewport_get_occluder_debug_texture(p_viewport);
3574 prev_camera_data = RSG::viewport->viewport_get_prev_camera_data(p_viewport);
3575 }
3576
3577 RENDER_TIMESTAMP("Render 3D Scene");
3578 scene_render->render_scene(p_render_buffers, p_camera_data, prev_camera_data, scene_cull_result.geometry_instances, scene_cull_result.light_instances, scene_cull_result.reflections, scene_cull_result.voxel_gi_instances, scene_cull_result.decals, scene_cull_result.lightmaps, scene_cull_result.fog_volumes, p_environment, camera_attributes, p_compositor, p_shadow_atlas, occluders_tex, p_reflection_probe.is_valid() ? RID() : scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass, p_screen_mesh_lod_threshold, render_shadow_data, max_shadows_used, render_sdfgi_data, cull.sdfgi.region_count, &sdfgi_update_data, r_render_info);
3579
3580 if (p_viewport.is_valid()) {
3581 RSG::viewport->viewport_set_prev_camera_data(p_viewport, p_camera_data);
3582 }
3583
3584 for (uint32_t i = 0; i < max_shadows_used; i++) {
3585 render_shadow_data[i].instances.clear();
3586 }
3587 max_shadows_used = 0;
3588
3589 for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
3590 render_sdfgi_data[i].instances.clear();
3591 }
3592 }
3593
3594 RID RendererSceneCull::_render_get_environment(RID p_camera, RID p_scenario) {
3595 Camera *camera = camera_owner.get_or_null(p_camera);
3596 if (camera && scene_render->is_environment(camera->env)) {
3597 return camera->env;
3598 }
3599
3600 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
3601 if (!scenario) {
3602 return RID();
3603 }
3604 if (scene_render->is_environment(scenario->environment)) {
3605 return scenario->environment;
3606 }
3607
3608 if (scene_render->is_environment(scenario->fallback_environment)) {
3609 return scenario->fallback_environment;
3610 }
3611
3612 return RID();
3613 }
3614
3615 RID RendererSceneCull::_render_get_compositor(RID p_camera, RID p_scenario) {
3616 Camera *camera = camera_owner.get_or_null(p_camera);
3617 if (camera && scene_render->is_compositor(camera->compositor)) {
3618 return camera->compositor;
3619 }
3620
3621 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
3622 if (scenario && scene_render->is_compositor(scenario->compositor)) {
3623 return scenario->compositor;
3624 }
3625
3626 return RID();
3627 }
3628
3629 void RendererSceneCull::render_empty_scene(const Ref<RenderSceneBuffers> &p_render_buffers, RID p_scenario, RID p_shadow_atlas) {
3630 #ifndef _3D_DISABLED
3631 Scenario *scenario = scenario_owner.get_or_null(p_scenario);
3632
3633 RID environment;
3634 if (scenario->environment.is_valid()) {
3635 environment = scenario->environment;
3636 } else {
3637 environment = scenario->fallback_environment;
3638 }
3639 RID compositor = scenario->compositor;
3640 RENDER_TIMESTAMP("Render Empty 3D Scene");
3641
3642 RendererSceneRender::CameraData camera_data;
3643 camera_data.set_camera(Transform3D(), Projection(), true, false, false);
3644
3645 scene_render->render_scene(p_render_buffers, &camera_data, &camera_data, PagedArray<RenderGeometryInstance *>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), environment, RID(), compositor, p_shadow_atlas, RID(), scenario->reflection_atlas, RID(), 0, 0, nullptr, 0, nullptr, 0, nullptr);
3646 #endif
3647 }
3648
3649 bool RendererSceneCull::_render_reflection_probe_step(Instance *p_instance, int p_step) {
3650 InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
3651 Scenario *scenario = p_instance->scenario;
3652 ERR_FAIL_NULL_V(scenario, true);
3653
3654 RenderingServerDefault::redraw_request(); //update, so it updates in editor
3655
3656 if (p_step == 0) {
3657 if (!RSG::light_storage->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
3658 return true; // All full, no atlas entry to render to.
3659 }
3660 } else if (!RSG::light_storage->reflection_probe_has_atlas_index(reflection_probe->instance)) {
3661 // We don't have an atlas to render to, just round off.
3662 // This is likely due to the atlas being reset.
3663 // If so the probe will be marked as dirty and start over.
3664 return true;
3665 }
3666
3667 if (p_step == 0) {
3668 static const Vector3 view_normals[6] = {
3669 Vector3(+1, 0, 0),
3670 Vector3(-1, 0, 0),
3671 Vector3(0, +1, 0),
3672 Vector3(0, -1, 0),
3673 Vector3(0, 0, +1),
3674 Vector3(0, 0, -1)
3675 };
3676 static const Vector3 view_up[6] = {
3677 Vector3(0, -1, 0),
3678 Vector3(0, -1, 0),
3679 Vector3(0, 0, +1),
3680 Vector3(0, 0, -1),
3681 Vector3(0, -1, 0),
3682 Vector3(0, -1, 0)
3683 };
3684
3685 Vector3 probe_size = RSG::light_storage->reflection_probe_get_size(p_instance->base);
3686 Vector3 origin_offset = RSG::light_storage->reflection_probe_get_origin_offset(p_instance->base);
3687 float max_distance = RSG::light_storage->reflection_probe_get_origin_max_distance(p_instance->base);
3688 float atlas_size = RSG::light_storage->reflection_atlas_get_size(scenario->reflection_atlas);
3689 float mesh_lod_threshold = RSG::light_storage->reflection_probe_get_mesh_lod_threshold(p_instance->base) / atlas_size;
3690 bool use_shadows = RSG::light_storage->reflection_probe_renders_shadows(p_instance->base);
3691 RID shadow_atlas = use_shadows ? scenario->reflection_probe_shadow_atlas : RID();
3692 RID environment = scenario->environment.is_valid() ? scenario->environment : scenario->fallback_environment;
3693 Ref<RenderSceneBuffers> render_buffers = RSG::light_storage->reflection_probe_atlas_get_render_buffers(scenario->reflection_atlas);
3694 for (uint32_t face = 0; face < 6; face++) {
3695 // Compute distance from origin offset to the actual view distance limit.
3696 Vector3 edge = view_normals[face] * probe_size / 2;
3697 float distance = Math::abs(view_normals[face].dot(edge) - view_normals[face].dot(origin_offset));
3698 max_distance = MAX(max_distance, distance);
3699
3700 // Render cubemap side.
3701 Projection cm;
3702 cm.set_perspective(90, 1, 0.01, max_distance);
3703
3704 Transform3D local_view;
3705 local_view.set_look_at(origin_offset, origin_offset + view_normals[face], view_up[face]);
3706
3707 RendererSceneRender::CameraData camera_data;
3708 Transform3D xform = p_instance->transform * local_view;
3709 camera_data.set_camera(xform, cm, false, false, false);
3710
3711 RENDER_TIMESTAMP("Render ReflectionProbe, Face " + itos(face));
3712 _render_scene(&camera_data, render_buffers, environment, RID(), RID(), RSG::light_storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, RID(), shadow_atlas, reflection_probe->instance, face, mesh_lod_threshold, use_shadows);
3713 }
3714
3715 RSG::light_storage->reflection_probe_instance_end_render(reflection_probe->instance, scenario->reflection_atlas);
3716 } else {
3717 // Do roughness postprocess step until it believes it's done.
3718 RENDER_TIMESTAMP("Post-Process ReflectionProbe, Step " + itos(p_step));
3719 return RSG::light_storage->reflection_probe_instance_postprocess_step(reflection_probe->instance);
3720 }
3721
3722 return false;
3723 }
3724
3725 void RendererSceneCull::render_probes() {
3726 /* REFLECTION PROBES */
3727
3728 SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
3729 Vector<SelfList<InstanceReflectionProbeData> *> done_list;
3730
3731 bool busy = false;
3732
3733 if (ref_probe) {
3734 RENDER_TIMESTAMP("Render ReflectionProbes");
3735
3736 while (ref_probe) {
3737 SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
3738 RID base = ref_probe->self()->owner->base;
3739
3740 switch (RSG::light_storage->reflection_probe_get_update_mode(base)) {
3741 case RS::REFLECTION_PROBE_UPDATE_ONCE: {
3742 if (busy) { // Already rendering something.
3743 break;
3744 }
3745
3746 bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
3747 if (done) {
3748 done_list.push_back(ref_probe);
3749 } else {
3750 ref_probe->self()->render_step++;
3751 }
3752
3753 busy = true; // Do not render another one of this kind.
3754 } break;
3755 case RS::REFLECTION_PROBE_UPDATE_ALWAYS: {
3756 int step = 0;
3757 bool done = false;
3758 while (!done) {
3759 done = _render_reflection_probe_step(ref_probe->self()->owner, step);
3760 step++;
3761 }
3762
3763 done_list.push_back(ref_probe);
3764 } break;
3765 }
3766
3767 ref_probe = next;
3768 }
3769
3770 // Now remove from our list
3771 for (SelfList<InstanceReflectionProbeData> *rp : done_list) {
3772 reflection_probe_render_list.remove(rp);
3773 }
3774 }
3775
3776 /* VOXEL GIS */
3777
3778 SelfList<InstanceVoxelGIData> *voxel_gi = voxel_gi_update_list.first();
3779
3780 if (voxel_gi) {
3781 RENDER_TIMESTAMP("Render VoxelGI");
3782 }
3783
3784 while (voxel_gi) {
3785 SelfList<InstanceVoxelGIData> *next = voxel_gi->next();
3786
3787 InstanceVoxelGIData *probe = voxel_gi->self();
3788 //Instance *instance_probe = probe->owner;
3789
3790 //check if probe must be setup, but don't do if on the lighting thread
3791
3792 bool cache_dirty = false;
3793 int cache_count = 0;
3794 {
3795 int light_cache_size = probe->light_cache.size();
3796 const InstanceVoxelGIData::LightCache *caches = probe->light_cache.ptr();
3797 const RID *instance_caches = probe->light_instances.ptr();
3798
3799 int idx = 0; //must count visible lights
3800 for (Instance *E : probe->lights) {
3801 Instance *instance = E;
3802 InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
3803 if (!instance->visible) {
3804 continue;
3805 }
3806 if (cache_dirty) {
3807 //do nothing, since idx must count all visible lights anyway
3808 } else if (idx >= light_cache_size) {
3809 cache_dirty = true;
3810 } else {
3811 const InstanceVoxelGIData::LightCache *cache = &caches[idx];
3812
3813 if (
3814 instance_caches[idx] != instance_light->instance ||
3815 cache->has_shadow != RSG::light_storage->light_has_shadow(instance->base) ||
3816 cache->type != RSG::light_storage->light_get_type(instance->base) ||
3817 cache->transform != instance->transform ||
3818 cache->color != RSG::light_storage->light_get_color(instance->base) ||
3819 cache->energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
3820 cache->intensity != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY) ||
3821 cache->bake_energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
3822 cache->radius != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
3823 cache->attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
3824 cache->spot_angle != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
3825 cache->spot_attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
3826 cache_dirty = true;
3827 }
3828 }
3829
3830 idx++;
3831 }
3832
3833 for (const Instance *instance : probe->owner->scenario->directional_lights) {
3834 InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
3835 if (!instance->visible) {
3836 continue;
3837 }
3838 if (cache_dirty) {
3839 //do nothing, since idx must count all visible lights anyway
3840 } else if (idx >= light_cache_size) {
3841 cache_dirty = true;
3842 } else {
3843 const InstanceVoxelGIData::LightCache *cache = &caches[idx];
3844
3845 if (
3846 instance_caches[idx] != instance_light->instance ||
3847 cache->has_shadow != RSG::light_storage->light_has_shadow(instance->base) ||
3848 cache->type != RSG::light_storage->light_get_type(instance->base) ||
3849 cache->transform != instance->transform ||
3850 cache->color != RSG::light_storage->light_get_color(instance->base) ||
3851 cache->energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
3852 cache->intensity != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY) ||
3853 cache->bake_energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
3854 cache->radius != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
3855 cache->attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
3856 cache->spot_angle != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
3857 cache->spot_attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION) ||
3858 cache->sky_mode != RSG::light_storage->light_directional_get_sky_mode(instance->base)) {
3859 cache_dirty = true;
3860 }
3861 }
3862
3863 idx++;
3864 }
3865
3866 if (idx != light_cache_size) {
3867 cache_dirty = true;
3868 }
3869
3870 cache_count = idx;
3871 }
3872
3873 bool update_lights = scene_render->voxel_gi_needs_update(probe->probe_instance);
3874
3875 if (cache_dirty) {
3876 probe->light_cache.resize(cache_count);
3877 probe->light_instances.resize(cache_count);
3878
3879 if (cache_count) {
3880 InstanceVoxelGIData::LightCache *caches = probe->light_cache.ptrw();
3881 RID *instance_caches = probe->light_instances.ptrw();
3882
3883 int idx = 0; //must count visible lights
3884 for (Instance *E : probe->lights) {
3885 Instance *instance = E;
3886 InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
3887 if (!instance->visible) {
3888 continue;
3889 }
3890
3891 InstanceVoxelGIData::LightCache *cache = &caches[idx];
3892
3893 instance_caches[idx] = instance_light->instance;
3894 cache->has_shadow = RSG::light_storage->light_has_shadow(instance->base);
3895 cache->type = RSG::light_storage->light_get_type(instance->base);
3896 cache->transform = instance->transform;
3897 cache->color = RSG::light_storage->light_get_color(instance->base);
3898 cache->energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
3899 cache->intensity = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY);
3900 cache->bake_energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
3901 cache->radius = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
3902 cache->attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
3903 cache->spot_angle = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
3904 cache->spot_attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
3905
3906 idx++;
3907 }
3908 for (const Instance *instance : probe->owner->scenario->directional_lights) {
3909 InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
3910 if (!instance->visible) {
3911 continue;
3912 }
3913
3914 InstanceVoxelGIData::LightCache *cache = &caches[idx];
3915
3916 instance_caches[idx] = instance_light->instance;
3917 cache->has_shadow = RSG::light_storage->light_has_shadow(instance->base);
3918 cache->type = RSG::light_storage->light_get_type(instance->base);
3919 cache->transform = instance->transform;
3920 cache->color = RSG::light_storage->light_get_color(instance->base);
3921 cache->energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
3922 cache->intensity = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY);
3923 cache->bake_energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
3924 cache->radius = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
3925 cache->attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
3926 cache->spot_angle = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
3927 cache->spot_attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
3928 cache->sky_mode = RSG::light_storage->light_directional_get_sky_mode(instance->base);
3929
3930 idx++;
3931 }
3932 }
3933
3934 update_lights = true;
3935 }
3936
3937 scene_cull_result.geometry_instances.clear();
3938
3939 RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
3940
3941 for (Instance *E : probe->dynamic_geometries) {
3942 Instance *ins = E;
3943 if (!ins->visible) {
3944 continue;
3945 }
3946 InstanceGeometryData *geom = (InstanceGeometryData *)ins->base_data;
3947
3948 if (ins->scenario && ins->array_index >= 0 && (ins->scenario->instance_data[ins->array_index].flags & InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY)) {
3949 uint32_t idx = 0;
3950 for (const Instance *F : geom->voxel_gi_instances) {
3951 InstanceVoxelGIData *voxel_gi2 = static_cast<InstanceVoxelGIData *>(F->base_data);
3952
3953 instance_pair_buffer[idx++] = voxel_gi2->probe_instance;
3954 if (idx == MAX_INSTANCE_PAIRS) {
3955 break;
3956 }
3957 }
3958
3959 ERR_FAIL_NULL(geom->geometry_instance);
3960 geom->geometry_instance->pair_voxel_gi_instances(instance_pair_buffer, idx);
3961
3962 ins->scenario->instance_data[ins->array_index].flags &= ~InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
3963 }
3964
3965 ERR_FAIL_NULL(geom->geometry_instance);
3966 scene_cull_result.geometry_instances.push_back(geom->geometry_instance);
3967 }
3968
3969 scene_render->voxel_gi_update(probe->probe_instance, update_lights, probe->light_instances, scene_cull_result.geometry_instances);
3970
3971 voxel_gi_update_list.remove(voxel_gi);
3972
3973 voxel_gi = next;
3974 }
3975 }
3976
3977 void RendererSceneCull::render_particle_colliders() {
3978 while (heightfield_particle_colliders_update_list.begin()) {
3979 Instance *hfpc = *heightfield_particle_colliders_update_list.begin();
3980
3981 if (hfpc->scenario && hfpc->base_type == RS::INSTANCE_PARTICLES_COLLISION && RSG::particles_storage->particles_collision_is_heightfield(hfpc->base)) {
3982 //update heightfield
3983 instance_cull_result.clear();
3984 scene_cull_result.geometry_instances.clear();
3985
3986 struct CullAABB {
3987 PagedArray<Instance *> *result;
3988 uint32_t heightfield_mask;
3989 _FORCE_INLINE_ bool operator()(void *p_data) {
3990 Instance *p_instance = (Instance *)p_data;
3991 if (p_instance->layer_mask & heightfield_mask) {
3992 result->push_back(p_instance);
3993 }
3994 return false;
3995 }
3996 };
3997
3998 CullAABB cull_aabb;
3999 cull_aabb.result = &instance_cull_result;
4000 cull_aabb.heightfield_mask = RSG::particles_storage->particles_collision_get_height_field_mask(hfpc->base);
4001 hfpc->scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(hfpc->transformed_aabb, cull_aabb);
4002 hfpc->scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(hfpc->transformed_aabb, cull_aabb);
4003
4004 for (int i = 0; i < (int)instance_cull_result.size(); i++) {
4005 Instance *instance = instance_cull_result[i];
4006 if (!instance || !((1 << instance->base_type) & (RS::INSTANCE_GEOMETRY_MASK & (~(1 << RS::INSTANCE_PARTICLES))))) { //all but particles to avoid self collision
4007 continue;
4008 }
4009 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
4010 ERR_FAIL_NULL(geom->geometry_instance);
4011 scene_cull_result.geometry_instances.push_back(geom->geometry_instance);
4012 }
4013
4014 scene_render->render_particle_collider_heightfield(hfpc->base, hfpc->transform, scene_cull_result.geometry_instances);
4015 }
4016 heightfield_particle_colliders_update_list.remove(heightfield_particle_colliders_update_list.begin());
4017 }
4018 }
4019
4020 void RendererSceneCull::_update_dirty_instance(Instance *p_instance) const {
4021 if (p_instance->update_aabb) {
4022 _update_instance_aabb(p_instance);
4023 }
4024
4025 if (p_instance->update_dependencies) {
4026 p_instance->dependency_tracker.update_begin();
4027
4028 if (p_instance->base.is_valid()) {
4029 RSG::utilities->base_update_dependency(p_instance->base, &p_instance->dependency_tracker);
4030 }
4031
4032 if (p_instance->material_override.is_valid()) {
4033 RSG::material_storage->material_update_dependency(p_instance->material_override, &p_instance->dependency_tracker);
4034 }
4035
4036 if (p_instance->material_overlay.is_valid()) {
4037 RSG::material_storage->material_update_dependency(p_instance->material_overlay, &p_instance->dependency_tracker);
4038 }
4039
4040 if (p_instance->base_type == RS::INSTANCE_MESH) {
4041 //remove materials no longer used and un-own them
4042
4043 int new_mat_count = RSG::mesh_storage->mesh_get_surface_count(p_instance->base);
4044 p_instance->materials.resize(new_mat_count);
4045
4046 _instance_update_mesh_instance(p_instance);
4047 }
4048
4049 if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
4050 // update the process material dependency
4051
4052 RID particle_material = RSG::particles_storage->particles_get_process_material(p_instance->base);
4053 if (particle_material.is_valid()) {
4054 RSG::material_storage->material_update_dependency(particle_material, &p_instance->dependency_tracker);
4055 }
4056 }
4057
4058 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
4059 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
4060
4061 bool can_cast_shadows = true;
4062 bool is_animated = false;
4063
4064 p_instance->instance_uniforms.materials_start();
4065
4066 if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_OFF) {
4067 can_cast_shadows = false;
4068 }
4069
4070 if (p_instance->material_override.is_valid()) {
4071 if (!RSG::material_storage->material_casts_shadows(p_instance->material_override)) {
4072 can_cast_shadows = false;
4073 }
4074 is_animated = RSG::material_storage->material_is_animated(p_instance->material_override);
4075 p_instance->instance_uniforms.materials_append(p_instance->material_override);
4076 } else {
4077 if (p_instance->base_type == RS::INSTANCE_MESH) {
4078 RID mesh = p_instance->base;
4079
4080 if (mesh.is_valid()) {
4081 bool cast_shadows = false;
4082
4083 for (int i = 0; i < p_instance->materials.size(); i++) {
4084 RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::mesh_storage->mesh_surface_get_material(mesh, i);
4085
4086 if (!mat.is_valid()) {
4087 cast_shadows = true;
4088 } else {
4089 if (RSG::material_storage->material_casts_shadows(mat)) {
4090 cast_shadows = true;
4091 }
4092
4093 if (RSG::material_storage->material_is_animated(mat)) {
4094 is_animated = true;
4095 }
4096
4097 p_instance->instance_uniforms.materials_append(mat);
4098
4099 RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
4100 }
4101 }
4102
4103 if (!cast_shadows) {
4104 can_cast_shadows = false;
4105 }
4106 }
4107
4108 } else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) {
4109 RID mesh = RSG::mesh_storage->multimesh_get_mesh(p_instance->base);
4110 if (mesh.is_valid()) {
4111 bool cast_shadows = false;
4112
4113 int sc = RSG::mesh_storage->mesh_get_surface_count(mesh);
4114 for (int i = 0; i < sc; i++) {
4115 RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, i);
4116
4117 if (!mat.is_valid()) {
4118 cast_shadows = true;
4119
4120 } else {
4121 if (RSG::material_storage->material_casts_shadows(mat)) {
4122 cast_shadows = true;
4123 }
4124 if (RSG::material_storage->material_is_animated(mat)) {
4125 is_animated = true;
4126 }
4127
4128 p_instance->instance_uniforms.materials_append(mat);
4129
4130 RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
4131 }
4132 }
4133
4134 if (!cast_shadows) {
4135 can_cast_shadows = false;
4136 }
4137
4138 RSG::utilities->base_update_dependency(mesh, &p_instance->dependency_tracker);
4139 }
4140 } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
4141 bool cast_shadows = false;
4142
4143 int dp = RSG::particles_storage->particles_get_draw_passes(p_instance->base);
4144
4145 for (int i = 0; i < dp; i++) {
4146 RID mesh = RSG::particles_storage->particles_get_draw_pass_mesh(p_instance->base, i);
4147 if (!mesh.is_valid()) {
4148 continue;
4149 }
4150
4151 int sc = RSG::mesh_storage->mesh_get_surface_count(mesh);
4152 for (int j = 0; j < sc; j++) {
4153 RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, j);
4154
4155 if (!mat.is_valid()) {
4156 cast_shadows = true;
4157 } else {
4158 if (RSG::material_storage->material_casts_shadows(mat)) {
4159 cast_shadows = true;
4160 }
4161
4162 if (RSG::material_storage->material_is_animated(mat)) {
4163 is_animated = true;
4164 }
4165
4166 p_instance->instance_uniforms.materials_append(mat);
4167
4168 RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
4169 }
4170 }
4171 }
4172
4173 if (!cast_shadows) {
4174 can_cast_shadows = false;
4175 }
4176 }
4177 }
4178
4179 if (p_instance->material_overlay.is_valid()) {
4180 can_cast_shadows = can_cast_shadows && RSG::material_storage->material_casts_shadows(p_instance->material_overlay);
4181 is_animated = is_animated || RSG::material_storage->material_is_animated(p_instance->material_overlay);
4182 p_instance->instance_uniforms.materials_append(p_instance->material_overlay);
4183 }
4184
4185 if (can_cast_shadows != geom->can_cast_shadows) {
4186 //ability to cast shadows change, let lights now
4187 for (const Instance *E : geom->lights) {
4188 InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
4189 light->make_shadow_dirty();
4190 }
4191
4192 geom->can_cast_shadows = can_cast_shadows;
4193 }
4194
4195 geom->material_is_animated = is_animated;
4196
4197 if (p_instance->instance_uniforms.materials_finish(p_instance->self)) {
4198 geom->geometry_instance->set_instance_shader_uniforms_offset(p_instance->instance_uniforms.location());
4199 }
4200 }
4201
4202 if (p_instance->skeleton.is_valid()) {
4203 RSG::mesh_storage->skeleton_update_dependency(p_instance->skeleton, &p_instance->dependency_tracker);
4204 }
4205
4206 p_instance->dependency_tracker.update_end();
4207
4208 if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
4209 InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
4210 ERR_FAIL_NULL(geom->geometry_instance);
4211 geom->geometry_instance->set_surface_materials(p_instance->materials);
4212 }
4213 }
4214
4215 _instance_update_list.remove(&p_instance->update_item);
4216
4217 _update_instance(p_instance);
4218
4219 p_instance->teleported = false;
4220 p_instance->update_aabb = false;
4221 p_instance->update_dependencies = false;
4222 }
4223
4224 void RendererSceneCull::update_dirty_instances() const {
4225 while (_instance_update_list.first()) {
4226 _update_dirty_instance(_instance_update_list.first()->self());
4227 }
4228
4229 // Update dirty resources after dirty instances as instance updates may affect resources.
4230 RSG::utilities->update_dirty_resources();
4231 }
4232
4233 void RendererSceneCull::update() {
4234 //optimize bvhs
4235
4236 uint32_t rid_count = scenario_owner.get_rid_count();
4237 RID *rids = (RID *)alloca(sizeof(RID) * rid_count);
4238 scenario_owner.fill_owned_buffer(rids);
4239 for (uint32_t i = 0; i < rid_count; i++) {
4240 Scenario *s = scenario_owner.get_or_null(rids[i]);
4241 s->indexers[Scenario::INDEXER_GEOMETRY].optimize_incremental(indexer_update_iterations);
4242 s->indexers[Scenario::INDEXER_VOLUMES].optimize_incremental(indexer_update_iterations);
4243 }
4244 scene_render->update();
4245 update_dirty_instances();
4246 render_particle_colliders();
4247 }
4248
4249 bool RendererSceneCull::free(RID p_rid) {
4250 if (p_rid.is_null()) {
4251 return true;
4252 }
4253
4254 if (scene_render->free(p_rid)) {
4255 return true;
4256 }
4257
4258 if (camera_owner.owns(p_rid)) {
4259 camera_owner.free(p_rid);
4260
4261 } else if (scenario_owner.owns(p_rid)) {
4262 Scenario *scenario = scenario_owner.get_or_null(p_rid);
4263
4264 while (scenario->instances.first()) {
4265 instance_set_scenario(scenario->instances.first()->self()->self, RID());
4266 }
4267 scenario->instance_aabbs.reset();
4268 scenario->instance_data.reset();
4269 scenario->instance_visibility.reset();
4270
4271 RSG::light_storage->shadow_atlas_free(scenario->reflection_probe_shadow_atlas);
4272 RSG::light_storage->reflection_atlas_free(scenario->reflection_atlas);
4273 scenario_owner.free(p_rid);
4274 RendererSceneOcclusionCull::get_singleton()->remove_scenario(p_rid);
4275
4276 } else if (RendererSceneOcclusionCull::get_singleton() && RendererSceneOcclusionCull::get_singleton()->is_occluder(p_rid)) {
4277 RendererSceneOcclusionCull::get_singleton()->free_occluder(p_rid);
4278 } else if (instance_owner.owns(p_rid)) {
4279 // delete the instance
4280
4281 update_dirty_instances();
4282
4283 Instance *instance = instance_owner.get_or_null(p_rid);
4284
4285 instance_geometry_set_lightmap(p_rid, RID(), Rect2(), 0);
4286 instance_set_scenario(p_rid, RID());
4287 instance_set_base(p_rid, RID());
4288 instance_geometry_set_material_override(p_rid, RID());
4289 instance_geometry_set_material_overlay(p_rid, RID());
4290 instance_attach_skeleton(p_rid, RID());
4291
4292 instance->instance_uniforms.free(instance->self);
4293 update_dirty_instances(); //in case something changed this
4294
4295 instance_owner.free(p_rid);
4296 } else {
4297 return false;
4298 }
4299
4300 return true;
4301 }
4302
4303 TypedArray<Image> RendererSceneCull::bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size) {
4304 return scene_render->bake_render_uv2(p_base, p_material_overrides, p_image_size);
4305 }
4306
4307 void RendererSceneCull::update_visibility_notifiers() {
4308 SelfList<InstanceVisibilityNotifierData> *E = visible_notifier_list.first();
4309 while (E) {
4310 SelfList<InstanceVisibilityNotifierData> *N = E->next();
4311
4312 InstanceVisibilityNotifierData *visibility_notifier = E->self();
4313 if (visibility_notifier->just_visible) {
4314 visibility_notifier->just_visible = false;
4315
4316 RSG::utilities->visibility_notifier_call(visibility_notifier->base, true, RSG::threaded);
4317 } else {
4318 if (visibility_notifier->visible_in_frame != RSG::rasterizer->get_frame_number()) {
4319 visible_notifier_list.remove(E);
4320
4321 RSG::utilities->visibility_notifier_call(visibility_notifier->base, false, RSG::threaded);
4322 }
4323 }
4324
4325 E = N;
4326 }
4327 }
4328
4329 /*******************************/
4330 /* Passthrough to Scene Render */
4331 /*******************************/
4332
4333 /* ENVIRONMENT API */
4334
4335 RendererSceneCull *RendererSceneCull::singleton = nullptr;
4336
4337 void RendererSceneCull::set_scene_render(RendererSceneRender *p_scene_render) {
4338 scene_render = p_scene_render;
4339 geometry_instance_pair_mask = scene_render->geometry_instance_get_pair_mask();
4340 }
4341
4342 /* INTERPOLATION API */
4343
4344 void RendererSceneCull::update_interpolation_tick(bool p_process) {
4345 // MultiMesh: Update interpolation in storage.
4346 RSG::mesh_storage->update_interpolation_tick(p_process);
4347 }
4348
4349 void RendererSceneCull::update_interpolation_frame(bool p_process) {
4350 // MultiMesh: Update interpolation in storage.
4351 RSG::mesh_storage->update_interpolation_frame(p_process);
4352 }
4353
4354 void RendererSceneCull::set_physics_interpolation_enabled(bool p_enabled) {
4355 _interpolation_data.interpolation_enabled = p_enabled;
4356 }
4357
4358 RendererSceneCull::RendererSceneCull() {
4359 render_pass = 1;
4360 singleton = this;
4361
4362 instance_cull_result.set_page_pool(&instance_cull_page_pool);
4363 instance_shadow_cull_result.set_page_pool(&instance_cull_page_pool);
4364
4365 for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
4366 render_shadow_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
4367 }
4368 for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
4369 render_sdfgi_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
4370 }
4371
4372 scene_cull_result.init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
4373 scene_cull_result_threads.resize(WorkerThreadPool::get_singleton()->get_thread_count());
4374 for (InstanceCullResult &thread : scene_cull_result_threads) {
4375 thread.init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
4376 }
4377
4378 indexer_update_iterations = GLOBAL_GET("rendering/limits/spatial_indexer/update_iterations_per_frame");
4379 thread_cull_threshold = GLOBAL_GET("rendering/limits/spatial_indexer/threaded_cull_minimum_instances");
4380 thread_cull_threshold = MAX(thread_cull_threshold, (uint32_t)WorkerThreadPool::get_singleton()->get_thread_count()); //make sure there is at least one thread per CPU
4381 RendererSceneOcclusionCull::HZBuffer::occlusion_jitter_enabled = GLOBAL_GET("rendering/occlusion_culling/jitter_projection");
4382
4383 dummy_occlusion_culling = memnew(RendererSceneOcclusionCull);
4384
4385 light_culler = memnew(RenderingLightCuller);
4386
4387 bool tighter_caster_culling = GLOBAL_DEF("rendering/lights_and_shadows/tighter_shadow_caster_culling", true);
4388 light_culler->set_caster_culling_active(tighter_caster_culling);
4389 light_culler->set_light_culling_active(tighter_caster_culling);
4390 }
4391
4392 RendererSceneCull::~RendererSceneCull() {
4393 instance_cull_result.reset();
4394 instance_shadow_cull_result.reset();
4395
4396 for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
4397 render_shadow_data[i].instances.reset();
4398 }
4399 for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
4400 render_sdfgi_data[i].instances.reset();
4401 }
4402
4403 scene_cull_result.reset();
4404 for (InstanceCullResult &thread : scene_cull_result_threads) {
4405 thread.reset();
4406 }
4407 scene_cull_result_threads.clear();
4408
4409 if (dummy_occlusion_culling) {
4410 memdelete(dummy_occlusion_culling);
4411 }
4412
4413 if (light_culler) {
4414 memdelete(light_culler);
4415 light_culler = nullptr;
4416 }
4417 }