You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

457 lines
13 KiB

extern crate imgui;
extern crate imgui_wgpu;
extern crate imgui_winit_support;
extern crate tobj;
extern crate winit;
use std::f32::consts::PI;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
use bytemuck::__core::ops::Range;
use cgmath::{
Decomposed, Deg, Euler, InnerSpace, Point3, Quaternion, Rad, Rotation3, SquareMatrix,
};
use futures::executor::block_on;
use futures::task::LocalSpawn;
use gilrs::{Gamepad, Gilrs};
use gilrs::Event as GilEvent;
use imgui::*;
use imgui_wgpu::{Renderer as ImguiRenderer, RendererConfig as ImguiRendererConfig};
use legion::*;
use rapier3d::counters::Timer;
use rapier3d::dynamics::{
IntegrationParameters, JointSet, RigidBody, RigidBodyBuilder, RigidBodyHandle, RigidBodySet,
};
use rapier3d::geometry::{BroadPhase, ColliderBuilder, ColliderHandle, ColliderSet, NarrowPhase};
use rapier3d::math;
use rapier3d::na::{Isometry, Isometry3, Vector, Vector3};
use rapier3d::pipeline::PhysicsPipeline;
use wgpu::{BindGroup, Buffer, TextureView};
use wgpu_subscriber;
use winit::{
event::{self, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
use winit::event::DeviceEvent::MouseMotion;
use winit::platform::unix::x11::ffi::Time;
use winit::window::Window;
use crate::camera::{Camera, CameraController};
use crate::components::{Collider, Color, LoopState, Physics, Position};
use crate::owned_event::{OwnedEvent, OwnedEventExtension};
use crate::physics::PhysicsState;
use crate::render::Renderer;
use legion::systems::{UnsafeResources, SyncResources};
use std::borrow::Borrow;
use imgui::__core::convert::TryInto;
use imgui_winit_support::WinitPlatform;
mod camera;
mod components;
mod geometry;
mod light;
mod owned_event;
mod physics;
mod render;
/*
Collision detection
https://nphysics.org/rigid_body_simulations_with_contacts/
Obj file format
http://paulbourke.net/dataformats/obj/
tobj obj loader
https://docs.rs/tobj/2.0.3/tobj/index.html
mesh generator lib, might be useful
https://docs.rs/genmesh/0.6.2/genmesh/
legion ECS
https://github.com/amethyst/legion
mvp:
ECS
animation
render 3d (good!)
input/io
collision / physics (yep!)
entities & behaviours (got the entities!)
*/
//log::info!("");
pub struct ImguiContext {
pub context: imgui::Context,
}
unsafe impl Send for ImguiContext {}
pub struct ImguiPlatform {
pub platform: WinitPlatform,
}
unsafe impl Send for ImguiPlatform {}
fn main() {
let mut world = World::default();
let mut render_schedule = Schedule::builder()
.add_system(render::render_test_system())
.build();
let mut update_schedule = Schedule::builder()
.add_system(physics::test_unsafe_system())
.add_system(physics::update_camera_system())
.add_system(physics::run_physics_system())
.add_system(physics::update_models_system())
// next system here, gamelogic update system?
.build();
let mut event_schedule = Schedule::builder()
.add_system(owned_event::event_dispatch_system())
.build();
let event_loop = EventLoop::<OwnedEventExtension>::with_user_event();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title("MVGE");
let window = builder.build(&event_loop).unwrap();
let mut resources = Resources::default();
// Load up all the resources
{
let mut imgui_context = imgui::Context::create();
let mut platform = imgui_winit_support::WinitPlatform::init(&mut imgui_context);
platform.attach_window(
imgui_context.io_mut(),
&window,
imgui_winit_support::HiDpiMode::Default,
);
// imgui rendering context
let mut imgui_context = ImguiContext {
context: imgui_context,
};
let mut imgui_platform = ImguiPlatform {
platform: platform,
};
let font_size = 20.0 as f32;
imgui_context.context.io_mut().font_global_scale = 1.0 as f32;
imgui_context.context.fonts().add_font(&[FontSource::DefaultFontData {
config: Some(imgui::FontConfig {
oversample_h: 1,
pixel_snap_h: true,
size_pixels: font_size,
..Default::default()
}),
}]);
imgui_context.context.set_ini_filename(None);
// The renderer
let mut renderer = render::Renderer::init(&window, &mut imgui_context);
entity_loading(&mut world, &mut renderer);
resources.insert(renderer);
resources.insert(Arc::new(Mutex::new(imgui_context)));
resources.insert(Arc::new(Mutex::new(imgui_platform)));
resources.insert(window);
// Physics
let (physics_state, physics_pipeline) =
PhysicsState::build(rapier3d::math::Vector::new(0.0, -9.81, 0.05));
resources.insert(physics_state);
resources.insert(physics_pipeline);
// Loop data
resources.insert(LoopState {
delta_time: Default::default(),
start_time: Instant::now(),
step_size: 0.01666, // 60hz
});
// And our event stack
resources.insert(Vec::<OwnedEvent<OwnedEventExtension>>::new());
};
let event_loop_proxy = event_loop.create_proxy();
std::thread::spawn(move || {
let mut gilrs = Gilrs::new().unwrap();
// Iterate over all connected gamepads
let mut gamepad: Option<Gamepad> = None;
for (_id, gamepad_) in gilrs.gamepads() {
if gamepad_.name() == "PS4" {
gamepad = Some(gamepad_);
}
println!(
"{} is {:?} {:?}",
gamepad_.name(),
gamepad_.power_info(),
gamepad_.id()
);
}
let mut active_gamepad = None;
loop {
while let Some(GilEvent { id, event, time }) = gilrs.next_event() {
println!("{:?} New event from {}: {:?}", time, id, event);
active_gamepad = Some(id);
event_loop_proxy
.send_event(OwnedEventExtension::GamepadEvent {
gil_event: GilEvent { id, event, time },
})
.ok();
}
// // You can also use cached gamepad state
// if let Some(gamepad) = active_gamepad.map(|id| gilrs.gamepad(id)) {
// if gamepad.is_pressed(Button::South) {
// println!("Button South is pressed (XBox - A, PS - X)");
// }
// }
std::thread::sleep(std::time::Duration::from_millis(50));
}
});
let mut elapsed_time: f32 = {
// deltatime since last frame
let loop_state = resources.get::<LoopState>().unwrap();
loop_state.start_time.elapsed()
}
.as_secs_f32();
let mut delta_time: f32 = 0.0;
let mut accumulator_time: f32 = 0.0;
let mut current_time: f32 = elapsed_time;
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Poll;
match event {
event::Event::NewEvents(cause) => {
event_schedule.execute(&mut world, &mut resources);
resources
.get_mut::<Vec<OwnedEvent<OwnedEventExtension>>>()
.unwrap()
.clear();
}
event::Event::MainEventsCleared => {
let (step_size, elapsed_time) = {
// deltatime since last frame
let loop_state = resources.get::<LoopState>().unwrap();
(
loop_state.step_size,
loop_state.start_time.elapsed().as_secs_f32(),
)
};
delta_time = elapsed_time - current_time;
current_time = elapsed_time;
if delta_time > 0.02 {
delta_time = 0.02;
}
accumulator_time += delta_time;
while ((accumulator_time - step_size) >= step_size) {
accumulator_time -= step_size;
// ==== DELTA TIME LOCKED ====
update_schedule.execute(&mut world, &mut resources);
}
// ==== FPS LOCKED ====
render_schedule.execute(&mut world, &mut resources);
}
// Resizing will queue a request_redraw
event::Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
log::info!("Resizing to {:?}", size);
let width = size.width;
let height = size.height;
resources
.get_mut::<Renderer>()
.unwrap()
.resize(width, height);
}
event::Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
event::Event::RedrawRequested(_) => {
// Call the render system
render_schedule.execute(&mut world, &mut resources);
}
_ => {}
}
resources
.get_mut::<Vec<OwnedEvent<OwnedEventExtension>>>()
.unwrap()
.push(event.into());
});
}
pub fn entity_loading(world: &mut World, renderer: &mut Renderer) {
let monkey_mesh = renderer.load_mesh_to_buffer("./resources/monkey.obj");
let camera_ent: Entity = world.push((
Camera {
position: Point3 {
x: 0.0,
y: 0.0,
z: 10.0,
},
yaw: Rad(-PI),
pitch: Rad(PI / 2.0),
},
Color {
r: 1.0,
g: 1.0,
b: 0.5,
a: 1.0,
},
CameraController::new(3.0, 1.0),
));
let light_mesh = renderer.load_mesh_to_buffer("./resources/light.obj");
let light_entity: Entity = world.push((
Position {
x: 0.0,
y: 0.0,
z: 0.0,
rot: Euler {
x: Deg(0.0),
y: Deg(-25.0),
z: Deg(0.0),
},
},
Color {
r: 1.0,
g: 0.0,
b: 1.0,
a: 1.0,
},
light_mesh.clone(),
renderer.create_light(),
));
let light_entity: Entity = world.push((
cgmath::Point3 {
x: -5.0 as f32,
y: 7.0 as f32,
z: 10.0 as f32,
},
light_mesh,
renderer.create_light(),
));
let offset = cgmath::vec3(2.0, 2.0, 2.0);
let transform = Decomposed {
disp: offset.clone(),
rot: Quaternion::from_axis_angle(offset.normalize(), Deg(50.0)),
scale: 1.0,
};
let monkey_entity: Entity = world.push((
Position {
x: 1.0,
y: 5.0,
z: 2.0,
rot: Euler {
x: Deg(90.0),
y: Deg(45.0),
z: Deg(15.0),
}, //mx: cgmath::Matrix4::from(transform),
},
monkey_mesh,
Color {
r: 0.0,
g: 1.0,
b: 0.0,
a: 1.0,
},
));
let mut dynamic_ball_body = RigidBodyBuilder::new_dynamic()
.position(Isometry3::new(Vector3::new(0.0, 0.0, 0.0), Vector::y()))
.build();
let mut static_floor_body = RigidBodyBuilder::new_static()
.position(Isometry3::new(Vector3::new(0.0, -8.0, 0.0), Vector::y()))
.build();
let ball_collider = ColliderBuilder::ball(1.5).build();
let floor_collider = ColliderBuilder::cuboid(10.0, 0.2, 10.0).build();
let plane_mesh = renderer.load_mesh_to_buffer("./resources/plane.obj");
let plane_entity: Entity = world.push((
Position {
x: 0.0,
y: -8.0,
z: 0.0,
rot: Euler {
x: Deg(0.0),
y: Deg(0.0),
z: Deg(0.0),
},
},
plane_mesh,
Color {
r: 1.0,
g: 0.5,
b: 0.5,
a: 1.0,
},
Physics {
rigid_body: static_floor_body,
rigid_body_handle: None,
},
Collider {
collider: floor_collider,
collider_handle: None,
},
));
let ball_mesh = renderer.load_mesh_to_buffer("./resources/ball.obj");
let ball_mesh: Entity = world.push((
Position {
x: 0.0,
y: 0.0,
z: 0.0,
rot: Euler {
x: Deg(25.0),
y: Deg(45.0),
z: Deg(15.0),
},
},
ball_mesh,
Color {
r: 1.0,
g: 0.5,
b: 0.5,
a: 1.0,
},
Physics {
rigid_body: dynamic_ball_body,
rigid_body_handle: None,
},
Collider {
collider: ball_collider,
collider_handle: None,
},
));
}