primitive meshes

This commit is contained in:
Jérôme Bousquié
2026-09-24 14:25:44 +02:00
parent 805babe53d
commit ab3f056dbb
36 changed files with 1531 additions and 808 deletions
+20
View File
@@ -0,0 +1,20 @@
//! glTF 2.0 / GLB loader.
//!
//! **Status: stub** — the full implementation requires the `gltf` crate and will
//! be added in a follow-up. For now, this module compiles (behind `feature = "import-gltf"`)
//! and returns a clear error.
use crate::core::geometry::Geometry;
use crate::mesh::import::MeshImportError;
use std::path::Path;
/// Loads a glTF 2.0 (.gltf JSON) or GLB (.glb binary) file.
///
/// # Errors
/// Always returns [`MeshImportError::Unsupported`] for now (implementation pending).
pub fn load_gltf(path: impl AsRef<Path>) -> Result<Vec<Geometry>, MeshImportError> {
let _ = path;
Err(MeshImportError::Unsupported(
"glTF import is not yet implemented (pending gltf crate wrapper)".into(),
))
}
+31
View File
@@ -0,0 +1,31 @@
//! File import loaders — each behind a feature flag.
//!
//! | Feature | Function | Format |
//!|---------|----------|--------|
//!| `import-obj` | `load_obj(path)` | Wavefront OBJ |
//!| `import-gltf` | `load_gltf(path)` | glTF 2.0 / GLB |
#[cfg(feature = "import-obj")]
pub mod obj;
#[cfg(feature = "import-gltf")]
#[path = "gltf.rs"]
pub mod gltf_loader;
#[cfg(feature = "import-obj")]
pub use obj::{load_obj, parse_obj};
#[cfg(feature = "import-gltf")]
pub use gltf_loader::load_gltf;
/// Error type for mesh file import.
#[derive(thiserror::Error, Debug)]
pub enum MeshImportError {
/// The file could not be read (I/O error).
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
/// The file content is malformed or cannot be parsed.
#[error("parse error: {0}")]
Parse(String),
/// The file uses features not supported by this loader.
#[error("unsupported format: {0}")]
Unsupported(String),
}
+311
View File
@@ -0,0 +1,311 @@
//! Wavefront OBJ parser — minimal, dependency-free.
//!
//! Supports: `v` (position), `vn` (normal), `vt` (UV), `f` (face, 3-4 verts).
//! Quads are split into triangles via fan triangulation.
use crate::core::geometry::Geometry;
use crate::mesh::import::MeshImportError;
use std::path::Path;
/// Parses a Wavefront OBJ file and returns a single [`Geometry`].
///
/// Supported directives: `v`, `vn`, `vt`, `f` (3 or 4 vertices per face).
/// Vertex references in `f` use 1-based indices.
/// If no `vn` lines are present, normals are computed (area-weighted face normals).
/// If no `vt` lines are present, UVs are omitted.
///
/// # Errors
/// Returns [`MeshImportError::Io`] if the file cannot be read,
/// or [`MeshImportError::Parse`] on malformed input.
pub fn load_obj(path: impl AsRef<Path>) -> Result<Geometry, MeshImportError> {
let content = std::fs::read_to_string(path).map_err(MeshImportError::Io)?;
parse_obj(&content)
}
/// Parses OBJ content from a string. See [`load_obj`] for supported features.
pub fn parse_obj(content: &str) -> Result<Geometry, MeshImportError> {
let mut positions: Vec<[f32; 3]> = Vec::new();
let mut file_normals: Vec<[f32; 3]> = Vec::new();
let mut file_uvs: Vec<[f32; 2]> = Vec::new();
// Unique vertex table: (pos_idx, opt_uv_idx, opt_norm_idx)
let mut vert_table: Vec<(usize, Option<usize>, Option<usize>)> = Vec::new();
let mut indices: Vec<u16> = Vec::new();
for (line_num, raw) in content.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
match parts[0] {
"v" => {
if parts.len() < 4 {
return Err(MeshImportError::Parse(format!(
"line {}: 'v' needs 3+ components",
line_num + 1
)));
}
let x = parts[1].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'v' x = '{}'", line_num + 1, parts[1]))
})?;
let y = parts[2].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'v' y = '{}'", line_num + 1, parts[2]))
})?;
let z = parts[3].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'v' z = '{}'", line_num + 1, parts[3]))
})?;
positions.push([x, y, z]);
}
"vn" => {
if parts.len() < 4 {
return Err(MeshImportError::Parse(format!(
"line {}: 'vn' needs 3+ components",
line_num + 1
)));
}
let x = parts[1].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'vn' x", line_num + 1))
})?;
let y = parts[2].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'vn' y", line_num + 1))
})?;
let z = parts[3].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'vn' z", line_num + 1))
})?;
file_normals.push([x, y, z]);
}
"vt" => {
if parts.len() < 3 {
return Err(MeshImportError::Parse(format!(
"line {}: 'vt' needs 2+ components",
line_num + 1
)));
}
let u = parts[1].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'vt' u", line_num + 1))
})?;
let v = parts[2].parse::<f32>().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad 'vt' v", line_num + 1))
})?;
file_uvs.push([u, v]);
}
"f" => {
if parts.len() < 4 {
return Err(MeshImportError::Parse(format!(
"line {}: 'f' needs 3+ vertices, got {}",
line_num + 1,
parts.len() - 1
)));
}
// Parse vertex references: "idx" or "idx/uv" or "idx/uv/norm"
let face_verts: Vec<(usize, Option<usize>, Option<usize>)> = parts[1..]
.iter()
.map(|tok| {
let mut fields = tok.split('/');
let idx_str = fields.next().unwrap_or("0");
let uv_str = fields.next();
let norm_str = fields.next();
let idx: usize = idx_str.parse().map_err(|_| {
MeshImportError::Parse(format!(
"line {}: bad face vertex index '{}'",
line_num + 1,
tok
))
})?;
if idx == 0 {
return Err(MeshImportError::Parse(format!(
"line {}: 0-based index not allowed in face",
line_num + 1
)));
}
let uv_idx = parse_opt_idx(uv_str, line_num, "uv")?;
let norm_idx = parse_opt_idx(norm_str, line_num, "norm")?;
Ok((idx - 1, uv_idx, norm_idx))
})
.collect::<Result<_, _>>()?;
// Map to unique vertex indices (dedup by pos+uv+norm tuple)
let mapped: Vec<u16> = face_verts
.iter()
.map(|&(pi, uvi, ni)| {
// Check if this combo already exists
if let Some(pos) = vert_table.iter().position(|&(ep, eu, en)| {
ep == pi && eu == uvi && en == ni
}) {
pos as u16
} else {
vert_table.push((pi, uvi, ni));
(vert_table.len() - 1) as u16
}
})
.collect();
// Fan triangulation
if mapped.len() == 3 {
indices.extend_from_slice(&mapped);
} else if mapped.len() > 3 {
for i in 1..mapped.len() - 1 {
indices.extend_from_slice(&[mapped[0], mapped[i], mapped[i + 1]]);
}
}
}
_ => {} // Ignore unknown directives
}
}
if positions.is_empty() {
return Err(MeshImportError::Parse("no vertices found".into()));
}
if vert_table.is_empty() {
return Err(MeshImportError::Parse("no faces found".into()));
}
// Build output vertex arrays from the table
let mut out_positions = Vec::with_capacity(vert_table.len());
let mut out_normals = Vec::with_capacity(vert_table.len());
let mut out_uvs = Vec::with_capacity(vert_table.len());
let mut has_any_uv = false;
for &(pi, uvi, ni) in &vert_table {
out_positions.push(positions[pi]);
if let Some(ni) = ni {
out_normals.push(file_normals[ni]);
} else {
out_normals.push([0.0, 0.0, 0.0]);
}
if let Some(uvi) = uvi {
out_uvs.push(file_uvs[uvi]);
has_any_uv = true;
} else {
out_uvs.push([0.0, 0.0]);
}
}
// Compute normals if file had none
if file_normals.is_empty() {
compute_normals(&out_positions, &indices, &mut out_normals);
}
let mut geo = Geometry::new(out_positions)
.with_normals(out_normals)
.with_indices(indices);
if has_any_uv {
geo = geo.with_uvs(out_uvs);
}
geo.validate()
.map_err(|e| MeshImportError::Parse(format!("validation failed: {e}")))?;
Ok(geo)
}
fn parse_opt_idx(
field: Option<&str>,
line_num: usize,
what: &str,
) -> Result<Option<usize>, MeshImportError> {
match field {
None | Some("") => Ok(None),
Some(s) => {
let idx: usize = s.parse().map_err(|_| {
MeshImportError::Parse(format!("line {}: bad {what} index '{s}'", line_num + 1))
})?;
if idx == 0 {
return Err(MeshImportError::Parse(format!(
"line {}: 0-based {what} index",
line_num + 1
)));
}
Ok(Some(idx - 1))
}
}
}
/// Computes area-weighted vertex normals from triangle faces.
fn compute_normals(positions: &[[f32; 3]], indices: &[u16], normals: &mut [[f32; 3]]) {
use glam::Vec3;
for n in normals.iter_mut() {
*n = [0.0, 0.0, 0.0];
}
for tri in indices.chunks(3) {
if tri.len() != 3 {
continue;
}
let (a, b, c) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
let pa = Vec3::from_array(positions[a]);
let pb = Vec3::from_array(positions[b]);
let pc = Vec3::from_array(positions[c]);
let fn_ = (pb - pa).cross(pc - pa);
for idx in [a, b, c] {
let n = &mut normals[idx];
n[0] += fn_.x;
n[1] += fn_.y;
n[2] += fn_.z;
}
}
for n in normals.iter_mut() {
let v = Vec3::from_array(*n);
*n = v.normalize().to_array();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_simple_triangle() {
let content = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
let geo = parse_obj(content).unwrap();
assert_eq!(geo.positions.len(), 3);
assert_eq!(geo.indices.as_ref().unwrap().len(), 3);
geo.validate().unwrap();
}
#[test]
fn parse_quad_splits_to_two_tris() {
let content = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1 2 3 4\n";
let geo = parse_obj(content).unwrap();
assert_eq!(geo.positions.len(), 4);
assert_eq!(geo.indices.as_ref().unwrap().len(), 6);
}
#[test]
fn parse_with_normals_and_uvs() {
let content = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvn 0 0 1\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1/1 2/2/1 3/3/1\n";
let geo = parse_obj(content).unwrap();
assert!(geo.normals.is_some());
assert!(geo.uvs.is_some());
let n = geo.normals.as_ref().unwrap();
assert_eq!(n[0], [0.0, 0.0, 1.0]);
}
#[test]
fn parse_no_normals_computes_them() {
let content = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
let geo = parse_obj(content).unwrap();
let n = geo.normals.as_ref().unwrap();
assert!((n[0][2] - 1.0).abs() < 1e-4, "expected +Z normal, got {:?}", n[0]);
}
#[test]
fn parse_empty_fails() {
assert!(parse_obj("").is_err());
assert!(parse_obj("# just a comment\n").is_err());
}
#[test]
fn parse_malformed_fails() {
assert!(parse_obj("v 1 2\nf 1 2 3\n").is_err());
assert!(parse_obj("v 0 0 0\nv 1 0 0\nf 1 2\n").is_err());
}
#[test]
fn parse_shared_vertex_dedup() {
let content = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1 2 3\nf 1 3 4\n";
let geo = parse_obj(content).unwrap();
assert_eq!(geo.positions.len(), 4);
assert_eq!(geo.indices.as_ref().unwrap().len(), 6);
}
}
+58
View File
@@ -0,0 +1,58 @@
//! # Mesh module — geometry sources for WSG
//!
//! This module is the single entry point for **where geometry data comes from**:
//!
//! - **`primitives`** — procedural generators (cube, sphere, torus, …), each behind a
//! feature flag so you only compile what you need.
//! - **`import`** — file loaders (OBJ, glTF), each behind a feature flag.
//!
//! All sources produce a [`Geometry`] (CPU-side vertex data: positions, normals, UVs,
//! indices). Turning that into a GPU renderable is the job of [`crate::scene::Scene::add_mesh`].
//!
//! ## Usage
//!
//! ```rust
//! use wsg_lib::mesh::cube;
//!
//! // Procedural (feature "prim-cube")
//! let geom = cube(2.0);
//! assert_eq!(geom.positions.len(), 24);
//! ```
//!
//! ## Features
//!
//! | Feature | Provides |
//! |---------|----------|
//! | `prim-cube` | `cube(size)` |
//! | `prim-sphere` | `uv_sphere(…)`, `icosphere(…)` |
//! | `prim-cylinder` | `cylinder(…)` |
//! | `prim-cone` | `cone(…)` |
//! | `prim-torus` | `torus(…)` |
//! | `prim-plane` | `plane(…)` |
//! | `all-prims` | all of the above |
//! | `import-obj` | `load_obj(path)` |
//! | `import-gltf` | `load_gltf(path)` |
pub mod primitives;
#[cfg(feature = "import-obj")]
pub mod import;
// Flat re-exports at the `wsg::mesh` level for convenience.
#[cfg(feature = "prim-cube")]
pub use primitives::cube;
#[cfg(feature = "prim-plane")]
pub use primitives::plane;
#[cfg(feature = "prim-sphere")]
pub use primitives::{icosphere, uv_sphere};
#[cfg(feature = "prim-cylinder")]
pub use primitives::cylinder;
#[cfg(feature = "prim-cone")]
pub use primitives::cone;
#[cfg(feature = "prim-torus")]
pub use primitives::torus;
#[cfg(feature = "import-obj")]
pub use import::load_obj;
#[cfg(feature = "import-gltf")]
pub use import::load_gltf;
+89
View File
@@ -0,0 +1,89 @@
//! Cone primitive — side (apex + base ring) + base cap.
use crate::core::geometry::Geometry;
use glam::Vec3;
/// Generates a cone of radius `radius` and height `height` (apex at +h/2, base at -h/2), closed by a
/// base, with `sectors` segments. Analytical side normals (tilted outward);
/// base normal −Y.
pub fn cone(radius: f32, height: f32, sectors: u32) -> Geometry {
let si = sectors.max(3);
let h = height * 0.5;
let (mut positions, mut normals, mut uvs, mut indices) = (
Vec::<[f32; 3]>::new(),
Vec::<[f32; 3]>::new(),
Vec::<[f32; 2]>::new(),
Vec::<u16>::new(),
);
// Side elements: apex + base ring.
let apex = 0u16;
positions.push([0.0, h, 0.0]);
normals.push([0.0, 1.0, 0.0]); // shared apex; normal close to +Y by default
uvs.push([0.5, 1.0]);
let base_start = 1u16;
for s in 0..=si {
let u = s as f32 / si as f32;
let theta = u * 2.0 * std::f32::consts::PI;
let (sin_t, cos_t) = theta.sin_cos();
positions.push([radius * cos_t, -h, radius * sin_t]);
// Side normal: normalize(h·cosθ, r, h·sinθ).
let n = Vec3::new(h * cos_t, radius, h * sin_t).normalize();
normals.push(n.to_array());
uvs.push([u, 0.0]);
}
for s in 0..si {
indices.extend_from_slice(&[apex, base_start + s as u16 + 1, base_start + s as u16]);
}
// Closed base (circle at -h/2, normal -Y).
let center = positions.len() as u16;
positions.push([0.0, -h, 0.0]);
normals.push([0.0, -1.0, 0.0]);
uvs.push([0.5, 0.5]);
let ring = positions.len() as u16;
for s in 0..=si {
let u = s as f32 / si as f32;
let theta = u * 2.0 * std::f32::consts::PI;
let (sin_t, cos_t) = theta.sin_cos();
positions.push([radius * cos_t, -h, radius * sin_t]);
normals.push([0.0, -1.0, 0.0]);
uvs.push([0.5 + 0.5 * cos_t, 0.5 + 0.5 * sin_t]);
}
for s in 0..si {
let r = ring + s as u16;
indices.extend_from_slice(&[center, r, r + 1]);
}
Geometry::new(positions)
.with_normals(normals)
.with_uvs(uvs)
.with_indices(indices)
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_valid(geo: &Geometry) {
geo.validate().expect("generated geometry must validate");
let positions = &geo.positions;
let normals = geo.normals.as_ref().expect("normals present");
let uvs = geo.uvs.as_ref().expect("uvs present");
let indices = geo.indices.as_ref().expect("indices present");
assert_eq!(normals.len(), positions.len());
assert_eq!(uvs.len(), positions.len());
for n in normals {
let len = Vec3::from_array(*n).length();
assert!((len - 1.0).abs() < 1e-3);
}
for &i in indices {
assert!((i as usize) < positions.len());
}
}
#[test]
fn cone_validate() {
assert_valid(&cone(0.5, 1.0, 16));
}
}
+97
View File
@@ -0,0 +1,97 @@
//! Cube primitive — 24 vertices (4 per face) + 36 indices.
use crate::core::geometry::Geometry;
/// Generates a cube centered at the origin, edge `size`, with one normal and UVs per face.
/// 24 vertices (4 per face) + 36 indices.
pub fn cube(size: f32) -> Geometry {
let s = size * 0.5;
let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [
(
[0.0, 0.0, 1.0],
[[-s, -s, s], [s, -s, s], [s, s, s], [-s, s, s]],
),
(
[0.0, 0.0, -1.0],
[[s, -s, -s], [-s, -s, -s], [-s, s, -s], [s, s, -s]],
),
(
[1.0, 0.0, 0.0],
[[s, -s, -s], [s, s, -s], [s, s, s], [s, -s, s]],
),
(
[-1.0, 0.0, 0.0],
[[-s, -s, s], [-s, s, s], [-s, s, -s], [-s, -s, -s]],
),
(
[0.0, 1.0, 0.0],
[[-s, s, -s], [s, s, -s], [s, s, s], [-s, s, s]],
),
(
[0.0, -1.0, 0.0],
[[-s, -s, s], [s, -s, s], [s, -s, -s], [-s, -s, -s]],
),
];
let mut positions = Vec::with_capacity(24);
let mut normals = Vec::with_capacity(24);
let mut uvs = Vec::with_capacity(24);
let quad_uvs = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
for (normal, corners) in faces {
for (i, corner) in corners.iter().enumerate() {
positions.push(*corner);
normals.push(normal);
uvs.push(quad_uvs[i]);
}
}
let mut indices = Vec::with_capacity(36);
for face in 0..6u16 {
let b = face * 4;
indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]);
}
Geometry::new(positions)
.with_normals(normals)
.with_uvs(uvs)
.with_indices(indices)
}
#[cfg(test)]
mod tests {
use super::*;
use glam::Vec3;
fn assert_valid(geo: &Geometry) {
geo.validate().expect("generated geometry must validate");
let positions = &geo.positions;
let normals = geo.normals.as_ref().expect("normals present");
let uvs = geo.uvs.as_ref().expect("uvs present");
let indices = geo.indices.as_ref().expect("indices present");
assert_eq!(normals.len(), positions.len(), "normals/positions count");
assert_eq!(uvs.len(), positions.len(), "uvs/positions count");
for n in normals {
let len = Vec3::from_array(*n).length();
assert!((len - 1.0).abs() < 1e-3, "unit normal, got {len}");
}
for &i in indices {
assert!((i as usize) < positions.len(), "index {i} in bounds");
}
}
#[test]
fn cube_counts() {
let g = cube(1.0);
assert_eq!(g.positions.len(), 24);
assert_eq!(g.indices.as_ref().unwrap().len(), 36);
assert_valid(&g);
let g2 = cube(2.0);
assert_eq!(
g2.positions,
g.positions
.iter()
.map(|p| [p[0] * 2.0, p[1] * 2.0, p[2] * 2.0])
.collect::<Vec<_>>()
);
}
}
+94
View File
@@ -0,0 +1,94 @@
//! Cylinder primitive — side + top/bottom caps.
use crate::core::geometry::Geometry;
use glam::Vec3;
/// Generates a cylinder of radius `radius` and height `height` (along Y, centered), with
/// `sectors` segments. Parts: side (smooth radial normals), top cap (+Y), bottom base (−Y).
pub fn cylinder(radius: f32, height: f32, sectors: u32) -> Geometry {
let si = sectors.max(3);
let h = height * 0.5;
let (mut positions, mut normals, mut uvs, mut indices) = (
Vec::<[f32; 3]>::new(),
Vec::<[f32; 3]>::new(),
Vec::<[f32; 2]>::new(),
Vec::<u16>::new(),
);
// Side: radial columns × 2 rows (bottom/top).
let side_base = 0u16;
for row in 0..=1 {
let y = if row == 0 { -h } else { h };
for s in 0..=si {
let u = s as f32 / si as f32;
let theta = u * 2.0 * std::f32::consts::PI;
let (sin_t, cos_t) = theta.sin_cos();
let radial = Vec3::new(cos_t, 0.0, sin_t);
positions.push((radial * radius + Vec3::new(0.0, y, 0.0)).to_array());
normals.push(radial.to_array());
uvs.push([u, row as f32]);
}
}
for s in 0..si {
let a = side_base + s as u16;
let b = a + 1;
let c = side_base + (si as u16) + 1 + s as u16;
let d = c + 1;
indices.extend_from_slice(&[a, c, b, b, c, d]);
}
// Caps: center + ring at each end.
for (y, normal) in [(h, [0.0, 1.0, 0.0]), (-h, [0.0, -1.0, 0.0])] {
let center = positions.len() as u16;
positions.push([0.0, y, 0.0]);
normals.push(normal);
uvs.push([0.5, 0.5]);
let ring_start = positions.len() as u16;
for s in 0..=si {
let u = s as f32 / si as f32;
let theta = u * 2.0 * std::f32::consts::PI;
let (sin_t, cos_t) = theta.sin_cos();
positions.push([radius * cos_t, y, radius * sin_t]);
normals.push(normal);
uvs.push([0.5 + 0.5 * cos_t, 0.5 + 0.5 * sin_t]);
}
for s in 0..si {
let a = ring_start + s as u16;
indices.extend_from_slice(&[center, a + 1, a]);
}
}
Geometry::new(positions)
.with_normals(normals)
.with_uvs(uvs)
.with_indices(indices)
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_valid(geo: &Geometry) {
geo.validate().expect("generated geometry must validate");
let positions = &geo.positions;
let normals = geo.normals.as_ref().expect("normals present");
let uvs = geo.uvs.as_ref().expect("uvs present");
let indices = geo.indices.as_ref().expect("indices present");
assert_eq!(normals.len(), positions.len());
assert_eq!(uvs.len(), positions.len());
for n in normals {
let len = Vec3::from_array(*n).length();
assert!((len - 1.0).abs() < 1e-3);
}
for &i in indices {
assert!((i as usize) < positions.len());
}
}
#[test]
fn cylinder_validate() {
assert_valid(&cylinder(0.5, 1.0, 16));
let c = cylinder(0.5, 1.0, 8);
assert!(c.positions.iter().all(|p| p[1].abs() <= 0.5 + 1e-5));
}
}
+33
View File
@@ -0,0 +1,33 @@
//! Procedural mesh generators — each behind a feature flag.
//!
//! Enable features in `Cargo.toml`:
//! ```toml
//! wsg = { features = ["prim-cube", "prim-sphere"] }
//! ```
#[cfg(feature = "prim-cube")]
pub mod cube;
#[cfg(feature = "prim-plane")]
pub mod plane;
#[cfg(feature = "prim-sphere")]
pub mod sphere;
#[cfg(feature = "prim-cylinder")]
pub mod cylinder;
#[cfg(feature = "prim-cone")]
pub mod cone;
#[cfg(feature = "prim-torus")]
pub mod torus;
// Flat re-exports: `use wsg::mesh::primitives::cube` or `use wsg::mesh::cube`
#[cfg(feature = "prim-cube")]
pub use cube::cube;
#[cfg(feature = "prim-plane")]
pub use plane::plane;
#[cfg(feature = "prim-sphere")]
pub use sphere::{icosphere, uv_sphere};
#[cfg(feature = "prim-cylinder")]
pub use cylinder::cylinder;
#[cfg(feature = "prim-cone")]
pub use cone::cone;
#[cfg(feature = "prim-torus")]
pub use torus::torus;
+74
View File
@@ -0,0 +1,74 @@
//! Plane primitive — horizontal plane in XZ with subdivisions.
use crate::core::geometry::Geometry;
/// Generates a horizontal plane in the XZ plane (normal +Y), centered at (0, 0, 0), with
/// `width` × `depth` dimensions, subdivided into `seg_x` × `seg_z` cells.
pub fn plane(width: f32, depth: f32, seg_x: u32, seg_z: u32) -> Geometry {
let sx = seg_x.max(1);
let sz = seg_z.max(1);
let (mut positions, mut normals, mut uvs, mut indices) = (
Vec::<[f32; 3]>::new(),
Vec::<[f32; 3]>::new(),
Vec::<[f32; 2]>::new(),
Vec::<u16>::new(),
);
for z in 0..=sz {
let vz = z as f32 / sz as f32;
for x in 0..=sx {
let vx = x as f32 / sx as f32;
positions.push([(vx - 0.5) * width, 0.0, (vz - 0.5) * depth]);
normals.push([0.0, 1.0, 0.0]);
uvs.push([vx, vz]);
}
}
for z in 0..sz {
for x in 0..sx {
let a = z * (sx + 1) + x;
let b = a + 1;
let c = (z + 1) * (sx + 1) + x;
let d = c + 1;
indices
.extend_from_slice(&[a as u16, c as u16, b as u16, b as u16, c as u16, d as u16]);
}
}
Geometry::new(positions)
.with_normals(normals)
.with_uvs(uvs)
.with_indices(indices)
}
#[cfg(test)]
mod tests {
use super::*;
use glam::Vec3;
fn assert_valid(geo: &Geometry) {
geo.validate().expect("generated geometry must validate");
let positions = &geo.positions;
let normals = geo.normals.as_ref().expect("normals present");
let uvs = geo.uvs.as_ref().expect("uvs present");
let indices = geo.indices.as_ref().expect("indices present");
assert_eq!(normals.len(), positions.len());
assert_eq!(uvs.len(), positions.len());
for n in normals {
let len = Vec3::from_array(*n).length();
assert!((len - 1.0).abs() < 1e-3);
}
for &i in indices {
assert!((i as usize) < positions.len());
}
}
#[test]
fn plane_counts() {
let g = plane(2.0, 3.0, 1, 1);
assert_eq!(g.positions.len(), 4);
assert_eq!(g.indices.as_ref().unwrap().len(), 6);
assert_valid(&g);
assert!(g.positions.iter().all(|p| p[1] == 0.0));
let g2 = plane(2.0, 3.0, 4, 5);
assert_eq!(g2.positions.len(), (4 + 1) * (5 + 1));
assert_valid(&g2);
}
}
+176
View File
@@ -0,0 +1,176 @@
//! Sphere primitives — UV sphere (lat/long) + icosphere (subdivided icosahedron).
use crate::core::geometry::Geometry;
use glam::Vec3;
use std::collections::HashMap;
/// Generates a UV (latitude/longitude) sphere of radius `radius`, with `sectors` segments around
/// and `stacks` vertical rings. Smooth normals = normalized position; spherical UVs.
pub fn uv_sphere(radius: f32, sectors: u32, stacks: u32) -> Geometry {
let si = sectors.max(3);
let st = stacks.max(3);
let (mut positions, mut normals, mut uvs, mut indices) = (
Vec::<[f32; 3]>::new(),
Vec::<[f32; 3]>::new(),
Vec::<[f32; 2]>::new(),
Vec::<u16>::new(),
);
for stack in 0..=st {
let v = stack as f32 / st as f32;
let phi = v * std::f32::consts::PI;
for sector in 0..=si {
let u = sector as f32 / si as f32;
let theta = u * 2.0 * std::f32::consts::PI;
let (sin_p, cos_p) = phi.sin_cos();
let (sin_t, cos_t) = theta.sin_cos();
let pos = Vec3::new(
radius * sin_p * cos_t,
radius * cos_p,
radius * sin_p * sin_t,
);
positions.push(pos.to_array());
normals.push(pos.normalize().to_array());
uvs.push([u, v]);
}
}
for stack in 0..st {
for sector in 0..si {
let k1 = stack * (si + 1) + sector;
let k2 = k1 + si + 1;
let (k1, k2) = (k1 as u16, k2 as u16);
indices.extend_from_slice(&[k1, k2, k1 + 1, k1 + 1, k2, k2 + 1]);
}
}
Geometry::new(positions)
.with_normals(normals)
.with_uvs(uvs)
.with_indices(indices)
}
/// Generates an icosphere (subdivided icosahedron) of radius `radius`.
/// `subdivisions = 0` gives an icosahedron (12 verts / 20 faces); each subdivision refines ×4.
pub fn icosphere(radius: f32, subdivisions: u32) -> Geometry {
let t = (1.0 + 5.0_f32.sqrt()) * 0.5;
let mut positions: Vec<Vec3> = [
[-1.0, t, 0.0], [1.0, t, 0.0], [-1.0, -t, 0.0], [1.0, -t, 0.0],
[0.0, -1.0, t], [0.0, 1.0, t], [0.0, -1.0, -t], [0.0, 1.0, -t],
[t, 0.0, -1.0], [t, 0.0, 1.0], [-t, 0.0, -1.0], [-t, 0.0, 1.0],
]
.iter()
.map(|v| Vec3::from_array(*v).normalize())
.collect();
let mut faces: Vec<[u32; 3]> = [
[0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11],
[1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8],
[3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9],
[4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1],
]
.into_iter()
.collect();
for _ in 0..subdivisions {
let mut midpoint = HashMap::new();
let old_faces = std::mem::take(&mut faces);
for [a, b, c] in old_faces {
let ab = subdiv_midpoint(&mut positions, &mut midpoint, a, b);
let bc = subdiv_midpoint(&mut positions, &mut midpoint, b, c);
let ca = subdiv_midpoint(&mut positions, &mut midpoint, c, a);
faces.push([a, ab, ca]);
faces.push([ab, b, bc]);
faces.push([ca, bc, c]);
faces.push([ab, bc, ca]);
}
}
let mut normals = Vec::with_capacity(positions.len());
let mut uvs = Vec::with_capacity(positions.len());
for p in &positions {
let dir = p.normalize();
normals.push(dir.to_array());
uvs.push(spherical_uv(dir));
}
let scaled: Vec<[f32; 3]> = positions.iter().map(|p| (*p * radius).to_array()).collect();
let mut indices = Vec::with_capacity(faces.len() * 3);
for [a, b, c] in &faces {
indices.extend_from_slice(&[*a as u16, *b as u16, *c as u16]);
}
Geometry::new(scaled)
.with_normals(normals)
.with_uvs(uvs)
.with_indices(indices)
}
fn subdiv_midpoint(
positions: &mut Vec<Vec3>,
cache: &mut HashMap<(u32, u32), u32>,
a: u32,
b: u32,
) -> u32 {
let key = if a < b { (a, b) } else { (b, a) };
if let Some(&i) = cache.get(&key) {
return i;
}
let mid = (positions[a as usize] + positions[b as usize]).normalize();
positions.push(mid);
let i = (positions.len() - 1) as u32;
cache.insert(key, i);
i
}
fn spherical_uv(dir: Vec3) -> [f32; 2] {
let u = 0.5 + (dir.z.atan2(dir.x) / (2.0 * std::f32::consts::PI));
let v = 0.5 - (dir.y.asin() / std::f32::consts::PI);
[u, v]
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_valid(geo: &Geometry) {
geo.validate().expect("generated geometry must validate");
let positions = &geo.positions;
let normals = geo.normals.as_ref().expect("normals present");
let uvs = geo.uvs.as_ref().expect("uvs present");
let indices = geo.indices.as_ref().expect("indices present");
assert_eq!(normals.len(), positions.len());
assert_eq!(uvs.len(), positions.len());
for n in normals {
let len = Vec3::from_array(*n).length();
assert!((len - 1.0).abs() < 1e-3);
}
for &i in indices {
assert!((i as usize) < positions.len());
}
}
#[test]
fn uv_sphere_counts_and_normals() {
let g = uv_sphere(1.0, 12, 8);
assert_eq!(g.positions.len(), (12 + 1) * (8 + 1));
assert_valid(&g);
for (p, n) in g.positions.iter().zip(g.normals.as_ref().unwrap()) {
let diff = (Vec3::from_array(*p) / 1.0 - Vec3::from_array(*n)).length();
assert!(diff < 1e-4);
}
}
#[test]
fn icosphere_grows_with_subdivision() {
let base = icosphere(1.0, 0);
assert_eq!(base.positions.len(), 12);
assert_eq!(base.indices.as_ref().unwrap().len(), 60);
assert_valid(&base);
let once = icosphere(1.0, 1);
assert!(once.positions.len() > base.positions.len());
assert_valid(&once);
for (p, n) in once.positions.iter().zip(once.normals.as_ref().unwrap()) {
let r = Vec3::from_array(*p).length();
assert!((r - 1.0).abs() < 1e-3);
let diff = (Vec3::from_array(*p).normalize() - Vec3::from_array(*n)).length();
assert!(diff < 1e-4);
}
}
}
+79
View File
@@ -0,0 +1,79 @@
//! Torus primitive — tube around a ring.
use crate::core::geometry::Geometry;
use glam::Vec3;
/// Generates a torus with major radius `major`, minor radius `minor`, with `major_segments`
/// segments around the ring and `minor_segments` around the tube cross-section.
pub fn torus(major: f32, minor: f32, major_segments: u32, minor_segments: u32) -> Geometry {
let mj = major_segments.max(3);
let mn = minor_segments.max(3);
let (mut positions, mut normals, mut uvs, mut indices) = (
Vec::<[f32; 3]>::new(),
Vec::<[f32; 3]>::new(),
Vec::<[f32; 2]>::new(),
Vec::<u16>::new(),
);
for i in 0..=mj {
let u = i as f32 / mj as f32;
let ua = u * 2.0 * std::f32::consts::PI;
let (sin_u, cos_u) = ua.sin_cos();
for j in 0..=mn {
let v = j as f32 / mn as f32;
let va = v * 2.0 * std::f32::consts::PI;
let (sin_v, cos_v) = va.sin_cos();
let ring = Vec3::new(
(major + minor * cos_v) * cos_u,
minor * sin_v,
(major + minor * cos_v) * sin_u,
);
positions.push(ring.to_array());
let n = Vec3::new(cos_v * cos_u, sin_v, cos_v * sin_u).normalize();
normals.push(n.to_array());
uvs.push([u, v]);
}
}
for i in 0..mj {
for j in 0..mn {
let a = i * (mn + 1) + j;
let b = a + 1;
let c = a + mn + 1;
let d = c + 1;
indices
.extend_from_slice(&[a as u16, b as u16, c as u16, b as u16, d as u16, c as u16]);
}
}
Geometry::new(positions)
.with_normals(normals)
.with_uvs(uvs)
.with_indices(indices)
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_valid(geo: &Geometry) {
geo.validate().expect("generated geometry must validate");
let positions = &geo.positions;
let normals = geo.normals.as_ref().expect("normals present");
let uvs = geo.uvs.as_ref().expect("uvs present");
let indices = geo.indices.as_ref().expect("indices present");
assert_eq!(normals.len(), positions.len());
assert_eq!(uvs.len(), positions.len());
for n in normals {
let len = Vec3::from_array(*n).length();
assert!((len - 1.0).abs() < 1e-3);
}
for &i in indices {
assert!((i as usize) < positions.len());
}
}
#[test]
fn torus_validate() {
let g = torus(1.0, 0.25, 24, 12);
assert_valid(&g);
assert_eq!(g.positions.len(), (24 + 1) * (12 + 1));
}
}