Metal: draw terrain sections as one index list per page run
wgpu replays an indirect multi-draw on Metal as one draw call per entry, so every frame encoded a draw per visible face range and translucent section (9,300 at render distance 32). Where multi-draw is emulated (Metal) and a frame has at least 4,096 section draws, a compute pass now copies the frame's section draws into one index list, in draw order, and each run of sections in the same arena page is one draw call: 9,309 draw calls become about 750 at RD32. Smaller frames keep the per-section draws, where the list's GPU cost (about 0.4 ms on an M4 Pro at RD16) outweighs the CPU saved. The picture is unchanged by construction: the same triangles from the same vertices in the same order through the same shader code. Only where a vertex finds its section's origin changes, from the instance attribute to a table: a section's vertices fill whole 256-vertex blocks of its page, each block names the section, and the section's camera-relative origin is computed on the CPU exactly as before. Vulkan keeps the native multi-draw. HORIZON_FLAT_DRAWS=1 draws every frame flat (any backend that supports it), 0 never; the control command `section-draws flat|indirect` switches in a running game for A/B checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -173,6 +173,16 @@ impl Game<'_> {
|
||||
.chain(super::pad::HELP)
|
||||
.collect::<Vec<_>>() }))),
|
||||
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
|
||||
"section-draws" => {
|
||||
let r = self.renderer.as_mut().ok_or("no renderer")?;
|
||||
match words.get(1).copied() {
|
||||
None => {}
|
||||
Some("flat") => r.set_flat_draws(true)?,
|
||||
Some("indirect") => r.set_flat_draws(false)?,
|
||||
Some(other) => return Err(format!("unknown section draw mode {other}").into()),
|
||||
}
|
||||
Ok(Some(json!({ "ok": true, "flat": r.flat_draws() })))
|
||||
}
|
||||
"sculk" => Ok(Some(self.sculk_command(&words)?)),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"pad" => Ok(Some(self.pad_command(&words)?)),
|
||||
|
||||
@@ -11,6 +11,7 @@ pub const HELP: &[&str] = &[
|
||||
"fill X1 Y1 Z1 X2 Y2 Z2 STATE fill a box with a block state without updates",
|
||||
"particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)",
|
||||
"signedit X Y Z [front|back] open the sign editor for the sign at X Y Z",
|
||||
"section-draws [flat|indirect] how terrain sections are drawn (A/B checks); replies the mode",
|
||||
];
|
||||
|
||||
impl Game<'_> {
|
||||
|
||||
@@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]
|
||||
}
|
||||
|
||||
mod arena;
|
||||
mod flat;
|
||||
mod java_stages;
|
||||
mod occlusion;
|
||||
mod pack_stages;
|
||||
@@ -101,6 +102,8 @@ struct SectionGpu {
|
||||
faces: crate::mesher::FaceGroups,
|
||||
sort: translucency::SortState,
|
||||
sorted_indices: Option<(u32, u64)>,
|
||||
/// Its id for flat draws (`flat::Flat::add`), when they are on.
|
||||
flat_id: Option<u32>,
|
||||
}
|
||||
/// Line segments the hit outline can hold.
|
||||
const MAX_OUTLINE_EDGES: u64 = 256;
|
||||
@@ -251,6 +254,10 @@ pub struct Renderer {
|
||||
pub config: wgpu::SurfaceConfiguration,
|
||||
solid: wgpu::RenderPipeline,
|
||||
translucent: wgpu::RenderPipeline,
|
||||
/// Flat section draws (`flat`), where multi-draw is emulated.
|
||||
flat: Option<flat::Flat>,
|
||||
/// `flat` draws this frame's sections (off: the per-section draws).
|
||||
flat_on: bool,
|
||||
sky: wgpu::RenderPipeline,
|
||||
dark_disc: wgpu::RenderPipeline,
|
||||
lines: wgpu::RenderPipeline,
|
||||
@@ -781,18 +788,19 @@ impl Renderer {
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &debug_line_attributes,
|
||||
})];
|
||||
let pipeline = |label: &str,
|
||||
vertex: &str,
|
||||
fragment: &str,
|
||||
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
cull: Option<wgpu::Face>,
|
||||
depth_write: bool,
|
||||
depth_test: bool,
|
||||
blend: Option<wgpu::BlendState>| {
|
||||
let pipeline_in = |layout: &wgpu::PipelineLayout,
|
||||
label: &str,
|
||||
vertex: &str,
|
||||
fragment: &str,
|
||||
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
cull: Option<wgpu::Face>,
|
||||
depth_write: bool,
|
||||
depth_test: bool,
|
||||
blend: Option<wgpu::BlendState>| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(&layout),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some(vertex),
|
||||
@@ -833,6 +841,28 @@ impl Renderer {
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let pipeline = |label: &str,
|
||||
vertex: &str,
|
||||
fragment: &str,
|
||||
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
cull: Option<wgpu::Face>,
|
||||
depth_write: bool,
|
||||
depth_test: bool,
|
||||
blend: Option<wgpu::BlendState>| {
|
||||
pipeline_in(
|
||||
&layout,
|
||||
label,
|
||||
vertex,
|
||||
fragment,
|
||||
buffers,
|
||||
topology,
|
||||
cull,
|
||||
depth_write,
|
||||
depth_test,
|
||||
blend,
|
||||
)
|
||||
};
|
||||
let tri = wgpu::PrimitiveTopology::TriangleList;
|
||||
let solid = pipeline(
|
||||
"Terrain solid",
|
||||
@@ -1649,7 +1679,34 @@ impl Renderer {
|
||||
std::mem::size_of::<TerrainVertex>() as u64,
|
||||
1 << 20,
|
||||
);
|
||||
let sorted_indices = arena::Arena::indices(&device, 1 << 16);
|
||||
// Sections as one index list per frame where multi-draw is emulated.
|
||||
let flat = flat::wanted(&adapter, &device).then(|| {
|
||||
let buffers = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<TerrainVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &TERRAIN_ATTRIBUTES,
|
||||
})];
|
||||
flat::Flat::new(
|
||||
&device,
|
||||
&bindings,
|
||||
arena.page_vertices(),
|
||||
|layout, label, fragment, blend| {
|
||||
pipeline_in(
|
||||
layout,
|
||||
label,
|
||||
"vs_terrain_flat",
|
||||
fragment,
|
||||
&buffers,
|
||||
tri,
|
||||
Some(wgpu::Face::Back),
|
||||
true,
|
||||
true,
|
||||
blend,
|
||||
)
|
||||
},
|
||||
)
|
||||
});
|
||||
let sorted_indices = arena::Arena::indices(&device, 1 << 16, flat.is_some());
|
||||
let indirect = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Section draws"),
|
||||
size: 1024 * 20,
|
||||
@@ -1684,6 +1741,8 @@ impl Renderer {
|
||||
config,
|
||||
solid,
|
||||
translucent,
|
||||
flat_on: flat.is_some(),
|
||||
flat,
|
||||
sky,
|
||||
dark_disc,
|
||||
lines,
|
||||
@@ -1906,6 +1965,18 @@ impl Renderer {
|
||||
}
|
||||
self.depth = Self::depth(&self.device, &self.config);
|
||||
}
|
||||
/// Whether sections are drawn as one index list per frame (`flat`).
|
||||
pub fn flat_draws(&self) -> bool {
|
||||
self.flat_on
|
||||
}
|
||||
/// Switches between flat and per-section draws, for A/B checks.
|
||||
pub fn set_flat_draws(&mut self, on: bool) -> Result<()> {
|
||||
if on && self.flat.is_none() {
|
||||
return Err("flat section draws are off on this device".into());
|
||||
}
|
||||
self.flat_on = on;
|
||||
Ok(())
|
||||
}
|
||||
pub fn section_count(&self) -> usize {
|
||||
self.sections.len()
|
||||
}
|
||||
@@ -1947,6 +2018,10 @@ impl Renderer {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let flat_id = self
|
||||
.flat
|
||||
.as_mut()
|
||||
.map(|f| f.add(&self.device, &self.queue, page, start, vertices));
|
||||
let stride = std::mem::size_of::<TerrainVertex>() as u64;
|
||||
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
|
||||
if !part.is_empty() {
|
||||
@@ -1976,6 +2051,7 @@ impl Renderer {
|
||||
.collect(),
|
||||
),
|
||||
sorted_indices,
|
||||
flat_id,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -2006,6 +2082,9 @@ impl Renderer {
|
||||
}
|
||||
fn release_section(&mut self, key: SectionKey) {
|
||||
if let Some(s) = self.sections.remove(key) {
|
||||
if let (Some(flat), Some(id)) = (&mut self.flat, s.flat_id) {
|
||||
flat.remove(id);
|
||||
}
|
||||
if let Some((page, start)) = s.sorted_indices {
|
||||
self.sorted_indices
|
||||
.release(page, start, u64::from(s.translucent) * 6);
|
||||
@@ -2022,6 +2101,9 @@ impl Renderer {
|
||||
self.block_entities.clear();
|
||||
self.sections.clear();
|
||||
self.arena.clear();
|
||||
if let Some(flat) = &mut self.flat {
|
||||
flat.clear();
|
||||
}
|
||||
self.sorted_indices.clear();
|
||||
self.translucency_cursor = 0;
|
||||
self.occlusion.clear();
|
||||
@@ -2204,6 +2286,9 @@ impl Renderer {
|
||||
pub fn render(&mut self, frame: &Frame) -> Result<bool> {
|
||||
self.arena.trim();
|
||||
self.sorted_indices.trim();
|
||||
if let Some(flat) = &mut self.flat {
|
||||
flat.trim(|page| self.arena.has_page(page));
|
||||
}
|
||||
if self.suspended {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -2510,7 +2595,32 @@ impl Renderer {
|
||||
} else {
|
||||
self.draws.len()
|
||||
};
|
||||
if self.multi_draw && !self.draws.is_empty() {
|
||||
let flat_frame = match &mut self.flat {
|
||||
Some(flat)
|
||||
if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws =>
|
||||
{
|
||||
let sections = &self.sections;
|
||||
let sorted = &self.sorted_indices;
|
||||
crate::spans::time("flatten", || {
|
||||
flat.prepare(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
&mut self.uploads,
|
||||
&self.draws,
|
||||
&self.draw_pages,
|
||||
solid_draws as usize,
|
||||
visible
|
||||
.iter()
|
||||
.filter_map(|v| sections.get(v.slot).flat_id.map(|id| (id, v.origin))),
|
||||
|page| sorted.buffer(page).clone(),
|
||||
)
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if flat_frame {
|
||||
self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.calls.len());
|
||||
} else if self.multi_draw && !self.draws.is_empty() {
|
||||
if self.draws.len() as u64 > self.indirect_capacity {
|
||||
self.indirect_capacity = (self.draws.len() as u64).next_power_of_two();
|
||||
self.indirect = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
@@ -2745,10 +2855,22 @@ impl Renderer {
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
pass.set_pipeline(&self.solid);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, 0, solid_draws);
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.solid);
|
||||
flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
None => {
|
||||
pass.set_pipeline(&self.solid);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, 0, solid_draws);
|
||||
}
|
||||
}
|
||||
if entity_quads > 0 {
|
||||
pass.set_pipeline(&self.entity_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
@@ -2785,10 +2907,22 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
|
||||
pass.draw(0..4, debug_depth..debug_depth + debug_top);
|
||||
}
|
||||
pass.set_pipeline(&self.translucent);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, solid_draws, translucent_draws);
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.translucent);
|
||||
flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
None => {
|
||||
pass.set_pipeline(&self.translucent);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, solid_draws, translucent_draws);
|
||||
}
|
||||
}
|
||||
// LevelRenderer.executeClassicTransparency: translucent targets'
|
||||
// outlines follow terrain, so its blending cannot wash them out.
|
||||
if outline_edges > 0 && frame.outline_after_terrain {
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
//! a frame binds it once and draws every section with indirect multi-draw.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Ranges are rounded up to this many vertices to limit fragmentation.
|
||||
const GRAIN: u64 = 256;
|
||||
/// Ranges are rounded up to this many vertices to limit fragmentation, and
|
||||
/// start at multiples of it (`flat` names sections by these blocks).
|
||||
pub const GRAIN: u64 = 256;
|
||||
/// The largest page, in bytes.
|
||||
pub const PAGE_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// Free vertex ranges: start -> length, never adjacent.
|
||||
#[derive(Debug, PartialEq)]
|
||||
@@ -65,8 +68,14 @@ impl Arena {
|
||||
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
|
||||
Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX)
|
||||
}
|
||||
pub fn indices(device: &wgpu::Device, capacity: u64) -> Self {
|
||||
Self::with_usage(device, 4, capacity, wgpu::BufferUsages::INDEX)
|
||||
/// Sorted translucent indices; `storage` when compute passes read them.
|
||||
pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self {
|
||||
let usage = if storage {
|
||||
wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE
|
||||
} else {
|
||||
wgpu::BufferUsages::INDEX
|
||||
};
|
||||
Self::with_usage(device, 4, capacity, usage)
|
||||
}
|
||||
fn with_usage(
|
||||
device: &wgpu::Device,
|
||||
@@ -75,7 +84,7 @@ impl Arena {
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> Self {
|
||||
// 256 MiB pages, or less where the device's buffers are smaller.
|
||||
let bytes = device.limits().max_buffer_size.min(256 << 20);
|
||||
let bytes = device.limits().max_buffer_size.min(PAGE_BYTES);
|
||||
let page_limit = (bytes / stride) / GRAIN * GRAIN;
|
||||
let capacity = capacity.next_multiple_of(GRAIN).min(page_limit);
|
||||
Self {
|
||||
@@ -132,6 +141,13 @@ impl Arena {
|
||||
pub fn bytes(&self) -> u64 {
|
||||
self.pages.iter().flatten().map(|p| p.capacity).sum::<u64>() * self.stride
|
||||
}
|
||||
/// The most vertices a page holds.
|
||||
pub fn page_vertices(&self) -> u64 {
|
||||
self.page_limit
|
||||
}
|
||||
pub fn has_page(&self, page: u32) -> bool {
|
||||
self.pages.get(page as usize).is_some_and(Option::is_some)
|
||||
}
|
||||
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
|
||||
&self.pages[page as usize]
|
||||
.as_ref()
|
||||
@@ -338,7 +354,7 @@ mod tests {
|
||||
};
|
||||
for mut arena in [
|
||||
Arena::new(&device, 28, GRAIN),
|
||||
Arena::indices(&device, GRAIN),
|
||||
Arena::indices(&device, GRAIN, false),
|
||||
] {
|
||||
arena.alloc(&device, &queue, GRAIN).unwrap();
|
||||
assert_eq!(arena.bytes(), arena.stride * GRAIN);
|
||||
@@ -397,7 +413,7 @@ mod tests {
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut arena = Arena::indices(&device, GRAIN);
|
||||
let mut arena = Arena::indices(&device, GRAIN, false);
|
||||
let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap();
|
||||
queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes());
|
||||
arena.video_memory_full = true;
|
||||
@@ -422,7 +438,7 @@ mod tests {
|
||||
let Some((device, queue)) = device() else {
|
||||
return;
|
||||
};
|
||||
let mut arena = Arena::indices(&device, GRAIN);
|
||||
let mut arena = Arena::indices(&device, GRAIN, false);
|
||||
arena.alloc(&device, &queue, GRAIN).unwrap();
|
||||
arena.video_memory_full = true;
|
||||
// Without mappable primary buffers nothing can spill: the request
|
||||
|
||||
@@ -0,0 +1,658 @@
|
||||
//! Flat section draws: where indirect multi-draw is emulated, as on Metal
|
||||
//! (wgpu replays it as one draw call per indirect entry), the frame's section
|
||||
//! draws are copied by a compute pass into one index list, in draw order, and
|
||||
//! drawn with one draw call per run of sections in the same arena page.
|
||||
//!
|
||||
//! The picture is the one the per-section draws give: the same triangles
|
||||
//! from the same vertices in the same order, through the same vertex and
|
||||
//! fragment code. Only where a vertex finds its section's origin changes:
|
||||
//! from the instance attribute to a table. A section's vertices fill whole
|
||||
//! blocks of `GRAIN` vertices of its page (the arena rounds every range up),
|
||||
//! so each block names one section: its id here, which indexes the frame's
|
||||
//! camera-relative origins (computed on the CPU exactly as for the instance
|
||||
//! attribute).
|
||||
use super::arena::GRAIN;
|
||||
|
||||
/// One section draw for `flatten.wgsl`: index count, first sorted index (or
|
||||
/// `QUADS` for a solid draw), base vertex, first index in the list.
|
||||
type Range = [u32; 4];
|
||||
const QUADS: u32 = u32::MAX;
|
||||
const GROUP_LIMIT: u32 = 65535;
|
||||
|
||||
struct PageTable {
|
||||
/// Section id of every block of the page.
|
||||
blocks: wgpu::Buffer,
|
||||
group: Option<wgpu::BindGroup>,
|
||||
}
|
||||
|
||||
/// A run of the frame's index list drawn from one arena page.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Call {
|
||||
pub page: u32,
|
||||
pub first: u32,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
pub struct Flat {
|
||||
pub solid: wgpu::RenderPipeline,
|
||||
pub translucent: wgpu::RenderPipeline,
|
||||
flatten: wgpu::ComputePipeline,
|
||||
compute_layout: wgpu::BindGroupLayout,
|
||||
draw_layout: wgpu::BindGroupLayout,
|
||||
blocks_per_page: u64,
|
||||
pages: Vec<Option<PageTable>>,
|
||||
free_ids: Vec<u32>,
|
||||
next_id: u32,
|
||||
origins: wgpu::Buffer,
|
||||
origin_capacity: u64,
|
||||
origin_data: Vec<[f32; 4]>,
|
||||
/// The frame's index list.
|
||||
pub indices: wgpu::Buffer,
|
||||
index_capacity: u64,
|
||||
ranges: wgpu::Buffer,
|
||||
range_capacity: u64,
|
||||
range_data: Vec<Range>,
|
||||
/// Segments of `range_data` by index source: (sorted index page or
|
||||
/// `None` for solid draws, first range, ranges).
|
||||
segments: Vec<(Option<u32>, u64, u64)>,
|
||||
empty: wgpu::Buffer,
|
||||
/// This frame's draw calls: solid ones, then translucent ones.
|
||||
pub calls: Vec<Call>,
|
||||
pub solid_calls: usize,
|
||||
/// Frames with fewer section draws keep the per-section draws.
|
||||
pub min_draws: usize,
|
||||
range_align: u64,
|
||||
}
|
||||
|
||||
/// Section draws from which a frame is drawn flat. Below it the index list
|
||||
/// costs the GPU more than the draw calls cost the CPU: on an M4 Pro at
|
||||
/// render distance 16 (2,900 draws) the copy and the list add about 0.4 ms
|
||||
/// of GPU time for 0.5–0.8 ms less CPU time; at 32 (9,300 draws) the CPU
|
||||
/// saves 1.3 ms.
|
||||
const MIN_DRAWS: usize = 4096;
|
||||
|
||||
/// Whether flat draws apply: the backend emulates multi-draw, and vertex
|
||||
/// shaders can read storage buffers large enough for an index page.
|
||||
/// `HORIZON_FLAT_DRAWS=1` draws every frame flat, `0` none.
|
||||
pub fn wanted(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool {
|
||||
match std::env::var("HORIZON_FLAT_DRAWS").as_deref() {
|
||||
Ok("0") => return false,
|
||||
Ok("1") => return supported(adapter, device),
|
||||
_ => {}
|
||||
}
|
||||
adapter.get_info().backend == wgpu::Backend::Metal && supported(adapter, device)
|
||||
}
|
||||
|
||||
fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool {
|
||||
let flags = adapter.get_downlevel_capabilities().flags;
|
||||
let limits = device.limits();
|
||||
flags.contains(wgpu::DownlevelFlags::VERTEX_STORAGE | wgpu::DownlevelFlags::COMPUTE_SHADERS)
|
||||
&& limits.max_storage_buffers_per_shader_stage >= 3
|
||||
&& limits.max_storage_buffer_binding_size >= super::arena::PAGE_BYTES
|
||||
}
|
||||
|
||||
fn storage(binding: u32, stage: wgpu::ShaderStages, read_only: bool) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: stage,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer(
|
||||
device: &wgpu::Device,
|
||||
label: &str,
|
||||
size: u64,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(label),
|
||||
size: size.max(16),
|
||||
usage: usage | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Lays out the frame's index list: each draw's range (destinations in draw
|
||||
/// order) grouped by index source into `ranges`, every group padded to
|
||||
/// `align` entries for binding, with `segments` naming each group; and the
|
||||
/// draw calls, one per run of draws in the same vertex page, solid and
|
||||
/// translucent apart. Returns the first translucent call and the list's
|
||||
/// length.
|
||||
fn plan(
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
solid_draws: usize,
|
||||
align: u64,
|
||||
calls: &mut Vec<Call>,
|
||||
ranges: &mut Vec<Range>,
|
||||
segments: &mut Vec<(Option<u32>, u64, u64)>,
|
||||
) -> (usize, u64) {
|
||||
calls.clear();
|
||||
ranges.clear();
|
||||
segments.clear();
|
||||
let mut solid_calls = None;
|
||||
let mut total = 0u64;
|
||||
let mut by_source: Vec<(Option<u32>, Vec<Range>)> = Vec::new();
|
||||
for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() {
|
||||
let first = if sorted.is_some() { d[2] } else { QUADS };
|
||||
let range = [d[0], first, d[3], total as u32];
|
||||
match by_source.iter_mut().find(|(s, _)| *s == sorted) {
|
||||
Some((_, list)) => list.push(range),
|
||||
None => by_source.push((sorted, vec![range])),
|
||||
}
|
||||
if i == solid_draws {
|
||||
solid_calls = Some(calls.len());
|
||||
}
|
||||
match calls.last_mut() {
|
||||
Some(last) if last.page == page && i != solid_draws => last.count += d[0],
|
||||
_ => calls.push(Call {
|
||||
page,
|
||||
first: total as u32,
|
||||
count: d[0],
|
||||
}),
|
||||
}
|
||||
total += u64::from(d[0]);
|
||||
}
|
||||
for (source, list) in by_source {
|
||||
segments.push((source, ranges.len() as u64, list.len() as u64));
|
||||
ranges.extend(list);
|
||||
let padded = (ranges.len() as u64).next_multiple_of(align);
|
||||
ranges.resize(padded as usize, [0; 4]);
|
||||
}
|
||||
(solid_calls.unwrap_or(calls.len()), total)
|
||||
}
|
||||
|
||||
impl Flat {
|
||||
/// `pipeline(layout, label, vertex entry, fragment entry, blend)` builds a
|
||||
/// terrain pipeline as the per-section ones, without the origin buffer.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
terrain_layout: &wgpu::BindGroupLayout,
|
||||
page_vertices: u64,
|
||||
pipeline: impl Fn(
|
||||
&wgpu::PipelineLayout,
|
||||
&str,
|
||||
&str,
|
||||
Option<wgpu::BlendState>,
|
||||
) -> wgpu::RenderPipeline,
|
||||
) -> Self {
|
||||
let vertex = wgpu::ShaderStages::VERTEX;
|
||||
let compute = wgpu::ShaderStages::COMPUTE;
|
||||
let draw_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Flat section draws"),
|
||||
entries: &[storage(0, vertex, true), storage(1, vertex, true)],
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Flat terrain layout"),
|
||||
bind_group_layouts: &[Some(terrain_layout), Some(&draw_layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let compute_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
entries: &[
|
||||
storage(0, compute, true),
|
||||
storage(1, compute, true),
|
||||
storage(2, compute, false),
|
||||
],
|
||||
});
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
|
||||
});
|
||||
let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
layout: Some(
|
||||
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
bind_group_layouts: &[Some(&compute_layout)],
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
module: &module,
|
||||
entry_point: Some("flatten"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let storage_usage = wgpu::BufferUsages::STORAGE;
|
||||
Self {
|
||||
solid: pipeline(&layout, "Terrain solid (flat)", "fs_solid", None),
|
||||
translucent: pipeline(
|
||||
&layout,
|
||||
"Terrain translucent (flat)",
|
||||
"fs_translucent",
|
||||
Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
),
|
||||
flatten,
|
||||
compute_layout,
|
||||
draw_layout,
|
||||
blocks_per_page: page_vertices.div_ceil(GRAIN),
|
||||
pages: Vec::new(),
|
||||
free_ids: Vec::new(),
|
||||
next_id: 0,
|
||||
origins: buffer(device, "Section origins by id", 16, storage_usage),
|
||||
origin_capacity: 1,
|
||||
origin_data: Vec::new(),
|
||||
indices: buffer(
|
||||
device,
|
||||
"Flat section indices",
|
||||
16,
|
||||
wgpu::BufferUsages::INDEX | storage_usage,
|
||||
),
|
||||
index_capacity: 4,
|
||||
ranges: buffer(device, "Flat section ranges", 16, storage_usage),
|
||||
range_capacity: 1,
|
||||
range_data: Vec::new(),
|
||||
segments: Vec::new(),
|
||||
empty: buffer(device, "No sorted indices", 16, storage_usage),
|
||||
calls: Vec::new(),
|
||||
solid_calls: 0,
|
||||
min_draws: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") {
|
||||
0
|
||||
} else {
|
||||
MIN_DRAWS
|
||||
},
|
||||
range_align: (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16)
|
||||
.max(1),
|
||||
}
|
||||
}
|
||||
/// A section uploaded to `vertices` vertices from `start` of `page`: its
|
||||
/// id, which its blocks now name.
|
||||
pub fn add(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
page: u32,
|
||||
start: u64,
|
||||
vertices: u64,
|
||||
) -> u32 {
|
||||
let id = self.free_ids.pop().unwrap_or_else(|| {
|
||||
self.next_id += 1;
|
||||
self.next_id - 1
|
||||
});
|
||||
let page = page as usize;
|
||||
if self.pages.len() <= page {
|
||||
self.pages.resize_with(page + 1, || None);
|
||||
}
|
||||
let table = self.pages[page].get_or_insert_with(|| PageTable {
|
||||
blocks: buffer(
|
||||
device,
|
||||
"Section ids by block",
|
||||
self.blocks_per_page * 4,
|
||||
wgpu::BufferUsages::STORAGE,
|
||||
),
|
||||
group: None,
|
||||
});
|
||||
let first = start / GRAIN;
|
||||
let ids = vec![id; vertices.div_ceil(GRAIN) as usize];
|
||||
queue.write_buffer(&table.blocks, first * 4, bytemuck::cast_slice(&ids));
|
||||
id
|
||||
}
|
||||
pub fn remove(&mut self, id: u32) {
|
||||
self.free_ids.push(id);
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.pages.clear();
|
||||
self.free_ids.clear();
|
||||
self.next_id = 0;
|
||||
}
|
||||
/// Forgets the tables of pages the arena released.
|
||||
pub fn trim(&mut self, live: impl Fn(u32) -> bool) {
|
||||
for (i, page) in self.pages.iter_mut().enumerate() {
|
||||
if page.is_some() && !live(i as u32) {
|
||||
*page = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Builds the frame's index list from `draws` (`DrawIndexedIndirectArgs`:
|
||||
/// index count, instances, first index, base vertex, first instance),
|
||||
/// solid ones first, with their (vertex page, sorted index page) and
|
||||
/// the origins of the sections they draw by id. Records the copy into
|
||||
/// `encoder`; `calls` then lists the frame's draw calls. False when the
|
||||
/// frame cannot be drawn flat (the per-section draws then apply).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
uploads: &mut super::upload::Uploads,
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
solid_draws: usize,
|
||||
origins: impl Iterator<Item = (u32, [f32; 3])>,
|
||||
sorted_page: impl Fn(u32) -> wgpu::Buffer,
|
||||
) -> bool {
|
||||
// Origins by section id.
|
||||
self.origin_data.clear();
|
||||
for (id, o) in origins {
|
||||
let id = id as usize;
|
||||
if self.origin_data.len() <= id {
|
||||
self.origin_data.resize(id + 1, [0.0; 4]);
|
||||
}
|
||||
self.origin_data[id] = [o[0], o[1], o[2], 0.0];
|
||||
}
|
||||
if self.origin_data.len() as u64 > self.origin_capacity {
|
||||
self.origin_capacity = (self.origin_data.len() as u64).next_power_of_two();
|
||||
self.origins = buffer(
|
||||
device,
|
||||
"Section origins by id",
|
||||
self.origin_capacity * 16,
|
||||
wgpu::BufferUsages::STORAGE,
|
||||
);
|
||||
for page in self.pages.iter_mut().flatten() {
|
||||
page.group = None;
|
||||
}
|
||||
}
|
||||
if !self.origin_data.is_empty() {
|
||||
uploads.buffer(
|
||||
encoder,
|
||||
&self.origins,
|
||||
0,
|
||||
bytemuck::cast_slice(&self.origin_data),
|
||||
);
|
||||
}
|
||||
let (solid_calls, total) = plan(
|
||||
draws,
|
||||
pages,
|
||||
solid_draws,
|
||||
self.range_align,
|
||||
&mut self.calls,
|
||||
&mut self.range_data,
|
||||
&mut self.segments,
|
||||
);
|
||||
self.solid_calls = solid_calls;
|
||||
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
|
||||
self.calls.clear();
|
||||
self.solid_calls = 0;
|
||||
return false;
|
||||
}
|
||||
if self.range_data.len() as u64 > self.range_capacity {
|
||||
self.range_capacity = (self.range_data.len() as u64).next_power_of_two();
|
||||
self.ranges = buffer(
|
||||
device,
|
||||
"Flat section ranges",
|
||||
self.range_capacity * 16,
|
||||
wgpu::BufferUsages::STORAGE,
|
||||
);
|
||||
}
|
||||
if total > self.index_capacity {
|
||||
self.index_capacity = total.next_power_of_two();
|
||||
self.indices = buffer(
|
||||
device,
|
||||
"Flat section indices",
|
||||
self.index_capacity * 4,
|
||||
wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE,
|
||||
);
|
||||
}
|
||||
uploads.buffer(
|
||||
encoder,
|
||||
&self.ranges,
|
||||
0,
|
||||
bytemuck::cast_slice(&self.range_data),
|
||||
);
|
||||
let groups: Vec<(wgpu::BindGroup, u32)> = self
|
||||
.segments
|
||||
.iter()
|
||||
.map(|&(source, first, count)| {
|
||||
let sorted = source.map(&sorted_page);
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
layout: &self.compute_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &self.ranges,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
}),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sorted.as_ref().unwrap_or(&self.empty).as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.indices.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
(group, count as u32)
|
||||
})
|
||||
.collect();
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
pass.set_pipeline(&self.flatten);
|
||||
for (group, count) in &groups {
|
||||
pass.set_bind_group(0, group, &[]);
|
||||
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
|
||||
}
|
||||
drop(pass);
|
||||
for page in self.calls.iter().map(|c| c.page) {
|
||||
let table = self.pages[page as usize]
|
||||
.as_mut()
|
||||
.expect("a drawn page has its block table");
|
||||
if table.group.is_none() {
|
||||
table.group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Flat section draws"),
|
||||
layout: &self.draw_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: table.blocks.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.origins.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
}));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Draws `calls` with a flat pipeline set and `vertices` giving each
|
||||
/// page's vertex buffer.
|
||||
pub fn draw<'a>(
|
||||
&self,
|
||||
pass: &mut wgpu::RenderPass<'_>,
|
||||
calls: &[Call],
|
||||
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
|
||||
) {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for call in calls {
|
||||
let table = self.pages[call.page as usize]
|
||||
.as_ref()
|
||||
.and_then(|t| t.group.as_ref())
|
||||
.expect("prepared page");
|
||||
pass.set_vertex_buffer(0, vertices(call.page).slice(..));
|
||||
pass.set_bind_group(1, table, &[]);
|
||||
pass.draw_indexed(call.first..call.first + call.count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Draws as `render` writes them: solid (page, quads at a base vertex)
|
||||
/// first, then translucent (page, sorted page, count, first sorted index,
|
||||
/// base vertex).
|
||||
fn sample() -> (Vec<[u32; 5]>, Vec<(u32, Option<u32>)>, usize) {
|
||||
let draws = vec![
|
||||
[6 * 3, 1, 0, 0, 0],
|
||||
[6 * 2, 1, 0, 512, 1],
|
||||
[6, 1, 0, 256, 2],
|
||||
[6 * 4, 1, 0, 1024, 3],
|
||||
[6 * 2, 1, 6, 768, 1],
|
||||
[6, 1, 0, 40, 0],
|
||||
];
|
||||
let pages = vec![
|
||||
(0, None),
|
||||
(0, None),
|
||||
(1, None),
|
||||
(0, None),
|
||||
(0, Some(0)),
|
||||
(0, Some(1)),
|
||||
];
|
||||
(draws, pages, 4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_draws_runs_of_a_page_in_order() {
|
||||
let (draws, pages, solid) = sample();
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (solid_calls, total) = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
assert_eq!(total, 6 * 13);
|
||||
let call = |page, first, count| Call { page, first, count };
|
||||
// Pages 0, 0 | 1 | 0, then translucent 0, 0 (never merged with solid).
|
||||
assert_eq!(
|
||||
calls,
|
||||
[
|
||||
call(0, 0, 30),
|
||||
call(1, 30, 6),
|
||||
call(0, 36, 24),
|
||||
call(0, 60, 18)
|
||||
]
|
||||
);
|
||||
assert_eq!(solid_calls, 3);
|
||||
// Solid ranges, then each sorted page's, every group padded to 4.
|
||||
assert_eq!(segments, [(None, 0, 4), (Some(0), 4, 1), (Some(1), 8, 1)]);
|
||||
assert_eq!(ranges[3], [24, QUADS, 1024, 36]);
|
||||
assert_eq!(ranges[4], [12, 6, 768, 60]);
|
||||
assert_eq!(ranges[8], [6, 0, 40, 72]);
|
||||
assert_eq!(ranges.len(), 12);
|
||||
}
|
||||
|
||||
/// The compute pass writes exactly the indices the per-section draws
|
||||
/// read: quads 0 1 2 0 2 3 for solid draws, sorted indices otherwise,
|
||||
/// plus the base vertex.
|
||||
#[test]
|
||||
fn flatten_writes_the_indices_of_the_per_section_draws() {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
|
||||
eprintln!("no GPU adapter: skipped");
|
||||
return;
|
||||
};
|
||||
let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default()))
|
||||
else {
|
||||
eprintln!("no GPU device: skipped");
|
||||
return;
|
||||
};
|
||||
use wgpu::util::DeviceExt;
|
||||
let (draws, pages, solid) = sample();
|
||||
let align = (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16).max(1);
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (_, total) = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
align,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
let sorted: [Vec<u32>; 2] = [
|
||||
(0..32).map(|i| (i * 7) % 32).collect(),
|
||||
(0..8).rev().collect(),
|
||||
];
|
||||
let mut expected = Vec::new();
|
||||
for (d, (_, page)) in draws.iter().zip(&pages) {
|
||||
for k in 0..d[0] {
|
||||
let i = match page {
|
||||
None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize],
|
||||
Some(p) => sorted[*p as usize][(d[2] + k) as usize],
|
||||
};
|
||||
expected.push(d[3] + i);
|
||||
}
|
||||
}
|
||||
let storage = |entries: &[u32]| {
|
||||
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: None,
|
||||
contents: bytemuck::cast_slice(entries),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
})
|
||||
};
|
||||
let range_buffer = storage(bytemuck::cast_slice(&ranges));
|
||||
let sorted_buffers = [storage(&sorted[0]), storage(&sorted[1]), storage(&[0; 4])];
|
||||
let out = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: total * 4,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let read = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: total * 4,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: None,
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some("flatten"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&Default::default());
|
||||
pass.set_pipeline(&pipeline);
|
||||
for &(source, first, count) in &segments {
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &range_buffer,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
}),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sorted_buffers[source.map_or(2, |p| p as usize)]
|
||||
.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: out.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.dispatch_workgroups(count as u32, 1, 1);
|
||||
}
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(&out, 0, &read, 0, total * 4);
|
||||
queue.submit([encoder.finish()]);
|
||||
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let got: Vec<u32> =
|
||||
bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec();
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Flat section draws (gfx/flat.rs): copies each section draw's indices into
|
||||
// one index list, in draw order, offset by the draw's base vertex. Solid
|
||||
// draws index quads (0 1 2 0 2 3 per quad, as Renderer::quad_indices);
|
||||
// translucent ones read their sorted indices.
|
||||
struct Range {
|
||||
count: u32,
|
||||
// First sorted index, or QUADS for a solid draw.
|
||||
first: u32,
|
||||
base: u32,
|
||||
dst: u32,
|
||||
}
|
||||
const QUADS: u32 = 0xffffffffu;
|
||||
const GROUP: u32 = 64u;
|
||||
@group(0) @binding(0) var<storage, read> ranges: array<Range>;
|
||||
@group(0) @binding(1) var<storage, read> sorted: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> out: array<u32>;
|
||||
@compute @workgroup_size(64)
|
||||
fn flatten(@builtin(workgroup_id) group: vec3<u32>,
|
||||
@builtin(local_invocation_index) lane: u32) {
|
||||
let r = group.y * 65535u + group.x;
|
||||
if r >= arrayLength(&ranges) {
|
||||
return;
|
||||
}
|
||||
let d = ranges[r];
|
||||
for (var k = lane; k < d.count; k += GROUP) {
|
||||
var i: u32;
|
||||
if d.first == QUADS {
|
||||
let c = k % 6u;
|
||||
i = (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u);
|
||||
} else {
|
||||
i = sorted[d.first + k];
|
||||
}
|
||||
out[d.dst + k] = d.base + i;
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,24 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> {
|
||||
@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>,
|
||||
@location(5) origin: vec4<f32>) -> TerrainOut {
|
||||
let pos = position + origin.xyz;
|
||||
return terrain_vertex(position, uv, layer, color, light, origin.xyz);
|
||||
}
|
||||
// Flat section draws (gfx/flat.rs): one draw per arena page over the frame's
|
||||
// index list. A section's vertices fill whole 256-vertex blocks of its page:
|
||||
// the block gives its resident slot, the slot its camera-relative origin.
|
||||
@group(1) @binding(0) var<storage, read> block_slots: array<u32>;
|
||||
@group(1) @binding(1) var<storage, read> slot_origins: array<vec4<f32>>;
|
||||
@vertex fn vs_terrain_flat(
|
||||
@builtin(vertex_index) vertex: u32,
|
||||
@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>
|
||||
) -> TerrainOut {
|
||||
let origin = slot_origins[block_slots[vertex >> 8u]];
|
||||
return terrain_vertex(position, uv, layer, color, light, origin.xyz);
|
||||
}
|
||||
fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f32>,
|
||||
light: vec2<u32>, origin: vec3<f32>) -> TerrainOut {
|
||||
let pos = position + origin;
|
||||
var out: TerrainOut;
|
||||
out.clip = globals.view_proj * vec4(pos, 1.0);
|
||||
out.uv = uv;
|
||||
|
||||
Reference in New Issue
Block a user