use std::collections::{HashMap,HashSet};
use crate::mesh_query::MeshQuery;
use crate::minkowski::{MinkowskiMesh,MinkowskiFace};
use crate::model::{self as model_physics,PhysicsMesh,PhysicsMeshTransform,TransformedMesh,PhysicsMeshId,PhysicsSubmeshId};
use strafesnet_common::bvh;
use strafesnet_common::map;
use strafesnet_common::run;
use strafesnet_common::aabb;
use strafesnet_common::model::{MeshId,ModelId};
use strafesnet_common::gameplay_attributes::{self,CollisionAttributesId};
use strafesnet_common::gameplay_modes::{self,StageId};
use strafesnet_common::gameplay_style::{self,StyleModifiers};
use strafesnet_common::controls_bitflag::Controls;
use strafesnet_common::instruction::{self,InstructionEmitter,InstructionConsumer,InstructionFeedback,TimedInstruction};
use strafesnet_common::integer::{self,vec3,mat3,Planar64,Planar64Vec3,Planar64Mat3,Angle32,Ratio64Vec2};
pub use strafesnet_common::physics::{Time,TimeInner};
use gameplay::ModeState;

pub type Body=crate::body::Body<TimeInner>;
pub type Trajectory=crate::body::Trajectory<TimeInner>;
type MouseState=strafesnet_common::mouse::MouseState<TimeInner>;

//external influence
//this is how you influence the physics from outside
use strafesnet_common::physics::{Instruction,MouseInstruction,ModeInstruction,MiscInstruction,SetControlInstruction};

//internal influence
//when the physics asks itself what happens next, this is how it's represented
#[derive(Debug,Clone)]
pub enum InternalInstruction{
	CollisionStart(Collision,model_physics::GigaTime),
	CollisionEnd(Collision,model_physics::GigaTime),
	StrafeTick,
	// TODO: add GigaTime to ReachWalkTargetVelocity
	ReachWalkTargetVelocity,
	// Water,
}

#[derive(Clone,Debug)]
pub struct InputState{
	mouse:MouseState,
	next_mouse:MouseState,
	controls:Controls,
}
impl InputState{
	fn set_next_mouse(&mut self,next_mouse:MouseState){
		// would this be correct?
		// if self.next_mouse.time==next_mouse.time{
			// self.next_mouse=next_mouse;
		// }else{
		//I like your functions magic language
		self.mouse=std::mem::replace(&mut self.next_mouse,next_mouse);
		//equivalently:
		//(self.next_mouse,self.mouse)=(next_mouse,self.next_mouse.clone());
		// }
	}
	fn replace_mouse(&mut self,mouse:MouseState,next_mouse:MouseState){
		(self.next_mouse,self.mouse)=(next_mouse,mouse);
	}
	fn get_control(&self,control:Controls)->bool{
		self.controls.contains(control)
	}
	fn set_control(&mut self,control:Controls,state:bool){
		self.controls.set(control,state)
	}
	fn time_delta(&self)->Time{
		self.next_mouse.time-self.mouse.time
	}
	fn mouse_delta(&self)->glam::IVec2{
		self.next_mouse.pos-self.mouse.pos
	}
	fn lerp_delta(&self,time:Time)->glam::IVec2{
		//these are deltas
		let dm=self.mouse_delta().as_i64vec2();
		let t=(time-self.mouse.time).nanos();
		let dt=self.time_delta().nanos();
		((dm*t)/dt).as_ivec2()
	}
}
impl Default for InputState{
	fn default()->Self{
		Self{
			mouse:MouseState{pos:Default::default(),time:Time::ZERO-Time::EPSILON*2},
			next_mouse:MouseState{pos:Default::default(),time:Time::ZERO-Time::EPSILON},
			controls:Default::default(),
		}
	}
}
#[derive(Clone,Debug)]
enum JumpDirection{
	Exactly(Planar64Vec3),
	FromContactNormal,
}
impl JumpDirection{
	fn direction(&self,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,contact:&ContactCollision)->Planar64Vec3{
		match self{
			JumpDirection::FromContactNormal=>contact_normal(models,hitbox_mesh,&contact.convex_mesh_id,contact.face_id),
			&JumpDirection::Exactly(dir)=>dir,
		}
	}
}
#[derive(Clone,Debug)]
enum TransientAcceleration{
	Reached,
	Reachable{
		acceleration:Planar64Vec3,
		time:Time,
	},
	//walk target will never be reached
	Unreachable{
		acceleration:Planar64Vec3,
	}
}
#[derive(Clone,Debug)]
struct ContactMoveState{
	jump_direction:JumpDirection,
	// TODO: this is bad data normalization, remove this
	contact:ContactCollision,
	target:TransientAcceleration,
}
impl TransientAcceleration{
	fn with_target_diff(target_diff:Planar64Vec3,accel:Planar64,time:Time)->Self{
		if target_diff==vec3::zero(){
			TransientAcceleration::Reached
		}else if accel==Planar64::ZERO{
			TransientAcceleration::Unreachable{
				acceleration:vec3::zero()
			}
		}else{
			//normal friction acceleration is clippedAcceleration.dot(normal)*friction
			TransientAcceleration::Reachable{
				acceleration:target_diff.with_length(accel).divide().wrap_64(),
				time:time+Time::from((target_diff.length()/accel).divide().clamp_64())
			}
		}
	}
	fn ground(walk_settings:&gameplay_style::WalkSettings,body:&Body,gravity:Planar64Vec3,target_velocity:Planar64Vec3)->Self{
		let target_diff=target_velocity-body.velocity;
		//precalculate accel
		let accel=walk_settings.accel(target_diff,gravity);
		Self::with_target_diff(target_diff,accel,body.time)
	}
	fn ladder(ladder_settings:&gameplay_style::LadderSettings,body:&Body,gravity:Planar64Vec3,target_velocity:Planar64Vec3)->Self{
		let target_diff=target_velocity-body.velocity;
		let accel=ladder_settings.accel(target_diff,gravity);
		Self::with_target_diff(target_diff,accel,body.time)
	}
	fn acceleration(&self)->Planar64Vec3{
		match self{
			TransientAcceleration::Reached=>vec3::zero(),
			&TransientAcceleration::Reachable{acceleration,time:_}=>acceleration,
			&TransientAcceleration::Unreachable{acceleration}=>acceleration,
		}
	}
}
impl ContactMoveState{
	fn ground(walk_settings:&gameplay_style::WalkSettings,body:&Body,gravity:Planar64Vec3,target_velocity:Planar64Vec3,contact:ContactCollision)->Self{
		Self{
			target:TransientAcceleration::ground(walk_settings,body,gravity,target_velocity),
			contact,
			jump_direction:JumpDirection::Exactly(vec3::Y),
		}
	}
	fn ladder(ladder_settings:&gameplay_style::LadderSettings,body:&Body,gravity:Planar64Vec3,target_velocity:Planar64Vec3,contact:ContactCollision)->Self{
		Self{//,style,velocity,normal,style.ladder_speed,style.ladder_accel
			target:TransientAcceleration::ladder(ladder_settings,body,gravity,target_velocity),
			contact,
			jump_direction:JumpDirection::FromContactNormal,
		}
	}
}
fn ground_things(walk_settings:&gameplay_style::WalkSettings,contact:&ContactCollision,touching:&TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState)->(Planar64Vec3,Planar64Vec3){
	let normal=contact_normal(models,hitbox_mesh,&contact.convex_mesh_id,contact.face_id);
	let gravity=touching.base_acceleration(models,style,camera,input_state);
	let control_dir=style.get_y_control_dir(camera,input_state.controls);
	let target_velocity=walk_settings.get_walk_target_velocity(control_dir,normal);
	let target_velocity_clipped=touching.constrain_velocity(models,hitbox_mesh,target_velocity);
	(gravity,target_velocity_clipped)
}
fn ladder_things(ladder_settings:&gameplay_style::LadderSettings,contact:&ContactCollision,touching:&TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState)->(Planar64Vec3,Planar64Vec3){
	let normal=contact_normal(models,hitbox_mesh,&contact.convex_mesh_id,contact.face_id);
	let gravity=touching.base_acceleration(models,style,camera,input_state);
	let control_dir=style.get_y_control_dir(camera,input_state.controls);
	let target_velocity=ladder_settings.get_ladder_target_velocity(control_dir,normal);
	let target_velocity_clipped=touching.constrain_velocity(models,hitbox_mesh,target_velocity);
	(gravity,target_velocity_clipped)
}

#[derive(Default)]
struct PhysicsModels{
	meshes:HashMap<PhysicsMeshId,PhysicsMesh>,
	contact_models:HashMap<ContactModelId,ContactModel>,
	intersect_models:HashMap<IntersectModelId,IntersectModel>,
	contact_attributes:HashMap<ContactAttributesId,gameplay_attributes::ContactAttributes>,
	intersect_attributes:HashMap<IntersectAttributesId,gameplay_attributes::IntersectAttributes>,
}
impl PhysicsModels{
	#[expect(dead_code)]
	fn clear(&mut self){
		self.meshes.clear();
		self.contact_models.clear();
		self.intersect_models.clear();
		self.contact_attributes.clear();
		self.intersect_attributes.clear();
	}
	fn mesh(&self,convex_mesh_id:ConvexMeshId<PhysicsModelId>)->TransformedMesh<'_>{
		let (mesh_id,transform)=match convex_mesh_id.model_id{
			PhysicsModelId::Contact(model_id)=>{
				let model=&self.contact_models[&model_id];
				(&model.mesh_id,&model.transform)
			},
			PhysicsModelId::Intersect(model_id)=>{
				let model=&self.intersect_models[&model_id];
				(&model.mesh_id,&model.transform)
			},
		};
		TransformedMesh::new(
			self.meshes[mesh_id].submesh_view(convex_mesh_id.submesh_id),
			transform
		)
	}
	//it's a bit weird to have three functions, but it's always going to be one of these
	fn contact_mesh(&self,convex_mesh_id:&ConvexMeshId<ContactModelId>)->TransformedMesh<'_>{
		let model=&self.contact_models[&convex_mesh_id.model_id];
		TransformedMesh::new(
			self.meshes[&model.mesh_id].submesh_view(convex_mesh_id.submesh_id),
			&model.transform
		)
	}
	fn intersect_mesh(&self,convex_mesh_id:&ConvexMeshId<IntersectModelId>)->TransformedMesh<'_>{
		let model=&self.intersect_models[&convex_mesh_id.model_id];
		TransformedMesh::new(
			self.meshes[&model.mesh_id].submesh_view(convex_mesh_id.submesh_id),
			&model.transform
		)
	}
	fn get_model_transform(&self,model_id:ModelId)->Option<&PhysicsMeshTransform>{
		//ModelId can possibly be a decoration
		match self.contact_models.get(&model_id.into()){
			Some(model)=>Some(&model.transform),
			None=>self.intersect_models.get(&model_id.into())
				.map(|model|&model.transform),
		}
	}
	fn contact_attr(&self,model_id:ContactModelId)->&gameplay_attributes::ContactAttributes{
		&self.contact_attributes[&self.contact_models[&model_id].attr_id]
	}
	fn intersect_attr(&self,model_id:IntersectModelId)->&gameplay_attributes::IntersectAttributes{
		&self.intersect_attributes[&self.intersect_models[&model_id].attr_id]
	}
}

