From 9c4787f5e2e34c76a8cff8c50ec52605f36c96e5 Mon Sep 17 00:00:00 2001 From: Jim Date: Mon, 1 Sep 2025 17:52:21 -0400 Subject: [PATCH] rework building placement to use physics system --- assets/settings/input_map.ron | 8 +- crates/building/src/lib.rs | 141 +++++++-------------------- crates/building_placement/src/lib.rs | 26 +++-- 3 files changed, 53 insertions(+), 122 deletions(-) diff --git a/assets/settings/input_map.ron b/assets/settings/input_map.ron index 03d50a5..ed21f50 100755 --- a/assets/settings/input_map.ron +++ b/assets/settings/input_map.ron @@ -1,7 +1,7 @@ ( map: { - KeyCode(ShiftLeft): [ - MultiPlaceTower, + MouseButton(Middle): [ + CameraOrbitEnable, ], MouseButton(Right): [ PlaceTower, @@ -9,8 +9,8 @@ MouseButton(Left): [ CameraPanEnable, ], - MouseButton(Middle): [ - CameraOrbitEnable, + KeyCode(ShiftLeft): [ + MultiPlaceTower, ], MouseScroll: [ CameraZoom, diff --git a/crates/building/src/lib.rs b/crates/building/src/lib.rs index 4325ddc..53ad324 100755 --- a/crates/building/src/lib.rs +++ b/crates/building/src/lib.rs @@ -20,7 +20,6 @@ pub struct BuildingPlugin; impl Plugin for BuildingPlugin { fn build(&self, app: &mut App) { app.init_resource::() - .init_resource::() .add_event::() .add_systems(FixedUpdate, place_building.in_set(GameSystemSet::PostTick)); } @@ -33,30 +32,6 @@ pub struct Building { pub info: Entity, } -#[derive(Component)] -#[component(on_remove = on_building_removed)] -struct BuildingPosition(IVec3); - -fn on_building_removed(mut world: DeferredWorld, context: HookContext) { - let (info, location) = world - .get_entity(context.entity) - .map(|e| { - ( - e.components::<&Building>().info, - e.components::<&BuildingPosition>().0, - ) - }) - .unwrap(); - let size = world - .get_entity(info) - .unwrap() - .components::<&BuildingInfo>() - .size; - world - .resource_mut::() - .remove_building(location, size); -} - #[derive(Component, Clone)] #[require(Name, Cost, UpgradeTree)] #[component(on_add = register_building_info)] @@ -68,6 +43,15 @@ pub struct BuildingInfo { pub unlocked: bool, } +impl BuildingInfo { + pub fn get_placed_collider_and_position(&self, pos: Vec3) -> (Collider, Vec3) { + let size_v3 = self.size.as_vec3(); + let collider = Collider::cuboid(size_v3.x, size_v3.y, size_v3.z); + let position = pos + Vec3::new(0., size_v3.y / 2., 0.); + (collider, position) + } +} + #[derive(Component)] pub struct BuildingPreview { pub info: Entity, @@ -114,76 +98,6 @@ pub struct PlacedBuilding { pub instance: Entity, } -#[derive(Resource, Default)] -pub struct PlacedBuildings { - pub map: HashMap, -} - -impl PlacedBuildings { - // todo - update these to account for building being in the center - pub fn placement_valid(&self, location: IVec3, info: &BuildingInfo) -> bool { - for x in 0..info.size.x { - for y in 0..info.size.y { - for z in 0..info.size.z { - if self - .map - .contains_key(&(location + IVec3::new(x as i32, y as i32, z as i32))) - { - //shouldn't happen - return false; - } - } - } - } - return true; - } - - fn place_building( - &mut self, - location: IVec3, - info: &BuildingInfo, - info_entity: Entity, - instance_entity: Entity, - ) { - for x in 0..info.size.x { - for y in 0..info.size.y { - for z in 0..info.size.z { - if self - .map - .insert( - location + IVec3::new(x as i32, y as i32, z as i32), - PlacedBuilding { - info: info_entity, - instance: instance_entity, - }, - ) - .is_some() - { - //shouldn't happen - error!("placed building on old building!!! RIP"); - } - } - } - } - } - fn remove_building(&mut self, location: IVec3, size: UVec3) { - for x in 0..size.x { - for y in 0..size.y { - for z in 0..size.z { - if self - .map - .remove(&(location + IVec3::new(x as i32, y as i32, z as i32))) - .is_none() - { - //shouldn't happen - error!("removed building where there wasn't one!!!! RIP"); - } - } - } - } - } -} - #[derive(Event)] pub struct PlaceBuilding { pub info: Entity, @@ -195,12 +109,31 @@ pub struct PopulatePlacedBuilding { pub info: Entity, } +pub fn valid_placement( + spatial_query: &SpatialQuery, + collider_query: &Query<&Building>, + size: Vec3, + position: Vec3, +) -> bool { + !spatial_query + .shape_intersections( + // shrink the collider a bit to allow for buildings right next to each other + &Collider::cuboid(size.x - 0.1, size.y - 0.1, size.z - 0.1), + position, + Quat::IDENTITY, + &SpatialQueryFilter::from_mask(Team::Core.collision_layers().memberships), + ) + .iter() + .any(|b| collider_query.contains(*b)) +} + fn place_building( mut reader: EventReader, - mut building_map: ResMut, mut commands: Commands, mut resources: ResMut, info_query: Query<(&BuildingInfo, &Cost, &Name), With>, + building_query: Query<&Building>, + spatial_query: SpatialQuery, ) { for PlaceBuilding { info: info_entity, @@ -211,25 +144,26 @@ fn place_building( error!("tried to place building without info or required components!"); continue; }; - if !building_map.placement_valid(*location, info) { - error!("invalid building placement at {:?}, rejecting", location); - continue; - } if !resources.buy(&cost) { info!("not enough money to buy tower!"); continue; } let size_v3 = info.size.as_vec3(); + let (collider, position) = info.get_placed_collider_and_position(location.as_vec3()); + if !valid_placement(&spatial_query, &building_query, size_v3, position) { + error!("tried to place building colliding with other building"); + continue; + } + let instance = commands .spawn(( // adjust model up slightly so base of all towers are aligned - Transform::from_translation(location.as_vec3() + Vec3::new(0., size_v3.y / 2., 0.)), + Transform::from_translation(position), Building { level: 0, info: *info_entity, }, - BuildingPosition(*location), - Collider::cuboid(size_v3.x, size_v3.y, size_v3.z), + collider, Mesh3d::default(), name.clone(), RigidBody::Static, @@ -242,7 +176,6 @@ fn place_building( }, )) .id(); - building_map.place_building(*location, info, *info_entity, instance); commands.trigger_targets(PopulatePlacedBuilding { info: *info_entity }, instance); } diff --git a/crates/building_placement/src/lib.rs b/crates/building_placement/src/lib.rs index b66d898..bee063b 100644 --- a/crates/building_placement/src/lib.rs +++ b/crates/building_placement/src/lib.rs @@ -2,8 +2,9 @@ #![allow(clippy::type_complexity)] #![allow(clippy::too_many_arguments)] +use avian3d::prelude::SpatialQuery; use bevy::prelude::*; -use building::{BuildingInfo, BuildingPreview, PlaceBuilding, PlacedBuildings}; +use building::{Building, BuildingInfo, BuildingPreview, PlaceBuilding, valid_placement}; use input::{Cancellable, Inputs, Selected, actions::InputAction}; use physics::Ground; @@ -49,7 +50,8 @@ fn move_preview( trigger: Trigger>, preview: Single<(&mut Transform, &mut ActiveBuildingPreview, &BuildingPreview)>, info_query: Query<&BuildingInfo>, - placed_buildings: Res, + building_query: Query<&Building>, + spatial_query: SpatialQuery, ) { let Some(dest) = trigger.event().hit.position else { return; @@ -61,20 +63,24 @@ fn move_preview( }; // center mouse on building let loc = dest.round(); - if !placed_buildings.placement_valid(loc.as_ivec3(), info) { + let (_, position) = info.get_placed_collider_and_position(loc); + if !valid_placement( + &spatial_query, + &building_query, + info.size.as_vec3(), + position, + ) { info!("invalid placement!!!!!"); return; } active.0 = loc.as_ivec3(); - tf.translation = loc + Vec3::Y * info.size.y as f32 / 2.; + tf.translation = position; } fn place_preview( _trigger: Trigger>, inputs: Res>, query: Single<(&BuildingPreview, &ActiveBuildingPreview)>, - info_query: Query<&BuildingInfo>, - placed_buildings: Res, mut place_writer: EventWriter, mut select_writer: EventWriter, ) { @@ -82,14 +88,6 @@ fn place_preview( return; } let (preview, active) = query.into_inner(); - let Ok(info) = info_query.get(preview.info) else { - error!("building preview has no associated info!"); - return; - }; - if !placed_buildings.placement_valid(active.0, info) { - info!("invalid placement!!!!!"); - return; - } if !inputs.pressed(InputAction::MultiPlaceTower) { select_writer.write(SelectBuildingPreview(None)); }