Compare commits

..

20 Commits

Author SHA1 Message Date
fff4b7a09d fix key repeats 2023-10-23 16:32:28 -07:00
dd0b8fd1f0 update code for winit 0.29.2 2023-10-23 16:32:26 -07:00
5493350023 update winit dep to 0.29.2 2023-10-23 16:31:58 -07:00
668dcbe745 hide some compiler complaints 2023-10-21 17:08:40 -07:00
2070c1d629 roblox_rocket style 2023-10-20 13:52:57 -07:00
e8f878b185 implement rocket_force 2023-10-20 13:52:57 -07:00
857b7f252f optional strafing + optional rocket force 2023-10-20 13:52:57 -07:00
7be7d2c0df literally into_worker 2023-10-18 18:21:11 -07:00
cb6b0acd44 TODO: need real functions 2023-10-18 18:21:11 -07:00
cbcf047c3f basic wormholes (no velocity or camera transformation) 2023-10-18 18:21:11 -07:00
6e5de4aa46 overhaul TempIndexedAttributes + add Wormhole indexing 2023-10-18 18:21:11 -07:00
cc776e7cb4 model_id is usize + PhysicsModels struct 2023-10-18 18:21:11 -07:00
5a66ac46b9 functionate that damn code block 2023-10-18 18:21:11 -07:00
38f6e1df3f overhaul attributes 2023-10-18 18:21:11 -07:00
849dcf98f7 overhaul StyleModifiers 2023-10-18 18:21:11 -07:00
d04d1be27e overhaul WalkState + implement ladders 2023-10-18 18:21:11 -07:00
35bfd1d366 implement simulate_move_rotation 2023-10-18 18:21:11 -07:00
586bf8ce89 unpub a bunch of physics stuff 2023-10-18 18:21:11 -07:00
127b205401 implement MoveState + TouchingState 2023-10-18 18:21:11 -07:00
4f596ca5d7 unneeded mut 2023-10-18 16:30:02 -07:00
10 changed files with 815 additions and 620 deletions

695
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -22,7 +22,7 @@ rbx_dom_weak = "2.5.0"
rbx_reflection_database = "0.2.7"
rbx_xml = "0.13.1"
wgpu = "0.17.0"
winit = "0.28.6"
winit = { version = "0.29.2", features = ["rwh_05"] }
#[profile.release]
#lto = true

@ -12,12 +12,12 @@ use crate::aabb::Aabb;
#[derive(Default)]
pub struct BvhNode{
children:Vec<Self>,
models:Vec<u32>,
models:Vec<usize>,
aabb:Aabb,
}
impl BvhNode{
pub fn the_tester<F:FnMut(u32)>(&self,aabb:&Aabb,f:&mut F){
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
for &model in &self.models{
f(model);
}
@ -37,7 +37,7 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
let n=boxen.len();
if n<20{
let mut aabb=Aabb::default();
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0 as u32}).collect();
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0}).collect();
BvhNode{
children:Vec::new(),
models,

@ -5,7 +5,7 @@ use std::str::FromStr;
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
use winit::{
event::{self, WindowEvent, DeviceEvent},
event_loop::{ControlFlow, EventLoop},
event_loop::EventLoop,
};
#[allow(dead_code)]
@ -88,7 +88,7 @@ async fn setup<E: Example>(title: &str) -> Setup {
env_logger::init();
};
let event_loop = EventLoop::new();
let event_loop = EventLoop::new().unwrap();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title(title);
#[cfg(windows_OFF)] // TODO
@ -302,15 +302,15 @@ fn start<E: Example>(
let mut example = E::init(&config, &adapter, &device, &queue);
log::info!("Entering render loop...");
event_loop.run(move |event, _, control_flow| {
event_loop.run(move |event, elwt| {
let _ = (&instance, &adapter); // force ownership by the closure
*control_flow = if cfg!(feature = "metal-auto-capture") {
ControlFlow::Exit
} else {
ControlFlow::Poll
};
// *control_flow = if cfg!(feature = "metal-auto-capture") {
// ControlFlow::Exit
// } else {
// ControlFlow::Poll
// };
match event {
event::Event::RedrawEventsCleared => {
event::Event::AboutToWait => {
#[cfg(not(target_arch = "wasm32"))]
spawner.run_until_stalled();
@ -318,48 +318,44 @@ fn start<E: Example>(
}
event::Event::WindowEvent {
event:
WindowEvent::Resized(size)
| WindowEvent::ScaleFactorChanged {
new_inner_size: &mut size,
..
},
// WindowEvent::Resized(size)
// | WindowEvent::ScaleFactorChanged {
// new_inner_size: &mut size,
// ..
// },
WindowEvent::Resized(size),//ignoring scale factor changed for now because mutex bruh
..
} => {
// Once winit is fixed, the detection conditions here can be removed.
// https://github.com/rust-windowing/winit/issues/2876
let max_dimension = adapter.limits().max_texture_dimension_2d;
if size.width > max_dimension || size.height > max_dimension {
log::warn!(
"The resizing size {:?} exceeds the limit of {}.",
size,
max_dimension
);
} else {
log::info!("Resizing to {:?}", size);
config.width = size.width.max(1);
config.height = size.height.max(1);
example.resize(&config, &device, &queue);
surface.configure(&device, &config);
}
log::info!("Resizing to {:?}", size);
config.width = size.width.max(1);
config.height = size.height.max(1);
example.resize(&config, &device, &queue);
surface.configure(&device, &config);
}
event::Event::DeviceEvent {
event,
..
} => {
example.device_event(&window,event);
},
event::Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input:
event::KeyboardInput {
virtual_keycode: Some(event::VirtualKeyCode::Escape),
event:
event::KeyEvent {
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),
state: event::ElementState::Pressed,
..
},
..
}
| WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
elwt.exit();
}
#[cfg(not(target_arch = "wasm32"))]
WindowEvent::KeyboardInput {
input:
event::KeyboardInput {
virtual_keycode: Some(event::VirtualKeyCode::Scroll),
event:
event::KeyEvent {
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::ScrollLock),
state: event::ElementState::Pressed,
..
},
@ -367,54 +363,47 @@ fn start<E: Example>(
} => {
println!("{:#?}", instance.generate_report());
}
WindowEvent::RedrawRequested => {
let frame = match surface.get_current_texture() {
Ok(frame) => frame,
Err(_) => {
surface.configure(&device, &config);
surface
.get_current_texture()
.expect("Failed to acquire next surface texture!")
}
};
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(surface_view_format),
..wgpu::TextureViewDescriptor::default()
});
example.render(&view, &device, &queue, &spawner);
frame.present();
#[cfg(target_arch = "wasm32")]
{
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
let image_bitmap = offscreen_canvas_setup
.offscreen_canvas
.transfer_to_image_bitmap()
.expect("couldn't transfer offscreen canvas to image bitmap.");
offscreen_canvas_setup
.bitmap_renderer
.transfer_from_image_bitmap(&image_bitmap);
log::info!("Transferring OffscreenCanvas to ImageBitmapRenderer");
}
}
}
_ => {
example.update(&window,&device,&queue,event);
}
},
event::Event::DeviceEvent {
event,
..
} => {
example.device_event(&window,event);
},
event::Event::RedrawRequested(_) => {
let frame = match surface.get_current_texture() {
Ok(frame) => frame,
Err(_) => {
surface.configure(&device, &config);
surface
.get_current_texture()
.expect("Failed to acquire next surface texture!")
}
};
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(surface_view_format),
..wgpu::TextureViewDescriptor::default()
});
example.render(&view, &device, &queue, &spawner);
frame.present();
#[cfg(target_arch = "wasm32")]
{
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
let image_bitmap = offscreen_canvas_setup
.offscreen_canvas
.transfer_to_image_bitmap()
.expect("couldn't transfer offscreen canvas to image bitmap.");
offscreen_canvas_setup
.bitmap_renderer
.transfer_from_image_bitmap(&image_bitmap);
log::info!("Transferring OffscreenCanvas to ImageBitmapRenderer");
}
}
}
_ => {}
}
});
}).unwrap();
}
#[cfg(not(target_arch = "wasm32"))]

