A view's first frame blocks on its blit pipeline behind every pipeline queued before it

Aperta
#26,600 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
55/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
rust

Direzione di ricerca

Read crates/bevy_core_pipeline/src/upscaling/mod.rs, especially prepare_view_upscaling_pipelines, then trace PipelineCache::block_on_render_pipeline and process_queue in the render pipeline cache. The report provides a reproduction and identifies the ordering that stalls frame 4. Investigate keeping unrelated queued pipelines asynchronous; done when the reproduction no longer waits for scene pipelines before the view's blit pipeline completes.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Bevy version and features

0.20.1, with the features in the Cargo.toml below. prepare_view_upscaling_pipelines and PipelineCache::block_on_render_pipeline are unchanged on main (42265b2).

What you did

Spawned the same 24 PBR mesh and material combinations in two headless apps, in release. In A, the camera was active for three empty frames first, so its blit pipeline was built before the scene arrived. In B, the scene was spawned with the camera inactive (Camera { is_active: false, .. }) and the camera was activated on frame 4, as when a camera is held back until the world is ready. Each app timed its frame 4.

What went wrong

B's frame 4 blocks for as long as the whole scene's pipelines take to build:

=== Bevy 0.20.1 Reproduction 04: First-Appearance View BlitPipeline Synchronous Stall ===
pbr_mesh_material_combinations_spawned: 24

Scenario A (camera already active on empty scene -> BlitPipeline cached before frame 4):
  frame_4_app_update_ms:              5.14 ms (non-blocking async queue)
  pipelines_after_frame_4:        75 total, 68 still compiling asynchronously
  subsequent_async_drain_wall_ms:    68.67 ms

Scenario B (camera held is_active = false -> activated on frame 4 alongside scene):
  frame_4_app_update_ms:            427.38 ms (stalled inside block_on_render_pipeline)
  pipelines_after_frame_4:        75 total, 0 still compiling asynchronously
  subsequent_async_drain_wall_ms:     0.00 ms

first_frame_stall_multiplier: 83.1x (427.38 ms stalled vs 5.14 ms async queue; +422.24 ms single-frame hitch)

prepare_view_upscaling_pipelines (crates/bevy_core_pipeline/src/upscaling/mod.rs) specializes the view's BlitPipeline and calls pipeline_cache.block_on_render_pipeline(pipeline). The pipeline is new, so block_on_render_pipeline runs process_queue(), which starts every pipeline queued so far, the scene's from RenderSystems::Queue earlier in the frame among them, and then waits for the blit pipeline's task, started after theirs (and, while #26152 stands, behind the same shader-cache lock). Pipeline compilation is asynchronous by default, yet the view's first frame waits for every pipeline queued before it.

Additional information

block_on_render_pipeline could start, or build in place, only the pipeline it waits for, leaving the rest of the queue asynchronous; or the blit pipeline's common variants could be specialized before RenderSystems::Queue, or at startup for the surface's format, so a newly active view does not wait behind the scene.

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:
//! `prepare_view_upscaling_pipelines` (`crates/bevy_core_pipeline/src/upscaling/mod.rs:51-106`)
//! calls `pipeline_cache.block_on_render_pipeline(pipeline)` in `RenderSystems::Prepare`
//! on the first frame a camera view obtains a `ViewTarget`.
//!
//! Because `RenderSystems::Queue` runs earlier in the same frame and pushes all newly
//! visible PBR/scene pipelines into `PipelineCache::new_pipelines` ahead of `BlitPipeline`,
//! `block_on_render_pipeline` spawns every queued scene pipeline onto `AsyncComputeTaskPool`
//! first (all contending on `Arc<Mutex<ShaderCache>>`), synchronously stalling that frame
//! behind the scene's shader compilation.

use std::time::Instant;

use bevy::{
    asset::RenderAssetUsages,
    camera::RenderTarget,
    core_pipeline::tonemapping::Tonemapping,
    log::LogPlugin,
    mesh::VertexAttributeValues,
    prelude::*,
    render::{
        RenderApp,
        pipelined_rendering::PipelinedRenderingPlugin,
        render_resource::{
            Extent3d, PipelineCache, TextureDimension, TextureFormat, TextureUsages,
        },
    },
    window::ExitCondition,
    winit::WinitPlugin,
};

#[derive(Component)]
struct TestCamera;

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_1x1_texture(rgba: [u8; 4], is_srgb: bool) -> Image {
    Image::new_fill(
        Extent3d {
            width: 1,
            height: 1,
            depth_or_array_layers: 1,
        },
        TextureDimension::D2,
        &rgba,
        if is_srgb {
            TextureFormat::Rgba8UnormSrgb
        } else {
            TextureFormat::Rgba8Unorm
        },
        RenderAssetUsages::default(),
    )
}

