The directional and spot shadow array is reallocated whenever the visible shadowed spot lights change for two frames

Open
#26,598 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
55/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
rust

Research direction

Start with prepare_lights in crates/bevy_pbr/src/render/light.rs and trace how it requests the shadow texture from TextureCache; then read TextureCache::update to understand when unused textures are retired. Compare the two-frame and one-frame reproductions in the issue. Done when the shadow array is retained across visibility changes and the reproduction no longer shows repeated texture reallocation.

Written by the indexing model from the issue text.

Description

Bevy version and features

0.20.1, with the features in the Cargo.toml below. prepare_lights and TextureCache are unchanged on main (42265b2).

What you did

Ran the headless reproduction below in release: a 4096 px DirectionalLightShadowMap, one directional light with shadows (4 cascades), four shadow-casting spot lights and one camera. The camera faces the spot lights, turns away for two frames and turns back, three times; turning away for one frame is the control.

What went wrong

prepare_lights (crates/bevy_pbr/src/render/light.rs) takes directional_light_depth_texture from the TextureCache with depth_or_array_layers set to the cascades plus the visible spot lights' shadow maps, and TextureCache::update drops a texture once it has gone unused for three updates. While the spot lights are out of view, a 4-layer array is used in place of the 8-layer one; after two frames the 8-layer array is dropped, and when the spot lights return a new one is created: 512 MiB at 4096 by 4096 by 8 Depth32Float, in a frame about seven times as long as the steady frame:

=== Bevy 0.20.1: `directional_light_depth_texture` Retirement & Reallocation ===
initial_shadow_array: 4096x4096x8 Depth32Float (512.0 MiB logical)
steady_state_8_layer_frame_median_ms: 1.76 ms
away_1_frame_control (layers 8 -> 4 -> 8): same_texture_id = true, revisit_frame_ms = 1.98 ms
away_2_frames_defect (layers 8 -> 4 -> 8 across 3 cycles): new_512_mib_texture_every_cycle = true
  cycle 1: 4->8 layer reallocation frame_ms = 12.10 ms (6.89x steady-state)
  cycle 2: 4->8 layer reallocation frame_ms = 12.12 ms (6.90x steady-state)
  cycle 3: 4->8 layer reallocation frame_ms = 12.56 ms (7.16x steady-state)

In a game, every change in the number of visible shadowed spot lights that lasts two frames swaps the array this way.

Additional information

Keeping the array at the largest layer count used while the map size and the device stay the same, and resetting it when either changes, avoids the churn; the layers a frame does not use stay unused.

Reproduction: Cargo.toml and src/main.rs
[package]
name = "bevy-repros"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
bevy = { version = "0.20.1", default-features = false, features = [
    "std",
    "async_executor",
    "multi_threaded",
    "reflect_auto_register",
    "bevy_asset",
    "bevy_camera",
    "bevy_color",
    "bevy_core_pipeline",
    "bevy_image",
    "bevy_light",
    "bevy_log",
    "bevy_material",
    "bevy_mesh",
    "bevy_mikktspace",
    "bevy_pbr",
    "bevy_post_process",
    "bevy_render",
    "bevy_shader",
    "bevy_window",
    "bevy_winit",
    "bluenoise_texture",
    "ktx2",
    "tonemapping_luts",
    "zstd_rust",
] }
//! Minimal headless reproduction for Bevy 0.20.1 (`bevy_pbr`):
//! `prepare_lights` (`render/light.rs:1532-1552`) keys `directional_light_depth_texture` in
//! `TextureCache` by exact `depth_or_array_layers = cascades + visible_spot_shadows`, and
//! `TextureCache::update` (`frames_since_last_use < 3`) retires an unused descriptor after
//! just 2 consecutive frames out of view, reallocating a 512 MiB (`4096x4096x8`
//! `Depth32Float`) texture array when the spot lights re-enter the frustum.

use std::{
    collections::HashSet,
    time::{Duration, Instant},
};

