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
18 changes: 12 additions & 6 deletions native/shared/src/renderer/material_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -628,12 +628,18 @@ impl MaterialSystem {
layout: &layouts.per_view,
entries: &per_view_entries,
});
// The stub_depth texture and cmp_sampler outlive the bind group via
// wgpu internal Arc; we don't need to hold them in the struct.
std::mem::forget(stub_depth);
std::mem::forget(stub_depth_view);
std::mem::forget(stub_depth_array_view);
std::mem::forget(cmp_sampler);
// The stub depth texture, its views and cmp_sampler stay alive for as
// long as the bind group does (wgpu holds its own references), so the
// handles are simply dropped here. They used to be `mem::forget`-ed:
// a forgotten handle never releases its reference, and every handle
// holds the device, so no renderer's device (and none of the memory
// heaps it had allocated, ~580 MB on a Radeon 760M) was ever freed.
// A process that built renderers in turn (the golden suite) ran out
// of memory after about 30.
drop(stub_depth);
drop(stub_depth_view);
drop(stub_depth_array_view);
drop(cmp_sampler);

// Default MaterialFactors UBO.
let default_mf = MaterialFactorsUniforms::default();
Expand Down
72 changes: 72 additions & 0 deletions native/shared/src/renderer/planar_pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,10 +329,52 @@ impl Renderer {
// Iterate probes by index — we mutate `material_system`'s
// commands view while iterating, so collect the work first.
let probe_count = self.planar_probes.len();
// Render a probe only on frames where something that samples it is in
// view. A probe redraws the scene mirrored (5 ms of a 27 ms fight frame
// on a Radeon 760M, almost all of it vertex work), and a reflection
// nobody sees is pure cost: in an arena whose river is behind the
// 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 = {
let main_planes = crate::scene::extract_frustum_planes(&self.current_vp_matrix);
let ms = &self.material_system;
let mut seen = vec![false; probe_count];
for cmd in ms.commands.iter().chain(ms.translucent_commands.iter()) {
let link = (cmd.material as usize)
.checked_sub(1)
.and_then(|m| ms.material_reflection_probe.get(m).copied().flatten());
let slot = match link {
Some(p) if p >= 1 && (p as usize) <= probe_count => p as usize - 1,
_ => continue,
};
if seen[slot] {
continue;
}
// Instanced or unknown bounds: assume visible.
let visible = 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))
}
_ => true,
};
if visible {
seen[slot] = true;
}
}
seen
};
for i in 0..probe_count {
if !probe_seen[i] {
continue;
}
let (
plane_y,
normal,
probe_res,
color_view,
depth_view,
aux_material_view,
Expand All @@ -342,6 +384,7 @@ impl Renderer {
Some(p) => (
p.plane_y,
p.normal,
p.resolution,
p.color_view.clone(),
p.depth_view.clone(),
p.aux_material_view.clone(),
Expand Down Expand Up @@ -538,6 +581,29 @@ impl Renderer {
// 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);
// 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
// in the reflection cost 5 ms of a 28 ms frame. A draw whose bounding
// sphere covers less than PROBE_MIN_PX probe pixels, seen from the
// mirrored eye, cannot show; skip it. (Vertical extent; proj[1][1] is
// cot(fov_y / 2) in both matrix conventions.)
const PROBE_MIN_PX: f32 = 3.0;
let px_per_unit_at_1m = proj[1][1] * probe_res as f32 * 0.5;
let too_small = |wmin: [f32; 3], wmax: [f32; 3]| -> bool {
if wmin[0] > wmax[0] {
return false; // no bounds: keep it
}
let c = [
(wmin[0] + wmax[0]) * 0.5 - mirror_cam[0],
(wmin[1] + wmax[1]) * 0.5 - mirror_cam[1],
(wmin[2] + wmax[2]) * 0.5 - mirror_cam[2],
];
let e = [wmax[0] - wmin[0], wmax[1] - wmin[1], wmax[2] - wmin[2]];
let r = 0.5 * (e[0] * e[0] + e[1] * e[1] + e[2] * e[2]).sqrt();
let d = (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]).sqrt();
d > r && 2.0 * r / d * px_per_unit_at_1m < PROBE_MIN_PX
};
let mut reflect_draws: Vec<(u64, usize, u32)> = Vec::new();
let mut node_slots: Vec<(usize, u32)> = Vec::new();
if let Some(model_buf) = &self.reflect_model_buf {
Expand Down Expand Up @@ -573,6 +639,9 @@ impl Renderer {
{
continue;
}
if too_small(wmin, wmax) {
continue;
}
let mirror_mvp = mat4_multiply(mirror_vp, cmd.model);
let base = staged.len();
staged.resize(base + stride, 0);
Expand All @@ -590,6 +659,9 @@ impl Renderer {
{
continue;
}
if too_small(*wmin, *wmax) {
continue;
}
let mirror_mvp = mat4_multiply(mirror_vp, *model);
let base = staged.len();
staged.resize(base + stride, 0);
Expand Down
6 changes: 4 additions & 2 deletions native/shared/src/renderer/quality_preset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ impl Renderer {
}

fn rebuild_render_targets(&mut self) {
let (w, h) = (self.native_width, self.native_height);
let (w, h) = self.native_size();
let (lw, lh) = (self.logical_width, self.logical_height);
if w > 0 && h > 0 {
self.resize(w, h, lw, lh);
Expand All @@ -246,7 +246,9 @@ impl Renderer {
self.taa_frame_index = 0;
self.taa_history_valid = false;
self.taa_history_written = false;
let (w, h) = (self.native_width, self.native_height);
// native_size(): before the platform's first resize native_width is 0,
// and resize(0, 0) would configure a 1 x 1 surface.
let (w, h) = self.native_size();
self.resize(w, h, self.logical_width, self.logical_height);
}
}
Expand Down
6 changes: 5 additions & 1 deletion native/shared/src/renderer/shaders/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -927,7 +927,11 @@ fn fs_main(in: VsOut) -> TaaOut {
let history_in_bounds =
prev_uv.x >= 0.0 && prev_uv.x <= 1.0 &&
prev_uv.y >= 0.0 && prev_uv.y <= 1.0;
if (history_in_bounds) {
// A current weight of 1 means there is no history to use (a reset, a camera
// cut, the first frames). Do not read it at all: its stale confidence used
// to feed the reconstruction-detail term below, so the frame after a cut
// still carried the previous camera's image at one 8-bit level.
if (history_in_bounds && current_weight < 0.999) {
var h_sample = sample_history_reprojected(prev_uv, camera_moving, object_moving);
if (native_camera_motion_px > 0.05) {
h_sample = sample_history_catmull_rom(prev_uv);
Expand Down
3 changes: 2 additions & 1 deletion native/shared/tests/golden_render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,8 @@ fn capture_realtime_diagnostics(eng: &mut EngineState, final_rgba: &[u8]) {
}
fn try_engine() -> Option<EngineState> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
// WGPU_BACKEND=vulkan|dx12|metal|gl narrows the pick (Windows has two views of one GPU).
backends: wgpu::Backends::from_env().unwrap_or(wgpu::Backends::all()),
..wgpu::InstanceDescriptor::new_without_display_handle()
});
let adapter =
Expand Down
7 changes: 6 additions & 1 deletion native/shared/tests/golden_render/lighting_upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,13 @@ fn static_ultra_scene_has_stable_renderer_owned_memory_for_1000_frames() {
run_frames(&mut eng, POOL_WARMUP_FRAMES);
wait_for_gpu(&eng.renderer.device);
let before = live_gpu_objects(&eng.renderer.device);
// wgpu-hal 29's Vulkan backend never counts a created texture (only
// add_raw_texture does) yet subtracts on every destroy, so `textures` reads
// negative there (-76 on a Radeon 760M, the default pick on Windows).
// Texture memory and views are counted both ways on every backend and still
// catch a leaked texture in the growth check below.
assert!(
before.buffers > 0 && before.textures > 0,
before.buffers > 0 && (before.textures > 0 || before.texture_memory > 0),
"wgpu test counters are disabled; this would be a vacuous memory gate: {before:?}"
);
let paths_before: serde_json::Value =
Expand Down
72 changes: 72 additions & 0 deletions native/shared/tests/render_targets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,3 +247,75 @@ fn deferred_frame_writes_render_target_override() {
px
);
}

/// The output scale applies once, to the window's size. Changing the render
/// scale (dynamic resolution does it all the time) or the temporal upscaler
/// rebuilds from the window, never from the already scaled surface: that once
/// applied the output scale again per change, and a 4K window at 0.75 ended at
/// 1215 x 683 after four render-scale steps.
#[test]
fn output_scale_does_not_compound_through_render_scale_changes() {
let Some(mut r) = try_renderer() else {
eprintln!("no GPU adapter — skipping");
return;
};
r.set_output_scale(0.5);
assert_eq!((r.physical_width(), r.physical_height()), (128, 128));
for s in [0.75, 0.5, 1.0, 0.6, 0.85] {
r.set_render_scale(s);
assert_eq!(
(r.physical_width(), r.physical_height()),
(128, 128),
"surface shrank after set_render_scale({s})"
);
assert_eq!(r.render_target_extent(), r.render_extent());
}
r.set_temporal_upscale(false);
r.set_temporal_upscale(true);
assert_eq!((r.physical_width(), r.physical_height()), (128, 128));
r.set_output_scale(1.0);
assert_eq!((r.physical_width(), r.physical_height()), (256, 256));
}

/// Dropping a renderer releases every GPU object it made. The material system
/// once `mem::forget`-ed a stub depth texture, two views and a sampler; each
/// handle holds the device, so no renderer's device or memory heaps were ever
/// freed (about 580 MB per renderer on a Radeon 760M, and the golden suite ran
/// out of memory after ~30 renderers).
#[test]
fn dropping_a_renderer_releases_its_textures() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::from_env().unwrap_or(wgpu::Backends::all()),
..wgpu::InstanceDescriptor::new_without_display_handle()
});
let Ok(adapter) =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
else {
eprintln!("no GPU adapter — skipping");
return;
};
if adapter.get_info().device_type == wgpu::DeviceType::Cpu {
eprintln!("software adapter — skipping");
return;
}
let Ok((device, queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_limits: adapter.limits(),
..Default::default()
})) else {
return;
};
let keep = device.clone();
let mut r = Renderer::new_headless(device, queue, 256, 256);
r.begin_frame();
r.end_frame();
let live = keep.get_internal_counters().hal;
assert!(live.texture_memory.read() > 0, "wgpu counters are off: the check would be vacuous");
drop(r);
let _ = keep.poll(wgpu::PollType::wait_indefinitely());
let after = keep.get_internal_counters().hal;
assert_eq!(
(after.texture_memory.read(), after.texture_views.read()),
(0, 0),
"textures outlived their renderer"
);
}
Loading