Merge pull request #1238 from rdbtCVS/t3/cache-lightning-bolt-geometry
🤖 Agent: merged after verify passed and the contributor integration on the desktop (v5: workspace tests 1887/0, naga 0 failures, parity --changed 304/0). Rendering checked with before/after scenes: the screenshots match, and per-frame CPU and GPU time goes down.
This commit is contained in:
@@ -109,6 +109,13 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>) -> Out {
|
||||
return entity_vertex(position, uv, overlay, color, light, normal);
|
||||
}
|
||||
// Retained bolt-local geometry, translated using the same f64 camera
|
||||
// subtraction as the former CPU path before adding each local f32 position.
|
||||
@vertex fn vs_lightning(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>, @location(5) normal: vec4<f32>,
|
||||
@location(6) offset: vec3<f32>) -> Out {
|
||||
return entity_vertex(offset + position, uv, overlay, color, light, normal);
|
||||
}
|
||||
struct CloudInfo {
|
||||
offset: vec4<f32>,
|
||||
colors: array<vec4<f32>, 4>,
|
||||
|
||||
@@ -9796,15 +9796,17 @@ impl Game<'_> {
|
||||
self.entity_geometry(camera, alpha, entities)
|
||||
});
|
||||
}
|
||||
let bolts = if title {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.bolt_instances()
|
||||
};
|
||||
let mut additive = Vec::new();
|
||||
if !title {
|
||||
self.bolt_geometry(camera, &mut additive);
|
||||
if self.dim == Dim::End {
|
||||
let mut dragon = Vec::new();
|
||||
self.dragon_geometry(camera, alpha, &mut dragon, &mut additive);
|
||||
self.dragon_fireball_geometry(camera, alpha, &mut dragon);
|
||||
entities.extend(dragon);
|
||||
}
|
||||
if !title && self.dim == Dim::End {
|
||||
let mut dragon = Vec::new();
|
||||
self.dragon_geometry(camera, alpha, &mut dragon, &mut additive);
|
||||
self.dragon_fireball_geometry(camera, alpha, &mut dragon);
|
||||
entities.extend(dragon);
|
||||
}
|
||||
// A Java pack's `clouds` replaces the cloud option (`renderClouds`:
|
||||
// "false", "fast", "true"), as Iris overrides `getCloudsType`.
|
||||
@@ -9916,6 +9918,13 @@ impl Game<'_> {
|
||||
}),
|
||||
entities: &entities,
|
||||
dynamic_lights: &self.dynamic_lights,
|
||||
lightning: horizon_client::gfx::lightning::Input {
|
||||
bolts: &bolts,
|
||||
uv: [
|
||||
self.gui.atlas.font.white().u0,
|
||||
self.gui.atlas.font.white().v0,
|
||||
],
|
||||
},
|
||||
additive: &additive,
|
||||
see_through: &see_through,
|
||||
celestial: if self.settings.horizon.sky || title {
|
||||
@@ -12394,6 +12403,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
|
||||
entities: &[],
|
||||
dynamic_lights: &[],
|
||||
clouds: None,
|
||||
lightning: Default::default(),
|
||||
additive: &[],
|
||||
see_through: &[],
|
||||
celestial: &[],
|
||||
|
||||
@@ -5,14 +5,8 @@
|
||||
//! witches, mooshroom colours, turtles, burnt items), lightning rods, the sky
|
||||
//! flash, the sounds and the branching additive bolt.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
mesher::Vertex,
|
||||
mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species},
|
||||
};
|
||||
use horizon_core::{
|
||||
position::BlockPos,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_client::mobs::{Damage, DamageKind, MobEvent, SpawnSetup, Species};
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
|
||||
pub(super) struct Bolt {
|
||||
at: [f64; 3],
|
||||
@@ -349,71 +343,14 @@ impl Game<'_> {
|
||||
|| e.stack.item.contains("netherite")
|
||||
});
|
||||
}
|
||||
/// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
|
||||
/// segments of 16 blocks, from the bolt's seed.
|
||||
pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
|
||||
let white = self.gui.atlas.font.white();
|
||||
let uv = [white.u0, white.v0];
|
||||
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
|
||||
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
|
||||
for b in &self.bolts {
|
||||
let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
|
||||
let mut random = LegacyRandom::new(b.seed);
|
||||
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
|
||||
let (mut x_off, mut z_off) = (0f32, 0f32);
|
||||
for i in (0..8).rev() {
|
||||
xs[i] = x_off;
|
||||
zs[i] = z_off;
|
||||
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
|
||||
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
|
||||
}
|
||||
for layer in 0..4 {
|
||||
let mut random = LegacyRandom::new(b.seed);
|
||||
for branch in 0..3 {
|
||||
let trunk = branch == 0;
|
||||
let start = 7 - branch;
|
||||
let end = if trunk { 0 } else { start - 3 + 1 };
|
||||
let mut sx = xs[start] - x_off;
|
||||
let mut sz = zs[start] - z_off;
|
||||
for segment in (end..=start).rev() {
|
||||
let (ex, ez) = (sx, sz);
|
||||
let spread = if trunk { 11 } else { 31 };
|
||||
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
|
||||
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
|
||||
let mut top = 0.1 + layer as f32 * 0.2;
|
||||
let mut bottom = top;
|
||||
if trunk {
|
||||
top *= segment as f32 * 0.1 + 1.0;
|
||||
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
|
||||
}
|
||||
for (rx, rz, lx, lz) in [
|
||||
(false, false, true, false),
|
||||
(true, false, true, true),
|
||||
(true, true, false, true),
|
||||
(false, true, false, false),
|
||||
] {
|
||||
let s = |p: bool, r: f32| if p { r } else { -r };
|
||||
let y0 = segment as f32 * 16.0;
|
||||
let corners = [
|
||||
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
|
||||
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
|
||||
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
|
||||
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
|
||||
];
|
||||
for c in corners {
|
||||
out.push(Vertex {
|
||||
normal: [0; 4],
|
||||
pos: (o + glam::Vec3::from_array(c)).to_array(),
|
||||
uv,
|
||||
layer: 2,
|
||||
color,
|
||||
light: 240 | 240 << 8,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Simulation-order render inputs; seeded geometry lives in the renderer.
|
||||
pub(super) fn bolt_instances(&self) -> Vec<horizon_client::gfx::lightning::Bolt> {
|
||||
self.bolts
|
||||
.iter()
|
||||
.map(|b| horizon_client::gfx::lightning::Bolt {
|
||||
at: b.at,
|
||||
seed: b.seed,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ mod arena;
|
||||
mod cull;
|
||||
mod flat;
|
||||
mod java_stages;
|
||||
pub mod lightning;
|
||||
mod lod;
|
||||
mod occlusion;
|
||||
mod pack_stages;
|
||||
@@ -193,7 +194,9 @@ pub struct Frame<'a> {
|
||||
pub dynamic_lights: &'a [[f32; 4]],
|
||||
/// Cloud mesh inputs; geometry and GPU storage are retained by the renderer.
|
||||
pub clouds: Option<crate::clouds::Input<'a>>,
|
||||
/// Additive translucent geometry after the entities (lightning, dragon rays).
|
||||
/// Retained lightning bolts, drawn before the other additive entities.
|
||||
pub lightning: lightning::Input<'a>,
|
||||
/// Additive translucent geometry after lightning (dragon rays).
|
||||
pub additive: &'a [Vertex],
|
||||
/// Name tags over everything, without depth (`TEXT_SEE_THROUGH`).
|
||||
pub see_through: &'a [Vertex],
|
||||
@@ -334,6 +337,8 @@ pub struct Renderer {
|
||||
cloud_uniform: wgpu::Buffer,
|
||||
cloud_group: wgpu::BindGroup,
|
||||
additive_pipeline: wgpu::RenderPipeline,
|
||||
lightning_pipeline: wgpu::RenderPipeline,
|
||||
lightning: lightning::Renderer,
|
||||
see_through_pipeline: wgpu::RenderPipeline,
|
||||
celestial_pipeline: wgpu::RenderPipeline,
|
||||
celestial_buffer: wgpu::Buffer,
|
||||
@@ -1664,8 +1669,17 @@ impl Renderer {
|
||||
alpha_blend,
|
||||
false,
|
||||
);
|
||||
let lightning_attributes = wgpu::vertex_attr_array![6=>Float32x3];
|
||||
let lightning_vertex = [
|
||||
entity_vertex[0].clone(),
|
||||
Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<[f32; 3]>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &lightning_attributes,
|
||||
}),
|
||||
];
|
||||
// BlendFunction.LIGHTNING: src alpha, one; no depth writes.
|
||||
let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
let additive_descriptor = wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Additive entities"),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
@@ -1709,6 +1723,16 @@ impl Renderer {
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
};
|
||||
let additive_pipeline = device.create_render_pipeline(&additive_descriptor);
|
||||
let lightning_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Lightning"),
|
||||
vertex: wgpu::VertexState {
|
||||
entry_point: Some("vs_lightning"),
|
||||
buffers: &lightning_vertex,
|
||||
..additive_descriptor.vertex.clone()
|
||||
},
|
||||
..additive_descriptor
|
||||
});
|
||||
let celestial_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Celestial bodies"),
|
||||
@@ -2110,6 +2134,8 @@ impl Renderer {
|
||||
cloud_uniform,
|
||||
cloud_group,
|
||||
additive_pipeline,
|
||||
lightning_pipeline,
|
||||
lightning: lightning::Renderer::new(),
|
||||
see_through_pipeline,
|
||||
celestial_pipeline,
|
||||
celestial_buffer,
|
||||
@@ -3279,6 +3305,13 @@ impl Renderer {
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.lightning.prepare(
|
||||
&self.device,
|
||||
&mut self.uploads,
|
||||
&mut encoder,
|
||||
&frame.lightning,
|
||||
camera,
|
||||
);
|
||||
let all_entities = &self.entity_batch.combined;
|
||||
let hand_quads = (frame.hand.len() / 4) as u32;
|
||||
let additive_quads = (frame.additive.len() / 4) as u32;
|
||||
@@ -3318,8 +3351,13 @@ impl Renderer {
|
||||
bytemuck::cast_slice(&frame.celestial[..celestial_vertices]),
|
||||
);
|
||||
}
|
||||
let max_quads =
|
||||
(world_quads + additive_quads + hand_quads + see_through_quads).max(cloud_quads);
|
||||
let max_quads = (world_quads + additive_quads + hand_quads + see_through_quads)
|
||||
.max(cloud_quads)
|
||||
.max(if frame.lightning.bolts.is_empty() {
|
||||
0
|
||||
} else {
|
||||
lightning::QUADS
|
||||
});
|
||||
if max_quads > self.index_quads {
|
||||
self.index_quads = max_quads.next_power_of_two();
|
||||
self.indices = Self::quad_indices(&self.device, self.index_quads);
|
||||
@@ -3622,6 +3660,12 @@ impl Renderer {
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if !frame.lightning.bolts.is_empty() {
|
||||
pass.set_pipeline(&self.lightning_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
self.lightning.draw(&mut pass, &frame.lightning);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if additive_quads > 0 {
|
||||
pass.set_pipeline(&self.additive_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Seeded, bolt-local lightning meshes retained until their last active bolt disappears.
|
||||
use crate::{gfx::upload::Uploads, mesher::Vertex};
|
||||
use glam::DVec3;
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use std::collections::HashMap;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// A bolt's render state. Simulation lifetime and flashes stay in the game.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Bolt {
|
||||
pub at: [f64; 3],
|
||||
pub seed: i64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Input<'a> {
|
||||
pub bolts: &'a [Bolt],
|
||||
/// Current atlas white texel; a changed rect invalidates retained vertices.
|
||||
pub uv: [f32; 2],
|
||||
}
|
||||
|
||||
// Four layers, fourteen segments (eight trunk, two branches of three), four quads.
|
||||
pub(super) const QUADS: u32 = 4 * 14 * 4;
|
||||
|
||||
/// `LightningBoltRenderer.submit`: keep random draws, layers and quad order unchanged.
|
||||
fn geometry(seed: i64, uv: [f32; 2]) -> Vec<Vertex> {
|
||||
let mut out = Vec::with_capacity(QUADS as usize * 4);
|
||||
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
|
||||
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
|
||||
let mut random = LegacyRandom::new(seed);
|
||||
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
|
||||
let (mut x_off, mut z_off) = (0f32, 0f32);
|
||||
for i in (0..8).rev() {
|
||||
xs[i] = x_off;
|
||||
zs[i] = z_off;
|
||||
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
|
||||
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
|
||||
}
|
||||
for layer in 0..4 {
|
||||
let mut random = LegacyRandom::new(seed);
|
||||
for branch in 0..3 {
|
||||
let trunk = branch == 0;
|
||||
let start = 7 - branch;
|
||||
let end = if trunk { 0 } else { start - 3 + 1 };
|
||||
let mut sx = xs[start] - x_off;
|
||||
let mut sz = zs[start] - z_off;
|
||||
for segment in (end..=start).rev() {
|
||||
let (ex, ez) = (sx, sz);
|
||||
let spread = if trunk { 11 } else { 31 };
|
||||
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
|
||||
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
|
||||
let mut top = 0.1 + layer as f32 * 0.2;
|
||||
let mut bottom = top;
|
||||
if trunk {
|
||||
top *= segment as f32 * 0.1 + 1.0;
|
||||
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
|
||||
}
|
||||
for (rx, rz, lx, lz) in [
|
||||
(false, false, true, false),
|
||||
(true, false, true, true),
|
||||
(true, true, false, true),
|
||||
(false, true, false, false),
|
||||
] {
|
||||
let s = |p: bool, r: f32| if p { r } else { -r };
|
||||
let y0 = segment as f32 * 16.0;
|
||||
let corners = [
|
||||
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
|
||||
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
|
||||
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
|
||||
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
|
||||
];
|
||||
for c in corners {
|
||||
out.push(Vertex {
|
||||
normal: [0; 4],
|
||||
pos: c,
|
||||
uv,
|
||||
layer: 2,
|
||||
color,
|
||||
light: 240 | 240 << 8,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
struct Cached<T> {
|
||||
mesh: T,
|
||||
used: bool,
|
||||
}
|
||||
|
||||
/// Shared seeds use the same mesh; storage is bounded by active unique seeds,
|
||||
/// including after seed changes, removals, dimension switches and disconnects.
|
||||
struct Cache<T> {
|
||||
uv: Option<[f32; 2]>,
|
||||
meshes: HashMap<i64, Cached<T>>,
|
||||
}
|
||||
impl<T> Cache<T> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
uv: None,
|
||||
meshes: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare(&mut self, input: &Input<'_>, mut build: impl FnMut(i64, [f32; 2]) -> T) {
|
||||
if self.uv != Some(input.uv) {
|
||||
self.meshes.clear();
|
||||
self.uv = Some(input.uv);
|
||||
}
|
||||
for cached in self.meshes.values_mut() {
|
||||
cached.used = false;
|
||||
}
|
||||
for bolt in input.bolts {
|
||||
self.meshes
|
||||
.entry(bolt.seed)
|
||||
.or_insert_with(|| Cached {
|
||||
mesh: build(bolt.seed, input.uv),
|
||||
used: true,
|
||||
})
|
||||
.used = true;
|
||||
}
|
||||
self.meshes.retain(|_, cached| cached.used);
|
||||
// HashMap::retain keeps its allocation. Release historical peak capacity
|
||||
// as well as meshes once the storm (or connection) is gone.
|
||||
if self.meshes.is_empty() {
|
||||
self.meshes = HashMap::new();
|
||||
} else if self.meshes.capacity() > self.meshes.len() * 4 {
|
||||
self.meshes.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn offset(bolt: &Bolt, camera: DVec3) -> [f32; 3] {
|
||||
(DVec3::from_array(bolt.at) - camera).as_vec3().to_array()
|
||||
}
|
||||
|
||||
pub(super) struct Renderer {
|
||||
cache: Cache<wgpu::Buffer>,
|
||||
instances: Option<wgpu::Buffer>,
|
||||
capacity: usize,
|
||||
}
|
||||
impl Renderer {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
cache: Cache::new(),
|
||||
instances: None,
|
||||
capacity: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
uploads: &mut Uploads,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
input: &Input<'_>,
|
||||
camera: DVec3,
|
||||
) {
|
||||
self.cache.prepare(input, |seed, uv| {
|
||||
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Lightning vertices"),
|
||||
contents: bytemuck::cast_slice(&geometry(seed, uv)),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
})
|
||||
});
|
||||
if input.bolts.is_empty() {
|
||||
self.instances = None;
|
||||
self.capacity = 0;
|
||||
return;
|
||||
}
|
||||
if input.bolts.len() > self.capacity || input.bolts.len() < self.capacity / 4 {
|
||||
self.capacity = input.bolts.len().next_power_of_two();
|
||||
self.instances = Some(device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Lightning offsets"),
|
||||
size: (self.capacity * std::mem::size_of::<[f32; 3]>()) as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
}));
|
||||
}
|
||||
let offsets: Vec<_> = input
|
||||
.bolts
|
||||
.iter()
|
||||
.map(|bolt| offset(bolt, camera))
|
||||
.collect();
|
||||
uploads.buffer(
|
||||
encoder,
|
||||
self.instances.as_ref().unwrap(),
|
||||
0,
|
||||
bytemuck::cast_slice(&offsets),
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, input: &Input<'_>) {
|
||||
let Some(instances) = &self.instances else {
|
||||
return;
|
||||
};
|
||||
pass.set_vertex_buffer(1, instances.slice(..));
|
||||
// Follow simulation order, including repeated seeds; HashMap order must
|
||||
// never change additive accumulation or the order before dragon rays.
|
||||
for (i, bolt) in input.bolts.iter().enumerate() {
|
||||
pass.set_vertex_buffer(0, self.cache.meshes[&bolt.seed].mesh.slice(..));
|
||||
pass.draw_indexed(0..QUADS * 6, 0, i as u32..i as u32 + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,495 @@
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
// Frozen pre-cache generator: compare every Vertex byte, including primitive
|
||||
// order and the original camera-relative rounding, without game resources.
|
||||
fn reference(seed: i64, at: [f64; 3], camera: DVec3, uv: [f32; 2]) -> Vec<Vertex> {
|
||||
let mut out = Vec::new();
|
||||
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
|
||||
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
|
||||
let b = Bolt { seed, at };
|
||||
{
|
||||
let o = (glam::DVec3::from_array(b.at) - camera).as_vec3();
|
||||
let mut random = LegacyRandom::new(b.seed);
|
||||
let (mut xs, mut zs) = ([0f32; 8], [0f32; 8]);
|
||||
let (mut x_off, mut z_off) = (0f32, 0f32);
|
||||
for i in (0..8).rev() {
|
||||
xs[i] = x_off;
|
||||
zs[i] = z_off;
|
||||
x_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
|
||||
z_off += (random.next_int_bound(11).unwrap_or(5) - 5) as f32;
|
||||
}
|
||||
for layer in 0..4 {
|
||||
let mut random = LegacyRandom::new(b.seed);
|
||||
for branch in 0..3 {
|
||||
let trunk = branch == 0;
|
||||
let start = 7 - branch;
|
||||
let end = if trunk { 0 } else { start - 3 + 1 };
|
||||
let mut sx = xs[start] - x_off;
|
||||
let mut sz = zs[start] - z_off;
|
||||
for segment in (end..=start).rev() {
|
||||
let (ex, ez) = (sx, sz);
|
||||
let spread = if trunk { 11 } else { 31 };
|
||||
sx += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
|
||||
sz += (random.next_int_bound(spread).unwrap_or(0) - spread / 2) as f32;
|
||||
let mut top = 0.1 + layer as f32 * 0.2;
|
||||
let mut bottom = top;
|
||||
if trunk {
|
||||
top *= segment as f32 * 0.1 + 1.0;
|
||||
bottom *= (segment as f32 - 1.0) * 0.1 + 1.0;
|
||||
}
|
||||
for (rx, rz, lx, lz) in [
|
||||
(false, false, true, false),
|
||||
(true, false, true, true),
|
||||
(true, true, false, true),
|
||||
(false, true, false, false),
|
||||
] {
|
||||
let s = |p: bool, r: f32| if p { r } else { -r };
|
||||
let y0 = segment as f32 * 16.0;
|
||||
let corners = [
|
||||
[sx + s(rx, bottom), y0, sz + s(rz, bottom)],
|
||||
[ex + s(rx, top), y0 + 16.0, ez + s(rz, top)],
|
||||
[ex + s(lx, top), y0 + 16.0, ez + s(lz, top)],
|
||||
[sx + s(lx, bottom), y0, sz + s(lz, bottom)],
|
||||
];
|
||||
for c in corners {
|
||||
out.push(Vertex {
|
||||
normal: [0; 4],
|
||||
pos: (o + glam::Vec3::from_array(c)).to_array(),
|
||||
uv,
|
||||
layer: 2,
|
||||
color,
|
||||
light: 240 | 240 << 8,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn seeds() -> Vec<i64> {
|
||||
let mut seeds = vec![0, 1, -1, i64::MIN, i64::MAX, 0x123456789abcdef];
|
||||
let mut random = LegacyRandom::new(42);
|
||||
seeds.extend((0..256).map(|_| random.next_long()));
|
||||
seeds
|
||||
}
|
||||
|
||||
/// Pinned 26.3 LightningBoltRenderer.lambda$submit$0, captured with an
|
||||
/// identity PoseStack and a VertexConsumer recording big-endian xyz floats.
|
||||
#[test]
|
||||
fn geometry_matches_pinned_vanilla_vertex_digest() {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut digest = Sha256::new();
|
||||
for seed in seeds() {
|
||||
for vertex in geometry(seed, [0.0; 2]) {
|
||||
for value in vertex.pos {
|
||||
digest.update(value.to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
format!("{:x}", digest.finalize()),
|
||||
"a9ed25caa50b9aa340faa4bb417b3d533b061f0dce66514e4bb212931444dee6"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_geometry_matches_original_generator() {
|
||||
let uv = [0.8125, 0.03125];
|
||||
for seed in seeds() {
|
||||
let local = geometry(seed, uv);
|
||||
assert_eq!(local.len(), QUADS as usize * 4);
|
||||
for (at, camera) in [
|
||||
([0.0; 3], DVec3::ZERO),
|
||||
([12.5, 64.0, -12.5], DVec3::new(-4.25, 71.125, 32.5)),
|
||||
(
|
||||
[29_999_999.5, -64.0, -29_999_999.5],
|
||||
DVec3::new(29_999_987.125, 67.75, -29_999_983.875),
|
||||
),
|
||||
] {
|
||||
let offset = offset(&Bolt { seed, at }, camera);
|
||||
let translated: Vec<_> = local
|
||||
.iter()
|
||||
.map(|v| Vertex {
|
||||
pos: (glam::Vec3::from_array(offset) + glam::Vec3::from_array(v.pos))
|
||||
.to_array(),
|
||||
..*v
|
||||
})
|
||||
.collect();
|
||||
let expected = reference(seed, at, camera, uv);
|
||||
assert_eq!(
|
||||
bytemuck::cast_slice::<_, u8>(&translated),
|
||||
bytemuck::cast_slice::<_, u8>(&expected),
|
||||
"seed {seed}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_tracks_seed_lifecycle_movement_and_atlas_reload() {
|
||||
let mut cache = Cache::new();
|
||||
let builds = Cell::new(0);
|
||||
let build = |seed, uv| {
|
||||
builds.set(builds.get() + 1);
|
||||
geometry(seed, uv)
|
||||
};
|
||||
let mut bolts = [
|
||||
Bolt {
|
||||
seed: 123,
|
||||
at: [0.0; 3],
|
||||
},
|
||||
Bolt {
|
||||
seed: 456,
|
||||
at: [1.0; 3],
|
||||
},
|
||||
];
|
||||
fn input(bolts: &[Bolt]) -> Input<'_> {
|
||||
Input {
|
||||
bolts,
|
||||
uv: [0.25, 0.5],
|
||||
}
|
||||
}
|
||||
cache.prepare(&input(&bolts), build);
|
||||
assert_eq!(builds.get(), 2);
|
||||
assert_eq!(cache.meshes.len(), 2);
|
||||
// Any number of rendered frames or multiplayer position updates reuse meshes.
|
||||
for i in 0..100 {
|
||||
bolts[0].at = [i as f64; 3];
|
||||
cache.prepare(&input(&bolts), build);
|
||||
}
|
||||
assert_eq!(builds.get(), 2);
|
||||
// A flash changes the seed; retire its previous mesh immediately.
|
||||
bolts[0].seed = 789;
|
||||
cache.prepare(&input(&bolts), build);
|
||||
assert_eq!(builds.get(), 3);
|
||||
assert!(!cache.meshes.contains_key(&123));
|
||||
// Removal retains other bolts, and repeated seeds still share geometry.
|
||||
bolts[0].seed = 456;
|
||||
cache.prepare(&input(&bolts), build);
|
||||
assert_eq!(builds.get(), 3);
|
||||
assert_eq!(cache.meshes.len(), 1);
|
||||
// Atlas replacement must update white texel UVs without changing the seed.
|
||||
cache.prepare(
|
||||
&Input {
|
||||
bolts: &bolts,
|
||||
uv: [0.75, 0.25],
|
||||
},
|
||||
build,
|
||||
);
|
||||
assert_eq!(builds.get(), 4);
|
||||
assert_eq!(cache.meshes[&456].mesh[0].uv, [0.75, 0.25]);
|
||||
// Disconnect/dimension switch/expiry drops every retained resource.
|
||||
cache.prepare(&Input::default(), build);
|
||||
assert!(cache.meshes.is_empty());
|
||||
assert_eq!(cache.meshes.capacity(), 0);
|
||||
cache.prepare(&input(&bolts), build);
|
||||
assert_eq!(builds.get(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_flash_sequence_keeps_only_active_seeds() {
|
||||
let mut cache = Cache::new();
|
||||
for seed in 0..10_000 {
|
||||
cache.prepare(
|
||||
&Input {
|
||||
bolts: &[Bolt { seed, at: [0.0; 3] }],
|
||||
uv: [0.0; 2],
|
||||
},
|
||||
|seed, _| seed,
|
||||
);
|
||||
assert_eq!(cache.meshes.len(), 1);
|
||||
assert_eq!(cache.meshes[&seed].mesh, seed);
|
||||
assert!(cache.meshes.capacity() < 16);
|
||||
}
|
||||
}
|
||||
|
||||
/// Exercise the actual entity shader and retained draw path offscreen. Run
|
||||
/// explicitly, separately from other headless device tests (some GPU drivers
|
||||
/// fail during concurrent device teardown). Machines without an adapter skip it.
|
||||
#[test]
|
||||
#[ignore = "requires GPU; run separately with --ignored --exact"]
|
||||
fn retained_gpu_draw_matches_transient_additive_draw() {
|
||||
use bytemuck::Zeroable;
|
||||
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;
|
||||
};
|
||||
eprintln!("lightning differential GPU: {}", adapter.get_info().name);
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).unwrap();
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Lightning differential shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(crate::gfx::entity_shader().into()),
|
||||
});
|
||||
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Unorm8x4,4=>Uint8x4,5=>Snorm8x4];
|
||||
let offsets = wgpu::vertex_attr_array![6=>Float32x3];
|
||||
let vertices = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &attributes,
|
||||
})];
|
||||
let retained_vertices = [
|
||||
vertices[0].clone(),
|
||||
Some(wgpu::VertexBufferLayout {
|
||||
array_stride: 12,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &offsets,
|
||||
}),
|
||||
];
|
||||
let pipelines: Vec<_> = [false, true]
|
||||
.into_iter()
|
||||
.map(|retained| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Lightning differential pipeline"),
|
||||
layout: None,
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some(if retained {
|
||||
"vs_lightning"
|
||||
} else {
|
||||
"vs_entity"
|
||||
}),
|
||||
compilation_options: Default::default(),
|
||||
buffers: if retained {
|
||||
&retained_vertices
|
||||
} else {
|
||||
&vertices
|
||||
},
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_celestial"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
blend: Some(wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::SrcAlpha,
|
||||
dst_factor: wgpu::BlendFactor::One,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::SrcAlpha,
|
||||
dst_factor: wgpu::BlendFactor::One,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
}),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let globals = crate::gfx::Globals {
|
||||
view_proj: (glam::Mat4::orthographic_rh(-100.0, 100.0, -10.0, 150.0, 0.1, 400.0)
|
||||
* glam::Mat4::look_at_rh(
|
||||
glam::Vec3::new(80.0, 30.0, 160.0),
|
||||
glam::Vec3::new(0.0, 60.0, 0.0),
|
||||
glam::Vec3::Y,
|
||||
))
|
||||
.to_cols_array_2d(),
|
||||
..crate::gfx::Globals::zeroed()
|
||||
};
|
||||
let globals = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: None,
|
||||
contents: bytemuck::bytes_of(&globals),
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
let size = wgpu::Extent3d {
|
||||
width: 256,
|
||||
height: 256,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = |format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let white = device
|
||||
.create_texture_with_data(
|
||||
&queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
&[255; 4],
|
||||
)
|
||||
.create_view(&Default::default());
|
||||
let sampler = device.create_sampler(&Default::default());
|
||||
let groups: Vec<_> = pipelines
|
||||
.iter()
|
||||
.map(|pipeline| {
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: globals.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&white),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::TextureView(&white),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut renderer = Renderer::new();
|
||||
let mut uploads = Uploads::new(&device);
|
||||
let mut bolts = [Bolt {
|
||||
seed: 123,
|
||||
at: [29_999_999.5, 64.0, -29_999_999.5],
|
||||
}; 3];
|
||||
bolts[1].seed = -456;
|
||||
bolts[1].at[0] -= 32.0;
|
||||
bolts[2].at[2] += 20.0;
|
||||
let indices = crate::gfx::Renderer::quad_indices(&device, QUADS * 3);
|
||||
for frame in 0..4 {
|
||||
let camera = DVec3::new(29_999_997.125 + frame as f64, 62.75, -29_999_998.875);
|
||||
if frame == 2 {
|
||||
bolts[0].seed = 789;
|
||||
}
|
||||
let input = Input {
|
||||
bolts: &bolts[..if frame == 3 { 1 } else { 3 }],
|
||||
uv: if frame == 3 { [0.75; 2] } else { [0.5; 2] },
|
||||
};
|
||||
let expected: Vec<_> = input
|
||||
.bolts
|
||||
.iter()
|
||||
.flat_map(|bolt| reference(bolt.seed, bolt.at, camera, input.uv))
|
||||
.collect();
|
||||
let transient = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: None,
|
||||
contents: bytemuck::cast_slice(&expected),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
renderer.prepare(&device, &mut uploads, &mut encoder, &input, camera);
|
||||
let mut readbacks = Vec::new();
|
||||
for mode in 0..2 {
|
||||
let color = texture(
|
||||
wgpu::TextureFormat::Rgba8Unorm,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
let view = color.create_view(&Default::default());
|
||||
let depth = texture(
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
)
|
||||
.create_view(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: None,
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(&pipelines[mode]);
|
||||
pass.set_bind_group(0, &groups[mode], &[]);
|
||||
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
if mode == 0 {
|
||||
pass.set_vertex_buffer(0, transient.slice(..));
|
||||
pass.draw_indexed(0..expected.len() as u32 / 4 * 6, 0, 0..1);
|
||||
} else {
|
||||
renderer.draw(&mut pass, &input);
|
||||
}
|
||||
}
|
||||
let read = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: 256 * 256 * 4,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
color.as_image_copy(),
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &read,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(1024),
|
||||
rows_per_image: None,
|
||||
},
|
||||
},
|
||||
size,
|
||||
);
|
||||
readbacks.push(read);
|
||||
}
|
||||
uploads.finish(&encoder);
|
||||
queue.submit([encoder.finish()]);
|
||||
for read in &readbacks {
|
||||
read.slice(..)
|
||||
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
|
||||
}
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let pixels: Vec<Vec<u8>> = readbacks
|
||||
.iter()
|
||||
.map(|read| read.slice(..).get_mapped_range().unwrap().to_vec())
|
||||
.collect();
|
||||
assert!(pixels[0].iter().any(|&b| b != 0), "empty reference frame");
|
||||
assert_eq!(pixels[0], pixels[1], "frame {frame}: GPU output differs");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user