Compare commits

..

2 Commits

Author SHA1 Message Date
17b0d12d4d we're chilling 2023-10-01 15:05:39 -07:00
1f9bdd9a34 multithreading remains a mystery 2023-10-01 14:56:02 -07:00
10 changed files with 530 additions and 1281 deletions

26
Cargo.lock generated
View File

@@ -834,29 +834,6 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "lazy-regex"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e723bd417b2df60a0f6a2b6825f297ea04b245d4ba52b5a22cb679bdf58b05fa"
dependencies = [
"lazy-regex-proc_macros",
"once_cell",
"regex",
]
[[package]]
name = "lazy-regex-proc_macros"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f0a1d9139f0ee2e862e08a9c5d0ba0470f2aa21cd1e1aa1b1562f83116c725f"
dependencies = [
"proc-macro2",
"quote",
"regex",
"syn 2.0.29",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.4.0" version = "1.4.0"
@@ -1689,15 +1666,14 @@ dependencies = [
"ddsfile", "ddsfile",
"env_logger", "env_logger",
"glam", "glam",
"lazy-regex",
"log", "log",
"obj", "obj",
"parking_lot",
"pollster", "pollster",
"rbx_binary", "rbx_binary",
"rbx_dom_weak", "rbx_dom_weak",
"rbx_reflection_database", "rbx_reflection_database",
"rbx_xml", "rbx_xml",
"regex",
"wgpu", "wgpu",
"winit", "winit",
] ]

View File

@@ -11,19 +11,18 @@ bytemuck = { version = "1.13.1", features = ["derive"] }
ddsfile = "0.5.1" ddsfile = "0.5.1"
env_logger = "0.10.0" env_logger = "0.10.0"
glam = "0.24.1" glam = "0.24.1"
lazy-regex = "3.0.2"
log = "0.4.20" log = "0.4.20"
obj = "0.10.2" obj = "0.10.2"
parking_lot = "0.12.1"
pollster = "0.3.0" pollster = "0.3.0"
rbx_binary = "0.7.1" 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"
regex = "1.9.5"
wgpu = "0.17.0" wgpu = "0.17.0"
winit = "0.28.6" winit = "0.28.6"
#[profile.release] [profile.release]
#lto = true lto = true
#strip = true strip = true
#codegen-units = 1 codegen-units = 1

View File

