Shadow volume culling and tighter shadow caster culling

Existing shadow caster culling using the BVH takes no account of the camera. This PR adds the highly encapsulated class VisualServerLightCuller which can cut down the casters in the shadow volume to only those which can cast shadows on the camera frustum.

This is used to:
* More accurately defer dirty updates to shadows when the shadow volume does not intersect the camera frustum.
* Tighter cull shadow casters to the view frustum.

Lights dirty state is now automatically managed:
* Continuous (tighter caster culling)
* Static (all casters are rendered)
This commit is contained in:
lawnjelly 2019-11-02 20:00:24 +00:00
parent e236747b31
commit 8ca631a466
6 changed files with 1416 additions and 18 deletions

View file

@ -1800,6 +1800,11 @@
<member name="rendering/quality/shadow_atlas/size.mobile" type="int" setter="" getter="" default="2048"> <member name="rendering/quality/shadow_atlas/size.mobile" type="int" setter="" getter="" default="2048">
Lower-end override for [member rendering/quality/shadow_atlas/size] on mobile devices, due to performance concerns or driver support. Lower-end override for [member rendering/quality/shadow_atlas/size] on mobile devices, due to performance concerns or driver support.
</member> </member>
<member name="rendering/quality/shadows/caster_culling" type="bool" setter="" getter="" default="true">
If [code]true[/code], items that cannot cast shadows into the view frustum will not be rendered into shadow maps.
This can increase performance.
[b]Note:[/b] This setting only takes effect when [member rendering/quality/shadows/light_culling] is also [code]true[/code].
</member>
<member name="rendering/quality/shadows/filter_mode" type="int" setter="" getter="" default="1"> <member name="rendering/quality/shadows/filter_mode" type="int" setter="" getter="" default="1">
Shadow filter mode. Higher-quality settings result in smoother shadows that flicker less when moving. "Disabled" is the fastest option, but also has the lowest quality. "PCF5" is smoother but is also slower. "PCF13" is the smoothest option, but is also the slowest. Shadow filter mode. Higher-quality settings result in smoother shadows that flicker less when moving. "Disabled" is the fastest option, but also has the lowest quality. "PCF5" is smoother but is also slower. "PCF13" is the smoothest option, but is also the slowest.
[b]Note:[/b] When using the GLES2 backend, the "PCF13" option actually uses 16 samples to emulate linear filtering in the shader. This results in a shadow appearance similar to the one produced by the GLES3 backend. [b]Note:[/b] When using the GLES2 backend, the "PCF13" option actually uses 16 samples to emulate linear filtering in the shader. This results in a shadow appearance similar to the one produced by the GLES3 backend.
@ -1807,6 +1812,10 @@
<member name="rendering/quality/shadows/filter_mode.mobile" type="int" setter="" getter="" default="0"> <member name="rendering/quality/shadows/filter_mode.mobile" type="int" setter="" getter="" default="0">
Lower-end override for [member rendering/quality/shadows/filter_mode] on mobile devices, due to performance concerns or driver support. Lower-end override for [member rendering/quality/shadows/filter_mode] on mobile devices, due to performance concerns or driver support.
</member> </member>
<member name="rendering/quality/shadows/light_culling" type="bool" setter="" getter="" default="true">
If [code]true[/code], prevents shadows from rendering for lights that do not intersect the view frustum.
This can increase performance.
</member>
<member name="rendering/quality/skinning/force_software_skinning" type="bool" setter="" getter="" default="false"> <member name="rendering/quality/skinning/force_software_skinning" type="bool" setter="" getter="" default="false">
Forces [MeshInstance] to always perform skinning on the CPU (applies to both GLES2 and GLES3). Forces [MeshInstance] to always perform skinning on the CPU (applies to both GLES2 and GLES3).
See also [member rendering/quality/skinning/software_skinning_fallback]. See also [member rendering/quality/skinning/software_skinning_fallback].

View file

