forked from StrafesNET/strafe-project
Compare commits
36 Commits
worker-poo
...
worker-sco
Author | SHA1 | Date | |
---|---|---|---|
580bbf2cc5 | |||
08f6d928cf | |||
de7b7ba7be | |||
008c66e052 | |||
ba250277bd | |||
085d4e7912 | |||
dd6b5bed24 | |||
9d4cadda30 | |||
242b4ab470 | |||
eaef3d3fd5 | |||
9d726c5419 | |||
9592f82c4e | |||
873c6ab935 | |||
7ba94c1b30 | |||
8fc6a7fb8f | |||
a3340143db | |||
9fc7884270 | |||
953b17bc69 | |||
8fcb4e5c6c | |||
073a076fe8 | |||
9848d66001 | |||
6474ddcbd1 | |||
c4cd73e914 | |||
bbb1857377 | |||
883be0bc01 | |||
5885036f8f | |||
076dab23cf | |||
c1001d6f37 | |||
08d4e7d997 | |||
e1f4f6e535 | |||
3a4c4ef9fe | |||
41dd155c50 | |||
5fd6ca219b | |||
1c22f4a3c3 | |||
1e6c489750 | |||
9f62f5f2fd |
1152
Cargo.lock
generated
1152
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -18,8 +18,8 @@ rbx_binary = "0.7.1"
|
|||||||
rbx_dom_weak = "2.5.0"
|
rbx_dom_weak = "2.5.0"
|
||||||
rbx_reflection_database = "0.2.7"
|
rbx_reflection_database = "0.2.7"
|
||||||
rbx_xml = "0.13.1"
|
rbx_xml = "0.13.1"
|
||||||
wgpu = "0.17.0"
|
wgpu = "0.18.0"
|
||||||
winit = "0.28.6"
|
winit = { version = "0.29.2", features = ["rwh_05"] }
|
||||||
|
|
||||||
#[profile.release]
|
#[profile.release]
|
||||||
#lto = true
|
#lto = true
|
||||||
|
44
src/bvh.rs
44
src/bvh.rs
@ -9,22 +9,34 @@ use crate::aabb::Aabb;
|
|||||||
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh
|
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh
|
||||||
//sort the centerpoints on each axis (3 lists)
|
//sort the centerpoints on each axis (3 lists)
|
||||||
//bv is put into octant based on whether it is upper or lower in each list
|
//bv is put into octant based on whether it is upper or lower in each list
|
||||||
|
enum BvhNodeContent{
|
||||||
|
Branch(Vec<BvhNode>),
|
||||||
|
Leaf(usize),
|
||||||
|
}
|
||||||
|
impl Default for BvhNodeContent{
|
||||||
|
fn default()->Self{
|
||||||
|
Self::Branch(Vec::new())
|
||||||
|
}
|
||||||
|
}
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct BvhNode{
|
pub struct BvhNode{
|
||||||
children:Vec<Self>,
|
content:BvhNodeContent,
|
||||||
models:Vec<usize>,
|
|
||||||
aabb:Aabb,
|
aabb:Aabb,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BvhNode{
|
impl BvhNode{
|
||||||
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
|
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
|
||||||
for &model in &self.models{
|
match &self.content{
|
||||||
f(model);
|
&BvhNodeContent::Leaf(model)=>f(model),
|
||||||
}
|
BvhNodeContent::Branch(children)=>for child in children{
|
||||||
for child in &self.children{
|
//this test could be moved outside the match statement
|
||||||
if aabb.intersects(&child.aabb){
|
//but that would test the root node aabb
|
||||||
child.the_tester(aabb,f);
|
//you're probably not going to spend a lot of time outside the map,
|
||||||
}
|
//so the test is extra work for nothing
|
||||||
|
if aabb.intersects(&child.aabb){
|
||||||
|
child.the_tester(aabb,f);
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -37,10 +49,15 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
|||||||
let n=boxen.len();
|
let n=boxen.len();
|
||||||
if n<20{
|
if n<20{
|
||||||
let mut aabb=Aabb::default();
|
let mut aabb=Aabb::default();
|
||||||
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0}).collect();
|
let nodes=boxen.into_iter().map(|b|{
|
||||||
|
aabb.join(&b.1);
|
||||||
|
BvhNode{
|
||||||
|
content:BvhNodeContent::Leaf(b.0),
|
||||||
|
aabb:b.1,
|
||||||
|
}
|
||||||
|
}).collect();
|
||||||
BvhNode{
|
BvhNode{
|
||||||
children:Vec::new(),
|
content:BvhNodeContent::Branch(nodes),
|
||||||
models,
|
|
||||||
aabb,
|
aabb,
|
||||||
}
|
}
|
||||||
}else{
|
}else{
|
||||||
@ -99,8 +116,7 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
|||||||
node
|
node
|
||||||
}).collect();
|
}).collect();
|
||||||
BvhNode{
|
BvhNode{
|
||||||
children,
|
content:BvhNodeContent::Branch(children),
|
||||||
models:Vec::new(),
|
|
||||||
aabb,
|
aabb,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
21
src/compat_worker.rs
Normal file
21
src/compat_worker.rs
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
pub type QNWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||||
|
pub type INWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||||
|
|
||||||
|
pub struct CompatNWorker<'a,Task>{
|
||||||
|
data:std::marker::PhantomData<Task>,
|
||||||
|
f:Box<dyn FnMut(Task)+Send+'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a,Task> CompatNWorker<'a,Task>{
|
||||||
|
pub fn new(f:impl FnMut(Task)+Send+'a)->CompatNWorker<'a,Task>{
|
||||||
|
Self{
|
||||||
|
data:std::marker::PhantomData,
|
||||||
|
f:Box::new(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send(&mut self,task:Task)->Result<(),()>{
|
||||||
|
(self.f)(task);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
211
src/graphics.rs
211
src/graphics.rs
@ -1,30 +1,38 @@
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
|
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
|
||||||
use crate::model_graphics::{GraphicsVertex,ModelGraphicsColor4,ModelGraphicsInstance,ModelGraphicsSingleTexture,IndexedModelGraphicsSingleTexture,IndexedGroupFixedTexture};
|
use crate::model_graphics::{GraphicsVertex,GraphicsModelColor4,GraphicsModelInstance,GraphicsModelSingleTexture,IndexedGraphicsModelSingleTexture,IndexedGroupFixedTexture};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ModelUpdate{
|
pub struct GraphicsModelUpdate{
|
||||||
transform:Option<glam::Mat4>,
|
transform:Option<glam::Mat4>,
|
||||||
color:Option<glam::Vec4>,
|
color:Option<glam::Vec4>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
struct Entity{
|
||||||
pub enum GraphicsInstruction{
|
index_count:u32,
|
||||||
UpdateModel(ModelUpdate),
|
index_buf:wgpu::Buffer,
|
||||||
Render,
|
}
|
||||||
|
fn create_entities<T:bytemuck::Pod>(device:&wgpu::Device,entities:&Vec<Vec<T>>)->Vec<Entity>{
|
||||||
|
entities.iter().map(|indices|{
|
||||||
|
let index_buf=device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
|
||||||
|
label:Some("Index"),
|
||||||
|
contents:bytemuck::cast_slice(indices),
|
||||||
|
usage:wgpu::BufferUsages::INDEX,
|
||||||
|
});
|
||||||
|
Entity{
|
||||||
|
index_buf,
|
||||||
|
index_count:indices.len() as u32,
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Entity {
|
struct GraphicsModel{
|
||||||
index_count: u32,
|
entities:Vec<Entity>,
|
||||||
index_buf: wgpu::Buffer,
|
model_buf:wgpu::Buffer,
|
||||||
}
|
vertex_buf:wgpu::Buffer,
|
||||||
|
bind_group:wgpu::BindGroup,
|
||||||
struct ModelGraphics {
|
index_format:wgpu::IndexFormat,
|
||||||
instances: Vec<ModelGraphicsInstance>,
|
instances:Vec<GraphicsModelInstance>,
|
||||||
vertex_buf: wgpu::Buffer,
|
|
||||||
entities: Vec<Entity>,
|
|
||||||
bind_group: wgpu::BindGroup,
|
|
||||||
model_buf: wgpu::Buffer,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct GraphicsSamplers{
|
pub struct GraphicsSamplers{
|
||||||
@ -63,12 +71,6 @@ fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
impl GraphicsCamera{
|
impl GraphicsCamera{
|
||||||
pub fn new(screen_size:glam::UVec2,fov:glam::Vec2)->Self{
|
|
||||||
Self{
|
|
||||||
screen_size,
|
|
||||||
fov,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn proj(&self)->glam::Mat4{
|
pub fn proj(&self)->glam::Mat4{
|
||||||
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
||||||
}
|
}
|
||||||
@ -91,6 +93,14 @@ impl GraphicsCamera{
|
|||||||
raw
|
raw
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl std::default::Default for GraphicsCamera{
|
||||||
|
fn default()->Self{
|
||||||
|
Self{
|
||||||
|
screen_size:glam::UVec2::ONE,
|
||||||
|
fov:glam::Vec2::ONE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct GraphicsState{
|
pub struct GraphicsState{
|
||||||
pipelines: GraphicsPipelines,
|
pipelines: GraphicsPipelines,
|
||||||
@ -100,7 +110,7 @@ pub struct GraphicsState{
|
|||||||
camera:GraphicsCamera,
|
camera:GraphicsCamera,
|
||||||
camera_buf: wgpu::Buffer,
|
camera_buf: wgpu::Buffer,
|
||||||
temp_squid_texture_view: wgpu::TextureView,
|
temp_squid_texture_view: wgpu::TextureView,
|
||||||
models: Vec<ModelGraphics>,
|
models: Vec<GraphicsModel>,
|
||||||
depth_view: wgpu::TextureView,
|
depth_view: wgpu::TextureView,
|
||||||
staging_belt: wgpu::util::StagingBelt,
|
staging_belt: wgpu::util::StagingBelt,
|
||||||
}
|
}
|
||||||
@ -134,7 +144,7 @@ impl GraphicsState{
|
|||||||
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
|
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
|
||||||
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
||||||
}
|
}
|
||||||
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:crate::model::IndexedModelInstances){
|
pub fn generate_models(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:crate::model::IndexedModelInstances){
|
||||||
//generate texture view per texture
|
//generate texture view per texture
|
||||||
|
|
||||||
//idk how to do this gooder lol
|
//idk how to do this gooder lol
|
||||||
@ -204,15 +214,15 @@ impl GraphicsState{
|
|||||||
let indexed_models_len=indexed_models.models.len();
|
let indexed_models_len=indexed_models.models.len();
|
||||||
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
|
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
|
||||||
for model in indexed_models.models.into_iter(){
|
for model in indexed_models.models.into_iter(){
|
||||||
//convert ModelInstance into ModelGraphicsInstance
|
//convert ModelInstance into GraphicsModelInstance
|
||||||
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
|
let instances:Vec<GraphicsModelInstance>=model.instances.into_iter().filter_map(|instance|{
|
||||||
if instance.color.w==0.0{
|
if instance.color.w==0.0{
|
||||||
None
|
None
|
||||||
}else{
|
}else{
|
||||||
Some(ModelGraphicsInstance{
|
Some(GraphicsModelInstance{
|
||||||
transform: instance.transform.into(),
|
transform: instance.transform.into(),
|
||||||
normal_transform: Into::<glam::Mat3>::into(instance.transform.matrix3).inverse().transpose(),
|
normal_transform: Into::<glam::Mat3>::into(instance.transform.matrix3).inverse().transpose(),
|
||||||
color:ModelGraphicsColor4::from(instance.color),
|
color:GraphicsModelColor4::from(instance.color),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}).collect();
|
}).collect();
|
||||||
@ -231,7 +241,7 @@ impl GraphicsState{
|
|||||||
//create new texture_index
|
//create new texture_index
|
||||||
let texture_index=unique_textures.len();
|
let texture_index=unique_textures.len();
|
||||||
unique_textures.push(group.texture);
|
unique_textures.push(group.texture);
|
||||||
unique_texture_models.push(IndexedModelGraphicsSingleTexture{
|
unique_texture_models.push(IndexedGraphicsModelSingleTexture{
|
||||||
unique_pos:model.unique_pos.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
unique_pos:model.unique_pos.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||||
unique_tex:model.unique_tex.iter().map(|v|*v.as_ref()).collect(),
|
unique_tex:model.unique_tex.iter().map(|v|*v.as_ref()).collect(),
|
||||||
unique_normal:model.unique_normal.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
unique_normal:model.unique_normal.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||||
@ -365,10 +375,10 @@ impl GraphicsState{
|
|||||||
//creating the vertex map is slightly different because the vertices are directly hashable
|
//creating the vertex map is slightly different because the vertices are directly hashable
|
||||||
let map_vertex_id:Vec<u32>=model.unique_vertices.iter().map(|unmapped_vertex|{
|
let map_vertex_id:Vec<u32>=model.unique_vertices.iter().map(|unmapped_vertex|{
|
||||||
let vertex=crate::model::IndexedVertex{
|
let vertex=crate::model::IndexedVertex{
|
||||||
pos:map_pos_id[unmapped_vertex.pos as usize] as u32,
|
pos:map_pos_id[unmapped_vertex.pos as usize],
|
||||||
tex:map_tex_id[unmapped_vertex.tex as usize] as u32,
|
tex:map_tex_id[unmapped_vertex.tex as usize],
|
||||||
normal:map_normal_id[unmapped_vertex.normal as usize] as u32,
|
normal:map_normal_id[unmapped_vertex.normal as usize],
|
||||||
color:map_color_id[unmapped_vertex.color as usize] as u32,
|
color:map_color_id[unmapped_vertex.color as usize],
|
||||||
};
|
};
|
||||||
(if let Some(&vertex_id)=vertex_id_from.get(&vertex){
|
(if let Some(&vertex_id)=vertex_id_from.get(&vertex){
|
||||||
vertex_id
|
vertex_id
|
||||||
@ -386,7 +396,7 @@ impl GraphicsState{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
//push model into dedup
|
//push model into dedup
|
||||||
deduplicated_models.push(IndexedModelGraphicsSingleTexture{
|
deduplicated_models.push(IndexedGraphicsModelSingleTexture{
|
||||||
unique_pos,
|
unique_pos,
|
||||||
unique_tex,
|
unique_tex,
|
||||||
unique_normal,
|
unique_normal,
|
||||||
@ -396,7 +406,7 @@ impl GraphicsState{
|
|||||||
groups:vec![IndexedGroupFixedTexture{
|
groups:vec![IndexedGroupFixedTexture{
|
||||||
polys
|
polys
|
||||||
}],
|
}],
|
||||||
instances:vec![ModelGraphicsInstance{
|
instances:vec![GraphicsModelInstance{
|
||||||
transform:glam::Mat4::IDENTITY,
|
transform:glam::Mat4::IDENTITY,
|
||||||
normal_transform:glam::Mat3::IDENTITY,
|
normal_transform:glam::Mat3::IDENTITY,
|
||||||
color
|
color
|
||||||
@ -414,10 +424,9 @@ impl GraphicsState{
|
|||||||
|
|
||||||
//de-index models
|
//de-index models
|
||||||
let deduplicated_models_len=deduplicated_models.len();
|
let deduplicated_models_len=deduplicated_models.len();
|
||||||
let models:Vec<ModelGraphicsSingleTexture>=deduplicated_models.into_iter().map(|model|{
|
let models:Vec<GraphicsModelSingleTexture>=deduplicated_models.into_iter().map(|model|{
|
||||||
let mut vertices = Vec::new();
|
let mut vertices = Vec::new();
|
||||||
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
|
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
|
||||||
let mut entities = Vec::new();
|
|
||||||
//this mut be combined in a more complex way if the models use different render patterns per group
|
//this mut be combined in a more complex way if the models use different render patterns per group
|
||||||
let mut indices = Vec::new();
|
let mut indices = Vec::new();
|
||||||
for group in model.groups {
|
for group in model.groups {
|
||||||
@ -428,7 +437,7 @@ impl GraphicsState{
|
|||||||
if let Some(&i)=index_from_vertex.get(&vertex_index){
|
if let Some(&i)=index_from_vertex.get(&vertex_index){
|
||||||
indices.push(i);
|
indices.push(i);
|
||||||
}else{
|
}else{
|
||||||
let i=vertices.len() as u16;
|
let i=vertices.len();
|
||||||
let vertex=&model.unique_vertices[vertex_index as usize];
|
let vertex=&model.unique_vertices[vertex_index as usize];
|
||||||
vertices.push(GraphicsVertex{
|
vertices.push(GraphicsVertex{
|
||||||
pos: model.unique_pos[vertex.pos as usize],
|
pos: model.unique_pos[vertex.pos as usize],
|
||||||
@ -443,18 +452,23 @@ impl GraphicsState{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
entities.push(indices);
|
GraphicsModelSingleTexture{
|
||||||
ModelGraphicsSingleTexture{
|
|
||||||
instances:model.instances,
|
instances:model.instances,
|
||||||
|
entities:if (u32::MAX as usize)<vertices.len(){
|
||||||
|
panic!("Model has too many vertices!")
|
||||||
|
}else if (u16::MAX as usize)<vertices.len(){
|
||||||
|
crate::model_graphics::Entities::U32(vec![indices.into_iter().map(|vertex_id|vertex_id as u32).collect()])
|
||||||
|
}else{
|
||||||
|
crate::model_graphics::Entities::U16(vec![indices.into_iter().map(|vertex_id|vertex_id as u16).collect()])
|
||||||
|
},
|
||||||
vertices,
|
vertices,
|
||||||
entities,
|
|
||||||
texture:model.texture,
|
texture:model.texture,
|
||||||
}
|
}
|
||||||
}).collect();
|
}).collect();
|
||||||
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
|
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
|
||||||
let mut model_count=0;
|
let mut model_count=0;
|
||||||
let mut instance_count=0;
|
let mut instance_count=0;
|
||||||
let uniform_buffer_binding_size=crate::graphics_context::required_limits().max_uniform_buffer_binding_size as usize;
|
let uniform_buffer_binding_size=crate::setup::required_limits().max_uniform_buffer_binding_size as usize;
|
||||||
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
|
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
|
||||||
self.models.reserve(models.len());
|
self.models.reserve(models.len());
|
||||||
for model in models.into_iter() {
|
for model in models.into_iter() {
|
||||||
@ -500,20 +514,17 @@ impl GraphicsState{
|
|||||||
usage: wgpu::BufferUsages::VERTEX,
|
usage: wgpu::BufferUsages::VERTEX,
|
||||||
});
|
});
|
||||||
//all of these are being moved here
|
//all of these are being moved here
|
||||||
self.models.push(ModelGraphics{
|
self.models.push(GraphicsModel{
|
||||||
instances:instances_chunk.to_vec(),
|
instances:instances_chunk.to_vec(),
|
||||||
vertex_buf,
|
vertex_buf,
|
||||||
entities: model.entities.iter().map(|indices|{
|
index_format:match &model.entities{
|
||||||
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
crate::model_graphics::Entities::U32(_)=>wgpu::IndexFormat::Uint32,
|
||||||
label: Some("Index"),
|
crate::model_graphics::Entities::U16(_)=>wgpu::IndexFormat::Uint16,
|
||||||
contents: bytemuck::cast_slice(&indices),
|
},
|
||||||
usage: wgpu::BufferUsages::INDEX,
|
entities:match &model.entities{
|
||||||
});
|
crate::model_graphics::Entities::U32(entities)=>create_entities(device,entities),
|
||||||
Entity {
|
crate::model_graphics::Entities::U16(entities)=>create_entities(device,entities),
|
||||||
index_buf,
|
},
|
||||||
index_count: indices.len() as u32,
|
|
||||||
}
|
|
||||||
}).collect(),
|
|
||||||
bind_group: model_bind_group,
|
bind_group: model_bind_group,
|
||||||
model_buf,
|
model_buf,
|
||||||
});
|
});
|
||||||
@ -528,10 +539,9 @@ impl GraphicsState{
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn new(
|
pub fn new(
|
||||||
config: &wgpu::SurfaceConfiguration,
|
device:&wgpu::Device,
|
||||||
_adapter: &wgpu::Adapter,
|
queue:&wgpu::Queue,
|
||||||
device: &wgpu::Device,
|
config:&wgpu::SurfaceConfiguration,
|
||||||
queue: &wgpu::Queue,
|
|
||||||
)->Self{
|
)->Self{
|
||||||
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
label: None,
|
label: None,
|
||||||
@ -801,6 +811,7 @@ impl GraphicsState{
|
|||||||
}),
|
}),
|
||||||
primitive: wgpu::PrimitiveState {
|
primitive: wgpu::PrimitiveState {
|
||||||
front_face: wgpu::FrontFace::Cw,
|
front_face: wgpu::FrontFace::Cw,
|
||||||
|
cull_mode:Some(wgpu::Face::Front),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
depth_stencil: Some(wgpu::DepthStencilState {
|
depth_stencil: Some(wgpu::DepthStencilState {
|
||||||
@ -814,14 +825,8 @@ impl GraphicsState{
|
|||||||
multiview: None,
|
multiview: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut physics = crate::physics::PhysicsState::default();
|
let camera=GraphicsCamera::default();
|
||||||
|
let camera_uniforms = camera.to_uniform_data(crate::physics::PhysicsOutputState::default().extrapolate(glam::IVec2::ZERO,crate::integer::Time::ZERO));
|
||||||
physics.load_user_settings(&user_settings);
|
|
||||||
|
|
||||||
let screen_size=glam::uvec2(config.width,config.height);
|
|
||||||
|
|
||||||
let camera=GraphicsCamera::new(screen_size,user_settings.calculate_fov(1.0,&screen_size).as_vec2());
|
|
||||||
let camera_uniforms = camera.to_uniform_data(physics.output().adjust_mouse(&crate::physics::MouseState::default()));
|
|
||||||
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
label: Some("Camera"),
|
label: Some("Camera"),
|
||||||
contents: bytemuck::cast_slice(&camera_uniforms),
|
contents: bytemuck::cast_slice(&camera_uniforms),
|
||||||
@ -876,32 +881,30 @@ impl GraphicsState{
|
|||||||
}
|
}
|
||||||
pub fn resize(
|
pub fn resize(
|
||||||
&mut self,
|
&mut self,
|
||||||
context:&crate::graphics_context::GraphicsContext,
|
device:&wgpu::Device,
|
||||||
|
config:&wgpu::SurfaceConfiguration,
|
||||||
|
user_settings:&crate::settings::UserSettings,
|
||||||
) {
|
) {
|
||||||
self.depth_view = Self::create_depth_texture(&context.config,&context.device);
|
self.depth_view=Self::create_depth_texture(config,device);
|
||||||
self.camera.screen_size=glam::uvec2(context.config.width, context.config.height);
|
self.camera.screen_size=glam::uvec2(config.width,config.height);
|
||||||
self.load_user_settings(&self.user_settings);
|
self.load_user_settings(user_settings);
|
||||||
}
|
}
|
||||||
pub fn render(
|
pub fn render(
|
||||||
&mut self,
|
&mut self,
|
||||||
view: &wgpu::TextureView,
|
view:&wgpu::TextureView,
|
||||||
device: &wgpu::Device,
|
device:&wgpu::Device,
|
||||||
queue: &wgpu::Queue,
|
queue:&wgpu::Queue,
|
||||||
|
physics_output:crate::physics::PhysicsOutputState,
|
||||||
|
predicted_time:crate::integer::Time,
|
||||||
|
mouse_pos:glam::IVec2,
|
||||||
) {
|
) {
|
||||||
//ideally this would be scheduled to execute and finish right before the render.
|
//TODO: use scheduled frame times to create beautiful smoothing simulation physics extrapolation assuming no input
|
||||||
let time=crate::integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
|
|
||||||
self.physics_thread.send(crate::instruction::TimedInstruction{
|
|
||||||
time,
|
|
||||||
instruction:crate::render_thread::InputInstruction::Idle,
|
|
||||||
}).unwrap();
|
|
||||||
//update time lol
|
|
||||||
self.mouse.time=time;
|
|
||||||
|
|
||||||
let mut encoder =
|
let mut encoder =
|
||||||
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||||
|
|
||||||
// update rotation
|
// update rotation
|
||||||
let camera_uniforms = self.camera.to_uniform_data(self.physics_thread.grab_clone().adjust_mouse(&self.mouse));
|
let camera_uniforms = self.camera.to_uniform_data(physics_output.extrapolate(mouse_pos,predicted_time));
|
||||||
self.staging_belt
|
self.staging_belt
|
||||||
.write_buffer(
|
.write_buffer(
|
||||||
&mut encoder,
|
&mut encoder,
|
||||||
@ -941,17 +944,19 @@ impl GraphicsState{
|
|||||||
b: 0.3,
|
b: 0.3,
|
||||||
a: 1.0,
|
a: 1.0,
|
||||||
}),
|
}),
|
||||||
store: true,
|
store:wgpu::StoreOp::Store,
|
||||||
},
|
},
|
||||||
})],
|
})],
|
||||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||||
view: &self.depth_view,
|
view: &self.depth_view,
|
||||||
depth_ops: Some(wgpu::Operations {
|
depth_ops: Some(wgpu::Operations {
|
||||||
load: wgpu::LoadOp::Clear(1.0),
|
load: wgpu::LoadOp::Clear(1.0),
|
||||||
store: false,
|
store:wgpu::StoreOp::Discard,
|
||||||
}),
|
}),
|
||||||
stencil_ops: None,
|
stencil_ops: None,
|
||||||
}),
|
}),
|
||||||
|
timestamp_writes:Default::default(),
|
||||||
|
occlusion_query_set:Default::default(),
|
||||||
});
|
});
|
||||||
|
|
||||||
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
|
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
|
||||||
@ -962,9 +967,9 @@ impl GraphicsState{
|
|||||||
rpass.set_bind_group(2, &model.bind_group, &[]);
|
rpass.set_bind_group(2, &model.bind_group, &[]);
|
||||||
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
||||||
|
|
||||||
for entity in model.entities.iter() {
|
for entity in model.entities.iter(){
|
||||||
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
|
rpass.set_index_buffer(entity.index_buf.slice(..),model.index_format);
|
||||||
rpass.draw_indexed(0..entity.index_count, 0, 0..model.instances.len() as u32);
|
rpass.draw_indexed(0..entity.index_count,0,0..model.instances.len() as u32);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -979,22 +984,22 @@ impl GraphicsState{
|
|||||||
}
|
}
|
||||||
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
||||||
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
|
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
|
||||||
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
fn get_instances_buffer_data(instances:&[GraphicsModelInstance]) -> Vec<f32> {
|
||||||
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
||||||
for (i,mi) in instances.iter().enumerate(){
|
for (i,mi) in instances.iter().enumerate(){
|
||||||
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
|
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
|
||||||
//model transform
|
//model transform
|
||||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||||
//normal transform
|
//normal transform
|
||||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
|
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
|
||||||
raw.extend_from_slice(&[0.0]);
|
raw.extend_from_slice(&[0.0]);
|
||||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
|
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
|
||||||
raw.extend_from_slice(&[0.0]);
|
raw.extend_from_slice(&[0.0]);
|
||||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
|
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
|
||||||
raw.extend_from_slice(&[0.0]);
|
raw.extend_from_slice(&[0.0]);
|
||||||
//color
|
//color
|
||||||
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color.get()));
|
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color.get()));
|
||||||
raw.append(&mut v);
|
raw.append(&mut v);
|
||||||
}
|
}
|
||||||
raw
|
raw
|
||||||
}
|
}
|
||||||
|
71
src/graphics_worker.rs
Normal file
71
src/graphics_worker.rs
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
pub enum Instruction{
|
||||||
|
Render(crate::physics::PhysicsOutputState,crate::integer::Time,glam::IVec2),
|
||||||
|
//UpdateModel(crate::graphics::GraphicsModelUpdate),
|
||||||
|
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||||
|
GenerateModels(crate::model::IndexedModelInstances),
|
||||||
|
ClearModels,
|
||||||
|
}
|
||||||
|
|
||||||
|
//Ideally the graphics thread worker description is:
|
||||||
|
/*
|
||||||
|
WorkerDescription{
|
||||||
|
input:Immediate,
|
||||||
|
output:Realtime(PoolOrdering::Ordered(3)),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
//up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order
|
||||||
|
|
||||||
|
pub fn new<'a>(
|
||||||
|
scope:&'a std::thread::Scope<'a,'_>,
|
||||||
|
mut graphics:crate::graphics::GraphicsState,
|
||||||
|
mut config:wgpu::SurfaceConfiguration,
|
||||||
|
surface:wgpu::Surface,
|
||||||
|
device:wgpu::Device,
|
||||||
|
queue:wgpu::Queue,
|
||||||
|
)->crate::worker::INWorker<'a,Instruction>{
|
||||||
|
let mut resize=None;
|
||||||
|
crate::worker::INWorker::new(scope,move |ins:Instruction|{
|
||||||
|
match ins{
|
||||||
|
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||||
|
graphics.generate_models(&device,&queue,indexed_model_instances);
|
||||||
|
},
|
||||||
|
Instruction::ClearModels=>{
|
||||||
|
graphics.clear();
|
||||||
|
},
|
||||||
|
Instruction::Resize(size,user_settings)=>{
|
||||||
|
resize=Some((size,user_settings));
|
||||||
|
}
|
||||||
|
Instruction::Render(physics_output,predicted_time,mouse_pos)=>{
|
||||||
|
if let Some((size,user_settings))=&resize{
|
||||||
|
println!("Resizing to {:?}",size);
|
||||||
|
let t0=std::time::Instant::now();
|
||||||
|
config.width=size.width.max(1);
|
||||||
|
config.height=size.height.max(1);
|
||||||
|
surface.configure(&device,&config);
|
||||||
|
graphics.resize(&device,&config,user_settings);
|
||||||
|
println!("Resize took {:?}",t0.elapsed());
|
||||||
|
}
|
||||||
|
//clear every time w/e
|
||||||
|
resize=None;
|
||||||
|
//this has to go deeper somehow
|
||||||
|
let frame=match surface.get_current_texture(){
|
||||||
|
Ok(frame)=>frame,
|
||||||
|
Err(_)=>{
|
||||||
|
surface.configure(&device,&config);
|
||||||
|
surface
|
||||||
|
.get_current_texture()
|
||||||
|
.expect("Failed to acquire next surface texture!")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
|
||||||
|
format:Some(config.view_formats[0]),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
graphics.render(&view,&device,&queue,physics_output,predicted_time,mouse_pos);
|
||||||
|
|
||||||
|
frame.present();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@ -41,6 +41,11 @@ impl std::fmt::Display for Time{
|
|||||||
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl std::default::Default for Time{
|
||||||
|
fn default()->Self{
|
||||||
|
Self(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
impl std::ops::Neg for Time{
|
impl std::ops::Neg for Time{
|
||||||
type Output=Time;
|
type Output=Time;
|
||||||
#[inline]
|
#[inline]
|
||||||
@ -310,8 +315,8 @@ impl Angle32{
|
|||||||
pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{
|
pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{
|
||||||
//((max-min as u32)/2 as i32)+min
|
//((max-min as u32)/2 as i32)+min
|
||||||
let midpoint=((
|
let midpoint=((
|
||||||
u32::from_ne_bytes(theta_max.0.to_ne_bytes())
|
(theta_max.0 as u32)
|
||||||
.wrapping_sub(u32::from_ne_bytes(theta_min.0.to_ne_bytes()))
|
.wrapping_sub(theta_min.0 as u32)
|
||||||
/2
|
/2
|
||||||
) as i32)//(u32::MAX/2) as i32 ALWAYS works
|
) as i32)//(u32::MAX/2) as i32 ALWAYS works
|
||||||
.wrapping_add(theta_min.0);
|
.wrapping_add(theta_min.0);
|
||||||
|
@ -23,14 +23,6 @@ fn recursive_collect_superclass(objects: &mut std::vec::Vec<rbx_dom_weak::types:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>{
|
|
||||||
let mut objects = std::vec::Vec::new();
|
|
||||||
recursive_collect_superclass(&mut objects, dom, dom.root(),"Decal");
|
|
||||||
//get ids
|
|
||||||
//clear vec
|
|
||||||
//next class
|
|
||||||
objects
|
|
||||||
}
|
|
||||||
fn planar64_affine3_from_roblox(cf:&rbx_dom_weak::types::CFrame,size:&rbx_dom_weak::types::Vector3)->Planar64Affine3{
|
fn planar64_affine3_from_roblox(cf:&rbx_dom_weak::types::CFrame,size:&rbx_dom_weak::types::Vector3)->Planar64Affine3{
|
||||||
Planar64Affine3::new(
|
Planar64Affine3::new(
|
||||||
Planar64Mat3::from_cols(
|
Planar64Mat3::from_cols(
|
||||||
@ -60,6 +52,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
force_can_collide=false;
|
force_can_collide=false;
|
||||||
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
|
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
|
||||||
},
|
},
|
||||||
|
"UnorderedCheckpoint"=>general.checkpoint=Some(crate::model::GameMechanicCheckpoint::Unordered{mode_id:0}),
|
||||||
"SetVelocity"=>general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Velocity(velocity)),
|
"SetVelocity"=>general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Velocity(velocity)),
|
||||||
"MapFinish"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish})},
|
"MapFinish"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish})},
|
||||||
"MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})},
|
"MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})},
|
||||||
@ -118,6 +111,12 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
"WormholeIn"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::Wormhole(crate::model::GameMechanicWormhole{destination_model_id:captures[2].parse::<u32>().unwrap()})),
|
"WormholeIn"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::Wormhole(crate::model::GameMechanicWormhole{destination_model_id:captures[2].parse::<u32>().unwrap()})),
|
||||||
_=>panic!("regex3[1] messed up bad"),
|
_=>panic!("regex3[1] messed up bad"),
|
||||||
}
|
}
|
||||||
|
}else if let Some(captures)=lazy_regex::regex!(r"^(OrderedCheckpoint)(\d+)$")
|
||||||
|
.captures(other){
|
||||||
|
match &captures[1]{
|
||||||
|
"OrderedCheckpoint"=>general.checkpoint=Some(crate::model::GameMechanicCheckpoint::Ordered{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
|
||||||
|
_=>panic!("regex3[1] messed up bad"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -218,9 +217,9 @@ type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
|||||||
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||||
#[derive(Clone,Eq,Hash,PartialEq)]
|
#[derive(Clone,Eq,Hash,PartialEq)]
|
||||||
enum RobloxBasePartDescription{
|
enum RobloxBasePartDescription{
|
||||||
Sphere,
|
Sphere(RobloxPartDescription),
|
||||||
Part(RobloxPartDescription),
|
Part(RobloxPartDescription),
|
||||||
Cylinder,
|
Cylinder(RobloxPartDescription),
|
||||||
Wedge(RobloxWedgeDescription),
|
Wedge(RobloxWedgeDescription),
|
||||||
CornerWedge(RobloxCornerWedgeDescription),
|
CornerWedge(RobloxCornerWedgeDescription),
|
||||||
}
|
}
|
||||||
@ -265,14 +264,12 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
||||||
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
|
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
|
||||||
},
|
},
|
||||||
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint(crate::model::TempAttrUnorderedCheckpoint{mode_id:0})),
|
|
||||||
other=>{
|
other=>{
|
||||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint|WormholeOut)(\d+)$");
|
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|WormholeOut)(\d+)$");
|
||||||
if let Some(captures) = regman.captures(other) {
|
if let Some(captures) = regman.captures(other) {
|
||||||
match &captures[1]{
|
match &captures[1]{
|
||||||
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
|
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
|
||||||
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn(crate::model::TempAttrSpawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()})),
|
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn(crate::model::TempAttrSpawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()})),
|
||||||
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint(crate::model::TempAttrOrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()})),
|
|
||||||
"WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
|
"WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
|
||||||
_=>None,
|
_=>None,
|
||||||
}
|
}
|
||||||
@ -301,6 +298,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
panic!("Part has no Shape!");
|
panic!("Part has no Shape!");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"TrussPart"=>primitives::Primitives::Cube,
|
||||||
"WedgePart"=>primitives::Primitives::Wedge,
|
"WedgePart"=>primitives::Primitives::Wedge,
|
||||||
"CornerWedgePart"=>primitives::Primitives::CornerWedge,
|
"CornerWedgePart"=>primitives::Primitives::CornerWedge,
|
||||||
_=>{
|
_=>{
|
||||||
@ -395,9 +393,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
f5,//Cube::Front
|
f5,//Cube::Front
|
||||||
]=part_texture_description;
|
]=part_texture_description;
|
||||||
let basepart_texture_description=match shape{
|
let basepart_texture_description=match shape{
|
||||||
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
|
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere([f0,f1,f2,f3,f4,f5]),
|
||||||
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
|
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
|
||||||
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
|
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder([f0,f1,f2,f3,f4,f5]),
|
||||||
//use front face texture first and use top face texture as a fallback
|
//use front face texture first and use top face texture as a fallback
|
||||||
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
|
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
|
||||||
f0,//Cube::Right->Wedge::Right
|
f0,//Cube::Right->Wedge::Right
|
||||||
@ -423,9 +421,10 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
let model_id=indexed_models.len();
|
let model_id=indexed_models.len();
|
||||||
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy
|
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy
|
||||||
indexed_models.push(match basepart_texture_description{
|
indexed_models.push(match basepart_texture_description{
|
||||||
RobloxBasePartDescription::Sphere=>primitives::unit_sphere(),
|
RobloxBasePartDescription::Sphere(part_texture_description)
|
||||||
RobloxBasePartDescription::Part(part_texture_description)=>{
|
|RobloxBasePartDescription::Cylinder(part_texture_description)
|
||||||
let mut cube_face_description=primitives::CubeFaceDescription::new();
|
|RobloxBasePartDescription::Part(part_texture_description)=>{
|
||||||
|
let mut cube_face_description=primitives::CubeFaceDescription::default();
|
||||||
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
|
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
|
||||||
cube_face_description.insert(
|
cube_face_description.insert(
|
||||||
match face_id{
|
match face_id{
|
||||||
@ -444,9 +443,8 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
}
|
}
|
||||||
primitives::generate_partial_unit_cube(cube_face_description)
|
primitives::generate_partial_unit_cube(cube_face_description)
|
||||||
},
|
},
|
||||||
RobloxBasePartDescription::Cylinder=>primitives::unit_cylinder(),
|
|
||||||
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{
|
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{
|
||||||
let mut wedge_face_description=primitives::WedgeFaceDescription::new();
|
let mut wedge_face_description=primitives::WedgeFaceDescription::default();
|
||||||
for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
|
for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
|
||||||
wedge_face_description.insert(
|
wedge_face_description.insert(
|
||||||
match face_id{
|
match face_id{
|
||||||
@ -465,7 +463,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
primitives::generate_partial_unit_wedge(wedge_face_description)
|
primitives::generate_partial_unit_wedge(wedge_face_description)
|
||||||
},
|
},
|
||||||
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_description)=>{
|
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_description)=>{
|
||||||
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::new();
|
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::default();
|
||||||
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
|
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
|
||||||
cornerwedge_face_description.insert(
|
cornerwedge_face_description.insert(
|
||||||
match face_id{
|
match face_id{
|
||||||
|
77
src/main.rs
77
src/main.rs
@ -1,11 +1,7 @@
|
|||||||
use std::time::Instant;
|
|
||||||
use physics::PhysicsInstruction;
|
|
||||||
use render_thread::InputInstruction;
|
|
||||||
use instruction::{TimedInstruction, InstructionConsumer};
|
|
||||||
|
|
||||||
mod bvh;
|
mod bvh;
|
||||||
mod aabb;
|
mod aabb;
|
||||||
mod model;
|
mod model;
|
||||||
|
mod setup;
|
||||||
mod window;
|
mod window;
|
||||||
mod worker;
|
mod worker;
|
||||||
mod zeroes;
|
mod zeroes;
|
||||||
@ -16,27 +12,10 @@ mod settings;
|
|||||||
mod primitives;
|
mod primitives;
|
||||||
mod instruction;
|
mod instruction;
|
||||||
mod load_roblox;
|
mod load_roblox;
|
||||||
mod render_thread;
|
mod compat_worker;
|
||||||
mod model_graphics;
|
mod model_graphics;
|
||||||
mod graphics_context;
|
mod physics_worker;
|
||||||
|
mod graphics_worker;
|
||||||
|
|
||||||
pub struct GlobalState{
|
|
||||||
start_time: std::time::Instant,
|
|
||||||
manual_mouse_lock:bool,
|
|
||||||
mouse:std::sync::Arc<std::sync::Mutex<physics::MouseState>>,
|
|
||||||
user_settings:settings::UserSettings,
|
|
||||||
//Ideally the graphics thread worker description is:
|
|
||||||
/*
|
|
||||||
WorkerDescription{
|
|
||||||
input:Immediate,
|
|
||||||
output:Realtime(PoolOrdering::Ordered(3)),
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
//up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order
|
|
||||||
graphics_thread:worker::INWorker<graphics::GraphicsInstruction>,
|
|
||||||
physics_thread:worker::QNWorker<TimedInstruction<InputInstruction>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
||||||
println!("Loading file: {:?}", &path);
|
println!("Loading file: {:?}", &path);
|
||||||
@ -83,7 +62,7 @@ fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_models()->model::IndexedModelInstances{
|
pub fn default_models()->model::IndexedModelInstances{
|
||||||
let mut indexed_models = Vec::new();
|
let mut indexed_models = Vec::new();
|
||||||
indexed_models.append(&mut model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),glam::Vec4::ONE));
|
indexed_models.append(&mut model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),glam::Vec4::ONE));
|
||||||
indexed_models.push(primitives::unit_sphere());
|
indexed_models.push(primitives::unit_sphere());
|
||||||
@ -139,49 +118,7 @@ fn default_models()->model::IndexedModelInstances{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlobalState {
|
|
||||||
fn init() -> Self {
|
|
||||||
//wee
|
|
||||||
let user_settings=settings::read_user_settings();
|
|
||||||
|
|
||||||
let mut graphics=GraphicsState::new();
|
|
||||||
|
|
||||||
graphics.load_user_settings(&user_settings);
|
|
||||||
|
|
||||||
//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(),
|
|
||||||
user_settings,
|
|
||||||
graphics,
|
|
||||||
physics_thread,
|
|
||||||
};
|
|
||||||
state.generate_model_graphics(&device,&queue,indexed_model_instances);
|
|
||||||
|
|
||||||
let args:Vec<String>=std::env::args().collect();
|
|
||||||
if args.len()==2{
|
|
||||||
let indexed_model_instances=load_file(std::path::PathBuf::from(&args[1]));
|
|
||||||
state.render_thread=RenderThread::new(user_settings,indexed_model_instances);
|
|
||||||
}
|
|
||||||
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main(){
|
fn main(){
|
||||||
let title=format!("Strafe Client v{}",env!("CARGO_PKG_VERSION")).as_str();
|
let context=setup::setup(format!("Strafe Client v{}",env!("CARGO_PKG_VERSION")).as_str());
|
||||||
let context=graphics_context::setup(title);
|
context.start();//creates and runs a window context
|
||||||
let global_state=GlobalState::init();//new
|
|
||||||
global_state.replace_models(&context,default_models());
|
|
||||||
context.start(global_state);
|
|
||||||
}
|
}
|
||||||
|
41
src/model.rs
41
src/model.rs
@ -50,10 +50,10 @@ pub struct IndexedModelInstances{
|
|||||||
}
|
}
|
||||||
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
||||||
pub struct ModeDescription{
|
pub struct ModeDescription{
|
||||||
|
//TODO: put "default" style modifiers in mode
|
||||||
|
//pub style:StyleModifiers,
|
||||||
pub start:usize,//start=model_id
|
pub start:usize,//start=model_id
|
||||||
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
|
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
|
||||||
pub ordered_checkpoints:Vec<usize>,//ordered_checkpoints[checkpoint_id]=model_id
|
|
||||||
pub unordered_checkpoints:Vec<usize>,//unordered_checkpoints[checkpoint_id]=model_id
|
|
||||||
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
||||||
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
||||||
}
|
}
|
||||||
@ -61,9 +61,6 @@ impl ModeDescription{
|
|||||||
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
|
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
|
||||||
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
|
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
|
||||||
}
|
}
|
||||||
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&usize>{
|
|
||||||
self.ordered_checkpoints.get(*self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id)?)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
//I don't want this code to exist!
|
//I don't want this code to exist!
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@ -76,23 +73,12 @@ pub struct TempAttrSpawn{
|
|||||||
pub stage_id:u32,
|
pub stage_id:u32,
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct TempAttrOrderedCheckpoint{
|
|
||||||
pub mode_id:u32,
|
|
||||||
pub checkpoint_id:u32,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempAttrUnorderedCheckpoint{
|
|
||||||
pub mode_id:u32,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempAttrWormhole{
|
pub struct TempAttrWormhole{
|
||||||
pub wormhole_id:u32,
|
pub wormhole_id:u32,
|
||||||
}
|
}
|
||||||
pub enum TempIndexedAttributes{
|
pub enum TempIndexedAttributes{
|
||||||
Start(TempAttrStart),
|
Start(TempAttrStart),
|
||||||
Spawn(TempAttrSpawn),
|
Spawn(TempAttrSpawn),
|
||||||
OrderedCheckpoint(TempAttrOrderedCheckpoint),
|
|
||||||
UnorderedCheckpoint(TempAttrUnorderedCheckpoint),
|
|
||||||
Wormhole(TempAttrWormhole),
|
Wormhole(TempAttrWormhole),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -126,6 +112,16 @@ pub enum GameMechanicBooster{
|
|||||||
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
|
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
pub enum GameMechanicCheckpoint{
|
||||||
|
Ordered{
|
||||||
|
mode_id:u32,
|
||||||
|
checkpoint_id:u32,
|
||||||
|
},
|
||||||
|
Unordered{
|
||||||
|
mode_id:u32,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
pub enum TrajectoryChoice{
|
pub enum TrajectoryChoice{
|
||||||
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
|
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
|
||||||
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
|
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
|
||||||
@ -171,6 +167,13 @@ pub enum StageElementBehaviour{
|
|||||||
Trigger,
|
Trigger,
|
||||||
Teleport,
|
Teleport,
|
||||||
Platform,
|
Platform,
|
||||||
|
//Acts like a trigger if you haven't hit all the checkpoints.
|
||||||
|
Checkpoint{
|
||||||
|
//if this is 2 you must have hit OrderedCheckpoint(0) OrderedCheckpoint(1) OrderedCheckpoint(2) to pass
|
||||||
|
ordered_checkpoint_id:Option<u32>,
|
||||||
|
//if this is 2 you must have hit at least 2 UnorderedCheckpoints to pass
|
||||||
|
unordered_checkpoint_count:u32,
|
||||||
|
},
|
||||||
JumpLimit(u32),
|
JumpLimit(u32),
|
||||||
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
||||||
}
|
}
|
||||||
@ -199,15 +202,17 @@ pub enum TeleportBehaviour{
|
|||||||
pub struct GameMechanicAttributes{
|
pub struct GameMechanicAttributes{
|
||||||
pub zone:Option<GameMechanicZone>,
|
pub zone:Option<GameMechanicZone>,
|
||||||
pub booster:Option<GameMechanicBooster>,
|
pub booster:Option<GameMechanicBooster>,
|
||||||
|
pub checkpoint:Option<GameMechanicCheckpoint>,
|
||||||
pub trajectory:Option<GameMechanicSetTrajectory>,
|
pub trajectory:Option<GameMechanicSetTrajectory>,
|
||||||
pub teleport_behaviour:Option<TeleportBehaviour>,
|
pub teleport_behaviour:Option<TeleportBehaviour>,
|
||||||
pub accelerator:Option<GameMechanicAccelerator>,
|
pub accelerator:Option<GameMechanicAccelerator>,
|
||||||
}
|
}
|
||||||
impl GameMechanicAttributes{
|
impl GameMechanicAttributes{
|
||||||
pub fn any(&self)->bool{
|
pub fn any(&self)->bool{
|
||||||
self.booster.is_some()
|
self.zone.is_some()
|
||||||
|
||self.booster.is_some()
|
||||||
|
||self.checkpoint.is_some()
|
||||||
||self.trajectory.is_some()
|
||self.trajectory.is_some()
|
||||||
||self.zone.is_some()
|
|
||||||
||self.teleport_behaviour.is_some()
|
||self.teleport_behaviour.is_some()
|
||||||
||self.accelerator.is_some()
|
||self.accelerator.is_some()
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ pub struct GraphicsVertex {
|
|||||||
pub struct IndexedGroupFixedTexture{
|
pub struct IndexedGroupFixedTexture{
|
||||||
pub polys:Vec<IndexedPolygon>,
|
pub polys:Vec<IndexedPolygon>,
|
||||||
}
|
}
|
||||||
pub struct IndexedModelGraphicsSingleTexture{
|
pub struct IndexedGraphicsModelSingleTexture{
|
||||||
pub unique_pos:Vec<[f32; 3]>,
|
pub unique_pos:Vec<[f32; 3]>,
|
||||||
pub unique_tex:Vec<[f32; 2]>,
|
pub unique_tex:Vec<[f32; 2]>,
|
||||||
pub unique_normal:Vec<[f32; 3]>,
|
pub unique_normal:Vec<[f32; 3]>,
|
||||||
@ -19,37 +19,41 @@ pub struct IndexedModelGraphicsSingleTexture{
|
|||||||
pub unique_vertices:Vec<IndexedVertex>,
|
pub unique_vertices:Vec<IndexedVertex>,
|
||||||
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
|
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
|
||||||
pub groups: Vec<IndexedGroupFixedTexture>,
|
pub groups: Vec<IndexedGroupFixedTexture>,
|
||||||
pub instances:Vec<ModelGraphicsInstance>,
|
pub instances:Vec<GraphicsModelInstance>,
|
||||||
}
|
}
|
||||||
pub struct ModelGraphicsSingleTexture{
|
pub enum Entities{
|
||||||
pub instances: Vec<ModelGraphicsInstance>,
|
U32(Vec<Vec<u32>>),
|
||||||
pub vertices: Vec<GraphicsVertex>,
|
U16(Vec<Vec<u16>>),
|
||||||
pub entities: Vec<Vec<u16>>,
|
}
|
||||||
pub texture: Option<u32>,
|
pub struct GraphicsModelSingleTexture{
|
||||||
|
pub instances:Vec<GraphicsModelInstance>,
|
||||||
|
pub vertices:Vec<GraphicsVertex>,
|
||||||
|
pub entities:Entities,
|
||||||
|
pub texture:Option<u32>,
|
||||||
}
|
}
|
||||||
#[derive(Clone,PartialEq)]
|
#[derive(Clone,PartialEq)]
|
||||||
pub struct ModelGraphicsColor4(glam::Vec4);
|
pub struct GraphicsModelColor4(glam::Vec4);
|
||||||
impl ModelGraphicsColor4{
|
impl GraphicsModelColor4{
|
||||||
pub const fn get(&self)->glam::Vec4{
|
pub const fn get(&self)->glam::Vec4{
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl From<glam::Vec4> for ModelGraphicsColor4{
|
impl From<glam::Vec4> for GraphicsModelColor4{
|
||||||
fn from(value:glam::Vec4)->Self{
|
fn from(value:glam::Vec4)->Self{
|
||||||
Self(value)
|
Self(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl std::hash::Hash for ModelGraphicsColor4{
|
impl std::hash::Hash for GraphicsModelColor4{
|
||||||
fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
|
fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
|
||||||
for &f in self.0.as_ref(){
|
for &f in self.0.as_ref(){
|
||||||
bytemuck::cast::<f32,u32>(f).hash(state);
|
bytemuck::cast::<f32,u32>(f).hash(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Eq for ModelGraphicsColor4{}
|
impl Eq for GraphicsModelColor4{}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ModelGraphicsInstance{
|
pub struct GraphicsModelInstance{
|
||||||
pub transform:glam::Mat4,
|
pub transform:glam::Mat4,
|
||||||
pub normal_transform:glam::Mat3,
|
pub normal_transform:glam::Mat3,
|
||||||
pub color:ModelGraphicsColor4,
|
pub color:GraphicsModelColor4,
|
||||||
}
|
}
|
||||||
|
325
src/physics.rs
325
src/physics.rs
@ -31,9 +31,12 @@ pub enum PhysicsInputInstruction {
|
|||||||
SetZoom(bool),
|
SetZoom(bool),
|
||||||
Reset,
|
Reset,
|
||||||
Idle,
|
Idle,
|
||||||
|
//Idle: there were no input events, but the simulation is safe to advance to this timestep
|
||||||
|
//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,Hash)]
|
#[derive(Clone,Hash,Default)]
|
||||||
pub struct Body {
|
pub struct Body {
|
||||||
position: Planar64Vec3,//I64 where 2^32 = 1 u
|
position: Planar64Vec3,//I64 where 2^32 = 1 u
|
||||||
velocity: Planar64Vec3,//I64 where 2^32 = 1 u/s
|
velocity: Planar64Vec3,//I64 where 2^32 = 1 u/s
|
||||||
@ -152,7 +155,7 @@ impl Default for Modes{
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct PhysicsModels{
|
struct PhysicsModels{
|
||||||
models:Vec<ModelPhysics>,
|
models:Vec<PhysicsModel>,
|
||||||
model_id_from_wormhole_id:std::collections::HashMap::<u32,usize>,
|
model_id_from_wormhole_id:std::collections::HashMap::<u32,usize>,
|
||||||
}
|
}
|
||||||
impl PhysicsModels{
|
impl PhysicsModels{
|
||||||
@ -160,13 +163,13 @@ impl PhysicsModels{
|
|||||||
self.models.clear();
|
self.models.clear();
|
||||||
self.model_id_from_wormhole_id.clear();
|
self.model_id_from_wormhole_id.clear();
|
||||||
}
|
}
|
||||||
fn get(&self,i:usize)->Option<&ModelPhysics>{
|
fn get(&self,i:usize)->Option<&PhysicsModel>{
|
||||||
self.models.get(i)
|
self.models.get(i)
|
||||||
}
|
}
|
||||||
fn get_wormhole_model(&self,wormhole_id:u32)->Option<&ModelPhysics>{
|
fn get_wormhole_model(&self,wormhole_id:u32)->Option<&PhysicsModel>{
|
||||||
self.models.get(*self.model_id_from_wormhole_id.get(&wormhole_id)?)
|
self.models.get(*self.model_id_from_wormhole_id.get(&wormhole_id)?)
|
||||||
}
|
}
|
||||||
fn push(&mut self,model:ModelPhysics)->usize{
|
fn push(&mut self,model:PhysicsModel)->usize{
|
||||||
let model_id=self.models.len();
|
let model_id=self.models.len();
|
||||||
self.models.push(model);
|
self.models.push(model);
|
||||||
model_id
|
model_id
|
||||||
@ -182,8 +185,7 @@ impl Default for PhysicsModels{
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct PhysicsCamera {
|
pub struct PhysicsCamera{
|
||||||
offset: Planar64Vec3,
|
|
||||||
//punch: Planar64Vec3,
|
//punch: Planar64Vec3,
|
||||||
//punch_velocity: Planar64Vec3,
|
//punch_velocity: Planar64Vec3,
|
||||||
sensitivity:Ratio64Vec2,//dots to Angle32 ratios
|
sensitivity:Ratio64Vec2,//dots to Angle32 ratios
|
||||||
@ -201,16 +203,6 @@ pub struct PhysicsCamera {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PhysicsCamera {
|
impl PhysicsCamera {
|
||||||
pub fn from_offset(offset:Planar64Vec3) -> Self {
|
|
||||||
Self{
|
|
||||||
offset,
|
|
||||||
sensitivity:Ratio64Vec2::ONE*200_000,
|
|
||||||
mouse:MouseState::default(),//t=0 does not cause divide by zero because it's immediately replaced
|
|
||||||
clamped_mouse_pos:glam::IVec2::ZERO,
|
|
||||||
angle_pitch_lower_limit:-Angle32::FRAC_PI_2,
|
|
||||||
angle_pitch_upper_limit:Angle32::FRAC_PI_2,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn move_mouse(&mut self,mouse_pos:glam::IVec2){
|
pub fn move_mouse(&mut self,mouse_pos:glam::IVec2){
|
||||||
let mut unclamped_mouse_pos=self.clamped_mouse_pos+mouse_pos-self.mouse.pos;
|
let mut unclamped_mouse_pos=self.clamped_mouse_pos+mouse_pos-self.mouse.pos;
|
||||||
unclamped_mouse_pos.y=unclamped_mouse_pos.y.clamp(
|
unclamped_mouse_pos.y=unclamped_mouse_pos.y.clamp(
|
||||||
@ -241,14 +233,31 @@ impl PhysicsCamera {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl std::default::Default for PhysicsCamera{
|
||||||
|
fn default()->Self{
|
||||||
|
Self{
|
||||||
|
sensitivity:Ratio64Vec2::ONE*200_000,
|
||||||
|
mouse:MouseState::default(),//t=0 does not cause divide by zero because it's immediately replaced
|
||||||
|
clamped_mouse_pos:glam::IVec2::ZERO,
|
||||||
|
angle_pitch_lower_limit:-Angle32::FRAC_PI_2,
|
||||||
|
angle_pitch_upper_limit:Angle32::FRAC_PI_2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct GameMechanicsState{
|
pub struct GameMechanicsState{
|
||||||
pub stage_id:u32,
|
stage_id:u32,
|
||||||
//jump_counts:HashMap<u32,u32>,
|
jump_counts:std::collections::HashMap<usize,u32>,//model_id -> jump count
|
||||||
|
next_ordered_checkpoint_id:u32,//which OrderedCheckpoint model_id you must pass next (if 0 you haven't passed OrderedCheckpoint0)
|
||||||
|
unordered_checkpoints:std::collections::HashSet<usize>,//hashset of UnorderedCheckpoint model ids
|
||||||
}
|
}
|
||||||
impl std::default::Default for GameMechanicsState{
|
impl std::default::Default for GameMechanicsState{
|
||||||
fn default() -> Self {
|
fn default()->Self{
|
||||||
Self{
|
Self{
|
||||||
stage_id:0,
|
stage_id:0,
|
||||||
|
next_ordered_checkpoint_id:0,
|
||||||
|
unordered_checkpoints:std::collections::HashSet::new(),
|
||||||
|
jump_counts:std::collections::HashMap::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -272,10 +281,23 @@ enum JumpImpulse{
|
|||||||
//Energy means it adds energy
|
//Energy means it adds energy
|
||||||
//Linear means it linearly adds on
|
//Linear means it linearly adds on
|
||||||
|
|
||||||
|
enum EnableStrafe{
|
||||||
|
Always,
|
||||||
|
MaskAny(u32),//hsw, shsw
|
||||||
|
MaskAll(u32),
|
||||||
|
//Function(Box<dyn Fn(u32)->bool>),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StrafeSettings{
|
||||||
|
enable:EnableStrafe,
|
||||||
|
air_accel_limit:Option<Planar64>,
|
||||||
|
tick_rate:Ratio64,
|
||||||
|
}
|
||||||
|
|
||||||
struct StyleModifiers{
|
struct StyleModifiers{
|
||||||
controls_mask:u32,//controls which are unable to be activated
|
controls_used:u32,//controls which are allowed to pass into gameplay
|
||||||
controls_held:u32,//controls which must be active to be able to strafe
|
controls_mask:u32,//controls which are masked from control state (e.g. jump in scroll style)
|
||||||
strafe_tick_rate:Ratio64,
|
strafe:Option<StrafeSettings>,
|
||||||
jump_impulse:JumpImpulse,
|
jump_impulse:JumpImpulse,
|
||||||
jump_calculation:JumpCalculation,
|
jump_calculation:JumpCalculation,
|
||||||
static_friction:Planar64,
|
static_friction:Planar64,
|
||||||
@ -288,12 +310,13 @@ struct StyleModifiers{
|
|||||||
swim_speed:Planar64,
|
swim_speed:Planar64,
|
||||||
mass:Planar64,
|
mass:Planar64,
|
||||||
mv:Planar64,
|
mv:Planar64,
|
||||||
air_accel_limit:Option<Planar64>,
|
rocket_force:Option<Planar64>,
|
||||||
gravity:Planar64Vec3,
|
gravity:Planar64Vec3,
|
||||||
hitbox_halfsize:Planar64Vec3,
|
hitbox_halfsize:Planar64Vec3,
|
||||||
|
camera_offset:Planar64Vec3,
|
||||||
}
|
}
|
||||||
impl std::default::Default for StyleModifiers{
|
impl std::default::Default for StyleModifiers{
|
||||||
fn default() -> Self {
|
fn default()->Self{
|
||||||
Self::roblox_bhop()
|
Self::roblox_bhop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -313,9 +336,13 @@ impl StyleModifiers{
|
|||||||
|
|
||||||
fn new()->Self{
|
fn new()->Self{
|
||||||
Self{
|
Self{
|
||||||
|
controls_used:!0,
|
||||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||||
controls_held:0,
|
strafe:Some(StrafeSettings{
|
||||||
strafe_tick_rate:Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
enable:EnableStrafe::Always,
|
||||||
|
air_accel_limit:None,
|
||||||
|
tick_rate:Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||||
|
}),
|
||||||
jump_impulse:JumpImpulse::FromEnergy(Planar64::int(512)),
|
jump_impulse:JumpImpulse::FromEnergy(Planar64::int(512)),
|
||||||
jump_calculation:JumpCalculation::Energy,
|
jump_calculation:JumpCalculation::Energy,
|
||||||
gravity:Planar64Vec3::int(0,-80,0),
|
gravity:Planar64Vec3::int(0,-80,0),
|
||||||
@ -323,7 +350,7 @@ impl StyleModifiers{
|
|||||||
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
||||||
mass:Planar64::int(1),
|
mass:Planar64::int(1),
|
||||||
mv:Planar64::int(2),
|
mv:Planar64::int(2),
|
||||||
air_accel_limit:None,
|
rocket_force:None,
|
||||||
walk_speed:Planar64::int(16),
|
walk_speed:Planar64::int(16),
|
||||||
walk_accel:Planar64::int(80),
|
walk_accel:Planar64::int(80),
|
||||||
ladder_speed:Planar64::int(16),
|
ladder_speed:Planar64::int(16),
|
||||||
@ -331,14 +358,19 @@ impl StyleModifiers{
|
|||||||
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
||||||
swim_speed:Planar64::int(12),
|
swim_speed:Planar64::int(12),
|
||||||
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
||||||
|
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn roblox_bhop()->Self{
|
fn roblox_bhop()->Self{
|
||||||
Self{
|
Self{
|
||||||
|
controls_used:!0,
|
||||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||||
controls_held:0,
|
strafe:Some(StrafeSettings{
|
||||||
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
enable:EnableStrafe::Always,
|
||||||
|
air_accel_limit:None,
|
||||||
|
tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||||
|
}),
|
||||||
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
||||||
jump_calculation:JumpCalculation::Capped,
|
jump_calculation:JumpCalculation::Capped,
|
||||||
gravity:Planar64Vec3::int(0,-100,0),
|
gravity:Planar64Vec3::int(0,-100,0),
|
||||||
@ -346,7 +378,7 @@ impl StyleModifiers{
|
|||||||
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
||||||
mass:Planar64::int(1),
|
mass:Planar64::int(1),
|
||||||
mv:Planar64::int(27)/10,
|
mv:Planar64::int(27)/10,
|
||||||
air_accel_limit:None,
|
rocket_force:None,
|
||||||
walk_speed:Planar64::int(18),
|
walk_speed:Planar64::int(18),
|
||||||
walk_accel:Planar64::int(90),
|
walk_accel:Planar64::int(90),
|
||||||
ladder_speed:Planar64::int(18),
|
ladder_speed:Planar64::int(18),
|
||||||
@ -354,13 +386,18 @@ impl StyleModifiers{
|
|||||||
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
||||||
swim_speed:Planar64::int(12),
|
swim_speed:Planar64::int(12),
|
||||||
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
||||||
|
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn roblox_surf()->Self{
|
fn roblox_surf()->Self{
|
||||||
Self{
|
Self{
|
||||||
|
controls_used:!0,
|
||||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||||
controls_held:0,
|
strafe:Some(StrafeSettings{
|
||||||
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
enable:EnableStrafe::Always,
|
||||||
|
air_accel_limit:None,
|
||||||
|
tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||||
|
}),
|
||||||
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
||||||
jump_calculation:JumpCalculation::Capped,
|
jump_calculation:JumpCalculation::Capped,
|
||||||
gravity:Planar64Vec3::int(0,-50,0),
|
gravity:Planar64Vec3::int(0,-50,0),
|
||||||
@ -368,7 +405,7 @@ impl StyleModifiers{
|
|||||||
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
||||||
mass:Planar64::int(1),
|
mass:Planar64::int(1),
|
||||||
mv:Planar64::int(27)/10,
|
mv:Planar64::int(27)/10,
|
||||||
air_accel_limit:None,
|
rocket_force:None,
|
||||||
walk_speed:Planar64::int(18),
|
walk_speed:Planar64::int(18),
|
||||||
walk_accel:Planar64::int(90),
|
walk_accel:Planar64::int(90),
|
||||||
ladder_speed:Planar64::int(18),
|
ladder_speed:Planar64::int(18),
|
||||||
@ -376,15 +413,19 @@ impl StyleModifiers{
|
|||||||
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
||||||
swim_speed:Planar64::int(12),
|
swim_speed:Planar64::int(12),
|
||||||
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
||||||
|
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn source_bhop()->Self{
|
fn source_bhop()->Self{
|
||||||
//camera_offset=vec3(0,64/16-73/16/2,0),
|
|
||||||
Self{
|
Self{
|
||||||
|
controls_used:!0,
|
||||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||||
controls_held:0,
|
strafe:Some(StrafeSettings{
|
||||||
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
enable:EnableStrafe::Always,
|
||||||
|
air_accel_limit:Some(Planar64::raw(150<<28)*66),
|
||||||
|
tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||||
|
}),
|
||||||
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
|
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
|
||||||
jump_calculation:JumpCalculation::Linear,
|
jump_calculation:JumpCalculation::Linear,
|
||||||
gravity:Planar64Vec3::raw(0,-800<<28,0),
|
gravity:Planar64Vec3::raw(0,-800<<28,0),
|
||||||
@ -392,7 +433,7 @@ impl StyleModifiers{
|
|||||||
kinetic_friction:Planar64::int(3),//?
|
kinetic_friction:Planar64::int(3),//?
|
||||||
mass:Planar64::int(1),
|
mass:Planar64::int(1),
|
||||||
mv:Planar64::raw(30<<28),
|
mv:Planar64::raw(30<<28),
|
||||||
air_accel_limit:Some(Planar64::raw(150<<28)*66),
|
rocket_force:None,
|
||||||
walk_speed:Planar64::int(18),//?
|
walk_speed:Planar64::int(18),//?
|
||||||
walk_accel:Planar64::int(90),//?
|
walk_accel:Planar64::int(90),//?
|
||||||
ladder_speed:Planar64::int(18),//?
|
ladder_speed:Planar64::int(18),//?
|
||||||
@ -400,14 +441,18 @@ impl StyleModifiers{
|
|||||||
ladder_dot:(Planar64::int(1)/2).sqrt(),//?
|
ladder_dot:(Planar64::int(1)/2).sqrt(),//?
|
||||||
swim_speed:Planar64::int(12),//?
|
swim_speed:Planar64::int(12),//?
|
||||||
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
|
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
|
||||||
|
camera_offset:Planar64Vec3::raw(0,(64<<28)-(73<<27),0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn source_surf()->Self{
|
fn source_surf()->Self{
|
||||||
//camera_offset=vec3(0,64/16-73/16/2,0),
|
|
||||||
Self{
|
Self{
|
||||||
|
controls_used:!0,
|
||||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||||
controls_held:0,
|
strafe:Some(StrafeSettings{
|
||||||
strafe_tick_rate:Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
enable:EnableStrafe::Always,
|
||||||
|
air_accel_limit:Some(Planar64::raw(150<<28)*66),
|
||||||
|
tick_rate:Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||||
|
}),
|
||||||
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
|
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
|
||||||
jump_calculation:JumpCalculation::Linear,
|
jump_calculation:JumpCalculation::Linear,
|
||||||
gravity:Planar64Vec3::raw(0,-800<<28,0),
|
gravity:Planar64Vec3::raw(0,-800<<28,0),
|
||||||
@ -415,7 +460,7 @@ impl StyleModifiers{
|
|||||||
kinetic_friction:Planar64::int(3),//?
|
kinetic_friction:Planar64::int(3),//?
|
||||||
mass:Planar64::int(1),
|
mass:Planar64::int(1),
|
||||||
mv:Planar64::raw(30<<28),
|
mv:Planar64::raw(30<<28),
|
||||||
air_accel_limit:Some(Planar64::raw(150<<28)*66),
|
rocket_force:None,
|
||||||
walk_speed:Planar64::int(18),//?
|
walk_speed:Planar64::int(18),//?
|
||||||
walk_accel:Planar64::int(90),//?
|
walk_accel:Planar64::int(90),//?
|
||||||
ladder_speed:Planar64::int(18),//?
|
ladder_speed:Planar64::int(18),//?
|
||||||
@ -423,6 +468,30 @@ impl StyleModifiers{
|
|||||||
ladder_dot:(Planar64::int(1)/2).sqrt(),//?
|
ladder_dot:(Planar64::int(1)/2).sqrt(),//?
|
||||||
swim_speed:Planar64::int(12),//?
|
swim_speed:Planar64::int(12),//?
|
||||||
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
|
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
|
||||||
|
camera_offset:Planar64Vec3::raw(0,(64<<28)-(73<<27),0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn roblox_rocket()->Self{
|
||||||
|
Self{
|
||||||
|
controls_used:!0,
|
||||||
|
controls_mask:!0,
|
||||||
|
strafe:None,
|
||||||
|
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
||||||
|
jump_calculation:JumpCalculation::Capped,
|
||||||
|
gravity:Planar64Vec3::int(0,-100,0),
|
||||||
|
static_friction:Planar64::int(2),
|
||||||
|
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
||||||
|
mass:Planar64::int(1),
|
||||||
|
mv:Planar64::int(27)/10,
|
||||||
|
rocket_force:Some(Planar64::int(200)),
|
||||||
|
walk_speed:Planar64::int(18),
|
||||||
|
walk_accel:Planar64::int(90),
|
||||||
|
ladder_speed:Planar64::int(18),
|
||||||
|
ladder_accel:Planar64::int(180),
|
||||||
|
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
||||||
|
swim_speed:Planar64::int(12),
|
||||||
|
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
||||||
|
camera_offset:Planar64Vec3::int(0,2,0),//4.5-2.5=2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -430,13 +499,19 @@ impl StyleModifiers{
|
|||||||
controls&self.controls_mask&control==control
|
controls&self.controls_mask&control==control
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn allow_strafe(&self,controls:u32)->bool{
|
||||||
|
//disable strafing according to strafe settings
|
||||||
|
match &self.strafe{
|
||||||
|
Some(StrafeSettings{enable:EnableStrafe::Always,air_accel_limit:_,tick_rate:_})=>true,
|
||||||
|
&Some(StrafeSettings{enable:EnableStrafe::MaskAny(mask),air_accel_limit:_,tick_rate:_})=>mask&controls!=0,
|
||||||
|
&Some(StrafeSettings{enable:EnableStrafe::MaskAll(mask),air_accel_limit:_,tick_rate:_})=>mask&controls==mask,
|
||||||
|
None=>false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn get_control_dir(&self,controls:u32)->Planar64Vec3{
|
fn get_control_dir(&self,controls:u32)->Planar64Vec3{
|
||||||
//don't get fancy just do it
|
//don't get fancy just do it
|
||||||
let mut control_dir:Planar64Vec3 = Planar64Vec3::ZERO;
|
let mut control_dir:Planar64Vec3 = Planar64Vec3::ZERO;
|
||||||
//Disallow strafing if held controls are not held
|
|
||||||
if controls&self.controls_held!=self.controls_held{
|
|
||||||
return control_dir;
|
|
||||||
}
|
|
||||||
//Apply mask after held check so you can require non-allowed keys to be held for some reason
|
//Apply mask after held check so you can require non-allowed keys to be held for some reason
|
||||||
let controls=controls&self.controls_mask;
|
let controls=controls&self.controls_mask;
|
||||||
if controls & Self::CONTROL_MOVEFORWARD == Self::CONTROL_MOVEFORWARD {
|
if controls & Self::CONTROL_MOVEFORWARD == Self::CONTROL_MOVEFORWARD {
|
||||||
@ -492,10 +567,9 @@ impl StyleModifiers{
|
|||||||
// return cross(cross(Normal,ControlDir),Normal)/sqrt(1-d*d)
|
// return cross(cross(Normal,ControlDir),Normal)/sqrt(1-d*d)
|
||||||
control_dir*self.walk_speed
|
control_dir*self.walk_speed
|
||||||
}
|
}
|
||||||
fn get_propulsion_target_velocity(&self,camera:&PhysicsCamera,controls:u32,next_mouse:&MouseState,time:Time)->Planar64Vec3{
|
fn get_propulsion_control_dir(&self,camera:&PhysicsCamera,controls:u32,next_mouse:&MouseState,time:Time)->Planar64Vec3{
|
||||||
let camera_mat=camera.simulate_move_rotation(camera.mouse.lerp(&next_mouse,time));
|
let camera_mat=camera.simulate_move_rotation(camera.mouse.lerp(&next_mouse,time));
|
||||||
let control_dir=camera_mat*self.get_control_dir(controls);
|
camera_mat*self.get_control_dir(controls)
|
||||||
control_dir*self.walk_speed
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -527,14 +601,15 @@ pub struct PhysicsState{
|
|||||||
//This is not the same as Reset which teleports you to Spawn0
|
//This is not the same as Reset which teleports you to Spawn0
|
||||||
spawn_point:Planar64Vec3,
|
spawn_point:Planar64Vec3,
|
||||||
}
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone,Default)]
|
||||||
pub struct PhysicsOutputState{
|
pub struct PhysicsOutputState{
|
||||||
camera:PhysicsCamera,
|
|
||||||
body:Body,
|
body:Body,
|
||||||
|
camera:PhysicsCamera,
|
||||||
|
camera_offset:Planar64Vec3,
|
||||||
}
|
}
|
||||||
impl PhysicsOutputState{
|
impl PhysicsOutputState{
|
||||||
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){
|
pub fn extrapolate(&self,mouse_pos:glam::IVec2,time:Time)->(glam::Vec3,glam::Vec2){
|
||||||
((self.body.extrapolated_position(mouse.time)+self.camera.offset).into(),self.camera.simulate_move_angles(mouse.pos))
|
((self.body.extrapolated_position(time)+self.camera_offset).into(),self.camera.simulate_move_angles(mouse_pos))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -553,7 +628,7 @@ enum PhysicsCollisionAttributes{
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ModelPhysics {
|
pub struct PhysicsModel {
|
||||||
//A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es
|
//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.
|
//in this iteration, all it needs is extents.
|
||||||
mesh: TreyMesh,
|
mesh: TreyMesh,
|
||||||
@ -561,7 +636,7 @@ pub struct ModelPhysics {
|
|||||||
attributes:PhysicsCollisionAttributes,
|
attributes:PhysicsCollisionAttributes,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ModelPhysics {
|
impl PhysicsModel {
|
||||||
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&crate::integer::Planar64Affine3,attributes:PhysicsCollisionAttributes)->Self{
|
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&crate::integer::Planar64Affine3,attributes:PhysicsCollisionAttributes)->Self{
|
||||||
let mut aabb=TreyMesh::default();
|
let mut aabb=TreyMesh::default();
|
||||||
for indexed_vertex in &model.unique_vertices {
|
for indexed_vertex in &model.unique_vertices {
|
||||||
@ -575,8 +650,8 @@ impl ModelPhysics {
|
|||||||
}
|
}
|
||||||
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
|
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
|
||||||
match &instance.attributes{
|
match &instance.attributes{
|
||||||
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::Contact{contacting,general}=>Some(PhysicsModel::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})),
|
||||||
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::Intersect{intersecting,general}=>Some(PhysicsModel::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersect{intersecting:intersecting.clone(),general:general.clone()})),
|
||||||
crate::model::CollisionAttributes::Decoration=>None,
|
crate::model::CollisionAttributes::Decoration=>None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -603,10 +678,10 @@ pub struct RelativeCollision {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RelativeCollision {
|
impl RelativeCollision {
|
||||||
fn model<'a>(&self,models:&'a PhysicsModels)->Option<&'a ModelPhysics>{
|
fn model<'a>(&self,models:&'a PhysicsModels)->Option<&'a PhysicsModel>{
|
||||||
models.get(self.model)
|
models.get(self.model)
|
||||||
}
|
}
|
||||||
// pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
|
// pub fn mesh(&self,models:&Vec<PhysicsModel>) -> TreyMesh {
|
||||||
// return self.model(models).unwrap().face_mesh(self.face).clone()
|
// return self.model(models).unwrap().face_mesh(self.face).clone()
|
||||||
// }
|
// }
|
||||||
fn normal(&self,models:&PhysicsModels) -> Planar64Vec3 {
|
fn normal(&self,models:&PhysicsModels) -> Planar64Vec3 {
|
||||||
@ -693,19 +768,19 @@ impl std::fmt::Display for Body{
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Default for PhysicsState{
|
impl Default for PhysicsState{
|
||||||
fn default() -> Self {
|
fn default()->Self{
|
||||||
Self{
|
Self{
|
||||||
spawn_point:Planar64Vec3::int(0,50,0),
|
spawn_point:Planar64Vec3::int(0,50,0),
|
||||||
body: Body::with_pva(Planar64Vec3::int(0,50,0),Planar64Vec3::int(0,0,0),Planar64Vec3::int(0,-100,0)),
|
body:Body::with_pva(Planar64Vec3::int(0,50,0),Planar64Vec3::int(0,0,0),Planar64Vec3::int(0,-100,0)),
|
||||||
time: Time::ZERO,
|
time:Time::ZERO,
|
||||||
style:StyleModifiers::default(),
|
style:StyleModifiers::default(),
|
||||||
touching:TouchingState::default(),
|
touching:TouchingState::default(),
|
||||||
models:PhysicsModels::default(),
|
models:PhysicsModels::default(),
|
||||||
bvh:crate::bvh::BvhNode::default(),
|
bvh:crate::bvh::BvhNode::default(),
|
||||||
move_state: MoveState::Air,
|
move_state: MoveState::Air,
|
||||||
camera: PhysicsCamera::from_offset(Planar64Vec3::int(0,2,0)),//4.5-2.5=2
|
camera:PhysicsCamera::default(),
|
||||||
next_mouse: MouseState::default(),
|
next_mouse:MouseState::default(),
|
||||||
controls: 0,
|
controls:0,
|
||||||
world:WorldState{},
|
world:WorldState{},
|
||||||
game:GameMechanicsState::default(),
|
game:GameMechanicsState::default(),
|
||||||
modes:Modes::default(),
|
modes:Modes::default(),
|
||||||
@ -718,12 +793,14 @@ impl PhysicsState {
|
|||||||
self.models.clear();
|
self.models.clear();
|
||||||
self.modes.clear();
|
self.modes.clear();
|
||||||
self.touching.clear();
|
self.touching.clear();
|
||||||
|
self.bvh=crate::bvh::BvhNode::default();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn output(&self)->PhysicsOutputState{
|
pub fn output(&self)->PhysicsOutputState{
|
||||||
PhysicsOutputState{
|
PhysicsOutputState{
|
||||||
body:self.body.clone(),
|
body:self.body.clone(),
|
||||||
camera:self.camera.clone(),
|
camera:self.camera.clone(),
|
||||||
|
camera_offset:self.style.camera_offset.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -739,19 +816,15 @@ impl PhysicsState {
|
|||||||
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
|
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
|
||||||
let mut starts=Vec::new();
|
let mut starts=Vec::new();
|
||||||
let mut spawns=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{
|
for model in &indexed_models.models{
|
||||||
//make aabb and run vertices to get realistic bounds
|
//make aabb and run vertices to get realistic bounds
|
||||||
for model_instance in &model.instances{
|
for model_instance in &model.instances{
|
||||||
if let Some(model_physics)=ModelPhysics::from_model(model,model_instance){
|
if let Some(model_physics)=PhysicsModel::from_model(model,model_instance){
|
||||||
let model_id=self.models.push(model_physics);
|
let model_id=self.models.push(model_physics);
|
||||||
for attr in &model_instance.temp_indexing{
|
for attr in &model_instance.temp_indexing{
|
||||||
match attr{
|
match attr{
|
||||||
crate::model::TempIndexedAttributes::Start(s)=>starts.push((model_id,s.clone())),
|
crate::model::TempIndexedAttributes::Start(s)=>starts.push((model_id,s.clone())),
|
||||||
crate::model::TempIndexedAttributes::Spawn(s)=>spawns.push((model_id,s.clone())),
|
crate::model::TempIndexedAttributes::Spawn(s)=>spawns.push((model_id,s.clone())),
|
||||||
crate::model::TempIndexedAttributes::OrderedCheckpoint(s)=>ordered_checkpoints.push((model_id,s.clone())),
|
|
||||||
crate::model::TempIndexedAttributes::UnorderedCheckpoint(s)=>unordered_checkpoints.push((model_id,s.clone())),
|
|
||||||
crate::model::TempIndexedAttributes::Wormhole(s)=>{self.models.model_id_from_wormhole_id.insert(s.wormhole_id,model_id);},
|
crate::model::TempIndexedAttributes::Wormhole(s)=>{self.models.model_id_from_wormhole_id.insert(s.wormhole_id,model_id);},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -763,9 +836,9 @@ impl PhysicsState {
|
|||||||
//this code builds ModeDescriptions from the unsorted lists at the top of the function
|
//this code builds ModeDescriptions from the unsorted lists at the top of the function
|
||||||
starts.sort_by_key(|tup|tup.1.mode_id);
|
starts.sort_by_key(|tup|tup.1.mode_id);
|
||||||
let mut mode_id_from_map_mode_id=std::collections::HashMap::new();
|
let mut mode_id_from_map_mode_id=std::collections::HashMap::new();
|
||||||
let mut modedatas:Vec<(usize,Vec<(u32,usize)>,Vec<(u32,usize)>,Vec<usize>,u32)>=starts.into_iter().enumerate().map(|(i,(model_id,s))|{
|
let mut modedatas:Vec<(usize,Vec<(u32,usize)>,u32)>=starts.into_iter().enumerate().map(|(i,(model_id,s))|{
|
||||||
mode_id_from_map_mode_id.insert(s.mode_id,i);
|
mode_id_from_map_mode_id.insert(s.mode_id,i);
|
||||||
(model_id,Vec::new(),Vec::new(),Vec::new(),s.mode_id)
|
(model_id,Vec::new(),s.mode_id)
|
||||||
}).collect();
|
}).collect();
|
||||||
for (model_id,s) in spawns{
|
for (model_id,s) in spawns{
|
||||||
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
|
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
|
||||||
@ -774,30 +847,13 @@ impl PhysicsState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (model_id,s) in ordered_checkpoints{
|
|
||||||
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
|
|
||||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
|
||||||
modedata.2.push((s.checkpoint_id,model_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (model_id,s) in unordered_checkpoints{
|
|
||||||
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
|
|
||||||
if let Some(modedata)=modedatas.get_mut(*mode_id){
|
|
||||||
modedata.3.push(model_id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for mut tup in modedatas.into_iter(){
|
for mut tup in modedatas.into_iter(){
|
||||||
tup.1.sort_by_key(|tup|tup.0);
|
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 eshmep1=std::collections::HashMap::new();
|
||||||
let mut eshmep2=std::collections::HashMap::new();
|
let mut eshmep2=std::collections::HashMap::new();
|
||||||
self.modes.insert(tup.4,crate::model::ModeDescription{
|
self.modes.insert(tup.2,crate::model::ModeDescription{
|
||||||
start:tup.0,
|
start:tup.0,
|
||||||
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
|
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,
|
spawn_from_stage_id:eshmep1,
|
||||||
ordered_checkpoint_from_checkpoint_id:eshmep2,
|
ordered_checkpoint_from_checkpoint_id:eshmep2,
|
||||||
});
|
});
|
||||||
@ -838,12 +894,14 @@ impl PhysicsState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
fn next_strafe_instruction(&self)->Option<TimedInstruction<PhysicsInstruction>>{
|
||||||
return Some(TimedInstruction{
|
self.style.strafe.as_ref().map(|strafe|{
|
||||||
time:Time::from_nanos(self.style.strafe_tick_rate.rhs_div_int(self.style.strafe_tick_rate.mul_int(self.time.nanos())+1)),
|
TimedInstruction{
|
||||||
//only poll the physics if there is a before and after mouse event
|
time:Time::from_nanos(strafe.tick_rate.rhs_div_int(strafe.tick_rate.mul_int(self.time.nanos())+1)),
|
||||||
instruction:PhysicsInstruction::StrafeTick
|
//only poll the physics if there is a before and after mouse event
|
||||||
});
|
instruction:PhysicsInstruction::StrafeTick
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
//state mutated on collision:
|
//state mutated on collision:
|
||||||
@ -877,16 +935,20 @@ impl PhysicsState {
|
|||||||
// });
|
// });
|
||||||
// }
|
// }
|
||||||
|
|
||||||
fn refresh_walk_target(&mut self){
|
fn refresh_walk_target(&mut self)->Option<Planar64Vec3>{
|
||||||
match &mut self.move_state{
|
match &mut self.move_state{
|
||||||
MoveState::Air|MoveState::Water=>(),
|
MoveState::Air|MoveState::Water=>None,
|
||||||
MoveState::Walk(WalkState{normal,state})=>{
|
MoveState::Walk(WalkState{normal,state})=>{
|
||||||
let n=normal;
|
let n=normal;
|
||||||
(*state,self.body.acceleration)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_walk_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
let a;
|
||||||
|
(*state,a)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_walk_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
||||||
|
Some(a)
|
||||||
},
|
},
|
||||||
MoveState::Ladder(WalkState{normal,state})=>{
|
MoveState::Ladder(WalkState{normal,state})=>{
|
||||||
let n=normal;
|
let n=normal;
|
||||||
(*state,self.body.acceleration)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_ladder_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
let a;
|
||||||
|
(*state,a)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_ladder_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
||||||
|
Some(a)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1057,7 +1119,7 @@ impl PhysicsState {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
//generate instruction
|
//generate instruction
|
||||||
if let Some(face) = exit_face{
|
if let Some(_face) = exit_face{
|
||||||
return Some(TimedInstruction {
|
return Some(TimedInstruction {
|
||||||
time: best_time,
|
time: best_time,
|
||||||
instruction: PhysicsInstruction::CollisionEnd(collision_data.clone())
|
instruction: PhysicsInstruction::CollisionEnd(collision_data.clone())
|
||||||
@ -1222,8 +1284,13 @@ fn teleport(body:&mut Body,touching:&mut TouchingState,style:&StyleModifiers,poi
|
|||||||
//TODO: calculate contacts and determine the actual state
|
//TODO: calculate contacts and determine the actual state
|
||||||
//touching.recalculate(body);
|
//touching.recalculate(body);
|
||||||
}
|
}
|
||||||
|
fn teleport_to_spawn(body:&mut Body,touching:&mut TouchingState,style:&StyleModifiers,mode:&crate::model::ModeDescription,models:&PhysicsModels,stage_id:u32)->Option<MoveState>{
|
||||||
|
let model=models.get(*mode.get_spawn_model_id(stage_id)? as usize)?;
|
||||||
|
let point=model.transform.transform_point3(Planar64Vec3::Y)+Planar64Vec3::Y*(style.hitbox_halfsize.y()+Planar64::ONE/16);
|
||||||
|
Some(teleport(body,touching,style,point))
|
||||||
|
}
|
||||||
|
|
||||||
fn run_teleport_behaviour(teleport_behaviour:&Option<crate::model::TeleportBehaviour>,game:&mut GameMechanicsState,models:&PhysicsModels,modes:&Modes,style:&StyleModifiers,touching:&mut TouchingState,body:&mut Body,model:&ModelPhysics)->Option<MoveState>{
|
fn run_teleport_behaviour(teleport_behaviour:&Option<crate::model::TeleportBehaviour>,game:&mut GameMechanicsState,models:&PhysicsModels,modes:&Modes,style:&StyleModifiers,touching:&mut TouchingState,body:&mut Body,model:&PhysicsModel)->Option<MoveState>{
|
||||||
match teleport_behaviour{
|
match teleport_behaviour{
|
||||||
Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{
|
Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{
|
||||||
if stage_element.force||game.stage_id<stage_element.stage_id{
|
if stage_element.force||game.stage_id<stage_element.stage_id{
|
||||||
@ -1234,12 +1301,24 @@ fn run_teleport_behaviour(teleport_behaviour:&Option<crate::model::TeleportBehav
|
|||||||
crate::model::StageElementBehaviour::Trigger
|
crate::model::StageElementBehaviour::Trigger
|
||||||
|crate::model::StageElementBehaviour::Teleport=>{
|
|crate::model::StageElementBehaviour::Teleport=>{
|
||||||
//I guess this is correct behaviour when trying to teleport to a non-existent spawn but it's still weird
|
//I guess this is correct behaviour when trying to teleport to a non-existent spawn but it's still weird
|
||||||
let model=models.get(*modes.get_mode(stage_element.mode_id)?.get_spawn_model_id(game.stage_id)? as usize)?;
|
teleport_to_spawn(body,touching,style,modes.get_mode(stage_element.mode_id)?,models,game.stage_id)
|
||||||
let point=model.transform.transform_point3(Planar64Vec3::Y)+Planar64Vec3::Y*(style.hitbox_halfsize.y()+Planar64::ONE/16);
|
|
||||||
Some(teleport(body,touching,style,point))
|
|
||||||
},
|
},
|
||||||
crate::model::StageElementBehaviour::Platform=>None,
|
crate::model::StageElementBehaviour::Platform=>None,
|
||||||
crate::model::StageElementBehaviour::JumpLimit(_)=>None,//TODO
|
&crate::model::StageElementBehaviour::JumpLimit(jump_limit)=>{
|
||||||
|
//let count=game.jump_counts.get(&model.id);
|
||||||
|
//TODO
|
||||||
|
None
|
||||||
|
},
|
||||||
|
&crate::model::StageElementBehaviour::Checkpoint{ordered_checkpoint_id,unordered_checkpoint_count}=>{
|
||||||
|
if (ordered_checkpoint_id.is_none()||ordered_checkpoint_id.is_some_and(|id|id<game.next_ordered_checkpoint_id))
|
||||||
|
&&unordered_checkpoint_count<=game.unordered_checkpoints.len() as u32{
|
||||||
|
//pass
|
||||||
|
None
|
||||||
|
}else{
|
||||||
|
//fail
|
||||||
|
teleport_to_spawn(body,touching,style,modes.get_mode(stage_element.mode_id)?,models,game.stage_id)
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
|
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
|
||||||
@ -1314,7 +1393,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
match booster{
|
match booster{
|
||||||
&crate::model::GameMechanicBooster::Affine(transform)=>v=transform.transform_point3(v),
|
&crate::model::GameMechanicBooster::Affine(transform)=>v=transform.transform_point3(v),
|
||||||
&crate::model::GameMechanicBooster::Velocity(velocity)=>v+=velocity,
|
&crate::model::GameMechanicBooster::Velocity(velocity)=>v+=velocity,
|
||||||
&crate::model::GameMechanicBooster::Energy{direction,energy}=>todo!(),
|
&crate::model::GameMechanicBooster::Energy{direction: _,energy: _}=>todo!(),
|
||||||
}
|
}
|
||||||
self.touching.constrain_velocity(&self.models,&mut v);
|
self.touching.constrain_velocity(&self.models,&mut v);
|
||||||
},
|
},
|
||||||
@ -1325,10 +1404,10 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
match trajectory{
|
match trajectory{
|
||||||
crate::model::GameMechanicSetTrajectory::AirTime(_) => todo!(),
|
crate::model::GameMechanicSetTrajectory::AirTime(_) => todo!(),
|
||||||
crate::model::GameMechanicSetTrajectory::Height(_) => todo!(),
|
crate::model::GameMechanicSetTrajectory::Height(_) => todo!(),
|
||||||
crate::model::GameMechanicSetTrajectory::TargetPointTime { target_point, time } => todo!(),
|
crate::model::GameMechanicSetTrajectory::TargetPointTime { target_point: _, time: _ } => todo!(),
|
||||||
crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint { target_point, speed, trajectory_choice } => todo!(),
|
crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint { target_point: _, speed: _, trajectory_choice: _ } => todo!(),
|
||||||
&crate::model::GameMechanicSetTrajectory::Velocity(velocity)=>v=velocity,
|
&crate::model::GameMechanicSetTrajectory::Velocity(velocity)=>v=velocity,
|
||||||
crate::model::GameMechanicSetTrajectory::DotVelocity { direction, dot } => todo!(),
|
crate::model::GameMechanicSetTrajectory::DotVelocity { direction: _, dot: _ } => todo!(),
|
||||||
}
|
}
|
||||||
self.touching.constrain_velocity(&self.models,&mut v);
|
self.touching.constrain_velocity(&self.models,&mut v);
|
||||||
},
|
},
|
||||||
@ -1338,9 +1417,11 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
if self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
|
if self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
|
||||||
self.jump();
|
self.jump();
|
||||||
}
|
}
|
||||||
self.refresh_walk_target();
|
if let Some(a)=self.refresh_walk_target(){
|
||||||
|
self.body.acceleration=a;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
|
PhysicsCollisionAttributes::Intersect{intersecting: _,general}=>{
|
||||||
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
|
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
|
||||||
self.touching.insert_intersect(c.model,c);
|
self.touching.insert_intersect(c.model,c);
|
||||||
run_teleport_behaviour(&general.teleport_behaviour,&mut self.game,&self.models,&self.modes,&self.style,&mut self.touching,&mut self.body,model);
|
run_teleport_behaviour(&general.teleport_behaviour,&mut self.game,&self.models,&self.modes,&self.style,&mut self.touching,&mut self.body,model);
|
||||||
@ -1350,9 +1431,12 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
PhysicsInstruction::CollisionEnd(c) => {
|
PhysicsInstruction::CollisionEnd(c) => {
|
||||||
let model=c.model(&self.models).unwrap();
|
let model=c.model(&self.models).unwrap();
|
||||||
match &model.attributes{
|
match &model.attributes{
|
||||||
PhysicsCollisionAttributes::Contact{contacting,general}=>{
|
PhysicsCollisionAttributes::Contact{contacting: _,general: _}=>{
|
||||||
self.touching.remove_contact(c.model);//remove contact before calling contact_constrain_acceleration
|
self.touching.remove_contact(c.model);//remove contact before calling contact_constrain_acceleration
|
||||||
let mut a=self.style.gravity;
|
let mut a=self.style.gravity;
|
||||||
|
if let Some(rocket_force)=self.style.rocket_force{
|
||||||
|
a+=self.style.get_propulsion_control_dir(&self.camera,self.controls,&self.next_mouse,self.time)*rocket_force;
|
||||||
|
}
|
||||||
self.touching.constrain_acceleration(&self.models,&mut a);
|
self.touching.constrain_acceleration(&self.models,&mut a);
|
||||||
self.body.acceleration=a;
|
self.body.acceleration=a;
|
||||||
//check ground
|
//check ground
|
||||||
@ -1362,10 +1446,12 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
//TODO: make this more advanced checking contacts
|
//TODO: make this more advanced checking contacts
|
||||||
self.move_state=MoveState::Air;
|
self.move_state=MoveState::Air;
|
||||||
},
|
},
|
||||||
_=>self.refresh_walk_target(),
|
_=>if let Some(a)=self.refresh_walk_target(){
|
||||||
|
self.body.acceleration=a;
|
||||||
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
|
PhysicsCollisionAttributes::Intersect{intersecting: _,general: _}=>{
|
||||||
self.touching.remove_intersect(c.model);
|
self.touching.remove_intersect(c.model);
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -1439,7 +1525,14 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
|||||||
PhysicsInputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
|
PhysicsInputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
|
||||||
}
|
}
|
||||||
if refresh_walk_target{
|
if refresh_walk_target{
|
||||||
self.refresh_walk_target();
|
if let Some(a)=self.refresh_walk_target(){
|
||||||
|
self.body.acceleration=a;
|
||||||
|
}else if let Some(rocket_force)=self.style.rocket_force{
|
||||||
|
let mut a=self.style.gravity;
|
||||||
|
a+=self.style.get_propulsion_control_dir(&self.camera,self.controls,&self.next_mouse,self.time)*rocket_force;
|
||||||
|
self.touching.constrain_acceleration(&self.models,&mut a);
|
||||||
|
self.body.acceleration=a;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
134
src/physics_worker.rs
Normal file
134
src/physics_worker.rs
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
use crate::integer::Time;
|
||||||
|
use crate::physics::{MouseState,PhysicsInputInstruction};
|
||||||
|
use crate::instruction::{TimedInstruction,InstructionConsumer};
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum InputInstruction {
|
||||||
|
MoveMouse(glam::IVec2),
|
||||||
|
MoveRight(bool),
|
||||||
|
MoveUp(bool),
|
||||||
|
MoveBack(bool),
|
||||||
|
MoveLeft(bool),
|
||||||
|
MoveDown(bool),
|
||||||
|
MoveForward(bool),
|
||||||
|
Jump(bool),
|
||||||
|
Zoom(bool),
|
||||||
|
Reset,
|
||||||
|
}
|
||||||
|
pub enum Instruction{
|
||||||
|
Input(InputInstruction),
|
||||||
|
Render,
|
||||||
|
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||||
|
GenerateModels(crate::model::IndexedModelInstances),
|
||||||
|
ClearModels,
|
||||||
|
//Graphics(crate::graphics_worker::Instruction),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new<'a>(scope:&'a std::thread::Scope<'a,'_>,mut physics:crate::physics::PhysicsState,graphics_worker:crate::worker::INWorker<'a,crate::graphics_worker::Instruction>)->crate::worker::QNWorker<'a,TimedInstruction<Instruction>>{
|
||||||
|
let mut mouse_blocking=true;
|
||||||
|
let mut last_mouse_time=physics.next_mouse.time;
|
||||||
|
let mut timeline=std::collections::VecDeque::new();
|
||||||
|
crate::worker::QNWorker::new(scope,move |ins:TimedInstruction<Instruction>|{
|
||||||
|
if if let Some(phys_input)=match &ins.instruction{
|
||||||
|
Instruction::Input(input_instruction)=>match input_instruction{
|
||||||
|
&InputInstruction::MoveMouse(m)=>{
|
||||||
|
if mouse_blocking{
|
||||||
|
//tell the game state which is living in the past about its future
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
|
||||||
|
});
|
||||||
|
}else{
|
||||||
|
//mouse has just started moving again after being still for longer than 10ms.
|
||||||
|
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::ReplaceMouse(
|
||||||
|
MouseState{time:last_mouse_time,pos:physics.next_mouse.pos},
|
||||||
|
MouseState{time:ins.time,pos:m}
|
||||||
|
),
|
||||||
|
});
|
||||||
|
//delay physics execution until we have an interpolation target
|
||||||
|
mouse_blocking=true;
|
||||||
|
}
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
None
|
||||||
|
},
|
||||||
|
&InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
|
||||||
|
&InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
|
||||||
|
&InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
|
||||||
|
&InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
|
||||||
|
&InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
|
||||||
|
&InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
|
||||||
|
&InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
|
||||||
|
&InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
|
||||||
|
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
|
||||||
|
},
|
||||||
|
Instruction::GenerateModels(_)=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::ClearModels=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::Resize(_,_)=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
Instruction::Render=>Some(PhysicsInputInstruction::Idle),
|
||||||
|
}{
|
||||||
|
//non-mouse event
|
||||||
|
timeline.push_back(TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:phys_input,
|
||||||
|
});
|
||||||
|
|
||||||
|
if mouse_blocking{
|
||||||
|
//assume the mouse has stopped moving after 10ms.
|
||||||
|
//shitty mice are 125Hz which is 8ms so this should cover that.
|
||||||
|
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
|
||||||
|
//so mouse events are probably not handled separately from drawing and fire right before it :(
|
||||||
|
if Time::from_millis(10)<ins.time-physics.next_mouse.time{
|
||||||
|
//push an event to extrapolate no movement from
|
||||||
|
timeline.push_front(TimedInstruction{
|
||||||
|
time:last_mouse_time,
|
||||||
|
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:physics.next_mouse.pos}),
|
||||||
|
});
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
|
||||||
|
mouse_blocking=false;
|
||||||
|
true
|
||||||
|
}else{
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//keep this up to date so that it can be used as a known-timestamp
|
||||||
|
//that the mouse was not moving when the mouse starts moving again
|
||||||
|
last_mouse_time=ins.time;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
//mouse event
|
||||||
|
true
|
||||||
|
}{
|
||||||
|
//empty queue
|
||||||
|
while let Some(instruction)=timeline.pop_front(){
|
||||||
|
physics.run(instruction.time);
|
||||||
|
physics.process_instruction(TimedInstruction{
|
||||||
|
time:instruction.time,
|
||||||
|
instruction:crate::physics::PhysicsInstruction::Input(instruction.instruction),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match ins.instruction{
|
||||||
|
Instruction::Render=>{
|
||||||
|
let _=graphics_worker.send(crate::graphics_worker::Instruction::Render(physics.output(),ins.time,physics.next_mouse.pos));
|
||||||
|
},
|
||||||
|
Instruction::Resize(size,user_settings)=>{
|
||||||
|
//block!
|
||||||
|
graphics_worker.blocking_send(crate::graphics_worker::Instruction::Resize(size,user_settings)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||||
|
physics.generate_models(&indexed_model_instances);
|
||||||
|
physics.spawn(indexed_model_instances.spawn_point);
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::GenerateModels(indexed_model_instances)).unwrap();
|
||||||
|
},
|
||||||
|
Instruction::ClearModels=>{
|
||||||
|
physics.clear();
|
||||||
|
graphics_worker.send(crate::graphics_worker::Instruction::ClearModels).unwrap();
|
||||||
|
},
|
||||||
|
_=>(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@ -126,17 +126,21 @@ const CORNERWEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
|||||||
Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
||||||
Planar64Vec3::int( 0, 0,-1),//CornerWedge::Front
|
Planar64Vec3::int( 0, 0,-1),//CornerWedge::Front
|
||||||
];
|
];
|
||||||
//HashMap fits this use case perfectly but feels like using a sledgehammer to drive a nail
|
|
||||||
pub fn unit_sphere()->crate::model::IndexedModel{
|
pub fn unit_sphere()->crate::model::IndexedModel{
|
||||||
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),Color4::ONE).remove(0);
|
unit_cube()
|
||||||
for pos in indexed_model.unique_pos.iter_mut(){
|
}
|
||||||
*pos=*pos/2;
|
#[derive(Default)]
|
||||||
}
|
pub struct CubeFaceDescription([Option<FaceDescription>;6]);
|
||||||
indexed_model
|
impl CubeFaceDescription{
|
||||||
|
pub fn insert(&mut self,index:CubeFace,value:FaceDescription){
|
||||||
|
self.0[index as usize]=Some(value);
|
||||||
|
}
|
||||||
|
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,6>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||||
|
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub type CubeFaceDescription=std::collections::HashMap::<CubeFace,FaceDescription>;
|
|
||||||
pub fn unit_cube()->crate::model::IndexedModel{
|
pub fn unit_cube()->crate::model::IndexedModel{
|
||||||
let mut t=CubeFaceDescription::new();
|
let mut t=CubeFaceDescription::default();
|
||||||
t.insert(CubeFace::Right,FaceDescription::default());
|
t.insert(CubeFace::Right,FaceDescription::default());
|
||||||
t.insert(CubeFace::Top,FaceDescription::default());
|
t.insert(CubeFace::Top,FaceDescription::default());
|
||||||
t.insert(CubeFace::Back,FaceDescription::default());
|
t.insert(CubeFace::Back,FaceDescription::default());
|
||||||
@ -145,17 +149,21 @@ pub fn unit_cube()->crate::model::IndexedModel{
|
|||||||
t.insert(CubeFace::Front,FaceDescription::default());
|
t.insert(CubeFace::Front,FaceDescription::default());
|
||||||
generate_partial_unit_cube(t)
|
generate_partial_unit_cube(t)
|
||||||
}
|
}
|
||||||
const TEAPOT_TRANSFORM:crate::integer::Planar64Mat3=crate::integer::Planar64Mat3::int_from_cols_array([0,1,0, -1,0,0, 0,0,1]);
|
|
||||||
pub fn unit_cylinder()->crate::model::IndexedModel{
|
pub fn unit_cylinder()->crate::model::IndexedModel{
|
||||||
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),Color4::ONE).remove(0);
|
unit_cube()
|
||||||
for pos in indexed_model.unique_pos.iter_mut(){
|
}
|
||||||
*pos=TEAPOT_TRANSFORM*(*pos)/10;
|
#[derive(Default)]
|
||||||
}
|
pub struct WedgeFaceDescription([Option<FaceDescription>;5]);
|
||||||
indexed_model
|
impl WedgeFaceDescription{
|
||||||
|
pub fn insert(&mut self,index:WedgeFace,value:FaceDescription){
|
||||||
|
self.0[index as usize]=Some(value);
|
||||||
|
}
|
||||||
|
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||||
|
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub type WedgeFaceDescription=std::collections::HashMap::<WedgeFace,FaceDescription>;
|
|
||||||
pub fn unit_wedge()->crate::model::IndexedModel{
|
pub fn unit_wedge()->crate::model::IndexedModel{
|
||||||
let mut t=WedgeFaceDescription::new();
|
let mut t=WedgeFaceDescription::default();
|
||||||
t.insert(WedgeFace::Right,FaceDescription::default());
|
t.insert(WedgeFace::Right,FaceDescription::default());
|
||||||
t.insert(WedgeFace::TopFront,FaceDescription::default());
|
t.insert(WedgeFace::TopFront,FaceDescription::default());
|
||||||
t.insert(WedgeFace::Back,FaceDescription::default());
|
t.insert(WedgeFace::Back,FaceDescription::default());
|
||||||
@ -163,9 +171,18 @@ pub fn unit_wedge()->crate::model::IndexedModel{
|
|||||||
t.insert(WedgeFace::Bottom,FaceDescription::default());
|
t.insert(WedgeFace::Bottom,FaceDescription::default());
|
||||||
generate_partial_unit_wedge(t)
|
generate_partial_unit_wedge(t)
|
||||||
}
|
}
|
||||||
pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,FaceDescription>;
|
#[derive(Default)]
|
||||||
|
pub struct CornerWedgeFaceDescription([Option<FaceDescription>;5]);
|
||||||
|
impl CornerWedgeFaceDescription{
|
||||||
|
pub fn insert(&mut self,index:CornerWedgeFace,value:FaceDescription){
|
||||||
|
self.0[index as usize]=Some(value);
|
||||||
|
}
|
||||||
|
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||||
|
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
||||||
let mut t=CornerWedgeFaceDescription::new();
|
let mut t=CornerWedgeFaceDescription::default();
|
||||||
t.insert(CornerWedgeFace::Right,FaceDescription::default());
|
t.insert(CornerWedgeFace::Right,FaceDescription::default());
|
||||||
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
|
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
|
||||||
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
|
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
|
||||||
@ -189,18 +206,6 @@ impl std::default::Default for FaceDescription{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl FaceDescription{
|
|
||||||
pub fn new(texture:u32,transform:glam::Affine2,color:Color4)->Self{
|
|
||||||
Self{texture:Some(texture),transform,color}
|
|
||||||
}
|
|
||||||
pub fn from_texture(texture:u32)->Self{
|
|
||||||
Self{
|
|
||||||
texture:Some(texture),
|
|
||||||
transform:glam::Affine2::IDENTITY,
|
|
||||||
color:Color4::ONE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//TODO: it's probably better to use a shared vertex buffer between all primitives and use indexed rendering instead of generating a unique vertex buffer for each primitive.
|
//TODO: it's probably better to use a shared vertex buffer between all primitives and use indexed rendering instead of generating a unique vertex buffer for each primitive.
|
||||||
//implementation: put all roblox primitives into one model.groups <- this won't work but I forget why
|
//implementation: put all roblox primitives into one model.groups <- this won't work but I forget why
|
||||||
pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate::model::IndexedModel{
|
pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate::model::IndexedModel{
|
||||||
@ -212,7 +217,7 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate:
|
|||||||
let mut groups=Vec::new();
|
let mut groups=Vec::new();
|
||||||
let mut transforms=Vec::new();
|
let mut transforms=Vec::new();
|
||||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||||
for (face,face_description) in face_descriptions.into_iter(){
|
for (face_id,face_description) in face_descriptions.pairs(){
|
||||||
//assume that scanning short lists is faster than hashing.
|
//assume that scanning short lists is faster than hashing.
|
||||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||||
transform_index
|
transform_index
|
||||||
@ -233,14 +238,6 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate:
|
|||||||
generated_color.push(face_description.color);
|
generated_color.push(face_description.color);
|
||||||
color_index
|
color_index
|
||||||
} as u32;
|
} as u32;
|
||||||
let face_id=match face{
|
|
||||||
CubeFace::Right => 0,
|
|
||||||
CubeFace::Top => 1,
|
|
||||||
CubeFace::Back => 2,
|
|
||||||
CubeFace::Left => 3,
|
|
||||||
CubeFace::Bottom => 4,
|
|
||||||
CubeFace::Front => 5,
|
|
||||||
};
|
|
||||||
//always push normal
|
//always push normal
|
||||||
let normal_index=generated_normal.len() as u32;
|
let normal_index=generated_normal.len() as u32;
|
||||||
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]);
|
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]);
|
||||||
@ -327,7 +324,7 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crat
|
|||||||
let mut groups=Vec::new();
|
let mut groups=Vec::new();
|
||||||
let mut transforms=Vec::new();
|
let mut transforms=Vec::new();
|
||||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||||
for (face,face_description) in face_descriptions.into_iter(){
|
for (face_id,face_description) in face_descriptions.pairs(){
|
||||||
//assume that scanning short lists is faster than hashing.
|
//assume that scanning short lists is faster than hashing.
|
||||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||||
transform_index
|
transform_index
|
||||||
@ -348,13 +345,6 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crat
|
|||||||
generated_color.push(face_description.color);
|
generated_color.push(face_description.color);
|
||||||
color_index
|
color_index
|
||||||
} as u32;
|
} as u32;
|
||||||
let face_id=match face{
|
|
||||||
WedgeFace::Right => 0,
|
|
||||||
WedgeFace::TopFront => 1,
|
|
||||||
WedgeFace::Back => 2,
|
|
||||||
WedgeFace::Left => 3,
|
|
||||||
WedgeFace::Bottom => 4,
|
|
||||||
};
|
|
||||||
//always push normal
|
//always push normal
|
||||||
let normal_index=generated_normal.len() as u32;
|
let normal_index=generated_normal.len() as u32;
|
||||||
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]);
|
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]);
|
||||||
@ -439,7 +429,7 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
|||||||
let mut groups=Vec::new();
|
let mut groups=Vec::new();
|
||||||
let mut transforms=Vec::new();
|
let mut transforms=Vec::new();
|
||||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||||
for (face,face_description) in face_descriptions.into_iter(){
|
for (face_id,face_description) in face_descriptions.pairs(){
|
||||||
//assume that scanning short lists is faster than hashing.
|
//assume that scanning short lists is faster than hashing.
|
||||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||||
transform_index
|
transform_index
|
||||||
@ -460,13 +450,6 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
|||||||
generated_color.push(face_description.color);
|
generated_color.push(face_description.color);
|
||||||
color_index
|
color_index
|
||||||
} as u32;
|
} as u32;
|
||||||
let face_id=match face{
|
|
||||||
CornerWedgeFace::Right => 0,
|
|
||||||
CornerWedgeFace::TopBack => 1,
|
|
||||||
CornerWedgeFace::TopLeft => 2,
|
|
||||||
CornerWedgeFace::Bottom => 3,
|
|
||||||
CornerWedgeFace::Front => 4,
|
|
||||||
};
|
|
||||||
//always push normal
|
//always push normal
|
||||||
let normal_index=generated_normal.len() as u32;
|
let normal_index=generated_normal.len() as u32;
|
||||||
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);
|
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);
|
||||||
|
@ -1,129 +0,0 @@
|
|||||||
use crate::integer::Time;
|
|
||||||
use crate::physics::{MouseState,PhysicsInputInstruction};
|
|
||||||
use crate::instruction::{TimedInstruction,InstructionConsumer};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum InputInstruction {
|
|
||||||
MoveMouse(glam::IVec2),
|
|
||||||
MoveRight(bool),
|
|
||||||
MoveUp(bool),
|
|
||||||
MoveBack(bool),
|
|
||||||
MoveLeft(bool),
|
|
||||||
MoveDown(bool),
|
|
||||||
MoveForward(bool),
|
|
||||||
Jump(bool),
|
|
||||||
Zoom(bool),
|
|
||||||
Reset,
|
|
||||||
Render,
|
|
||||||
//Idle: there were no input events, but the simulation is safe to advance to this timestep
|
|
||||||
//for interpolation / networking / playback reasons, most playback heads will always want
|
|
||||||
//to be 1 instruction ahead to generate the next state for interpolation.
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct RenderState{
|
|
||||||
physics:crate::physics::PhysicsState,
|
|
||||||
graphics:crate::graphics::GraphicsState,
|
|
||||||
}
|
|
||||||
impl RenderState{
|
|
||||||
pub fn new(user_settings:&crate::settings::UserSettings,indexed_model_instances:crate::model::IndexedModelInstances){
|
|
||||||
|
|
||||||
let mut physics=crate::physics::PhysicsState::default();
|
|
||||||
physics.spawn(indexed_model_instances.spawn_point);
|
|
||||||
physics.load_user_settings(user_settings);
|
|
||||||
physics.generate_models(&indexed_model_instances);
|
|
||||||
|
|
||||||
let mut graphics=Self::new_graphics_state();
|
|
||||||
graphics.load_user_settings(user_settings);
|
|
||||||
graphics.generate_models(indexed_model_instances);
|
|
||||||
//manual reset
|
|
||||||
}
|
|
||||||
pub fn into_worker(mut self)->crate::worker::CNWorker<TimedInstruction<InputInstruction>>{
|
|
||||||
let mut mouse_blocking=true;
|
|
||||||
let mut last_mouse_time=self.physics.next_mouse.time;
|
|
||||||
let mut timeline=std::collections::VecDeque::new();
|
|
||||||
crate::worker::CNWorker::new(move |ins:TimedInstruction<InputInstruction>|{
|
|
||||||
let mut render=false;
|
|
||||||
if if let Some(phys_input)=match ins.instruction{
|
|
||||||
InputInstruction::MoveMouse(m)=>{
|
|
||||||
if mouse_blocking{
|
|
||||||
//tell the game state which is living in the past about its future
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
|
|
||||||
});
|
|
||||||
}else{
|
|
||||||
//mouse has just started moving again after being still for longer than 10ms.
|
|
||||||
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::ReplaceMouse(
|
|
||||||
MouseState{time:last_mouse_time,pos:self.physics.next_mouse.pos},
|
|
||||||
MouseState{time:ins.time,pos:m}
|
|
||||||
),
|
|
||||||
});
|
|
||||||
//delay physics execution until we have an interpolation target
|
|
||||||
mouse_blocking=true;
|
|
||||||
}
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
None
|
|
||||||
},
|
|
||||||
InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
|
|
||||||
InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
|
|
||||||
InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
|
|
||||||
InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
|
|
||||||
InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
|
|
||||||
InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
|
|
||||||
InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
|
|
||||||
InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
|
|
||||||
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
|
|
||||||
InputInstruction::Render=>{render=true;Some(PhysicsInputInstruction::Idle)},
|
|
||||||
}{
|
|
||||||
//non-mouse event
|
|
||||||
timeline.push_back(TimedInstruction{
|
|
||||||
time:ins.time,
|
|
||||||
instruction:phys_input,
|
|
||||||
});
|
|
||||||
|
|
||||||
if mouse_blocking{
|
|
||||||
//assume the mouse has stopped moving after 10ms.
|
|
||||||
//shitty mice are 125Hz which is 8ms so this should cover that.
|
|
||||||
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
|
|
||||||
//so mouse events are probably not handled separately from drawing and fire right before it :(
|
|
||||||
if Time::from_millis(10)<ins.time-self.physics.next_mouse.time{
|
|
||||||
//push an event to extrapolate no movement from
|
|
||||||
timeline.push_front(TimedInstruction{
|
|
||||||
time:last_mouse_time,
|
|
||||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:self.physics.next_mouse.pos}),
|
|
||||||
});
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
|
|
||||||
mouse_blocking=false;
|
|
||||||
true
|
|
||||||
}else{
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
//keep this up to date so that it can be used as a known-timestamp
|
|
||||||
//that the mouse was not moving when the mouse starts moving again
|
|
||||||
last_mouse_time=ins.time;
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
//mouse event
|
|
||||||
true
|
|
||||||
}{
|
|
||||||
//empty queue
|
|
||||||
while let Some(instruction)=timeline.pop_front(){
|
|
||||||
self.physics.run(instruction.time);
|
|
||||||
self.physics.process_instruction(TimedInstruction{
|
|
||||||
time:instruction.time,
|
|
||||||
instruction:crate::physics::PhysicsInstruction::Input(instruction.instruction),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if render{
|
|
||||||
self.graphics.render();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,11 +1,14 @@
|
|||||||
use crate::integer::{Ratio64,Ratio64Vec2};
|
use crate::integer::{Ratio64,Ratio64Vec2};
|
||||||
|
#[derive(Clone)]
|
||||||
struct Ratio{
|
struct Ratio{
|
||||||
ratio:f64,
|
ratio:f64,
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedFov{
|
enum DerivedFov{
|
||||||
FromScreenAspect,
|
FromScreenAspect,
|
||||||
FromAspect(Ratio),
|
FromAspect(Ratio),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Fov{
|
enum Fov{
|
||||||
Exactly{x:f64,y:f64},
|
Exactly{x:f64,y:f64},
|
||||||
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
||||||
@ -16,9 +19,11 @@ impl Default for Fov{
|
|||||||
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedSensitivity{
|
enum DerivedSensitivity{
|
||||||
FromRatio(Ratio64),
|
FromRatio(Ratio64),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Sensitivity{
|
enum Sensitivity{
|
||||||
Exactly{x:Ratio64,y:Ratio64},
|
Exactly{x:Ratio64,y:Ratio64},
|
||||||
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
||||||
@ -30,7 +35,7 @@ impl Default for Sensitivity{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default,Clone)]
|
||||||
pub struct UserSettings{
|
pub struct UserSettings{
|
||||||
fov:Fov,
|
fov:Fov,
|
||||||
sensitivity:Sensitivity,
|
sensitivity:Sensitivity,
|
||||||
|
@ -1,54 +1,70 @@
|
|||||||
fn optional_features() -> wgpu::Features {
|
use crate::instruction::TimedInstruction;
|
||||||
wgpu::Features::empty()
|
use crate::window::WindowInstruction;
|
||||||
|
|
||||||
|
fn optional_features()->wgpu::Features{
|
||||||
|
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||||
|
|wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||||
}
|
}
|
||||||
fn required_features() -> wgpu::Features {
|
fn required_features()->wgpu::Features{
|
||||||
wgpu::Features::empty()
|
wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||||
}
|
}
|
||||||
fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities {
|
fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{
|
||||||
wgpu::DownlevelCapabilities {
|
wgpu::DownlevelCapabilities{
|
||||||
flags: wgpu::DownlevelFlags::empty(),
|
flags:wgpu::DownlevelFlags::empty(),
|
||||||
shader_model: wgpu::ShaderModel::Sm5,
|
shader_model:wgpu::ShaderModel::Sm5,
|
||||||
..wgpu::DownlevelCapabilities::default()
|
..wgpu::DownlevelCapabilities::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn required_limits() -> wgpu::Limits {
|
pub fn required_limits()->wgpu::Limits{
|
||||||
wgpu::Limits::downlevel_webgl2_defaults() // These downlevel limits will allow the code to run on all possible hardware
|
wgpu::Limits::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GraphicsContextPartial1{
|
struct SetupContextPartial1{
|
||||||
backends:wgpu::Backends,
|
backends:wgpu::Backends,
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
}
|
}
|
||||||
fn create_instance()->GraphicsContextPartial1{
|
fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
|
||||||
|
let mut builder = winit::window::WindowBuilder::new();
|
||||||
|
builder = builder.with_title(title);
|
||||||
|
#[cfg(windows_OFF)] // TODO
|
||||||
|
{
|
||||||
|
use winit::platform::windows::WindowBuilderExtWindows;
|
||||||
|
builder = builder.with_no_redirection_bitmap(true);
|
||||||
|
}
|
||||||
|
builder.build(event_loop)
|
||||||
|
}
|
||||||
|
fn create_instance()->SetupContextPartial1{
|
||||||
let backends=wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
let backends=wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
||||||
let dx12_shader_compiler=wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
let dx12_shader_compiler=wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
||||||
GraphicsContextPartial1{
|
SetupContextPartial1{
|
||||||
backends,
|
backends,
|
||||||
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
|
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
|
||||||
backends,
|
backends,
|
||||||
dx12_shader_compiler,
|
dx12_shader_compiler,
|
||||||
|
..Default::default()
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial1{
|
impl SetupContextPartial1{
|
||||||
fn create_surface(self,window:&winit::window::Window)->Result<GraphicsContextPartial2,wgpu::CreateSurfaceError>{
|
fn create_surface(self,window:&winit::window::Window)->Result<SetupContextPartial2,wgpu::CreateSurfaceError>{
|
||||||
Ok(GraphicsContextPartial2{
|
Ok(SetupContextPartial2{
|
||||||
backends:self.backends,
|
backends:self.backends,
|
||||||
|
surface:unsafe{self.instance.create_surface(window)}?,
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:unsafe{self.instance.create_surface(window)}?
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
struct GraphicsContextPartial2{
|
struct SetupContextPartial2{
|
||||||
backends:wgpu::Backends,
|
backends:wgpu::Backends,
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
surface:wgpu::Surface,
|
surface:wgpu::Surface,
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial2{
|
impl SetupContextPartial2{
|
||||||
fn pick_adapter(self)->GraphicsContextPartial3{
|
fn pick_adapter(self)->SetupContextPartial3{
|
||||||
let adapter;
|
let adapter;
|
||||||
|
|
||||||
let optional_features=optional_features();
|
//TODO: prefer adapter that implements optional features
|
||||||
|
//let optional_features=optional_features();
|
||||||
let required_features=required_features();
|
let required_features=required_features();
|
||||||
|
|
||||||
//no helper function smh gotta write it myself
|
//no helper function smh gotta write it myself
|
||||||
@ -99,20 +115,20 @@ impl GraphicsContextPartial2{
|
|||||||
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
||||||
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
||||||
);
|
);
|
||||||
GraphicsContextPartial3{
|
SetupContextPartial3{
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:self.surface,
|
surface:self.surface,
|
||||||
adapter,
|
adapter,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
struct GraphicsContextPartial3{
|
struct SetupContextPartial3{
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
surface:wgpu::Surface,
|
surface:wgpu::Surface,
|
||||||
adapter:wgpu::Adapter,
|
adapter:wgpu::Adapter,
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial3{
|
impl SetupContextPartial3{
|
||||||
fn request_device(self)->GraphicsContextPartial4{
|
fn request_device(self)->SetupContextPartial4{
|
||||||
let optional_features=optional_features();
|
let optional_features=optional_features();
|
||||||
let required_features=required_features();
|
let required_features=required_features();
|
||||||
|
|
||||||
@ -131,7 +147,7 @@ impl GraphicsContextPartial3{
|
|||||||
))
|
))
|
||||||
.expect("Unable to find a suitable GPU adapter!");
|
.expect("Unable to find a suitable GPU adapter!");
|
||||||
|
|
||||||
GraphicsContextPartial4{
|
SetupContextPartial4{
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:self.surface,
|
surface:self.surface,
|
||||||
adapter:self.adapter,
|
adapter:self.adapter,
|
||||||
@ -140,45 +156,44 @@ impl GraphicsContextPartial3{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
struct GraphicsContextPartial4{
|
struct SetupContextPartial4{
|
||||||
instance:wgpu::Instance,
|
instance:wgpu::Instance,
|
||||||
surface:wgpu::Surface,
|
surface:wgpu::Surface,
|
||||||
adapter:wgpu::Adapter,
|
adapter:wgpu::Adapter,
|
||||||
device:wgpu::Device,
|
device:wgpu::Device,
|
||||||
queue:wgpu::Queue,
|
queue:wgpu::Queue,
|
||||||
}
|
}
|
||||||
impl GraphicsContextPartial4{
|
impl SetupContextPartial4{
|
||||||
fn configure_surface(self,size:&winit::dpi::PhysicalSize<u32>)->GraphicsContext{
|
fn configure_surface(self,size:&winit::dpi::PhysicalSize<u32>)->SetupContext{
|
||||||
let mut config=self.surface
|
let mut config=self.surface
|
||||||
.get_default_config(&self.adapter, size.width, size.height)
|
.get_default_config(&self.adapter, size.width, size.height)
|
||||||
.expect("Surface isn't supported by the adapter.");
|
.expect("Surface isn't supported by the adapter.");
|
||||||
let surface_view_format=config.format.add_srgb_suffix();
|
let surface_view_format=config.format.add_srgb_suffix();
|
||||||
config.view_formats.push(surface_view_format);
|
config.view_formats.push(surface_view_format);
|
||||||
|
config.present_mode=wgpu::PresentMode::AutoNoVsync;
|
||||||
self.surface.configure(&self.device, &config);
|
self.surface.configure(&self.device, &config);
|
||||||
|
|
||||||
GraphicsContext{
|
SetupContext{
|
||||||
instance:self.instance,
|
instance:self.instance,
|
||||||
surface:self.surface,
|
surface:self.surface,
|
||||||
adapter:self.adapter,
|
|
||||||
device:self.device,
|
device:self.device,
|
||||||
queue:self.queue,
|
queue:self.queue,
|
||||||
config,
|
config,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub struct GraphicsContext{
|
pub struct SetupContext{
|
||||||
pub instance:wgpu::Instance,
|
pub instance:wgpu::Instance,
|
||||||
pub surface:wgpu::Surface,
|
pub surface:wgpu::Surface,
|
||||||
pub adapter:wgpu::Adapter,
|
|
||||||
pub device:wgpu::Device,
|
pub device:wgpu::Device,
|
||||||
pub queue:wgpu::Queue,
|
pub queue:wgpu::Queue,
|
||||||
pub config:wgpu::SurfaceConfiguration,
|
pub config:wgpu::SurfaceConfiguration,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn setup(title:&str)->GraphicsContextSetup{
|
pub fn setup(title:&str)->SetupContextSetup{
|
||||||
let event_loop=winit::event_loop::EventLoop::new();
|
let event_loop=winit::event_loop::EventLoop::new().unwrap();
|
||||||
|
|
||||||
let window=crate::window::WindowState::create_window(title,&event_loop).unwrap();
|
let window=create_window(title,&event_loop).unwrap();
|
||||||
|
|
||||||
println!("Initializing the surface...");
|
println!("Initializing the surface...");
|
||||||
|
|
||||||
@ -190,126 +205,111 @@ pub fn setup(title:&str)->GraphicsContextSetup{
|
|||||||
|
|
||||||
let partial_4=partial_3.request_device();
|
let partial_4=partial_3.request_device();
|
||||||
|
|
||||||
GraphicsContextSetup{
|
SetupContextSetup{
|
||||||
window,
|
window,
|
||||||
event_loop,
|
event_loop,
|
||||||
partial_graphics_context:partial_4,
|
partial_context:partial_4,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GraphicsContextSetup{
|
pub struct SetupContextSetup{
|
||||||
window:winit::window::Window,
|
window:winit::window::Window,
|
||||||
event_loop:winit::event_loop::EventLoop<()>,
|
event_loop:winit::event_loop::EventLoop<()>,
|
||||||
partial_graphics_context:GraphicsContextPartial4,
|
partial_context:SetupContextPartial4,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GraphicsContextSetup{
|
impl SetupContextSetup{
|
||||||
fn into_split(self)->(winit::window::Window,winit::event_loop::EventLoop<()>,GraphicsContext){
|
fn into_split(self)->(winit::window::Window,winit::event_loop::EventLoop<()>,SetupContext){
|
||||||
let size=self.window.inner_size();
|
let size=self.window.inner_size();
|
||||||
//Steal values and drop self
|
//Steal values and drop self
|
||||||
(
|
(
|
||||||
self.window,
|
self.window,
|
||||||
self.event_loop,
|
self.event_loop,
|
||||||
self.partial_graphics_context.configure_surface(&size),
|
self.partial_context.configure_surface(&size),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
pub fn start(self,mut global_state:crate::GlobalState){
|
pub fn start(self){
|
||||||
let (window,event_loop,graphics_context)=self.into_split();
|
let (window,event_loop,setup_context)=self.into_split();
|
||||||
|
|
||||||
println!("Entering render loop...");
|
//dedicated thread to ping request redraw back and resize the window doesn't seem logical
|
||||||
event_loop.run(move |event,_,control_flow|{
|
//but here I am doing it
|
||||||
*control_flow=if cfg!(feature="metal-auto-capture"){
|
let root_time=std::time::Instant::now();
|
||||||
winit::event_loop::ControlFlow::Exit
|
std::thread::scope(|s|{
|
||||||
}else{
|
let window=crate::window::WindowContextSetup::new(&setup_context,window);
|
||||||
winit::event_loop::ControlFlow::Poll
|
//the thread that spawns the physics thread
|
||||||
};
|
let window_thread=window.into_worker(s,setup_context);
|
||||||
|
|
||||||
|
//schedule frames at 165fps
|
||||||
|
let event_loop_proxy=event_loop.create_proxy();
|
||||||
|
|
||||||
|
s.spawn(move ||{
|
||||||
|
loop{
|
||||||
|
std::thread::sleep(std::time::Duration::from_nanos(1_000_000_000/165));
|
||||||
|
event_loop_proxy.send_event(()).ok();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
println!("Entering event loop...");
|
||||||
|
run_event_loop(event_loop,window_thread,root_time).unwrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_event_loop(
|
||||||
|
event_loop:winit::event_loop::EventLoop<()>,
|
||||||
|
window_thread:crate::worker::QNWorker<TimedInstruction<WindowInstruction>>,
|
||||||
|
root_time:std::time::Instant
|
||||||
|
)->Result<(),winit::error::EventLoopError>{
|
||||||
|
event_loop.run(move |event,elwt|{
|
||||||
|
let time=crate::integer::Time::from_nanos(root_time.elapsed().as_nanos() as i64);
|
||||||
|
// *control_flow=if cfg!(feature="metal-auto-capture"){
|
||||||
|
// winit::event_loop::ControlFlow::Exit
|
||||||
|
// }else{
|
||||||
|
// winit::event_loop::ControlFlow::Poll
|
||||||
|
// };
|
||||||
match event{
|
match event{
|
||||||
winit::event::Event::RedrawEventsCleared=>{
|
winit::event::Event::UserEvent(())=>{
|
||||||
window.request_redraw();
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::RequestRedraw}).unwrap();
|
||||||
}
|
}
|
||||||
winit::event::Event::WindowEvent {
|
winit::event::Event::WindowEvent {
|
||||||
event:
|
event:
|
||||||
winit::event::WindowEvent::Resized(size)
|
// WindowEvent::Resized(size)
|
||||||
| winit::event::WindowEvent::ScaleFactorChanged {
|
// | WindowEvent::ScaleFactorChanged {
|
||||||
new_inner_size:&mut size,
|
// new_inner_size: &mut size,
|
||||||
..
|
// ..
|
||||||
},
|
// },
|
||||||
..
|
winit::event::WindowEvent::Resized(size),//ignoring scale factor changed for now because mutex bruh
|
||||||
|
window_id:_,
|
||||||
} => {
|
} => {
|
||||||
// Once winit is fixed, the detection conditions here can be removed.
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Resize(size)}).unwrap();
|
||||||
// https://github.com/rust-windowing/winit/issues/2876
|
|
||||||
// this has been fixed if I update winit (remove the if statement and only use the else case)
|
|
||||||
//drop adapter when you delete this
|
|
||||||
let max_dimension=graphics_context.adapter.limits().max_texture_dimension_2d;
|
|
||||||
if max_dimension<size.width||max_dimension<size.height{
|
|
||||||
println!(
|
|
||||||
"The resizing size {:?} exceeds the limit of {}.",
|
|
||||||
size,
|
|
||||||
max_dimension
|
|
||||||
);
|
|
||||||
}else{
|
|
||||||
println!("Resizing to {:?}",size);
|
|
||||||
graphics_context.config.width=size.width.max(1);
|
|
||||||
graphics_context.config.height=size.height.max(1);
|
|
||||||
window.resize(&graphics_context);
|
|
||||||
graphics_context.surface.configure(&graphics_context.device,&graphics_context.config);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
winit::event::Event::WindowEvent{event,..}=>match event{
|
winit::event::Event::WindowEvent{event,..}=>match event{
|
||||||
winit::event::WindowEvent::KeyboardInput{
|
winit::event::WindowEvent::KeyboardInput{
|
||||||
input:
|
event:
|
||||||
winit::event::KeyboardInput{
|
winit::event::KeyEvent {
|
||||||
virtual_keycode:Some(winit::event::VirtualKeyCode::Escape),
|
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),
|
||||||
state: winit::event::ElementState::Pressed,
|
state: winit::event::ElementState::Pressed,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
|winit::event::WindowEvent::CloseRequested=>{
|
|winit::event::WindowEvent::CloseRequested=>{
|
||||||
*control_flow=winit::event_loop::ControlFlow::Exit;
|
elwt.exit();
|
||||||
}
|
}
|
||||||
winit::event::WindowEvent::KeyboardInput{
|
winit::event::WindowEvent::RedrawRequested=>{
|
||||||
input:
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Render}).unwrap();
|
||||||
winit::event::KeyboardInput{
|
|
||||||
virtual_keycode:Some(winit::event::VirtualKeyCode::Scroll),
|
|
||||||
state: winit::event::ElementState::Pressed,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
}=>{
|
|
||||||
println!("{:#?}",graphics_context.instance.generate_report());
|
|
||||||
}
|
}
|
||||||
_=>{
|
_=>{
|
||||||
global_state.update(event);
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::WindowEvent(event)}).unwrap();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
winit::event::Event::DeviceEvent{
|
winit::event::Event::DeviceEvent{
|
||||||
event,
|
event,
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
global_state.device_event(event);
|
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::DeviceEvent(event)}).unwrap();
|
||||||
},
|
},
|
||||||
winit::event::Event::RedrawRequested(_)=>{
|
|
||||||
let frame=match graphics_context.surface.get_current_texture(){
|
|
||||||
Ok(frame)=>frame,
|
|
||||||
Err(_)=>{
|
|
||||||
graphics_context.surface.configure(&graphics_context.device,&graphics_context.config);
|
|
||||||
graphics_context.surface
|
|
||||||
.get_current_texture()
|
|
||||||
.expect("Failed to acquire next surface texture!")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
|
|
||||||
format:Some(graphics_context.config.view_formats[0]),
|
|
||||||
..wgpu::TextureViewDescriptor::default()
|
|
||||||
});
|
|
||||||
|
|
||||||
graphics.render(&view,&graphics_context.device,&graphics_context.queue);
|
|
||||||
|
|
||||||
frame.present();
|
|
||||||
}
|
|
||||||
_=>{}
|
_=>{}
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
|
213
src/window.rs
213
src/window.rs
@ -1,50 +1,68 @@
|
|||||||
pub struct WindowState{
|
use crate::instruction::TimedInstruction;
|
||||||
//ok
|
use crate::physics_worker::InputInstruction;
|
||||||
}
|
|
||||||
impl WindowState{
|
|
||||||
fn resize(&mut self);
|
|
||||||
fn render(&self);
|
|
||||||
|
|
||||||
fn update(&mut self, window: &winit::window::Window, event: winit::event::WindowEvent) {
|
pub enum WindowInstruction{
|
||||||
let time=integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
|
Resize(winit::dpi::PhysicalSize<u32>),
|
||||||
|
WindowEvent(winit::event::WindowEvent),
|
||||||
|
DeviceEvent(winit::event::DeviceEvent),
|
||||||
|
RequestRedraw,
|
||||||
|
Render,
|
||||||
|
}
|
||||||
|
|
||||||
|
//holds thread handles to dispatch to
|
||||||
|
struct WindowContext<'a>{
|
||||||
|
manual_mouse_lock:bool,
|
||||||
|
mouse:crate::physics::MouseState,//std::sync::Arc<std::sync::Mutex<>>
|
||||||
|
screen_size:glam::UVec2,
|
||||||
|
user_settings:crate::settings::UserSettings,
|
||||||
|
window:winit::window::Window,
|
||||||
|
physics_thread:crate::worker::QNWorker<'a,TimedInstruction<crate::physics_worker::Instruction>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowContext<'_>{
|
||||||
|
fn get_middle_of_screen(&self)->winit::dpi::PhysicalPosition<f32>{
|
||||||
|
winit::dpi::PhysicalPosition::new(self.screen_size.x as f32/2.0,self.screen_size.y as f32/2.0)
|
||||||
|
}
|
||||||
|
fn window_event(&mut self,time:crate::integer::Time,event: winit::event::WindowEvent) {
|
||||||
match event {
|
match event {
|
||||||
winit::event::WindowEvent::DroppedFile(path)=>{
|
winit::event::WindowEvent::DroppedFile(path)=>{
|
||||||
std::thread::spawn(move ||{
|
//blocking because it's simpler...
|
||||||
let indexed_model_instances=load_file(path);
|
if let Some(indexed_model_instances)=crate::load_file(path){
|
||||||
self.render_thread.send(Instruction::Die(indexed_model_instances));
|
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::ClearModels}).unwrap();
|
||||||
});
|
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::GenerateModels(indexed_model_instances)}).unwrap();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
winit::event::WindowEvent::Focused(state)=>{
|
winit::event::WindowEvent::Focused(_state)=>{
|
||||||
//pause unpause
|
//pause unpause
|
||||||
//recalculate pressed keys on focus
|
//recalculate pressed keys on focus
|
||||||
},
|
},
|
||||||
winit::event::WindowEvent::KeyboardInput {
|
winit::event::WindowEvent::KeyboardInput{
|
||||||
input:winit::event::KeyboardInput{state, virtual_keycode,..},
|
event:winit::event::KeyEvent{state,logical_key,repeat:false,..},
|
||||||
..
|
..
|
||||||
}=>{
|
}=>{
|
||||||
let s=match state {
|
let s=match state{
|
||||||
winit::event::ElementState::Pressed => true,
|
winit::event::ElementState::Pressed=>true,
|
||||||
winit::event::ElementState::Released => false,
|
winit::event::ElementState::Released=>false,
|
||||||
};
|
};
|
||||||
match virtual_keycode{
|
match logical_key{
|
||||||
Some(winit::event::VirtualKeyCode::Tab)=>{
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab)=>{
|
||||||
if s{
|
if s{
|
||||||
self.manual_mouse_lock=false;
|
self.manual_mouse_lock=false;
|
||||||
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)){
|
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
}
|
}
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not release cursor: {:?}",e),
|
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||||
}
|
}
|
||||||
}else{
|
}else{
|
||||||
//if cursor is outside window don't lock but apparently there's no get pos function
|
//if cursor is outside window don't lock but apparently there's no get pos function
|
||||||
//let pos=window.get_cursor_pos();
|
//let pos=window.get_cursor_pos();
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(_)=>{
|
Err(_)=>{
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>{
|
Err(e)=>{
|
||||||
self.manual_mouse_lock=true;
|
self.manual_mouse_lock=true;
|
||||||
@ -54,62 +72,62 @@ impl WindowState{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
window.set_cursor_visible(s);
|
self.window.set_cursor_visible(s);
|
||||||
},
|
},
|
||||||
Some(winit::event::VirtualKeyCode::F11)=>{
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::F11)=>{
|
||||||
if s{
|
if s{
|
||||||
if window.fullscreen().is_some(){
|
if self.window.fullscreen().is_some(){
|
||||||
window.set_fullscreen(None);
|
self.window.set_fullscreen(None);
|
||||||
}else{
|
}else{
|
||||||
window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
|
self.window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Some(winit::event::VirtualKeyCode::Escape)=>{
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape)=>{
|
||||||
if s{
|
if s{
|
||||||
self.manual_mouse_lock=false;
|
self.manual_mouse_lock=false;
|
||||||
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not release cursor: {:?}",e),
|
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||||
}
|
}
|
||||||
window.set_cursor_visible(true);
|
self.window.set_cursor_visible(true);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Some(keycode)=>{
|
keycode=>{
|
||||||
if let Some(input_instruction)=match keycode {
|
if let Some(input_instruction)=match keycode{
|
||||||
winit::event::VirtualKeyCode::W => Some(InputInstruction::MoveForward(s)),
|
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space)=>Some(InputInstruction::Jump(s)),
|
||||||
winit::event::VirtualKeyCode::A => Some(InputInstruction::MoveLeft(s)),
|
winit::keyboard::Key::Character(key)=>match key.as_str(){
|
||||||
winit::event::VirtualKeyCode::S => Some(InputInstruction::MoveBack(s)),
|
"w"=>Some(InputInstruction::MoveForward(s)),
|
||||||
winit::event::VirtualKeyCode::D => Some(InputInstruction::MoveRight(s)),
|
"a"=>Some(InputInstruction::MoveLeft(s)),
|
||||||
winit::event::VirtualKeyCode::E => Some(InputInstruction::MoveUp(s)),
|
"s"=>Some(InputInstruction::MoveBack(s)),
|
||||||
winit::event::VirtualKeyCode::Q => Some(InputInstruction::MoveDown(s)),
|
"d"=>Some(InputInstruction::MoveRight(s)),
|
||||||
winit::event::VirtualKeyCode::Space => Some(InputInstruction::Jump(s)),
|
"e"=>Some(InputInstruction::MoveUp(s)),
|
||||||
winit::event::VirtualKeyCode::Z => Some(InputInstruction::Zoom(s)),
|
"q"=>Some(InputInstruction::MoveDown(s)),
|
||||||
winit::event::VirtualKeyCode::R => if s{Some(InputInstruction::Reset)}else{None},
|
"z"=>Some(InputInstruction::Zoom(s)),
|
||||||
_ => None,
|
"r"=>if s{Some(InputInstruction::Reset)}else{None},
|
||||||
|
_=>None,
|
||||||
|
},
|
||||||
|
_=>None,
|
||||||
}{
|
}{
|
||||||
self.physics_thread.send(TimedInstruction{
|
self.physics_thread.send(TimedInstruction{
|
||||||
time,
|
time,
|
||||||
instruction:input_instruction,
|
instruction:crate::physics_worker::Instruction::Input(input_instruction),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
_=>(),
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
_=>(),
|
_=>(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) {
|
fn device_event(&mut self,time:crate::integer::Time,event: winit::event::DeviceEvent) {
|
||||||
//there's no way this is the best way get a timestamp.
|
|
||||||
let time=integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
|
|
||||||
match event {
|
match event {
|
||||||
winit::event::DeviceEvent::MouseMotion {
|
winit::event::DeviceEvent::MouseMotion {
|
||||||
delta,//these (f64,f64) are integers on my machine
|
delta,//these (f64,f64) are integers on my machine
|
||||||
} => {
|
} => {
|
||||||
if self.manual_mouse_lock{
|
if self.manual_mouse_lock{
|
||||||
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)){
|
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||||
Ok(())=>(),
|
Ok(())=>(),
|
||||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||||
}
|
}
|
||||||
@ -121,7 +139,7 @@ impl WindowState{
|
|||||||
self.mouse.pos+=delta;
|
self.mouse.pos+=delta;
|
||||||
self.physics_thread.send(TimedInstruction{
|
self.physics_thread.send(TimedInstruction{
|
||||||
time,
|
time,
|
||||||
instruction:InputInstruction::MoveMouse(self.mouse.pos),
|
instruction:crate::physics_worker::Instruction::Input(InputInstruction::MoveMouse(self.mouse.pos)),
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
},
|
},
|
||||||
winit::event::DeviceEvent::MouseWheel {
|
winit::event::DeviceEvent::MouseWheel {
|
||||||
@ -131,22 +149,95 @@ impl WindowState{
|
|||||||
if false{//self.physics.style.use_scroll{
|
if false{//self.physics.style.use_scroll{
|
||||||
self.physics_thread.send(TimedInstruction{
|
self.physics_thread.send(TimedInstruction{
|
||||||
time,
|
time,
|
||||||
instruction:InputInstruction::Jump(true),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
instruction:crate::physics_worker::Instruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_=>(),
|
_=>(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
|
pub struct WindowContextSetup{
|
||||||
let mut builder = winit::window::WindowBuilder::new();
|
user_settings:crate::settings::UserSettings,
|
||||||
builder = builder.with_title(title);
|
window:winit::window::Window,
|
||||||
#[cfg(windows_OFF)] // TODO
|
physics:crate::physics::PhysicsState,
|
||||||
{
|
graphics:crate::graphics::GraphicsState,
|
||||||
use winit::platform::windows::WindowBuilderExtWindows;
|
}
|
||||||
builder = builder.with_no_redirection_bitmap(true);
|
|
||||||
|
impl WindowContextSetup{
|
||||||
|
pub fn new(context:&crate::setup::SetupContext,window:winit::window::Window)->Self{
|
||||||
|
//wee
|
||||||
|
let user_settings=crate::settings::read_user_settings();
|
||||||
|
|
||||||
|
let args:Vec<String>=std::env::args().collect();
|
||||||
|
let indexed_model_instances=if args.len()==2{
|
||||||
|
crate::load_file(std::path::PathBuf::from(&args[1]))
|
||||||
|
}else{
|
||||||
|
None
|
||||||
|
}.unwrap_or(crate::default_models());
|
||||||
|
|
||||||
|
let mut physics=crate::physics::PhysicsState::default();
|
||||||
|
physics.load_user_settings(&user_settings);
|
||||||
|
physics.generate_models(&indexed_model_instances);
|
||||||
|
physics.spawn(indexed_model_instances.spawn_point);
|
||||||
|
|
||||||
|
let mut graphics=crate::graphics::GraphicsState::new(&context.device,&context.queue,&context.config);
|
||||||
|
graphics.load_user_settings(&user_settings);
|
||||||
|
graphics.generate_models(&context.device,&context.queue,indexed_model_instances);
|
||||||
|
|
||||||
|
Self{
|
||||||
|
user_settings,
|
||||||
|
window,
|
||||||
|
graphics,
|
||||||
|
physics,
|
||||||
}
|
}
|
||||||
builder.build(event_loop)
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
fn into_context<'a>(self,scope:&'a std::thread::Scope<'a,'_>,setup_context:crate::setup::SetupContext)->WindowContext<'a>{
|
||||||
|
let screen_size=glam::uvec2(setup_context.config.width,setup_context.config.height);
|
||||||
|
let graphics_thread=crate::graphics_worker::new(scope,self.graphics,setup_context.config,setup_context.surface,setup_context.device,setup_context.queue);
|
||||||
|
WindowContext{
|
||||||
|
manual_mouse_lock:false,
|
||||||
|
mouse:crate::physics::MouseState::default(),
|
||||||
|
//make sure to update this!!!!!
|
||||||
|
screen_size,
|
||||||
|
user_settings:self.user_settings,
|
||||||
|
window:self.window,
|
||||||
|
physics_thread:crate::physics_worker::new(scope,self.physics,graphics_thread),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_worker<'a>(self,scope:&'a std::thread::Scope<'a,'_>,setup_context:crate::setup::SetupContext)->crate::worker::QNWorker<'a,TimedInstruction<WindowInstruction>>{
|
||||||
|
let mut window_context=self.into_context(scope,setup_context);
|
||||||
|
crate::worker::QNWorker::new(scope,move |ins:TimedInstruction<WindowInstruction>|{
|
||||||
|
match ins.instruction{
|
||||||
|
WindowInstruction::RequestRedraw=>{
|
||||||
|
window_context.window.request_redraw();
|
||||||
|
}
|
||||||
|
WindowInstruction::WindowEvent(window_event)=>{
|
||||||
|
window_context.window_event(ins.time,window_event);
|
||||||
|
},
|
||||||
|
WindowInstruction::DeviceEvent(device_event)=>{
|
||||||
|
window_context.device_event(ins.time,device_event);
|
||||||
|
},
|
||||||
|
WindowInstruction::Resize(size)=>{
|
||||||
|
window_context.physics_thread.send(
|
||||||
|
TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Resize(size,window_context.user_settings.clone())
|
||||||
|
}
|
||||||
|
).unwrap();
|
||||||
|
}
|
||||||
|
WindowInstruction::Render=>{
|
||||||
|
window_context.physics_thread.send(
|
||||||
|
TimedInstruction{
|
||||||
|
time:ins.time,
|
||||||
|
instruction:crate::physics_worker::Instruction::Render
|
||||||
|
}
|
||||||
|
).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
123
src/worker.rs
123
src/worker.rs
@ -1,6 +1,6 @@
|
|||||||
use std::thread;
|
use std::thread;
|
||||||
use std::sync::{mpsc,Arc};
|
use std::sync::{mpsc,Arc};
|
||||||
use parking_lot::{Mutex,Condvar};
|
use parking_lot::Mutex;
|
||||||
|
|
||||||
//WorkerPool
|
//WorkerPool
|
||||||
struct Pool(u32);
|
struct Pool(u32);
|
||||||
@ -104,17 +104,15 @@ QN = WorkerDescription{
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
//None Output Worker does all its work internally from the perspective of the work submitter
|
//None Output Worker does all its work internally from the perspective of the work submitter
|
||||||
pub struct QNWorker<Task:Send> {
|
pub struct QNWorker<'a,Task:Send>{
|
||||||
sender: mpsc::Sender<Task>,
|
sender: mpsc::Sender<Task>,
|
||||||
|
handle:thread::ScopedJoinHandle<'a,()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task:Send+'static> QNWorker<Task>{
|
impl<'a,Task:Send+'a> QNWorker<'a,Task>{
|
||||||
pub fn new<F:FnMut(Task)+Send+'static>(mut f:F)->Self{
|
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->QNWorker<'a,Task>{
|
||||||
let (sender,receiver)=mpsc::channel::<Task>();
|
let (sender,receiver)=mpsc::channel::<Task>();
|
||||||
let ret=Self {
|
let handle=scope.spawn(move ||{
|
||||||
sender,
|
|
||||||
};
|
|
||||||
thread::spawn(move ||{
|
|
||||||
loop {
|
loop {
|
||||||
match receiver.recv() {
|
match receiver.recv() {
|
||||||
Ok(task)=>f(task),
|
Ok(task)=>f(task),
|
||||||
@ -125,7 +123,10 @@ impl<Task:Send+'static> QNWorker<Task>{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
ret
|
Self{
|
||||||
|
sender,
|
||||||
|
handle,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
||||||
self.sender.send(task)
|
self.sender.send(task)
|
||||||
@ -139,104 +140,36 @@ IN = WorkerDescription{
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
//Inputs are dropped if the worker is busy
|
//Inputs are dropped if the worker is busy
|
||||||
pub struct INWorker<Task:Clone>{
|
pub struct INWorker<'a,Task:Send>{
|
||||||
input:Arc<(Mutex<Task>,Condvar)>,
|
sender: mpsc::SyncSender<Task>,
|
||||||
|
handle:thread::ScopedJoinHandle<'a,()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task:Clone+Send+'static> INWorker<Task>{
|
impl<'a,Task:Send+'a> INWorker<'a,Task>{
|
||||||
pub fn new<F:FnMut(Task)+Send+'static>(task:Task,mut f:F)->Self{
|
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->INWorker<'a,Task>{
|
||||||
let ret=Self {
|
let (sender,receiver)=mpsc::sync_channel::<Task>(1);
|
||||||
input:Arc::new((Mutex::new(task),Condvar::new())),
|
let handle=scope.spawn(move ||{
|
||||||
};
|
|
||||||
let input=ret.input.clone();
|
|
||||||
thread::spawn(move ||{
|
|
||||||
loop {
|
loop {
|
||||||
input.1.wait(&mut input.0.lock());
|
match receiver.recv() {
|
||||||
f(input.0.lock().clone());
|
Ok(task)=>f(task),
|
||||||
}
|
|
||||||
});
|
|
||||||
ret
|
|
||||||
}
|
|
||||||
pub fn send(&self,task:Task){
|
|
||||||
*self.input.0.lock()=task;
|
|
||||||
self.input.1.notify_one();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//worker pools work by cloning a mpsc and passing it into the thread, the thread sends its results through that
|
|
||||||
//worker pools have a master thread that manages the pool so that the work submission thread does not need to implement async
|
|
||||||
|
|
||||||
pub struct QQWorkerPool<Task:Send,Value:Send>{
|
|
||||||
sender:mpsc::Sender<Task>,
|
|
||||||
queue:Arc<Mutex<std::collections::VecDeque<Value>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Task:Send+'static,Value:Send+'static> QQWorkerPool<Task,Value>{
|
|
||||||
pub fn new<F:Fn(Task)->Value+Send+'static>(pool_size:usize,f:F)->Self{
|
|
||||||
let (task_sender,task_receiver)=mpsc::channel::<Task>();
|
|
||||||
let (value_sender,value_receiver)=mpsc::channel::<Value>();
|
|
||||||
let ret=Self{
|
|
||||||
sender:task_sender,
|
|
||||||
queue:Arc::new(Mutex::new(std::collections::VecDeque::new())),
|
|
||||||
};
|
|
||||||
let mut queue_collect=ret.queue.clone();
|
|
||||||
let mut worker_senders=Vec::with_capacity(pool_size);
|
|
||||||
let mut active_workers_collect=Arc::new(Mutex::new(0usize));
|
|
||||||
let mut active_workers_dispatch=active_workers_collect.clone();
|
|
||||||
let mut condvar_collect=Arc::new(Condvar::new());
|
|
||||||
let mut condvar_dispatch=condvar_collect.clone();
|
|
||||||
//task dispatch thread
|
|
||||||
thread::spawn(move ||{
|
|
||||||
loop{
|
|
||||||
//block if no workers are available, value collection thread will notify
|
|
||||||
let n=*active_workers_dispatch.lock();
|
|
||||||
if n==pool_size{
|
|
||||||
//wait for notifiy
|
|
||||||
condvar_dispatch.wait(&mut active_workers_dispatch.lock());
|
|
||||||
}
|
|
||||||
match task_receiver.recv(){
|
|
||||||
Ok(task)=>{
|
|
||||||
*active_workers_dispatch.lock()+=1;
|
|
||||||
//workers are never full here
|
|
||||||
//else if workers busy: spawn a new worker
|
|
||||||
//else: send task to an available worker
|
|
||||||
}
|
|
||||||
Err(_)=>{
|
Err(_)=>{
|
||||||
println!("Dispatch stopping.",);
|
println!("Worker stopping.",);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
//value collection thread (bad idea, put this logic in each thread)
|
Self{
|
||||||
thread::spawn(move ||{
|
sender,
|
||||||
loop{
|
handle,
|
||||||
match value_receiver.recv(){
|
}
|
||||||
Ok(value)=>{
|
|
||||||
//maybe I can be smart with this as a signal that a worker finished a task
|
|
||||||
let n=*active_workers_collect.lock();
|
|
||||||
*active_workers_collect.lock()-=1;
|
|
||||||
if n==pool_size{
|
|
||||||
condvar_collect.notify_one();
|
|
||||||
}
|
|
||||||
(*queue_collect.lock()).push_front(value);
|
|
||||||
}
|
|
||||||
Err(_)=>{
|
|
||||||
println!("Collection stopping.",);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
ret
|
|
||||||
}
|
}
|
||||||
|
//blocking!
|
||||||
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
pub fn blocking_send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
|
||||||
self.sender.send(task)
|
self.sender.send(task)
|
||||||
}
|
}
|
||||||
|
pub fn send(&self,task:Task)->Result<(), mpsc::TrySendError<Task>>{
|
||||||
pub fn get(&self)->Option<Value>{
|
self.sender.try_send(task)
|
||||||
(*self.queue.lock()).pop_back()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
1
tools/arcane
Executable file
1
tools/arcane
Executable file
@ -0,0 +1 @@
|
|||||||
|
mangohud ../target/release/strafe-client bhop_maps/5692113331.rbxm
|
1
tools/bhop_maps
Symbolic link
1
tools/bhop_maps
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
/run/media/quat/Files/Documents/map-files/verify-scripts/maps/bhop_all/
|
1
tools/cross-compile.sh
Executable file
1
tools/cross-compile.sh
Executable file
@ -0,0 +1 @@
|
|||||||
|
cargo build --release --target x86_64-pc-windows-gnu
|
4
tools/make-demo.sh
Executable file
4
tools/make-demo.sh
Executable file
@ -0,0 +1,4 @@
|
|||||||
|
mkdir -p ../target/demo
|
||||||
|
mv ../target/x86_64-pc-windows-gnu/release/strafe-client.exe ../target/demo/strafe-client.exe
|
||||||
|
rm ../target/demo.7z
|
||||||
|
7z a -t7z -mx=9 -mfb=273 -ms -md=31 -myx=9 -mtm=- -mmt -mmtf -md=1536m -mmf=bt3 -mmc=10000 -mpb=0 -mlc=0 ../target/demo.7z ../target/demo
|
1
tools/run
Executable file
1
tools/run
Executable file
@ -0,0 +1 @@
|
|||||||
|
mangohud ../target/release/strafe-client "$1"
|
4
tools/settings.conf
Normal file
4
tools/settings.conf
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
[camera]
|
||||||
|
sensitivity_x=98384
|
||||||
|
fov_y=1.0
|
||||||
|
#fov_x_from_y_ratio=1.33333333333333333333333333333333
|
1
tools/textures
Symbolic link
1
tools/textures
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
/run/media/quat/Files/Documents/map-files/verify-scripts/textures/dds/
|
1
tools/toc
Executable file
1
tools/toc
Executable file
@ -0,0 +1 @@
|
|||||||
|
mangohud ../target/release/strafe-client bhop_maps/5692152916.rbxm
|
Reference in New Issue
Block a user