fn spawn_pbr_variants(world: &mut World) -> usize {
    let tex_color = world
        .resource_mut::<Assets<Image>>()
        .add(make_1x1_texture([220, 200, 180, 255], true));
    let tex_linear = world
        .resource_mut::<Assets<Image>>()
        .add(make_1x1_texture([128, 128, 255, 255], false));

    let mesh_handles = world.resource_scope(|_w, mut meshes: Mut<Assets<Mesh>>| {
        let base: Mesh = Cuboid::new(0.7, 0.7, 0.7).into();
        let with_tangents = base
            .clone()
            .with_generated_tangents()
            .expect("cuboid tangents");

        let mut with_colors = base.clone();
        let vcount = with_colors.count_vertices();
        with_colors.insert_attribute(
            Mesh::ATTRIBUTE_COLOR,
            VertexAttributeValues::Float32x4(vec![[1.0, 1.0, 1.0, 1.0]; vcount]),
        );

        let mut with_both = with_tangents.clone();
        with_both.insert_attribute(
            Mesh::ATTRIBUTE_COLOR,
            VertexAttributeValues::Float32x4(vec![[1.0, 1.0, 1.0, 1.0]; vcount]),
        );

        vec![
            meshes.add(base),
            meshes.add(with_tangents),
            meshes.add(with_colors),
            meshes.add(with_both),
        ]
    });

    let mat_handles = world.resource_scope(|_w, mut materials: Mut<Assets<StandardMaterial>>| {
        vec![
            materials.add(StandardMaterial {
                base_color: Color::srgb(0.8, 0.3, 0.2),
                ..default()
            }),
            materials.add(StandardMaterial {
                base_color_texture: Some(tex_color.clone()),
                normal_map_texture: Some(tex_linear.clone()),
                ..default()
            }),
            materials.add(StandardMaterial {
                base_color_texture: Some(tex_color.clone()),
                metallic_roughness_texture: Some(tex_linear.clone()),
                occlusion_texture: Some(tex_linear.clone()),
                ..default()
            }),
            materials.add(StandardMaterial {
                base_color_texture: Some(tex_color.clone()),
                alpha_mode: AlphaMode::Mask(0.5),
                double_sided: true,
                cull_mode: None,
                ..default()
            }),
            materials.add(StandardMaterial {
                base_color: Color::srgba(0.3, 0.7, 0.9, 0.6),
                alpha_mode: AlphaMode::Blend,
                ..default()
            }),
            materials.add(StandardMaterial {
                unlit: true,
                emissive_texture: Some(tex_color.clone()),
                ..default()
            }),
        ]
    });

    let mut spawned = 0usize;
    for mesh in &mesh_handles {
        for mat in &mat_handles {
            let x = (spawned % 6) as f32 * 1.3 - 3.25;
            let y = (spawned / 6) as f32 * 1.3 - 2.0;
            world.spawn((
                Mesh3d(mesh.clone()),
                MeshMaterial3d(mat.clone()),
                Transform::from_xyz(x, y, 0.0),
            ));
            spawned += 1;
        }
    }

    world.spawn((
        DirectionalLight {
            shadow_maps_enabled: true,
            ..default()
        },
        Transform::from_xyz(4.0, 8.0, 6.0).looking_at(Vec3::ZERO, Vec3::Y),
    ));

    spawned
}

fn pipeline_stats(app: &App) -> (usize, usize) {
    let pc = app.sub_app(RenderApp).world().resource::<PipelineCache>();
    (pc.pipelines().count(), pc.waiting_pipelines().count())
}

/// Scenario A: Camera is already active for 3 empty frames (so its `BlitPipeline` is cached),
/// then the 24 PBR variants are spawned right before frame 4.
fn run_scenario_prewarmed_blit() -> (usize, f64, usize, usize, f64) {
    let mut app = make_headless_app();
    {
        let world = app.world_mut();
        let mut target = Image::new_target_texture(64, 64, TextureFormat::Rgba8UnormSrgb, None);
        target.texture_descriptor.usage |= TextureUsages::COPY_SRC;
        let target_handle = world.resource_mut::<Assets<Image>>().add(target);

        world.spawn((
            TestCamera,
            Camera3d::default(),
            Camera {
                is_active: true,
                ..default()
            },
            RenderTarget::Image(target_handle.into()),
            Tonemapping::TonyMcMapface,
            Transform::from_xyz(0.0, 0.0, 12.0).looking_at(Vec3::ZERO, Vec3::Y),
        ));
    }

    // 3 empty frames: `BlitPipeline` compiles on frame 1 with an empty queue.
    for _ in 0..3 {
        app.update();
    }

    let variants = spawn_pbr_variants(app.world_mut());

    // Frame 4: 24 PBR variants enter `RenderSystems::Queue`, while `BlitPipeline` is already cached.
    let t_frame4 = Instant::now();
    app.update();
    let frame4_ms = t_frame4.elapsed().as_secs_f64() * 1000.0;
    let (total_after_f4, waiting_after_f4) = pipeline_stats(&app);

    let t_drain = Instant::now();
    for _ in 0..30 {
        if pipeline_stats(&app).1 == 0 {
            break;
        }
        app.update();
    }
    let drain_ms = t_drain.elapsed().as_secs_f64() * 1000.0;

    (variants, frame4_ms, total_after_f4, waiting_after_f4, drain_ms)
}