#[derive(Clone,Copy,Debug)]
pub struct PhysicsCamera{
	//punch: Planar64Vec3,
	//punch_velocity: Planar64Vec3,
	sensitivity:Ratio64Vec2,//dots to Angle32 ratios
	clamped_mouse_pos:glam::IVec2,//angles are calculated from this cumulative value
	//angle limits could be an enum + struct that defines whether it's limited and selects clamp or wrap depending
	// enum AngleLimit{
	// 	Unlimited,
	// 	Limited{lower:Angle32,upper:Angle32},
	// }
	//pitch_limit:AngleLimit,
	//yaw_limit:AngleLimit,
}

impl PhysicsCamera{
	const ANGLE_PITCH_LOWER_LIMIT:Angle32=Angle32::NEG_FRAC_PI_2;
	const ANGLE_PITCH_UPPER_LIMIT:Angle32=Angle32::FRAC_PI_2;
	fn set_sensitivity(&mut self,sensitivity:Ratio64Vec2){
		// Calculate nearest mouse position in new sensitivity
		self.clamped_mouse_pos.x=(self.clamped_mouse_pos.x as i128*self.sensitivity.x.num() as i128*sensitivity.x.den() as i128/(sensitivity.x.num() as i128*self.sensitivity.x.den() as i128)) as i32;
		self.clamped_mouse_pos.y=(self.clamped_mouse_pos.y as i128*self.sensitivity.y.num() as i128*sensitivity.y.den() as i128/(sensitivity.y.num() as i128*self.sensitivity.y.den() as i128)) as i32;
		self.sensitivity=sensitivity;
	}
	pub fn move_mouse(&mut self,mouse_delta:glam::IVec2){
		let mut unclamped_mouse_pos=self.clamped_mouse_pos+mouse_delta;
		unclamped_mouse_pos.y=unclamped_mouse_pos.y.clamp(
			self.sensitivity.y.rhs_div_int(Self::ANGLE_PITCH_LOWER_LIMIT.get() as i64) as i32,
			self.sensitivity.y.rhs_div_int(Self::ANGLE_PITCH_UPPER_LIMIT.get() as i64) as i32,
		);
		self.clamped_mouse_pos=unclamped_mouse_pos;
	}
	pub fn simulate_move_angles(&self,mouse_delta:glam::IVec2)->glam::Vec2{
		let a=-self.sensitivity.mul_int((self.clamped_mouse_pos+mouse_delta).as_i64vec2());
		let ax=Angle32::wrap_from_i64(a.x);
		let ay=Angle32::clamp_from_i64(a.y)
		//clamp to actual vertical cam limit
		.clamp(Self::ANGLE_PITCH_LOWER_LIMIT,Self::ANGLE_PITCH_UPPER_LIMIT);
		return glam::vec2(ax.into(),ay.into());
	}
	#[inline]
	fn get_rotation(&self,mouse_pos:glam::IVec2)->Planar64Mat3{
		let a=-self.sensitivity.mul_int(mouse_pos.as_i64vec2());
		let ax=Angle32::wrap_from_i64(a.x);
		let ay=Angle32::clamp_from_i64(a.y)
		//clamp to actual vertical cam limit
		.clamp(Self::ANGLE_PITCH_LOWER_LIMIT,Self::ANGLE_PITCH_UPPER_LIMIT);
		mat3::from_rotation_yx(ax,ay)
	}
	fn rotation(&self)->Planar64Mat3{
		self.get_rotation(self.clamped_mouse_pos)
	}
	#[expect(dead_code)]
	fn simulate_move_rotation(&self,mouse_delta:glam::IVec2)->Planar64Mat3{
		self.get_rotation(self.clamped_mouse_pos+mouse_delta)
	}
	fn get_rotation_y(&self,mouse_pos_x:i32)->Planar64Mat3{
		let ax=-self.sensitivity.x.mul_int(mouse_pos_x as i64);
		mat3::from_rotation_y(Angle32::wrap_from_i64(ax))
	}
	fn rotation_y(&self)->Planar64Mat3{
		self.get_rotation_y(self.clamped_mouse_pos.x)
	}
	fn simulate_move_rotation_y(&self,mouse_delta_x:i32)->Planar64Mat3{
		self.get_rotation_y(self.clamped_mouse_pos.x+mouse_delta_x)
	}
}

impl Default for PhysicsCamera{
	fn default()->Self{
		Self{
			sensitivity:Ratio64Vec2::ONE*200_000,
			clamped_mouse_pos:glam::IVec2::ZERO,
		}
	}
}
mod gameplay{
	use super::{gameplay_modes,HashSet,HashMap,ModelId};
	pub enum JumpIncrementResult{
		Allowed,
		ExceededLimit,
	}
	impl JumpIncrementResult{
		pub const fn is_allowed(self)->bool{
			matches!(self,JumpIncrementResult::Allowed)
		}
	}
	#[derive(Clone,Debug)]
	pub struct ModeState{
		mode_id:gameplay_modes::ModeId,
		stage_id:gameplay_modes::StageId,
		next_ordered_checkpoint_id:gameplay_modes::CheckpointId,//which OrderedCheckpoint model_id you must pass next (if 0 you haven't passed OrderedCheckpoint0)
		unordered_checkpoints:HashSet<ModelId>,
		jump_counts:HashMap<ModelId,u32>,//model_id -> jump count
	}
	impl ModeState{
		pub const fn get_mode_id(&self)->gameplay_modes::ModeId{
			self.mode_id
		}
		pub const fn get_stage_id(&self)->gameplay_modes::StageId{
			self.stage_id
		}
		pub const fn get_next_ordered_checkpoint_id(&self)->gameplay_modes::CheckpointId{
			self.next_ordered_checkpoint_id
		}
		fn increment_jump_count(&mut self,model_id:ModelId)->u32{
			*self.jump_counts.entry(model_id).and_modify(|c|*c+=1).or_insert(1)
		}
		pub fn try_increment_jump_count(&mut self,model_id:ModelId,jump_limit:Option<u8>)->JumpIncrementResult{
			match jump_limit{
				Some(jump_limit) if (jump_limit as u32)<self.increment_jump_count(model_id)=>JumpIncrementResult::ExceededLimit,
				_=>JumpIncrementResult::Allowed,
			}
		}
		pub const fn ordered_checkpoint_count(&self)->u32{
			self.next_ordered_checkpoint_id.get()
		}
		pub fn unordered_checkpoint_count(&self)->u32{
			self.unordered_checkpoints.len() as u32
		}
		#[expect(dead_code)]
		pub fn set_mode_id(&mut self,mode_id:gameplay_modes::ModeId){
			self.clear();
			self.mode_id=mode_id;
		}
		pub fn set_stage_id(&mut self,stage_id:gameplay_modes::StageId){
			self.clear_checkpoints();
			self.stage_id=stage_id;
		}
		pub fn accumulate_ordered_checkpoint(&mut self,stage:&gameplay_modes::Stage,model_id:ModelId){
			if stage.is_next_ordered_checkpoint(self.get_next_ordered_checkpoint_id(),model_id){
				self.next_ordered_checkpoint_id=gameplay_modes::CheckpointId::new(self.next_ordered_checkpoint_id.get()+1);
			}
		}
		pub fn accumulate_unordered_checkpoint(&mut self,stage:&gameplay_modes::Stage,model_id:ModelId){
			if stage.is_unordered_checkpoint(model_id){
				self.unordered_checkpoints.insert(model_id);
			}
		}
		pub fn clear(&mut self){
			self.clear_jump_counts();
			self.clear_checkpoints();
		}
		pub fn clear_jump_counts(&mut self){
			self.jump_counts.clear();
		}
		pub fn clear_checkpoints(&mut self){
			self.next_ordered_checkpoint_id=gameplay_modes::CheckpointId::FIRST;
			self.unordered_checkpoints.clear();
		}
	}
	impl Default for ModeState{
		fn default()->Self{
			Self{
				mode_id:gameplay_modes::ModeId::MAIN,
				stage_id:gameplay_modes::StageId::FIRST,
				next_ordered_checkpoint_id:gameplay_modes::CheckpointId::FIRST,
				unordered_checkpoints:HashSet::new(),
				jump_counts:HashMap::new(),
			}
		}
	}
}
#[derive(Clone,Debug)]
struct WorldState{}

struct HitboxMesh{
	halfsize:Planar64Vec3,
	mesh:PhysicsMesh,
	transform:PhysicsMeshTransform,
}
impl HitboxMesh{
	fn new(mesh:PhysicsMesh,transform:integer::Planar64Affine3)->Self{
		//calculate extents
		let mut aabb=aabb::Aabb::default();
		let transform=PhysicsMeshTransform::new(transform);
		let transformed_mesh=TransformedMesh::new(mesh.complete_mesh_view(),&transform);
		for vert in transformed_mesh.verts(){
			aabb.grow(vert.narrow_64().unwrap());
		}
		Self{
			halfsize:aabb.size()>>1,
			mesh,
			transform,
		}
	}
	#[inline]
	fn transformed_mesh(&self)->TransformedMesh<'_>{
		TransformedMesh::new(self.mesh.complete_mesh_view(),&self.transform)
	}
}

trait StyleHelper{
	fn get_control(&self,control:Controls,controls:Controls)->bool;
	fn get_control_dir(&self,controls:Controls)->Planar64Vec3;
	fn get_y_control_dir(&self,camera:&PhysicsCamera,controls:Controls)->Planar64Vec3;
	fn get_propulsion_control_dir(&self,camera:&PhysicsCamera,controls:Controls)->Planar64Vec3;
	fn calculate_mesh(&self)->HitboxMesh;
}
impl StyleHelper for StyleModifiers{
	fn get_control(&self,control:Controls,controls:Controls)->bool{
		controls.intersection(self.controls_mask).contains(control)
	}

	fn get_control_dir(&self,controls:Controls)->Planar64Vec3{
		//don't get fancy just do it
		let mut control_dir:Planar64Vec3=vec3::zero();
		//Apply mask after held check so you can require non-allowed keys to be held for some reason
		let controls=controls.intersection(self.controls_mask);
		if controls.contains(Controls::MoveForward){
			control_dir+=Self::FORWARD_DIR;
		}
		if controls.contains(Controls::MoveBackward){
			control_dir-=Self::FORWARD_DIR;
		}
		if controls.contains(Controls::MoveLeft){
			control_dir-=Self::RIGHT_DIR;
		}
		if controls.contains(Controls::MoveRight){
			control_dir+=Self::RIGHT_DIR;
		}
		if controls.contains(Controls::MoveUp){
			control_dir+=Self::UP_DIR;
		}
		if controls.contains(Controls::MoveDown){
			control_dir-=Self::UP_DIR;
		}
		return control_dir
	}

	fn get_y_control_dir(&self,camera:&PhysicsCamera,controls:Controls)->Planar64Vec3{
		(camera.rotation_y()*self.get_control_dir(controls)).wrap_64()
	}