@ -721,9 +721,7 @@ bool SceneTree::idle(float p_time) {
#endif #endif
if (_physics_interpolation_enabled) { VisualServer::get_singleton()->pre_draw(true);
VisualServer::get_singleton()->pre_draw(true);
}
return _quit; return _quit;
} }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,218 @@
/**************************************************************************/
/* visual_server_light_culler.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#ifndef VISUAL_SERVER_LIGHT_CULLER_H
#define VISUAL_SERVER_LIGHT_CULLER_H
#include "core/math/plane.h"
#include "core/math/vector3.h"
#include "visual_server_scene.h"
struct CameraMatrix;
class Transform;
// For testing performance improvements from the LightCuller:
// Uncomment LIGHT_CULLER_DEBUG_FLASH and it will turn the culler
// on and off every LIGHT_CULLER_DEBUG_FLASH_FREQUENCY camera prepares.
// Uncomment LIGHT_CULLER_DEBUG_LOGGING to get periodic print of the number of casters culled before / after.
// #define LIGHT_CULLER_DEBUG_LOGGING
// #define LIGHT_CULLER_DEBUG_FLASH
#define LIGHT_CULLER_DEBUG_FLASH_FREQUENCY 1024
////////////////////////////////////////////////////////////////////////////////////////////////
// The code to generate the lookup table is included but commented out.
// This may be useful for debugging / regenerating the LUT in the future,
// especially if the order of planes changes.
// When this define is set, the generated lookup table will be printed to debug output.
// The generated lookup table can be copy pasted
// straight to LUT_entry_sizes and LUT_entries.
// See the referenced article for explanation.
// #define VISUAL_SERVER_LIGHT_CULLER_CALCULATE_LUT
////////////////////////////////////////////////////////////////////////////////////////////////
// This define will be set automatically depending on earlier defines, you can leave this as is.
#if defined(LIGHT_CULLER_DEBUG_LOGGING) || defined(VISUAL_SERVER_LIGHT_CULLER_CALCULATE_LUT)
#define VISUAL_SERVER_LIGHT_CULLER_DEBUG_STRINGS
#endif
// Culls shadow casters that can't cast shadows into the camera frustum.
class VisualServerLightCuller {
public:
VisualServerLightCuller();
private:
class LightSource {
public:
enum SourceType {
ST_UNKNOWN,
ST_DIRECTIONAL,
ST_SPOTLIGHT,
ST_OMNI,
};
LightSource() {
type = ST_UNKNOWN;
angle = 0.0f;
range = FLT_MAX;
}
// All in world space, culling done in world space.
Vector3 pos;
Vector3 dir;
SourceType type;
float angle; // For spotlight.
float range;
};
// Same order as godot.
enum PlaneOrder {
PLANE_NEAR,
PLANE_FAR,
PLANE_LEFT,
PLANE_TOP,
PLANE_RIGHT,
PLANE_BOTTOM,
PLANE_TOTAL,
};
// Same order as godot.
enum PointOrder {
PT_FAR_LEFT_TOP,
PT_FAR_LEFT_BOTTOM,
PT_FAR_RIGHT_TOP,
PT_FAR_RIGHT_BOTTOM,
PT_NEAR_LEFT_TOP,
PT_NEAR_LEFT_BOTTOM,
PT_NEAR_RIGHT_TOP,
PT_NEAR_RIGHT_BOTTOM,
};
// 6 bits, 6 planes.
enum {
NUM_CAM_PLANES = 6,
NUM_CAM_POINTS = 8,
MAX_CULL_PLANES = 17,
LUT_SIZE = 64,
};
public:
// Before each pass with a different camera, you must call this so the culler can pre-create
// the camera frustum planes and corner points in world space which are used for the culling.
bool prepare_camera(const Transform &p_cam_transform, const CameraMatrix &p_cam_matrix);
// Returns false if the entire light is culled (i.e. there is no intersection between the light and the view frustum).
bool prepare_light(const VisualServerScene::Instance &p_instance);
// Cull according to the planes that were setup in the previous call to prepare_light.
int cull(int p_count, VisualServerScene::Instance **p_result_array);
// Can turn on and off from the engine if desired.
void set_caster_culling_active(bool p_active) { data.caster_culling_active = p_active; }
void set_light_culling_active(bool p_active) { data.light_culling_active = p_active; }
private:
// Internal version uses LightSource.
bool _add_light_camera_planes(const LightSource &p_light_source);
// Directional light gives parallel culling planes (as opposed to point lights).
bool add_light_camera_planes_directional(const LightSource &p_light_source);
// Is the light culler active? maybe not in the editor...
bool is_caster_culling_active() const { return data.caster_culling_active; }
bool is_light_culling_active() const { return data.light_culling_active; }
// Do we want to log some debug output?
bool is_logging() const { return data.debug_count == 0; }
// Culling planes.
void add_cull_plane(const Plane &p);
struct Data {
// Camera frustum planes (world space) - order ePlane.
Vector<Plane> frustum_planes;
// Camera frustum corners (world space) - order ePoint.
Vector3 frustum_points[NUM_CAM_POINTS];
// We are storing cull planes in a ye olde style array to prevent needless allocations.
Plane cull_planes[MAX_CULL_PLANES];
int num_cull_planes = 0;
// The whole light can be out of range of the view frustum, in which case all casters should be culled.
bool out_of_range = false;
#ifdef VISUAL_SERVER_LIGHT_CULLER_DEBUG_STRINGS
static String plane_bitfield_to_string(unsigned int BF);
// Names of the plane and point enums, useful for debugging.
static const char *string_planes[];
static const char *string_points[];
#endif
// Precalculated look up table.
static uint8_t LUT_entry_sizes[LUT_SIZE];
static uint8_t LUT_entries[LUT_SIZE][8];
bool caster_culling_active = true;
bool light_culling_active = true;
// Light culling is a basic on / off switch.
// Caster culling only works if light culling is also on.
bool is_active() const { return light_culling_active; }
// Ideally a frame counter, but for ease of implementation
// this is just incremented on each prepare_camera.
// used to turn on and off debugging features.
int debug_count = -1;
} data;
// This functionality is not required in general use (and is compiled out),
// as the lookup table can normally be hard coded
// (provided order of planes etc does not change).
// It is provided for debugging / future maintenance.
#ifdef VISUAL_SERVER_LIGHT_CULLER_CALCULATE_LUT
void get_neighbouring_planes(PlaneOrder p_plane, PlaneOrder r_neigh_planes[4]) const;
void get_corners_of_planes(PlaneOrder p_plane_a, PlaneOrder p_plane_b, PointOrder r_points[2]) const;
void create_LUT();
void compact_LUT_entry(uint32_t p_entry_id);
void debug_print_LUT();
void debug_print_LUT_as_table();
void add_LUT(int p_plane_0, int p_plane_1, PointOrder p_pts[2]);
void add_LUT_entry(uint32_t p_entry_id, PointOrder p_pts[2]);
String debug_string_LUT_entry(const LocalVector<uint8_t> &p_entry, bool p_pair = false);
String string_LUT_entry(const LocalVector<uint8_t> &p_entry);
// Contains a list of points for each combination of plane facing directions.
LocalVector<uint8_t> _calculated_LUT[LUT_SIZE];
#endif
};
#endif // VISUAL_SERVER_LIGHT_CULLER_H

View file

@ -33,6 +33,7 @@
#include "core/math/transform_interpolator.h" #include "core/math/transform_interpolator.h"
#include "core/os/os.h" #include "core/os/os.h"
#include "visual_server_globals.h" #include "visual_server_globals.h"
#include "visual_server_light_culler.h"
#include "visual_server_raster.h" #include "visual_server_raster.h"
#include <new> #include <new>
@ -337,7 +338,7 @@ void *VisualServerScene::_instance_pair(void *p_self, SpatialPartitionID, Instan
List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo); List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
if (geom->can_cast_shadows) { if (geom->can_cast_shadows) {
light->shadow_dirty = true; light->make_shadow_dirty();
} }
geom->lighting_dirty = true; geom->lighting_dirty = true;
@ -409,7 +410,7 @@ void VisualServerScene::_instance_unpair(void *p_self, SpatialPartitionID, Insta
light->geometries.erase(E); light->geometries.erase(E);
if (geom->can_cast_shadows) { if (geom->can_cast_shadows) {
light->shadow_dirty = true; light->make_shadow_dirty();
} }
geom->lighting_dirty = true; geom->lighting_dirty = true;
@ -490,6 +491,12 @@ void VisualServerScene::pre_draw(bool p_will_draw) {
if (_interpolation_data.interpolation_enabled) { if (_interpolation_data.interpolation_enabled) {
update_interpolation_frame(p_will_draw); update_interpolation_frame(p_will_draw);
} }
// Opportunity to cheaply get any project settings that have changed.
if (ProjectSettings::get_singleton()->has_changes()) {
light_culler->set_caster_culling_active(GLOBAL_GET("rendering/quality/shadows/caster_culling"));
light_culler->set_light_culling_active(GLOBAL_GET("rendering/quality/shadows/light_culling"));
}
} }
void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) { void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) {
@ -802,7 +809,7 @@ void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask)
if (geom->can_cast_shadows) { if (geom->can_cast_shadows) {
for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) { for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
light->shadow_dirty = true; light->make_shadow_dirty();
} }
} }
} }
@ -1217,7 +1224,7 @@ void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) {
if (geom->can_cast_shadows) { if (geom->can_cast_shadows) {
for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) { for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
light->shadow_dirty = true; light->make_shadow_dirty();
} }
} }
} }
@ -2043,7 +2050,7 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data); InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
VSG::scene_render->light_instance_set_transform(light->instance, *instance_xform); VSG::scene_render->light_instance_set_transform(light->instance, *instance_xform);
light->shadow_dirty = true; light->make_shadow_dirty();
} }
if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) { if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
@ -2075,7 +2082,7 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
if (geom->can_cast_shadows) { if (geom->can_cast_shadows) {
for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) { for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
light->shadow_dirty = true; light->make_shadow_dirty();
} }
} }
@ -2461,6 +2468,15 @@ bool VisualServerScene::_light_instance_update_shadow(Instance *p_instance, cons
switch (VSG::storage->light_get_type(p_instance->base)) { switch (VSG::storage->light_get_type(p_instance->base)) {
case VS::LIGHT_DIRECTIONAL: { case VS::LIGHT_DIRECTIONAL: {
// Directional light always needs preparing as it takes a different path to other lights.
light_culler->prepare_light(*p_instance);
// Directional lights can always do a tighter cull.
// This should occur because shadow_dirty_count is never decremented for directional lights.
#ifdef DEV_ENABLED
DEV_CHECK_ONCE(!light->is_shadow_update_full());
#endif
float max_distance = p_cam_projection.get_z_far(); float max_distance = p_cam_projection.get_z_far();
float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE); float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
@ -2719,6 +2735,10 @@ bool VisualServerScene::_light_instance_update_shadow(Instance *p_instance, cons
VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i, bias_scale); VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i, bias_scale);
} }
// Do a secondary cull to remove casters that don't intersect with the camera frustum.
// Note this could possibly be done in a more efficient place if we can share the cull results for each split.
cull_count = light_culler->cull(cull_count, instance_shadow_cull_result);
VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count); VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
} }
@ -2743,6 +2763,12 @@ bool VisualServerScene::_light_instance_update_shadow(Instance *p_instance, cons
planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0)); planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
int cull_count = p_scenario->sps->cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK); int cull_count = p_scenario->sps->cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
// Do a secondary cull to remove casters that don't intersect with the camera frustum.
if (!light->is_shadow_update_full()) {
cull_count = light_culler->cull(cull_count, instance_shadow_cull_result);
}
Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z); Plane near_plane(light_transform.origin, light_transform.basis.get_axis(2) * z);
for (int j = 0; j < cull_count; j++) { for (int j = 0; j < cull_count; j++) {
@ -2796,6 +2822,11 @@ bool VisualServerScene::_light_instance_update_shadow(Instance *p_instance, cons
int cull_count = _cull_convex_from_point(p_scenario, light_transform, cm, planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, light->previous_room_id_hint, VS::INSTANCE_GEOMETRY_MASK); int cull_count = _cull_convex_from_point(p_scenario, light_transform, cm, planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, light->previous_room_id_hint, VS::INSTANCE_GEOMETRY_MASK);
// Do a secondary cull to remove casters that don't intersect with the camera frustum.
if (!light->is_shadow_update_full()) {
cull_count = light_culler->cull(cull_count, instance_shadow_cull_result);
}
Plane near_plane(xform.origin, -xform.basis.get_axis(2)); Plane near_plane(xform.origin, -xform.basis.get_axis(2));
for (int j = 0; j < cull_count; j++) { for (int j = 0; j < cull_count; j++) {
Instance *instance = instance_shadow_cull_result[j]; Instance *instance = instance_shadow_cull_result[j];
@ -2831,6 +2862,11 @@ bool VisualServerScene::_light_instance_update_shadow(Instance *p_instance, cons
Vector<Plane> planes = cm.get_projection_planes(light_transform); Vector<Plane> planes = cm.get_projection_planes(light_transform);
int cull_count = _cull_convex_from_point(p_scenario, light_transform, cm, planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, light->previous_room_id_hint, VS::INSTANCE_GEOMETRY_MASK); int cull_count = _cull_convex_from_point(p_scenario, light_transform, cm, planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, light->previous_room_id_hint, VS::INSTANCE_GEOMETRY_MASK);
// Do a secondary cull to remove casters that don't intersect with the camera frustum.
if (!light->is_shadow_update_full()) {
cull_count = light_culler->cull(cull_count, instance_shadow_cull_result);
}
Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2)); Plane near_plane(light_transform.origin, -light_transform.basis.get_axis(2));
for (int j = 0; j < cull_count; j++) { for (int j = 0; j < cull_count; j++) {
Instance *instance = instance_shadow_cull_result[j]; Instance *instance = instance_shadow_cull_result[j];
@ -2991,6 +3027,9 @@ void VisualServerScene::render_camera(Ref<ARVRInterface> &p_interface, ARVRInter
}; };
void VisualServerScene::_prepare_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int32_t &r_previous_room_id_hint) { void VisualServerScene::_prepare_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int32_t &r_previous_room_id_hint) {
// Prepare the light - camera volume culling system.
light_culler->prepare_camera(p_cam_transform, p_cam_projection);
// Note, in stereo rendering: // Note, in stereo rendering:
// - p_cam_transform will be a transform in the middle of our two eyes // - p_cam_transform will be a transform in the middle of our two eyes
// - p_cam_projection is a wider frustrum that encompasses both eyes // - p_cam_projection is a wider frustrum that encompasses both eyes
@ -3283,16 +3322,41 @@ void VisualServerScene::_prepare_scene(const Transform p_cam_transform, const Ca
} }
} }
if (light->shadow_dirty) { // We can detect whether multiple cameras are hitting this light, whether or not the shadow is dirty,
light->last_version++; // so that we can turn off tighter caster culling.
light->shadow_dirty = false; light->detect_light_intersects_multiple_cameras(Engine::get_singleton()->get_frames_drawn());
if (light->is_shadow_dirty()) {
// Dirty shadows have no need to be drawn if
// the light volume doesn't intersect the camera frustum.
// Returns false if the entire light can be culled.
bool allow_redraw = light_culler->prepare_light(*ins);
// Directional lights aren't handled here, _light_instance_update_shadow is called from elsewhere.
// Checking for this in case this changes, as this is assumed.
DEV_CHECK_ONCE(VSG::storage->light_get_type(ins->base) != VS::LIGHT_DIRECTIONAL);
// Tighter caster culling to the camera frustum should work correctly with multiple viewports + cameras.
// The first camera will cull tightly, but if the light is present on more than 1 camera, the second will
// do a full render, and mark the light as non-dirty.
// There is however a cost to tighter shadow culling in this situation (2 shadow updates in 1 frame),
// so we should detect this and switch off tighter caster culling automatically.
// This is done in the logic for `decrement_shadow_dirty()`.
if (allow_redraw) {
light->last_version++;
light->decrement_shadow_dirty();
}
} }
bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version); bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
if (redraw) { if (redraw) {
//must redraw! //must redraw!
light->shadow_dirty = _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario, p_visible_layers); if (_light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario, p_visible_layers)) {
// If the light requests another update (animated material?)...
light->make_shadow_dirty();
}
} }
} }
} }
@ -4517,7 +4581,7 @@ void VisualServerScene::_update_dirty_instance(Instance *p_instance) {
//ability to cast shadows change, let lights now //ability to cast shadows change, let lights now
for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) { for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data); InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
light->shadow_dirty = true; light->make_shadow_dirty();
} }
geom->can_cast_shadows = can_cast_shadows; geom->can_cast_shadows = can_cast_shadows;
@ -4629,12 +4693,17 @@ VisualServerScene::VisualServerScene() {
probe_bake_thread.start(_gi_probe_bake_threads, this); probe_bake_thread.start(_gi_probe_bake_threads, this);
probe_bake_thread_exit = false; probe_bake_thread_exit = false;
light_culler = memnew(VisualServerLightCuller);
render_pass = 1; render_pass = 1;
singleton = this; singleton = this;
_use_bvh = GLOBAL_DEF("rendering/quality/spatial_partitioning/use_bvh", true); _use_bvh = GLOBAL_DEF("rendering/quality/spatial_partitioning/use_bvh", true);
GLOBAL_DEF("rendering/quality/spatial_partitioning/bvh_collision_margin", 0.1); GLOBAL_DEF("rendering/quality/spatial_partitioning/bvh_collision_margin", 0.1);
ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/spatial_partitioning/bvh_collision_margin", PropertyInfo(Variant::REAL, "rendering/quality/spatial_partitioning/bvh_collision_margin", PROPERTY_HINT_RANGE, "0.0,2.0,0.01")); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/spatial_partitioning/bvh_collision_margin", PropertyInfo(Variant::REAL, "rendering/quality/spatial_partitioning/bvh_collision_margin", PROPERTY_HINT_RANGE, "0.0,2.0,0.01"));
light_culler->set_caster_culling_active(GLOBAL_DEF("rendering/quality/shadows/caster_culling", true));
light_culler->set_light_culling_active(GLOBAL_DEF("rendering/quality/shadows/light_culling", true));
_visual_server_callbacks = nullptr; _visual_server_callbacks = nullptr;
} }
@ -4642,4 +4711,9 @@ VisualServerScene::~VisualServerScene() {
probe_bake_thread_exit = true; probe_bake_thread_exit = true;
probe_bake_sem.post(); probe_bake_sem.post();
probe_bake_thread.wait_to_finish(); probe_bake_thread.wait_to_finish();
if (light_culler) {
memdelete(light_culler);
light_culler = nullptr;
}
} }

View file

@ -43,6 +43,8 @@
#include "portals/portal_renderer.h" #include "portals/portal_renderer.h"
#include "servers/arvr/arvr_interface.h" #include "servers/arvr/arvr_interface.h"
class VisualServerLightCuller;
class VisualServerScene { class VisualServerScene {
public: public:
enum { enum {
@ -484,16 +486,60 @@ public:
RID instance; RID instance;
uint64_t last_version; uint64_t last_version;
List<Instance *>::Element *D; // directional light in scenario List<Instance *>::Element *D; // directional light in scenario
bool shadow_dirty;
List<PairInfo> geometries; List<PairInfo> geometries;
Instance *baked_light; Instance *baked_light;
int32_t previous_room_id_hint; int32_t previous_room_id_hint;
private:
// Instead of a single dirty flag, we maintain a count
// so that we can detect lights that are being made dirty
// each frame, and switch on tighter caster culling.
int32_t shadow_dirty_count;
uint32_t light_update_frame_id;
bool light_intersects_multiple_cameras;
uint32_t light_intersects_multiple_cameras_timeout_frame_id;
public:
bool is_shadow_dirty() const { return shadow_dirty_count != 0; }
void make_shadow_dirty() { shadow_dirty_count = light_intersects_multiple_cameras ? 1 : 2; }
void detect_light_intersects_multiple_cameras(uint32_t p_frame_id) {
// We need to detect the case where shadow updates are occurring
// more than once per frame. In this case, we need to turn off
// tighter caster culling, so situation reverts to one full shadow update
// per frame (light_intersects_multiple_cameras is set).
if (p_frame_id == light_update_frame_id) {
light_intersects_multiple_cameras = true;
light_intersects_multiple_cameras_timeout_frame_id = p_frame_id + 60;
} else {
// When shadow_volume_intersects_multiple_cameras is set, we
// want to detect the situation this is no longer the case, via a timeout.
// The system can go back to tighter caster culling in this situation.
// Having a long-ish timeout prevents rapid cycling.
if (light_intersects_multiple_cameras && (p_frame_id >= light_intersects_multiple_cameras_timeout_frame_id)) {
light_intersects_multiple_cameras = false;
light_intersects_multiple_cameras_timeout_frame_id = UINT32_MAX;
}
}
light_update_frame_id = p_frame_id;
}
void decrement_shadow_dirty() {
shadow_dirty_count--;
DEV_ASSERT(shadow_dirty_count >= 0);
}
// Shadow updates can either full (everything in the shadow volume)
// or closely culled to the camera frustum.
bool is_shadow_update_full() const { return shadow_dirty_count == 0; }
InstanceLightData() { InstanceLightData() {
shadow_dirty = true; shadow_dirty_count = 1;
light_update_frame_id = UINT32_MAX;
light_intersects_multiple_cameras_timeout_frame_id = UINT32_MAX;
light_intersects_multiple_cameras = false;
D = nullptr; D = nullptr;
last_version = 0; last_version = 0;
baked_light = nullptr; baked_light = nullptr;
@ -623,6 +669,7 @@ public:
RID light_instance_cull_result[MAX_LIGHTS_CULLED]; RID light_instance_cull_result[MAX_LIGHTS_CULLED];
int light_cull_count; int light_cull_count;
int directional_light_count; int directional_light_count;
VisualServerLightCuller *light_culler;
RID reflection_probe_instance_cull_result[MAX_REFLECTION_PROBES_CULLED]; RID reflection_probe_instance_cull_result[MAX_REFLECTION_PROBES_CULLED];
int reflection_probe_cull_count; int reflection_probe_cull_count;