use bitvec::vec::BitVec;
use cgmath::{EuclideanSpace as _, MetricSpace as _, Point3, Vector3, Zero as _};
use ordered_float::OrderedFloat;
use std::fmt::Debug;
use std::ops::Range;
use crate::camera::Flaws;
use crate::math::{Face6, GridAab, GridCoordinate, GridPoint, GridRotation};
use crate::mesh::{BlockMesh, GfxVertex, MeshOptions, TextureTile};
use crate::space::{BlockIndex, Space};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SpaceMesh<V, T> {
vertices: Vec<V>,
indices: Vec<u32>,
opaque_range: Range<usize>,
transparent_ranges: [Range<usize>; DepthOrdering::COUNT],
block_indices_used: BitVec,
textures_used: Vec<T>,
flaws: Flaws,
}
impl<V, T> SpaceMesh<V, T> {
#[allow(clippy::doc_markdown)] #[inline]
pub fn new<'p, P>(
space: &Space,
bounds: GridAab,
options: &MeshOptions,
block_meshes: P,
) -> SpaceMesh<V, T>
where
V: GfxVertex + 'p,
P: BlockMeshProvider<'p, V, T>,
T: TextureTile + 'p,
{
let mut this = Self::default();
this.compute(space, bounds, options, block_meshes);
this
}
#[inline]
pub fn vertices(&self) -> &[V] {
&self.vertices
}
#[inline]
pub fn indices(&self) -> &[u32] {
&self.indices
}
pub fn flaws(&self) -> Flaws {
self.flaws
}
#[inline]
pub fn is_empty(&self) -> bool {
self.indices.is_empty()
}
#[inline]
pub fn opaque_range(&self) -> Range<usize> {
self.opaque_range.clone()
}
#[inline]
pub fn transparent_range(&self, ordering: DepthOrdering) -> Range<usize> {
self.transparent_ranges[ordering.to_index()].clone()
}
#[inline]
pub fn blocks_used_iter(&self) -> impl Iterator<Item = BlockIndex> + '_ {
self.block_indices_used.iter_ones().map(|i| i as BlockIndex)
}
#[allow(dead_code)] fn consistency_check(&self) {
assert_eq!(self.opaque_range().start, 0);
let len_transparent = self.transparent_range(DepthOrdering::Any).len();
for &rot in &GridRotation::ALL {
assert_eq!(
self.transparent_range(DepthOrdering::Direction(rot)).len(),
len_transparent,
"transparent range {rot:?} does not have the same \
length ({len_transparent}) as others"
);
}
assert_eq!(self.opaque_range().end % 3, 0);
assert_eq!(self.indices.len() % 3, 0);
for index in self.indices.iter().copied() {
assert!(index < self.vertices.len() as u32);
}
}
}
impl<V: GfxVertex, T: TextureTile> SpaceMesh<V, T> {
pub fn compute<'p, P>(
&mut self,
space: &Space,
bounds: GridAab,
_options: &MeshOptions,
mut block_meshes: P,
) where
P: BlockMeshProvider<'p, V, T>,
V: 'p,
T: 'p,
{
self.vertices.clear();
self.indices.clear();
self.block_indices_used.clear();
self.textures_used.clear();
self.flaws = Flaws::empty();
let mut transparent_indices = Vec::new();
for cube in bounds.interior_iter() {
let index: BlockIndex = match space.get_block_index(cube) {
Some(index) => index,
None => continue,
};
let already_seen_index = bitset_set_and_get(&mut self.block_indices_used, index.into());
let block_mesh = match block_meshes.get(index) {
Some(mesh) => mesh,
None => continue,
};
if !already_seen_index {
self.textures_used
.extend(block_mesh.textures().iter().cloned());
self.flaws |= block_mesh.flaws();
}
write_block_mesh_to_space_mesh(
block_mesh,
cube - bounds.lower_bounds().to_vec(),
&mut self.vertices,
&mut self.indices,
&mut transparent_indices,
|face| {
let adjacent_cube = cube + face.normal_vector();
if let Some(adj_block_index) = space.get_block_index(adjacent_cube) {
if block_meshes
.get(adj_block_index)
.map(|adj_mesh| adj_mesh.face_vertices[face.opposite()].fully_opaque)
.unwrap_or(false)
{
bitset_set_and_get(
&mut self.block_indices_used,
adj_block_index.into(),
);
return true;
}
}
false
},
);
}
self.sort_and_store_transparent_indices(transparent_indices);
#[cfg(debug_assertions)]
self.consistency_check();
}
fn sort_and_store_transparent_indices(&mut self, transparent_indices: Vec<u32>) {
self.opaque_range = 0..self.indices.len();
if !V::WANTS_DEPTH_SORTING || transparent_indices.is_empty() {
let range = extend_giving_range(&mut self.indices, transparent_indices);
self.transparent_ranges.fill(range);
} else {
struct QuadWithMid<S> {
indices: [u32; 6],
midpoint: Point3<S>,
}
let quads = bytemuck::cast_slice::<u32, [u32; 6]>(&transparent_indices);
let mut sortable_quads: Vec<QuadWithMid<V::Coordinate>> = quads
.iter()
.map(|&indices| QuadWithMid {
indices,
midpoint: Self::midpoint(&self.vertices, indices),
})
.collect();
self.transparent_ranges[DepthOrdering::Within.to_index()] =
extend_giving_range(&mut self.indices, transparent_indices);
for rot in GridRotation::ALL_BUT_REFLECTIONS {
let ordering = DepthOrdering::Direction(rot);
let basis = rot.inverse().to_basis();
sortable_quads.sort_by_key(|quad| -> [OrderedFloat<V::Coordinate>; 3] {
basis
.map(|f| OrderedFloat(-f.dot(quad.midpoint.to_vec())))
.into()
});
self.transparent_ranges[ordering.to_index()] = extend_giving_range(
&mut self.indices,
sortable_quads.iter().flat_map(|tri| tri.indices),
);
self.transparent_ranges[ordering.rev().to_index()] = extend_giving_range(
&mut self.indices,
sortable_quads.iter().rev().flat_map(|tri| tri.indices),
);
}
}
}
pub fn depth_sort_for_view(&mut self, view_position: Point3<V::Coordinate>) -> bool {
if !V::WANTS_DEPTH_SORTING {
return false;
}
let range = self.transparent_range(DepthOrdering::Within);
if range.len() < 12 {
return false;
}
let slice: &mut [u32] = &mut self.indices[range];
let slice: &mut [[u32; 6]] = bytemuck::cast_slice_mut(slice);
let vertices = &self.vertices; slice.sort_unstable_by_key(|indices| {
-OrderedFloat(view_position.distance2(Self::midpoint(vertices, *indices)))
});
true
}
#[inline]
fn midpoint(vertices: &[V], indices: [u32; 6]) -> Point3<V::Coordinate> {
let one_half = <V::Coordinate as num_traits::NumCast>::from(0.5f32).unwrap();
let v0 = vertices[indices[0] as usize].position();
let v1 = vertices[indices[1] as usize].position();
let v2 = vertices[indices[2] as usize].position();
let max = v0
.zip(v1, num_traits::Float::max)
.zip(v2, num_traits::Float::max);
let min = v0
.zip(v1, num_traits::Float::min)
.zip(v2, num_traits::Float::min);
(max + min.to_vec()) * one_half
}
}
fn write_block_mesh_to_space_mesh<V: GfxVertex, T: TextureTile>(
block_mesh: &BlockMesh<V, T>,
cube: GridPoint,
vertices: &mut Vec<V>,
opaque_indices: &mut Vec<u32>,
transparent_indices: &mut Vec<u32>,
mut neighbor_is_fully_opaque: impl FnMut(Face6) -> bool,
) {
if block_mesh.is_empty() {
return;
}
let inst = V::instantiate_block(cube);
for (face, face_mesh) in block_mesh.all_face_meshes() {
if face_mesh.is_empty() {
continue;
}
if let Ok(face) = Face6::try_from(face) {
if neighbor_is_fully_opaque(face) {
continue;
}
}
let index_offset_usize = vertices.len();
let index_offset: u32 = index_offset_usize
.try_into()
.expect("vertex index overflow");
vertices.extend(face_mesh.vertices.iter());
for vertex in &mut vertices[index_offset_usize..] {
vertex.instantiate_vertex(inst);
}
opaque_indices.extend(face_mesh.indices_opaque.iter().map(|i| i + index_offset));
transparent_indices.extend(
face_mesh
.indices_transparent
.iter()
.map(|i| i + index_offset),
);
}
}
const ZERO_RANGE: Range<usize> = 0..0;
impl<V, T> Default for SpaceMesh<V, T> {
#[inline]
fn default() -> Self {
Self {
vertices: Vec::new(),
indices: Vec::new(),
opaque_range: ZERO_RANGE,
transparent_ranges: [ZERO_RANGE; DepthOrdering::COUNT],
block_indices_used: BitVec::new(),
textures_used: Vec::new(),
flaws: Flaws::empty(),
}
}
}
impl<V: GfxVertex, T: TextureTile> From<&BlockMesh<V, T>> for SpaceMesh<V, T> {
fn from(block_mesh: &BlockMesh<V, T>) -> Self {
let mut block_indices_used = BitVec::new();
block_indices_used.push(true);
let mut space_mesh = Self {
vertices: Vec::with_capacity(
block_mesh
.all_face_meshes()
.map(|(_, fm)| fm.vertices.len())
.sum(),
),
indices: Vec::with_capacity(
block_mesh
.all_face_meshes()
.map(|(_, fm)| fm.indices_opaque.len())
.sum(),
),
opaque_range: 0..0,
transparent_ranges: [ZERO_RANGE; DepthOrdering::COUNT],
block_indices_used,
textures_used: block_mesh.textures_used.clone(),
flaws: block_mesh.flaws(),
};
let mut transparent_indices = Vec::with_capacity(
block_mesh
.all_face_meshes()
.map(|(_, fm)| fm.indices_transparent.len())
.sum(),
);
write_block_mesh_to_space_mesh(
block_mesh,
GridPoint::origin(),
&mut space_mesh.vertices,
&mut space_mesh.indices,
&mut transparent_indices,
|_| false,
);
space_mesh.sort_and_store_transparent_indices(transparent_indices);
space_mesh
}
}
fn bitset_set_and_get(v: &mut BitVec, index: usize) -> bool {
let previous = if index >= v.len() {
v.resize(index + 1, false);
false
} else {
v[index]
};
v.set(index, true);
previous
}
fn extend_giving_range<T>(
storage: &mut Vec<T>,
items: impl IntoIterator<Item = T>,
) -> Range<usize> {
let start = storage.len();
storage.extend(items);
let end = storage.len();
start..end
}
pub trait BlockMeshProvider<'a, V, T> {
fn get(&mut self, index: BlockIndex) -> Option<&'a BlockMesh<V, T>>;
}
impl<'a, V, T> BlockMeshProvider<'a, V, T> for &'a [BlockMesh<V, T>] {
fn get(&mut self, index: BlockIndex) -> Option<&'a BlockMesh<V, T>> {
<[_]>::get(self, usize::from(index))
}
}
#[allow(clippy::exhaustive_enums)]
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum DepthOrdering {
Any,
Within,
Direction(GridRotation),
}
impl DepthOrdering {
const ROT_COUNT: usize = GridRotation::ALL.len();
const COUNT: usize = Self::ROT_COUNT + 1;
#[allow(dead_code)] fn from_index(index: usize) -> Self {
const LAST_ROT: usize = DepthOrdering::ROT_COUNT - 1;
match index {
0..=LAST_ROT => Self::Direction(GridRotation::ALL[index]),
DepthOrdering::ROT_COUNT => Self::Within,
_ => panic!("out of range"),
}
}
fn to_index(self) -> usize {
match self {
DepthOrdering::Direction(rotation) => rotation as usize,
DepthOrdering::Within | DepthOrdering::Any => DepthOrdering::ROT_COUNT,
}
}
pub fn from_view_direction(direction: Vector3<GridCoordinate>) -> DepthOrdering {
if direction == Vector3::zero() {
return DepthOrdering::Within;
}
let abs = direction.map(GridCoordinate::abs);
let permutation = if abs.z > abs.x {
if abs.y > abs.x {
if abs.z > abs.y {
GridRotation::RZYX
} else {
GridRotation::RYZX
}
} else if abs.z > abs.y {
GridRotation::RZXY
} else {
GridRotation::RYZX
}
} else if abs.y > abs.x {
GridRotation::RYXZ
} else {
if abs.z > abs.y {
GridRotation::RXZY
} else {
GridRotation::RXYZ
}
};
let flips = if direction.x < 0 {
GridRotation::RxYZ
} else {
GridRotation::IDENTITY
} * if direction.y < 0 {
GridRotation::RXyZ
} else {
GridRotation::IDENTITY
} * if direction.z < 0 {
GridRotation::RXYz
} else {
GridRotation::IDENTITY
};
DepthOrdering::Direction(permutation.inverse() * flips)
}
fn rev(self) -> Self {
match self {
DepthOrdering::Any | DepthOrdering::Within => self,
DepthOrdering::Direction(rot) => DepthOrdering::Direction(rot * GridRotation::Rxyz),
}
}
}