use bevy::{
    camera::RenderTarget,
    light::DirectionalLightShadowMap,
    log::LogPlugin,
    pbr::ViewShadowBindings,
    prelude::*,
    render::{
        RenderApp,
        pipelined_rendering::PipelinedRenderingPlugin,
        render_resource::{PipelineCache, TextureFormat, TextureId, TextureUsages},
    },
    window::ExitCondition,
    winit::WinitPlugin,
};

#[derive(Component)]
struct ShadowTestCamera;

fn make_headless_app() -> App {
    let mut app = App::new();
    app.add_plugins(
        DefaultPlugins
            .set(WindowPlugin {
                primary_window: None,
                exit_condition: ExitCondition::DontExit,
                ..default()
            })
            .disable::<WinitPlugin>()
            .disable::<PipelinedRenderingPlugin>()
            .disable::<LogPlugin>(),
    );
    app.finish();
    app.cleanup();
    app
}

fn make_target(images: &mut Assets<Image>) -> Handle<Image> {
    let mut img = Image::new_target_texture(64, 64, TextureFormat::Rgba8UnormSrgb, None);
    img.texture_descriptor.usage |= TextureUsages::COPY_SRC;
    images.add(img)
}

fn inspect_shadow_array(app: &mut App) -> (TextureId, u32, u32, u64) {
    let render_world = app.sub_app_mut(RenderApp).world_mut();
    let mut q = render_world.query::<&ViewShadowBindings>();
    let bindings = q
        .iter(render_world)
        .next()
        .expect("expected ViewShadowBindings on active 3D camera");
    let tex = &bindings.directional_light_depth_texture;
    let width = tex.width();
    let layers = tex.depth_or_array_layers();
    let logical_bytes = (width as u64) * (tex.height() as u64) * (layers as u64) * 4;
    (tex.id(), width, layers, logical_bytes)
}

fn set_camera_look_z(app: &mut App, z_target: f32) {
    let world = app.world_mut();
    let mut q = world.query_filtered::<&mut Transform, With<ShadowTestCamera>>();
    for mut t in q.iter_mut(world) {
        *t = Transform::from_xyz(0.0, 2.0, 0.0).looking_at(Vec3::new(0.0, 2.0, z_target), Vec3::Y);
    }
}

