diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index be842c3c6..ce47eb659 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -107,6 +107,12 @@ struct SectionGpu { } /// Line segments the hit outline can hold. const MAX_OUTLINE_EDGES: u64 = 256; +/// Staging buffer size for section meshes: a frame of uploads while +/// exploring fits in a few. +const SECTION_UPLOAD_CHUNK: u64 = 4 << 20; +/// Section copies are submitted early past this many staged bytes, which +/// bounds the staging memory frames that are not drawn can hold. +const SECTION_COPY_LIMIT: u64 = 64 << 20; pub struct Frame<'a> { pub camera: DVec3, pub yaw: f32, @@ -319,6 +325,13 @@ pub struct Renderer { lightmap_sampler: wgpu::Sampler, animations: AnimatedSprites, uploads: upload::Uploads, + /// Section meshes are staged through their own belt into + /// `section_copies`, which the next submission runs ahead of the frame: + /// `Queue::write_buffer` would make a staging buffer per write. + section_uploads: upload::Uploads, + section_copies: Option, + /// Bytes staged in `section_copies`. + section_copy_bytes: u64, /// Whether `lightmap` holds `lightmap_pixels` yet. lightmap_uploaded: bool, sprite_minimum_size: u32, @@ -1726,6 +1739,7 @@ impl Renderer { .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); let uploads = upload::Uploads::new(&device); + let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK); let panorama = panorama::Panorama::new( &device, &queue, @@ -1800,6 +1814,9 @@ impl Renderer { lightmap_sampler, animations: AnimatedSprites::new(animations, sprite_size, sprite_mips), uploads, + section_uploads, + section_copies: None, + section_copy_bytes: 0, lightmap_uploaded: false, sprite_minimum_size, indices, @@ -2004,14 +2021,20 @@ impl Renderer { self.indices = Self::quad_indices(&self.device, self.index_quads); } let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64; + let encoder = self.section_copies.get_or_insert_with(|| { + self.device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Section uploads"), + }) + }); // With video and system memory both full, the section is not drawn. - let Some((page, start)) = self.arena.alloc(&self.device, &self.queue, vertices) else { + let Some((page, start)) = self.arena.alloc(&self.device, encoder, vertices) else { return; }; let sorted_indices = if translucent > 0 { let indices = self.sorted_indices - .alloc(&self.device, &self.queue, u64::from(translucent) * 6); + .alloc(&self.device, encoder, u64::from(translucent) * 6); if indices.is_none() { self.arena.release(page, start, vertices); return; @@ -2020,22 +2043,35 @@ impl Renderer { } else { None }; - let flat_id = self - .flat - .as_mut() - .map(|f| f.add(&self.device, &self.queue, page, start, vertices)); + let flat_id = self.flat.as_mut().map(|f| { + f.add( + &self.device, + encoder, + &mut self.section_uploads, + page, + start, + vertices, + ) + }); let stride = std::mem::size_of::() as u64; for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] { if !part.is_empty() { let bytes: &[u8] = bytemuck::cast_slice(part); self.uploaded_bytes += bytes.len() as u64; - self.queue.write_buffer( + self.section_copy_bytes += bytes.len() as u64; + self.section_uploads.buffer( + encoder, self.arena.buffer(page), (start + offset as u64) * stride, bytes, ); } } + if self.section_copy_bytes >= SECTION_COPY_LIMIT + && let Some(copies) = self.take_section_copies() + { + self.queue.submit([copies]); + } self.sections.insert( key, SectionGpu { @@ -2057,6 +2093,13 @@ impl Renderer { }, ); } + /// The section copies recorded since the last submission, closed. + fn take_section_copies(&mut self) -> Option { + let encoder = self.section_copies.take()?; + self.section_copy_bytes = 0; + self.section_uploads.finish(&encoder); + Some(encoder.finish()) + } /// Draws `count` section draws from `first` with the arena and section /// origins bound: one indirect multi-draw, or a loop without it. /// Consecutive draws in one arena page share a vertex buffer binding, @@ -2286,6 +2329,14 @@ impl Renderer { ); } pub fn render(&mut self, frame: &Frame) -> Result { + let rendered = self.draw_frame(frame); + // A frame that was not drawn still submits the section copies. + if let Some(copies) = self.take_section_copies() { + self.queue.submit([copies]); + } + rendered + } + fn draw_frame(&mut self, frame: &Frame) -> Result { self.arena.trim(); self.sorted_indices.trim(); if let Some(flat) = &mut self.flat { @@ -3159,7 +3210,11 @@ impl Renderer { .map(|path| (path, self.copy_frame(&mut encoder, &target_texture))); self.uploads.finish(&encoder); let commands = crate::spans::time("encode", || encoder.finish()); - let submission = crate::spans::time("submit", || self.queue.submit([commands])); + // The section copies run first: this frame draws what they write. + let copies = self.take_section_copies(); + let submission = crate::spans::time("submit", || { + self.queue.submit(copies.into_iter().chain([commands])) + }); if let Some(timer) = &mut self.gpu_timer { timer.submitted(); timer.collect(&self.device, &mut self.gpu_times); diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 74d3b98e9..8da835aa2 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -155,12 +155,14 @@ impl Arena { .buffer } /// A range of `vertices`: (page, first vertex). Grows the newest page - /// (copying its contents on the GPU) or starts a new one when nothing - /// free is large enough; `None` when no memory is left for it. + /// (copying its contents on the GPU, in `encoder`) or starts a new one + /// when nothing free is large enough; `None` when no memory is left for + /// it. Writes to the arena belong in `encoder` too, so that those + /// recorded before a grow reach the grown page. pub fn alloc( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, vertices: u64, ) -> Option<(u32, u64)> { let len = Self::span(vertices).min(self.page_limit); @@ -178,7 +180,7 @@ impl Arena { let current = page.capacity; let grown = (current * 2).max(current + len).min(self.page_limit); if (grown - current >= len || grown == self.page_limit) - && self.grow(device, queue, last, grown) + && self.grow(device, encoder, last, grown) && let Some(start) = self.pages[last].as_mut().unwrap().free.take(len) { return Some((last as u32, start)); @@ -228,7 +230,7 @@ impl Arena { fn grow( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, page: usize, capacity: u64, ) -> bool { @@ -237,12 +239,8 @@ impl Arena { return false; }; let old = self.pages[page].as_mut().expect("live arena page"); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("Grow section arena"), - }); + // Copies recorded for the old buffer run before this one. encoder.copy_buffer_to_buffer(&old.buffer, 0, &buffer, 0, old.capacity * self.stride); - // Writes queued for the old buffer run before this copy. - queue.submit([encoder.finish()]); let previous = old.capacity; old.buffer = buffer; old.capacity = capacity; @@ -304,6 +302,50 @@ mod tests { .ok() } + /// `Arena::alloc`, with the copies of a grow submitted at once. + fn alloc( + arena: &mut Arena, + device: &wgpu::Device, + queue: &wgpu::Queue, + vertices: u64, + ) -> Option<(u32, u64)> { + let mut encoder = device.create_command_encoder(&Default::default()); + let range = arena.alloc(device, &mut encoder, vertices); + queue.submit([encoder.finish()]); + range + } + + #[test] + fn writes_recorded_before_a_grow_reach_the_grown_page() { + let Some((device, queue)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let mut arena = Arena::indices(&device, GRAIN, false); + let mut uploads = super::super::upload::Uploads::new(&device); + let mut encoder = device.create_command_encoder(&Default::default()); + let (page, start) = arena.alloc(&device, &mut encoder, GRAIN).unwrap(); + uploads.buffer( + &mut encoder, + arena.buffer(page), + start * 4, + &7u32.to_le_bytes(), + ); + // The page is full: the next range grows it, in the same encoder. + let (grown, next) = arena.alloc(&device, &mut encoder, GRAIN).unwrap(); + assert_eq!(grown, page); + uploads.buffer( + &mut encoder, + arena.buffer(grown), + next * 4, + &9u32.to_le_bytes(), + ); + uploads.finish(&encoder); + queue.submit([encoder.finish()]); + assert_eq!(read(&device, &queue, arena.buffer(page), start * 4), 7); + assert_eq!(read(&device, &queue, arena.buffer(page), next * 4), 9); + } + #[test] fn empty_pages_are_reclaimed_without_moving_live_ranges() { let Some((device, queue)) = device() else { @@ -313,9 +355,9 @@ mod tests { let mut arena = Arena::new(&device, 4, GRAIN); arena.page_limit = 2 * GRAIN; assert_eq!(arena.bytes(), 0); - let (first, a) = arena.alloc(&device, &queue, GRAIN).unwrap(); - let (_, b) = arena.alloc(&device, &queue, GRAIN).unwrap(); - let (live, c) = arena.alloc(&device, &queue, 2 * GRAIN).unwrap(); + let (first, a) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); + let (_, b) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); + let (live, c) = alloc(&mut arena, &device, &queue, 2 * GRAIN).unwrap(); let buffer = arena.buffer(live).clone(); let data = [1u8, 2, 3, 4]; queue.write_buffer(&buffer, c * 4, &data); @@ -327,7 +369,7 @@ mod tests { arena.trim(); assert_eq!(arena.bytes(), 2 * GRAIN * 4); assert_eq!(arena.buffer(live), &buffer); - let (reused, d) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (reused, d) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); assert_eq!(reused, first); let (tx, rx) = std::sync::mpsc::channel(); @@ -356,11 +398,11 @@ mod tests { Arena::new(&device, 28, GRAIN), Arena::indices(&device, GRAIN, false), ] { - arena.alloc(&device, &queue, GRAIN).unwrap(); + alloc(&mut arena, &device, &queue, GRAIN).unwrap(); assert_eq!(arena.bytes(), arena.stride * GRAIN); arena.clear(); assert_eq!(arena.bytes(), 0); - assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0))); + assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), Some((0, 0))); assert_eq!(arena.bytes(), arena.stride * GRAIN); } } @@ -414,12 +456,12 @@ mod tests { return; } let mut arena = Arena::indices(&device, GRAIN, false); - let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (page, start) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes()); arena.video_memory_full = true; // The full page can't grow in video memory: it moves to system // memory with its contents, and new ranges come from there. - let (grown, next) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (grown, next) = alloc(&mut arena, &device, &queue, GRAIN).unwrap(); assert!(arena.spilled); assert_eq!(grown, page); assert!( @@ -439,13 +481,13 @@ mod tests { return; }; let mut arena = Arena::indices(&device, GRAIN, false); - arena.alloc(&device, &queue, GRAIN).unwrap(); + alloc(&mut arena, &device, &queue, GRAIN).unwrap(); arena.video_memory_full = true; // Without mappable primary buffers nothing can spill: the request // fails, and the arena keeps what it has. - assert_eq!(arena.alloc(&device, &queue, GRAIN), None); + assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), None); assert_eq!(arena.bytes(), GRAIN * 4); arena.release(0, 0, GRAIN); - assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0))); + assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), Some((0, 0))); } } diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index b867a42c2..ff58e3ca6 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -262,11 +262,12 @@ impl Flat { } } /// A section uploaded to `vertices` vertices from `start` of `page`: its - /// id, which its blocks now name. + /// id, which its blocks now name (written through `uploads` in `encoder`). pub fn add( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + uploads: &mut super::upload::Uploads, page: u32, start: u64, vertices: u64, @@ -290,7 +291,12 @@ impl Flat { }); 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)); + uploads.buffer( + encoder, + &table.blocks, + first * 4, + bytemuck::cast_slice(&ids), + ); id } pub fn remove(&mut self, id: u32) { diff --git a/crates/horizon-client/src/gfx/upload.rs b/crates/horizon-client/src/gfx/upload.rs index d42958862..a60791d4c 100644 --- a/crates/horizon-client/src/gfx/upload.rs +++ b/crates/horizon-client/src/gfx/upload.rs @@ -14,8 +14,13 @@ pub struct Uploads { impl Uploads { pub fn new(device: &wgpu::Device) -> Self { + Self::with_chunk(device, CHUNK) + } + /// A belt whose staging buffers hold `chunk` bytes (larger writes get + /// a buffer of their own). + pub fn with_chunk(device: &wgpu::Device, chunk: u64) -> Self { Self { - belt: wgpu::util::StagingBelt::new(device.clone(), CHUNK), + belt: wgpu::util::StagingBelt::new(device.clone(), chunk), } } /// Copy tightly packed RGBA8 `pixels` (`width` by `height`) into one mip