Compare commits

..

16 Commits

Author SHA1 Message Date
6251c2d1b2 hack camera offset 2026-01-22 09:51:04 -08:00
21a90438f9 marble 2026-01-22 09:51:04 -08:00
edf1d8b699 bot file playback 2026-01-22 09:51:04 -08:00
fbd0f26958 add strafesnet_roblox_bot_file dep 2026-01-22 09:51:04 -08:00
848874d889 fix release build 2026-01-22 09:51:04 -08:00
6eae3bc350 optional directories 2026-01-22 09:51:04 -08:00
ae369085e3 toc 2026-01-22 09:51:04 -08:00
d86d7259d7 include map in binary 2026-01-22 09:51:04 -08:00
7843b414e7 use existing canvas 2026-01-22 09:51:04 -08:00
f9d4a8c344 use chrono instead of std::time 2026-01-22 09:51:04 -08:00
594684aea4 pick up wasm dep 2026-01-22 09:51:04 -08:00
fab7349b3e color functions 2026-01-22 09:51:04 -08:00
1c4a58de8b attach canvas 2026-01-22 09:51:04 -08:00
a310173182 replace enumerate_adapters with request_adapter 2026-01-22 09:51:04 -08:00
448b12f353 drop Send requirement 2026-01-22 09:51:04 -08:00
a4acb87a0d Initial trunk 2026-01-22 09:51:04 -08:00
22 changed files with 316 additions and 854 deletions

20
Cargo.lock generated
View File

