Skip to content

Commit 030aedb

Browse files
committed
feat: facing blocks
1 parent 7bbc4a9 commit 030aedb

File tree

4 files changed

+59
-19
lines changed

4 files changed

+59
-19
lines changed

src/main.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::sync::{Arc, Mutex};
12
use std::{
23
fs::File,
34
io::BufReader,
@@ -8,12 +9,14 @@ use std::{
89
};
910

1011
use bytemuck::{Pod, Zeroable};
11-
use player::CameraController;
1212
use glam::vec2;
1313
use material::Texture;
1414
use model::VertexData;
15+
use player::CameraController;
1516
use state::State;
1617
use tobj::{load_obj, load_obj_buf, LoadOptions};
18+
use winit::keyboard::KeyCode;
19+
use winit::window::CursorGrabMode;
1720
use winit::{
1821
dpi::{PhysicalPosition, PhysicalSize},
1922
event::*,
@@ -29,16 +32,16 @@ const DEFAULT_WINDOW_HEIGHT: u32 = 800;
2932
extern crate lazy_static;
3033

3134
pub mod blocks;
32-
pub mod player;
3335
pub mod chunk;
3436
pub mod collision;
3537
pub mod material;
3638
pub mod model;
3739
pub mod pipeline;
40+
pub mod player;
3841
pub mod state;
42+
pub mod ui;
3943
pub mod utils;
4044
pub mod world;
41-
pub mod ui;
4245

4346
async fn run(event_loop: EventLoop<()>, window: Window) {
4447
// let model: Obj = load_obj(input).unwrap();
@@ -51,11 +54,12 @@ async fn run(event_loop: EventLoop<()>, window: Window) {
5154
size.width = size.width.max(1);
5255
size.width = size.height.max(1);
5356

54-
let mut state = State::new(&window).await;
55-
let window = &window;
57+
let window = Arc::new(Mutex::new(window));
58+
let mut state = State::new(window.clone()).await;
5659

5760
let mut prev_mouse_pos = glam::vec2(0.0, 0.0);
5861
let mut cursor_in = false;
62+
let mut cursor_grab = CursorGrabMode::None;
5963

6064
event_loop
6165
.run(move |event, target| {
@@ -69,7 +73,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) {
6973
match event {
7074
WindowEvent::Resized(new_size) => {
7175
state.resize(new_size);
72-
window.request_redraw();
76+
window.lock().unwrap().request_redraw();
7377
}
7478
// WindowEvent::RedrawRequested => {}
7579
WindowEvent::CloseRequested
@@ -110,7 +114,7 @@ async fn run(event_loop: EventLoop<()>, window: Window) {
110114
state.update(delta_time.as_secs_f32(), total_time.as_secs_f32());
111115
state.draw();
112116

113-
window.request_redraw();
117+
window.lock().unwrap().request_redraw();
114118
}
115119

116120
_ => {}

src/player.rs

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::time::{Duration, Instant};
33

44
use glam::{vec2, vec3, Mat2, Vec2, Vec3};
55

6-
use crate::blocks::block::Block;
6+
use crate::blocks::block::{Block, FaceDirections};
77
use crate::collision::{CollisionPoint, RayResult};
88
use crate::{
99
collision::CollisionBox,
@@ -39,6 +39,7 @@ pub struct Player {
3939
pub jump_action_start: Option<Instant>,
4040
pub is_ghost: bool,
4141
pub facing_block: Option<Arc<Mutex<Block>>>,
42+
pub facing_face: Option<FaceDirections>,
4243
}
4344
impl Player {
4445
// Position relative to the chunk
@@ -64,7 +65,7 @@ impl Player {
6465
pub fn get_facing_block<'a>(
6566
&mut self,
6667
collisions: &'a Vec<CollisionBox>,
67-
) -> Option<&'a CollisionBox> {
68+
) -> Option<(&'a CollisionBox, FaceDirections)> {
6869
let forward = self.camera.calc_target();
6970
let mut ray_results: Vec<RayResult> = vec![];
7071

@@ -84,6 +85,7 @@ impl Player {
8485

8586
let mut block_collision: Option<&CollisionBox> = None;
8687
let mut max_distance = f32::MAX;
88+
let mut point: Option<Vec3> = None;
8789

8890
for result in ray_results.iter() {
8991
let mut closest_point = result.points[0];
@@ -95,10 +97,30 @@ impl Player {
9597
if closest_point.distance(self.camera.eye) < max_distance {
9698
max_distance = closest_point.distance(self.camera.eye);
9799
block_collision = Some(result.collision);
100+
point = Some(closest_point.clone());
98101
}
99102
}
100-
101-
return block_collision;
103+
let mut face_direction = None;
104+
105+
return match (block_collision, point) {
106+
(Some(block_collision), Some(point)) => {
107+
// TODO: This can be precomputed
108+
109+
let point_dir = ((block_collision.center() - point).normalize()) * -1.0;
110+
111+
let face_directions = FaceDirections::all();
112+
let mut best_dot = -1.0;
113+
for face in face_directions.iter() {
114+
let dot = point_dir.dot(face.get_normal_vector());
115+
if dot > best_dot {
116+
best_dot = dot;
117+
face_direction = Some(face);
118+
}
119+
}
120+
Some((block_collision, *face_direction.unwrap()))
121+
}
122+
_ => None,
123+
};
102124
}
103125
pub fn calc_current_chunk(&self) -> (i32, i32) {
104126
(

src/state.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::ops::Deref;
2+
use std::sync::Mutex;
13
use std::{cell::RefCell, f32::consts, rc::Rc, sync::Arc};
24

35
use crate::collision::CollisionBox;
@@ -12,6 +14,7 @@ use crate::{
1214
};
1315
use glam::{vec2, Quat, Vec3};
1416
use wgpu::{util::DeviceExt, BufferUsages};
17+
use winit::window::CursorGrabMode;
1518
use winit::{
1619
dpi::{LogicalSize, PhysicalSize},
1720
event::{DeviceEvent, ElementState, KeyEvent},
@@ -20,10 +23,11 @@ use winit::{
2023
};
2124

2225
impl State {
23-
pub async fn new(window: &Window) -> Self {
24-
let size = window.inner_size();
26+
pub async fn new(window: Arc<Mutex<Window>>) -> Self {
27+
let windowbrw = window.lock().unwrap();
28+
let size = windowbrw.inner_size();
2529
let instance = wgpu::Instance::default();
26-
let surface = unsafe { instance.create_surface(&window).unwrap() };
30+
let surface = unsafe { instance.create_surface(&*windowbrw).unwrap() };
2731
let adapter = instance
2832
.request_adapter(&wgpu::RequestAdapterOptions {
2933
power_preference: wgpu::PowerPreference::default(),
@@ -78,6 +82,7 @@ impl State {
7882
is_jumping: false,
7983
on_ground: false,
8084
facing_block: None,
85+
facing_face: None,
8186
jump_action_start: None,
8287
is_ghost: false,
8388
};
@@ -97,6 +102,7 @@ impl State {
97102
pipelines: vec![],
98103
surface_config,
99104
instance,
105+
window: window.clone(),
100106
device,
101107
world,
102108
queue,
@@ -141,6 +147,15 @@ impl State {
141147
physical_key: PhysicalKey::Code(KeyCode::KeyQ),
142148
..
143149
} => self.camera_controller.movement_vector.y = -1.0 * is_pressed,
150+
KeyEvent {
151+
physical_key: PhysicalKey::Code(KeyCode::KeyK),
152+
..
153+
} => self
154+
.window
155+
.lock()
156+
.unwrap()
157+
.set_cursor_grab(CursorGrabMode::Confined)
158+
.unwrap(),
144159
KeyEvent {
145160
physical_key: PhysicalKey::Code(KeyCode::Space),
146161
state: winit::event::ElementState::Pressed,
@@ -168,9 +183,6 @@ impl State {
168183
} else {
169184
self.config.polygon_mode = wgpu::PolygonMode::Line
170185
}
171-
172-
// self.pipelines.pop();
173-
// self.pipelines.push(Box::new(Pipeline::new(&self)))
174186
}
175187
_ => {}
176188
}
@@ -206,9 +218,10 @@ impl State {
206218
delta_time,
207219
&collisions,
208220
);
209-
if let Some(block) = self.player.get_facing_block(&collisions) {
221+
if let Some((block, face_dir)) = self.player.get_facing_block(&collisions) {
210222
let block = self.world.get_blocks_absolute(&block.to_block_position());
211223
self.player.facing_block = block;
224+
self.player.facing_face = Some(face_dir);
212225
}
213226

214227
let uniforms = Uniforms::from(&self.player.camera);
@@ -340,6 +353,7 @@ pub struct State {
340353
pub adapter: wgpu::Adapter,
341354
pub device: Arc<wgpu::Device>,
342355
pub queue: Arc<wgpu::Queue>,
356+
pub window: Arc<Mutex<Window>>,
343357
pub surface_config: wgpu::SurfaceConfiguration,
344358
pub pipelines: Vec<Box<dyn PipelineTrait>>,
345359
pub player: Player,

src/ui.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ impl UI {
4747
.as_ref()
4848
.unwrap()
4949
.iter()
50-
.find(|f| f.face_direction == FaceDirections::Top)
50+
.find(|f| f.face_direction == player.facing_face.unwrap())
5151
.unwrap()
5252
.create_face_data_abs(&block);
5353

0 commit comments

Comments
 (0)