fn main() {
    let mut app = make_headless_app();
    app.insert_resource(DirectionalLightShadowMap { size: 4096 });

    {
        let world = app.world_mut();
        let target =
            world.resource_scope(|_w, mut images: Mut<Assets<Image>>| make_target(&mut images));
        let floor_mesh = world
            .resource_mut::<Assets<Mesh>>()
            .add(Cuboid::new(20.0, 0.5, 20.0));
        let mat = world
            .resource_mut::<Assets<StandardMaterial>>()
            .add(StandardMaterial::default());

        // Receiver surface at z = -25m, lit by 1 directional light (4 cascades) + 4 spot lights.
        world.spawn((
            Mesh3d(floor_mesh),
            MeshMaterial3d(mat),
            Transform::from_xyz(0.0, 0.0, -25.0),
        ));

        world.spawn((
            DirectionalLight {
                shadow_maps_enabled: true,
                ..default()
            },
            Transform::from_xyz(4.0, 10.0, 4.0).looking_at(Vec3::new(0.0, 0.0, -25.0), Vec3::Y),
        ));

        for i in 0..4 {
            let x = (i as f32 - 1.5) * 3.0;
            world.spawn((
                SpotLight {
                    intensity: 100_000.0,
                    range: 12.0,
                    shadow_maps_enabled: true,
                    ..default()
                },
                Transform::from_xyz(x, 6.0, -25.0)
                    .looking_at(Vec3::new(x, 0.0, -25.0), Vec3::Z),
            ));
        }

        world.spawn((
            ShadowTestCamera,
            Camera3d::default(),
            RenderTarget::Image(target.into()),
            Transform::from_xyz(0.0, 2.0, 0.0)
                .looking_at(Vec3::new(0.0, 2.0, -25.0), Vec3::Y),
        ));
    }

    // Warm up facing -Z until shadow & PBR pipelines finish compiling (4 cascades + 4 spot = 8 layers).
    for _ in 0..4 {
        app.update();
    }
    for _ in 0..200 {
        let waiting = app
            .sub_app(RenderApp)
            .world()
            .resource::<PipelineCache>()
            .waiting_pipelines()
            .count();
        if waiting == 0 {
            break;
        }
        std::thread::sleep(Duration::from_millis(5));
        app.update();
    }
    for _ in 0..6 {
        app.update();
    }

    let mut steady_ms = Vec::with_capacity(8);
    for _ in 0..8 {
        let t0 = Instant::now();
        app.update();
        steady_ms.push(t0.elapsed().as_secs_f64() * 1000.0);
    }
    steady_ms.sort_by(|a, b| a.total_cmp(b));
    let median_steady_ms = steady_ms[steady_ms.len() / 2];

    let (initial_id, map_width, initial_layers, initial_bytes) = inspect_shadow_array(&mut app);

    // Control check: Look away (+Z) for 1 frame (`frames_since_last_use` reaches 2 < 3 -> retained), then back.
    set_camera_look_z(&mut app, 25.0);
    app.update();
    let (_away1_id, _, away1_layers, _) = inspect_shadow_array(&mut app);
    set_camera_look_z(&mut app, -25.0);
    let t_ret = Instant::now();
    app.update();
    let retained_revisit_ms = t_ret.elapsed().as_secs_f64() * 1000.0;
    let (after_1_away_id, _, after_1_away_layers, _) = inspect_shadow_array(&mut app);

    // Defect check: Repeat 3 cycles of looking away (+Z) for 2 frames (`frames_since_last_use` reaches 3 -> retired!) and back (-Z).
    let mut realloc_spikes_ms = Vec::with_capacity(3);
    let mut new_ids = Vec::with_capacity(3);
    let mut away2_layers = 0u32;

    for _ in 0..3 {
        set_camera_look_z(&mut app, 25.0);
        for _ in 0..2 {
            app.update();
        }
        let (_, _, layers_away, _) = inspect_shadow_array(&mut app);
        away2_layers = layers_away;

        set_camera_look_z(&mut app, -25.0);
        let t0 = Instant::now();
        app.update();
        let spike_ms = t0.elapsed().as_secs_f64() * 1000.0;
        let (revisit_id, _, revisit_layers, _) = inspect_shadow_array(&mut app);
        assert_eq!(revisit_layers, 8);
        realloc_spikes_ms.push(spike_ms);
        new_ids.push(revisit_id);

        // Settle 2 frames before next cycle.
        app.update();
        app.update();
    }

    let all_new_ids_distinct = {
        let mut s = HashSet::new();
        s.insert(after_1_away_id);
        new_ids.iter().all(|id| s.insert(*id))
    };

    println!("=== Bevy 0.20.1: `directional_light_depth_texture` Retirement & Reallocation ===");
    println!(
        "initial_shadow_array: {}x{}x{} Depth32Float ({:.1} MiB logical)",
        map_width,
        map_width,
        initial_layers,
        initial_bytes as f64 / (1024.0 * 1024.0)
    );
    println!("steady_state_8_layer_frame_median_ms: {:.2} ms", median_steady_ms);
    println!(
        "away_1_frame_control (layers {} -> {} -> {}): same_texture_id = {}, revisit_frame_ms = {:.2} ms",
        initial_layers,
        away1_layers,
        after_1_away_layers,
        after_1_away_id == initial_id,
        retained_revisit_ms
    );
    println!(
        "away_2_frames_defect (layers {} -> {} -> 8 across 3 cycles): new_512_mib_texture_every_cycle = {}",
        initial_layers, away2_layers, all_new_ids_distinct
    );
    for (idx, ms) in realloc_spikes_ms.iter().enumerate() {
        println!(
            "  cycle {}: 4->8 layer reallocation frame_ms = {:.2} ms ({:.2}x steady-state)",
            idx + 1,
            ms,
            ms / median_steady_ms.max(1e-6)
        );
    }
}
Dominant language
Rust
Stars
49.8k
Forks
5.1k
Avg merge
3d 4h
Merged PRs (30d)
136

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from bevyengine/bevy

All issues in bevyengine/bevy

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.