Compare commits

...

58 Commits

Author SHA1 Message Date
8665ce07f1 debug-26 2026-01-26 07:53:43 -08:00
abed044dfd print mesh 2026-01-23 08:25:26 -08:00
aeb3583d7f print body 2026-01-23 08:11:16 -08:00
0745447386 clip depth 2026-01-22 10:21:21 -08:00
bf1fb8e7fb make it green 2026-01-22 10:10:12 -08:00
b7e01b13d1 animate hitbox 2026-01-22 10:10:12 -08:00
2803a7308f fix hitbox size 2026-01-22 10:10:12 -08:00
a4362e04e3 render debug hitbox 2026-01-22 10:10:12 -08:00
242fac8959 the debug pipeline 2026-01-22 10:10:12 -08:00
8328f1897d rename mesh shader pipeline variable 2026-01-22 10:10:12 -08:00
97e22e0b9c 2s 2026-01-22 10:10:12 -08:00
adf13053f7 doin it wrong 2026-01-22 10:10:12 -08:00
6766b2d8e9 display animated crawl 2026-01-22 10:10:12 -08:00
2daab36253 fev mesh0 2026-01-22 10:10:12 -08:00
77bd681d5b update debug vis in the right place 2026-01-22 10:10:11 -08:00
b7ecc5ff16 press H to debug simulation 2026-01-22 10:10:11 -08:00
90da36d851 project ideal point 2026-01-22 10:10:11 -08:00
bd4ce78a0c wonky edge shader 2026-01-22 10:10:11 -08:00
e97a2a375d freakin huge circle 2026-01-22 10:10:11 -08:00
a1b5d12da7 edge shader 2026-01-22 10:10:11 -08:00
a84db143b0 do less sin 2026-01-22 10:10:11 -08:00
f70cb8a2e7 plumb vert pos 2026-01-22 10:10:11 -08:00
b78c56a1e4 add needless complexity 2026-01-22 10:10:11 -08:00
b983df1b97 ez modulo 2026-01-22 10:10:11 -08:00
1e3d9b5c37 0.5 world-space unit circle 2026-01-22 10:10:11 -08:00
981814ff4f Revert "drop resolution for thick lines"
This reverts commit 0ddd41c1b6.
2026-01-22 10:10:11 -08:00
c79b24b6b9 fix mesh shader 2026-01-22 10:10:11 -08:00
ae0c2138b3 0.1 screen sizes 2026-01-22 10:10:11 -08:00
71ca1f9dfc disable culling 2026-01-22 10:10:11 -08:00
1f3c897dc6 draw a circle at the mesh center for now 2026-01-22 10:10:11 -08:00
ffc74ee52e draw_mesh_tasks 2026-01-22 10:10:11 -08:00
696c084e03 raise limits 2026-01-22 10:10:11 -08:00
8fe826414b fix shader 2026-01-22 10:10:11 -08:00
dfc18c9d08 raise limits 2026-01-22 10:10:11 -08:00
9d8999f0c7 raise limits 2026-01-22 10:10:11 -08:00
345c89dc1a stage visibility 2026-01-22 10:10:11 -08:00
f5b1a71bd7 disable edge pipeline 2026-01-22 10:10:11 -08:00
82f98b5caf raise limits 2026-01-22 10:10:11 -08:00
156509b787 fix shader 2026-01-22 10:10:11 -08:00
8f627d530d enable experimental feature 2026-01-22 10:10:11 -08:00
96ff7f06af write shader 2026-01-22 10:10:11 -08:00
4cb7bd7e8b wgpu bleeding edge 2026-01-22 10:10:11 -08:00
7ca4cddb90 wip mesh shader circle 2026-01-22 10:10:11 -08:00
5c1c050b10 the bug 2026-01-22 10:10:11 -08:00
8250e8e0d0 type safe enough 2026-01-22 10:10:11 -08:00
261ac43d26 ya 2026-01-22 10:10:11 -08:00
c62fe77649 done 2026-01-22 10:10:11 -08:00
c61cf70a48 the 2026-01-22 10:10:11 -08:00
2dc91dd4f9 generate topological indices 2026-01-22 10:10:11 -08:00
ac11b80eef create fev pipelines 2026-01-22 10:10:11 -08:00
e1d61b56a0 drop resolution for thick lines 2026-01-22 10:10:11 -08:00
1c0a28e3ff fix lints 2026-01-22 10:10:11 -08:00
4628cb1c15 fix rebase 2026-01-22 10:10:11 -08:00
5d0d474a91 debug physics models visually 2026-01-22 10:10:11 -08:00
f52a59ddba Session::debug_raycast_print_model_id_if_changed 2026-01-22 10:10:10 -08:00
11d8b55865 skip faces early 2026-01-22 10:10:10 -08:00
d78de7ba90 physics: PhysicsData::trace_ray 2026-01-22 10:10:10 -08:00
f591981f53 physics: derive Eq for Minkowski FEV 2026-01-22 10:10:10 -08:00
13 changed files with 775 additions and 20 deletions

