resource production via graveyard, workers, and selectable buildlings

This commit is contained in:
Jim 2025-08-31 22:26:07 -04:00
parent 87fcc35a49
commit 921947c131
Signed by: jim
GPG key ID: 3D7D94BA53088BF4
20 changed files with 364 additions and 24 deletions

View file

@ -9,6 +9,7 @@ avian3d = { workspace = true }
combat = { path = "../combat" }
state = { path = "../state" }
resources = { path = "../resources" }
input = { path = "../input" }
[lints]
workspace = true

View file

@ -9,6 +9,7 @@ use bevy::{
prelude::*,
};
use combat::{Health, Team};
use input::Selectable;
use resources::{Cost, Resources};
use state::GameSystemSet;
@ -24,7 +25,7 @@ impl Plugin for BuildingPlugin {
}
#[derive(Component)]
#[require(Health, Team::Core, PhysicsPickable)]
#[require(Health, Team::Core, PhysicsPickable, Selectable)]
pub struct Building {
pub level: u32,
pub info: Entity,

View file

@ -12,7 +12,7 @@ use combat::{
projectiles::{Fire, Projectile, ProjectileLauncher, get_shotgun_launch_vectors},
};
use combat_damagers::ContactDamage;
use resources::Cost;
use resources::{Cost, Quantity};
pub struct BuildingBarragerPlugin;
@ -72,7 +72,10 @@ fn register(
size: SIZE,
unlocked: true,
},
Cost { souls: 0, bones: 0 },
Cost(Quantity {
souls: 20,
bones: 20,
}),
Name::new("Barrager"),
));
commands.insert_resource(BuildingResources {

View file

@ -6,7 +6,7 @@ use bevy::prelude::*;
use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{Defense, Health};
use combat_damagers::ContactDamage;
use resources::Cost;
use resources::{Cost, Quantity};
pub struct BuildingImpalerPlugin;
@ -62,7 +62,7 @@ fn register(
size: SIZE,
unlocked: true,
},
Cost { souls: 5, bones: 0 },
Cost(Quantity { souls: 5, bones: 0 }),
Name::new("Impaler"),
));
commands.insert_resource(ImpalerResources {

View file

@ -4,7 +4,7 @@
use bevy::prelude::*;
use building::{BuildingInfo, BuildingPreview, PlaceBuilding, PlacedBuildings};
use input::{Cancellable, Inputs, actions::InputAction};
use input::{Cancellable, Inputs, Selected, actions::InputAction};
use physics::Ground;
pub struct BuildingPlacementPlugin;
@ -37,9 +37,10 @@ fn init(mut commands: Commands, query: Single<Entity, With<Ground>>, mut setup:
fn cancel_preview(
mut writer: EventWriter<SelectBuildingPreview>,
query: Query<(), (With<ActiveBuildingPreview>, With<Cancellable>)>,
selected: Query<(), With<Selected>>,
inputs: Res<Inputs<Update>>,
) {
if !query.is_empty() && inputs.just_pressed(InputAction::Cancel) {
if !query.is_empty() && (inputs.just_pressed(InputAction::Cancel) || !selected.is_empty()) {
writer.write(SelectBuildingPreview(None));
}
}

View file

@ -210,7 +210,6 @@ fn on_die(
) {
if let Ok(drop) = drops.get(trigger.target()) {
resources.souls += drop.souls;
info!("you now have {} souls", resources.souls);
}
if let Ok(mut ec) = commands.get_entity(trigger.target()) {
info!(

View file

@ -5,6 +5,7 @@ edition = "2024"
[dependencies]
bevy = { workspace = true }
avian3d = { workspace = true }
serde = { workspace = true }
ron = { workspace = true }
state = { path = "../state" }

View file

@ -7,6 +7,7 @@ pub mod conditions;
use std::{fs, marker::PhantomData};
use avian3d::prelude::*;
use bevy::{
input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll},
platform::collections::HashMap,
@ -22,21 +23,93 @@ pub struct InputPlugin;
impl Plugin for InputPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Inputs<FixedUpdate>>()
app.add_event::<SelectEntity>()
.init_resource::<Inputs<FixedUpdate>>()
.init_resource::<Inputs<Update>>()
.configure_sets(Update, GameSystemSet::UpdateInputs)
.add_systems(Startup, setup_input_map)
.add_systems(
Update,
(update_inputs_frame, save_input_map).in_set(GameSystemSet::UpdateInputs),
(
update_inputs_frame,
save_input_map,
(cancel_selection, update_selection).chain(),
)
.in_set(GameSystemSet::UpdateInputs),
)
.add_systems(FixedPostUpdate, clear_changed_fixed);
.add_systems(FixedPostUpdate, clear_changed_fixed)
.add_observer(select);
}
}
#[derive(Component)]
pub struct Cancellable;
#[derive(Component, Default)]
pub struct Selectable;
#[derive(Component)]
pub struct Selected;
#[derive(Event)]
pub struct SelectEntity(pub Option<Entity>);
fn cancel_selection(
mut writer: EventWriter<SelectEntity>,
query: Query<(), (With<Selected>, With<Cancellable>)>,
inputs: Res<Inputs<Update>>,
) {
if !query.is_empty() && inputs.just_pressed(InputAction::Cancel) {
writer.write(SelectEntity(None));
}
}
fn select(
trigger: Trigger<Pointer<Click>>,
physics_query: Query<(), With<PhysicsPickable>>,
mut writer: EventWriter<SelectEntity>,
) {
// avoid deselecting when clicking on ui
if physics_query.contains(trigger.event().target) {
writer.write(SelectEntity(Some(trigger.event().target)));
}
}
fn update_selection(
mut reader: EventReader<SelectEntity>,
mut old_query: Query<Entity, With<Selected>>,
new_query: Query<(), With<Selectable>>,
name_query: Query<&Name>,
mut commands: Commands,
) {
let Some(SelectEntity(opt_entity)) = reader.read().last() else {
return;
};
let Some(new_entity) = opt_entity else {
for entity in old_query.iter_mut() {
if *opt_entity != Some(entity) {
commands.entity(entity).remove::<(Selected, Cancellable)>();
}
}
return;
};
if !new_query.contains(*new_entity) {
info!(
"thing is not selectable {:?} {:?}",
new_entity,
name_query.get(*new_entity)
);
return;
}
for entity in old_query.iter_mut() {
if *opt_entity != Some(entity) {
commands.entity(entity).remove::<(Selected, Cancellable)>();
}
}
commands.entity(*new_entity).insert((Selected, Cancellable));
}
#[derive(Hash, Clone, Copy, Debug, Reflect, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputMethod {
Unbound,

View file

@ -14,6 +14,7 @@ combat = { path = "../combat" }
physics = { path = "../physics" }
building = { path = "../building" }
inhabitant_coranth = { path = "../inhabitant_coranth" }
resource_graveyard = { path = "../resource_graveyard" }
[lints]
workspace = true

View file

@ -16,6 +16,7 @@ use building::{BuildingTypes, PlaceBuilding};
use camera::ControlledCamera;
use inhabitant_coranth::SpawnCoranth;
use physics::{Ground, PhysicsLayers};
use resource_graveyard::PlaceGraveyard;
use state::{AppState, GameSystemSet};
pub struct LevelPlugin;
@ -34,6 +35,7 @@ fn setup(
buildings: Res<BuildingTypes>,
mut place_writer: EventWriter<PlaceBuilding>,
mut coranth_writer: EventWriter<SpawnCoranth>,
mut graveyard_writer: EventWriter<PlaceGraveyard>,
) {
let level_size = 50.0;
// Static physics object with a collision shape
@ -50,6 +52,7 @@ fn setup(
CollisionLayers::new(PhysicsLayers::Ground, LayerMask::ALL),
PhysicsPickable,
Ground,
Name::new("ground"),
));
for y in 5..15 {
@ -57,6 +60,9 @@ fn setup(
transform: Transform::from_xyz(y as f32 * 0.25, y as f32 * 1.1, 0.0),
});
}
graveyard_writer.write(PlaceGraveyard(Vec3::new(-10., 0.25, -10.)));
place_writer.write(PlaceBuilding {
info: buildings.info.get("Core").unwrap().0,
location: IVec3 { x: 5, y: 0, z: 5 },
@ -72,6 +78,11 @@ fn setup(
},
Transform::from_xyz(-2.5, 4.5, 2.5).looking_at(Vec3::ZERO, Dir3::Y),
));
commands.insert_resource(AmbientLight {
brightness: lux::AMBIENT_DAYLIGHT,
color: Color::srgb(0.98, 0.95, 0.82),
..default()
});
// Camera
commands.spawn((

View file

@ -0,0 +1,15 @@
[package]
name = "resource_graveyard"
version = "0.1.0"
edition = "2024"
[dependencies]
bevy = { workspace = true }
avian3d = {workspace = true }
state = { path = "../state" }
resources = { path = "../resources" }
input = { path = "../input" }
[lints]
workspace = true

View file

@ -0,0 +1,81 @@
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use std::time::Duration;
use avian3d::prelude::{Collider, PhysicsPickable, RigidBody, Sensor};
use bevy::prelude::*;
use input::Selectable;
use resources::{Quantity, ResourceDeposit};
use state::GameSystemSet;
pub struct ResourceGraveyardPlugin;
impl Plugin for ResourceGraveyardPlugin {
fn build(&self, app: &mut App) {
app.add_event::<PlaceGraveyard>()
.add_systems(Startup, init)
.add_systems(FixedUpdate, spawn.in_set(GameSystemSet::PostTick));
}
}
#[derive(Component)]
pub struct Graveyard;
#[derive(Event)]
pub struct PlaceGraveyard(pub Vec3);
#[derive(Resource)]
struct GraveyardResources {
mesh: Handle<Mesh>,
material: Handle<StandardMaterial>,
}
const SIZE: Vec3 = Vec3::new(2.0, 0.5, 2.0);
fn init(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let mesh = meshes.add(Cuboid::from_size(SIZE));
let base_material = StandardMaterial {
base_color: Color::srgb_u8(0xff, 0xe2, 0xe2),
metallic: 0.2,
perceptual_roughness: 0.8,
..default()
};
let material = materials.add(base_material);
commands.insert_resource(GraveyardResources {
mesh: mesh,
material: material,
});
}
fn spawn(
mut reader: EventReader<PlaceGraveyard>,
mut commands: Commands,
res: Res<GraveyardResources>,
) {
for PlaceGraveyard(dest) in reader.read() {
commands.spawn((
Graveyard,
Transform::from_translation(*dest),
ResourceDeposit {
bounty: Quantity { souls: 0, bones: 5 },
level: 0,
harvest_time: Duration::from_secs(5),
},
Mesh3d(res.mesh.clone()),
MeshMaterial3d(res.material.clone()),
Sensor,
RigidBody::Static,
Collider::cuboid(SIZE.x, SIZE.y, SIZE.z),
PhysicsPickable,
Selectable,
Name::new("Graveyard"),
));
}
}

View file

@ -2,14 +2,19 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use std::time::Duration;
use bevy::prelude::*;
use state::AppState;
use state::{AppState, GameSystemSet};
pub struct ResourcesPlugin;
impl Plugin for ResourcesPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Game), setup);
app.add_systems(OnEnter(AppState::Game), setup)
.add_systems(FixedUpdate, tick_harvest.in_set(GameSystemSet::Execute))
.insert_resource(AvailableWorkers(5))
.add_observer(on_harvest);
}
}
@ -38,14 +43,32 @@ impl Resources {
self.bones = self.bones.saturating_sub(cost.bones);
true
}
pub fn add(&mut self, quantity: Quantity) {
self.souls = self.souls.saturating_add(quantity.souls);
self.bones = self.bones.saturating_add(quantity.bones);
}
}
#[derive(Component, Default)]
pub struct Cost {
#[derive(Component, Default, Deref, DerefMut)]
pub struct Cost(pub Quantity);
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Quantity {
pub souls: u32,
pub bones: u32,
}
impl std::ops::Mul<u32> for Quantity {
type Output = Quantity;
fn mul(self, rhs: u32) -> Self::Output {
Self {
souls: self.souls.saturating_mul(rhs),
bones: self.bones.saturating_mul(rhs),
}
}
}
#[derive(Component)]
pub struct Drops {
pub souls: u32,
@ -56,3 +79,52 @@ impl Default for Drops {
Self { souls: 1 }
}
}
#[derive(Component, Default)]
#[require(Transform, Name)]
pub struct ResourceDeposit {
pub bounty: Quantity,
pub level: u32,
pub harvest_time: Duration,
// todo - add finite resources and refresh timer
}
#[derive(Component, Default)]
#[require(ResourceDeposit)]
pub struct WorkedResourceDeposit {
pub workers: u32,
pub worked_duration: Duration,
}
#[derive(Event)]
pub struct Harvested;
fn tick_harvest(
mut commands: Commands,
mut deposit_query: Query<(Entity, &ResourceDeposit, &mut WorkedResourceDeposit)>,
time: Res<Time>,
) {
let delta = time.delta();
for (entity, deposit, mut worked) in deposit_query.iter_mut() {
worked.worked_duration += delta;
if worked.worked_duration >= deposit.harvest_time {
commands.trigger_targets(Harvested, entity);
worked.worked_duration -= deposit.harvest_time;
}
}
}
fn on_harvest(
trigger: Trigger<Harvested>,
deposit_query: Query<(&ResourceDeposit, &WorkedResourceDeposit)>,
mut resources: ResMut<Resources>,
) {
let Ok((deposit, worked)) = deposit_query.get(trigger.target()) else {
error!("harvested something that was not a resource deposit or not worked OwO");
return;
};
resources.add(deposit.bounty * worked.workers);
}
#[derive(Resource)]
pub struct AvailableWorkers(pub u32);

View file

@ -2,7 +2,7 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use avian3d::prelude::*;
// use avian3d::prelude::*;
use bevy::prelude::*;
use bevy_inspector_egui::quick::WorldInspectorPlugin;
use input::{actions::InputAction, conditions::action_just_pressed};
@ -14,7 +14,7 @@ impl Plugin for UiDebugPlugin {
fn build(&self, app: &mut App) {
app.init_state::<DebugUIState>()
.add_plugins(WorldInspectorPlugin::new().run_if(in_state(DebugUIState::Enabled)))
.add_plugins(PhysicsDebugPlugin::default())
// .add_plugins(PhysicsDebugPlugin::default())
.add_systems(
Update,
toggle_debug_ui

View file

@ -10,6 +10,7 @@ bevy_egui = { workspace = true }
ui_state = { path = "../ui_state" }
resources = { path = "../resources" }
building = { path = "../building" }
input = { path = "../input" }
building_placement = { path = "../building_placement" }
[lints]

View file

@ -9,7 +9,8 @@ use bevy_egui::{
};
use building::BuildingInfo;
use building_placement::SelectBuildingPreview;
use resources::{Cost, Resources};
use input::{SelectEntity, Selected};
use resources::{AvailableWorkers, Cost, ResourceDeposit, Resources, WorkedResourceDeposit};
use ui_state::GameUIState;
pub struct UiIngamePlugin;
@ -25,9 +26,14 @@ impl Plugin for UiIngamePlugin {
fn resource_ui(
mut contexts: EguiContexts,
mut commands: Commands,
resources: Res<Resources>,
mut available_workers: ResMut<AvailableWorkers>,
buildings: Query<(&BuildingInfo, &Cost, &Name)>,
mut select_writer: EventWriter<SelectBuildingPreview>,
selected: Query<(Entity, &Name), With<Selected>>,
mut selected_resource_deposit: Query<(&ResourceDeposit, Option<&mut WorkedResourceDeposit>)>,
mut selected_preview_writer: EventWriter<SelectBuildingPreview>,
mut select_writer: EventWriter<SelectEntity>,
) {
let ctx = contexts.ctx_mut().unwrap();
let large_font_size = 24.;
@ -38,6 +44,62 @@ fn resource_ui(
.title_bar(false)
.anchor(Align2::RIGHT_TOP, [0., 0.])
.show(ctx, |ui| {
if let Ok((selected, selected_name)) = selected.single() {
if ui.button("x").clicked() {
select_writer.write(SelectEntity(None));
}
ui.heading(selected_name.as_str());
if let Ok((deposit, mut opt_worked)) = selected_resource_deposit.get_mut(selected) {
ui.label(
RichText::new(format!("Level {} deposit", deposit.level)).size(font_size),
);
ui.heading(
RichText::new(if let Some(ref worked) = opt_worked {
format!("{} workers", worked.workers)
} else {
"Not worked".to_string()
})
.size(large_font_size)
.underline(),
);
// worker management buttons
// add
if available_workers.0 == 0 {
ui.add_enabled(false, egui::Button::new("No workers available"));
} else {
if ui.button("Add worker").clicked() {
available_workers.0 = available_workers.0.saturating_sub(1);
if let Some(ref mut worked) = opt_worked {
worked.workers = worked.workers.saturating_add(1);
} else {
commands.entity(selected).insert(WorkedResourceDeposit {
workers: 1,
..default()
});
}
}
}
// remove
if let Some(ref mut worked) = opt_worked {
if ui.button("Remove worker").clicked() {
worked.workers = worked.workers.saturating_sub(1);
available_workers.0 = available_workers.0.saturating_add(1);
if worked.workers == 0 {
commands.entity(selected).remove::<WorkedResourceDeposit>();
}
}
}
ui.heading(RichText::new("Bounty").underline());
ui.label(
RichText::new(format!("Souls: {}", deposit.bounty.souls)).size(font_size),
);
ui.label(
RichText::new(format!("Bones: {}", deposit.bounty.bones)).size(font_size),
);
}
return;
}
ui.label(RichText::new(format!("Souls: {}", resources.souls)).size(large_font_size));
ui.label(RichText::new(format!("Bones: {}", resources.bones)).size(large_font_size));
ui.heading(RichText::new("Buildings").underline());
@ -72,7 +134,7 @@ fn resource_ui(
)
.clicked()
{
select_writer.write(SelectBuildingPreview(Some(info.preview)));
selected_preview_writer.write(SelectBuildingPreview(Some(info.preview)));
}
}
});