Merge pull request #609 from LookImEcho-Rick/fix/563-translucent-block-outline
fix(rendering): correct selection outline on translucent blocks
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
//! Transport for the vanilla quad sorting / viewpoint parity gate.
|
||||
use horizon_client::gfx::translucency::{SortState, Sorter, quad_center};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufWriter, Write},
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Case {
|
||||
origin: [i32; 3],
|
||||
quads: Vec<[[f32; 3]; 4]>,
|
||||
cameras: Vec<[f64; 3]>,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let [input, output] = args.as_slice() else {
|
||||
return Err("usage: translucency_fixture INPUT OUTPUT".into());
|
||||
};
|
||||
let mut out = BufWriter::new(fs::File::create(output)?);
|
||||
for line in fs::read_to_string(input)?.lines() {
|
||||
let case: Case = serde_json::from_str(line)?;
|
||||
let centers: Vec<_> = case.quads.iter().map(|q| quad_center(q[0], q[2])).collect();
|
||||
let mut state = SortState::new(centers.clone());
|
||||
let mut sorter = Sorter::default();
|
||||
let mut cache_sorter = Sorter::default();
|
||||
let frames: Vec<_> = case
|
||||
.cameras
|
||||
.iter()
|
||||
.map(|&camera| {
|
||||
let update = state
|
||||
.update(camera, case.origin, &mut cache_sorter)
|
||||
.is_some();
|
||||
let local = std::array::from_fn(|i| (camera[i] - f64::from(case.origin[i])) as f32);
|
||||
json!({"indices": sorter.sort(¢ers, local), "update": update})
|
||||
})
|
||||
.collect();
|
||||
let bits: Vec<_> = centers
|
||||
.iter()
|
||||
.map(|c| c.map(|f| f.to_bits() as i32))
|
||||
.collect();
|
||||
writeln!(out, "{}", json!({"centers": bits, "frames": frames}))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -8460,12 +8460,23 @@ impl Game<'_> {
|
||||
let debug_lines = horizon_client::gizmos::camera_relative(&lines, at, view);
|
||||
let debug_lines_on_top = horizon_client::gizmos::camera_relative(&on_top, at, view);
|
||||
let debug_crosshair = horizon_client::gizmos::camera_relative(&crosshair.on_top, at, view);
|
||||
// LevelRenderer.renderHitOutline: the outline shape's edges.
|
||||
// LevelExtractor.extractBlockOutline: model translucency controls draw order.
|
||||
let mut outline_after_terrain = false;
|
||||
let outline = if self.screen == Screen::Playing && !self.spectator() {
|
||||
self.pick()
|
||||
.map(|h| {
|
||||
let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]);
|
||||
let f = self.res.facts.get(state);
|
||||
outline_after_terrain = self
|
||||
.pack
|
||||
.assets
|
||||
.model_catalog
|
||||
.collect(state, BlockPos::new(h.pos[0], h.pos[1], h.pos[2]))
|
||||
.is_ok_and(|models| {
|
||||
models
|
||||
.iter()
|
||||
.any(|(_, model)| model.faces.iter().any(|f| f.translucent))
|
||||
});
|
||||
let o = if f.outline_offset {
|
||||
self.pack
|
||||
.context
|
||||
@@ -8615,6 +8626,7 @@ impl Game<'_> {
|
||||
}),
|
||||
dark_disc: self.dark_disc(camera),
|
||||
outline,
|
||||
outline_after_terrain,
|
||||
debug_lines: &debug_lines,
|
||||
debug_lines_on_top: &debug_lines_on_top,
|
||||
debug_crosshair: &debug_crosshair,
|
||||
|
||||
@@ -64,6 +64,7 @@ mod pack_stages;
|
||||
pub mod panorama;
|
||||
mod resident;
|
||||
mod timing;
|
||||
pub mod translucency;
|
||||
pub(crate) mod upload;
|
||||
mod world_post;
|
||||
|
||||
@@ -98,6 +99,8 @@ struct SectionGpu {
|
||||
translucent: u32,
|
||||
/// The solid quads by facing: back-facing groups are skipped.
|
||||
faces: crate::mesher::FaceGroups,
|
||||
sort: translucency::SortState,
|
||||
sorted_indices: Option<(u32, u64)>,
|
||||
}
|
||||
/// Line segments the hit outline can hold.
|
||||
const MAX_OUTLINE_EDGES: u64 = 256;
|
||||
@@ -133,6 +136,8 @@ pub struct Frame<'a> {
|
||||
pub dark_disc: bool,
|
||||
/// The hit block outline as line segments (from, to) in world space.
|
||||
pub outline: Vec<[f64; 6]>,
|
||||
/// `BlockOutlineRenderState.isTranslucent`: draw after translucent terrain.
|
||||
pub outline_after_terrain: bool,
|
||||
/// `lines` with a colour and pixel width (`gizmos::camera_relative`):
|
||||
/// the fishing line and debug gizmos, depth tested, then gizmos drawn
|
||||
/// over everything.
|
||||
@@ -318,6 +323,9 @@ pub struct Renderer {
|
||||
depth: wgpu::TextureView,
|
||||
sections: resident::Resident<SectionGpu>,
|
||||
arena: arena::Arena,
|
||||
sorted_indices: arena::Arena,
|
||||
translucent_sorter: translucency::Sorter,
|
||||
translucency_cursor: usize,
|
||||
/// `DrawIndexedIndirectArgs` for this frame's solid then translucent draws.
|
||||
indirect: wgpu::Buffer,
|
||||
indirect_capacity: u64,
|
||||
@@ -329,8 +337,8 @@ pub struct Renderer {
|
||||
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
|
||||
/// index, base vertex, first instance.
|
||||
draws: Vec<[u32; 5]>,
|
||||
/// The arena page of each of `draws`.
|
||||
draw_pages: Vec<u32>,
|
||||
/// Vertex arena page and optional sorted index arena page of each draw.
|
||||
draw_pages: Vec<(u32, Option<u32>)>,
|
||||
/// Block-entity blocks per meshed section (world position, state id).
|
||||
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
|
||||
/// VisGraph face connectivity per meshed section (cave culling).
|
||||
@@ -836,7 +844,7 @@ impl Renderer {
|
||||
&terrain_buffers,
|
||||
tri,
|
||||
Some(wgpu::Face::Back),
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
Some(alpha_blend),
|
||||
);
|
||||
@@ -869,7 +877,7 @@ impl Renderer {
|
||||
&line_buffers,
|
||||
wgpu::PrimitiveTopology::TriangleStrip,
|
||||
None,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
Some(alpha_blend),
|
||||
);
|
||||
@@ -1633,6 +1641,7 @@ impl Renderer {
|
||||
std::mem::size_of::<TerrainVertex>() as u64,
|
||||
1 << 20,
|
||||
);
|
||||
let sorted_indices = arena::Arena::indices(&device, 1 << 16);
|
||||
let indirect = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Section draws"),
|
||||
size: 1024 * 20,
|
||||
@@ -1726,6 +1735,9 @@ impl Renderer {
|
||||
depth,
|
||||
sections: resident::Resident::default(),
|
||||
arena,
|
||||
sorted_indices,
|
||||
translucent_sorter: translucency::Sorter::default(),
|
||||
translucency_cursor: 0,
|
||||
indirect,
|
||||
indirect_capacity: 1024,
|
||||
multi_draw,
|
||||
@@ -1910,6 +1922,10 @@ impl Renderer {
|
||||
}
|
||||
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
|
||||
let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices);
|
||||
let sorted_indices = (translucent > 0).then(|| {
|
||||
self.sorted_indices
|
||||
.alloc(&self.device, &self.queue, u64::from(translucent) * 6)
|
||||
});
|
||||
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() {
|
||||
@@ -1930,6 +1946,15 @@ impl Renderer {
|
||||
solid,
|
||||
translucent,
|
||||
faces: mesh.faces,
|
||||
sort: translucency::SortState::new(
|
||||
mesh.translucent
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|q| translucency::quad_center(q[0].pos, q[2].pos))
|
||||
.collect(),
|
||||
),
|
||||
sorted_indices,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1940,17 +1965,19 @@ impl Renderer {
|
||||
fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) {
|
||||
let (mut i, end) = (first as usize, (first + count) as usize);
|
||||
while i < end {
|
||||
let page = self.draw_pages[i];
|
||||
let (page, index_page) = self.draw_pages[i];
|
||||
let run = self.draw_pages[i..end]
|
||||
.iter()
|
||||
.take_while(|&&p| p == page)
|
||||
.take_while(|&&p| p == (page, index_page))
|
||||
.count();
|
||||
pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..));
|
||||
let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p));
|
||||
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
if self.multi_draw {
|
||||
pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32);
|
||||
} else {
|
||||
for d in &self.draws[i..i + run] {
|
||||
pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1);
|
||||
pass.draw_indexed(d[2]..d[2] + d[0], d[3] as i32, d[4]..d[4] + 1);
|
||||
}
|
||||
}
|
||||
i += run;
|
||||
@@ -1958,6 +1985,10 @@ impl Renderer {
|
||||
}
|
||||
fn release_section(&mut self, key: SectionKey) {
|
||||
if let Some(s) = self.sections.remove(key) {
|
||||
if let Some((page, start)) = s.sorted_indices {
|
||||
self.sorted_indices
|
||||
.release(page, start, u64::from(s.translucent) * 6);
|
||||
}
|
||||
self.arena
|
||||
.release(s.page, s.start, u64::from(s.solid + s.translucent) * 4);
|
||||
}
|
||||
@@ -1970,6 +2001,8 @@ impl Renderer {
|
||||
self.block_entities.clear();
|
||||
self.sections.clear();
|
||||
self.arena.clear();
|
||||
self.sorted_indices.clear();
|
||||
self.translucency_cursor = 0;
|
||||
self.occlusion.clear();
|
||||
}
|
||||
pub fn remove(&mut self, key: SectionKey) {
|
||||
@@ -2391,19 +2424,51 @@ impl Renderer {
|
||||
s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| {
|
||||
let first = s.start + u64::from(first) * 4;
|
||||
self.draws.push([quads * 6, 1, 0, first as u32, i as u32]);
|
||||
self.draw_pages.push(s.page);
|
||||
self.draw_pages.push((s.page, None));
|
||||
});
|
||||
}
|
||||
let solid_draws = self.draws.len() as u32;
|
||||
// LevelRenderer: nearby sections each frame, plus a rotating eighth
|
||||
// (at least 15) of the visible list. Cached views avoid needless sorts.
|
||||
let count = visible.len();
|
||||
let budget = (count / 8).max(15).min(count);
|
||||
self.translucency_cursor %= count.max(1);
|
||||
for (i, v) in visible.iter().enumerate().rev() {
|
||||
let s = self.sections.get(v.slot);
|
||||
if s.translucent > 0 {
|
||||
let s = self.sections.get_mut(v.slot);
|
||||
if let Some((index_page, index_start)) = s.sorted_indices {
|
||||
let nearby = (v.key.0 - camera_section.0).abs() <= 2
|
||||
&& (v.key.1 - camera_section.1).abs() <= 2
|
||||
&& (v.key.2 - camera_section.2).abs() <= 2;
|
||||
let scheduled = (i + count - self.translucency_cursor) % count < budget;
|
||||
let origin = [
|
||||
v.key.0 * 16,
|
||||
crate::chunk::MIN_Y + v.key.1 * 16,
|
||||
v.key.2 * 16,
|
||||
];
|
||||
if (!s.sort.is_sorted() || nearby || scheduled)
|
||||
&& let Some(indices) =
|
||||
s.sort
|
||||
.update(camera.to_array(), origin, &mut self.translucent_sorter)
|
||||
{
|
||||
self.uploads.buffer(
|
||||
&mut encoder,
|
||||
self.sorted_indices.buffer(index_page),
|
||||
index_start * 4,
|
||||
bytemuck::cast_slice(indices),
|
||||
);
|
||||
}
|
||||
let first = s.start + u64::from(s.solid) * 4;
|
||||
self.draws
|
||||
.push([s.translucent * 6, 1, 0, first as u32, i as u32]);
|
||||
self.draw_pages.push(s.page);
|
||||
self.draws.push([
|
||||
s.translucent * 6,
|
||||
1,
|
||||
index_start as u32,
|
||||
first as u32,
|
||||
i as u32,
|
||||
]);
|
||||
self.draw_pages.push((s.page, Some(index_page)));
|
||||
}
|
||||
}
|
||||
self.translucency_cursor += budget;
|
||||
let translucent_draws = self.draws.len() as u32 - solid_draws;
|
||||
if self.multi_draw && !self.draws.is_empty() {
|
||||
if self.draws.len() as u64 > self.indirect_capacity {
|
||||
@@ -2665,7 +2730,7 @@ impl Renderer {
|
||||
pass.draw_indexed(0..additive_quads * 6, (world_quads * 4) as i32, 0..1);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if outline_edges > 0 {
|
||||
if outline_edges > 0 && !frame.outline_after_terrain {
|
||||
pass.set_pipeline(&self.lines);
|
||||
pass.set_vertex_buffer(0, self.outline.slice(..));
|
||||
pass.draw(0..4, 0..outline_edges as u32);
|
||||
@@ -2684,6 +2749,14 @@ impl Renderer {
|
||||
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 {
|
||||
pass.set_pipeline(&self.lines);
|
||||
pass.set_vertex_buffer(0, self.outline.slice(..));
|
||||
pass.draw(0..4, 0..outline_edges as u32);
|
||||
}
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
// LevelRenderer: the world border after translucent terrain and weather.
|
||||
if let Some(b) = frame.border.as_ref().filter(|_| !frame.title) {
|
||||
pass.set_pipeline(&self.border_pipeline);
|
||||
|
||||
@@ -52,31 +52,47 @@ pub struct Arena {
|
||||
pages: Vec<Page>,
|
||||
stride: u64,
|
||||
page_limit: u64,
|
||||
usage: wgpu::BufferUsages,
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
fn with_usage(
|
||||
device: &wgpu::Device,
|
||||
stride: u64,
|
||||
capacity: u64,
|
||||
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 page_limit = (bytes / stride) / GRAIN * GRAIN;
|
||||
let capacity = capacity.next_multiple_of(GRAIN).min(page_limit);
|
||||
Self {
|
||||
pages: vec![Page {
|
||||
buffer: Self::create(device, stride, capacity),
|
||||
buffer: Self::create(device, stride, capacity, usage),
|
||||
capacity,
|
||||
free: FreeList::new(capacity),
|
||||
}],
|
||||
stride,
|
||||
page_limit,
|
||||
usage,
|
||||
}
|
||||
}
|
||||
fn create(device: &wgpu::Device, stride: u64, capacity: u64) -> wgpu::Buffer {
|
||||
fn create(
|
||||
device: &wgpu::Device,
|
||||
stride: u64,
|
||||
capacity: u64,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Section vertex arena"),
|
||||
label: Some("Section buffer arena"),
|
||||
size: capacity * stride,
|
||||
usage: wgpu::BufferUsages::VERTEX
|
||||
| wgpu::BufferUsages::COPY_DST
|
||||
| wgpu::BufferUsages::COPY_SRC,
|
||||
usage: usage | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
@@ -121,7 +137,7 @@ impl Arena {
|
||||
let mut free = FreeList::new(capacity);
|
||||
let start = free.take(len).expect("a new page fits one section");
|
||||
self.pages.push(Page {
|
||||
buffer: Self::create(device, self.stride, capacity),
|
||||
buffer: Self::create(device, self.stride, capacity, self.usage),
|
||||
capacity,
|
||||
free,
|
||||
});
|
||||
@@ -133,7 +149,7 @@ impl Arena {
|
||||
}
|
||||
fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, page: usize, capacity: u64) {
|
||||
let capacity = capacity.next_multiple_of(GRAIN).min(self.page_limit);
|
||||
let buffer = Self::create(device, self.stride, capacity);
|
||||
let buffer = Self::create(device, self.stride, capacity, self.usage);
|
||||
let old = &mut self.pages[page];
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Grow section arena"),
|
||||
|
||||
@@ -58,6 +58,9 @@ impl<T> Resident<T> {
|
||||
pub fn get(&self, slot: u32) -> &T {
|
||||
&self.items[slot as usize].1
|
||||
}
|
||||
pub fn get_mut(&mut self, slot: u32) -> &mut T {
|
||||
&mut self.items[slot as usize].1
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.items.clear();
|
||||
self.slots.clear();
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Vanilla 26.3 MeshData.SortState / VertexSorting.byDistance.
|
||||
//! Keep vertex order intact; only the quad indices change as the camera moves.
|
||||
|
||||
/// MeshData.decodeQuadCentroids uses the opposite corners, not all four vertices.
|
||||
pub fn quad_center(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
std::array::from_fn(|i| (a[i] + b[i]) / 2.0)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Sorter {
|
||||
order: Vec<(u32, f32)>,
|
||||
indices: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Sorter {
|
||||
pub fn sort(&mut self, centers: &[[f32; 3]], camera: [f32; 3]) -> &[u32] {
|
||||
self.order.clear();
|
||||
self.order.extend(centers.iter().enumerate().map(|(i, c)| {
|
||||
let [x, y, z] = std::array::from_fn(|j| camera[j] - c[j]);
|
||||
(i as u32, x * x + y * y + z * z)
|
||||
}));
|
||||
// VertexSorting uses a stable merge sort, preserving mesh order for ties.
|
||||
self.order.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
self.indices.clear();
|
||||
for &(quad, _) in &self.order {
|
||||
let v = quad * 4;
|
||||
self.indices.extend([v, v + 1, v + 2, v + 2, v + 3, v]);
|
||||
}
|
||||
&self.indices
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SortState {
|
||||
centers: Vec<[f32; 3]>,
|
||||
last: Option<([i32; 3], [i32; 3])>,
|
||||
}
|
||||
|
||||
impl SortState {
|
||||
pub fn new(centers: Vec<[f32; 3]>) -> Self {
|
||||
Self {
|
||||
centers,
|
||||
last: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_sorted(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
/// TranslucencyPointOfView and ResortTransparencyTask: diagonal views keep
|
||||
/// their ordering until the point of view changes; aligned views also
|
||||
/// resort on crossing a block boundary. Sub-block movement needs no upload.
|
||||
pub fn update<'a>(
|
||||
&mut self,
|
||||
camera: [f64; 3],
|
||||
origin: [i32; 3],
|
||||
sorter: &'a mut Sorter,
|
||||
) -> Option<&'a [u32]> {
|
||||
let block = camera.map(|v| v.floor() as i32);
|
||||
let pov = std::array::from_fn(|i| ((block[i] >> 4) - (origin[i] >> 4)).clamp(-1, 1));
|
||||
if let Some((last_block, last_pov)) = self.last
|
||||
&& last_pov == pov
|
||||
&& (last_block == block || !pov.contains(&0))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.last = Some((block, pov));
|
||||
Some(sorter.sort(
|
||||
&self.centers,
|
||||
std::array::from_fn(|i| (camera[i] - f64::from(origin[i])) as f32),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn equal_distances_keep_mesh_order_and_triangle_winding() {
|
||||
let mut sorter = Sorter::default();
|
||||
assert_eq!(
|
||||
sorter.sort(
|
||||
&[[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [4.0, 0.0, 0.0]],
|
||||
[0.0; 3]
|
||||
),
|
||||
&[8, 9, 10, 10, 11, 8, 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4]
|
||||
);
|
||||
assert!(sorter.sort(&[], [0.0; 3]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn movement_reverses_faces_without_moving_vertices() {
|
||||
let centers = [[0.5, 0.5, 0.0], [0.5, 0.5, 1.0]];
|
||||
let mut sorter = Sorter::default();
|
||||
assert_eq!(sorter.sort(¢ers, [0.5, 0.5, -2.0])[0], 4);
|
||||
assert_eq!(sorter.sort(¢ers, [0.5, 0.5, 3.0])[0], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_viewpoint_handles_negative_and_large_coordinates() {
|
||||
let origin = [-30_000_000, -64, 30_000_000];
|
||||
let mut state = SortState::new(vec![[0.5; 3]]);
|
||||
let mut sorter = Sorter::default();
|
||||
let camera = [-29_999_999.5, -63.5, 30_000_000.5];
|
||||
assert!(state.update(camera, origin, &mut sorter).is_some());
|
||||
assert!(state.update(camera, origin, &mut sorter).is_none());
|
||||
assert!(
|
||||
state
|
||||
.update([-29_999_999.1, -63.1, 30_000_000.9], origin, &mut sorter)
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
state
|
||||
.update([-29_999_998.9, -63.1, 30_000_000.9], origin, &mut sorter)
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 150 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 232 KiB |
@@ -0,0 +1,63 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.vertex.*;
|
||||
import com.mojang.renderpearl.api.pipeline.IndexType;
|
||||
import java.nio.*;
|
||||
import java.nio.file.*;
|
||||
import net.minecraft.client.renderer.chunk.TranslucencyPointOfView;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.SectionPos;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/** Original probe calling the pinned game's centroid, sorting and index writers. */
|
||||
public final class VanillaTranslucencyOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
try (var out = Files.newBufferedWriter(Path.of(args[1]))) {
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
JsonObject input = JsonParser.parseString(line).getAsJsonObject();
|
||||
JsonArray quads = input.getAsJsonArray("quads");
|
||||
ByteBuffer vertices = ByteBuffer.allocate(quads.size() * 48).order(ByteOrder.nativeOrder());
|
||||
for (JsonElement quad : quads)
|
||||
for (JsonElement vertex : quad.getAsJsonArray())
|
||||
for (JsonElement component : vertex.getAsJsonArray()) vertices.putFloat(component.getAsFloat());
|
||||
vertices.flip();
|
||||
CompactVectorArray centers = new CompactVectorArray(quads.size());
|
||||
MeshData.decodeQuadCentroids(vertices, quads.size() * 4, DefaultVertexFormat.POSITION, centers, 0);
|
||||
JsonArray centerBits = new JsonArray();
|
||||
for (int i = 0; i < centers.size(); i++) {
|
||||
JsonArray c = new JsonArray();
|
||||
c.add(Float.floatToIntBits(centers.getX(i)));
|
||||
c.add(Float.floatToIntBits(centers.getY(i)));
|
||||
c.add(Float.floatToIntBits(centers.getZ(i)));
|
||||
centerBits.add(c);
|
||||
}
|
||||
JsonArray origin = input.getAsJsonArray("origin");
|
||||
int ox = origin.get(0).getAsInt(), oy = origin.get(1).getAsInt(), oz = origin.get(2).getAsInt();
|
||||
long section = SectionPos.asLong(ox >> 4, oy >> 4, oz >> 4);
|
||||
BlockPos lastBlock = null;
|
||||
TranslucencyPointOfView lastPov = null;
|
||||
JsonArray frames = new JsonArray();
|
||||
for (JsonElement element : input.getAsJsonArray("cameras")) {
|
||||
JsonArray c = element.getAsJsonArray();
|
||||
Vec3 camera = new Vec3(c.get(0).getAsDouble(), c.get(1).getAsDouble(), c.get(2).getAsDouble());
|
||||
BlockPos block = BlockPos.containing(camera);
|
||||
TranslucencyPointOfView pov = TranslucencyPointOfView.of(camera, section);
|
||||
boolean update = lastPov == null || !lastPov.equals(pov) || (!block.equals(lastBlock) && pov.isAxisAligned());
|
||||
if (update) { lastPov = pov; lastBlock = block; }
|
||||
var sorting = VertexSorting.byDistance((float)(camera.x - ox), (float)(camera.y - oy), (float)(camera.z - oz));
|
||||
ByteBuffer buffer = ByteBuffer.allocate(quads.size() * 24).order(ByteOrder.nativeOrder());
|
||||
new MeshData.SortState(centers, IndexType.INT).writeSortedIndexBuffer(buffer, sorting);
|
||||
buffer.flip();
|
||||
JsonArray indices = new JsonArray();
|
||||
while (buffer.hasRemaining()) indices.add(buffer.getInt());
|
||||
JsonObject frame = new JsonObject();
|
||||
frame.add("indices", indices); frame.addProperty("update", update); frames.add(frame);
|
||||
}
|
||||
JsonObject result = new JsonObject();
|
||||
result.add("centers", centerBits); result.add("frames", frames);
|
||||
out.write(result.toString()); out.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare quad centroids, sorted triangle indices and cached viewpoints with vanilla 26.3."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
|
||||
def cases():
|
||||
rng = random.Random(563)
|
||||
# Equal distances and a skewed quad detect unstable ties and averaging all four corners.
|
||||
yield {'origin': [0, 0, 0], 'quads': [
|
||||
[[-1, 0, 0]] * 4, [[1, 0, 0]] * 4,
|
||||
[[0, 0, 0], [100, 100, 100], [2, 2, 2], [200, 200, 200]]],
|
||||
'cameras': [[0, 0, 0], [0.1, 0.1, 0.1], [1, 0, 0], [-1, 0, 0]]}
|
||||
for count in [0, 1, 2, 64, *[rng.randrange(3, 100) for _ in range(200)]]:
|
||||
origin = [rng.choice([-30000000, -64, -16, 0, 16, 30000000]) for _ in range(3)]
|
||||
# SectionPos packs Y into fewer bits; world-border coordinates apply to X/Z.
|
||||
origin[1] = rng.choice([-64, -16, 0, 16, 304])
|
||||
quads = [[[rng.uniform(-1, 17) for _ in range(3)] for _ in range(4)] for _ in range(count)]
|
||||
# Walk through block and section boundaries, including negative and diagonal viewpoints.
|
||||
cameras = [[o + d for o in origin] for d in [-32.5, -32.1, -31.9, -16, -0.1, 0, 0.9, 1.1, 15.9, 16, 32, 48]]
|
||||
cameras += [[origin[i] + rng.uniform(-64, 64) for i in range(3)] for _ in range(8)]
|
||||
yield {'origin': origin, 'quads': quads, 'cameras': cameras}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--profile', default='fast', help='Cargo build profile')
|
||||
args = parser.parse_args()
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'translucency-parity'
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(parents=True, exist_ok=True)
|
||||
inputs = build / 'inputs.jsonl'
|
||||
inputs.write_text(''.join(json.dumps(c) + '\n' for c in cases()), encoding='utf-8')
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, stdout=log, stderr=subprocess.STDOUT, timeout=600)
|
||||
if result.returncode:
|
||||
raise RuntimeError((build / (name + '.log')).read_text()[-4000:])
|
||||
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes,
|
||||
lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTranslucencyOracle.java'], 'compile-java')
|
||||
vanilla, rust = build / 'vanilla.jsonl', build / 'rust.jsonl'
|
||||
run(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTranslucencyOracle', inputs, vanilla], 'vanilla')
|
||||
run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'translucency_fixture', '--', inputs, rust], 'rust')
|
||||
expected = [json.loads(line) for line in vanilla.read_text().splitlines()]
|
||||
actual = [json.loads(line) for line in rust.read_text().splitlines()]
|
||||
assert len(expected) == len(actual), 'case count differs'
|
||||
for i, (a, b) in enumerate(zip(expected, actual)):
|
||||
assert a == b, f'sorting mismatch in case {i}; inspect {build}'
|
||||
frames = sum(len(c['frames']) for c in expected)
|
||||
print(f'translucency parity ok: {len(expected)} cases, {frames} camera views; centroids, indices and cache decisions match exactly')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user