@@ -14,6 +14,8 @@ pub enum PhysicsInstruction {
// ) // )
//InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it) //InputInstructions conditionally activate RefreshWalkTarget (by doing what SetWalkTargetVelocity used to do and then flagging it)
Input(InputInstruction), Input(InputInstruction),
//temp
SetSpawnPosition(glam::Vec3),
} }
#[derive(Debug)] #[derive(Debug)]
pub enum InputInstruction { pub enum InputInstruction {
@@ -32,7 +34,7 @@ pub enum InputInstruction {
//for interpolation / networking / playback reasons, most playback heads will always want //for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation. //to be 1 instruction ahead to generate the next state for interpolation.
} }
#[derive(Clone)]
pub struct Body { pub struct Body {
position: glam::Vec3,//I64 where 2^32 = 1 u position: glam::Vec3,//I64 where 2^32 = 1 u
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
@@ -43,20 +45,20 @@ trait MyHash{
fn hash(&self) -> u64; fn hash(&self) -> u64;
} }
impl MyHash for Body { impl MyHash for Body {
fn hash(&self) -> u64 { fn hash(&self) -> u64 {
let mut hasher=std::collections::hash_map::DefaultHasher::new(); let mut hasher=std::collections::hash_map::DefaultHasher::new();
for &el in self.position.as_ref().iter() { for &el in self.position.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
} }
for &el in self.velocity.as_ref().iter() { for &el in self.velocity.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
} }
for &el in self.acceleration.as_ref().iter() { for &el in self.acceleration.as_ref().iter() {
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
} }
std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice()); std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice());
return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid
} }
} }
pub enum MoveRestriction { pub enum MoveRestriction {
@@ -78,9 +80,9 @@ impl InputState {
} }
impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{ impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<InputInstruction>> { fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<InputInstruction>> {
//this is polled by PhysicsState for actions like Jump //this is polled by PhysicsState for actions like Jump
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed. //no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
self.queue.get(0) self.queue.get(0)
} }
} }
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
@@ -91,33 +93,47 @@ impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
} }
*/ */
//hey dumbass just use a delta enum MouseInterpolation {
#[derive(Clone)] First,//just checks the last value
pub struct MouseState { Lerp,//lerps between
pub pos: glam::IVec2,
pub time: TIME,
} }
impl Default for MouseState{ pub struct MouseInterpolationState {
fn default() -> Self { interpolation: MouseInterpolation,
time0: TIME,
time1: TIME,
mouse0: glam::IVec2,
mouse1: glam::IVec2,
}
impl MouseInterpolationState {
pub fn new() -> Self {
Self { Self {
time:0, interpolation:MouseInterpolation::First,
pos:glam::IVec2::ZERO, time0:0,
time1:1,//ONE NANOSECOND!!!! avoid divide by zero
mouse0:glam::IVec2::ZERO,
mouse1:glam::IVec2::ZERO,
} }
} }
} pub fn move_mouse(&mut self,time:TIME,delta:glam::IVec2){
impl MouseState { self.time0=self.time1;
pub fn move_mouse(&mut self,pos:glam::IVec2,time:TIME){ self.mouse0=self.mouse1;
self.time=time; self.time1=time;
self.pos=pos; self.mouse1=self.mouse1+delta;
} }
pub fn lerp(&self,target:&MouseState,time:TIME)->glam::IVec2 { pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
let m0=self.pos.as_i64vec2(); match self.interpolation {
let m1=target.pos.as_i64vec2(); MouseInterpolation::First => self.mouse0,
//these are deltas MouseInterpolation::Lerp => {
let t1t=(target.time-time) as i64; let m0=self.mouse0.as_i64vec2();
let tt0=(time-self.time) as i64; let m1=self.mouse1.as_i64vec2();
let dt=(target.time-self.time) as i64; //these are deltas
((m0*t1t+m1*tt0)/dt).as_ivec2() let t1t=(self.time1-time) as i64;
let tt0=(time-self.time0) as i64;
let dt=(self.time1-self.time0) as i64;
((m0*t1t+m1*tt0)/dt).as_ivec2()
}
}
} }
} }
@@ -140,168 +156,127 @@ impl WalkState {
} }
} }
#[derive(Clone)] // Note: we use the Y=up coordinate space in this example.
pub struct PhysicsCamera { pub struct Camera {
offset: glam::Vec3, offset: glam::Vec3,
angles: glam::DVec2,//YAW AND THEN PITCH angles: glam::DVec2,//YAW AND THEN PITCH
//punch: glam::Vec3, //punch: glam::Vec3,
//punch_velocity: glam::Vec3, //punch_velocity: glam::Vec3,
fov: glam::Vec2,//slope
sensitivity: glam::DVec2, sensitivity: glam::DVec2,
mouse:MouseState, time: TIME,
} }
#[inline] #[inline]
fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 { fn mat3_from_rotation_y_f64(angle: f64) -> glam::Mat3 {
let (sina, cosa) = angle.sin_cos(); let (sina, cosa) = angle.sin_cos();
glam::Mat3::from_cols( glam::Mat3::from_cols(
glam::Vec3::new(cosa as f32, 0.0, -sina as f32), glam::Vec3::new(cosa as f32, 0.0, -sina as f32),
glam::Vec3::Y, glam::Vec3::Y,
glam::Vec3::new(sina as f32, 0.0, cosa as f32), glam::Vec3::new(sina as f32, 0.0, cosa as f32),
)
}
#[inline]
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
//glam_assert!(z_near > 0.0 && z_far > 0.0);
let r = z_far / (z_near - z_far);
glam::Mat4::from_cols(
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, r, -1.0),
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
) )
} }
impl PhysicsCamera { impl Camera {
pub fn from_offset(offset:glam::Vec3) -> Self { pub fn from_offset(offset:glam::Vec3,aspect:f32) -> Self {
Self{ Self{
offset, offset,
angles: glam::DVec2::ZERO, angles: glam::DVec2::ZERO,
sensitivity: glam::dvec2(1.0/16384.0,1.0/16384.0), fov: glam::vec2(aspect,1.0),
mouse:MouseState{pos:glam::IVec2::ZERO,time:-1},//escape initialization hell divide by zero sensitivity: glam::dvec2(1.0/6144.0,1.0/6144.0),
time: 0,
} }
} }
pub fn simulate_move_angles(&self, mouse_pos: glam::IVec2) -> glam::DVec2 { fn simulate_move_angles(&self, delta: glam::IVec2) -> glam::DVec2 {
let mut a=self.angles-self.sensitivity*(mouse_pos-self.mouse.pos).as_dvec2(); let mut a=self.angles-self.sensitivity*delta.as_dvec2();
a.y=a.y.clamp(-std::f64::consts::FRAC_PI_2, std::f64::consts::FRAC_PI_2); a.y=a.y.clamp(-std::f64::consts::FRAC_PI_2, std::f64::consts::FRAC_PI_2);
return a return a
} }
fn simulate_move_rotation_y(&self, mouse_pos_x: i32) -> glam::Mat3 { fn simulate_move_rotation_y(&self, delta_x: i32) -> glam::Mat3 {
mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*((mouse_pos_x-self.mouse.pos.x) as f64)) mat3_from_rotation_y_f64(self.angles.x-self.sensitivity.x*(delta_x as f64))
}
pub fn proj(&self)->glam::Mat4{
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
}
pub fn view(&self,pos:glam::Vec3)->glam::Mat4{
//f32 good enough for view matrix
glam::Mat4::from_translation(pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.angles.x as f32, self.angles.y as f32, 0f32)
}
pub fn set_fov_aspect(&mut self,fov:f32,aspect:f32){
self.fov.x=fov*aspect;
self.fov.y=fov;
} }
} }
pub struct GameMechanicsState{ const CONTROL_MOVEFORWARD:u32 = 0b00000001;
pub stage_id:u32, const CONTROL_MOVEBACK:u32 = 0b00000010;
//jump_counts:HashMap<u32,u32>, const CONTROL_MOVERIGHT:u32 = 0b00000100;
} const CONTROL_MOVELEFT:u32 = 0b00001000;
impl std::default::Default for GameMechanicsState{ const CONTROL_MOVEUP:u32 = 0b00010000;
fn default() -> Self { const CONTROL_MOVEDOWN:u32 = 0b00100000;
Self{ const CONTROL_JUMP:u32 = 0b01000000;
stage_id:0, const CONTROL_ZOOM:u32 = 0b10000000;
}
const FORWARD_DIR:glam::Vec3 = glam::Vec3::new(0.0,0.0,-1.0);
const RIGHT_DIR:glam::Vec3 = glam::Vec3::new(1.0,0.0,0.0);
const UP_DIR:glam::Vec3 = glam::Vec3::new(0.0,1.0,0.0);
fn get_control_dir(controls: u32) -> glam::Vec3{
//don't get fancy just do it
let mut control_dir:glam::Vec3 = glam::Vec3::new(0.0,0.0,0.0);
if controls & CONTROL_MOVEFORWARD == CONTROL_MOVEFORWARD {
control_dir+=FORWARD_DIR;
} }
} if controls & CONTROL_MOVEBACK == CONTROL_MOVEBACK {
control_dir+=-FORWARD_DIR;
pub struct WorldState{}
pub struct StyleModifiers{
pub controls_mask:u32,//controls which are unable to be activated
pub controls_held:u32,//controls which must be active to be able to strafe
pub mv:f32,
pub walkspeed:f32,
pub friction:f32,
pub walk_accel:f32,
pub gravity:glam::Vec3,
pub strafe_tick_num:TIME,
pub strafe_tick_den:TIME,
pub hitbox_halfsize:glam::Vec3,
}
impl std::default::Default for StyleModifiers{
fn default() -> Self {
Self{
controls_mask: !0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
walkspeed: 18.0,
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
}
} }
} if controls & CONTROL_MOVELEFT == CONTROL_MOVELEFT {
impl StyleModifiers{ control_dir+=-RIGHT_DIR;
const CONTROL_MOVEFORWARD:u32 = 0b00000001;
const CONTROL_MOVEBACK:u32 = 0b00000010;
const CONTROL_MOVERIGHT:u32 = 0b00000100;
const CONTROL_MOVELEFT:u32 = 0b00001000;
const CONTROL_MOVEUP:u32 = 0b00010000;
const CONTROL_MOVEDOWN:u32 = 0b00100000;
const CONTROL_JUMP:u32 = 0b01000000;
const CONTROL_ZOOM:u32 = 0b10000000;
const FORWARD_DIR:glam::Vec3 = glam::Vec3::NEG_Z;
const RIGHT_DIR:glam::Vec3 = glam::Vec3::X;
const UP_DIR:glam::Vec3 = glam::Vec3::Y;
fn get_control(&self,control:u32,controls:u32)->bool{
controls&self.controls_mask&control==control
} }
if controls & CONTROL_MOVERIGHT == CONTROL_MOVERIGHT {
fn get_control_dir(&self,controls:u32)->glam::Vec3{ control_dir+=RIGHT_DIR;
//don't get fancy just do it
let mut control_dir:glam::Vec3 = glam::Vec3::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
let controls=controls&self.controls_mask;
if controls & Self::CONTROL_MOVEFORWARD == Self::CONTROL_MOVEFORWARD {
control_dir+=Self::FORWARD_DIR;
}
if controls & Self::CONTROL_MOVEBACK == Self::CONTROL_MOVEBACK {
control_dir+=-Self::FORWARD_DIR;
}
if controls & Self::CONTROL_MOVELEFT == Self::CONTROL_MOVELEFT {
control_dir+=-Self::RIGHT_DIR;
}
if controls & Self::CONTROL_MOVERIGHT == Self::CONTROL_MOVERIGHT {
control_dir+=Self::RIGHT_DIR;
}
if controls & Self::CONTROL_MOVEUP == Self::CONTROL_MOVEUP {
control_dir+=Self::UP_DIR;
}
if controls & Self::CONTROL_MOVEDOWN == Self::CONTROL_MOVEDOWN {
control_dir+=-Self::UP_DIR;
}
return control_dir
} }
if controls & CONTROL_MOVEUP == CONTROL_MOVEUP {
control_dir+=UP_DIR;
}
if controls & CONTROL_MOVEDOWN == CONTROL_MOVEDOWN {
control_dir+=-UP_DIR;
}
return control_dir
} }
pub struct PhysicsState{ pub struct PhysicsState {
pub time:TIME, pub body: Body,
pub body:Body, pub hitbox_halfsize: glam::Vec3,
pub world:WorldState,//currently there is only one state the world can be in pub contacts: std::collections::HashSet::<RelativeCollision>,
pub game:GameMechanicsState,
pub style:StyleModifiers,
pub contacts:std::collections::HashMap::<u32,RelativeCollision>,
pub intersects:std::collections::HashMap::<u32,RelativeCollision>,
//pub intersections: Vec<ModelId>, //pub intersections: Vec<ModelId>,
pub models: Vec<ModelPhysics>,
//camera must exist in state because wormholes modify the camera, also camera punch //camera must exist in state because wormholes modify the camera, also camera punch
pub camera:PhysicsCamera, pub camera: Camera,
pub next_mouse:MouseState,//Where is the mouse headed next pub mouse_interpolation: MouseInterpolationState,
pub controls:u32, pub controls: u32,
pub walk:WalkState, pub time: TIME,
pub grounded:bool, pub strafe_tick_num: TIME,
//all models pub strafe_tick_den: TIME,
pub models:Vec<ModelPhysics>, pub tick: u32,
pub mv: f32,
pub modes:Vec<crate::model::ModeDescription>, pub walk: WalkState,
pub mode_from_mode_id:std::collections::HashMap::<u32,usize>, pub walkspeed: f32,
//the spawn point is where you spawn when you load into the map. pub friction: f32,
//This is not the same as Reset which teleports you to Spawn0 pub walk_accel: f32,
pub spawn_point:glam::Vec3, pub gravity: glam::Vec3,
} pub grounded: bool,
#[derive(Clone)] pub spawn_point: glam::Vec3,
pub struct PhysicsOutputState{
camera:PhysicsCamera,
body:Body,
}
impl PhysicsOutputState{
pub fn adjust_mouse(&self,mouse:&MouseState)->(glam::Vec3,glam::Vec2){
(self.body.extrapolated_position(mouse.time),self.camera.simulate_move_angles(mouse.pos).as_vec2())
}
} }
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)] #[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
@@ -413,42 +388,20 @@ impl Aabb {
type TreyMeshFace = AabbFace; type TreyMeshFace = AabbFace;
type TreyMesh = Aabb; type TreyMesh = Aabb;
enum PhysicsCollisionAttributes{
Contact{//track whether you are contacting the object
contacting:crate::model::ContactingAttributes,
general:crate::model::GameMechanicAttributes,
},
Intersect{//track whether you are intersecting the object
intersecting:crate::model::IntersectingAttributes,
general:crate::model::GameMechanicAttributes,
},
}
pub struct ModelPhysics { pub struct ModelPhysics {
//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,
transform:glam::Affine3A,
attributes:PhysicsCollisionAttributes,
} }
impl ModelPhysics { impl ModelPhysics {
fn from_model_transform_attributes(model:&crate::model::IndexedModel,transform:&glam::Affine3A,attributes:PhysicsCollisionAttributes)->Self{ pub fn from_model(model:&crate::model::IndexedModel,model_transform:glam::Affine3A) -> Self {
let mut aabb=Aabb::new(); let mut aabb=Aabb::new();
for indexed_vertex in &model.unique_vertices { for indexed_vertex in &model.unique_vertices {
aabb.grow(transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize]))); aabb.grow(model_transform.transform_point3(glam::Vec3::from_array(model.unique_pos[indexed_vertex.pos as usize])));
} }
Self{ Self{
mesh:aabb, mesh:aabb,
attributes,
transform:transform.clone(),
}
}
pub fn from_model(model:&crate::model::IndexedModel,instance:&crate::model::ModelInstance) -> Option<Self> {
match &instance.attributes{
crate::model::CollisionAttributes::Contact{contacting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Contact{contacting:contacting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Intersect{intersecting,general}=>Some(ModelPhysics::from_model_transform_attributes(model,&instance.transform,PhysicsCollisionAttributes::Intersect{intersecting:intersecting.clone(),general:general.clone()})),
crate::model::CollisionAttributes::Decoration=>None,
} }
} }
pub fn unit_vertices(&self) -> [glam::Vec3;8] { pub fn unit_vertices(&self) -> [glam::Vec3;8] {
@@ -487,14 +440,11 @@ pub struct RelativeCollision {
} }
impl RelativeCollision { impl RelativeCollision {
pub fn model<'a>(&self,models:&'a Vec<ModelPhysics>)->Option<&'a ModelPhysics>{
models.get(self.model as usize)
}
pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh { pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
return self.model(models).unwrap().face_mesh(self.face).clone() return models.get(self.model as usize).unwrap().face_mesh(self.face).clone()
} }
pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 { pub fn normal(&self,models:&Vec<ModelPhysics>) -> glam::Vec3 {
return self.model(models).unwrap().face_normal(self.face) return models.get(self.model as usize).unwrap().face_normal(self.face)
} }
} }
@@ -524,183 +474,7 @@ impl Body {
} }
} }
impl Default for PhysicsState{
fn default() -> Self {
Self{
spawn_point:glam::vec3(0.0,50.0,0.0),
body: Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
time: 0,
style:StyleModifiers::default(),
grounded: false,
contacts: std::collections::HashMap::new(),
intersects: std::collections::HashMap::new(),
models: Vec::new(),
walk: WalkState::new(),
camera: PhysicsCamera::from_offset(glam::vec3(0.0,4.5-2.5,0.0)),
next_mouse: MouseState::default(),
controls: 0,
world:WorldState{},
game:GameMechanicsState::default(),
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
}
}
}
impl PhysicsState { impl PhysicsState {
pub fn clear(&mut self){
self.models.clear();
self.modes.clear();
self.contacts.clear();
self.intersects.clear();
}
pub fn into_worker(mut self)->crate::worker::Worker<TimedInstruction<InputInstruction>,PhysicsOutputState>{
let mut last_time=0;
//last_time: this indicates the last time the mouse position was known.
//Only used to generate a MouseState right before mouse movement
//to finalize a long period of no movement and avoid interpolating from a long out-of-date MouseState.
let mut mouse_blocking=true;//waiting for next_mouse to be written
let mut timeline=std::collections::VecDeque::new();
crate::worker::Worker::new(self.output(),move |ins:TimedInstruction<InputInstruction>|{
let run_queue=match &ins.instruction{
InputInstruction::MoveMouse(_)=>{
//I FORGOT TO EDIT THE MOVE MOUSE TIMESTAMPS
if !mouse_blocking{
//mouse has not been moving for a while.
//make sure not to interpolate between two distant MouseStates.
//generate a mouse instruction with no movement timestamped at last InputInstruction
//Idle instructions are CRITICAL to keeping this value up to date
//interpolate normally (now that prev mouse pos is up to date)
// timeline.push_back(TimedInstruction{
// time:last_time,
// instruction:InputInstruction::MoveMouse(self.next_mouse.pos),
// });
}
mouse_blocking=true;//block physics until the next mouse event or mouse event timeout.
true//empty queue
},
_=>{
if mouse_blocking{
//maybe I can turn this inside out by making this anotehr state machine where 50_000_000 is an instruction timestamp
//check if last mouse move is within 50ms
if ins.time-self.next_mouse.time<50_000_000{
false//do not empty queue
}else{
mouse_blocking=false;
// timeline.push_back(TimedInstruction{
// time:ins.time,
// instruction:InputInstruction::MoveMouse(self.next_mouse.pos),
// });
true
}
}else{
true
}
},
};
last_time=ins.time;
timeline.push_back(ins);
if run_queue{
//empty queue
while let Some(instruction)=timeline.pop_front(){
self.run(instruction.time);
self.process_instruction(TimedInstruction{
time:instruction.time,
instruction:PhysicsInstruction::Input(instruction.instruction),
});
}
}
self.output()
})
}
pub fn output(&self)->PhysicsOutputState{
PhysicsOutputState{
body:self.body.clone(),
camera:self.camera.clone(),
}
}
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
let mut starts=Vec::new();
let mut spawns=Vec::new();
let mut ordered_checkpoints=Vec::new();
let mut unordered_checkpoints=Vec::new();
for model in &indexed_models.models{
//make aabb and run vertices to get realistic bounds
for model_instance in &model.instances{
if let Some(model_physics)=ModelPhysics::from_model(model,model_instance){
let model_id=self.models.len() as u32;
self.models.push(model_physics);
for attr in &model_instance.temp_indexing{
match attr{
crate::model::TempIndexedAttributes::Start{mode_id}=>starts.push((*mode_id,model_id)),
crate::model::TempIndexedAttributes::Spawn{mode_id,stage_id}=>spawns.push((*mode_id,model_id,*stage_id)),
crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id,checkpoint_id}=>ordered_checkpoints.push((*mode_id,model_id,*checkpoint_id)),
crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id}=>unordered_checkpoints.push((*mode_id,model_id)),
}
}
}
}
}
//I don't wanna write structs for temporary structures
//this code builds ModeDescriptions from the unsorted lists at the top of the function
starts.sort_by_key(|tup|tup.0);
let mut eshmep=std::collections::HashMap::new();
let mut modedatas:Vec<(u32,Vec<(u32,u32)>,Vec<(u32,u32)>,Vec<u32>)>=starts.into_iter().enumerate().map(|(i,tup)|{
eshmep.insert(tup.0,i);
(tup.1,Vec::new(),Vec::new(),Vec::new())
}).collect();
for tup in spawns{
if let Some(mode_id)=eshmep.get(&tup.0){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.1.push((tup.2,tup.1));
}
}
}
for tup in ordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.2.push((tup.2,tup.1));
}
}
}
for tup in unordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.3.push(tup.1);
}
}
}
let num_modes=self.modes.len();
for (mode_id,mode) in eshmep{
self.mode_from_mode_id.insert(mode_id,num_modes+mode);
}
self.modes.append(&mut modedatas.into_iter().map(|mut tup|{
tup.1.sort_by_key(|tup|tup.0);
tup.2.sort_by_key(|tup|tup.0);
let mut eshmep1=std::collections::HashMap::new();
let mut eshmep2=std::collections::HashMap::new();
crate::model::ModeDescription{
start:tup.0,
spawns:tup.1.into_iter().enumerate().map(|(i,tup)|{eshmep1.insert(tup.0,i);tup.1}).collect(),
ordered_checkpoints:tup.2.into_iter().enumerate().map(|(i,tup)|{eshmep2.insert(tup.0,i);tup.1}).collect(),
unordered_checkpoints:tup.3,
spawn_from_stage_id:eshmep1,
ordered_checkpoint_from_checkpoint_id:eshmep2,
}
}).collect());
println!("Physics Objects: {}",self.models.len());
}
pub fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
self.modes.get(mode)
}else{
None
}
}
//tickless gaming //tickless gaming
pub fn run(&mut self, time_limit:TIME){ pub fn run(&mut self, time_limit:TIME){
//prepare is ommitted - everything is done via instructions. //prepare is ommitted - everything is done via instructions.
@@ -727,7 +501,7 @@ impl PhysicsState {
} }
fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){ fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){
for (_,contact) in &self.contacts { for contact in self.contacts.iter() {
let n=contact.normal(&self.models); let n=contact.normal(&self.models);
let d=velocity.dot(n); let d=velocity.dot(n);
if d<0f32{ if d<0f32{
@@ -736,7 +510,7 @@ impl PhysicsState {
} }
} }
fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){ fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){
for (_,contact) in &self.contacts { for contact in self.contacts.iter() {
let n=contact.normal(&self.models); let n=contact.normal(&self.models);
let d=acceleration.dot(n); let d=acceleration.dot(n);
if d<0f32{ if d<0f32{
@@ -746,7 +520,7 @@ impl PhysicsState {
} }
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> { fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
return Some(TimedInstruction{ return Some(TimedInstruction{
time:(self.time*self.style.strafe_tick_num/self.style.strafe_tick_den+1)*self.style.strafe_tick_den/self.style.strafe_tick_num, time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
//only poll the physics if there is a before and after mouse event //only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick instruction:PhysicsInstruction::StrafeTick
}); });
@@ -796,7 +570,7 @@ impl PhysicsState {
self.body.acceleration=a; self.body.acceleration=a;
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
}else{ }else{
let accel=self.style.walk_accel.min(self.style.gravity.length()*self.style.friction); let accel=self.walk_accel.min(self.gravity.length()*self.friction);
let time_delta=target_diff.length()/accel; let time_delta=target_diff.length()/accel;
let mut a=target_diff/time_delta; let mut a=target_diff/time_delta;
self.contact_constrain_acceleration(&mut a); self.contact_constrain_acceleration(&mut a);
@@ -825,7 +599,7 @@ impl PhysicsState {
fn mesh(&self) -> TreyMesh { fn mesh(&self) -> TreyMesh {
let mut aabb=Aabb::new(); let mut aabb=Aabb::new();
for vertex in Aabb::unit_vertices(){ for vertex in Aabb::unit_vertices(){
aabb.grow(self.body.position+self.style.hitbox_halfsize*vertex); aabb.grow(self.body.position+self.hitbox_halfsize*vertex);
} }
aabb aabb
} }
@@ -1109,19 +883,12 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
//JUST POLLING!!! NO MUTATION //JUST POLLING!!! NO MUTATION
let mut collector = crate::instruction::InstructionCollector::new(time_limit); let mut collector = crate::instruction::InstructionCollector::new(time_limit);
//check for collision stop instructions with curent contacts //check for collision stop instructions with curent contacts
for (_,collision_data) in &self.contacts { for collision_data in self.contacts.iter() {
collector.collect(self.predict_collision_end(self.time,time_limit,collision_data)); collector.collect(self.predict_collision_end(self.time,time_limit,collision_data));
} }
// for collision_data in &self.intersects{
// collector.collect(self.predict_collision_end2(self.time,time_limit,collision_data));
// }
//check for collision start instructions (against every part in the game with no optimization!!) //check for collision start instructions (against every part in the game with no optimization!!)
for i in 0..self.models.len() { for i in 0..self.models.len() {
let i=i as u32; collector.collect(self.predict_collision_start(self.time,time_limit,i as u32));
if self.contacts.contains_key(&i)||self.intersects.contains_key(&i){
continue;
}
collector.collect(self.predict_collision_start(self.time,time_limit,i));
} }
if self.grounded { if self.grounded {
//walk maintenance //walk maintenance
@@ -1137,116 +904,63 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState { impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) { fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
match &ins.instruction { match &ins.instruction {
PhysicsInstruction::Input(InputInstruction::Idle) PhysicsInstruction::StrafeTick => (),
|PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),
|PhysicsInstruction::StrafeTick => (), _=>println!("{:?}",ins),
_=>println!("{:?}",ins),
} }
//selectively update body //selectively update body
match &ins.instruction { match &ins.instruction {
//PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::Input(_) PhysicsInstruction::Input(_)
|PhysicsInstruction::ReachWalkTargetVelocity |PhysicsInstruction::SetSpawnPosition(_)
|PhysicsInstruction::CollisionStart(_) |PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionEnd(_) |PhysicsInstruction::CollisionStart(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time), |PhysicsInstruction::CollisionEnd(_)
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
} }
match ins.instruction { match ins.instruction {
PhysicsInstruction::SetSpawnPosition(position)=>{
self.spawn_point=position;
}
PhysicsInstruction::CollisionStart(c) => { PhysicsInstruction::CollisionStart(c) => {
let model=c.model(&self.models).unwrap(); //check ground
match &model.attributes{ match &c.face {
PhysicsCollisionAttributes::Contact{contacting,general}=>{ AabbFace::Top => {
match &contacting.surf{ //ground
Some(surf)=>println!("I'm surfing!"), self.grounded=true;
None=>match &c.face { },
AabbFace::Top => { _ => (),
//ground }
self.grounded=true; self.contacts.insert(c);
}, //flatten v
_ => (), let mut v=self.body.velocity;
}, self.contact_constrain_velocity(&mut v);
} self.body.velocity=v;
//check ground if self.grounded&&self.controls&CONTROL_JUMP!=0{
self.contacts.insert(c.model,c); self.jump();
match &general.stage_element{
Some(stage_element)=>{
if stage_element.force||self.game.stage_id<stage_element.stage_id{
self.game.stage_id=stage_element.stage_id;
}
match stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>(),
crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{
//TODO make good
if let Some(mode)=self.get_mode(stage_element.mode_id){
if let Some(&spawn)=mode.get_spawn_model_id(self.game.stage_id){
if let Some(model)=self.models.get(spawn as usize){
self.body.position=model.transform.transform_point3(glam::Vec3::Y)+glam::Vec3::Y*(self.style.hitbox_halfsize.y+0.1);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear();
self.intersects.clear();
self.body.acceleration=self.style.gravity;
self.walk.state=WalkEnum::Reached;
self.grounded=false;
}else{println!("bad1");}
}else{println!("bad2");}
}else{println!("bad3");}
},
crate::model::StageElementBehaviour::Platform=>(),
}
},
None=>(),
}
//flatten v
let mut v=self.body.velocity;
self.contact_constrain_velocity(&mut v);
match &general.booster{
Some(booster)=>{
v+=booster.velocity;
self.contact_constrain_velocity(&mut v);
},
None=>(),
}
self.body.velocity=v;
if self.grounded&&self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
self.jump();
}
self.refresh_walk_target();
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
self.intersects.insert(c.model,c);
},
} }
self.refresh_walk_target();
}, },
PhysicsInstruction::CollisionEnd(c) => { PhysicsInstruction::CollisionEnd(c) => {
let model=c.model(&self.models).unwrap(); self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration
match &model.attributes{ let mut a=self.gravity;
PhysicsCollisionAttributes::Contact{contacting,general}=>{ self.contact_constrain_acceleration(&mut a);
self.contacts.remove(&c.model);//remove contact before calling contact_constrain_acceleration self.body.acceleration=a;
let mut a=self.style.gravity; //check ground
self.contact_constrain_acceleration(&mut a); match &c.face {
self.body.acceleration=a; AabbFace::Top => {
//check ground self.grounded=false;
match &c.face { },
AabbFace::Top => { _ => (),
self.grounded=false; }
}, self.refresh_walk_target();
_ => (),
}
self.refresh_walk_target();
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
self.intersects.remove(&c.model);
},
}
}, },
PhysicsInstruction::StrafeTick => { PhysicsInstruction::StrafeTick => {
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x); let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
let control_dir=camera_mat*self.style.get_control_dir(self.controls); let control_dir=camera_mat*get_control_dir(self.controls);
let d=self.body.velocity.dot(control_dir); let d=self.body.velocity.dot(control_dir);
if d<self.style.mv { if d<self.mv {
let mut v=self.body.velocity+(self.style.mv-d)*control_dir; let mut v=self.body.velocity+(self.mv-d)*control_dir;
self.contact_constrain_velocity(&mut v); self.contact_constrain_velocity(&mut v);
self.body.velocity=v; self.body.velocity=v;
} }
@@ -1262,51 +976,64 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
}, },
PhysicsInstruction::Input(input_instruction) => { PhysicsInstruction::Input(input_instruction) => {
let mut refresh_walk_target=true; let mut refresh_walk_target=false;
let mut refresh_walk_target_velocity=true;
match input_instruction{ match input_instruction{
InputInstruction::MoveMouse(m) => { InputInstruction::MoveMouse(m) => {
self.camera.angles=self.camera.simulate_move_angles(self.next_mouse.pos); self.camera.angles=self.camera.simulate_move_angles(self.mouse_interpolation.mouse1-self.mouse_interpolation.mouse0);
self.camera.mouse.move_mouse(self.next_mouse.pos,self.next_mouse.time); self.mouse_interpolation.move_mouse(self.time,m);
self.next_mouse.move_mouse(m,self.time); refresh_walk_target=true;
},
InputInstruction::MoveForward(s) => {
self.set_control(CONTROL_MOVEFORWARD,s);
refresh_walk_target=true;
},
InputInstruction::MoveLeft(s) => {
self.set_control(CONTROL_MOVELEFT,s);
refresh_walk_target=true;
},
InputInstruction::MoveBack(s) => {
self.set_control(CONTROL_MOVEBACK,s);
refresh_walk_target=true;
},
InputInstruction::MoveRight(s) => {
self.set_control(CONTROL_MOVERIGHT,s);
refresh_walk_target=true;
},
InputInstruction::MoveUp(s) => {
self.set_control(CONTROL_MOVEUP,s);
refresh_walk_target=true;
},
InputInstruction::MoveDown(s) => {
self.set_control(CONTROL_MOVEDOWN,s);
refresh_walk_target=true;
}, },
InputInstruction::MoveForward(s) => self.set_control(StyleModifiers::CONTROL_MOVEFORWARD,s),
InputInstruction::MoveLeft(s) => self.set_control(StyleModifiers::CONTROL_MOVELEFT,s),
InputInstruction::MoveBack(s) => self.set_control(StyleModifiers::CONTROL_MOVEBACK,s),
InputInstruction::MoveRight(s) => self.set_control(StyleModifiers::CONTROL_MOVERIGHT,s),
InputInstruction::MoveUp(s) => self.set_control(StyleModifiers::CONTROL_MOVEUP,s),
InputInstruction::MoveDown(s) => self.set_control(StyleModifiers::CONTROL_MOVEDOWN,s),
InputInstruction::Jump(s) => { InputInstruction::Jump(s) => {
self.set_control(StyleModifiers::CONTROL_JUMP,s); self.set_control(CONTROL_JUMP,s);
refresh_walk_target=true;
if self.grounded{ if self.grounded{
self.jump(); self.jump();
} }
refresh_walk_target_velocity=false;
}, },
InputInstruction::Zoom(s) => { InputInstruction::Zoom(s) => {
self.set_control(StyleModifiers::CONTROL_ZOOM,s); self.set_control(CONTROL_ZOOM,s);
refresh_walk_target=false;
}, },
InputInstruction::Reset => { InputInstruction::Reset => {
//temp //temp
self.body.position=self.spawn_point; self.body.position=self.spawn_point;
self.body.velocity=glam::Vec3::ZERO;
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))} //manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.contacts.clear(); self.contacts.clear();
self.body.acceleration=self.style.gravity; self.body.acceleration=self.gravity;
self.walk.state=WalkEnum::Reached; self.walk.state=WalkEnum::Reached;
self.grounded=false; self.grounded=false;
refresh_walk_target=false;
}, },
InputInstruction::Idle => {refresh_walk_target=false;},//literally idle! InputInstruction::Idle => (),//literally idle!
} }
//calculate control dir
let camera_mat=self.camera.simulate_move_rotation_y(self.mouse_interpolation.interpolated_position(self.time).x-self.mouse_interpolation.mouse0.x);
let control_dir=camera_mat*get_control_dir(self.controls);
//calculate walk target velocity
if refresh_walk_target{ if refresh_walk_target{
//calculate walk target velocity self.walk.target_velocity=self.walkspeed*control_dir;
if refresh_walk_target_velocity{
let camera_mat=self.camera.simulate_move_rotation_y(self.camera.mouse.lerp(&self.next_mouse,self.time).x);
let control_dir=camera_mat*self.style.get_control_dir(self.controls);
self.walk.target_velocity=self.style.walkspeed*control_dir;
}
self.refresh_walk_target(); self.refresh_walk_target();
} }
}, },

View File

@@ -51,9 +51,8 @@ pub trait Example: 'static + Sized {
device: &wgpu::Device, device: &wgpu::Device,
queue: &wgpu::Queue, queue: &wgpu::Queue,
); );
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent); fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
fn device_event(&mut self, window: &winit::window::Window, event: DeviceEvent); fn device_event(&mut self, event: DeviceEvent);
fn load_file(&mut self, path:std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue);
fn render( fn render(
&mut self, &mut self,
view: &wgpu::TextureView, view: &wgpu::TextureView,
@@ -368,14 +367,14 @@ fn start<E: Example>(
println!("{:#?}", instance.generate_report()); println!("{:#?}", instance.generate_report());
} }
_ => { _ => {
example.update(&window,&device,&queue,event); example.update(&device,&queue,event);
} }
}, },
event::Event::DeviceEvent { event::Event::DeviceEvent {
event, event,
.. ..
} => { } => {
example.device_event(&window,event); example.device_event(event);
}, },
event::Event::RedrawRequested(_) => { event::Event::RedrawRequested(_) => {

View File

@@ -1,11 +1,11 @@
#[derive(Debug)] #[derive(Debug)]
pub struct TimedInstruction<I> { pub struct TimedInstruction<I> {
pub time: crate::physics::TIME, pub time: crate::body::TIME,
pub instruction: I, pub instruction: I,
} }
pub trait InstructionEmitter<I> { pub trait InstructionEmitter<I> {
fn next_instruction(&self, time_limit:crate::physics::TIME) -> Option<TimedInstruction<I>>; fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<I>>;
} }
pub trait InstructionConsumer<I> { pub trait InstructionConsumer<I> {
fn process_instruction(&mut self, instruction:TimedInstruction<I>); fn process_instruction(&mut self, instruction:TimedInstruction<I>);
@@ -13,11 +13,11 @@ pub trait InstructionConsumer<I> {
//PROPER PRIVATE FIELDS!!! //PROPER PRIVATE FIELDS!!!
pub struct InstructionCollector<I> { pub struct InstructionCollector<I> {
time: crate::physics::TIME, time: crate::body::TIME,
instruction: Option<I>, instruction: Option<I>,
} }
impl<I> InstructionCollector<I> { impl<I> InstructionCollector<I> {
pub fn new(time:crate::physics::TIME) -> Self { pub fn new(time:crate::body::TIME) -> Self {
Self{ Self{
time, time,
instruction:None instruction:None

View File

@@ -1,3 +1,5 @@
use crate::model::{IndexedModelInstances,ModelInstance};
use crate::primitives; use crate::primitives;
fn class_is_a(class: &str, superclass: &str) -> bool { fn class_is_a(class: &str, superclass: &str) -> bool {
@@ -30,89 +32,13 @@ fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>
//next class //next class
objects objects
} }
fn get_attributes(name:&str,can_collide:bool,velocity:glam::Vec3,force_intersecting:bool)->crate::model::CollisionAttributes{
let mut general=crate::model::GameMechanicAttributes::default();
let mut intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default();
match name{
//"Water"=>intersecting.water=Some(crate::model::IntersectingWater{density:1.0,drag:1.0}),
"Accelerator"=>intersecting.accelerator=Some(crate::model::IntersectingAccelerator{acceleration:velocity}),
"MapFinish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish}),
"MapAnticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat}),
"Platform"=>general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0,
stage_id:0,
force:false,
behaviour:crate::model::StageElementBehaviour::Platform,
}),
other=>{
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Spawn|SpawnAt|Trigger|Teleport|Platform)(\d+)$")
.captures(other){
general.stage_element=Some(crate::model::GameMechanicStageElement{
mode_id:0,
stage_id:captures[3].parse::<u32>().unwrap(),
force:match captures.get(1){
Some(m)=>m.as_str()=="Force",
None=>false,
},
behaviour:match &captures[2]{
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
"Trigger"=>crate::model::StageElementBehaviour::Trigger,
"Teleport"=>crate::model::StageElementBehaviour::Teleport,
"Platform"=>crate::model::StageElementBehaviour::Platform,
_=>panic!("regex1[2] messed up bad"),
}
})
}else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$")
.captures(other){
match &captures[1]{
"Finish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Finish}),
"Anticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Anitcheat}),
_=>panic!("regex2[1] messed up bad"),
}
}
}
}
//need some way to skip this
if velocity!=glam::Vec3::ZERO{
general.booster=Some(crate::model::GameMechanicBooster{velocity});
}
match can_collide{
true=>{
match name{
//"Bounce"=>(),
"Surf"=>contacting.surf=Some(crate::model::ContactingSurf{}),
"Ladder"=>contacting.ladder=Some(crate::model::ContactingLadder{sticky:true}),
other=>{
//REGEX!!!!
//Jump#
//WormholeIn#
}
}
crate::model::CollisionAttributes::Contact{contacting,general}
},
false=>if force_intersecting
||general.jump_limit.is_some()
||general.booster.is_some()
||general.zone.is_some()
||general.stage_element.is_some()
||general.wormhole.is_some()
||intersecting.water.is_some()
||intersecting.accelerator.is_some()
{
crate::model::CollisionAttributes::Intersect{intersecting,general}
}else{
crate::model::CollisionAttributes::Decoration
},
}
}
struct RobloxAssetId(u64); struct RobloxAssetId(u64);
struct RobloxAssetIdParseErr; struct RobloxAssetIdParseErr;
impl std::str::FromStr for RobloxAssetId { impl std::str::FromStr for RobloxAssetId {
type Err=RobloxAssetIdParseErr; type Err=RobloxAssetIdParseErr;
fn from_str(s: &str) -> Result<Self, Self::Err>{ fn from_str(s: &str) -> Result<Self, Self::Err>{
let regman=lazy_regex::regex!(r"(\d+)$"); let regman=regex::Regex::new(r"(\d+)$").unwrap();
if let Some(captures) = regman.captures(s) { if let Some(captures) = regman.captures(s) {
if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture
if let Ok(id) = captures[0].parse::<u64>() { if let Ok(id) = captures[0].parse::<u64>() {
@@ -185,7 +111,7 @@ enum RobloxBasePartDescription{
Wedge(RobloxWedgeDescription), Wedge(RobloxWedgeDescription),
CornerWedge(RobloxCornerWedgeDescription), CornerWedge(RobloxCornerWedgeDescription),
} }
pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::IndexedModelInstances{ pub fn generate_indexed_models_roblox(dom:rbx_dom_weak::WeakDom) -> Result<(IndexedModelInstances,glam::Vec3), Box<dyn std::error::Error>>{
//IndexedModelInstances includes textures //IndexedModelInstances includes textures
let mut spawn_point=glam::Vec3::ZERO; let mut spawn_point=glam::Vec3::ZERO;
@@ -203,17 +129,13 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
if let ( if let (
Some(rbx_dom_weak::types::Variant::CFrame(cf)), Some(rbx_dom_weak::types::Variant::CFrame(cf)),
Some(rbx_dom_weak::types::Variant::Vector3(size)), Some(rbx_dom_weak::types::Variant::Vector3(size)),
Some(rbx_dom_weak::types::Variant::Vector3(velocity)),
Some(rbx_dom_weak::types::Variant::Float32(transparency)), Some(rbx_dom_weak::types::Variant::Float32(transparency)),
Some(rbx_dom_weak::types::Variant::Color3uint8(color3)), Some(rbx_dom_weak::types::Variant::Color3uint8(color3)),
Some(rbx_dom_weak::types::Variant::Bool(can_collide)),
) = ( ) = (
object.properties.get("CFrame"), object.properties.get("CFrame"),
object.properties.get("Size"), object.properties.get("Size"),
object.properties.get("Velocity"),
object.properties.get("Transparency"), object.properties.get("Transparency"),
object.properties.get("Color"), object.properties.get("Color"),
object.properties.get("CanCollide"),
) )
{ {
let model_transform=glam::Affine3A::from_translation( let model_transform=glam::Affine3A::from_translation(
@@ -229,35 +151,14 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
* glam::Affine3A::from_scale( * glam::Affine3A::from_scale(
glam::Vec3::new(size.x,size.y,size.z)/2.0 glam::Vec3::new(size.x,size.y,size.z)/2.0
); );
if object.name=="MapStart"{
//push TempIndexedAttributes spawn_point=model_transform.transform_point3(glam::Vec3::Y)+glam::vec3(0.0,2.5,0.0);
let mut force_intersecting=false; println!("Found MapStart{:?}",spawn_point);
let mut temp_indexing_attributes=Vec::new(); }
if let Some(attr)=match &object.name[..]{ if *transparency==1.0 {
"MapStart"=>{ continue;
spawn_point=model_transform.transform_point3(glam::Vec3::ZERO)+glam::vec3(0.0,2.5,0.0);
Some(crate::model::TempIndexedAttributes::Start{mode_id:0})
},
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
other=>{
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
if let Some(captures) = regman.captures(other) {
match &captures[1]{
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start{mode_id:captures[2].parse::<u32>().unwrap()}),
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()}),
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
_=>None,
}
}else{
None
}
}
}{
force_intersecting=true;
temp_indexing_attributes.push(attr);
} }
//TODO: also detect "CylinderMesh" etc here
let shape=match &object.class[..]{ let shape=match &object.class[..]{
"Part"=>{ "Part"=>{
if let Some(rbx_dom_weak::types::Variant::Enum(shape))=object.properties.get("Shape"){ if let Some(rbx_dom_weak::types::Variant::Enum(shape))=object.properties.get("Shape"){
@@ -267,10 +168,14 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
2=>primitives::Primitives::Cylinder, 2=>primitives::Primitives::Cylinder,
3=>primitives::Primitives::Wedge, 3=>primitives::Primitives::Wedge,
4=>primitives::Primitives::CornerWedge, 4=>primitives::Primitives::CornerWedge,
_=>panic!("Funky roblox PartType={};",shape.to_u32()), _=>{
println!("Funky roblox PartType={}; defaulting to cube",shape.to_u32());
primitives::Primitives::Cube
},
} }
}else{ }else{
panic!("Part has no Shape!"); println!("Part has no Shape! defaulting to cube");
primitives::Primitives::Cube
} }
}, },
"WedgePart"=>primitives::Primitives::Wedge, "WedgePart"=>primitives::Primitives::Wedge,
@@ -281,6 +186,38 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
} }
}; };
//TODO: also detect "CylinderMesh" etc here
let mut face_map=std::collections::HashMap::new();
match shape{
primitives::Primitives::Cube => {
face_map.insert(0,0);//Right
face_map.insert(1,1);//Top
face_map.insert(2,2);//Back
face_map.insert(3,3);//Left
face_map.insert(4,4);//Bottom
face_map.insert(5,5);//Front
},
primitives::Primitives::Wedge => {
face_map.insert(0,0);//Right
face_map.insert(1,1);//Top -> TopFront (some surf maps put surf textures on the Top face)
face_map.insert(2,1);//Front -> TopFront
face_map.insert(3,2);//Back
face_map.insert(4,3);//Left
face_map.insert(5,4);//Bottom
},
primitives::Primitives::CornerWedge => {
//Right -> None
face_map.insert(1,0);//Top
//Back -> None
face_map.insert(3,1);//Right
face_map.insert(4,2);//Bottom
face_map.insert(5,3);//Front
},
//do not support textured spheres/cylinders imported from roblox
//this can be added later, there are some maps that use it
primitives::Primitives::Sphere
|primitives::Primitives::Cylinder => (),
}
//use the biggest one and cut it down later... //use the biggest one and cut it down later...
let mut part_texture_description:RobloxPartDescription=[None,None,None,None,None,None]; let mut part_texture_description:RobloxPartDescription=[None,None,None,None,None,None];
temp_objects.clear(); temp_objects.clear();
@@ -308,7 +245,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
texture_id texture_id
}; };
let normal_id=normalid.to_u32(); let normal_id=normalid.to_u32();
if normal_id<6{ if let Some(&face)=face_map.get(&normal_id){
let mut roblox_texture_transform=RobloxTextureTransform::default(); let mut roblox_texture_transform=RobloxTextureTransform::default();
let mut roblox_texture_color=glam::Vec4::ONE; let mut roblox_texture_color=glam::Vec4::ONE;
if decal.class=="Texture"{ if decal.class=="Texture"{
@@ -332,7 +269,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
3=>(size.z,size.y),//left 3=>(size.z,size.y),//left
4=>(size.x,size.z),//bottom 4=>(size.x,size.z),//bottom
5=>(size.x,size.y),//front 5=>(size.x,size.y),//front
_=>panic!("unreachable"), _=>(1.,1.),
}; };
roblox_texture_transform=RobloxTextureTransform{ roblox_texture_transform=RobloxTextureTransform{
offset_u:*ox/(*sx),offset_v:*oy/(*sy), offset_u:*ox/(*sx),offset_v:*oy/(*sy),
@@ -341,7 +278,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
roblox_texture_color=glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency); roblox_texture_color=glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency);
} }
} }
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{ part_texture_description[face]=Some(RobloxFaceTextureDescription{
texture:texture_id, texture:texture_id,
color:roblox_texture_color, color:roblox_texture_color,
transform:roblox_texture_transform, transform:roblox_texture_transform,
@@ -354,34 +291,16 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
} }
} }
//obscure rust syntax "slice pattern" //obscure rust syntax "slice pattern"
let [ let [f0,f1,f2,f3,f4,f5]=part_texture_description;
f0,//Cube::Right
f1,//Cube::Top
f2,//Cube::Back
f3,//Cube::Left
f4,//Cube::Bottom
f5,//Cube::Front
]=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,
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,
//use front face texture first and use top face texture as a fallback //HAHAHA
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([ primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([f0,f1,f2,f3,f4]),
f0,//Cube::Right->Wedge::Right primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([f0,f1,f2,f3]),
if f5.is_some(){f5}else{f1},//Cube::Front|Cube::Top->Wedge::TopFront
f2,//Cube::Back->Wedge::Back
f3,//Cube::Left->Wedge::Left
f4,//Cube::Bottom->Wedge::Bottom
]),
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
f0,//Cube::Right->CornerWedge::Right
f1,//Cube::Top->CornerWedge::Top
f4,//Cube::Bottom->CornerWedge::Bottom
f5,//Cube::Front->CornerWedge::Front
]),
}; };
//make new model if unit cube has not been created before //make new model if unit cube has not been crated before
let model_id=if let Some(&model_id)=model_id_from_description.get(&basepart_texture_description){ let model_id=if let Some(&model_id)=model_id_from_description.get(&basepart_texture_description){
//push to existing texture model //push to existing texture model
model_id model_id
@@ -451,19 +370,15 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
}); });
model_id model_id
}; };
indexed_models[model_id].instances.push(crate::model::ModelInstance { indexed_models[model_id].instances.push(ModelInstance {
transform:model_transform, transform:model_transform,
color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency), color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
attributes:get_attributes(&object.name,*can_collide,glam::vec3(velocity.x,velocity.y,velocity.z),force_intersecting),
temp_indexing:temp_indexing_attributes,
}); });
} }
} }
} }
crate::model::IndexedModelInstances{ Ok((IndexedModelInstances{
textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(), textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),
models:indexed_models, models:indexed_models,
spawn_point, },spawn_point))
modes:Vec::new(),
}
} }

