Struct SharedShape

Source
pub struct SharedShape(pub Arc<dyn Shape>);
Expand description

A reference-counted, shareable geometric shape.

SharedShape is a wrapper around Arc<dyn Shape> that allows multiple parts of your code to share ownership of the same shape without copying it. This is particularly useful when the same geometric shape is used by multiple colliders or when you want to avoid the memory overhead of duplicating complex shapes like triangle meshes.

§Why use SharedShape?

  • Memory efficiency: Share expensive shapes (like TriMesh or HeightField) across multiple colliders
  • Performance: Cloning a SharedShape only increments a reference count, not the shape data
  • Type erasure: Store different shape types uniformly via the Shape trait
  • Flexibility: Can be converted to a unique instance via make_mut when needed

§When to use SharedShape?

Use SharedShape when:

  • You need multiple colliders with the same geometry
  • You’re working with large, complex shapes (meshes, compounds, heightfields)
  • You want to store heterogeneous shape types in a collection

Use concrete shape types directly when:

  • You have a single, simple shape that won’t be shared
  • You need direct access to shape-specific methods

§Examples

Creating and sharing a ball shape:


// Create a ball with radius 1.0
let shape = SharedShape::ball(1.0);

// Clone it cheaply - only the Arc is cloned, not the shape data
let shape_clone = shape.clone();

// Both shapes reference the same underlying ball
assert_eq!(shape.as_ball().unwrap().radius, 1.0);
assert_eq!(shape_clone.as_ball().unwrap().radius, 1.0);

Tuple Fields§

§0: Arc<dyn Shape>

Implementations§

Source§

impl SharedShape

Source

pub fn new(shape: impl Shape) -> Self

Wraps any shape type into a SharedShape.

This constructor accepts any type that implements the Shape trait and wraps it in an Arc for shared ownership.

§Examples

let ball = Ball::new(1.0);
let shared = SharedShape::new(ball);
Source

pub fn make_mut(&mut self) -> &mut dyn Shape

Returns a mutable reference to the underlying shape, cloning it if necessary.

This method implements copy-on-write semantics. If the Arc has multiple references, it will clone the shape data to create a unique instance. Otherwise, no cloning occurs.

§Examples

let mut shape1 = SharedShape::ball(1.0);
let shape2 = shape1.clone(); // Shares the same Arc

// This will clone the shape because it's shared
let ball = shape1.make_mut().as_ball_mut().unwrap();
ball.radius = 2.0;

// shape1 has been modified, shape2 still has the original value
assert_eq!(shape1.as_ball().unwrap().radius, 2.0);
assert_eq!(shape2.as_ball().unwrap().radius, 1.0);
Source

pub fn compound(shapes: Vec<(Isometry<f32>, SharedShape)>) -> Self

Creates a compound shape made of multiple subshapes.

Each subshape has its own position and orientation relative to the compound’s origin.

§Examples

let ball1 = SharedShape::ball(0.5);
let ball2 = SharedShape::ball(0.5);

#[cfg(feature = "dim3")]
let compound = SharedShape::compound(vec![
    (Isometry::translation(1.0, 0.0, 0.0), ball1),
    (Isometry::translation(-1.0, 0.0, 0.0), ball2),
]);

#[cfg(feature = "dim2")]
let compound = SharedShape::compound(vec![
    (Isometry::translation(1.0, 0.0), ball1),
    (Isometry::translation(-1.0, 0.0), ball2),
]);
Source

pub fn ball(radius: f32) -> Self

Creates a ball (sphere in 3D, circle in 2D) with the specified radius.

A ball is the simplest and most efficient collision shape.

§Examples

let ball = SharedShape::ball(1.0);
assert_eq!(ball.as_ball().unwrap().radius, 1.0);
Source

pub fn halfspace(outward_normal: Unit<Vector<f32>>) -> Self

Initialize a plane shape defined by its outward normal.

Source

pub fn cuboid(hx: f32, hy: f32) -> Self

Initialize a cuboid shape defined by its half-extents.

Source

pub fn round_cuboid(hx: f32, hy: f32, border_radius: f32) -> Self

Initialize a round cuboid shape defined by its half-extents and border radius.

Source

pub fn capsule(a: Point<f32>, b: Point<f32>, radius: f32) -> Self

Initialize a capsule shape from its endpoints and radius.

Source

pub fn capsule_x(half_height: f32, radius: f32) -> Self

Initialize a capsule shape aligned with the x axis.

Source

pub fn capsule_y(half_height: f32, radius: f32) -> Self

Creates a capsule aligned with the Y axis.

A capsule is a line segment with rounded ends, commonly used for character controllers.

§Examples

// Create a character capsule: 1.8 units tall with 0.3 radius
let character = SharedShape::capsule_y(0.9, 0.3);
Source