@ -404,12 +404,11 @@ impl TryFrom<[f32;3]> for Unit32Vec3{
*/
///[-1.0,1.0] = [-2^32,2^32]
#[derive(Clone,Copy,Debug,Hash,Eq,Ord,PartialEq,PartialOrd)]
#[derive(Clone,Copy,Hash,Eq,Ord,PartialEq,PartialOrd)]
pub struct Planar64(i64);
impl Planar64{
pub const ZERO:Self=Self(0);
pub const ONE:Self=Self(1<<32);
pub const FRAC_1_SQRT2:Self=Self(3_037_000_500);
#[inline]
pub const fn int(num:i32)->Self{
Self(Self::ONE.0*num as i64)
@ -564,7 +563,7 @@ impl std::ops::Div<Planar64> for Planar64{
///[-1.0,1.0] = [-2^32,2^32]
#[derive(Clone,Copy,Debug,Default,Hash,Eq,PartialEq)]
#[derive(Clone,Copy,Default,Hash,Eq,PartialEq)]
pub struct Planar64Vec3(glam::I64Vec3);
impl Planar64Vec3{
pub const ZERO:Self=Planar64Vec3(glam::I64Vec3::ZERO);
@ -630,14 +629,6 @@ impl Planar64Vec3{
)>>32) as i64)
}
#[inline]
/* pub fn cross(&self,rhs:Self)->Planar64Vec3{
Planar64Vec3(((
(self.0.x as i128)*(rhs.0.x as i128)+
(self.0.y as i128)*(rhs.0.y as i128)+
(self.0.z as i128)*(rhs.0.z as i128)
)>>32) as i64)
}*/
#[inline]
pub fn length(&self)->Planar64{
let radicand=(self.0.x as i128)*(self.0.x as i128)+(self.0.y as i128)*(self.0.y as i128)+(self.0.z as i128)*(self.0.z as i128);
Planar64(unsafe{(radicand as f64).sqrt().to_int_unchecked()})

@ -49,7 +49,6 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
let mut intersecting=crate::model::IntersectingAttributes::default();
let mut contacting=crate::model::ContactingAttributes::default();
let mut force_can_collide=can_collide;
const GRAVITY:Planar64Vec3=Planar64Vec3::int(0,-100,0);
match name{
"Water"=>{
force_can_collide=false;
@ -124,20 +123,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
}
//need some way to skip this
if velocity!=Planar64Vec3::ZERO{
//assume all vertical boosters are targetting a height
let vg=velocity.dot(GRAVITY);
if Planar64::ZERO<=vg{
//weird down booster
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
}else{
println!("set attr");
let gg=GRAVITY.dot(GRAVITY);
let height=-vg*gg.sqrt().sqrt()*Planar64::FRAC_1_SQRT2/gg;//vi/sqrt(-2*a)=d
let v=velocity-GRAVITY*(vg/gg);
//if we are adding zero SO BE IT, the check to see if the vectors are parallel is too sensitive
general.booster=Some(crate::model::GameMechanicBooster::Velocity(v));
general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Height(height));
}
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
}
match force_can_collide{
true=>{
@ -277,16 +263,17 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
if let Some(attr)=match &object.name[..]{
"MapStart"=>{
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
Some(crate::model::TempIndexedAttributes::Start{mode_id:0})
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
},
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint(crate::model::TempAttrUnorderedCheckpoint{mode_id:0})),
other=>{
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint|WormholeOut)(\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()}),
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn(crate::model::TempAttrSpawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()})),
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint(crate::model::TempAttrOrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()})),
"WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
_=>None,
}
}else{

@ -1093,20 +1093,20 @@ impl framework::Example for GlobalState {
let time=integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
match event {
winit::event::WindowEvent::DroppedFile(path) => self.load_file(path,device,queue),
winit::event::WindowEvent::Focused(state)=>{
winit::event::WindowEvent::Focused(_state)=>{
//pause unpause
//recalculate pressed keys on focus
},
winit::event::WindowEvent::KeyboardInput {
input:winit::event::KeyboardInput{state, virtual_keycode,..},
winit::event::WindowEvent::KeyboardInput{
event:winit::event::KeyEvent{state,logical_key,repeat:false,..},
..
}=>{
let s=match state {
winit::event::ElementState::Pressed => true,
winit::event::ElementState::Released => false,
};
match virtual_keycode{
Some(winit::event::VirtualKeyCode::Tab)=>{
match logical_key{
winit::keyboard::Key::Named(winit::keyboard::NamedKey::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)){
@ -1135,7 +1135,7 @@ impl framework::Example for GlobalState {
}
window.set_cursor_visible(s);
},
Some(winit::event::VirtualKeyCode::F11)=>{
winit::keyboard::Key::Named(winit::keyboard::NamedKey::F11)=>{
if s{
if window.fullscreen().is_some(){
window.set_fullscreen(None);
@ -1144,7 +1144,7 @@ impl framework::Example for GlobalState {
}
}
},
Some(winit::event::VirtualKeyCode::Escape)=>{
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape)=>{
if s{
self.manual_mouse_lock=false;
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
@ -1154,18 +1154,21 @@ impl framework::Example for GlobalState {
window.set_cursor_visible(true);
}
},
Some(keycode)=>{
keycode=>{
if let Some(input_instruction)=match keycode {
winit::event::VirtualKeyCode::W => Some(InputInstruction::MoveForward(s)),
winit::event::VirtualKeyCode::A => Some(InputInstruction::MoveLeft(s)),
winit::event::VirtualKeyCode::S => Some(InputInstruction::MoveBack(s)),
winit::event::VirtualKeyCode::D => Some(InputInstruction::MoveRight(s)),
winit::event::VirtualKeyCode::E => Some(InputInstruction::MoveUp(s)),
winit::event::VirtualKeyCode::Q => Some(InputInstruction::MoveDown(s)),
winit::event::VirtualKeyCode::Space => Some(InputInstruction::Jump(s)),
winit::event::VirtualKeyCode::Z => Some(InputInstruction::Zoom(s)),
winit::event::VirtualKeyCode::R => if s{Some(InputInstruction::Reset)}else{None},
_ => None,
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space)=>Some(InputInstruction::Jump(s)),
winit::keyboard::Key::Character(c)=>match c.as_str(){
"w"=>Some(InputInstruction::MoveForward(s)),
"a"=>Some(InputInstruction::MoveLeft(s)),
"s"=>Some(InputInstruction::MoveBack(s)),
"d"=>Some(InputInstruction::MoveRight(s)),
"e"=>Some(InputInstruction::MoveUp(s)),
"q"=>Some(InputInstruction::MoveDown(s)),
"z"=>Some(InputInstruction::Zoom(s)),
"r"=>if s{Some(InputInstruction::Reset)}else{None},
_=>None,
}
_=>None,
}{
self.physics_thread.send(TimedInstruction{
time,
@ -1173,7 +1176,6 @@ impl framework::Example for GlobalState {
}).unwrap();
}
},
_=>(),
}
},
_=>(),

@ -50,44 +50,50 @@ pub struct IndexedModelInstances{
}
//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 start:usize,//start=model_id
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
pub ordered_checkpoints:Vec<usize>,//ordered_checkpoints[checkpoint_id]=model_id
pub unordered_checkpoints:Vec<usize>,//unordered_checkpoints[checkpoint_id]=model_id
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
pub 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_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
}
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 fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&usize>{
self.ordered_checkpoints.get(*self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id)?)
}
}
//I don't want this code to exist!
#[derive(Clone)]
pub struct TempAttrStart{
pub mode_id:u32,
}
#[derive(Clone)]
pub struct TempAttrSpawn{
pub mode_id:u32,
pub stage_id:u32,
}
#[derive(Clone)]
pub struct TempAttrOrderedCheckpoint{
pub mode_id:u32,
pub checkpoint_id:u32,
}
#[derive(Clone)]
pub struct TempAttrUnorderedCheckpoint{
pub mode_id:u32,
}
#[derive(Clone)]
pub struct TempAttrWormhole{
pub wormhole_id:u32,
}
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,
},
Start(TempAttrStart),
Spawn(TempAttrSpawn),
OrderedCheckpoint(TempAttrOrderedCheckpoint),
UnorderedCheckpoint(TempAttrUnorderedCheckpoint),
Wormhole(TempAttrWormhole),
}
//you have this effect while in contact
@ -119,12 +125,12 @@ pub enum GameMechanicBooster{
Velocity(Planar64Vec3),//straight up boost velocity adds to your current velocity
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
}
#[derive(Clone,Debug)]
#[derive(Clone)]
pub enum TrajectoryChoice{
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
}
#[derive(Clone,Debug)]
#[derive(Clone)]
pub enum GameMechanicSetTrajectory{
AirTime(Time),//air time (relative to gravity direction) is invariant across mass and gravity changes
Height(Planar64),//boost height (relative to gravity direction) is invariant across mass and gravity changes

@ -57,38 +57,6 @@ pub struct Body {
time:Time,//nanoseconds x xxxxD!
}
pub enum MoveRestriction {
Air,
Water,
Ground,
Ladder,//multiple ladders how
}
/*
enum InputInstruction {
}
struct InputState {
}
impl InputState {
pub fn get_control(&self,control:u32) -> bool {
self.controls&control!=0
}
}
impl crate::instruction::InstructionEmitter<InputInstruction> for InputState{
fn next_instruction(&self, time_limit:crate::body::Time) -> Option<TimedInstruction<InputInstruction>> {
//this is polled by PhysicsState for actions like Jump
//no, it has to be the other way around. physics is run up until the jump instruction, and then the jump instruction is pushed.
self.queue.get(0)
}
}
impl crate::instruction::InstructionConsumer<InputInstruction> for InputState{
fn process_instruction(&mut self,ins:TimedInstruction<InputInstruction>){
//add to queue
self.queue.push(ins);
}
}
*/
//hey dumbass just use a delta
#[derive(Clone,Debug)]
pub struct MouseState {
@ -130,7 +98,7 @@ struct WalkState{
impl WalkEnum{
//args going crazy
//(walk_enum,body.acceleration)=with_target_velocity();
fn with_target_velocity(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&Vec<ModelPhysics>,mut velocity:Planar64Vec3,normal:&Planar64Vec3)->(WalkEnum,Planar64Vec3){
fn with_target_velocity(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&PhysicsModels,mut velocity:Planar64Vec3,normal:&Planar64Vec3)->(WalkEnum,Planar64Vec3){
touching.constrain_velocity(models,&mut velocity);
let mut target_diff=velocity-body.velocity;
//remove normal component
@ -156,14 +124,14 @@ impl WalkEnum{
}
}
impl WalkState{
fn ground(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&Vec<ModelPhysics>,mut velocity:Planar64Vec3)->(Self,Planar64Vec3){
fn ground(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&PhysicsModels,velocity:Planar64Vec3)->(Self,Planar64Vec3){
let (walk_enum,a)=WalkEnum::with_target_velocity(touching,body,style,models,velocity,&Planar64Vec3::Y);
(Self{
state:walk_enum,
normal:Planar64Vec3::Y,
},a)
}
fn ladder(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&Vec<ModelPhysics>,mut velocity:Planar64Vec3,normal:&Planar64Vec3)->(Self,Planar64Vec3){
fn ladder(touching:&TouchingState,body:&Body,style:&StyleModifiers,models:&PhysicsModels,velocity:Planar64Vec3,normal:&Planar64Vec3)->(Self,Planar64Vec3){
let (walk_enum,a)=WalkEnum::with_target_velocity(touching,body,style,models,velocity,normal);
(Self{
state:walk_enum,
@ -172,7 +140,62 @@ impl WalkState{
}
}
struct Modes{
modes:Vec<crate::model::ModeDescription>,
mode_from_mode_id:std::collections::HashMap::<u32,usize>,
}
impl Modes{
fn clear(&mut self){
self.modes.clear();
self.mode_from_mode_id.clear();
}
fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
self.modes.get(*self.mode_from_mode_id.get(&mode_id)?)
}
fn insert(&mut self,temp_map_mode_id:u32,mode:crate::model::ModeDescription){
let mode_id=self.modes.len();
self.mode_from_mode_id.insert(temp_map_mode_id,mode_id);
self.modes.push(mode);
}
}
impl Default for Modes{
fn default() -> Self {
Self{
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
}
}
}
struct PhysicsModels{
models:Vec<ModelPhysics>,
model_id_from_wormhole_id:std::collections::HashMap::<u32,usize>,
}
impl PhysicsModels{
fn clear(&mut self){
self.models.clear();
self.model_id_from_wormhole_id.clear();
}
fn get(&self,i:usize)->Option<&ModelPhysics>{
self.models.get(i)
}
fn get_wormhole_model(&self,wormhole_id:u32)->Option<&ModelPhysics>{
self.models.get(*self.model_id_from_wormhole_id.get(&wormhole_id)?)
}
fn push(&mut self,model:ModelPhysics)->usize{
let model_id=self.models.len();
self.models.push(model);
model_id
}
}
impl Default for PhysicsModels{
fn default() -> Self {
Self{
models:Vec::new(),
model_id_from_wormhole_id:std::collections::HashMap::new(),
}
}
}
#[derive(Clone)]
pub struct PhysicsCamera {
@ -268,7 +291,7 @@ enum JumpImpulse{
struct StyleModifiers{
controls_mask:u32,//controls which are unable to be activated
controls_held:u32,//controls which must be active to be able to strafe
strafe_tick_rate:Ratio64,
strafe_tick_rate:Option<Ratio64>,
jump_impulse:JumpImpulse,
jump_calculation:JumpCalculation,
static_friction:Planar64,
@ -282,6 +305,7 @@ struct StyleModifiers{
mass:Planar64,
mv:Planar64,
air_accel_limit:Option<Planar64>,
rocket_force:Option<Planar64>,
gravity:Planar64Vec3,
hitbox_halfsize:Planar64Vec3,
}
@ -308,7 +332,7 @@ impl StyleModifiers{
Self{
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held:0,
strafe_tick_rate:Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap(),
strafe_tick_rate:Some(Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap()),
jump_impulse:JumpImpulse::FromEnergy(Planar64::int(512)),
jump_calculation:JumpCalculation::Energy,
gravity:Planar64Vec3::int(0,-80,0),
@ -317,6 +341,7 @@ impl StyleModifiers{
mass:Planar64::int(1),
mv:Planar64::int(2),
air_accel_limit:None,
rocket_force:None,
walk_speed:Planar64::int(16),
walk_accel:Planar64::int(80),
ladder_speed:Planar64::int(16),
@ -331,7 +356,7 @@ impl StyleModifiers{
Self{
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held:0,
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
jump_calculation:JumpCalculation::Capped,
gravity:Planar64Vec3::int(0,-100,0),
@ -340,6 +365,7 @@ impl StyleModifiers{
mass:Planar64::int(1),
mv:Planar64::int(27)/10,
air_accel_limit:None,
rocket_force:None,
walk_speed:Planar64::int(18),
walk_accel:Planar64::int(90),
ladder_speed:Planar64::int(18),
@ -353,7 +379,7 @@ impl StyleModifiers{
Self{
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held:0,
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
jump_calculation:JumpCalculation::Capped,
gravity:Planar64Vec3::int(0,-50,0),
@ -362,6 +388,7 @@ impl StyleModifiers{
mass:Planar64::int(1),
mv:Planar64::int(27)/10,
air_accel_limit:None,
rocket_force:None,
walk_speed:Planar64::int(18),
walk_accel:Planar64::int(90),
ladder_speed:Planar64::int(18),
@ -377,7 +404,7 @@ impl StyleModifiers{
Self{
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held:0,
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
jump_calculation:JumpCalculation::Linear,
gravity:Planar64Vec3::raw(0,-800<<28,0),
@ -386,6 +413,7 @@ impl StyleModifiers{
mass:Planar64::int(1),
mv:Planar64::raw(30<<28),
air_accel_limit:Some(Planar64::raw(150<<28)*66),
rocket_force:None,
walk_speed:Planar64::int(18),//?
walk_accel:Planar64::int(90),//?
ladder_speed:Planar64::int(18),//?
@ -400,7 +428,7 @@ impl StyleModifiers{
Self{
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held:0,
strafe_tick_rate:Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap(),
strafe_tick_rate:Some(Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap()),
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
jump_calculation:JumpCalculation::Linear,
gravity:Planar64Vec3::raw(0,-800<<28,0),
@ -409,6 +437,7 @@ impl StyleModifiers{
mass:Planar64::int(1),
mv:Planar64::raw(30<<28),
air_accel_limit:Some(Planar64::raw(150<<28)*66),
rocket_force:None,
walk_speed:Planar64::int(18),//?
walk_accel:Planar64::int(90),//?
ladder_speed:Planar64::int(18),//?
@ -418,6 +447,29 @@ impl StyleModifiers{
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
}
}
fn roblox_rocket()->Self{
Self{
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
controls_held:0,
strafe_tick_rate:None,
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
jump_calculation:JumpCalculation::Capped,
gravity:Planar64Vec3::int(0,-100,0),
static_friction:Planar64::int(2),
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
mass:Planar64::int(1),
mv:Planar64::int(27)/10,
air_accel_limit:None,
rocket_force:Some(Planar64::int(200)),
walk_speed:Planar64::int(18),
walk_accel:Planar64::int(90),
ladder_speed:Planar64::int(18),
ladder_accel:Planar64::int(180),
ladder_dot:(Planar64::int(1)/2).sqrt(),
swim_speed:Planar64::int(12),
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
}
}
fn get_control(&self,control:u32,controls:u32)->bool{
controls&self.controls_mask&control==control
@ -485,10 +537,9 @@ impl StyleModifiers{
// return cross(cross(Normal,ControlDir),Normal)/sqrt(1-d*d)
control_dir*self.walk_speed
}
fn get_propulsion_target_velocity(&self,camera:&PhysicsCamera,controls:u32,next_mouse:&MouseState,time:Time)->Planar64Vec3{
fn get_propulsion_control_dir(&self,camera:&PhysicsCamera,controls:u32,next_mouse:&MouseState,time:Time)->Planar64Vec3{
let camera_mat=camera.simulate_move_rotation(camera.mouse.lerp(&next_mouse,time));
let control_dir=camera_mat*self.get_control_dir(controls);
control_dir*self.walk_speed
camera_mat*self.get_control_dir(controls)
}
}
@ -512,11 +563,10 @@ pub struct PhysicsState{
controls:u32,
move_state:MoveState,
//all models
models:Vec<ModelPhysics>,
models:PhysicsModels,
bvh:crate::bvh::BvhNode,
modes:Vec<crate::model::ModeDescription>,
mode_from_mode_id:std::collections::HashMap::<u32,usize>,
modes:Modes,
//the spawn point is where you spawn when you load into the map.
//This is not the same as Reset which teleports you to Spawn0
pub spawn_point:Planar64Vec3,
@ -592,44 +642,44 @@ impl ModelPhysics {
//OR have a separate list from contacts for model intersection
#[derive(Debug,Clone,Eq,Hash,PartialEq)]
pub struct RelativeCollision {
face: TreyMeshFace,//just an id
model: u32,//using id to avoid lifetimes
face:TreyMeshFace,//just an id
model:usize,//using id to avoid lifetimes
}
impl RelativeCollision {
pub fn model<'a>(&self,models:&'a Vec<ModelPhysics>)->Option<&'a ModelPhysics>{
models.get(self.model as usize)
fn model<'a>(&self,models:&'a PhysicsModels)->Option<&'a ModelPhysics>{
models.get(self.model)
}
// pub fn mesh(&self,models:&Vec<ModelPhysics>) -> TreyMesh {
// return self.model(models).unwrap().face_mesh(self.face).clone()
// }
pub fn normal(&self,models:&Vec<ModelPhysics>) -> Planar64Vec3 {
fn normal(&self,models:&PhysicsModels) -> Planar64Vec3 {
return self.model(models).unwrap().face_normal(self.face)
}
}
struct TouchingState{
contacts:std::collections::HashMap::<u32,RelativeCollision>,
intersects:std::collections::HashMap::<u32,RelativeCollision>,
contacts:std::collections::HashMap::<usize,RelativeCollision>,
intersects:std::collections::HashMap::<usize,RelativeCollision>,
}
impl TouchingState{
fn clear(&mut self){
self.contacts.clear();
self.intersects.clear();
}
fn insert_contact(&mut self,model_id:u32,collision:RelativeCollision)->Option<RelativeCollision>{
fn insert_contact(&mut self,model_id:usize,collision:RelativeCollision)->Option<RelativeCollision>{
self.contacts.insert(model_id,collision)
}
fn remove_contact(&mut self,model_id:u32)->Option<RelativeCollision>{
fn remove_contact(&mut self,model_id:usize)->Option<RelativeCollision>{
self.contacts.remove(&model_id)
}
fn insert_intersect(&mut self,model_id:u32,collision:RelativeCollision)->Option<RelativeCollision>{
fn insert_intersect(&mut self,model_id:usize,collision:RelativeCollision)->Option<RelativeCollision>{
self.intersects.insert(model_id,collision)
}
fn remove_intersect(&mut self,model_id:u32)->Option<RelativeCollision>{
fn remove_intersect(&mut self,model_id:usize)->Option<RelativeCollision>{
self.intersects.remove(&model_id)
}
fn constrain_velocity(&self,models:&Vec<ModelPhysics>,velocity:&mut Planar64Vec3){
fn constrain_velocity(&self,models:&PhysicsModels,velocity:&mut Planar64Vec3){
for (_,contact) in &self.contacts {
let n=contact.normal(models);
let d=velocity.dot(n);
@ -638,7 +688,7 @@ impl TouchingState{
}
}
}
fn constrain_acceleration(&self,models:&Vec<ModelPhysics>,acceleration:&mut Planar64Vec3){
fn constrain_acceleration(&self,models:&PhysicsModels,acceleration:&mut Planar64Vec3){
for (_,contact) in &self.contacts {
let n=contact.normal(models);
let d=acceleration.dot(n);
@ -694,7 +744,7 @@ impl Default for PhysicsState{
time: Time::ZERO,
style:StyleModifiers::default(),
touching:TouchingState::default(),
models: Vec::new(),
models:PhysicsModels::default(),
bvh:crate::bvh::BvhNode::default(),
move_state: MoveState::Air,
camera: PhysicsCamera::from_offset(Planar64Vec3::int(0,2,0)),//4.5-2.5=2
@ -702,8 +752,7 @@ impl Default for PhysicsState{
controls: 0,
world:WorldState{},
game:GameMechanicsState::default(),
modes:Vec::new(),
mode_from_mode_id:std::collections::HashMap::new(),
modes:Modes::default(),
}
}
}
@ -818,81 +867,70 @@ impl PhysicsState {
//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);
let model_id=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)),
crate::model::TempIndexedAttributes::Start(s)=>starts.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::Spawn(s)=>spawns.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::OrderedCheckpoint(s)=>ordered_checkpoints.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::UnorderedCheckpoint(s)=>unordered_checkpoints.push((model_id,s.clone())),
crate::model::TempIndexedAttributes::Wormhole(s)=>{self.models.model_id_from_wormhole_id.insert(s.wormhole_id,model_id);},
}
}
}
}
}
self.bvh=crate::bvh::generate_bvh(self.models.iter().map(|m|m.mesh().clone()).collect());
self.bvh=crate::bvh::generate_bvh(self.models.models.iter().map(|m|m.mesh().clone()).collect());
//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())
starts.sort_by_key(|tup|tup.1.mode_id);
let mut mode_id_from_map_mode_id=std::collections::HashMap::new();
let mut modedatas:Vec<(usize,Vec<(u32,usize)>,Vec<(u32,usize)>,Vec<usize>,u32)>=starts.into_iter().enumerate().map(|(i,(model_id,s))|{
mode_id_from_map_mode_id.insert(s.mode_id,i);
(model_id,Vec::new(),Vec::new(),Vec::new(),s.mode_id)
}).collect();
for tup in spawns{
if let Some(mode_id)=eshmep.get(&tup.0){
for (model_id,s) in spawns{
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.1.push((tup.2,tup.1));
modedata.1.push((s.stage_id,model_id));
}
}
}
for tup in ordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
for (model_id,s) in ordered_checkpoints{
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.2.push((tup.2,tup.1));
modedata.2.push((s.checkpoint_id,model_id));
}
}
}
for tup in unordered_checkpoints{
if let Some(mode_id)=eshmep.get(&tup.0){
for (model_id,s) in unordered_checkpoints{
if let Some(mode_id)=mode_id_from_map_mode_id.get(&s.mode_id){
if let Some(modedata)=modedatas.get_mut(*mode_id){
modedata.3.push(tup.1);
modedata.3.push(model_id);
}
}
}
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|{
for mut tup in modedatas.into_iter(){
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{
self.modes.insert(tup.4,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());
});
}
println!("Physics Objects: {}",self.models.models.len());
}
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
self.camera.sensitivity=user_settings.calculate_sensitivity();
}
pub fn get_mode(&self,mode_id:u32)->Option<&crate::model::ModeDescription>{
if let Some(&mode)=self.mode_from_mode_id.get(&mode_id){
self.modes.get(mode)
}else{
None
}
}
//tickless gaming
pub fn run(&mut self, time_limit:Time){
//prepare is ommitted - everything is done via instructions.
@ -923,11 +961,13 @@ impl PhysicsState {
}
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
return Some(TimedInstruction{
time:Time::from_nanos(self.style.strafe_tick_rate.rhs_div_int(self.style.strafe_tick_rate.mul_int(self.time.nanos()+1)+1)),
//only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick
});
self.style.strafe_tick_rate.as_ref().map(|strafe_tick_rate|{
TimedInstruction{
time:Time::from_nanos(strafe_tick_rate.rhs_div_int(strafe_tick_rate.mul_int(self.time.nanos())+1)),
//only poll the physics if there is a before and after mouse event
instruction:PhysicsInstruction::StrafeTick
}
})
}
//state mutated on collision:
@ -961,16 +1001,20 @@ impl PhysicsState {
// });
// }
fn refresh_walk_target(&mut self){
fn refresh_walk_target(&mut self)->Option<Planar64Vec3>{
match &mut self.move_state{
MoveState::Air|MoveState::Water=>(),
MoveState::Air|MoveState::Water=>None,
MoveState::Walk(WalkState{normal,state})=>{
let n=normal;
(*state,self.body.acceleration)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_walk_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
let a;
(*state,a)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_walk_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
Some(a)
},
MoveState::Ladder(WalkState{normal,state})=>{
let n=normal;
(*state,self.body.acceleration)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_ladder_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
let a;
(*state,a)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_ladder_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
Some(a)
},
}
}
@ -1141,7 +1185,7 @@ impl PhysicsState {
},
}
//generate instruction
if let Some(face) = exit_face{
if let Some(_face) = exit_face{
return Some(TimedInstruction {
time: best_time,
instruction: PhysicsInstruction::CollisionEnd(collision_data.clone())
@ -1149,9 +1193,9 @@ impl PhysicsState {
}
None
}
fn predict_collision_start(&self,time:Time,time_limit:Time,model_id:u32) -> Option<TimedInstruction<PhysicsInstruction>> {
fn predict_collision_start(&self,time:Time,time_limit:Time,model_id:usize) -> Option<TimedInstruction<PhysicsInstruction>> {
let mesh0=self.mesh();
let mesh1=self.models.get(model_id as usize).unwrap().mesh();
let mesh1=self.models.get(model_id).unwrap().mesh();
let (p,v,a,body_time)=(self.body.position,self.body.velocity,self.body.acceleration,self.body.time);
//find best t
let mut best_time=time_limit;
@ -1256,12 +1300,12 @@ impl PhysicsState {
}
}
//generate instruction
if let Some(face) = best_face{
return Some(TimedInstruction {
if let Some(face)=best_face{
return Some(TimedInstruction{
time: best_time,
instruction: PhysicsInstruction::CollisionStart(RelativeCollision {
instruction:PhysicsInstruction::CollisionStart(RelativeCollision{
face,
model: model_id
model:model_id
})
})
}
@ -1275,6 +1319,7 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
//JUST POLLING!!! NO MUTATION
let mut collector = crate::instruction::InstructionCollector::new(time_limit);
//check for collision stop instructions with curent contacts
//TODO: make this into a touching.next_instruction(&mut collector) member function
for (_,collision_data) in &self.touching.contacts {
collector.collect(self.predict_collision_end(self.time,time_limit,collision_data));
}
@ -1296,6 +1341,45 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
}
}
fn teleport(body:&mut Body,touching:&mut TouchingState,style:&StyleModifiers,point:Planar64Vec3)->MoveState{
body.position=point;
//manual clear //for c in contacts{process_instruction(CollisionEnd(c))}
touching.clear();
body.acceleration=style.gravity;
MoveState::Air
//TODO: calculate contacts and determine the actual state
//touching.recalculate(body);
}
fn run_teleport_behaviour(teleport_behaviour:&Option<crate::model::TeleportBehaviour>,game:&mut GameMechanicsState,models:&PhysicsModels,modes:&Modes,style:&StyleModifiers,touching:&mut TouchingState,body:&mut Body,model:&ModelPhysics)->Option<MoveState>{
match teleport_behaviour{
Some(crate::model::TeleportBehaviour::StageElement(stage_element))=>{
if stage_element.force||game.stage_id<stage_element.stage_id{
game.stage_id=stage_element.stage_id;
}
match &stage_element.behaviour{
crate::model::StageElementBehaviour::SpawnAt=>None,
crate::model::StageElementBehaviour::Trigger
|crate::model::StageElementBehaviour::Teleport=>{
//I guess this is correct behaviour when trying to teleport to a non-existent spawn but it's still weird
let model=models.get(*modes.get_mode(stage_element.mode_id)?.get_spawn_model_id(game.stage_id)? as usize)?;
let point=model.transform.transform_point3(Planar64Vec3::Y)+Planar64Vec3::Y*(style.hitbox_halfsize.y()+Planar64::ONE/16);
Some(teleport(body,touching,style,point))
},
crate::model::StageElementBehaviour::Platform=>None,
crate::model::StageElementBehaviour::JumpLimit(_)=>None,//TODO
}
},
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
let origin_model=model;
let destination_model=models.get_wormhole_model(wormhole.destination_model_id)?;
//ignore the transform for now
Some(teleport(body,touching,style,body.position-origin_model.transform.translation+destination_model.transform.translation))
}
None=>None,
}
}
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
match &ins.instruction {
@ -1349,37 +1433,8 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
}
//check ground
self.touching.insert_contact(c.model,c);
match &general.teleport_behaviour{
Some(crate::model::TeleportBehaviour::StageElement(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(Planar64Vec3::Y)+Planar64Vec3::Y*(self.style.hitbox_halfsize.y()+Planar64::ONE/16);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.touching.clear();
self.body.acceleration=self.style.gravity;
self.move_state=MoveState::Air;//TODO: calculate contacts and determine the actual state
}else{println!("bad1");}
}else{println!("bad2");}
}else{println!("bad3");}
},
crate::model::StageElementBehaviour::Platform=>(),
crate::model::StageElementBehaviour::JumpLimit(_)=>(),//TODO
}
},
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
//telefart
}
None=>(),
}
//I love making functions with 10 arguments to dodge the borrow checker
run_teleport_behaviour(&general.teleport_behaviour,&mut self.game,&self.models,&self.modes,&self.style,&mut self.touching,&mut self.body,model);
//flatten v
self.touching.constrain_velocity(&self.models,&mut v);
match &general.booster{
@ -1387,7 +1442,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
match booster{
&crate::model::GameMechanicBooster::Affine(transform)=>v=transform.transform_point3(v),
&crate::model::GameMechanicBooster::Velocity(velocity)=>v+=velocity,
&crate::model::GameMechanicBooster::Energy{direction,energy}=>todo!(),
&crate::model::GameMechanicBooster::Energy{direction: _,energy: _}=>todo!(),
}
self.touching.constrain_velocity(&self.models,&mut v);
},
@ -1395,25 +1450,13 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
}
match &general.trajectory{
Some(trajectory)=>{
println!("??? {:?}",trajectory);
match trajectory{
&crate::model::GameMechanicSetTrajectory::Height(height)=>{
//vg=sqrt(-2*gg*height)
println!("height booster h={}",height);
let vg=v.dot(self.style.gravity);
let gg=self.style.gravity.dot(self.style.gravity);
let hb=(gg.sqrt()*height*2).sqrt()*gg.sqrt();
println!("hb={} vg={}",hb,vg);
let b=self.style.gravity*((-hb-vg)/gg);
println!("bopo {}",b);
v+=b;
},
crate::model::GameMechanicSetTrajectory::AirTime(_) => todo!(),
crate::model::GameMechanicSetTrajectory::Height(_) => todo!(),
crate::model::GameMechanicSetTrajectory::TargetPointTime { target_point: _, time: _ } => todo!(),
crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint { target_point: _, speed: _, trajectory_choice: _ } => todo!(),
&crate::model::GameMechanicSetTrajectory::Velocity(velocity)=>v=velocity,
crate::model::GameMechanicSetTrajectory::AirTime(_)
|crate::model::GameMechanicSetTrajectory::TargetPointTime{target_point:_,time:_}
|crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint{target_point:_,speed:_,trajectory_choice:_}
|crate::model::GameMechanicSetTrajectory::DotVelocity{direction:_,dot:_}
=>(),
crate::model::GameMechanicSetTrajectory::DotVelocity { direction: _, dot: _ } => todo!(),
}
self.touching.constrain_velocity(&self.models,&mut v);
},
@ -1423,51 +1466,26 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
if self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
self.jump();
}
self.refresh_walk_target();
if let Some(a)=self.refresh_walk_target(){
self.body.acceleration=a;
}
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
PhysicsCollisionAttributes::Intersect{intersecting: _,general}=>{
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
self.touching.insert_intersect(c.model,c);
match &general.teleport_behaviour{
Some(crate::model::TeleportBehaviour::StageElement(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(Planar64Vec3::Y)+Planar64Vec3::Y*(self.style.hitbox_halfsize.y()+Planar64::ONE/16);
//manual clear //for c in self.contacts{process_instruction(CollisionEnd(c))}
self.touching.clear();
self.body.acceleration=self.style.gravity;
self.move_state=MoveState::Air;//TODO: calculate contacts and determine the actual state
}else{println!("bad1");}
}else{println!("bad2");}
}else{println!("bad3");}
},
crate::model::StageElementBehaviour::Platform=>(),
crate::model::StageElementBehaviour::JumpLimit(_)=>(),//TODO
}
},
Some(crate::model::TeleportBehaviour::Wormhole(wormhole))=>{
//telefart
}
None=>(),
}
run_teleport_behaviour(&general.teleport_behaviour,&mut self.game,&self.models,&self.modes,&self.style,&mut self.touching,&mut self.body,model);
},
}
},
PhysicsInstruction::CollisionEnd(c) => {
let model=c.model(&self.models).unwrap();
match &model.attributes{
PhysicsCollisionAttributes::Contact{contacting,general}=>{
PhysicsCollisionAttributes::Contact{contacting: _,general: _}=>{
self.touching.remove_contact(c.model);//remove contact before calling contact_constrain_acceleration
let mut a=self.style.gravity;
if let Some(rocket_force)=self.style.rocket_force{
a+=self.style.get_propulsion_control_dir(&self.camera,self.controls,&self.next_mouse,self.time)*rocket_force;
}
self.touching.constrain_acceleration(&self.models,&mut a);
self.body.acceleration=a;
//check ground
@ -1477,10 +1495,12 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
//TODO: make this more advanced checking contacts
self.move_state=MoveState::Air;
},
_=>self.refresh_walk_target(),
_=>if let Some(a)=self.refresh_walk_target(){
self.body.acceleration=a;
},
}
},
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
PhysicsCollisionAttributes::Intersect{intersecting: _,general: _}=>{
self.touching.remove_intersect(c.model);
},
}
@ -1554,7 +1574,14 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
PhysicsInputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
}
if refresh_walk_target{
self.refresh_walk_target();
if let Some(a)=self.refresh_walk_target(){
self.body.acceleration=a;
}else if let Some(rocket_force)=self.style.rocket_force{
let mut a=self.style.gravity;
a+=self.style.get_propulsion_control_dir(&self.camera,self.controls,&self.next_mouse,self.time)*rocket_force;
self.touching.constrain_acceleration(&self.models,&mut a);
self.body.acceleration=a;
}
}
},
}

@ -6,7 +6,7 @@ pub fn zeroes2(a0:Planar64,a1:Planar64,a2:Planar64) -> Vec<Planar64>{
if a2==Planar64::ZERO{
return zeroes1(a0, a1);
}
let mut radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
let radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
if 0<radicand {
//start with f64 sqrt
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});