use super::*;
pub(crate) fn mesher_sanitize_f32(value: f32, fallback: f32) -> f32 {
if value.is_finite() { value } else { fallback }
}
pub(crate) fn metaball_wyvill_kernel(q_sq: f32) -> f32 {
if q_sq >= 1.0 {
return 0.0;
}
let diff: f32 = (1.0 - q_sq).max(0.0);
diff * diff * diff
}
pub(crate) fn compute_anisotropic_scales(
positions: &[Vec3],
config: LiquidMesherConfig,
out_scales: &mut Vec<Vec3>,
) {
let radius: f32 = config.get_influence_radius();
let inv_r: f32 = 1.0 / radius.max(1e-4);
out_scales.clear();
out_scales.resize(positions.len(), Vec3::splat(inv_r));
if !config.get_anisotropic() || config.get_anisotropy_strength() <= 1e-4 || positions.len() < 4
{
return;
}
let search_r: f32 = radius * 1.5;
let search_r_sq: f32 = search_r * search_r;
let strength: f32 = config.get_anisotropy_strength().clamp(0.0, 0.85);
let max_sample_check: usize = positions.len().min(512);
for (idx, &pi) in positions.iter().enumerate() {
let mut var_x: f32 = 0.0;
let mut var_y: f32 = 0.0;
let mut var_z: f32 = 0.0;
let mut w_sum: f32 = 0.0;
for &pj in positions.iter().take(max_sample_check) {
let diff: Vec3 = pj.sub(pi);
let d_sq: f32 = diff.length_sq();
if d_sq > 1e-10 && d_sq < search_r_sq {
let w: f32 = 1.0 - (d_sq / search_r_sq);
var_x += w * diff.get_x() * diff.get_x();
var_y += w * diff.get_y() * diff.get_y();
var_z += w * diff.get_z() * diff.get_z();
w_sum += w;
}
}
if w_sum > 1e-5 {
let sx: f32 = (var_x / w_sum).sqrt();
let sy: f32 = (var_y / w_sum).sqrt();
let sz: f32 = (var_z / w_sum).sqrt();
let mean: f32 = ((sx + sy + sz) / 3.0).max(1e-4);
let scale_x: f32 = (1.0 + strength * (sx / mean - 1.0)).clamp(0.65, 1.45);
let scale_y: f32 = (1.0 + strength * (sy / mean - 1.0)).clamp(0.65, 1.45);
let scale_z: f32 = (1.0 + strength * (sz / mean - 1.0)).clamp(0.65, 1.45);
out_scales[idx] = Vec3::new(inv_r / scale_x, inv_r / scale_y, inv_r / scale_z);
}
}
}
pub(crate) fn build_metaball_scalar_field_3d(
positions: &[Vec3],
config: LiquidMesherConfig,
scratch: &mut LiquidMesherScratch,
) -> Option<ScalarGrid3DDesc> {
if positions.is_empty() {
return None;
}
let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
let mut valid_count: usize = 0;
for &p in positions.iter() {
if p.get_x().is_finite() && p.get_y().is_finite() && p.get_z().is_finite() {
bounds.expand_point(p);
valid_count += 1;
}
}
if valid_count == 0 {
return None;
}
let radius: f32 = config.get_influence_radius();
let base_voxel: f32 = config.get_voxel_size();
let pad_m: f32 = radius + (config.get_padding_cells() as f32) * base_voxel;
let origin: Vec3 = bounds.get_min().sub(Vec3::splat(pad_m));
let upper: Vec3 = bounds.get_max().add(Vec3::splat(pad_m));
let span: Vec3 = upper.sub(origin);
let max_dim: usize = config.get_max_grid_dim();
let max_extent: f32 = span
.get_x()
.max(span.get_y())
.max(span.get_z())
.max(base_voxel);
let voxel_size: f32 = base_voxel.max(max_extent / (max_dim.saturating_sub(2).max(4) as f32));
let nx: usize = ((span.get_x() / voxel_size).ceil() as usize + 1).clamp(4, max_dim);
let ny: usize = ((span.get_y() / voxel_size).ceil() as usize + 1).clamp(4, max_dim);
let nz: usize = ((span.get_z() / voxel_size).ceil() as usize + 1).clamp(4, max_dim);
let total: usize = nx * ny * nz;
let mut aniso_scales: Vec<Vec3> = take(scratch.get_mut_aniso_scales());
compute_anisotropic_scales(positions, config, &mut aniso_scales);
let mut field: Vec<f32> = take(scratch.get_mut_scalar_field());
field.clear();
field.resize(total, 0.0);
let inv_voxel: f32 = 1.0 / voxel_size;
let max_reach: f32 = radius * 1.5;
let plane: usize = nx * ny;
for (idx, &p) in positions.iter().enumerate() {
if !p.get_x().is_finite() || !p.get_y().is_finite() || !p.get_z().is_finite() {
continue;
}
let inv_scale: Vec3 = aniso_scales[idx];
let rel: Vec3 = p.sub(origin);
let cx: f32 = rel.get_x() * inv_voxel;
let cy: f32 = rel.get_y() * inv_voxel;
let cz: f32 = rel.get_z() * inv_voxel;
let reach_cells: f32 = max_reach * inv_voxel;
let x0: usize = (cx - reach_cells).floor().max(0.0) as usize;
let x1: usize = (cx + reach_cells).ceil().min((nx - 1) as f32) as usize;
let y0: usize = (cy - reach_cells).floor().max(0.0) as usize;
let y1: usize = (cy + reach_cells).ceil().min((ny - 1) as f32) as usize;
let z0: usize = (cz - reach_cells).floor().max(0.0) as usize;
let z1: usize = (cz + reach_cells).ceil().min((nz - 1) as f32) as usize;
for iz in z0..=z1 {
let wz: f32 = origin.get_z() + iz as f32 * voxel_size;
let qz: f32 = (wz - p.get_z()) * inv_scale.get_z();
let qz2: f32 = qz * qz;
if qz2 >= 1.0 {
continue;
}
let z_off: usize = iz * plane;
for iy in y0..=y1 {
let wy: f32 = origin.get_y() + iy as f32 * voxel_size;
let qy: f32 = (wy - p.get_y()) * inv_scale.get_y();
let qyz2: f32 = qz2 + qy * qy;
if qyz2 >= 1.0 {
continue;
}
let row: usize = z_off + iy * nx;
for ix in x0..=x1 {
let wx: f32 = origin.get_x() + ix as f32 * voxel_size;
let qx: f32 = (wx - p.get_x()) * inv_scale.get_x();
let q_sq: f32 = qyz2 + qx * qx;
if q_sq < 1.0 {
field[row + ix] += metaball_wyvill_kernel(q_sq);
}
}
}
}
}
scratch.set_scalar_field(field);
scratch.set_aniso_scales(aniso_scales);
Some(ScalarGrid3DDesc::new(nx, ny, nz, origin, voxel_size))
}
pub(crate) fn sample_scalar_gradient_normal(
field: &[f32],
grid: ScalarGrid3DDesc,
world_pos: Vec3,
) -> Vec3 {
let nx: usize = grid.get_nx();
let ny: usize = grid.get_ny();
let nz: usize = grid.get_nz();
let voxel: f32 = grid.get_voxel_size();
let rel: Vec3 = world_pos.sub(grid.get_origin()).scale(1.0 / voxel);
let gx: f32 = rel.get_x().clamp(0.0, (nx - 1) as f32);
let gy: f32 = rel.get_y().clamp(0.0, (ny - 1) as f32);
let gz: f32 = rel.get_z().clamp(0.0, (nz - 1) as f32);
let eps: f32 = 0.5;
let shape: (usize, usize, usize) = (nx, ny, nz);
let (fx_p, _, _): (f32, f32, f32) =
mac_sample_3d_with_bounds(field, shape, Vec3::new(gx + eps, gy, gz));
let (fx_m, _, _): (f32, f32, f32) =
mac_sample_3d_with_bounds(field, shape, Vec3::new(gx - eps, gy, gz));
let (fy_p, _, _): (f32, f32, f32) =
mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy + eps, gz));
let (fy_m, _, _): (f32, f32, f32) =
mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy - eps, gz));
let (fz_p, _, _): (f32, f32, f32) =
mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy, gz + eps));
let (fz_m, _, _): (f32, f32, f32) =
mac_sample_3d_with_bounds(field, shape, Vec3::new(gx, gy, gz - eps));
let grad: Vec3 = Vec3::new(fx_m - fx_p, fy_m - fy_p, fz_m - fz_p);
let len: f32 = grad.length();
if len.is_finite() && len > 1e-6 {
grad.scale(1.0 / len)
} else {
Vec3::new(0.0, 1.0, 0.0)
}
}
pub(crate) fn run_marching_cubes_3d(
grid: ScalarGrid3DDesc,
config: LiquidMesherConfig,
scratch: &mut LiquidMesherScratch,
name: &str,
material: PbrMaterial,
) -> Mesh3D {
let nx: usize = grid.get_nx();
let ny: usize = grid.get_ny();
let nz: usize = grid.get_nz();
let origin: Vec3 = grid.get_origin();
let voxel: f32 = grid.get_voxel_size();
let iso: f32 = config.get_iso_level();
let weld: bool = config.get_weld_vertices();
let grad_normals: bool = config.get_smooth_normals_from_gradient();
let plane: usize = nx * ny;
let field: Vec<f32> = take(scratch.get_mut_scalar_field());
let mut edge_vertices: Vec<u32> = take(scratch.get_mut_edge_vertices());
if weld {
let edge_slots: usize = nx * ny * nz * 3;
edge_vertices.clear();
edge_vertices.resize(edge_slots, MC_UNASSIGNED_VERTEX);
}
let mut vertices: Vec<Vertex3D> = Vec::new();
let mut indices: Vec<[u32; 3]> = Vec::new();
for iz in 0..(nz - 1) {
for iy in 0..(ny - 1) {
for ix in 0..(nx - 1) {
let mut vals: [f32; 8] = [0.0; 8];
let mut mask: usize = 0;
for corner in 0..8 {
let off: [usize; 3] = FLUID_MC_CORNER_OFFSETS[corner];
let cx: usize = ix + off[0];
let cy: usize = iy + off[1];
let cz: usize = iz + off[2];
let val: f32 = field[cz * plane + cy * nx + cx];
vals[corner] = val;
if val >= iso {
mask |= 1usize << corner;
}
}
if mask == 0 || mask == 255 {
continue;
}
let tri_row: [i8; 16] = FLUID_MC_TRI_TABLE[mask];
let mut tri_cursor: usize = 0;
while tri_cursor < 15 && tri_row[tri_cursor] >= 0 {
let mut tri_v: [u32; 3] = [0; 3];
for slot in 0..3 {
let edge_id: usize = tri_row[tri_cursor + slot] as usize;
let edge_slot_off: [usize; 4] = MC_EDGE_SLOT_OFFSET[edge_id];
let ex: usize = ix + edge_slot_off[0];
let ey: usize = iy + edge_slot_off[1];
let ez: usize = iz + edge_slot_off[2];
let axis: usize = edge_slot_off[3];
let flat_edge: usize = ((ez * plane + ey * nx + ex) * 3) + axis;
if weld && edge_vertices[flat_edge] != MC_UNASSIGNED_VERTEX {
tri_v[slot] = edge_vertices[flat_edge];
continue;
}
let [c0, c1]: [usize; 2] = FLUID_MC_EDGE_CORNERS[edge_id];
let v0: f32 = vals[c0];
let v1: f32 = vals[c1];
let denom: f32 = v1 - v0;
let t: f32 = if denom.abs() > 1e-6 {
((iso - v0) / denom).clamp(0.0, 1.0)
} else {
0.5
};
let o0: [usize; 3] = FLUID_MC_CORNER_OFFSETS[c0];
let o1: [usize; 3] = FLUID_MC_CORNER_OFFSETS[c1];
let p0: Vec3 = Vec3::new(
origin.get_x() + (ix + o0[0]) as f32 * voxel,
origin.get_y() + (iy + o0[1]) as f32 * voxel,
origin.get_z() + (iz + o0[2]) as f32 * voxel,
);
let p1: Vec3 = Vec3::new(
origin.get_x() + (ix + o1[0]) as f32 * voxel,
origin.get_y() + (iy + o1[1]) as f32 * voxel,
origin.get_z() + (iz + o1[2]) as f32 * voxel,
);
let pos: Vec3 = p0.lerp(p1, t);
let normal: Vec3 = if grad_normals {
sample_scalar_gradient_normal(&field, grid, pos)
} else {
Vec3::new(0.0, 1.0, 0.0)
};
let vid: u32 = vertices.len() as u32;
vertices.push(Vertex3D::new(pos, normal));
if weld {
edge_vertices[flat_edge] = vid;
}
tri_v[slot] = vid;
}
if tri_v[0] != tri_v[1] && tri_v[1] != tri_v[2] && tri_v[2] != tri_v[0] {
indices.push(tri_v);
}
tri_cursor += 3;
}
}
}
}
scratch.set_scalar_field(field);
scratch.set_edge_vertices(edge_vertices);
let mesh_name: String = if name.is_empty() {
LIQUID_MESHER_DEFAULT_NAME.to_string()
} else {
name.to_string()
};
let mut mesh: Mesh3D = Mesh3D::from_parts(mesh_name, vertices, indices, material);
if !grad_normals {
mesh.compute_smooth_normals();
}
mesh.set_is_closed(true);
mesh
}
pub(crate) fn rasterize_metaballs_2d_impl(
positions: &[Vec2],
desc: &LiquidRaster2DDesc,
scratch: &mut LiquidMesherScratch,
out_rgba: &mut [u8],
) {
let width: usize = desc.get_width();
let height: usize = desc.get_height();
let total: usize = width.saturating_mul(height);
if total == 0 || out_rgba.len() < total * 4 {
return;
}
let wmin: Vec2 = desc.get_world_min();
let wmax: Vec2 = desc.get_world_max();
let span_x: f32 = (wmax.get_x() - wmin.get_x()).abs().max(1e-4);
let span_y: f32 = (wmax.get_y() - wmin.get_y()).abs().max(1e-4);
let radius: f32 = mesher_sanitize_f32(desc.get_influence_radius(), 0.12).max(1e-4);
let inv_r: f32 = 1.0 / radius;
let iso: f32 = mesher_sanitize_f32(desc.get_iso_level(), 0.35).clamp(0.05, 5.0);
let px_per_m_x: f32 = width as f32 / span_x;
let px_per_m_y: f32 = height as f32 / span_y;
let rad_px_x: f32 = radius * px_per_m_x;
let rad_px_y: f32 = radius * px_per_m_y;
let mut field: Vec<f32> = take(scratch.get_mut_raster_field());
field.clear();
field.resize(total, 0.0);
for &p in positions.iter() {
let px_w: f32 = p.get_x();
let py_w: f32 = p.get_y();
if !px_w.is_finite() || !py_w.is_finite() {
continue;
}
let cx: f32 = (px_w - wmin.get_x()) * px_per_m_x;
let cy: f32 = (wmax.get_y() - py_w) * px_per_m_y;
let x0: usize = (cx - rad_px_x).floor().max(0.0) as usize;
let x1: usize = (cx + rad_px_x).ceil().min((width - 1) as f32) as usize;
let y0: usize = (cy - rad_px_y).floor().max(0.0) as usize;
let y1: usize = (cy + rad_px_y).ceil().min((height - 1) as f32) as usize;
for py in y0..=y1 {
let wy: f32 = wmax.get_y() - (py as f32 + 0.5) / px_per_m_y;
let qy: f32 = (wy - py_w) * inv_r;
let qy2: f32 = qy * qy;
if qy2 >= 1.0 {
continue;
}
let row: usize = py * width;
for px in x0..=x1 {
let wx: f32 = wmin.get_x() + (px as f32 + 0.5) / px_per_m_x;
let qx: f32 = (wx - px_w) * inv_r;
let q_sq: f32 = qx * qx + qy2;
if q_sq < 1.0 {
field[row + px] += metaball_wyvill_kernel(q_sq);
}
}
}
}
let grad_scale: (f32, f32) = (
(px_per_m_x * radius * 0.14).max(1.2),
(px_per_m_y * radius * 0.14).max(1.2),
);
#[cfg(not(target_arch = "wasm32"))]
if height >= 32 && total >= 4096 {
let view: LiquidRgbaMutView = LiquidRgbaMutView {
ptr: out_rgba.as_mut_ptr(),
};
global_engine_worker_pool().parallel_for_chunks(
height,
8,
|y0: usize, y1: usize, _: usize| {
let byte_offset: usize = y0 * width * 4;
let byte_len: usize = (y1 - y0) * width * 4;
let row_rgba: &mut [u8] =
unsafe { from_raw_parts_mut(view.ptr().add(byte_offset), byte_len) };
shade_metaball_row_band(&field, desc, iso, grad_scale, (y0, y1), row_rgba);
},
);
scratch.set_raster_field(field);
return;
}
shade_metaball_row_band(
&field,
desc,
iso,
grad_scale,
(0, height),
&mut out_rgba[..total * 4],
);
scratch.set_raster_field(field);
}
pub(crate) fn shade_metaball_row_band(
field: &[f32],
desc: &LiquidRaster2DDesc,
iso: f32,
grad_scale: (f32, f32),
rows: (usize, usize),
out_rgba: &mut [u8],
) {
let width: usize = desc.get_width();
let height: usize = desc.get_height();
let (y_start, y_end): (usize, usize) = rows;
let (grad_scale_x, grad_scale_y): (f32, f32) = grad_scale;
let bg: [u8; 4] = desc.get_background_rgba();
let bg_r: f32 = bg[0] as f32 / 255.0;
let bg_g: f32 = bg[1] as f32 / 255.0;
let bg_b: f32 = bg[2] as f32 / 255.0;
let deep: Vec3 = desc.get_deep_color();
let shallow: Vec3 = desc.get_shallow_color();
let spec_col: Vec3 = desc.get_specular_color();
let light_dir: Vec3 = Vec3::new(-0.45, 0.72, 0.52).normalize();
let half_v: Vec3 = light_dir.add(Vec3::new(0.0, 0.0, 1.0)).normalize();
let aa_band: f32 = (iso * 0.22).max(0.03);
for py in y_start..y_end {
let row: usize = py * width;
let row_local: usize = (py - y_start) * width;
let row_up: usize = py.saturating_sub(1) * width;
let row_dn: usize = (py + 1).min(height - 1) * width;
for px in 0..width {
let idx: usize = row + px;
let val: f32 = field[idx];
let base: usize = (row_local + px) * 4;
let cov: f32 = ((val - (iso - aa_band)) / (2.0 * aa_band)).clamp(0.0, 1.0);
if cov <= 1e-4 {
out_rgba[base] = bg[0];
out_rgba[base + 1] = bg[1];
out_rgba[base + 2] = bg[2];
out_rgba[base + 3] = bg[3];
continue;
}
let xl: usize = px.saturating_sub(1);
let xr: usize = (px + 1).min(width - 1);
let gx: f32 = field[row + xl] - field[row + xr];
let gy: f32 = field[row_dn + px] - field[row_up + px];
let normal: Vec3 = Vec3::new(gx * grad_scale_x, gy * grad_scale_y, 0.48).normalize();
let depth_t: f32 = ((val - iso) / (iso * 2.5)).clamp(0.0, 1.0);
let tint: Vec3 = shallow.lerp(deep, depth_t);
let fresnel: f32 =
(0.04 + 0.96 * (1.0 - normal.get_z().clamp(0.0, 1.0)).powi(4)).clamp(0.0, 1.0);
let diff: f32 = (0.45 + 0.55 * normal.dot(light_dir).max(0.0)).clamp(0.0, 1.0);
let spec: f32 = normal.dot(half_v).max(0.0).powi(28);
let col: Vec3 = tint
.scale(diff)
.add(spec_col.scale(0.34 * fresnel + 0.78 * spec));
let r: f32 = bg_r + (col.get_x().clamp(0.0, 1.0) - bg_r) * cov;
let g: f32 = bg_g + (col.get_y().clamp(0.0, 1.0) - bg_g) * cov;
let b: f32 = bg_b + (col.get_z().clamp(0.0, 1.0) - bg_b) * cov;
out_rgba[base] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
out_rgba[base + 1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
out_rgba[base + 2] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
out_rgba[base + 3] = 255;
}
}
}