pub fn segment(a: Point<f32>, b: Point<f32>) -> Self

Initialize a segment shape from its endpoints.

Source

pub fn triangle(a: Point<f32>, b: Point<f32>, c: Point<f32>) -> Self

Initializes a triangle shape.

Source

pub fn round_triangle( a: Point<f32>, b: Point<f32>, c: Point<f32>, border_radius: f32, ) -> Self

Initializes a triangle shape with round corners.

Source

pub fn polyline( vertices: Vec<Point<f32>>, indices: Option<Vec<[u32; 2]>>, ) -> Self

Initializes a polyline shape defined by its vertex and index buffers.

If no index buffer is provided, the polyline is assumed to describe a line strip.

Source

pub fn trimesh( vertices: Vec<Point<f32>>, indices: Vec<[u32; 3]>, ) -> Result<Self, TriMeshBuilderError>

Creates a triangle mesh shape from vertices and triangle indices.

A triangle mesh represents a complex surface as a collection of triangles, useful for terrain, static geometry, or any shape that can’t be represented by simpler primitives.

§Returns

Returns Ok(SharedShape) if the mesh is valid, or an error if indices are out of bounds.

§Examples

#[cfg(feature = "dim3")]
let vertices = vec![
    Point::new(0.0, 0.0, 0.0),
    Point::new(1.0, 0.0, 0.0),
    Point::new(0.0, 1.0, 0.0),
];
#[cfg(feature = "dim3")]
let indices = vec![[0, 1, 2]];
#[cfg(feature = "dim3")]
let mesh = SharedShape::trimesh(vertices, indices).unwrap();
Source

pub fn trimesh_with_flags( vertices: Vec<Point<f32>>, indices: Vec<[u32; 3]>, flags: TriMeshFlags, ) -> Result<Self, TriMeshBuilderError>

Initializes a triangle mesh shape defined by its vertex and index buffers and pre-processing flags.

Source

pub fn voxels(voxel_size: Vector<f32>, grid_coords: &[Point<i32>]) -> Self

Initializes a shape made of voxels.

Each voxel has the size voxel_size and grid coordinate given by grid_coords. The primitive_geometry controls the behavior of collision detection at voxels boundaries.

For initializing a voxels shape from points in space, see Self::voxels_from_points. For initializing a voxels shape from a mesh to voxelize, see Self::voxelized_mesh. For initializing multiple voxels shape from the convex decomposition of a mesh, see Self::voxelized_convex_decomposition.

Source

pub fn voxels_from_points( voxel_size: Vector<f32>, points: &[Point<f32>], ) -> Self

Initializes a shape made of voxels.

Each voxel has the size voxel_size and contains at least one point from centers. The primitive_geometry controls the behavior of collision detection at voxels boundaries.

Source

pub fn voxelized_mesh( vertices: &[Point<f32>], indices: &[[u32; 2]], voxel_size: f32, fill_mode: FillMode, ) -> Self

Initializes a voxels shape obtained from the decomposition of the given trimesh (in 3D) or polyline (in 2D) into voxelized convex parts.

Source

pub fn voxelized_convex_decomposition( vertices: &[Point<f32>], indices: &[[u32; 2]], ) -> Vec<Self>

Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or polyline (in 2D) into voxelized convex parts.

Source

pub fn voxelized_convex_decomposition_with_params( vertices: &[Point<f32>], indices: &[[u32; 2]], params: &VHACDParameters, ) -> Vec<Self>

Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or polyline (in 2D) into voxelized convex parts.

Source

pub fn convex_decomposition( vertices: &[Point<f32>], indices: &[[u32; 2]], ) -> Self

Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or polyline (in 2D) into convex parts.

Source

pub fn round_convex_decomposition( vertices: &[Point<f32>], indices: &[[u32; 2]], border_radius: f32, ) -> Self

Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or polyline (in 2D) into convex parts dilated with round corners.

Source

pub fn convex_decomposition_with_params( vertices: &[Point<f32>], indices: &[[u32; 2]], params: &VHACDParameters, ) -> Self

Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or polyline (in 2D) into convex parts.

Source

pub fn round_convex_decomposition_with_params( vertices: &[Point<f32>], indices: &[[u32; 2]], params: &VHACDParameters, border_radius: f32, ) -> Self

Initializes a compound shape obtained from the decomposition of the given trimesh (in 3D) or polyline (in 2D) into convex parts dilated with round corners.

Source

pub fn convex_hull(points: &[Point<f32>]) -> Option<Self>

Creates a new shared shape that is the convex-hull of the given points.

Source

pub fn convex_polyline(points: Vec<Point<f32>>) -> Option<Self>

Creates a new shared shape that is a 2D convex polygon from a set of points assumed to describe a counter-clockwise convex polyline.

