forked from StrafesNET/strafe-project
Compare commits
19 Commits
physics-th
...
physics-th
Author | SHA1 | Date | |
---|---|---|---|
0a5a0f4c66 | |||
c61b6cfb90 | |||
e8cb4a6f70 | |||
8a81a57036 | |||
17331ba609 | |||
a24f8f5ff1 | |||
e90520bb89 | |||
f2e4286a08 | |||
bd6cd5eacc | |||
f2dfb438d0 | |||
7c8bc8d647 | |||
4943bc6a7f | |||
55eebba1c5 | |||
b8f13539db | |||
fb2e2afeb9 | |||
f30f246e5f | |||
0ac49308a0 | |||
30cbbbca1b | |||
66fa8fd637 |
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -1692,6 +1692,7 @@ dependencies = [
|
||||
"lazy-regex",
|
||||
"log",
|
||||
"obj",
|
||||
"parking_lot",
|
||||
"pollster",
|
||||
"rbx_binary",
|
||||
"rbx_dom_weak",
|
||||
|
@ -14,6 +14,7 @@ glam = "0.24.1"
|
||||
lazy-regex = "3.0.2"
|
||||
log = "0.4.20"
|
||||
obj = "0.10.2"
|
||||
parking_lot = "0.12.1"
|
||||
pollster = "0.3.0"
|
||||
rbx_binary = "0.7.1"
|
||||
rbx_dom_weak = "2.5.0"
|
||||
@ -22,7 +23,7 @@ rbx_xml = "0.13.1"
|
||||
wgpu = "0.17.0"
|
||||
winit = "0.28.6"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
#[profile.release]
|
||||
#lto = true
|
||||
#strip = true
|
||||
#codegen-units = 1
|
||||
|
@ -1,11 +1,11 @@
|
||||
#[derive(Debug)]
|
||||
pub struct TimedInstruction<I> {
|
||||
pub time: crate::body::TIME,
|
||||
pub time: crate::physics::TIME,
|
||||
pub instruction: I,
|
||||
}
|
||||
|
||||
pub trait InstructionEmitter<I> {
|
||||
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<I>>;
|
||||
fn next_instruction(&self, time_limit:crate::physics::TIME) -> Option<TimedInstruction<I>>;
|
||||
}
|
||||
pub trait InstructionConsumer<I> {
|
||||
fn process_instruction(&mut self, instruction:TimedInstruction<I>);
|
||||
@ -13,11 +13,11 @@ pub trait InstructionConsumer<I> {
|
||||
|
||||
//PROPER PRIVATE FIELDS!!!
|
||||
pub struct InstructionCollector<I> {
|
||||
time: crate::body::TIME,
|
||||
time: crate::physics::TIME,
|
||||
instruction: Option<I>,
|
||||
}
|
||||
impl<I> InstructionCollector<I> {
|
||||
pub fn new(time:crate::body::TIME) -> Self {
|
||||
pub fn new(time:crate::physics::TIME) -> Self {
|
||||
Self{
|
||||
time,
|
||||
instruction:None
|
||||
|
@ -30,7 +30,7 @@ fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>
|
||||
//next class
|
||||
objects
|
||||
}
|
||||
fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3)->crate::model::CollisionAttributes{
|
||||
fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersecting:bool)->crate::model::CollisionAttributes{
|
||||
let mut general=crate::model::GameMechanicAttributes::default();
|
||||
let mut intersecting=crate::model::IntersectingAttributes::default();
|
||||
let mut contacting=crate::model::ContactingAttributes::default();
|
||||
@ -46,7 +46,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3)->crate::model:
|
||||
behaviour:crate::model::StageElementBehaviour::Platform,
|
||||
}),
|
||||
other=>{
|
||||
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(SpawnAt|Trigger|Teleport|Platform)(\d+)$")
|
||||
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Spawn|SpawnAt|Trigger|Teleport|Platform)(\d+)$")
|
||||
.captures(other){
|
||||
general.stage_element=Some(crate::model::GameMechanicStageElement{
|
||||
mode_id:0,
|
||||
@ -56,7 +56,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3)->crate::model:
|
||||
None=>false,
|
||||
},
|
||||
behaviour:match &captures[2]{
|
||||
"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
|
||||
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
|
||||
"Trigger"=>crate::model::StageElementBehaviour::Trigger,
|
||||
"Teleport"=>crate::model::StageElementBehaviour::Teleport,
|
||||
"Platform"=>crate::model::StageElementBehaviour::Platform,
|
||||
@ -89,9 +89,21 @@ fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3)->crate::model:
|
||||
//WormholeIn#
|
||||
}
|
||||
}
|
||||
return crate::model::CollisionAttributes::Contact{contacting,general};
|
||||
crate::model::CollisionAttributes::Contact{contacting,general}
|
||||
},
|
||||
false=>if force_intersecting
|
||||
||general.jump_limit.is_some()
|
||||
||general.booster.is_some()
|
||||
||general.zone.is_some()
|
||||
||general.stage_element.is_some()
|
||||
||general.wormhole.is_some()
|
||||
||intersecting.water.is_some()
|
||||
||intersecting.accelerator.is_some()
|
||||
{
|
||||
crate::model::CollisionAttributes::Intersect{intersecting,general}
|
||||
}else{
|
||||
crate::model::CollisionAttributes::Decoration
|
||||
},
|
||||
false=>return crate::model::CollisionAttributes::Decoration,
|
||||
}
|
||||
}
|
||||
|
||||
@ -219,6 +231,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
);
|
||||
|
||||
//push TempIndexedAttributes
|
||||
let mut force_intersecting=false;
|
||||
let mut temp_indexing_attributes=Vec::new();
|
||||
if let Some(attr)=match &object.name[..]{
|
||||
"MapStart"=>{
|
||||
@ -227,11 +240,11 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
},
|
||||
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
|
||||
other=>{
|
||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|OrderedCheckpoint)(\d+)$");
|
||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
|
||||
if let Some(captures) = regman.captures(other) {
|
||||
match &captures[1]{
|
||||
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start{mode_id:captures[2].parse::<u32>().unwrap()}),
|
||||
"Spawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()}),
|
||||
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()}),
|
||||
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
|
||||
_=>None,
|
||||
}
|
||||
@ -240,6 +253,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
}
|
||||
}
|
||||
}{
|
||||
force_intersecting=true;
|
||||
temp_indexing_attributes.push(attr);
|
||||
}
|
||||
|
||||
@ -354,17 +368,17 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
|
||||
//use front face texture first and use top face texture as a fallback
|
||||
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
|
||||
f0,//Wedge::Right
|
||||
if f5.is_some(){f5}else{f1},//Wedge::TopFront
|
||||
f2,//Wedge::Back
|
||||
f3,//Wedge::Left
|
||||
f4,//Wedge::Bottom
|
||||
f0,//Cube::Right->Wedge::Right
|
||||
if f5.is_some(){f5}else{f1},//Cube::Front|Cube::Top->Wedge::TopFront
|
||||
f2,//Cube::Back->Wedge::Back
|
||||
f3,//Cube::Left->Wedge::Left
|
||||
f4,//Cube::Bottom->Wedge::Bottom
|
||||
]),
|
||||
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
|
||||
f0,//CornerWedge::Right
|
||||
f1,//CornerWedge::Top
|
||||
f4,//CornerWedge::Bottom
|
||||
f5,//CornerWedge::Front
|
||||
f0,//Cube::Right->CornerWedge::Right
|
||||
f1,//Cube::Top->CornerWedge::Top
|
||||
f4,//Cube::Bottom->CornerWedge::Bottom
|
||||
f5,//Cube::Front->CornerWedge::Front
|
||||
]),
|
||||
};
|
||||
//make new model if unit cube has not been created before
|
||||
@ -440,7 +454,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
||||
indexed_models[model_id].instances.push(crate::model::ModelInstance {
|
||||
transform:model_transform,
|
||||
color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
|
||||
attributes:get_attributes(&object.name,*can_collide,glam::vec3(velocity.x,velocity.y,velocity.z)),
|
||||
attributes:get_attributes(&object.name,*can_collide,glam::vec3(velocity.x,velocity.y,velocity.z),force_intersecting),
|
||||
temp_indexing:temp_indexing_attributes,
|
||||
});
|
||||
}
|
||||
|
263
src/main.rs
263
src/main.rs
@ -1,12 +1,15 @@
|
||||
use std::{borrow::Cow, time::Instant};
|
||||
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
|
||||
use model::{Vertex,ModelInstance,ModelGraphicsInstance};
|
||||
use body::{InputInstruction, PhysicsInstruction};
|
||||
use instruction::{TimedInstruction, InstructionConsumer};
|
||||
use physics::{InputInstruction, PhysicsInstruction};
|
||||
use instruction::TimedInstruction;
|
||||
|
||||
use crate::instruction::InstructionConsumer;
|
||||
|
||||
mod body;
|
||||
mod model;
|
||||
mod zeroes;
|
||||
mod worker;
|
||||
mod physics;
|
||||
mod framework;
|
||||
mod primitives;
|
||||
mod instruction;
|
||||
@ -43,14 +46,65 @@ pub struct GraphicsPipelines{
|
||||
model: wgpu::RenderPipeline,
|
||||
}
|
||||
|
||||
pub struct GraphicsCamera{
|
||||
screen_size: glam::UVec2,
|
||||
fov: glam::Vec2,//slope
|
||||
//camera angles and such are extrapolated and passed in every time
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
|
||||
//glam_assert!(z_near > 0.0 && z_far > 0.0);
|
||||
let r = z_far / (z_near - z_far);
|
||||
glam::Mat4::from_cols(
|
||||
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
|
||||
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
|
||||
glam::Vec4::new(0.0, 0.0, r, -1.0),
|
||||
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
|
||||
)
|
||||
}
|
||||
impl GraphicsCamera{
|
||||
pub fn new(screen_size:glam::UVec2,fov_y:f32)->Self{
|
||||
Self{
|
||||
screen_size,
|
||||
fov: glam::vec2(fov_y*(screen_size.x as f32)/(screen_size.y as f32),fov_y),
|
||||
}
|
||||
}
|
||||
pub fn proj(&self)->glam::Mat4{
|
||||
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
||||
}
|
||||
pub fn view(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
|
||||
//f32 good enough for view matrix
|
||||
glam::Mat4::from_translation(pos) * glam::Mat4::from_euler(glam::EulerRot::YXZ, angles.x, angles.y, 0f32)
|
||||
}
|
||||
pub fn set_screen_size(&mut self,screen_size:glam::UVec2){
|
||||
self.screen_size=screen_size;
|
||||
self.fov.x=self.fov.y*(screen_size.x as f32)/(screen_size.y as f32);
|
||||
}
|
||||
|
||||
pub fn to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 3 + 4] {
|
||||
let proj=self.proj();
|
||||
let proj_inv = proj.inverse();
|
||||
let view=self.view(pos,angles);
|
||||
let view_inv = view.inverse();
|
||||
|
||||
let mut raw = [0f32; 16 * 3 + 4];
|
||||
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
|
||||
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
|
||||
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
||||
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
|
||||
raw
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphicsState{
|
||||
screen_size: (u32, u32),
|
||||
pipelines: GraphicsPipelines,
|
||||
bind_groups: GraphicsBindGroups,
|
||||
bind_group_layouts: GraphicsBindGroupLayouts,
|
||||
samplers: GraphicsSamplers,
|
||||
temp_squid_texture_view: wgpu::TextureView,
|
||||
camera:GraphicsCamera,
|
||||
camera_buf: wgpu::Buffer,
|
||||
temp_squid_texture_view: wgpu::TextureView,
|
||||
models: Vec<ModelGraphics>,
|
||||
depth_view: wgpu::TextureView,
|
||||
staging_belt: wgpu::util::StagingBelt,
|
||||
@ -65,8 +119,9 @@ impl GraphicsState{
|
||||
pub struct GlobalState{
|
||||
start_time: std::time::Instant,
|
||||
manual_mouse_lock:bool,
|
||||
mouse:physics::MouseState,
|
||||
graphics:GraphicsState,
|
||||
physics:body::PhysicsState,
|
||||
physics_thread:worker::Worker<TimedInstruction<InputInstruction>,physics::PhysicsOutputState>,
|
||||
}
|
||||
|
||||
impl GlobalState{
|
||||
@ -94,71 +149,6 @@ impl GlobalState{
|
||||
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
|
||||
}
|
||||
|
||||
fn generate_model_physics(&mut self,indexed_models:&model::IndexedModelInstances){
|
||||
let mut starts=Vec::new();
|
||||
let mut spawns=Vec::new();
|
||||
let mut ordered_checkpoints=Vec::new();
|
||||
let mut unordered_checkpoints=Vec::new();
|
||||
for model in &indexed_models.models{
|
||||
//make aabb and run vertices to get realistic bounds
|
||||
for model_instance in &model.instances{
|
||||
if let Some(model_physics)=body::ModelPhysics::from_model(model,model_instance){
|
||||
let model_id=self.physics.models.len() as u32;
|
||||
//snoop it before it gets stolen
|
||||
for attr in model_instance.temp_indexing.iter(){
|
||||
match attr{
|
||||
model::TempIndexedAttributes::Start{mode_id}=>starts.push((*mode_id,model_id)),
|
||||
model::TempIndexedAttributes::Spawn{mode_id,stage_id}=>spawns.push((*mode_id,model_id,*stage_id)),
|
||||
model::TempIndexedAttributes::OrderedCheckpoint{mode_id,checkpoint_id}=>ordered_checkpoints.push((*mode_id,model_id,*checkpoint_id)),
|
||||
model::TempIndexedAttributes::UnorderedCheckpoint{mode_id}=>unordered_checkpoints.push((*mode_id,model_id)),
|
||||
}
|
||||
}
|
||||
//steal it
|
||||
self.physics.models.push(model_physics);
|
||||
}
|
||||
}
|
||||
}
|
||||
//I don't wanna write structs for temporary structures
|
||||
//this code builds ModeDescriptions from the unsorted lists at the top of the function
|
||||
starts.sort_by_key(|tup|tup.0);
|
||||
let mut eshmep=std::collections::HashMap::new();
|
||||
let mut modedatas:Vec<(u32,Vec<(u32,u32)>,Vec<(u32,u32)>,Vec<u32>)>=starts.into_iter().enumerate().map(|(i,tup)|{
|
||||
eshmep.insert(tup.0,i);
|
||||
(tup.1,Vec::new(),Vec::new(),Vec::new())
|
||||
}).collect();
|
||||
for tup in spawns{
|
||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||
modedata.1.push((tup.2,tup.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
for tup in ordered_checkpoints{
|
||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||
modedata.2.push((tup.2,tup.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
for tup in unordered_checkpoints{
|
||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||
modedata.3.push(tup.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.physics.modes.append(&mut modedatas.into_iter().map(|mut tup|{
|
||||
tup.1.sort_by_key(|tup|tup.0);
|
||||
tup.2.sort_by_key(|tup|tup.0);
|
||||
model::ModeDescription{
|
||||
start:tup.0,
|
||||
spawns:tup.1.into_iter().map(|tup|tup.1).collect(),
|
||||
ordered_checkpoints:tup.2.into_iter().map(|tup|tup.1).collect(),
|
||||
unordered_checkpoints:tup.3,
|
||||
}
|
||||
}).collect());
|
||||
println!("Physics Objects: {}",self.physics.models.len());
|
||||
}
|
||||
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){
|
||||
//generate texture view per texture
|
||||
|
||||
@ -228,7 +218,7 @@ impl GlobalState{
|
||||
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
|
||||
let indexed_models_len=indexed_models.models.len();
|
||||
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
|
||||
for mut model in indexed_models.models.into_iter(){
|
||||
for model in indexed_models.models.into_iter(){
|
||||
//convert ModelInstance into ModelGraphicsInstance
|
||||
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
|
||||
if instance.color.w==0.0{
|
||||
@ -401,20 +391,6 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
||||
raw
|
||||
}
|
||||
|
||||
fn to_uniform_data(camera: &body::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
|
||||
let proj=camera.proj();
|
||||
let proj_inv = proj.inverse();
|
||||
let view=camera.view(pos);
|
||||
let view_inv = view.inverse();
|
||||
|
||||
let mut raw = [0f32; 16 * 3 + 4];
|
||||
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
|
||||
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
|
||||
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
||||
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
|
||||
raw
|
||||
}
|
||||
|
||||
impl framework::Example for GlobalState {
|
||||
fn optional_features() -> wgpu::Features {
|
||||
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||
@ -575,23 +551,6 @@ impl framework::Example for GlobalState {
|
||||
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||
});
|
||||
|
||||
let physics = body::PhysicsState {
|
||||
spawn_point:glam::vec3(0.0,50.0,0.0),
|
||||
body: body::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
|
||||
time: 0,
|
||||
style:body::StyleModifiers::default(),
|
||||
grounded: false,
|
||||
contacts: std::collections::HashSet::new(),
|
||||
models: Vec::new(),
|
||||
walk: body::WalkState::new(),
|
||||
camera: body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)),
|
||||
mouse_interpolation: body::MouseInterpolationState::new(),
|
||||
controls: 0,
|
||||
world:body::WorldState{},
|
||||
game:body::GameMechanicsState::default(),
|
||||
modes:Vec::new(),
|
||||
};
|
||||
|
||||
//load textures
|
||||
let device_features = device.features();
|
||||
|
||||
@ -786,7 +745,10 @@ impl framework::Example for GlobalState {
|
||||
multiview: None,
|
||||
});
|
||||
|
||||
let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0));
|
||||
let mut physics = physics::PhysicsState::default();
|
||||
|
||||
let camera=GraphicsCamera::new(glam::uvec2(config.width,config.height), 1.0);
|
||||
let camera_uniforms = camera.to_uniform_data(physics.output().adjust_mouse(&physics.next_mouse));
|
||||
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Camera"),
|
||||
contents: bytemuck::cast_slice(&camera_uniforms),
|
||||
@ -802,6 +764,7 @@ impl framework::Example for GlobalState {
|
||||
],
|
||||
label: Some("Camera"),
|
||||
});
|
||||
|
||||
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &skybox_texture_bind_group_layout,
|
||||
entries: &[
|
||||
@ -820,7 +783,6 @@ impl framework::Example for GlobalState {
|
||||
let depth_view = Self::create_depth_texture(config, device);
|
||||
|
||||
let graphics=GraphicsState {
|
||||
screen_size: (config.width,config.height),
|
||||
pipelines:GraphicsPipelines{
|
||||
skybox:sky_pipeline,
|
||||
model:model_pipeline
|
||||
@ -829,6 +791,7 @@ impl framework::Example for GlobalState {
|
||||
camera:camera_bind_group,
|
||||
skybox_texture:skybox_texture_bind_group,
|
||||
},
|
||||
camera,
|
||||
camera_buf,
|
||||
models: Vec::new(),
|
||||
depth_view,
|
||||
@ -838,20 +801,30 @@ impl framework::Example for GlobalState {
|
||||
temp_squid_texture_view: squid_texture_view,
|
||||
};
|
||||
|
||||
let mut state=GlobalState{
|
||||
start_time:Instant::now(),
|
||||
manual_mouse_lock:false,
|
||||
graphics,
|
||||
physics,
|
||||
};
|
||||
|
||||
let indexed_model_instances=model::IndexedModelInstances{
|
||||
textures:Vec::new(),
|
||||
models:indexed_models,
|
||||
spawn_point:glam::Vec3::Y*50.0,
|
||||
modes:Vec::new(),
|
||||
};
|
||||
state.generate_model_physics(&indexed_model_instances);
|
||||
|
||||
//how to multithread
|
||||
|
||||
//1. build
|
||||
physics.generate_models(&indexed_model_instances);
|
||||
|
||||
//2. move
|
||||
let physics_thread=physics.into_worker();
|
||||
|
||||
//3. forget
|
||||
|
||||
let mut state=GlobalState{
|
||||
start_time:Instant::now(),
|
||||
manual_mouse_lock:false,
|
||||
mouse:physics::MouseState::default(),
|
||||
graphics,
|
||||
physics_thread,
|
||||
};
|
||||
state.generate_model_graphics(&device,&queue,indexed_model_instances);
|
||||
|
||||
let args:Vec<String>=std::env::args().collect();
|
||||
@ -902,20 +875,20 @@ impl framework::Example for GlobalState {
|
||||
}{
|
||||
let spawn_point=indexed_model_instances.spawn_point;
|
||||
//if generate_indexed_models succeeds, clear the previous ones
|
||||
self.physics.clear();
|
||||
self.graphics.clear();
|
||||
self.generate_model_physics(&indexed_model_instances);
|
||||
|
||||
let mut physics=physics::PhysicsState::default();
|
||||
physics.game.stage_id=0;
|
||||
physics.spawn_point=spawn_point;
|
||||
physics.process_instruction(instruction::TimedInstruction{
|
||||
time:physics.time,
|
||||
instruction: PhysicsInstruction::Input(InputInstruction::Reset),
|
||||
});
|
||||
physics.generate_models(&indexed_model_instances);
|
||||
self.physics_thread=physics.into_worker();
|
||||
|
||||
self.generate_model_graphics(device,queue,indexed_model_instances);
|
||||
//manual reset
|
||||
let time=self.physics.time;
|
||||
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
|
||||
time,
|
||||
instruction: body::PhysicsInstruction::SetSpawnPosition(spawn_point),
|
||||
});
|
||||
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
|
||||
time,
|
||||
instruction: body::PhysicsInstruction::Input(body::InputInstruction::Reset),
|
||||
});
|
||||
}else{
|
||||
println!("No modeldatas were generated");
|
||||
}
|
||||
@ -976,7 +949,7 @@ impl framework::Example for GlobalState {
|
||||
15=>{//Tab
|
||||
if s{
|
||||
self.manual_mouse_lock=false;
|
||||
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.screen_size.0 as f32/2.0, self.graphics.screen_size.1 as f32/2.0)){
|
||||
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
|
||||
Ok(())=>(),
|
||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||
}
|
||||
@ -1005,18 +978,17 @@ impl framework::Example for GlobalState {
|
||||
},
|
||||
_ => {println!("scancode {}",keycode);None},
|
||||
}{
|
||||
self.physics.run(time);
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(input_instruction),
|
||||
})
|
||||
instruction:input_instruction,
|
||||
}).unwrap();
|
||||
}
|
||||
},
|
||||
winit::event::DeviceEvent::MouseMotion {
|
||||
delta,//these (f64,f64) are integers on my machine
|
||||
} => {
|
||||
if self.manual_mouse_lock{
|
||||
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.screen_size.0 as f32/2.0, self.graphics.screen_size.1 as f32/2.0)){
|
||||
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
|
||||
Ok(())=>(),
|
||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||
}
|
||||
@ -1024,21 +996,22 @@ impl framework::Example for GlobalState {
|
||||
//do not step the physics because the mouse polling rate is higher than the physics can run.
|
||||
//essentially the previous input will be overwritten until a true step runs
|
||||
//which is fine because they run all the time.
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
let delta=glam::ivec2(delta.0 as i32,delta.1 as i32);
|
||||
self.mouse.pos+=delta;
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(InputInstruction::MoveMouse(glam::ivec2(delta.0 as i32,delta.1 as i32))),
|
||||
})
|
||||
instruction:InputInstruction::MoveMouse(self.mouse.pos),
|
||||
}).unwrap();
|
||||
},
|
||||
winit::event::DeviceEvent::MouseWheel {
|
||||
delta,
|
||||
} => {
|
||||
println!("mousewheel {:?}",delta);
|
||||
if false{//self.physics.style.use_scroll{
|
||||
self.physics.run(time);
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||
})
|
||||
instruction:InputInstruction::Jump(true),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||
}).unwrap();
|
||||
}
|
||||
}
|
||||
_=>(),
|
||||
@ -1052,8 +1025,7 @@ impl framework::Example for GlobalState {
|
||||
_queue: &wgpu::Queue,
|
||||
) {
|
||||
self.graphics.depth_view = Self::create_depth_texture(config, device);
|
||||
self.graphics.screen_size = (config.width, config.height);
|
||||
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
|
||||
self.graphics.camera.set_screen_size(glam::uvec2(config.width, config.height));
|
||||
}
|
||||
|
||||
fn render(
|
||||
@ -1063,15 +1035,20 @@ impl framework::Example for GlobalState {
|
||||
queue: &wgpu::Queue,
|
||||
_spawner: &framework::Spawner,
|
||||
) {
|
||||
//ideally this would be scheduled to execute and finish right before the render.
|
||||
let time=self.start_time.elapsed().as_nanos() as i64;
|
||||
|
||||
self.physics.run(time);
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:InputInstruction::Idle,
|
||||
}).unwrap();
|
||||
//update time lol
|
||||
self.mouse.time=time;
|
||||
|
||||
let mut encoder =
|
||||
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||
|
||||
// update rotation
|
||||
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
|
||||
let camera_uniforms = self.graphics.camera.to_uniform_data(self.physics_thread.grab_clone().adjust_mouse(&self.mouse));
|
||||
self.graphics.staging_belt
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
@ -1082,6 +1059,7 @@ impl framework::Example for GlobalState {
|
||||
)
|
||||
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
||||
//This code only needs to run when the uniforms change
|
||||
/*
|
||||
for model in self.graphics.models.iter() {
|
||||
let model_uniforms = get_instances_buffer_data(&model.instances);
|
||||
self.graphics.staging_belt
|
||||
@ -1094,6 +1072,7 @@ impl framework::Example for GlobalState {
|
||||
)
|
||||
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
|
||||
}
|
||||
*/
|
||||
self.graphics.staging_belt.finish();
|
||||
|
||||
{
|
||||
|
18
src/model.rs
18
src/model.rs
@ -85,6 +85,24 @@ pub struct ModeDescription{
|
||||
pub spawns:Vec<u32>,//spawns[spawn_id]=model_id
|
||||
pub ordered_checkpoints:Vec<u32>,//ordered_checkpoints[checkpoint_id]=model_id
|
||||
pub unordered_checkpoints:Vec<u32>,//unordered_checkpoints[checkpoint_id]=model_id
|
||||
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
||||
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
||||
}
|
||||
impl ModeDescription{
|
||||
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&u32>{
|
||||
if let Some(&spawn)=self.spawn_from_stage_id.get(&stage_id){
|
||||
self.spawns.get(spawn)
|
||||
}else{
|
||||
None
|
||||
}
|
||||
}
|
||||
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&u32>{
|
||||
if let Some(&checkpoint)=self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id){
|
||||
self.ordered_checkpoints.get(checkpoint)
|
||||
}else{
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
pub enum TempIndexedAttributes{
|
||||
Start{
|
||||
|
@ -14,8 +14,6 @@ pub enum PhysicsInstruction {
|
||||
// )
|
||||
//InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
|
||||
Input(InputInstruction),
|
||||
//temp
|
||||
SetSpawnPosition(glam::Vec3),
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum InputInstruction {
|
||||
@ -34,7 +32,7 @@ pub enum InputInstruction {
|
||||
//for interpolation / networking / playback reasons, most playback heads will always want
|
||||
//to be 1 instruction ahead to generate the next state for interpolation.
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Body {
|
||||
position: glam::Vec3,//I64 where 2^32 = 1 u
|
||||
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
|
||||
@ -45,20 +43,20 @@ trait MyHash{
|
||||
fn hash(&self) -> u64;
|
||||
}
|
||||
impl MyHash for Body {
|
||||
fn hash(&self) -> u64 {
|
||||
fn hash(&self) -> u64 {
|
||||
let mut hasher=std::collections::hash_map::DefaultHasher::new();
|
||||
for &el in self.position.as_ref().iter() {
|
||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
||||
}
|
||||
for &el in self.velocity.as_ref().iter() {
|
||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
||||
}
|
||||
for &el in self.acceleration.as_ref().iter() {
|
||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
||||
}
|
||||
std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice());
|
||||
for &el in self.position.as_ref().iter() {
|
||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
||||
}
|
||||
for &el in self.velocity.as_ref().iter() {
|
||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
||||
}
|
||||
for &el in self.acceleration.as_ref().iter() {
|
||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
||||
}
|
||||
std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice());
|
||||
return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum MoveRestriction {
|
||||
@ -80,9 +78,9 @@ impl InputState {
|
||||
}
|
||||
impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{
|
||||
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<InputInstruction>> {
|
||||
//this is polled by PhysicsState for actions like Jump
|
||||
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
|
||||
self.queue.get(0)
|
||||
//this is polled by PhysicsState for actions like Jump
|
||||
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
|
||||
self.queue.get(0)
|
||||
}
|
||||
}
|
||||
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
|
||||
@ -93,49 +91,33 @@ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
|
||||
}
|
||||
*/
|
||||
|
||||
enum MouseInterpolation {
|
||||
First,//just checks the last value
|
||||
Lerp,//lerps between
|
||||
}
|
||||
|
||||
//hey dumbass just use a delta
|
||||
pub struct MouseInterpolationState {
|
||||
interpolation: MouseInterpolation,
|
||||
time0: TIME,
|
||||
time1: TIME,
|
||||
mouse0: glam::IVec2,
|
||||
mouse1: glam::IVec2,
|
||||
#[derive(Clone)]
|
||||
pub struct MouseState {
|
||||
pub pos: glam::IVec2,
|
||||
pub time: TIME,
|
||||
}
|
||||
|
||||
impl MouseInterpolationState {
|
||||
pub fn new() -> Self {
|
||||
impl Default for MouseState{
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
interpolation:MouseInterpolation::First,
|
||||
time0:0,
|
||||
time1:1,//ONE NANOSECOND!!!! avoid divide by zero
|
||||
mouse0:glam::IVec2::ZERO,
|
||||
mouse1:glam::IVec2::ZERO,
|
||||
time:0,
|
||||
pos:glam::IVec2::ZERO,
|
||||
}
|
||||
}
|
||||
pub fn move_mouse(&mut self,time:TIME,delta:glam::IVec2){
|
||||
self.time0=self.time1;
|
||||
self.mouse0=self.mouse1;
|
||||
self.time1=time;
|
||||
self.mouse1=self.mouse1+delta;
|
||||
}
|
||||
impl MouseState {
|
||||
pub fn move_mouse(&mut self,pos:glam::IVec2,time:TIME){
|
||||
self.time=time;
|
||||
self.pos=pos;
|
||||
}
|
||||
pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
|
||||
match self.interpolation {
|
||||
MouseInterpolation::First => self.mouse0,
|
||||
MouseInterpolation::Lerp => {
|
||||
let m0=self.mouse0.as_i64vec2();
|
||||
let m1=self.mouse1.as_i64vec2();
|
||||
//these are deltas
|
||||
let t1t=(self.time1-time) as i64;
|
||||
let tt0=(time-self.time0) as i64;
|
||||
let dt=(self.time1-self.time0) as i64;
|
||||
((m0*t1t+m1*tt0)/dt).as_ivec2()
|
||||
}
|
||||
}
|
||||
pub fn lerp(&self,target:&MouseState,time:TIME)->glam::IVec2 {
|
||||
let m0=self.pos.as_i64vec2();
|
||||
let m1=target.pos.as_i64vec2();
|
||||
//these are deltas
|
||||
let t1t=(target.time-time) as i64;
|
||||
let tt0=(time-self.time) as i64;
|
||||
let dt=(target.time-self.time) as i64;
|
||||
((m0*t1t+m1*tt0)/dt).as_ivec2()
|
||||
}
|
||||
}
|
||||
|
||||
@ -158,76 +140,52 @@ impl WalkState {
|
||||
}
|
||||
}
|
||||
|
||||
// Note: we use the Y=up coordinate space in this example.
|
||||
pub struct Camera {
|
||||
#[derive(Clone)]
|
||||
pub struct PhysicsCamera {
|
||||
offset: glam::Vec3,
|
||||
angles: glam::DVec2,//YAW AND THEN PITCH
|
||||
//punch: glam::Vec3,
|
||||
//punch_velocity: glam::Vec3,
|
||||
fov: glam::Vec2,//slope
|
||||
sensitivity: glam::DVec2,
|
||||
time: TIME,
|
||||
mouse:MouseState,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 {
|
||||
let (sina, cosa) = angle.sin_cos();
|
||||
glam::Mat3::from_cols(
|
||||
glam::Vec3::new(cosa as f32, 0.0, -sina as f32),
|
||||
glam::Vec3::Y,
|
||||
glam::Vec3::new(sina as f32, 0.0, cosa as f32),
|
||||
)
|
||||
}
|
||||
#[inline]
|
||||
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
|
||||
//glam_assert!(z_near > 0.0 && z_far > 0.0);
|
||||
let r = z_far / (z_near - z_far);
|
||||
glam::Mat4::from_cols(
|
||||
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
|
||||
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
|
||||
glam::Vec4::new(0.0, 0.0, r, -1.0),
|
||||
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
|
||||
let (sina, cosa) = angle.sin_cos();
|
||||
glam::Mat3::from_cols(
|
||||
glam::Vec3::new(cosa as f32, 0.0, -sina as f32),
|
||||
glam::Vec3::Y,
|
||||
glam::Vec3::new(sina as f32, 0.0, cosa as f32),
|
||||
)
|
||||
}
|
||||
impl Camera {
|
||||
pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
|
||||
impl PhysicsCamera {
|
||||
pub fn from_offset(offset:glam::Vec3) -> Self {
|
||||
Self{
|
||||
offset,
|
||||
angles: glam::DVec2::ZERO,
|
||||
fov: glam::vec2(aspect,1.0),
|
||||
sensitivity: glam::dvec2(1.0/6144.0,1.0/6144.0),
|
||||
time: 0,
|
||||
offset,
|
||||
angles: glam::DVec2::ZERO,
|
||||
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0),
|
||||
mouse:MouseState{pos:glam::IVec2::ZERO,time:-1},//escape initialization hell divide by zero
|
||||
}
|
||||
}
|
||||
fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
|
||||
let mut a=self.angles-self.sensitivity*delta.as_dvec2();
|
||||
pub fn simulate_move_angles(&self, mouse_pos: glam::IVec2) -> glam::DVec2 {
|
||||
let mut a=self.angles-self.sensitivity*(mouse_pos-self.mouse.pos).as_dvec2();
|
||||
a.y=a.y.clamp(-std::f64::consts::FRAC_PI_2, std::f64::consts::FRAC_PI_2);
|
||||
return a
|
||||
}
|
||||
fn simulate_move_rotation_y(&self, delta_x: i32) -> glam::Mat3 {
|
||||
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*(delta_x as f64))
|
||||
}
|
||||
pub fn proj(&self)->glam::Mat4{
|
||||
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
||||
}
|
||||
pub fn view(&self,pos:glam::Vec3)->glam::Mat4{
|
||||
//f32 good enough for view matrix
|
||||
glam::Mat4::from_translation(pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.angles.x as f32, self.angles.y as f32, 0f32)
|
||||
}
|
||||
pub fn set_fov_aspect(&mut self,fov:f32,aspect:f32){
|
||||
self.fov.x=fov*aspect;
|
||||
self.fov.y=fov;
|
||||
fn simulate_move_rotation_y(&self, mouse_pos_x: i32) -> glam::Mat3 {
|
||||
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*((mouse_pos_x-self.mouse.pos.x) as f64))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GameMechanicsState{
|
||||
pub spawn_id:u32,
|
||||
pub stage_id:u32,
|
||||
//jump_counts:HashMap<u32,u32>,
|
||||
}
|
||||
impl std::default::Default for GameMechanicsState{
|
||||
fn default() -> Self {
|
||||
Self{
|
||||
spawn_id:0,
|
||||
stage_id:0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -277,7 +235,7 @@ impl StyleModifiers{
|
||||
const UP_DIR:glam::Vec3 = glam::Vec3::Y;
|
||||
|
||||
fn get_control(&self,control:u32,controls:u32)->bool{
|
||||
controls&self.controls_mask&control!=0
|
||||
controls&self.controls_mask&control==control
|
||||
}
|
||||
|
||||
fn get_control_dir(&self,controls:u32)->glam::Vec3{
|
||||
@ -317,11 +275,12 @@ pub struct PhysicsState{
|
||||
pub world:WorldState,//currently there is only one state the world can be in
|
||||
pub game:GameMechanicsState,
|
||||
pub style:StyleModifiers,
|
||||
pub contacts:std::collections::HashSet::<RelativeCollision>,
|
||||
pub contacts:std::collections::HashMap::<u32,RelativeCollision>,
|
||||
pub intersects:std::collections::HashMap::<u32,RelativeCollision>,
|
||||
//pub intersections: Vec<ModelId>,
|
||||
//camera must exist in state because wormholes modify the camera, also camera punch
|
||||
pub camera:Camera,
|
||||
pub mouse_interpolation:MouseInterpolationState,
|
||||
pub camera:PhysicsCamera,
|
||||
pub next_mouse:MouseState,//Where is the mouse headed next
|
||||
pub controls:u32,
|
||||
pub walk:WalkState,
|
||||
pub grounded:bool,
|
||||
@ -329,10 +288,21 @@ pub struct PhysicsState{
|
||||
pub models:Vec<ModelPhysics>,
|
||||
|
||||
pub modes:Vec<crate::model::ModeDescription>,
|
||||
pub mode_from_mode_id:std::collections::HashMap::<u32,usize>,
|
||||
//the spawn point is where you spawn when you load into the map.
|
||||
//This is not the same as Reset which teleports you to Spawn0
|
||||
pub spawn_point:glam::Vec3,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct PhysicsOutputState{
|
||||
camera:PhysicsCamera,
|
||||
body:Body,
|
||||
}
|
||||
impl PhysicsOutputState{
|
||||
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){
|
||||
(self.body.extrapolated_position(mouse.time),self.camera.simulate_move_angles(mouse.pos).as_vec2())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub enum AabbFace{
|
||||
@ -458,6 +428,7 @@ pub struct ModelPhysics {
|
||||
//A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es
|
||||
//in this iteration, all it needs is extents.
|
||||
mesh: TreyMesh,
|
||||
transform:glam::Affine3A,
|
||||
attributes:PhysicsCollisionAttributes,
|
||||
}
|
||||
|
||||
@ -470,13 +441,14 @@ impl ModelPhysics {
|
||||
Self{
|
||||
mesh:aabb,
|
||||
attributes,
|
||||
transform:transform.clone(),
|
||||
}
|
||||
}
|
||||
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
|
||||
match &instance.attributes{
|
||||
crate::model::CollisionAttributes::Decoration=>None,
|
||||
crate::model::CollisionAttributes::Contact{contacting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})),
|
||||
crate::model::CollisionAttributes::Intersect{intersecting,general}=>None,//Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersecting{intersecting,general})),
|
||||
crate::model::CollisionAttributes::Intersect{intersecting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersect{intersecting:intersecting.clone(),general:general.clone()})),
|
||||
crate::model::CollisionAttributes::Decoration=>None,
|
||||
}
|
||||
}
|
||||
pub fn unit_vertices(&self) -> [glam::Vec3;8] {
|
||||
@ -552,10 +524,182 @@ impl Body {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PhysicsState{
|
||||
fn default() -> Self {
|
||||
Self{
|
||||
spawn_point:glam::vec3(0.0,50.0,0.0),
|
||||
body: Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
|
||||
time: 0,
|
||||
style:StyleModifiers::default(),
|
||||
grounded: false,
|
||||
contacts: std::collections::HashMap::new(),
|
||||
intersects: std::collections::HashMap::new(),
|
||||
models: Vec::new(),
|
||||
walk: WalkState::new(),
|
||||
camera: PhysicsCamera::from_offset(glam::vec3(0.0,4.5-2.5,0.0)),
|
||||
next_mouse: MouseState::default(),
|
||||
controls: 0,
|
||||
world:WorldState{},
|
||||
game:GameMechanicsState::default(),
|
||||
modes:Vec::new(),
|
||||
mode_from_mode_id:std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PhysicsState {
|
||||
pub fn clear(&mut self){
|
||||
self.models.clear();
|
||||
self.modes.clear();
|
||||
self.contacts.clear();
|
||||
self.intersects.clear();
|
||||
}
|
||||
|
||||
pub fn into_worker(mut self)->crate::worker::Worker<TimedInstruction<InputInstruction>,PhysicsOutputState>{
|
||||
let mut last_time=0;
|
||||
//last_time: this indicates the last time the mouse position was known.
|
||||
//Only used to generate a MouseState right before mouse movement
|
||||
//to finalize a long period of no movement and avoid interpolating from a long out-of-date MouseState.
|
||||
let mut mouse_blocking=true;//waiting for next_mouse to be written
|
||||
let mut timeline=std::collections::VecDeque::new();
|
||||
crate::worker::Worker::new(self.output(),move |ins:TimedInstruction<InputInstruction>|{
|
||||
let run_queue=match &ins.instruction{
|
||||
InputInstruction::MoveMouse(_)=>{
|
||||
//I FORGOT TO EDIT THE MOVE MOUSE TIMESTAMPS
|
||||
if !mouse_blocking{
|
||||
//mouse has not been moving for a while.
|
||||
//make sure not to interpolate between two distant MouseStates.
|
||||
//generate a mouse instruction with no movement timestamped at last InputInstruction
|
||||
//Idle instructions are CRITICAL to keeping this value up to date
|
||||
//interpolate normally (now that prev mouse pos is up to date)
|
||||
// timeline.push_back(TimedInstruction{
|
||||
// time:last_time,
|
||||
// instruction:InputInstruction::MoveMouse(self.next_mouse.pos),
|
||||
// });
|
||||
}
|
||||
mouse_blocking=true;//block physics until the next mouse event or mouse event timeout.
|
||||
true//empty queue
|
||||
},
|
||||
_=>{
|
||||
if mouse_blocking{
|
||||
//maybe I can turn this inside out by making this anotehr state machine where 50_000_000 is an instruction timestamp
|
||||
//check if last mouse move is within 50ms
|
||||
if ins.time-self.next_mouse.time<50_000_000{
|
||||
false//do not empty queue
|
||||
}else{
|
||||
mouse_blocking=false;
|
||||
// timeline.push_back(TimedInstruction{
|
||||
// time:ins.time,
|
||||
// instruction:InputInstruction::MoveMouse(self.next_mouse.pos),
|
||||
// });
|
||||
true
|
||||
}
|
||||
}else{
|
||||
true
|
||||
}
|
||||
},
|
||||
};
|
||||
last_time=ins.time;
|
||||
timeline.push_back(ins);
|
||||
if run_queue{
|
||||
//empty queue
|
||||
while let Some(instruction)=timeline.pop_front(){
|
||||
self.run(instruction.time);
|
||||
self.process_instruction(TimedInstruction{
|
||||
time:instruction.time,
|
||||
instruction:PhysicsInstruction::Input(instruction.instruction),
|
||||
});
|
||||
}
|
||||
}
|
||||
self.output()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn output(&self)->PhysicsOutputState{
|
||||
PhysicsOutputState{
|
||||
body:self.body.clone(),
|
||||
camera:self.camera.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
|
||||
let mut starts=Vec::new();
|
||||
let mut spawns=Vec::new();
|
||||
let mut ordered_checkpoints=Vec::new();
|
||||
let mut unordered_checkpoints=Vec::new();
|
||||
for model in &indexed_models.models{
|
||||
//make aabb and run vertices to get realistic bounds
|
||||
for model_instance in &model.instances{
|
||||
if let Some(model_physics)=ModelPhysics::from_model(model,model_instance){
|
||||
let model_id=self.models.len() as u32;
|
||||
self.models.push(model_physics);
|
||||
for attr in &model_instance.temp_indexing{
|
||||
match attr{
|
||||
crate::model::TempIndexedAttributes::Start{mode_id}=>starts.push((*mode_id,model_id)),
|
||||
crate::model::TempIndexedAttributes::Spawn{mode_id,stage_id}=>spawns.push((*mode_id,model_id,*stage_id)),
|
||||
crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id,checkpoint_id}=>ordered_checkpoints.push((*mode_id,model_id,*checkpoint_id)),
|
||||
crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id}=>unordered_checkpoints.push((*mode_id,model_id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//I don't wanna write structs for temporary structures
|
||||
//this code builds ModeDescriptions from the unsorted lists at the top of the function
|
||||
starts.sort_by_key(|tup|tup.0);
|
||||
let mut eshmep=std::collections::HashMap::new();
|
||||
let mut modedatas:Vec<(u32,Vec<(u32,u32)>,Vec<(u32,u32)>,Vec<u32>)>=starts.into_iter().enumerate().map(|(i,tup)|{
|
||||
eshmep.insert(tup.0,i);
|
||||
(tup.1,Vec::new(),Vec::new(),Vec::new())
|
||||
}).collect();
|
||||
for tup in spawns{
|
||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||
modedata.1.push((tup.2,tup.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
for tup in ordered_checkpoints{
|
||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||
modedata.2.push((tup.2,tup.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
for tup in unordered_checkpoints{
|
||||
if let Some(mode_id)=eshmep.get(&tup.0){
|
||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
||||
modedata.3.push(tup.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
let num_modes=self.modes.len();
|
||||
for (mode_id,mode) in eshmep{
|
||||
self.mode_from_mode_id.insert(mode_id,num_modes+mode);
|
||||
}
|
||||
self.modes.append(&mut modedatas.into_iter().map(|mut tup|{
|
||||
tup.1.sort_by_key(|tup|tup.0);
|
||||
tup.2.sort_by_key(|tup|tup.0);
|
||||
let mut eshmep1=std::collections::HashMap::new();
|
||||
let mut eshmep2=std::collections::HashMap::new();
|
||||
crate::model::ModeDescription{
|
||||
start:tup.0,
|
||||
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
|
||||
ordered_checkpoints:tup.2.into_iter().enumerate().map(|(i,tup)|{eshmep2.insert(tup.0,i);tup.1}).collect(),
|
||||
unordered_checkpoints:tup.3,
|
||||
spawn_from_stage_id:eshmep1,
|
||||
ordered_checkpoint_from_checkpoint_id:eshmep2,
|
||||
}
|
||||
}).collect());
|
||||
println!("Physics Objects: {}",self.models.len());
|
||||
}
|
||||
|
||||
pub fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
|
||||
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
|
||||
self.modes.get(mode)
|
||||
}else{
|
||||
None
|
||||
}
|
||||
}
|
||||
//tickless gaming
|
||||
pub fn run(&mut self, time_limit:TIME){
|
||||
@ -583,7 +727,7 @@ impl PhysicsState {
|
||||
}
|
||||
|
||||
fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){
|
||||
for contact in self.contacts.iter() {
|
||||
for (_,contact) in &self.contacts {
|
||||
let n=contact.normal(&self.models);
|
||||
let d=velocity.dot(n);
|
||||
if d<0f32{
|
||||
@ -592,7 +736,7 @@ impl PhysicsState {
|
||||
}
|
||||
}
|
||||
fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){
|
||||
for contact in self.contacts.iter() {
|
||||
for (_,contact) in &self.contacts {
|
||||
let n=contact.normal(&self.models);
|
||||
let d=acceleration.dot(n);
|
||||
if d<0f32{
|
||||
@ -965,12 +1109,19 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
|
||||
//JUST POLLING!!! NO MUTATION
|
||||
let mut collector = crate::instruction::InstructionCollector::new(time_limit);
|
||||
//check for collision stop instructions with curent contacts
|
||||
for collision_data in self.contacts.iter() {
|
||||
for (_,collision_data) in &self.contacts {
|
||||
collector.collect(self.predict_collision_end(self.time,time_limit,collision_data));
|
||||
}
|
||||
// for collision_data in &self.intersects{
|
||||
// collector.collect(self.predict_collision_end2(self.time,time_limit,collision_data));
|
||||
// }
|
||||
//check for collision start instructions (against every part in the game with no optimization!!)
|
||||
for i in 0..self.models.len() {
|
||||
collector.collect(self.predict_collision_start(self.time,time_limit,i as u32));
|
||||
let i=i as u32;
|
||||
if self.contacts.contains_key(&i)||self.intersects.contains_key(&i){
|
||||
continue;
|
||||
}
|
||||
collector.collect(self.predict_collision_start(self.time,time_limit,i));
|
||||
}
|
||||
if self.grounded {
|
||||
//walk maintenance
|
||||
@ -986,59 +1137,112 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
|
||||
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
|
||||
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
|
||||
match &ins.instruction {
|
||||
PhysicsInstruction::StrafeTick => (),
|
||||
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
|
||||
_=>println!("{:?}",ins),
|
||||
PhysicsInstruction::Input(InputInstruction::Idle)
|
||||
|PhysicsInstruction::Input(InputInstruction::MoveMouse(_))
|
||||
|PhysicsInstruction::StrafeTick => (),
|
||||
_=>println!("{:?}",ins),
|
||||
}
|
||||
//selectively update body
|
||||
match &ins.instruction {
|
||||
PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
|
||||
PhysicsInstruction::Input(_)
|
||||
|PhysicsInstruction::SetSpawnPosition(_)
|
||||
|PhysicsInstruction::ReachWalkTargetVelocity
|
||||
|PhysicsInstruction::CollisionStart(_)
|
||||
|PhysicsInstruction::CollisionEnd(_)
|
||||
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
|
||||
//PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
|
||||
PhysicsInstruction::Input(_)
|
||||
|PhysicsInstruction::ReachWalkTargetVelocity
|
||||
|PhysicsInstruction::CollisionStart(_)
|
||||
|PhysicsInstruction::CollisionEnd(_)
|
||||
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
|
||||
}
|
||||
match ins.instruction {
|
||||
PhysicsInstruction::SetSpawnPosition(position)=>{
|
||||
self.spawn_point=position;
|
||||
}
|
||||
PhysicsInstruction::CollisionStart(c) => {
|
||||
//check ground
|
||||
match &c.face {
|
||||
AabbFace::Top => {
|
||||
//ground
|
||||
self.grounded=true;
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
self.contacts.insert(c);
|
||||
//flatten v
|
||||
let mut v=self.body.velocity;
|
||||
self.contact_constrain_velocity(&mut v);
|
||||
self.body.velocity=v;
|
||||
if self.grounded&&self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
|
||||
self.jump();
|
||||
let model=c.model(&self.models).unwrap();
|
||||
match &model.attributes{
|
||||
PhysicsCollisionAttributes::Contact{contacting,general}=>{
|
||||
match &contacting.surf{
|
||||
Some(surf)=>println!("I'm surfing!"),
|
||||
None=>match &c.face {
|
||||
AabbFace::Top => {
|
||||
//ground
|
||||
self.grounded=true;
|
||||
},
|
||||
_ => (),
|
||||
},
|
||||
}
|
||||
//check ground
|
||||
self.contacts.insert(c.model,c);
|
||||
match &general.stage_element{
|
||||
Some(stage_element)=>{
|
||||
if stage_element.force||self.game.stage_id<stage_element.stage_id{
|
||||
self.game.stage_id=stage_element.stage_id;
|
||||
}
|
||||
match stage_element.behaviour{
|
||||
crate::model::StageElementBehaviour::SpawnAt=>(),
|
||||
crate::model::StageElementBehaviour::Trigger
|
||||
|crate::model::StageElementBehaviour::Teleport=>{
|
||||
//TODO make good
|
||||
if let Some(mode)=self.get_mode(stage_element.mode_id){
|
||||
if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){
|
||||
if let Some(model)=self.models.get(spawn as usize){
|
||||
self.body.position=model.transform.transform_point3(glam::Vec3::Y)+glam::Vec3::Y*(self.style.hitbox_halfsize.y+0.1);
|
||||
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
|
||||
self.contacts.clear();
|
||||
self.intersects.clear();
|
||||
self.body.acceleration=self.style.gravity;
|
||||
self.walk.state=WalkEnum::Reached;
|
||||
self.grounded=false;
|
||||
}else{println!("bad1");}
|
||||
}else{println!("bad2");}
|
||||
}else{println!("bad3");}
|
||||
},
|
||||
crate::model::StageElementBehaviour::Platform=>(),
|
||||
}
|
||||
},
|
||||
None=>(),
|
||||
}
|
||||
//flatten v
|
||||
let mut v=self.body.velocity;
|
||||
self.contact_constrain_velocity(&mut v);
|
||||
match &general.booster{
|
||||
Some(booster)=>{
|
||||
v+=booster.velocity;
|
||||
self.contact_constrain_velocity(&mut v);
|
||||
},
|
||||
None=>(),
|
||||
}
|
||||
self.body.velocity=v;
|
||||
if self.grounded&&self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
|
||||
self.jump();
|
||||
}
|
||||
self.refresh_walk_target();
|
||||
},
|
||||
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
|
||||
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
|
||||
self.intersects.insert(c.model,c);
|
||||
},
|
||||
}
|
||||
self.refresh_walk_target();
|
||||
},
|
||||
PhysicsInstruction::CollisionEnd(c) => {
|
||||
self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration
|
||||
let mut a=self.style.gravity;
|
||||
self.contact_constrain_acceleration(&mut a);
|
||||
self.body.acceleration=a;
|
||||
//check ground
|
||||
match &c.face {
|
||||
AabbFace::Top => {
|
||||
self.grounded=false;
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
self.refresh_walk_target();
|
||||
let model=c.model(&self.models).unwrap();
|
||||
match &model.attributes{
|
||||
PhysicsCollisionAttributes::Contact{contacting,general}=>{
|
||||
self.contacts.remove(&c.model);//remove contact before calling contact_constrain_acceleration
|
||||
let mut a=self.style.gravity;
|
||||
self.contact_constrain_acceleration(&mut a);
|
||||
self.body.acceleration=a;
|
||||
//check ground
|
||||
match &c.face {
|
||||
AabbFace::Top => {
|
||||
self.grounded=false;
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
self.refresh_walk_target();
|
||||
},
|
||||
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
|
||||
self.intersects.remove(&c.model);
|
||||
},
|
||||
}
|
||||
},
|
||||
PhysicsInstruction::StrafeTick => {
|
||||
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
|
||||
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
|
||||
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
|
||||
let d=self.body.velocity.dot(control_dir);
|
||||
if d<self.style.mv {
|
||||
@ -1062,8 +1266,9 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
let mut refresh_walk_target_velocity=true;
|
||||
match input_instruction{
|
||||
InputInstruction::MoveMouse(m) => {
|
||||
self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0);
|
||||
self.mouse_interpolation.move_mouse(self.time,m);
|
||||
self.camera.angles=self.camera.simulate_move_angles(self.next_mouse.pos);
|
||||
self.camera.mouse.move_mouse(self.next_mouse.pos,self.next_mouse.time);
|
||||
self.next_mouse.move_mouse(m,self.time);
|
||||
},
|
||||
InputInstruction::MoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
|
||||
InputInstruction::MoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s),
|
||||
@ -1098,7 +1303,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
if refresh_walk_target{
|
||||
//calculate walk target velocity
|
||||
if refresh_walk_target_velocity{
|
||||
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
|
||||
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
|
||||
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
|
||||
self.walk.target_velocity=self.style.walkspeed*control_dir;
|
||||
}
|
82
src/worker.rs
Normal file
82
src/worker.rs
Normal file
@ -0,0 +1,82 @@
|
||||
use std::thread;
|
||||
use std::sync::{mpsc,Arc};
|
||||
use parking_lot::Mutex;
|
||||
|
||||
//The goal here is to have a worker thread that parks itself when it runs out of work.
|
||||
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
|
||||
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
|
||||
|
||||
pub struct Worker<Task:Send,Value:Clone> {
|
||||
sender: mpsc::Sender<Task>,
|
||||
value:Arc<Mutex<Value>>,
|
||||
}
|
||||
|
||||
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
||||
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
|
||||
let (sender, receiver) = mpsc::channel::<Task>();
|
||||
let ret=Self {
|
||||
sender,
|
||||
value:Arc::new(Mutex::new(value)),
|
||||
};
|
||||
let value=ret.value.clone();
|
||||
thread::spawn(move || {
|
||||
loop {
|
||||
match receiver.recv() {
|
||||
Ok(task) => {
|
||||
let v=f(task);//make sure function is evaluated before lock is acquired
|
||||
*value.lock()=v;
|
||||
}
|
||||
Err(_) => {
|
||||
println!("Worker stopping.",);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
|
||||
self.sender.send(task)
|
||||
}
|
||||
|
||||
pub fn grab_clone(&self)->Value{
|
||||
self.value.lock().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]//How to run this test with printing: cargo test --release -- --nocapture
|
||||
fn test_worker() {
|
||||
println!("hiiiii");
|
||||
// Create the worker thread
|
||||
let worker = Worker::new(crate::physics::Body::with_pva(glam::Vec3::ZERO,glam::Vec3::ZERO,glam::Vec3::ZERO),
|
||||
|_|crate::physics::Body::with_pva(glam::Vec3::ONE,glam::Vec3::ONE,glam::Vec3::ONE)
|
||||
);
|
||||
|
||||
// Send tasks to the worker
|
||||
for i in 0..5 {
|
||||
let task = crate::instruction::TimedInstruction{
|
||||
time:0,
|
||||
instruction:crate::physics::PhysicsInstruction::StrafeTick,
|
||||
};
|
||||
worker.send(task).unwrap();
|
||||
}
|
||||
|
||||
// Optional: Signal the worker to stop (in a real-world scenario)
|
||||
// sender.send("STOP".to_string()).unwrap();
|
||||
|
||||
// Sleep to allow the worker thread to finish processing
|
||||
thread::sleep(std::time::Duration::from_secs(2));
|
||||
|
||||
// Send a new task
|
||||
let task = crate::instruction::TimedInstruction{
|
||||
time:0,
|
||||
instruction:crate::physics::PhysicsInstruction::StrafeTick,
|
||||
};
|
||||
worker.send(task).unwrap();
|
||||
|
||||
println!("value={:?}",worker.grab_clone());
|
||||
|
||||
// wait long enough to see print from final task
|
||||
thread::sleep(std::time::Duration::from_secs(1));
|
||||
}
|
Reference in New Issue
Block a user