Skip to content

Commit b48645a

Browse files
IceSentrynicopap
andcommitted
add gpu picking
Co-authored-by: Kaylee Simmons <[email protected]> Co-authored-by: Nicola Papale <[email protected]>
1 parent 36eedbf commit b48645a

File tree

15 files changed

+931
-27
lines changed

15 files changed

+931
-27
lines changed

Cargo.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1443,6 +1443,16 @@ description = "Shows how to rumble a gamepad using force feedback"
14431443
category = "Input"
14441444
wasm = false
14451445

1446+
[[example]]
1447+
name = "gpu_picking"
1448+
path = "examples/input/gpu_picking.rs"
1449+
1450+
[package.metadata.example.gpu_picking]
1451+
name = "GPU picking"
1452+
description = "Mouse picking using the gpu"
1453+
category = "Input"
1454+
wasm = true
1455+
14461456
[[example]]
14471457
name = "keyboard_input"
14481458
path = "examples/input/keyboard_input.rs"
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// This shader shows how to enable the gpu picking feature for a material
2+
3+
// You'll need the mesh binding because that's where the entity index is
4+
#import bevy_pbr::mesh_bindings mesh
5+
#import bevy_pbr::mesh_vertex_output MeshVertexOutput
6+
7+
@group(1) @binding(0)
8+
var<uniform> color: vec4<f32>;
9+
10+
// Gpu picking uses multiple fragment output
11+
struct FragmentOutput {
12+
@location(0) color: vec4<f32>,
13+
// You can detect the feature with this flag
14+
#ifdef GPU_PICKING
15+
@location(1) mesh_id: u32,
16+
#endif
17+
};
18+
19+
@fragment
20+
fn fragment(in: MeshVertexOutput) -> FragmentOutput {
21+
var out: FragmentOutput;
22+
out.color = color;
23+
// make sure to output the entity index for gpu picking to work correctly
24+
#ifdef GPU_PICKING
25+
out.mesh_id = mesh[in.instance_index].id;
26+
#endif
27+
return out;
28+
}

crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::{
77
use bevy_ecs::{prelude::*, query::QueryItem};
88
use bevy_render::{
99
camera::ExtractedCamera,
10+
picking::{ExtractedGpuPickingCamera, VisibleMeshIdTextures},
1011
render_graph::{NodeRunError, RenderGraphContext, ViewNode},
1112
render_phase::RenderPhase,
1213
render_resource::{
@@ -34,8 +35,10 @@ impl ViewNode for MainOpaquePass3dNode {
3435
Option<&'static DepthPrepass>,
3536
Option<&'static NormalPrepass>,
3637
Option<&'static MotionVectorPrepass>,
38+
Option<&'static ExtractedGpuPickingCamera>,
3739
Option<&'static SkyboxPipelineId>,
3840
Option<&'static SkyboxBindGroup>,
41+
Option<&'static VisibleMeshIdTextures>,
3942
&'static ViewUniformOffset,
4043
);
4144

@@ -53,8 +56,10 @@ impl ViewNode for MainOpaquePass3dNode {
5356
depth_prepass,
5457
normal_prepass,
5558
motion_vector_prepass,
59+
gpu_picking_camera,
5660
skybox_pipeline,
5761
skybox_bind_group,
62+
mesh_id_textures,
5863
view_uniform_offset,
5964
): QueryItem<Self::ViewQuery>,
6065
world: &World,
@@ -64,21 +69,34 @@ impl ViewNode for MainOpaquePass3dNode {
6469
#[cfg(feature = "trace")]
6570
let _main_opaque_pass_3d_span = info_span!("main_opaque_pass_3d").entered();
6671

72+
let mut color_attachments = vec![Some(target.get_color_attachment(Operations {
73+
load: match camera_3d.clear_color {
74+
ClearColorConfig::Default => LoadOp::Clear(world.resource::<ClearColor>().0.into()),
75+
ClearColorConfig::Custom(color) => LoadOp::Clear(color.into()),
76+
ClearColorConfig::None => LoadOp::Load,
77+
},
78+
store: true,
79+
}))];
80+
81+
if gpu_picking_camera.is_some() {
82+
if let Some(mesh_id_textures) = mesh_id_textures {
83+
color_attachments.push(Some(mesh_id_textures.get_color_attachment(Operations {
84+
load: match camera_3d.clear_color {
85+
ClearColorConfig::None => LoadOp::Load,
86+
// TODO clear this earlier?
87+
_ => LoadOp::Clear(VisibleMeshIdTextures::clear_color()),
88+
},
89+
store: true,
90+
})));
91+
}
92+
}
93+
6794
// Setup render pass
6895
let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor {
6996
label: Some("main_opaque_pass_3d"),
7097
// NOTE: The opaque pass loads the color
7198
// buffer as well as writing to it.
72-
color_attachments: &[Some(target.get_color_attachment(Operations {
73-
load: match camera_3d.clear_color {
74-
ClearColorConfig::Default => {
75-
LoadOp::Clear(world.resource::<ClearColor>().0.into())
76-
}
77-
ClearColorConfig::Custom(color) => LoadOp::Clear(color.into()),
78-
ClearColorConfig::None => LoadOp::Load,
79-
},
80-
store: true,
81-
}))],
99+
color_attachments: &color_attachments,
82100
depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
83101
view: &depth.view,
84102
// NOTE: The opaque main pass loads the depth buffer and possibly overwrites it

crates/bevy_core_pipeline/src/core_3d/main_transparent_pass_3d_node.rs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::core_3d::Transparent3d;
22
use bevy_ecs::{prelude::*, query::QueryItem};
33
use bevy_render::{
44
camera::ExtractedCamera,
5+
picking::{ExtractedGpuPickingCamera, VisibleMeshIdTextures},
56
render_graph::{NodeRunError, RenderGraphContext, ViewNode},
67
render_phase::RenderPhase,
78
render_resource::{LoadOp, Operations, RenderPassDepthStencilAttachment, RenderPassDescriptor},
@@ -21,12 +22,16 @@ impl ViewNode for MainTransparentPass3dNode {
2122
&'static RenderPhase<Transparent3d>,
2223
&'static ViewTarget,
2324
&'static ViewDepthTexture,
25+
Option<&'static ExtractedGpuPickingCamera>,
26+
Option<&'static VisibleMeshIdTextures>,
2427
);
2528
fn run(
2629
&self,
2730
graph: &mut RenderGraphContext,
2831
render_context: &mut RenderContext,
29-
(camera, transparent_phase, target, depth): QueryItem<Self::ViewQuery>,
32+
(camera, transparent_phase, target, depth, gpu_picking_camera, mesh_id_textures): QueryItem<
33+
Self::ViewQuery,
34+
>,
3035
world: &World,
3136
) -> Result<(), NodeRunError> {
3237
let view_entity = graph.view_entity();
@@ -37,13 +42,27 @@ impl ViewNode for MainTransparentPass3dNode {
3742
#[cfg(feature = "trace")]
3843
let _main_transparent_pass_3d_span = info_span!("main_transparent_pass_3d").entered();
3944

45+
let mut color_attachments = vec![Some(target.get_color_attachment(Operations {
46+
load: LoadOp::Load,
47+
store: true,
48+
}))];
49+
50+
if gpu_picking_camera.is_some() {
51+
if let Some(mesh_id_textures) = mesh_id_textures {
52+
color_attachments.push(Some(mesh_id_textures.get_color_attachment(
53+
Operations {
54+
// The texture is already cleared in the opaque pass
55+
load: LoadOp::Load,
56+
store: true,
57+
},
58+
)));
59+
}
60+
}
61+
4062
let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor {
4163
label: Some("main_transparent_pass_3d"),
4264
// NOTE: The transparent pass loads the color buffer as well as overwriting it where appropriate.
43-
color_attachments: &[Some(target.get_color_attachment(Operations {
44-
load: LoadOp::Load,
45-
store: true,
46-
}))],
65+
color_attachments: &color_attachments,
4766
depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
4867
view: &depth.view,
4968
// NOTE: For the transparent pass we load the depth buffer. There should be no

crates/bevy_core_pipeline/src/core_3d/mod.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub mod graph {
1414
pub const MAIN_OPAQUE_PASS: &str = "main_opaque_pass";
1515
pub const MAIN_TRANSPARENT_PASS: &str = "main_transparent_pass";
1616
pub const END_MAIN_PASS: &str = "end_main_pass";
17+
pub const ENTITY_INDEX_BUFFER_COPY: &str = "entity_index_buffer_copy";
1718
pub const BLOOM: &str = "bloom";
1819
pub const TONEMAPPING: &str = "tonemapping";
1920
pub const FXAA: &str = "fxaa";
@@ -35,6 +36,7 @@ use bevy_ecs::prelude::*;
3536
use bevy_render::{
3637
camera::{Camera, ExtractedCamera},
3738
extract_component::ExtractComponentPlugin,
39+
picking::{ExtractedGpuPickingCamera, VisibleMeshIdTextures, MESH_ID_TEXTURE_FORMAT},
3840
prelude::Msaa,
3941
render_graph::{EmptyNode, RenderGraphApp, ViewNodeRunner},
4042
render_phase::{
@@ -94,6 +96,7 @@ impl Plugin for Core3dPlugin {
9496
sort_phase_system::<AlphaMask3dPrepass>.in_set(RenderSet::PhaseSort),
9597
prepare_core_3d_depth_textures.in_set(RenderSet::PrepareResources),
9698
prepare_prepass_textures.in_set(RenderSet::PrepareResources),
99+
prepare_entity_textures.in_set(RenderSet::PrepareResources),
97100
),
98101
);
99102

@@ -493,3 +496,63 @@ pub fn prepare_prepass_textures(
493496
});
494497
}
495498
}
499+
500+
/// Create the required textures based on the camera size
501+
pub fn prepare_entity_textures(
502+
mut commands: Commands,
503+
mut texture_cache: ResMut<TextureCache>,
504+
msaa: Res<Msaa>,
505+
render_device: Res<RenderDevice>,
506+
views_3d: Query<
507+
(Entity, &ExtractedCamera),
508+
(
509+
With<ExtractedGpuPickingCamera>,
510+
With<RenderPhase<Opaque3d>>,
511+
With<RenderPhase<AlphaMask3d>>,
512+
),
513+
>,
514+
) {
515+
for (entity, camera) in &views_3d {
516+
let Some(physical_target_size) = camera.physical_target_size else {
517+
continue;
518+
};
519+
520+
let size = Extent3d {
521+
depth_or_array_layers: 1,
522+
width: physical_target_size.x,
523+
height: physical_target_size.y,
524+
};
525+
526+
let descriptor = TextureDescriptor {
527+
label: None,
528+
size,
529+
mip_level_count: 1,
530+
sample_count: 1,
531+
dimension: TextureDimension::D2,
532+
format: MESH_ID_TEXTURE_FORMAT,
533+
usage: TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_SRC,
534+
view_formats: &[],
535+
};
536+
537+
let mesh_id_textures = VisibleMeshIdTextures {
538+
main: texture_cache.get(
539+
&render_device,
540+
TextureDescriptor {
541+
label: Some("main_entity_texture"),
542+
..descriptor
543+
},
544+
),
545+
sampled: (msaa.samples() > 1).then(|| {
546+
texture_cache.get(
547+
&render_device,
548+
TextureDescriptor {
549+
label: Some("main_entity_texture_sampled"),
550+
sample_count: msaa.samples(),
551+
..descriptor
552+
},
553+
)
554+
}),
555+
};
556+
commands.entity(entity).insert(mesh_id_textures);
557+
}
558+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use bevy_app::Plugin;
2+
use bevy_ecs::{query::QueryItem, world::World};
3+
use bevy_render::{
4+
picking::{CurrentGpuPickingBufferIndex, ExtractedGpuPickingCamera, VisibleMeshIdTextures},
5+
render_graph::{RenderGraphApp, RenderGraphContext, ViewNode, ViewNodeRunner},
6+
renderer::RenderContext,
7+
RenderApp,
8+
};
9+
10+
use crate::core_3d::CORE_3D;
11+
12+
#[derive(Default)]
13+
pub struct EntityIndexBufferCopyNode;
14+
impl ViewNode for EntityIndexBufferCopyNode {
15+
type ViewQuery = (
16+
&'static VisibleMeshIdTextures,
17+
&'static ExtractedGpuPickingCamera,
18+
);
19+
20+
fn run(
21+
&self,
22+
_graph: &mut RenderGraphContext,
23+
render_context: &mut RenderContext,
24+
(mesh_id_textures, gpu_picking_camera): QueryItem<Self::ViewQuery>,
25+
world: &World,
26+
) -> Result<(), bevy_render::render_graph::NodeRunError> {
27+
let current_buffer_index = world.resource::<CurrentGpuPickingBufferIndex>();
28+
gpu_picking_camera.run_node(
29+
render_context.command_encoder(),
30+
&mesh_id_textures.main.texture,
31+
current_buffer_index,
32+
);
33+
Ok(())
34+
}
35+
}
36+
37+
pub struct EntityIndexBufferCopyPlugin;
38+
impl Plugin for EntityIndexBufferCopyPlugin {
39+
fn build(&self, app: &mut bevy_app::App) {
40+
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else {
41+
return;
42+
};
43+
44+
// 3D
45+
use crate::core_3d::graph::node::*;
46+
render_app
47+
.add_render_graph_node::<ViewNodeRunner<EntityIndexBufferCopyNode>>(
48+
CORE_3D,
49+
ENTITY_INDEX_BUFFER_COPY,
50+
)
51+
.add_render_graph_edge(CORE_3D, UPSCALING, ENTITY_INDEX_BUFFER_COPY);
52+
}
53+
}

crates/bevy_core_pipeline/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ pub mod clear_color;
66
pub mod contrast_adaptive_sharpening;
77
pub mod core_2d;
88
pub mod core_3d;
9+
pub mod entity_index_buffer_copy;
910
pub mod fullscreen_vertex_shader;
1011
pub mod fxaa;
1112
pub mod msaa_writeback;
@@ -40,6 +41,7 @@ use crate::{
4041
contrast_adaptive_sharpening::CASPlugin,
4142
core_2d::Core2dPlugin,
4243
core_3d::Core3dPlugin,
44+
entity_index_buffer_copy::EntityIndexBufferCopyPlugin,
4345
fullscreen_vertex_shader::FULLSCREEN_SHADER_HANDLE,
4446
fxaa::FxaaPlugin,
4547
msaa_writeback::MsaaWritebackPlugin,
@@ -79,6 +81,7 @@ impl Plugin for CorePipelinePlugin {
7981
BloomPlugin,
8082
FxaaPlugin,
8183
CASPlugin,
84+
EntityIndexBufferCopyPlugin,
8285
));
8386
}
8487
}

0 commit comments

Comments
 (0)