Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions native/shared/src/renderer/geometry_arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,56 @@
use super::super::{material_indirection::GpuCompletionTracker, Vertex3D};
use super::GeometrySlice;

/// The depth-only twin of an arena vertex: what a pass that only writes depth
/// reads (position, and uv + vertex alpha for an alpha-tested cutout).
///
/// WHY A TWIN STREAM. `Vertex3D` is 96 bytes, and a depth pass that reads only
/// its position still pulls whole 96-byte vertices through the cache. On an
/// integrated GPU, whose vertex fetch shares system memory with everything
/// else, the forest's ~1.1M vertices cost ~4 ms per pass that draws them, and a
/// frame draws them into every shadow cascade and lamp shadow face as well as
/// the camera. This stream is a quarter of that, at the same vertex index:
/// vertex i of the arena is twin i here, so a draw's `base_vertex` and index
/// range are unchanged and only the bound buffer and pipeline differ.
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct DepthVertex {
pub(crate) position: [f32; 3],
pub(crate) uv: [f32; 2],
pub(crate) alpha: f32,
}

/// Bytes of the arena's `Vertex3D` stream per byte of its depth twin.
const DEPTH_RATIO: u64 =
(std::mem::size_of::<Vertex3D>() / std::mem::size_of::<DepthVertex>()) as u64;
const _: () = assert!(
std::mem::size_of::<Vertex3D>() % std::mem::size_of::<DepthVertex>() == 0,
"the depth twin must divide the vertex stride exactly",
);

impl DepthVertex {
pub(crate) fn desc() -> wgpu::VertexBufferLayout<'static> {
const ATTRS: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![
0 => Float32x3,
1 => Float32x2,
2 => Float32,
];
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<DepthVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &ATTRS,
}
}

