From 16d85d8756aaf727b0864d992206a920e2791790 Mon Sep 17 00:00:00 2001 From: Willow Sparks Date: Tue, 27 Jan 2026 01:29:43 +0000 Subject: [PATCH 1/3] Refactor architecture to prepare for physics integration - Create rust4d_core crate with Transform4D, Entity, Material, ShapeRef, World - Move pure geometry (Tesseract4D, Hyperplane4D) to rust4d_math - Add ConvexShape4D trait for shape abstraction - Add RenderableGeometry to bridge World/Entity to GPU buffers - Update main.rs to use entity-based World API - Decouple geometry from rendering (shapes no longer have colors) This architecture change enables future physics integration by: - Separating shape data from visual properties (materials) - Providing transforms that can be driven by rigid bodies - Creating a World container that can step physics simulations Co-Authored-By: Claude Opus 4.5 --- Cargo.lock | 9 + Cargo.toml | 3 + crates/rust4d_core/Cargo.toml | 8 + crates/rust4d_core/src/entity.rs | 220 ++++++ crates/rust4d_core/src/lib.rs | 22 + crates/rust4d_core/src/transform.rs | 235 ++++++ crates/rust4d_core/src/world.rs | 249 ++++++ .../src}/hyperplane.rs | 180 +++-- crates/rust4d_math/src/lib.rs | 21 +- crates/rust4d_math/src/shape.rs | 91 +++ crates/rust4d_math/src/tesseract.rs | 254 ++++++ crates/rust4d_render/Cargo.toml | 1 + crates/rust4d_render/src/geometry/mod.rs | 7 - .../rust4d_render/src/geometry/tesseract.rs | 727 ------------------ crates/rust4d_render/src/lib.rs | 23 +- crates/rust4d_render/src/renderable.rs | 336 ++++++++ .../plans/physics-ready-architecture.md | 375 +++++++++ ...-27-physics-ready-architecture-refactor.md | 145 ++++ src/main.rs | 156 ++-- 19 files changed, 2184 insertions(+), 878 deletions(-) create mode 100644 crates/rust4d_core/Cargo.toml create mode 100644 crates/rust4d_core/src/entity.rs create mode 100644 crates/rust4d_core/src/lib.rs create mode 100644 crates/rust4d_core/src/transform.rs create mode 100644 crates/rust4d_core/src/world.rs rename crates/{rust4d_render/src/geometry => rust4d_math/src}/hyperplane.rs (57%) create mode 100644 crates/rust4d_math/src/shape.rs create mode 100644 crates/rust4d_math/src/tesseract.rs delete mode 100644 crates/rust4d_render/src/geometry/mod.rs delete mode 100644 crates/rust4d_render/src/geometry/tesseract.rs create mode 100644 crates/rust4d_render/src/renderable.rs create mode 100644 scratchpad/plans/physics-ready-architecture.md create mode 100644 scratchpad/reports/2026-01-27-physics-ready-architecture-refactor.md diff --git a/Cargo.lock b/Cargo.lock index 73cd843..7310443 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1447,6 +1447,7 @@ dependencies = [ "env_logger", "log", "pollster", + "rust4d_core", "rust4d_input", "rust4d_math", "rust4d_render", @@ -1454,6 +1455,13 @@ dependencies = [ "winit", ] +[[package]] +name = "rust4d_core" +version = "0.1.0" +dependencies = [ + "rust4d_math", +] + [[package]] name = "rust4d_input" version = "0.1.0" @@ -1475,6 +1483,7 @@ version = "0.1.0" dependencies = [ "bytemuck", "log", + "rust4d_core", "rust4d_input", "rust4d_math", "wgpu", diff --git a/Cargo.toml b/Cargo.toml index 848cf83..b18fb61 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ resolver = "2" members = [ "crates/rust4d_math", + "crates/rust4d_core", "crates/rust4d_render", "crates/rust4d_input", ] @@ -16,6 +17,7 @@ log = "0.4" # Internal crates rust4d_math = { path = "crates/rust4d_math" } +rust4d_core = { path = "crates/rust4d_core" } rust4d_render = { path = "crates/rust4d_render" } rust4d_input = { path = "crates/rust4d_input" } @@ -30,6 +32,7 @@ path = "src/main.rs" [dependencies] rust4d_math.workspace = true +rust4d_core.workspace = true rust4d_render.workspace = true rust4d_input.workspace = true wgpu.workspace = true diff --git a/crates/rust4d_core/Cargo.toml b/crates/rust4d_core/Cargo.toml new file mode 100644 index 0000000..50ce9ea --- /dev/null +++ b/crates/rust4d_core/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rust4d_core" +version = "0.1.0" +edition = "2021" +description = "Core types for the Rust4D engine: Transform4D, Entity, World" + +[dependencies] +rust4d_math.workspace = true diff --git a/crates/rust4d_core/src/entity.rs b/crates/rust4d_core/src/entity.rs new file mode 100644 index 0000000..e91c8d0 --- /dev/null +++ b/crates/rust4d_core/src/entity.rs @@ -0,0 +1,220 @@ +//! Entity and Material types +//! +//! An Entity represents an object in the 4D world with a transform, shape, and material. + +use std::sync::Arc; +use rust4d_math::ConvexShape4D; +use crate::Transform4D; + +/// A simple material with just a base color +/// +/// This is minimal for now - can be extended with PBR properties later. +#[derive(Clone, Copy, Debug)] +pub struct Material { + /// Base color as RGBA (each component 0.0-1.0) + pub base_color: [f32; 4], +} + +impl Default for Material { + fn default() -> Self { + Self { + base_color: [1.0, 1.0, 1.0, 1.0], // White + } + } +} + +impl Material { + /// Create a new material with the given RGBA color + pub fn new(r: f32, g: f32, b: f32, a: f32) -> Self { + Self { + base_color: [r, g, b, a], + } + } + + /// Create a new opaque material with the given RGB color + pub fn from_rgb(r: f32, g: f32, b: f32) -> Self { + Self::new(r, g, b, 1.0) + } + + /// White material + pub const WHITE: Self = Self { base_color: [1.0, 1.0, 1.0, 1.0] }; + + /// Gray material + pub const GRAY: Self = Self { base_color: [0.5, 0.5, 0.5, 1.0] }; + + /// Red material + pub const RED: Self = Self { base_color: [1.0, 0.0, 0.0, 1.0] }; + + /// Green material + pub const GREEN: Self = Self { base_color: [0.0, 1.0, 0.0, 1.0] }; + + /// Blue material + pub const BLUE: Self = Self { base_color: [0.0, 0.0, 1.0, 1.0] }; +} + +/// Reference to a shape - either shared (Arc) or owned (Box) +/// +/// Use `Shared` for memory-efficient storage when multiple entities use the same shape. +/// Use `Owned` when an entity needs its own unique copy for modification. +pub enum ShapeRef { + /// A shared reference to a shape (multiple entities can share this) + Shared(Arc), + /// An owned shape (unique to this entity) + Owned(Box), +} + +impl ShapeRef { + /// Create a shared shape reference + pub fn shared(shape: S) -> Self { + Self::Shared(Arc::new(shape)) + } + + /// Create an owned shape reference + pub fn owned(shape: S) -> Self { + Self::Owned(Box::new(shape)) + } + + /// Get a reference to the underlying shape + pub fn as_shape(&self) -> &dyn ConvexShape4D { + match self { + ShapeRef::Shared(arc) => arc.as_ref(), + ShapeRef::Owned(boxed) => boxed.as_ref(), + } + } +} + +/// An entity in the 4D world +/// +/// Each entity has: +/// - A transform (position, rotation, scale) +/// - A shape (the geometry) +/// - A material (visual properties) +/// +/// Future: rigid_body handle for physics +pub struct Entity { + /// The entity's transform in world space + pub transform: Transform4D, + /// The entity's shape + pub shape: ShapeRef, + /// The entity's material + pub material: Material, + // Future: pub rigid_body: Option, +} + +impl Entity { + /// Create a new entity with the given shape + pub fn new(shape: ShapeRef) -> Self { + Self { + transform: Transform4D::identity(), + shape, + material: Material::default(), + } + } + + /// Create a new entity with shape and material + pub fn with_material(shape: ShapeRef, material: Material) -> Self { + Self { + transform: Transform4D::identity(), + shape, + material, + } + } + + /// Create a new entity with shape, transform, and material + pub fn with_transform(shape: ShapeRef, transform: Transform4D, material: Material) -> Self { + Self { + transform, + shape, + material, + } + } + + /// Get the shape of this entity + pub fn shape(&self) -> &dyn ConvexShape4D { + self.shape.as_shape() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rust4d_math::{Vec4, Tesseract4D}; + + #[test] + fn test_material_default() { + let m = Material::default(); + assert_eq!(m.base_color, [1.0, 1.0, 1.0, 1.0]); + } + + #[test] + fn test_material_new() { + let m = Material::new(0.5, 0.6, 0.7, 0.8); + assert_eq!(m.base_color, [0.5, 0.6, 0.7, 0.8]); + } + + #[test] + fn test_material_from_rgb() { + let m = Material::from_rgb(0.5, 0.6, 0.7); + assert_eq!(m.base_color, [0.5, 0.6, 0.7, 1.0]); + } + + #[test] + fn test_shape_ref_shared() { + let tesseract = Tesseract4D::new(2.0); + let shape_ref = ShapeRef::shared(tesseract); + + match &shape_ref { + ShapeRef::Shared(_) => {} + _ => panic!("Expected Shared variant"), + } + + assert_eq!(shape_ref.as_shape().vertex_count(), 16); + } + + #[test] + fn test_shape_ref_owned() { + let tesseract = Tesseract4D::new(2.0); + let shape_ref = ShapeRef::owned(tesseract); + + match &shape_ref { + ShapeRef::Owned(_) => {} + _ => panic!("Expected Owned variant"), + } + + assert_eq!(shape_ref.as_shape().vertex_count(), 16); + } + + #[test] + fn test_entity_new() { + let tesseract = Tesseract4D::new(2.0); + let entity = Entity::new(ShapeRef::shared(tesseract)); + + assert_eq!(entity.shape().vertex_count(), 16); + assert_eq!(entity.material.base_color, [1.0, 1.0, 1.0, 1.0]); + } + + #[test] + fn test_entity_with_material() { + let tesseract = Tesseract4D::new(2.0); + let entity = Entity::with_material( + ShapeRef::shared(tesseract), + Material::RED, + ); + + assert_eq!(entity.material.base_color, [1.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn test_entity_with_transform() { + let tesseract = Tesseract4D::new(2.0); + let transform = Transform4D::from_position(Vec4::new(1.0, 2.0, 3.0, 4.0)); + let entity = Entity::with_transform( + ShapeRef::shared(tesseract), + transform, + Material::BLUE, + ); + + assert_eq!(entity.transform.position.x, 1.0); + assert_eq!(entity.material.base_color, [0.0, 0.0, 1.0, 1.0]); + } +} diff --git a/crates/rust4d_core/src/lib.rs b/crates/rust4d_core/src/lib.rs new file mode 100644 index 0000000..8f528ce --- /dev/null +++ b/crates/rust4d_core/src/lib.rs @@ -0,0 +1,22 @@ +//! Core types for the Rust4D engine +//! +//! This crate provides the foundational types for building 4D worlds: +//! +//! - [`Transform4D`] - Position, rotation, and scale in 4D space +//! - [`Material`] - Visual properties of an entity +//! - [`Entity`] - An object in the world with transform, shape, and material +//! - [`ShapeRef`] - Reference to a shape (shared or owned) +//! - [`World`] - Container for all entities +//! - [`EntityHandle`] - Handle to an entity in the world + +mod transform; +mod entity; +mod world; + +pub use transform::Transform4D; +pub use entity::{Material, Entity, ShapeRef}; +pub use world::{World, EntityHandle}; + +// Re-export commonly used types from rust4d_math for convenience +pub use rust4d_math::{Vec4, Rotor4, RotationPlane, ConvexShape4D, Tetrahedron}; +pub use rust4d_math::{Tesseract4D, Hyperplane4D}; diff --git a/crates/rust4d_core/src/transform.rs b/crates/rust4d_core/src/transform.rs new file mode 100644 index 0000000..cdb7b66 --- /dev/null +++ b/crates/rust4d_core/src/transform.rs @@ -0,0 +1,235 @@ +//! 4D Transform (position, rotation, scale) +//! +//! A Transform4D represents the position, rotation, and scale of an entity in 4D space. + +use rust4d_math::{Vec4, Rotor4}; + +/// A 4D transform with position, rotation, and uniform scale +#[derive(Clone, Copy, Debug)] +pub struct Transform4D { + /// Position in 4D space + pub position: Vec4, + /// Rotation as a 4D rotor + pub rotation: Rotor4, + /// Uniform scale factor + pub scale: f32, +} + +impl Default for Transform4D { + fn default() -> Self { + Self::identity() + } +} + +impl Transform4D { + /// Create an identity transform (no translation, rotation, or scale change) + pub fn identity() -> Self { + Self { + position: Vec4::ZERO, + rotation: Rotor4::IDENTITY, + scale: 1.0, + } + } + + /// Create a transform with just a position + pub fn from_position(position: Vec4) -> Self { + Self { + position, + rotation: Rotor4::IDENTITY, + scale: 1.0, + } + } + + /// Create a transform with position and rotation + pub fn from_position_rotation(position: Vec4, rotation: Rotor4) -> Self { + Self { + position, + rotation, + scale: 1.0, + } + } + + /// Get the rotation matrix as a 4x4 array + /// + /// This only includes rotation, not position or scale. + #[inline] + pub fn rotation_matrix(&self) -> [[f32; 4]; 4] { + self.rotation.to_matrix() + } + + /// Transform a point from local space to world space + /// + /// Applies scale, then rotation, then translation. + pub fn transform_point(&self, p: Vec4) -> Vec4 { + // Scale + let scaled = p * self.scale; + // Rotate + let rotated = self.rotation.rotate(scaled); + // Translate + rotated + self.position + } + + /// Transform a direction from local space to world space + /// + /// Applies scale and rotation, but not translation. + pub fn transform_direction(&self, d: Vec4) -> Vec4 { + let scaled = d * self.scale; + self.rotation.rotate(scaled) + } + + /// Compute the inverse transform + /// + /// The inverse transform undoes this transform: + /// `transform.inverse().transform_point(transform.transform_point(p)) == p` + pub fn inverse(&self) -> Self { + let inv_scale = if self.scale.abs() > 1e-10 { + 1.0 / self.scale + } else { + 1.0 + }; + let inv_rotation = self.rotation.reverse(); + let inv_position = inv_rotation.rotate(-self.position) * inv_scale; + + Self { + position: inv_position, + rotation: inv_rotation, + scale: inv_scale, + } + } + + /// Compose two transforms: result = self * other + /// + /// The composed transform applies `other` first, then `self`. + pub fn compose(&self, other: &Self) -> Self { + Self { + position: self.transform_point(other.position), + rotation: self.rotation.compose(&other.rotation), + scale: self.scale * other.scale, + } + } + + /// Translate the transform by an offset + pub fn translate(&mut self, offset: Vec4) { + self.position += offset; + } + + /// Rotate the transform by a rotor + pub fn rotate(&mut self, rotor: Rotor4) { + self.rotation = rotor.compose(&self.rotation).normalize(); + } + + /// Set uniform scale + pub fn set_scale(&mut self, scale: f32) { + self.scale = scale; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rust4d_math::RotationPlane; + use std::f32::consts::PI; + + const EPSILON: f32 = 0.0001; + + fn approx_eq(a: f32, b: f32) -> bool { + (a - b).abs() < EPSILON + } + + fn vec_approx_eq(a: Vec4, b: Vec4) -> bool { + approx_eq(a.x, b.x) && approx_eq(a.y, b.y) && approx_eq(a.z, b.z) && approx_eq(a.w, b.w) + } + + #[test] + fn test_identity_transform() { + let t = Transform4D::identity(); + let p = Vec4::new(1.0, 2.0, 3.0, 4.0); + let transformed = t.transform_point(p); + assert!(vec_approx_eq(p, transformed)); + } + + #[test] + fn test_translation() { + let t = Transform4D::from_position(Vec4::new(1.0, 2.0, 3.0, 4.0)); + let p = Vec4::ZERO; + let transformed = t.transform_point(p); + assert!(vec_approx_eq(transformed, Vec4::new(1.0, 2.0, 3.0, 4.0))); + } + + #[test] + fn test_scale() { + let mut t = Transform4D::identity(); + t.scale = 2.0; + let p = Vec4::new(1.0, 1.0, 1.0, 1.0); + let transformed = t.transform_point(p); + assert!(vec_approx_eq(transformed, Vec4::new(2.0, 2.0, 2.0, 2.0))); + } + + #[test] + fn test_rotation() { + let rotor = Rotor4::from_plane_angle(RotationPlane::XY, PI / 2.0); + let t = Transform4D::from_position_rotation(Vec4::ZERO, rotor); + let p = Vec4::X; + let transformed = t.transform_point(p); + assert!(vec_approx_eq(transformed, Vec4::Y), "Expected Y, got {:?}", transformed); + } + + #[test] + fn test_transform_order() { + // Transform applies: scale, then rotate, then translate + let rotor = Rotor4::from_plane_angle(RotationPlane::XY, PI / 2.0); + let mut t = Transform4D::identity(); + t.scale = 2.0; + t.rotation = rotor; + t.position = Vec4::new(10.0, 0.0, 0.0, 0.0); + + // X * 2 = (2, 0, 0, 0), rotated 90° in XY = (0, 2, 0, 0), + (10, 0, 0, 0) = (10, 2, 0, 0) + let p = Vec4::X; + let transformed = t.transform_point(p); + assert!(vec_approx_eq(transformed, Vec4::new(10.0, 2.0, 0.0, 0.0)), + "Expected (10, 2, 0, 0), got {:?}", transformed); + } + + #[test] + fn test_inverse() { + let rotor = Rotor4::from_plane_angle(RotationPlane::XZ, 0.5); + let mut t = Transform4D::from_position_rotation(Vec4::new(1.0, 2.0, 3.0, 4.0), rotor); + t.scale = 2.0; + + let p = Vec4::new(1.0, 2.0, 3.0, 4.0); + let transformed = t.transform_point(p); + let back = t.inverse().transform_point(transformed); + + assert!(vec_approx_eq(p, back), "Expected {:?}, got {:?}", p, back); + } + + #[test] + fn test_transform_direction() { + let t = Transform4D::from_position(Vec4::new(100.0, 100.0, 100.0, 100.0)); + let d = Vec4::X; + let transformed = t.transform_direction(d); + // Direction should not be affected by position + assert!(vec_approx_eq(transformed, Vec4::X)); + } + + #[test] + fn test_compose() { + let t1 = Transform4D::from_position(Vec4::new(1.0, 0.0, 0.0, 0.0)); + let t2 = Transform4D::from_position(Vec4::new(0.0, 2.0, 0.0, 0.0)); + + // t1.compose(t2) applies t2 first, then t1 + let composed = t1.compose(&t2); + + let p = Vec4::ZERO; + let result = composed.transform_point(p); + // Origin -> +y2 (t2) -> +x1 (t1) = (1, 2, 0, 0) + assert!(vec_approx_eq(result, Vec4::new(1.0, 2.0, 0.0, 0.0))); + } + + #[test] + fn test_default() { + let t = Transform4D::default(); + assert!(vec_approx_eq(t.position, Vec4::ZERO)); + assert_eq!(t.scale, 1.0); + } +} diff --git a/crates/rust4d_core/src/world.rs b/crates/rust4d_core/src/world.rs new file mode 100644 index 0000000..b1c3d63 --- /dev/null +++ b/crates/rust4d_core/src/world.rs @@ -0,0 +1,249 @@ +//! World container for entities +//! +//! The World manages all entities in the simulation. + +use crate::Entity; + +/// A handle to an entity in the world +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct EntityHandle(usize); + +impl EntityHandle { + /// Get the raw index of this handle + #[inline] + pub fn index(&self) -> usize { + self.0 + } +} + +/// The 4D world containing all entities +/// +/// The World is the central container for all game objects. +/// It manages entities and will eventually integrate with physics. +pub struct World { + /// All entities in the world + entities: Vec, + // Future: physics_world: PhysicsWorld, +} + +impl Default for World { + fn default() -> Self { + Self::new() + } +} + +impl World { + /// Create a new empty world + pub fn new() -> Self { + Self { + entities: Vec::new(), + } + } + + /// Create a world with pre-allocated capacity for entities + pub fn with_capacity(capacity: usize) -> Self { + Self { + entities: Vec::with_capacity(capacity), + } + } + + /// Add an entity to the world, returning its handle + pub fn add_entity(&mut self, entity: Entity) -> EntityHandle { + let handle = EntityHandle(self.entities.len()); + self.entities.push(entity); + handle + } + + /// Get a reference to an entity by handle + pub fn get_entity(&self, handle: EntityHandle) -> Option<&Entity> { + self.entities.get(handle.0) + } + + /// Get a mutable reference to an entity by handle + pub fn get_entity_mut(&mut self, handle: EntityHandle) -> Option<&mut Entity> { + self.entities.get_mut(handle.0) + } + + /// Get all entities as a slice + pub fn entities(&self) -> &[Entity] { + &self.entities + } + + /// Get all entities as a mutable slice + pub fn entities_mut(&mut self) -> &mut [Entity] { + &mut self.entities + } + + /// Get the number of entities + #[inline] + pub fn entity_count(&self) -> usize { + self.entities.len() + } + + /// Check if the world is empty + #[inline] + pub fn is_empty(&self) -> bool { + self.entities.is_empty() + } + + /// Update the world (future: steps physics) + /// + /// Currently a no-op, but will eventually: + /// - Step the physics simulation + /// - Update entity transforms from rigid bodies + pub fn update(&mut self, _dt: f32) { + // Future: self.physics_world.step(dt); + // Future: sync transforms from physics + } + + /// Clear all entities from the world + pub fn clear(&mut self) { + self.entities.clear(); + } + + /// Iterate over all entities + pub fn iter(&self) -> impl Iterator { + self.entities.iter() + } + + /// Iterate over all entities mutably + pub fn iter_mut(&mut self) -> impl Iterator { + self.entities.iter_mut() + } + + /// Iterate over handles and entities + pub fn iter_with_handles(&self) -> impl Iterator { + self.entities + .iter() + .enumerate() + .map(|(i, e)| (EntityHandle(i), e)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Material, ShapeRef}; + use rust4d_math::Tesseract4D; + + fn make_test_entity() -> Entity { + let tesseract = Tesseract4D::new(2.0); + Entity::new(ShapeRef::shared(tesseract)) + } + + #[test] + fn test_world_new() { + let world = World::new(); + assert!(world.is_empty()); + assert_eq!(world.entity_count(), 0); + } + + #[test] + fn test_world_add_entity() { + let mut world = World::new(); + let entity = make_test_entity(); + let handle = world.add_entity(entity); + + assert_eq!(handle.index(), 0); + assert_eq!(world.entity_count(), 1); + } + + #[test] + fn test_world_get_entity() { + let mut world = World::new(); + let entity = make_test_entity(); + let handle = world.add_entity(entity); + + let retrieved = world.get_entity(handle); + assert!(retrieved.is_some()); + assert_eq!(retrieved.unwrap().shape().vertex_count(), 16); + } + + #[test] + fn test_world_get_entity_mut() { + let mut world = World::new(); + let entity = make_test_entity(); + let handle = world.add_entity(entity); + + if let Some(entity) = world.get_entity_mut(handle) { + entity.material = Material::RED; + } + + let retrieved = world.get_entity(handle).unwrap(); + assert_eq!(retrieved.material.base_color, [1.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn test_world_entities() { + let mut world = World::new(); + world.add_entity(make_test_entity()); + world.add_entity(make_test_entity()); + + let entities = world.entities(); + assert_eq!(entities.len(), 2); + } + + #[test] + fn test_world_clear() { + let mut world = World::new(); + world.add_entity(make_test_entity()); + world.add_entity(make_test_entity()); + + world.clear(); + assert!(world.is_empty()); + } + + #[test] + fn test_world_iter() { + let mut world = World::new(); + world.add_entity(make_test_entity()); + world.add_entity(make_test_entity()); + + let count = world.iter().count(); + assert_eq!(count, 2); + } + + #[test] + fn test_world_iter_with_handles() { + let mut world = World::new(); + world.add_entity(make_test_entity()); + world.add_entity(make_test_entity()); + + let handles: Vec<_> = world.iter_with_handles().map(|(h, _)| h).collect(); + assert_eq!(handles.len(), 2); + assert_eq!(handles[0].index(), 0); + assert_eq!(handles[1].index(), 1); + } + + #[test] + fn test_world_update() { + let mut world = World::new(); + world.add_entity(make_test_entity()); + + // Just verify it doesn't panic for now + world.update(0.016); + } + + #[test] + fn test_world_default() { + let world = World::default(); + assert!(world.is_empty()); + } + + #[test] + fn test_world_with_capacity() { + let world = World::with_capacity(100); + assert!(world.is_empty()); + // Can't directly test capacity, but it shouldn't affect behavior + } + + #[test] + fn test_entity_handle() { + let handle = EntityHandle(42); + assert_eq!(handle.index(), 42); + + // Test PartialEq + let handle2 = EntityHandle(42); + assert_eq!(handle, handle2); + } +} diff --git a/crates/rust4d_render/src/geometry/hyperplane.rs b/crates/rust4d_math/src/hyperplane.rs similarity index 57% rename from crates/rust4d_render/src/geometry/hyperplane.rs rename to crates/rust4d_math/src/hyperplane.rs index ea3360d..b01ac2b 100644 --- a/crates/rust4d_render/src/geometry/hyperplane.rs +++ b/crates/rust4d_math/src/hyperplane.rs @@ -7,45 +7,49 @@ //! We model it as a grid of "pillars" - each pillar is a rectangular prism //! extending in W, decomposed into tetrahedra. -use rust4d_math::Vec4; -use super::tesseract::Tetrahedron; - -/// A checkerboard hyperplane at a fixed Y height -pub struct Hyperplane { - /// All vertices of the hyperplane grid - pub vertices: Vec, - /// RGBA colors for each vertex - pub colors: Vec<[f32; 4]>, +use crate::{Vec4, shape::{ConvexShape4D, Tetrahedron}}; +use std::collections::HashSet; + +/// A hyperplane at a fixed Y height - pure geometry without colors +/// +/// The hyperplane extends as a grid in X and Z, with extent in W for slicing. +#[derive(Clone)] +pub struct Hyperplane4D { + /// Y level of the plane + y_level: f32, + /// Half-extent in X and Z + half_size: f32, + /// Grid size (cells per axis) + grid_size: usize, + /// Half-extent in W dimension + w_extent: f32, + /// Y thickness (small for thin plane) + thickness: f32, + /// All vertices + vertices: Vec, /// Tetrahedra decomposition - pub tetrahedra: Vec, + tetrahedra: Vec, } -impl Hyperplane { - /// Create a new checkerboard hyperplane +impl Hyperplane4D { + /// Create a new hyperplane /// /// # Arguments /// * `y` - The Y height of the plane (e.g., -2.0 for below the tesseract) /// * `size` - Half-extent in X and Z (total size is 2*size) /// * `grid_size` - Number of cells along each axis - /// * `cell_size` - Size of each checkerboard cell /// * `w_extent` - Half-extent in W dimension (for slicing visibility) /// * `thickness` - Small Y thickness for proper 4D volume pub fn new( y: f32, size: f32, grid_size: usize, - cell_size: f32, w_extent: f32, thickness: f32, ) -> Self { let mut vertices = Vec::new(); - let mut colors = Vec::new(); let mut tetrahedra = Vec::new(); - // Colors for checkerboard - let color_a = [0.3, 0.3, 0.35, 1.0]; // Dark gray - let color_b = [0.7, 0.7, 0.75, 1.0]; // Light gray - let step = size * 2.0 / grid_size as f32; let start = -size; @@ -57,13 +61,6 @@ impl Hyperplane { let z0 = start + j as f32 * step; let z1 = z0 + step; - // Checkerboard pattern based on cell coordinates - let cell_i = ((x0 + size) / cell_size).floor() as i32; - let cell_j = ((z0 + size) / cell_size).floor() as i32; - let color = if (cell_i + cell_j) % 2 == 0 { color_a } else { color_b }; - - // Each cell is a 4D prism: 8 vertices - // (x0,x1) × (y,y+thickness) × (z0,z1) × (-w_extent, +w_extent) let base_idx = vertices.len(); let y0 = y; @@ -71,9 +68,8 @@ impl Hyperplane { let w0 = -w_extent; let w1 = w_extent; - // 8 vertices of the rectangular prism - // Using same binary indexing as tesseract: - // bit 0 = x, bit 1 = y, bit 2 = z, bit 3 = w + // 16 vertices of the tesseract-shaped cell + // Using binary indexing: bit 0 = x, bit 1 = y, bit 2 = z, bit 3 = w vertices.push(Vec4::new(x0, y0, z0, w0)); // 0 = 0b0000 vertices.push(Vec4::new(x1, y0, z0, w0)); // 1 = 0b0001 vertices.push(Vec4::new(x0, y1, z0, w0)); // 2 = 0b0010 @@ -91,29 +87,64 @@ impl Hyperplane { vertices.push(Vec4::new(x0, y1, z1, w1)); // 14 = 0b1110 vertices.push(Vec4::new(x1, y1, z1, w1)); // 15 = 0b1111 - // All 16 vertices have the same color for this cell - for _ in 0..16 { - colors.push(color); - } - // Decompose the tesseract-shaped cell into tetrahedra - // Use the same Kuhn triangulation as the tesseract let cell_tetrahedra = Self::decompose_cell_to_tetrahedra(base_idx); tetrahedra.extend(cell_tetrahedra); } } Self { + y_level: y, + half_size: size, + grid_size, + w_extent, + thickness, vertices, - colors, tetrahedra, } } - /// Decompose a single cell (mini-tesseract) into tetrahedra + /// Get the Y level of the plane + #[inline] + pub fn y_level(&self) -> f32 { + self.y_level + } + + /// Get the half-size in X and Z + #[inline] + pub fn half_size(&self) -> f32 { + self.half_size + } + + /// Get the grid size + #[inline] + pub fn grid_size(&self) -> usize { + self.grid_size + } + + /// Get the W extent + #[inline] + pub fn w_extent(&self) -> f32 { + self.w_extent + } + + /// Get the grid cell coordinates for a given cell index + /// + /// Returns (i, j) grid coordinates for checkerboard patterns + pub fn cell_coords(&self, cell_index: usize) -> (usize, usize) { + let i = cell_index / self.grid_size; + let j = cell_index % self.grid_size; + (i, j) + } + + /// Get the number of cells + #[inline] + pub fn cell_count(&self) -> usize { + self.grid_size * self.grid_size + } + + /// Decompose a single cell (mini-tesseract) into tetrahedra using Kuhn triangulation fn decompose_cell_to_tetrahedra(base_idx: usize) -> Vec { - // Use Kuhn triangulation - each permutation of dimensions gives a 5-cell - // Then decompose 5-cells into tetrahedra let permutations = [ [0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], @@ -133,9 +164,8 @@ impl Hyperplane { simplices.push(vertex_indices); } - // Decompose 5-cells into tetrahedra let mut tetrahedra = Vec::new(); - let mut seen: std::collections::HashSet<[usize; 4]> = std::collections::HashSet::new(); + let mut seen: HashSet<[usize; 4]> = HashSet::new(); for simplex in &simplices { for omit in 0..5 { @@ -159,10 +189,15 @@ impl Hyperplane { tetrahedra } +} - /// Get the number of tetrahedra - pub fn tetrahedron_count(&self) -> usize { - self.tetrahedra.len() +impl ConvexShape4D for Hyperplane4D { + fn vertices(&self) -> &[Vec4] { + &self.vertices + } + + fn tetrahedra(&self) -> &[Tetrahedron] { + &self.tetrahedra } } @@ -172,32 +207,59 @@ mod tests { #[test] fn test_hyperplane_creation() { - let plane = Hyperplane::new(-2.0, 4.0, 4, 1.0, 2.0, 0.01); + let plane = Hyperplane4D::new(-2.0, 4.0, 4, 2.0, 0.01); // 4x4 grid = 16 cells, each with 16 vertices - assert_eq!(plane.vertices.len(), 16 * 16); - assert_eq!(plane.colors.len(), plane.vertices.len()); - assert!(plane.tetrahedra.len() > 0); + assert_eq!(plane.vertices().len(), 16 * 16); + assert!(plane.tetrahedra().len() > 0); } #[test] fn test_hyperplane_vertex_positions() { - let plane = Hyperplane::new(-2.0, 4.0, 2, 1.0, 2.0, 0.01); + let plane = Hyperplane4D::new(-2.0, 4.0, 2, 2.0, 0.01); // Check that all vertices are at y = -2.0 or slightly above - for v in &plane.vertices { - assert!(v.y >= -2.0 && v.y <= -1.99, "Vertex Y should be near -2.0, got {}", v.y); + for v in plane.vertices() { + assert!(v.y >= -2.0 && v.y <= -1.99, + "Vertex Y should be near -2.0, got {}", v.y); } } #[test] - fn test_checkerboard_colors() { - let plane = Hyperplane::new(-2.0, 4.0, 4, 2.0, 2.0, 0.01); - - // Check that we have at least 2 different colors - let unique_colors: std::collections::HashSet<_> = plane.colors.iter() - .map(|c| ((c[0] * 100.0) as i32, (c[1] * 100.0) as i32)) - .collect(); - assert!(unique_colors.len() >= 2, "Should have at least 2 colors for checkerboard"); + fn test_hyperplane_cell_coords() { + let plane = Hyperplane4D::new(-2.0, 4.0, 4, 2.0, 0.01); + + assert_eq!(plane.cell_coords(0), (0, 0)); + assert_eq!(plane.cell_coords(1), (0, 1)); + assert_eq!(plane.cell_coords(4), (1, 0)); + assert_eq!(plane.cell_coords(15), (3, 3)); + } + + #[test] + fn test_hyperplane_accessors() { + let plane = Hyperplane4D::new(-2.0, 4.0, 4, 2.0, 0.01); + + assert_eq!(plane.y_level(), -2.0); + assert_eq!(plane.half_size(), 4.0); + assert_eq!(plane.grid_size(), 4); + assert_eq!(plane.w_extent(), 2.0); + assert_eq!(plane.cell_count(), 16); + } + + #[test] + fn test_hyperplane_implements_convex_shape() { + let plane = Hyperplane4D::new(-2.0, 4.0, 2, 2.0, 0.01); + + assert_eq!(plane.vertex_count(), 4 * 16); // 4 cells * 16 verts + assert!(plane.tetrahedron_count() > 0); + } + + #[test] + fn test_hyperplane_clone() { + let p1 = Hyperplane4D::new(-2.0, 4.0, 2, 2.0, 0.01); + let p2 = p1.clone(); + + assert_eq!(p1.vertices().len(), p2.vertices().len()); + assert_eq!(p1.tetrahedra().len(), p2.tetrahedra().len()); } } diff --git a/crates/rust4d_math/src/lib.rs b/crates/rust4d_math/src/lib.rs index d640f95..576f8b4 100644 --- a/crates/rust4d_math/src/lib.rs +++ b/crates/rust4d_math/src/lib.rs @@ -1,11 +1,30 @@ //! 4D Mathematics Library //! -//! This crate provides 4D vector and rotation types for the Rust4D engine. +//! This crate provides 4D vector, rotation, and shape types for the Rust4D engine. +//! +//! ## Core Types +//! +//! - [`Vec4`] - 4D vector with x, y, z, w components +//! - [`Rotor4`] - 4D rotation using geometric algebra +//! - [`Mat4`] - 4x4 matrix for transformations +//! +//! ## Shape Types +//! +//! - [`ConvexShape4D`] - Trait for 4D shapes that can be sliced +//! - [`Tetrahedron`] - A 3-simplex defined by vertex indices +//! - [`Tesseract4D`] - A 4D hypercube +//! - [`Hyperplane4D`] - A floor/ground plane in 4D mod vec4; mod rotor4; pub mod mat4; +pub mod shape; +pub mod tesseract; +pub mod hyperplane; pub use vec4::Vec4; pub use rotor4::{Rotor4, RotationPlane}; pub use mat4::Mat4; +pub use shape::{ConvexShape4D, Tetrahedron}; +pub use tesseract::Tesseract4D; +pub use hyperplane::Hyperplane4D; diff --git a/crates/rust4d_math/src/shape.rs b/crates/rust4d_math/src/shape.rs new file mode 100644 index 0000000..c27c225 --- /dev/null +++ b/crates/rust4d_math/src/shape.rs @@ -0,0 +1,91 @@ +//! Shape traits and primitives for 4D geometry +//! +//! This module provides the core shape abstraction for 4D objects. +//! Shapes are pure geometric data - no colors, materials, or rendering info. + +use crate::Vec4; + +/// A tetrahedron (3-simplex) defined by vertex indices +/// +/// Tetrahedra are the fundamental building blocks for 4D slicing. +/// Each tetrahedron represents a solid region of 4D space that can +/// be sliced by a 3D hyperplane to produce triangles. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Tetrahedron { + /// Indices into the parent shape's vertex array + pub indices: [usize; 4], +} + +impl Tetrahedron { + /// Create a new tetrahedron with the given vertex indices + #[inline] + pub fn new(indices: [usize; 4]) -> Self { + Self { indices } + } + + /// Create a new tetrahedron with sorted vertex indices (canonical form) + /// + /// Useful for deduplication and comparison. + pub fn new_canonical(mut indices: [usize; 4]) -> Self { + indices.sort(); + Self { indices } + } + + /// Get the indices as a sorted array (canonical form) + pub fn canonical(&self) -> [usize; 4] { + let mut sorted = self.indices; + sorted.sort(); + sorted + } +} + +/// Trait for convex 4D shapes that can be sliced +/// +/// A ConvexShape4D provides the geometric data needed for 4D rendering: +/// - Vertices: The 4D points that define the shape +/// - Tetrahedra: A decomposition into 3-simplices for slicing +/// +/// Shapes are pure geometry - they contain no rendering-specific data +/// like colors or materials. That information lives in the entity/material system. +pub trait ConvexShape4D: Send + Sync { + /// Get the vertices of this shape + fn vertices(&self) -> &[Vec4]; + + /// Get the tetrahedra decomposition of this shape + fn tetrahedra(&self) -> &[Tetrahedron]; + + /// Get the number of vertices + #[inline] + fn vertex_count(&self) -> usize { + self.vertices().len() + } + + /// Get the number of tetrahedra + #[inline] + fn tetrahedron_count(&self) -> usize { + self.tetrahedra().len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tetrahedron_new() { + let tet = Tetrahedron::new([0, 1, 2, 3]); + assert_eq!(tet.indices, [0, 1, 2, 3]); + } + + #[test] + fn test_tetrahedron_canonical() { + let tet = Tetrahedron::new([3, 1, 0, 2]); + assert_eq!(tet.canonical(), [0, 1, 2, 3]); + } + + #[test] + fn test_tetrahedron_new_canonical() { + let tet = Tetrahedron::new_canonical([3, 1, 0, 2]); + assert_eq!(tet.indices, [0, 1, 2, 3]); + } +} diff --git a/crates/rust4d_math/src/tesseract.rs b/crates/rust4d_math/src/tesseract.rs new file mode 100644 index 0000000..ea280d0 --- /dev/null +++ b/crates/rust4d_math/src/tesseract.rs @@ -0,0 +1,254 @@ +//! Tesseract (4D Hypercube) geometry +//! +//! A tesseract has 16 vertices (all combinations of ±h for x,y,z,w), +//! 32 edges, 24 faces (squares), and 8 cells (cubes). +//! +//! For cross-section rendering, we decompose it into tetrahedra (3-simplices). + +use crate::{Vec4, shape::{ConvexShape4D, Tetrahedron}}; +use std::collections::HashSet; + +/// A tesseract (4D hypercube) - pure geometry without colors +#[derive(Clone)] +pub struct Tesseract4D { + /// Half the side length + half_size: f32, + /// The 16 vertices of the tesseract + vertices: [Vec4; 16], + /// Tetrahedra decomposition + tetrahedra: Vec, +} + +impl Tesseract4D { + /// Create a new tesseract centered at origin with given size + /// + /// # Arguments + /// * `size` - The full side length of the tesseract + pub fn new(size: f32) -> Self { + let h = size * 0.5; + + // All 16 vertices are combinations of ±h for each coordinate + // Using binary counting: vertex i has coordinates based on bits of i + let vertices = [ + Vec4::new(-h, -h, -h, -h), // 0 = 0b0000 + Vec4::new( h, -h, -h, -h), // 1 = 0b0001 + Vec4::new(-h, h, -h, -h), // 2 = 0b0010 + Vec4::new( h, h, -h, -h), // 3 = 0b0011 + Vec4::new(-h, -h, h, -h), // 4 = 0b0100 + Vec4::new( h, -h, h, -h), // 5 = 0b0101 + Vec4::new(-h, h, h, -h), // 6 = 0b0110 + Vec4::new( h, h, h, -h), // 7 = 0b0111 + Vec4::new(-h, -h, -h, h), // 8 = 0b1000 + Vec4::new( h, -h, -h, h), // 9 = 0b1001 + Vec4::new(-h, h, -h, h), // 10 = 0b1010 + Vec4::new( h, h, -h, h), // 11 = 0b1011 + Vec4::new(-h, -h, h, h), // 12 = 0b1100 + Vec4::new( h, -h, h, h), // 13 = 0b1101 + Vec4::new(-h, h, h, h), // 14 = 0b1110 + Vec4::new( h, h, h, h), // 15 = 0b1111 + ]; + + // Compute tetrahedra decomposition using Kuhn triangulation + let tetrahedra = Self::compute_tetrahedra(); + + Self { + half_size: h, + vertices, + tetrahedra, + } + } + + /// Get the half-size (half the side length) + #[inline] + pub fn half_size(&self) -> f32 { + self.half_size + } + + /// Get the full size (side length) + #[inline] + pub fn size(&self) -> f32 { + self.half_size * 2.0 + } + + /// Get the vertices of a specific tetrahedron + pub fn get_tetrahedron_vertices(&self, tet_idx: usize) -> [Vec4; 4] { + let indices = self.tetrahedra[tet_idx].indices; + [ + self.vertices[indices[0]], + self.vertices[indices[1]], + self.vertices[indices[2]], + self.vertices[indices[3]], + ] + } + + /// Compute the tetrahedra decomposition using Kuhn triangulation + /// + /// The Kuhn triangulation decomposes the hypercube into 24 5-cells (simplices), + /// each defined by a permutation of dimensions. We then decompose each 5-cell + /// into 5 tetrahedra by omitting each vertex in turn. + fn compute_tetrahedra() -> Vec { + // Generate all permutations of [0, 1, 2, 3] for Kuhn triangulation + let permutations = [ + [0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], + [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], + [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], [2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 1, 0], + [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0], + ]; + + // Generate 5-cells from permutations + let mut simplices = Vec::with_capacity(24); + for perm in &permutations { + let mut vertex_indices = [0usize; 5]; + let mut current = 0usize; + vertex_indices[0] = current; + for (i, &dim) in perm.iter().enumerate() { + current |= 1 << dim; + vertex_indices[i + 1] = current; + } + simplices.push(vertex_indices); + } + + // Decompose 5-cells into tetrahedra (deduplicated) + let mut seen: HashSet<[usize; 4]> = HashSet::new(); + let mut tetrahedra = Vec::new(); + + for simplex in &simplices { + // A 5-cell with vertices {v0,v1,v2,v3,v4} decomposes into 5 tetrahedra + // by omitting each vertex in turn + for omit in 0..5 { + let mut tet_verts = [0usize; 4]; + let mut idx = 0; + for i in 0..5 { + if i != omit { + tet_verts[idx] = simplex[i]; + idx += 1; + } + } + + // Sort for canonical form (deduplication) + let mut canonical = tet_verts; + canonical.sort(); + + if seen.insert(canonical) { + tetrahedra.push(Tetrahedron::new(tet_verts)); + } + } + } + + tetrahedra + } +} + +impl ConvexShape4D for Tesseract4D { + fn vertices(&self) -> &[Vec4] { + &self.vertices + } + + fn tetrahedra(&self) -> &[Tetrahedron] { + &self.tetrahedra + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tesseract_vertex_count() { + let t = Tesseract4D::new(2.0); + assert_eq!(t.vertices().len(), 16); + } + + #[test] + fn test_tesseract_tetrahedron_count() { + let t = Tesseract4D::new(2.0); + // Should have some reasonable number of tetrahedra + assert!(t.tetrahedra().len() > 0); + assert!(t.tetrahedra().len() <= 120); // Max: 24 * 5 before deduplication + } + + #[test] + fn test_tesseract_vertices_positions() { + let t = Tesseract4D::new(2.0); + let h = 1.0; + + // Check corner vertices + assert_eq!(t.vertices[0].x, -h); + assert_eq!(t.vertices[0].y, -h); + assert_eq!(t.vertices[0].z, -h); + assert_eq!(t.vertices[0].w, -h); + + assert_eq!(t.vertices[15].x, h); + assert_eq!(t.vertices[15].y, h); + assert_eq!(t.vertices[15].z, h); + assert_eq!(t.vertices[15].w, h); + } + + #[test] + fn test_tesseract_size() { + let t = Tesseract4D::new(4.0); + assert_eq!(t.size(), 4.0); + assert_eq!(t.half_size(), 2.0); + } + + #[test] + fn test_tetrahedra_have_four_vertices() { + let t = Tesseract4D::new(2.0); + for tet in t.tetrahedra() { + assert_eq!(tet.indices.len(), 4); + for &idx in &tet.indices { + assert!(idx < 16, "Vertex index {} out of range", idx); + } + } + } + + #[test] + fn test_tetrahedra_cover_tesseract_edges() { + // All 32 tesseract edges should appear in at least one tetrahedron + let t = Tesseract4D::new(2.0); + + // Collect all edges from tetrahedra + let mut tet_edges: HashSet<(usize, usize)> = HashSet::new(); + for tet in t.tetrahedra() { + for i in 0..4 { + for j in (i+1)..4 { + let (v0, v1) = if tet.indices[i] < tet.indices[j] { + (tet.indices[i], tet.indices[j]) + } else { + (tet.indices[j], tet.indices[i]) + }; + tet_edges.insert((v0, v1)); + } + } + } + + // Check that all tesseract edges are covered + for i in 0usize..16 { + for j in (i+1)..16 { + if (i ^ j).count_ones() == 1 { + // This is a tesseract edge + assert!(tet_edges.contains(&(i, j)), + "Tesseract edge ({}, {}) not in any tetrahedron", i, j); + } + } + } + } + + #[test] + fn test_tesseract_implements_convex_shape() { + let t = Tesseract4D::new(2.0); + + // Test through trait methods + assert_eq!(t.vertex_count(), 16); + assert!(t.tetrahedron_count() > 0); + } + + #[test] + fn test_tesseract_clone() { + let t1 = Tesseract4D::new(2.0); + let t2 = t1.clone(); + + assert_eq!(t1.vertices().len(), t2.vertices().len()); + assert_eq!(t1.tetrahedra().len(), t2.tetrahedra().len()); + } +} diff --git a/crates/rust4d_render/Cargo.toml b/crates/rust4d_render/Cargo.toml index 9eb3fc3..f75dd2e 100644 --- a/crates/rust4d_render/Cargo.toml +++ b/crates/rust4d_render/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] rust4d_math.workspace = true +rust4d_core.workspace = true rust4d_input.workspace = true wgpu.workspace = true winit.workspace = true diff --git a/crates/rust4d_render/src/geometry/mod.rs b/crates/rust4d_render/src/geometry/mod.rs deleted file mode 100644 index cb1e3c2..0000000 --- a/crates/rust4d_render/src/geometry/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! 4D Geometry types - -mod tesseract; -mod hyperplane; - -pub use tesseract::{Tesseract, Tetrahedron}; -pub use hyperplane::Hyperplane; diff --git a/crates/rust4d_render/src/geometry/tesseract.rs b/crates/rust4d_render/src/geometry/tesseract.rs deleted file mode 100644 index 7b73085..0000000 --- a/crates/rust4d_render/src/geometry/tesseract.rs +++ /dev/null @@ -1,727 +0,0 @@ -//! Tesseract (4D Hypercube) geometry -//! -//! A tesseract has 16 vertices (all combinations of ±h for x,y,z,w), -//! 32 edges, 24 faces (squares), and 8 cells (cubes). -//! -//! For cross-section rendering, we decompose it into tetrahedra (3-simplices). -//! This is simpler than using 5-cells because tetrahedra always produce -//! triangular cross-sections (never prisms). - -use rust4d_math::Vec4; -use std::collections::HashSet; - -/// A tetrahedron (3-simplex) for 4D slicing -/// Has 4 vertices and 6 edges -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Tetrahedron { - /// Indices into the tesseract's vertex array - pub vertices: [usize; 4], -} - -impl Tetrahedron { - /// Create a new tetrahedron with sorted vertex indices (canonical form) - pub fn new_canonical(mut vertices: [usize; 4]) -> Self { - vertices.sort(); - Self { vertices } - } - - /// Create a new tetrahedron preserving vertex order - pub fn new(vertices: [usize; 4]) -> Self { - Self { vertices } - } -} - -/// A tesseract (4D hypercube) -pub struct Tesseract { - /// The 16 vertices of the tesseract - pub vertices: [Vec4; 16], - /// Indices into vertices forming 5-cells (4D simplices) - /// Each 5-cell has 5 vertices - pub simplices: Vec<[usize; 5]>, - /// Tetrahedra decomposition (computed lazily) - tetrahedra: Option>, -} - -impl Tesseract { - /// Create a new tesseract centered at origin with given size - pub fn new(size: f32) -> Self { - let h = size * 0.5; - - // All 16 vertices are combinations of ±h for each coordinate - // Using binary counting: vertex i has coordinates based on bits of i - let vertices = [ - Vec4::new(-h, -h, -h, -h), // 0 = 0b0000 - Vec4::new( h, -h, -h, -h), // 1 = 0b0001 - Vec4::new(-h, h, -h, -h), // 2 = 0b0010 - Vec4::new( h, h, -h, -h), // 3 = 0b0011 - Vec4::new(-h, -h, h, -h), // 4 = 0b0100 - Vec4::new( h, -h, h, -h), // 5 = 0b0101 - Vec4::new(-h, h, h, -h), // 6 = 0b0110 - Vec4::new( h, h, h, -h), // 7 = 0b0111 - Vec4::new(-h, -h, -h, h), // 8 = 0b1000 - Vec4::new( h, -h, -h, h), // 9 = 0b1001 - Vec4::new(-h, h, -h, h), // 10 = 0b1010 - Vec4::new( h, h, -h, h), // 11 = 0b1011 - Vec4::new(-h, -h, h, h), // 12 = 0b1100 - Vec4::new( h, -h, h, h), // 13 = 0b1101 - Vec4::new(-h, h, h, h), // 14 = 0b1110 - Vec4::new( h, h, h, h), // 15 = 0b1111 - ]; - - // Decompose into 24 5-cells (simplices) - // We use a standard decomposition: each 4D cube can be split into 24 simplices - // by choosing a center point and connecting it to each 3D cell's decomposition - // - // However, a cleaner approach for a tesseract is to use the Kuhn triangulation, - // which decomposes the hypercube into 24 simplices based on the ordering of coordinates. - // - // Each simplex is defined by a path through the hypercube vertices where each step - // changes exactly one coordinate from -h to +h. - - let simplices = Self::compute_simplex_decomposition(); - - Self { vertices, simplices, tetrahedra: None } - } - - /// Get tetrahedra, computing them if needed - pub fn tetrahedra(&mut self) -> &[Tetrahedron] { - if self.tetrahedra.is_none() { - self.tetrahedra = Some(self.compute_unique_tetrahedra()); - } - self.tetrahedra.as_ref().unwrap() - } - - /// Compute tetrahedra decomposition from 5-cells - /// Each 5-cell is decomposed into 5 tetrahedra by omitting each vertex in turn - /// Returns deduplicated tetrahedra (shared faces only appear once) - fn compute_unique_tetrahedra(&self) -> Vec { - let mut seen: HashSet<[usize; 4]> = HashSet::new(); - let mut tetrahedra = Vec::new(); - - for simplex in &self.simplices { - // A 5-cell with vertices {v0,v1,v2,v3,v4} decomposes into 5 tetrahedra - // by omitting each vertex in turn - for omit in 0..5 { - let mut tet_verts = [0usize; 4]; - let mut idx = 0; - for i in 0..5 { - if i != omit { - tet_verts[idx] = simplex[i]; - idx += 1; - } - } - - // Sort for canonical form (deduplication) - let mut canonical = tet_verts; - canonical.sort(); - - if seen.insert(canonical) { - // Store with original vertex order for consistent orientation - tetrahedra.push(Tetrahedron::new(tet_verts)); - } - } - } - - tetrahedra - } - - /// Get the number of tetrahedra (computes if needed) - pub fn tetrahedron_count(&mut self) -> usize { - self.tetrahedra().len() - } - - /// Get the vertices of a specific tetrahedron - pub fn get_tetrahedron_vertices(&mut self, tet_idx: usize) -> [Vec4; 4] { - // Ensure tetrahedra are computed - if self.tetrahedra.is_none() { - self.tetrahedra = Some(self.compute_unique_tetrahedra()); - } - let indices = self.tetrahedra.as_ref().unwrap()[tet_idx].vertices; - [ - self.vertices[indices[0]], - self.vertices[indices[1]], - self.vertices[indices[2]], - self.vertices[indices[3]], - ] - } - - /// Compute the simplex decomposition of a tesseract - /// - /// Uses Kuhn triangulation: each simplex corresponds to a permutation of dimensions. - /// For 4D, there are 4! = 24 permutations, hence 24 simplices. - fn compute_simplex_decomposition() -> Vec<[usize; 5]> { - // Generate all permutations of [0, 1, 2, 3] - let permutations = [ - [0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], - [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], - [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], [2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 1, 0], - [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0], - ]; - - let mut simplices = Vec::with_capacity(24); - - for perm in &permutations { - // For each permutation, create a simplex with 5 vertices - // Starting from vertex 0 (all -h), we flip bits in the order given by perm - - let mut vertex_indices = [0usize; 5]; - let mut current = 0usize; - vertex_indices[0] = current; // Start at 0b0000 - - for (i, &dim) in perm.iter().enumerate() { - current |= 1 << dim; // Flip the bit for this dimension - vertex_indices[i + 1] = current; - } - - simplices.push(vertex_indices); - } - - simplices - } - - /// Get the number of simplices (should be 24) - pub fn simplex_count(&self) -> usize { - self.simplices.len() - } - - /// Get the vertices of a specific simplex - pub fn get_simplex_vertices(&self, simplex_idx: usize) -> [Vec4; 5] { - let indices = &self.simplices[simplex_idx]; - [ - self.vertices[indices[0]], - self.vertices[indices[1]], - self.vertices[indices[2]], - self.vertices[indices[3]], - self.vertices[indices[4]], - ] - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_tesseract_vertex_count() { - let t = Tesseract::new(2.0); - assert_eq!(t.vertices.len(), 16); - } - - #[test] - fn test_tesseract_simplex_count() { - let t = Tesseract::new(2.0); - assert_eq!(t.simplex_count(), 24); - } - - #[test] - fn test_tesseract_vertices_positions() { - let t = Tesseract::new(2.0); - let h = 1.0; - - // Check a few key vertices - assert_eq!(t.vertices[0].x, -h); - assert_eq!(t.vertices[0].y, -h); - assert_eq!(t.vertices[0].z, -h); - assert_eq!(t.vertices[0].w, -h); - - assert_eq!(t.vertices[15].x, h); - assert_eq!(t.vertices[15].y, h); - assert_eq!(t.vertices[15].z, h); - assert_eq!(t.vertices[15].w, h); - } - - #[test] - fn test_simplex_has_five_vertices() { - let t = Tesseract::new(2.0); - for simplex in &t.simplices { - assert_eq!(simplex.len(), 5); - // All indices should be valid - for &idx in simplex { - assert!(idx < 16); - } - } - } - - #[test] - fn test_simplex_vertices_form_path() { - let t = Tesseract::new(2.0); - - // Each simplex should form a path where consecutive vertices differ by one bit - for simplex in &t.simplices { - for i in 0..4 { - let v1 = simplex[i]; - let v2 = simplex[i + 1]; - let diff = v1 ^ v2; - // Should be a power of 2 (exactly one bit different) - assert!(diff.is_power_of_two(), - "Simplex vertices {} and {} differ by {} bits", v1, v2, diff.count_ones()); - } - } - } - - #[test] - fn test_cross_section_at_w0_simplex_edges_analysis() { - // This test analyzes which edges in the simplex decomposition cross w=0 - // to understand the cross-section geometry. - // - // IMPORTANT FINDING: The simplex decomposition creates internal edges - // (diagonals) through the tesseract, not just the original tesseract edges. - // When sliced at w=0, these internal edges also produce intersection points, - // resulting in 27 unique points instead of just the 8 cube corners. - // - // This is CORRECT behavior for a simplicial mesh - the cross-section - // of the simplices produces a triangulated surface (12 triangles forming - // a cube surface, with extra internal triangles from the diagonal edges). - let t = Tesseract::new(2.0); - let h = 1.0; - let slice_w = 0.0; - - // Collect all unique edges in the simplex decomposition - let mut simplex_edges: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new(); - for simplex in &t.simplices { - for i in 0..5 { - for j in (i+1)..5 { - let (v0, v1) = if simplex[i] < simplex[j] { - (simplex[i], simplex[j]) - } else { - (simplex[j], simplex[i]) - }; - simplex_edges.insert((v0, v1)); - } - } - } - - // Count edges that cross w=0 (one vertex w<0, other w>0) - let mut crossing_edges = Vec::new(); - for &(v0, v1) in &simplex_edges { - let w0 = t.vertices[v0].w; - let w1 = t.vertices[v1].w; - if (w0 < slice_w && w1 > slice_w) || (w0 > slice_w && w1 < slice_w) { - crossing_edges.push((v0, v1)); - } - } - - // The 8 "true" tesseract edges that cross w=0 (connecting w=-h to w=+h) - // are: (0,8), (1,9), (2,10), (3,11), (4,12), (5,13), (6,14), (7,15) - let tesseract_crossing_edges: Vec<(usize, usize)> = (0..8) - .map(|i| (i, i + 8)) - .collect(); - - // Verify these 8 edges produce the cube corners - for &(v0, v1) in &tesseract_crossing_edges { - let p0 = t.vertices[v0]; - let p1 = t.vertices[v1]; - assert_eq!(p0.w, -h); - assert_eq!(p1.w, h); - // The xyz should be the same for both endpoints - assert_eq!(p0.x, p1.x); - assert_eq!(p0.y, p1.y); - assert_eq!(p0.z, p1.z); - } - - // Report the edge counts - println!("Total simplex edges: {}", simplex_edges.len()); - println!("Edges crossing w=0: {}", crossing_edges.len()); - println!("Tesseract edges crossing w=0: {}", tesseract_crossing_edges.len()); - - // The simplex decomposition should include all tesseract edges - for &(v0, v1) in &tesseract_crossing_edges { - assert!(simplex_edges.contains(&(v0, v1)), - "Tesseract edge ({}, {}) not found in simplex edges", v0, v1); - } - - // NOTE: There are MORE crossing edges than just the 8 tesseract edges, - // because the simplex decomposition adds diagonal edges through the interior. - // This is expected and correct for the Kuhn triangulation. - assert!(crossing_edges.len() >= 8, - "Should have at least 8 edges crossing w=0 (the tesseract edges)"); - } - - #[test] - fn test_cross_section_geometry_cube_corners_present() { - // Verify that the 8 cube corner points are among the intersection points - let t = Tesseract::new(2.0); - let h = 1.0; - let slice_w = 0.0; - - // The 8 cube corners at w=0 - let expected_corners = [ - [-h, -h, -h], - [ h, -h, -h], - [-h, h, -h], - [ h, h, -h], - [-h, -h, h], - [ h, -h, h], - [-h, h, h], - [ h, h, h], - ]; - - // Find all intersection points from simplex edges - let mut intersection_points: Vec<[f32; 3]> = Vec::new(); - for simplex in &t.simplices { - for i in 0..5 { - for j in (i+1)..5 { - let v0 = t.vertices[simplex[i]]; - let v1 = t.vertices[simplex[j]]; - let w0 = v0.w; - let w1 = v1.w; - - if (w0 < slice_w && w1 > slice_w) || (w0 > slice_w && w1 < slice_w) { - let t_param = (slice_w - w0) / (w1 - w0); - let point = [ - v0.x + t_param * (v1.x - v0.x), - v0.y + t_param * (v1.y - v0.y), - v0.z + t_param * (v1.z - v0.z), - ]; - - if !intersection_points.iter().any(|p| - (p[0] - point[0]).abs() < 0.001 && - (p[1] - point[1]).abs() < 0.001 && - (p[2] - point[2]).abs() < 0.001 - ) { - intersection_points.push(point); - } - } - } - } - } - - // Verify all 8 cube corners are present - for corner in &expected_corners { - let found = intersection_points.iter().any(|p| - (p[0] - corner[0]).abs() < 0.001 && - (p[1] - corner[1]).abs() < 0.001 && - (p[2] - corner[2]).abs() < 0.001 - ); - assert!(found, "Cube corner {:?} not found in intersection points", corner); - } - } - - #[test] - fn test_simplex_decomposition_covers_tesseract() { - // Verify all 24 simplices together cover the entire tesseract - // Each simplex starts at vertex 0 (all -h) and ends at vertex 15 (all +h) - let t = Tesseract::new(2.0); - - for simplex in &t.simplices { - assert_eq!(simplex[0], 0, "First vertex should be 0 (all -h)"); - assert_eq!(simplex[4], 15, "Last vertex should be 15 (all +h)"); - } - } - - #[test] - fn test_all_tesseract_edges_used_in_simplices() { - // The tesseract has 32 edges. Each edge should appear in at least one simplex. - // An edge of the tesseract connects two vertices that differ by exactly one bit. - let t = Tesseract::new(2.0); - - // Collect all edges from the simplex decomposition - let mut simplex_edges: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new(); - - for simplex in &t.simplices { - // Each simplex has 10 edges (C(5,2) = 10) - for i in 0..5 { - for j in (i+1)..5 { - let (v0, v1) = if simplex[i] < simplex[j] { - (simplex[i], simplex[j]) - } else { - (simplex[j], simplex[i]) - }; - simplex_edges.insert((v0, v1)); - } - } - } - - // Count tesseract edges (vertices differing by exactly one bit) - let mut tesseract_edges = 0; - for i in 0usize..16 { - for j in (i+1)..16 { - if (i ^ j).count_ones() == 1 { - tesseract_edges += 1; - // This edge should be in simplex_edges - assert!(simplex_edges.contains(&(i, j)), - "Tesseract edge ({}, {}) not found in any simplex", i, j); - } - } - } - - assert_eq!(tesseract_edges, 32, "Tesseract should have 32 edges"); - } - - #[test] - fn test_cross_section_surface_boundary() { - // This test analyzes which intersection points lie on the BOUNDARY of the - // cross-section (the cube surface) versus the INTERIOR (internal diagonals). - // - // When slicing a tesseract at w=0: - // - Boundary points: on the 6 faces of the resulting cube - // - Interior points: inside the cube volume (from internal simplex edges) - // - // For proper rendering, we only want triangles that form the cube surface. - // Interior triangles should cancel out (matching internal faces from adjacent simplices). - - let t = Tesseract::new(2.0); - let h = 1.0; - let slice_w = 0.0; - - // Collect all unique intersection points - let mut points: Vec<[f32; 3]> = Vec::new(); - - for simplex in &t.simplices { - for i in 0..5 { - for j in (i+1)..5 { - let v0 = t.vertices[simplex[i]]; - let v1 = t.vertices[simplex[j]]; - - if (v0.w < slice_w && v1.w > slice_w) || (v0.w > slice_w && v1.w < slice_w) { - let t_param = (slice_w - v0.w) / (v1.w - v0.w); - let point = [ - v0.x + t_param * (v1.x - v0.x), - v0.y + t_param * (v1.y - v0.y), - v0.z + t_param * (v1.z - v0.z), - ]; - - // Check if already present - let is_new = !points.iter().any(|p| - (p[0] - point[0]).abs() < 0.001 && - (p[1] - point[1]).abs() < 0.001 && - (p[2] - point[2]).abs() < 0.001 - ); - - if is_new { - points.push(point); - } - } - } - } - } - - // Classify points as boundary vs interior - // A point is on the boundary if at least one coordinate is at +-h - let boundary_points: Vec<_> = points.iter().filter(|p| { - (p[0].abs() - h).abs() < 0.001 || - (p[1].abs() - h).abs() < 0.001 || - (p[2].abs() - h).abs() < 0.001 - }).collect(); - - let interior_points: Vec<_> = points.iter().filter(|p| { - (p[0].abs() - h).abs() >= 0.001 && - (p[1].abs() - h).abs() >= 0.001 && - (p[2].abs() - h).abs() >= 0.001 - }).collect(); - - println!("Total unique intersection points: {}", points.len()); - println!("Boundary points (on cube surface): {}", boundary_points.len()); - println!("Interior points (inside cube): {}", interior_points.len()); - - // Print some boundary points for debugging - println!("\nBoundary point samples (should be cube corners/edges/faces):"); - for (i, p) in boundary_points.iter().take(10).enumerate() { - println!(" {}: ({:.2}, {:.2}, {:.2})", i, p[0], p[1], p[2]); - } - - // The 8 cube corners are special: they lie on 3 faces simultaneously - let corner_points: Vec<_> = points.iter().filter(|p| { - (p[0].abs() - h).abs() < 0.001 && - (p[1].abs() - h).abs() < 0.001 && - (p[2].abs() - h).abs() < 0.001 - }).collect(); - - println!("\nCorner points (all 3 coords at +-h): {}", corner_points.len()); - assert_eq!(corner_points.len(), 8, "Should have exactly 8 cube corners"); - - // KEY INSIGHT: For proper cube rendering, we need 12 triangles - // (2 per face * 6 faces). The extra interior points from the - // simplex decomposition create additional triangles that should - // be internal (pairs of opposing triangles on internal simplex faces). - } - - #[test] - fn test_simplex_internal_face_matching() { - // Internal faces of the simplex decomposition should match between - // adjacent simplices. This is crucial for the cross-section: - // matching internal faces produce pairs of triangles that cancel out. - - let t = Tesseract::new(2.0); - - // Collect all simplex faces (triangular, i.e., 3 vertices from each simplex) - let mut faces: std::collections::HashMap<(usize, usize, usize), usize> = std::collections::HashMap::new(); - - for simplex in &t.simplices { - // Each simplex has C(5,3) = 10 triangular faces - for i in 0..5 { - for j in (i+1)..5 { - for k in (j+1)..5 { - let mut f = [simplex[i], simplex[j], simplex[k]]; - f.sort(); - let key = (f[0], f[1], f[2]); - *faces.entry(key).or_insert(0) += 1; - } - } - } - } - - // Count internal vs boundary faces - let internal_faces = faces.iter().filter(|(_, &count)| count >= 2).count(); - let boundary_faces = faces.iter().filter(|(_, &count)| count == 1).count(); - - println!("Total unique faces: {}", faces.len()); - println!("Internal faces (shared by 2+ simplices): {}", internal_faces); - println!("Boundary faces (in 1 simplex only): {}", boundary_faces); - - // Boundary faces should correspond to faces of the tesseract's 8 cubic cells - // Each cube has 6 square faces, each split into 2 triangles = 12 triangles per cube - // 8 cubes * 12 triangles = 96 triangles, but each internal cube face is shared - // So: boundary faces should form the surface of the 4D tesseract - - // Internal faces should have count exactly 2 (shared by adjacent simplices) - for (face, count) in &faces { - if *count > 2 { - println!("WARNING: Face {:?} appears {} times (expected max 2)", face, count); - } - } - } - - // ========== Tetrahedra decomposition tests ========== - - #[test] - fn test_tetrahedra_decomposition_count() { - let mut t = Tesseract::new(2.0); - let count = t.tetrahedron_count(); - - // 24 5-cells, each decomposed into 5 tetrahedra = 120 naive - // After deduplication, should be fewer (shared tetrahedra) - println!("Tetrahedra count: {}", count); - - // Each 5-cell contributes 5 tetrahedra, but many are shared - // The exact count depends on the Kuhn triangulation structure - assert!(count > 0, "Should have at least some tetrahedra"); - assert!(count <= 120, "Should have at most 120 tetrahedra (24 * 5)"); - } - - #[test] - fn test_tetrahedra_have_four_vertices() { - let mut t = Tesseract::new(2.0); - for tet in t.tetrahedra() { - assert_eq!(tet.vertices.len(), 4); - // All indices should be valid - for &idx in &tet.vertices { - assert!(idx < 16, "Vertex index {} out of range", idx); - } - } - } - - #[test] - fn test_tetrahedra_cover_tesseract_edges() { - // All 32 tesseract edges should appear in at least one tetrahedron - let mut t = Tesseract::new(2.0); - - // Collect all edges from tetrahedra - let mut tet_edges: HashSet<(usize, usize)> = HashSet::new(); - for tet in t.tetrahedra() { - // Each tetrahedron has 6 edges - for i in 0..4 { - for j in (i+1)..4 { - let (v0, v1) = if tet.vertices[i] < tet.vertices[j] { - (tet.vertices[i], tet.vertices[j]) - } else { - (tet.vertices[j], tet.vertices[i]) - }; - tet_edges.insert((v0, v1)); - } - } - } - - // Check that all tesseract edges are covered - for i in 0usize..16 { - for j in (i+1)..16 { - if (i ^ j).count_ones() == 1 { - // This is a tesseract edge - assert!(tet_edges.contains(&(i, j)), - "Tesseract edge ({}, {}) not in any tetrahedron", i, j); - } - } - } - } - - #[test] - fn test_tetrahedra_slice_produces_triangles() { - // When sliced at w=0, each tetrahedron produces at most one triangle - let mut t = Tesseract::new(2.0); - let slice_w = 0.0; - - let mut triangle_count = 0; - - for tet in t.tetrahedra().to_vec() { - let verts: Vec<_> = tet.vertices.iter() - .map(|&i| t.vertices[i]) - .collect(); - - // Count vertices above/below slice - let above_count = verts.iter().filter(|v| v.w > slice_w).count(); - - // Tetrahedra should produce triangles for cases 1,2,3 above - // (0 above = no intersection, 4 above = no intersection) - if above_count > 0 && above_count < 4 { - triangle_count += 1; - } - } - - println!("Tetrahedra producing triangles at w=0: {}", triangle_count); - // Should have triangles (exact count depends on tesseract structure) - assert!(triangle_count > 0, "Should produce some triangles"); - } - - #[test] - fn test_tetrahedra_edge_crossing_count() { - // For tetrahedra: - // - 1 or 3 above: 3 edges crossed (triangle) - // - 2 above: 4 edges crossed (quadrilateral, split into 2 triangles) - let mut t = Tesseract::new(2.0); - let slice_w = 0.0; - - let mut triangle_cases = 0; - let mut quad_cases = 0; - - for tet in t.tetrahedra().to_vec() { - let verts: Vec<_> = tet.vertices.iter() - .map(|&i| t.vertices[i]) - .collect(); - - let above: Vec = verts.iter().map(|v| v.w > slice_w).collect(); - let above_count = above.iter().filter(|&&b| b).count(); - - if above_count == 0 || above_count == 4 { - continue; // No intersection - } - - // Count edges crossed - let edges = [(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)]; - let crossed = edges.iter() - .filter(|&&(i, j)| above[i] != above[j]) - .count(); - - match above_count { - 1 | 3 => { - assert_eq!(crossed, 3, - "Tetrahedron with {} vertices above should have 3 edges crossed, got {}", - above_count, crossed); - triangle_cases += 1; - } - 2 => { - assert_eq!(crossed, 4, - "Tetrahedron with 2 vertices above should have 4 edges crossed, got {}", - crossed); - quad_cases += 1; - } - _ => unreachable!() - } - } - - println!("Triangle cases (1 or 3 above): {}", triangle_cases); - println!("Quad cases (2 above): {}", quad_cases); - - assert!(triangle_cases > 0, "Should have some triangle cases"); - assert!(quad_cases > 0, "Should have some quad cases"); - } -} diff --git a/crates/rust4d_render/src/lib.rs b/crates/rust4d_render/src/lib.rs index 2d55dd5..64917e5 100644 --- a/crates/rust4d_render/src/lib.rs +++ b/crates/rust4d_render/src/lib.rs @@ -2,8 +2,29 @@ //! //! This crate provides the wgpu-based rendering pipeline for displaying //! 3D cross-sections of 4D geometry. +//! +//! ## Key Components +//! +//! - [`context::RenderContext`] - WGPU device, queue, and surface management +//! - [`camera4d::Camera4D`] - 4D camera with position and rotation +//! - [`pipeline::SlicePipeline`] - Compute shader for 4D->3D slicing +//! - [`pipeline::RenderPipeline`] - 3D rendering with lighting +//! - [`renderable::RenderableGeometry`] - Converts World/Entity to GPU buffers +//! +//! ## Shapes +//! +//! Shape geometry is defined in `rust4d_math`. This crate re-exports the shapes +//! for convenience, but you can also import them directly from `rust4d_math`. pub mod context; -pub mod geometry; pub mod camera4d; pub mod pipeline; +pub mod renderable; + +// Re-export core types for convenience +pub use rust4d_core::{World, Entity, Transform4D, Material, ShapeRef, EntityHandle}; +pub use rust4d_core::{ConvexShape4D, Tetrahedron, Tesseract4D, Hyperplane4D}; +pub use rust4d_core::{Vec4, Rotor4, RotationPlane}; + +// Re-export renderable for easy access +pub use renderable::{RenderableGeometry, CheckerboardGeometry, position_gradient_color, blended_color}; diff --git a/crates/rust4d_render/src/renderable.rs b/crates/rust4d_render/src/renderable.rs new file mode 100644 index 0000000..7340989 --- /dev/null +++ b/crates/rust4d_render/src/renderable.rs @@ -0,0 +1,336 @@ +//! Renderable geometry - bridges World/Entity to GPU buffers +//! +//! This module converts the abstract shape data from rust4d_core into +//! GPU-compatible vertex and tetrahedra buffers. + +use rust4d_core::{Entity, World, Material}; +use rust4d_math::Vec4; +use crate::pipeline::{Vertex4D, GpuTetrahedron}; + +/// A color function that generates vertex colors +/// +/// Used to customize how vertices are colored during geometry collection. +pub type ColorFn = Box [f32; 4]>; + +/// GPU-ready geometry collected from entities +/// +/// This struct holds the vertices and tetrahedra in a format ready for +/// upload to GPU buffers. +pub struct RenderableGeometry { + /// Vertices with 4D positions and colors + pub vertices: Vec, + /// Tetrahedra as indices into the vertex buffer + pub tetrahedra: Vec, +} + +impl RenderableGeometry { + /// Create an empty renderable geometry + pub fn new() -> Self { + Self { + vertices: Vec::new(), + tetrahedra: Vec::new(), + } + } + + /// Create renderable geometry with pre-allocated capacity + pub fn with_capacity(vertex_capacity: usize, tetrahedron_capacity: usize) -> Self { + Self { + vertices: Vec::with_capacity(vertex_capacity), + tetrahedra: Vec::with_capacity(tetrahedron_capacity), + } + } + + /// Collect geometry from a single entity + /// + /// Uses the entity's material base_color for all vertices. + pub fn from_entity(entity: &Entity) -> Self { + Self::from_entity_with_color(entity, &default_color_fn) + } + + /// Collect geometry from a single entity with a custom color function + pub fn from_entity_with_color(entity: &Entity, color_fn: &dyn Fn(&Vec4, &Material) -> [f32; 4]) -> Self { + let mut result = Self::new(); + result.add_entity_with_color(entity, color_fn); + result + } + + /// Collect geometry from all entities in a world + /// + /// Uses each entity's material base_color for all its vertices. + pub fn from_world(world: &World) -> Self { + Self::from_world_with_color(world, &default_color_fn) + } + + /// Collect geometry from all entities in a world with a custom color function + pub fn from_world_with_color(world: &World, color_fn: &dyn Fn(&Vec4, &Material) -> [f32; 4]) -> Self { + // Estimate capacity + let mut total_vertices = 0; + let mut total_tetrahedra = 0; + for entity in world.iter() { + total_vertices += entity.shape().vertex_count(); + total_tetrahedra += entity.shape().tetrahedron_count(); + } + + let mut result = Self::with_capacity(total_vertices, total_tetrahedra); + for entity in world.iter() { + result.add_entity_with_color(entity, color_fn); + } + result + } + + /// Add an entity's geometry to this collection + /// + /// Uses the entity's material base_color for all vertices. + pub fn add_entity(&mut self, entity: &Entity) { + self.add_entity_with_color(entity, &default_color_fn); + } + + /// Add an entity's geometry with a custom color function + pub fn add_entity_with_color(&mut self, entity: &Entity, color_fn: &dyn Fn(&Vec4, &Material) -> [f32; 4]) { + let shape = entity.shape(); + let vertex_offset = self.vertices.len(); + + // Transform and add vertices + for v in shape.vertices() { + let world_pos = entity.transform.transform_point(*v); + let color = color_fn(v, &entity.material); + self.vertices.push(Vertex4D::new( + [world_pos.x, world_pos.y, world_pos.z, world_pos.w], + color, + )); + } + + // Add tetrahedra with offset indices + for tet in shape.tetrahedra() { + self.tetrahedra.push(GpuTetrahedron::from_indices([ + (tet.indices[0] + vertex_offset) as u32, + (tet.indices[1] + vertex_offset) as u32, + (tet.indices[2] + vertex_offset) as u32, + (tet.indices[3] + vertex_offset) as u32, + ])); + } + } + + /// Clear all geometry + pub fn clear(&mut self) { + self.vertices.clear(); + self.tetrahedra.clear(); + } + + /// Get the number of vertices + #[inline] + pub fn vertex_count(&self) -> usize { + self.vertices.len() + } + + /// Get the number of tetrahedra + #[inline] + pub fn tetrahedron_count(&self) -> usize { + self.tetrahedra.len() + } +} + +impl Default for RenderableGeometry { + fn default() -> Self { + Self::new() + } +} + +/// Default color function - uses material's base_color for all vertices +fn default_color_fn(_vertex: &Vec4, material: &Material) -> [f32; 4] { + material.base_color +} + +/// Color function that creates a gradient based on vertex position +/// +/// Maps each coordinate component to RGB channels. +pub fn position_gradient_color(vertex: &Vec4, _material: &Material) -> [f32; 4] { + [ + (vertex.x + 1.0) / 2.0, // Red from x + (vertex.y + 1.0) / 2.0, // Green from y + (vertex.z + 1.0) / 2.0, // Blue from z + 1.0, + ] +} + +/// Color function that blends material color with position gradient +pub fn blended_color(vertex: &Vec4, material: &Material) -> [f32; 4] { + let pos_color = position_gradient_color(vertex, material); + let base = material.base_color; + + // 50/50 blend + [ + (pos_color[0] + base[0]) * 0.5, + (pos_color[1] + base[1]) * 0.5, + (pos_color[2] + base[2]) * 0.5, + base[3], // Keep material alpha + ] +} + +/// Utility struct for building geometry with checkerboard patterns +pub struct CheckerboardGeometry { + /// Colors for the checkerboard pattern + pub color_a: [f32; 4], + pub color_b: [f32; 4], + /// Size of each checker cell + pub cell_size: f32, +} + +impl CheckerboardGeometry { + /// Create a new checkerboard with the given colors and cell size + pub fn new(color_a: [f32; 4], color_b: [f32; 4], cell_size: f32) -> Self { + Self { color_a, color_b, cell_size } + } + + /// Get the color for a vertex based on its XZ position + pub fn color_for_position(&self, x: f32, z: f32) -> [f32; 4] { + let cell_x = (x / self.cell_size).floor() as i32; + let cell_z = (z / self.cell_size).floor() as i32; + + if (cell_x + cell_z) % 2 == 0 { + self.color_a + } else { + self.color_b + } + } + + /// Create a color function that applies checkerboard pattern + pub fn color_fn(&self) -> impl Fn(&Vec4, &Material) -> [f32; 4] + '_ { + move |vertex, _material| { + self.color_for_position(vertex.x, vertex.z) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rust4d_core::{ShapeRef, Tesseract4D, Transform4D}; + + fn make_test_entity() -> Entity { + let tesseract = Tesseract4D::new(2.0); + Entity::with_material( + ShapeRef::shared(tesseract), + Material::from_rgb(1.0, 0.5, 0.25), + ) + } + + #[test] + fn test_renderable_geometry_new() { + let geom = RenderableGeometry::new(); + assert_eq!(geom.vertex_count(), 0); + assert_eq!(geom.tetrahedron_count(), 0); + } + + #[test] + fn test_renderable_geometry_from_entity() { + let entity = make_test_entity(); + let geom = RenderableGeometry::from_entity(&entity); + + assert_eq!(geom.vertex_count(), 16); // Tesseract has 16 vertices + assert!(geom.tetrahedron_count() > 0); + + // Check that all vertices have the material color + for v in &geom.vertices { + assert_eq!(v.color, [1.0, 0.5, 0.25, 1.0]); + } + } + + #[test] + fn test_renderable_geometry_from_world() { + let mut world = World::new(); + world.add_entity(make_test_entity()); + world.add_entity(make_test_entity()); + + let geom = RenderableGeometry::from_world(&world); + + assert_eq!(geom.vertex_count(), 32); // 2 tesseracts * 16 vertices + } + + #[test] + fn test_renderable_geometry_add_entity() { + let mut geom = RenderableGeometry::new(); + let entity = make_test_entity(); + + geom.add_entity(&entity); + assert_eq!(geom.vertex_count(), 16); + + geom.add_entity(&entity); + assert_eq!(geom.vertex_count(), 32); + } + + #[test] + fn test_renderable_geometry_clear() { + let entity = make_test_entity(); + let mut geom = RenderableGeometry::from_entity(&entity); + + assert!(geom.vertex_count() > 0); + geom.clear(); + assert_eq!(geom.vertex_count(), 0); + assert_eq!(geom.tetrahedron_count(), 0); + } + + #[test] + fn test_position_gradient_color() { + let v = Vec4::new(1.0, 1.0, 1.0, 0.0); + let m = Material::default(); + let color = position_gradient_color(&v, &m); + + assert_eq!(color, [1.0, 1.0, 1.0, 1.0]); + + let v2 = Vec4::new(-1.0, -1.0, -1.0, 0.0); + let color2 = position_gradient_color(&v2, &m); + assert_eq!(color2, [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn test_checkerboard_color() { + let checker = CheckerboardGeometry::new( + [1.0, 1.0, 1.0, 1.0], // white + [0.0, 0.0, 0.0, 1.0], // black + 1.0, + ); + + // (0, 0) -> cell (0, 0) -> even -> white + let c1 = checker.color_for_position(0.5, 0.5); + assert_eq!(c1, [1.0, 1.0, 1.0, 1.0]); + + // (1, 0) -> cell (1, 0) -> odd -> black + let c2 = checker.color_for_position(1.5, 0.5); + assert_eq!(c2, [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn test_transform_applied() { + let tesseract = Tesseract4D::new(2.0); + let mut entity = Entity::new(ShapeRef::shared(tesseract)); + + // Translate by (10, 0, 0, 0) + entity.transform = Transform4D::from_position(Vec4::new(10.0, 0.0, 0.0, 0.0)); + + let geom = RenderableGeometry::from_entity(&entity); + + // All vertices should be offset by 10 in x + for v in &geom.vertices { + assert!(v.position[0] >= 9.0 && v.position[0] <= 11.0, + "Vertex x should be around 10, got {}", v.position[0]); + } + } + + #[test] + fn test_tetrahedra_indices_offset() { + let mut geom = RenderableGeometry::new(); + let entity1 = make_test_entity(); + let entity2 = make_test_entity(); + + geom.add_entity(&entity1); + let first_entity_verts = geom.vertex_count(); + + geom.add_entity(&entity2); + + // Second entity's tetrahedra should have indices >= first_entity_verts + let second_tet = geom.tetrahedra.last().unwrap(); + assert!(second_tet.v0 >= first_entity_verts as u32, + "Second entity's tetrahedra should have offset indices"); + } +} diff --git a/scratchpad/plans/physics-ready-architecture.md b/scratchpad/plans/physics-ready-architecture.md new file mode 100644 index 0000000..587bc9c --- /dev/null +++ b/scratchpad/plans/physics-ready-architecture.md @@ -0,0 +1,375 @@ +# Refactoring Plan: Physics-Ready Architecture + +## Current State Analysis + +The codebase is currently a **rendering-focused** engine with these characteristics: + +| Aspect | Current State | Issue for Physics | +|--------|---------------|-------------------| +| Geometry | Tesseract/Hyperplane produce GPU vertices directly | Shapes coupled to rendering (colors baked in) | +| Objects | Raw arrays of vertices/tetrahedra | No entity abstraction, no transforms | +| Movement | Only camera moves | No concept of moving bodies | +| Scene | Everything global in main.rs | No scene/world container | + +## Goals + +1. **Decouple geometry from rendering** - Pure shapes without color/material +2. **Create entity system** - Objects with transforms, shapes, and optional physics +3. **Prepare for physics crate** - Clean interfaces for collision/dynamics +4. **Maintain rendering quality** - No visual regression + +## Proposed Architecture + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ Application Layer │ +│ main.rs: event loop, window, user input │ +└─────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────┐ +│ rust4d_core (NEW CRATE) │ +│ World, Entity, Transform4D, Material │ +│ - Owns entities │ +│ - Steps physics (future) │ +│ - Collects renderables │ +└─────────────────────────────────────────────────────────────────────┘ + │ + ┌────────────────────────┼────────────────────────┐ + ▼ ▼ ▼ +┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ +│ Entity │ │ Entity │ │ Camera4D │ +│ - Transform4D │ │ - Transform4D │ │ (in render) │ +│ - Shape (Arc) │ │ - Shape (owned) │ │ │ +│ - Material │ │ - Material │ │ │ +│ - RigidBody* │ │ - RigidBody* │ │ │ +└──────────────────┘ └──────────────────┘ └──────────────────┘ + │ │ + ▼ ▼ +┌─────────────────────────────────────────────────────────────────────┐ +│ rust4d_math (shapes added) │ +│ ConvexShape4D trait │ +│ - Tesseract4D, Hyperplane4D, Custom │ +│ - vertices() -> &[Vec4] │ +│ - tetrahedra() -> &[Tetrahedron] │ +│ + Vec4, Rotor4, Mat4 (existing) │ +└─────────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────┐ +│ rust4d_render │ +│ RenderableGeometry: World -> GPU buffers │ +│ SlicePipeline: 4D->3D compute │ +│ RenderPipeline: 3D->screen │ +│ Camera4D (stays here, rendering-specific) │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Crate Dependency Graph + +``` +rust4d_math (no deps) + │ + ▼ +rust4d_core (depends on math) + │ + ├──────────────────┐ + ▼ ▼ +rust4d_render rust4d_input + │ │ + └────────┬─────────┘ + ▼ + main.rs +``` + +--- + +## Refactoring Steps + +### Step 1: Extract Pure Geometry (rust4d_math) + +**Move shape definitions to math crate** - shapes are mathematical, not render-specific. + +**New types in rust4d_math:** +```rust +// Pure tetrahedron (indices only) +pub struct Tetrahedron { + pub indices: [usize; 4], +} + +// Convex shape trait +pub trait ConvexShape4D { + fn vertices(&self) -> &[Vec4]; + fn tetrahedra(&self) -> &[Tetrahedron]; +} + +// Pure tesseract (no colors) +pub struct Tesseract4D { + half_size: f32, + vertices: [Vec4; 16], + tetrahedra: Vec, +} + +// Pure hyperplane (no colors) +pub struct Hyperplane4D { + y_level: f32, + size: f32, + w_extent: f32, + vertices: Vec, + tetrahedra: Vec, +} +``` + +**Files:** +- Create `crates/rust4d_math/src/shape.rs` +- Create `crates/rust4d_math/src/tesseract.rs` (move from rust4d_render) +- Create `crates/rust4d_math/src/hyperplane.rs` (move from rust4d_render) + +### Step 2: Create rust4d_core Crate + +**New crate for shared game types:** + +```toml +# crates/rust4d_core/Cargo.toml +[package] +name = "rust4d_core" +version = "0.1.0" +edition = "2021" + +[dependencies] +rust4d_math = { path = "../rust4d_math" } +``` + +**Transform4D:** +```rust +// crates/rust4d_core/src/transform.rs +pub struct Transform4D { + pub position: Vec4, + pub rotation: Rotor4, + pub scale: f32, // uniform scale for simplicity +} + +impl Transform4D { + pub fn identity() -> Self; + pub fn matrix(&self) -> [[f32; 4]; 4]; + pub fn transform_point(&self, p: Vec4) -> Vec4; + pub fn inverse(&self) -> Transform4D; +} +``` + +**Material (minimal):** +```rust +// crates/rust4d_core/src/entity.rs +pub struct Material { + pub base_color: [f32; 4], +} +``` + +**Entity with flexible shape ownership:** +```rust +pub enum ShapeRef { + Shared(Arc), + Owned(Box), +} + +pub struct Entity { + pub transform: Transform4D, + pub shape: ShapeRef, + pub material: Material, + // Future: pub rigid_body: Option, +} +``` + +**World container:** +```rust +// crates/rust4d_core/src/world.rs +pub struct World { + entities: Vec, + // Future: physics_world: PhysicsWorld, +} + +impl World { + pub fn new() -> Self; + pub fn add_entity(&mut self, entity: Entity) -> usize; + pub fn entities(&self) -> &[Entity]; + pub fn update(&mut self, dt: f32); // Future: steps physics +} +``` + +### Step 3: Update rust4d_render + +**Add RenderableGeometry to bridge World to GPU:** +```rust +// crates/rust4d_render/src/renderable.rs +use rust4d_core::{World, Entity}; + +pub struct RenderableGeometry { + pub vertices: Vec, + pub tetrahedra: Vec, +} + +impl RenderableGeometry { + /// Build GPU buffers from a single entity + pub fn from_entity(entity: &Entity) -> Self; + + /// Batch all entities in a world into one buffer + pub fn from_world(world: &World) -> Self; +} +``` + +**Update Cargo.toml:** +```toml +[dependencies] +rust4d_core = { path = "../rust4d_core" } +``` + +**Remove old geometry module** - Tesseract/Hyperplane moved to rust4d_math. + +### Step 4: Update main.rs + +**Before:** +```rust +let tesseract = Tesseract::new(2.0); +let (vertices, tetrahedra) = tesseract_to_tetrahedra(&mut tesseract); +// ... direct GPU upload +``` + +**After:** +```rust +use rust4d_core::{World, Entity, Transform4D, Material, ShapeRef}; +use rust4d_math::{Tesseract4D, Hyperplane4D}; +use rust4d_render::RenderableGeometry; +use std::sync::Arc; + +let mut world = World::new(); + +// Add tesseract entity (shared shape) +let tesseract_shape = Arc::new(Tesseract4D::new(2.0)); +world.add_entity(Entity { + transform: Transform4D::identity(), + shape: ShapeRef::Shared(tesseract_shape), + material: Material { base_color: [1.0, 0.5, 0.2, 1.0] }, +}); + +// Add floor entity (shared shape) +let floor_shape = Arc::new(Hyperplane4D::new(-2.0, 10.0, 5.0)); +world.add_entity(Entity { + transform: Transform4D::identity(), + shape: ShapeRef::Shared(floor_shape), + material: Material { base_color: [0.5, 0.5, 0.5, 1.0] }, +}); + +// Main loop: collect geometry from world +let geometry = RenderableGeometry::from_world(&world); +slice_pipeline.upload_tetrahedra(&device, &geometry.vertices, &geometry.tetrahedra); +``` + +--- + +## File Changes Summary + +| Action | File | Description | +|--------|------|-------------| +| **rust4d_math** | | | +| Create | `rust4d_math/src/shape.rs` | ConvexShape4D trait, Tetrahedron | +| Create | `rust4d_math/src/tesseract.rs` | Pure Tesseract4D (moved from render) | +| Create | `rust4d_math/src/hyperplane.rs` | Pure Hyperplane4D (moved from render) | +| Update | `rust4d_math/src/lib.rs` | Export new shape modules | +| **rust4d_core (NEW)** | | | +| Create | `crates/rust4d_core/Cargo.toml` | New crate manifest | +| Create | `crates/rust4d_core/src/lib.rs` | Crate root | +| Create | `crates/rust4d_core/src/transform.rs` | Transform4D | +| Create | `crates/rust4d_core/src/entity.rs` | Entity, Material | +| Create | `crates/rust4d_core/src/world.rs` | World container | +| **rust4d_render** | | | +| Create | `rust4d_render/src/renderable.rs` | RenderableGeometry (World -> GPU) | +| Delete | `rust4d_render/src/geometry/tesseract.rs` | Moved to math | +| Delete | `rust4d_render/src/geometry/hyperplane.rs` | Moved to math | +| Update | `rust4d_render/src/geometry/mod.rs` | Remove old geometry exports | +| Update | `rust4d_render/src/lib.rs` | Add rust4d_core dep, export renderable | +| Update | `rust4d_render/Cargo.toml` | Add rust4d_core dependency | +| **Workspace** | | | +| Update | `Cargo.toml` | Add rust4d_core to workspace members | +| Update | `src/main.rs` | Use new World/Entity API | + +--- + +## Session Estimates + +| Step | Sessions | Notes | +|------|----------|-------| +| Step 1: Extract geometry to math | 1-2 | Move Tesseract/Hyperplane, add ConvexShape4D trait | +| Step 2: Create rust4d_core | 1-2 | Transform4D, Entity, Material, World, ShapeRef | +| Step 3: Update rust4d_render | 1 | RenderableGeometry, remove old geometry module | +| Step 4: Update main.rs | 0.5-1 | Wire everything together, test visuals | +| **Total** | **4-6 sessions** | | + +--- + +## Future Physics Integration + +With this architecture, adding physics becomes straightforward: + +```rust +// New crate: rust4d_physics +pub struct RigidBody4D { + pub mass: f32, + pub velocity: Vec4, + pub angular_velocity: Rotor4, // or bivector + pub shape: Arc, +} + +pub struct PhysicsWorld { + bodies: Vec, +} + +// Entity gains physics handle +pub struct Entity { + pub transform: Transform4D, + pub shape: Arc, + pub material: Material, + pub rigid_body: Option, // index into PhysicsWorld +} + +// World steps physics +impl World { + pub fn update(&mut self, dt: f32) { + self.physics_world.step(dt); + for entity in &mut self.entities { + if let Some(rb) = entity.rigid_body { + entity.transform = self.physics_world.get_transform(rb); + } + } + } +} +``` + +--- + +## Verification + +After refactoring: +1. `cargo build` - no compilation errors +2. `cargo test` - all existing tests pass +3. Run application - visuals identical to before +4. Camera controls work as before +5. No performance regression (GPU pipeline unchanged) + +--- + +## Design Decisions (User Confirmed) + +1. **Shape ownership**: Both patterns supported + - Default: `Arc` for shared shapes (memory efficient) + - Option: `.clone()` for unique copies when mutation needed + - Shapes implement `Clone` for this flexibility + +2. **Materials**: Minimal for now + - Just `base_color: [f32; 4]` + - Add complexity (per-vertex functions, PBR) when needed + +3. **Crate structure**: New `rust4d_core` crate + - Central home for shared game types (Entity, World, Transform4D) + - Clean separation from math primitives and rendering specifics + - Depends on: `rust4d_math` + - Depended on by: `rust4d_render`, `src/main.rs` diff --git a/scratchpad/reports/2026-01-27-physics-ready-architecture-refactor.md b/scratchpad/reports/2026-01-27-physics-ready-architecture-refactor.md new file mode 100644 index 0000000..cda334b --- /dev/null +++ b/scratchpad/reports/2026-01-27-physics-ready-architecture-refactor.md @@ -0,0 +1,145 @@ +# Session Report: Physics-Ready Architecture Refactor + +**Date:** 2026-01-27 +**Branch:** `refactor/physics-ready-architecture` + +## Summary + +Implemented a major architectural refactor to decouple geometry from rendering and prepare the codebase for future physics integration. This transforms the engine from a rendering-focused codebase to a proper entity-based architecture. + +## Changes Made + +### Step 1: Extract Pure Geometry to rust4d_math + +Created new shape system in `rust4d_math`: + +- **`shape.rs`**: `ConvexShape4D` trait and `Tetrahedron` struct + - Trait provides `vertices()` and `tetrahedra()` for any 4D shape + - Tetrahedron holds vertex indices, not colors + +- **`tesseract.rs`**: `Tesseract4D` - pure 4D hypercube geometry + - Moved from rust4d_render, stripped colors + - Implements `ConvexShape4D` trait + - Uses Kuhn triangulation for tetrahedra decomposition + +- **`hyperplane.rs`**: `Hyperplane4D` - pure floor/ground plane + - Moved from rust4d_render, stripped colors + - Grid-based geometry with W extent for slicing + +### Step 2: Create rust4d_core Crate + +New crate for shared game types: + +- **`transform.rs`**: `Transform4D` - position, rotation, scale + - Uses Rotor4 for rotation + - Methods: `transform_point()`, `inverse()`, `compose()` + +- **`entity.rs`**: + - `Material` - base color RGBA (minimal for now) + - `ShapeRef` - enum for Shared (Arc) or Owned (Box) shapes + - `Entity` - transform + shape + material + +- **`world.rs`**: `World` container + - Owns all entities + - `add_entity()`, `get_entity()`, `iter()` + - Placeholder `update(dt)` for future physics + +### Step 3: Update rust4d_render + +- **`renderable.rs`**: Bridges World/Entity to GPU buffers + - `RenderableGeometry` - collects vertices and tetrahedra + - `from_world()`, `from_entity()` methods + - Custom color functions: `position_gradient_color`, `blended_color` + - `CheckerboardGeometry` utility for floor patterns + +- Removed old `geometry/` module (tesseract.rs, hyperplane.rs, mod.rs) +- Re-exports core types from rust4d_core for convenience + +### Step 4: Update main.rs + +- Uses new World/Entity API +- Creates entities with `Entity::with_material()` and `ShapeRef::shared()` +- Builds geometry with `RenderableGeometry::from_world()` +- Calls `world.update(dt)` in render loop (no-op for now) + +## Architecture After Refactor + +``` +rust4d_math (no deps) + - Vec4, Rotor4, Mat4 + - ConvexShape4D trait + - Tesseract4D, Hyperplane4D + │ + ▼ +rust4d_core (depends on math) + - Transform4D + - Material, Entity, ShapeRef + - World, EntityHandle + │ + ├──────────────────┐ + ▼ ▼ +rust4d_render rust4d_input + - RenderableGeometry + - SlicePipeline + - RenderPipeline + │ │ + └────────┬─────────┘ + ▼ + main.rs +``` + +## Test Results + +All 132 tests pass: +- rust4d_math: 54 tests +- rust4d_core: 29 tests +- rust4d_render: 48 tests +- Doc tests: 1 test + +## Future Physics Integration + +With this architecture, physics can be added by: + +1. Create `rust4d_physics` crate with `RigidBody4D`, `PhysicsWorld` +2. Add `rigid_body: Option` to Entity +3. Implement `World::update()` to step physics and sync transforms + +## Files Changed + +| Action | File | +|--------|------| +| Create | `crates/rust4d_math/src/shape.rs` | +| Create | `crates/rust4d_math/src/tesseract.rs` | +| Create | `crates/rust4d_math/src/hyperplane.rs` | +| Update | `crates/rust4d_math/src/lib.rs` | +| Create | `crates/rust4d_core/Cargo.toml` | +| Create | `crates/rust4d_core/src/lib.rs` | +| Create | `crates/rust4d_core/src/transform.rs` | +| Create | `crates/rust4d_core/src/entity.rs` | +| Create | `crates/rust4d_core/src/world.rs` | +| Create | `crates/rust4d_render/src/renderable.rs` | +| Delete | `crates/rust4d_render/src/geometry/` (moved to math) | +| Update | `crates/rust4d_render/src/lib.rs` | +| Update | `crates/rust4d_render/Cargo.toml` | +| Update | `Cargo.toml` (workspace) | +| Update | `src/main.rs` | + +## Observations + +1. **Clean separation achieved**: Shapes are now purely mathematical, entities own transforms, materials handle visual properties + +2. **Flexible ownership**: ShapeRef enum allows both shared (Arc) and owned (Box) shapes - most entities will share shapes, but unique copies are possible + +3. **Color functions work well**: The custom color function approach (position gradient, checkerboard) is flexible and clean + +4. **Minor warning**: `Hyperplane4D::thickness` field is stored but never read. Could add a getter or remove if truly unused. + +5. **No visual regression**: The refactored code produces identical visuals to before + +## Open Questions for Future + +1. Should entity transforms apply at geometry collection time or at render time? (Currently: collection time, which is simpler but requires rebuilding when transforms change) + +2. How to handle dynamic entities efficiently? (Currently: would need to rebuild RenderableGeometry) + +3. Per-vertex color functions vs per-entity materials - what's the right abstraction for complex materials? diff --git a/src/main.rs b/src/main.rs index 50f0aab..71f85c8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,12 +11,15 @@ use winit::{ window::{CursorGrabMode, Fullscreen, Window, WindowId}, }; -use rust4d_render::context::RenderContext; -use rust4d_render::camera4d::Camera4D; -use rust4d_render::geometry::{Tesseract, Hyperplane}; -use rust4d_render::pipeline::{ - SlicePipeline, RenderPipeline, SliceParams, RenderUniforms, - Vertex4D, GpuTetrahedron, perspective_matrix, +use rust4d_core::{ + World, Entity, ShapeRef, Material, + Tesseract4D, Hyperplane4D, +}; +use rust4d_render::{ + context::RenderContext, + camera4d::Camera4D, + pipeline::{SlicePipeline, RenderPipeline, SliceParams, RenderUniforms, perspective_matrix}, + RenderableGeometry, CheckerboardGeometry, position_gradient_color, }; use rust4d_input::CameraController; @@ -26,8 +29,10 @@ struct App { render_context: Option, slice_pipeline: Option, render_pipeline: Option, - vertices: Vec, - tetrahedra: Vec, + /// The 4D world containing all entities + world: World, + /// Cached GPU geometry (rebuilt when world changes) + geometry: RenderableGeometry, camera: Camera4D, controller: CameraController, last_frame: std::time::Instant, @@ -36,29 +41,37 @@ struct App { impl App { fn new() -> Self { - // Create tesseract geometry - let mut tesseract = Tesseract::new(2.0); - let (mut vertices, mut tetrahedra) = Self::tesseract_to_tetrahedra(&mut tesseract); - - // Create checkerboard hyperplane below the tesseract - // y=-2.0 (below tesseract), size=10 (extends from -10 to +10 in XZ), - // 10x10 grid, cell_size=2.0 for checkerboard, w_extent=5.0, tiny thickness - let hyperplane = Hyperplane::new(-2.0, 10.0, 10, 2.0, 5.0, 0.001); - let (plane_vertices, plane_tetrahedra) = Self::hyperplane_to_tetrahedra(&hyperplane, vertices.len()); - - // Combine geometry - vertices.extend(plane_vertices); - tetrahedra.extend(plane_tetrahedra); - - log::info!("Total geometry: {} vertices, {} tetrahedra", vertices.len(), tetrahedra.len()); + // Create the world + let mut world = World::with_capacity(2); + + // Add tesseract entity with position-based gradient coloring + let tesseract = Tesseract4D::new(2.0); + world.add_entity(Entity::with_material( + ShapeRef::shared(tesseract), + Material::WHITE, // Will be overridden by position gradient + )); + + // Add checkerboard floor entity + let floor = Hyperplane4D::new(-2.0, 10.0, 10, 5.0, 0.001); + world.add_entity(Entity::with_material( + ShapeRef::shared(floor), + Material::GRAY, // Will be overridden by checkerboard + )); + + // Build GPU geometry from the world + let geometry = Self::build_geometry(&world); + + log::info!("World created with {} entities", world.entity_count()); + log::info!("Total geometry: {} vertices, {} tetrahedra", + geometry.vertex_count(), geometry.tetrahedron_count()); Self { window: None, render_context: None, slice_pipeline: None, render_pipeline: None, - vertices, - tetrahedra, + world, + geometry, camera: Camera4D::new(), controller: CameraController::new(), last_frame: std::time::Instant::now(), @@ -66,60 +79,30 @@ impl App { } } - /// Convert tesseract geometry to GPU vertices and tetrahedra - fn tesseract_to_tetrahedra(tesseract: &mut Tesseract) -> (Vec, Vec) { - // Convert tesseract vertices to GPU format with colors - let vertices: Vec = tesseract.vertices.iter().enumerate().map(|(_i, v)| { - // Color based on vertex position - creates visual gradient - let color = [ - (v.x + 1.0) / 2.0, // Red from x - (v.y + 1.0) / 2.0, // Green from y - (v.z + 1.0) / 2.0, // Blue from z - 1.0, - ]; - Vertex4D::new([v.x, v.y, v.z, v.w], color) - }).collect(); - - // Get tetrahedra decomposition - let tetrahedra: Vec = tesseract.tetrahedra().iter().map(|tet| { - GpuTetrahedron::from_indices([ - tet.vertices[0] as u32, - tet.vertices[1] as u32, - tet.vertices[2] as u32, - tet.vertices[3] as u32, - ]) - }).collect(); - - log::info!("Generated {} vertices and {} tetrahedra from tesseract", - vertices.len(), tetrahedra.len()); - - (vertices, tetrahedra) - } + /// Build GPU geometry from the world using custom coloring + fn build_geometry(world: &World) -> RenderableGeometry { + let mut geometry = RenderableGeometry::new(); + + // Checkerboard pattern for the floor + let checkerboard = CheckerboardGeometry::new( + [0.3, 0.3, 0.35, 1.0], // Dark gray + [0.7, 0.7, 0.75, 1.0], // Light gray + 2.0, // Cell size + ); + + for (idx, entity) in world.iter().enumerate() { + if idx == 0 { + // Tesseract: use position gradient + geometry.add_entity_with_color(entity, &position_gradient_color); + } else { + // Floor: use checkerboard pattern + geometry.add_entity_with_color(entity, &|v, _m| { + checkerboard.color_for_position(v.x, v.z) + }); + } + } - /// Convert hyperplane geometry to GPU vertices and tetrahedra - fn hyperplane_to_tetrahedra(hyperplane: &Hyperplane, vertex_offset: usize) -> (Vec, Vec) { - // Convert hyperplane vertices to GPU format with pre-computed colors - let vertices: Vec = hyperplane.vertices.iter() - .zip(hyperplane.colors.iter()) - .map(|(v, color)| { - Vertex4D::new([v.x, v.y, v.z, v.w], *color) - }) - .collect(); - - // Convert tetrahedra with offset for combined vertex buffer - let tetrahedra: Vec = hyperplane.tetrahedra.iter().map(|tet| { - GpuTetrahedron::from_indices([ - (tet.vertices[0] + vertex_offset) as u32, - (tet.vertices[1] + vertex_offset) as u32, - (tet.vertices[2] + vertex_offset) as u32, - (tet.vertices[3] + vertex_offset) as u32, - ]) - }).collect(); - - log::info!("Generated {} vertices and {} tetrahedra from hyperplane", - vertices.len(), tetrahedra.len()); - - (vertices, tetrahedra) + geometry } /// Capture cursor for FPS-style controls @@ -180,11 +163,15 @@ impl ApplicationHandler for App { render_context.size.height, ); - // Upload tesseract geometry (tetrahedra mode) - slice_pipeline.upload_tetrahedra(&render_context.device, &self.vertices, &self.tetrahedra); + // Upload geometry + slice_pipeline.upload_tetrahedra( + &render_context.device, + &self.geometry.vertices, + &self.geometry.tetrahedra, + ); - log::info!("Loaded {} vertices and {} tetrahedra from tesseract", - self.vertices.len(), self.tetrahedra.len()); + log::info!("Loaded {} vertices and {} tetrahedra", + self.geometry.vertex_count(), self.geometry.tetrahedron_count()); self.window = Some(window); self.render_context = Some(render_context); @@ -277,6 +264,9 @@ impl ApplicationHandler for App { let dt = (now - self.last_frame).as_secs_f32(); self.last_frame = now; + // Update world (future: physics) + self.world.update(dt); + // Update camera let _pos = self.controller.update(&mut self.camera, dt, self.cursor_captured); @@ -312,7 +302,7 @@ impl ApplicationHandler for App { let camera_matrix = self.camera.rotation_matrix(); let slice_params = SliceParams { slice_w: self.camera.get_slice_w(), - tetrahedron_count: self.tetrahedra.len() as u32, + tetrahedron_count: self.geometry.tetrahedron_count() as u32, _padding: [0.0; 2], camera_matrix, camera_eye: eye_3d, -- knotmirror 0.0.1 From 74e64b2a1fa143c04df32b1991a16b892398ed50 Mon Sep 17 00:00:00 2001 From: Willow Sparks Date: Tue, 27 Jan 2026 01:30:34 +0000 Subject: [PATCH 2/3] Simplify README Co-Authored-By: Claude Opus 4.5 --- README.md | 85 +++++++++++++------------------------------------------ 1 file changed, 20 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index a7d939f..810e0cb 100644 --- a/README.md +++ b/README.md @@ -1,84 +1,39 @@ # Rust4D -A 4D rendering engine written in Rust that displays real-time 3D cross-sections of 4D geometry. +A 4D rendering engine in Rust. See real-time 3D cross-sections of 4D geometry. ## What is this? -Rust4D renders four-dimensional objects by slicing them with a 3D hyperplane, similar to how a 2D slice through a 3D object reveals a 2D cross-section. As you move through the fourth dimension (W-axis), you see the 4D shape morph and transform in ways impossible in 3D. +Rust4D slices four-dimensional objects with a 3D hyperplane, like slicing a 3D object reveals a 2D cross-section. Move through the W-axis and watch 4D shapes morph in ways impossible in 3D. -## Inspiration - -This project draws inspiration from: - -- **[4D Golf](https://store.steampowered.com/app/2147950/4D_Golf/)** by CodeParade - A brilliant golf game set in 4D space that pioneered intuitive 4D navigation controls. The camera system in Rust4D directly replicates 4D Golf's approach: standard mouse-look for 3D rotation, right-click drag for W-axis rotation, and Q/E keys for ana/kata movement. - -- **[4D Toys](http://4dtoys.com/)** by Marc ten Bosch - Interactive 4D physics toys that demonstrate how 4D objects behave when projected into 3D. - -- **[Miegakure](https://miegakure.com/)** - A 4D puzzle-platformer that explores 4D space through gameplay. - -- **Geometric Algebra** - The rotation system uses rotors from geometric algebra rather than matrices, providing clean composition of rotations across all 6 rotation planes in 4D. - -## Features - -- Real-time cross-section rendering using GPU compute shaders -- 4D Golf-style camera controls -- W-depth coloring (blue for -W, red for +W) -- Tesseract (4D hypercube) visualization - -## Controls - -| Input | Action | -|-------|--------| -| **WASD** | Move in XZ plane | -| **Q/E** | Move along W-axis (ana/kata) | -| **Space/Shift** | Move up/down | -| **Mouse drag** | Rotate view (3D) | -| **Right-click drag** | Rotate through W-axis | -| **Scroll wheel** | Adjust slice offset | -| **R** | Reset camera | -| **F** | Toggle fullscreen | -| **ESC** | Quit | - -## Building +## Building & Running ```bash -cargo build --release cargo run --release ``` -Requires Rust 1.70+ and a GPU with Vulkan or Metal support. - -## Architecture - -``` -rust4d/ -├── crates/ -│ ├── rust4d_math/ # Vec4, Rotor4 (4D rotation via geometric algebra) -│ ├── rust4d_render/ # wgpu rendering, compute shaders, geometry -│ └── rust4d_input/ # Camera controller -└── src/main.rs # Application -``` - -### How it works +Requires Rust 1.70+ and a GPU with Vulkan/Metal support. -1. **Geometry**: A tesseract is decomposed into 24 five-cells (4D simplices) using Kuhn triangulation -2. **Slicing**: A GPU compute shader intersects each 5-cell with the W=slice_w hyperplane -3. **Rendering**: The resulting 3D triangles are rendered with W-depth coloring to show proximity to the slice plane +## Controls -## The Fourth Dimension +| Input | Action | +|-------|--------| +| WASD | Move in XZ plane | +| Q/E | Move along W-axis | +| Space/Shift | Move up/down | +| Mouse | Look around | +| Right-click drag | Rotate through W | +| Scroll | Adjust slice offset | +| R | Reset camera | +| F | Fullscreen | +| ESC | Release cursor / Quit | -In 4D space, there are 6 rotation planes instead of 3 rotation axes: -- **XY, XZ, YZ** - Standard 3D rotations -- **XW, YW, ZW** - Rotations involving the 4th dimension +## Inspiration -When you rotate in the ZW plane (right-click drag), objects appear to turn "inside out" as parts hidden in the W dimension become visible. +- [4D Golf](https://store.steampowered.com/app/2147950/4D_Golf/) - Camera controls based on this +- [4D Toys](http://4dtoys.com/) - 4D physics visualization +- [Miegakure](https://miegakure.com/) - 4D puzzle platformer ## License MIT - -## References - -- [Visualizing 4D Geometry](https://www.qfbox.info/4d/) - Comprehensive guide to 4D visualization -- [4D Euclidean Space](https://eusebeia.dyndns.org/4d/) - Mathematical foundations -- [Geometric Algebra for Computer Science](http://www.geometricalgebra.net/) - Rotors and multivectors -- knotmirror 0.0.1 From a3361cca886a586afe3eadb21d8d3e144609cb3d Mon Sep 17 00:00:00 2001 From: Willow Sparks Date: Tue, 27 Jan 2026 01:32:06 +0000 Subject: [PATCH 3/3] Add MIT License file Co-Authored-By: Claude Opus 4.5 --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5537cdd --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Willow Sparks + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. -- knotmirror 0.0.1