@@ -3834,6 +3834,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
name = "strafe-client"
version = "0.11.0"
dependencies = [
"chrono",
"glam",
"parking_lot",
"pollster",
@@ -3843,9 +3844,13 @@ dependencies = [
"strafesnet_graphics",
"strafesnet_physics",
"strafesnet_rbx_loader",
"strafesnet_roblox_bot_file",
"strafesnet_session",
"strafesnet_settings",
"strafesnet_snf",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"wgpu",
"winit",
]
@@ -3892,8 +3897,6 @@ dependencies = [
"glam",
"id",
"strafesnet_common",
"strafesnet_physics",
"strafesnet_rbx_loader",
"strafesnet_session",
"strafesnet_settings",
"wgpu",
@@ -3928,6 +3931,17 @@ dependencies = [
"strafesnet_deferred_loader",
]
[[package]]
name = "strafesnet_roblox_bot_file"
version = "0.8.1"
source = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
checksum = "33d0fa524476d8b6cf23269b0c9cff6334b70585546b807cb8ec193858defecd"
dependencies = [
"binrw 0.15.0",
"bitflags 2.10.0",
"itertools 0.14.0",
]
[[package]]
name = "strafesnet_session"
version = "0.1.0"
@@ -4993,7 +5007,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]

View File

@@ -9,8 +9,6 @@ ddsfile = "0.5.1"
glam = "0.30.0"
id = { version = "0.1.0", registry = "strafesnet" }
strafesnet_common = { path = "../../lib/common", registry = "strafesnet" }
strafesnet_physics = { path = "../physics", registry = "strafesnet" }
strafesnet_rbx_loader = { path = "../../lib/rbx_loader", registry = "strafesnet" }
strafesnet_session = { path = "../session", registry = "strafesnet" }
strafesnet_settings = { path = "../settings", registry = "strafesnet" }
wgpu = "28.0.0"

View File

@@ -5,20 +5,10 @@ use strafesnet_settings::settings;
use strafesnet_session::session;
use strafesnet_common::model::{self, ColorId, NormalId, PolygonIter, PositionId, RenderConfigId, TextureCoordinateId, VertexId};
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
use crate::model::{self as model_graphics,IndexedGraphicsMeshOwnedRenderConfig,IndexedGraphicsMeshOwnedRenderConfigId,GraphicsMeshOwnedRenderConfig,GraphicsModelColor4,GraphicsModelOwned,GraphicsVertex,DebugGraphicsVertex};
use crate::model::{self as model_graphics,IndexedGraphicsMeshOwnedRenderConfig,IndexedGraphicsMeshOwnedRenderConfigId,GraphicsMeshOwnedRenderConfig,GraphicsModelColor4,GraphicsModelOwned,GraphicsVertex};
pub fn required_limits()->wgpu::Limits{
let mut limits=wgpu::Limits::default();
limits.max_task_invocations_per_dimension=1;
limits.max_task_invocations_per_workgroup=1;
limits.max_mesh_invocations_per_dimension=1;
limits.max_mesh_invocations_per_workgroup=1;
limits.max_task_mesh_workgroup_total_count=1;
limits.max_task_mesh_workgroups_per_dimension=1;
limits.max_task_payload_size=4;
limits.max_mesh_output_vertices=2*(3+2+4+8);
limits.max_mesh_output_primitives=2*(1+2+4+8)+2;
limits
wgpu::Limits::default()
}
struct Indices{
@@ -46,135 +36,12 @@ struct GraphicsModel{
instance_count:u32,
}
struct DebugGraphicsSubmesh{
verts:Vec<strafesnet_physics::model::MeshVertId>,
edges:Vec<[strafesnet_physics::model::MeshVertId;2]>,
faces:Vec<Indices>,
}
struct DebugGraphicsMesh{
vertices:Vec<DebugGraphicsVertex>,
indices:Indices,
submeshes:Vec<DebugGraphicsSubmesh>,
vertex_buf:wgpu::Buffer,
}
impl DebugGraphicsMesh{
fn new(device:&wgpu::Device,mesh:&model::Mesh)->Self{
let vertices:Vec<DebugGraphicsVertex>=mesh.unique_pos.iter().copied().map(|pos|{
DebugGraphicsVertex{
pos:pos.to_array().map(Into::into),
}
}).collect();
let vertex_buf=device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
label:Some("Vertex"),
contents:bytemuck::cast_slice(&vertices),
usage:wgpu::BufferUsages::VERTEX,
});
macro_rules! indices{
($indices:expr)=>{
if (u32::MAX as usize)<vertices.len(){
panic!("Model has too many vertices!");
}else if (u16::MAX as usize)<vertices.len(){
Indices::new(device,&$indices.into_iter().map(|vertex_idx|vertex_idx.get() as u32).collect(),wgpu::IndexFormat::Uint32)
}else{
Indices::new(device,&$indices.into_iter().map(|vertex_idx|vertex_idx.get() as u16).collect(),wgpu::IndexFormat::Uint16)
}
};
}
let mut all_indices=Vec::new();
let submeshes=if let Ok(physics_mesh)=strafesnet_physics::model::PhysicsMesh::try_from(mesh){
physics_mesh.submesh_views().into_iter().map(|submesh_view|DebugGraphicsSubmesh{
verts:submesh_view.verts().to_owned(),
edges:submesh_view.edge_vert_ids_iter().collect(),
faces:submesh_view.face_vert_ids_iter().map(|face_verts|{
// triangulate
let mut indices=Vec::new();
let mut poly_vertices=face_verts.into_iter();
if let (Some(a),Some(mut b))=(poly_vertices.next(),poly_vertices.next()){
for c in poly_vertices{
indices.extend([a,b,c]);
all_indices.extend([a,b,c]);
b=c;
}
}
indices!(indices)
}).collect(),
}).collect()
}else{
//idc
Vec::new()
};
let indices=indices!(all_indices);
DebugGraphicsMesh{
vertices,
indices,
submeshes,
vertex_buf,
}
}
}
struct DebugGraphicsModel{
debug_mesh_id:u32,
bind_group:wgpu::BindGroup,
// 32 bytes used to tell the mesh shader where to draw
// Vert: [vec4,_]
// Edge: [vec4,vec4]
debug_buf:wgpu::Buffer,
model_buf:wgpu::Buffer,
}
impl DebugGraphicsModel{
fn new(device:&wgpu::Device,layout:&wgpu::BindGroupLayout,model:&model::Model,model_id:usize,color:glam::Vec4)->Self{
let model_uniforms=get_instances_buffer_data(&[GraphicsModelOwned{
transform:model.transform.into(),
normal_transform:glam::Mat3::from_cols_array_2d(&model.transform.matrix3.to_array().map(|row|row.map(Into::into))).inverse().transpose(),
color:GraphicsModelColor4::new(color),
}]);
let model_buf=device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
label:Some(format!("Debug Model{} Buf",model_id).as_str()),
contents:bytemuck::cast_slice(&model_uniforms),
usage:wgpu::BufferUsages::UNIFORM|wgpu::BufferUsages::COPY_DST,
});
let debug_buf=device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
label:Some(format!("Debug Model{} EV Buf",model_id).as_str()),
contents:bytemuck::cast_slice(&[0u8;32]),
usage:wgpu::BufferUsages::UNIFORM|wgpu::BufferUsages::COPY_DST,
});
let bind_group=device.create_bind_group(&wgpu::BindGroupDescriptor{
layout,
entries:&[
wgpu::BindGroupEntry{
binding:0,
resource:model_buf.as_entire_binding(),
},
wgpu::BindGroupEntry{
binding:1,
resource:debug_buf.as_entire_binding(),
},
],
label:Some(format!("Debug Model{} Bind Group",model_id).as_str()),
});
DebugGraphicsModel{
debug_mesh_id:model.mesh.get(),
bind_group,
debug_buf,
model_buf,
}
}
}
struct GraphicsSamplers{
repeat:wgpu::Sampler,
}
struct GraphicsBindGroupLayouts{
model:wgpu::BindGroupLayout,
debug_model:wgpu::BindGroupLayout,
}
struct GraphicsBindGroups{
@@ -185,9 +52,6 @@ struct GraphicsBindGroups{
struct GraphicsPipelines{
skybox:wgpu::RenderPipeline,
model:wgpu::RenderPipeline,
debug:wgpu::RenderPipeline,
debug_edge:wgpu::RenderPipeline,
debug_vert:wgpu::RenderPipeline,
}
struct GraphicsCamera{
@@ -268,10 +132,6 @@ pub struct GraphicsState{
camera_buf:wgpu::Buffer,
temp_squid_texture_view:wgpu::TextureView,
models:Vec<GraphicsModel>,
debug_meshes:Vec<DebugGraphicsMesh>,
debug_models:Vec<DebugGraphicsModel>,
hitbox_mesh:DebugGraphicsMesh,
hitbox_model:DebugGraphicsModel,
depth_view:wgpu::TextureView,
staging_belt:wgpu::util::StagingBelt,
}
@@ -306,16 +166,6 @@ impl GraphicsState{
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
}
pub fn generate_models(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,map:&map::CompleteMap){
//generate debug meshes, each debug model refers to one
self.debug_meshes=map.meshes.iter().map(|mesh|
DebugGraphicsMesh::new(device,mesh)
).collect();
//generate debug models, only one will be rendered at a time
self.debug_models=map.models.iter().enumerate().map(|(model_id,model)|{
DebugGraphicsModel::new(device,&self.bind_group_layouts.debug_model,model,model_id,glam::vec4(1.0,0.0,0.0,0.2))
}).collect();
//generate texture view per texture
let texture_views:HashMap<model::TextureId,wgpu::TextureView>=map.textures.iter().enumerate().filter_map(|(texture_id,texture_data)|{
let texture_id=model::TextureId::new(texture_id as u32);
@@ -696,7 +546,7 @@ impl GraphicsState{
entries:&[
wgpu::BindGroupLayoutEntry{
binding:0,
visibility:wgpu::ShaderStages::VERTEX|wgpu::ShaderStages::MESH,
visibility:wgpu::ShaderStages::VERTEX,
ty:wgpu::BindingType::Buffer{
ty:wgpu::BufferBindingType::Uniform,
has_dynamic_offset:false,
@@ -758,31 +608,6 @@ impl GraphicsState{
},
],
});
let debug_model_bind_group_layout=device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor{
label:Some("Debug Model Bind Group Layout"),
entries:&[
wgpu::BindGroupLayoutEntry{
binding:0,
visibility:wgpu::ShaderStages::VERTEX_FRAGMENT|wgpu::ShaderStages::MESH,
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::MESH,
ty:wgpu::BindingType::Buffer{
ty:wgpu::BufferBindingType::Uniform,
has_dynamic_offset:false,
min_binding_size:None,
},
count:None,
},
],
});
let clamp_sampler=device.create_sampler(&wgpu::SamplerDescriptor{
label:Some("Clamp Sampler"),
@@ -931,14 +756,6 @@ impl GraphicsState{
],
immediate_size:0,
});
let debug_model_pipeline_layout=device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor{
label:None,
bind_group_layouts:&[
&camera_bind_group_layout,
&debug_model_bind_group_layout,
],
immediate_size:0,
});
let sky_pipeline_layout=device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor{
label:None,
bind_group_layouts:&[
@@ -1014,92 +831,6 @@ impl GraphicsState{
multiview_mask:None,
cache:None,
});
let debug_model_pipeline=device.create_render_pipeline(&wgpu::RenderPipelineDescriptor{
label:Some("Debug Pipeline"),
layout:Some(&debug_model_pipeline_layout),
vertex:wgpu::VertexState{
module:&shader,
entry_point:Some("vs_debug"),
buffers:&[wgpu::VertexBufferLayout{
array_stride:size_of::<DebugGraphicsVertex>() as wgpu::BufferAddress,
step_mode:wgpu::VertexStepMode::Vertex,
attributes:&wgpu::vertex_attr_array![0=>Float32x3],
}],
compilation_options:wgpu::PipelineCompilationOptions::default(),
},
fragment:Some(wgpu::FragmentState{
module:&shader,
entry_point:Some("fs_debug"),
targets:&[Some(wgpu::ColorTargetState{
format:config.view_formats[0],
blend:Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask:wgpu::ColorWrites::default(),
})],
compilation_options:wgpu::PipelineCompilationOptions::default(),
}),
primitive:wgpu::PrimitiveState{
topology:wgpu::PrimitiveTopology::TriangleList,
front_face:wgpu::FrontFace::Cw,
cull_mode:Some(wgpu::Face::Front),
..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_mask:None,
cache:None,
});
let mut debug_model_pipeline_ms=wgpu::MeshPipelineDescriptor{
label:None,//filled in below
layout:Some(&debug_model_pipeline_layout),
task:Some(wgpu::TaskState{
module:&shader,
entry_point:Some("ts_main"),
compilation_options:wgpu::PipelineCompilationOptions::default(),
}),
mesh:wgpu::MeshState{
module:&shader,
entry_point:None,//filled in below
compilation_options:wgpu::PipelineCompilationOptions::default(),
},
fragment:Some(wgpu::FragmentState{
module:&shader,
entry_point:Some("fs_debug"),
targets:&[Some(wgpu::ColorTargetState{
format:config.view_formats[0],
blend:Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask:wgpu::ColorWrites::default(),
})],
compilation_options:wgpu::PipelineCompilationOptions::default(),
}),
primitive:wgpu::PrimitiveState{
topology:wgpu::PrimitiveTopology::TriangleList,
front_face:wgpu::FrontFace::Cw,
cull_mode:None,
..Default::default()
},
depth_stencil:Some(wgpu::DepthStencilState{
format:Self::DEPTH_FORMAT,
depth_write_enabled:true,
depth_compare:wgpu::CompareFunction::Always,
stencil:wgpu::StencilState::default(),
bias:wgpu::DepthBiasState::default(),
}),
multisample:wgpu::MultisampleState::default(),
multiview:None,
cache:None,
};
debug_model_pipeline_ms.label=Some("Debug Vert Pipeline");
debug_model_pipeline_ms.mesh.entry_point=Some("ms_debug_vert");
let debug_model_pipeline_vert=device.create_mesh_pipeline(&debug_model_pipeline_ms);
debug_model_pipeline_ms.label=Some("Debug Edge Pipeline");
debug_model_pipeline_ms.mesh.entry_point=Some("ms_debug_edge");
let debug_model_pipeline_edge=device.create_mesh_pipeline(&debug_model_pipeline_ms);
let camera=GraphicsCamera::default();
let camera_uniforms=camera.to_uniform_data(glam::Vec3::ZERO,glam::Vec2::ZERO);
@@ -1136,23 +867,10 @@ impl GraphicsState{
let depth_view=Self::create_depth_texture(config,device);
// WHIP UP A CUBE
let cube_face_description=strafesnet_rbx_loader::primitives::CubeFaceDescription::new(Default::default(),RenderConfigId::new(0));
let hitbox_mesh=DebugGraphicsMesh::new(device,&strafesnet_rbx_loader::primitives::unit_cube(cube_face_description));
let hitbox_model=DebugGraphicsModel::new(device,&debug_model_bind_group_layout,&model::Model{
mesh:model::MeshId::new(u32::MAX),
attributes:strafesnet_common::gameplay_attributes::CollisionAttributesId::new(0),
color:glam::Vec4::new(0.0,0.0,1.0,0.2),
transform:strafesnet_common::integer::Planar64Affine3::IDENTITY,
},u32::MAX as usize,glam::vec4(0.0,1.0,0.0,0.2));
Self{
pipelines:GraphicsPipelines{
skybox:sky_pipeline,
model:model_pipeline,
debug:debug_model_pipeline,
debug_edge:debug_model_pipeline_edge,
debug_vert:debug_model_pipeline_vert,
model:model_pipeline
},
bind_groups:GraphicsBindGroups{
camera:camera_bind_group,
@@ -1161,16 +879,9 @@ impl GraphicsState{
camera,
camera_buf,
models:Vec::new(),
debug_meshes:Vec::new(),
debug_models:Vec::new(),
hitbox_mesh,
hitbox_model,
depth_view,
staging_belt:wgpu::util::StagingBelt::new(device.clone(),0x100),
bind_group_layouts:GraphicsBindGroupLayouts{
model:model_bind_group_layout,
debug_model:debug_model_bind_group_layout,
},
bind_group_layouts:GraphicsBindGroupLayouts{model:model_bind_group_layout},
samplers:GraphicsSamplers{repeat:repeat_sampler},
temp_squid_texture_view:squid_texture_view,
}
@@ -1224,66 +935,6 @@ impl GraphicsState{
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
}
*/
// update hitbox mesh transform
if let Some(debug_hitbox_position)=frame_state.debug_hitbox_position{
let model_uniforms=get_instances_buffer_data(&[GraphicsModelOwned{
transform:debug_hitbox_position.into(),
normal_transform:glam::Mat3::IDENTITY,
color:GraphicsModelColor4::new(glam::vec4(1.0,0.0,0.0,0.2)),
}]);
let debug_slice=bytemuck::cast_slice(&model_uniforms);
self.staging_belt.write_buffer(
&mut encoder,
&self.hitbox_model.model_buf,
0,
wgpu::BufferSize::new(debug_slice.len() as wgpu::BufferAddress).unwrap(),
).copy_from_slice(debug_slice);
}
// upload the edge or vertex for the mesh shader to highlight
if let Some(hit)=&frame_state.hit{
if let Some(closest_fev)=&hit.closest_fev{
let model_id:model::ModelId=hit.convex_mesh_id.model_id.into();
if let Some(model)=self.debug_models.get(model_id.get() as usize){
let mesh=&self.debug_meshes[model.debug_mesh_id as usize];
match closest_fev{
strafesnet_physics::model::FEV::Face(_face)=>{
// face is rendered normally
},
strafesnet_physics::model::FEV::Edge(edge)=>{
let [v0_id,v1_id]=mesh.submeshes[hit.convex_mesh_id.submesh_id.get() as usize].edges[edge.get() as usize];
let v0_pos=mesh.vertices[v0_id.get() as usize].pos;
let v1_pos=mesh.vertices[v1_id.get() as usize].pos;
let debug_data=[glam::Vec3A::from_array(v0_pos).extend(1.0).to_array(),glam::Vec3A::from_array(v1_pos).extend(1.0).to_array()];
let debug_slice=bytemuck::cast_slice(&debug_data);
self.staging_belt
.write_buffer(
&mut encoder,
&model.debug_buf,
0,
wgpu::BufferSize::new(debug_slice.len() as wgpu::BufferAddress).unwrap(),
)
.copy_from_slice(debug_slice);
},
strafesnet_physics::model::FEV::Vert(vert)=>{
let vert_id=mesh.submeshes[hit.convex_mesh_id.submesh_id.get() as usize].verts[vert.get() as usize].get();
let pos=mesh.vertices[vert_id as usize].pos;
let debug_data=[glam::Vec3A::from_array(pos).extend(1.0).to_array()];
let debug_slice=bytemuck::cast_slice(&debug_data);
self.staging_belt
.write_buffer(
&mut encoder,
&model.debug_buf,
0,
wgpu::BufferSize::new(debug_slice.len() as wgpu::BufferAddress).unwrap(),
)
.copy_from_slice(debug_slice);
},
}
}
}
}
self.staging_belt.finish();
{
@@ -1319,7 +970,6 @@ impl GraphicsState{
rpass.set_bind_group(0,&self.bind_groups.camera,&[]);
rpass.set_bind_group(1,&self.bind_groups.skybox_texture,&[]);
// Draw all models.
rpass.set_pipeline(&self.pipelines.model);
for model in &self.models{
rpass.set_bind_group(2,&model.bind_group,&[]);
@@ -1331,46 +981,6 @@ impl GraphicsState{
rpass.set_pipeline(&self.pipelines.skybox);
rpass.draw(0..3,0..1);
// render a single debug_model in red
if let Some(hit)=&frame_state.hit{
if let Some(closest_fev)=&hit.closest_fev{
let model_id:model::ModelId=hit.convex_mesh_id.model_id.into();
if let Some(model)=self.debug_models.get(model_id.get() as usize){
let mesh=&self.debug_meshes[model.debug_mesh_id as usize];
rpass.set_bind_group(1,&model.bind_group,&[]);
rpass.set_vertex_buffer(0,mesh.vertex_buf.slice(..));
match closest_fev{
strafesnet_physics::model::FEV::Face(face)=>{
rpass.set_pipeline(&self.pipelines.debug);
let indices=&mesh.submeshes[hit.convex_mesh_id.submesh_id.get() as usize].faces[face.get() as usize];
rpass.set_index_buffer(indices.buf.slice(..),indices.format);
//TODO: loop over triangle strips
rpass.draw_indexed(0..indices.count,0,0..1);
},
strafesnet_physics::model::FEV::Edge(_edge)=>{
rpass.set_pipeline(&self.pipelines.debug_edge);
// the data has already been primed by the staging belt
rpass.draw_mesh_tasks(1, 1, 1);
},
strafesnet_physics::model::FEV::Vert(_vert)=>{
rpass.set_pipeline(&self.pipelines.debug_vert);
// the data has already been primed by the staging belt
rpass.draw_mesh_tasks(1, 1, 1);
},
}
}
}
}
if frame_state.debug_hitbox_position.is_some(){
rpass.set_bind_group(1,&self.hitbox_model.bind_group,&[]);
rpass.set_vertex_buffer(0,self.hitbox_mesh.vertex_buf.slice(..));
rpass.set_pipeline(&self.pipelines.debug);
rpass.set_index_buffer(self.hitbox_mesh.indices.buf.slice(..),self.hitbox_mesh.indices.format);
//TODO: loop over triangle strips
rpass.draw_indexed(0..self.hitbox_mesh.indices.count,0,0..1);
}
}
queue.submit(std::iter::once(encoder.finish()));

View File

@@ -8,11 +8,6 @@ pub struct GraphicsVertex{
pub normal:[f32;3],
pub color:[f32;4],
}
#[derive(Clone,Copy,Pod,Zeroable)]
#[repr(C)]
pub struct DebugGraphicsVertex{
pub pos:[f32;3],
}
#[derive(Clone,Copy,id::Id)]
pub struct IndexedGraphicsMeshOwnedRenderConfigId(u32);
pub struct IndexedGraphicsMeshOwnedRenderConfig{

View File

@@ -15,12 +15,6 @@ pub enum CrawlResult<M:MeshQuery>{
Hit(M::Face,GigaTime),
}
impl<M:MeshQuery> CrawlResult<M>{
pub fn fev(self)->FEV<M>{
match self{
CrawlResult::Miss(fev)=>fev,
CrawlResult::Hit(face,_)=>FEV::Face(face),
}
}
pub fn hit(self)->Option<(M::Face,GigaTime)>{
match self{
CrawlResult::Miss(_)=>None,

View File

@@ -1,6 +1,6 @@
mod body;
mod face_crawler;
pub mod model;
mod model;
mod push_solve;
mod minimum_difference;

View File

@@ -60,7 +60,7 @@ impl DirectedEdge for SubmeshDirectedEdgeId{
}
//Vertex <-> Edge <-> Face -> Collide
#[derive(Debug,Clone)]
#[derive(Debug)]
pub enum FEV<M:MeshQuery>{
Face(M::Face),
Edge(<M::Edge as DirectedEdge>::UndirectedEdge),
@@ -444,24 +444,6 @@ pub struct PhysicsMeshView<'a>{
data:&'a PhysicsMeshData,
topology:&'a PhysicsMeshTopology,
}
impl PhysicsMeshView<'_>{
pub fn verts(&self)->&[MeshVertId]{
&self.topology.verts
}
pub fn edge_vert_ids_iter(&self)->impl Iterator<Item=[MeshVertId;2]>+'_{
self.topology.edge_topology.iter().map(|edge|{
edge.verts.map(|vert_id|self.topology.verts[vert_id.get() as usize])
})
}
pub fn face_vert_ids_iter(&self)->impl Iterator<Item=impl Iterator<Item=MeshVertId>>+'_{
self.topology.face_topology.iter().map(|face|{
face.edges.iter().map(|edge_id|{
let vert_id=self.topology.edge_topology[edge_id.as_undirected().get() as usize].verts[edge_id.parity() as usize];
self.topology.verts[vert_id.get() as usize]
})
})
}
}
impl MeshQuery for PhysicsMeshView<'_>{
type Face=SubmeshFaceId;
type Edge=SubmeshDirectedEdgeId;
@@ -544,9 +526,6 @@ impl TransformedMesh<'_>{
pub fn verts<'a>(&'a self)->impl Iterator<Item=Vector3<Fixed<2,64>>>+'a{
self.view.data.verts.iter().map(|&Vert(pos)|self.transform.vertex.transform_point3(pos))
}
pub fn faces(&self)->impl Iterator<Item=SubmeshFaceId>{
(0..self.view.topology.faces.len() as u32).map(SubmeshFaceId::new)
}
}
impl MeshQuery for TransformedMesh<'_>{
type Face=SubmeshFaceId;
@@ -633,7 +612,7 @@ impl UndirectedEdge for MinkowskiEdge{
}
}
}
#[derive(Clone,Copy,Debug,Eq,PartialEq)]
#[derive(Clone,Copy,Debug)]
pub enum MinkowskiDirectedEdge{
VertEdge(SubmeshVertId,SubmeshDirectedEdgeId),
EdgeVert(SubmeshDirectedEdgeId,SubmeshVertId),
@@ -670,31 +649,6 @@ pub struct MinkowskiMesh<'a>{
mesh1:TransformedMesh<'a>,
}
impl FEV<MinkowskiMesh<'_>>{
pub fn mesh0<'a>(self)->FEV<TransformedMesh<'a>>{
match self{
FEV::Face(face)=>{
match face{
MinkowskiFace::VertFace(submesh_vert_id,_)=>FEV::Vert(submesh_vert_id),
MinkowskiFace::EdgeEdge(submesh_edge_id,..)=>FEV::Edge(submesh_edge_id),
MinkowskiFace::FaceVert(submesh_face_id,_)=>FEV::Face(submesh_face_id),
}
},
FEV::Edge(edge)=>{
match edge{
MinkowskiEdge::VertEdge(submesh_vert_id,_)=>FEV::Vert(submesh_vert_id),
MinkowskiEdge::EdgeVert(submesh_edge_id,_)=>FEV::Edge(submesh_edge_id),
}
},
FEV::Vert(vert)=>{
match vert{
MinkowskiVert::VertVert(submesh_vert_id,_)=>FEV::Vert(submesh_vert_id),
}
},
}
}
}
pub type GigaTime=Ratio<Fixed<4,128>,Fixed<4,128>>;
pub fn into_giga_time(time:Time,relative_to:Time)->GigaTime{
let r=(time-relative_to).to_ratio();

View File

@@ -1,5 +1,4 @@
use std::collections::{HashMap,HashSet};
use crate::model::DirectedEdge;
use crate::model::{self as model_physics,PhysicsMesh,PhysicsMeshTransform,TransformedMesh,MeshQuery,PhysicsMeshId,PhysicsSubmeshId};
use strafesnet_common::bvh;
use strafesnet_common::map;
@@ -263,6 +262,15 @@ pub struct PhysicsCamera{
impl PhysicsCamera{
const ANGLE_PITCH_LOWER_LIMIT:Angle32=Angle32::NEG_FRAC_PI_2;
const ANGLE_PITCH_UPPER_LIMIT:Angle32=Angle32::FRAC_PI_2;
pub fn new(
sensitivity:Ratio64Vec2,
clamped_mouse_pos:glam::IVec2,
)->Self{
Self{
sensitivity,
clamped_mouse_pos,
}
}
pub fn move_mouse(&mut self,mouse_delta:glam::IVec2){
let mut unclamped_mouse_pos=self.clamped_mouse_pos+mouse_delta;
unclamped_mouse_pos.y=unclamped_mouse_pos.y.clamp(
@@ -288,8 +296,7 @@ impl PhysicsCamera{
.clamp(Self::ANGLE_PITCH_LOWER_LIMIT,Self::ANGLE_PITCH_UPPER_LIMIT);
mat3::from_rotation_yx(ax,ay)
}
#[inline]
pub fn rotation(&self)->Planar64Mat3{
fn rotation(&self)->Planar64Mat3{
self.get_rotation(self.clamped_mouse_pos)
}
#[expect(dead_code)]
@@ -671,7 +678,7 @@ impl From<CollisionAttributesId> for IntersectAttributesId{
}
}
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct ContactModelId(u32);
struct ContactModelId(u32);
impl From<ContactModelId> for ModelId{
fn from(value:ContactModelId)->ModelId{
ModelId::new(value.get())
@@ -683,7 +690,7 @@ impl From<ModelId> for ContactModelId{
}
}
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
pub struct IntersectModelId(u32);
struct IntersectModelId(u32);
impl From<IntersectModelId> for ModelId{
fn from(value:IntersectModelId)->ModelId{
ModelId::new(value.get())
@@ -695,7 +702,7 @@ impl From<ModelId> for IntersectModelId{
}
}
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
pub enum PhysicsModelId{
enum PhysicsModelId{
Contact(ContactModelId),
Intersect(IntersectModelId),
}
@@ -709,9 +716,9 @@ impl From<PhysicsModelId> for ModelId{
}
//unique physics meshes indexed by this
#[derive(Debug,Clone,Copy,Eq,Hash,PartialEq)]
pub struct ConvexMeshId<Id>{
pub model_id:Id,
pub submesh_id:PhysicsSubmeshId,
struct ConvexMeshId<Id>{
model_id:Id,
submesh_id:PhysicsSubmeshId,
}
impl<Id> ConvexMeshId<Id>{
fn map<NewId>(self,model_id:NewId)->ConvexMeshId<NewId>{
@@ -876,7 +883,7 @@ pub struct PhysicsState{
//input_state
input_state:InputState,
//style
style:StyleModifiers,//mode style with custom style updates applied
pub style:StyleModifiers,//mode style with custom style updates applied
//gameplay_state
mode_state:ModeState,
move_state:MoveState,
@@ -1000,57 +1007,6 @@ impl PhysicsData{
hitbox_mesh:StyleModifiers::default().calculate_mesh(),
}
}
pub fn trace_ray(&self,ray:strafesnet_common::ray::Ray)->Option<ConvexMeshId<PhysicsModelId>>{
let (_time,convex_mesh_id)=self.bvh.sample_ray(&ray,Time::ZERO,Time::MAX/4,|&model,ray|{
let mesh=self.models.mesh(model);
// brute force trace every face
let faces=mesh.faces().filter_map(|face_id|{
let (n,d)=mesh.face_nd(face_id);
// trace ray onto face
// n.(o+d*t)==n.p
// n.o + n.d * t == n.p
// t == (n.p - n.o)/n.d
let nd=n.dot(ray.direction);
if nd.is_zero(){
return None;
}
let t=(d-n.dot(ray.origin))/nd;
Some((face_id,t,n))
});
let mut min=None;
for (face_id,t,n) in faces{
if let Some(min)=min&&min<t{
continue;
}
// check if point of intersection is behind face edges
// *2 because average of 2 vertices
let p=ray.extrapolate(t)*2;
let is_inside_face=mesh.face_edges(face_id).as_ref().iter().all(|&directed_edge_id|{
let edge_n=mesh.directed_edge_n(directed_edge_id);
let cross_n=edge_n.cross(n);
let &[vert0,vert1]=mesh.edge_verts(directed_edge_id.as_undirected()).as_ref();
cross_n.dot(p)<cross_n.dot(mesh.vert(vert0)+mesh.vert(vert1))
});
if is_inside_face{
min=Some(t);
}
}
min.map(Into::into)
})?;
Some(*convex_mesh_id)
}
pub fn closest_fev_not_inside(&self,convex_mesh_id:ConvexMeshId<PhysicsModelId>,point:Planar64Vec3)->Option<model_physics::FEV<model_physics::MinkowskiMesh<'_>>>{
let model_mesh=self.models.mesh(convex_mesh_id);
let minkowski=model_physics::MinkowskiMesh::minkowski_sum(model_mesh,self.hitbox_mesh.transformed_mesh());
let fev=crate::minimum_difference::closest_fev_not_inside(&minkowski,point)?;
Some(fev)
}
pub fn trace(&self,convex_mesh_id:ConvexMeshId<PhysicsModelId>,body:&Body,time:Time)->Option<model_physics::FEV<model_physics::MinkowskiMesh<'_>>>{
let model_mesh=self.models.mesh(convex_mesh_id);
let minkowski=model_physics::MinkowskiMesh::minkowski_sum(model_mesh,self.hitbox_mesh.transformed_mesh());
let fev=crate::minimum_difference::closest_fev_not_inside(&minkowski,body.extrapolated_position(time))?;
Some(fev)
}
pub fn new(map:&map::CompleteMap)->Self{
let modes=map.modes.clone().denormalize();
let mut used_contact_attributes=Vec::new();
@@ -1199,9 +1155,6 @@ impl PhysicsData{
modes,
}
}
pub fn vertex_transform(&self)->&integer::Planar64Affine3{
&self.hitbox_mesh.transform.vertex
}
}
// the collection of information required to run physics
pub struct PhysicsContext<'a>{

View File

@@ -48,7 +48,6 @@ pub enum SessionControlInstruction{
StopSpectate,
SaveReplay,
LoadIntoReplayState,
DebugSimulation,
}
pub enum SessionPlaybackInstruction{
SkipForward,
@@ -61,8 +60,6 @@ pub struct FrameState{
pub body:physics::Body,
pub camera:physics::PhysicsCamera,
pub time:PhysicsTime,
pub hit:Option<Hit>,
pub debug_hitbox_position:Option<strafesnet_common::integer::Planar64Affine3>,
}
pub struct Simulation{
@@ -79,38 +76,11 @@ impl Simulation{
physics,
}
}
pub fn get_frame_state(
&self,
time:SessionTime,
debug_model:Option<Hit>,
debug_hitbox_position:Option<strafesnet_common::integer::Planar64Affine3>,
)->FrameState{
pub fn get_frame_state(&self,time:SessionTime)->FrameState{
FrameState{
body:self.physics.camera_body(),
camera:self.physics.camera(),
time:self.timer.time(time),
hit:debug_model,
debug_hitbox_position,
}
}
}
// a paused simulation which displays a period of its future traced over the model under the cursor
struct DebugSimulation{
physics:physics::PhysicsState,
timer:strafesnet_common::timer::TimerFixed<Scaled<SessionTimeInner,PhysicsTimeInner>,strafesnet_common::timer::Paused>,
cycle_duration:PhysicsTime,
}
impl DebugSimulation{
pub fn new(simulation:&Simulation,time:SessionTime,cycle_duration:PhysicsTime)->Self{
let timer=match &simulation.timer{
Timer::Paused(timer_fixed)=>*timer_fixed,
Timer::Unpaused(timer_fixed)=>timer_fixed.into_paused(time),
};
Self{
physics:simulation.physics.clone(),
timer,
cycle_duration,
}
}
}
@@ -178,14 +148,8 @@ enum ViewState{
Replay(BotId),
}
#[derive(Clone)]
pub struct Hit{
pub convex_mesh_id:physics::ConvexMeshId<physics::PhysicsModelId>,
pub closest_fev:Option<strafesnet_physics::model::FEV<strafesnet_physics::model::TransformedMesh<'static>>>
}
pub struct Session{
directories:Directories,
directories:Option<Directories>,
user_settings:UserSettings,
mouse_interpolator:MouseInterpolator,
view_state:ViewState,
@@ -196,13 +160,11 @@ pub struct Session{
recording:Recording,
//players:HashMap<PlayerId,Simulation>,
replays:HashMap<BotId,Replay>,
last_ray_hit:Option<Hit>,
debug_simulation:Option<DebugSimulation>,
}
impl Session{
pub fn new(
user_settings:UserSettings,
directories:Directories,
directories:Option<Directories>,
simulation:Simulation,
)->Self{
Self{
@@ -214,8 +176,6 @@ impl Session{
view_state:ViewState::Play,
recording:Default::default(),
replays:HashMap::new(),
last_ray_hit:None,
debug_simulation:None,
}
}
fn clear_recording(&mut self){
@@ -226,45 +186,13 @@ impl Session{
self.geometry_shared=PhysicsData::new(map);
}
pub fn get_frame_state(&self,time:SessionTime)->Option<FrameState>{
let debug_hitbox_position=self.debug_simulation.as_ref().map(|debug_simulation|{
let simulation_time=debug_simulation.timer.time();
let loop_time=simulation_time+PhysicsTime::raw(time.get().rem_euclid(debug_simulation.cycle_duration.get())>>1);
let transform=self.geometry_shared.vertex_transform();
strafesnet_common::integer::Planar64Affine3::new(transform.matrix3,debug_simulation.physics.body().extrapolated_position(loop_time))
});
match &self.view_state{
ViewState::Play=>Some(self.simulation.get_frame_state(time,self.last_ray_hit.clone(),debug_hitbox_position)),
ViewState::Play=>Some(self.simulation.get_frame_state(time)),
ViewState::Replay(bot_id)=>self.replays.get(bot_id).map(|replay|
replay.simulation.get_frame_state(time,None,debug_hitbox_position)
replay.simulation.get_frame_state(time)
),
}
}
pub fn debug_raycast_print_model_id_if_changed(&mut self,time:SessionTime){
let Some(debug_simulation)=&self.debug_simulation else{
return;
};
if let Some(frame_state)=self.get_frame_state(time){
let ray=strafesnet_common::ray::Ray{
origin:frame_state.body.extrapolated_position(self.simulation.timer.time(time)),
direction:-frame_state.camera.rotation().z_axis,
};
match self.geometry_shared.trace_ray(ray){
Some(convex_mesh_id)=>{
if self.last_ray_hit.as_ref().map_or(true,|last|last.convex_mesh_id!=convex_mesh_id){
println!("MeshId={convex_mesh_id:?}");
}
let simulation_time=debug_simulation.timer.time();
let loop_time=simulation_time+PhysicsTime::raw(time.get().rem_euclid(debug_simulation.cycle_duration.get())>>1);
let closest_fev=self.geometry_shared.trace(convex_mesh_id,debug_simulation.physics.body(),loop_time);
self.last_ray_hit=Some(Hit{
convex_mesh_id,
closest_fev:closest_fev.map(|fev|fev.mesh0()),
});
},
None=>self.last_ray_hit=None,
}
}
}
pub fn user_settings(&self)->&UserSettings{
&self.user_settings
}
@@ -377,19 +305,21 @@ impl InstructionConsumer<Instruction<'_>> for Session{
match view_state{
ViewState::Play=>(),
ViewState::Replay(bot_id)=>if let Some(replay)=self.replays.remove(&bot_id){
let mut replays_path=self.directories.replays.clone();
let file_name=format!("{}.snfb",ins.time);
std::thread::spawn(move ||{
std::fs::create_dir_all(replays_path.as_path()).unwrap();
replays_path.push(file_name);
let file=std::fs::File::create(replays_path).unwrap();
strafesnet_snf::bot::write_bot(
std::io::BufWriter::new(file),
strafesnet_physics::VERSION.get(),
replay.recording.instructions
).unwrap();
println!("Finished writing bot file!");
});
if let Some(directories)=&self.directories{
let mut replays_path=directories.replays.clone();
let file_name=format!("{}.snfb",ins.time);
std::thread::spawn(move ||{
std::fs::create_dir_all(replays_path.as_path()).unwrap();
replays_path.push(file_name);
let file=std::fs::File::create(replays_path).unwrap();
strafesnet_snf::bot::write_bot(
std::io::BufWriter::new(file),
strafesnet_physics::VERSION.get(),
replay.recording.instructions
).unwrap();
println!("Finished writing bot file!");
});
}
},
}
_=self.simulation.timer.set_paused(ins.time,false);
@@ -480,10 +410,6 @@ impl InstructionConsumer<Instruction<'_>> for Session{
// begin spectate
self.view_state=ViewState::Replay(bot_id);
},
Instruction::Control(SessionControlInstruction::DebugSimulation)=>{
println!("Body={}",self.simulation.physics.body());
self.debug_simulation=Some(DebugSimulation::new(&self.simulation,ins.time,PhysicsTime::ONE_SECOND<<1));
},
Instruction::Idle=>{
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Idle);
// this just refreshes the replays

View File

@@ -16,6 +16,7 @@ source = ["dep:strafesnet_deferred_loader", "dep:strafesnet_bsp_loader"]
roblox = ["dep:strafesnet_deferred_loader", "dep:strafesnet_rbx_loader"]
[dependencies]
chrono = "0.4.39"
glam = "0.30.0"
parking_lot = "0.12.1"
pollster = "0.4.0"
@@ -25,9 +26,13 @@ strafesnet_deferred_loader = { path = "../lib/deferred_loader", registry = "stra
strafesnet_graphics = { path = "../engine/graphics", registry = "strafesnet" }
strafesnet_physics = { path = "../engine/physics", registry = "strafesnet" }
strafesnet_rbx_loader = { path = "../lib/rbx_loader", registry = "strafesnet", optional = true }
strafesnet_roblox_bot_file = { version = "0.8.1", registry = "strafesnet" }
strafesnet_session = { path = "../engine/session", registry = "strafesnet" }
strafesnet_settings = { path = "../engine/settings", registry = "strafesnet" }
strafesnet_snf = { path = "../lib/snf", registry = "strafesnet", optional = true }
wasm-bindgen = "0.2.99"
wasm-bindgen-futures = "0.4.49"
web-sys = { version = "0.3.76", features = ["console"] }
wgpu = "28.0.0"
winit = "0.30.7"

View File

@@ -4,12 +4,12 @@ use strafesnet_common::instruction::TimedInstruction;
use strafesnet_common::session::Time as SessionTime;
pub struct App<'a>{
root_time:std::time::Instant,
root_time:chrono::DateTime<chrono::Utc>,
window_thread:crate::compat_worker::QNWorker<'a,TimedInstruction<Instruction,SessionTime>>,
}
impl<'a> App<'a>{
pub fn new(
root_time:std::time::Instant,
root_time:chrono::DateTime<chrono::Utc>,
window_thread:crate::compat_worker::QNWorker<'a,TimedInstruction<Instruction,SessionTime>>,
)->App<'a>{
Self{
@@ -18,7 +18,7 @@ impl<'a> App<'a>{
}
}
fn send_timed_instruction(&mut self,instruction:Instruction){
let time=integer::Time::from_nanos(self.root_time.elapsed().as_nanos() as i64);
let time=integer::Time::from_nanos((chrono::Utc::now()-self.root_time).num_nanoseconds().unwrap());
self.window_thread.send(TimedInstruction{time,instruction}).unwrap();
}
}

View File

@@ -2,11 +2,11 @@ pub type QNWorker<'a,Task>=CompatNWorker<'a,Task>;
pub type INWorker<'a,Task>=CompatNWorker<'a,Task>;
pub struct CompatNWorker<'a,Task>{
f:Box<dyn FnMut(Task)+Send+'a>,
f:Box<dyn FnMut(Task)+'a>,
}
impl<'a,Task> CompatNWorker<'a,Task>{
pub fn new(f:impl FnMut(Task)+Send+'a)->CompatNWorker<'a,Task>{
pub fn new(f:impl FnMut(Task)+'a)->CompatNWorker<'a,Task>{
Self{
f:Box::new(f),
}

View File

@@ -87,10 +87,13 @@ pub enum LoadFormat{
Bot(strafesnet_snf::bot::Segment),
}
pub fn load<P:AsRef<std::path::Path>>(path:P)->Result<LoadFormat,LoadError>{
pub fn load_file<P:AsRef<std::path::Path>>(path:P)->Result<LoadFormat,LoadError>{
//blocking because it's simpler...
let file=std::fs::File::open(path).map_err(LoadError::File)?;
match read(file).map_err(LoadError::ReadError)?{
load(file)
}
pub fn load<R:Read+std::io::Seek>(reader:R)->Result<LoadFormat,LoadError>{
match read(reader).map_err(LoadError::ReadError)?{
#[cfg(feature="snf")]
ReadFormat::SNFB(bot)=>Ok(LoadFormat::Bot(bot)),
#[cfg(feature="snf")]

View File

@@ -33,12 +33,12 @@ pub fn new(
},
Instruction::Resize(size,user_settings)=>{
println!("Resizing to {:?}",size);
let t0=std::time::Instant::now();
//let t0=std::time::Instant::now();
config.width=size.width.max(1);
config.height=size.height.max(1);
surface.configure(&device,&config);
graphics.resize(&device,&config,&user_settings);
println!("Resize took {:?}",t0.elapsed());
//println!("Resize took {:?}",t0.elapsed());
}
Instruction::Render(frame_state)=>{
//this has to go deeper somehow

View File

@@ -9,5 +9,8 @@ mod graphics_worker;
const TITLE:&'static str=concat!("Strafe Client v",env!("CARGO_PKG_VERSION"));
fn main(){
setup::setup_and_start(TITLE);
#[cfg(target_arch="wasm32")]
wasm_bindgen_futures::spawn_local(setup::setup_and_start(TITLE));
#[cfg(not(target_arch="wasm32"))]
pollster::block_on(setup::setup_and_start(TITLE));
}

View File

@@ -1,13 +1,15 @@
use crate::graphics_worker::Instruction as GraphicsInstruction;
use strafesnet_settings::{directories::Directories,settings};
use strafesnet_session::session::{
FrameState,
Session,Simulation,SessionInputInstruction,SessionControlInstruction,SessionPlaybackInstruction,ImplicitModeInstruction,
Instruction as SessionInstruction,
};
use strafesnet_common::instruction::{TimedInstruction,InstructionConsumer};
use strafesnet_common::physics::Time as PhysicsTime;
use strafesnet_common::session::Time as SessionTime;
use strafesnet_common::timer::Timer;
use strafesnet_common::instruction::TimedInstruction;
use strafesnet_common::physics::{Time as PhysicsTime,TimeInner as PhysicsTimeInner};
use strafesnet_common::session::{Time as SessionTime,TimeInner as SessionTimeInner};
use strafesnet_common::timer::{Scaled,Timer,TimerState};
use strafesnet_physics::physics::PhysicsData;
pub enum Instruction{
SessionInput(SessionInputInstruction),
@@ -19,12 +21,136 @@ pub enum Instruction{
LoadReplay(strafesnet_snf::bot::Segment),
}
fn vector3_to_glam(v:&strafesnet_roblox_bot_file::v0::Vector3)->glam::Vec3{
glam::vec3(v.x,v.y,v.z)
}
fn f32_to_p64(f:f32)->strafesnet_common::integer::Planar64{
f.try_into().unwrap_or(strafesnet_common::integer::Planar64::ZERO)
}
struct PlayBacker{
//Instructions
timelines:strafesnet_roblox_bot_file::v0::Block,
//"Simulation"
event_id:usize,
offset:f64,
duration:f64,
timer:Timer<Scaled<SessionTimeInner,PhysicsTimeInner>>,
physics_data:PhysicsData,
camera_offset:strafesnet_common::integer::Planar64Vec3,
}
impl PlayBacker{
pub fn new(
physics_data:PhysicsData,
timelines:strafesnet_roblox_bot_file::v0::Block,
camera_offset:strafesnet_common::integer::Planar64Vec3,
)->Self{
let first=timelines.output_events.first().unwrap();
let last=timelines.output_events.last().unwrap();
Self{
offset:first.time,
duration:last.time-first.time,
timelines,
event_id:0,
timer:Timer::from_state(Scaled::identity(),false),
physics_data,
camera_offset,
}
}
pub fn handle_instruction(&mut self,TimedInstruction{time,instruction}:&TimedInstruction<SessionInstruction,SessionTime>){
//match the instruction so the playback is pausable :D
match instruction{
&SessionInstruction::Control(SessionControlInstruction::SetPaused(paused))=>{
let _=self.timer.set_paused(*time,paused);
},
_=>(),
}
let simulation_time=self.timer.time(*time);
let mut time_float=simulation_time.get() as f64/PhysicsTime::ONE_SECOND.get() as f64+self.offset;
loop{
match self.timelines.output_events.get(self.event_id+1){
Some(next_event)=>{
if next_event.time<time_float{
self.event_id+=1;
}else{
break;
}
},
None=>{
//reset playback
self.event_id=0;
self.offset-=self.duration;
time_float-=self.duration;
},
}
}
}
pub fn get_frame_state(&self,time:SessionTime)->FrameState{
use strafesnet_physics::physics::{Body,PhysicsCamera};
let time=self.timer.time(time);
let event0=&self.timelines.output_events[self.event_id];
let event1=&self.timelines.output_events[self.event_id+1];
let p0=vector3_to_glam(&event0.event.position);
let p1=vector3_to_glam(&event1.event.position);
let v0=vector3_to_glam(&event0.event.velocity);
let v1=vector3_to_glam(&event1.event.velocity);
let a0=vector3_to_glam(&event0.event.acceleration);
let a1=vector3_to_glam(&event1.event.acceleration);
let t0=event0.time;
let t1=event1.time;
let time_float=time.get() as f64/PhysicsTime::ONE_SECOND.get() as f64;
let t=((time_float+self.offset-t0)/(t1-t0)) as f32;
let p=p0.lerp(p1,t).to_array().map(f32_to_p64);
let v=v0.lerp(v1,t).to_array().map(f32_to_p64);
let a=a0.lerp(a1,t).to_array().map(f32_to_p64);
//println!("position={:?}",p);
let angles0=vector3_to_glam(&event0.event.angles);
let angles1=vector3_to_glam(&event1.event.angles);
let angles=angles0.lerp(angles1,t);
// mask mantissa out and set it to minimum value
// let ax_epsilon=f32::from_bits(angles.x.to_bits()&!((1<<23)-1)|1);
// let ay_epsilon=f32::from_bits(angles.y.to_bits()&!((1<<23)-1)|1);
let body=Body{
time,
position:strafesnet_common::integer::Planar64Vec3::new(p)+self.camera_offset,
velocity:strafesnet_common::integer::Planar64Vec3::new(v),
acceleration:strafesnet_common::integer::Planar64Vec3::new(a),
};
const FLOAT64_TO_ANGLE32_RADIANS:f64=((1i64<<31) as f64)/std::f64::consts::PI;
// xy is reversed in strafe client for some reason
let (ax,ay)=(
-angles.y as f64*FLOAT64_TO_ANGLE32_RADIANS,
-angles.x as f64*FLOAT64_TO_ANGLE32_RADIANS,
);
let camera=PhysicsCamera::new(
strafesnet_common::integer::Ratio64Vec2::new(1.0f32.try_into().unwrap(),1.0f32.try_into().unwrap()),
glam::ivec2(ax as i64 as i32,ay as i64 as i32)
);
FrameState{
body,
camera,
time,
}
}
pub fn user_settings(&self)->settings::UserSettings{
//oof, settings ignored
settings::UserSettings::default()
}
pub fn change_map(&mut self,_time:SessionTime,map:&strafesnet_common::map::CompleteMap){
self.physics_data=PhysicsData::new(&map);
}
}
pub fn new<'a>(
mut graphics_worker:crate::compat_worker::INWorker<'a,crate::graphics_worker::Instruction>,
directories:Directories,
directories:Option<Directories>,
user_settings:settings::UserSettings,
)->crate::compat_worker::QNWorker<'a,TimedInstruction<Instruction,SessionTime>>{
let physics=strafesnet_physics::physics::PhysicsState::default();
let camera_offset=physics.style.camera_offset;
let timer=Timer::unpaused(SessionTime::ZERO,PhysicsTime::ZERO);
let simulation=Simulation::new(timer,physics);
let mut session=Session::new(
@@ -32,11 +158,20 @@ pub fn new<'a>(
directories,
simulation,
);
//load bot
let physics=PhysicsData::empty();
let data=include_bytes!("/home/quat/strafesnet/roblox_bot_file/files/bhop_marble_7cf33a64-7120-4514-b9fa-4fe29d9523d");
let bot_file=strafesnet_roblox_bot_file::v0::read_all_to_block(std::io::Cursor::new(data)).unwrap();
let mut interpolator=PlayBacker::new(
physics,
bot_file,
camera_offset,
);
crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<Instruction,SessionTime>|{
// excruciating pain
macro_rules! run_session_instruction{
($time:expr,$instruction:expr)=>{
session.process_instruction(TimedInstruction{
interpolator.handle_instruction(&TimedInstruction{
time:$time,
instruction:$instruction,
});
@@ -59,20 +194,17 @@ pub fn new<'a>(
},
Instruction::Render=>{
run_session_instruction!(ins.time,SessionInstruction::Idle);
// update model under cursor
session.debug_raycast_print_model_id_if_changed(ins.time);
if let Some(frame_state)=session.get_frame_state(ins.time){
if let Some(frame_state)=Some(interpolator.get_frame_state(ins.time)){
run_graphics_worker_instruction!(GraphicsInstruction::Render(frame_state));
}
},
Instruction::Resize(physical_size)=>{
run_session_instruction!(ins.time,SessionInstruction::Idle);
let user_settings=session.user_settings().clone();
let user_settings=interpolator.user_settings().clone();
run_graphics_worker_instruction!(GraphicsInstruction::Resize(physical_size,user_settings));
},
Instruction::ChangeMap(complete_map)=>{
interpolator.change_map(ins.time,&complete_map);
run_session_instruction!(ins.time,SessionInstruction::ChangeMap(&complete_map));
run_session_instruction!(ins.time,SessionInstruction::Input(SessionInputInstruction::Mode(ImplicitModeInstruction::ResetAndSpawn(strafesnet_common::gameplay_modes::ModeId::MAIN,strafesnet_common::gameplay_modes::StageId::FIRST))));
run_graphics_worker_instruction!(GraphicsInstruction::ChangeMap(complete_map));

View File

@@ -3,7 +3,7 @@ fn optional_features()->wgpu::Features{
|wgpu::Features::TEXTURE_COMPRESSION_ETC2
}
fn required_features()->wgpu::Features{
wgpu::Features::TEXTURE_COMPRESSION_BC|wgpu::Features::EXPERIMENTAL_MESH_SHADER
wgpu::Features::TEXTURE_COMPRESSION_BC
}
fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{
wgpu::DownlevelCapabilities{
@@ -20,6 +20,16 @@ struct SetupContextPartial1{
fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
let mut attr=winit::window::WindowAttributes::default();
attr=attr.with_title(title);
#[cfg(target_arch="wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
let canvas=web_sys::window().unwrap()
.document().unwrap()
.get_element_by_id("canvas").unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>().unwrap();
attr=attr.with_canvas(Some(canvas));
}
event_loop.create_window(attr)
}
fn create_instance()->SetupContextPartial1{
@@ -44,43 +54,20 @@ struct SetupContextPartial2<'a>{
surface:wgpu::Surface<'a>,
}
impl<'a> SetupContextPartial2<'a>{
fn pick_adapter(self)->SetupContextPartial3<'a>{
async fn pick_adapter(self)->SetupContextPartial3<'a>{
let adapter;
//TODO: prefer adapter that implements optional features
//let optional_features=optional_features();
let required_features=required_features();
//no helper function smh gotta write it myself
let adapters=pollster::block_on(self.instance.enumerate_adapters(self.backends));
let mut chosen_adapter=None;
let mut chosen_adapter_score=0;
for adapter in adapters {
if !adapter.is_surface_supported(&self.surface) {
continue;
}
let score=match adapter.get_info().device_type{
wgpu::DeviceType::IntegratedGpu=>3,
wgpu::DeviceType::DiscreteGpu=>4,
wgpu::DeviceType::VirtualGpu=>2,
wgpu::DeviceType::Other|wgpu::DeviceType::Cpu=>1,
};
let adapter_features=adapter.features();
if chosen_adapter_score<score&&adapter_features.contains(required_features) {
chosen_adapter_score=score;
chosen_adapter=Some(adapter);
}
}
if let Some(maybe_chosen_adapter)=chosen_adapter{
adapter=maybe_chosen_adapter;
}else{
panic!("No suitable GPU adapters found on the system!");
}
let chosen_adapter=self.instance.request_adapter(&wgpu::RequestAdapterOptions{
power_preference:wgpu::PowerPreference::HighPerformance,
force_fallback_adapter:false,
compatible_surface:Some(&self.surface),
}).await;
adapter=chosen_adapter.unwrap();
let adapter_info=adapter.get_info();
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
@@ -110,14 +97,15 @@ struct SetupContextPartial3<'a>{
adapter:wgpu::Adapter,
}
impl<'a> SetupContextPartial3<'a>{
fn request_device(self)->SetupContextPartial4<'a>{
async fn request_device(self)->SetupContextPartial4<'a>{
let optional_features=optional_features();
let required_features=required_features();
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the surface.
let needed_limits=strafesnet_graphics::graphics::required_limits().using_resolution(self.adapter.limits());
let (device, queue)=pollster::block_on(self.adapter
let trace_dir=std::env::var("WGPU_TRACE");
let (device, queue)=self.adapter
.request_device(
&wgpu::DeviceDescriptor{
label:None,
@@ -125,9 +113,9 @@ impl<'a> SetupContextPartial3<'a>{
required_limits:needed_limits,
memory_hints:wgpu::MemoryHints::Performance,
trace:wgpu::Trace::Off,
experimental_features:unsafe{wgpu::ExperimentalFeatures::enabled()},
experimental_features:wgpu::ExperimentalFeatures::disabled(),
},
))
).await
.expect("Unable to find a suitable GPU adapter!");
SetupContextPartial4{
@@ -169,7 +157,7 @@ pub struct SetupContext<'a>{
pub config:wgpu::SurfaceConfiguration,
}
pub fn setup_and_start(title:&str){
pub async fn setup_and_start(title:&str){
let event_loop=winit::event_loop::EventLoop::new().unwrap();
println!("Initializing the surface...");
@@ -180,9 +168,9 @@ pub fn setup_and_start(title:&str){
let partial_2=partial_1.create_surface(&window).unwrap();
let partial_3=partial_2.pick_adapter();
let partial_3=partial_2.pick_adapter().await;
let partial_4=partial_3.request_device();
let partial_4=partial_3.request_device().await;
let size=window.inner_size();
@@ -196,16 +184,16 @@ pub fn setup_and_start(title:&str){
setup_context,
);
for arg in std::env::args().skip(1){
//for arg in std::env::args().skip(1){
window_thread.send(strafesnet_common::instruction::TimedInstruction{
time:strafesnet_common::integer::Time::ZERO,
instruction:crate::window::Instruction::WindowEvent(winit::event::WindowEvent::DroppedFile(arg.into())),
instruction:crate::window::Instruction::WindowEvent(winit::event::WindowEvent::DroppedFile("".into())),
}).unwrap();
};
//};
println!("Entering event loop...");
let mut app=crate::app::App::new(
std::time::Instant::now(),
chrono::Utc::now(),
window_thread
);
event_loop.run_app(&mut app).unwrap();

View File

@@ -1,5 +1,3 @@
enable wgpu_mesh_shader;
struct Camera {
// from camera to screen
proj: mat4x4<f32>,
@@ -88,166 +86,6 @@ fn vs_entity_texture(
return result;
}
@group(1)
@binding(0)
var<uniform> model_instance: ModelInstance;
@group(1)
@binding(1)
var<uniform> ve_verts: array<vec4<f32>, 2>;
struct DebugEntityOutput {
@builtin(position) position: vec4<f32>,
};
@vertex
fn vs_debug(
@location(0) pos: vec3<f32>,
) -> DebugEntityOutput {
var position: vec4<f32> = model_instance.transform * vec4<f32>(pos, 1.0);
var result: DebugEntityOutput;
result.position = camera.proj * camera.view * position;
return result;
}
struct TaskPayload {
four_bytes: u32,
}
var<task_payload> taskPayload: TaskPayload;
@task
@payload(taskPayload)
@workgroup_size(1)
fn ts_main() -> @builtin(mesh_task_size) vec3<u32> {
taskPayload.four_bytes = 0;
return vec3(1, 1, 1);
}
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) color: vec4<f32>,
}
struct PrimitiveOutput {
@builtin(triangle_indices) indices: vec3<u32>,
}
struct CircleOutput {
@builtin(vertices) vertices: array<VertexOutput, 24>,
@builtin(primitives) primitives: array<PrimitiveOutput, 22>,
@builtin(vertex_count) vertex_count: u32,
@builtin(primitive_count) primitive_count: u32,
}
var<workgroup> mesh_output: CircleOutput;
const tau: f32 = 3.141592653589793 * 2.0;
fn modulo(value:u32,modulus:u32)->u32{
return value-value/modulus*modulus;
}
@mesh(mesh_output)
@payload(taskPayload)
@workgroup_size(1)
fn ms_debug_vert(){
// circle with 24 vertices.
const LAYERS:u32 = 3;
const N:u32 = 3*(1<<LAYERS);
mesh_output.vertex_count = N;
mesh_output.primitive_count = N-2;
var vertex_world_position: vec4<f32> = model_instance.transform * ve_verts[0];
var vertex_screen_position: vec4<f32> = camera.proj * camera.view * vertex_world_position;
for (var i:u32 = 0; i<N/4; i++){
// draw a 1 unit redius circle
var theta: f32 = f32(i) * tau / f32(N);
var cos_sin: vec2<f32> = vec2(cos(theta), sin(theta));
var offset: vec2<f32> = 0.5 * cos_sin;
mesh_output.vertices[i].position = vertex_screen_position + vec4<f32>(offset, 0.0, 0.0);
mesh_output.vertices[i+N/4].position = vertex_screen_position + vec4<f32>(-offset.y, offset.x, 0.0, 0.0);
mesh_output.vertices[i+N/4*2].position = vertex_screen_position + vec4<f32>(-offset, 0.0, 0.0);
mesh_output.vertices[i+N/4*3].position = vertex_screen_position + vec4<f32>(offset.y, -offset.x, 0.0, 0.0);
}
// max area triangle indices
// the big triangle
mesh_output.primitives[0].indices = vec3<u32>(0, N/3, N/3*2);
// 3 layers of infill triangles to approximate circle better than 1 triangle.
// we start on the outer layer because it's easier to construct this way
var count:u32=N;
var base:u32=1;
for (var layer:u32 = 0; layer<LAYERS; layer++){
count=count>>1;
var step:u32=N/count;
for (var i:u32 = 0; i<count; i++){
mesh_output.primitives[base+i].indices = vec3<u32>(i*step, i*step+(step>>1), modulo(i*step+step,N));
}
base+=count;
}
}
@mesh(mesh_output)
@payload(taskPayload)
@workgroup_size(1)
fn ms_debug_edge(){
// draw two circles for now.
const LAYERS:u32 = 3;
const N:u32 = 2*(1<<LAYERS);
mesh_output.vertex_count = 2*(3+2+4+8);
mesh_output.primitive_count = 2*(1+2+4+8)+2;
var v0_world_position: vec4<f32> = model_instance.transform * ve_verts[0];
var v1_world_position: vec4<f32> = model_instance.transform * ve_verts[1];
var v0_screen_position: vec4<f32> = camera.proj * camera.view * v0_world_position;
var v1_screen_position: vec4<f32> = camera.proj * camera.view * v1_world_position;
var edge_dir_world: vec4<f32> = normalize(v0_world_position - v1_world_position);
var edge_dir_screen: vec4<f32> = camera.proj * camera.view * edge_dir_world;
for (var i:u32 = 0; i<=N/2; i++){
// two half circles that make a whole
var theta: f32 = f32(i) * tau / f32(N);
var cos_sin: vec2<f32> = vec2(cos(theta), sin(theta));
// construct basis vectors
var y_axis: vec2<f32> = edge_dir_screen.xy;
var x_axis: vec2<f32> = y_axis.yx;
x_axis.x = -x_axis.x;
var offset: vec4<f32> = vec4<f32>(0.5 * (x_axis * cos_sin.x + y_axis * cos_sin.y), 0.0, 0.0);;
mesh_output.vertices[i].position = v0_screen_position + offset;
mesh_output.vertices[N/2+1+i].position = v1_screen_position - offset;
}
// max area triangle indices
// number of primitives per circle half
const P:u32 = N/2;
// the big triangles between the circles
mesh_output.primitives[0].indices = vec3<u32>(0, N/2+1, P);
mesh_output.primitives[P].indices = vec3<u32>(N/2+1, 0, P + N/2+1);
// 3 layers of infill triangles to approximate circle better than 1 triangle.
// we start on the outer layer because it's easier to construct this way
var count:u32=P;
var base:u32=1;
for (var layer:u32 = 0; layer<LAYERS; layer++){
count=count>>1;
var step:u32=P/count;
for (var i:u32 = 0; i<count; i++){
var indices = vec3<u32>(i*step, i*step+(step>>1), i*step+step);
mesh_output.primitives[base+i].indices = indices;
mesh_output.primitives[P+base+i].indices = indices + N/2+1;
}
base+=count;
}
}
//group 2 is the skybox texture
@group(1)
@binding(0)
@@ -272,8 +110,3 @@ fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),0.5+0.5*abs(d));
}
@fragment
fn fs_debug(vertex: DebugEntityOutput) -> @location(0) vec4<f32> {
return model_instance.color;
}

View File

@@ -57,7 +57,8 @@ impl WindowContext<'_>{
fn window_event(&mut self,time:SessionTime,event:winit::event::WindowEvent){
match event{
winit::event::WindowEvent::DroppedFile(path)=>{
match crate::file::load(path.as_path()){
let data=include_bytes!("/run/media/quat/Files/Documents/map-files/strafesnet/maps/bhop_snfm/5692093612.snfm");
match crate::file::load(std::io::Cursor::new(data)){
Ok(LoadFormat::Map(map))=>self.physics_thread.send(TimedInstruction{time,instruction:PhysicsWorkerInstruction::ChangeMap(map)}).unwrap(),
Ok(LoadFormat::Bot(bot))=>self.physics_thread.send(TimedInstruction{time,instruction:PhysicsWorkerInstruction::LoadReplay(bot)}).unwrap(),
Err(e)=>println!("Failed to load file: {e}"),
@@ -171,7 +172,6 @@ impl WindowContext<'_>{
"X"|"x"=>session_ctrl!(StopSpectate,s),
"N"|"n"=>session_ctrl!(SaveReplay,s),
"J"|"j"=>session_ctrl!(LoadIntoReplayState,s),
"H"|"h"=>session_ctrl!(DebugSimulation,s),
_=>None,
},
_=>None,
@@ -237,17 +237,21 @@ impl WindowContext<'_>{
}
}
}
pub fn worker<'a>(
window:&'a winit::window::Window,
setup_context:crate::setup::SetupContext<'a>,
)->crate::compat_worker::QNWorker<'a,TimedInstruction<Instruction,SessionTime>>{
// WindowContextSetup::new
#[cfg(feature="user-install")]
let directories=Directories::user().unwrap();
let directories=Directories::user();
#[cfg(not(feature="user-install"))]
let directories=Directories::portable().unwrap();
let directories=Directories::portable().ok();
let user_settings=directories.settings();
let user_settings=match &directories{
Some(directories)=>directories.settings(),
None=>strafesnet_settings::settings::UserSettings::default(),
};
let mut graphics=strafesnet_graphics::graphics::GraphicsState::new(&setup_context.device,&setup_context.queue,&setup_context.config);
graphics.load_user_settings(&user_settings);

1
web-client/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/dist

2
web-client/Trunk.toml Normal file
View File

@@ -0,0 +1,2 @@
[build]
target = "index.html"

47
web-client/index.html Normal file
View File

@@ -0,0 +1,47 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, height=device-height, initial-scale=1"
/>
<title>Strafe Client</title>
<base data-trunk-public-url />
<style type="text/css">
:focus {
outline: none;
}
body {
margin: 0px;
background: #fff;
width: 100%;
height: 100%;
}
#content {
/* This allows the flexbox to grow to max size, this is needed for WebGPU */
flex: 1 1 100%;
/* This forces CSS to ignore the width/height of the canvas, this is needed for WebGL */
contain: size;
}
.main-canvas {
margin: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas class="main-canvas" id="canvas"></canvas>
<link
data-trunk
rel="rust"
href="../strafe-client/Cargo.toml"
data-wasm-opt-params="--enable-bulk-memory --enable-nontrapping-float-to-int"
/>
</body>
</html>