This does not compute the convex-hull of the input points: convexity of the input is assumed and not checked. For a version that calculates the convex hull of the input points, use SharedShape::convex_hull instead.

The generated ConvexPolygon will contain the given points with any point collinear to the previous and next ones removed. For a version that leaves the input points unmodified, use SharedShape::convex_polyline_unmodified.

Returns None if all points form an almost flat line.

Source

pub fn convex_polyline_unmodified(points: Vec<Point<f32>>) -> Option<Self>

Creates a new shared shape that is a 2D convex polygon from a set of points assumed to describe a counter-clockwise convex polyline.

This is the same as SharedShape::convex_polyline but without removing any point from the input even if some are coplanar.

Returns None if points doesn’t contain at least three points.

Source

pub fn round_convex_hull( points: &[Point<f32>], border_radius: f32, ) -> Option<Self>

Creates a new shared shape with rounded corners that is the convex-hull of the given points, dilated by border_radius.

Source

pub fn round_convex_polyline( points: Vec<Point<f32>>, border_radius: f32, ) -> Option<Self>

Creates a new shared shape with round corners that is a convex polygon formed by the given set of points assumed to form a convex polyline (no convex-hull will be automatically computed).

Source

pub fn heightfield(heights: DVector<f32>, scale: Vector<f32>) -> Self

Initializes a heightfield shape defined by its set of height and a scale factor along each coordinate axis.

Methods from Deref<Target = dyn Shape>§

Source

pub fn is<__T: Shape>(&self) -> bool

Returns true if the trait object wraps an object of type __T.

Source

pub fn downcast_rc<__T: Shape>(self: Rc<Self>) -> Result<Rc<__T>, Rc<Self>>

Returns an Rc-ed object from an Rc-ed trait object if the underlying object is of type __T. Returns the original Rc-ed trait if it isn’t.

Source

pub fn downcast_ref<__T: Shape>(&self) -> Option<&__T>

Returns a reference to the object within the trait object if it is of type __T, or None if it isn’t.

Source

pub fn downcast_arc<__T: Shape + Any + Send + Sync>( self: Arc<Self>, ) -> Result<Arc<__T>, Arc<Self>>

Returns an Arc-ed object from an Arc-ed trait object if the underlying object is of type __T. Returns the original Arc-ed trait if it isn’t.

Source

pub fn as_shape<T: Shape>(&self) -> Option<&T>

Converts this abstract shape to the given shape, if it is one.

Source

pub fn as_ball(&self) -> Option<&Ball>

Converts this abstract shape to a ball, if it is one.

Source

pub fn as_cuboid(&self) -> Option<&Cuboid>

Converts this abstract shape to a cuboid, if it is one.

Source

pub fn as_halfspace(&self) -> Option<&HalfSpace>

Converts this abstract shape to a halfspace, if it is one.

Source

pub fn as_segment(&self) -> Option<&Segment>

Converts this abstract shape to a segment, if it is one.

Source

pub fn as_capsule(&self) -> Option<&Capsule>

Converts this abstract shape to a capsule, if it is one.

Source

pub fn as_triangle(&self) -> Option<&Triangle>

Converts this abstract shape to a triangle, if it is one.

Source

pub fn as_voxels(&self) -> Option<&Voxels>

Converts this abstract shape to voxels, if it is one.

Source

pub fn as_compound(&self) -> Option<&Compound>

Converts this abstract shape to a compound shape, if it is one.

Source

pub fn as_trimesh(&self) -> Option<&TriMesh>

Converts this abstract shape to a triangle mesh, if it is one.

Source

pub fn as_polyline(&self) -> Option<&Polyline>

Converts this abstract shape to a polyline, if it is one.

Source

pub fn as_heightfield(&self) -> Option<&HeightField>

Converts this abstract shape to a heightfield, if it is one.

Source

pub fn as_round_cuboid(&self) -> Option<&RoundCuboid>

Converts this abstract shape to a round cuboid, if it is one.

Source

pub fn as_round_triangle(&self) -> Option<&RoundTriangle>

Converts this abstract shape to a round triangle, if it is one.

Source

pub fn as_convex_polygon(&self) -> Option<&ConvexPolygon>

Converts this abstract shape to a convex polygon, if it is one.

Source

pub fn as_round_convex_polygon(&self) -> Option<&RoundConvexPolygon>

Converts this abstract shape to a round convex polygon, if it is one.

Trait Implementations§

Source§

impl AsRef<dyn Shape> for SharedShape

Source§

fn as_ref(&self) -> &dyn Shape

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for SharedShape

Source§

fn clone(&self) -> SharedShape

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SharedShape

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for SharedShape

Source§

type Target = dyn Shape

The resulting type after dereferencing.
Source§

fn deref(&self) -> &dyn Shape

Dereferences the value.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.