### Quick Start Example Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-core/README.md Demonstrates basic usage of Point3, Tolerance trait for near comparisons, and BoundingBox creation and diagonal calculation. ```rust use monstertruck_core::{cgmath64::*, tolerance::Tolerance, bounding_box::BoundingBox}; let a = Point3::new(1.0, 2.0, 3.0); let b = Point3::new(1.0 + 1e-7, 2.0, 3.0); assert!(a.near(&b)); // within TOLERANCE (1e-6) let bb: BoundingBox = vec![ Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 2.0, 3.0), ].into_iter().collect(); assert_eq!(bb.diagonal(), Vector3::new(1.0, 2.0, 3.0)); ``` -------------------------------- ### Rust: Quick Start Assembly Example Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-assembly/README.md Demonstrates how to create a new assembly, add nodes and edges with transform values, and then iterate through paths to calculate the accumulated transform. This is useful for setting up hierarchical or sequential assembly structures. ```rust use monstertruck_assembly::assy::*; let mut assy = Assembly::<(), (), f64, ()>::new(); // Create nodes and connect with transform edges let nodes = assy.create_nodes([().into(); 4]); assy.create_edge(nodes[0], nodes[1], 2.0.into()); assy.create_edge(nodes[1], nodes[2], 3.0.into()); assy.create_edge(nodes[2], nodes[3], 5.0.into()); // Walk the path and accumulate transforms let path = assy.maximal_paths_iter(nodes[0]).next().unwrap(); assert_eq!(path.matrix(), 30.0); // 2 * 3 * 5 ``` -------------------------------- ### Quick Start: Initialize Scene and Create Polygon Instance Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-render/README.md Demonstrates the basic setup for monstertruck-render. Use this to initialize the rendering device, create a scene, and add a polygon instance to it. ```rust use monstertruck_gpu::*; use monstertruck_render::*; let handler = pollster::block_on(DeviceHandler::default_device()); let mut scene = Scene::new(handler, &Default::default()); // Create render instances from a mesh let creator = scene.instance_creator(); let instance: PolygonInstance = creator.create_instance( &mesh, &PolygonState { material: Material { albedo: Vector4::new(0.8, 0.2, 0.2, 1.0), roughness: 0.3, ..Default::default() }, ..Default::default() }, ); scene.add_object(&instance); ``` -------------------------------- ### Install wasm-pack and basic-http-server Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-wasm/examples/Readme.md Installs the necessary tools for building and serving the WebAssembly application. ```bash cargo install wasm-pack basic-http-server ``` -------------------------------- ### Quick Start: Initialize Device and Scene Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-gpu/README.md Initializes the default wgpu device handler and creates a new scene with a default camera configuration. This is the starting point for rendering with monstertruck-gpu. ```rust use std::f64::consts::TAU; use monstertruck_core::cgmath64::*; use monstertruck_gpu::*; let handler = pollster::block_on(DeviceHandler::default_device()); let scene = Scene::new(handler, &SceneDescriptor { studio: StudioConfig { camera: Camera { matrix: Matrix4::look_at_rh( Point3::new(1.0, 1.0, 1.0), Point3::origin(), Vector3::unit_y(), ).invert().unwrap(), method: ProjectionMethod::perspective(Rad(TAU / 8.0)), near_clip: 0.1, far_clip: 100.0, }, ..Default::default() }, ..Default::default() }); ``` -------------------------------- ### Run Basic Rotation Example Source: https://github.com/virtualritz/monstertruck/blob/master/README.md Use this command to clone required submodules and run the basic object rotation example using Cargo. ```bash git submodule update --init ``` ```bash cargo run --example rotate-objects ``` -------------------------------- ### Build and Serve Ad-hoc Viewer Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-wasm/examples/Readme.md Builds the WebAssembly project for the web target, copies necessary files to the 'pkg' directory, and starts a local HTTP server to host the application. ```bash wasm-pack build --target web cp examples/bootstrap.js examples/index.html examples/script.js pkg cd pkg basic-http-server -a 127.0.0.1:8080 ``` -------------------------------- ### Preview STEP Face Geometry Source: https://github.com/virtualritz/monstertruck/blob/master/AGENTS.md Use the `preview-step-face` example to render diagnostic images of specific faces from a STEP file. This is useful for debugging meshing or trim path issues when test output is insufficient. ```bash cargo run --example preview-step-face -- resources/step/abc-0008.step \ --face 10 --face 17 --shell 1 --out target/face-previews ``` -------------------------------- ### Geometric Modeling Example: Spheres on Cube Corners Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck/README.md This Rust example demonstrates creating a unit cube, placing spheres on its corners, performing boolean operations (difference and union), and filleting all edges using the monstertruck library. It requires the 'modeling' and 'solid' features. ```rust use monstertruck_modeling::* use monstertruck_solid::{difference, fillet_edges_by_id, or, FilletOptions}; use std::f64::consts::PI; fn sphere(center: Point3, radius: f64) -> Solid { let top = builder::vertex(Point3::new(0.0, radius, 0.0)); let wire: Wire = builder::revolve( &top, Point3::origin(), Vector3::unit_x(), builder::SweepAngle::Partial(Rad(PI)), 3, ); let shell = builder::cone(&wire, Vector3::unit_y(), Rad(7.0), 4); builder::translated(&Solid::new(vec![shell]), center.to_vec()) } fn main() -> anyhow::Result<()> { let tol = 0.01; let r = 1.0 / 3.0; // Unit cube at origin. let v = builder::vertex(Point3::origin()); let cube = builder::extrude( &builder::extrude(&builder::extrude(&v, Vector3::unit_x()), Vector3::unit_y()), Vector3::unit_z(), ); // Tetrahedral group A -- subtract. let subtract = [ Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 1.0, 0.0), Point3::new(1.0, 0.0, 1.0), Point3::new(0.0, 1.0, 1.0), ]; // Tetrahedral group B -- union. let unite = [ Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0), Point3::new(0.0, 0.0, 1.0), Point3::new(1.0, 1.0, 1.0), ]; let mut body = cube; for &c in &subtract { body = difference(&body, &sphere(c, r), tol) .map_err(|e| anyhow::anyhow!("difference failed at {:?}: {}", c, e)?); } for &c in &unite { body = or(&body, &sphere(c, r), tol) .map_err(|e| anyhow::anyhow!("union failed at {:?}: {}", c, e)?); } // Fillet all edges. let mut shell = body.into_boundaries().pop().unwrap(); let edge_ids: Vec<_> = shell .iter() .flat_map(|face| face.edge_iter()) .map(|e| e.id()) .collect(); fillet_edges_by_id(&mut shell, &edge_ids, Some(&FilletOptions::constant(0.05)))?; let result = Solid::new(vec![shell]); std::fs::write("output.json", serde_json::to_vec_pretty(&result)?) Ok(()) } ``` -------------------------------- ### Re-exported Modules Example Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck/README.md Demonstrates how to access modules from enabled features of the monstertruck crate. For example, 'modeling' is available if the 'modeling' feature is enabled. ```rust monstertruck::core // always available monstertruck::modeling // with "modeling" monstertruck::meshing // with "meshing" monstertruck::geometry // with "geometry" // ... etc. ``` -------------------------------- ### Build and Tessellate a Cube Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-meshing/README.md This snippet demonstrates how to build a simple cube using the builder API and then perform triangulation to create a mesh. Ensure you have the necessary prelude and modeling crates imported. ```rust use monstertruck_meshing::prelude::*; use monstertruck_modeling::*; // Build a cube and tessellate it let v = builder::vertex(Point3::origin()); let cube: Solid = builder::extrude( &builder::extrude(&builder::extrude(&v, Vector3::unit_x()), Vector3::unit_y()), Vector3::unit_z(), ); let mesh = cube.triangulation(0.01).to_polygon(); ``` -------------------------------- ### Build a Unit Cube with Monstertruck Modeling Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-modeling/README.md Demonstrates building a unit cube by successively extruding a point, edge, and face using the `monstertruck_modeling` crate. Requires importing the crate and its builder module. ```rust use monstertruck_modeling::* // Build a unit cube by three successive extrusions: point -> edge -> face -> solid let v = builder::vertex(Point3::new(-0.5, -0.5, -0.5)); let e = builder::extrude(&v, Vector3::unit_x()); let f = builder::extrude(&e, Vector3::unit_y()); let cube: Solid = builder::extrude(&f, Vector3::unit_z()); assert_eq!(cube.boundaries()[0].len(), 6) // six faces ``` -------------------------------- ### Deriving Geometric Traits for Enums Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-derive/README.md Use derive macros to delegate trait method implementations to inner types within an enum. This example shows deriving ParametricCurve and BoundedCurve for a custom curve enum. ```rust use monstertruck_traits::prelude::*; /// An enum of curve types -- derive macros delegate trait methods /// to the inner type via match arms. #[derive(Clone, ParametricCurve, BoundedCurve)] pub enum MyCurve { Line(Line), Nurbs(NurbsCurve), } let curve: MyCurve = MyCurve::Line(/* ... */); let pt = curve.evaluate(0.5); // dispatches to Line::evaluate ``` -------------------------------- ### Run All Core Tests Source: https://github.com/virtualritz/monstertruck/blob/master/AGENTS.md Execute all core tests using the `just test-cpu` command. ```bash # Run all core tests just test-cpu ``` -------------------------------- ### Create and Evaluate a B-spline Curve in Rust Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-geometry/README.md Demonstrates how to create a quadratic Bezier curve using BsplineCurve and evaluate points and derivatives along the curve. Ensure to import the necessary prelude. ```rust use monstertruck_geometry::prelude::*; // A quadratic Bezier curve from (0,0,0) through (1,1,0) to (2,0,0) let knot_vec = KnotVector::bezier_knot(2); let ctrl_pts = vec![ Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 1.0, 0.0), Point3::new(2.0, 0.0, 0.0), ]; let curve = BsplineCurve::new(knot_vec, ctrl_pts); let mid = curve.evaluate(0.5); // Point3 at parameter t=0.5 let tan = curve.derivative(0.5); // tangent vector let (t0, t1) = curve.range_tuple(); // (0.0, 1.0) ``` -------------------------------- ### Build Cube with Monstertruck-WASM Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-wasm/README.md Demonstrates building a cube by successive extrusions and tessellating it into a polygon mesh using monstertruck-wasm. Ensure `init()` is awaited before using other functions. ```javascript import init, { vertex, line, extrude } from "monstertruck-wasm"; await init(); // Build a cube by successive extrusions const v = vertex(0, 0, 0); const edge = extrude(v.upcast(), [1, 0, 0]); const face = extrude(edge, [0, 1, 0]); const solid = extrude(face, [0, 0, 1]); // Tessellate and get vertex buffer const mesh = solid.into_solid().to_polygon(0.01); ``` -------------------------------- ### Format Rust Code Source: https://github.com/virtualritz/monstertruck/blob/master/AGENTS.md Format all Rust code in the project using `cargo fmt --all`. ```bash # Format code cargo fmt --all ``` -------------------------------- ### Parse STEP File and Extract Shell Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-step/README.md Loads a STEP file into a Table and extracts a shell, converting it to a compressed shell. Ensure the 'model.step' file exists in the same directory. ```rust use monstertruck_step::load::{*, step_geometry::*}; // Parse a STEP file let step_string = std::fs::read_to_string("model.step").unwrap(); let table = Table::from_step(&step_string).unwrap(); // Extract a shell and convert to topology let step_shell = table.shell.values().next().unwrap(); let compressed = table.to_compressed_shell(step_shell).unwrap(); ``` -------------------------------- ### Create a Basic Polygon Mesh in Rust Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-mesh/README.md Use this snippet to create a simple polygon mesh with positions and faces. Ensure you have the `monstertruck_mesh` crate imported. ```rust use monstertruck_mesh::*; let positions = vec![ Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0), ]; let faces = Faces::from_iter(&[[0, 1, 2]]); let mesh = PolygonMesh::new( StandardAttributes { positions, ..Default::default() }, faces, ); assert_eq!(mesh.positions().len(), 3); assert_eq!(mesh.tri_faces().len(), 1); ``` -------------------------------- ### Run Rust Clippy Linter Source: https://github.com/virtualritz/monstertruck/blob/master/AGENTS.md Run the Clippy linter across all targets and apply warnings using `cargo clippy --all-targets -- -W warnings`. ```bash # Run clippy linter cargo clippy --all-targets -- -W warnings ``` -------------------------------- ### Run Rust Tests Source: https://github.com/virtualritz/monstertruck/blob/master/AGENTS.md Use `cargo test` to run tests for a specific Rust crate. This command also builds the necessary components. ```bash # Run tests (this also builds everything) cargo test -p monstertruck-geometry --lib ``` -------------------------------- ### Run Tests and Clippy Checks Source: https://github.com/virtualritz/monstertruck/blob/master/AGENTS.md Always run `cargo test` and `cargo clippy` with warning checks enabled before committing code. Address all warnings to maintain code quality. ```bash cargo test cargo clippy --all-targets -- -W warnings ``` -------------------------------- ### Compute Union of Two Cubes Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-solid/README.md Demonstrates how to create two overlapping cubes and compute their union using the `or` function. Requires importing `monstertruck_modeling` and `monstertruck_solid::or`. ```rust use monstertruck_modeling::* use monstertruck_solid::or; // Build two overlapping cubes and compute their union let v = builder::vertex(Point3::origin()); let cube_a: Solid = builder::extrude( &builder::extrude(&builder::extrude(&v, Vector3::unit_x()), Vector3::unit_y()), Vector3::unit_z(), ); let cube_b = builder::translated(&cube_a, Vector3::new(0.5, 0.5, 0.0)); let union: Option = or(&cube_a, &cube_b, 0.05); ``` -------------------------------- ### Build a Tetrahedron using Monstertruck Topology Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-topology/README.md This Rust code snippet demonstrates how to construct a tetrahedron using the monstertruck-topology crate. It involves creating vertices, edges, wires, faces, and finally a solid. ```rust monstertruck_topology::prelude!((), (), ()); // Build a tetrahedron from vertices and edges let v = Vertex::from_points(&[(); 4]); let edge = [ Edge::new(&v[0], &v[1], ()), Edge::new(&v[0], &v[2], ()), Edge::new(&v[0], &v[3], ()), Edge::new(&v[1], &v[2], ()), Edge::new(&v[1], &v[3], ()), Edge::new(&v[2], &v[3], ()), ]; let wire = vec![ wire![&edge[0], &edge[3], &edge[1].inverse()], wire![&edge[1], &edge[5], &edge[2].inverse()], wire![&edge[2], &edge[4].inverse(), &edge[0].inverse()], wire![&edge[3], &edge[5], &edge[4].inverse()], ]; let mut face: Vec = wire.into_iter().map(|w| Face::new(vec![w], ())).collect(); face[3].invert(); let solid = Solid::new(vec![face.into()]); ``` -------------------------------- ### Run Specific Rust Test Source: https://github.com/virtualritz/monstertruck/blob/master/AGENTS.md To run a single, specific test within a Rust crate, use `cargo test` with the test name. ```bash # Run a specific test cargo test -p monstertruck-geometry test_name ``` -------------------------------- ### Fragment Shader with Microfacet BRDF Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-wasm/examples/index.html This GLSL fragment shader implements a physically-based rendering model using the microfacet theory. It calculates lighting contributions from diffuse and specular components based on material properties and light sources. ```glsl #version 300 es precision highp float; in vec3 vertex_position; in vec2 vertex_uv; in vec3 vertex_normal; uniform vec3 camera_position; uniform vec3 camera_direction; uniform vec3 camera_updirection; uniform vec2 resolution; out vec4 color; // Based on the microfacet theory // cf: https://qiita.com/mebiusbox2/items/e7063c5dfe1424e0d01a struct Light { vec4 position; vec4 color; ivec4 light_type; }; struct Material { vec4 albedo; float roughness; float reflectance; float ambient_ratio; }; // light direction from point to light vec3 light_direction(Light light, vec3 position) { switch(light.light_type[0]) { case 0: return normalize(light.position.xyz - position); default: return light.position.xyz; } } vec3 irradiance(Light light, vec3 position, vec3 normal) { vec3 light_dir = light_direction(light, position); return light.color.xyz * clamp(dot(light_dir, normal), 0.0, 1.0); } vec3 diffuse_brdf(Material material) { return material.albedo.xyz * (1.0 - material.reflectance); } float microfacet_distribution(vec3 middle, vec3 normal, float alpha) { float dotNH = dot(normal, middle); float alpha2 = alpha * alpha; float sqrt_denom = 1.0 - dotNH * dotNH * (1.0 - alpha2); return alpha2 / (sqrt_denom * sqrt_denom); } float schlick_approxy(vec3 vec, vec3 normal, float k) { float dotNV = dot(normal, vec); return dotNV / (dotNV * (1.0 - k) + k); } float geometric_decay(vec3 light_dir, vec3 camera_dir, vec3 normal, float alpha) { float k = alpha / 2.0; return schlick_approxy(light_dir, normal, k) * schlick_approxy(camera_dir, normal, k); } vec3 fresnel(vec3 f0, vec3 middle, vec3 camera_dir) { float c = 1.0 - dot(middle, camera_dir); c = c * c * c * c * c; return f0 + (1.0 - f0) * c; } vec3 specular_brdf(Material material, vec3 camera_dir, vec3 light_dir, vec3 normal) { vec3 specular_color = material.albedo.xyz * material.reflectance; vec3 middle = normalize(camera_dir + light_dir); float alpha = material.roughness * material.roughness; float distribution = microfacet_distribution(middle, normal, alpha); float decay = geometric_decay(light_dir, camera_dir, normal, alpha); vec3 fresnel_color = fresnel(specular_color, middle, camera_dir); float dotCN = clamp(dot(camera_dir, normal), 0.0, 1.0); float dotLN = clamp(dot(light_dir, normal), 0.0, 1.0); float denom = 4.0 * dotCN * dotLN; if (denom < 1.0e-6) { return vec3(0.0, 0.0, 0.0); } return distribution * decay / denom * fresnel_color; } vec3 microfacet_color(vec3 position, vec3 normal, Light light, vec3 camera_dir, Material material) { vec3 light_dir = light_direction(light, position); vec3 irradiance = irradiance(light, position, normal); vec3 diffuse = diffuse_brdf(material); vec3 specular = specular_brdf(material, camera_dir, light_dir, normal); return (diffuse + specular) * irradiance; } vec3 ambient_correction(vec3 pre_color, Material material) { return pre_color * (1.0 - material.ambient_ratio) + material.albedo.xyz * material.ambient_ratio; } void main() { vec3 position = vertex_position; vec2 uv = vertex_uv; vec3 normal = normalize(vertex_normal); uv.y = 1.0 - uv.y; /* discard by texture */ Material mat; mat.albedo = vec4(1); mat.roughness = 0.5; mat.reflectance = 0.5; mat.ambient_ratio = 0.04; Light light; light.position = vec4(camera_position, 1); light.color = vec4(1); light.light_type = ivec4(0); vec3 camera_dir = normalize(camera_position - position); vec3 col = microfacet_color(position, normal, light, camera_dir, mat); col = ambient_correction(col, mat); color = vec4(col, 1.0); } ``` -------------------------------- ### Adding monstertruck-traits Dependency Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck-derive/README.md To use the derive macros, add the `monstertruck-traits` crate with the `derive` feature enabled to your Cargo.toml. ```toml monstertruck-traits = { version = "0.2", features = ["derive"] } ``` -------------------------------- ### Add Monstertruck Dependency Source: https://github.com/virtualritz/monstertruck/blob/master/monstertruck/README.md Add the Monstertruck crate to your project's dependencies, enabling the 'full' feature for all capabilities. ```toml [dependencies] monstertruck = { version = "0.2", features = ["full"] } ```