/// Scenario B: The exact same 24 PBR variants are spawned while `camera.is_active == false`
/// for 3 frames, then `camera.is_active = true` is flipped right before frame 4.
fn run_scenario_first_frame_active_camera() -> (usize, f64, usize, usize, f64) {
    let mut app = make_headless_app();
    let variants = {
        let world = app.world_mut();
        let mut target = Image::new_target_texture(64, 64, TextureFormat::Rgba8UnormSrgb, None);
        target.texture_descriptor.usage |= TextureUsages::COPY_SRC;
        let target_handle = world.resource_mut::<Assets<Image>>().add(target);

        let count = spawn_pbr_variants(world);

        world.spawn((
            TestCamera,
            Camera3d::default(),
            Camera {
                is_active: false,
                ..default()
            },
            RenderTarget::Image(target_handle.into()),
            Tonemapping::TonyMcMapface,
            Transform::from_xyz(0.0, 0.0, 12.0).looking_at(Vec3::ZERO, Vec3::Y),
        ));
        count
    };

    for _ in 0..3 {
        app.update();
    }

    // Activate camera before frame 4: `Queue` enqueues 24 PBR pipelines ahead of `BlitPipeline`,
    // and `prepare_view_upscaling_pipelines` calls `block_on_render_pipeline(blit_pipeline)`.
    {
        let world = app.world_mut();
        let mut q = world.query_filtered::<&mut Camera, With<TestCamera>>();
        for mut cam in q.iter_mut(world) {
            cam.is_active = true;
        }
    }

    let t_frame4 = Instant::now();
    app.update();
    let frame4_ms = t_frame4.elapsed().as_secs_f64() * 1000.0;
    let (total_after_f4, waiting_after_f4) = pipeline_stats(&app);

    let t_drain = Instant::now();
    for _ in 0..30 {
        if pipeline_stats(&app).1 == 0 {
            break;
        }
        app.update();
    }
    let drain_ms = t_drain.elapsed().as_secs_f64() * 1000.0;

    (variants, frame4_ms, total_after_f4, waiting_after_f4, drain_ms)
}

fn main() {
    // One tiny warmup app so Vulkan/driver shared library initialization does not skew whichever runs first.
    {
        let mut warmup = make_headless_app();
        warmup.update();
    }

    let (variants_a, frame4_a_ms, total_a, waiting_a, drain_a_ms) = run_scenario_prewarmed_blit();
    let (variants_b, frame4_b_ms, total_b, waiting_b, drain_b_ms) =
        run_scenario_first_frame_active_camera();

    assert_eq!(variants_a, variants_b);

    println!("=== Bevy 0.20.1 Reproduction 04: First-Appearance View BlitPipeline Synchronous Stall ===");
    println!("pbr_mesh_material_combinations_spawned: {}", variants_a);
    println!();
    println!("Scenario A (camera already active on empty scene -> BlitPipeline cached before frame 4):");
    println!("  frame_4_app_update_ms:          {:>8.2} ms (non-blocking async queue)", frame4_a_ms);
    println!(
        "  pipelines_after_frame_4:        {} total, {} still compiling asynchronously",
        total_a, waiting_a
    );
    println!("  subsequent_async_drain_wall_ms: {:>8.2} ms", drain_a_ms);
    println!();
    println!("Scenario B (camera held is_active = false -> activated on frame 4 alongside scene):");
    println!("  frame_4_app_update_ms:          {:>8.2} ms (stalled inside block_on_render_pipeline)", frame4_b_ms);
    println!(
        "  pipelines_after_frame_4:        {} total, {} still compiling asynchronously",
        total_b, waiting_b
    );
    println!("  subsequent_async_drain_wall_ms: {:>8.2} ms", drain_b_ms);
    println!();
    println!(
        "first_frame_stall_multiplier: {:.1}x ({:.2} ms stalled vs {:.2} ms async queue; +{:.2} ms single-frame hitch)",
        frame4_b_ms / frame4_a_ms.max(1e-6),
        frame4_b_ms,
        frame4_a_ms,
        frame4_b_ms - frame4_a_ms
    );
}
Lingua principale
Rust
Stelle
49.8k
Fork
5.1k
Merge medio
3g 4h
PR unite (30g)
136

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di bevyengine/bevy

Tutte le issue di bevyengine/bevy

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.