fn of(v: &Vertex3D) -> Self {
Self {
position: v.position,
uv: v.uv,
alpha: v.color[3],
}
}
}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
struct FreeRange {
offset: u64,
Expand All @@ -19,6 +69,8 @@ struct RetiredGeometry {

pub(super) struct GeometryArena {
pub(super) vertex: wgpu::Buffer,
/// `vertex`'s depth-only twin (see `DepthVertex`), byte offset / DEPTH_RATIO.
pub(super) depth: wgpu::Buffer,
pub(super) index: wgpu::Buffer,
vertex_capacity: u64,
index_capacity: u64,
Expand Down Expand Up @@ -48,6 +100,7 @@ impl GeometryArena {
),
full_warned: false,
vertex: create_vertex_arena(device, Self::INITIAL_CAPACITY),
depth: create_depth_arena(device, Self::INITIAL_CAPACITY / DEPTH_RATIO),
index: create_index_arena(device, Self::INITIAL_CAPACITY),
vertex_capacity: Self::INITIAL_CAPACITY,
index_capacity: Self::INITIAL_CAPACITY,
Expand Down Expand Up @@ -120,6 +173,12 @@ impl GeometryArena {
);
if vertex_size > 0 {
queue.write_buffer(&self.vertex, vertex_offset, bytemuck::cast_slice(vertices));
let depth: Vec<DepthVertex> = vertices.iter().map(DepthVertex::of).collect();
queue.write_buffer(
&self.depth,
vertex_offset / DEPTH_RATIO,
bytemuck::cast_slice(&depth),
);
}
if index_size > 0 {
queue.write_buffer(&self.index, index_offset, bytemuck::cast_slice(indices));
Expand Down Expand Up @@ -199,10 +258,19 @@ impl GeometryArena {
});
if new_vertex_capacity != self.vertex_capacity {
let next = create_vertex_arena(device, new_vertex_capacity);
let next_depth = create_depth_arena(device, new_vertex_capacity / DEPTH_RATIO);
if copy_vertex_end > 0 {
encoder.copy_buffer_to_buffer(&self.vertex, 0, &next, 0, copy_vertex_end);
encoder.copy_buffer_to_buffer(
&self.depth,
0,
&next_depth,
0,
copy_vertex_end / DEPTH_RATIO,
);
}
self.vertex = next;
self.depth = next_depth;
self.vertex_capacity = new_vertex_capacity;
}
if new_index_capacity != self.index_capacity {
Expand Down Expand Up @@ -230,6 +298,17 @@ fn create_vertex_arena(device: &wgpu::Device, size: u64) -> wgpu::Buffer {
})
}

fn create_depth_arena(device: &wgpu::Device, size: u64) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("gpu_driven_shared_depth_vertices"),
size: size.max(4),
usage: wgpu::BufferUsages::VERTEX
| wgpu::BufferUsages::COPY_SRC
| wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}

fn create_index_arena(device: &wgpu::Device, size: u64) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("gpu_driven_shared_indices"),
Expand Down
9 changes: 9 additions & 0 deletions native/shared/src/renderer/gpu_driven.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use std::sync::OnceLock;
#[path = "geometry_arena.rs"]
mod geometry_arena;
use geometry_arena::GeometryArena;
pub(crate) use geometry_arena::DepthVertex;

pub const GPU_DRIVEN_FEATURES: wgpu::Features = wgpu::Features::INDIRECT_FIRST_INSTANCE;
pub(crate) const DRAW_FLAG_DOUBLE_SIDED: u32 = 1 << 0;
Expand Down Expand Up @@ -387,6 +388,14 @@ impl GpuDrivenRenderer {
(&self.arena.vertex, &self.arena.index)
}

/// The depth-only twin of a draw's vertex buffer, when it has one: a draw
/// from the shared arena reads `geometry_arena::DepthVertex` at the same
/// vertex index (same `base_vertex`, same index range). Anything else
/// (dedicated buffers, immediate batches) has no twin.
pub(crate) fn depth_twin(&self, vertex: &wgpu::Buffer) -> Option<&wgpu::Buffer> {
std::ptr::eq(vertex, &self.arena.vertex).then_some(&self.arena.depth)
}

pub fn upload_static(
&mut self,
device: &wgpu::Device,
Expand Down
14 changes: 12 additions & 2 deletions native/shared/src/renderer/local_light_shadows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,10 +522,15 @@ pub(crate) struct PassInputs<'a> {
pub queue: &'a wgpu::Queue,
pub nodes: &'a [ShadowDrawEntry],
pub vbs: &'a [&'a wgpu::Buffer],
/// Per `vbs` entry, its depth-only twin stream if it has one.
pub depth_vbs: &'a [Option<&'a wgpu::Buffer>],
pub ibs: &'a [&'a wgpu::Buffer],
pub cutout_bgs: &'a [&'a wgpu::BindGroup],
pub pipeline: &'a wgpu::RenderPipeline,
pub pipeline_cutout: &'a wgpu::RenderPipeline,
/// `pipeline` / `pipeline_cutout` reading the depth twin stream.
pub pipeline_compact: &'a wgpu::RenderPipeline,
pub pipeline_cutout_compact: &'a wgpu::RenderPipeline,
pub pipeline_skinned: &'a wgpu::RenderPipeline,
pub joint_bind_group: &'a wgpu::BindGroup,
pub camera_pos: [f32; 3],
Expand Down Expand Up @@ -890,21 +895,26 @@ impl LocalLightShadows {
} else {
0
};
// 3 / 4: kinds 0 / 1 drawn from the depth twin stream.
let twin = if kind == 2 { None } else { inputs.depth_vbs[entry.vb_idx] };
let kind = if twin.is_some() { kind + 3 } else { kind };
if kind != current_kind {
pass.set_pipeline(match kind {
1 => inputs.pipeline_cutout,
2 => inputs.pipeline_skinned,
3 => inputs.pipeline_compact,
4 => inputs.pipeline_cutout_compact,
_ => inputs.pipeline,
});
current_kind = kind;
}
pass.set_bind_group(0, &gpu.draw_bind_group, &[(base + slot * stride) as u32]);
if kind == 1 {
if kind == 1 || kind == 4 {
pass.set_bind_group(1, inputs.cutout_bgs[entry.cutout_idx as usize], &[]);
} else if kind == 2 {
pass.set_bind_group(1, inputs.joint_bind_group, &[]);
}
pass.set_vertex_buffer(0, inputs.vbs[entry.vb_idx].slice(..));
pass.set_vertex_buffer(0, twin.unwrap_or(inputs.vbs[entry.vb_idx]).slice(..));
pass.set_index_buffer(
inputs.ibs[entry.ib_idx].slice(..),
wgpu::IndexFormat::Uint32,
Expand Down
70 changes: 60 additions & 10 deletions native/shared/src/renderer/planar_pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,10 +336,23 @@ impl Renderer {
// camera half the time, that was most frames. A probe skipped this way
// is simply not sampled; the frame the surface comes back into view
// renders it before the main pass reads it.
let probe_seen = {
//
// The same walk finds WHERE on screen the probe is read. A surface reads
// its probe at its own screen position (plus a ripple offset), and a
// point on the mirror plane lands on the same screen position in the
// mirrored view as in the real one. So only the screen rectangle of the
// visible surface, grown by PROBE_READ_MARGIN_NDC, is ever sampled: the
// probe culls its draws to that part of the mirrored frustum and
// scissors to it. A river seen as a band across the bottom of the
// screen no longer redraws the whole mirrored forest above the band.
let full_rect = [-1.0_f32, 1.0, -1.0, 1.0];
let (probe_seen, probe_rect) = {
let main_planes = crate::scene::extract_frustum_planes(&self.current_vp_matrix);
let ms = &self.material_system;
let mut seen = vec![false; probe_count];
// None = nothing yet; Some(full_rect) once any draw is unbounded.
let mut rect: Vec<Option<[f32; 4]>> = vec![None; probe_count];
let crop = !self.dbg_skip("probe_crop");
for cmd in ms.commands.iter().chain(ms.translucent_commands.iter()) {
let link = (cmd.material as usize)
.checked_sub(1)
Expand All @@ -348,29 +361,57 @@ impl Renderer {
Some(p) if p >= 1 && (p as usize) <= probe_count => p as usize - 1,
_ => continue,
};
if seen[slot] {
if rect[slot] == Some(full_rect) {
continue;
}
// Instanced or unknown bounds: assume visible.
let visible = match (cmd.instance, self.model_gpu_cache.get(&cmd.mesh_handle)) {
// Instanced or unknown bounds: visible, anywhere on screen.
let on_screen = match (cmd.instance, self.model_gpu_cache.get(&cmd.mesh_handle)) {
(None, Some(Some(meshes))) if cmd.mesh_idx < meshes.len() => {
let m = &meshes[cmd.mesh_idx];
let (wmin, wmax) = transform_aabb(&cmd.model, m.local_min, m.local_max);
!(wmin[0] <= wmax[0]
&& crate::scene::aabb_outside_frustum(&main_planes, wmin, wmax))
if wmin[0] > wmax[0] {
Some(full_rect)
} else if crate::scene::aabb_outside_frustum(&main_planes, wmin, wmax) {
None
} else if !crop {
Some(full_rect)
} else {
// Bounds that pass the box test but whose faces all
// clip away still count: be generous, not exact.
Some(
planar_reflection::surface_screen_rect(
&self.current_vp_matrix,
&main_planes,
wmin,
wmax,
)
.map(|r| {
planar_reflection::grow_screen_rect(
r,
planar_reflection::PROBE_READ_MARGIN_NDC,
)
})
.unwrap_or(full_rect),
)
}
}
_ => true,
_ => Some(full_rect),
};
if visible {
if let Some(r) = on_screen {
seen[slot] = true;
rect[slot] = Some(match rect[slot] {
None => r,
Some(a) => [a[0].min(r[0]), a[1].max(r[1]), a[2].min(r[2]), a[3].max(r[3])],
});
}
}
seen
(seen, rect)
};
for i in 0..probe_count {
if !probe_seen[i] {
continue;
}
let read_rect = probe_rect[i].unwrap_or(full_rect);
let (
plane_y,
normal,
Expand Down Expand Up @@ -580,7 +621,13 @@ impl Renderer {
// append after the cached models in the same slot space —
// creation order decides who survives the cap, so games
// should create hero geometry before filler (grass).
let mirror_planes = crate::scene::extract_frustum_planes(&mirror_vp);
// Cropped to the screen rectangle the surface reads (see probe_rect).
// Horizontal planes only: surface_screen_rect bounds a surface by
// the top and bottom faces of its box, exact for a level surface.
let read_rect = if normal[1].abs() > 0.999 { read_rect } else { full_rect };
let mirror_planes = planar_reflection::cropped_frustum_planes(&mirror_vp, read_rect);
let (sc_x, sc_y, sc_w, sc_h) =
planar_reflection::screen_rect_scissor(read_rect, probe_res);
// Projected-size cull. The probe is small (512 px in the shooter) and
// the water shows it rippled, yet every draw the mirrored frustum can
// see used to be drawn at full detail: on an integrated GPU the forest
Expand Down Expand Up @@ -743,6 +790,8 @@ impl Renderer {
occlusion_query_set: None,
multiview_mask: None,
});
// Outside the read rectangle the clear stays: nothing samples it.
pass.set_scissor_rect(sc_x, sc_y, sc_w, sc_h);
mat_sys.dispatch_with_view(
&mut pass,
view_bg,
Expand Down Expand Up @@ -812,6 +861,7 @@ impl Renderer {
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_scissor_rect(sc_x, sc_y, sc_w, sc_h);
if let (Some(rp), Some(rmbg), Some(rlbg)) =
(refl_pipeline, refl_model_bg, refl_light_bg)
{
Expand Down
Loading