use super::*;
/// Default neutral vertex positioned at origin with `+Y` normal, `+X` tangent, and white vertex color.
impl Default for Vertex3D {
/// Returns a default 64-byte `Vertex3D`.
///
/// # Returns
///
/// - `Self` - Default `Vertex3D`.
fn default() -> Self {
Self::from_pos_normal(Vec3::zero(), Vec3::new(0.0, 1.0, 0.0))
}
}
/// Compact and full attribute constructors for `Vertex3D`.
impl Vertex3D {
/// Constructs a `Vertex3D` from `position` and `normal` with identity tangent, zero UVs, and opaque white color.
///
/// # Arguments
///
/// - `Vec3` - Local-space 3D position.
/// - `Vec3` - Local-space unit surface normal.
///
/// # Returns
///
/// - `Self` - Constructed 64-byte vertex.
#[must_use]
pub const fn new(position: Vec3, normal: Vec3) -> Self {
Self::from_pos_normal(position, normal)
}
/// Constructs a `Vertex3D` from `position` and `normal` with default tangent, UV, and color attributes.
///
/// # Arguments
///
/// - `Vec3` - Local-space 3D position.
/// - `Vec3` - Local-space unit surface normal.
///
/// # Returns
///
/// - `Self` - Constructed 64-byte vertex.
#[must_use]
pub const fn from_pos_normal(position: Vec3, normal: Vec3) -> Self {
Self {
position,
normal,
tangent: [1.0, 0.0, 0.0, 1.0],
uv0: [0.0, 0.0],
uv1: [0.0, 0.0],
color0: [255, 255, 255, 255],
flags: 0,
}
}
/// Constructs a fully populated 64-byte `Vertex3D` with tangent, dual UVs, vertex color, and attribute flags.
///
/// # Arguments
///
/// - `Vec3` - Local-space 3D position.
/// - `Vec3` - Local-space unit surface normal.
/// - `[f32; 4]` - Tangent vector `(tx, ty, tz, handedness_sign)`.
/// - `[f32; 2]` - Primary UV coordinate (`TEXCOORD_0`).
/// - `[f32; 2]` - Secondary UV coordinate (`TEXCOORD_1`).
/// - `[u8; 4]` - Packed UNORM8 RGBA vertex color (`COLOR_0`).
/// - `u32` - Attribute bitmask flags.
///
/// # Returns
///
/// - `Self` - Fully populated 64-byte vertex.
#[must_use]
pub const fn from_full(
position: Vec3,
normal: Vec3,
tangent: [f32; 4],
uv0: [f32; 2],
uv1: [f32; 2],
color0: [u8; 4],
flags: u32,
) -> Self {
Self {
position,
normal,
tangent,
uv0,
uv1,
color0,
flags,
}
}
}
/// Default neutral matte PBR material.
impl Default for PbrMaterial {
/// Returns a mid-gray dielectric PBR material.
///
/// # Returns
///
/// - `Self` - Default `PbrMaterial`.
fn default() -> Self {
Self {
base_color: Vec3::new(0.72, 0.75, 0.80),
metallic: 0.1,
roughness: 0.55,
emissive: Vec3::zero(),
reflectivity: 0.12,
surface_detail: SurfaceDetailMode::None,
}
}
}
/// Material presets and fluent builders for metallic conductors, dielectrics, architectural glass, and neon signage.
impl PbrMaterial {
/// Creates a PBR material from an sRGB `Color`, `metallic`, `roughness`, and `reflectivity`.
///
/// # Arguments
///
/// - `Color` - Base albedo color.
/// - `f32` - Metallic scalar `[0.0, 1.0]`.
/// - `f32` - Roughness scalar `[0.04, 1.0]`.
/// - `f32` - Ray-traced reflectivity weight `[0.0, 1.0]`.
///
/// # Returns
///
/// - `Self` - Configured PBR material.
#[must_use]
pub fn pbr(color: Color, metallic: f32, roughness: f32, reflectivity: f32) -> Self {
Self {
base_color: Vec3::from_color(color),
metallic: metallic.clamp(0.0, 1.0),
roughness: roughness.clamp(0.04, 1.0),
emissive: Vec3::zero(),
reflectivity: reflectivity.clamp(0.0, 1.0),
surface_detail: SurfaceDetailMode::None,
}
}
/// Creates a metallic conductor PBR material (chrome, painted car body, brushed steel).
///
/// # Arguments
///
/// - `Color` - Base metallic reflectance color.
/// - `f32` - Surface roughness in `[0.04, 1.0]`.
///
/// # Returns
///
/// - `Self` - Conductor PBR material.
#[must_use]
pub fn metallic(color: Color, roughness: f32) -> Self {
let red_val: f32 = roughness.clamp(0.04, 1.0);
Self::pbr(
color,
0.92,
red_val,
(1.0 - red_val * 0.8).clamp(0.15, 0.96),
)
}
/// Creates a non-metallic dielectric PBR material (asphalt, concrete, matte plastic, cloth).
///
/// # Arguments
///
/// - `Color` - Base diffuse albedo color.
/// - `f32` - Surface roughness in `[0.04, 1.0]`.
///
/// # Returns
///
/// - `Self` - Dielectric PBR material.
#[must_use]
pub fn dielectric(color: Color, roughness: f32) -> Self {
let red_val: f32 = roughness.clamp(0.04, 1.0);
Self::pbr(
color,
0.04,
red_val,
(0.35 * (1.0 - red_val)).clamp(0.04, 0.35),
)
}
/// Creates a highly reflective architectural glass PBR material.
///
/// # Arguments
///
/// - `Color` - Subtle glass tint color.
/// - `f32` - Surface roughness in `[0.04, 0.4]`.
///
/// # Returns
///
/// - `Self` - Reflective glass PBR material.
#[must_use]
pub fn glass(color: Color, roughness: f32) -> Self {
let red_val: f32 = roughness.clamp(0.04, 0.4);
Self::pbr(color, 0.12, red_val, 0.88)
}
/// Creates an emissive neon PBR material for city signage, vehicle tail-lights, and beacons.
///
/// # Arguments
///
/// - `Color` - Base and emissive neon color.
/// - `f32` - Emissive intensity multiplier.
///
/// # Returns
///
/// - `Self` - Emissive PBR material.
#[must_use]
pub fn neon(color: Color, intensity: f32) -> Self {
let rgb: Vec3 = Vec3::from_color(color);
Self {
base_color: rgb,
metallic: 0.2,
roughness: 0.2,
emissive: rgb.scale(intensity.max(0.2)),
reflectivity: 0.3,
surface_detail: SurfaceDetailMode::None,
}
}
/// Returns a copy of this material with custom linear HDR emissive radiance.
///
/// # Arguments
///
/// - `Self` - Base material.
/// - `Vec3` - Emissive HDR RGB radiance.
///
/// # Returns
///
/// - `Self` - Updated material.
#[must_use]
pub fn with_emissive(mut self, emissive: Vec3) -> Self {
self.set_emissive(emissive);
self
}
/// Returns a copy of this material with adjusted surface roughness.
///
/// # Arguments
///
/// - `Self` - Base material.
/// - `f32` - Surface roughness clamped to `[0.04, 1.0]`.
///
/// # Returns
///
/// - `Self` - Updated material.
#[must_use]
pub fn with_roughness(mut self, roughness: f32) -> Self {
self.set_roughness(roughness.clamp(0.04, 1.0));
self
}
/// Returns a copy of this material with adjusted metallic factor.
///
/// # Arguments
///
/// - `Self` - Base material.
/// - `f32` - Metallic factor clamped to `[0.0, 1.0]`.
///
/// # Returns
///
/// - `Self` - Updated material.
#[must_use]
pub fn with_metallic(mut self, metallic: f32) -> Self {
self.set_metallic(metallic.clamp(0.0, 1.0));
self
}
/// Returns a copy of this material with adjusted ray-traced reflectivity.
///
/// # Arguments
///
/// - `Self` - Base material.
/// - `f32` - Reflectivity weight clamped to `[0.0, 1.0]`.
///
/// # Returns
///
/// - `Self` - Updated material.
#[must_use]
pub fn with_reflectivity(mut self, reflectivity: f32) -> Self {
self.set_reflectivity(reflectivity.clamp(0.0, 1.0));
self
}
/// Returns a copy of this material with the requested procedural surface detail overlay.
///
/// # Arguments
///
/// - `Self` - Base material.
/// - `SurfaceDetailMode` - Procedural surface detail mode.
///
/// # Returns
///
/// - `Self` - Updated material.
#[must_use]
pub fn with_surface_detail(mut self, mode: SurfaceDetailMode) -> Self {
self.set_surface_detail(mode);
self
}
}
/// Fluent constructors for `BoxMeshDesc`.
impl BoxMeshDesc {
/// Creates a box mesh descriptor with default ground pivot and neutral PBR material.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `Vec3` - Box extents `(width, height, depth)`.
///
/// # Returns
///
/// - `Self` - Ready descriptor.
#[must_use]
pub fn new(name: &str, size: Vec3) -> Self {
Self {
name: name.to_string(),
size,
ground_pivot: true,
material: PbrMaterial::default(),
}
}
/// Sets whether the box rests on `y = 0` or is centered at the origin.
///
/// # Arguments
///
/// - `Self` - Base descriptor.
/// - `bool` - Ground pivot toggle.
///
/// # Returns
///
/// - `Self` - Updated descriptor.
#[must_use]
pub fn with_ground_pivot(mut self, ground_pivot: bool) -> Self {
self.set_ground_pivot(ground_pivot);
self
}
/// Assigns the PBR material for the generated box mesh.
///
/// # Arguments
///
/// - `Self` - Base descriptor.
/// - `PbrMaterial` - Surface material.
///
/// # Returns
///
/// - `Self` - Updated descriptor.
#[must_use]
pub fn with_material(mut self, material: PbrMaterial) -> Self {
self.set_material(material);
self
}
}
/// Fluent constructors for `GroundPlaneDesc`.
impl GroundPlaneDesc {
/// Creates a ground plane descriptor with default subdivisions and neutral PBR material.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `f32` - Width along X.
/// - `f32` - Depth along Z.
///
/// # Returns
///
/// - `Self` - Ready descriptor.
#[must_use]
pub fn new(name: &str, width: f32, depth: f32) -> Self {
Self {
name: name.to_string(),
width,
depth,
subdivisions: 8,
material: PbrMaterial::default(),
}
}
/// Sets the grid subdivision count along each axis.
///
/// # Arguments
///
/// - `Self` - Base descriptor.
/// - `usize` - Subdivision count.
///
/// # Returns
///
/// - `Self` - Updated descriptor.
#[must_use]
pub fn with_subdivisions(mut self, subdivisions: usize) -> Self {
self.set_subdivisions(subdivisions);
self
}
/// Assigns the PBR material for the generated ground plane.
///
/// # Arguments
///
/// - `Self` - Base descriptor.
/// - `PbrMaterial` - Surface material.
///
/// # Returns
///
/// - `Self` - Updated descriptor.
#[must_use]
pub fn with_material(mut self, material: PbrMaterial) -> Self {
self.set_material(material);
self
}
}
/// Mesh construction, Nanite-style meshlet clustering, decimation, and procedural asset generators for `Mesh3D`.
impl Mesh3D {
/// Partitions indexed triangles into Nanite-style `Meshlet3D` clusters with tight axis-aligned bounding boxes and normal cones.
///
/// # Arguments
///
/// - `&[Vertex3D]` - Source vertex buffer.
/// - `&[[u32; 3]]` - Source triangle indices.
///
/// # Returns
///
/// - `Vec<Meshlet3D>` - Contiguous cluster descriptors covering all triangles.
#[must_use]
pub fn build_meshlets_from_parts(
vertices: &[Vertex3D],
indices: &[[u32; 3]],
) -> Vec<Meshlet3D> {
if indices.is_empty() {
return Vec::new();
}
let cluster_count: usize = indices.len().div_ceil(MESHLET_MAX_TRIS);
let mut out: Vec<Meshlet3D> = Vec::with_capacity(cluster_count);
let mut start: usize = 0;
while start < indices.len() {
let end: usize = (start + MESHLET_MAX_TRIS).min(indices.len());
let mut cluster_box: AxisAlignedBox3D = AxisAlignedBox3D::empty();
let mut avg_n: Vec3 = Vec3::zero();
let mut valid_tris: usize = 0;
for tri in &indices[start..end] {
let (i0, i1, i2): (usize, usize, usize) =
(tri[0] as usize, tri[1] as usize, tri[2] as usize);
if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
let p0: Vec3 = vertices[i0].get_position();
let p1: Vec3 = vertices[i1].get_position();
let p2: Vec3 = vertices[i2].get_position();
cluster_box.expand_point(p0);
cluster_box.expand_point(p1);
cluster_box.expand_point(p2);
let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
avg_n = avg_n.add(fn_vec);
valid_tris += 1;
}
}
if valid_tris == 0 {
cluster_box = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
}
let cone_axis: Vec3 = avg_n.normalize();
let mut min_dot: f32 = 1.0;
for tri in &indices[start..end] {
let (i0, i1, i2): (usize, usize, usize) =
(tri[0] as usize, tri[1] as usize, tri[2] as usize);
if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
let p0: Vec3 = vertices[i0].get_position();
let p1: Vec3 = vertices[i1].get_position();
let p2: Vec3 = vertices[i2].get_position();
let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
min_dot = min_dot.min(fn_vec.dot(cone_axis));
}
}
let radius: f32 = cluster_box.radius().max(0.05);
let screen_error: f32 = radius / ((end - start).max(1) as f32).sqrt();
out.push(Meshlet3D::new(
start as u32,
(end - start) as u32,
cluster_box,
cone_axis,
min_dot,
screen_error,
));
start = end;
}
out
}
/// Constructs a `Mesh3D`, computes its local `AxisAlignedBox3D`, and partitions Nanite-style `Meshlet3D` clusters.
///
/// # Arguments
///
/// - `String` - Asset name.
/// - `Vec<Vertex3D>` - Vertex list.
/// - `Vec<[u32; 3]>` - Triangle indices.
/// - `PbrMaterial` - Default material.
///
/// # Returns
///
/// - `Self` - Ready indexed mesh with meshlets.
#[must_use]
pub fn from_parts(
name: String,
vertices: Vec<Vertex3D>,
indices: Vec<[u32; 3]>,
material: PbrMaterial,
) -> Self {
let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
for item_val in vertices.iter() {
bounds.expand_point(item_val.get_position());
}
if vertices.is_empty() {
bounds = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
}
let meshlets: Vec<Meshlet3D> = Self::build_meshlets_from_parts(&vertices, &indices);
Self {
name,
vertices,
indices,
bounds,
material,
sub_materials: Vec::new(),
tri_materials: Vec::new(),
meshlets,
skin_influences: Vec::new(),
morph_targets: Vec::new(),
material_index: None,
is_closed: false,
}
}
/// Recomputes area-weighted smooth per-vertex normals across all indexed triangles.
///
/// # Arguments
///
/// - `&Self` - Mutable 3D mesh.
pub fn compute_smooth_normals(&mut self) {
let vert_count: usize = self.get_vertices().len();
if vert_count == 0 {
return;
}
let mut accum: Vec<Vec3> = vec![Vec3::zero(); vert_count];
let verts: &[Vertex3D] = self.get_vertices().as_slice();
for tri in self.get_indices().iter() {
let (i0, i1, i2): (usize, usize, usize) =
(tri[0] as usize, tri[1] as usize, tri[2] as usize);
if i0 < vert_count && i1 < vert_count && i2 < vert_count {
let p0: Vec3 = verts[i0].get_position();
let p1: Vec3 = verts[i1].get_position();
let p2: Vec3 = verts[i2].get_position();
let weighted_n: Vec3 = p1.sub(p0).cross(p2.sub(p0));
accum[i0] = accum[i0].add(weighted_n);
accum[i1] = accum[i1].add(weighted_n);
accum[i2] = accum[i2].add(weighted_n);
}
}
for (idx, vert) in self.get_mut_vertices().iter_mut().enumerate() {
let sum_n: Vec3 = accum[idx];
if sum_n.length_sq() > 1e-10 {
vert.set_normal(sum_n.normalize());
}
}
}
/// Computes MikkTSpace-compatible Lengyel tangent-space vectors `(tx, ty, tz, handedness)` from positions, normals, and `uv0`.
///
/// # Arguments
///
/// - `&Self` - Mutable 3D mesh.
pub fn compute_lengyel_tangents(&mut self) {
let vert_count: usize = self.get_vertices().len();
if vert_count == 0 {
return;
}
let mut tan1: Vec<Vec3> = vec![Vec3::zero(); vert_count];
let mut tan2: Vec<Vec3> = vec![Vec3::zero(); vert_count];
let verts: &[Vertex3D] = self.get_vertices().as_slice();
for tri in self.get_indices().iter() {
let (i0, i1, i2): (usize, usize, usize) =
(tri[0] as usize, tri[1] as usize, tri[2] as usize);
if i0 >= vert_count || i1 >= vert_count || i2 >= vert_count {
continue;
}
let p0: Vec3 = verts[i0].get_position();
let p1: Vec3 = verts[i1].get_position();
let p2: Vec3 = verts[i2].get_position();
let w0: [f32; 2] = verts[i0].get_uv0();
let w1: [f32; 2] = verts[i1].get_uv0();
let w2: [f32; 2] = verts[i2].get_uv0();
let e1: Vec3 = p1.sub(p0);
let e2: Vec3 = p2.sub(p0);
let s1: f32 = w1[0] - w0[0];
let s2: f32 = w2[0] - w0[0];
let t1: f32 = w1[1] - w0[1];
let t2: f32 = w2[1] - w0[1];
let det: f32 = s1 * t2 - s2 * t1;
if det.abs() < 1e-10 {
continue;
}
let inv_det: f32 = 1.0 / det;
let sdir: Vec3 = Vec3::new(
(t2 * e1.get_x() - t1 * e2.get_x()) * inv_det,
(t2 * e1.get_y() - t1 * e2.get_y()) * inv_det,
(t2 * e1.get_z() - t1 * e2.get_z()) * inv_det,
);
let tdir: Vec3 = Vec3::new(
(s1 * e2.get_x() - s2 * e1.get_x()) * inv_det,
(s1 * e2.get_y() - s2 * e1.get_y()) * inv_det,
(s1 * e2.get_z() - s2 * e1.get_z()) * inv_det,
);
tan1[i0] = tan1[i0].add(sdir);
tan1[i1] = tan1[i1].add(sdir);
tan1[i2] = tan1[i2].add(sdir);
tan2[i0] = tan2[i0].add(tdir);
tan2[i1] = tan2[i1].add(tdir);
tan2[i2] = tan2[i2].add(tdir);
}
for (idx, vert) in self.get_mut_vertices().iter_mut().enumerate() {
let n: Vec3 = vert.get_normal().normalize();
let t: Vec3 = tan1[idx];
let ortho: Vec3 = t.sub(n.scale(n.dot(t)));
let unit_t: Vec3 = if ortho.length_sq() > 1e-10 {
ortho.normalize()
} else {
let fallback_axis: Vec3 = if n.get_y().abs() < 0.99 {
Vec3::new(0.0, 1.0, 0.0)
} else {
Vec3::new(1.0, 0.0, 0.0)
};
fallback_axis.cross(n).normalize()
};
let handedness: f32 = if n.cross(t).dot(tan2[idx]) < 0.0 {
-1.0
} else {
1.0
};
vert.set_tangent([unit_t.get_x(), unit_t.get_y(), unit_t.get_z(), handedness]);
let next_flags: u32 = vert.get_flags() | 4;
vert.set_flags(next_flags);
}
}
/// Resolves the effective PBR material and sub-material slot for triangle `tri_index`.
///
/// # Arguments
///
/// - `usize` - Triangle index inside `indices`.
/// - `PbrMaterial` - Instance primary PBR material used when slot is `0`.
///
/// # Returns
///
/// - `(PbrMaterial, u16)` - Effective PBR material and resolved material slot.
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
pub fn resolve_triangle_material(
&self,
tri_index: usize,
primary_material: PbrMaterial,
) -> (PbrMaterial, u16) {
let Self {
sub_materials,
tri_materials,
..
} = self;
if tri_materials.is_empty() {
return (primary_material, 0);
}
let slot: u16 = tri_materials.get(tri_index).copied().unwrap_or(0);
if slot == 0 {
(primary_material, 0)
} else if let Some(&sub_mat) = sub_materials.get((slot - 1) as usize) {
(sub_mat, slot)
} else {
(primary_material, 0)
}
}
/// Appends a single outward-oriented flat-shaded triangle tagged with `mat_slot`.
///
/// # Arguments
///
/// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
/// - `&mut Vec<u16>` - Destination per-triangle material slot table.
/// - `(Vec3, Vec3, Vec3)` - Triangle vertices `(vert_a, vert_b, vert_c)` in CCW outward order.
/// - `u16` - Sub-material slot index (`0` = primary material).
fn push_flat_tri(
vertices: &mut Vec<Vertex3D>,
indices: &mut Vec<[u32; 3]>,
tri_materials: &mut Vec<u16>,
corners: (Vec3, Vec3, Vec3),
mat_slot: u16,
) {
let (vert_a, vert_b, vert_c): (Vec3, Vec3, Vec3) = corners;
let face_normal: Vec3 = vert_b.sub(vert_a).cross(vert_c.sub(vert_a)).normalize();
let base_idx: u32 = vertices.len() as u32;
vertices.push(Vertex3D::new(vert_a, face_normal));
vertices.push(Vertex3D::new(vert_b, face_normal));
vertices.push(Vertex3D::new(vert_c, face_normal));
indices.push([base_idx, base_idx + 1, base_idx + 2]);
tri_materials.push(mat_slot);
}
/// Appends a flat-shaded CCW quad split into two triangles tagged with `mat_slot`.
///
/// # Arguments
///
/// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
/// - `&mut Vec<u16>` - Destination per-triangle material slot table.
/// - `[Vec3; 4]` - Quad vertices in CCW outward order.
/// - `u16` - Sub-material slot index.
fn push_flat_quad(
vertices: &mut Vec<Vertex3D>,
indices: &mut Vec<[u32; 3]>,
tri_materials: &mut Vec<u16>,
quad: [Vec3; 4],
mat_slot: u16,
) {
let edge_u: Vec3 = quad[1].sub(quad[0]);
let edge_v: Vec3 = quad[2].sub(quad[0]);
let face_normal: Vec3 = edge_u.cross(edge_v).normalize();
let base_idx: u32 = vertices.len() as u32;
for corner in quad.into_iter() {
vertices.push(Vertex3D::new(corner, face_normal));
}
indices.push([base_idx, base_idx + 1, base_idx + 2]);
indices.push([base_idx, base_idx + 2, base_idx + 3]);
tri_materials.push(mat_slot);
tri_materials.push(mat_slot);
}
/// Appends a closed 6-face tapered frustum/box prism with explicit bottom and top corner quads.
///
/// Bottom corners are ordered `[(-x,+z), (+x,+z), (+x,-z), (-x,-z)]` and top corners match identically.
///
/// # Arguments
///
/// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
/// - `&mut Vec<u16>` - Destination per-triangle material slot table.
/// - `[Vec3; 4]` - Bottom loop corners `[bl_rear, br_rear, br_front, bl_front]`.
/// - `[Vec3; 4]` - Top loop corners `[tl_rear, tr_rear, tr_front, tl_front]`.
/// - `[u16; 6]` - Per-face material slots `[rear(+z), front(-z), right(+x), left(-x), top(+y), bottom(-y)]`.
fn push_tapered_prism(
vertices: &mut Vec<Vertex3D>,
indices: &mut Vec<[u32; 3]>,
tri_materials: &mut Vec<u16>,
bottom: [Vec3; 4],
top: [Vec3; 4],
face_slots: [u16; 6],
) {
Self::push_flat_quad(
vertices,
indices,
tri_materials,
[bottom[0], bottom[1], top[1], top[0]],
face_slots[0],
);
Self::push_flat_quad(
vertices,
indices,
tri_materials,
[bottom[2], bottom[3], top[3], top[2]],
face_slots[1],
);
Self::push_flat_quad(
vertices,
indices,
tri_materials,
[bottom[1], bottom[2], top[2], top[1]],
face_slots[2],
);
Self::push_flat_quad(
vertices,
indices,
tri_materials,
[bottom[3], bottom[0], top[0], top[3]],
face_slots[3],
);
Self::push_flat_quad(
vertices,
indices,
tri_materials,
[top[0], top[1], top[2], top[3]],
face_slots[4],
);
Self::push_flat_quad(
vertices,
indices,
tri_materials,
[bottom[3], bottom[2], bottom[1], bottom[0]],
face_slots[5],
);
}
/// Appends an axis-aligned box prism centered at `center` with `(width, height, depth)` tagged uniformly with `mat_slot`.
///
/// # Arguments
///
/// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
/// - `&mut Vec<u16>` - Destination per-triangle material slot table.
/// - `Vec3` - Box center position.
/// - `Vec3` - Box extents `(width, height, depth)`.
/// - `u16` - Sub-material slot applied to all six faces.
fn push_box_part(
vertices: &mut Vec<Vertex3D>,
indices: &mut Vec<[u32; 3]>,
tri_materials: &mut Vec<u16>,
center: Vec3,
size: Vec3,
mat_slot: u16,
) {
let half_x: f32 = size.get_x() * 0.5;
let half_y: f32 = size.get_y() * 0.5;
let half_z: f32 = size.get_z() * 0.5;
let cx: f32 = center.get_x();
let cy: f32 = center.get_y();
let cz: f32 = center.get_z();
let bottom: [Vec3; 4] = [
Vec3::new(cx - half_x, cy - half_y, cz + half_z),
Vec3::new(cx + half_x, cy - half_y, cz + half_z),
Vec3::new(cx + half_x, cy - half_y, cz - half_z),
Vec3::new(cx - half_x, cy - half_y, cz - half_z),
];
let top: [Vec3; 4] = [
Vec3::new(cx - half_x, cy + half_y, cz + half_z),
Vec3::new(cx + half_x, cy + half_y, cz + half_z),
Vec3::new(cx + half_x, cy + half_y, cz - half_z),
Vec3::new(cx - half_x, cy + half_y, cz - half_z),
];
Self::push_tapered_prism(vertices, indices, tri_materials, bottom, top, [mat_slot; 6]);
}
/// Appends a single closed, watertight stepped multi-tier polygon shell connecting consecutive CCW rings with zero internal caps and strictly outward-facing wall, terrace, and soffit normals.
///
/// # Arguments
///
/// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
/// - `&mut Vec<u16>` - Destination per-triangle material slot table.
/// - `&[(&[Vec3], u16)]` - Ordered bottom-to-top CCW polygon rings paired with the material slot for the strip connecting the previous ring to the current ring.
/// - `(u16, u16)` - `(bottom_cap_slot, top_cap_slot)` material slots for the outer base and roof caps.
fn push_stepped_polygon_shell(
vertices: &mut Vec<Vertex3D>,
indices: &mut Vec<[u32; 3]>,
tri_materials: &mut Vec<u16>,
profile_rings: &[(&[Vec3], u16)],
cap_slots: (u16, u16),
) {
if profile_rings.len() < 2 {
return;
}
let mut ring_len: usize = usize::MAX;
for &(ring, _) in profile_rings.iter() {
ring_len = ring_len.min(ring.len());
}
if ring_len < 3 {
return;
}
for ring_idx in 1..profile_rings.len() {
let prev_ring: &[Vec3] = profile_rings[ring_idx - 1].0;
let (curr_ring, strip_slot): (&[Vec3], u16) = profile_rings[ring_idx];
for corner_idx in 0..ring_len {
let next_corner: usize = (corner_idx + 1) % ring_len;
Self::push_flat_quad(
vertices,
indices,
tri_materials,
[
prev_ring[corner_idx],
prev_ring[next_corner],
curr_ring[next_corner],
curr_ring[corner_idx],
],
strip_slot,
);
}
}
let first_ring: &[Vec3] = profile_rings[0].0;
let last_ring: &[Vec3] = profile_rings[profile_rings.len() - 1].0;
let (bottom_cap_slot, top_cap_slot): (u16, u16) = cap_slots;
let inv_count: f32 = 1.0 / (ring_len as f32);
let mut bottom_center: Vec3 = Vec3::zero();
let mut top_center: Vec3 = Vec3::zero();
for corner_idx in 0..ring_len {
bottom_center = bottom_center.add(first_ring[corner_idx]);
top_center = top_center.add(last_ring[corner_idx]);
}
bottom_center = bottom_center.scale(inv_count);
top_center = top_center.scale(inv_count);
for corner_idx in 0..ring_len {
let next_corner: usize = (corner_idx + 1) % ring_len;
Self::push_flat_tri(
vertices,
indices,
tri_materials,
(top_center, last_ring[corner_idx], last_ring[next_corner]),
top_cap_slot,
);
Self::push_flat_tri(
vertices,
indices,
tri_materials,
(
bottom_center,
first_ring[next_corner],
first_ring[corner_idx],
),
bottom_cap_slot,
);
}
}
/// Generates an axis-aligned box mesh of dimensions `(w, h, d)` resting on `y = 0` or centered.
///
/// # Arguments
///
/// - `&str` - Mesh name.
/// - `f32` - Width along X.
/// - `f32` - Height along Y.
/// - `f32` - Depth along Z.
/// - `bool` - When `true`, base rests on `y = 0`; otherwise centered at origin.
/// - `PbrMaterial` - Surface PBR material.
///
/// # Returns
///
/// - `Self` - Indexed 12-triangle box mesh with crisp flat face normals.
#[must_use]
pub fn box_mesh(
name: &str,
width_val: f32,
height_val: f32,
delta_val: f32,
ground_pivot: bool,
material: PbrMaterial,
) -> Self {
let hx: f32 = width_val * 0.5;
let hz: f32 = delta_val * 0.5;
let y0: f32 = if ground_pivot { 0.0 } else { -height_val * 0.5 };
let y1: f32 = if ground_pivot {
height_val
} else {
height_val * 0.5
};
let faces: [([Vec3; 4], Vec3); 6] = [
(
[
Vec3::new(-hx, y0, hz),
Vec3::new(hx, y0, hz),
Vec3::new(hx, y1, hz),
Vec3::new(-hx, y1, hz),
],
Vec3::new(0.0, 0.0, 1.0),
),
(
[
Vec3::new(hx, y0, -hz),
Vec3::new(-hx, y0, -hz),
Vec3::new(-hx, y1, -hz),
Vec3::new(hx, y1, -hz),
],
Vec3::new(0.0, 0.0, -1.0),
),
(
[
Vec3::new(hx, y0, hz),
Vec3::new(hx, y0, -hz),
Vec3::new(hx, y1, -hz),
Vec3::new(hx, y1, hz),
],
Vec3::new(1.0, 0.0, 0.0),
),
(
[
Vec3::new(-hx, y0, -hz),
Vec3::new(-hx, y0, hz),
Vec3::new(-hx, y1, hz),
Vec3::new(-hx, y1, -hz),
],
Vec3::new(-1.0, 0.0, 0.0),
),
(
[
Vec3::new(-hx, y1, hz),
Vec3::new(hx, y1, hz),
Vec3::new(hx, y1, -hz),
Vec3::new(-hx, y1, -hz),
],
Vec3::new(0.0, 1.0, 0.0),
),
(
[
Vec3::new(-hx, y0, -hz),
Vec3::new(hx, y0, -hz),
Vec3::new(hx, y0, hz),
Vec3::new(-hx, y0, hz),
],
Vec3::new(0.0, -1.0, 0.0),
),
];
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
for (quad, item_count) in faces.into_iter() {
let base: u32 = vertices.len() as u32;
for point_val in quad.into_iter() {
vertices.push(Vertex3D::new(point_val, item_count));
}
indices.push([base, base + 1, base + 2]);
indices.push([base, base + 2, base + 3]);
}
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
mesh.set_is_closed(true);
mesh
}
/// Generates a horizontal ground/road quad plane at `y = 0` subdivided for crisp specular/shadow falloff.
///
/// # Arguments
///
/// - `&str` - Mesh name.
/// - `f32` - Width along X.
/// - `f32` - Depth along Z.
/// - `usize` - Grid subdivisions per axis.
/// - `PbrMaterial` - Surface PBR material.
///
/// # Returns
///
/// - `Self` - Subdivided ground plane mesh.
#[must_use]
pub fn ground_plane(
name: &str,
width_val: f32,
delta_val: f32,
subdivisions: usize,
material: PbrMaterial,
) -> Self {
let segs: usize = subdivisions.clamp(1, 16);
let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
for iz in 0..=segs {
let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * delta_val;
for ix in 0..=segs {
let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * width_val;
vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
}
}
let stride: u32 = (segs + 1) as u32;
for iz in 0..segs {
for ix in 0..segs {
let i0: u32 = (iz as u32) * stride + (ix as u32);
let i1: u32 = i0 + 1;
let i2: u32 = i0 + stride;
let i3: u32 = i2 + 1;
indices.push([i0, i2, i1]);
indices.push([i1, i2, i3]);
}
}
Self::from_parts(name.to_string(), vertices, indices, material)
}
/// Builds a subdivided coastal ocean water ring mesh spanning `outer_span` while omitting submerged interior quads strictly inside the solid island footprint and grouping triangles into spatially coherent 4x4 blocks for Nanite frustum culling.
///
/// # Arguments
///
/// - `&str` - Mesh asset name.
/// - `f32` - Total horizontal outer span in meters along X and Z.
/// - `f32` - Solid island half-width along X in meters.
/// - `f32` - Solid island half-depth along Z in meters.
/// - `usize` - Grid subdivisions along each axis (`8..=32`).
/// - `PbrMaterial` - Ocean water PBR material.
///
/// # Returns
///
/// - `Self` - Watertight coastal ocean ring mesh with spatial meshlets.
#[must_use]
pub fn coastal_ocean_ring(
name: &str,
outer_span: f32,
inner_half_x: f32,
inner_half_z: f32,
subdivisions: usize,
material: PbrMaterial,
) -> Self {
let seg_count: usize = subdivisions.clamp(8, 32);
let cut_half_x: f32 = (inner_half_x - 2.0).max(0.0);
let cut_half_z: f32 = (inner_half_z - 2.0).max(0.0);
let mut vertices: Vec<Vertex3D> = Vec::with_capacity((seg_count + 1) * (seg_count + 1));
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(seg_count * seg_count * 2);
let up_normal: Vec3 = Vec3::new(0.0, 1.0, 0.0);
let inv_segs: f32 = 1.0 / (seg_count as f32);
for grid_z in 0..=seg_count {
let pos_z: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
for grid_x in 0..=seg_count {
let pos_x: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
vertices.push(Vertex3D::new(Vec3::new(pos_x, 0.0, pos_z), up_normal));
}
}
let row_stride: u32 = (seg_count + 1) as u32;
let mut block_z: usize = 0;
while block_z < seg_count {
let end_z: usize = (block_z + 4).min(seg_count);
let mut block_x: usize = 0;
while block_x < seg_count {
let end_x: usize = (block_x + 4).min(seg_count);
for grid_z in block_z..end_z {
let quad_z0: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
let quad_z1: f32 = (((grid_z + 1) as f32) * inv_segs - 0.5) * outer_span;
for grid_x in block_x..end_x {
let quad_x0: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
let quad_x1: f32 = (((grid_x + 1) as f32) * inv_segs - 0.5) * outer_span;
let inside_x: bool = quad_x0 >= -cut_half_x && quad_x1 <= cut_half_x;
let inside_z: bool = quad_z0 >= -cut_half_z && quad_z1 <= cut_half_z;
if inside_x && inside_z {
continue;
}
let idx0: u32 = (grid_z as u32) * row_stride + (grid_x as u32);
let idx1: u32 = idx0 + 1;
let idx2: u32 = idx0 + row_stride;
let idx3: u32 = idx2 + 1;
indices.push([idx0, idx2, idx1]);
indices.push([idx1, idx2, idx3]);
}
}
block_x += 4;
}
block_z += 4;
}
Self::from_parts(name.to_string(), vertices, indices, material)
}
/// Builds the default sculpted GT supercar mesh (curved Lamborghini V12 supercar).
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary car body clearcoat paint PBR material.
///
/// # Returns
///
/// - `Self` - Composite smooth-shaded multi-material vehicle mesh.
#[must_use]
pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
Self::aventador_svj(name, material)
}
/// Builds an ultra-sculpted authentic Lamborghini (Revuelto / Aventador SVJ V12 DNA) supercar mesh with continuous Catmull-Rom curved bodywork, smooth normals, carved wheel arches, teardrop canopy, exposed V12 engine bay, Y-shaped LED headlights and taillights, swan-neck curved GT wing, multi-fin carbon diffuser, high-mounted central twin hexagonal titanium exhausts, and concave 10-spoke Y-pattern wheels.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary metallic pearlescent body paint PBR material.
///
/// # Returns
///
/// - `Self` - Closed smooth-shaded multi-material Lamborghini supercar mesh.
#[must_use]
pub fn aventador_svj(name: &str, material: PbrMaterial) -> Self {
build_lamborghini_supercar(name, material)
}
/// Builds an ultra-sculpted authentic Lamborghini Revuelto / Aventador SVJ V12 curved supercar mesh.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary metallic clearcoat paint PBR material.
///
/// # Returns
///
/// - `Self` - Closed smooth-shaded multi-material Lamborghini supercar mesh.
#[must_use]
pub fn lamborghini_revuelto(name: &str, material: PbrMaterial) -> Self {
build_lamborghini_supercar(name, material)
}
/// Builds an ultra-sculpted authentic 2025/2026 Ford Mustang S650 (Dark Horse / GT Fastback DNA) mesh with continuous Catmull-Rom curved Coke-bottle bodywork, domed power-bulge hood with heat extractor vent, trapezoidal S650 hex grille, tri-bar DRL brow and triple-projector LED headlamps, sweeping fastback roofline, concave gloss-black rear decklid with glowing tri-bar red LED taillights, sculpted diffuser with quad outboard dark-chrome exhaust tips, curved performance decklid spoiler, and split-5-spoke forged wheels with red Brembo calipers.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary metallic muscle-car paint PBR material.
///
/// # Returns
///
/// - `Self` - Closed smooth-shaded multi-material Ford Mustang S650 mesh.
#[must_use]
pub fn shelby_cobra(name: &str, material: PbrMaterial) -> Self {
build_mustang_s650_supercar(name, material)
}
/// Builds an ultra-sculpted authentic 2025/2026 Ford Mustang S650 Dark Horse / GT fastback supercar mesh.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary metallic clearcoat paint PBR material.
///
/// # Returns
///
/// - `Self` - Closed smooth-shaded multi-material Ford Mustang S650 mesh.
#[must_use]
pub fn mustang_s650(name: &str, material: PbrMaterial) -> Self {
build_mustang_s650_supercar(name, material)
}
/// Builds a smooth curved modern four-door executive NPC traffic sedan mesh.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary metallic exterior paint PBR material.
///
/// # Returns
///
/// - `Self` - Closed smooth-shaded multi-material modern NPC sedan mesh.
#[must_use]
pub fn npc_sedan(name: &str, material: PbrMaterial) -> Self {
build_npc_sedan(name, material)
}
/// Builds a smooth curved modern grand-tourer NPC traffic sport coupe mesh.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary metallic exterior paint PBR material.
///
/// # Returns
///
/// - `Self` - Closed smooth-shaded multi-material modern NPC sport coupe mesh.
#[must_use]
pub fn npc_coupe(name: &str, material: PbrMaterial) -> Self {
build_npc_coupe(name, material)
}
/// Builds a smooth curved modern luxury crossover NPC traffic SUV mesh.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `PbrMaterial` - Primary metallic exterior paint PBR material.
///
/// # Returns
///
/// - `Self` - Closed smooth-shaded multi-material modern NPC SUV mesh.
#[must_use]
pub fn npc_suv(name: &str, material: PbrMaterial) -> Self {
build_npc_suv(name, material)
}
/// Generates an 8-vertex CCW chamfered octagon ring centered at `(0, y, 0)` with flat cardinal walls at `±half_extent` and 45-degree corner bevels cut at `±chamfer_inner`, optionally rotated by `twist_rad` around `+Y`.
///
/// # Arguments
///
/// - `f32` - Elevation along Y.
/// - `f32` - Half-extent to flat cardinal walls.
/// - `f32` - Coordinate where diagonal corner bevel begins (`<= half_extent`).
/// - `f32` - Counter-clockwise rotation around `+Y` in radians.
///
/// # Returns
///
/// - `[Vec3; 8]` - Eight vertices ordered CCW when viewed from `+Y`.
fn building_chamfered_ring(
y_val: f32,
half_extent: f32,
chamfer_inner: f32,
twist_rad: f32,
) -> [Vec3; 8] {
let raw: [(f32, f32); 8] = [
(half_extent, chamfer_inner),
(half_extent, -chamfer_inner),
(chamfer_inner, -half_extent),
(-chamfer_inner, -half_extent),
(-half_extent, -chamfer_inner),
(-half_extent, chamfer_inner),
(-chamfer_inner, half_extent),
(chamfer_inner, half_extent),
];
let (sin_t, cos_t): (f32, f32) = twist_rad.sin_cos();
let mut ring: [Vec3; 8] = [Vec3::zero(); 8];
for (idx, &(rx, rz)) in raw.iter().enumerate() {
let rot_x: f32 = rx * cos_t + rz * sin_t;
let rot_z: f32 = -rx * sin_t + rz * cos_t;
ring[idx] = Vec3::new(rot_x, y_val, rot_z);
}
ring
}
/// Generates a 16-vertex CCW circular/slanted ring centered at `(0, y_base, 0)` with vertices aligned on cardinal axes `(±radius, 0)` and `(0, ±radius)`.
///
/// # Arguments
///
/// - `f32` - Base elevation along Y.
/// - `f32` - Ring radius in XZ (`<= 0.50`).
/// - `f32` - Linear Y slope applied along `+X` (`0.0` for horizontal rings).
///
/// # Returns
///
/// - `[Vec3; MESH_CYLINDER_TOWER_SEGMENTS]` - Sixteen vertices ordered CCW when viewed from `+Y`.
fn building_cylinder_ring(
y_base: f32,
radius: f32,
slope_x: f32,
) -> [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] {
let mut ring: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
[Vec3::zero(); MESH_CYLINDER_TOWER_SEGMENTS];
let step_rad: f32 = (2.0 * PI) / (MESH_CYLINDER_TOWER_SEGMENTS as f32);
for (idx, dst) in ring.iter_mut().enumerate() {
let angle: f32 = (idx as f32) * step_rad;
let (sin_a, cos_a): (f32, f32) = angle.sin_cos();
let px: f32 = cos_a * radius;
let pz: f32 = -sin_a * radius;
let py: f32 = y_base + cos_a * slope_x;
*dst = Vec3::new(px, py, pz);
}
ring
}
/// Builds the shared 4-slot architectural accent sub-material table (`slot 1` warm stone/titanium trim, `slot 2` smoked roof/mullion, `slot 3` champagne-bronze metallic ribs/spires, `slot 4` warm illuminated crown/soffit glow).
///
/// # Arguments
///
/// - `Color` - Stone/trim accent color (`slot 1`).
/// - `Color` - Metallic rib/spire accent color (`slot 3`).
/// - `Color` - Warm illuminated architectural glow color (`slot 4`).
///
/// # Returns
///
/// - `Vec<PbrMaterial>` - Four architectural accent sub-materials.
fn building_sub_materials(
trim_color: Color,
metal_color: Color,
glow_color: Color,
) -> Vec<PbrMaterial> {
vec![
PbrMaterial::pbr(trim_color, 0.22, 0.42, 0.32),
PbrMaterial::pbr(Color::hex(0x161D29), 0.36, 0.56, 0.24),
PbrMaterial::metallic(metal_color, 0.18),
PbrMaterial::neon(glow_color, 1.15),
]
}
/// Generates a 4-vertex CCW horizontal rectangular ring centered at `(center_x, y_val, center_z)` with half-extents `(half_x, half_z)`.
///
/// # Arguments
///
/// - `f32` - Horizontal X center coordinate.
/// - `f32` - Vertical elevation along Y.
/// - `f32` - Horizontal Z center coordinate.
/// - `f32` - Half extent along X.
/// - `f32` - Half extent along Z.
///
/// # Returns
///
/// - `[Vec3; 4]` - Four vertices ordered CCW when viewed from `+Y`.
fn building_rect_ring(
center_x: f32,
y_val: f32,
center_z: f32,
half_x: f32,
half_z: f32,
) -> [Vec3; 4] {
[
Vec3::new(center_x + half_x, y_val, center_z + half_z),
Vec3::new(center_x + half_x, y_val, center_z - half_z),
Vec3::new(center_x - half_x, y_val, center_z - half_z),
Vec3::new(center_x - half_x, y_val, center_z + half_z),
]
}
/// Generates a 4-vertex CCW cross-section ring oriented radially around `anchor` for continuous helical spire ribs.
///
/// # Arguments
///
/// - `Vec3` - Corner anchor point on the twisted tower perimeter.
/// - `f32` - Outward radial offset applied to the rib center.
/// - `f32` - Half thickness along the radial axis.
/// - `f32` - Half width along the horizontal tangent axis.
///
/// # Returns
///
/// - `[Vec3; 4]` - Four cross-section vertices ordered CCW when viewed from `+Y`.
fn building_rib_ring(
anchor: Vec3,
radial_offset: f32,
half_radial: f32,
half_tangent: f32,
) -> [Vec3; 4] {
let radial_horiz: Vec3 = Vec3::new(anchor.get_x(), 0.0, anchor.get_z());
let radial_dir: Vec3 = if radial_horiz.length_sq() > 1.0e-8 {
radial_horiz.normalize()
} else {
Vec3::new(1.0, 0.0, 0.0)
};
let tangent_dir: Vec3 = Vec3::new(radial_dir.get_z(), 0.0, -radial_dir.get_x());
let center: Vec3 = anchor.add(radial_dir.scale(radial_offset));
let radial_vec: Vec3 = radial_dir.scale(half_radial);
let tangent_vec: Vec3 = tangent_dir.scale(half_tangent);
[
center.add(radial_vec).sub(tangent_vec),
center.add(radial_vec).add(tangent_vec),
center.sub(radial_vec).add(tangent_vec),
center.sub(radial_vec).sub(tangent_vec),
]
}
/// Builds Archetype 1: an Art-Deco stepped setback skyscraper (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) featuring a grand stone podium, three tiered setbacks with vertical corner pilasters, an illuminated warm-gold crown pavilion, and a slender tapered spire.
///
/// # Arguments
///
/// - `&str` - Mesh asset name.
/// - `PbrMaterial` - Primary curtain-wall facade material (`slot 0`).
///
/// # Returns
///
/// - `Self` - Closed multi-material unit Art-Deco setback tower mesh.
#[must_use]
pub fn building_art_deco_tower(name: &str, material: PbrMaterial) -> Self {
let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
Color::hex(0x9A8970),
Color::hex(0xB89456),
Color::hex(0xFFCB6B),
);
let slot_facade: u16 = 0;
let slot_stone: u16 = 1;
let slot_roof: u16 = 2;
let slot_metal: u16 = 3;
let slot_glow: u16 = 4;
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(640);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(300);
let mut tri_materials: Vec<u16> = Vec::with_capacity(300);
let ring_base_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.000, 0.0, 0.480, 0.480);
let ring_base_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.160, 0.0, 0.480, 0.480);
let ring_pod_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.160, 0.0, 0.500, 0.500);
let ring_pod_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.188, 0.0, 0.500, 0.500);
let ring_mid_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.188, 0.0, 0.425, 0.425);
let ring_mid_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.550, 0.0, 0.425, 0.425);
let ring_mid_ledge_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.550, 0.0, 0.472, 0.472);
let ring_mid_ledge_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.578, 0.0, 0.472, 0.472);
let ring_upper_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.578, 0.0, 0.335, 0.335);
let ring_upper_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.750, 0.0, 0.335, 0.335);
let ring_upper_ledge_bot: [Vec3; 4] =
Self::building_rect_ring(0.0, 0.750, 0.0, 0.382, 0.382);
let ring_upper_ledge_top: [Vec3; 4] =
Self::building_rect_ring(0.0, 0.778, 0.0, 0.382, 0.382);
let ring_crown_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.778, 0.0, 0.235, 0.235);
let ring_crown_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.854, 0.0, 0.235, 0.235);
let ring_metal_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.854, 0.0, 0.255, 0.255);
let ring_metal_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.870, 0.0, 0.255, 0.255);
let ring_glow_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.870, 0.0, 0.160, 0.160);
let ring_glow_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.916, 0.0, 0.160, 0.160);
let ring_roof_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.916, 0.0, 0.176, 0.176);
let ring_roof_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.932, 0.0, 0.176, 0.176);
let ring_spire_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.932, 0.0, 0.072, 0.072);
let ring_spire_top: [Vec3; 4] = Self::building_rect_ring(0.0, 0.984, 0.0, 0.016, 0.016);
let ring_beacon_bot: [Vec3; 4] = Self::building_rect_ring(0.0, 0.984, 0.0, 0.022, 0.022);
let ring_beacon_top: [Vec3; 4] = Self::building_rect_ring(0.0, 1.000, 0.0, 0.018, 0.018);
let shell_rings: [(&[Vec3], u16); 24] = [
(&ring_base_bot, slot_roof),
(&ring_base_top, slot_facade),
(&ring_pod_bot, slot_stone),
(&ring_pod_top, slot_stone),
(&ring_mid_bot, slot_stone),
(&ring_mid_top, slot_facade),
(&ring_mid_ledge_bot, slot_stone),
(&ring_mid_ledge_top, slot_stone),
(&ring_upper_bot, slot_stone),
(&ring_upper_top, slot_facade),
(&ring_upper_ledge_bot, slot_stone),
(&ring_upper_ledge_top, slot_stone),
(&ring_crown_bot, slot_stone),
(&ring_crown_top, slot_facade),
(&ring_metal_bot, slot_metal),
(&ring_metal_top, slot_metal),
(&ring_glow_bot, slot_metal),
(&ring_glow_top, slot_glow),
(&ring_roof_bot, slot_roof),
(&ring_roof_top, slot_roof),
(&ring_spire_bot, slot_roof),
(&ring_spire_top, slot_metal),
(&ring_beacon_bot, slot_glow),
(&ring_beacon_top, slot_glow),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&shell_rings,
(slot_roof, slot_glow),
);
for sign_x in [-1.0_f32, 1.0_f32] {
for sign_z in [-1.0_f32, 1.0_f32] {
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(sign_x * 0.426, 0.369, sign_z * 0.426),
Vec3::new(0.060, 0.390, 0.060),
slot_metal,
);
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(sign_x * 0.336, 0.664, sign_z * 0.336),
Vec3::new(0.056, 0.200, 0.056),
slot_metal,
);
}
}
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
mesh.set_is_closed(true);
mesh
}
/// Builds Archetype 2: a chamfered octagonal modernist glass tower (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with horizontal structural sky-deck slab bands, a recessed illuminated mid-level sky-garden notch, and a sculpted angled roof parapet.
///
/// # Arguments
///
/// - `&str` - Mesh asset name.
/// - `PbrMaterial` - Primary glass curtain-wall material (`slot 0`).
///
/// # Returns
///
/// - `Self` - Closed multi-material unit chamfered glass tower mesh.
#[must_use]
pub fn building_chamfered_glass_tower(name: &str, material: PbrMaterial) -> Self {
let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
Color::hex(0x64748B),
Color::hex(0x94A3B8),
Color::hex(0x7DD3FC),
);
let slot_facade: u16 = 0;
let slot_slab: u16 = 1;
let slot_roof: u16 = 2;
let slot_metal: u16 = 3;
let slot_glow: u16 = 4;
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(960);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(460);
let mut tri_materials: Vec<u16> = Vec::with_capacity(460);
let ring_00: [Vec3; 8] = Self::building_chamfered_ring(0.000, 0.480, 0.315, 0.0);
let ring_01: [Vec3; 8] = Self::building_chamfered_ring(0.140, 0.480, 0.315, 0.0);
let ring_02: [Vec3; 8] = Self::building_chamfered_ring(0.140, 0.500, 0.335, 0.0);
let ring_03: [Vec3; 8] = Self::building_chamfered_ring(0.164, 0.500, 0.335, 0.0);
let ring_04: [Vec3; 8] = Self::building_chamfered_ring(0.164, 0.480, 0.315, 0.0);
let ring_05: [Vec3; 8] = Self::building_chamfered_ring(0.330, 0.480, 0.315, 0.0);
let ring_06: [Vec3; 8] = Self::building_chamfered_ring(0.330, 0.500, 0.335, 0.0);
let ring_07: [Vec3; 8] = Self::building_chamfered_ring(0.354, 0.500, 0.335, 0.0);
let ring_08: [Vec3; 8] = Self::building_chamfered_ring(0.354, 0.480, 0.315, 0.0);
let ring_09: [Vec3; 8] = Self::building_chamfered_ring(0.508, 0.480, 0.315, 0.0);
let ring_10: [Vec3; 8] = Self::building_chamfered_ring(0.508, 0.500, 0.335, 0.0);
let ring_11: [Vec3; 8] = Self::building_chamfered_ring(0.536, 0.500, 0.335, 0.0);
let ring_12: [Vec3; 8] = Self::building_chamfered_ring(0.536, 0.380, 0.250, 0.0);
let ring_13: [Vec3; 8] = Self::building_chamfered_ring(0.614, 0.380, 0.250, 0.0);
let ring_14: [Vec3; 8] = Self::building_chamfered_ring(0.614, 0.495, 0.330, 0.0);
let ring_15: [Vec3; 8] = Self::building_chamfered_ring(0.642, 0.495, 0.330, 0.0);
let ring_16: [Vec3; 8] = Self::building_chamfered_ring(0.642, 0.475, 0.310, 0.0);
let ring_17: [Vec3; 8] = Self::building_chamfered_ring(0.760, 0.475, 0.310, 0.0);
let ring_18: [Vec3; 8] = Self::building_chamfered_ring(0.760, 0.495, 0.330, 0.0);
let ring_19: [Vec3; 8] = Self::building_chamfered_ring(0.784, 0.495, 0.330, 0.0);
let ring_20: [Vec3; 8] = Self::building_chamfered_ring(0.784, 0.475, 0.310, 0.0);
let ring_21: [Vec3; 8] = Self::building_chamfered_ring(0.884, 0.475, 0.310, 0.0);
let ring_22: [Vec3; 8] = Self::building_chamfered_ring(0.884, 0.492, 0.324, 0.0);
let ring_23: [Vec3; 8] = Self::building_chamfered_ring(0.912, 0.492, 0.324, 0.0);
let mut ring_24: [Vec3; 8] = Self::building_chamfered_ring(0.962, 0.475, 0.310, 0.0);
for corner in ring_24.iter_mut() {
let slope_y: f32 = corner.get_y() + corner.get_x() * 0.075;
corner.set_y(slope_y.min(1.0));
}
let shell_rings: [(&[Vec3], u16); 25] = [
(&ring_00, slot_roof),
(&ring_01, slot_facade),
(&ring_02, slot_slab),
(&ring_03, slot_slab),
(&ring_04, slot_slab),
(&ring_05, slot_facade),
(&ring_06, slot_slab),
(&ring_07, slot_slab),
(&ring_08, slot_slab),
(&ring_09, slot_facade),
(&ring_10, slot_slab),
(&ring_11, slot_slab),
(&ring_12, slot_slab),
(&ring_13, slot_facade),
(&ring_14, slot_glow),
(&ring_15, slot_slab),
(&ring_16, slot_slab),
(&ring_17, slot_facade),
(&ring_18, slot_slab),
(&ring_19, slot_slab),
(&ring_20, slot_slab),
(&ring_21, slot_facade),
(&ring_22, slot_glow),
(&ring_23, slot_glow),
(&ring_24, slot_metal),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&shell_rings,
(slot_roof, slot_roof),
);
for sign_x in [-1.0_f32, 1.0_f32] {
for sign_z in [-1.0_f32, 1.0_f32] {
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(sign_x * 0.365, 0.575, sign_z * 0.365),
Vec3::new(0.058, 0.106, 0.058),
slot_metal,
);
}
}
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
mesh.set_is_closed(true);
mesh
}
/// Builds Archetype 3: a twisted tapering futuristic spire (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with helical metallic exoskeletal ribs, a glowing observation rim band, and an asymmetrical diagonal roof fin.
///
/// # Arguments
///
/// - `&str` - Mesh asset name.
/// - `PbrMaterial` - Primary curtain-wall facade material (`slot 0`).
///
/// # Returns
///
/// - `Self` - Closed multi-material unit twisted spire mesh.
#[must_use]
pub fn building_twisted_spire_tower(name: &str, material: PbrMaterial) -> Self {
let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
Color::hex(0x334155),
Color::hex(0xD8E2EE),
Color::hex(0x38BDF8),
);
let slot_facade: u16 = 0;
let slot_base: u16 = 1;
let slot_roof: u16 = 2;
let slot_metal: u16 = 3;
let slot_glow: u16 = 4;
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(820);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(380);
let mut tri_materials: Vec<u16> = Vec::with_capacity(380);
let base_lo: [Vec3; 8] = Self::building_chamfered_ring(0.000, 0.500, 0.340, 0.00);
let base_hi: [Vec3; 8] = Self::building_chamfered_ring(0.120, 0.490, 0.330, 0.00);
let tier_0: [Vec3; 8] = Self::building_chamfered_ring(0.120, 0.450, 0.300, 0.00);
let tier_1: [Vec3; 8] = Self::building_chamfered_ring(0.320, 0.410, 0.270, 0.16);
let tier_2: [Vec3; 8] = Self::building_chamfered_ring(0.520, 0.360, 0.240, 0.32);
let tier_3: [Vec3; 8] = Self::building_chamfered_ring(0.700, 0.310, 0.200, 0.48);
let tier_4: [Vec3; 8] = Self::building_chamfered_ring(0.836, 0.260, 0.170, 0.62);
let glow_lo: [Vec3; 8] = Self::building_chamfered_ring(0.836, 0.278, 0.184, 0.62);
let glow_hi: [Vec3; 8] = Self::building_chamfered_ring(0.864, 0.278, 0.184, 0.62);
let cap_hi: [Vec3; 8] = Self::building_chamfered_ring(0.892, 0.256, 0.168, 0.62);
let shell_rings: [(&[Vec3], u16); 10] = [
(&base_lo, slot_roof),
(&base_hi, slot_base),
(&tier_0, slot_roof),
(&tier_1, slot_facade),
(&tier_2, slot_facade),
(&tier_3, slot_facade),
(&tier_4, slot_facade),
(&glow_lo, slot_glow),
(&glow_hi, slot_glow),
(&cap_hi, slot_base),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&shell_rings,
(slot_roof, slot_roof),
);
let rib_anchor_bot: [Vec3; 8] = Self::building_chamfered_ring(0.105, 0.453, 0.302, 0.00);
let rib_anchor_top: [Vec3; 8] = Self::building_chamfered_ring(0.850, 0.258, 0.169, 0.62);
for rib_idx in [0usize, 2usize, 4usize, 6usize] {
let rib_r0: [Vec3; 4] =
Self::building_rib_ring(rib_anchor_bot[rib_idx], 0.006, 0.018, 0.018);
let rib_r1: [Vec3; 4] = Self::building_rib_ring(tier_1[rib_idx], 0.006, 0.018, 0.018);
let rib_r2: [Vec3; 4] = Self::building_rib_ring(tier_2[rib_idx], 0.006, 0.018, 0.018);
let rib_r3: [Vec3; 4] = Self::building_rib_ring(tier_3[rib_idx], 0.006, 0.018, 0.018);
let rib_r4: [Vec3; 4] =
Self::building_rib_ring(rib_anchor_top[rib_idx], 0.006, 0.018, 0.018);
let rib_rings: [(&[Vec3], u16); 5] = [
(&rib_r0, slot_metal),
(&rib_r1, slot_metal),
(&rib_r2, slot_metal),
(&rib_r3, slot_metal),
(&rib_r4, slot_metal),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&rib_rings,
(slot_metal, slot_metal),
);
}
let fin_bot: [Vec3; 4] = [
Vec3::new(-0.18, 0.878, 0.075),
Vec3::new(0.20, 0.878, 0.075),
Vec3::new(0.20, 0.878, -0.075),
Vec3::new(-0.18, 0.878, -0.075),
];
let fin_top: [Vec3; 4] = [
Vec3::new(0.06, 1.000, 0.045),
Vec3::new(0.20, 0.990, 0.045),
Vec3::new(0.20, 0.990, -0.045),
Vec3::new(0.06, 1.000, -0.045),
];
Self::push_tapered_prism(
&mut vertices,
&mut indices,
&mut tri_materials,
fin_bot,
fin_top,
[slot_metal; 6],
);
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
mesh.set_is_closed(true);
mesh
}
/// Builds Archetype 4: a cantilevered contemporary tech and cultural tower (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with a sleek glass podium, recessed atrium waist, boldly offset upper cantilevered volumes with warm illuminated overhang soffits, and a rooftop louver pergola.
///
/// # Arguments
///
/// - `&str` - Mesh asset name.
/// - `PbrMaterial` - Primary curtain-wall facade material (`slot 0`).
///
/// # Returns
///
/// - `Self` - Closed multi-material unit cantilevered tower mesh.
#[must_use]
pub fn building_cantilever_tech_tower(name: &str, material: PbrMaterial) -> Self {
let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
Color::hex(0x475569),
Color::hex(0xCBD5E1),
Color::hex(0xFBBF24),
);
let slot_facade: u16 = 0;
let slot_frame: u16 = 1;
let slot_roof: u16 = 2;
let slot_metal: u16 = 3;
let slot_glow: u16 = 4;
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(680);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(320);
let mut tri_materials: Vec<u16> = Vec::with_capacity(320);
let lower_r0: [Vec3; 4] = Self::building_rect_ring(0.0, 0.000, 0.0, 0.480, 0.480);
let lower_r1: [Vec3; 4] = Self::building_rect_ring(0.0, 0.208, 0.0, 0.480, 0.480);
let lower_r2: [Vec3; 4] = Self::building_rect_ring(0.0, 0.208, 0.0, 0.500, 0.500);
let lower_r3: [Vec3; 4] = Self::building_rect_ring(0.0, 0.236, 0.0, 0.500, 0.500);
let lower_r4: [Vec3; 4] = Self::building_rect_ring(0.0, 0.236, 0.0, 0.310, 0.310);
let lower_r5: [Vec3; 4] = Self::building_rect_ring(0.0, 0.436, 0.0, 0.310, 0.310);
let mid_r0: [Vec3; 4] = Self::building_rect_ring(-0.06, 0.436, 0.02, 0.400, 0.440);
let mid_r1: [Vec3; 4] = Self::building_rect_ring(-0.06, 0.456, 0.02, 0.400, 0.440);
let mid_r2: [Vec3; 4] = Self::building_rect_ring(-0.06, 0.456, 0.02, 0.415, 0.455);
let mid_r3: [Vec3; 4] = Self::building_rect_ring(-0.06, 0.690, 0.02, 0.415, 0.455);
let mid_r4: [Vec3; 4] = Self::building_rect_ring(-0.06, 0.690, 0.02, 0.430, 0.460);
let mid_r5: [Vec3; 4] = Self::building_rect_ring(-0.06, 0.718, 0.02, 0.430, 0.460);
let lower_mid_rings: [(&[Vec3], u16); 12] = [
(&lower_r0, slot_roof),
(&lower_r1, slot_facade),
(&lower_r2, slot_frame),
(&lower_r3, slot_frame),
(&lower_r4, slot_frame),
(&lower_r5, slot_facade),
(&mid_r0, slot_glow),
(&mid_r1, slot_glow),
(&mid_r2, slot_facade),
(&mid_r3, slot_facade),
(&mid_r4, slot_frame),
(&mid_r5, slot_frame),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&lower_mid_rings,
(slot_roof, slot_frame),
);
let upper_r0: [Vec3; 4] = Self::building_rect_ring(0.08, 0.704, -0.02, 0.380, 0.440);
let upper_r1: [Vec3; 4] = Self::building_rect_ring(0.08, 0.732, -0.02, 0.380, 0.440);
let upper_r2: [Vec3; 4] = Self::building_rect_ring(0.08, 0.732, -0.02, 0.400, 0.460);
let upper_r3: [Vec3; 4] = Self::building_rect_ring(0.08, 0.922, -0.02, 0.400, 0.460);
let upper_r4: [Vec3; 4] = Self::building_rect_ring(0.08, 0.922, -0.02, 0.420, 0.480);
let upper_r5: [Vec3; 4] = Self::building_rect_ring(0.08, 0.950, -0.02, 0.420, 0.480);
let upper_rings: [(&[Vec3], u16); 6] = [
(&upper_r0, slot_glow),
(&upper_r1, slot_glow),
(&upper_r2, slot_facade),
(&upper_r3, slot_facade),
(&upper_r4, slot_roof),
(&upper_r5, slot_roof),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&upper_rings,
(slot_glow, slot_roof),
);
for post_x in [-0.26_f32, 0.42_f32] {
for post_z in [-0.40_f32, 0.36_f32] {
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(post_x, 0.9615, post_z),
Vec3::new(0.040, 0.051, 0.040),
slot_metal,
);
}
}
for beam_idx in 0..5usize {
let beam_z: f32 = -0.38 + (beam_idx as f32) * 0.19;
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(0.08, 0.987, beam_z),
Vec3::new(0.76, 0.026, 0.044),
slot_metal,
);
}
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
mesh.set_is_closed(true);
mesh
}
/// Builds Archetype 5: a 16-sided smooth cylindrical landmark glass tower (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with a recessed lobby colonnade, horizontal metallic floor-slab rings, and a sculpted slanted crown.
///
/// # Arguments
///
/// - `&str` - Mesh asset name.
/// - `PbrMaterial` - Primary curved glass facade material (`slot 0`).
///
/// # Returns
///
/// - `Self` - Closed multi-material unit cylindrical landmark mesh.
#[must_use]
pub fn building_cylindrical_landmark(name: &str, material: PbrMaterial) -> Self {
let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
Color::hex(0xCBD5E1),
Color::hex(0xE2E8F0),
Color::hex(0x34D399),
);
let slot_facade: u16 = 0;
let slot_stone: u16 = 1;
let slot_roof: u16 = 2;
let slot_metal: u16 = 3;
let slot_glow: u16 = 4;
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(1400);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(680);
let mut tri_materials: Vec<u16> = Vec::with_capacity(680);
let ring_00: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.000, 0.380, 0.0);
let ring_01: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.136, 0.380, 0.0);
let ring_02: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.136, 0.500, 0.0);
let ring_03: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.166, 0.500, 0.0);
let ring_04: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.166, 0.478, 0.0);
let ring_05: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.376, 0.478, 0.0);
let ring_06: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.376, 0.500, 0.0);
let ring_07: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.398, 0.500, 0.0);
let ring_08: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.398, 0.478, 0.0);
let ring_09: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.596, 0.478, 0.0);
let ring_10: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.596, 0.500, 0.0);
let ring_11: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.618, 0.500, 0.0);
let ring_12: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.618, 0.478, 0.0);
let ring_13: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.806, 0.478, 0.0);
let ring_14: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.806, 0.500, 0.0);
let ring_15: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.828, 0.500, 0.0);
let ring_16: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.828, 0.478, 0.0);
let ring_17: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.850, 0.478, 0.0);
let ring_18: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.850, 0.498, 0.0);
let ring_19: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.870, 0.498, 0.0);
let ring_20: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.870, 0.482, 0.0);
let ring_21: [Vec3; MESH_CYLINDER_TOWER_SEGMENTS] =
Self::building_cylinder_ring(0.945, 0.456, 0.052);
let shell_rings: [(&[Vec3], u16); 22] = [
(&ring_00, slot_roof),
(&ring_01, slot_facade),
(&ring_02, slot_stone),
(&ring_03, slot_stone),
(&ring_04, slot_stone),
(&ring_05, slot_facade),
(&ring_06, slot_metal),
(&ring_07, slot_metal),
(&ring_08, slot_metal),
(&ring_09, slot_facade),
(&ring_10, slot_metal),
(&ring_11, slot_metal),
(&ring_12, slot_metal),
(&ring_13, slot_facade),
(&ring_14, slot_metal),
(&ring_15, slot_metal),
(&ring_16, slot_metal),
(&ring_17, slot_facade),
(&ring_18, slot_glow),
(&ring_19, slot_glow),
(&ring_20, slot_glow),
(&ring_21, slot_metal),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&shell_rings,
(slot_roof, slot_roof),
);
let column_step: f32 = (2.0 * PI) / 8.0;
for column_idx in 0..8usize {
let column_angle: f32 = (column_idx as f32) * column_step;
let (sin_col, cos_col): (f32, f32) = column_angle.sin_cos();
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(cos_col * 0.440, 0.0755, -sin_col * 0.440),
Vec3::new(0.060, 0.151, 0.060),
slot_stone,
);
}
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
mesh.set_is_closed(true);
mesh
}
/// Builds Archetype 6: a human-scale boutique neo-classical mid-rise boulevard podium block (`[-0.5, +0.5]` unit footprint, `y in [0, 1]`) with a recessed warm-lit ground-floor retail arcade colonnade, projecting stone cornices, pilasters, terraced penthouse setback, and rooftop warm accent lighting.
///
/// # Arguments
///
/// - `&str` - Mesh asset name.
/// - `PbrMaterial` - Primary architectural facade material (`slot 0`).
///
/// # Returns
///
/// - `Self` - Closed multi-material unit boutique boulevard podium mesh.
#[must_use]
pub fn building_boutique_podium_block(name: &str, material: PbrMaterial) -> Self {
let sub_materials: Vec<PbrMaterial> = Self::building_sub_materials(
Color::hex(0xA6957C),
Color::hex(0x9B7B4A),
Color::hex(0xFDE68A),
);
let slot_facade: u16 = 0;
let slot_stone: u16 = 1;
let slot_roof: u16 = 2;
let slot_metal: u16 = 3;
let slot_glow: u16 = 4;
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(760);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(360);
let mut tri_materials: Vec<u16> = Vec::with_capacity(360);
let ring_00: [Vec3; 4] = Self::building_rect_ring(0.0, 0.000, 0.0, 0.380, 0.380);
let ring_01: [Vec3; 4] = Self::building_rect_ring(0.0, 0.220, 0.0, 0.380, 0.380);
let ring_02: [Vec3; 4] = Self::building_rect_ring(0.0, 0.220, 0.0, 0.396, 0.396);
let ring_03: [Vec3; 4] = Self::building_rect_ring(0.0, 0.256, 0.0, 0.396, 0.396);
let ring_04: [Vec3; 4] = Self::building_rect_ring(0.0, 0.256, 0.0, 0.380, 0.380);
let ring_05: [Vec3; 4] = Self::building_rect_ring(0.0, 0.280, 0.0, 0.380, 0.380);
let ring_06: [Vec3; 4] = Self::building_rect_ring(0.0, 0.280, 0.0, 0.500, 0.500);
let ring_07: [Vec3; 4] = Self::building_rect_ring(0.0, 0.330, 0.0, 0.500, 0.500);
let ring_08: [Vec3; 4] = Self::building_rect_ring(0.0, 0.330, 0.0, 0.455, 0.455);
let ring_09: [Vec3; 4] = Self::building_rect_ring(0.0, 0.750, 0.0, 0.455, 0.455);
let ring_10: [Vec3; 4] = Self::building_rect_ring(0.0, 0.750, 0.0, 0.500, 0.500);
let ring_11: [Vec3; 4] = Self::building_rect_ring(0.0, 0.800, 0.0, 0.500, 0.500);
let ring_12: [Vec3; 4] = Self::building_rect_ring(0.0, 0.800, 0.0, 0.330, 0.330);
let ring_13: [Vec3; 4] = Self::building_rect_ring(0.0, 0.932, 0.0, 0.330, 0.330);
let ring_14: [Vec3; 4] = Self::building_rect_ring(0.0, 0.932, 0.0, 0.352, 0.352);
let ring_15: [Vec3; 4] = Self::building_rect_ring(0.0, 0.954, 0.0, 0.352, 0.352);
let ring_16: [Vec3; 4] = Self::building_rect_ring(0.0, 0.954, 0.0, 0.320, 0.320);
let ring_17: [Vec3; 4] = Self::building_rect_ring(0.0, 0.982, 0.0, 0.320, 0.320);
let shell_rings: [(&[Vec3], u16); 18] = [
(&ring_00, slot_roof),
(&ring_01, slot_facade),
(&ring_02, slot_glow),
(&ring_03, slot_glow),
(&ring_04, slot_glow),
(&ring_05, slot_facade),
(&ring_06, slot_stone),
(&ring_07, slot_stone),
(&ring_08, slot_stone),
(&ring_09, slot_facade),
(&ring_10, slot_stone),
(&ring_11, slot_stone),
(&ring_12, slot_stone),
(&ring_13, slot_facade),
(&ring_14, slot_roof),
(&ring_15, slot_roof),
(&ring_16, slot_roof),
(&ring_17, slot_glow),
];
Self::push_stepped_polygon_shell(
&mut vertices,
&mut indices,
&mut tri_materials,
&shell_rings,
(slot_roof, slot_roof),
);
let pier_coords: [f32; 3] = [-0.448, 0.0, 0.448];
for &pier_x in pier_coords.iter() {
for &pier_z in pier_coords.iter() {
if pier_x.abs() < 0.01 && pier_z.abs() < 0.01 {
continue;
}
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(pier_x, 0.148, pier_z),
Vec3::new(0.072, 0.296, 0.072),
slot_stone,
);
}
}
for sign_x in [-1.0_f32, 1.0_f32] {
for sign_z in [-1.0_f32, 1.0_f32] {
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(sign_x * 0.454, 0.5445, sign_z * 0.454),
Vec3::new(0.064, 0.461, 0.064),
slot_stone,
);
}
}
for rail_x in [-0.280_f32, 0.280_f32] {
Self::push_box_part(
&mut vertices,
&mut indices,
&mut tri_materials,
Vec3::new(rail_x, 0.984, 0.0),
Vec3::new(0.036, 0.032, 0.600),
slot_metal,
);
}
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
mesh.set_is_closed(true);
mesh
}
/// Builds an instanced Vice Boulevard coastal palm tree with a gracefully leaning segmented trunk and seven arching multi-segment tropical fronds.
///
/// # Arguments
///
/// - `&str` - Asset name.
///
/// # Returns
///
/// - `Self` - Multi-material palm tree mesh (`slot 0` warm bark trunk, `slot 1` emerald tropical fronds).
#[must_use]
pub fn palm_tree(name: &str) -> Self {
let bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
let frond_top_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x227848), 0.05, 0.56, 0.08);
let frond_under_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x134A2D), 0.04, 0.68, 0.05);
let sub_materials: Vec<PbrMaterial> = vec![frond_top_mat, frond_under_mat];
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(520);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(260);
let mut tri_materials: Vec<u16> = Vec::with_capacity(260);
let ring_specs: [(f32, f32, f32, f32); 5] = [
(0.0, 0.0, 0.0, 0.30),
(1.9, 0.14, 0.05, 0.25),
(3.9, 0.32, 0.08, 0.21),
(5.8, 0.44, 0.06, 0.17),
(7.5, 0.48, 0.02, 0.14),
];
let trunk_step: f32 = (2.0 * PI) / (MESH_PALM_TRUNK_SEGMENTS as f32);
for seg_idx in 0..4usize {
let (y0, ox0, oz0, r0): (f32, f32, f32, f32) = ring_specs[seg_idx];
let (y1, ox1, oz1, r1): (f32, f32, f32, f32) = ring_specs[seg_idx + 1];
for side_idx in 0..MESH_PALM_TRUNK_SEGMENTS {
let a0: f32 = (side_idx as f32) * trunk_step;
let a1: f32 = ((side_idx + 1) as f32) * trunk_step;
let (s0, c0): (f32, f32) = a0.sin_cos();
let (s1, c1): (f32, f32) = a1.sin_cos();
let p0: Vec3 = Vec3::new(ox0 + c0 * r0, y0, oz0 + s0 * r0);
let p1: Vec3 = Vec3::new(ox0 + c1 * r0, y0, oz0 + s1 * r0);
let p2: Vec3 = Vec3::new(ox1 + c1 * r1, y1, oz1 + s1 * r1);
let p3: Vec3 = Vec3::new(ox1 + c0 * r1, y1, oz1 + s0 * r1);
Self::push_flat_quad(
&mut vertices,
&mut indices,
&mut tri_materials,
[p0, p1, p2, p3],
0,
);
}
}
let crown: Vec3 = Vec3::new(0.48, 7.45, 0.02);
let frond_step: f32 = (2.0 * PI) / (MESH_PALM_FROND_COUNT as f32);
for tier_idx in 0..2usize {
let tier_count: usize = if tier_idx == 0 {
MESH_PALM_FROND_COUNT
} else {
5
};
let tier_step: f32 = if tier_idx == 0 {
frond_step
} else {
(2.0 * PI) / 5.0
};
let tier_yaw_off: f32 = if tier_idx == 0 { 0.25 } else { 0.62 };
let tier_origin: Vec3 = crown.add(Vec3::new(0.0, (tier_idx as f32) * 0.22, 0.0));
for frond_idx in 0..tier_count {
let yaw: f32 = (frond_idx as f32) * tier_step + tier_yaw_off;
let (sy, cy): (f32, f32) = yaw.sin_cos();
let dir: Vec3 = Vec3::new(cy, 0.0, sy);
let right: Vec3 = Vec3::new(-sy, 0.0, cy);
let reach: f32 = if tier_idx == 0 {
if frond_idx % 2 == 0 { 2.85 } else { 2.45 }
} else {
1.85
};
let lift: f32 = if tier_idx == 0 { 0.48 } else { 0.92 };
let drop_tip: f32 = if tier_idx == 0 { -1.18 } else { -0.18 };
let p_mid: Vec3 = tier_origin
.add(dir.scale(reach * 0.44))
.add(Vec3::new(0.0, lift, 0.0));
let p_arch: Vec3 = tier_origin.add(dir.scale(reach * 0.78)).add(Vec3::new(
0.0,
lift * 0.15 - 0.12,
0.0,
));
let p_tip: Vec3 = tier_origin
.add(dir.scale(reach))
.add(Vec3::new(0.0, drop_tip, 0.0));
let w_mid: Vec3 = right.scale(if tier_idx == 0 { 0.34 } else { 0.26 });
let w_arch: Vec3 = right.scale(if tier_idx == 0 { 0.24 } else { 0.18 });
let sag_mid: Vec3 = Vec3::new(0.0, -0.16, 0.0);
let sag_arch: Vec3 = Vec3::new(0.0, -0.20, 0.0);
let mid_l: Vec3 = p_mid.sub(w_mid).add(sag_mid);
let mid_r: Vec3 = p_mid.add(w_mid).add(sag_mid);
let arch_l: Vec3 = p_arch.sub(w_arch).add(sag_arch);
let arch_r: Vec3 = p_arch.add(w_arch).add(sag_arch);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(tier_origin, p_mid, mid_l),
1,
);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(tier_origin, mid_r, p_mid),
1,
);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(tier_origin, mid_l, p_mid),
2,
);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(tier_origin, p_mid, mid_r),
2,
);
Self::push_flat_quad(
&mut vertices,
&mut indices,
&mut tri_materials,
[mid_l, p_mid, p_arch, arch_l],
1,
);
Self::push_flat_quad(
&mut vertices,
&mut indices,
&mut tri_materials,
[p_mid, mid_r, arch_r, p_arch],
1,
);
Self::push_flat_quad(
&mut vertices,
&mut indices,
&mut tri_materials,
[arch_l, p_arch, p_mid, mid_l],
2,
);
Self::push_flat_quad(
&mut vertices,
&mut indices,
&mut tri_materials,
[p_arch, arch_r, mid_r, p_mid],
2,
);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(arch_l, p_arch, p_tip),
1,
);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(p_arch, arch_r, p_tip),
1,
);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(p_arch, arch_l, p_tip),
2,
);
Self::push_flat_tri(
&mut vertices,
&mut indices,
&mut tri_materials,
(arch_r, p_arch, p_tip),
2,
);
}
}
let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, bark_mat);
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
mesh.set_is_closed(false);
mesh
}
/// Builds a box mesh from a fluent `BoxMeshDesc`.
///
/// # Arguments
///
/// - `&BoxMeshDesc` - Box mesh descriptor.
///
/// # Returns
///
/// - `Self` - Indexed 12-triangle box mesh.
#[must_use]
pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
let size: Vec3 = desc.get_size();
Self::box_mesh(
desc.get_name(),
size.get_x(),
size.get_y(),
size.get_z(),
desc.get_ground_pivot(),
desc.get_material(),
)
}
/// Builds a subdivided ground plane from a fluent `GroundPlaneDesc`.
///
/// # Arguments
///
/// - `&GroundPlaneDesc` - Ground plane descriptor.
///
/// # Returns
///
/// - `Self` - Subdivided ground plane mesh.
#[must_use]
pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
Self::ground_plane(
desc.get_name(),
desc.get_width(),
desc.get_depth(),
desc.get_subdivisions(),
desc.get_material(),
)
}
/// Builds a simplified proxy mesh enclosing this mesh's axis-aligned bounding box for distant LOD tiers.
///
/// # Arguments
///
/// - `&Self` - Source mesh reference.
/// - `&str` - LOD suffix label.
///
/// # Returns
///
/// - `Self` - Lightweight 12-triangle LOD proxy mesh.
#[must_use]
pub fn build_lod_proxy(&self, suffix: &str) -> Self {
let blue_val: AxisAlignedBox3D = self.get_bounds();
let size: Vec3 = blue_val.get_max().sub(blue_val.get_min());
let center: Vec3 = blue_val.center();
let mut proxy: Self = Self::box_mesh(
&format!("{}_{suffix}", self.get_name()),
size.get_x().max(0.2),
size.get_y().max(0.2),
size.get_z().max(0.2),
false,
self.get_material(),
);
for item_val in proxy.get_mut_vertices().iter_mut() {
item_val.set_position(item_val.get_position().add(center));
}
proxy.set_bounds(blue_val);
let meshlets: Vec<Meshlet3D> =
Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
proxy.set_meshlets(meshlets);
proxy
}
/// Produces a mid-detail decimated mesh by retaining dominant triangles while preserving bounding silhouette.
///
/// # Arguments
///
/// - `&Self` - Source mesh reference.
/// - `&str` - LOD suffix label.
///
/// # Returns
///
/// - `Self` - Decimated intermediate LOD mesh.
#[must_use]
pub fn build_mid_lod(&self, suffix: &str) -> Self {
let verts: &[Vertex3D] = self.get_vertices().as_slice();
let tris: &[[u32; 3]] = self.get_indices().as_slice();
if tris.len() <= 24 {
return self.build_lod_proxy(suffix);
}
let mut scored: Vec<(f32, [u32; 3], u16)> = Vec::with_capacity(tris.len());
let default_mat: PbrMaterial = self.get_material();
for (tri_idx, tri) in tris.iter().copied().enumerate() {
let (i0, i1, i2): (usize, usize, usize) =
(tri[0] as usize, tri[1] as usize, tri[2] as usize);
if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
let p0: Vec3 = verts[i0].get_position();
let p1: Vec3 = verts[i1].get_position();
let p2: Vec3 = verts[i2].get_position();
let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
let (resolved_mat, slot): (PbrMaterial, u16) =
self.resolve_triangle_material(tri_idx, default_mat);
let emissive_boost: f32 = if resolved_mat.get_emissive().length_sq() > 0.25 {
8.0
} else {
1.0
};
scored.push((area2 * emissive_boost, tri, slot));
}
}
scored.sort_unstable_by(
|alpha_val: &(f32, [u32; 3], u16), blue_val: &(f32, [u32; 3], u16)| {
blue_val.0.total_cmp(&alpha_val.0)
},
);
let keep: usize = (scored.len() / 2).max(12);
let mut reduced: Vec<[u32; 3]> = Vec::with_capacity(keep);
let mut reduced_slots: Vec<u16> = if self.get_tri_materials().is_empty() {
Vec::new()
} else {
Vec::with_capacity(keep)
};
for (_, tri, slot) in scored.into_iter().take(keep) {
reduced.push(tri);
if !self.get_tri_materials().is_empty() {
reduced_slots.push(slot);
}
}
let mut mid_mesh: Self = Self::from_parts(
format!("{}_{suffix}", self.get_name()),
self.get_vertices().clone(),
reduced,
self.get_material(),
);
if !reduced_slots.is_empty() {
mid_mesh.set_sub_materials(self.get_sub_materials().clone());
mid_mesh.set_tri_materials(reduced_slots);
}
mid_mesh.set_is_closed(self.get_is_closed());
mid_mesh
}
}
/// Multi-level continuous LOD chain creation and screen-error selection for `MeshLodChain`.
impl MeshLodChain {
/// Builds a continuous 3-tier Nanite-style LOD chain (`LOD0` full -> `LOD1` mid -> `LOD2` proxy) automatically.
///
/// # Arguments
///
/// - `Mesh3D` - Full-resolution `LOD0` mesh.
///
/// # Returns
///
/// - `Self` - Ready LOD chain.
#[must_use]
pub fn from_mesh(mesh: Mesh3D) -> Self {
let tri_count: usize = mesh.get_indices().len();
if tri_count > 32 {
let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
Self {
levels: vec![mesh, lod1, lod2],
}
} else if tri_count > 16 {
let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
Self {
levels: vec![mesh, lod1],
}
} else {
let clone_lod1: Mesh3D = mesh.clone();
Self {
levels: vec![mesh, clone_lod1],
}
}
}
/// Wraps a sculpted hero or foliage mesh in a single-level LOD chain so it never degrades into an opaque bounding-box proxy.
///
/// # Arguments
///
/// - `Mesh3D` - Full-resolution `LOD0` mesh.
///
/// # Returns
///
/// - `Self` - Single-tier LOD chain preserving exact silhouette at all distances.
#[must_use]
pub fn single_level(mesh: Mesh3D) -> Self {
Self { levels: vec![mesh] }
}
/// Selects the appropriate `Mesh3D` detail level for `distance` and `lod_bias`.
///
/// # Arguments
///
/// - `&Self` - LOD chain reference.
/// - `f32` - Camera-to-object distance in meters.
/// - `f32` - Quality LOD bias multiplier.
///
/// # Returns
///
/// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
#[must_use]
pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
let levels: &[Mesh3D] = self.get_levels().as_slice();
let effective_dist: f32 = distance * lod_bias.max(0.25);
if levels.len() > 2 && effective_dist > 135.0 {
(&levels[2], 2)
} else if levels.len() > 1 && effective_dist > 78.0 {
(&levels[1], 1)
} else {
(&levels[0], 0)
}
}
/// Nanite-style continuous LOD selection driven by projected screen-space pixel coverage.
///
/// # Arguments
///
/// - `&Self` - LOD chain reference.
/// - `f32` - Camera-to-object distance in meters.
/// - `f32` - World-space bounding sphere radius in meters.
/// - `f32` - Projected viewport focal length in pixels (`height / (2 * tan(fov/2))`).
/// - `f32` - Quality LOD bias multiplier (`< 1.0` higher detail, `> 1.0` aggressive simplification).
///
/// # Returns
///
/// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
#[must_use]
pub fn select_screen_error(
&self,
distance: f32,
bounds_radius: f32,
focal_px: f32,
lod_bias: f32,
) -> (&Mesh3D, usize) {
let levels: &[Mesh3D] = self.get_levels().as_slice();
let safe_dist: f32 = distance.max(0.5);
let projected_px: f32 =
(bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
if levels.len() > 2 && projected_px < 3.5 {
(&levels[2], 2)
} else if levels.len() > 1 && projected_px < 9.0 {
(&levels[1], 1)
} else {
(&levels[0], 0)
}
}
}
/// Native Wavefront `.obj`, Khronos glTF 2.0 `.gltf`/`.glb`, and baked binary model importers for `ModelImporter3D`.
impl ModelImporter3D {
/// Imports a 3D model from text source in the specified `ModelFormat` and generates LOD chains.
///
/// # Arguments
///
/// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
/// - `&str` - Raw `.obj` or `.gltf` text content.
/// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
///
/// # Returns
///
/// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error diagnostic.
pub fn import(
format: ModelFormat,
source: &str,
fallback_material: PbrMaterial,
) -> Result<ImportedModel3D, String> {
match format {
ModelFormat::Obj => Self::parse_obj(source, fallback_material),
ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
ModelFormat::GlbBinary | ModelFormat::Euv3dBinary | ModelFormat::BlendInspect => {
Err(ERR_TEXT_FORMAT_UNSUPPORTED.to_string())
}
}
}
/// Imports a 3D model from raw binary or UTF-8 bytes in `Obj`, `GltfJson`, or `GlbBinary` format.
///
/// # Arguments
///
/// - `ModelFormat` - Source interchange format.
/// - `&[u8]` - Raw file bytes.
/// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
///
/// # Returns
///
/// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error.
pub fn import_bytes(
format: ModelFormat,
bytes: &[u8],
fallback_material: PbrMaterial,
) -> Result<ImportedModel3D, String> {
match format {
ModelFormat::Obj => {
let text: &str = from_utf8(bytes)
.ok()
.ok_or_else(|| ERR_OBJ_EMPTY.to_string())?;
Self::parse_obj(text, fallback_material)
}
ModelFormat::GltfJson => {
let text: &str = from_utf8(bytes)
.ok()
.ok_or_else(|| ERR_GLTF_EMPTY.to_string())?;
Self::parse_gltf_json(text, fallback_material)
}
ModelFormat::GlbBinary => {
let scene: ImportedScene3D = parse_glb_bytes(bytes)?;
if scene.get_meshes().is_empty() {
return Err(ERR_GLTF_EMPTY.to_string());
}
let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GlbBinary);
if scene.get_materials().is_empty() {
for chain in model.get_mut_meshes().iter_mut() {
for lvl in chain.get_mut_levels().iter_mut() {
lvl.set_material(fallback_material);
}
}
}
Ok(model)
}
ModelFormat::Euv3dBinary => {
let bundle: BakedAssetBundle3D = Euv3dPackage::decode_bytes(bytes)?;
if bundle.get_lod_chains().is_empty() {
return Err(ERR_GLTF_EMPTY.to_string());
}
let total_vertices: usize = bundle
.get_lod_chains()
.iter()
.filter_map(|c: &MeshLodChain| c.get_levels().first())
.map(|m: &Mesh3D| m.get_vertices().len())
.sum();
let total_triangles: usize = bundle
.get_lod_chains()
.iter()
.filter_map(|c: &MeshLodChain| c.get_levels().first())
.map(|m: &Mesh3D| m.get_indices().len())
.sum();
Ok(ImportedModel3D {
name: bundle.get_scene().get_name().clone(),
format: ModelFormat::Euv3dBinary,
meshes: bundle.get_lod_chains().clone(),
total_vertices,
total_triangles,
})
}
ModelFormat::BlendInspect => Err(ERR_BINARY_FORMAT_UNSUPPORTED.to_string()),
}
}
/// Resolves a signed 1-based Wavefront OBJ index (positive or negative relative to `len`) into a 0-based index.
///
/// # Arguments
///
/// - `i32` - Signed 1-based OBJ index.
/// - `usize` - Current length of the corresponding attribute array.
///
/// # Returns
///
/// - `Option<usize>` - Resolved 0-based index if in bounds.
#[must_use]
fn resolve_obj_index(raw: i32, len: usize) -> Option<usize> {
if raw > 0 {
let idx: usize = (raw - 1) as usize;
if idx < len { Some(idx) } else { None }
} else if raw < 0 {
let idx: isize = (len as isize) + (raw as isize);
if idx >= 0 && (idx as usize) < len {
Some(idx as usize)
} else {
None
}
} else {
None
}
}
/// Parses a Wavefront `.mtl` material library into a named `PbrMaterial` map (`Kd`, `Ke`, `Ns`, `Pm`, `Pr`).
///
/// # Arguments
///
/// - `&str` - Raw `.mtl` ASCII text.
/// - `PbrMaterial` - Base fallback material template.
///
/// # Returns
///
/// - `HashMap<String, PbrMaterial>` - Parsed material table keyed by `newmtl` identifier.
#[must_use]
pub fn parse_mtl(mtl_source: &str, fallback: PbrMaterial) -> HashMap<String, PbrMaterial> {
let mut table: HashMap<String, PbrMaterial> = HashMap::new();
let mut active_name: Option<String> = None;
let mut active_mat: PbrMaterial = fallback;
for raw_line in mtl_source.lines() {
let line: &str = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.is_empty() {
continue;
}
if parts[0] == MTL_DIRECTIVE_NEWMTL && parts.len() >= 2 {
if let Some(prev_name) = active_name.take() {
let _: Option<PbrMaterial> = table.insert(prev_name, active_mat);
}
active_name = Some(parts[1].to_string());
active_mat = fallback;
} else if parts[0] == "Kd" && parts.len() >= 4 {
let r: f32 = parts[1].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
let g: f32 = parts[2].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
let b: f32 = parts[3].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
active_mat.set_base_color(Vec3::new(r, g, b));
} else if parts[0] == "Ke" && parts.len() >= 4 {
let r: f32 = parts[1].parse::<f32>().unwrap_or(0.0).max(0.0);
let g: f32 = parts[2].parse::<f32>().unwrap_or(0.0).max(0.0);
let b: f32 = parts[3].parse::<f32>().unwrap_or(0.0).max(0.0);
active_mat.set_emissive(Vec3::new(r, g, b));
} else if parts[0] == "Pm" && parts.len() >= 2 {
let metal: f32 = parts[1].parse::<f32>().unwrap_or(0.0).clamp(0.0, 1.0);
active_mat.set_metallic(metal);
} else if parts[0] == "Pr" && parts.len() >= 2 {
let rough: f32 = parts[1].parse::<f32>().unwrap_or(0.5).clamp(0.04, 1.0);
active_mat.set_roughness(rough);
active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
} else if parts[0] == "Ns" && parts.len() >= 2 {
let ns: f32 = parts[1].parse::<f32>().unwrap_or(64.0).clamp(0.0, 1000.0);
let rough: f32 = (1.0 - (ns / 1000.0).sqrt()).clamp(0.04, 1.0);
active_mat.set_roughness(rough);
active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
}
}
if let Some(last_name) = active_name {
let _: Option<PbrMaterial> = table.insert(last_name, active_mat);
}
table
}
/// Parses a Wavefront `.obj` mesh (`o`, `g`, `v`, `vt`, `vn`, `f`, `mtllib`, `usemtl`) with optional `.mtl` library, negative index support, vertex deduplication, and Lengyel tangents.
///
/// # Arguments
///
/// - `&str` - Raw `.obj` ASCII text.
/// - `Option<&str>` - Optional companion `.mtl` ASCII text.
/// - `PbrMaterial` - Fallback PBR material.
///
/// # Returns
///
/// - `Result<ImportedModel3D, String>` - Parsed model or error string.
pub fn parse_obj_with_mtl(
source: &str,
mtl_source: Option<&str>,
material: PbrMaterial,
) -> Result<ImportedModel3D, String> {
let mtl_table: HashMap<String, PbrMaterial> = mtl_source
.map(|text: &str| Self::parse_mtl(text, material))
.unwrap_or_default();
let mut positions: Vec<Vec3> = Vec::new();
let mut uvs: Vec<[f32; 2]> = Vec::new();
let mut normals: Vec<Vec3> = Vec::new();
let mut vertices: Vec<Vertex3D> = Vec::new();
let mut indices: Vec<[u32; 3]> = Vec::new();
let mut dedup: HashMap<(usize, Option<usize>, Option<usize>), u32> = HashMap::new();
let mut sub_materials: Vec<PbrMaterial> = Vec::new();
let mut sub_mat_slots: HashMap<String, u16> = HashMap::new();
let mut tri_materials: Vec<u16> = Vec::new();
let mut active_slot: u16 = 0;
let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
let mut saw_any_uv: bool = false;
let mut saw_any_normal: bool = false;
for raw_line in source.lines() {
let line: &str = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.is_empty() {
continue;
}
match parts[0] {
"o" | "g" if parts.len() >= 2 => {
model_name = parts[1].to_string();
}
token if token == OBJ_DIRECTIVE_MTLLIB => {}
token if token == OBJ_DIRECTIVE_USEMTL && parts.len() >= 2 => {
let mat_name: &str = parts[1];
if let Some(&slot) = sub_mat_slots.get(mat_name) {
active_slot = slot;
} else if let Some(&parsed_mat) = mtl_table.get(mat_name) {
sub_materials.push(parsed_mat);
let new_slot: u16 = sub_materials.len() as u16;
let _: Option<u16> = sub_mat_slots.insert(mat_name.to_string(), new_slot);
active_slot = new_slot;
} else {
active_slot = 0;
}
}
"v" if parts.len() >= 4 => {
let pos_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
let pos_y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
let pos_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
positions.push(Vec3::new(pos_x, pos_y, pos_z));
}
"vt" if parts.len() >= 3 => {
let coord_u: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
let coord_v: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
uvs.push([coord_u, coord_v]);
saw_any_uv = true;
}
"vn" if parts.len() >= 4 => {
let coord_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
let coord_y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
let coord_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
normals.push(Vec3::new(coord_x, coord_y, coord_z).normalize());
saw_any_normal = true;
}
"f" if parts.len() >= 4 => {
let mut face_refs: Vec<(usize, Option<usize>, Option<usize>)> =
Vec::with_capacity(parts.len() - 1);
for token in parts.iter().skip(1) {
let comps: Vec<&str> = token.split('/').collect();
let v_raw: i32 = comps
.first()
.and_then(|s: &&str| s.parse::<i32>().ok())
.unwrap_or(0);
let Some(v_idx) = Self::resolve_obj_index(v_raw, positions.len()) else {
continue;
};
let vt_idx: Option<usize> = comps
.get(1)
.and_then(|s: &&str| s.parse::<i32>().ok())
.and_then(|raw: i32| Self::resolve_obj_index(raw, uvs.len()));
let vn_idx: Option<usize> = comps
.get(2)
.and_then(|s: &&str| s.parse::<i32>().ok())
.and_then(|raw: i32| Self::resolve_obj_index(raw, normals.len()));
face_refs.push((v_idx, vt_idx, vn_idx));
}
if face_refs.len() >= 3 {
for entry_index in 1..(face_refs.len() - 1) {
let tri_keys: [(usize, Option<usize>, Option<usize>); 3] = [
face_refs[0],
face_refs[entry_index],
face_refs[entry_index + 1],
];
let p0: Vec3 = positions[tri_keys[0].0];
let p1: Vec3 = positions[tri_keys[1].0];
let p2: Vec3 = positions[tri_keys[2].0];
let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
let mut out_tri: [u32; 3] = [0u32; 3];
for lane in 0..3usize {
let key: (usize, Option<usize>, Option<usize>) = tri_keys[lane];
let vert_id: u32 = if key.2.is_some() {
if let Some(&existing) = dedup.get(&key) {
existing
} else {
let id: u32 = vertices.len() as u32;
let mut v: Vertex3D = Vertex3D::new(
positions[key.0],
key.2
.and_then(|ni: usize| normals.get(ni).copied())
.unwrap_or(face_n),
);
if let Some(ti) = key.1
&& let Some(&uv_pair) = uvs.get(ti)
{
v.set_uv0(uv_pair);
v.set_flags(1);
}
vertices.push(v);
let _: Option<u32> = dedup.insert(key, id);
id
}
} else {
let id: u32 = vertices.len() as u32;
let mut v: Vertex3D = Vertex3D::new(positions[key.0], face_n);
if let Some(ti) = key.1
&& let Some(&uv_pair) = uvs.get(ti)
{
v.set_uv0(uv_pair);
v.set_flags(1);
}
vertices.push(v);
id
};
out_tri[lane] = vert_id;
}
indices.push(out_tri);
if !sub_materials.is_empty() {
tri_materials.push(active_slot);
}
}
}
}
_ => {}
}
}
if indices.is_empty() {
return Err(ERR_OBJ_EMPTY.to_string());
}
let mut mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
if !sub_materials.is_empty() {
if tri_materials.len() < mesh.get_indices().len() {
tri_materials.resize(mesh.get_indices().len(), 0);
}
mesh.set_sub_materials(sub_materials);
mesh.set_tri_materials(tri_materials);
}
if !saw_any_normal && dedup.len() < mesh.get_vertices().len() {
mesh.compute_smooth_normals();
}
if saw_any_uv {
mesh.compute_lengyel_tangents();
}
let total_vertices: usize = mesh.get_vertices().len();
let total_triangles: usize = mesh.get_indices().len();
Ok(ImportedModel3D {
name: model_name,
format: ModelFormat::Obj,
meshes: vec![MeshLodChain::from_mesh(mesh)],
total_vertices,
total_triangles,
})
}
/// Parses a Wavefront `.obj` mesh (`o`, `g`, `v`, `vt`, `vn`, `f` with n-gon fan triangulation, negative indices, and auto-normals).
///
/// # Arguments
///
/// - `&str` - Raw `.obj` ASCII text.
/// - `PbrMaterial` - Material assigned to the parsed mesh.
///
/// # Returns
///
/// - `Result<ImportedModel3D, String>` - Parsed model or error string.
pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
Self::parse_obj_with_mtl(source, None, material)
}
/// Parses a Khronos glTF 2.0 JSON asset (full buffers/bufferViews/accessors/Principled BSDF plus legacy inline geometry fallback).
///
/// # Arguments
///
/// - `&str` - Raw `.gltf` JSON string.
/// - `PbrMaterial` - Fallback PBR material when JSON omits `materials`.
///
/// # Returns
///
/// - `Result<ImportedModel3D, String>` - Parsed model bundle or validation error.
pub fn parse_gltf_json(
source: &str,
fallback_material: PbrMaterial,
) -> Result<ImportedModel3D, String> {
let scene: ImportedScene3D = parse_gltf_document(source, None, None)?;
if scene.get_meshes().is_empty() {
return Err(ERR_GLTF_EMPTY.to_string());
}
let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GltfJson);
if scene.get_materials().is_empty() {
for chain in model.get_mut_meshes().iter_mut() {
for lvl in chain.get_mut_levels().iter_mut() {
lvl.set_material(fallback_material);
}
}
}
Ok(model)
}
}