	fn get_propulsion_control_dir(&self,camera:&PhysicsCamera,controls:Controls)->Planar64Vec3{
		//don't interpolate this! discrete mouse movement, constant acceleration
		(camera.rotation()*self.get_control_dir(controls)).wrap_64()
	}
	fn calculate_mesh(&self)->HitboxMesh{
		let mesh=match self.hitbox.mesh{
			gameplay_style::HitboxMesh::Box=>PhysicsMesh::unit_cube(),
			gameplay_style::HitboxMesh::Cylinder=>PhysicsMesh::unit_cylinder(),
		};
		let transform=integer::Planar64Affine3::new(
			mat3::from_diagonal(self.hitbox.halfsize),
			vec3::zero()
		);
		HitboxMesh::new(mesh,transform)
	}
}
#[derive(Clone,Debug)]
enum MoveState{
	Air,
	Walk(ContactMoveState),
	Ladder(ContactMoveState),
	#[expect(dead_code)]
	Water,
	Fly,
}
impl MoveState{
	//call this after state.move_state is changed
	fn acceleration(&self,touching:&TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState)->Planar64Vec3{
		match self{
			MoveState::Fly=>vec3::zero(),
			MoveState::Air
			|MoveState::Water
			=>{
				// calculate base acceleration
				let base_acceleration=touching.base_acceleration(models,style,camera,input_state);
				// constrain_acceleration clips according to contacts
				touching.constrain_acceleration(models,hitbox_mesh,base_acceleration)
			},
			MoveState::Walk(walk_state)
			|MoveState::Ladder(walk_state)
			=>walk_state.target.acceleration(),
		}
	}
	//function to coerce &mut self into &self
	fn update_fly_velocity(&self,body:&mut Body,touching:&TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState){
		match self{
			MoveState::Air=>(),
			MoveState::Water=>(),
			MoveState::Fly=>{
				//set velocity according to current control state
				let v=style.get_propulsion_control_dir(camera,input_state.controls)*80;
				//set_velocity clips velocity according to current touching state
				set_velocity(body,touching,models,hitbox_mesh,v);
			},
			MoveState::Walk(_walk_state)
			|MoveState::Ladder(_walk_state)
			=>(),
		}
	}
	/// changes the move state
	fn update_walk_target(&mut self,body:&Body,touching:&TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState){
		match self{
			MoveState::Fly
			|MoveState::Air
			|MoveState::Water=>(),
			MoveState::Walk(ContactMoveState{target,contact,jump_direction:_})=>{
				if let Some(walk_settings)=&style.walk{
					let (gravity,target_velocity)=ground_things(walk_settings,contact,touching,models,hitbox_mesh,style,camera,input_state);
					*target=TransientAcceleration::ground(walk_settings,body,gravity,target_velocity);
				}else{
					panic!("ContactMoveState exists in style which does not allow walking!");
				}
			},
			MoveState::Ladder(ContactMoveState{target,contact,jump_direction:_})=>{
				if let Some(ladder_settings)=&style.ladder{
					let (gravity,target_velocity)=ladder_things(ladder_settings,contact,touching,models,hitbox_mesh,style,camera,input_state);
					*target=TransientAcceleration::ladder(ladder_settings,body,gravity,target_velocity);
				}else{
					panic!("ContactMoveState exists in style which does not allow walking!");
				}
			},
		}
	}
	fn get_walk_state(&self)->Option<&ContactMoveState>{
		match self{
			MoveState::Walk(walk_state)
			|MoveState::Ladder(walk_state)
			=>Some(walk_state),
			MoveState::Air
			|MoveState::Water
			|MoveState::Fly
			=>None,
		}
	}
	fn next_move_instruction(&self,strafe:&Option<gameplay_style::StrafeSettings>,time:Time)->Option<TimedInstruction<InternalInstruction,Time>>{
		//check if you have a valid walk state and create an instruction
		match self{
			MoveState::Walk(walk_state)|MoveState::Ladder(walk_state)=>match &walk_state.target{
				&TransientAcceleration::Reachable{acceleration:_,time}=>Some(TimedInstruction{
					time,
					instruction:InternalInstruction::ReachWalkTargetVelocity
				}),
				TransientAcceleration::Unreachable{acceleration:_}
				|TransientAcceleration::Reached
				=>None,
			}
			MoveState::Air=>strafe.as_ref().map(|strafe|{
				TimedInstruction{
					time:strafe.next_tick(time),
					//only poll the physics if there is a before and after mouse event
					instruction:InternalInstruction::StrafeTick
				}
			}),
			MoveState::Water=>None,//TODO
			MoveState::Fly=>None,
		}
	}
	fn set_move_state(&mut self,move_state:MoveState,body:&mut Body,touching:&TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState){
		*self=move_state;
		//this function call reads the above state that was just set
		self.update_walk_target(body,touching,models,hitbox_mesh,style,camera,input_state);
		self.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state);
	}
	fn cull_velocity(&mut self,velocity:Planar64Vec3,body:&mut Body,touching:&mut TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState){
		//TODO: be more precise about contacts
		if set_velocity_cull(body,touching,models,hitbox_mesh,velocity){
			// TODO do better
			// TODO: unduplicate this code
			match self.get_walk_state(){
				// did you stop touching the thing you were walking on?
				Some(walk_state)=>if !touching.contains_contact(&walk_state.contact.convex_mesh_id){
					self.set_move_state(MoveState::Air,body,touching,models,hitbox_mesh,style,camera,input_state);
				}else{
					// stopped touching something else while walking
					self.update_walk_target(body,touching,models,hitbox_mesh,style,camera,input_state);
					self.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state);
				},
				// not walking, but stopped touching something
				None=>self.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state),
			}
		}
	}
}

#[derive(Clone,Hash,Eq,PartialEq)]
enum PhysicsCollisionAttributes{
	Contact(gameplay_attributes::ContactAttributes),
	Intersect(gameplay_attributes::IntersectAttributes),
}
struct NonPhysicsError;
impl TryFrom<&gameplay_attributes::CollisionAttributes> for PhysicsCollisionAttributes{
	type Error=NonPhysicsError;
	fn try_from(value:&gameplay_attributes::CollisionAttributes)->Result<Self,Self::Error>{
		match value{
			gameplay_attributes::CollisionAttributes::Decoration=>Err(NonPhysicsError),
			gameplay_attributes::CollisionAttributes::Contact(attr)=>Ok(Self::Contact(attr.clone())),
			gameplay_attributes::CollisionAttributes::Intersect(attr)=>Ok(Self::Intersect(attr.clone())),
		}
	}
}
#[derive(Clone,Copy,Hash,id::Id,Eq,PartialEq)]
struct ContactAttributesId(u32);
impl From<ContactAttributesId> for CollisionAttributesId{
	fn from(value:ContactAttributesId)->CollisionAttributesId{
		CollisionAttributesId::new(value.0)
	}
}
impl From<CollisionAttributesId> for ContactAttributesId{
	fn from(value:CollisionAttributesId)->Self{
		Self::new(value.get())
	}
}
#[derive(Clone,Copy,Hash,id::Id,Eq,PartialEq)]
struct IntersectAttributesId(u32);
impl From<IntersectAttributesId> for CollisionAttributesId{
	fn from(value:IntersectAttributesId)->CollisionAttributesId{
		CollisionAttributesId::new(value.0)
	}
}
impl From<CollisionAttributesId> for IntersectAttributesId{
	fn from(value:CollisionAttributesId)->Self{
		Self::new(value.get())
	}
}
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
struct ContactModelId(u32);
impl From<ContactModelId> for ModelId{
	fn from(value:ContactModelId)->ModelId{
		ModelId::new(value.get())
	}
}
impl From<ModelId> for ContactModelId{
	fn from(other: ModelId)->Self{
		Self::new(other.get())
	}
}
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
struct IntersectModelId(u32);
impl From<IntersectModelId> for ModelId{
	fn from(value:IntersectModelId)->ModelId{
		ModelId::new(value.get())
	}
}
impl From<ModelId> for IntersectModelId{
	fn from(other: ModelId)->Self{
		Self::new(other.get())
	}
}
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
enum PhysicsModelId{
	Contact(ContactModelId),
	Intersect(IntersectModelId),
}
impl From<PhysicsModelId> for ModelId{
	fn from(value:PhysicsModelId)->ModelId{
		ModelId::new(match value{
			PhysicsModelId::Contact(model_id)=>model_id.get(),
			PhysicsModelId::Intersect(model_id)=>model_id.get(),
		})
	}
}
//unique physics meshes indexed by this
#[derive(Debug,Clone,Copy,Eq,Hash,PartialEq)]
struct ConvexMeshId<Id>{
	model_id:Id,
	submesh_id:PhysicsSubmeshId,
}
impl<Id> ConvexMeshId<Id>{
	fn map<NewId>(self,model_id:NewId)->ConvexMeshId<NewId>{
		ConvexMeshId{
			model_id,
			submesh_id:self.submesh_id,
		}
	}
}
struct ContactModel{
	mesh_id:PhysicsMeshId,
	attr_id:ContactAttributesId,
	transform:PhysicsMeshTransform,
}
struct IntersectModel{
	mesh_id:PhysicsMeshId,
	attr_id:IntersectAttributesId,
	transform:PhysicsMeshTransform,
}