View File

@@ -1,15 +1,12 @@
use std::{borrow::Cow, time::Instant}; use std::{borrow::Cow, time::Instant};
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel}; use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
use model::{Vertex,ModelInstance,ModelGraphicsInstance}; use model::{Vertex,ModelInstance,ModelGraphicsInstance};
use physics::{InputInstruction, PhysicsInstruction}; use body::{InputInstruction, PhysicsInstruction};
use instruction::TimedInstruction; use instruction::{TimedInstruction, InstructionConsumer};
use crate::instruction::InstructionConsumer;
mod body;
mod model; mod model;
mod zeroes; mod zeroes;
mod worker;
mod physics;
mod framework; mod framework;
mod primitives; mod primitives;
mod instruction; mod instruction;
@@ -41,90 +38,27 @@ pub struct GraphicsBindGroups {
skybox_texture: wgpu::BindGroup, skybox_texture: wgpu::BindGroup,
} }
pub struct GraphicsPipelines{ pub struct GraphicsPipelines {
skybox: wgpu::RenderPipeline, skybox: wgpu::RenderPipeline,
model: wgpu::RenderPipeline, model: wgpu::RenderPipeline,
} }
pub struct GraphicsCamera{ pub struct GraphicsData {
screen_size: glam::UVec2, start_time: std::time::Instant,
fov: glam::Vec2,//slope screen_size: (u32, u32),
//camera angles and such are extrapolated and passed in every time physics: body::PhysicsState,
}
#[inline]
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
//glam_assert!(z_near > 0.0 && z_far > 0.0);
let r = z_far / (z_near - z_far);
glam::Mat4::from_cols(
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, r, -1.0),
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
)
}
impl GraphicsCamera{
pub fn new(screen_size:glam::UVec2,fov_y:f32)->Self{
Self{
screen_size,
fov: glam::vec2(fov_y*(screen_size.x as f32)/(screen_size.y as f32),fov_y),
}
}
pub fn proj(&self)->glam::Mat4{
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
}
pub fn view(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
//f32 good enough for view matrix
glam::Mat4::from_translation(pos) * glam::Mat4::from_euler(glam::EulerRot::YXZ, angles.x, angles.y, 0f32)
}
pub fn set_screen_size(&mut self,screen_size:glam::UVec2){
self.screen_size=screen_size;
self.fov.x=self.fov.y*(screen_size.x as f32)/(screen_size.y as f32);
}
pub fn to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 3 + 4] {
let proj=self.proj();
let proj_inv = proj.inverse();
let view=self.view(pos,angles);
let view_inv = view.inverse();
let mut raw = [0f32; 16 * 3 + 4];
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
raw
}
}
pub struct GraphicsState{
pipelines: GraphicsPipelines, pipelines: GraphicsPipelines,
bind_groups: GraphicsBindGroups, bind_groups: GraphicsBindGroups,
bind_group_layouts: GraphicsBindGroupLayouts, bind_group_layouts: GraphicsBindGroupLayouts,
samplers: GraphicsSamplers, samplers: GraphicsSamplers,
camera:GraphicsCamera,
camera_buf: wgpu::Buffer,
temp_squid_texture_view: wgpu::TextureView, temp_squid_texture_view: wgpu::TextureView,
camera_buf: wgpu::Buffer,
models: Vec<ModelGraphics>, models: Vec<ModelGraphics>,
depth_view: wgpu::TextureView, depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt, staging_belt: wgpu::util::StagingBelt,
} }
impl GraphicsState{ impl GraphicsData {
pub fn clear(&mut self){
self.models.clear();
}
}
pub struct GlobalState{
start_time: std::time::Instant,
manual_mouse_lock:bool,
mouse:physics::MouseState,
graphics:GraphicsState,
physics_thread:worker::Worker<TimedInstruction<InputInstruction>,physics::PhysicsOutputState>,
}
impl GlobalState{
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus; const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
fn create_depth_texture( fn create_depth_texture(
@@ -149,24 +83,32 @@ impl GlobalState{
depth_texture.create_view(&wgpu::TextureViewDescriptor::default()) depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
} }
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:model::IndexedModelInstances){ fn generate_model_physics(&mut self,indexed_models:&model::IndexedModelInstances){
for model in &indexed_models.models{
//make aabb and run vertices to get realistic bounds
for model_instance in &model.instances{
self.physics.models.push(body::ModelPhysics::from_model(&model,model_instance.transform));
}
}
println!("Physics Objects: {}",self.physics.models.len());
}
fn generate_model_graphics(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,mut indexed_models: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
let mut double_map=std::collections::HashMap::<u32,u32>::new(); let mut double_map=std::collections::HashMap::<u32,u32>::new();
let mut texture_loading_threads=Vec::new(); let mut texture_loading_threads=Vec::new();
let num_textures=indexed_models.textures.len(); for (i,t) in indexed_models.textures.iter().enumerate(){
for (i,texture_id) in indexed_models.textures.into_iter().enumerate(){ if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",t))){
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",texture_id))){
double_map.insert(i as u32, texture_loading_threads.len() as u32); double_map.insert(i as u32, texture_loading_threads.len() as u32);
texture_loading_threads.push((texture_id,std::thread::spawn(move ||{ texture_loading_threads.push(std::thread::spawn(move ||{
ddsfile::Dds::read(&mut file).unwrap() (i,ddsfile::Dds::read(&mut file).unwrap())
}))); }));
} }
} }
let texture_views:Vec<wgpu::TextureView>=texture_loading_threads.into_iter().map(|(texture_id,thread)|{ let texture_views:Vec<wgpu::TextureView>=texture_loading_threads.into_iter().map(|t|{
let image=thread.join().unwrap(); let (i,image)=t.join().unwrap();
let (mut width,mut height)=(image.get_width(),image.get_height()); let (mut width,mut height)=(image.get_width(),image.get_height());
@@ -202,39 +144,35 @@ impl GlobalState{
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
format, format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some(format!("Texture{}",texture_id).as_str()), label: Some(format!("Texture{}",i).as_str()),
view_formats: &[], view_formats: &[],
}, },
&image.data, &image.data,
); );
texture.create_view(&wgpu::TextureViewDescriptor { texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(format!("Texture{} View",texture_id).as_str()), label: Some(format!("Texture{} View",i).as_str()),
dimension: Some(wgpu::TextureViewDimension::D2), dimension: Some(wgpu::TextureViewDimension::D2),
..wgpu::TextureViewDescriptor::default() ..wgpu::TextureViewDescriptor::default()
}) })
}).collect(); }).collect();
let indexed_models_len=indexed_models.models.len();
//split groups with different textures into separate models //split groups with different textures into separate models
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups. //the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
let indexed_models_len=indexed_models.models.len(); let mut unique_texture_models=Vec::with_capacity(indexed_models.models.len());
let mut unique_texture_models=Vec::with_capacity(indexed_models_len); for mut model in indexed_models.models.drain(..){
for model in indexed_models.models.into_iter(){
//convert ModelInstance into ModelGraphicsInstance //convert ModelInstance into ModelGraphicsInstance
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{ let instances:Vec<ModelGraphicsInstance>=model.instances.iter().map(|instance|{
if instance.color.w==0.0{ ModelGraphicsInstance{
None transform: glam::Mat4::from(instance.transform),
}else{ normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
Some(ModelGraphicsInstance{ color: instance.color,
transform: glam::Mat4::from(instance.transform),
normal_transform: glam::Mat4::from(instance.transform.inverse()).transpose(),
color: instance.color,
})
} }
}).collect(); }).collect();
//check each group, if it's using a new texture then make a new clone of the model //check each group, if it's using a new texture then make a new clone of the model
let id=unique_texture_models.len(); let id=unique_texture_models.len();
let mut unique_textures=Vec::new(); let mut unique_textures=Vec::new();
for group in model.groups.into_iter(){ for group in model.groups.drain(..){
//ignore zero coppy optimization for now //ignore zero coppy optimization for now
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){ let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
texture_index texture_index
@@ -261,7 +199,7 @@ impl GlobalState{
} }
//de-index models //de-index models
let mut models=Vec::with_capacity(unique_texture_models.len()); let mut models=Vec::with_capacity(unique_texture_models.len());
for model in unique_texture_models.into_iter(){ for model in unique_texture_models.drain(..){
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(); let mut entities = Vec::new();
@@ -298,13 +236,13 @@ impl GlobalState{
texture:model.texture, texture:model.texture,
}); });
} }
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities //drain 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=<GlobalState as framework::Example>::required_limits().max_uniform_buffer_binding_size as usize; let uniform_buffer_binding_size=<GraphicsData as framework::Example>::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.graphics.models.reserve(models.len()); self.models.reserve(models.len());
for model in models.into_iter() { for model in models.drain(..) {
instance_count+=model.instances.len(); instance_count+=model.instances.len();
for instances_chunk in model.instances.rchunks(chunk_size){ for instances_chunk in model.instances.rchunks(chunk_size){
model_count+=1; model_count+=1;
@@ -318,13 +256,13 @@ impl GlobalState{
Some(texture_id)=>{ Some(texture_id)=>{
match double_map.get(&texture_id){ match double_map.get(&texture_id){
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize], Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
None=>&self.graphics.temp_squid_texture_view, None=>&self.temp_squid_texture_view,
} }
}, },
None=>&self.graphics.temp_squid_texture_view, None=>&self.temp_squid_texture_view,
}; };
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.graphics.bind_group_layouts.model, layout: &self.bind_group_layouts.model,
entries: &[ entries: &[
wgpu::BindGroupEntry { wgpu::BindGroupEntry {
binding: 0, binding: 0,
@@ -336,7 +274,7 @@ impl GlobalState{
}, },
wgpu::BindGroupEntry { wgpu::BindGroupEntry {
binding: 2, binding: 2,
resource: wgpu::BindingResource::Sampler(&self.graphics.samplers.repeat), resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
}, },
], ],
label: Some(format!("Model{} Bind Group",model_count).as_str()), label: Some(format!("Model{} Bind Group",model_count).as_str()),
@@ -347,7 +285,7 @@ impl GlobalState{
usage: wgpu::BufferUsages::VERTEX, usage: wgpu::BufferUsages::VERTEX,
}); });
//all of these are being moved here //all of these are being moved here
self.graphics.models.push(ModelGraphics{ self.models.push(ModelGraphics{
instances:instances_chunk.to_vec(), instances:instances_chunk.to_vec(),
vertex_buf, vertex_buf,
entities: model.entities.iter().map(|indices|{ entities: model.entities.iter().map(|indices|{
@@ -366,10 +304,10 @@ impl GlobalState{
}); });
} }
} }
println!("Texture References={}",num_textures); println!("Texture References={}",indexed_models.textures.len());
println!("Textures Loaded={}",texture_views.len()); println!("Textures Loaded={}",texture_views.len());
println!("Indexed Models={}",indexed_models_len); println!("Indexed Models={}",indexed_models_len);
println!("Graphics Objects: {}",self.graphics.models.len()); println!("Graphics Objects: {}",self.models.len());
println!("Graphics Instances: {}",instance_count); println!("Graphics Instances: {}",instance_count);
} }
} }
@@ -391,7 +329,21 @@ fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
raw raw
} }
impl framework::Example for GlobalState { fn to_uniform_data(camera: &body::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
let proj=camera.proj();
let proj_inv = proj.inverse();
let view=camera.view(pos);
let view_inv = view.inverse();
let mut raw = [0f32; 16 * 3 + 4];
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
raw
}
impl framework::Example for GraphicsData {
fn optional_features() -> wgpu::Features { fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2 | wgpu::Features::TEXTURE_COMPRESSION_ETC2
@@ -416,44 +368,34 @@ impl framework::Example for GlobalState {
println!("models.len = {:?}", indexed_models.len()); println!("models.len = {:?}", indexed_models.len());
indexed_models[0].instances.push(ModelInstance{ indexed_models[0].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)), transform:glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.)),
..Default::default() color:glam::Vec4::ONE,
}); });
//quad monkeys //quad monkeys
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)), transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,10.)),
..Default::default() color:glam::Vec4::ONE,
}); });
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)), transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,10.)),
color:glam::vec4(1.0,0.0,0.0,1.0), color:glam::vec4(1.0,0.0,0.0,1.0),
..Default::default()
}); });
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)), transform:glam::Affine3A::from_translation(glam::vec3(10.,5.,20.)),
color:glam::vec4(0.0,1.0,0.0,1.0), color:glam::vec4(0.0,1.0,0.0,1.0),
..Default::default()
}); });
indexed_models[1].instances.push(ModelInstance{ indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)), transform:glam::Affine3A::from_translation(glam::vec3(20.,5.,20.)),
color:glam::vec4(0.0,0.0,1.0,1.0), color:glam::vec4(0.0,0.0,1.0,1.0),
..Default::default()
});
//decorative monkey
indexed_models[1].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(15.,10.,15.)),
color:glam::vec4(0.5,0.5,0.5,0.5),
attributes:model::CollisionAttributes::Decoration,
..Default::default()
}); });
//teapot //teapot
indexed_models[2].instances.push(ModelInstance{ indexed_models[2].instances.push(ModelInstance{
transform:glam::Affine3A::from_scale_rotation_translation(glam::vec3(0.5, 1.0, 0.2),glam::quat(-0.22248298016985793,-0.839457167990537,-0.05603504040830783,-0.49261857546227916),glam::vec3(-10.,7.,10.)), transform:glam::Affine3A::from_scale_rotation_translation(glam::vec3(0.5, 1.0, 0.2),glam::quat(-0.22248298016985793,-0.839457167990537,-0.05603504040830783,-0.49261857546227916),glam::vec3(-10.,7.,10.)),
..Default::default() color:glam::Vec4::ONE,
}); });
//ground //ground
indexed_models[3].instances.push(ModelInstance{ indexed_models[3].instances.push(ModelInstance{
transform:glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0)), transform:glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0)),
..Default::default() color:glam::Vec4::ONE,
}); });
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -551,6 +493,28 @@ impl framework::Example for GlobalState {
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
}); });
let physics = body::PhysicsState {
spawn_point:glam::vec3(0.0,50.0,0.0),
body: body::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
time: 0,
tick: 0,
strafe_tick_num: 100,//100t
strafe_tick_den: 1_000_000_000,
gravity: glam::vec3(0.0,-100.0,0.0),
friction: 1.2,
walk_accel: 90.0,
mv: 2.7,
grounded: false,
walkspeed: 18.0,
contacts: std::collections::HashSet::new(),
models: Vec::new(),
walk: body::WalkState::new(),
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
camera: body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)),
mouse_interpolation: body::MouseInterpolationState::new(),
controls: 0,
};
//load textures //load textures
let device_features = device.features(); let device_features = device.features();
@@ -745,10 +709,7 @@ impl framework::Example for GlobalState {
multiview: None, multiview: None,
}); });
let mut physics = physics::PhysicsState::default(); let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0));
let camera=GraphicsCamera::new(glam::uvec2(config.width,config.height), 1.0);
let camera_uniforms = camera.to_uniform_data(physics.output().adjust_mouse(&physics.next_mouse));
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { 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),
@@ -764,7 +725,6 @@ impl framework::Example for GlobalState {
], ],
label: Some("Camera"), label: Some("Camera"),
}); });
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &skybox_texture_bind_group_layout, layout: &skybox_texture_bind_group_layout,
entries: &[ entries: &[
@@ -782,7 +742,10 @@ impl framework::Example for GlobalState {
let depth_view = Self::create_depth_texture(config, device); let depth_view = Self::create_depth_texture(config, device);
let graphics=GraphicsState { let mut graphics=GraphicsData {
start_time: Instant::now(),
screen_size: (config.width,config.height),
physics,
pipelines:GraphicsPipelines{ pipelines:GraphicsPipelines{
skybox:sky_pipeline, skybox:sky_pipeline,
model:model_pipeline model:model_pipeline
@@ -791,7 +754,6 @@ impl framework::Example for GlobalState {
camera:camera_bind_group, camera:camera_bind_group,
skybox_texture:skybox_texture_bind_group, skybox_texture:skybox_texture_bind_group,
}, },
camera,
camera_buf, camera_buf,
models: Vec::new(), models: Vec::new(),
depth_view, depth_view,
@@ -804,115 +766,82 @@ impl framework::Example for GlobalState {
let indexed_model_instances=model::IndexedModelInstances{ let indexed_model_instances=model::IndexedModelInstances{
textures:Vec::new(), textures:Vec::new(),
models:indexed_models, models:indexed_models,
spawn_point:glam::Vec3::Y*50.0,
modes:Vec::new(),
}; };
graphics.generate_model_physics(&indexed_model_instances);
graphics.generate_model_graphics(&device,&queue,indexed_model_instances);
//how to multithread return graphics;
//1. build
physics.generate_models(&indexed_model_instances);
//2. move
let physics_thread=physics.into_worker();
//3. forget
let mut state=GlobalState{
start_time:Instant::now(),
manual_mouse_lock:false,
mouse:physics::MouseState::default(),
graphics,
physics_thread,
};
state.generate_model_graphics(&device,&queue,indexed_model_instances);
let args:Vec<String>=std::env::args().collect();
if args.len()==2{
state.load_file(std::path::PathBuf::from(&args[1]), device, queue);
}
return state;
}
fn load_file(&mut self,path: std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue){
println!("Loading file: {:?}", &path);
//oh boy! let's load the map!
if let Ok(file)=std::fs::File::open(path){
let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.snf = "SNMF"
//.snf = "SNBF"
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
//
if let Some(indexed_model_instances)={
match &first_8[0..4]{
b"<rob"=>{
match match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
other=>Err(format!("Unknown Roblox file type {:?}",other)),
}{
Ok(dom)=>Some(load_roblox::generate_indexed_models(dom)),
Err(e)=>{
println!("Error loading roblox file:{:?}",e);
None
},
}
},
//b"VBSP"=>Some(load_bsp::generate_indexed_models(input)),
//b"SNFM"=>Some(sniffer::generate_indexed_models(input)),
//b"SNFB"=>Some(sniffer::load_bot(input)),
other=>{
println!("loser file {:?}",other);
None
},
}
}{
let spawn_point=indexed_model_instances.spawn_point;
//if generate_indexed_models succeeds, clear the previous ones
self.graphics.clear();
let mut physics=physics::PhysicsState::default();
physics.game.stage_id=0;
physics.spawn_point=spawn_point;
physics.process_instruction(instruction::TimedInstruction{
time:physics.time,
instruction: PhysicsInstruction::Input(InputInstruction::Reset),
});
physics.generate_models(&indexed_model_instances);
self.physics_thread=physics.into_worker();
self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset
}else{
println!("No modeldatas were generated");
}
}else{
println!("Failed to read first 8 bytes and seek back to beginning of file.");
}
}else{
println!("Could not open file");
}
} }
#[allow(clippy::single_match)] #[allow(clippy::single_match)]
fn update(&mut self, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) { fn update(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, event: winit::event::WindowEvent) {
//nothing atm
match event { match event {
winit::event::WindowEvent::DroppedFile(path) => self.load_file(path,device,queue), winit::event::WindowEvent::DroppedFile(path) => {
winit::event::WindowEvent::Focused(state)=>{ println!("opening file: {:?}", &path);
//pause unpause //oh boy! let's load the map!
//recalculate pressed keys on focus if let Ok(file)=std::fs::File::open(path){
} let mut input = std::io::BufReader::new(file);
let mut first_8=[0u8;8];
//.rbxm roblox binary = "<roblox!"
//.rbxmx roblox xml = "<roblox "
//.bsp = "VBSP"
//.vmf =
//.snf = "SNMF"
//.snf = "SNBF"
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
//
if let Some(Ok((indexed_model_instances,spawn_point)))={
match &first_8[0..4]{
b"<rob"=>{
match match &first_8[4..8]{
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
other=>Err(format!("Unknown Roblox file type {:?}",other)),
}{
Ok(dom)=>Some(load_roblox::generate_indexed_models_roblox(dom)),
Err(e)=>{
println!("Error loading roblox file:{:?}",e);
None
},
}
},
//b"VBSP"=>load_valve::generate_indexed_models_valve(input),
//b"SNFM"=>sniffer::generate_indexed_models(input),
//b"SNFB"=>sniffer::load_bot(input),
_=>None,
}
}{
//if generate_indexed_models succeeds, clear the previous ones
self.models.clear();
self.physics.models.clear();
self.generate_model_physics(&indexed_model_instances);
self.generate_model_graphics(device,queue,indexed_model_instances);
//manual reset
let time=self.physics.time;
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::SetSpawnPosition(spawn_point),
});
instruction::InstructionConsumer::process_instruction(&mut self.physics, instruction::TimedInstruction{
time,
instruction: body::PhysicsInstruction::Input(body::InputInstruction::Reset),
});
}else{
println!("No modeldatas were generated");
}
}else{
println!("Failed to read first 8 bytes and seek back to beginning of file.");
}
}else{
println!("Could not open file");
}
},
_=>(), _=>(),
} }
} }
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) { fn device_event(&mut self, event: winit::event::DeviceEvent) {
//there's no way this is the best way get a timestamp. //there's no way this is the best way get a timestamp.
let time=self.start_time.elapsed().as_nanos() as i64; let time=self.start_time.elapsed().as_nanos() as i64;
match event { match event {
@@ -926,92 +855,46 @@ impl framework::Example for GlobalState {
winit::event::ElementState::Released => false, winit::event::ElementState::Released => false,
}; };
if let Some(input_instruction)=match keycode { if let Some(input_instruction)=match keycode {
17=>Some(InputInstruction::MoveForward(s)),//W 17 => Some(InputInstruction::MoveForward(s)),//W
30=>Some(InputInstruction::MoveLeft(s)),//A 30 => Some(InputInstruction::MoveLeft(s)),//A
31=>Some(InputInstruction::MoveBack(s)),//S 31 => Some(InputInstruction::MoveBack(s)),//S
32=>Some(InputInstruction::MoveRight(s)),//D 32 => Some(InputInstruction::MoveRight(s)),//D
18=>Some(InputInstruction::MoveUp(s)),//E 18 => Some(InputInstruction::MoveUp(s)),//E
16=>Some(InputInstruction::MoveDown(s)),//Q 16 => Some(InputInstruction::MoveDown(s)),//Q
57=>Some(InputInstruction::Jump(s)),//Space 57 => Some(InputInstruction::Jump(s)),//Space
44=>Some(InputInstruction::Zoom(s)),//Z 44 => Some(InputInstruction::Zoom(s)),//Z
19=>if s{Some(InputInstruction::Reset)}else{None},//R 19 => if s{Some(InputInstruction::Reset)}else{None},//R
01=>{//Esc _ => None,
if s{ }
self.manual_mouse_lock=false; {
match window.set_cursor_grab(winit::window::CursorGrabMode::None){ self.physics.run(time);
Ok(())=>(), self.physics.process_instruction(TimedInstruction{
Err(e)=>println!("Could not release cursor: {:?}",e),
}
window.set_cursor_visible(true);
}
None
},
15=>{//Tab
if s{
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)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
}else{
//if cursor is outside window don't lock but apparently there's no get pos function
//let pos=window.get_cursor_pos();
match window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
Ok(())=>(),
Err(_)=>{
match window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
Ok(())=>(),
Err(e)=>{
self.manual_mouse_lock=true;
println!("Could not confine cursor: {:?}",e)
},
}
}
}
}
window.set_cursor_visible(s);
None
},
_ => {println!("scancode {}",keycode);None},
}{
self.physics_thread.send(TimedInstruction{
time, time,
instruction:input_instruction, instruction:PhysicsInstruction::Input(input_instruction),
}).unwrap(); })
} }
}, },
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{
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
}
//do not step the physics because the mouse polling rate is higher than the physics can run. //do not step the physics because the mouse polling rate is higher than the physics can run.
//essentially the previous input will be overwritten until a true step runs //essentially the previous input will be overwritten until a true step runs
//which is fine because they run all the time. //which is fine because they run all the time.
let delta=glam::ivec2(delta.0 as i32,delta.1 as i32); self.physics.process_instruction(TimedInstruction{
self.mouse.pos+=delta;
self.physics_thread.send(TimedInstruction{
time, time,
instruction:InputInstruction::MoveMouse(self.mouse.pos), instruction:PhysicsInstruction::Input(InputInstruction::MoveMouse(glam::ivec2(delta.0 as i32,delta.1 as i32))),
}).unwrap(); })
}, },
winit::event::DeviceEvent::MouseWheel { winit::event::DeviceEvent::MouseWheel {
delta, delta,
} => { } => {
println!("mousewheel {:?}",delta); println!("mousewheel{:?}",delta);
if false{//self.physics.style.use_scroll{ if true{//self.physics.use_scroll
self.physics_thread.send(TimedInstruction{ self.physics.run(time);
self.physics.process_instruction(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:PhysicsInstruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
}).unwrap(); })
} }
} }
_=>(), _=>(),
@@ -1024,8 +907,9 @@ impl framework::Example for GlobalState {
device: &wgpu::Device, device: &wgpu::Device,
_queue: &wgpu::Queue, _queue: &wgpu::Queue,
) { ) {
self.graphics.depth_view = Self::create_depth_texture(config, device); self.depth_view = Self::create_depth_texture(config, device);
self.graphics.camera.set_screen_size(glam::uvec2(config.width, config.height)); self.screen_size = (config.width, config.height);
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
} }
fn render( fn render(
@@ -1035,34 +919,28 @@ impl framework::Example for GlobalState {
queue: &wgpu::Queue, queue: &wgpu::Queue,
_spawner: &framework::Spawner, _spawner: &framework::Spawner,
) { ) {
//ideally this would be scheduled to execute and finish right before the render.
let time=self.start_time.elapsed().as_nanos() as i64; let time=self.start_time.elapsed().as_nanos() as i64;
self.physics_thread.send(TimedInstruction{
time, self.physics.run(time);
instruction: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.graphics.camera.to_uniform_data(self.physics_thread.grab_clone().adjust_mouse(&self.mouse)); let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
self.graphics.staging_belt self.staging_belt
.write_buffer( .write_buffer(
&mut encoder, &mut encoder,
&self.graphics.camera_buf, &self.camera_buf,
0, 0,
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(), wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device, device,
) )
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms)); .copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
//This code only needs to run when the uniforms change //This code only needs to run when the uniforms change
/* for model in self.models.iter() {
for model in self.graphics.models.iter() {
let model_uniforms = get_instances_buffer_data(&model.instances); let model_uniforms = get_instances_buffer_data(&model.instances);
self.graphics.staging_belt self.staging_belt
.write_buffer( .write_buffer(
&mut encoder, &mut encoder,
&model.model_buf,//description of where data will be written when command is executed &model.model_buf,//description of where data will be written when command is executed
@@ -1072,8 +950,7 @@ impl framework::Example for GlobalState {
) )
.copy_from_slice(bytemuck::cast_slice(&model_uniforms)); .copy_from_slice(bytemuck::cast_slice(&model_uniforms));
} }
*/ self.staging_belt.finish();
self.graphics.staging_belt.finish();
{ {
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -1092,7 +969,7 @@ impl framework::Example for GlobalState {
}, },
})], })],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.graphics.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: false,
@@ -1101,11 +978,11 @@ impl framework::Example for GlobalState {
}), }),
}); });
rpass.set_bind_group(0, &self.graphics.bind_groups.camera, &[]); rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
rpass.set_bind_group(1, &self.graphics.bind_groups.skybox_texture, &[]); rpass.set_bind_group(1, &self.bind_groups.skybox_texture, &[]);
rpass.set_pipeline(&self.graphics.pipelines.model); rpass.set_pipeline(&self.pipelines.model);
for model in self.graphics.models.iter() { for model in self.models.iter() {
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(..));
@@ -1115,18 +992,18 @@ impl framework::Example for GlobalState {
} }
} }
rpass.set_pipeline(&self.graphics.pipelines.skybox); rpass.set_pipeline(&self.pipelines.skybox);
rpass.draw(0..3, 0..1); rpass.draw(0..3, 0..1);
} }
queue.submit(std::iter::once(encoder.finish())); queue.submit(std::iter::once(encoder.finish()));
self.graphics.staging_belt.recall(); self.staging_belt.recall();
} }
} }
fn main() { fn main() {
framework::run::<GlobalState>( framework::run::<GraphicsData>(
format!("Strafe Client v{}", format!("Strafe Client v{}",
env!("CARGO_PKG_VERSION") env!("CARGO_PKG_VERSION")
).as_str() ).as_str()

View File

@@ -56,175 +56,13 @@ pub struct ModelGraphicsInstance{
pub color:glam::Vec4, pub color:glam::Vec4,
} }
pub struct ModelInstance{ pub struct ModelInstance{
//pub id:u64,//this does not actually help with map fixes resimulating bots, they must always be resimulated
pub transform:glam::Affine3A, pub transform:glam::Affine3A,
pub color:glam::Vec4,//transparency is in here pub color:glam::Vec4,
pub attributes:CollisionAttributes,
pub temp_indexing:Vec<TempIndexedAttributes>,
}
impl std::default::Default for ModelInstance{
fn default() -> Self {
Self{
color:glam::Vec4::ONE,
transform:Default::default(),
attributes:Default::default(),
temp_indexing:Default::default(),
}
}
} }
pub struct IndexedModelInstances{ pub struct IndexedModelInstances{
pub textures:Vec<String>,//RenderPattern pub textures:Vec<String>,//RenderPattern
pub models:Vec<IndexedModel>, pub models:Vec<IndexedModel>,
//may make this into an object later. //object_index for spawns, triggers etc?
pub modes:Vec<ModeDescription>,
pub spawn_point:glam::Vec3,
}
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
pub struct ModeDescription{
pub start:u32,//start=model_id
pub spawns:Vec<u32>,//spawns[spawn_id]=model_id
pub ordered_checkpoints:Vec<u32>,//ordered_checkpoints[checkpoint_id]=model_id
pub unordered_checkpoints:Vec<u32>,//unordered_checkpoints[checkpoint_id]=model_id
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
}
impl ModeDescription{
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&u32>{
if let Some(&spawn)=self.spawn_from_stage_id.get(&stage_id){
self.spawns.get(spawn)
}else{
None
}
}
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&u32>{
if let Some(&checkpoint)=self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id){
self.ordered_checkpoints.get(checkpoint)
}else{
None
}
}
}
pub enum TempIndexedAttributes{
Start{
mode_id:u32,
},
Spawn{
mode_id:u32,
stage_id:u32,
},
OrderedCheckpoint{
mode_id:u32,
checkpoint_id:u32,
},
UnorderedCheckpoint{
mode_id:u32,
},
}
//you have this effect while in contact
#[derive(Clone)]
pub struct ContactingSurf{}
#[derive(Clone)]
pub struct ContactingLadder{
pub sticky:bool
}
//you have this effect while intersecting
#[derive(Clone)]
pub struct IntersectingWater{
pub viscosity:i64,
pub density:i64,
pub current:glam::Vec3,
}
#[derive(Clone)]
pub struct IntersectingAccelerator{
pub acceleration:glam::Vec3
}
//All models can be given these attributes
#[derive(Clone)]
pub struct GameMechanicJumpLimit{
pub count:u32,
}
#[derive(Clone)]
pub struct GameMechanicBooster{
pub velocity:glam::Vec3,
}
#[derive(Clone)]
pub enum ZoneBehaviour{
//Start is indexed
//Checkpoints are indexed
Finish,
Anitcheat,
}
#[derive(Clone)]
pub struct GameMechanicZone{
pub mode_id:u32,
pub behaviour:ZoneBehaviour,
}
// enum TrapCondition{
// FasterThan(i64),
// SlowerThan(i64),
// InRange(i64,i64),
// OutsideRange(i64,i64),
// }
#[derive(Clone)]
pub enum StageElementBehaviour{
//Spawn,//The behaviour of stepping on a spawn setting the spawnid
SpawnAt,
Trigger,
Teleport,
Platform,
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
}
#[derive(Clone)]
pub struct GameMechanicStageElement{
pub mode_id:u32,
pub stage_id:u32,//which spawn to send to
pub force:bool,//allow setting to lower spawn id i.e. 7->3
pub behaviour:StageElementBehaviour
}
#[derive(Clone)]
pub struct GameMechanicWormhole{//(position,angles)*=origin.transform.inverse()*destination.transform
pub model_id:u32,
}
#[derive(Default,Clone)]
pub struct GameMechanicAttributes{
pub jump_limit:Option<GameMechanicJumpLimit>,
pub booster:Option<GameMechanicBooster>,
pub zone:Option<GameMechanicZone>,
pub stage_element:Option<GameMechanicStageElement>,
pub wormhole:Option<GameMechanicWormhole>,//stage_element and wormhole are in conflict
}
#[derive(Default,Clone)]
pub struct ContactingAttributes{
pub elasticity:Option<u32>,//[1/2^32,1] 0=None (elasticity+1)/2^32
//friction?
pub surf:Option<ContactingSurf>,
pub ladder:Option<ContactingLadder>,
}
#[derive(Default,Clone)]
pub struct IntersectingAttributes{
pub water:Option<IntersectingWater>,
pub accelerator:Option<IntersectingAccelerator>,
}
//Spawn(u32) NO! spawns are indexed in the map header instead of marked with attibutes
pub enum CollisionAttributes{
Decoration,//visual only
Contact{//track whether you are contacting the object
contacting:ContactingAttributes,
general:GameMechanicAttributes,
},
Intersect{//track whether you are intersecting the object
intersecting:IntersectingAttributes,
general:GameMechanicAttributes,
},
}
impl std::default::Default for CollisionAttributes{
fn default() -> Self {
Self::Contact{
contacting:ContactingAttributes::default(),
general:GameMechanicAttributes::default()
}
}
} }
pub fn generate_indexed_model_list_from_obj(data:obj::ObjData,color:[f32;4]) -> Vec<IndexedModel>{ pub fn generate_indexed_model_list_from_obj(data:obj::ObjData,color:[f32;4]) -> Vec<IndexedModel>{

View File

@@ -113,11 +113,11 @@ pub enum CornerWedgeFace{
Front, Front,
} }
const CORNERWEDGE_DEFAULT_NORMALS:[[f32;3];5]=[ const CORNERWEDGE_DEFAULT_NORMALS:[[f32;3];5]=[
[ 1., 0., 0.],//CornerWedge::Right [ 1., 0., 0.],//Wedge::Right
[ 0., 1., 1.],//CornerWedge::BackTop [ 0., 1., 1.],//Wedge::BackTop
[-1., 1., 0.],//CornerWedge::LeftTop [-1., 1., 0.],//Wedge::LeftTop
[ 0.,-1., 0.],//CornerWedge::Bottom [ 0.,-1., 0.],//Wedge::Bottom
[ 0., 0.,-1.],//CornerWedge::Front [ 0., 0.,-1.],//Wedge::Front
]; ];
//HashMap fits this use case perfectly but feels like using a sledgehammer to drive a nail //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{
@@ -206,7 +206,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,face_description) in face_descriptions.iter(){
//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
@@ -321,7 +321,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,face_description) in face_descriptions.iter(){
//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
@@ -433,7 +433,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,face_description) in face_descriptions.iter(){
//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

View File

@@ -1,82 +0,0 @@
use std::thread;
use std::sync::{mpsc,Arc};
use parking_lot::Mutex;
//The goal here is to have a worker thread that parks itself when it runs out of work.
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
pub struct Worker<Task:Send,Value:Clone> {
sender: mpsc::Sender<Task>,
value:Arc<Mutex<Value>>,
}
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
let (sender, receiver) = mpsc::channel::<Task>();
let ret=Self {
sender,
value:Arc::new(Mutex::new(value)),
};
let value=ret.value.clone();
thread::spawn(move || {
loop {
match receiver.recv() {
Ok(task) => {
let v=f(task);//make sure function is evaluated before lock is acquired
*value.lock()=v;
}
Err(_) => {
println!("Worker stopping.",);
break;
}
}
}
});
ret
}
pub fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
self.sender.send(task)
}
pub fn grab_clone(&self)->Value{
self.value.lock().clone()
}
}
#[test]//How to run this test with printing: cargo test --release -- --nocapture
fn test_worker() {
println!("hiiiii");
// Create the worker thread
let worker = Worker::new(crate::physics::Body::with_pva(glam::Vec3::ZERO,glam::Vec3::ZERO,glam::Vec3::ZERO),
|_|crate::physics::Body::with_pva(glam::Vec3::ONE,glam::Vec3::ONE,glam::Vec3::ONE)
);
// Send tasks to the worker
for i in 0..5 {
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::physics::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
}
// Optional: Signal the worker to stop (in a real-world scenario)
// sender.send("STOP".to_string()).unwrap();
// Sleep to allow the worker thread to finish processing
thread::sleep(std::time::Duration::from_secs(2));
// Send a new task
let task = crate::instruction::TimedInstruction{
time:0,
instruction:crate::physics::PhysicsInstruction::StrafeTick,
};
worker.send(task).unwrap();
println!("value={:?}",worker.grab_clone());
// wait long enough to see print from final task
thread::sleep(std::time::Duration::from_secs(1));
}