Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.h
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Physics/Body/MassProperties.h>7#include <Jolt/Physics/Collision/BackFaceMode.h>8#include <Jolt/Physics/Collision/CollisionCollector.h>9#include <Jolt/Physics/Collision/ShapeFilter.h>10#include <Jolt/Geometry/AABox.h>11#include <Jolt/Core/Reference.h>12#include <Jolt/Core/Color.h>13#include <Jolt/Core/Result.h>14#include <Jolt/Core/NonCopyable.h>15#include <Jolt/Core/UnorderedMap.h>16#include <Jolt/Core/UnorderedSet.h>17#include <Jolt/Core/StreamUtils.h>18#include <Jolt/ObjectStream/SerializableObject.h>1920JPH_NAMESPACE_BEGIN2122struct RayCast;23class RayCastSettings;24struct ShapeCast;25class ShapeCastSettings;26class RayCastResult;27class ShapeCastResult;28class CollidePointResult;29class CollideShapeResult;30class SubShapeIDCreator;31class SubShapeID;32class PhysicsMaterial;33class TransformedShape;34class Plane;35class CollideSoftBodyVertexIterator;36class Shape;37class StreamOut;38class StreamIn;39#ifdef JPH_DEBUG_RENDERER40class DebugRenderer;41#endif // JPH_DEBUG_RENDERER4243using CastRayCollector = CollisionCollector<RayCastResult, CollisionCollectorTraitsCastRay>;44using CastShapeCollector = CollisionCollector<ShapeCastResult, CollisionCollectorTraitsCastShape>;45using CollidePointCollector = CollisionCollector<CollidePointResult, CollisionCollectorTraitsCollidePoint>;46using CollideShapeCollector = CollisionCollector<CollideShapeResult, CollisionCollectorTraitsCollideShape>;47using TransformedShapeCollector = CollisionCollector<TransformedShape, CollisionCollectorTraitsCollideShape>;4849using ShapeRefC = RefConst<Shape>;50using ShapeList = Array<ShapeRefC>;51using PhysicsMaterialRefC = RefConst<PhysicsMaterial>;52using PhysicsMaterialList = Array<PhysicsMaterialRefC>;5354/// Shapes are categorized in groups, each shape can return which group it belongs to through its Shape::GetType function.55enum class EShapeType : uint856{57Convex, ///< Used by ConvexShape, all shapes that use the generic convex vs convex collision detection system (box, sphere, capsule, tapered capsule, cylinder, triangle)58Compound, ///< Used by CompoundShape59Decorated, ///< Used by DecoratedShape60Mesh, ///< Used by MeshShape61HeightField, ///< Used by HeightFieldShape62SoftBody, ///< Used by SoftBodyShape6364// User defined shapes65User1,66User2,67User3,68User4,6970Plane, ///< Used by PlaneShape71Empty, ///< Used by EmptyShape72};7374/// This enumerates all shape types, each shape can return its type through Shape::GetSubType75enum class EShapeSubType : uint876{77// Convex shapes78Sphere,79Box,80Triangle,81Capsule,82TaperedCapsule,83Cylinder,84ConvexHull,8586// Compound shapes87StaticCompound,88MutableCompound,8990// Decorated shapes91RotatedTranslated,92Scaled,93OffsetCenterOfMass,9495// Other shapes96Mesh,97HeightField,98SoftBody,99100// User defined shapes101User1,102User2,103User3,104User4,105User5,106User6,107User7,108User8,109110// User defined convex shapes111UserConvex1,112UserConvex2,113UserConvex3,114UserConvex4,115UserConvex5,116UserConvex6,117UserConvex7,118UserConvex8,119120// Other shapes121Plane,122TaperedCylinder,123Empty,124};125126// Sets of shape sub types127static constexpr EShapeSubType sAllSubShapeTypes[] = { EShapeSubType::Sphere, EShapeSubType::Box, EShapeSubType::Triangle, EShapeSubType::Capsule, EShapeSubType::TaperedCapsule, EShapeSubType::Cylinder, EShapeSubType::ConvexHull, EShapeSubType::StaticCompound, EShapeSubType::MutableCompound, EShapeSubType::RotatedTranslated, EShapeSubType::Scaled, EShapeSubType::OffsetCenterOfMass, EShapeSubType::Mesh, EShapeSubType::HeightField, EShapeSubType::SoftBody, EShapeSubType::User1, EShapeSubType::User2, EShapeSubType::User3, EShapeSubType::User4, EShapeSubType::User5, EShapeSubType::User6, EShapeSubType::User7, EShapeSubType::User8, EShapeSubType::UserConvex1, EShapeSubType::UserConvex2, EShapeSubType::UserConvex3, EShapeSubType::UserConvex4, EShapeSubType::UserConvex5, EShapeSubType::UserConvex6, EShapeSubType::UserConvex7, EShapeSubType::UserConvex8, EShapeSubType::Plane, EShapeSubType::TaperedCylinder, EShapeSubType::Empty };128static constexpr EShapeSubType sConvexSubShapeTypes[] = { EShapeSubType::Sphere, EShapeSubType::Box, EShapeSubType::Triangle, EShapeSubType::Capsule, EShapeSubType::TaperedCapsule, EShapeSubType::Cylinder, EShapeSubType::ConvexHull, EShapeSubType::TaperedCylinder, EShapeSubType::UserConvex1, EShapeSubType::UserConvex2, EShapeSubType::UserConvex3, EShapeSubType::UserConvex4, EShapeSubType::UserConvex5, EShapeSubType::UserConvex6, EShapeSubType::UserConvex7, EShapeSubType::UserConvex8 };129static constexpr EShapeSubType sCompoundSubShapeTypes[] = { EShapeSubType::StaticCompound, EShapeSubType::MutableCompound };130static constexpr EShapeSubType sDecoratorSubShapeTypes[] = { EShapeSubType::RotatedTranslated, EShapeSubType::Scaled, EShapeSubType::OffsetCenterOfMass };131132/// How many shape types we support133static constexpr uint NumSubShapeTypes = uint(std::size(sAllSubShapeTypes));134135/// Names of sub shape types136static constexpr const char *sSubShapeTypeNames[] = { "Sphere", "Box", "Triangle", "Capsule", "TaperedCapsule", "Cylinder", "ConvexHull", "StaticCompound", "MutableCompound", "RotatedTranslated", "Scaled", "OffsetCenterOfMass", "Mesh", "HeightField", "SoftBody", "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "UserConvex1", "UserConvex2", "UserConvex3", "UserConvex4", "UserConvex5", "UserConvex6", "UserConvex7", "UserConvex8", "Plane", "TaperedCylinder", "Empty" };137static_assert(std::size(sSubShapeTypeNames) == NumSubShapeTypes);138139/// Class that can construct shapes and that is serializable using the ObjectStream system.140/// Can be used to store shape data in 'uncooked' form (i.e. in a form that is still human readable and authorable).141/// Once the shape has been created using the Create() function, the data will be moved into the Shape class142/// in a form that is optimized for collision detection. After this, the ShapeSettings object is no longer needed143/// and can be destroyed. Each shape class has a derived class of the ShapeSettings object to store shape specific144/// data.145class JPH_EXPORT ShapeSettings : public SerializableObject, public RefTarget<ShapeSettings>146{147JPH_DECLARE_SERIALIZABLE_ABSTRACT(JPH_EXPORT, ShapeSettings)148149public:150using ShapeResult = Result<Ref<Shape>>;151152/// Create a shape according to the settings specified by this object.153virtual ShapeResult Create() const = 0;154155/// When creating a shape, the result is cached so that calling Create() again will return the same shape.156/// If you make changes to the ShapeSettings you need to call this function to clear the cached result to allow Create() to build a new shape.157void ClearCachedResult() { mCachedResult.Clear(); }158159/// User data (to be used freely by the application)160uint64 mUserData = 0;161162protected:163mutable ShapeResult mCachedResult;164};165166/// Function table for functions on shapes167class JPH_EXPORT ShapeFunctions168{169public:170/// Construct a shape171Shape * (*mConstruct)() = nullptr;172173/// Color of the shape when drawing174Color mColor = Color::sBlack;175176/// Get an entry in the registry for a particular sub type177static inline ShapeFunctions & sGet(EShapeSubType inSubType) { return sRegistry[int(inSubType)]; }178179private:180static ShapeFunctions sRegistry[NumSubShapeTypes];181};182183/// Base class for all shapes (collision volume of a body). Defines a virtual interface for collision detection.184class JPH_EXPORT Shape : public RefTarget<Shape>, public NonCopyable185{186public:187JPH_OVERRIDE_NEW_DELETE188189using ShapeResult = ShapeSettings::ShapeResult;190191/// Constructor192Shape(EShapeType inType, EShapeSubType inSubType) : mShapeType(inType), mShapeSubType(inSubType) { }193Shape(EShapeType inType, EShapeSubType inSubType, const ShapeSettings &inSettings, [[maybe_unused]] ShapeResult &outResult) : mUserData(inSettings.mUserData), mShapeType(inType), mShapeSubType(inSubType) { }194195/// Destructor196virtual ~Shape() = default;197198/// Get type199inline EShapeType GetType() const { return mShapeType; }200inline EShapeSubType GetSubType() const { return mShapeSubType; }201202/// User data (to be used freely by the application)203uint64 GetUserData() const { return mUserData; }204void SetUserData(uint64 inUserData) { mUserData = inUserData; }205206/// Check if this shape can only be used to create a static body or if it can also be dynamic/kinematic207virtual bool MustBeStatic() const { return false; }208209/// All shapes are centered around their center of mass. This function returns the center of mass position that needs to be applied to transform the shape to where it was created.210virtual Vec3 GetCenterOfMass() const { return Vec3::sZero(); }211212/// Get local bounding box including convex radius, this box is centered around the center of mass rather than the world transform213virtual AABox GetLocalBounds() const = 0;214215/// Get the max number of sub shape ID bits that are needed to be able to address any leaf shape in this shape. Used mainly for checking that it is smaller or equal than SubShapeID::MaxBits.216virtual uint GetSubShapeIDBitsRecursive() const = 0;217218/// Get world space bounds including convex radius.219/// This shape is scaled by inScale in local space first.220/// This function can be overridden to return a closer fitting world space bounding box, by default it will just transform what GetLocalBounds() returns.221virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const { return GetLocalBounds().Scaled(inScale).Transformed(inCenterOfMassTransform); }222223/// Get world space bounds including convex radius.224AABox GetWorldSpaceBounds(DMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const225{226// Use single precision version using the rotation only227AABox bounds = GetWorldSpaceBounds(inCenterOfMassTransform.GetRotation(), inScale);228229// Apply translation230bounds.Translate(inCenterOfMassTransform.GetTranslation());231232return bounds;233}234235/// Returns the radius of the biggest sphere that fits entirely in the shape. In case this shape consists of multiple sub shapes, it returns the smallest sphere of the parts.236/// This can be used as a measure of how far the shape can be moved without risking going through geometry.237virtual float GetInnerRadius() const = 0;238239/// Calculate the mass and inertia of this shape240virtual MassProperties GetMassProperties() const = 0;241242/// Get the leaf shape for a particular sub shape ID.243/// @param inSubShapeID The full sub shape ID that indicates the path to the leaf shape244/// @param outRemainder What remains of the sub shape ID after removing the path to the leaf shape (could e.g. refer to a triangle within a MeshShape)245/// @return The shape or null if the sub shape ID is invalid246virtual const Shape * GetLeafShape([[maybe_unused]] const SubShapeID &inSubShapeID, SubShapeID &outRemainder) const;247248/// Get the material assigned to a particular sub shape ID249virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const = 0;250251/// Get the surface normal of a particular sub shape ID and point on surface (all vectors are relative to center of mass for this shape).252/// Note: When you have a CollideShapeResult or ShapeCastResult you should use -mPenetrationAxis.Normalized() as contact normal as GetSurfaceNormal will only return face normals (and not vertex or edge normals).253virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const = 0;254255/// Type definition for a supporting face256using SupportingFace = StaticArray<Vec3, 32>;257258/// Get the vertices of the face that faces inDirection the most (includes any convex radius). Note that this function can only return faces of259/// convex shapes or triangles, which is why a sub shape ID to get to that leaf must be provided.260/// @param inSubShapeID Sub shape ID of target shape261/// @param inDirection Direction that the face should be facing (in local space to this shape)262/// @param inCenterOfMassTransform Transform to transform outVertices with263/// @param inScale Scale in local space of the shape (scales relative to its center of mass)264/// @param outVertices Resulting face. The returned face can be empty if the shape doesn't have polygons to return (e.g. because it's a sphere). The face will be returned in world space.265virtual void GetSupportingFace([[maybe_unused]] const SubShapeID &inSubShapeID, [[maybe_unused]] Vec3Arg inDirection, [[maybe_unused]] Vec3Arg inScale, [[maybe_unused]] Mat44Arg inCenterOfMassTransform, [[maybe_unused]] SupportingFace &outVertices) const { /* Nothing */ }266267/// Get the user data of a particular sub shape ID. Corresponds with the value stored in Shape::GetUserData of the leaf shape pointed to by inSubShapeID.268virtual uint64 GetSubShapeUserData([[maybe_unused]] const SubShapeID &inSubShapeID) const { return mUserData; }269270/// Get the direct child sub shape and its transform for a sub shape ID.271/// @param inSubShapeID Sub shape ID that indicates the path to the leaf shape272/// @param inPositionCOM The position of the center of mass of this shape273/// @param inRotation The orientation of this shape274/// @param inScale Scale in local space of the shape (scales relative to its center of mass)275/// @param outRemainder The remainder of the sub shape ID after removing the sub shape276/// @return Direct child sub shape and its transform, note that the body ID and sub shape ID will be invalid277virtual TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const;278279/// Gets the properties needed to do buoyancy calculations for a body using this shape280/// @param inCenterOfMassTransform Transform that takes this shape (centered around center of mass) to world space (or a desired other space)281/// @param inScale Scale in local space of the shape (scales relative to its center of mass)282/// @param inSurface The surface plane of the liquid relative to inCenterOfMassTransform283/// @param outTotalVolume On return this contains the total volume of the shape284/// @param outSubmergedVolume On return this contains the submerged volume of the shape285/// @param outCenterOfBuoyancy On return this contains the world space center of mass of the submerged volume286#ifdef JPH_DEBUG_RENDERER287/// @param inBaseOffset The offset to transform inCenterOfMassTransform to world space (in double precision mode this can be used to shift the whole operation closer to the origin). Only used for debug drawing.288#endif289virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy290#ifdef JPH_DEBUG_RENDERER // Not using JPH_IF_DEBUG_RENDERER for Doxygen291, RVec3Arg inBaseOffset292#endif293) const = 0;294295#ifdef JPH_DEBUG_RENDERER296/// Draw the shape at a particular location with a particular color (debugging purposes)297virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const = 0;298299/// Draw the results of the GetSupportFunction with the convex radius added back on to show any errors introduced by this process (only relevant for convex shapes)300virtual void DrawGetSupportFunction([[maybe_unused]] DebugRenderer *inRenderer, [[maybe_unused]] RMat44Arg inCenterOfMassTransform, [[maybe_unused]] Vec3Arg inScale, [[maybe_unused]] ColorArg inColor, [[maybe_unused]] bool inDrawSupportDirection) const { /* Only implemented for convex shapes */ }301302/// Draw the results of the GetSupportingFace function to show any errors introduced by this process (only relevant for convex shapes)303virtual void DrawGetSupportingFace([[maybe_unused]] DebugRenderer *inRenderer, [[maybe_unused]] RMat44Arg inCenterOfMassTransform, [[maybe_unused]] Vec3Arg inScale) const { /* Only implemented for convex shapes */ }304#endif // JPH_DEBUG_RENDERER305306/// Cast a ray against this shape, returns true if it finds a hit closer than ioHit.mFraction and updates that fraction. Otherwise ioHit is left untouched and the function returns false.307/// Note that the ray should be relative to the center of mass of this shape (i.e. subtract Shape::GetCenterOfMass() from RayCast::mOrigin if you want to cast against the shape in the space it was created).308/// Convex objects will be treated as solid (meaning if the ray starts inside, you'll get a hit fraction of 0) and back face hits against triangles are returned.309/// If you want the surface normal of the hit use GetSurfaceNormal(ioHit.mSubShapeID2, inRay.GetPointOnRay(ioHit.mFraction)).310virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const = 0;311312/// Cast a ray against this shape. Allows returning multiple hits through ioCollector. Note that this version is more flexible but also slightly slower than the CastRay function that returns only a single hit.313/// If you want the surface normal of the hit use GetSurfaceNormal(collected sub shape ID, inRay.GetPointOnRay(collected faction)).314virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const = 0;315316/// Check if inPoint is inside this shape. For this tests all shapes are treated as if they were solid.317/// Note that inPoint should be relative to the center of mass of this shape (i.e. subtract Shape::GetCenterOfMass() from inPoint if you want to test against the shape in the space it was created).318/// For a mesh shape, this test will only provide sensible information if the mesh is a closed manifold.319/// For each shape that collides, ioCollector will receive a hit.320virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const = 0;321322/// Collides all vertices of a soft body with this shape and updates SoftBodyVertex::mCollisionPlane, SoftBodyVertex::mCollidingShapeIndex and SoftBodyVertex::mLargestPenetration if a collision with more penetration was found.323/// @param inCenterOfMassTransform Center of mass transform for this shape relative to the vertices.324/// @param inScale Scale in local space of the shape (scales relative to its center of mass)325/// @param inVertices The vertices of the soft body326/// @param inNumVertices The number of vertices in inVertices327/// @param inCollidingShapeIndex Value to store in CollideSoftBodyVertexIterator::mCollidingShapeIndex when a collision was found328virtual void CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const = 0;329330/// Collect the leaf transformed shapes of all leaf shapes of this shape.331/// inBox is the world space axis aligned box which leaf shapes should collide with.332/// inPositionCOM/inRotation/inScale describes the transform of this shape.333/// inSubShapeIDCreator represents the current sub shape ID of this shape.334virtual void CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const;335336/// Transforms this shape and all of its children with inTransform, resulting shape(s) are passed to ioCollector.337/// Note that not all shapes support all transforms (especially true for scaling), the resulting shape will try to match the transform as accurately as possible.338/// @param inCenterOfMassTransform The transform (rotation, translation, scale) that the center of mass of the shape should get339/// @param ioCollector The transformed shapes will be passed to this collector340virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const;341342/// Scale this shape. Note that not all shapes support all scales, this will return a shape that matches the scale as accurately as possible. See Shape::IsValidScale for more information.343/// @param inScale The scale to use for this shape (note: this scale is applied to the entire shape in the space it was created, most other functions apply the scale in the space of the leaf shapes and from the center of mass!)344ShapeResult ScaleShape(Vec3Arg inScale) const;345346/// An opaque buffer that holds shape specific information during GetTrianglesStart/Next.347struct alignas(16) GetTrianglesContext { uint8 mData[4288]; };348349/// This is the minimum amount of triangles that should be requested through GetTrianglesNext.350static constexpr int cGetTrianglesMinTrianglesRequested = 32;351352/// To start iterating over triangles, call this function first.353/// ioContext is a temporary buffer and should remain untouched until the last call to GetTrianglesNext.354/// inBox is the world space bounding in which you want to get the triangles.355/// inPositionCOM/inRotation/inScale describes the transform of this shape.356/// To get the actual triangles call GetTrianglesNext.357virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const = 0;358359/// Call this repeatedly to get all triangles in the box.360/// outTriangleVertices should be large enough to hold 3 * inMaxTriangleRequested entries.361/// outMaterials (if it is not null) should contain inMaxTrianglesRequested entries.362/// The function returns the amount of triangles that it found (which will be <= inMaxTrianglesRequested), or 0 if there are no more triangles.363/// Note that the function can return a value < inMaxTrianglesRequested and still have more triangles to process (triangles can be returned in blocks).364/// Note that the function may return triangles outside of the requested box, only coarse culling is performed on the returned triangles.365virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const = 0;366367///@name Binary serialization of the shape. Note that this saves the 'cooked' shape in a format which will not be backwards compatible for newer library versions.368/// In this case you need to recreate the shape from the ShapeSettings object and save it again. The user is expected to call SaveBinaryState followed by SaveMaterialState and SaveSubShapeState.369/// The stream should be stored as is and the material and shape list should be saved using the applications own serialization system (e.g. by assigning an ID to each pointer).370/// When restoring data, call sRestoreFromBinaryState to get the shape and then call RestoreMaterialState and RestoreSubShapeState to restore the pointers to the external objects.371/// Alternatively you can use SaveWithChildren and sRestoreWithChildren to save and restore the shape and all its child shapes and materials in a single stream.372///@{373374/// Saves the contents of the shape in binary form to inStream.375virtual void SaveBinaryState(StreamOut &inStream) const;376377/// Creates a Shape of the correct type and restores its contents from the binary stream inStream.378static ShapeResult sRestoreFromBinaryState(StreamIn &inStream);379380/// Outputs the material references that this shape has to outMaterials.381virtual void SaveMaterialState([[maybe_unused]] PhysicsMaterialList &outMaterials) const { /* By default do nothing */ }382383/// Restore the material references after calling sRestoreFromBinaryState. Note that the exact same materials need to be provided in the same order as returned by SaveMaterialState.384virtual void RestoreMaterialState([[maybe_unused]] const PhysicsMaterialRefC *inMaterials, [[maybe_unused]] uint inNumMaterials) { JPH_ASSERT(inNumMaterials == 0); }385386/// Outputs the shape references that this shape has to outSubShapes.387virtual void SaveSubShapeState([[maybe_unused]] ShapeList &outSubShapes) const { /* By default do nothing */ }388389/// Restore the shape references after calling sRestoreFromBinaryState. Note that the exact same shapes need to be provided in the same order as returned by SaveSubShapeState.390virtual void RestoreSubShapeState([[maybe_unused]] const ShapeRefC *inSubShapes, [[maybe_unused]] uint inNumShapes) { JPH_ASSERT(inNumShapes == 0); }391392using ShapeToIDMap = StreamUtils::ObjectToIDMap<Shape>;393using IDToShapeMap = StreamUtils::IDToObjectMap<Shape>;394using MaterialToIDMap = StreamUtils::ObjectToIDMap<PhysicsMaterial>;395using IDToMaterialMap = StreamUtils::IDToObjectMap<PhysicsMaterial>;396397/// Save this shape, all its children and its materials. Pass in an empty map in ioShapeMap / ioMaterialMap or reuse the same map while saving multiple shapes to the same stream in order to avoid writing duplicates.398void SaveWithChildren(StreamOut &inStream, ShapeToIDMap &ioShapeMap, MaterialToIDMap &ioMaterialMap) const;399400/// Restore a shape, all its children and materials. Pass in an empty map in ioShapeMap / ioMaterialMap or reuse the same map while reading multiple shapes from the same stream in order to restore duplicates.401static ShapeResult sRestoreWithChildren(StreamIn &inStream, IDToShapeMap &ioShapeMap, IDToMaterialMap &ioMaterialMap);402403///@}404405/// Class that holds information about the shape that can be used for logging / data collection purposes406struct Stats407{408Stats(size_t inSizeBytes, uint inNumTriangles) : mSizeBytes(inSizeBytes), mNumTriangles(inNumTriangles) { }409410size_t mSizeBytes; ///< Amount of memory used by this shape (size in bytes)411uint mNumTriangles; ///< Number of triangles in this shape (when applicable)412};413414/// Get stats of this shape. Use for logging / data collection purposes only. Does not add values from child shapes, use GetStatsRecursive for this.415virtual Stats GetStats() const = 0;416417using VisitedShapes = UnorderedSet<const Shape *>;418419/// Get the combined stats of this shape and its children.420/// @param ioVisitedShapes is used to track which shapes have already been visited, to avoid calculating the wrong memory size.421virtual Stats GetStatsRecursive(VisitedShapes &ioVisitedShapes) const;422423///< Volume of this shape (m^3). Note that for compound shapes the volume may be incorrect since child shapes can overlap which is not accounted for.424virtual float GetVolume() const = 0;425426/// Test if inScale is a valid scale for this shape. Some shapes can only be scaled uniformly, compound shapes cannot handle shapes427/// being rotated and scaled (this would cause shearing), scale can never be zero. When the scale is invalid, the function will return false.428///429/// Here's a list of supported scales:430/// * SphereShape: Scale must be uniform (signs of scale are ignored).431/// * BoxShape: Any scale supported (signs of scale are ignored).432/// * TriangleShape: Any scale supported when convex radius is zero, otherwise only uniform scale supported.433/// * CapsuleShape: Scale must be uniform (signs of scale are ignored).434/// * TaperedCapsuleShape: Scale must be uniform (sign of Y scale can be used to flip the capsule).435/// * CylinderShape: Scale must be uniform in XZ plane, Y can scale independently (signs of scale are ignored).436/// * RotatedTranslatedShape: Scale must not cause shear in the child shape.437/// * CompoundShape: Scale must not cause shear in any of the child shapes.438virtual bool IsValidScale(Vec3Arg inScale) const;439440/// This function will make sure that if you wrap this shape in a ScaledShape that the scale is valid.441/// Note that this involves discarding components of the scale that are invalid, so the resulting scaled shape may be different than the requested scale.442/// Compare the return value of this function with the scale you passed in to detect major inconsistencies and possibly warn the user.443/// @param inScale Local space scale for this shape.444/// @return Scale that can be used to wrap this shape in a ScaledShape. IsValidScale will return true for this scale.445virtual Vec3 MakeScaleValid(Vec3Arg inScale) const;446447#ifdef JPH_DEBUG_RENDERER448/// Debug helper which draws the intersection between water and the shapes, the center of buoyancy and the submerged volume449static bool sDrawSubmergedVolumes;450#endif // JPH_DEBUG_RENDERER451452protected:453/// This function should not be called directly, it is used by sRestoreFromBinaryState.454virtual void RestoreBinaryState(StreamIn &inStream);455456/// A fallback version of CollidePoint that uses a ray cast and counts the number of hits to determine if the point is inside the shape. Odd number of hits means inside, even number of hits means outside.457static void sCollidePointUsingRayCast(const Shape &inShape, Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter);458459private:460uint64 mUserData = 0;461EShapeType mShapeType;462EShapeSubType mShapeSubType;463};464465JPH_NAMESPACE_END466467468