#[derive(Debug,Clone,Copy,Hash)]
pub struct ContactCollision{
	convex_mesh_id:ConvexMeshId<ContactModelId>,
	face_id:MinkowskiFace,
}
#[derive(Debug,Clone,Copy,Eq,Hash,PartialEq)]
pub struct IntersectCollision{
	convex_mesh_id:ConvexMeshId<IntersectModelId>,
}
#[derive(Debug,Clone,Hash)]
pub enum Collision{
	Contact(ContactCollision),
	Intersect(IntersectCollision),
}
impl Collision{
	fn new(convex_mesh_id:ConvexMeshId<PhysicsModelId>,face_id:MinkowskiFace)->Self{
		match convex_mesh_id.model_id{
			PhysicsModelId::Contact(model_id)=>Collision::Contact(ContactCollision{convex_mesh_id:convex_mesh_id.map(model_id),face_id}),
			PhysicsModelId::Intersect(model_id)=>Collision::Intersect(IntersectCollision{convex_mesh_id:convex_mesh_id.map(model_id)}),
		}
	}
}
#[derive(Clone,Debug,Default)]
struct TouchingState{
	// This is kind of jank, it's a ContactCollision
	// but split over the Key and Value of the HashMap.
	contacts:HashMap<ConvexMeshId<ContactModelId>,MinkowskiFace>,
	intersects:HashSet<ConvexMeshId<IntersectModelId>>,
}
impl TouchingState{
	fn clear(&mut self){
		self.contacts.clear();
		self.intersects.clear();
	}
	fn insert_contact(&mut self,contact:ContactCollision)->Option<MinkowskiFace>{
		self.contacts.insert(contact.convex_mesh_id,contact.face_id)
	}
	fn insert_intersect(&mut self,intersect:IntersectCollision)->bool{
		self.intersects.insert(intersect.convex_mesh_id)
	}
	fn remove_contact(&mut self,convex_mesh_id:&ConvexMeshId<ContactModelId>)->Option<MinkowskiFace>{
		self.contacts.remove(convex_mesh_id)
	}
	fn remove_intersect(&mut self,convex_mesh_id:&ConvexMeshId<IntersectModelId>)->bool{
		self.intersects.remove(convex_mesh_id)
	}
	fn contains_contact(&self,convex_mesh_id:&ConvexMeshId<ContactModelId>)->bool{
		self.contacts.contains_key(convex_mesh_id)
	}
	fn contains_intersect(&self,convex_mesh_id:&ConvexMeshId<IntersectModelId>)->bool{
		self.intersects.contains(convex_mesh_id)
	}
	fn contains(&self,convex_mesh_id:&ConvexMeshId<PhysicsModelId>)->bool{
		match convex_mesh_id.model_id{
			PhysicsModelId::Contact(contact_model_id)=>self.contains_contact(&convex_mesh_id.map(contact_model_id)),
			PhysicsModelId::Intersect(intersect_model_id)=>self.contains_intersect(&convex_mesh_id.map(intersect_model_id)),
		}
	}
	fn base_acceleration(&self,models:&PhysicsModels,style:&StyleModifiers,camera:&PhysicsCamera,input_state:&InputState)->Planar64Vec3{
		let mut a=style.gravity;
		if let Some(rocket_settings)=&style.rocket{
			a+=rocket_settings.acceleration(style.get_propulsion_control_dir(camera,input_state.controls));
		}
		//add accelerators
		for contact in self.contacts.keys(){
			if let Some(accelerator)=&models.contact_attr(contact.model_id).general.accelerator{
				a+=accelerator.acceleration;
			}
		}
		for intersect in &self.intersects{
			if let Some(accelerator)=&models.intersect_attr(intersect.model_id).general.accelerator{
				a+=accelerator.acceleration;
			}
		}
		//TODO: add water
		a
	}
	fn constrain_velocity(&self,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,velocity:Planar64Vec3)->Planar64Vec3{
		let contacts:Vec<_>=self.contacts.iter().map(|(convex_mesh_id,face_id)|{
			let n=contact_normal(models,hitbox_mesh,convex_mesh_id,*face_id);
			crate::push_solve::Contact{
				position:vec3::zero(),
				velocity:n,
				normal:n,
			}
		}).collect();
		crate::push_solve::push_solve(&contacts,velocity).0
	}
	fn constrain_acceleration(&self,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,acceleration:Planar64Vec3)->Planar64Vec3{
		let contacts:Vec<_>=self.contacts.iter().map(|(convex_mesh_id,face_id)|{
			let n=contact_normal(models,hitbox_mesh,convex_mesh_id,*face_id);
			crate::push_solve::Contact{
				position:vec3::zero(),
				velocity:n,
				normal:n,
			}
		}).collect();
		crate::push_solve::push_solve(&contacts,acceleration).0
	}
	fn predict_collision_end(&self,collector:&mut instruction::InstructionCollector<InternalInstruction,Time>,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,trajectory:&Trajectory,start_time:Time){
		// let relative_body=body.relative_to(&Body::ZERO);
		for (convex_mesh_id,face_id) in &self.contacts{
			//detect face slide off
			let model_mesh=models.contact_mesh(convex_mesh_id);
			let minkowski=MinkowskiMesh::minkowski_sum(model_mesh,hitbox_mesh.transformed_mesh());
			collector.collect(minkowski.predict_collision_face_out(&trajectory,start_time..collector.time(),*face_id).map(|(_face,time)|{
				TimedInstruction{
					time:trajectory.time+time.into(),
					instruction:InternalInstruction::CollisionEnd(
						Collision::Contact(ContactCollision{face_id:*face_id,convex_mesh_id:*convex_mesh_id}),
						time
					),
				}
			}));
		}
		for convex_mesh_id in &self.intersects{
			//detect model collision in reverse
			let model_mesh=models.intersect_mesh(convex_mesh_id);
			let minkowski=MinkowskiMesh::minkowski_sum(model_mesh,hitbox_mesh.transformed_mesh());
			collector.collect(minkowski.predict_collision_out(&trajectory,start_time..collector.time()).map(|(_face,time)|{
				TimedInstruction{
					time:trajectory.time+time.into(),
					instruction:InternalInstruction::CollisionEnd(
						Collision::Intersect(IntersectCollision{convex_mesh_id:*convex_mesh_id}),
						time
					),
				}
			}));
		}
	}
}

#[derive(Clone,Debug)]
pub struct PhysicsState{
	time:Time,
	body:Body,
	_world:WorldState,//currently there is only one state the world can be in
	touching:TouchingState,
	//camera must exist in state because wormholes modify the camera, also camera punch
	camera:PhysicsCamera,
	//input_state
	input_state:InputState,
	//style
	style:StyleModifiers,//mode style with custom style updates applied
	//gameplay_state
	mode_state:ModeState,
	move_state:MoveState,
	//run is non optional: when you spawn in a run is created
	//the run cannot be finished unless you start it by visiting
	//a start zone.  If you change mode, a new run is created.
	run:run::Run,
}

impl Default for PhysicsState{
	fn default()->Self{
 		Self{
			body:Body::new(vec3::int(0,50,0),vec3::int(0,0,0),Time::ZERO),
			time:Time::ZERO,
			style:StyleModifiers::default(),
			touching:TouchingState::default(),
			move_state:MoveState::Air,
			camera:PhysicsCamera::default(),
			input_state:InputState::default(),
			_world:WorldState{},
			mode_state:ModeState::default(),
			run:run::Run::new(),
		}
	}
}

impl PhysicsState{
	pub fn new_with_body(body:Body)->Self{
		Self{
			body,
			..Self::default()
		}
	}
	pub const fn body(&self)->&Body{
		&self.body
	}
	pub fn camera_trajectory(&self,data:&PhysicsData)->Trajectory{
		let acceleration=self.acceleration(data);
		Trajectory::new(
			self.body.position+self.style.camera_offset,
			self.body.velocity,
			acceleration,
			self.body.time,
		)
	}
	pub const fn camera(&self)->PhysicsCamera{
		self.camera
	}
	pub const fn mode(&self)->gameplay_modes::ModeId{
		self.mode_state.get_mode_id()
	}
	pub const fn style_mut(&mut self)->&mut StyleModifiers{
		&mut self.style
	}
	pub fn get_finish_time(&self)->Option<run::Time>{
		self.run.get_finish_time()
	}
	fn is_no_clip_enabled(&self)->bool{
		self.input_state.get_control(Controls::Sprint)
	}
	pub fn clear(&mut self){
		self.touching.clear();
	}
	fn reset_to_default(&mut self){
		*self=Self::default();
	}
	fn next_move_instruction(&self)->Option<TimedInstruction<InternalInstruction,Time>>{
		self.move_state.next_move_instruction(&self.style.strafe,self.time)
	}
	fn cull_velocity(&mut self,data:&PhysicsData,velocity:Planar64Vec3){
		self.move_state.cull_velocity(velocity,&mut self.body,&mut self.touching,&data.models,&data.hitbox_mesh,&self.style,&self.camera,&self.input_state);
	}
	fn set_move_state(&mut self,data:&PhysicsData,move_state:MoveState){
		self.move_state.set_move_state(move_state,&mut self.body,&self.touching,&data.models,&data.hitbox_mesh,&self.style,&self.camera,&self.input_state);
	}
	fn acceleration(&self,data:&PhysicsData)->Planar64Vec3{
		self.move_state.acceleration(&self.touching,&data.models,&data.hitbox_mesh,&self.style,&self.camera,&self.input_state)
	}
	//state mutated on collision:
	//Accelerator
	//stair step-up

	//state mutated on instruction
	//change fly acceleration (fly_sustain)
	//change fly velocity

	//generic event emmiters
	//PlatformStandTime
	//walk/swim/air/ladder sounds
	//VState?

	//falling under the map
	// fn next_respawn_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
	// 	if self.body.position<self.world.min_y {
	// 		return Some(TimedInstruction{
	// 			time:self.time,
	// 			instruction:PhysicsInstruction::Trigger(None)
	// 		});
	// 	}
	// }

