Better shader org, prep for gi

This commit is contained in:
2026-09-21 23:12:26 +02:00
parent a332ac08ed
commit e673c6dc0d
17 changed files with 1323 additions and 1625 deletions
+380 -116
View File
@@ -59,6 +59,7 @@ use winit::window::WindowId;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::producers::ChunkedProducer;
use crate::producers::SdfGenerator;
use crate::producers::SineGenerator;
use crate::producers::TerrainGenerator;
use crate::sparse_tree::NTreeNodeLocator;
@@ -82,6 +83,14 @@ mod sparse_tree;
mod voxel_cache;
//
enum DisplayTexture
{
Target,
Normal,
Pos,
Albedo,
}
struct State
{
instance: wgpu::Instance,
@@ -92,16 +101,23 @@ struct State
surface: wgpu::Surface<'static>,
depth_buffer: (wgpu::Texture, wgpu::TextureView),
target_texture: (wgpu::Texture, wgpu::TextureView),
position_gbuffer: (wgpu::Texture, wgpu::TextureView),
normal_gbuffer: (wgpu::Texture, wgpu::TextureView),
albedo_gbuffer: (wgpu::Texture, wgpu::TextureView),
surface_format: wgpu::TextureFormat,
target_blitter: wgpu::util::TextureBlitter,
egui_renderer: EguiRenderer,
display: DisplayTexture,
//pipeline: RenderPipeline,
pipeline: ComputePipeline,
gi_pipeline: ComputePipeline,
surface_bg_layout: BindGroupLayout,
gi_bg_layout: BindGroupLayout,
voxel_cache: Arc<Mutex<VoxelCache<4>>>,
cache_interface: Arc<CacheProducerInterface<4>>,
terrain_generator: Arc<TerrainGenerator<4>>,
terrain_generator: Arc<SdfGenerator<4>>,
//terrain_generator: Arc<TerrainGenerator<4>>,
chunk_pos_map: Arc<HashMap<u32, (usize, usize, usize)>>,
instance_buffer: Buffer,
instance_count: usize,
@@ -170,6 +186,7 @@ impl State
| Features::TIMESTAMP_QUERY_INSIDE_ENCODERS
| Features::STORAGE_RESOURCE_BINDING_ARRAY
| Features::BUFFER_BINDING_ARRAY
| Features::PASSTHROUGH_SHADERS
| Features::SHADER_INT64,
required_limits: wgpu::Limits {
max_immediate_size: 112,
@@ -192,12 +209,16 @@ impl State
let egui_renderer = EguiRenderer::new(&device, surface_format, &window);
let attributes = vec![VoxelAttribute { word_count: 1 }];
let attributes = vec![
VoxelAttribute { word_count: 1 },
VoxelAttribute { word_count: 3 },
];
let mut voxel_cache =
VoxelCache::<4>::new(100_000, device.clone(), queue.clone(), attributes.clone());
let cache_interface = CacheProducerInterface::new(1024, &device, attributes.clone());
let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
//let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
let terrain_generator = SdfGenerator::<4>::new(5);
// let terrain_generator = TerrainGenerator::<4>::new(
// 5,
// "./pointe_percee/height.tif",
@@ -210,11 +231,12 @@ impl State
// 0.2,
// "/home/albin/Documents/vxls_maps/lapiz/ortho.jpg",
// );
//
let mut chunk_pos_map = HashMap::new();
let chunk_instances = (0..terrain_generator.chunk_width)
.cartesian_product(0..terrain_generator.chunk_height)
.cartesian_product(0..terrain_generator.chunk_alt)
let chunk_instances = (0..20)
.cartesian_product(0..20)
.cartesian_product(0..20)
.map(|((x, z), y)| {
let chunk_id = voxel_cache.structure_table.allocate_structure(true);
//dbg!(chunk_id);
@@ -258,38 +280,159 @@ impl State
// };
//let shader_module = device.create_shader_module(include_wgsl!("../shaders/voxel.wgsl"));
// let shader_module = unsafe {
// device.create_shader_module_trusted(
// wgpu::ShaderModuleDescriptor {
// label: Some("../shaders/voxel.spv"),
// source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed(
// wgpu::include_spirv_source!("../shaders/voxel.spv"),
// )),
// },
// wgpu::ShaderRuntimeChecks {
// bounds_checks: false,
// force_loop_bounding: false,
// ray_query_initialization_tracking: false,
// task_shader_dispatch_tracking: false,
// mesh_shader_primitive_indices_clamp: false,
// int_div_checks: false,
// },
// )
// };
let shader_module = unsafe {
device.create_shader_module_trusted(
wgpu::ShaderModuleDescriptor {
label: Some("../shaders/voxel.spv"),
source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed(
wgpu::include_spirv_source!("../shaders/voxel.spv"),
)),
},
wgpu::ShaderRuntimeChecks {
bounds_checks: false,
force_loop_bounding: false,
ray_query_initialization_tracking: false,
task_shader_dispatch_tracking: false,
mesh_shader_primitive_indices_clamp: false,
int_div_checks: false,
},
)
device.create_shader_module_passthrough({
wgpu::ShaderModuleDescriptorPassthrough {
label: wgpu::__macro_helpers::Some("../shaders/voxel.spv"),
spirv: Some(std::borrow::Cow::Borrowed(wgpu::include_spirv_source!(
"../shaders/voxel.spv"
))),
entry_points: std::borrow::Cow::Borrowed(&[
wgpu::PassthroughShaderEntryPoint {
name: std::borrow::Cow::Borrowed("ray_march_compute"),
workgroup_size: (16, 16, 1),
},
]),
dxil: None,
metallib: None,
msl: None,
hlsl: None,
glsl: None,
wgsl: None,
}
})
};
let surface_bind_group_layout =
let gi_shader_module = unsafe {
device.create_shader_module_passthrough({
wgpu::ShaderModuleDescriptorPassthrough {
label: wgpu::__macro_helpers::Some("../shaders/gi.spv"),
spirv: Some(std::borrow::Cow::Borrowed(wgpu::include_spirv_source!(
"../shaders/gi.spv"
))),
entry_points: std::borrow::Cow::Borrowed(&[
wgpu::PassthroughShaderEntryPoint {
name: std::borrow::Cow::Borrowed("gi"),
workgroup_size: (16, 16, 1),
},
]),
dxil: None,
metallib: None,
msl: None,
hlsl: None,
glsl: None,
wgsl: None,
}
})
};
let ray_march_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("surface_bg_layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
entries: &[
// Pos gbuffer
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
count: None,
}],
// Albedo gbuffer
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
// Normal gbuffer
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
],
});
let gi_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("gi_bg_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
// Pos gbuffer
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::ReadOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
// Albedo gbuffer
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::ReadOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
// Normal gbuffer
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::ReadOnly,
format: wgpu::TextureFormat::Rgba32Float,
view_dimension: wgpu::TextureViewDimension::D2,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
@@ -297,7 +440,7 @@ impl State
bind_group_layouts: &[
Some(&voxel_cache.bind_group_layout()),
Some(&surface_bind_group_layout),
Some(&ray_march_bind_group_layout),
],
immediate_size: size_of::<Immediates>() as u32,
});
@@ -311,62 +454,24 @@ impl State
cache: None,
});
/*
let chunk_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader_module,
entry_point: Some("chunk"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: (size_of::<f32>() * 3 + size_of::<u32>()) as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x3,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Uint32,
offset: (size_of::<f32>() * 3) as u64,
shader_location: 1,
},
],
})],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Front),
unclipped_depth: false,
polygon_mode: wgpu::PolygonMode::Fill,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth24PlusStencil8,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &shader_module,
entry_point: Some("fragment"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
targets: &[Some(wgpu::ColorTargetState {
format: surface_format,
blend: None,
write_mask: wgpu::ColorWrites::default(),
})],
}),
multiview_mask: None,
let gi_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Gi pipeline layout"),
bind_group_layouts: &[
Some(&voxel_cache.bind_group_layout()),
Some(&gi_bind_group_layout),
],
immediate_size: size_of::<Immediates>() as u32,
});
let gi_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Compute render"),
layout: Some(&gi_pipeline_layout),
module: &gi_shader_module,
entry_point: Some("gi"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
*/
let state = State {
instance,
@@ -376,13 +481,34 @@ impl State
surface_format,
egui_renderer,
depth_buffer: Self::create_depth_buffer(&device, size.width, size.height),
position_gbuffer: Self::create_gbuffer_texture(
&device,
size.width,
size.height,
wgpu::TextureFormat::Rgba32Float,
),
normal_gbuffer: Self::create_gbuffer_texture(
&device,
size.width,
size.height,
wgpu::TextureFormat::Rgba32Float,
),
albedo_gbuffer: Self::create_gbuffer_texture(
&device,
size.width,
size.height,
wgpu::TextureFormat::Rgba32Float,
),
gi_pipeline,
gi_bg_layout: gi_bind_group_layout,
target_texture: Self::create_target_texture(&device, size.width, size.height),
target_blitter: wgpu::util::TextureBlitterBuilder::new(&device, surface_format)
.sample_type(wgpu::FilterMode::Nearest)
.build(),
display: DisplayTexture::Target,
queue,
device,
surface_bg_layout: surface_bind_group_layout,
surface_bg_layout: ray_march_bind_group_layout,
usage_vec: Arc::new(Mutex::new(vec![])),
pipeline: chunk_pipeline,
voxel_cache: Arc::new(Mutex::new(voxel_cache)),
@@ -403,6 +529,32 @@ impl State
state
}
fn create_gbuffer_texture(
device: &Device,
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> (Texture, TextureView)
{
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Target texture"),
size: Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING,
view_formats: &[format.add_srgb_suffix()],
});
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
(texture, texture_view)
}
fn create_target_texture(device: &Device, width: u32, height: u32) -> (Texture, TextureView)
{
let texture = device.create_texture(&wgpu::TextureDescriptor {
@@ -420,7 +572,7 @@ impl State
view_formats: &[],
});
let texture_view = texture.create_view(&wgpu::wgt::TextureViewDescriptor::default());
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
(texture, texture_view)
}
@@ -433,6 +585,38 @@ impl State
{
self.egui_renderer.handle_input(&self.window, event);
self.camera.handle_input(event);
if self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyT)
{
self.display = DisplayTexture::Target;
}
if self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyN)
{
self.display = DisplayTexture::Normal;
}
if self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyQ)
{
self.display = DisplayTexture::Albedo;
}
if self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyP)
{
self.display = DisplayTexture::Pos;
}
}
fn handle_device_event(&mut self, event: &DeviceEvent)
@@ -487,6 +671,7 @@ impl State
desired_maximum_frame_latency: 2,
present_mode: wgpu::PresentMode::AutoVsync,
};
println!("Surface conf");
self.surface.configure(&self.device, &surface_config);
}
@@ -494,13 +679,32 @@ impl State
{
self.size = new_size;
self.camera.aspect = new_size.width as f32 / new_size.height as f32;
self.configure_surface();
// reconfigure the surface
self.configure_surface();
self.depth_buffer =
Self::create_depth_buffer(&self.device, new_size.width, new_size.height);
self.target_texture =
Self::create_target_texture(&self.device, new_size.width, new_size.height);
self.position_gbuffer = Self::create_gbuffer_texture(
&self.device,
self.size.width,
self.size.height,
wgpu::TextureFormat::Rgba32Float,
);
self.normal_gbuffer = Self::create_gbuffer_texture(
&self.device,
self.size.width,
self.size.height,
wgpu::TextureFormat::Rgba32Float,
);
self.albedo_gbuffer = Self::create_gbuffer_texture(
&self.device,
self.size.width,
self.size.height,
wgpu::TextureFormat::Rgba32Float,
);
}
fn render(&mut self)
@@ -551,10 +755,43 @@ impl State
let surface_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("surface_bg"),
layout: &self.surface_bg_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&self.target_texture.1),
}],
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&self.position_gbuffer.1),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&self.albedo_gbuffer.1),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&self.normal_gbuffer.1),
},
],
});
let gi_surface_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("surface_bg"),
layout: &self.gi_bg_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&self.target_texture.1),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&self.position_gbuffer.1),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&self.albedo_gbuffer.1),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&self.normal_gbuffer.1),
},
],
});
// ~~ Ray-marching timestamp query setup ~~
@@ -594,9 +831,12 @@ impl State
width: self.size.width,
height: self.size.height,
chunk_width: self.terrain_generator.chunk_width as u32,
chunk_height: self.terrain_generator.chunk_height as u32,
chunk_alt: self.terrain_generator.chunk_alt as u32,
// chunk_width: self.terrain_generator.chunk_width as u32,
// chunk_height: self.terrain_generator.chunk_height as u32,
// chunk_alt: self.terrain_generator.chunk_alt as u32,
chunk_width: 20,
chunk_height: 20,
chunk_alt: 20,
}];
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.dispatch_workgroups(
@@ -604,15 +844,26 @@ impl State
self.size.height.div_ceil(16),
1,
);
renderpass.set_pipeline(&self.gi_pipeline);
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.set_bind_group(1, Some(&gi_surface_bg), &[]);
renderpass.dispatch_workgroups(
self.size.width.div_ceil(16),
self.size.height.div_ceil(16),
1,
);
drop(renderpass);
}
self.target_blitter.copy(
&self.device,
&mut encoder,
&self.target_texture.1,
&texture_view,
);
let target_view = match self.display
{
DisplayTexture::Target => &self.target_texture.1,
DisplayTexture::Normal => &self.normal_gbuffer.1,
DisplayTexture::Pos => &self.position_gbuffer.1,
DisplayTexture::Albedo => &self.albedo_gbuffer.1,
};
self.target_blitter
.copy(&self.device, &mut encoder, target_view, &texture_view);
/*
{
let mut renderpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -692,18 +943,23 @@ impl State
"Ray-marching time: {}",
*self.rm_time.lock() / 1_000_000.
));
egui_plot::Plot::new("Plot").show(ui, |plot_ui| {
plot_ui.bar_chart(BarChart::new(
"histo",
self.usage_vec
.lock()
.iter()
.enumerate()
.map(|(i, x)| egui_plot::Bar::new(i as f64, *x as f64))
.collect(),
));
});
ui.label("Hello !")
// ui.image(egui::ImageSource::Texture(egui::load::SizedTexture::new(
// position_id,
// [512., 512.],
// )));
egui_plot::Plot::new("Plot")
.height(512.)
.show(ui, |plot_ui| {
plot_ui.bar_chart(BarChart::new(
"histo",
self.usage_vec
.lock()
.iter()
.enumerate()
.map(|(i, x)| egui_plot::Bar::new(i as f64, *x as f64))
.collect(),
));
});
},
);
@@ -815,6 +1071,7 @@ impl State
let mut structure_nodes: Vec<StructurePoolElement<4>> = vec![];
let mut color_nodes: Vec<[ColorBytes; 64]> = vec![];
let mut normal_nodes: Vec<[(f32, f32, f32); 64]> = vec![];
let mut location_nodes = vec![];
cache_node_requests
@@ -879,6 +1136,7 @@ impl State
pointers: node.structure,
},
node.colors,
node.normals,
location,
)
})
@@ -887,7 +1145,8 @@ impl State
.for_each(|data| {
structure_nodes.push(data.0);
color_nodes.push(std::array::from_fn(|i| data.1[i].into()));
location_nodes.push(data.2);
normal_nodes.push(data.2);
location_nodes.push(data.3);
});
if structure_nodes.len() != 0
@@ -902,6 +1161,11 @@ impl State
0,
unsafe { as_raw_bytes(color_nodes.as_slice()) },
);
cloned_queue.write_buffer(
&cloned_cache_interface.attributes_buffers()[1],
0,
unsafe { as_raw_bytes(normal_nodes.as_slice()) },
);
cloned_queue.write_buffer(
cloned_cache_interface.location_nodes_buffer(),
0,