Compare commits

...

17 Commits
web ... suzanne

Author SHA1 Message Date
28ffc28dca buffer binding array? 2023-09-05 12:02:54 -07:00
7b5ce3feb1 dedicated staging belt 2023-09-05 12:02:54 -07:00
d2fdb5d94b entity_id trash 2023-09-05 12:02:54 -07:00
b68dfa791d array + instance_index is not the way 2023-09-05 12:02:54 -07:00
2df929c15f no fragment 2023-09-05 12:02:54 -07:00
1746d5445c add entity CFrames 2023-09-01 15:24:45 -07:00
5dbe207d39 comment on value 2023-09-01 14:57:38 -07:00
a853eb965e rename uniform_buf to camera_buf 2023-09-01 14:57:04 -07:00
ba2bab562f add suzanne 2023-09-01 14:22:12 -07:00
ce5f6fceb9 modulo is implemented incorrectly by the shader language 2023-09-01 00:10:19 -07:00
7179f20e67 add zoom 2023-08-31 22:48:17 -07:00
e25a2d7a7a use slope fov 2023-08-31 22:47:55 -07:00
7c247b6949 fix strafe bug 2023-08-31 12:37:53 -07:00
49fde16c4f rbhop friction 2023-08-31 12:16:51 -07:00
403910d2d8 rbhop jump power 2023-08-31 12:10:49 -07:00
7a23ef2734 add walking 2023-08-31 12:04:18 -07:00
1e25f71618 brain lol 2023-08-31 02:21:39 -07:00
3 changed files with 2756 additions and 66 deletions

2580
models/suzanne.obj Normal file

File diff suppressed because it is too large Load Diff