	// fn next_water_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
	// 	return Some(TimedInstruction{
	// 		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
	// 		instruction:PhysicsInstruction::Water
	// 	});
	// }
}
// shared geometry for simulations
pub struct PhysicsData{
	//permanent map data
	bvh:bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	//transient map/environment data (open world loads/unloads parts of this data)
	models:PhysicsModels,
	//semi-transient data
	modes:gameplay_modes::Modes,
	//cached calculations
	hitbox_mesh:HitboxMesh,
}
impl PhysicsData{
	pub fn empty()->Self{
 		Self{
			bvh:bvh::BvhNode::empty(),
			models:Default::default(),
			modes:Default::default(),
			hitbox_mesh:StyleModifiers::default().calculate_mesh(),
		}
	}
	pub fn new(map:&map::CompleteMap)->Self{
		let modes=map.modes.clone().denormalize();
		let mut used_contact_attributes=Vec::new();
		let mut used_intersect_attributes=Vec::new();

		//temporary type for type safety lol
		#[derive(Clone,Copy,Hash,Eq,PartialEq)]
		enum PhysicsAttributesId{
			Contact(ContactAttributesId),
			Intersect(IntersectAttributesId),
		}

		let mut contact_models=HashMap::new();
		let mut intersect_models=HashMap::new();

		let mut physics_attr_id_from_model_attr_id=HashMap::<CollisionAttributesId,PhysicsAttributesId>::new();
		let mut used_meshes=Vec::new();
		let mut physics_mesh_id_from_model_mesh_id=HashMap::<MeshId,PhysicsMeshId>::new();
		for (model_id,model) in map.models.iter().enumerate(){
			let attr_id=match physics_attr_id_from_model_attr_id.entry(model.attributes){
				std::collections::hash_map::Entry::Occupied(entry)=>*entry.get(),
				std::collections::hash_map::Entry::Vacant(entry)=>{
					//check if it's real
					match map.attributes.get(model.attributes.get() as usize).and_then(|m_attr|{
						PhysicsCollisionAttributes::try_from(m_attr).map_or(None,|p_attr|{
							let attr_id=match p_attr{
								PhysicsCollisionAttributes::Contact(attr)=>{
									let attr_id=ContactAttributesId::new(used_contact_attributes.len() as u32);
									used_contact_attributes.push(attr);
									PhysicsAttributesId::Contact(attr_id)
								},
								PhysicsCollisionAttributes::Intersect(attr)=>{
									let attr_id=IntersectAttributesId::new(used_intersect_attributes.len() as u32);
									used_intersect_attributes.push(attr);
									PhysicsAttributesId::Intersect(attr_id)
								},
							};
							Some(*entry.insert(attr_id))
						})
					}){
						Some(attr_id)=>attr_id,
						None=>continue,
					}
				}
			};
			let mesh_id=if let Some(&mesh_id)=physics_mesh_id_from_model_mesh_id.get(&model.mesh){
				mesh_id
			}else{
				match map.meshes.get(model.mesh.get() as usize).and_then(|mesh|{
					match PhysicsMesh::try_from(mesh){
						Ok(physics_mesh)=>{
							let mesh_id=PhysicsMeshId::new(used_meshes.len() as u32);
							used_meshes.push(physics_mesh);
							physics_mesh_id_from_model_mesh_id.insert(model.mesh,mesh_id);
							Some(mesh_id)
						},
						Err(e)=>{
							println!("Failed to build PhysicsMesh: {e}");
							None
						}
					}
				}){
					Some(mesh_id)=>mesh_id,
					None=>continue,
				}
			};
			let transform=PhysicsMeshTransform::new(model.transform);
			match attr_id{
				PhysicsAttributesId::Contact(attr_id)=>{
					let contact_model_id=ContactModelId::new(model_id as u32);
					contact_models.insert(contact_model_id,ContactModel{
						mesh_id,
						attr_id,
						transform,
					});
				},
				PhysicsAttributesId::Intersect(attr_id)=>{
					let intersect_model_id=IntersectModelId::new(model_id as u32);
					intersect_models.insert(intersect_model_id,IntersectModel{
						mesh_id,
						attr_id,
						transform,
					});
				},
			}
		}
		let meshes:HashMap<PhysicsMeshId,PhysicsMesh>=used_meshes.into_iter()
			.enumerate()
			.map(|(mesh_id,mesh)|
				(PhysicsMeshId::new(mesh_id as u32),mesh)
			).collect();
		let convex_mesh_aabb_list=
		// use the map models iteration order to ensure that the
		// order that the models are passed into bvh::generate_bvh is consistent
		map.models.iter().enumerate().filter_map(|(model_id,model)|{
			match map.attributes.get(model.attributes.get() as usize){
				None|Some(gameplay_attributes::CollisionAttributes::Decoration)=>None,
				Some(gameplay_attributes::CollisionAttributes::Contact(_))=>{
					let model_id=ContactModelId::new(model_id as u32);
					let model=contact_models.get(&model_id)?;
					Some((PhysicsModelId::Contact(model_id),&model.mesh_id,&model.transform))
				},
				Some(gameplay_attributes::CollisionAttributes::Intersect(_))=>{
					let model_id=IntersectModelId::new(model_id as u32);
					let model=intersect_models.get(&model_id)?;
					Some((PhysicsModelId::Intersect(model_id),&model.mesh_id,&model.transform))
				},
			}
		})
		.flat_map(|(model_id,mesh_id,transform)|{
			meshes[mesh_id].submesh_views()
			.enumerate().map(move|(submesh_id,view)|{
				let mut aabb=aabb::Aabb::default();
				let transformed_mesh=TransformedMesh::new(view,transform);
				for v in transformed_mesh.verts(){
					aabb.grow(v.narrow_64().unwrap());
				}
				(ConvexMeshId{
					model_id,
					submesh_id:PhysicsSubmeshId::new(submesh_id as u32),
				},aabb)
			})
		}).collect();
		let bvh=bvh::generate_bvh(convex_mesh_aabb_list);
		let model_count=contact_models.len()+intersect_models.len();
		let models=PhysicsModels{
			meshes,
			contact_models,
			intersect_models,
			contact_attributes:used_contact_attributes.into_iter()
				.enumerate()
				.map(|(attr_id,attr)|
					(ContactAttributesId::new(attr_id as u32),attr)
				).collect(),
			intersect_attributes:used_intersect_attributes.into_iter()
				.enumerate()
				.map(|(attr_id,attr)|
					(IntersectAttributesId::new(attr_id as u32),attr)
				).collect(),
		};
		println!("Physics Objects: {}",model_count);
		Self{
			hitbox_mesh:StyleModifiers::default().calculate_mesh(),
			bvh,
			models,
			modes,
		}
	}
}
// the collection of information required to run physics
pub struct PhysicsContext<'a>{
	state:&'a mut PhysicsState,//this captures the entire state of the physics.
	data:&'a PhysicsData,//data currently loaded into memory which is needded for physics to run, but is not part of the state.
}
// the physics consumes both Instruction and PhysicsInternalInstruction,
// but can only emit PhysicsInternalInstruction
impl InstructionConsumer<InternalInstruction> for PhysicsContext<'_>{
	type Time=Time;
	fn process_instruction(&mut self,ins:TimedInstruction<InternalInstruction,Time>){
		atomic_internal_instruction(&mut self.state,&self.data,ins)
	}
}
impl InstructionConsumer<Instruction> for PhysicsContext<'_>{
	type Time=Time;
	fn process_instruction(&mut self,ins:TimedInstruction<Instruction,Time>){
		atomic_input_instruction(&mut self.state,&self.data,ins)
	}
}
impl InstructionEmitter<InternalInstruction> for PhysicsContext<'_>{
	type Time=Time;
	//this little next instruction function could cache its return value and invalidate the cached value by watching the State.
	fn next_instruction(&self,time_limit:Time)->Option<TimedInstruction<InternalInstruction,Time>>{
		next_instruction_internal(&self.state,&self.data,time_limit)
	}
}
impl<'a> PhysicsContext<'a>{
	pub fn run_input_instruction(
		state:&mut PhysicsState,
		data:&PhysicsData,
		instruction:TimedInstruction<Instruction,Time>
	){
		let mut context=PhysicsContext{state,data};
		context.process_exhaustive(instruction.time);
		context.process_instruction(instruction);
	}
	pub fn iter_internal(
		state:&'a mut PhysicsState,
		data:&'a PhysicsData,
		time_limit:Time,
	)->instruction::InstructionIter<InternalInstruction,Time,Self>{
		PhysicsContext{state,data}.into_iter(time_limit)
	}
}

//this is the one who asks
fn next_instruction_internal(state:&PhysicsState,data:&PhysicsData,time_limit:Time)->Option<TimedInstruction<InternalInstruction,Time>>{
	//JUST POLLING!!! NO MUTATION
	let mut collector=instruction::InstructionCollector::new(time_limit);

	collector.collect(state.next_move_instruction());

	let trajectory=state.body.with_acceleration(state.acceleration(data));
	//check for collision ends
	state.touching.predict_collision_end(&mut collector,&data.models,&data.hitbox_mesh,&trajectory,state.time);

	if state.is_no_clip_enabled(){
		return collector.take();
	}

	//check for collision starts
	let mut aabb=aabb::Aabb::default();
	trajectory.grow_aabb(&mut aabb,state.time,collector.time());
	aabb.inflate(data.hitbox_mesh.halfsize);
	//relative to moving platforms
	//let relative_body=state.body.relative_to(&Body::ZERO);
	data.bvh.sample_aabb(&aabb,&mut |convex_mesh_id|{
		if state.touching.contains(convex_mesh_id){
			return;
		}
		//no checks are needed because of the time limits.
		let model_mesh=data.models.mesh(*convex_mesh_id);
		let minkowski=MinkowskiMesh::minkowski_sum(model_mesh,data.hitbox_mesh.transformed_mesh());
		collector.collect(minkowski.predict_collision_in(&trajectory,state.time..collector.time())
			.map(|(face,dt)|
				TimedInstruction{
					time:trajectory.time+dt.into(),
					instruction:InternalInstruction::CollisionStart(
						Collision::new(*convex_mesh_id,face),
						dt
					)
				}
			)
		);
	});
	collector.take()
}


fn contact_normal(
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	convex_mesh_id:&ConvexMeshId<ContactModelId>,
    face_id:MinkowskiFace,
)->Planar64Vec3{
	let model_mesh=models.contact_mesh(convex_mesh_id);
	let minkowski=MinkowskiMesh::minkowski_sum(model_mesh,hitbox_mesh.transformed_mesh());
	// TODO: normalize to i64::MAX>>1
	// wrap for speed
	minkowski.face_nd(face_id).0.wrap_64()
}

fn recalculate_touching(
	move_state:&mut MoveState,
	body:&mut Body,
	touching:&mut TouchingState,
	run:&mut run::Run,
	mode_state:&mut ModeState,
	mode:Option<&gameplay_modes::Mode>,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	bvh:&bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	time:Time,
){
	//collision_end all existing contacts
	//I would have preferred while let Some(contact)=contacts.pop()
	//but there is no such method
	while let Some((&convex_mesh_id,_face_id))=touching.contacts.iter().next(){
		collision_end_contact(move_state,body,touching,models,hitbox_mesh,style,camera,input_state,models.contact_attr(convex_mesh_id.model_id),&convex_mesh_id)
	}
	while let Some(&convex_mesh_id)=touching.intersects.iter().next(){
		collision_end_intersect(move_state,body,touching,models,hitbox_mesh,style,camera,input_state,mode,run,models.intersect_attr(convex_mesh_id.model_id),&convex_mesh_id,time);
	}
	//find all models in the teleport region
	let mut aabb=aabb::Aabb::default();
	aabb.grow(body.position);
	aabb.inflate(hitbox_mesh.halfsize);
	//relative to moving platforms
	//let relative_body=state.body.relative_to(&Body::ZERO);
	bvh.sample_aabb(&aabb,&mut |&convex_mesh_id|{
		//no checks are needed because of the time limits.
		let model_mesh=models.mesh(convex_mesh_id);
		let minkowski=MinkowskiMesh::minkowski_sum(model_mesh,hitbox_mesh.transformed_mesh());
		if minkowski.contains_point(body.position){
			match convex_mesh_id.model_id{
				//being inside of contact objects is an invalid physics state
				//but the physics isn't advanced enough to do anything about it yet
				//TODO: PushSolve and search for the closest valid position
				PhysicsModelId::Contact(_)=>(),
				PhysicsModelId::Intersect(model_id)=>
				collision_start_intersect(move_state,body,mode_state,touching,mode,run,models,hitbox_mesh,bvh,style,camera,input_state,
					models.intersect_attr(model_id),
					IntersectCollision{
						convex_mesh_id:convex_mesh_id.map(model_id),
					},
					time,
				),
			}
		}
	});
}
fn set_position(
	point:Planar64Vec3,
	move_state:&mut MoveState,
	body:&mut Body,
	touching:&mut TouchingState,
	run:&mut run::Run,
	mode_state:&mut ModeState,
	mode:Option<&gameplay_modes::Mode>,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	bvh:&bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	time:Time,
)->Planar64Vec3{
	//test intersections at new position
	//hovering above the surface 0 units is not intersecting.  you will fall into it just fine
	body.position=point;
	//calculate contacts and determine the actual state
	recalculate_touching(move_state,body,touching,run,mode_state,mode,models,hitbox_mesh,bvh,style,camera,input_state,time);
	point
}
fn set_velocity_cull(body:&mut Body,touching:&mut TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,v:Planar64Vec3)->bool{
	//This is not correct but is better than what I have
	let mut culled=false;
	touching.contacts.retain(|convex_mesh_id,face_id|{
		let n=contact_normal(models,hitbox_mesh,convex_mesh_id,*face_id);
		let r=n.dot(v).is_positive();
		if r{
			culled=true;
		}
		!r
	});
	set_velocity(body,touching,models,hitbox_mesh,v);
	culled
}
fn set_velocity(body:&mut Body,touching:&TouchingState,models:&PhysicsModels,hitbox_mesh:&HitboxMesh,v:Planar64Vec3){
	body.velocity=touching.constrain_velocity(models,hitbox_mesh,v);
}

fn teleport(
	point:Planar64Vec3,
	move_state:&mut MoveState,
	body:&mut Body,
	touching:&mut TouchingState,
	run:&mut run::Run,
	mode_state:&mut ModeState,
	mode:Option<&gameplay_modes::Mode>,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	bvh:&bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	time:Time,
){
	set_position(point,move_state,body,touching,run,mode_state,mode,models,hitbox_mesh,bvh,style,camera,input_state,time);
}
enum TeleportToSpawnError{
	NoModel,
}
fn teleport_to_spawn(
	spawn_model_id:ModelId,
	move_state:&mut MoveState,
	body:&mut Body,
	touching:&mut TouchingState,
	run:&mut run::Run,
	mode_state:&mut ModeState,
	mode:&gameplay_modes::Mode,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	bvh:&bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	time:Time,
)->Result<(),TeleportToSpawnError>{
	//jump count and checkpoints are always reset on teleport_to_spawn.
	//Map makers are expected to use tools to prevent
	//multi-boosting on JumpLimit boosters such as spawning into a SetVelocity
	mode_state.clear();
	const EPSILON:Planar64=Planar64::raw((1<<32)/16);
	let transform=models.get_model_transform(spawn_model_id).ok_or(TeleportToSpawnError::NoModel)?;
	//TODO: transform.vertex.matrix3.col(1)+transform.vertex.translation
	let point=transform.vertex.transform_point3(vec3::Y).clamp_64()+Planar64Vec3::new([Planar64::ZERO,style.hitbox.halfsize.y+EPSILON,Planar64::ZERO]);
	teleport(point,move_state,body,touching,run,mode_state,Some(mode),models,hitbox_mesh,bvh,style,camera,input_state,time);
	Ok(())
}