2
Cargo.lock generated
View File

@@ -3892,6 +3892,8 @@ dependencies = [
"glam", "glam",
"id", "id",
"strafesnet_common", "strafesnet_common",
"strafesnet_physics",
"strafesnet_rbx_loader",
"strafesnet_session", "strafesnet_session",
"strafesnet_settings", "strafesnet_settings",
"wgpu", "wgpu",

View File

@@ -9,6 +9,8 @@ ddsfile = "0.5.1"
glam = "0.30.0" glam = "0.30.0"
id = { version = "0.1.0", registry = "strafesnet" } id = { version = "0.1.0", registry = "strafesnet" }
strafesnet_common = { path = "../../lib/common", 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_session = { path = "../session", registry = "strafesnet" }
strafesnet_settings = { path = "../settings", registry = "strafesnet" } strafesnet_settings = { path = "../settings", registry = "strafesnet" }
wgpu = "28.0.0" wgpu = "28.0.0"

View File

@@ -5,10 +5,20 @@ use strafesnet_settings::settings;
use strafesnet_session::session; use strafesnet_session::session;
use strafesnet_common::model::{self, ColorId, NormalId, PolygonIter, PositionId, RenderConfigId, TextureCoordinateId, VertexId}; use strafesnet_common::model::{self, ColorId, NormalId, PolygonIter, PositionId, RenderConfigId, TextureCoordinateId, VertexId};
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel}; use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
use crate::model::{self as model_graphics,IndexedGraphicsMeshOwnedRenderConfig,IndexedGraphicsMeshOwnedRenderConfigId,GraphicsMeshOwnedRenderConfig,GraphicsModelColor4,GraphicsModelOwned,GraphicsVertex}; use crate::model::{self as model_graphics,IndexedGraphicsMeshOwnedRenderConfig,IndexedGraphicsMeshOwnedRenderConfigId,GraphicsMeshOwnedRenderConfig,GraphicsModelColor4,GraphicsModelOwned,GraphicsVertex,DebugGraphicsVertex};
pub fn required_limits()->wgpu::Limits{ pub fn required_limits()->wgpu::Limits{
wgpu::Limits::default() 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
} }
struct Indices{ struct Indices{
@@ -36,12 +46,135 @@ struct GraphicsModel{
instance_count:u32, 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{ struct GraphicsSamplers{
repeat:wgpu::Sampler, repeat:wgpu::Sampler,
} }
struct GraphicsBindGroupLayouts{ struct GraphicsBindGroupLayouts{
model:wgpu::BindGroupLayout, model:wgpu::BindGroupLayout,
debug_model:wgpu::BindGroupLayout,
} }
struct GraphicsBindGroups{ struct GraphicsBindGroups{
@@ -52,6 +185,9 @@ struct GraphicsBindGroups{
struct GraphicsPipelines{ struct GraphicsPipelines{
skybox:wgpu::RenderPipeline, skybox:wgpu::RenderPipeline,
model:wgpu::RenderPipeline, model:wgpu::RenderPipeline,
debug:wgpu::RenderPipeline,
debug_edge:wgpu::RenderPipeline,
debug_vert:wgpu::RenderPipeline,
} }
struct GraphicsCamera{ struct GraphicsCamera{
@@ -132,6 +268,10 @@ pub struct GraphicsState{
camera_buf:wgpu::Buffer, camera_buf:wgpu::Buffer,
temp_squid_texture_view:wgpu::TextureView, temp_squid_texture_view:wgpu::TextureView,
models:Vec<GraphicsModel>, models:Vec<GraphicsModel>,
debug_meshes:Vec<DebugGraphicsMesh>,
debug_models:Vec<DebugGraphicsModel>,
hitbox_mesh:DebugGraphicsMesh,
hitbox_model:DebugGraphicsModel,
depth_view:wgpu::TextureView, depth_view:wgpu::TextureView,
staging_belt:wgpu::util::StagingBelt, staging_belt:wgpu::util::StagingBelt,
} }
@@ -166,6 +306,16 @@ impl GraphicsState{
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2(); 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){ 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 //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_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); let texture_id=model::TextureId::new(texture_id as u32);
@@ -546,7 +696,7 @@ impl GraphicsState{
entries:&[ entries:&[
wgpu::BindGroupLayoutEntry{ wgpu::BindGroupLayoutEntry{
binding:0, binding:0,
visibility:wgpu::ShaderStages::VERTEX, visibility:wgpu::ShaderStages::VERTEX|wgpu::ShaderStages::MESH,
ty:wgpu::BindingType::Buffer{ ty:wgpu::BindingType::Buffer{
ty:wgpu::BufferBindingType::Uniform, ty:wgpu::BufferBindingType::Uniform,
has_dynamic_offset:false, has_dynamic_offset:false,
@@ -608,6 +758,31 @@ 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{ let clamp_sampler=device.create_sampler(&wgpu::SamplerDescriptor{
label:Some("Clamp Sampler"), label:Some("Clamp Sampler"),
@@ -756,6 +931,14 @@ impl GraphicsState{
], ],
immediate_size:0, 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{ let sky_pipeline_layout=device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor{
label:None, label:None,
bind_group_layouts:&[ bind_group_layouts:&[
@@ -831,6 +1014,92 @@ impl GraphicsState{
multiview_mask:None, multiview_mask:None,
cache: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=GraphicsCamera::default();
let camera_uniforms=camera.to_uniform_data(glam::Vec3::ZERO,glam::Vec2::ZERO); let camera_uniforms=camera.to_uniform_data(glam::Vec3::ZERO,glam::Vec2::ZERO);
@@ -867,10 +1136,23 @@ impl GraphicsState{
let depth_view=Self::create_depth_texture(config,device); 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{ Self{
pipelines:GraphicsPipelines{ pipelines:GraphicsPipelines{
skybox:sky_pipeline, skybox:sky_pipeline,
model:model_pipeline model:model_pipeline,
debug:debug_model_pipeline,
debug_edge:debug_model_pipeline_edge,
debug_vert:debug_model_pipeline_vert,
}, },
bind_groups:GraphicsBindGroups{ bind_groups:GraphicsBindGroups{
camera:camera_bind_group, camera:camera_bind_group,
@@ -879,9 +1161,16 @@ impl GraphicsState{
camera, camera,
camera_buf, camera_buf,
models:Vec::new(), models:Vec::new(),
debug_meshes:Vec::new(),
debug_models:Vec::new(),
hitbox_mesh,
hitbox_model,
depth_view, depth_view,
staging_belt:wgpu::util::StagingBelt::new(device.clone(),0x100), staging_belt:wgpu::util::StagingBelt::new(device.clone(),0x100),
bind_group_layouts:GraphicsBindGroupLayouts{model:model_bind_group_layout}, bind_group_layouts:GraphicsBindGroupLayouts{
model:model_bind_group_layout,
debug_model:debug_model_bind_group_layout,
},
samplers:GraphicsSamplers{repeat:repeat_sampler}, samplers:GraphicsSamplers{repeat:repeat_sampler},
temp_squid_texture_view:squid_texture_view, temp_squid_texture_view:squid_texture_view,
} }
@@ -935,6 +1224,66 @@ impl GraphicsState{
.copy_from_slice(bytemuck::cast_slice(&model_uniforms)); .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(); self.staging_belt.finish();
{ {
@@ -970,6 +1319,7 @@ impl GraphicsState{
rpass.set_bind_group(0,&self.bind_groups.camera,&[]); rpass.set_bind_group(0,&self.bind_groups.camera,&[]);
rpass.set_bind_group(1,&self.bind_groups.skybox_texture,&[]); rpass.set_bind_group(1,&self.bind_groups.skybox_texture,&[]);
// Draw all models.
rpass.set_pipeline(&self.pipelines.model); rpass.set_pipeline(&self.pipelines.model);
for model in &self.models{ for model in &self.models{
rpass.set_bind_group(2,&model.bind_group,&[]); rpass.set_bind_group(2,&model.bind_group,&[]);
@@ -981,6 +1331,46 @@ impl GraphicsState{
rpass.set_pipeline(&self.pipelines.skybox); rpass.set_pipeline(&self.pipelines.skybox);
rpass.draw(0..3,0..1); 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())); queue.submit(std::iter::once(encoder.finish()));

View File

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

View File

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

View File

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

View File

@@ -60,7 +60,7 @@ impl DirectedEdge for SubmeshDirectedEdgeId{
} }
//Vertex <-> Edge <-> Face -> Collide //Vertex <-> Edge <-> Face -> Collide
#[derive(Debug)] #[derive(Debug,Clone)]
pub enum FEV<M:MeshQuery>{ pub enum FEV<M:MeshQuery>{
Face(M::Face), Face(M::Face),
Edge(<M::Edge as DirectedEdge>::UndirectedEdge), Edge(<M::Edge as DirectedEdge>::UndirectedEdge),
@@ -444,6 +444,24 @@ pub struct PhysicsMeshView<'a>{
data:&'a PhysicsMeshData, data:&'a PhysicsMeshData,
topology:&'a PhysicsMeshTopology, 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<'_>{ impl MeshQuery for PhysicsMeshView<'_>{
type Face=SubmeshFaceId; type Face=SubmeshFaceId;
type Edge=SubmeshDirectedEdgeId; type Edge=SubmeshDirectedEdgeId;
@@ -526,6 +544,9 @@ impl TransformedMesh<'_>{
pub fn verts<'a>(&'a self)->impl Iterator<Item=Vector3<Fixed<2,64>>>+'a{ 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)) 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<'_>{ impl MeshQuery for TransformedMesh<'_>{
type Face=SubmeshFaceId; type Face=SubmeshFaceId;
@@ -612,7 +633,7 @@ impl UndirectedEdge for MinkowskiEdge{
} }
} }
} }
#[derive(Clone,Copy,Debug)] #[derive(Clone,Copy,Debug,Eq,PartialEq)]
pub enum MinkowskiDirectedEdge{ pub enum MinkowskiDirectedEdge{
VertEdge(SubmeshVertId,SubmeshDirectedEdgeId), VertEdge(SubmeshVertId,SubmeshDirectedEdgeId),
EdgeVert(SubmeshDirectedEdgeId,SubmeshVertId), EdgeVert(SubmeshDirectedEdgeId,SubmeshVertId),
@@ -649,6 +670,31 @@ pub struct MinkowskiMesh<'a>{
mesh1:TransformedMesh<'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 type GigaTime=Ratio<Fixed<4,128>,Fixed<4,128>>;
pub fn into_giga_time(time:Time,relative_to:Time)->GigaTime{ pub fn into_giga_time(time:Time,relative_to:Time)->GigaTime{
let r=(time-relative_to).to_ratio(); let r=(time-relative_to).to_ratio();

View File

@@ -1,4 +1,5 @@
use std::collections::{HashMap,HashSet}; use std::collections::{HashMap,HashSet};
use crate::model::DirectedEdge;
use crate::model::{self as model_physics,PhysicsMesh,PhysicsMeshTransform,TransformedMesh,MeshQuery,PhysicsMeshId,PhysicsSubmeshId}; use crate::model::{self as model_physics,PhysicsMesh,PhysicsMeshTransform,TransformedMesh,MeshQuery,PhysicsMeshId,PhysicsSubmeshId};
use strafesnet_common::bvh; use strafesnet_common::bvh;
use strafesnet_common::map; use strafesnet_common::map;
@@ -287,7 +288,8 @@ impl PhysicsCamera{
.clamp(Self::ANGLE_PITCH_LOWER_LIMIT,Self::ANGLE_PITCH_UPPER_LIMIT); .clamp(Self::ANGLE_PITCH_LOWER_LIMIT,Self::ANGLE_PITCH_UPPER_LIMIT);
mat3::from_rotation_yx(ax,ay) mat3::from_rotation_yx(ax,ay)
} }
fn rotation(&self)->Planar64Mat3{ #[inline]
pub fn rotation(&self)->Planar64Mat3{
self.get_rotation(self.clamped_mouse_pos) self.get_rotation(self.clamped_mouse_pos)
} }
#[expect(dead_code)] #[expect(dead_code)]
@@ -669,7 +671,7 @@ impl From<CollisionAttributesId> for IntersectAttributesId{
} }
} }
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)] #[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
struct ContactModelId(u32); pub struct ContactModelId(u32);
impl From<ContactModelId> for ModelId{ impl From<ContactModelId> for ModelId{
fn from(value:ContactModelId)->ModelId{ fn from(value:ContactModelId)->ModelId{
ModelId::new(value.get()) ModelId::new(value.get())
@@ -681,7 +683,7 @@ impl From<ModelId> for ContactModelId{
} }
} }
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)] #[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
struct IntersectModelId(u32); pub struct IntersectModelId(u32);
impl From<IntersectModelId> for ModelId{ impl From<IntersectModelId> for ModelId{
fn from(value:IntersectModelId)->ModelId{ fn from(value:IntersectModelId)->ModelId{
ModelId::new(value.get()) ModelId::new(value.get())
@@ -693,7 +695,7 @@ impl From<ModelId> for IntersectModelId{
} }
} }
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)] #[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
enum PhysicsModelId{ pub enum PhysicsModelId{
Contact(ContactModelId), Contact(ContactModelId),
Intersect(IntersectModelId), Intersect(IntersectModelId),
} }
@@ -707,9 +709,9 @@ impl From<PhysicsModelId> for ModelId{
} }
//unique physics meshes indexed by this //unique physics meshes indexed by this
#[derive(Debug,Clone,Copy,Eq,Hash,PartialEq)] #[derive(Debug,Clone,Copy,Eq,Hash,PartialEq)]
struct ConvexMeshId<Id>{ pub struct ConvexMeshId<Id>{
model_id:Id, pub model_id:Id,
submesh_id:PhysicsSubmeshId, pub submesh_id:PhysicsSubmeshId,
} }
impl<Id> ConvexMeshId<Id>{ impl<Id> ConvexMeshId<Id>{
fn map<NewId>(self,model_id:NewId)->ConvexMeshId<NewId>{ fn map<NewId>(self,model_id:NewId)->ConvexMeshId<NewId>{
@@ -998,6 +1000,57 @@ impl PhysicsData{
hitbox_mesh:StyleModifiers::default().calculate_mesh(), 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{ pub fn new(map:&map::CompleteMap)->Self{
let modes=map.modes.clone().denormalize(); let modes=map.modes.clone().denormalize();
let mut used_contact_attributes=Vec::new(); let mut used_contact_attributes=Vec::new();
@@ -1146,6 +1199,9 @@ impl PhysicsData{
modes, modes,
} }
} }
pub fn vertex_transform(&self)->&integer::Planar64Affine3{
&self.hitbox_mesh.transform.vertex
}
} }
// the collection of information required to run physics // the collection of information required to run physics
pub struct PhysicsContext<'a>{ pub struct PhysicsContext<'a>{

View File

@@ -48,6 +48,7 @@ pub enum SessionControlInstruction{
StopSpectate, StopSpectate,
SaveReplay, SaveReplay,
LoadIntoReplayState, LoadIntoReplayState,
DebugSimulation,
} }
pub enum SessionPlaybackInstruction{ pub enum SessionPlaybackInstruction{
SkipForward, SkipForward,
@@ -60,6 +61,8 @@ pub struct FrameState{
pub body:physics::Body, pub body:physics::Body,
pub camera:physics::PhysicsCamera, pub camera:physics::PhysicsCamera,
pub time:PhysicsTime, pub time:PhysicsTime,
pub hit:Option<Hit>,
pub debug_hitbox_position:Option<strafesnet_common::integer::Planar64Affine3>,
} }
pub struct Simulation{ pub struct Simulation{
@@ -76,11 +79,38 @@ impl Simulation{
physics, physics,
} }
} }
pub fn get_frame_state(&self,time:SessionTime)->FrameState{ pub fn get_frame_state(
&self,
time:SessionTime,
debug_model:Option<Hit>,
debug_hitbox_position:Option<strafesnet_common::integer::Planar64Affine3>,
)->FrameState{
FrameState{ FrameState{
body:self.physics.camera_body(), body:self.physics.camera_body(),
camera:self.physics.camera(), camera:self.physics.camera(),
time:self.timer.time(time), 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,
} }
} }
} }
@@ -148,6 +178,12 @@ enum ViewState{
Replay(BotId), 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{ pub struct Session{
directories:Directories, directories:Directories,
user_settings:UserSettings, user_settings:UserSettings,
@@ -160,6 +196,8 @@ pub struct Session{
recording:Recording, recording:Recording,
//players:HashMap<PlayerId,Simulation>, //players:HashMap<PlayerId,Simulation>,
replays:HashMap<BotId,Replay>, replays:HashMap<BotId,Replay>,
last_ray_hit:Option<Hit>,
debug_simulation:Option<DebugSimulation>,
} }
impl Session{ impl Session{
pub fn new( pub fn new(
@@ -176,6 +214,8 @@ impl Session{
view_state:ViewState::Play, view_state:ViewState::Play,
recording:Default::default(), recording:Default::default(),
replays:HashMap::new(), replays:HashMap::new(),
last_ray_hit:None,
debug_simulation:None,
} }
} }
fn clear_recording(&mut self){ fn clear_recording(&mut self){
@@ -186,13 +226,45 @@ impl Session{
self.geometry_shared=PhysicsData::new(map); self.geometry_shared=PhysicsData::new(map);
} }
pub fn get_frame_state(&self,time:SessionTime)->Option<FrameState>{ 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{ match &self.view_state{
ViewState::Play=>Some(self.simulation.get_frame_state(time)), ViewState::Play=>Some(self.simulation.get_frame_state(time,self.last_ray_hit.clone(),debug_hitbox_position)),
ViewState::Replay(bot_id)=>self.replays.get(bot_id).map(|replay| ViewState::Replay(bot_id)=>self.replays.get(bot_id).map(|replay|
replay.simulation.get_frame_state(time) replay.simulation.get_frame_state(time,None,debug_hitbox_position)
), ),
} }
} }
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{ pub fn user_settings(&self)->&UserSettings{
&self.user_settings &self.user_settings
} }
@@ -408,6 +480,10 @@ impl InstructionConsumer<Instruction<'_>> for Session{
// begin spectate // begin spectate
self.view_state=ViewState::Replay(bot_id); 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=>{ Instruction::Idle=>{
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Idle); run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Idle);
// this just refreshes the replays // this just refreshes the replays

View File

@@ -59,6 +59,10 @@ pub fn new<'a>(
}, },
Instruction::Render=>{ Instruction::Render=>{
run_session_instruction!(ins.time,SessionInstruction::Idle); 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)=session.get_frame_state(ins.time){
run_graphics_worker_instruction!(GraphicsInstruction::Render(frame_state)); run_graphics_worker_instruction!(GraphicsInstruction::Render(frame_state));
} }

View File

@@ -3,7 +3,7 @@ fn optional_features()->wgpu::Features{
|wgpu::Features::TEXTURE_COMPRESSION_ETC2 |wgpu::Features::TEXTURE_COMPRESSION_ETC2
} }
fn required_features()->wgpu::Features{ fn required_features()->wgpu::Features{
wgpu::Features::TEXTURE_COMPRESSION_BC wgpu::Features::TEXTURE_COMPRESSION_BC|wgpu::Features::EXPERIMENTAL_MESH_SHADER
} }
fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{ fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{
wgpu::DownlevelCapabilities{ wgpu::DownlevelCapabilities{
@@ -125,7 +125,7 @@ impl<'a> SetupContextPartial3<'a>{
required_limits:needed_limits, required_limits:needed_limits,
memory_hints:wgpu::MemoryHints::Performance, memory_hints:wgpu::MemoryHints::Performance,
trace:wgpu::Trace::Off, trace:wgpu::Trace::Off,
experimental_features:wgpu::ExperimentalFeatures::disabled(), experimental_features:unsafe{wgpu::ExperimentalFeatures::enabled()},
}, },
)) ))
.expect("Unable to find a suitable GPU adapter!"); .expect("Unable to find a suitable GPU adapter!");

View File

@@ -1,3 +1,5 @@
enable wgpu_mesh_shader;
struct Camera { struct Camera {
// from camera to screen // from camera to screen
proj: mat4x4<f32>, proj: mat4x4<f32>,
@@ -86,6 +88,166 @@ fn vs_entity_texture(
return result; 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 2 is the skybox texture
@group(1) @group(1)
@binding(0) @binding(0)
@@ -110,3 +272,8 @@ fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb; 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)); 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

@@ -171,6 +171,7 @@ impl WindowContext<'_>{
"X"|"x"=>session_ctrl!(StopSpectate,s), "X"|"x"=>session_ctrl!(StopSpectate,s),
"N"|"n"=>session_ctrl!(SaveReplay,s), "N"|"n"=>session_ctrl!(SaveReplay,s),
"J"|"j"=>session_ctrl!(LoadIntoReplayState,s), "J"|"j"=>session_ctrl!(LoadIntoReplayState,s),
"H"|"h"=>session_ctrl!(DebugSimulation,s),
_=>None, _=>None,
}, },
_=>None, _=>None,