Compare commits
2 Commits
load-textu
...
timelines
| Author | SHA1 | Date | |
|---|---|---|---|
| 53d2b5b3f5 | |||
| c565120ea7 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -1405,7 +1405,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "strafe-client"
|
name = "strafe-client"
|
||||||
version = "0.3.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-executor",
|
"async-executor",
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "strafe-client"
|
name = "strafe-client"
|
||||||
version = "0.3.0"
|
version = "0.2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|||||||
BIN
images/squid.dds
BIN
images/squid.dds
Binary file not shown.
684
src/body.rs
684
src/body.rs
@@ -1,14 +1,11 @@
|
|||||||
use crate::{instruction::{InstructionEmitter, InstructionConsumer, TimedInstruction}, zeroes::zeroes2};
|
use crate::instruction::TimedInstruction;
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum PhysicsInstruction {
|
pub enum PhysicsInstruction {
|
||||||
CollisionStart(RelativeCollision),
|
CollisionStart(RelativeCollision),
|
||||||
CollisionEnd(RelativeCollision),
|
CollisionEnd(RelativeCollision),
|
||||||
SetControlDir(glam::Vec3),
|
|
||||||
StrafeTick,
|
StrafeTick,
|
||||||
Jump,
|
Jump,
|
||||||
SetWalkTargetVelocity(glam::Vec3),
|
SetWalkTargetVelocity(glam::Vec3),
|
||||||
RefreshWalkTarget,
|
|
||||||
ReachWalkTargetVelocity,
|
ReachWalkTargetVelocity,
|
||||||
// Water,
|
// Water,
|
||||||
// Spawn(
|
// Spawn(
|
||||||
@@ -19,143 +16,35 @@ pub enum PhysicsInstruction {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct Body {
|
pub struct Body {
|
||||||
position: glam::Vec3,//I64 where 2^32 = 1 u
|
pub position: glam::Vec3,//I64 where 2^32 = 1 u
|
||||||
velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
|
pub velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
|
||||||
acceleration: glam::Vec3,//I64 where 2^32 = 1 u/s/s
|
pub time: TIME,//nanoseconds x xxxxD!
|
||||||
time: TIME,//nanoseconds x xxxxD!
|
|
||||||
}
|
|
||||||
trait MyHash{
|
|
||||||
fn hash(&self) -> u64;
|
|
||||||
}
|
|
||||||
impl MyHash for Body {
|
|
||||||
fn hash(&self) -> u64 {
|
|
||||||
let mut hasher=std::collections::hash_map::DefaultHasher::new();
|
|
||||||
for &el in self.position.as_ref().iter() {
|
|
||||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
|
||||||
}
|
|
||||||
for &el in self.velocity.as_ref().iter() {
|
|
||||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
|
||||||
}
|
|
||||||
for &el in self.acceleration.as_ref().iter() {
|
|
||||||
std::hash::Hasher::write(&mut hasher, el.to_ne_bytes().as_slice());
|
|
||||||
}
|
|
||||||
std::hash::Hasher::write(&mut hasher, self.time.to_ne_bytes().as_slice());
|
|
||||||
return std::hash::Hasher::finish(&hasher);//hash check to see if walk target is valid
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum MoveRestriction {
|
pub enum MoveRestriction {
|
||||||
Air,
|
Air,
|
||||||
Water,
|
Water,
|
||||||
Ground,
|
Ground,
|
||||||
Ladder,//multiple ladders how
|
Ladder,//multiple ladders how
|
||||||
}
|
|
||||||
|
|
||||||
enum MouseInterpolation {
|
|
||||||
First,//just checks the last value
|
|
||||||
Lerp,//lerps between
|
|
||||||
}
|
|
||||||
|
|
||||||
enum InputInstruction {
|
|
||||||
MoveMouse(glam::IVec2),
|
|
||||||
Jump(bool),
|
|
||||||
}
|
|
||||||
|
|
||||||
struct InputState {
|
|
||||||
controls: u32,
|
|
||||||
mouse_interpolation: MouseInterpolation,
|
|
||||||
time: TIME,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl InputState {
|
|
||||||
pub fn get_control(&self,control:u32) -> bool {
|
|
||||||
self.controls&control!=0
|
|
||||||
}
|
|
||||||
pub fn process_instruction(&mut self,ins:InputInstruction){
|
|
||||||
match ins {
|
|
||||||
InputInstruction::MoveMouse(m) => todo!("set mouse_interpolation"),
|
|
||||||
InputInstruction::Jump(b) => todo!("how does info about style modifiers get here"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct MouseInterpolationState {
|
|
||||||
interpolation: MouseInterpolation,
|
|
||||||
time0: TIME,
|
|
||||||
time1: TIME,
|
|
||||||
mouse0: glam::IVec2,
|
|
||||||
mouse1: glam::IVec2,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MouseInterpolationState {
|
|
||||||
pub fn move_mouse(&mut self,time:TIME,pos:glam::IVec2){
|
|
||||||
self.time0=self.time1;
|
|
||||||
self.mouse0=self.mouse1;
|
|
||||||
self.time1=time;
|
|
||||||
self.mouse1=pos;
|
|
||||||
}
|
|
||||||
pub fn interpolated_position(&self,time:TIME) -> glam::IVec2 {
|
|
||||||
match self.interpolation {
|
|
||||||
MouseInterpolation::First => self.mouse0,
|
|
||||||
MouseInterpolation::Lerp => {
|
|
||||||
let m0=self.mouse0.as_i64vec2();
|
|
||||||
let m1=self.mouse1.as_i64vec2();
|
|
||||||
//these are deltas
|
|
||||||
let t1t=(self.time1-time) as i64;
|
|
||||||
let tt0=(time-self.time0) as i64;
|
|
||||||
let dt=(self.time1-self.time0) as i64;
|
|
||||||
((m0*t1t+m1*tt0)/dt).as_ivec2()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum WalkEnum{
|
|
||||||
Reached,
|
|
||||||
Transient,
|
|
||||||
Invalid,
|
|
||||||
}
|
|
||||||
pub struct WalkState {
|
|
||||||
pub target_velocity: glam::Vec3,
|
|
||||||
pub target_time: TIME,
|
|
||||||
pub state: WalkEnum,
|
|
||||||
}
|
|
||||||
impl WalkState {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self{
|
|
||||||
target_velocity:glam::Vec3::ZERO,
|
|
||||||
target_time:0,
|
|
||||||
state:WalkEnum::Invalid,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct PhysicsState {
|
pub struct PhysicsState {
|
||||||
pub body: Body,
|
pub body: Body,
|
||||||
pub hitbox_halfsize: glam::Vec3,
|
pub contacts: Vec<RelativeCollision>,
|
||||||
pub contacts: std::collections::HashSet::<RelativeCollision>,
|
|
||||||
//pub intersections: Vec<ModelId>,
|
|
||||||
//temp
|
|
||||||
pub models_cringe_clone: Vec<Model>,
|
pub models_cringe_clone: Vec<Model>,
|
||||||
pub temp_control_dir: glam::Vec3,
|
|
||||||
//camera must exist in state because wormholes modify the camera, also camera punch
|
|
||||||
//pub camera: Camera,
|
|
||||||
//pub mouse_interpolation: MouseInterpolationState,
|
|
||||||
pub time: TIME,
|
pub time: TIME,
|
||||||
pub strafe_tick_num: TIME,
|
pub strafe_tick_num: TIME,
|
||||||
pub strafe_tick_den: TIME,
|
pub strafe_tick_den: TIME,
|
||||||
pub tick: u32,
|
pub tick: u32,
|
||||||
pub mv: f32,
|
pub mv: f32,
|
||||||
pub walk: WalkState,
|
|
||||||
pub walkspeed: f32,
|
pub walkspeed: f32,
|
||||||
pub friction: f32,
|
pub friction: f32,
|
||||||
pub walk_accel: f32,
|
|
||||||
pub gravity: glam::Vec3,
|
pub gravity: glam::Vec3,
|
||||||
pub grounded: bool,
|
pub grounded: bool,
|
||||||
pub jump_trying: bool,
|
pub jump_trying: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
#[derive(Clone,Copy)]
|
||||||
pub enum AabbFace{
|
pub enum AabbFace{
|
||||||
Right,//+X
|
Right,//+X
|
||||||
Top,
|
Top,
|
||||||
@@ -179,16 +68,6 @@ impl Aabb {
|
|||||||
// [0.0f32, 1., 0.],
|
// [0.0f32, 1., 0.],
|
||||||
// [0.0f32, -1., 0.],
|
// [0.0f32, -1., 0.],
|
||||||
// ];
|
// ];
|
||||||
const VERTEX_DATA: [glam::Vec3; 8] = [
|
|
||||||
glam::vec3(1., -1., -1.),
|
|
||||||
glam::vec3(1., 1., -1.),
|
|
||||||
glam::vec3(1., 1., 1.),
|
|
||||||
glam::vec3(1., -1., 1.),
|
|
||||||
glam::vec3(-1., -1., 1.),
|
|
||||||
glam::vec3(-1., 1., 1.),
|
|
||||||
glam::vec3(-1., 1., -1.),
|
|
||||||
glam::vec3(-1., -1., -1.),
|
|
||||||
];
|
|
||||||
const VERTEX_DATA_RIGHT: [glam::Vec3; 4] = [
|
const VERTEX_DATA_RIGHT: [glam::Vec3; 4] = [
|
||||||
glam::vec3(1., -1., -1.),
|
glam::vec3(1., -1., -1.),
|
||||||
glam::vec3(1., 1., -1.),
|
glam::vec3(1., 1., -1.),
|
||||||
@@ -245,10 +124,7 @@ impl Aabb {
|
|||||||
AabbFace::Front => glam::vec3(0.,0.,-1.),
|
AabbFace::Front => glam::vec3(0.,0.,-1.),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn unit_vertices() -> [glam::Vec3;8] {
|
pub fn face_vertices(face:AabbFace) -> [glam::Vec3;4] {
|
||||||
return Self::VERTEX_DATA;
|
|
||||||
}
|
|
||||||
pub fn unit_face_vertices(face:AabbFace) -> [glam::Vec3;4] {
|
|
||||||
match face {
|
match face {
|
||||||
AabbFace::Right => Self::VERTEX_DATA_RIGHT,
|
AabbFace::Right => Self::VERTEX_DATA_RIGHT,
|
||||||
AabbFace::Top => Self::VERTEX_DATA_TOP,
|
AabbFace::Top => Self::VERTEX_DATA_TOP,
|
||||||
@@ -260,8 +136,7 @@ impl Aabb {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//pretend to be using what we want to eventually do
|
type Face = AabbFace;
|
||||||
type TreyMeshFace = AabbFace;
|
|
||||||
type TreyMesh = Aabb;
|
type TreyMesh = Aabb;
|
||||||
|
|
||||||
pub struct Model {
|
pub struct Model {
|
||||||
@@ -274,42 +149,25 @@ impl Model {
|
|||||||
pub fn new(transform:glam::Mat4) -> Self {
|
pub fn new(transform:glam::Mat4) -> Self {
|
||||||
Self{transform}
|
Self{transform}
|
||||||
}
|
}
|
||||||
pub fn unit_vertices(&self) -> [glam::Vec3;8] {
|
pub fn face_vertices(&self,face:Face) -> [glam::Vec3;4] {
|
||||||
Aabb::unit_vertices()
|
Aabb::face_vertices(face)
|
||||||
}
|
}
|
||||||
pub fn mesh(&self) -> TreyMesh {
|
pub fn face_mesh(&self,face:Face) -> TreyMesh {
|
||||||
let mut aabb=Aabb::new();
|
let mut aabb=Aabb::new();
|
||||||
for &vertex in self.unit_vertices().iter() {
|
for &vertex in self.face_vertices(face).iter() {
|
||||||
aabb.grow(glam::Vec4Swizzles::xyz(self.transform*vertex.extend(1.0)));
|
aabb.grow(vertex);
|
||||||
}
|
}
|
||||||
return aabb;
|
return aabb;
|
||||||
}
|
}
|
||||||
pub fn unit_face_vertices(&self,face:TreyMeshFace) -> [glam::Vec3;4] {
|
pub fn face_normal(&self,face:Face) -> glam::Vec3 {
|
||||||
Aabb::unit_face_vertices(face)
|
let mut n=glam::Vec3Swizzles::xyzz(Aabb::normal(face));
|
||||||
}
|
n.w=0.0;//what a man will do to avoid writing out the components
|
||||||
pub fn face_mesh(&self,face:TreyMeshFace) -> TreyMesh {
|
glam::Vec4Swizzles::xyz(self.transform*n)//this is wrong for scale
|
||||||
let mut aabb=self.mesh();
|
|
||||||
//in this implementation face = worldspace aabb face
|
|
||||||
match face {
|
|
||||||
AabbFace::Right => aabb.min.x=aabb.max.x,
|
|
||||||
AabbFace::Top => aabb.min.y=aabb.max.y,
|
|
||||||
AabbFace::Back => aabb.min.z=aabb.max.z,
|
|
||||||
AabbFace::Left => aabb.max.x=aabb.min.x,
|
|
||||||
AabbFace::Bottom => aabb.max.y=aabb.min.y,
|
|
||||||
AabbFace::Front => aabb.max.z=aabb.min.z,
|
|
||||||
}
|
|
||||||
return aabb;
|
|
||||||
}
|
|
||||||
pub fn face_normal(&self,face:TreyMeshFace) -> glam::Vec3 {
|
|
||||||
glam::Vec4Swizzles::xyz(Aabb::normal(face).extend(0.0))//this is wrong for scale
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//need non-face (full model) variant for CanCollide false objects
|
|
||||||
//OR have a separate list from contacts for model intersection
|
|
||||||
#[derive(Debug,Clone,Eq,Hash,PartialEq)]
|
|
||||||
pub struct RelativeCollision {
|
pub struct RelativeCollision {
|
||||||
face: TreyMeshFace,//just an id
|
face: Face,//just an id
|
||||||
model: u32,//using id to avoid lifetimes
|
model: u32,//using id to avoid lifetimes
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -324,65 +182,28 @@ impl RelativeCollision {
|
|||||||
|
|
||||||
pub type TIME = i64;
|
pub type TIME = i64;
|
||||||
|
|
||||||
impl Body {
|
const CONTROL_JUMP:u32 = 0b01000000;//temp DATA NORMALIZATION!@#$
|
||||||
pub fn with_pva(position:glam::Vec3,velocity:glam::Vec3,acceleration:glam::Vec3) -> Self {
|
|
||||||
Self{
|
|
||||||
position,
|
|
||||||
velocity,
|
|
||||||
acceleration,
|
|
||||||
time: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn extrapolated_position(&self,time: TIME)->glam::Vec3{
|
|
||||||
let dt=(time-self.time) as f64/1_000_000_000f64;
|
|
||||||
self.position+self.velocity*(dt as f32)+self.acceleration*((0.5*dt*dt) as f32)
|
|
||||||
}
|
|
||||||
pub fn extrapolated_velocity(&self,time: TIME)->glam::Vec3{
|
|
||||||
let dt=(time-self.time) as f64/1_000_000_000f64;
|
|
||||||
self.velocity+self.acceleration*(dt as f32)
|
|
||||||
}
|
|
||||||
pub fn advance_time(&mut self, time: TIME){
|
|
||||||
self.position=self.extrapolated_position(time);
|
|
||||||
self.velocity=self.extrapolated_velocity(time);
|
|
||||||
self.time=time;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PhysicsState {
|
impl PhysicsState {
|
||||||
//tickless gaming
|
//delete this, we are tickless gamers
|
||||||
pub fn run(&mut self, time_limit:TIME){
|
pub fn run(&mut self, time: TIME){
|
||||||
//prepare is ommitted - everything is done via instructions.
|
//prepare is ommitted - everything is done via instructions.
|
||||||
while let Some(instruction) = self.next_instruction(time_limit) {//collect
|
while let Some(instruction) = self.next_instruction() {//collect
|
||||||
|
if time<instruction.time {
|
||||||
|
break;
|
||||||
|
}
|
||||||
//advance
|
//advance
|
||||||
//self.advance_time(instruction.time);
|
self.advance_time(instruction.time);
|
||||||
//process
|
//process
|
||||||
self.process_instruction(instruction);
|
self.process_instruction(instruction);
|
||||||
//write hash lol
|
//write hash lol
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn advance_time(&mut self, time: TIME){
|
//delete this
|
||||||
self.body.advance_time(time);
|
pub fn extrapolate_position(&self, time: TIME) -> glam::Vec3 {
|
||||||
self.time=time;
|
let dt=(time-self.body.time) as f64/1_000_000_000f64;
|
||||||
}
|
self.body.position+self.body.velocity*(dt as f32)+self.gravity*((0.5*dt*dt) as f32)
|
||||||
|
|
||||||
fn contact_constrain_velocity(&self,velocity:&mut glam::Vec3){
|
|
||||||
for contact in self.contacts.iter() {
|
|
||||||
let n=contact.normal(&self.models_cringe_clone);
|
|
||||||
let d=velocity.dot(n);
|
|
||||||
if d<0f32{
|
|
||||||
(*velocity)-=d/n.length_squared()*n;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn contact_constrain_acceleration(&self,acceleration:&mut glam::Vec3){
|
|
||||||
for contact in self.contacts.iter() {
|
|
||||||
let n=contact.normal(&self.models_cringe_clone);
|
|
||||||
let d=acceleration.dot(n);
|
|
||||||
if d<0f32{
|
|
||||||
(*acceleration)-=d/n.length_squared()*n;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
@@ -425,316 +246,38 @@ impl PhysicsState {
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
fn next_walk_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
fn next_walk_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
//check if you have a valid walk state and create an instruction
|
//check if you are accelerating towards a walk target velocity and create an instruction
|
||||||
if self.grounded{
|
return None;
|
||||||
match self.walk.state{
|
|
||||||
WalkEnum::Transient=>Some(TimedInstruction{
|
|
||||||
time:self.walk.target_time,
|
|
||||||
instruction:PhysicsInstruction::ReachWalkTargetVelocity
|
|
||||||
}),
|
|
||||||
WalkEnum::Invalid=>Some(TimedInstruction{
|
|
||||||
time:self.time,
|
|
||||||
instruction:PhysicsInstruction::RefreshWalkTarget,
|
|
||||||
}),
|
|
||||||
WalkEnum::Reached=>None,
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
fn mesh(&self) -> TreyMesh {
|
fn predict_collision_end(&self,model:&Model) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
let mut aabb=Aabb::new();
|
|
||||||
for vertex in Aabb::unit_vertices(){
|
|
||||||
aabb.grow(self.body.position+self.hitbox_halfsize*vertex);
|
|
||||||
}
|
|
||||||
aabb
|
|
||||||
}
|
|
||||||
fn predict_collision_end(&self,time:TIME,time_limit:TIME,collision_data:&RelativeCollision) -> Option<TimedInstruction<PhysicsInstruction>> {
|
|
||||||
//must treat cancollide false objects differently: you may not exit through the same face you entered.
|
//must treat cancollide false objects differently: you may not exit through the same face you entered.
|
||||||
//RelativeCollsion must reference the full model instead of a particular face
|
|
||||||
//this is Ctrl+C Ctrl+V of predict_collision_start but with v=-v before the calc and t=-t after the calc
|
|
||||||
//find best t
|
|
||||||
let mut best_time=time_limit;
|
|
||||||
let mut exit_face:Option<TreyMeshFace>=None;
|
|
||||||
let mesh0=self.mesh();
|
|
||||||
let mesh1=self.models_cringe_clone.get(collision_data.model as usize).unwrap().mesh();
|
|
||||||
let (v,a)=(-self.body.velocity,self.body.acceleration);
|
|
||||||
//collect x
|
|
||||||
match collision_data.face {
|
|
||||||
AabbFace::Top|AabbFace::Back|AabbFace::Bottom|AabbFace::Front=>{
|
|
||||||
for t in zeroes2(mesh0.max.x-mesh1.min.x,v.x,0.5*a.x) {
|
|
||||||
//negative t = back in time
|
|
||||||
//must be moving towards surface to collide
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((-t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&0f32<v.x+a.x*-t{
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
exit_face=Some(TreyMeshFace::Left);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for t in zeroes2(mesh0.min.x-mesh1.max.x,v.x,0.5*a.x) {
|
|
||||||
//negative t = back in time
|
|
||||||
//must be moving towards surface to collide
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((-t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&v.x+a.x*-t<0f32{
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
exit_face=Some(TreyMeshFace::Right);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
AabbFace::Left=>{
|
|
||||||
//generate event if v.x<0||a.x<0
|
|
||||||
if -v.x<0f32{
|
|
||||||
best_time=time;
|
|
||||||
exit_face=Some(TreyMeshFace::Left);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
AabbFace::Right=>{
|
|
||||||
//generate event if 0<v.x||0<a.x
|
|
||||||
if 0f32<(-v.x){
|
|
||||||
best_time=time;
|
|
||||||
exit_face=Some(TreyMeshFace::Right);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
//collect y
|
|
||||||
match collision_data.face {
|
|
||||||
AabbFace::Left|AabbFace::Back|AabbFace::Right|AabbFace::Front=>{
|
|
||||||
for t in zeroes2(mesh0.max.y-mesh1.min.y,v.y,0.5*a.y) {
|
|
||||||
//negative t = back in time
|
|
||||||
//must be moving towards surface to collide
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((-t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&0f32<v.y+a.y*-t{
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
exit_face=Some(TreyMeshFace::Bottom);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for t in zeroes2(mesh0.min.y-mesh1.max.y,v.y,0.5*a.y) {
|
|
||||||
//negative t = back in time
|
|
||||||
//must be moving towards surface to collide
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((-t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&v.y+a.y*-t<0f32{
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
exit_face=Some(TreyMeshFace::Top);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
AabbFace::Bottom=>{
|
|
||||||
//generate event if v.y<0||a.y<0
|
|
||||||
if -v.y<0f32{
|
|
||||||
best_time=time;
|
|
||||||
exit_face=Some(TreyMeshFace::Bottom);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
AabbFace::Top=>{
|
|
||||||
//generate event if 0<v.y||0<a.y
|
|
||||||
if 0f32<(-v.y){
|
|
||||||
best_time=time;
|
|
||||||
exit_face=Some(TreyMeshFace::Top);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
//collect z
|
|
||||||
match collision_data.face {
|
|
||||||
AabbFace::Left|AabbFace::Bottom|AabbFace::Right|AabbFace::Top=>{
|
|
||||||
for t in zeroes2(mesh0.max.z-mesh1.min.z,v.z,0.5*a.z) {
|
|
||||||
//negative t = back in time
|
|
||||||
//must be moving towards surface to collide
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((-t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&0f32<v.z+a.z*-t{
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
exit_face=Some(TreyMeshFace::Front);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for t in zeroes2(mesh0.min.z-mesh1.max.z,v.z,0.5*a.z) {
|
|
||||||
//negative t = back in time
|
|
||||||
//must be moving towards surface to collide
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((-t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&v.z+a.z*-t<0f32{
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
exit_face=Some(TreyMeshFace::Back);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
AabbFace::Front=>{
|
|
||||||
//generate event if v.z<0||a.z<0
|
|
||||||
if -v.z<0f32{
|
|
||||||
best_time=time;
|
|
||||||
exit_face=Some(TreyMeshFace::Front);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
AabbFace::Back=>{
|
|
||||||
//generate event if 0<v.z||0<a.z
|
|
||||||
if 0f32<(-v.z){
|
|
||||||
best_time=time;
|
|
||||||
exit_face=Some(TreyMeshFace::Back);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
//generate instruction
|
|
||||||
if let Some(face) = exit_face{
|
|
||||||
return Some(TimedInstruction {
|
|
||||||
time: best_time,
|
|
||||||
instruction: PhysicsInstruction::CollisionEnd(collision_data.clone())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
fn predict_collision_start(&self,time:TIME,time_limit:TIME,model_id:u32) -> Option<TimedInstruction<PhysicsInstruction>> {
|
fn predict_collision_start(&self,model:&Model) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
//find best t
|
|
||||||
let mut best_time=time_limit;
|
|
||||||
let mut best_face:Option<TreyMeshFace>=None;
|
|
||||||
let mesh0=self.mesh();
|
|
||||||
let mesh1=self.models_cringe_clone.get(model_id as usize).unwrap().mesh();
|
|
||||||
let (p,v,a)=(self.body.position,self.body.velocity,self.body.acceleration);
|
|
||||||
//collect x
|
|
||||||
for t in zeroes2(mesh0.max.x-mesh1.min.x,v.x,0.5*a.x) {
|
|
||||||
//must collide now or in the future
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&0f32<v.x+a.x*t{
|
|
||||||
let dp=self.body.extrapolated_position(t_time)-p;
|
|
||||||
//faces must be overlapping
|
|
||||||
if mesh1.min.y<mesh0.max.y+dp.y&&mesh0.min.y+dp.y<mesh1.max.y&&mesh1.min.z<mesh0.max.z+dp.z&&mesh0.min.z+dp.z<mesh1.max.z {
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
best_face=Some(TreyMeshFace::Left);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for t in zeroes2(mesh0.min.x-mesh1.max.x,v.x,0.5*a.x) {
|
|
||||||
//must collide now or in the future
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&v.x+a.x*t<0f32{
|
|
||||||
let dp=self.body.extrapolated_position(t_time)-p;
|
|
||||||
//faces must be overlapping
|
|
||||||
if mesh1.min.y<mesh0.max.y+dp.y&&mesh0.min.y+dp.y<mesh1.max.y&&mesh1.min.z<mesh0.max.z+dp.z&&mesh0.min.z+dp.z<mesh1.max.z {
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
best_face=Some(TreyMeshFace::Right);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//collect y
|
|
||||||
for t in zeroes2(mesh0.max.y-mesh1.min.y,v.y,0.5*a.y) {
|
|
||||||
//must collide now or in the future
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&0f32<v.y+a.y*t{
|
|
||||||
let dp=self.body.extrapolated_position(t_time)-p;
|
|
||||||
//faces must be overlapping
|
|
||||||
if mesh1.min.x<mesh0.max.x+dp.x&&mesh0.min.x+dp.x<mesh1.max.x&&mesh1.min.z<mesh0.max.z+dp.z&&mesh0.min.z+dp.z<mesh1.max.z {
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
best_face=Some(TreyMeshFace::Bottom);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for t in zeroes2(mesh0.min.y-mesh1.max.y,v.y,0.5*a.y) {
|
|
||||||
//must collide now or in the future
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&v.y+a.y*t<0f32{
|
|
||||||
let dp=self.body.extrapolated_position(t_time)-p;
|
|
||||||
//faces must be overlapping
|
|
||||||
if mesh1.min.x<mesh0.max.x+dp.x&&mesh0.min.x+dp.x<mesh1.max.x&&mesh1.min.z<mesh0.max.z+dp.z&&mesh0.min.z+dp.z<mesh1.max.z {
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
best_face=Some(TreyMeshFace::Top);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//collect z
|
|
||||||
for t in zeroes2(mesh0.max.z-mesh1.min.z,v.z,0.5*a.z) {
|
|
||||||
//must collide now or in the future
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&0f32<v.z+a.z*t{
|
|
||||||
let dp=self.body.extrapolated_position(t_time)-p;
|
|
||||||
//faces must be overlapping
|
|
||||||
if mesh1.min.y<mesh0.max.y+dp.y&&mesh0.min.y+dp.y<mesh1.max.y&&mesh1.min.x<mesh0.max.x+dp.x&&mesh0.min.x+dp.x<mesh1.max.x {
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
best_face=Some(TreyMeshFace::Front);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for t in zeroes2(mesh0.min.z-mesh1.max.z,v.z,0.5*a.z) {
|
|
||||||
//must collide now or in the future
|
|
||||||
//must beat the current soonest collision time
|
|
||||||
//must be moving towards surface
|
|
||||||
let t_time=self.body.time+((t as f64)*1_000_000_000f64) as TIME;
|
|
||||||
if time<=t_time&&t_time<best_time&&v.z+a.z*t<0f32{
|
|
||||||
let dp=self.body.extrapolated_position(t_time)-p;
|
|
||||||
//faces must be overlapping
|
|
||||||
if mesh1.min.y<mesh0.max.y+dp.y&&mesh0.min.y+dp.y<mesh1.max.y&&mesh1.min.x<mesh0.max.x+dp.x&&mesh0.min.x+dp.x<mesh1.max.x {
|
|
||||||
//collect valid t
|
|
||||||
best_time=t_time;
|
|
||||||
best_face=Some(TreyMeshFace::Back);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//generate instruction
|
|
||||||
if let Some(face) = best_face{
|
|
||||||
return Some(TimedInstruction {
|
|
||||||
time: best_time,
|
|
||||||
instruction: PhysicsInstruction::CollisionStart(RelativeCollision {
|
|
||||||
face,
|
|
||||||
model: model_id
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState {
|
impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState {
|
||||||
//this little next instruction function can cache its return value and invalidate the cached value by watching the State.
|
//this little next instruction function can cache its return value and invalidate the cached value by watching the State.
|
||||||
fn next_instruction(&self,time_limit:TIME) -> Option<TimedInstruction<PhysicsInstruction>> {
|
fn next_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
//JUST POLLING!!! NO MUTATION
|
//JUST POLLING!!! NO MUTATION
|
||||||
let mut collector = crate::instruction::InstructionCollector::new(time_limit);
|
let mut collector = crate::instruction::InstructionCollector::new();
|
||||||
|
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
|
||||||
|
if self.grounded&&self.jump_trying {
|
||||||
|
//scroll will be implemented with InputInstruction::Jump(true) but it blocks setting self.jump_trying=true
|
||||||
|
collector.collect(Some(TimedInstruction{
|
||||||
|
time:self.time,
|
||||||
|
instruction:PhysicsInstruction::Jump
|
||||||
|
}));
|
||||||
|
}
|
||||||
//check for collision stop instructions with curent contacts
|
//check for collision stop instructions with curent contacts
|
||||||
for collision_data in self.contacts.iter() {
|
for collision_data in self.contacts.iter() {
|
||||||
collector.collect(self.predict_collision_end(self.time,time_limit,collision_data));
|
collector.collect(self.predict_collision_end(self.models_cringe_clone.get(collision_data.model as usize).unwrap()));
|
||||||
}
|
}
|
||||||
//check for collision start instructions (against every part in the game with no optimization!!)
|
//check for collision start instructions (against every part in the game with no optimization!!)
|
||||||
for i in 0..self.models_cringe_clone.len() {
|
for model in &self.models_cringe_clone {
|
||||||
collector.collect(self.predict_collision_start(self.time,time_limit,i as u32));
|
collector.collect(self.predict_collision_start(model));
|
||||||
}
|
}
|
||||||
if self.grounded {
|
if self.grounded {
|
||||||
//walk maintenance
|
//walk maintenance
|
||||||
@@ -749,109 +292,30 @@ impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState
|
|||||||
|
|
||||||
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
|
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
|
||||||
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
|
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
|
||||||
match &ins.instruction {
|
//mutate position and velocity and time
|
||||||
PhysicsInstruction::StrafeTick => (),
|
self.body.advance_time(ins.time);//should this be in a separate function: self.advance_time?
|
||||||
_=>println!("{:?}",ins),
|
|
||||||
}
|
|
||||||
//selectively update body
|
|
||||||
match &ins.instruction {
|
|
||||||
PhysicsInstruction::SetWalkTargetVelocity(_)
|
|
||||||
|PhysicsInstruction::SetControlDir(_) => self.time=ins.time,//TODO: queue instructions
|
|
||||||
PhysicsInstruction::RefreshWalkTarget
|
|
||||||
|PhysicsInstruction::ReachWalkTargetVelocity
|
|
||||||
|PhysicsInstruction::CollisionStart(_)
|
|
||||||
|PhysicsInstruction::CollisionEnd(_)
|
|
||||||
|PhysicsInstruction::StrafeTick
|
|
||||||
|PhysicsInstruction::Jump => self.advance_time(ins.time),
|
|
||||||
}
|
|
||||||
match ins.instruction {
|
match ins.instruction {
|
||||||
PhysicsInstruction::CollisionStart(c) => {
|
PhysicsInstruction::CollisionStart(_) => todo!(),
|
||||||
//check ground
|
PhysicsInstruction::CollisionEnd(_) => todo!(),
|
||||||
match &c.face {
|
PhysicsInstruction::StrafeTick => {
|
||||||
AabbFace::Top => {
|
let control_dir=self.get_control_dir();//this respects your mouse interpolation settings
|
||||||
//ground
|
let d=self.body.velocity.dot(control_dir);
|
||||||
self.grounded=true;
|
if d<self.mv {
|
||||||
},
|
self.body.velocity+=(self.mv-d)*control_dir;
|
||||||
_ => (),
|
}
|
||||||
}
|
}
|
||||||
self.contacts.insert(c);
|
PhysicsInstruction::Jump => {
|
||||||
//flatten v
|
|
||||||
let mut v=self.body.velocity;
|
|
||||||
self.contact_constrain_velocity(&mut v);
|
|
||||||
self.body.velocity=v;
|
|
||||||
self.walk.state=WalkEnum::Invalid;
|
|
||||||
},
|
|
||||||
PhysicsInstruction::CollisionEnd(c) => {
|
|
||||||
self.contacts.remove(&c);//remove contact before calling contact_constrain_acceleration
|
|
||||||
let mut a=self.gravity;
|
|
||||||
self.contact_constrain_acceleration(&mut a);
|
|
||||||
self.body.acceleration=a;
|
|
||||||
self.walk.state=WalkEnum::Invalid;
|
|
||||||
//check ground
|
|
||||||
match &c.face {
|
|
||||||
AabbFace::Top => {
|
|
||||||
self.grounded=false;
|
|
||||||
},
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
PhysicsInstruction::SetControlDir(control_dir)=>{
|
|
||||||
self.temp_control_dir=control_dir;
|
|
||||||
self.walk.state=WalkEnum::Invalid;
|
|
||||||
},
|
|
||||||
PhysicsInstruction::StrafeTick => {
|
|
||||||
//let control_dir=self.get_control_dir();//this should respect your mouse interpolation settings
|
|
||||||
let d=self.body.velocity.dot(self.temp_control_dir);
|
|
||||||
if d<self.mv {
|
|
||||||
let mut v=self.body.velocity+(self.mv-d)*self.temp_control_dir;
|
|
||||||
self.contact_constrain_velocity(&mut v);
|
|
||||||
self.body.velocity=v;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PhysicsInstruction::Jump => {
|
|
||||||
self.grounded=false;//do I need this?
|
self.grounded=false;//do I need this?
|
||||||
let mut v=self.body.velocity+glam::Vec3::new(0.0,0.715588/2.0*100.0,0.0);
|
self.body.velocity+=glam::Vec3::new(0.0,0.715588/2.0*100.0,0.0);
|
||||||
self.contact_constrain_velocity(&mut v);
|
}
|
||||||
self.body.velocity=v;
|
PhysicsInstruction::ReachWalkTargetVelocity => {
|
||||||
self.walk.state=WalkEnum::Invalid;
|
//precisely set velocity
|
||||||
},
|
self.body.velocity=self.walk_target_velocity;
|
||||||
PhysicsInstruction::ReachWalkTargetVelocity => {
|
}
|
||||||
//precisely set velocity
|
PhysicsInstruction::SetWalkTargetVelocity(v) => {
|
||||||
let mut a=glam::Vec3::ZERO;
|
self.walk_target_velocity=v;
|
||||||
self.contact_constrain_acceleration(&mut a);
|
//calculate acceleration yada yada
|
||||||
self.body.acceleration=a;
|
},
|
||||||
let mut v=self.walk.target_velocity;
|
|
||||||
self.contact_constrain_velocity(&mut v);
|
|
||||||
self.body.velocity=v;
|
|
||||||
self.walk.state=WalkEnum::Reached;
|
|
||||||
},
|
|
||||||
PhysicsInstruction::RefreshWalkTarget => {
|
|
||||||
//calculate acceleration yada yada
|
|
||||||
if self.grounded{
|
|
||||||
let mut v=self.walk.target_velocity;
|
|
||||||
self.contact_constrain_velocity(&mut v);
|
|
||||||
let mut target_diff=v-self.body.velocity;
|
|
||||||
target_diff.y=0f32;
|
|
||||||
if target_diff==glam::Vec3::ZERO{
|
|
||||||
let mut a=glam::Vec3::ZERO;
|
|
||||||
self.contact_constrain_acceleration(&mut a);
|
|
||||||
self.body.acceleration=a;
|
|
||||||
self.walk.state=WalkEnum::Reached;
|
|
||||||
}else{
|
|
||||||
let accel=self.walk_accel.min(self.gravity.length()*self.friction);
|
|
||||||
let time_delta=target_diff.length()/accel;
|
|
||||||
let mut a=target_diff/time_delta;
|
|
||||||
self.contact_constrain_acceleration(&mut a);
|
|
||||||
self.body.acceleration=a;
|
|
||||||
self.walk.target_time=self.body.time+((time_delta as f64)*1_000_000_000f64) as TIME;
|
|
||||||
self.walk.state=WalkEnum::Transient;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
PhysicsInstruction::SetWalkTargetVelocity(v) => {
|
|
||||||
self.walk.target_velocity=v;
|
|
||||||
self.walk.state=WalkEnum::Invalid;
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -279,6 +279,11 @@ fn start<E: Example>(
|
|||||||
log::info!("Initializing the example...");
|
log::info!("Initializing the example...");
|
||||||
let mut example = E::init(&config, &adapter, &device, &queue);
|
let mut example = E::init(&config, &adapter, &device, &queue);
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
let mut last_frame_inst = Instant::now();
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
let (mut frame_count, mut accum_time) = (0, 0.0);
|
||||||
|
|
||||||
log::info!("Entering render loop...");
|
log::info!("Entering render loop...");
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, _, control_flow| {
|
||||||
let _ = (&instance, &adapter); // force ownership by the closure
|
let _ = (&instance, &adapter); // force ownership by the closure
|
||||||
@@ -359,6 +364,20 @@ fn start<E: Example>(
|
|||||||
example.move_mouse(delta);
|
example.move_mouse(delta);
|
||||||
},
|
},
|
||||||
event::Event::RedrawRequested(_) => {
|
event::Event::RedrawRequested(_) => {
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
{
|
||||||
|
accum_time += last_frame_inst.elapsed().as_secs_f32();
|
||||||
|
last_frame_inst = Instant::now();
|
||||||
|
frame_count += 1;
|
||||||
|
if frame_count == 100 {
|
||||||
|
println!(
|
||||||
|
"Avg frame time {}ms",
|
||||||
|
accum_time * 1000.0 / frame_count as f32
|
||||||
|
);
|
||||||
|
accum_time = 0.0;
|
||||||
|
frame_count = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let frame = match surface.get_current_texture() {
|
let frame = match surface.get_current_texture() {
|
||||||
Ok(frame) => frame,
|
Ok(frame) => frame,
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
#[derive(Debug)]
|
|
||||||
pub struct TimedInstruction<I> {
|
pub struct TimedInstruction<I> {
|
||||||
pub time: crate::body::TIME,
|
pub time: crate::body::TIME,
|
||||||
pub instruction: I,
|
pub instruction: I,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait InstructionEmitter<I> {
|
pub trait InstructionEmitter<I> {
|
||||||
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<I>>;
|
fn next_instruction(&self) -> Option<TimedInstruction<I>>;
|
||||||
}
|
}
|
||||||
pub trait InstructionConsumer<I> {
|
pub trait InstructionConsumer<I> {
|
||||||
fn process_instruction(&mut self, instruction:TimedInstruction<I>);
|
fn process_instruction(&mut self, instruction:TimedInstruction<I>);
|
||||||
@@ -13,36 +12,26 @@ pub trait InstructionConsumer<I> {
|
|||||||
|
|
||||||
//PROPER PRIVATE FIELDS!!!
|
//PROPER PRIVATE FIELDS!!!
|
||||||
pub struct InstructionCollector<I> {
|
pub struct InstructionCollector<I> {
|
||||||
time: crate::body::TIME,
|
instruction: Option<TimedInstruction<I>>,
|
||||||
instruction: Option<I>,
|
|
||||||
}
|
}
|
||||||
impl<I> InstructionCollector<I> {
|
impl<I> InstructionCollector<I> {
|
||||||
pub fn new(time:crate::body::TIME) -> Self {
|
pub fn new() -> Self {
|
||||||
Self{
|
Self{instruction:None}
|
||||||
time,
|
|
||||||
instruction:None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn collect(&mut self,instruction:Option<TimedInstruction<I>>){
|
pub fn collect(&mut self,instruction:Option<TimedInstruction<I>>){
|
||||||
match instruction {
|
match &instruction {
|
||||||
Some(unwrap_instruction) => {
|
Some(unwrap_instruction) => match &self.instruction {
|
||||||
if unwrap_instruction.time<self.time {
|
Some(unwrap_best_instruction) => if unwrap_instruction.time<unwrap_best_instruction.time {
|
||||||
self.time=unwrap_instruction.time;
|
self.instruction=instruction;
|
||||||
self.instruction=Some(unwrap_instruction.instruction);
|
},
|
||||||
}
|
None => self.instruction=instruction,
|
||||||
},
|
},
|
||||||
None => (),
|
None => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn instruction(self) -> Option<TimedInstruction<I>> {
|
pub fn instruction(self) -> Option<TimedInstruction<I>> {
|
||||||
//STEAL INSTRUCTION AND DESTROY INSTRUCTIONCOLLECTOR
|
//STEAL INSTRUCTION AND DESTROY INSTRUCTIONCOLLECTOR
|
||||||
match self.instruction {
|
return self.instruction
|
||||||
Some(instruction)=>Some(TimedInstruction{
|
|
||||||
time:self.time,
|
|
||||||
instruction
|
|
||||||
}),
|
|
||||||
None => None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
pub mod framework;
|
pub mod framework;
|
||||||
pub mod body;
|
pub mod body;
|
||||||
pub mod zeroes;
|
|
||||||
pub mod instruction;
|
pub mod instruction;
|
||||||
|
pub mod timelines;
|
||||||
|
|||||||
525
src/main.rs
525
src/main.rs
@@ -19,13 +19,13 @@ struct Entity {
|
|||||||
|
|
||||||
//temp?
|
//temp?
|
||||||
struct ModelData {
|
struct ModelData {
|
||||||
transforms: Vec<glam::Mat4>,
|
transform: glam::Mat4,
|
||||||
vertex_buf: wgpu::Buffer,
|
vertex_buf: wgpu::Buffer,
|
||||||
entities: Vec<Entity>,
|
entities: Vec<Entity>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ModelGraphics {
|
struct ModelGraphics {
|
||||||
transforms: Vec<glam::Mat4>,
|
transform: glam::Mat4,
|
||||||
vertex_buf: wgpu::Buffer,
|
vertex_buf: wgpu::Buffer,
|
||||||
entities: Vec<Entity>,
|
entities: Vec<Entity>,
|
||||||
bind_group: wgpu::BindGroup,
|
bind_group: wgpu::BindGroup,
|
||||||
@@ -113,29 +113,21 @@ impl Camera {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct GraphicsBindGroups {
|
pub struct Skybox {
|
||||||
camera: wgpu::BindGroup,
|
|
||||||
skybox_texture: wgpu::BindGroup,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct GraphicsPipelines {
|
|
||||||
skybox: wgpu::RenderPipeline,
|
|
||||||
model: wgpu::RenderPipeline,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct GraphicsData {
|
|
||||||
start_time: std::time::Instant,
|
start_time: std::time::Instant,
|
||||||
camera: Camera,
|
camera: Camera,
|
||||||
physics: strafe_client::body::PhysicsState,
|
physics: strafe_client::body::PhysicsState,
|
||||||
pipelines: GraphicsPipelines,
|
sky_pipeline: wgpu::RenderPipeline,
|
||||||
bind_groups: GraphicsBindGroups,
|
entity_pipeline: wgpu::RenderPipeline,
|
||||||
|
ground_pipeline: wgpu::RenderPipeline,
|
||||||
|
main_bind_group: wgpu::BindGroup,
|
||||||
camera_buf: wgpu::Buffer,
|
camera_buf: wgpu::Buffer,
|
||||||
models: Vec<ModelGraphics>,
|
models: Vec<ModelGraphics>,
|
||||||
depth_view: wgpu::TextureView,
|
depth_view: wgpu::TextureView,
|
||||||
staging_belt: wgpu::util::StagingBelt,
|
staging_belt: wgpu::util::StagingBelt,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GraphicsData {
|
impl Skybox {
|
||||||
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
|
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
|
||||||
|
|
||||||
fn create_depth_texture(
|
fn create_depth_texture(
|
||||||
@@ -161,17 +153,14 @@ impl GraphicsData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_transform_uniform_data(transforms:&Vec<glam::Mat4>) -> Vec<f32> {
|
fn get_transform_uniform_data(transform:&glam::Mat4) -> [f32; 4*4] {
|
||||||
let mut raw = Vec::with_capacity(4*4*transforms.len());
|
let mut raw = [0f32; 4*4];
|
||||||
for (i,t) in transforms.iter().enumerate(){
|
raw[0..16].copy_from_slice(&AsRef::<[f32; 4*4]>::as_ref(transform)[..]);
|
||||||
let mut v = raw.split_off(4*4*i);
|
|
||||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(t)[..]);
|
|
||||||
raw.append(&mut v);
|
|
||||||
}
|
|
||||||
raw
|
raw
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_obj(device:&wgpu::Device,modeldatas:& mut Vec<ModelData>,data:obj::ObjData){
|
fn add_obj(device:&wgpu::Device,modeldatas:& mut Vec<ModelData>,source:&[u8]){
|
||||||
|
let data = obj::ObjData::load_buf(&source[..]).unwrap();
|
||||||
let mut vertices = Vec::new();
|
let mut vertices = Vec::new();
|
||||||
let mut vertex_index = std::collections::HashMap::<obj::IndexTuple,u16>::new();
|
let mut vertex_index = std::collections::HashMap::<obj::IndexTuple,u16>::new();
|
||||||
for object in data.objects {
|
for object in data.objects {
|
||||||
@@ -183,7 +172,7 @@ fn add_obj(device:&wgpu::Device,modeldatas:& mut Vec<ModelData>,data:obj::ObjDat
|
|||||||
for &index in &[0, end_index - 1, end_index] {
|
for &index in &[0, end_index - 1, end_index] {
|
||||||
let vert = poly.0[index];
|
let vert = poly.0[index];
|
||||||
if let Some(&i)=vertex_index.get(&vert){
|
if let Some(&i)=vertex_index.get(&vert){
|
||||||
indices.push(i);
|
indices.push(i as u16);
|
||||||
}else{
|
}else{
|
||||||
let i=vertices.len() as u16;
|
let i=vertices.len() as u16;
|
||||||
vertices.push(Vertex {
|
vertices.push(Vertex {
|
||||||
@@ -213,14 +202,14 @@ fn add_obj(device:&wgpu::Device,modeldatas:& mut Vec<ModelData>,data:obj::ObjDat
|
|||||||
usage: wgpu::BufferUsages::VERTEX,
|
usage: wgpu::BufferUsages::VERTEX,
|
||||||
});
|
});
|
||||||
modeldatas.push(ModelData {
|
modeldatas.push(ModelData {
|
||||||
transforms: vec![glam::Mat4::default()],
|
transform: glam::Mat4::default(),
|
||||||
vertex_buf,
|
vertex_buf,
|
||||||
entities,
|
entities,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl strafe_client::framework::Example for GraphicsData {
|
impl strafe_client::framework::Example for Skybox {
|
||||||
fn optional_features() -> wgpu::Features {
|
fn optional_features() -> wgpu::Features {
|
||||||
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||||
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||||
@@ -234,40 +223,14 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let mut modeldatas = Vec::<ModelData>::new();
|
let mut modeldatas = Vec::<ModelData>::new();
|
||||||
let ground=obj::ObjData{
|
add_obj(device,& mut modeldatas,include_bytes!("../models/teslacyberv3.0.obj"));
|
||||||
position: vec![[-1.0,0.0,-1.0],[1.0,0.0,-1.0],[1.0,0.0,1.0],[-1.0,0.0,1.0]],
|
add_obj(device,& mut modeldatas,include_bytes!("../models/suzanne.obj"));
|
||||||
texture: vec![[-10.0,-10.0],[10.0,-10.0],[10.0,10.0],[-10.0,10.0]],
|
add_obj(device,& mut modeldatas,include_bytes!("../models/teapot.obj"));
|
||||||
normal: vec![[0.0,1.0,0.0]],
|
|
||||||
objects: vec![obj::Object{
|
|
||||||
name: "Ground Object".to_owned(),
|
|
||||||
groups: vec![obj::Group{
|
|
||||||
name: "Ground Group".to_owned(),
|
|
||||||
index: 0,
|
|
||||||
material: None,
|
|
||||||
polys: vec![obj::SimplePolygon(vec![
|
|
||||||
obj::IndexTuple(0,Some(0),Some(0)),
|
|
||||||
obj::IndexTuple(1,Some(1),Some(0)),
|
|
||||||
obj::IndexTuple(2,Some(2),Some(0)),
|
|
||||||
obj::IndexTuple(3,Some(3),Some(0)),
|
|
||||||
])]
|
|
||||||
}]
|
|
||||||
}],
|
|
||||||
material_libs: Vec::new(),
|
|
||||||
};
|
|
||||||
add_obj(device,& mut modeldatas,obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap());
|
|
||||||
add_obj(device,& mut modeldatas,obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap());
|
|
||||||
add_obj(device,& mut modeldatas,obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap());
|
|
||||||
add_obj(device,& mut modeldatas,ground);
|
|
||||||
println!("models.len = {:?}", modeldatas.len());
|
println!("models.len = {:?}", modeldatas.len());
|
||||||
modeldatas[0].transforms[0]=glam::Mat4::from_translation(glam::vec3(10.,0.,-10.));
|
modeldatas[1].transform=glam::Mat4::from_translation(glam::vec3(10.,5.,10.));
|
||||||
modeldatas[1].transforms[0]=glam::Mat4::from_translation(glam::vec3(10.,5.,10.));
|
modeldatas[2].transform=glam::Mat4::from_translation(glam::vec3(-10.,5.,10.));
|
||||||
modeldatas[1].transforms.push(glam::Mat4::from_translation(glam::vec3(20.,5.,10.)));
|
|
||||||
modeldatas[1].transforms.push(glam::Mat4::from_translation(glam::vec3(10.,5.,20.)));
|
|
||||||
modeldatas[1].transforms.push(glam::Mat4::from_translation(glam::vec3(20.,5.,20.)));
|
|
||||||
modeldatas[2].transforms[0]=glam::Mat4::from_translation(glam::vec3(-10.,5.,10.));
|
|
||||||
modeldatas[3].transforms[0]=glam::Mat4::from_translation(glam::vec3(0.,0.,0.))*glam::Mat4::from_scale(glam::vec3(160.0, 1.0, 160.0));
|
|
||||||
|
|
||||||
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
let main_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
label: None,
|
label: None,
|
||||||
entries: &[
|
entries: &[
|
||||||
wgpu::BindGroupLayoutEntry {
|
wgpu::BindGroupLayoutEntry {
|
||||||
@@ -280,13 +243,8 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
},
|
},
|
||||||
count: None,
|
count: None,
|
||||||
},
|
},
|
||||||
],
|
|
||||||
});
|
|
||||||
let skybox_texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
||||||
label: Some("Skybox Texture Bind Group Layout"),
|
|
||||||
entries: &[
|
|
||||||
wgpu::BindGroupLayoutEntry {
|
wgpu::BindGroupLayoutEntry {
|
||||||
binding: 0,
|
binding: 1,
|
||||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
ty: wgpu::BindingType::Texture {
|
ty: wgpu::BindingType::Texture {
|
||||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||||
@@ -295,37 +253,6 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
},
|
},
|
||||||
count: None,
|
count: None,
|
||||||
},
|
},
|
||||||
wgpu::BindGroupLayoutEntry {
|
|
||||||
binding: 1,
|
|
||||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
|
||||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
|
||||||
count: None,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
let model_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
||||||
label: Some("Model Bind Group Layout"),
|
|
||||||
entries: &[
|
|
||||||
wgpu::BindGroupLayoutEntry {
|
|
||||||
binding: 0,
|
|
||||||
visibility: wgpu::ShaderStages::VERTEX,
|
|
||||||
ty: wgpu::BindingType::Buffer {
|
|
||||||
ty: wgpu::BufferBindingType::Uniform,
|
|
||||||
has_dynamic_offset: false,
|
|
||||||
min_binding_size: None,
|
|
||||||
},
|
|
||||||
count: None,
|
|
||||||
},
|
|
||||||
wgpu::BindGroupLayoutEntry {
|
|
||||||
binding: 1,
|
|
||||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
|
||||||
ty: wgpu::BindingType::Texture {
|
|
||||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
|
||||||
multisampled: false,
|
|
||||||
view_dimension: wgpu::TextureViewDimension::D2,
|
|
||||||
},
|
|
||||||
count: None,
|
|
||||||
},
|
|
||||||
wgpu::BindGroupLayoutEntry {
|
wgpu::BindGroupLayoutEntry {
|
||||||
binding: 2,
|
binding: 2,
|
||||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
@@ -334,26 +261,20 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
let model_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
let clamp_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
label: None,
|
||||||
label: Some("Clamp Sampler"),
|
entries: &[
|
||||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
wgpu::BindGroupLayoutEntry {
|
||||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
binding: 0,
|
||||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
visibility: wgpu::ShaderStages::VERTEX,
|
||||||
mag_filter: wgpu::FilterMode::Linear,
|
ty: wgpu::BindingType::Buffer {
|
||||||
min_filter: wgpu::FilterMode::Linear,
|
ty: wgpu::BufferBindingType::Uniform,
|
||||||
mipmap_filter: wgpu::FilterMode::Linear,
|
has_dynamic_offset: false,
|
||||||
..Default::default()
|
min_binding_size: None,
|
||||||
});
|
},
|
||||||
let repeat_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
count: None,
|
||||||
label: Some("Repeat Sampler"),
|
},
|
||||||
address_mode_u: wgpu::AddressMode::Repeat,
|
],
|
||||||
address_mode_v: wgpu::AddressMode::Repeat,
|
|
||||||
address_mode_w: wgpu::AddressMode::Repeat,
|
|
||||||
mag_filter: wgpu::FilterMode::Linear,
|
|
||||||
min_filter: wgpu::FilterMode::Linear,
|
|
||||||
mipmap_filter: wgpu::FilterMode::Linear,
|
|
||||||
..Default::default()
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create the render pipeline
|
// Create the render pipeline
|
||||||
@@ -364,152 +285,43 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
|
|
||||||
let camera = Camera {
|
let camera = Camera {
|
||||||
screen_size: (config.width, config.height),
|
screen_size: (config.width, config.height),
|
||||||
offset: glam::Vec3::new(0.0,4.5-2.5,0.0),
|
offset: glam::Vec3::new(0.0,4.5,0.0),
|
||||||
fov: 1.0, //fov_slope = tan(fov_y/2)
|
fov: 1.0, //fov_slope = tan(fov_y/2)
|
||||||
pitch: 0.0,
|
pitch: 0.0,
|
||||||
yaw: 0.0,
|
yaw: 0.0,
|
||||||
controls:0,
|
controls:0,
|
||||||
};
|
};
|
||||||
let physics = strafe_client::body::PhysicsState {
|
let physics = strafe_client::body::PhysicsState {
|
||||||
body: strafe_client::body::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
|
body: strafe_client::body::Body {
|
||||||
|
position: glam::Vec3::new(5.0,0.0,5.0),
|
||||||
|
velocity: glam::Vec3::new(0.0,0.0,0.0),
|
||||||
|
time: 0,
|
||||||
|
},
|
||||||
time: 0,
|
time: 0,
|
||||||
tick: 0,
|
tick: 0,
|
||||||
strafe_tick_num: 100,//100t
|
strafe_tick_num: 100,//100t
|
||||||
strafe_tick_den: 1_000_000_000,
|
strafe_tick_den: 1_000_000_000,
|
||||||
gravity: glam::vec3(0.0,-100.0,0.0),
|
gravity: glam::Vec3::new(0.0,-100.0,0.0),
|
||||||
friction: 1.2,
|
friction: 90.0,
|
||||||
walk_accel: 90.0,
|
|
||||||
mv: 2.7,
|
mv: 2.7,
|
||||||
grounded: false,
|
grounded: true,
|
||||||
jump_trying: false,
|
jump_trying: false,
|
||||||
temp_control_dir: glam::Vec3::ZERO,
|
|
||||||
walkspeed: 18.0,
|
walkspeed: 18.0,
|
||||||
contacts: std::collections::HashSet::new(),
|
contacts: Vec::<strafe_client::body::RelativeCollision>::new(),
|
||||||
models_cringe_clone: modeldatas.iter().map(|m|m.transforms.iter().map(|t|strafe_client::body::Model::new(*t))).flatten().collect(),
|
models_cringe_clone: modeldatas.iter().map(|m|strafe_client::body::Model::new(m.transform)).collect(),
|
||||||
walk: strafe_client::body::WalkState::new(),
|
|
||||||
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
//load textures
|
let camera_uniforms = camera.to_uniform_data(physics.extrapolate_position(0));
|
||||||
let device_features = device.features();
|
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Camera"),
|
||||||
let skybox_texture_view={
|
contents: bytemuck::cast_slice(&camera_uniforms),
|
||||||
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||||
log::info!("Using ASTC");
|
});
|
||||||
wgpu::TextureFormat::Astc {
|
|
||||||
block: AstcBlock::B4x4,
|
|
||||||
channel: AstcChannel::UnormSrgb,
|
|
||||||
}
|
|
||||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
|
||||||
log::info!("Using ETC2");
|
|
||||||
wgpu::TextureFormat::Etc2Rgb8UnormSrgb
|
|
||||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
|
||||||
log::info!("Using BC");
|
|
||||||
wgpu::TextureFormat::Bc1RgbaUnormSrgb
|
|
||||||
} else {
|
|
||||||
log::info!("Using plain");
|
|
||||||
wgpu::TextureFormat::Bgra8UnormSrgb
|
|
||||||
};
|
|
||||||
|
|
||||||
let size = wgpu::Extent3d {
|
|
||||||
width: IMAGE_SIZE,
|
|
||||||
height: IMAGE_SIZE,
|
|
||||||
depth_or_array_layers: 6,
|
|
||||||
};
|
|
||||||
|
|
||||||
let layer_size = wgpu::Extent3d {
|
|
||||||
depth_or_array_layers: 1,
|
|
||||||
..size
|
|
||||||
};
|
|
||||||
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
|
||||||
|
|
||||||
log::debug!(
|
|
||||||
"Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu",
|
|
||||||
skybox_format,
|
|
||||||
IMAGE_SIZE,
|
|
||||||
IMAGE_SIZE,
|
|
||||||
max_mips,
|
|
||||||
);
|
|
||||||
|
|
||||||
let bytes = match skybox_format {
|
|
||||||
wgpu::TextureFormat::Astc {
|
|
||||||
block: AstcBlock::B4x4,
|
|
||||||
channel: AstcChannel::UnormSrgb,
|
|
||||||
} => &include_bytes!("../images/astc.dds")[..],
|
|
||||||
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
|
|
||||||
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
|
|
||||||
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let skybox_image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap();
|
|
||||||
|
|
||||||
let skybox_texture = device.create_texture_with_data(
|
|
||||||
queue,
|
|
||||||
&wgpu::TextureDescriptor {
|
|
||||||
size,
|
|
||||||
mip_level_count: max_mips,
|
|
||||||
sample_count: 1,
|
|
||||||
dimension: wgpu::TextureDimension::D2,
|
|
||||||
format: skybox_format,
|
|
||||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
|
||||||
label: Some("Skybox Texture"),
|
|
||||||
view_formats: &[],
|
|
||||||
},
|
|
||||||
&skybox_image.data,
|
|
||||||
);
|
|
||||||
|
|
||||||
skybox_texture.create_view(&wgpu::TextureViewDescriptor {
|
|
||||||
label: Some("Skybox Texture View"),
|
|
||||||
dimension: Some(wgpu::TextureViewDimension::Cube),
|
|
||||||
..wgpu::TextureViewDescriptor::default()
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
//squid
|
|
||||||
let squid_texture_view={
|
|
||||||
let size = wgpu::Extent3d {
|
|
||||||
width: 1076,
|
|
||||||
height: 1076,
|
|
||||||
depth_or_array_layers: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
let layer_size = wgpu::Extent3d {
|
|
||||||
depth_or_array_layers: 1,
|
|
||||||
..size
|
|
||||||
};
|
|
||||||
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
|
||||||
|
|
||||||
let bytes = &include_bytes!("../images/squid.dds")[..];
|
|
||||||
|
|
||||||
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap();
|
|
||||||
|
|
||||||
let texture = device.create_texture_with_data(
|
|
||||||
queue,
|
|
||||||
&wgpu::TextureDescriptor {
|
|
||||||
size,
|
|
||||||
mip_level_count: max_mips,
|
|
||||||
sample_count: 1,
|
|
||||||
dimension: wgpu::TextureDimension::D2,
|
|
||||||
format: wgpu::TextureFormat::Bc7RgbaUnorm,
|
|
||||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
|
||||||
label: Some("Squid Texture"),
|
|
||||||
view_formats: &[],
|
|
||||||
},
|
|
||||||
&image.data,
|
|
||||||
);
|
|
||||||
|
|
||||||
texture.create_view(&wgpu::TextureViewDescriptor {
|
|
||||||
label: Some("Squid Texture View"),
|
|
||||||
dimension: Some(wgpu::TextureViewDimension::D2),
|
|
||||||
..wgpu::TextureViewDescriptor::default()
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
//drain the modeldata vec so entities can be /moved/ to models.entities
|
//drain the modeldata vec so entities can be /moved/ to models.entities
|
||||||
let mut models = Vec::<ModelGraphics>::with_capacity(modeldatas.len());
|
let mut models = Vec::<ModelGraphics>::with_capacity(modeldatas.len());
|
||||||
for (i,modeldata) in modeldatas.drain(..).enumerate() {
|
for (i,modeldata) in modeldatas.drain(..).enumerate() {
|
||||||
let model_uniforms = get_transform_uniform_data(&modeldata.transforms);
|
let model_uniforms = get_transform_uniform_data(&modeldata.transform);
|
||||||
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
label: Some(format!("ModelGraphics{}",i).as_str()),
|
label: Some(format!("ModelGraphics{}",i).as_str()),
|
||||||
contents: bytemuck::cast_slice(&model_uniforms),
|
contents: bytemuck::cast_slice(&model_uniforms),
|
||||||
@@ -522,20 +334,12 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
binding: 0,
|
binding: 0,
|
||||||
resource: model_buf.as_entire_binding(),
|
resource: model_buf.as_entire_binding(),
|
||||||
},
|
},
|
||||||
wgpu::BindGroupEntry {
|
|
||||||
binding: 1,
|
|
||||||
resource: wgpu::BindingResource::TextureView(&squid_texture_view),
|
|
||||||
},
|
|
||||||
wgpu::BindGroupEntry {
|
|
||||||
binding: 2,
|
|
||||||
resource: wgpu::BindingResource::Sampler(&repeat_sampler),
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
label: Some(format!("ModelGraphics{}",i).as_str()),
|
label: Some(format!("ModelGraphics{}",i).as_str()),
|
||||||
});
|
});
|
||||||
//all of these are being moved here
|
//all of these are being moved here
|
||||||
models.push(ModelGraphics{
|
models.push(ModelGraphics{
|
||||||
transforms: modeldata.transforms,
|
transform: modeldata.transform,
|
||||||
vertex_buf:modeldata.vertex_buf,
|
vertex_buf:modeldata.vertex_buf,
|
||||||
entities: modeldata.entities,
|
entities: modeldata.entities,
|
||||||
bind_group: model_bind_group,
|
bind_group: model_bind_group,
|
||||||
@@ -545,17 +349,13 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
|
|
||||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||||
label: None,
|
label: None,
|
||||||
bind_group_layouts: &[
|
bind_group_layouts: &[&main_bind_group_layout, &model_bind_group_layout],
|
||||||
&camera_bind_group_layout,
|
|
||||||
&model_bind_group_layout,
|
|
||||||
&skybox_texture_bind_group_layout,
|
|
||||||
],
|
|
||||||
push_constant_ranges: &[],
|
push_constant_ranges: &[],
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create the render pipelines
|
// Create the render pipelines
|
||||||
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
label: Some("Sky Pipeline"),
|
label: Some("Sky"),
|
||||||
layout: Some(&pipeline_layout),
|
layout: Some(&pipeline_layout),
|
||||||
vertex: wgpu::VertexState {
|
vertex: wgpu::VertexState {
|
||||||
module: &shader,
|
module: &shader,
|
||||||
@@ -581,12 +381,12 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
multisample: wgpu::MultisampleState::default(),
|
multisample: wgpu::MultisampleState::default(),
|
||||||
multiview: None,
|
multiview: None,
|
||||||
});
|
});
|
||||||
let model_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
let entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
label: Some("Model Pipeline"),
|
label: Some("Entity"),
|
||||||
layout: Some(&pipeline_layout),
|
layout: Some(&pipeline_layout),
|
||||||
vertex: wgpu::VertexState {
|
vertex: wgpu::VertexState {
|
||||||
module: &shader,
|
module: &shader,
|
||||||
entry_point: "vs_entity_texture",
|
entry_point: "vs_entity",
|
||||||
buffers: &[wgpu::VertexBufferLayout {
|
buffers: &[wgpu::VertexBufferLayout {
|
||||||
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
|
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
|
||||||
step_mode: wgpu::VertexStepMode::Vertex,
|
step_mode: wgpu::VertexStepMode::Vertex,
|
||||||
@@ -595,7 +395,34 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
},
|
},
|
||||||
fragment: Some(wgpu::FragmentState {
|
fragment: Some(wgpu::FragmentState {
|
||||||
module: &shader,
|
module: &shader,
|
||||||
entry_point: "fs_entity_texture",
|
entry_point: "fs_entity",
|
||||||
|
targets: &[Some(config.view_formats[0].into())],
|
||||||
|
}),
|
||||||
|
primitive: wgpu::PrimitiveState {
|
||||||
|
front_face: wgpu::FrontFace::Cw,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
depth_stencil: Some(wgpu::DepthStencilState {
|
||||||
|
format: Self::DEPTH_FORMAT,
|
||||||
|
depth_write_enabled: true,
|
||||||
|
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||||
|
stencil: wgpu::StencilState::default(),
|
||||||
|
bias: wgpu::DepthBiasState::default(),
|
||||||
|
}),
|
||||||
|
multisample: wgpu::MultisampleState::default(),
|
||||||
|
multiview: None,
|
||||||
|
});
|
||||||
|
let ground_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
|
label: Some("Ground"),
|
||||||
|
layout: Some(&pipeline_layout),
|
||||||
|
vertex: wgpu::VertexState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "vs_ground",
|
||||||
|
buffers: &[],
|
||||||
|
},
|
||||||
|
fragment: Some(wgpu::FragmentState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "fs_ground",
|
||||||
targets: &[Some(config.view_formats[0].into())],
|
targets: &[Some(config.view_formats[0].into())],
|
||||||
}),
|
}),
|
||||||
primitive: wgpu::PrimitiveState {
|
primitive: wgpu::PrimitiveState {
|
||||||
@@ -613,51 +440,118 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
multiview: None,
|
multiview: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let camera_uniforms = camera.to_uniform_data(physics.body.extrapolated_position(0));
|
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||||
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
label: None,
|
||||||
label: Some("Camera"),
|
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||||
contents: bytemuck::cast_slice(&camera_uniforms),
|
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||||
|
mag_filter: wgpu::FilterMode::Linear,
|
||||||
|
min_filter: wgpu::FilterMode::Linear,
|
||||||
|
mipmap_filter: wgpu::FilterMode::Linear,
|
||||||
|
..Default::default()
|
||||||
});
|
});
|
||||||
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
||||||
layout: &camera_bind_group_layout,
|
let device_features = device.features();
|
||||||
|
|
||||||
|
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
|
||||||
|
log::info!("Using ASTC");
|
||||||
|
wgpu::TextureFormat::Astc {
|
||||||
|
block: AstcBlock::B4x4,
|
||||||
|
channel: AstcChannel::UnormSrgb,
|
||||||
|
}
|
||||||
|
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
||||||
|
log::info!("Using ETC2");
|
||||||
|
wgpu::TextureFormat::Etc2Rgb8UnormSrgb
|
||||||
|
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
||||||
|
log::info!("Using BC");
|
||||||
|
wgpu::TextureFormat::Bc1RgbaUnormSrgb
|
||||||
|
} else {
|
||||||
|
log::info!("Using plain");
|
||||||
|
wgpu::TextureFormat::Bgra8UnormSrgb
|
||||||
|
};
|
||||||
|
|
||||||
|
let size = wgpu::Extent3d {
|
||||||
|
width: IMAGE_SIZE,
|
||||||
|
height: IMAGE_SIZE,
|
||||||
|
depth_or_array_layers: 6,
|
||||||
|
};
|
||||||
|
|
||||||
|
let layer_size = wgpu::Extent3d {
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
..size
|
||||||
|
};
|
||||||
|
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||||
|
|
||||||
|
log::debug!(
|
||||||
|
"Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu",
|
||||||
|
skybox_format,
|
||||||
|
IMAGE_SIZE,
|
||||||
|
IMAGE_SIZE,
|
||||||
|
max_mips,
|
||||||
|
);
|
||||||
|
|
||||||
|
let bytes = match skybox_format {
|
||||||
|
wgpu::TextureFormat::Astc {
|
||||||
|
block: AstcBlock::B4x4,
|
||||||
|
channel: AstcChannel::UnormSrgb,
|
||||||
|
} => &include_bytes!("../images/astc.dds")[..],
|
||||||
|
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
|
||||||
|
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
|
||||||
|
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap();
|
||||||
|
|
||||||
|
let texture = device.create_texture_with_data(
|
||||||
|
queue,
|
||||||
|
&wgpu::TextureDescriptor {
|
||||||
|
size,
|
||||||
|
mip_level_count: max_mips,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: wgpu::TextureDimension::D2,
|
||||||
|
format: skybox_format,
|
||||||
|
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||||
|
label: None,
|
||||||
|
view_formats: &[],
|
||||||
|
},
|
||||||
|
&image.data,
|
||||||
|
);
|
||||||
|
|
||||||
|
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||||
|
label: None,
|
||||||
|
dimension: Some(wgpu::TextureViewDimension::Cube),
|
||||||
|
..wgpu::TextureViewDescriptor::default()
|
||||||
|
});
|
||||||
|
let main_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &main_bind_group_layout,
|
||||||
entries: &[
|
entries: &[
|
||||||
wgpu::BindGroupEntry {
|
wgpu::BindGroupEntry {
|
||||||
binding: 0,
|
binding: 0,
|
||||||
resource: camera_buf.as_entire_binding(),
|
resource: camera_buf.as_entire_binding(),
|
||||||
},
|
},
|
||||||
],
|
|
||||||
label: Some("Camera"),
|
|
||||||
});
|
|
||||||
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
||||||
layout: &skybox_texture_bind_group_layout,
|
|
||||||
entries: &[
|
|
||||||
wgpu::BindGroupEntry {
|
|
||||||
binding: 0,
|
|
||||||
resource: wgpu::BindingResource::TextureView(&skybox_texture_view),
|
|
||||||
},
|
|
||||||
wgpu::BindGroupEntry {
|
wgpu::BindGroupEntry {
|
||||||
binding: 1,
|
binding: 1,
|
||||||
resource: wgpu::BindingResource::Sampler(&clamp_sampler),
|
resource: wgpu::BindingResource::TextureView(&texture_view),
|
||||||
|
},
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 2,
|
||||||
|
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
label: Some("Sky Texture"),
|
label: Some("Camera"),
|
||||||
});
|
});
|
||||||
|
|
||||||
let depth_view = Self::create_depth_texture(config, device);
|
let depth_view = Self::create_depth_texture(config, device);
|
||||||
|
|
||||||
GraphicsData {
|
Skybox {
|
||||||
start_time: Instant::now(),
|
start_time: Instant::now(),
|
||||||
camera,
|
camera,
|
||||||
physics,
|
physics,
|
||||||
pipelines:GraphicsPipelines{
|
sky_pipeline,
|
||||||
skybox:sky_pipeline,
|
entity_pipeline,
|
||||||
model:model_pipeline
|
ground_pipeline,
|
||||||
},
|
main_bind_group,
|
||||||
bind_groups:GraphicsBindGroups{
|
|
||||||
camera:camera_bind_group,
|
|
||||||
skybox_texture:skybox_texture_bind_group,
|
|
||||||
},
|
|
||||||
camera_buf,
|
camera_buf,
|
||||||
models,
|
models,
|
||||||
depth_view,
|
depth_view,
|
||||||
@@ -739,45 +633,18 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
_spawner: &strafe_client::framework::Spawner,
|
_spawner: &strafe_client::framework::Spawner,
|
||||||
) {
|
) {
|
||||||
let camera_mat=glam::Mat3::from_rotation_y(self.camera.yaw);
|
let camera_mat=glam::Mat3::from_euler(glam::EulerRot::YXZ,self.camera.yaw,0f32,0f32);
|
||||||
let control_dir=camera_mat*get_control_dir(self.camera.controls&(CONTROL_MOVELEFT|CONTROL_MOVERIGHT|CONTROL_MOVEFORWARD|CONTROL_MOVEBACK)).normalize_or_zero();
|
let control_dir=camera_mat*get_control_dir(self.camera.controls&(CONTROL_MOVELEFT|CONTROL_MOVERIGHT|CONTROL_MOVEFORWARD|CONTROL_MOVEBACK)).normalize_or_zero();
|
||||||
|
|
||||||
let time=self.start_time.elapsed().as_nanos() as i64;
|
let time=self.start_time.elapsed().as_nanos() as i64;
|
||||||
|
|
||||||
self.physics.run(time);
|
self.physics.run(time,control_dir,self.camera.controls);
|
||||||
|
|
||||||
//ALL OF THIS IS TOTALLY WRONG!!!
|
|
||||||
let walk_target_velocity=self.physics.walkspeed*control_dir;
|
|
||||||
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
|
|
||||||
if self.physics.grounded&&walk_target_velocity!=self.physics.walk.target_velocity {
|
|
||||||
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{
|
|
||||||
time,
|
|
||||||
instruction:strafe_client::body::PhysicsInstruction::SetWalkTargetVelocity(walk_target_velocity)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if control_dir!=self.physics.temp_control_dir {
|
|
||||||
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{
|
|
||||||
time,
|
|
||||||
instruction:strafe_client::body::PhysicsInstruction::SetControlDir(control_dir)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
self.physics.jump_trying=self.camera.controls&CONTROL_JUMP!=0;
|
|
||||||
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
|
|
||||||
if self.physics.grounded&&self.physics.jump_trying {
|
|
||||||
//scroll will be implemented with InputInstruction::Jump(true) but it blocks setting self.jump_trying=true
|
|
||||||
strafe_client::instruction::InstructionConsumer::process_instruction(&mut self.physics, strafe_client::instruction::TimedInstruction{
|
|
||||||
time,
|
|
||||||
instruction:strafe_client::body::PhysicsInstruction::Jump
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut encoder =
|
let mut encoder =
|
||||||
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||||
|
|
||||||
// update rotation
|
// update rotation
|
||||||
let camera_uniforms = self.camera.to_uniform_data(self.physics.body.extrapolated_position(time));
|
let camera_uniforms = self.camera.to_uniform_data(self.physics.extrapolate_position(time));
|
||||||
self.staging_belt
|
self.staging_belt
|
||||||
.write_buffer(
|
.write_buffer(
|
||||||
&mut encoder,
|
&mut encoder,
|
||||||
@@ -789,7 +656,7 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
||||||
//This code only needs to run when the uniforms change
|
//This code only needs to run when the uniforms change
|
||||||
for model in self.models.iter() {
|
for model in self.models.iter() {
|
||||||
let model_uniforms = get_transform_uniform_data(&model.transforms);
|
let model_uniforms = get_transform_uniform_data(&model.transform);
|
||||||
self.staging_belt
|
self.staging_belt
|
||||||
.write_buffer(
|
.write_buffer(
|
||||||
&mut encoder,
|
&mut encoder,
|
||||||
@@ -828,21 +695,25 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
|
rpass.set_bind_group(0, &self.main_bind_group, &[]);
|
||||||
rpass.set_bind_group(2, &self.bind_groups.skybox_texture, &[]);
|
|
||||||
|
|
||||||
rpass.set_pipeline(&self.pipelines.model);
|
rpass.set_pipeline(&self.entity_pipeline);
|
||||||
for model in self.models.iter() {
|
for model in self.models.iter() {
|
||||||
rpass.set_bind_group(1, &model.bind_group, &[]);
|
rpass.set_bind_group(1, &model.bind_group, &[]);
|
||||||
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
||||||
|
|
||||||
for entity in model.entities.iter() {
|
for entity in model.entities.iter() {
|
||||||
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
|
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
|
||||||
rpass.draw_indexed(0..entity.index_count, 0, 0..model.transforms.len() as u32);
|
rpass.draw_indexed(0..entity.index_count, 0, 0..1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
rpass.set_pipeline(&self.pipelines.skybox);
|
rpass.set_pipeline(&self.ground_pipeline);
|
||||||
|
//rpass.set_index_buffer(&[0u16,1,2,1,2,3][..] as wgpu::BufferSlice, wgpu::IndexFormat::Uint16);
|
||||||
|
//rpass.draw_indexed(0..4, 0, 0..1);
|
||||||
|
rpass.draw(0..6, 0..1);
|
||||||
|
|
||||||
|
rpass.set_pipeline(&self.sky_pipeline);
|
||||||
rpass.draw(0..3, 0..1);
|
rpass.draw(0..3, 0..1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -853,7 +724,7 @@ impl strafe_client::framework::Example for GraphicsData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
strafe_client::framework::run::<GraphicsData>(
|
strafe_client::framework::run::<Skybox>(
|
||||||
format!("Strafe Client v{}",
|
format!("Strafe Client v{}",
|
||||||
env!("CARGO_PKG_VERSION")
|
env!("CARGO_PKG_VERSION")
|
||||||
).as_str()
|
).as_str()
|
||||||
|
|||||||
120
src/shader.wgsl
120
src/shader.wgsl
@@ -1,4 +1,9 @@
|
|||||||
struct Camera {
|
struct SkyOutput {
|
||||||
|
@builtin(position) position: vec4<f32>,
|
||||||
|
@location(0) sampledir: vec3<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Data {
|
||||||
// from camera to screen
|
// from camera to screen
|
||||||
proj: mat4x4<f32>,
|
proj: mat4x4<f32>,
|
||||||
// from screen to camera
|
// from screen to camera
|
||||||
@@ -8,16 +13,9 @@ struct Camera {
|
|||||||
// camera position
|
// camera position
|
||||||
cam_pos: vec4<f32>,
|
cam_pos: vec4<f32>,
|
||||||
};
|
};
|
||||||
|
|
||||||
//group 0 is the camera
|
|
||||||
@group(0)
|
@group(0)
|
||||||
@binding(0)
|
@binding(0)
|
||||||
var<uniform> camera: Camera;
|
var<uniform> r_data: Data;
|
||||||
|
|
||||||
struct SkyOutput {
|
|
||||||
@builtin(position) position: vec4<f32>,
|
|
||||||
@location(0) sampledir: vec3<f32>,
|
|
||||||
};
|
|
||||||
|
|
||||||
@vertex
|
@vertex
|
||||||
fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||||
@@ -32,8 +30,8 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// transposition = inversion for this orthonormal matrix
|
// transposition = inversion for this orthonormal matrix
|
||||||
let inv_model_view = transpose(mat3x3<f32>(camera.view[0].xyz, camera.view[1].xyz, camera.view[2].xyz));
|
let inv_model_view = transpose(mat3x3<f32>(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz));
|
||||||
let unprojected = camera.proj_inv * pos;
|
let unprojected = r_data.proj_inv * pos;
|
||||||
|
|
||||||
var result: SkyOutput;
|
var result: SkyOutput;
|
||||||
result.sampledir = inv_model_view * unprojected.xyz;
|
result.sampledir = inv_model_view * unprojected.xyz;
|
||||||
@@ -41,65 +39,93 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_ENTITY_INSTANCES=1024;
|
struct GroundOutput {
|
||||||
//group 1 is the model
|
@builtin(position) position: vec4<f32>,
|
||||||
@group(1)
|
@location(4) pos: vec3<f32>,
|
||||||
@binding(0)
|
};
|
||||||
var<uniform> entity_transforms: array<mat4x4<f32>,MAX_ENTITY_INSTANCES>;
|
|
||||||
//var<uniform> entity_texture_transforms: array<mat3x3<f32>,MAX_ENTITY_INSTANCES>;
|
|
||||||
//my fancy idea is to create a megatexture for each model that includes all the textures each intance will need
|
|
||||||
//the texture transform then maps the texture coordinates to the location of the specific texture
|
|
||||||
//how to do no texture?
|
|
||||||
@group(1)
|
|
||||||
@binding(1)
|
|
||||||
var model_texture: texture_2d<f32>;
|
|
||||||
@group(1)
|
|
||||||
@binding(2)
|
|
||||||
var model_sampler: sampler;
|
|
||||||
|
|
||||||
struct EntityOutputTexture {
|
@vertex
|
||||||
|
fn vs_ground(@builtin(vertex_index) vertex_index: u32) -> GroundOutput {
|
||||||
|
// hacky way to draw two triangles that make a square
|
||||||
|
let tmp1 = i32(vertex_index)/2-i32(vertex_index)/3;
|
||||||
|
let tmp2 = i32(vertex_index)&1;
|
||||||
|
let pos = vec3<f32>(
|
||||||
|
f32(tmp1) * 2.0 - 1.0,
|
||||||
|
0.0,
|
||||||
|
f32(tmp2) * 2.0 - 1.0
|
||||||
|
) * 160.0;
|
||||||
|
|
||||||
|
var result: GroundOutput;
|
||||||
|
result.pos = pos;
|
||||||
|
result.position = r_data.proj * r_data.view * vec4<f32>(pos, 1.0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EntityOutput {
|
||||||
@builtin(position) position: vec4<f32>,
|
@builtin(position) position: vec4<f32>,
|
||||||
@location(1) texture: vec2<f32>,
|
@location(1) texture: vec2<f32>,
|
||||||
@location(2) normal: vec3<f32>,
|
@location(2) normal: vec3<f32>,
|
||||||
@location(3) view: vec3<f32>,
|
@location(3) view: vec3<f32>,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@group(1)
|
||||||
|
@binding(0)
|
||||||
|
var<uniform> r_EntityTransform: mat4x4<f32>;
|
||||||
|
|
||||||
@vertex
|
@vertex
|
||||||
fn vs_entity_texture(
|
fn vs_entity(
|
||||||
@builtin(instance_index) instance: u32,
|
|
||||||
@location(0) pos: vec3<f32>,
|
@location(0) pos: vec3<f32>,
|
||||||
@location(1) texture: vec2<f32>,
|
@location(1) texture: vec2<f32>,
|
||||||
@location(2) normal: vec3<f32>,
|
@location(2) normal: vec3<f32>,
|
||||||
) -> EntityOutputTexture {
|
) -> EntityOutput {
|
||||||
var position: vec4<f32> = entity_transforms[instance] * vec4<f32>(pos, 1.0);
|
var position: vec4<f32> = r_EntityTransform * vec4<f32>(pos, 1.0);
|
||||||
var result: EntityOutputTexture;
|
var result: EntityOutput;
|
||||||
result.normal = (entity_transforms[instance] * vec4<f32>(normal, 0.0)).xyz;
|
result.normal = (r_EntityTransform * vec4<f32>(normal, 0.0)).xyz;
|
||||||
result.texture=texture;//(entity_texture_transforms[instance] * vec3<f32>(texture, 1.0)).xy;
|
result.texture=texture;
|
||||||
result.view = position.xyz - camera.cam_pos.xyz;
|
result.view = position.xyz - r_data.cam_pos.xyz;
|
||||||
result.position = camera.proj * camera.view * position;
|
result.position = r_data.proj * r_data.view * position;
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
//group 2 is the skybox texture
|
@group(0)
|
||||||
@group(2)
|
|
||||||
@binding(0)
|
|
||||||
var cube_texture: texture_cube<f32>;
|
|
||||||
@group(2)
|
|
||||||
@binding(1)
|
@binding(1)
|
||||||
var cube_sampler: sampler;
|
var r_texture: texture_cube<f32>;
|
||||||
|
@group(0)
|
||||||
|
@binding(2)
|
||||||
|
var r_sampler: sampler;
|
||||||
|
|
||||||
@fragment
|
@fragment
|
||||||
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
|
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
|
||||||
return textureSample(cube_texture, model_sampler, vertex.sampledir);
|
return textureSample(r_texture, r_sampler, vertex.sampledir);
|
||||||
}
|
}
|
||||||
|
|
||||||
@fragment
|
@fragment
|
||||||
fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
|
fn fs_entity(vertex: EntityOutput) -> @location(0) vec4<f32> {
|
||||||
let incident = normalize(vertex.view);
|
let incident = normalize(vertex.view);
|
||||||
let normal = normalize(vertex.normal);
|
let normal = normalize(vertex.normal);
|
||||||
let d = dot(normal, incident);
|
let d = dot(normal, incident);
|
||||||
let reflected = incident - 2.0 * d * normal;
|
let reflected = incident - 2.0 * d * normal;
|
||||||
|
|
||||||
let fragment_color = textureSample(model_texture, model_sampler, vertex.texture).rgb;
|
let dir = vec3<f32>(-1.0)+2.0*vec3<f32>(vertex.texture.x,0.0,vertex.texture.y);
|
||||||
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
|
let texture_color = textureSample(r_texture, r_sampler, dir).rgb;
|
||||||
return vec4<f32>(mix(vec3<f32>(0.1) + 0.5 * reflected_color,fragment_color,1.0-pow(1.0-abs(d),2.0)), 1.0);
|
let reflected_color = textureSample(r_texture, r_sampler, reflected).rgb;
|
||||||
|
return vec4<f32>(mix(vec3<f32>(0.1) + 0.5 * reflected_color,texture_color,1.0-pow(1.0-abs(d),2.0)), 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modulo_euclidean (a: f32, b: f32) -> f32 {
|
||||||
|
var m = a % b;
|
||||||
|
if (m < 0.0) {
|
||||||
|
if (b < 0.0) {
|
||||||
|
m -= b;
|
||||||
|
} else {
|
||||||
|
m += b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
@fragment
|
||||||
|
fn fs_ground(vertex: GroundOutput) -> @location(0) vec4<f32> {
|
||||||
|
let dir = vec3<f32>(-1.0)+vec3<f32>(modulo_euclidean(vertex.pos.x/16.,1.0),0.0,modulo_euclidean(vertex.pos.z/16.,1.0))*2.0;
|
||||||
|
return vec4<f32>(textureSample(r_texture, r_sampler, dir).rgb, 1.0);
|
||||||
}
|
}
|
||||||
|
|||||||
47
src/timelines.rs
Normal file
47
src/timelines.rs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
type ORDER = u32;
|
||||||
|
|
||||||
|
pub struct Tracker {
|
||||||
|
order: ORDER,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TimelineInstruction<I>{
|
||||||
|
pub order: ORDER,//absolute ordering of instructions which can be used for sorting even when there are multiple simultaneous timestamps
|
||||||
|
pub instruction: crate::instruction::TimedInstruction<I>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Timeline<I>{
|
||||||
|
instructions: std::collections::VecDeque<TimelineInstruction<I>>,
|
||||||
|
trackers: Vec<Tracker>,//wrong
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<I> Timeline<I>{
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self{
|
||||||
|
instructions:std::collections::VecDeque::<TimelineInstruction<I>>::new(),
|
||||||
|
trackers:Vec::<Tracker>::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
return self.instructions.len()
|
||||||
|
}
|
||||||
|
pub fn first(&self) -> Option<&TimelineInstruction<I>> {
|
||||||
|
return self.instructions.get(0)
|
||||||
|
}
|
||||||
|
pub fn last(&self) -> Option<&TimelineInstruction<I>> {
|
||||||
|
return self.instructions.get(self.instructions.len()-1)
|
||||||
|
}
|
||||||
|
pub fn append(&mut self,instruction:TimelineInstruction<I>){
|
||||||
|
let i=self.instructions.len();
|
||||||
|
self.instructions.push_back(instruction);
|
||||||
|
for tracker in self.trackers.iter() {
|
||||||
|
tracker.set_active(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn get_index_after_time(&mut self,time:crate::body::TIME) -> usize{
|
||||||
|
self.instructions.partition_point(|ins|ins.instruction.time<time)
|
||||||
|
}
|
||||||
|
pub fn get_index_after_order(&mut self,order:ORDER) -> usize{
|
||||||
|
self.instructions.partition_point(|ins|ins.order<order)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
//find roots of polynomials
|
|
||||||
pub fn zeroes2(a0:f32,a1:f32,a2:f32) -> Vec<f32>{
|
|
||||||
if a2==0f32{
|
|
||||||
return zeroes1(a0, a1);
|
|
||||||
}
|
|
||||||
let mut radicand=a1*a1-4f32*a2*a0;
|
|
||||||
if 0f32<radicand {
|
|
||||||
radicand=radicand.sqrt();
|
|
||||||
if 0f32<a2 {
|
|
||||||
return vec![(-a1-radicand)/(2f32*a2),(-a1+radicand)/(2f32*a2)];
|
|
||||||
} else {
|
|
||||||
return vec![(-a1+radicand)/(2f32*a2),(-a1-radicand)/(2f32*a2)];
|
|
||||||
}
|
|
||||||
} else if radicand==0f32 {
|
|
||||||
return vec![-a1/(2f32*a2)];
|
|
||||||
} else {
|
|
||||||
return vec![];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[inline]
|
|
||||||
pub fn zeroes1(a0:f32,a1:f32) -> Vec<f32> {
|
|
||||||
if a1==0f32{
|
|
||||||
return vec![];
|
|
||||||
} else {
|
|
||||||
return vec![-a0/a1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user