struct CheckpointCheckOutcome{
	set_stage:Option<StageId>,
	teleport_to_model:Option<ModelId>,
}

// stage_element.touch_result(mode,mode_state)
fn checkpoint_check(
	mode_state:&ModeState,
	stage_element:&gameplay_modes::StageElement,
	mode:&gameplay_modes::Mode,
)->CheckpointCheckOutcome{
	let current_stage_id=mode_state.get_stage_id();
	let target_stage_id=stage_element.stage_id();
	if current_stage_id<target_stage_id{
		//checkpoint check
		//check if current stage is complete
		if let Some(current_stage)=mode.get_stage(current_stage_id){
			if !current_stage.is_complete(mode_state.ordered_checkpoint_count(),mode_state.unordered_checkpoint_count()){
				return CheckpointCheckOutcome{
					set_stage:None,
					teleport_to_model:Some(current_stage.spawn()),
				};
			}
		}
		//check if all between stages have no checkpoints required to pass them
		for stage_id in current_stage_id.get()+1..target_stage_id.get(){
			let stage_id=StageId::new(stage_id);
			//check if none of the between stages has checkpoints, if they do teleport back to that stage
			match mode.get_stage(stage_id){
				Some(stage)=>if !stage.is_empty(){
					return CheckpointCheckOutcome{
						set_stage:Some(stage_id),
						teleport_to_model:Some(stage.spawn()),
					};
				},
				//no such stage! set to last existing stage
				None=>return CheckpointCheckOutcome{
					set_stage:Some(StageId::new(stage_id.get()-1)),
					teleport_to_model:None,
				},
			}
		};
		//notably you do not get teleported for touching ordered checkpoints in the wrong order within the same stage.
		return CheckpointCheckOutcome{
			set_stage:Some(target_stage_id),
			teleport_to_model:None,
		};
	}else if stage_element.force(){
		//forced stage_element will set the stage_id even if the stage has already been passed
		return CheckpointCheckOutcome{
			set_stage:Some(target_stage_id),
			teleport_to_model:None,
		};
	}
	CheckpointCheckOutcome{
		set_stage:None,
		teleport_to_model:None,
	}
}

fn run_teleport_behaviour(
	model_id:ModelId,
	wormhole:Option<&gameplay_attributes::Wormhole>,
	mode:Option<&gameplay_modes::Mode>,
	move_state:&mut MoveState,
	body:&mut Body,
	touching:&mut TouchingState,
	run:&mut run::Run,
	mode_state:&mut ModeState,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	bvh:&bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	time:Time,
){
	if let Some(mode)=mode{
		if let Some(stage_element)=mode.get_element(model_id){
			if let Some(stage)=mode.get_stage(stage_element.stage_id()){
				let CheckpointCheckOutcome{set_stage,teleport_to_model}=checkpoint_check(mode_state,stage_element,mode);
				if let Some(stage_id)=set_stage{
					mode_state.set_stage_id(stage_id);
				}
				if let Some(model_id)=teleport_to_model{
					let _=teleport_to_spawn(model_id,move_state,body,touching,run,mode_state,mode,models,hitbox_mesh,bvh,style,camera,input_state,time);
					return;
				}
				match stage_element.behaviour(){
					gameplay_modes::StageElementBehaviour::SpawnAt=>(),
					gameplay_modes::StageElementBehaviour::Trigger
					|gameplay_modes::StageElementBehaviour::Teleport=>if let Some(mode_state_stage)=mode.get_stage(mode_state.get_stage_id()){
						//I guess this is correct behaviour when trying to teleport to a non-existent spawn but it's still weird
						let _=teleport_to_spawn(mode_state_stage.spawn(),move_state,body,touching,run,mode_state,mode,models,hitbox_mesh,bvh,style,camera,input_state,time);
						return;
					},
					gameplay_modes::StageElementBehaviour::Platform=>(),
					gameplay_modes::StageElementBehaviour::Check=>(),//this is to run the checkpoint check behaviour without any other side effects
					gameplay_modes::StageElementBehaviour::Checkpoint=>{
						//each of these checks if the model is actually a valid respective checkpoint object
						//accumulate sequential ordered checkpoints
						mode_state.accumulate_ordered_checkpoint(&stage,model_id);
						//insert model id in accumulated unordered checkpoints
						mode_state.accumulate_unordered_checkpoint(&stage,model_id);
					},
				}
			}
		}
	}
	if let Some(&gameplay_attributes::Wormhole{destination_model})=wormhole{
		if let (Some(origin),Some(destination))=(models.get_model_transform(model_id),models.get_model_transform(destination_model)){
			let point=body.position-origin.vertex.translation+destination.vertex.translation;
			//TODO: camera angles
			teleport(point,move_state,body,touching,run,mode_state,mode,models,hitbox_mesh,bvh,style,camera,input_state,time);
		}
	}
}

fn is_not_spawn_at(
	mode:Option<&gameplay_modes::Mode>,
	model_id:ModelId,
)->bool{
	if let Some(mode)=mode{
		if let Some(stage_element)=mode.get_element(model_id){
			return stage_element.behaviour()!=gameplay_modes::StageElementBehaviour::SpawnAt;
		}
	}
	true
}

fn collision_start_contact(
	move_state:&mut MoveState,
	body:&mut Body,
	mode_state:&mut ModeState,
	touching:&mut TouchingState,
	run:&mut run::Run,
	mode:Option<&gameplay_modes::Mode>,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	bvh:&bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	attr:&gameplay_attributes::ContactAttributes,
	contact:ContactCollision,
	time:Time,
){
	let incident_velocity=body.velocity;
	//add to touching
	touching.insert_contact(contact);
	//clip v
	set_velocity(body,touching,models,hitbox_mesh,incident_velocity);
	let mut allow_jump=true;
	let model_id=contact.convex_mesh_id.model_id.into();
	let mut allow_run_teleport_behaviour=is_not_spawn_at(mode,model_id);
	match &attr.contacting.contact_behaviour{
		Some(gameplay_attributes::ContactingBehaviour::Surf)=>(),
		Some(gameplay_attributes::ContactingBehaviour::Cling)=>println!("Unimplemented!"),
		&Some(gameplay_attributes::ContactingBehaviour::Elastic(elasticity))=>{
			let reflected_velocity=body.velocity+((body.velocity-incident_velocity)*Planar64::raw(elasticity as i64+1)).wrap_64();
			set_velocity(body,touching,models,hitbox_mesh,reflected_velocity);
		},
		Some(gameplay_attributes::ContactingBehaviour::Ladder(contacting_ladder))=>
		if let Some(ladder_settings)=&style.ladder{
			if contacting_ladder.sticky{
				//kill v
				//actually you could do this with a booster attribute :thinking:
				//it's a little bit different because maybe you want to chain ladders together
				set_velocity(body,touching,models,hitbox_mesh,vec3::zero());//model.velocity
			}
			//ladder walkstate
			let (gravity,target_velocity)=ladder_things(ladder_settings,&contact,touching,models,hitbox_mesh,style,camera,input_state);
			let walk_state=ContactMoveState::ladder(ladder_settings,body,gravity,target_velocity,contact);
			move_state.set_move_state(MoveState::Ladder(walk_state),body,touching,models,hitbox_mesh,style,camera,input_state);
		},
		Some(gameplay_attributes::ContactingBehaviour::NoJump)=>allow_jump=false,
		None=>if let Some(walk_settings)=&style.walk{
			if walk_settings.is_slope_walkable(contact_normal(models,hitbox_mesh,&contact.convex_mesh_id,contact.face_id),vec3::Y){
				allow_run_teleport_behaviour=true;
				//ground
				let (gravity,target_velocity)=ground_things(walk_settings,&contact,touching,models,hitbox_mesh,style,camera,input_state);
				let walk_state=ContactMoveState::ground(walk_settings,body,gravity,target_velocity,contact);
				move_state.set_move_state(MoveState::Walk(walk_state),body,touching,models,hitbox_mesh,style,camera,input_state);
			}
		},
	}
	match &attr.general.trajectory{
		Some(trajectory)=>{
			match trajectory{
				gameplay_attributes::SetTrajectory::AirTime(_)=>todo!(),
				gameplay_attributes::SetTrajectory::Height(_)=>todo!(),
				gameplay_attributes::SetTrajectory::TargetPointTime{..}=>todo!(),
				gameplay_attributes::SetTrajectory::TargetPointSpeed{..}=>todo!(),
				&gameplay_attributes::SetTrajectory::Velocity(velocity)=>{
					move_state.cull_velocity(velocity,body,touching,models,hitbox_mesh,style,camera,input_state);
				},
				gameplay_attributes::SetTrajectory::DotVelocity{..}=>todo!(),
			}
		},
		None=>(),
	}
	//I love making functions with 10 arguments to dodge the borrow checker
	if allow_run_teleport_behaviour{
		run_teleport_behaviour(model_id,attr.general.wormhole.as_ref(),mode,move_state,body,touching,run,mode_state,models,hitbox_mesh,bvh,style,camera,input_state,time);
	}
	if allow_jump&&style.get_control(Controls::Jump,input_state.controls){
		if let (Some(jump_settings),Some(walk_state))=(&style.jump,move_state.get_walk_state()){
			let mut exceeded_jump_limit=false;
			if let Some(mode)=mode{
				if let Some(stage_element)=mode.get_element(model_id){
					if !mode_state.try_increment_jump_count(model_id,stage_element.jump_limit()).is_allowed(){
						exceeded_jump_limit=true;
					}
				}
			}
			if exceeded_jump_limit{
				if let Some(mode)=mode{
					if let Some(spawn_model_id)=mode.get_spawn_model_id(mode_state.get_stage_id()){
						let _=teleport_to_spawn(spawn_model_id,move_state,body,touching,run,mode_state,mode,models,hitbox_mesh,bvh,style,camera,input_state,time);
					}
				}
			}else{
				let jump_dir=walk_state.jump_direction.direction(models,hitbox_mesh,&walk_state.contact);
				let jumped_velocity=jump_settings.jumped_velocity(style,jump_dir,body.velocity,attr.general.booster.as_ref());
				move_state.cull_velocity(jumped_velocity,body,touching,models,hitbox_mesh,style,camera,input_state);
			}
		}
	}
	//doing enum to set the acceleration when surfing
	//doing input_and_body to refresh the walk state if you hit a wall while accelerating
	move_state.update_walk_target(body,touching,models,hitbox_mesh,style,camera,input_state);
	move_state.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state);
}

