diff --git a/Cargo.lock b/Cargo.lock index be4fd50..23fa29d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1687,6 +1687,15 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "camera" +version = "0.1.0" +dependencies = [ + "bevy", + "input", + "state", +] + [[package]] name = "cc" version = "1.2.34" @@ -1897,7 +1906,9 @@ version = "0.1.0" dependencies = [ "bevy", "bevy-inspector-egui", + "camera", "input", + "level", "physics", "setup", "state", @@ -2923,6 +2934,16 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +[[package]] +name = "level" +version = "0.1.0" +dependencies = [ + "avian3d", + "bevy", + "camera", + "state", +] + [[package]] name = "lewton" version = "0.10.2" diff --git a/Cargo.toml b/Cargo.toml index f2ff88e..32aee5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,4 +40,6 @@ input = { path = "crates/input" } ui = { path = "crates/ui" } setup = { path = "crates/setup" } ui_pause = { path = "crates/ui_pause" } +level = { path = "crates/level" } +camera = { path = "crates/camera" } #new internal crates go here diff --git a/assets/settings/input_map.ron b/assets/settings/input_map.ron index 44cb22c..2c24da8 100644 --- a/assets/settings/input_map.ron +++ b/assets/settings/input_map.ron @@ -1,6 +1,26 @@ ( map: { - KeyCode(F1): ToggleDebugUI, - KeyCode(KeyA): TogglePause, + KeyCode(F1): [ + ToggleDebugUI, + ], + MouseScroll: [ + CameraZoom, + ], + MouseMovementX: [ + CameraYaw, + CameraPanX, + ], + MouseMovementY: [ + CameraPanY, + ], + KeyCode(Escape): [ + TogglePause, + ], + MouseButton(Left): [ + CameraPanEnable, + ], + MouseButton(Middle): [ + CameraOrbitEnable, + ], }, ) \ No newline at end of file diff --git a/crates/camera/Cargo.toml b/crates/camera/Cargo.toml new file mode 100644 index 0000000..10e61cd --- /dev/null +++ b/crates/camera/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "camera" +version = "0.1.0" +edition = "2024" + +[dependencies] +bevy = { workspace = true } + +input = { path = "../input" } +state = { path = "../state" } + +[lints] +workspace = true diff --git a/crates/camera/src/lib.rs b/crates/camera/src/lib.rs new file mode 100644 index 0000000..f5a6b90 --- /dev/null +++ b/crates/camera/src/lib.rs @@ -0,0 +1,104 @@ +//bevy system signatures often violate these rules +#![allow(clippy::type_complexity)] +#![allow(clippy::too_many_arguments)] + +use bevy::prelude::*; +use input::{Inputs, actions::InputAction, conditions::action_pressed}; +use state::GameSystemSet; + +pub struct CameraPlugin; + +impl Plugin for CameraPlugin { + fn build(&self, app: &mut App) { + app.init_resource::().add_systems( + Update, + ( + orbit.run_if(action_pressed::(InputAction::CameraOrbitEnable)), + zoom, + pan.run_if(action_pressed::(InputAction::CameraPanEnable)), + update_camera, + ) + .in_set(GameSystemSet::Update) + .chain(), + ); + } +} + +#[derive(Component, Default)] +pub struct ControlledCamera { + pub target: Vec3, +} + +#[derive(Debug, Resource)] +struct CameraState { + zoom_speed: f32, + zoom_distance_mult: f32, + distance: f32, + min_distance: f32, + max_distance: f32, + yaw_speed: f32, + pan_speed: f32, + pan_zoom_mult: f32, +} + +impl Default for CameraState { + fn default() -> Self { + Self { + distance: 20.0, + min_distance: 1.0, + max_distance: 100.0, + zoom_speed: 1., + zoom_distance_mult: 0.1, + yaw_speed: 0.004, + pan_speed: 0.01, + pan_zoom_mult: 0.1, + } + } +} + +fn update_camera(query: Single<(&mut Transform, &ControlledCamera)>, state: ResMut) { + let (mut camera, ControlledCamera { target }) = query.into_inner(); + + camera.translation = *target - camera.forward().as_vec3() * state.distance; +} + +fn zoom(inputs: Res>, mut state: ResMut) { + let input = -inputs.get(InputAction::CameraZoom); + let delta_zoom = input * state.zoom_speed + + input * state.zoom_speed * state.zoom_distance_mult * state.distance; + state.distance = (state.distance + delta_zoom).clamp(state.min_distance, state.max_distance); +} + +fn orbit( + mut camera: Single<&mut Transform, With>, + camera_settings: Res, + inputs: Res>, +) { + let delta_yaw = -inputs.get(InputAction::CameraYaw) * camera_settings.yaw_speed; + + let (yaw, pitch, roll) = camera.rotation.to_euler(EulerRot::YXZ); + + let yaw = yaw + delta_yaw; + camera.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll); +} + +fn pan( + inputs: Res>, + state: Res, + query: Single<(&Transform, &mut ControlledCamera)>, +) { + let pan_speed = state.pan_speed + state.pan_speed * state.pan_zoom_mult * state.distance; + let delta = Vec2::new( + inputs.get(InputAction::CameraPanX), + inputs.get(InputAction::CameraPanY), + ); + + let (tf, mut camera) = query.into_inner(); + + let projected_left = Vec3::new(tf.left().x, 0.0, tf.left().z).normalize(); + let vx = projected_left * delta.x; + let projected_forward = Vec3::new(tf.forward().x, 0.0, tf.forward().z).normalize(); + let vy = projected_forward * delta.y; + + camera.target += (vx + vy) * pan_speed; +} diff --git a/crates/input/src/actions.rs b/crates/input/src/actions.rs index 88632fb..fceabff 100644 --- a/crates/input/src/actions.rs +++ b/crates/input/src/actions.rs @@ -1,4 +1,4 @@ -use bevy::{platform::collections::HashMap, prelude::*}; +use bevy::prelude::*; use serde::{Deserialize, Serialize}; use crate::{InputMap, InputMethod}; @@ -7,21 +7,37 @@ use crate::{InputMap, InputMethod}; pub enum InputAction { ToggleDebugUI, TogglePause, + CameraZoom, + CameraYaw, + CameraPanX, + CameraPanY, + CameraPanEnable, + CameraOrbitEnable, } impl Default for InputMap { fn default() -> Self { - Self { - map: HashMap::from_iter(vec![ - ( - InputMethod::KeyCode(KeyCode::F1), - InputAction::ToggleDebugUI, - ), - ( - InputMethod::KeyCode(KeyCode::Escape), - InputAction::TogglePause, - ), - ]), - } + Self::from_iter(vec![ + ( + InputMethod::KeyCode(KeyCode::F1), + InputAction::ToggleDebugUI, + ), + ( + InputMethod::KeyCode(KeyCode::Escape), + InputAction::TogglePause, + ), + (InputMethod::MouseMovementX, InputAction::CameraYaw), + (InputMethod::MouseScroll, InputAction::CameraZoom), + ( + InputMethod::MouseButton(MouseButton::Middle), + InputAction::CameraOrbitEnable, + ), + (InputMethod::MouseMovementX, InputAction::CameraPanX), + (InputMethod::MouseMovementY, InputAction::CameraPanY), + ( + InputMethod::MouseButton(MouseButton::Left), + InputAction::CameraPanEnable, + ), + ]) } } diff --git a/crates/input/src/lib.rs b/crates/input/src/lib.rs index c43c723..1e48d18 100644 --- a/crates/input/src/lib.rs +++ b/crates/input/src/lib.rs @@ -7,7 +7,11 @@ pub mod conditions; use std::{fs, marker::PhantomData}; -use bevy::{input::mouse::AccumulatedMouseMotion, platform::collections::HashMap, prelude::*}; +use bevy::{ + input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll}, + platform::collections::HashMap, + prelude::*, +}; use ron::ser::PrettyConfig; use serde::{Deserialize, Serialize}; use state::GameSystemSet; @@ -32,18 +36,31 @@ impl Plugin for InputPlugin { #[derive(Hash, Clone, Copy, Debug, Reflect, PartialEq, Eq, Serialize, Deserialize)] pub enum InputMethod { + Unbound, MouseButton(MouseButton), KeyCode(KeyCode), + MouseScroll, MouseMovementX, MouseMovementY, } #[derive(Resource, Serialize, Deserialize)] pub struct InputMap { - pub map: HashMap, + pub map: HashMap>, } impl InputMap { + pub fn from_iter(iter: I) -> Self + where + I: IntoIterator, + { + let mut map: HashMap> = HashMap::new(); + for (method, action) in iter { + map.entry(method).or_insert_with(Vec::new).push(action); + } + Self { map } + } + fn save_to_file(&self, path: &str) -> Result<()> { let json = ron::ser::to_string_pretty(self, PrettyConfig::default())?; fs::write(path, json)?; @@ -122,6 +139,7 @@ fn update_inputs_frame( input_map: Res, mouse_movement: Res, mouse_buttons: Res>, + mouse_scroll: Res, keyboard: Res>, ) { fn set_value(action: &InputAction, value: f32, map: &mut HashMap) { @@ -143,37 +161,49 @@ fn update_inputs_frame( for input in frame_inputs.map.values_mut() { input.changed = false; } - for (method, action) in input_map.map.iter() { - match method { - InputMethod::MouseButton(mouse_button) => { - let value = if mouse_buttons.pressed(*mouse_button) { - 1.0 - } else { - -1.0 - }; - set_value(action, value, &mut frame_inputs.map); - set_value(action, value, &mut fixed_inputs.map); - } - InputMethod::KeyCode(key_code) => { - let value = if keyboard.pressed(*key_code) { - 1.0 - } else { - -1.0 - }; - set_value(action, value, &mut frame_inputs.map); - set_value(action, value, &mut fixed_inputs.map); - } - InputMethod::MouseMovementX => { - let value = mouse_movement.delta.x; - set_value(action, value, &mut frame_inputs.map); - // want to get accumulated mouse movement in here if needed - add_value(action, value, &mut fixed_inputs.map); - } - InputMethod::MouseMovementY => { - let value = mouse_movement.delta.y; - set_value(action, value, &mut frame_inputs.map); - // want to get accumulated mouse movement in here if needed - add_value(action, value, &mut fixed_inputs.map); + for (method, actions) in input_map.map.iter() { + for action in actions.iter() { + match method { + InputMethod::Unbound => { + set_value(action, 0., &mut frame_inputs.map); + set_value(action, 0., &mut fixed_inputs.map); + } + InputMethod::MouseButton(mouse_button) => { + let value = if mouse_buttons.pressed(*mouse_button) { + 1.0 + } else { + -1.0 + }; + set_value(action, value, &mut frame_inputs.map); + set_value(action, value, &mut fixed_inputs.map); + } + InputMethod::KeyCode(key_code) => { + let value = if keyboard.pressed(*key_code) { + 1.0 + } else { + -1.0 + }; + set_value(action, value, &mut frame_inputs.map); + set_value(action, value, &mut fixed_inputs.map); + } + InputMethod::MouseScroll => { + let value = mouse_scroll.delta.y; + set_value(action, value, &mut frame_inputs.map); + // want to get accumulated mouse movement in here if needed + add_value(action, value, &mut fixed_inputs.map); + } + InputMethod::MouseMovementX => { + let value = mouse_movement.delta.x; + set_value(action, value, &mut frame_inputs.map); + // want to get accumulated mouse movement in here if needed + add_value(action, value, &mut fixed_inputs.map); + } + InputMethod::MouseMovementY => { + let value = mouse_movement.delta.y; + set_value(action, value, &mut frame_inputs.map); + // want to get accumulated mouse movement in here if needed + add_value(action, value, &mut fixed_inputs.map); + } } } } @@ -199,8 +229,15 @@ fn save_input_map(input_map: Res) { fn setup_input_map(mut commands: Commands) { let input_map = match InputMap::load_from_file(INPUT_MAP_PATH) { - Ok(map) => { + Ok(mut map) => { info!("Loaded input map"); + + for (key, value) in InputMap::default().map { + if !map.map.values().any(|v| *v == value) { + info!("missing action {:?}, adding default", value); + map.map.insert(key, value); + } + } map } Err(e) => { diff --git a/crates/level/Cargo.toml b/crates/level/Cargo.toml new file mode 100644 index 0000000..d6007fc --- /dev/null +++ b/crates/level/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "level" +version = "0.1.0" +edition = "2024" + +[dependencies] +bevy = { workspace = true } +state = { path = "../state" } +camera = { path = "../camera" } +avian3d = { workspace = true } + +[lints] +workspace = true diff --git a/crates/level/src/lib.rs b/crates/level/src/lib.rs new file mode 100644 index 0000000..450e9ed --- /dev/null +++ b/crates/level/src/lib.rs @@ -0,0 +1,85 @@ +//bevy system signatures often violate these rules +#![allow(clippy::type_complexity)] +#![allow(clippy::too_many_arguments)] + +use avian3d::prelude::*; +use bevy::{ + core_pipeline::{bloom::Bloom, experimental::taa::TemporalAntiAliasing}, + pbr::{Atmosphere, ScreenSpaceAmbientOcclusion, light_consts::lux}, + prelude::*, + render::camera::Exposure, +}; +use camera::ControlledCamera; +use state::AppState; + +pub struct LevelPlugin; + +impl Plugin for LevelPlugin { + fn build(&self, app: &mut App) { + app.add_systems(OnEnter(AppState::Game), setup); + } +} + +fn setup( + mut commands: Commands, + mut meshes: ResMut>, + mut materials: ResMut>, +) { + let level_size = 50.0; + // Static physics object with a collision shape + commands.spawn(( + RigidBody::Static, + Collider::cuboid(level_size, 0.5, level_size), + Mesh3d(meshes.add(Cuboid::new(level_size, 0.5, level_size))), + MeshMaterial3d(materials.add(StandardMaterial { + base_color: Color::srgb_u8(52, 125, 117), + perceptual_roughness: 0.8, + ..default() + })), + )); + + // Dynamic physics object with a collision shape and initial angular velocity + for y in 5..15 { + commands.spawn(( + RigidBody::Dynamic, + Collider::cuboid(1.0, 1.0, 1.0), + AngularVelocity(Vec3::new(2.5, 3.5, 1.5)), + Mesh3d(meshes.add(Cuboid::from_length(1.0))), + MeshMaterial3d(materials.add(StandardMaterial { + base_color: Color::srgb_u8(220, 156, 86), + metallic: 1.0, + perceptual_roughness: 0.3, + ..default() + })), + Transform::from_xyz(0.0, y as f32 * 1.1, 0.0), + )); + } + + // Light + commands.spawn(( + DirectionalLight { + shadows_enabled: true, + illuminance: lux::RAW_SUNLIGHT, + color: Color::srgb(0.98, 0.95, 0.82), + ..default() + }, + Transform::from_xyz(-2.5, 4.5, 2.5).looking_at(Vec3::ZERO, Dir3::Y), + )); + + // Camera + commands.spawn(( + Camera3d::default(), + Camera { + hdr: true, + ..default() + }, + ControlledCamera::default(), + Msaa::Off, + TemporalAntiAliasing::default(), + ScreenSpaceAmbientOcclusion::default(), + Atmosphere::EARTH, + Exposure::SUNLIGHT, + Bloom::NATURAL, + Transform::from_xyz(-2.5, 9.5, 9.0).looking_at(Vec3::ZERO, Dir3::Y), + )); +} diff --git a/crates/physics/src/lib.rs b/crates/physics/src/lib.rs index d0e0e4b..b5fdb79 100644 --- a/crates/physics/src/lib.rs +++ b/crates/physics/src/lib.rs @@ -4,52 +4,11 @@ use avian3d::prelude::*; use bevy::prelude::*; -use state::AppState; pub struct PhysicsPlugin; impl Plugin for PhysicsPlugin { fn build(&self, app: &mut App) { - app.add_plugins(PhysicsPlugins::default()) - .add_systems(OnEnter(AppState::Game), setup); + app.add_plugins(PhysicsPlugins::default()); } } - -fn setup( - mut commands: Commands, - mut meshes: ResMut>, - mut materials: ResMut>, -) { - // Static physics object with a collision shape - commands.spawn(( - RigidBody::Static, - Collider::cylinder(4.0, 0.1), - Mesh3d(meshes.add(Cylinder::new(4.0, 0.1))), - MeshMaterial3d(materials.add(Color::WHITE)), - )); - - // Dynamic physics object with a collision shape and initial angular velocity - commands.spawn(( - RigidBody::Dynamic, - Collider::cuboid(1.0, 1.0, 1.0), - AngularVelocity(Vec3::new(2.5, 3.5, 1.5)), - Mesh3d(meshes.add(Cuboid::from_length(1.0))), - MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))), - Transform::from_xyz(0.0, 4.0, 0.0), - )); - - // Light - commands.spawn(( - PointLight { - shadows_enabled: true, - ..default() - }, - Transform::from_xyz(4.0, 8.0, 4.0), - )); - - // Camera - commands.spawn(( - Camera3d::default(), - Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Dir3::Y), - )); -} diff --git a/crates/state/src/lib.rs b/crates/state/src/lib.rs index 53850f9..f5f5b6b 100644 --- a/crates/state/src/lib.rs +++ b/crates/state/src/lib.rs @@ -32,12 +32,13 @@ impl Plugin for StatePlugin { Update, ( GameSystemSet::UpdateInputs, + GameSystemSet::UI, ( GameSystemSet::PreUpdate, GameSystemSet::Update, GameSystemSet::PostUpdate, ) - .run_if(in_state(GameState::Running).or(in_state(GameState::Paused))) + .run_if(in_state(GameState::Running)) .chain(), ) .chain(), @@ -68,7 +69,8 @@ pub enum GameState { pub enum GameSystemSet { // runs even if game is not loaded/active UpdateInputs, - // update - cosmetic only. runs while game is paused + UI, + // update - cosmetic only. does not run while game is paused PreUpdate, Update, PostUpdate, diff --git a/src/main.rs b/src/main.rs index 3252f70..f2bc431 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,8 @@ fn main() { input::InputPlugin, setup::SetupPlugin, ui_pause::UiPausePlugin, + level::LevelPlugin, + camera::CameraPlugin, // new internal crates go here ));