diff options
Diffstat (limited to 'src_testbed')
| -rw-r--r-- | src_testbed/camera2d.rs | 2 | ||||
| -rw-r--r-- | src_testbed/camera3d.rs | 2 | ||||
| -rw-r--r-- | src_testbed/debug_render.rs | 6 | ||||
| -rw-r--r-- | src_testbed/graphics.rs | 26 | ||||
| -rw-r--r-- | src_testbed/objects/node.rs | 84 | ||||
| -rw-r--r-- | src_testbed/plugin.rs | 6 | ||||
| -rw-r--r-- | src_testbed/testbed.rs | 80 |
7 files changed, 117 insertions, 89 deletions
diff --git a/src_testbed/camera2d.rs b/src_testbed/camera2d.rs index 6ba17a1..ae5c163 100644 --- a/src_testbed/camera2d.rs +++ b/src_testbed/camera2d.rs @@ -48,7 +48,7 @@ impl OrbitCameraPlugin { fn mouse_motion_system( _time: Res<Time>, mut mouse_motion_events: EventReader<MouseMotion>, - mouse_button_input: Res<Input<MouseButton>>, + mouse_button_input: Res<ButtonInput<MouseButton>>, mut query: Query<(&mut OrbitCamera, &mut Transform, &mut Camera)>, ) { let mut delta = Vec2::ZERO; diff --git a/src_testbed/camera3d.rs b/src_testbed/camera3d.rs index 9c3764e..b2313b7 100644 --- a/src_testbed/camera3d.rs +++ b/src_testbed/camera3d.rs @@ -61,7 +61,7 @@ impl OrbitCameraPlugin { fn mouse_motion_system( time: Res<Time>, mut mouse_motion_events: EventReader<MouseMotion>, - mouse_button_input: Res<Input<MouseButton>>, + mouse_button_input: Res<ButtonInput<MouseButton>>, mut query: Query<(&mut OrbitCamera, &mut Transform, &mut Camera)>, ) { let mut delta = Vec2::ZERO; diff --git a/src_testbed/debug_render.rs b/src_testbed/debug_render.rs index 0e0b8b8..3138546 100644 --- a/src_testbed/debug_render.rs +++ b/src_testbed/debug_render.rs @@ -30,11 +30,11 @@ impl Plugin for RapierDebugRenderPlugin { } } -struct BevyLinesRenderBackend<'a> { - gizmos: Gizmos<'a>, +struct BevyLinesRenderBackend<'w, 's> { + gizmos: Gizmos<'w, 's>, } -impl<'a> DebugRenderBackend for BevyLinesRenderBackend<'a> { +impl<'w, 's> DebugRenderBackend for BevyLinesRenderBackend<'w, 's> { #[cfg(feature = "dim2")] fn draw_line(&mut self, _: DebugRenderObject, a: Point<Real>, b: Point<Real>, color: [f32; 4]) { self.gizmos.line( diff --git a/src_testbed/graphics.rs b/src_testbed/graphics.rs index 552d4c7..226be4d 100644 --- a/src_testbed/graphics.rs +++ b/src_testbed/graphics.rs @@ -22,6 +22,9 @@ pub type BevyMaterial = ColorMaterial; #[cfg(feature = "dim3")] pub type BevyMaterial = StandardMaterial; +pub type InstancedMaterials = HashMap<Point3<usize>, Handle<BevyMaterial>>; +pub const SELECTED_OBJECT_MATERIAL_KEY: Point3<usize> = point![42, 42, 42]; + pub struct GraphicsManager { rand: Pcg32, b2sn: HashMap<RigidBodyHandle, Vec<EntityWithGraphics>>, @@ -30,6 +33,7 @@ pub struct GraphicsManager { b2wireframe: HashMap<RigidBodyHandle, bool>, ground_color: Point3<f32>, prefab_meshes: HashMap<ShapeType, Handle<Mesh>>, + instanced_materials: InstancedMaterials, pub gfx_shift: Vector<Real>, } @@ -43,10 +47,15 @@ impl GraphicsManager { ground_color: point![0.5, 0.5, 0.5], b2wireframe: HashMap::new(), prefab_meshes: HashMap::new(), + instanced_materials: HashMap::new(), gfx_shift: Vector::zeros(), } } + pub fn selection_material(&self) -> Handle<BevyMaterial> { + self.instanced_materials[&SELECTED_OBJECT_MATERIAL_KEY].clone_weak() + } + pub fn clear(&mut self, commands: &mut Commands) { for sns in self.b2sn.values_mut() { for sn in sns.iter_mut() { @@ -54,6 +63,7 @@ impl GraphicsManager { } } + self.instanced_materials.clear(); self.b2sn.clear(); self.c2color.clear(); self.b2color.clear(); @@ -159,10 +169,11 @@ impl GraphicsManager { fn gen_color(rng: &mut Pcg32) -> Point3<f32> { let mut color: Point3<f32> = rng.gen(); - color *= 1.5; - color.x = color.x.min(1.0); - color.y = color.y.min(1.0); - color.z = color.z.min(1.0); + + // Quantize the colors a bit to get some amount of auto-instancing from bevy. + color.x = (color.x * 5.0).round() / 5.0; + color.y = (color.y * 5.0).round() / 5.0; + color.z = (color.z * 5.0).round() / 5.0; color } @@ -191,7 +202,7 @@ impl GraphicsManager { commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<BevyMaterial>, - components: &mut Query<(&mut Transform,)>, + components: &mut Query<&mut Transform>, handle: RigidBodyHandle, bodies: &RigidBodySet, colliders: &ColliderSet, @@ -214,7 +225,7 @@ impl GraphicsManager { commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<BevyMaterial>, - components: &mut Query<(&mut Transform,)>, + components: &mut Query<&mut Transform>, handle: RigidBodyHandle, bodies: &RigidBodySet, colliders: &ColliderSet, @@ -330,6 +341,7 @@ impl GraphicsManager { meshes, materials, &self.prefab_meshes, + &mut self.instanced_materials, shape, handle, *pos, @@ -345,7 +357,7 @@ impl GraphicsManager { &mut self, _bodies: &RigidBodySet, colliders: &ColliderSet, - components: &mut Query<(&mut Transform,)>, + components: &mut Query<&mut Transform>, _materials: &mut Assets<BevyMaterial>, ) { for (_, ns) in self.b2sn.iter_mut() { diff --git a/src_testbed/objects/node.rs b/src_testbed/objects/node.rs index cdc042b..478fead 100644 --- a/src_testbed/objects/node.rs +++ b/src_testbed/objects/node.rs @@ -14,7 +14,7 @@ use rapier::geometry::{ColliderHandle, ColliderSet, Shape, ShapeType}; use rapier::geometry::{Cone, Cylinder}; use rapier::math::{Isometry, Real, Vector}; -use crate::graphics::BevyMaterial; +use crate::graphics::{BevyMaterial, InstancedMaterials, SELECTED_OBJECT_MATERIAL_KEY}; #[cfg(feature = "dim2")] use { bevy_sprite::MaterialMesh2dBundle, @@ -30,15 +30,43 @@ pub struct EntityWithGraphics { pub collider: Option<ColliderHandle>, pub delta: Isometry<Real>, pub opacity: f32, - material: Handle<BevyMaterial>, + pub material: Handle<BevyMaterial>, } impl EntityWithGraphics { + pub fn register_selected_object_material( + materials: &mut Assets<BevyMaterial>, + instanced_materials: &mut InstancedMaterials, + ) { + if instanced_materials.contains_key(&SELECTED_OBJECT_MATERIAL_KEY) { + return; // Already added. + } + + #[cfg(feature = "dim2")] + let selection_material = ColorMaterial { + color: Color::rgb(1.0, 0.0, 0.0), + texture: None, + }; + #[cfg(feature = "dim3")] + let selection_material = StandardMaterial { + metallic: 0.5, + perceptual_roughness: 0.5, + double_sided: true, // TODO: this doesn't do anything? + ..StandardMaterial::from(Color::rgb(1.0, 0.0, 0.0)) + }; + + instanced_materials.insert( + SELECTED_OBJECT_MATERIAL_KEY, + materials.add(selection_material), + ); + } + pub fn spawn( commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<BevyMaterial>, prefab_meshs: &HashMap<ShapeType, Handle<Mesh>>, + instanced_materials: &mut InstancedMaterials, shape: &dyn Shape, collider: Option<ColliderHandle>, collider_pos: Isometry<Real>, @@ -46,6 +74,8 @@ impl EntityWithGraphics { color: Point3<f32>, sensor: bool, ) -> Self { + Self::register_selected_object_material(materials, instanced_materials); + let entity = commands.spawn_empty().id(); let scale = collider_mesh_scale(shape); @@ -90,21 +120,23 @@ impl EntityWithGraphics { double_sided: true, // TODO: this doesn't do anything? ..StandardMaterial::from(bevy_color) }; - let material_handle = materials.add(material); + let material_handle = instanced_materials + .entry(color.coords.map(|c| (c * 255.0) as usize).into()) + .or_insert_with(|| materials.add(material)); let material_weak_handle = material_handle.clone_weak(); if let Some(mesh) = mesh { #[cfg(feature = "dim2")] let bundle = MaterialMesh2dBundle { mesh: mesh.into(), - material: material_handle, + material: material_handle.clone_weak(), transform, ..Default::default() }; #[cfg(feature = "dim3")] let bundle = PbrBundle { mesh, - material: material_handle, + material: material_handle.clone_weak(), transform, ..Default::default() }; @@ -133,28 +165,6 @@ impl EntityWithGraphics { commands.entity(self.entity).despawn(); } - pub fn select(&mut self, materials: &mut Assets<BevyMaterial>) { - // NOTE: we don't just call `self.set_color` because that would - // overwrite self.base_color too. - self.color = point![1.0, 0.0, 0.0]; - if let Some(material) = materials.get_mut(&self.material) { - #[cfg(feature = "dim2")] - { - material.color = - Color::rgba(self.color.x, self.color.y, self.color.z, self.opacity); - } - #[cfg(feature = "dim3")] - { - material.base_color = - Color::rgba(self.color.x, self.color.y, self.color.z, self.opacity); - } - } - } - - pub fn unselect(&mut self, materials: &mut Assets<BevyMaterial>) { - self.set_color(materials, self.base_color); - } - pub fn set_color(&mut self, materials: &mut Assets<BevyMaterial>, color: Point3<f32>) { if let Some(material) = materials.get_mut(&self.material) { #[cfg(feature = "dim2")] @@ -173,11 +183,11 @@ impl EntityWithGraphics { pub fn update( &mut self, colliders: &ColliderSet, - components: &mut Query<(&mut Transform,)>, + components: &mut Query<&mut Transform>, gfx_shift: &Vector<Real>, ) { if let Some(Some(co)) = self.collider.map(|c| colliders.get(c)) { - if let Ok(mut pos) = components.get_component_mut::<Transform>(self.entity) { + if let Ok(mut pos) = components.get_mut(self.entity) { let co_pos = co.position() * self.delta; pos.translation.x = (co_pos.translation.vector.x + gfx_shift.x) as f32; pos.translation.y = (co_pos.translation.vector.y + gfx_shift.y) as f32; @@ -230,18 +240,14 @@ impl EntityWithGraphics { // // Cuboid mesh // - let cuboid = Mesh::from(shape::Cube { size: 2.0 }); + let cuboid = Mesh::from(bevy::math::primitives::Cuboid::new(2.0, 2.0, 2.0)); out.insert(ShapeType::Cuboid, meshes.add(cuboid.clone())); out.insert(ShapeType::RoundCuboid, meshes.add(cuboid)); // // Ball mesh // - let ball = Mesh::try_from(shape::Icosphere { - subdivisions: 2, - radius: 1.0, - }) - .unwrap(); + let ball = Mesh::try_from(bevy::math::primitives::Sphere::new(1.0)).unwrap(); out.insert(ShapeType::Ball, meshes.add(ball)); // @@ -309,14 +315,14 @@ fn bevy_polyline(buffers: (Vec<Point2<Real>>, Option<Vec<[u32; 2]>>)) -> Mesh { let normals: Vec<_> = (0..vertices.len()).map(|_| [0.0, 0.0, 1.0]).collect(); // Generate the mesh - let mut mesh = Mesh::new(PrimitiveTopology::LineStrip); + let mut mesh = Mesh::new(PrimitiveTopology::LineStrip, Default::default()); mesh.insert_attribute( Mesh::ATTRIBUTE_POSITION, VertexAttributeValues::from(vertices), ); mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, VertexAttributeValues::from(normals)); mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, VertexAttributeValues::from(uvs)); - mesh.set_indices(Some(Indices::U32(indices))); + mesh.insert_indices(Indices::U32(indices)); mesh } @@ -352,14 +358,14 @@ fn bevy_mesh(buffers: (Vec<Point3<Real>>, Vec<[u32; 3]>)) -> Mesh { let uvs: Vec<_> = (0..vertices.len()).map(|_| [0.0, 0.0]).collect(); // Generate the mesh - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); + let mut mesh = Mesh::new(PrimitiveTopology::TriangleList, Default::default()); mesh.insert_attribute( Mesh::ATTRIBUTE_POSITION, VertexAttributeValues::from(vertices), ); mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, VertexAttributeValues::from(normals)); mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, VertexAttributeValues::from(uvs)); - mesh.set_indices(Some(Indices::U32(indices))); + mesh.insert_indices(Indices::U32(indices)); mesh } diff --git a/src_testbed/plugin.rs b/src_testbed/plugin.rs index 7f19aa9..42fdd17 100644 --- a/src_testbed/plugin.rs +++ b/src_testbed/plugin.rs @@ -14,7 +14,7 @@ pub trait TestbedPlugin { commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<BevyMaterial>, - components: &mut Query<(&mut Transform,)>, + components: &mut Query<&mut Transform>, harness: &mut Harness, ); fn clear_graphics(&mut self, graphics: &mut GraphicsManager, commands: &mut Commands); @@ -26,7 +26,7 @@ pub trait TestbedPlugin { commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<BevyMaterial>, - components: &mut Query<(&mut Transform,)>, + components: &mut Query<&mut Transform>, harness: &mut Harness, ); fn update_ui( @@ -37,7 +37,7 @@ pub trait TestbedPlugin { commands: &mut Commands, meshes: &mut Assets<Mesh>, materials: &mut Assets<BevyMaterial>, - components: &mut Query<(&mut Transform,)>, + components: &mut Query<&mut Transform>, ); fn profiling_string(&self) -> String; } diff --git a/src_testbed/testbed.rs b/src_testbed/testbed.rs index 780e23e..7be4594 100644 --- a/src_testbed/testbed.rs +++ b/src_testbed/testbed.rs @@ -31,8 +31,7 @@ use crate::box2d_backend::Box2dWorld; use crate::harness::Harness; #[cfg(all(feature = "dim3", feature = "other-backends"))] use crate::physx_backend::PhysxWorld; -use bevy::render::camera::Camera; -use bevy_core_pipeline::prelude::ClearColor; +use bevy::render::camera::{Camera, ClearColor}; use bevy_egui::EguiContexts; use bevy_pbr::wireframe::WireframePlugin; use bevy_pbr::AmbientLight; @@ -155,11 +154,11 @@ pub struct TestbedGraphics<'a, 'b, 'c, 'd, 'e, 'f> { commands: &'a mut Commands<'d, 'e>, meshes: &'a mut Assets<Mesh>, materials: &'a mut Assets<BevyMaterial>, - components: &'a mut Query<'b, 'f, (&'c mut Transform,)>, + components: &'a mut Query<'b, 'f, &'c mut Transform>, #[allow(dead_code)] // Dead in 2D but not in 3D. camera_transform: GlobalTransform, camera: &'a mut OrbitCamera, - keys: &'a Input<KeyCode>, + keys: &'a ButtonInput<KeyCode>, } pub struct Testbed<'a, 'b, 'c, 'd, 'e, 'f> { @@ -468,7 +467,7 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> TestbedGraphics<'a, 'b, 'c, 'd, 'e, 'f> { ) } - pub fn keys(&self) -> &Input<KeyCode> { + pub fn keys(&self) -> &ButtonInput<KeyCode> { self.keys } } @@ -660,7 +659,7 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { } #[cfg(feature = "dim3")] - fn update_vehicle_controller(&mut self, events: &Input<KeyCode>) { + fn update_vehicle_controller(&mut self, events: &ButtonInput<KeyCode>) { if self.state.running == RunMode::Stop { return; } @@ -671,16 +670,16 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { for key in events.get_pressed() { match *key { - KeyCode::Right => { + KeyCode::ArrowRight => { steering_angle += -0.7; } - KeyCode::Left => { + KeyCode::ArrowLeft => { steering_angle += 0.7; } - KeyCode::Up => { + KeyCode::ArrowUp => { engine_force += 30.0; } - KeyCode::Down => { + KeyCode::ArrowDown => { engine_force += -30.0; } _ => {} @@ -703,7 +702,7 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { } } - fn update_character_controller(&mut self, events: &Input<KeyCode>) { + fn update_character_controller(&mut self, events: &ButtonInput<KeyCode>) { if self.state.running == RunMode::Stop { return; } @@ -715,10 +714,10 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { #[cfg(feature = "dim2")] for key in events.get_pressed() { match *key { - KeyCode::Right => { + KeyCode::ArrowRight => { desired_movement += Vector::x(); } - KeyCode::Left => { + KeyCode::ArrowLeft => { desired_movement -= Vector::x(); } KeyCode::Space => { @@ -750,16 +749,16 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { for key in events.get_pressed() { match *key { - KeyCode::Right => { + KeyCode::ArrowRight => { desired_movement += rot_x; } - KeyCode::Left => { + KeyCode::ArrowLeft => { desired_movement -= rot_x; } - KeyCode::Up => { + KeyCode::ArrowUp => { desired_movement -= rot_z; } - KeyCode::Down => { + KeyCode::ArrowDown => { desired_movement += rot_z; } KeyCode::Space => { @@ -818,22 +817,22 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { } } - fn handle_common_events(&mut self, events: &Input<KeyCode>) { + fn handle_common_events(&mut self, events: &ButtonInput<KeyCode>) { for key in events.get_just_released() { match *key { - KeyCode::T => { + KeyCode::KeyT => { if self.state.running == RunMode::Stop { self.state.running = RunMode::Running; } else { self.state.running = RunMode::Stop; } } - KeyCode::S => self.state.running = RunMode::Step, - KeyCode::R => self + KeyCode::KeyS => self.state.running = RunMode::Step, + KeyCode::KeyR => self .state .action_flags .set(TestbedActionFlags::EXAMPLE_CHANGED, true), - KeyCode::C => { + KeyCode::KeyC => { // Delete 1 collider of 10% of the remaining dynamic bodies. let mut colliders: Vec<_> = self .harness @@ -859,7 +858,7 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { ); } } - KeyCode::D => { + KeyCode::KeyD => { // Delete 10% of the remaining dynamic bodies. let dynamic_bodies: Vec<_> = self .harness @@ -884,7 +883,7 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { ); } } - KeyCode::J => { + KeyCode::KeyJ => { // Delete 10% of the remaining impulse_joints. let impulse_joints: Vec<_> = self .harness @@ -898,7 +897,7 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { self.harness.physics.impulse_joints.remove(*to_delete, true); } } - KeyCode::A => { + KeyCode::KeyA => { // Delete 10% of the remaining multibody_joints. let multibody_joints: Vec<_> = self .harness @@ -915,7 +914,7 @@ impl<'a, 'b, 'c, 'd, 'e, 'f> Testbed<'a, 'b, 'c, 'd, 'e, 'f> { .remove(*to_delete, true); } } - KeyCode::M => { + KeyCode::KeyM => { // Delete one remaining multibody. let to_delete = self .harness @@ -1013,10 +1012,14 @@ fn draw_contacts(_nf: &NarrowPhase, _colliders: &ColliderSet) { #[cfg(feature = "dim3")] fn setup_graphics_environment(mut commands: Commands) { + commands.insert_resource(AmbientLight { + brightness: 100.0, + ..Default::default() + }); + commands.spawn(DirectionalLightBundle { directional_light: DirectionalLight { - illuminance: 10000.0, - shadows_enabled: true, + shadows_enabled: false, ..Default::default() }, transform: Transform { @@ -1102,9 +1105,10 @@ fn update_testbed( #[cfg(feature = "other-backends")] mut other_backends: NonSendMut<OtherBackends>, mut plugins: NonSendMut<Plugins>, mut ui_context: EguiContexts, - mut gfx_components: Query<(&mut Transform,)>, + mut gfx_components: Query<&mut Transform>, mut cameras: Query<(&Camera, &GlobalTransform, &mut OrbitCamera)>, - keys: Res<Input<KeyCode>>, + mut material_handles: Query<&mut Handle<BevyMaterial>>, + keys: Res<ButtonInput<KeyCode>>, ) { let meshes = &mut *meshes; let materials = &mut *materials; @@ -1448,7 +1452,7 @@ fn update_testbed( if let Ok(window) = windows.get_single() { for (camera, camera_pos, _) in cameras.iter_mut() { highlight_hovered_body( - &mut *materials, + &mut material_handles, &mut graphics, &mut state, &harness.physics, @@ -1502,7 +1506,7 @@ fn clear( #[cfg(feature = "dim2")] fn highlight_hovered_body( - _materials: &mut Assets<BevyMaterial>, + _material_handles: &mut Query<&mut Handle<BevyMaterial>>, _graphics_manager: &mut GraphicsManager, _testbed_state: &mut TestbedState, _physics: &PhysicsState, @@ -1515,7 +1519,7 @@ fn highlight_hovered_body( #[cfg(feature = "dim3")] fn highlight_hovered_body( - materials: &mut Assets<BevyMaterial>, + material_handles: &mut Query<&mut Handle<BevyMaterial>>, graphics_manager: &mut GraphicsManager, testbed_state: &mut TestbedState, physics: &PhysicsState, @@ -1526,7 +1530,9 @@ fn highlight_hovered_body( if let Some(highlighted_body) = testbed_state.highlighted_body { if let Some(nodes) = graphics_manager.body_nodes_mut(highlighted_body) { for node in nodes { - node.unselect(materials) + if let Ok(mut handle) = material_handles.get_mut(node.entity) { + *handle = node.material.clone_weak() + }; } } } @@ -1558,8 +1564,12 @@ fn highlight_hovered_body( if let Some(parent_handle) = collider.parent() { testbed_state.highlighted_body = Some(parent_handle); + let selection_material = graphics_manager.selection_material(); + for node in graphics_manager.body_nodes_mut(parent_handle).unwrap() { - node.select(materials) + if let Ok(mut handle) = material_handles.get_mut(node.entity) { + *handle = selection_material.clone_weak(); + } } } } |
