Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Parry2d
https://docs.rs/parry2d/latest
Admin
Documentation for the Parry2d library or project, focusing on its features and usage.
Tokens:
674,663
Snippets:
4,443
Trust Score:
9.1
Update:
2 months ago
Context
Chat
Benchmark
87
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Run the oriented polyline example Source: https://docs.rs/parry2d/latest/src/oriented_polyline2d/oriented_polyline2d.rs.html Execute the example using the cargo command. ```bash cargo run -p parry2d --example oriented_polyline2d ``` -------------------------------- ### Calling a documented function in an example Source: https://docs.rs/parry2d/latest/scrape-examples-help.html Example of how to invoke a library function within an external example file. ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Create and Verify a Segment Source: https://docs.rs/parry2d/latest/parry2d/shape/struct.Segment.html Example demonstrating how to instantiate a Segment and verify its properties. ```rust use parry3d::shape::Segment; use parry3d::math::Vector; // Create a horizontal segment of length 5 let a = Vector::ZERO; let b = Vector::new(5.0, 0.0, 0.0); let segment = Segment::new(a, b); assert_eq!(segment.length(), 5.0); assert_eq!(segment.a, a); assert_eq!(segment.b, b); ``` -------------------------------- ### Simple Translation Example Source: https://docs.rs/parry2d/latest/src/parry2d/query/nonlinear_shape_cast/nonlinear_rigid_motion.rs.html Demonstrates creating a motion profile with only linear velocity. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::query::NonlinearRigidMotion; use parry3d::math::{Pose, Vector}; // Object moving right at 5 units/second, no rotation let motion = NonlinearRigidMotion::new( Pose::translation(0.0, 0.0, 0.0), // start at origin Vector::ZERO, // rotation center (irrelevant here) Vector::new(5.0, 0.0, 0.0), // moving right Vector::ZERO, // not rotating ); // At t=2.0 seconds, object has moved 10 units right let pos_at_2 = motion.position_at_time(2.0); assert_eq!(pos_at_2.translation.x, 10.0); # } ``` -------------------------------- ### BVH Node Access Example Source: https://docs.rs/parry2d/latest/src/parry2d/partitioning/bvh/bvh_tree.rs.html Shows how to initialize a BVH from leaves and verify the leaf count. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::partitioning::{Bvh, BvhBuildStrategy}; use parry3d::bounding_volume::Aabb; use parry3d::math::Vector; let aabbs = vec![ Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)), Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)), Aabb::new(Vector::new(4.0, 0.0, 0.0), Vector::new(5.0, 1.0, 1.0)), ]; let bvh = Bvh::from_leaves(BvhBuildStrategy::default(), &aabbs); // Access the root node's children // The BVH stores nodes as BvhNodeWide pairs internally assert_eq!(bvh.leaf_count(), 3); # } ``` -------------------------------- ### Pure Rotation Example (3D) Source: https://docs.rs/parry2d/latest/src/parry2d/query/nonlinear_shape_cast/nonlinear_rigid_motion.rs.html Demonstrates creating a motion profile with only angular velocity. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::query::NonlinearRigidMotion; use parry3d::math::{Pose, Vector}; use std::f32::consts::PI; // Object spinning around Y axis, no translation let motion = NonlinearRigidMotion::new( Pose::translation(0.0, 0.0, 0.0), Vector::ZERO, // rotate around origin Vector::ZERO, // not translating Vector::new(0.0, PI, 0.0), // rotating around Y at π rad/s (180°/s) ); // At t=1.0 second, object has rotated 180 degrees let pos_at_1 = motion.position_at_time(1.0); // Object is now rotated 180° around Y axis # } ``` -------------------------------- ### Volume Computation Example Source: https://docs.rs/parry2d/latest/src/parry2d/transformation/voxelization/voxel_set.rs.html Shows how to voxelize a ball with interior filling and compute its approximate volume. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::transformation::voxelization::{FillMode, VoxelSet}; use parry3d::shape::Ball; /// let ball = Ball::new(1.0); let (vertices, indices) = ball.to_trimesh(20, 20); // Voxelize with interior filling let voxels = VoxelSet::voxelize( &vertices, &indices, 20, FillMode::FloodFill { detect_cavities: false }, false, ); // Compute approximate volume let voxel_volume = voxels.compute_volume(); let expected_volume = 4.0 / 3.0 * std::f32::consts::PI; println!("Voxel volume: {:.3}, Expected: {:.3}", voxel_volume, expected_volume); # } ``` -------------------------------- ### Usage examples for for_each_dim! Source: https://docs.rs/parry2d/latest/src/parry2d/macros.rs.html Demonstrates basic usage and usage with a dimension index constant. ```rust for_each_dim! { min[ii] = a[ii].min(b[ii]); } // Expands to: // min.x = a.x.min(b.x); // min.y = a.y.min(b.y); // min.z = a.z.min(b.z); // only in 3D ``` ```rust for_each_dim! { i => if mask & (1 << i) != 0 { result[ii] = -result[ii]; } } ``` -------------------------------- ### Basic Ball instantiation Source: https://docs.rs/parry2d/latest/parry2d/shape/struct.Ball.html A simple example of creating a ball and verifying its radius. ```rust 3fn main() { 4 let ball = Ball::new(1.0); 5 assert!(ball.radius == 1.0); 6} ``` -------------------------------- ### Construct a TriMesh Source: https://docs.rs/parry2d/latest/parry2d/shape/struct.TriMesh.html Examples of creating a TriMesh in 3D and 2D environments. ```rust use parry3d::shape::TriMesh; use parry3d::math::Vector; // Create a simple triangle mesh (a single triangle) let vertices = vec![ Vector::ZERO, Vector::new(1.0, 0.0, 0.0), Vector::new(0.0, 1.0, 0.0), ]; let indices = vec![[0, 1, 2]]; let trimesh = TriMesh::new(vertices, indices).expect("Invalid mesh"); assert_eq!(trimesh.num_triangles(), 1); ``` ```rust use parry2d::shape::TriMesh; use parry2d::math::Vector; // Create a quad (two triangles) in 2D let vertices = vec![ Vector::ZERO, // bottom-left Vector::new(1.0, 0.0), // bottom-right Vector::new(1.0, 1.0), // top-right Vector::new(0.0, 1.0), // top-left ]; let indices = vec![ [0, 1, 2], // first triangle [0, 2, 3], // second triangle ]; let quad = TriMesh::new(vertices, indices).unwrap(); assert_eq!(quad.num_triangles(), 2); assert_eq!(quad.vertices().len(), 4); ``` -------------------------------- ### Usage Example Source: https://docs.rs/parry2d/latest/parry2d/query/sat/fn.triangle_support_map_find_local_separating_normal_oneway.html Demonstrates how to use the function to find the separation between a triangle and a ball. ```rust use parry2d::shape::{Triangle, Ball}; use parry2d::query::sat::triangle_support_map_find_local_separating_normal_oneway; use parry2d::math::{Vector, Pose}; let triangle = Triangle::new( Vector::ZERO, Vector::new(2.0, 0.0), Vector::new(1.0, 2.0) ); let sphere = Ball::new(0.5); let pos12 = Pose::translation(3.0, 1.0); let (separation, normal) = triangle_support_map_find_local_separating_normal_oneway( &triangle, &sphere, &pos12 ); if separation > 0.0 { println!("Separated by {} along edge normal {}", separation, normal); } ``` -------------------------------- ### Usage Example Source: https://docs.rs/parry2d/latest/parry2d/query/sat/fn.cuboid_support_map_find_local_separating_normal_oneway.html Demonstrates how to use the function to find the separation between a cuboid and a ball. ```rust use parry2d::shape::{Cuboid, Ball}; use parry2d::query::sat::cuboid_support_map_find_local_separating_normal_oneway; use parry2d::math::{Pose, Vector}; let cube = Cuboid::new(Vector::new(1.0, 1.0)); let sphere = Ball::new(0.5); // Position sphere to the right of the cube let pos12 = Pose::translation(2.0, 0.0); let (separation, normal) = cuboid_support_map_find_local_separating_normal_oneway( &cube, &sphere, &pos12 ); if separation > 0.0 { println!("Shapes separated by {} along normal {}", separation, normal); } else { println!("Shapes overlapping by {} along normal {}", -separation, normal); } ``` -------------------------------- ### Ray Casting Example Source: https://docs.rs/parry2d/latest/parry2d/query/details/struct.Ray.html Demonstrates creating a ray and casting it against a ball shape to determine the time-of-impact. ```rust use parry3d::query::{Ray, RayCast}; use parry3d::shape::Ball; use parry3d::math::{Vector, Pose}; // Create a ray from origin pointing along +X axis let ray = Ray::new( Vector::ZERO, Vector::new(1.0, 0.0, 0.0) // Normalized direction ); // Create a ball at position (5, 0, 0) with radius 1 let ball = Ball::new(1.0); let ball_pos = Pose::translation(5.0, 0.0, 0.0); // Cast the ray against the ball if let Some(toi) = ball.cast_ray(&ball_pos, &ray, 100.0, true) { // Ray hits at t=4.0 (center at 5.0 minus radius 1.0) assert_eq!(toi, 4.0); // Compute the actual hit point let hit_point = ray.point_at(toi); assert_eq!(hit_point, Vector::new(4.0, 0.0, 0.0)); } ``` -------------------------------- ### Initialize a 2D Cuboid Source: https://docs.rs/parry2d/latest/parry2d/math/struct.Vec2.html Example of creating a Cuboid structure with specific half-extents. ```rust fn main() { let cuboid = Cuboid::new(Vector::new(2.0, 1.0)); assert!(cuboid.half_extents.x == 2.0); assert!(cuboid.half_extents.y == 1.0); } ``` -------------------------------- ### World-Space Support Point with Rotation Source: https://docs.rs/parry2d/latest/src/parry2d/shape/support_map.rs.html Example demonstrating the use of the support_point method with a rotated cuboid. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::shape::{Cuboid, SupportMap}; ``` -------------------------------- ### Voxelization and Conversion Source: https://docs.rs/parry2d/latest/parry2d/transformation/voxelization/struct.VoxelizedVolume.html Example showing how to create a dense VoxelizedVolume from a mesh and convert it into a sparse VoxelSet. ```rust use parry3d::transformation::voxelization::{FillMode, VoxelSet, VoxelizedVolume}; use parry3d::shape::Ball; /// let ball = Ball::new(1.0); let (vertices, indices) = ball.to_trimesh(10, 10); // Create dense volume let volume = VoxelizedVolume::voxelize( &vertices, &indices, 10, FillMode::SurfaceOnly, false, ); // Convert to sparse set (automatic via Into trait) let voxel_set: VoxelSet = volume.into(); ``` -------------------------------- ### PointQuery Trait Usage Source: https://docs.rs/parry2d/latest/src/parry2d/query/point/point_query.rs.html Example setup for using the PointQuery trait with a Cuboid shape. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::query::PointQuery; use parry3d::shape::Cuboid; use parry3d::math::{Vector, Pose}; ``` -------------------------------- ### Create and Configure Capsules Source: https://docs.rs/parry2d/latest/parry2d/shape/struct.Capsule.html Examples demonstrating how to initialize capsules using different constructors and verify their dimensions. ```rust use parry3d::shape::Capsule; use parry3d::math::Vector; // Create a vertical capsule (aligned with Y axis) // Half-height of 2.0 means the segment is 4.0 units long let capsule = Capsule::new_y(2.0, 0.5); assert_eq!(capsule.radius, 0.5); assert_eq!(capsule.height(), 4.0); // Create a custom capsule between two points let a = Vector::ZERO; let b = Vector::new(3.0, 4.0, 0.0); let custom = Capsule::new(a, b, 1.0); assert_eq!(custom.height(), 5.0); // Distance from a to b ``` ```rust use parry3d::shape::Capsule; // Create a capsule extending 6 units along X axis (3 units in each direction) // with radius 0.5 let capsule = Capsule::new_x(3.0, 0.5); assert_eq!(capsule.height(), 6.0); assert_eq!(capsule.radius, 0.5); // The center is at the origin let center = capsule.center(); assert!(center.length() < 1e-6); ``` ```rust use parry3d::shape::Capsule; // Create a typical character capsule: 2 units tall with 0.3 radius let character = Capsule::new_y(1.0, 0.3); assert_eq!(character.height(), 2.0); assert_eq!(character.radius, 0.3); // Total height including the spherical caps: 2.0 + 2 * 0.3 = 2.6 ``` ```rust use parry3d::shape::Capsule; use parry3d::math::Vector; // Create a diagonal capsule let a = Vector::ZERO; let b = Vector::new(3.0, 4.0, 0.0); let capsule = Capsule::new(a, b, 0.5); // Height is the distance between a and b assert_eq!(capsule.height(), 5.0); // 3-4-5 triangle // Center is the midpoint let center = capsule.center(); assert_eq!(center, Vector::new(1.5, 2.0, 0.0)); ``` -------------------------------- ### Perform Shape Casting with cast_shapes Source: https://docs.rs/parry2d/latest/src/parry2d/query/shape_cast/shape_cast.rs.html Demonstrates how to use cast_shapes to detect collisions between two moving balls. The example handles the case where shapes are already overlapping at the start. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::query::{cast_shapes, ShapeCastOptions, ShapeCastStatus}; use parry3d::shape::Ball; use parry3d::math::{Pose, Vector}; let ball1 = Ball::new(2.0); let ball2 = Ball::new(2.0); // Overlapping balls (centers 3 units apart, radii sum to 4) let pos1 = Pose::translation(0.0, 0.0, 0.0); let pos2 = Pose::translation(3.0, 0.0, 0.0); let vel1 = Vector::X; let vel2 = Vector::ZERO; let options = ShapeCastOptions::default(); if let Ok(Some(hit)) = cast_shapes(&pos1, vel1, &ball1, &pos2, vel2, &ball2, options) { // Already penetrating assert_eq!(hit.time_of_impact, 0.0); assert_eq!(hit.status, ShapeCastStatus::PenetratingOrWithinTargetDist); } # } ``` -------------------------------- ### Performing EPA penetration queries Source: https://docs.rs/parry2d/latest/parry2d/query/epa/index.html Demonstrates the setup for an EPA query using a GJK-derived simplex. Note that the example uses parry3d imports as provided in the source documentation. ```rust use parry3d::query::epa::EPA; use parry3d::query::gjk::VoronoiSimplex; use parry3d::shape::Ball; use parry3d::math::Pose; let ball1 = Ball::new(1.0); let ball2 = Ball::new(1.0); let pos12 = Pose::translation(1.5, 0.0, 0.0); // Overlapping balls // GJK detects penetration, EPA computes contact details let simplex = VoronoiSimplex::new(); // Would be filled by GJK let mut epa = EPA::new(); // If GJK detected penetration, EPA can compute: // - Contact points on each shape // - Penetration depth // - Contact normal // if let Some((pt1, pt2, normal)) = epa.closest_points(&pos12, &ball1, &ball2, &simplex) { // println!("Contact normal: {}", normal); // } ``` -------------------------------- ### PointProjection::new Source: https://docs.rs/parry2d/latest/parry2d/query/point/struct.PointProjection.html Initializes a new PointProjection instance. ```APIDOC ## pub fn new(is_inside: bool, point: Vector) -> Self ### Description Initializes a new `PointProjection` with the specified interior status and closest surface point. ### Parameters - **is_inside** (bool) - Required - Whether the query point is inside the shape. - **point** (Vector) - Required - The closest point on the shape's surface. ``` -------------------------------- ### Create a HalfSpace instance Source: https://docs.rs/parry2d/latest/parry2d/shape/struct.HalfSpace.html Examples demonstrating how to initialize a HalfSpace with different normal vectors in 2D and 3D contexts. ```rust use parry3d::shape::HalfSpace; use parry3d::math::{Vector}; // Ground plane with normal pointing up let ground = HalfSpace::new((Vector::Y.normalize())); ``` ```rust use parry2d::shape::HalfSpace; use parry2d::math::Vector; // Wall with normal pointing to the right let wall = HalfSpace::new(Vector::X.normalize()); ``` ```rust use parry3d::shape::HalfSpace; use parry3d::math::{Vector}; // Plane with normal at 45-degree angle let custom_normal = Vector::new(1.0, 1.0, 0.0); let plane = HalfSpace::new((custom_normal).normalize()); // Verify the normal is normalized assert!((plane.normal.length() - 1.0).abs() < 1e-5); ``` ```rust fn main() { let halfspace = HalfSpace::new(Vector::Y); assert!(halfspace.normal.x == 0.0); assert!(halfspace.normal.y == 1.0); } ``` -------------------------------- ### VecMap IntoIterator example Source: https://docs.rs/parry2d/latest/src/parry2d/utils/vec_map.rs.html Example usage of IntoIterator for VecMap. ```rust use parry::utils::VecMap; let mut map = VecMap::new(); map.insert(1, "a"); map.insert(3, "c"); map.insert(2, "b"); ``` -------------------------------- ### Intersecting Shapes Example Source: https://docs.rs/parry2d/latest/src/parry2d/query/closest_points/closest_points_shape_shape.rs.html Example demonstrating the detection of intersecting shapes. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::query::{closest_points, ClosestPoints}; use parry3d::shape::Cuboid; use parry3d::math::{Pose, Vector}; ``` -------------------------------- ### Initialize and query BoundingSphere properties Source: https://docs.rs/parry2d/latest/parry2d/bounding_volume/struct.BoundingSphere.html Demonstrates creating a BoundingSphere and verifying its center, radius, and point containment. ```rust use parry3d::bounding_volume::BoundingSphere; use parry3d::math::Vector; // Create a bounding sphere with center at origin and radius 2.0 let sphere = BoundingSphere::new(Vector::ZERO, 2.0); // Check basic properties assert_eq!(sphere.center(), Vector::ZERO); assert_eq!(sphere.radius(), 2.0); // Test if a point is within the sphere let point = Vector::new(1.0, 1.0, 0.0); let distance = (point - sphere.center()).length(); assert!(distance <= sphere.radius()); ``` -------------------------------- ### Point in Polygon Usage Examples Source: https://docs.rs/parry2d/latest/src/parry2d/utils/point_in_poly2d.rs.html Examples demonstrating how to check if points are inside complex, self-intersecting, or empty polygons. ```rust let inside_corner = Vector::new(0.5, 0.5); let outside_corner = Vector::new(1.5, 1.5); assert!(point_in_poly2d(inside_corner, &l_shape)); assert!(!point_in_poly2d(outside_corner, &l_shape)); ``` ```rust # #[cfg(all(feature = "dim2", feature = "f32"))] { use parry2d::utils::point_in_poly2d; use parry2d::math::Vector; // A star shape (self-intersecting creates a complex winding pattern) let star = vec![ Vector::new(0.0, 1.0), Vector::new(0.5, 0.5), Vector::new(1.0, 1.0), Vector::new(0.7, 0.3), Vector::new(1.0, -0.5), Vector::ZERO, Vector::new(-1.0, -0.5), Vector::new(-0.7, 0.3), Vector::new(-1.0, 1.0), Vector::new(-0.5, 0.5), ]; let center = Vector::new(0.0, 0.5); assert!(point_in_poly2d(center, &star)); # } ``` ```rust # #[cfg(all(feature = "dim2", feature = "f32"))] { use parry2d::utils::point_in_poly2d; use parry2d::math::Vector; let empty: Vec<Vector> = vec![]; let point = Vector::new(1.0, 1.0); // An empty polygon contains no points assert!(!point_in_poly2d(point, &empty)); # } ``` -------------------------------- ### Configure Construction Strategies Source: https://docs.rs/parry2d/latest/src/parry2d/partitioning/bvh/bvh_tree.rs.html Select different build strategies to balance tree construction time against query performance. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::partitioning::{Bvh, BvhBuildStrategy}; use parry3d::bounding_volume::Aabb; use parry3d::math::Vector; # } ``` -------------------------------- ### Example usage of closest_points Source: https://docs.rs/parry2d/latest/src/parry2d/query/epa/epa2.rs.html Example snippet showing how to retrieve penetration depth and contact normal from the closest_points method. ```rust // if let Some((pt1, pt2, normal)) = epa.closest_points(&pos12, &ball1, &ball2, &simplex) { // println!("Penetration depth: {}", (pt2 - pt1).length()); // println!("Contact normal: {}", normal); // } ``` -------------------------------- ### get Source: https://docs.rs/parry2d/latest/parry2d/utils/hashmap/type.HashMap.html Returns a reference to the value corresponding to the key. ```APIDOC ## pub fn get<Q>(&self, k: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type. ``` -------------------------------- ### HashSet Initialization and Configuration Source: https://docs.rs/parry2d/latest/parry2d/utils/hashset/type.HashSet.html Methods for creating new HashSet instances with specific hashers and allocators, and retrieving configuration details. ```APIDOC ## pub fn allocator(&self) -> &A ### Description Returns a reference to the underlying allocator used by the HashSet. ## pub const fn with_hasher_in(hasher: S, alloc: A) -> HashSet<T, S, A> ### Description Creates a new empty hash set which will use the given hasher to hash keys. The set is initially created with a capacity of 0. ## pub fn with_capacity_and_hasher_in(capacity: usize, hasher: S, alloc: A) -> HashSet<T, S, A> ### Description Creates an empty HashSet with the specified capacity, using the provided hasher to hash keys. ## pub fn hasher(&self) -> &S ### Description Returns a reference to the set’s BuildHasher. ``` -------------------------------- ### get Source: https://docs.rs/parry2d/latest/parry2d/utils/hashset/enum.Entry.html Returns a reference to this entry’s value. ```APIDOC ## pub fn get(&self) -> &T ### Description Returns a reference to this entry’s value. ### Signature `pub fn get(&self) -> &T` ``` -------------------------------- ### Iterating over a HashSet Source: https://docs.rs/parry2d/latest/parry2d/utils/hashset/type.HashSet.html Example of iterating over a HashSet using a loop. ```rust let mut i = 0; let expected = [1, 2, 4, 5]; for x in &a { assert!(expected.contains(x)); i += 1; } assert_eq!(i, expected.len()); ``` -------------------------------- ### Configure VHACD Parameters Source: https://docs.rs/parry2d/latest/src/parry2d/transformation/vhacd/mod.rs.html Demonstrates how to set up VHACDParameters to control the quality and granularity of the decomposition process. ```rust // Configure parameters for higher quality decomposition let params = VHACDParameters { resolution: 128, // Higher = more detail (but slower) concavity: 0.001, // Lower = more parts but better fit max_convex_hulls: 32, // Maximum number of convex parts plane_downsampling: 4, // Precision of plane search convex_hull_downsampling: 4, // Precision of convex hull generation alpha: 0.05, // Bias toward symmetrical splits beta: 0.05, // Bias toward revolution axis splits convex_hull_approximation: true, // Approximate for speed fill_mode: FillMode::FloodFill { detect_cavities: false, }, }; let decomposition = VHACD::decompose(¶ms, &vertices, &indices, false); ``` -------------------------------- ### Initialize Sparse Voxel Grid Source: https://docs.rs/parry2d/latest/parry2d/mass_properties/struct.MassProperties.html Setup for a large sparse voxel grid using 0.1m voxels. ```rust use parry3d::mass_properties::MassProperties; use parry3d::shape::Voxels; use parry3d::math::{Vector, IVector}; // Large sparse grid (only stores filled voxels since v0.25.0) let voxel_size = Vector::new(0.1, 0.1, 0.1); ``` -------------------------------- ### Configure Bvh Construction Strategies Source: https://docs.rs/parry2d/latest/parry2d/partitioning/struct.Bvh.html Shows how to choose between Binned and Ploc strategies to balance build time and query performance. ```rust use parry3d::partitioning::{Bvh, BvhBuildStrategy}; use parry3d::bounding_volume::Aabb; use parry3d::math::Vector; let aabbs = vec![ Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)), Aabb::new(Vector::new(2.0, 0.0, 0.0), Vector::new(3.0, 1.0, 1.0)), ]; // Binned strategy: Fast construction, good quality (recommended default) let bvh_binned = Bvh::from_leaves(BvhBuildStrategy::Binned, &aabbs); // PLOC strategy: Slower construction, best quality for ray-casting // Use this for static scenes with heavy query workloads let bvh_ploc = Bvh::from_leaves(BvhBuildStrategy::Ploc, &aabbs); ``` -------------------------------- ### Handling TopologyError Source: https://docs.rs/parry2d/latest/parry2d/shape/enum.TriMeshBuilderError.html Example of catching a TopologyError when using TriMeshFlags::HALF_EDGE_TOPOLOGY. ```rust let vertices = vec![ Vector::ZERO, Vector::new(1.0, 0.0, 0.0), Vector::new(0.0, 1.0, 0.0), ]; // Triangle with duplicate vertices let bad_indices = vec![[0, 0, 1]]; match TriMesh::with_flags(vertices, bad_indices, TriMeshFlags::HALF_EDGE_TOPOLOGY) { Err(TriMeshBuilderError::TopologyError(topo_err)) => { println!("Topology error: {}", topo_err); // Handle the specific topology issue } _ => {} } ``` -------------------------------- ### Create a Convex Polygon Source: https://docs.rs/parry2d/latest/parry2d/math/struct.Vec2.html Example of creating a ConvexPolygon from a list of points. ```rust fn main() { let points = vec![ Vector::new(-1.0, 1.0), Vector::new(-0.5, -0.5), Vector::new(0.5, -0.5), Vector::new(1.0, 1.0), ]; let convex = ConvexPolygon::from_convex_polyline(points).expect("Invalid convex polygon."); assert!(convex.points().len() == 4); } ``` -------------------------------- ### get_disjoint_mut Source: https://docs.rs/parry2d/latest/parry2d/utils/hashmap/type.HashMap.html Attempts to get mutable references to N values in the map at once. ```APIDOC ## pub fn get_disjoint_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] ### Description Attempts to get mutable references to N values in the map at once. Returns an array of length N with the results of each query. ``` -------------------------------- ### get Source: https://docs.rs/parry2d/latest/parry2d/utils/hashset/type.HashSet.html Returns a reference to the value in the set, if any, that is equal to the given value. ```APIDOC ## pub fn get<Q>(&self, value: &Q) -> Option<&T> ### Description Returns a reference to the value in the set, if any, that is equal to the given value. ``` -------------------------------- ### from_rotation_arc_colinear Source: https://docs.rs/parry2d/latest/parry2d/math/type.Rot3.html Gets the minimal rotation for transforming a vector to be colinear with another. ```APIDOC ## pub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Quat ### Description Gets the minimal rotation for transforming `from` to either `to` or `-to`. The resulting quaternion will rotate `from` so that it is colinear with `to`. ### Parameters - **from** (Vec3) - Required - Unit vector to rotate from. - **to** (Vec3) - Required - Unit vector to rotate to. ### Panics Will panic if `from` or `to` are not normalized when `glam_assert` is enabled. ``` -------------------------------- ### Leaf Node Creation Example Source: https://docs.rs/parry2d/latest/src/parry2d/partitioning/bvh/bvh_tree.rs.html Demonstrates how to instantiate a leaf node with an AABB and associated user data. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::partitioning::BvhNode; use parry3d::bounding_volume::Aabb; use parry3d::math::Vector; // Create a leaf node let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)); let leaf = BvhNode::leaf(aabb, 42); assert!(leaf.is_leaf()); assert_eq!(leaf.leaf_data(), Some(42)); assert_eq!(leaf.aabb(), aabb); # } ``` ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::partitioning::BvhNode; use parry3d::bounding_volume::Aabb; use parry3d::math::Vector; // Create an AABB for a unit cube let aabb = Aabb::new(Vector::ZERO, Vector::new(1.0, 1.0, 1.0)); // Create a leaf node with index 0 let leaf = BvhNode::leaf(aabb, 0); assert!(leaf.is_leaf()); assert_eq!(leaf.leaf_data(), Some(0)); assert_eq!(leaf.aabb(), aabb); # } ``` -------------------------------- ### Voxelized Volume Query Example Source: https://docs.rs/parry2d/latest/src/parry2d/transformation/voxelization/voxelized_volume.rs.html Demonstrates how to voxelize a cuboid and iterate through the resulting volume to check individual voxel states. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::transformation::voxelization::{FillMode, VoxelValue, VoxelizedVolume}; use parry3d::shape::Cuboid; use parry3d::math::Vector; let cuboid = Cuboid::new(Vector::new(1.0, 1.0, 1.0)); let (vertices, indices) = cuboid.to_trimesh(); // Create a dense voxelized volume let volume = VoxelizedVolume::voxelize( &vertices, &indices, 8, FillMode::FloodFill { detect_cavities: false }, false, ); // Query individual voxel values let resolution = volume.resolution(); for i in 0..resolution[0] { for j in 0..resolution[1] { for k in 0..resolution[2] { match volume.voxel(i, j, k) { VoxelValue::PrimitiveOnSurface => { // This voxel is on the boundary } VoxelValue::PrimitiveInsideSurface => { // This voxel is inside the shape } VoxelValue::PrimitiveOutsideSurface => { // This voxel is outside the shape } _ => { ``` -------------------------------- ### Compute TriMesh AABB Source: https://docs.rs/parry2d/latest/src/parry2d/shape/trimesh.rs.html Example of calculating the axis-aligned bounding box for a TriMesh. ```rust use parry3d::shape::TriMesh; use parry3d::math::{Vector, Pose}; let vertices = vec![ Vector::ZERO, Vector::new(1.0, 0.0, 0.0), Vector::new(0.0, 1.0, 0.0), ]; ``` -------------------------------- ### Point Query Operations Example Source: https://docs.rs/parry2d/latest/src/parry2d/query/point/point_query.rs.html Demonstrates basic point projection, distance calculation, and containment testing for a cuboid shape. ```rust let cuboid = Cuboid::new(Vector::splat(1.0)); let cuboid_pos = Pose::translation(5.0, 0.0, 0.0); let query_point = Vector::ZERO; // Project point onto cuboid surface let projection = cuboid.project_point(&cuboid_pos, query_point, true); println!("Closest point on cuboid: {:?}", projection.point); println!("Is inside: {}", projection.is_inside); // Calculate distance to cuboid let distance = cuboid.distance_to_point(&cuboid_pos, query_point, true); println!("Distance: {}", distance); // Test if point is inside cuboid let is_inside = cuboid.contains_point(&cuboid_pos, query_point); println!("Contains: {}", is_inside); ``` -------------------------------- ### Configure Custom VHACD Parameters Source: https://docs.rs/parry2d/latest/src/parry2d/transformation/vhacd/vhacd.rs.html Shows how to initialize the decomposition process with custom settings for higher quality results. ```rust use parry3d::math::Vector; use parry3d::transformation::vhacd::{VHACD, VHACDParameters}; // High-quality decomposition settings let params = VHACDParameters { ``` -------------------------------- ### Example Usage of project_origin Source: https://docs.rs/parry2d/latest/parry2d/query/gjk/fn.project_origin.html Demonstrates projecting the origin onto a Ball shape using a reusable VoronoiSimplex. ```rust use parry3d::shape::Ball; use parry3d::query::gjk::{project_origin, VoronoiSimplex}; use parry3d::math::Pose; // Create a ball at position (5, 0, 0) let ball = Ball::new(1.0); let position = Pose::translation(5.0, 0.0, 0.0); // Project the origin onto the ball let mut simplex = VoronoiSimplex::new(); if let Some(closest_point) = project_origin(&position, &ball, &mut simplex) { println!("Closest point on ball: {:?}", closest_point); // The point will be approximately (-1, 0, 0) in local space // which is the left side of the ball facing the origin } ``` -------------------------------- ### Scale a HalfSpace Source: https://docs.rs/parry2d/latest/parry2d/shape/struct.HalfSpace.html Examples showing how to apply scaling to a HalfSpace, including uniform, non-uniform, and degenerate cases. ```rust use parry3d::shape::HalfSpace; use parry3d::math::{Vector}; let ground = HalfSpace::new(Vector::Y.normalize()); // Uniform scaling doesn't change the normal direction let scaled = ground.scaled(Vector::splat(2.0)).unwrap(); assert_eq!(scaled.normal, Vector::Y); ``` ```rust use parry3d::shape::HalfSpace; use parry3d::math::{Vector}; // Diagonal plane let plane = HalfSpace::new( (Vector::new(1.0, 1.0, 0.0).normalize()) ); // Scale X-axis by 2.0, Y-axis stays 1.0 let scaled = plane.scaled(Vector::new(2.0, 1.0, 1.0)).unwrap(); // The normal changes direction due to non-uniform scaling // It's no longer at 45 degrees assert!(scaled.normal.x != scaled.normal.y); ``` ```rust use parry3d::shape::HalfSpace; use parry3d::math::{Vector}; // Horizontal ground plane let ground = HalfSpace::new((Vector::Y.normalize())); // Scaling Y to zero makes the normal degenerate let scaled = ground.scaled(Vector::new(1.0, 0.0, 1.0)); assert!(scaled.is_none()); // Returns None because normal becomes zero ``` ```rust use parry2d::shape::HalfSpace; use parry2d::math::Vector; // Create a wall in a 2D platformer let wall = HalfSpace::new(Vector::X.normalize()); // Apply level scaling (e.g., for pixel-perfect rendering) let pixel_scale = Vector::new(16.0, 16.0); if let Some(scaled_wall) = wall.scaled(pixel_scale) { // Use the scaled wall for collision detection } ``` -------------------------------- ### Calculate Mass from File Source: https://docs.rs/parry2d/latest/parry2d/mass_properties/struct.MassProperties.html Example of printing the mass of a model loaded from a file. ```rust println!("Model mass: {:.2} kg", props.mass()); ``` -------------------------------- ### Calculate Mass from Voxels Source: https://docs.rs/parry2d/latest/parry2d/mass_properties/struct.MassProperties.html Demonstrates how to initialize a voxel grid and compute mass properties using a specified density. ```rust // Scatter some voxels in a large space (efficient with sparse storage) let voxels = &[ IVector::new(0, 0, 0), IVector::new(100, 50, 75), IVector::new(-50, 200, -30), ]; let voxels = Voxels::new(voxel_size, voxels); let density = 1000.0; let props = MassProperties::from_voxels(density, &voxels); // Only 3 voxels contribute to mass println!("Sparse voxel mass: {:.4} kg", props.mass()); ``` -------------------------------- ### Create a TriMesh with Half-Edge Topology Source: https://docs.rs/parry2d/latest/src/parry2d/shape/trimesh.rs.html Demonstrates initializing a mesh with the HALF_EDGE_TOPOLOGY flag enabled to access topology information. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::shape::{TriMesh, TriMeshFlags}; use parry3d::math::Vector; // Create vertices for a simple mesh let vertices = vec![ Vector::ZERO, Vector::new(1.0, 0.0, 0.0), Vector::new(0.0, 1.0, 0.0), Vector::new(1.0, 1.0, 0.0), ]; let indices = vec![[0, 1, 2], [1, 3, 2]]; // Create a mesh with half-edge topology let flags = TriMeshFlags::HALF_EDGE_TOPOLOGY; let mesh = TriMesh::with_flags(vertices.clone(), indices.clone(), flags) .expect("Failed to create mesh"); // The topology information is now available assert!(mesh.topology().is_some()); # } ``` -------------------------------- ### Get Bounding Sphere Source: https://docs.rs/parry2d/latest/src/parry2d/bounding_volume/aabb.rs.html Computes the smallest bounding sphere that contains the AABB. ```rust /// The smallest bounding sphere containing this `Aabb`. #[inline] pub fn bounding_sphere(&self) -> BoundingSphere { let center = self.center(); let radius = self.mins.distance(self.maxs) * 0.5; BoundingSphere::new(center, radius) } ``` -------------------------------- ### Using the Default Dispatcher Source: https://docs.rs/parry2d/latest/src/parry2d/query/query_dispatcher.rs.html Example demonstrating how to use the DefaultQueryDispatcher to perform an intersection test between a Ball and a Cuboid. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::query::{QueryDispatcher, DefaultQueryDispatcher}; use parry3d::shape::{Ball, Cuboid}; use parry3d::math::{Pose, Vector}; let dispatcher = DefaultQueryDispatcher; let ball = Ball::new(1.0); let cuboid = Cuboid::new(Vector::splat(2.0)); let pos1 = Pose::identity(); let pos2 = Pose::translation(5.0, 0.0, 0.0); let pos12 = pos1.inv_mul(&pos2); // Test intersection ``` -------------------------------- ### Retrieve value from HashSet Source: https://docs.rs/parry2d/latest/parry2d/utils/hashset/type.HashSet.html Demonstrates getting a reference to a value if it exists in the set. ```rust use hashbrown::HashSet; let set: HashSet<_> = [1, 2, 3].into_iter().collect(); assert_eq!(set.get(&2), Some(&2)); assert_eq!(set.get(&4), None); ``` -------------------------------- ### Initializing BVH with change detection margin Source: https://docs.rs/parry2d/latest/src/parry2d/partitioning/bvh/bvh_refit.rs.html Setup snippet for a BVH instance with a workspace, often used before applying refit operations. ```rust # #[cfg(all(feature = "dim3", feature = "f32"))] { use parry3d::partitioning::{Bvh, BvhWorkspace}; use parry3d::bounding_volume::Aabb; use parry3d::math::Vector; let mut bvh = Bvh::new(); let mut workspace = BvhWorkspace::default(); # } ``` -------------------------------- ### Create a SortedPair Source: https://docs.rs/parry2d/latest/parry2d/utils/struct.SortedPair.html Demonstrates initializing a SortedPair with two values, which are then stored in ascending order. ```rust let pair = SortedPair::new(10, 5); // Elements are automatically sorted assert_eq!(pair.0, 5); assert_eq!(pair.1, 10); ``` -------------------------------- ### Get Value from VecMap Source: https://docs.rs/parry2d/latest/parry2d/utils/struct.VecMap.html Retrieves a reference to the value associated with the given key. ```rust use parry::utils::VecMap; let mut map = VecMap::new(); map.insert(1, "a"); assert_eq!(map.get(1), Some(&"a")); assert_eq!(map.get(2), None); ``` -------------------------------- ### Checking Voxel Type Source: https://docs.rs/parry2d/latest/parry2d/shape/enum.VoxelType.html Example demonstrating how to create a voxel grid and query the VoxelType of a specific voxel. ```rust use parry3d::shape::{Voxels, VoxelType}; use parry3d::math::{Vector, IVector}; // Create a small 2x2x2 cube of voxels let voxels = Voxels::new( Vector::new(1.0, 1.0, 1.0), &[ IVector::new(0, 0, 0), IVector::new(1, 0, 0), IVector::new(0, 1, 0), IVector::new(1, 1, 0), IVector::new(0, 0, 1), IVector::new(1, 0, 1), IVector::new(0, 1, 1), IVector::new(1, 1, 1), ], ); // Check voxel type - interior voxels are fully surrounded let state = voxels.voxel_state(IVector::new(0, 0, 0)).unwrap(); let voxel_type = state.voxel_type(); println!("Voxel type: {:?}", voxel_type); ``` -------------------------------- ### Get the number of triangles Source: https://docs.rs/parry2d/latest/parry2d/shape/struct.TriMesh.html Returns the total count of triangles defined in the mesh. ```rust use parry3d::shape::TriMesh; use parry3d::math::Vector; let vertices = vec![ Vector::ZERO, Vector::new(1.0, 0.0, 0.0), Vector::new(0.0, 1.0, 0.0), Vector::new(1.0, 1.0, 0.0), ]; let indices = vec![[0, 1, 2], [1, 3, 2]]; let mesh = TriMesh::new(vertices, indices).unwrap(); assert_eq!(mesh.num_triangles(), 2); ```