improve graphics and add camera controls

This commit is contained in:
Jim 2025-08-24 14:46:57 -04:00
parent 82a0fbdb50
commit 87fcc2b817
Signed by: jim
GPG key ID: 3236D2F059A7C0AC
12 changed files with 367 additions and 93 deletions

21
Cargo.lock generated
View file

@ -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"

View file

@ -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

View file

@ -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,
],
},
)

13
crates/camera/Cargo.toml Normal file
View file

@ -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

104
crates/camera/src/lib.rs Normal file
View file

@ -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::<CameraState>().add_systems(
Update,
(
orbit.run_if(action_pressed::<Update>(InputAction::CameraOrbitEnable)),
zoom,
pan.run_if(action_pressed::<Update>(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<CameraState>) {
let (mut camera, ControlledCamera { target }) = query.into_inner();
camera.translation = *target - camera.forward().as_vec3() * state.distance;
}
fn zoom(inputs: Res<Inputs<Update>>, mut state: ResMut<CameraState>) {
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<ControlledCamera>>,
camera_settings: Res<CameraState>,
inputs: Res<Inputs<Update>>,
) {
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<Inputs<Update>>,
state: Res<CameraState>,
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;
}

View file

@ -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,
),
])
}
}

View file

@ -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<InputMethod, InputAction>,
pub map: HashMap<InputMethod, Vec<InputAction>>,
}
impl InputMap {
pub fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = (InputMethod, InputAction)>,
{
let mut map: HashMap<InputMethod, Vec<InputAction>> = 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<InputMap>,
mouse_movement: Res<AccumulatedMouseMotion>,
mouse_buttons: Res<ButtonInput<MouseButton>>,
mouse_scroll: Res<AccumulatedMouseScroll>,
keyboard: Res<ButtonInput<KeyCode>>,
) {
fn set_value(action: &InputAction, value: f32, map: &mut HashMap<InputAction, InputState>) {
@ -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<InputMap>) {
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) => {

13
crates/level/Cargo.toml Normal file
View file

@ -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

85
crates/level/src/lib.rs Normal file
View file

@ -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<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
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),
));
}

View file

@ -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<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// 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),
));
}

View file

@ -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,

View file

@ -19,6 +19,8 @@ fn main() {
input::InputPlugin,
setup::SetupPlugin,
ui_pause::UiPausePlugin,
level::LevelPlugin,
camera::CameraPlugin,
// new internal crates go here
));