Huge input update, FPS Camera controls system

Long day. I now store winit:🪟:Window in a mutex.
This commit is contained in:
reo 2025-09-28 01:31:14 +03:00
parent 1e9b997aeb
commit 46c8c32819
15 changed files with 307 additions and 39 deletions

View file

@ -0,0 +1,114 @@
use crate::system::{System, SystemContext};
use glam::{Quat, Vec3};
use winit::event::DeviceEvent::MouseMotion;
use winit::event::{ElementState, Event, MouseButton, WindowEvent};
use winit::keyboard::PhysicalKey;
use winit::window::CursorGrabMode;
use raidillon_assets::model_path;
use raidillon_platform::Camera;
pub struct FPSCameraSystem {
mouse_delta: (f64, f64),
mouse_enabled: bool,
position: Vec3,
yaw: f32,
pitch: f32,
speed: f32,
sensitivity: f32,
}
impl Default for FPSCameraSystem {
fn default() -> Self {
Self {
mouse_delta: Default::default(),
mouse_enabled: Default::default(),
position: Vec3::new(0.0, 0.0, 2.0),
yaw: -90.0,
pitch: 0.0,
speed: 3.0,
sensitivity: 0.1,
}
}
}
impl System for FPSCameraSystem {
fn load_world(&mut self, ctx: &mut SystemContext) {
ctx.scene.world.spawn((Camera {
eye: Vec3::new(0.0, 0.0, 2.0),
center: Vec3::ZERO,
up: Vec3::Y,
fovy: 60_f32.to_radians(),
aspect: ctx.platform_context.frame_width / ctx.platform_context.frame_height,
znear: 0.1,
zfar: 100.0,
},));
}
fn handle_event(&mut self, ctx: &mut SystemContext) {
let event2 = ctx.platform_context.current_event.clone();
match event2 {
Event::DeviceEvent { device_id, event} => {
match event {
MouseMotion { delta } => {
self.mouse_delta.0 += delta.0;
self.mouse_delta.1 += delta.1;
},
_ => {}
}
},
Event::WindowEvent { event, .. } => match event {
WindowEvent::MouseInput { state, button, .. } => {
if button == MouseButton::Right {
// blood and tear
let window = ctx.platform_context.window.lock().unwrap();
match state {
ElementState::Pressed => {
if window
.set_cursor_grab(CursorGrabMode::Confined)
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Locked))
.is_ok()
{
window.set_cursor_visible(false);
self.mouse_enabled = true;
}
}
ElementState::Released => {
let _ = window.set_cursor_grab(CursorGrabMode::None);
window.set_cursor_visible(true);
self.mouse_enabled = false;
}
}
}
}
_ => {},
},
_ => {},
}
}
fn frame_update(&mut self, ctx: &mut SystemContext) {
if self.mouse_enabled {
self.yaw += self.mouse_delta.0 as f32 * self.sensitivity;
self.pitch -= self.mouse_delta.1 as f32 * self.sensitivity;
self.pitch = self.pitch.clamp(-89.0, 89.0);
}
ctx.scene.world.query_mut::<&mut Camera>().into_iter().for_each(|(_, camera)| {
camera.eye = self.position;
camera.center = self.position + self.front();
});
self.mouse_delta = (0.0, 0.0);
}
}
impl FPSCameraSystem {
pub fn front(&self) -> Vec3 {
let yaw_rad = self.yaw.to_radians();
let pitch_rad = self.pitch.to_radians();
Vec3::new(
yaw_rad.cos() * pitch_rad.cos(),
pitch_rad.sin(),
yaw_rad.sin() * pitch_rad.cos(),
).normalize()
}
}