use super::*;
#[must_use]
pub(crate) fn sanitize_scalar(value: f32, fallback: f32) -> f32 {
if value.is_finite() { value } else { fallback }
}
#[must_use]
pub(crate) fn sanitize_vec3(value: Vec3, fallback: Vec3) -> Vec3 {
Vec3::new(
sanitize_scalar(value.get_x(), fallback.get_x()),
sanitize_scalar(value.get_y(), fallback.get_y()),
sanitize_scalar(value.get_z(), fallback.get_z()),
)
}
#[must_use]
pub(crate) fn safe_unit_normal(normal: Vec3) -> Vec3 {
let clean: Vec3 = sanitize_vec3(normal, Vec3::new(0.0, 1.0, 0.0));
let len_sq: f32 = clean.length_sq();
if len_sq > MESH_OPS_EPSILON_SQ && len_sq.is_finite() {
clean.scale(1.0 / len_sq.sqrt())
} else {
Vec3::new(0.0, 1.0, 0.0)
}
}
#[must_use]
pub(crate) fn make_textured_vertex(position: Vec3, normal: Vec3, uv0: [f32; 2]) -> Vertex3D {
let clean_pos: Vec3 = sanitize_vec3(position, Vec3::zero());
let clean_normal: Vec3 = safe_unit_normal(normal);
let clean_uv: [f32; 2] = [sanitize_scalar(uv0[0], 0.0), sanitize_scalar(uv0[1], 0.0)];
let fallback_axis: Vec3 = if clean_normal.get_y().abs() < 0.99 {
Vec3::new(0.0, 1.0, 0.0)
} else {
Vec3::new(1.0, 0.0, 0.0)
};
let tangent_vec: Vec3 = safe_unit_normal(fallback_axis.cross(clean_normal));
Vertex3D::from_full(
clean_pos,
clean_normal,
[
tangent_vec.get_x(),
tangent_vec.get_y(),
tangent_vec.get_z(),
1.0,
],
clean_uv,
[0.0, 0.0],
[255, 255, 255, 255],
VERTEX_FLAG_UV0,
)
}
fn resolve_merged_material_slot(
material: PbrMaterial,
primary: PbrMaterial,
sub_materials: &mut Vec<PbrMaterial>,
) -> u16 {
if material == primary {
return 0;
}
for (idx, existing) in sub_materials.iter().enumerate() {
if *existing == material {
return (idx + 1) as u16;
}
}
sub_materials.push(material);
sub_materials.len() as u16
}
#[must_use]
fn ordered_cost_key(cost: f32) -> u64 {
let clamped: f32 = if cost.is_finite() {
cost.max(0.0)
} else {
f32::MAX
};
clamped.to_bits() as u64
}
#[must_use]
fn canonical_edge(a: u32, b: u32) -> (u32, u32) {
if a < b { (a, b) } else { (b, a) }
}
#[must_use]
pub fn merge_meshes(meshes: &[Mesh3D], name: &str) -> Mesh3D {
let mesh_name: String = if name.is_empty() {
MESH_OPS_DEFAULT_MERGED_NAME.to_string()
} else {
name.to_string()
};
let mut total_verts: usize = 0;
let mut total_tris: usize = 0;
let mut primary_material: Option<PbrMaterial> = None;
let mut all_closed: bool = true;
let mut non_empty_count: usize = 0;
for mesh in meshes.iter() {
total_verts += mesh.get_vertices().len();
total_tris += mesh.get_indices().len();
if !mesh.get_indices().is_empty() {
non_empty_count += 1;
if primary_material.is_none() {
primary_material = Some(mesh.get_material());
}
if !mesh.get_is_closed() {
all_closed = false;
}
}
}
let primary: PbrMaterial = primary_material.unwrap_or_default();
if total_tris == 0 {
return Mesh3D::from_parts(mesh_name, Vec::new(), Vec::new(), primary);
}
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(total_verts);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity(total_tris);
let mut sub_materials: Vec<PbrMaterial> = Vec::new();
let mut tri_materials: Vec<u16> = Vec::with_capacity(total_tris);
let mut uses_sub_materials: bool = false;
for mesh in meshes.iter() {
let src_verts: &[Vertex3D] = mesh.get_vertices();
let src_tris: &[[u32; 3]] = mesh.get_indices();
if src_verts.is_empty() || src_tris.is_empty() {
continue;
}
let base_vertex: u32 = vertices.len() as u32;
vertices.extend_from_slice(src_verts);
let mesh_primary: PbrMaterial = mesh.get_material();
for (tri_idx, tri) in src_tris.iter().enumerate() {
indices.push([
base_vertex + tri[0],
base_vertex + tri[1],
base_vertex + tri[2],
]);
let (resolved_mat, _): (PbrMaterial, u16) =
mesh.resolve_triangle_material(tri_idx, mesh_primary);
let slot: u16 = resolve_merged_material_slot(resolved_mat, primary, &mut sub_materials);
if slot != 0 {
uses_sub_materials = true;
}
tri_materials.push(slot);
}
}
let mut merged: Mesh3D = Mesh3D::from_parts(mesh_name, vertices, indices, primary);
merged.set_is_closed(non_empty_count > 0 && all_closed);
if uses_sub_materials {
merged.set_sub_materials(sub_materials);
merged.set_tri_materials(tri_materials);
}
merged
}
#[must_use]
pub fn transform_mesh(mesh: &Mesh3D, transform: &Mat4) -> Mesh3D {
let elems: [f32; 16] = transform.get_elements();
let col0: Vec3 = Vec3::new(elems[0], elems[1], elems[2]);
let col1: Vec3 = Vec3::new(elems[4], elems[5], elems[6]);
let col2: Vec3 = Vec3::new(elems[8], elems[9], elems[10]);
let det: f32 = col0.dot(col1.cross(col2));
let flip_winding: bool = det.is_finite() && det < 0.0;
let normal_basis: [Vec3; 3] = transform.normal_matrix_3x3();
let src_verts: &[Vertex3D] = mesh.get_vertices();
let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(src_verts.len());
for vert in src_verts.iter() {
let new_pos: Vec3 = sanitize_vec3(transform.mul_point3(vert.get_position()), Vec3::zero());
let raw_n: Vec3 = Mat4::transform_normal_with_basis(vert.get_normal(), normal_basis);
let new_normal: Vec3 = safe_unit_normal(if flip_winding {
raw_n.scale(-1.0)
} else {
raw_n
});
let old_t: [f32; 4] = vert.get_tangent();
let raw_t: Vec3 = transform.mul_vec3(Vec3::new(old_t[0], old_t[1], old_t[2]));
let ortho_t: Vec3 = raw_t.sub(new_normal.scale(new_normal.dot(raw_t)));
let unit_t: Vec3 = if ortho_t.length_sq() > MESH_OPS_NORMAL_EPSILON {
safe_unit_normal(ortho_t)
} else {
let axis: Vec3 = if new_normal.get_y().abs() < 0.99 {
Vec3::new(0.0, 1.0, 0.0)
} else {
Vec3::new(1.0, 0.0, 0.0)
};
safe_unit_normal(axis.cross(new_normal))
};
let handedness: f32 = if flip_winding { -old_t[3] } else { old_t[3] };
let clean_w: f32 = if handedness < 0.0 { -1.0 } else { 1.0 };
out_verts.push(Vertex3D::from_full(
new_pos,
new_normal,
[unit_t.get_x(), unit_t.get_y(), unit_t.get_z(), clean_w],
vert.get_uv0(),
vert.get_uv1(),
vert.get_color0(),
vert.get_flags(),
));
}
let src_tris: &[[u32; 3]] = mesh.get_indices();
let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(src_tris.len());
for tri in src_tris.iter() {
if flip_winding {
out_tris.push([tri[0], tri[2], tri[1]]);
} else {
out_tris.push(*tri);
}
}
let mut out_mesh: Mesh3D = Mesh3D::from_parts(
mesh.get_name().clone(),
out_verts,
out_tris,
mesh.get_material(),
);
out_mesh.set_is_closed(mesh.get_is_closed());
if !mesh.get_sub_materials().is_empty() {
out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
out_mesh.set_tri_materials(mesh.get_tri_materials().clone());
}
out_mesh
}
#[must_use]
pub fn weld_vertices(mesh: &Mesh3D, epsilon: f32) -> Mesh3D {
let eps: f32 =
sanitize_scalar(epsilon, MESH_OPS_MIN_WELD_EPSILON).max(MESH_OPS_MIN_WELD_EPSILON);
let eps_sq: f32 = eps * eps;
let inv_cell: f32 = 1.0 / eps;
let src_verts: &[Vertex3D] = mesh.get_vertices();
let src_tris: &[[u32; 3]] = mesh.get_indices();
let mut buckets: HashMap<(i64, i64, i64), Vec<u32>> = HashMap::with_capacity(src_verts.len());
let mut clusters: Vec<WeldAccumulator> = Vec::with_capacity(src_verts.len());
let mut remap: Vec<u32> = Vec::with_capacity(src_verts.len());
for vert in src_verts.iter() {
let pos: Vec3 = sanitize_vec3(vert.get_position(), Vec3::zero());
let cx: i64 = (pos.get_x() * inv_cell).floor() as i64;
let cy: i64 = (pos.get_y() * inv_cell).floor() as i64;
let cz: i64 = (pos.get_z() * inv_cell).floor() as i64;
let mut matched: Option<u32> = None;
for dx in -1_i64..=1_i64 {
for dy in -1_i64..=1_i64 {
for dz in -1_i64..=1_i64 {
if let Some(candidates) = buckets.get(&(cx + dx, cy + dy, cz + dz)) {
for &cluster_idx in candidates.iter() {
let anchor: Vec3 = clusters[cluster_idx as usize].get_anchor();
if pos.sub(anchor).length_sq() <= eps_sq {
matched = Some(cluster_idx);
break;
}
}
}
if matched.is_some() {
break;
}
}
if matched.is_some() {
break;
}
}
if matched.is_some() {
break;
}
}
let uv0: [f32; 2] = vert.get_uv0();
let uv1: [f32; 2] = vert.get_uv1();
let col: [u8; 4] = vert.get_color0();
let normal: Vec3 = safe_unit_normal(vert.get_normal());
if let Some(cluster_idx) = matched {
let acc: &mut WeldAccumulator = &mut clusters[cluster_idx as usize];
acc.set_pos_sum(acc.get_pos_sum().add(pos));
acc.set_normal_sum(acc.get_normal_sum().add(normal));
let old_uv0: [f32; 2] = acc.get_uv0_sum();
acc.set_uv0_sum([old_uv0[0] + uv0[0], old_uv0[1] + uv0[1]]);
let old_uv1: [f32; 2] = acc.get_uv1_sum();
acc.set_uv1_sum([old_uv1[0] + uv1[0], old_uv1[1] + uv1[1]]);
let old_col: [f32; 4] = acc.get_color_sum();
acc.set_color_sum([
old_col[0] + (col[0] as f32),
old_col[1] + (col[1] as f32),
old_col[2] + (col[2] as f32),
old_col[3] + (col[3] as f32),
]);
acc.set_flags(acc.get_flags() | vert.get_flags());
acc.set_count(acc.get_count() + 1);
remap.push(cluster_idx);
} else {
let new_idx: u32 = clusters.len() as u32;
clusters.push(WeldAccumulator {
pos_sum: pos,
normal_sum: normal,
uv0_sum: uv0,
uv1_sum: uv1,
color_sum: [col[0] as f32, col[1] as f32, col[2] as f32, col[3] as f32],
flags: vert.get_flags(),
anchor: pos,
count: 1,
});
buckets.entry((cx, cy, cz)).or_default().push(new_idx);
remap.push(new_idx);
}
}
let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(clusters.len());
for acc in clusters.iter() {
let inv_count: f32 = 1.0 / (acc.get_count().max(1) as f32);
let avg_pos: Vec3 = acc.get_pos_sum().scale(inv_count);
let avg_n: Vec3 = safe_unit_normal(acc.get_normal_sum());
let uv0_sum: [f32; 2] = acc.get_uv0_sum();
let uv1_sum: [f32; 2] = acc.get_uv1_sum();
let col_sum: [f32; 4] = acc.get_color_sum();
let avg_col: [u8; 4] = [
(col_sum[0] * inv_count).round().clamp(0.0, 255.0) as u8,
(col_sum[1] * inv_count).round().clamp(0.0, 255.0) as u8,
(col_sum[2] * inv_count).round().clamp(0.0, 255.0) as u8,
(col_sum[3] * inv_count).round().clamp(0.0, 255.0) as u8,
];
out_verts.push(Vertex3D::from_full(
avg_pos,
avg_n,
[1.0, 0.0, 0.0, 1.0],
[uv0_sum[0] * inv_count, uv0_sum[1] * inv_count],
[uv1_sum[0] * inv_count, uv1_sum[1] * inv_count],
avg_col,
acc.get_flags(),
));
}
let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(src_tris.len());
let src_tri_mats: &[u16] = mesh.get_tri_materials();
let has_tri_mats: bool = !src_tri_mats.is_empty();
let mut out_tri_mats: Vec<u16> =
Vec::with_capacity(if has_tri_mats { src_tris.len() } else { 0 });
for (tri_idx, tri) in src_tris.iter().enumerate() {
let (a, b, c): (usize, usize, usize) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
if a >= remap.len() || b >= remap.len() || c >= remap.len() {
continue;
}
let i0: u32 = remap[a];
let i1: u32 = remap[b];
let i2: u32 = remap[c];
if i0 == i1 || i1 == i2 || i2 == i0 {
continue;
}
out_tris.push([i0, i1, i2]);
if has_tri_mats {
out_tri_mats.push(src_tri_mats.get(tri_idx).copied().unwrap_or(0));
}
}
let mut out_mesh: Mesh3D = Mesh3D::from_parts(
mesh.get_name().clone(),
out_verts,
out_tris,
mesh.get_material(),
);
out_mesh.set_is_closed(mesh.get_is_closed());
if has_tri_mats {
out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
out_mesh.set_tri_materials(out_tri_mats);
}
out_mesh
}
#[must_use]
pub fn recompute_smooth_normals(mesh: &Mesh3D) -> Mesh3D {
let mut out_mesh: Mesh3D = mesh.clone();
let vert_count: usize = out_mesh.get_vertices().len();
if vert_count == 0 {
return out_mesh;
}
let mut accum: Vec<Vec3> = vec![Vec3::zero(); vert_count];
for tri in out_mesh.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 verts: &[Vertex3D] = out_mesh.get_vertices();
let p0: Vec3 = verts[i0].get_position();
let p1: Vec3 = verts[i1].get_position();
let p2: Vec3 = verts[i2].get_position();
let face_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0));
if face_vec.length_sq() > MESH_OPS_EPSILON_SQ && face_vec.length_sq().is_finite() {
accum[i0] = accum[i0].add(face_vec);
accum[i1] = accum[i1].add(face_vec);
accum[i2] = accum[i2].add(face_vec);
}
}
for (idx, vert) in out_mesh.get_mut_vertices().iter_mut().enumerate() {
let sum_n: Vec3 = accum[idx];
if sum_n.length_sq() > MESH_OPS_EPSILON_SQ {
vert.set_normal(safe_unit_normal(sum_n));
} else {
vert.set_normal(safe_unit_normal(vert.get_normal()));
}
}
let meshlets: Vec<Meshlet3D> =
Mesh3D::build_meshlets_from_parts(out_mesh.get_vertices(), out_mesh.get_indices());
out_mesh.set_meshlets(meshlets);
out_mesh
}
#[must_use]
pub fn recompute_flat_normals(mesh: &Mesh3D) -> Mesh3D {
let src_verts: &[Vertex3D] = mesh.get_vertices();
let src_tris: &[[u32; 3]] = mesh.get_indices();
let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(src_tris.len() * 3);
let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(src_tris.len());
let src_tri_mats: &[u16] = mesh.get_tri_materials();
let has_tri_mats: bool = !src_tri_mats.is_empty();
let mut out_tri_mats: Vec<u16> =
Vec::with_capacity(if has_tri_mats { src_tris.len() } else { 0 });
for (tri_idx, tri) in src_tris.iter().enumerate() {
let (i0, i1, i2): (usize, usize, usize) =
(tri[0] as usize, tri[1] as usize, tri[2] as usize);
if i0 >= src_verts.len() || i1 >= src_verts.len() || i2 >= src_verts.len() {
continue;
}
let v0: Vertex3D = src_verts[i0];
let v1: Vertex3D = src_verts[i1];
let v2: Vertex3D = src_verts[i2];
let face_n: Vec3 = safe_unit_normal(
v1.get_position()
.sub(v0.get_position())
.cross(v2.get_position().sub(v0.get_position())),
);
let base: u32 = out_verts.len() as u32;
for mut v in [v0, v1, v2] {
v.set_normal(face_n);
out_verts.push(v);
}
out_tris.push([base, base + 1, base + 2]);
if has_tri_mats {
out_tri_mats.push(src_tri_mats.get(tri_idx).copied().unwrap_or(0));
}
}
let mut out_mesh: Mesh3D = Mesh3D::from_parts(
mesh.get_name().clone(),
out_verts,
out_tris,
mesh.get_material(),
);
out_mesh.set_is_closed(mesh.get_is_closed());
if has_tri_mats {
out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
out_mesh.set_tri_materials(out_tri_mats);
}
out_mesh
}
#[must_use]
pub fn generate_box_projected_uvs(mesh: &Mesh3D, scale: f32) -> Mesh3D {
let uv_scale: f32 = sanitize_scalar(scale, 1.0);
let effective_scale: f32 = if uv_scale.abs() > 1e-6 { uv_scale } else { 1.0 };
let mut out_mesh: Mesh3D = mesh.clone();
for vert in out_mesh.get_mut_vertices().iter_mut() {
let pos: Vec3 = vert.get_position();
let normal: Vec3 = safe_unit_normal(vert.get_normal());
let ax: f32 = normal.get_x().abs();
let ay: f32 = normal.get_y().abs();
let az: f32 = normal.get_z().abs();
let uv: [f32; 2] = if ax >= ay && ax >= az {
[pos.get_z() * effective_scale, pos.get_y() * effective_scale]
} else if ay >= ax && ay >= az {
[pos.get_x() * effective_scale, pos.get_z() * effective_scale]
} else {
[pos.get_x() * effective_scale, pos.get_y() * effective_scale]
};
vert.set_uv0([sanitize_scalar(uv[0], 0.0), sanitize_scalar(uv[1], 0.0)]);
vert.set_flags(vert.get_flags() | VERTEX_FLAG_UV0);
}
out_mesh
}
#[must_use]
pub fn compute_tangents(mesh: &Mesh3D) -> Mesh3D {
let mut out_mesh: Mesh3D = mesh.clone();
let vert_count: usize = out_mesh.get_vertices().len();
if vert_count == 0 {
return out_mesh;
}
let mut tan1: Vec<Vec3> = vec![Vec3::zero(); vert_count];
let mut tan2: Vec<Vec3> = vec![Vec3::zero(); vert_count];
let verts: &[Vertex3D] = out_mesh.get_vertices();
for tri in out_mesh.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 uv0: [f32; 2] = verts[i0].get_uv0();
let uv1: [f32; 2] = verts[i1].get_uv0();
let uv2: [f32; 2] = verts[i2].get_uv0();
let e1: Vec3 = p1.sub(p0);
let e2: Vec3 = p2.sub(p0);
let du1: f32 = uv1[0] - uv0[0];
let du2: f32 = uv2[0] - uv0[0];
let dv1: f32 = uv1[1] - uv0[1];
let dv2: f32 = uv2[1] - uv0[1];
let det: f32 = du1 * dv2 - du2 * dv1;
if !det.is_finite() || det.abs() < MESH_OPS_NORMAL_EPSILON {
continue;
}
let inv_det: f32 = 1.0 / det;
let area_weight: f32 = e1.cross(e2).length().max(1e-6);
let sdir: Vec3 = Vec3::new(
(dv2 * e1.get_x() - dv1 * e2.get_x()) * inv_det,
(dv2 * e1.get_y() - dv1 * e2.get_y()) * inv_det,
(dv2 * e1.get_z() - dv1 * e2.get_z()) * inv_det,
)
.scale(area_weight);
let tdir: Vec3 = Vec3::new(
(du1 * e2.get_x() - du2 * e1.get_x()) * inv_det,
(du1 * e2.get_y() - du2 * e1.get_y()) * inv_det,
(du1 * e2.get_z() - du2 * e1.get_z()) * inv_det,
)
.scale(area_weight);
if sdir.length_sq().is_finite() && tdir.length_sq().is_finite() {
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 out_mesh.get_mut_vertices().iter_mut().enumerate() {
let n: Vec3 = safe_unit_normal(vert.get_normal());
let t: Vec3 = tan1[idx];
let ortho: Vec3 = t.sub(n.scale(n.dot(t)));
let unit_t: Vec3 = if ortho.length_sq() > MESH_OPS_NORMAL_EPSILON {
safe_unit_normal(ortho)
} else {
let 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)
};
safe_unit_normal(axis.cross(n))
};
let handedness: f32 = if n.cross(unit_t).dot(tan2[idx]) < 0.0 {
-1.0
} else {
1.0
};
vert.set_normal(n);
vert.set_tangent([unit_t.get_x(), unit_t.get_y(), unit_t.get_z(), handedness]);
vert.set_flags(vert.get_flags() | VERTEX_FLAG_TANGENT);
}
out_mesh
}
fn is_collapse_valid(
v0: u32,
v1: u32,
target_pos: Vec3,
verts: &[DecimationVertex],
tris: &[DecimationTriangle],
v_tris: &[Vec<usize>],
) -> bool {
let mut nbrs0: Vec<u32> = Vec::with_capacity(v_tris[v0 as usize].len() * 2);
let mut edge_tri_count: usize = 0;
for &t_idx in v_tris[v0 as usize].iter() {
let tri: DecimationTriangle = tris[t_idx];
if !tri.get_alive() {
continue;
}
let idx: [u32; 3] = tri.get_indices();
let has_v1: bool = idx[0] == v1 || idx[1] == v1 || idx[2] == v1;
if has_v1 {
edge_tri_count += 1;
}
for &vid in idx.iter() {
if vid != v0 && vid != v1 && !nbrs0.contains(&vid) {
nbrs0.push(vid);
}
}
}
if edge_tri_count == 0 {
return false;
}
let mut shared_nbrs: Vec<u32> = Vec::new();
for &t_idx in v_tris[v1 as usize].iter() {
let tri: DecimationTriangle = tris[t_idx];
if !tri.get_alive() {
continue;
}
for &vid in tri.get_indices().iter() {
if vid != v0 && vid != v1 && nbrs0.contains(&vid) && !shared_nbrs.contains(&vid) {
shared_nbrs.push(vid);
}
}
}
if shared_nbrs.len() != edge_tri_count {
return false;
}
for &check_vid in [v0, v1].iter() {
for &t_idx in v_tris[check_vid as usize].iter() {
let tri: DecimationTriangle = tris[t_idx];
if !tri.get_alive() {
continue;
}
let idx: [u32; 3] = tri.get_indices();
if (idx[0] == v0 || idx[1] == v0 || idx[2] == v0)
&& (idx[0] == v1 || idx[1] == v1 || idx[2] == v1)
{
continue;
}
let p0: Vec3 = verts[idx[0] as usize].get_position();
let p1: Vec3 = verts[idx[1] as usize].get_position();
let p2: Vec3 = verts[idx[2] as usize].get_position();
let old_cross: Vec3 = p1.sub(p0).cross(p2.sub(p0));
let np0: Vec3 = if idx[0] == v0 || idx[0] == v1 {
target_pos
} else {
p0
};
let np1: Vec3 = if idx[1] == v0 || idx[1] == v1 {
target_pos
} else {
p1
};
let np2: Vec3 = if idx[2] == v0 || idx[2] == v1 {
target_pos
} else {
p2
};
let new_cross: Vec3 = np1.sub(np0).cross(np2.sub(np0));
if new_cross.length_sq() <= MESH_OPS_EPSILON_SQ {
return false;
}
if old_cross.length_sq() > MESH_OPS_EPSILON_SQ {
let old_n: Vec3 = safe_unit_normal(old_cross);
let new_n: Vec3 = safe_unit_normal(new_cross);
if old_n.dot(new_n) <= MESH_OPS_FLIP_DOT_LIMIT {
return false;
}
}
}
}
true
}
#[must_use]
pub fn decimate_mesh(mesh: &Mesh3D, target_ratio: f32) -> Mesh3D {
let ratio: f32 = sanitize_scalar(target_ratio, 1.0).clamp(0.01, 1.0);
let src_verts: &[Vertex3D] = mesh.get_vertices();
let src_tris: &[[u32; 3]] = mesh.get_indices();
if src_verts.is_empty() || src_tris.len() <= MESH_OPS_MIN_TRIS || ratio >= 0.999 {
return mesh.clone();
}
let target_tris: usize = ((src_tris.len() as f32) * ratio)
.round()
.max(MESH_OPS_MIN_TRIS as f32) as usize;
if target_tris >= src_tris.len() {
return mesh.clone();
}
let mut verts: Vec<DecimationVertex> = Vec::with_capacity(src_verts.len());
for vert in src_verts.iter() {
let col: [u8; 4] = vert.get_color0();
verts.push(DecimationVertex {
position: sanitize_vec3(vert.get_position(), Vec3::zero()),
normal: safe_unit_normal(vert.get_normal()),
uv0: vert.get_uv0(),
uv1: vert.get_uv1(),
color: [col[0] as f32, col[1] as f32, col[2] as f32, col[3] as f32],
flags: vert.get_flags(),
quadric: QuadricErrorMatrix::default(),
version: 0,
alive: true,
});
}
let src_tri_mats: &[u16] = mesh.get_tri_materials();
let has_tri_mats: bool = !src_tri_mats.is_empty();
let mut tris: Vec<DecimationTriangle> = Vec::with_capacity(src_tris.len());
let mut v_tris: Vec<Vec<usize>> = vec![Vec::new(); verts.len()];
let mut edge_counts: HashMap<(u32, u32), u32> = HashMap::with_capacity(src_tris.len() * 2);
for (tri_idx, tri) in src_tris.iter().enumerate() {
let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
if (a as usize) >= verts.len()
|| (b as usize) >= verts.len()
|| (c as usize) >= verts.len()
|| a == b
|| b == c
|| c == a
{
continue;
}
let slot: u16 = if has_tri_mats {
src_tri_mats.get(tri_idx).copied().unwrap_or(0)
} else {
0
};
let active_idx: usize = tris.len();
tris.push(DecimationTriangle {
indices: [a, b, c],
material_slot: slot,
alive: true,
});
v_tris[a as usize].push(active_idx);
v_tris[b as usize].push(active_idx);
v_tris[c as usize].push(active_idx);
let p0: Vec3 = verts[a as usize].get_position();
let p1: Vec3 = verts[b as usize].get_position();
let p2: Vec3 = verts[c as usize].get_position();
let cross_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0));
let area: f32 = cross_vec.length() * 0.5;
if area > 1e-9 && area.is_finite() {
let n: Vec3 = safe_unit_normal(cross_vec);
let d: f32 = -n.dot(p0);
let plane_q: QuadricErrorMatrix =
QuadricErrorMatrix::from_plane(n.get_x(), n.get_y(), n.get_z(), d, area.max(1e-4));
for &vid in [a, b, c].iter() {
let cur_q: QuadricErrorMatrix = verts[vid as usize].get_quadric();
verts[vid as usize].set_quadric(cur_q.combine(plane_q));
}
}
for edge in [
canonical_edge(a, b),
canonical_edge(b, c),
canonical_edge(c, a),
] {
let count_entry: &mut u32 = edge_counts.entry(edge).or_insert(0);
*count_entry += 1;
}
}
for tri in tris.iter() {
let idx: [u32; 3] = tri.get_indices();
let p0: Vec3 = verts[idx[0] as usize].get_position();
let p1: Vec3 = verts[idx[1] as usize].get_position();
let p2: Vec3 = verts[idx[2] as usize].get_position();
let face_n: Vec3 = safe_unit_normal(p1.sub(p0).cross(p2.sub(p0)));
for (ea, eb) in [(idx[0], idx[1]), (idx[1], idx[2]), (idx[2], idx[0])] {
let count: u32 = edge_counts
.get(&canonical_edge(ea, eb))
.copied()
.unwrap_or(0);
if count == 1 {
let pa: Vec3 = verts[ea as usize].get_position();
let pb: Vec3 = verts[eb as usize].get_position();
let edge_vec: Vec3 = pb.sub(pa);
let edge_len: f32 = edge_vec.length();
if edge_len > 1e-6 {
let bn: Vec3 = safe_unit_normal(edge_vec.cross(face_n));
let bd: f32 = -bn.dot(pa);
let bq: QuadricErrorMatrix = QuadricErrorMatrix::from_plane(
bn.get_x(),
bn.get_y(),
bn.get_z(),
bd,
edge_len * MESH_OPS_BOUNDARY_WEIGHT,
);
let qa: QuadricErrorMatrix = verts[ea as usize].get_quadric();
let qb: QuadricErrorMatrix = verts[eb as usize].get_quadric();
verts[ea as usize].set_quadric(qa.combine(bq));
verts[eb as usize].set_quadric(qb.combine(bq));
}
}
}
}
let mut heap: BTreeSet<DecimationCandidate> = BTreeSet::new();
let mut seq: u64 = 0;
for &(v0, v1) in edge_counts.keys() {
let q_sum: QuadricErrorMatrix = verts[v0 as usize]
.get_quadric()
.combine(verts[v1 as usize].get_quadric());
let (_, cost): (Vec3, f32) = q_sum.solve_optimal_point(
verts[v0 as usize].get_position(),
verts[v1 as usize].get_position(),
);
seq += 1;
heap.insert(DecimationCandidate {
cost_key: ordered_cost_key(cost),
sequence: seq,
v0,
v1,
ver0: 0,
ver1: 0,
});
}
let mut alive_tris: usize = tris.len();
let mut neighbor_edges: Vec<u32> = Vec::with_capacity(32);
while alive_tris > target_tris {
let Some(cand) = heap.pop_first() else {
break;
};
let v0: u32 = cand.get_v0();
let v1: u32 = cand.get_v1();
if v0 == v1 {
continue;
}
let vert0: DecimationVertex = verts[v0 as usize];
let vert1: DecimationVertex = verts[v1 as usize];
if !vert0.get_alive()
|| !vert1.get_alive()
|| vert0.get_version() != cand.get_ver0()
|| vert1.get_version() != cand.get_ver1()
{
continue;
}
let q_sum: QuadricErrorMatrix = vert0.get_quadric().combine(vert1.get_quadric());
let (target_pos, _): (Vec3, f32) =
q_sum.solve_optimal_point(vert0.get_position(), vert1.get_position());
if !is_collapse_valid(v0, v1, target_pos, &verts, &tris, &v_tris) {
continue;
}
let seg: Vec3 = vert1.get_position().sub(vert0.get_position());
let seg_len_sq: f32 = seg.length_sq();
let alpha: f32 = if seg_len_sq > MESH_OPS_EPSILON_SQ {
(target_pos.sub(vert0.get_position()).dot(seg) / seg_len_sq).clamp(0.0, 1.0)
} else {
0.5
};
let uv0_a: [f32; 2] = vert0.get_uv0();
let uv0_b: [f32; 2] = vert1.get_uv0();
let uv1_a: [f32; 2] = vert0.get_uv1();
let uv1_b: [f32; 2] = vert1.get_uv1();
let col_a: [f32; 4] = vert0.get_color();
let col_b: [f32; 4] = vert1.get_color();
let next_ver: u32 = vert0.get_version() + 1;
verts[v0 as usize].set_position(target_pos);
verts[v0 as usize].set_normal(safe_unit_normal(
vert0.get_normal().lerp(vert1.get_normal(), alpha),
));
verts[v0 as usize].set_uv0([
uv0_a[0] + (uv0_b[0] - uv0_a[0]) * alpha,
uv0_a[1] + (uv0_b[1] - uv0_a[1]) * alpha,
]);
verts[v0 as usize].set_uv1([
uv1_a[0] + (uv1_b[0] - uv1_a[0]) * alpha,
uv1_a[1] + (uv1_b[1] - uv1_a[1]) * alpha,
]);
verts[v0 as usize].set_color([
col_a[0] + (col_b[0] - col_a[0]) * alpha,
col_a[1] + (col_b[1] - col_a[1]) * alpha,
col_a[2] + (col_b[2] - col_a[2]) * alpha,
col_a[3] + (col_b[3] - col_a[3]) * alpha,
]);
verts[v0 as usize].set_flags(vert0.get_flags() | vert1.get_flags());
verts[v0 as usize].set_quadric(q_sum);
verts[v0 as usize].set_version(next_ver);
verts[v1 as usize].set_alive(false);
let moved_tris: Vec<usize> = take(&mut v_tris[v1 as usize]);
for t_idx in moved_tris.into_iter() {
if !tris[t_idx].get_alive() {
continue;
}
let mut idx: [u32; 3] = tris[t_idx].get_indices();
for slot in idx.iter_mut() {
if *slot == v1 {
*slot = v0;
}
}
if idx[0] == idx[1] || idx[1] == idx[2] || idx[2] == idx[0] {
tris[t_idx].set_alive(false);
alive_tris = alive_tris.saturating_sub(1);
} else {
tris[t_idx].set_indices(idx);
if !v_tris[v0 as usize].contains(&t_idx) {
v_tris[v0 as usize].push(t_idx);
}
}
}
v_tris[v0 as usize].retain(|t_idx: &usize| tris[*t_idx].get_alive());
neighbor_edges.clear();
for &t_idx in v_tris[v0 as usize].iter() {
let idx: [u32; 3] = tris[t_idx].get_indices();
for &vid in idx.iter() {
if vid != v0 && verts[vid as usize].get_alive() && !neighbor_edges.contains(&vid) {
neighbor_edges.push(vid);
}
}
}
for &nbr in neighbor_edges.iter() {
let (ea, eb): (u32, u32) = canonical_edge(v0, nbr);
let combined_q: QuadricErrorMatrix = verts[ea as usize]
.get_quadric()
.combine(verts[eb as usize].get_quadric());
let (_, edge_cost): (Vec3, f32) = combined_q.solve_optimal_point(
verts[ea as usize].get_position(),
verts[eb as usize].get_position(),
);
seq += 1;
heap.insert(DecimationCandidate {
cost_key: ordered_cost_key(edge_cost),
sequence: seq,
v0: ea,
v1: eb,
ver0: verts[ea as usize].get_version(),
ver1: verts[eb as usize].get_version(),
});
}
}
let mut remap: Vec<u32> = vec![u32::MAX; verts.len()];
let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(alive_tris);
let mut out_tri_mats: Vec<u16> = Vec::with_capacity(if has_tri_mats { alive_tris } else { 0 });
for tri in tris.iter() {
if !tri.get_alive() {
continue;
}
let idx: [u32; 3] = tri.get_indices();
let mut mapped: [u32; 3] = [0; 3];
for (corner, &vid) in idx.iter().enumerate() {
let slot: u32 = remap[vid as usize];
if slot == u32::MAX {
let new_id: u32 = out_verts.len() as u32;
let dv: DecimationVertex = verts[vid as usize];
let col: [f32; 4] = dv.get_color();
out_verts.push(Vertex3D::from_full(
dv.get_position(),
dv.get_normal(),
[1.0, 0.0, 0.0, 1.0],
dv.get_uv0(),
dv.get_uv1(),
[
col[0].round().clamp(0.0, 255.0) as u8,
col[1].round().clamp(0.0, 255.0) as u8,
col[2].round().clamp(0.0, 255.0) as u8,
col[3].round().clamp(0.0, 255.0) as u8,
],
dv.get_flags(),
));
remap[vid as usize] = new_id;
mapped[corner] = new_id;
} else {
mapped[corner] = slot;
}
}
if mapped[0] != mapped[1] && mapped[1] != mapped[2] && mapped[2] != mapped[0] {
out_tris.push(mapped);
if has_tri_mats {
out_tri_mats.push(tri.get_material_slot());
}
}
}
let mut out_mesh: Mesh3D = Mesh3D::from_parts(
mesh.get_name().clone(),
out_verts,
out_tris,
mesh.get_material(),
);
out_mesh.set_is_closed(mesh.get_is_closed());
if has_tri_mats {
out_mesh.set_sub_materials(mesh.get_sub_materials().clone());
out_mesh.set_tri_materials(out_tri_mats);
}
let smoothed: Mesh3D = recompute_smooth_normals(&out_mesh);
compute_tangents(&smoothed)
}
#[must_use]
pub fn build_lod_chain(mesh: &Mesh3D, ratios: &[f32]) -> MeshLodChain {
let mut clean_ratios: Vec<f32> = Vec::with_capacity(ratios.len());
for &ratio in ratios.iter() {
if ratio.is_finite() && ratio > 0.0 {
clean_ratios.push(ratio.clamp(0.01, 1.0));
}
}
clean_ratios.sort_by(|a: &f32, b: &f32| b.total_cmp(a));
if clean_ratios.is_empty() {
return MeshLodChain::single_level(mesh.clone());
}
let mut levels: Vec<Mesh3D> = Vec::with_capacity(clean_ratios.len());
for (idx, &ratio) in clean_ratios.iter().enumerate() {
if ratio >= 0.999 {
if levels.is_empty() {
levels.push(mesh.clone());
}
} else {
let mut decimated: Mesh3D = decimate_mesh(mesh, ratio);
decimated.set_name(format!("{}_lod{}", mesh.get_name(), idx));
levels.push(decimated);
}
}
if levels.is_empty() {
levels.push(mesh.clone());
}
let mut chain: MeshLodChain = MeshLodChain::single_level(levels[0].clone());
chain.set_levels(levels);
chain
}