fn collision_start_intersect(
	move_state:&mut MoveState,
	body:&mut Body,
	mode_state:&mut ModeState,
	touching:&mut TouchingState,
	mode:Option<&gameplay_modes::Mode>,
	run:&mut run::Run,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	bvh:&bvh::BvhNode<ConvexMeshId<PhysicsModelId>>,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	attr:&gameplay_attributes::IntersectAttributes,
	intersect:IntersectCollision,
	time:Time,
){
	//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
	touching.insert_intersect(intersect);
	//insta booster!
	if let Some(booster)=&attr.general.booster{
		move_state.cull_velocity(booster.boost(body.velocity),body,touching,models,hitbox_mesh,style,camera,input_state);
	}
	if let Some(mode)=mode{
		let zone=mode.get_zone(intersect.convex_mesh_id.model_id.into());
		match zone{
			Some(gameplay_modes::Zone::Start)=>{
				println!("@@@@ Starting new run!");
				*run=run::Run::new();
			},
			Some(gameplay_modes::Zone::Finish)=>{
				match run.finish(time){
					Ok(())=>{
						let time=run.time(time);
						let h=time.get()/(Time::ONE_SECOND.get()*60*60);
						let m=(time.get()/(Time::ONE_SECOND.get()*60)).rem_euclid(60);
						let s=(time.get()/(Time::ONE_SECOND.get())).rem_euclid(60);
						let ms=(time.get()/(Time::ONE_MILLISECOND.get())).rem_euclid(1000);
						let us=(time.get()/(Time::ONE_MICROSECOND.get())).rem_euclid(1000);
						let ns=(time.get()/(Time::ONE_NANOSECOND.get())).rem_euclid(1000);
						if h==0{
							println!("@@@@ Finished run time={m:02}:{s:02}.{ms:03}_{us:03}_{ns:03}");
						}else{
							println!("@@@@ Finished run time={h}:{m:02}:{s:02}.{ms:03}_{us:03}_{ns:03}");
						}
					},
					Err(e)=>println!("@@@@ Run Finish error:{e:?}"),
				}
			},
			Some(gameplay_modes::Zone::Anticheat)=>run.flag(run::FlagReason::Anticheat),
			None=>(),
		}
	}
	move_state.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state);
	run_teleport_behaviour(intersect.convex_mesh_id.model_id.into(),attr.general.wormhole.as_ref(),mode,move_state,body,touching,run,mode_state,models,hitbox_mesh,bvh,style,camera,input_state,time);
}

fn collision_end_contact(
	move_state:&mut MoveState,
	body:&mut Body,
	touching:&mut TouchingState,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	_attr:&gameplay_attributes::ContactAttributes,
	convex_mesh_id:&ConvexMeshId<ContactModelId>,
){
	touching.remove_contact(convex_mesh_id);//remove contact before calling contact_constrain_acceleration
	//check ground
	//TODO do better
	//this is inner code from move_state.cull_velocity
	match move_state.get_walk_state(){
		// did you stop touching the thing you were walking on?
		// This does not check the face! Is that a bad thing? It should be
		// impossible to stop touching a different face than you started touching...
		Some(walk_state)=>if &walk_state.contact.convex_mesh_id==convex_mesh_id{
			move_state.set_move_state(MoveState::Air,body,touching,models,hitbox_mesh,style,camera,input_state);
		}else{
			// stopped touching something else while walking
			move_state.update_walk_target(body,touching,models,hitbox_mesh,style,camera,input_state);
			move_state.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state);
		},
		// not walking, but stopped touching something
		None=>move_state.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state),
	}
}
fn collision_end_intersect(
	move_state:&mut MoveState,
	body:&mut Body,
	touching:&mut TouchingState,
	models:&PhysicsModels,
	hitbox_mesh:&HitboxMesh,
	style:&StyleModifiers,
	camera:&PhysicsCamera,
	input_state:&InputState,
	mode:Option<&gameplay_modes::Mode>,
	run:&mut run::Run,
	_attr:&gameplay_attributes::IntersectAttributes,
	convex_mesh_id:&ConvexMeshId<IntersectModelId>,
	time:Time,
){
	touching.remove_intersect(convex_mesh_id);
	move_state.update_fly_velocity(body,touching,models,hitbox_mesh,style,camera,input_state);
	if let Some(mode)=mode{
		let zone=mode.get_zone(convex_mesh_id.model_id.into());
		match zone{
			Some(gameplay_modes::Zone::Start)=>{
				match run.start(time){
					Ok(())=>println!("@@@@ Started run"),
					Err(e)=>println!("@@@@ Run Start error:{e:?}"),
				}
			},
			_=>(),
		}
	}
}
fn atomic_internal_instruction(state:&mut PhysicsState,data:&PhysicsData,ins:TimedInstruction<InternalInstruction,Time>){
	state.time=ins.time;
	match ins.instruction{
		// collisions advance the body precisely
		InternalInstruction::CollisionStart(_,dt)
		|InternalInstruction::CollisionEnd(_,dt)=>{
			state.body=state.body.with_acceleration(state.acceleration(data)).extrapolated_body_ratio_dt(dt);
		},
		// this advances imprecisely
		InternalInstruction::ReachWalkTargetVelocity=>state.body=state.body.with_acceleration(state.acceleration(data)).extrapolated_body(state.time),
		// strafe tick decides for itself whether to advance the body.
		InternalInstruction::StrafeTick=>(),
	}
	match ins.instruction{
		InternalInstruction::CollisionStart(collision,_)=>{
			let mode=data.modes.get_mode(state.mode_state.get_mode_id());
			match collision{
				Collision::Contact(contact)=>collision_start_contact(
					&mut state.move_state,&mut state.body,&mut state.mode_state,&mut state.touching,&mut state.run,
					mode,
					&data.models,&data.hitbox_mesh,&data.bvh,&state.style,&state.camera,&state.input_state,
					data.models.contact_attr(contact.convex_mesh_id.model_id),
					contact,
					state.time,
				),
				Collision::Intersect(intersect)=>collision_start_intersect(
					&mut state.move_state,&mut state.body,&mut state.mode_state,&mut state.touching,
					mode,
					&mut state.run,&data.models,&data.hitbox_mesh,&data.bvh,&state.style,&state.camera,&state.input_state,
					data.models.intersect_attr(intersect.convex_mesh_id.model_id),
					intersect,
					state.time,
				),
			}
		},
		InternalInstruction::CollisionEnd(collision,_)=>match collision{
			Collision::Contact(contact)=>collision_end_contact(
				&mut state.move_state,&mut state.body,&mut state.touching,&data.models,&data.hitbox_mesh,&state.style,&state.camera,&state.input_state,
				data.models.contact_attr(contact.convex_mesh_id.model_id),
				&contact.convex_mesh_id
			),
			Collision::Intersect(intersect)=>collision_end_intersect(
				&mut state.move_state,&mut state.body,&mut state.touching,&data.models,&data.hitbox_mesh,&state.style,&state.camera,&state.input_state,
				data.modes.get_mode(state.mode_state.get_mode_id()),
				&mut state.run,
				data.models.intersect_attr(intersect.convex_mesh_id.model_id),
				&intersect.convex_mesh_id,
				state.time
			),
		},
		InternalInstruction::StrafeTick=>{
			//TODO make this less huge
			if let Some(strafe_settings)=&state.style.strafe{
				let controls=state.input_state.controls;
				if strafe_settings.activates(controls){
					let masked_controls=strafe_settings.mask(controls);
					let control_dir=state.style.get_control_dir(masked_controls);
					if control_dir!=vec3::zero(){
						// manually advance time
						let extrapolated_body=state.body.with_acceleration(state.acceleration(data)).extrapolated_body(state.time);
						let camera_mat=state.camera.simulate_move_rotation_y(state.input_state.lerp_delta(state.time).x);
						if let Some(ticked_velocity)=strafe_settings.tick_velocity(extrapolated_body.velocity,(camera_mat*control_dir).with_length(Planar64::ONE).divide().wrap_64()){
							state.body=extrapolated_body;
							//this is wrong but will work ig
							//need to note which push planes activate in push solve and keep those
							state.cull_velocity(data,ticked_velocity);
						}
					}
				}
			}
		}
		InternalInstruction::ReachWalkTargetVelocity=>{
			match &mut state.move_state{
				MoveState::Air
				|MoveState::Water
				|MoveState::Fly
				=>println!("ReachWalkTargetVelocity fired for non-walking MoveState"),
				MoveState::Walk(walk_state)|MoveState::Ladder(walk_state)=>{
					//velocity is already handled by extrapolated_body
					//we know that the acceleration is precisely zero because the walk target is known to be reachable
					//which means that gravity can be fully cancelled
					//ignore moving platforms for now
					let target=core::mem::replace(&mut walk_state.target,TransientAcceleration::Reached);
					// check what the target was to see if it was invalid
					match target{
						//you are not supposed to reach a walk target which is already reached!
						TransientAcceleration::Reached=>println!("Invalid walk target: Reached"),
						TransientAcceleration::Reachable{..}=>(),
						//you are not supposed to reach an unreachable walk target!
						TransientAcceleration::Unreachable{..}=>println!("Invalid walk target: Unreachable"),
					}
				}
			}
		},
	}
}