@ -1,5 +1,5 @@
use bytemuck::{Pod, Zeroable};
use std::{borrow::Cow, f32::consts,time::Instant};
use std::{borrow::Cow, time::Instant};
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
const IMAGE_SIZE: u32 = 128;
@ -9,9 +9,11 @@ const IMAGE_SIZE: u32 = 128;
struct Vertex {
pos: [f32; 3],
normal: [f32; 3],
entity_id: u32,
}
struct Entity {
transform: glam::Affine3A,
vertex_count: u32,
vertex_buf: wgpu::Buffer,
}
@ -25,13 +27,17 @@ struct Camera {
friction: f32,
screen_size: (u32, u32),
offset: glam::Vec3,
fov: f32,
yaw: f32,
pitch: f32,
controls: u32,
mv: f32,
grounded: bool,
walkspeed: f32,
}
const MAGIC_ENTITIES: usize = 7;
const CONTROL_MOVEFORWARD:u32 = 0b00000001;
const CONTROL_MOVEBACK:u32 = 0b00000010;
const CONTROL_MOVERIGHT:u32 = 0b00000100;
@ -39,7 +45,7 @@ const CONTROL_MOVELEFT:u32 = 0b00001000;
const CONTROL_MOVEUP:u32 = 0b00010000;
const CONTROL_MOVEDOWN:u32 = 0b00100000;
const CONTROL_JUMP:u32 = 0b01000000;
//const CONTROL_ZOOM:u32 = 0b10000000;
const CONTROL_ZOOM:u32 = 0b10000000;
const FORWARD_DIR:glam::Vec3 = glam::Vec3::new(0.0,0.0,-1.0);
const RIGHT_DIR:glam::Vec3 = glam::Vec3::new(1.0,0.0,0.0);
@ -69,10 +75,27 @@ fn get_control_dir(controls: u32) -> glam::Vec3{
return control_dir
}
#[inline]
fn perspective_rh(fov_y_slope: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
//glam_assert!(z_near > 0.0 && z_far > 0.0);
let r = z_far / (z_near - z_far);
glam::Mat4::from_cols(
glam::Vec4::new(1.0/(fov_y_slope * aspect_ratio), 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, r, -1.0),
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
)
}
impl Camera {
fn to_uniform_data(&self) -> [f32; 16 * 3 + 4] {
let aspect = self.screen_size.0 as f32 / self.screen_size.1 as f32;
let proj = glam::Mat4::perspective_rh(consts::FRAC_PI_2, aspect, 1.0, 200.0);
let fov = if self.controls&CONTROL_ZOOM==0 {
self.fov
}else{
self.fov/5.0
};
let proj = perspective_rh(fov, aspect, 1.0, 200.0);
let view = (glam::Mat4::from_translation(self.pos+self.offset) * glam::Mat4::from_euler(glam::EulerRot::YXZ, self.yaw, self.pitch, 0f32)).inverse();
let proj_inv = proj.inverse();
@ -81,7 +104,7 @@ impl Camera {
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view)[..]);
raw[48..51].copy_from_slice(AsRef::<[f32; 3]>::as_ref(&self.pos));
raw[51] = 1.0;
raw[51] = 1.0;//cam_pos is vec4
raw
}
}
@ -92,10 +115,12 @@ pub struct Skybox {
entity_pipeline: wgpu::RenderPipeline,
ground_pipeline: wgpu::RenderPipeline,
bind_group: wgpu::BindGroup,
uniform_buf: wgpu::Buffer,
camera_buf: wgpu::Buffer,
entity_buf: wgpu::Buffer,
entities: Vec<Entity>,
depth_view: wgpu::TextureView,
staging_belt: wgpu::util::StagingBelt,
camera_stagingbelt: wgpu::util::StagingBelt,
entity_stagingbelt: wgpu::util::StagingBelt,
}
impl Skybox {
@ -124,11 +149,55 @@ impl Skybox {
}
}
fn get_entity_uniform_data(entities:& Vec<Entity>) -> [f32; (9+3)*MAGIC_ENTITIES] {
let mut raw = [0f32; (9+3)*MAGIC_ENTITIES];
for (i,entity) in entities.iter().enumerate() {
raw[i*12..(i+1)*12-3].copy_from_slice(&AsRef::<[f32; 9]>::as_ref(&glam::Mat3::from(entity.transform.matrix3))[..]);
raw[i*12+9..(i+1)*12].copy_from_slice(AsRef::<[f32; 3]>::as_ref(&glam::Vec3::from(entity.transform.translation)));
}
raw
}
fn add_obj(device:&wgpu::Device,entities:& mut Vec<Entity>,source:&[u8]){
let data = obj::ObjData::load_buf(&source[..]).unwrap();
let mut vertices = Vec::new();
for object in data.objects {
for group in object.groups {
vertices.clear();
let entity_id = entities.len() as u32;
for poly in group.polys {
for end_index in 2..poly.0.len() {
for &index in &[0, end_index - 1, end_index] {
let obj::IndexTuple(position_id, _texture_id, normal_id) =
poly.0[index];
vertices.push(Vertex {
pos: data.position[position_id],
normal: data.normal[normal_id.unwrap()],
entity_id,
})
}
}
}
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex"),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
entities.push(Entity {
transform: glam::Affine3A::default(),
vertex_count: vertices.len() as u32,
vertex_buf,
});
}
}
}
impl strafe_client::framework::Example for Skybox {
fn optional_features() -> wgpu::Features {
wgpu::Features::TEXTURE_COMPRESSION_ASTC
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
| wgpu::Features::TEXTURE_COMPRESSION_BC
| wgpu::Features::BUFFER_BINDING_ARRAY
}
fn init(
@ -137,45 +206,18 @@ impl strafe_client::framework::Example for Skybox {
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Self {
let mut entities = Vec::new();
{
let source = include_bytes!("../models/teslacyberv3.0.obj");
let data = obj::ObjData::load_buf(&source[..]).unwrap();
let mut vertices = Vec::new();
for object in data.objects {
for group in object.groups {
vertices.clear();
for poly in group.polys {
for end_index in 2..poly.0.len() {
for &index in &[0, end_index - 1, end_index] {
let obj::IndexTuple(position_id, _texture_id, normal_id) =
poly.0[index];
vertices.push(Vertex {
pos: data.position[position_id],
normal: data.normal[normal_id.unwrap()],
})
}
}
}
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex"),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
entities.push(Entity {
vertex_count: vertices.len() as u32,
vertex_buf,
});
}
}
}
let mut entities = Vec::<Entity>::new();
add_obj(device,& mut entities,include_bytes!("../models/teslacyberv3.0.obj"));
add_obj(device,& mut entities,include_bytes!("../models/suzanne.obj"));
println!("entities.len = {:?}", entities.len());
entities[6].transform=glam::Affine3A::from_translation(glam::vec3(10.,5.,10.));
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
@ -199,6 +241,16 @@ impl strafe_client::framework::Example for Skybox {
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: Some(std::num::NonZeroU32::new(MAGIC_ENTITIES as u32).unwrap()),
},
],
});
@ -213,19 +265,28 @@ impl strafe_client::framework::Example for Skybox {
pos: glam::Vec3::new(5.0,0.0,5.0),
vel: glam::Vec3::new(0.0,0.0,0.0),
gravity: glam::Vec3 { x: 0.0, y: -100.0, z: 0.0 },
friction: 80.0,
friction: 90.0,
screen_size: (config.width, config.height),
offset: glam::Vec3::new(0.0,4.5,0.0),
fov: 1.0, //fov_slope = tan(fov_y/2)
pitch: 0.0,
yaw: 0.0,
mv: 2.7,
controls:0,
grounded: true,
walkspeed: 18.0,
};
let raw_uniforms = camera.to_uniform_data();
let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Buffer"),
contents: bytemuck::cast_slice(&raw_uniforms),
let camera_uniforms = camera.to_uniform_data();
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Camera"),
contents: bytemuck::cast_slice(&camera_uniforms),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
let entity_uniforms = get_entity_uniform_data(&entities);
let entity_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("EntityData"),
contents: bytemuck::cast_slice(&entity_uniforms),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
});
@ -272,7 +333,7 @@ impl strafe_client::framework::Example for Skybox {
buffers: &[wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3],
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Uint32],
}],
},
fragment: Some(wgpu::FragmentState {
@ -410,7 +471,7 @@ impl strafe_client::framework::Example for Skybox {
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buf.as_entire_binding(),
resource: camera_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
@ -420,6 +481,10 @@ impl strafe_client::framework::Example for Skybox {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 3,
resource: entity_buf.as_entire_binding(),
},
],
label: None,
});
@ -432,10 +497,12 @@ impl strafe_client::framework::Example for Skybox {
entity_pipeline,
ground_pipeline,
bind_group,
uniform_buf,
camera_buf,
entity_buf,
entities,
depth_view,
staging_belt: wgpu::util::StagingBelt::new(0x100),
camera_stagingbelt: wgpu::util::StagingBelt::new(0x100),
entity_stagingbelt: wgpu::util::StagingBelt::new(0x100),
}
}
@ -480,6 +547,10 @@ impl strafe_client::framework::Example for Skybox {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_JUMP,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_JUMP,
}
(k,winit::event::VirtualKeyCode::Z) => match k {
winit::event::ElementState::Pressed => self.camera.controls|=CONTROL_ZOOM,
winit::event::ElementState::Released => self.camera.controls&=!CONTROL_ZOOM,
}
_ => (),
}
}
@ -515,7 +586,7 @@ impl strafe_client::framework::Example for Skybox {
let dt=(time-self.camera.time).as_secs_f32();
self.camera.time=time;
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));
let control_dir=camera_mat*get_control_dir(self.camera.controls&(CONTROL_MOVELEFT|CONTROL_MOVERIGHT|CONTROL_MOVEFORWARD|CONTROL_MOVEBACK)).normalize_or_zero();
let d=self.camera.vel.dot(control_dir);
if d<self.camera.mv {
self.camera.vel+=(self.camera.mv-d)*control_dir;
@ -529,14 +600,16 @@ impl strafe_client::framework::Example for Skybox {
}
if self.camera.grounded&&(self.camera.controls&CONTROL_JUMP)!=0 {
self.camera.grounded=false;
self.camera.vel+=glam::Vec3::new(0.0,50.0,0.0);
self.camera.vel+=glam::Vec3::new(0.0,0.715588/2.0*100.0,0.0);
}
if self.camera.grounded {
let applied_friction=self.camera.friction*dt;
if applied_friction*applied_friction<self.camera.vel.length_squared() {
self.camera.vel-=applied_friction*self.camera.vel.normalize();
let targetv=control_dir*self.camera.walkspeed;
let diffv=targetv-self.camera.vel;
if applied_friction*applied_friction<diffv.length_squared() {
self.camera.vel+=applied_friction*diffv.normalize();
} else {
self.camera.vel=glam::Vec3::new(0.0,0.0,0.0);
self.camera.vel=targetv;
}
}
@ -544,18 +617,31 @@ impl strafe_client::framework::Example for Skybox {
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// update rotation
let raw_uniforms = self.camera.to_uniform_data();
self.staging_belt
let camera_uniforms = self.camera.to_uniform_data();
self.camera_stagingbelt
.write_buffer(
&mut encoder,
&self.uniform_buf,
&self.camera_buf,
0,
wgpu::BufferSize::new((raw_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device,
)
.copy_from_slice(bytemuck::cast_slice(&raw_uniforms));
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
self.staging_belt.finish();
self.camera_stagingbelt.finish();
let entity_uniforms = get_entity_uniform_data(&self.entities);
self.entity_stagingbelt
.write_buffer(
&mut encoder,
&self.entity_buf,//description of where data will be written when command is executed
0,//offset in staging belt?
wgpu::BufferSize::new((entity_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
device,
)
.copy_from_slice(bytemuck::cast_slice(&entity_uniforms));
self.entity_stagingbelt.finish();
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@ -600,7 +686,8 @@ impl strafe_client::framework::Example for Skybox {
queue.submit(std::iter::once(encoder.finish()));
self.staging_belt.recall();
self.camera_stagingbelt.recall();
self.entity_stagingbelt.recall();
}
}

@ -47,8 +47,8 @@ struct GroundOutput {
@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)-i32(vertex_index)/3*2) / 2;
let tmp2 = (i32(vertex_index)-i32(vertex_index)/3*2) & 1;
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,
@ -67,15 +67,26 @@ struct EntityOutput {
@location(3) view: vec3<f32>,
};
struct EntityTransform {
matrix3: mat3x3<f32>,
translation: vec3<f32>,
};
@group(0)
@binding(3)
var<uniform> r_EntityTransforms: array<EntityTransform, 7>;
@vertex
fn vs_entity(
@location(0) pos: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) entity_id: u32,
) -> EntityOutput {
var position: vec3<f32> = r_EntityTransforms[entity_id].matrix3 * pos+r_EntityTransforms[entity_id].translation;
var result: EntityOutput;
result.normal = normal;
result.view = pos - r_data.cam_pos.xyz;
result.position = r_data.proj * r_data.view * vec4<f32>(pos, 1.0);
result.normal = r_EntityTransforms[entity_id].matrix3 * normal;
result.view = position - r_data.cam_pos.xyz;
result.position = r_data.proj * r_data.view * vec4<f32>(position, 1.0);
return result;
}
@ -101,8 +112,20 @@ fn fs_entity(vertex: EntityOutput) -> @location(0) vec4<f32> {
return vec4<f32>(vec3<f32>(0.1) + 0.5 * reflected_color, 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>(vertex.pos.x/16.%1.0,0.0,vertex.pos.z/16.%1.0)*2.0;
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);
}