use super::*;
#[must_use]
fn subdiv_vertex_from_mesh(v: &Vertex3D) -> SubdivVertex {
let col: [u8; 4] = v.get_color0();
SubdivVertex {
position: sanitize_vec3(v.get_position(), Vec3::zero()),
uv0: v.get_uv0(),
uv1: v.get_uv1(),
color: [col[0] as f32, col[1] as f32, col[2] as f32, col[3] as f32],
flags: v.get_flags(),
}
}
#[must_use]
fn subdiv_vertex_to_mesh(sv: SubdivVertex) -> Vertex3D {
let col: [f32; 4] = sv.get_color();
Vertex3D::from_full(
sanitize_vec3(sv.get_position(), Vec3::zero()),
Vec3::new(0.0, 1.0, 0.0),
[1.0, 0.0, 0.0, 1.0],
sv.get_uv0(),
sv.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,
],
sv.get_flags(),
)
}
#[must_use]
fn blend_subdiv_vertices(terms: &[(SubdivVertex, f32)]) -> SubdivVertex {
let mut pos: Vec3 = Vec3::zero();
let mut uv0: [f32; 2] = [0.0, 0.0];
let mut uv1: [f32; 2] = [0.0, 0.0];
let mut col: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
let mut flags: u32 = 0;
for &(sv, w) in terms.iter() {
pos = pos.add(sv.get_position().scale(w));
let u0: [f32; 2] = sv.get_uv0();
let u1: [f32; 2] = sv.get_uv1();
let c: [f32; 4] = sv.get_color();
uv0[0] += u0[0] * w;
uv0[1] += u0[1] * w;
uv1[0] += u1[0] * w;
uv1[1] += u1[1] * w;
col[0] += c[0] * w;
col[1] += c[1] * w;
col[2] += c[2] * w;
col[3] += c[3] * w;
flags |= sv.get_flags();
}
SubdivVertex {
position: sanitize_vec3(pos, Vec3::zero()),
uv0,
uv1,
color: col,
flags,
}
}
#[must_use]
fn average_subdiv_indices(verts: &[SubdivVertex], indices: &[u32]) -> SubdivVertex {
if indices.is_empty() {
return SubdivVertex::default();
}
let inv: f32 = 1.0 / (indices.len() as f32);
let mut pos: Vec3 = Vec3::zero();
let mut uv0: [f32; 2] = [0.0, 0.0];
let mut uv1: [f32; 2] = [0.0, 0.0];
let mut col: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
let mut flags: u32 = 0;
for &idx in indices.iter() {
let sv: SubdivVertex = verts[idx as usize];
pos = pos.add(sv.get_position());
let u0: [f32; 2] = sv.get_uv0();
let u1: [f32; 2] = sv.get_uv1();
let c: [f32; 4] = sv.get_color();
uv0[0] += u0[0];
uv0[1] += u0[1];
uv1[0] += u1[0];
uv1[1] += u1[1];
col[0] += c[0];
col[1] += c[1];
col[2] += c[2];
col[3] += c[3];
flags |= sv.get_flags();
}
SubdivVertex {
position: pos.scale(inv),
uv0: [uv0[0] * inv, uv0[1] * inv],
uv1: [uv1[0] * inv, uv1[1] * inv],
color: [col[0] * inv, col[1] * inv, col[2] * inv, col[3] * inv],
flags,
}
}
#[must_use]
fn edge_key(a: u32, b: u32) -> (u32, u32) {
if a < b { (a, b) } else { (b, a) }
}
#[must_use]
fn is_convex_quad(verts: &[SubdivVertex], q: [u32; 4], face_normal: Vec3) -> bool {
for i in 0..4 {
let p_prev: Vec3 = verts[q[(i + 3) % 4] as usize].get_position();
let p_curr: Vec3 = verts[q[i] as usize].get_position();
let p_next: Vec3 = verts[q[(i + 1) % 4] as usize].get_position();
let e0: Vec3 = p_curr.sub(p_prev);
let e1: Vec3 = p_next.sub(p_curr);
if e0.cross(e1).dot(face_normal) <= 1e-7 {
return false;
}
}
true
}
#[must_use]
fn build_quad_dominant_faces(
verts: &[SubdivVertex],
tris: &[[u32; 3]],
tri_mats: &[u16],
) -> Vec<PolyFace> {
let mut normals: Vec<Vec3> = Vec::with_capacity(tris.len());
let mut half_edges: HashMap<(u32, u32), (usize, u32)> = HashMap::with_capacity(tris.len() * 3);
for (ti, tri) in tris.iter().enumerate() {
let p0: Vec3 = verts[tri[0] as usize].get_position();
let p1: Vec3 = verts[tri[1] as usize].get_position();
let p2: Vec3 = verts[tri[2] as usize].get_position();
normals.push(safe_unit_normal(p1.sub(p0).cross(p2.sub(p0))));
half_edges.insert((tri[0], tri[1]), (ti, tri[2]));
half_edges.insert((tri[1], tri[2]), (ti, tri[0]));
half_edges.insert((tri[2], tri[0]), (ti, tri[1]));
}
let mut used: Vec<bool> = vec![false; tris.len()];
let mut faces: Vec<PolyFace> = Vec::with_capacity(tris.len());
for (ti, tri) in tris.iter().enumerate() {
if used[ti] {
continue;
}
let mat_a: u16 = tri_mats.get(ti).copied().unwrap_or(0);
let na: Vec3 = normals[ti];
let mut best_pair: Option<(usize, [u32; 4], f32)> = None;
let edges: [(u32, u32, u32); 3] = [
(tri[0], tri[1], tri[2]),
(tri[1], tri[2], tri[0]),
(tri[2], tri[0], tri[1]),
];
for (a, b, opp_a) in edges {
if let Some(&(tj, opp_b)) = half_edges.get(&(b, a)) {
if tj == ti || used[tj] {
continue;
}
let mat_b: u16 = tri_mats.get(tj).copied().unwrap_or(0);
if mat_a != mat_b || na.dot(normals[tj]) < SUBDIV_COPLANAR_COS {
continue;
}
let quad: [u32; 4] = [a, opp_b, b, opp_a];
if !is_convex_quad(verts, quad, na) {
continue;
}
let diag_len: f32 = verts[b as usize]
.get_position()
.sub(verts[a as usize].get_position())
.length_sq();
let should_take: bool = match best_pair {
None => true,
Some((_, _, prev_len)) => diag_len > prev_len,
};
if should_take {
best_pair = Some((tj, quad, diag_len));
}
}
}
if let Some((tj, quad, _)) = best_pair {
used[ti] = true;
used[tj] = true;
faces.push(PolyFace {
vertices: quad.to_vec(),
material_slot: mat_a,
});
} else {
used[ti] = true;
faces.push(PolyFace {
vertices: tri.to_vec(),
material_slot: mat_a,
});
}
}
faces
}
#[must_use]
fn catmull_clark_step(
verts: &[SubdivVertex],
faces: &[PolyFace],
) -> (Vec<SubdivVertex>, Vec<PolyFace>) {
let orig_v_count: usize = verts.len();
let face_count: usize = faces.len();
let mut face_pts: Vec<SubdivVertex> = Vec::with_capacity(face_count);
let mut edge_faces: HashMap<(u32, u32), Vec<usize>> = HashMap::with_capacity(face_count * 4);
let mut vert_faces: Vec<Vec<usize>> = vec![Vec::new(); orig_v_count];
let mut vert_edges: Vec<Vec<u32>> = vec![Vec::new(); orig_v_count];
for (fi, face) in faces.iter().enumerate() {
let fv: &[u32] = face.get_vertices();
face_pts.push(average_subdiv_indices(verts, fv));
let k: usize = fv.len();
for i in 0..k {
let a: u32 = fv[i];
let b: u32 = fv[(i + 1) % k];
vert_faces[a as usize].push(fi);
if !vert_edges[a as usize].contains(&b) {
vert_edges[a as usize].push(b);
}
if !vert_edges[b as usize].contains(&a) {
vert_edges[b as usize].push(a);
}
edge_faces.entry(edge_key(a, b)).or_default().push(fi);
}
}
let mut next_verts: Vec<SubdivVertex> =
Vec::with_capacity(orig_v_count + face_count + edge_faces.len());
for v_idx in 0..orig_v_count {
let orig: SubdivVertex = verts[v_idx];
let nbrs: &[u32] = &vert_edges[v_idx];
let mut bnd_nbrs: Vec<u32> = Vec::new();
for &nbr in nbrs.iter() {
let inc_count: usize = edge_faces
.get(&edge_key(v_idx as u32, nbr))
.map_or(0, |list: &Vec<usize>| list.len());
if inc_count == 1 {
bnd_nbrs.push(nbr);
}
}
let updated: SubdivVertex = if !bnd_nbrs.is_empty() {
if bnd_nbrs.len() == 2 {
blend_subdiv_vertices(&[
(orig, 0.75),
(verts[bnd_nbrs[0] as usize], 0.125),
(verts[bnd_nbrs[1] as usize], 0.125),
])
} else {
orig
}
} else {
let n: usize = nbrs.len();
let inc_f: &[usize] = &vert_faces[v_idx];
if n >= 3 && !inc_f.is_empty() {
let inv_f: f32 = 1.0 / (inc_f.len() as f32);
let mut f_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(inc_f.len());
for &fi in inc_f.iter() {
f_terms.push((face_pts[fi], inv_f));
}
let f_avg: SubdivVertex = blend_subdiv_vertices(&f_terms);
let inv_n: f32 = 1.0 / (n as f32);
let mut r_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(n + 1);
r_terms.push((orig, 0.5));
for &nbr in nbrs.iter() {
r_terms.push((verts[nbr as usize], 0.5 * inv_n));
}
let r_avg: SubdivVertex = blend_subdiv_vertices(&r_terms);
let nf: f32 = n as f32;
blend_subdiv_vertices(&[
(f_avg, 1.0 / nf),
(r_avg, 2.0 / nf),
(orig, (nf - 3.0) / nf),
])
} else {
orig
}
};
next_verts.push(updated);
}
let face_base: u32 = next_verts.len() as u32;
next_verts.extend_from_slice(&face_pts);
let mut edge_vert_map: HashMap<(u32, u32), u32> = HashMap::with_capacity(edge_faces.len());
for (&ek, inc_f) in edge_faces.iter() {
let va: SubdivVertex = verts[ek.0 as usize];
let vb: SubdivVertex = verts[ek.1 as usize];
let edge_pt: SubdivVertex = if inc_f.len() == 2 {
blend_subdiv_vertices(&[
(va, 0.25),
(vb, 0.25),
(face_pts[inc_f[0]], 0.25),
(face_pts[inc_f[1]], 0.25),
])
} else {
blend_subdiv_vertices(&[(va, 0.5), (vb, 0.5)])
};
let e_idx: u32 = next_verts.len() as u32;
next_verts.push(edge_pt);
edge_vert_map.insert(ek, e_idx);
}
let mut next_faces: Vec<PolyFace> = Vec::with_capacity(face_count * 4);
for (fi, face) in faces.iter().enumerate() {
let fv: &[u32] = face.get_vertices();
let k: usize = fv.len();
let f_vid: u32 = face_base + (fi as u32);
let mat_slot: u16 = face.get_material_slot();
for i in 0..k {
let v_curr: u32 = fv[i];
let v_next: u32 = fv[(i + 1) % k];
let v_prev: u32 = fv[(i + k - 1) % k];
let e_next: u32 = edge_vert_map
.get(&edge_key(v_curr, v_next))
.copied()
.unwrap_or(v_curr);
let e_prev: u32 = edge_vert_map
.get(&edge_key(v_prev, v_curr))
.copied()
.unwrap_or(v_curr);
next_faces.push(PolyFace {
vertices: vec![v_curr, e_next, f_vid, e_prev],
material_slot: mat_slot,
});
}
}
(next_verts, next_faces)
}
#[must_use]
pub fn subdivide_catmull_clark(mesh: &Mesh3D, levels: u32) -> Mesh3D {
let iters: u32 = levels.min(SUBDIV_MAX_LEVELS);
if iters == 0 || mesh.get_indices().is_empty() {
return mesh.clone();
}
let welded: Mesh3D = weld_vertices(mesh, SUBDIV_WELD_EPSILON);
let mut verts: Vec<SubdivVertex> = welded
.get_vertices()
.iter()
.map(subdiv_vertex_from_mesh)
.collect();
let mut faces: Vec<PolyFace> =
build_quad_dominant_faces(&verts, welded.get_indices(), welded.get_tri_materials());
for _ in 0..iters {
let (next_v, next_f): (Vec<SubdivVertex>, Vec<PolyFace>) =
catmull_clark_step(&verts, &faces);
verts = next_v;
faces = next_f;
}
let has_sub_mats: bool = !welded.get_sub_materials().is_empty();
let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
for sv in verts.into_iter() {
out_verts.push(subdiv_vertex_to_mesh(sv));
}
let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(faces.len() * 2);
let mut out_tri_mats: Vec<u16> =
Vec::with_capacity(if has_sub_mats { faces.len() * 2 } else { 0 });
for face in faces.iter() {
let fv: &[u32] = face.get_vertices();
let mat: u16 = face.get_material_slot();
if fv.len() == 3 {
out_tris.push([fv[0], fv[1], fv[2]]);
if has_sub_mats {
out_tri_mats.push(mat);
}
} else if fv.len() == 4 {
let d02: f32 = out_verts[fv[0] as usize]
.get_position()
.sub(out_verts[fv[2] as usize].get_position())
.length_sq();
let d13: f32 = out_verts[fv[1] as usize]
.get_position()
.sub(out_verts[fv[3] as usize].get_position())
.length_sq();
if d02 <= d13 {
out_tris.push([fv[0], fv[1], fv[2]]);
out_tris.push([fv[0], fv[2], fv[3]]);
} else {
out_tris.push([fv[0], fv[1], fv[3]]);
out_tris.push([fv[1], fv[2], fv[3]]);
}
if has_sub_mats {
out_tri_mats.push(mat);
out_tri_mats.push(mat);
}
} else if fv.len() > 4 {
for i in 1..(fv.len() - 1) {
out_tris.push([fv[0], fv[i], fv[i + 1]]);
if has_sub_mats {
out_tri_mats.push(mat);
}
}
}
}
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_sub_mats {
out_mesh.set_sub_materials(welded.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]
fn loop_subdiv_step(
verts: &[SubdivVertex],
tris: &[[u32; 3]],
tri_mats: &[u16],
) -> (Vec<SubdivVertex>, Vec<[u32; 3]>, Vec<u16>) {
let orig_v_count: usize = verts.len();
let mut edge_opps: HashMap<(u32, u32), Vec<u32>> = HashMap::with_capacity(tris.len() * 2);
let mut vert_nbrs: Vec<Vec<u32>> = vec![Vec::new(); orig_v_count];
for tri in tris.iter() {
let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
edge_opps.entry(edge_key(a, b)).or_default().push(c);
edge_opps.entry(edge_key(b, c)).or_default().push(a);
edge_opps.entry(edge_key(c, a)).or_default().push(b);
for (u, v) in [(a, b), (b, c), (c, a)] {
if !vert_nbrs[u as usize].contains(&v) {
vert_nbrs[u as usize].push(v);
}
if !vert_nbrs[v as usize].contains(&u) {
vert_nbrs[v as usize].push(u);
}
}
}
let mut next_verts: Vec<SubdivVertex> = Vec::with_capacity(orig_v_count + edge_opps.len());
for v_idx in 0..orig_v_count {
let orig: SubdivVertex = verts[v_idx];
let nbrs: &[u32] = &vert_nbrs[v_idx];
let mut bnd_nbrs: Vec<u32> = Vec::new();
for &nbr in nbrs.iter() {
let opp_count: usize = edge_opps
.get(&edge_key(v_idx as u32, nbr))
.map_or(0, |list: &Vec<u32>| list.len());
if opp_count == 1 {
bnd_nbrs.push(nbr);
}
}
let updated: SubdivVertex = if !bnd_nbrs.is_empty() {
if bnd_nbrs.len() == 2 {
blend_subdiv_vertices(&[
(orig, 0.75),
(verts[bnd_nbrs[0] as usize], 0.125),
(verts[bnd_nbrs[1] as usize], 0.125),
])
} else {
orig
}
} else {
let n: usize = nbrs.len();
if n >= 3 {
let nf: f32 = n as f32;
let term: f32 = 0.375 + 0.25 * (TAU / nf).cos();
let beta: f32 = (0.625 - term * term) / nf;
let mut blend_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(n + 1);
blend_terms.push((orig, 1.0 - nf * beta));
for &nbr in nbrs.iter() {
blend_terms.push((verts[nbr as usize], beta));
}
blend_subdiv_vertices(&blend_terms)
} else {
orig
}
};
next_verts.push(updated);
}
let mut edge_vert_map: HashMap<(u32, u32), u32> = HashMap::with_capacity(edge_opps.len());
for (&ek, opps) in edge_opps.iter() {
let va: SubdivVertex = verts[ek.0 as usize];
let vb: SubdivVertex = verts[ek.1 as usize];
let odd_pt: SubdivVertex = if opps.len() == 2 {
blend_subdiv_vertices(&[
(va, 0.375),
(vb, 0.375),
(verts[opps[0] as usize], 0.125),
(verts[opps[1] as usize], 0.125),
])
} else {
blend_subdiv_vertices(&[(va, 0.5), (vb, 0.5)])
};
let e_idx: u32 = next_verts.len() as u32;
next_verts.push(odd_pt);
edge_vert_map.insert(ek, e_idx);
}
let mut next_tris: Vec<[u32; 3]> = Vec::with_capacity(tris.len() * 4);
let has_mats: bool = !tri_mats.is_empty();
let mut next_mats: Vec<u16> = Vec::with_capacity(if has_mats { tris.len() * 4 } else { 0 });
for (ti, tri) in tris.iter().enumerate() {
let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
let ab: u32 = edge_vert_map.get(&edge_key(a, b)).copied().unwrap_or(a);
let bc: u32 = edge_vert_map.get(&edge_key(b, c)).copied().unwrap_or(b);
let ca: u32 = edge_vert_map.get(&edge_key(c, a)).copied().unwrap_or(c);
next_tris.push([a, ab, ca]);
next_tris.push([b, bc, ab]);
next_tris.push([c, ca, bc]);
next_tris.push([ab, bc, ca]);
if has_mats {
let slot: u16 = tri_mats.get(ti).copied().unwrap_or(0);
next_mats.push(slot);
next_mats.push(slot);
next_mats.push(slot);
next_mats.push(slot);
}
}
(next_verts, next_tris, next_mats)
}
#[must_use]
pub fn subdivide_loop(mesh: &Mesh3D, levels: u32) -> Mesh3D {
let iters: u32 = levels.min(SUBDIV_MAX_LEVELS);
if iters == 0 || mesh.get_indices().is_empty() {
return mesh.clone();
}
let welded: Mesh3D = weld_vertices(mesh, SUBDIV_WELD_EPSILON);
let mut verts: Vec<SubdivVertex> = welded
.get_vertices()
.iter()
.map(subdiv_vertex_from_mesh)
.collect();
let mut tris: Vec<[u32; 3]> = welded.get_indices().to_vec();
let mut tri_mats: Vec<u16> = welded.get_tri_materials().to_vec();
for _ in 0..iters {
let (nv, nt, nm): (Vec<SubdivVertex>, Vec<[u32; 3]>, Vec<u16>) =
loop_subdiv_step(&verts, &tris, &tri_mats);
verts = nv;
tris = nt;
tri_mats = nm;
}
let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
for sv in verts.into_iter() {
out_verts.push(subdiv_vertex_to_mesh(sv));
}
let mut out_mesh: Mesh3D = Mesh3D::from_parts(
mesh.get_name().clone(),
out_verts,
tris,
mesh.get_material(),
);
out_mesh.set_is_closed(mesh.get_is_closed());
if !tri_mats.is_empty() {
out_mesh.set_sub_materials(welded.get_sub_materials().clone());
out_mesh.set_tri_materials(tri_mats);
}
let smoothed: Mesh3D = recompute_smooth_normals(&out_mesh);
compute_tangents(&smoothed)
}