fn atomic_input_instruction(state:&mut PhysicsState,data:&PhysicsData,ins:TimedInstruction<Instruction,Time>){
	state.time=ins.time;
	let should_advance_body=match ins.instruction{
		//the body may as well be a quantum wave function
		//as far as these instruction are concerned (they don't care where it is)
		Instruction::Misc(MiscInstruction::SetSensitivity(..))
		|Instruction::Mode(_)
		|Instruction::SetControl(SetControlInstruction::SetZoom(..))
		|Instruction::Idle=>false,
		//these controls only update the body if you are on the ground
		Instruction::Mouse(_)
		|Instruction::SetControl(_)=>{
			match &state.move_state{
				MoveState::Fly
				|MoveState::Water
				|MoveState::Walk(_)
				|MoveState::Ladder(_)=>true,
				MoveState::Air=>false,
			}
		},
		//the body must be updated unconditionally
		Instruction::Misc(MiscInstruction::PracticeFly)=>true,
	};
	if should_advance_body{
		state.body=state.body.with_acceleration(state.acceleration(data)).extrapolated_body(state.time);
	}

	let mut b_refresh_walk_target=true;
	match ins.instruction{
		Instruction::Mouse(MouseInstruction::SetNextMouse(m))=>{
			state.camera.move_mouse(state.input_state.mouse_delta());
			state.input_state.set_next_mouse(m);
		},
		Instruction::Mouse(MouseInstruction::ReplaceMouse{m0,m1})=>{
			state.camera.move_mouse(state.input_state.mouse_delta());
			state.camera.move_mouse(m0.pos-state.input_state.next_mouse.pos);
			state.input_state.replace_mouse(m0,m1);
		},
		Instruction::Misc(MiscInstruction::SetSensitivity(sensitivity))=>state.camera.set_sensitivity(sensitivity),
		Instruction::SetControl(SetControlInstruction::SetMoveForward(s))=>state.input_state.set_control(Controls::MoveForward,s),
		Instruction::SetControl(SetControlInstruction::SetMoveLeft(s))=>state.input_state.set_control(Controls::MoveLeft,s),
		Instruction::SetControl(SetControlInstruction::SetMoveBack(s))=>state.input_state.set_control(Controls::MoveBackward,s),
		Instruction::SetControl(SetControlInstruction::SetMoveRight(s))=>state.input_state.set_control(Controls::MoveRight,s),
		Instruction::SetControl(SetControlInstruction::SetMoveUp(s))=>state.input_state.set_control(Controls::MoveUp,s),
		Instruction::SetControl(SetControlInstruction::SetMoveDown(s))=>state.input_state.set_control(Controls::MoveDown,s),
		Instruction::SetControl(SetControlInstruction::SetJump(s))=>{
			state.input_state.set_control(Controls::Jump,s);
			if let Some(walk_state)=state.move_state.get_walk_state(){
				if let Some(jump_settings)=&state.style.jump{
					let jump_dir=walk_state.jump_direction.direction(&data.models,&data.hitbox_mesh,&walk_state.contact);
					let booster_option=data.models.contact_attr(walk_state.contact.convex_mesh_id.model_id).general.booster.as_ref();
					let jumped_velocity=jump_settings.jumped_velocity(&state.style,jump_dir,state.body.velocity,booster_option);
					state.cull_velocity(data,jumped_velocity);
				}
			}
			b_refresh_walk_target=false;
		},
		Instruction::SetControl(SetControlInstruction::SetZoom(s))=>{
			state.input_state.set_control(Controls::Zoom,s);
			b_refresh_walk_target=false;
		},
		Instruction::SetControl(SetControlInstruction::SetSprint(s))=>{
			state.input_state.set_control(Controls::Sprint,s);
		},
		Instruction::Mode(ModeInstruction::Reset)=>{
			//totally reset physics state
			state.reset_to_default();
			b_refresh_walk_target=false;
		},
		Instruction::Mode(ModeInstruction::Restart(mode_id))=>{
			//teleport to mode start zone
			let mut spawn_point=vec3::zero();
			let mode=data.modes.get_mode(mode_id);
			if let Some(mode)=mode{
				// set style
				state.style=mode.get_style().clone();
				//TODO: spawn at the bottom of the start zone plus the hitbox size
				//TODO: set camera angles to face the same way as the start zone
				if let Some(transform)=data.models.get_model_transform(mode.get_start()){
					// NOTE: this value may be 0,0,0 on source maps
					spawn_point=transform.vertex.translation;
				}
			}
			set_position(spawn_point,&mut state.move_state,&mut state.body,&mut state.touching,&mut state.run,&mut state.mode_state,mode,&data.models,&data.hitbox_mesh,&data.bvh,&state.style,&state.camera,&state.input_state,state.time);
			set_velocity(&mut state.body,&state.touching,&data.models,&data.hitbox_mesh,vec3::zero());
			state.set_move_state(data,MoveState::Air);
			b_refresh_walk_target=false;
		}
		// Spawn does not necessarily imply reset
		Instruction::Mode(ModeInstruction::Spawn(mode_id,stage_id))=>{
			//spawn at a particular stage
			if let Some(mode)=data.modes.get_mode(mode_id){
				// set style
				state.style=mode.get_style().clone();
				// teleport to stage in mode
				if let Some(stage)=mode.get_stage(stage_id){
					let _=teleport_to_spawn(
						stage.spawn(),
						&mut state.move_state,&mut state.body,&mut state.touching,&mut state.run,&mut state.mode_state,
						mode,
						&data.models,&data.hitbox_mesh,&data.bvh,&state.style,&state.camera,&state.input_state,state.time
					);
				}
			}
			b_refresh_walk_target=false;
		},
		Instruction::Misc(MiscInstruction::PracticeFly)=>{
			match &state.move_state{
				MoveState::Fly=>{
					state.set_move_state(data,MoveState::Air);
				},
				_=>{
					state.set_move_state(data,MoveState::Fly);
				},
			}
			b_refresh_walk_target=false;
		},
		Instruction::Idle=>{
			//literally idle!
			b_refresh_walk_target=false;
		},
	}
	if b_refresh_walk_target{
		state.move_state.update_walk_target(&mut state.body,&state.touching,&data.models,&data.hitbox_mesh,&state.style,&state.camera,&state.input_state);
		state.move_state.update_fly_velocity(&mut state.body,&state.touching,&data.models,&data.hitbox_mesh,&state.style,&state.camera,&state.input_state);
		state.cull_velocity(data,state.body.velocity);
		//also check if accelerating away from surface
	}
}

#[cfg(test)]
mod test{
	use strafesnet_common::integer::{vec3::{self,int as int3},mat3};
	use super::*;
	fn test_collision_axis_aligned(relative_body:Trajectory,expected_collision_time:Option<Time>){
		let h0=HitboxMesh::new(PhysicsMesh::unit_cube(),integer::Planar64Affine3::new(mat3::from_diagonal(int3(5,1,5)>>1),vec3::zero()));
		let h1=StyleModifiers::roblox_bhop().calculate_mesh();
		let hitbox_mesh=h1.transformed_mesh();
		let platform_mesh=h0.transformed_mesh();
		let minkowski=MinkowskiMesh::minkowski_sum(platform_mesh,hitbox_mesh);
		let collision=minkowski.predict_collision_in(&relative_body,..);
		assert_eq!(collision.map(|tup|relative_body.time+tup.1.into()),expected_collision_time,"Incorrect time of collision");
	}
	fn test_collision_rotated(relative_body:Trajectory,expected_collision_time:Option<Time>){
		let h0=HitboxMesh::new(PhysicsMesh::unit_cube(),
			integer::Planar64Affine3::new(
				Planar64Mat3::from_cols([
					int3(5,0,1)>>1,
					int3(0,1,0)>>1,
					int3(-1,0,5)>>1,
				]),
				vec3::zero()
			),
		);
		let h1=StyleModifiers::roblox_bhop().calculate_mesh();
		let hitbox_mesh=h1.transformed_mesh();
		let platform_mesh=h0.transformed_mesh();
		let minkowski=MinkowskiMesh::minkowski_sum(platform_mesh,hitbox_mesh);
		let collision=minkowski.predict_collision_in(&relative_body,..);
		assert_eq!(collision.map(|tup|relative_body.time+tup.1.into()),expected_collision_time,"Incorrect time of collision");
	}
	fn test_collision(relative_body:Trajectory,expected_collision_time:Option<Time>){
		test_collision_axis_aligned(relative_body,expected_collision_time);
		test_collision_rotated(relative_body,expected_collision_time);
	}
	#[test]
	fn test_collision_degenerate_straight_down(){
		test_collision(Trajectory::new(
			int3(0,5,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)));
	}
	#[test]
	fn test_collision_zero_time_exact(){
		test_collision(Trajectory::new(
			int3(0,3,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_zero_time_epsilon(){
		test_collision(Trajectory::new(
			int3(0,3,0)+(vec3::Y>>32),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_small_mv(){
		test_collision(Trajectory::new(
			int3(0,5,0),
			int3(0,-1,0)+(vec3::X>>32),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)));
	}
	#[test]
	fn test_collision_degenerate_east(){
		test_collision(Trajectory::new(
			int3(3,5,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)));
	}
	#[test]
	fn test_collision_degenerate_south(){
		test_collision(Trajectory::new(
			int3(0,5,3),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)));
	}
	#[test]
	fn test_collision_degenerate_west(){
		test_collision(Trajectory::new(
			int3(-3,5,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)));
	}
	#[test]
	fn test_collision_degenerate_north(){
		test_collision(Trajectory::new(
			int3(0,5,-3),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)));
	}
	#[test]
	fn test_collision_parabola_edge_east_from_west(){
		test_collision(Trajectory::new(
			int3(3,3,0),
			int3(100,-1,0),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_south_from_north(){
		test_collision(Trajectory::new(
			int3(0,3,3),
			int3(0,-1,100),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_west_from_east(){
		test_collision(Trajectory::new(
			int3(-3,3,0),
			int3(-100,-1,0),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_north_from_south(){
		test_collision(Trajectory::new(
			int3(0,3,-3),
			int3(0,-1,-100),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_north_from_ne(){
		test_collision(Trajectory::new(
			int3(0,6,-7)>>1,
			int3(-10,-1,1),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_north_from_nw(){
		test_collision(Trajectory::new(
			int3(0,6,-7)>>1,
			int3(10,-1,1),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_east_from_se(){
		test_collision(Trajectory::new(
			int3(7,6,0)>>1,
			int3(-1,-1,-10),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_east_from_ne(){
		test_collision(Trajectory::new(
			int3(7,6,0)>>1,
			int3(-1,-1,10),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_south_from_se(){
		test_collision(Trajectory::new(
			int3(0,6,7)>>1,
			int3(-10,-1,-1),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_south_from_sw(){
		test_collision(Trajectory::new(
			int3(0,6,7)>>1,
			int3(10,-1,-1),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_west_from_se(){
		test_collision(Trajectory::new(
			int3(-7,6,0)>>1,
			int3(1,-1,-10),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_parabola_edge_west_from_ne(){
		test_collision(Trajectory::new(
			int3(-7,6,0)>>1,
			int3(1,-1,10),
			int3(0,-1,0),
			Time::ZERO
		).relative_to(&Trajectory::ZERO,Time::from_secs(-1)),Some(Time::from_secs(0)));
	}
	#[test]
	fn test_collision_oblique(){
		test_collision(Trajectory::new(
			int3(0,5,0),
			int3(1,-64,2)>>6,// /64
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)));
	}
	#[test]
	fn zoom_hit_nothing(){
		test_collision(Trajectory::new(
			int3(0,10,0),
			int3(1,0,0),
			int3(0,1,0),
			Time::ZERO
		),None);
	}
	#[test]
	fn already_inside_hit_nothing(){
		test_collision(Trajectory::new(
			vec3::zero(),
			int3(1,0,0),
			int3(0,1,0),
			Time::ZERO
		),None);
	}
	// overlap edges by 1 epsilon
	#[test]
	fn almost_miss_north(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(0,10,-7)>>1)+vec3::raw_xyz(0,0,1),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)))
	}
	#[test]
	fn almost_miss_east(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(7,10,0)>>1)+vec3::raw_xyz(-1,0,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)))
	}
	#[test]
	fn almost_miss_south(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(0,10,7)>>1)+vec3::raw_xyz(0,0,-1),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)))
	}
	#[test]
	fn almost_miss_west(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(-7,10,0)>>1)+vec3::raw_xyz(1,0,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),Some(Time::from_secs(2)))
	}
	// exactly miss edges
	#[test]
	fn exact_miss_north(){
		test_collision_axis_aligned(Trajectory::new(
			int3(0,10,-7)>>1,
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
	#[test]
	fn exact_miss_east(){
		test_collision_axis_aligned(Trajectory::new(
			int3(7,10,0)>>1,
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
	#[test]
	fn exact_miss_south(){
		test_collision_axis_aligned(Trajectory::new(
			int3(0,10,7)>>1,
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
	#[test]
	fn exact_miss_west(){
		test_collision_axis_aligned(Trajectory::new(
			int3(-7,10,0)>>1,
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
	// miss edges by 1 epsilon
	#[test]
	fn narrow_miss_north(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(0,10,-7)>>1)-vec3::raw_xyz(0,0,1),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
	#[test]
	fn narrow_miss_east(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(7,10,0)>>1)-vec3::raw_xyz(-1,0,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
	#[test]
	fn narrow_miss_south(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(0,10,7)>>1)-vec3::raw_xyz(0,0,-1),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
	#[test]
	fn narrow_miss_west(){
		test_collision_axis_aligned(Trajectory::new(
			(int3(-7,10,0)>>1)-vec3::raw_xyz(1,0,0),
			int3(0,-1,0),
			vec3::zero(),
			Time::ZERO
		),None)
	}
}
