Debian Codegraph @

thirdparty/jolt_physics/Jolt/Physics/Collision/TransformedShape.h

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #pragma once
6
7 #include <Jolt/Physics/Collision/ObjectLayer.h>
8 #include <Jolt/Physics/Collision/ShapeFilter.h>
9 #include <Jolt/Physics/Collision/Shape/Shape.h>
10 #include <Jolt/Physics/Collision/Shape/SubShapeID.h>
11 #include <Jolt/Physics/Collision/BackFaceMode.h>
12 #include <Jolt/Physics/Body/BodyID.h>
13
14 JPH_NAMESPACE_BEGIN
15
16 struct RRayCast;
17 struct RShapeCast;
18 class CollideShapeSettings;
19 class RayCastResult;
20
21 /// Temporary data structure that contains a shape and a transform.
22 /// This structure can be obtained from a body (e.g. after a broad phase query) under lock protection.
23 /// The lock can then be released and collision detection operations can be safely performed since
24 /// the class takes a reference on the shape and does not use anything from the body anymore.
25 class JPH_EXPORT TransformedShape
26 {
27 public:
28 JPH_OVERRIDE_NEW_DELETE
29
30 /// Constructor
31 TransformedShape() = default;
32 TransformedShape(RVec3Arg inPositionCOM, QuatArg inRotation, const Shape *inShape, const BodyID &inBodyID, const SubShapeIDCreator &inSubShapeIDCreator = SubShapeIDCreator()) : mShapePositionCOM(inPositionCOM), mShapeRotation(inRotation), mShape(inShape), mBodyID(inBodyID), mSubShapeIDCreator(inSubShapeIDCreator) { }
33
34 /// Cast a ray and find the closest hit. Returns true if it finds a hit. Hits further than ioHit.mFraction will not be considered and in this case ioHit will remain unmodified (and the function will return false).
35 /// 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 are returned.
36 /// If you want the surface normal of the hit use GetWorldSpaceSurfaceNormal(ioHit.mSubShapeID2, inRay.GetPointOnRay(ioHit.mFraction)) on this object.
37 bool CastRay(const RRayCast &inRay, RayCastResult &ioHit) const;
38
39 /// Cast a ray, allows collecting multiple hits. Note that this version is more flexible but also slightly slower than the CastRay function that returns only a single hit.
40 /// If you want the surface normal of the hit use GetWorldSpaceSurfaceNormal(collected sub shape ID, inRay.GetPointOnRay(collected fraction)) on this object.
41 void CastRay(const RRayCast &inRay, const RayCastSettings &inRayCastSettings, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
42
43 /// Check if inPoint is inside any shapes. For this tests all shapes are treated as if they were solid.
44 /// For a mesh shape, this test will only provide sensible information if the mesh is a closed manifold.
45 /// For each shape that collides, ioCollector will receive a hit
46 void CollidePoint(RVec3Arg inPoint, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
47
48 /// Collide a shape and report any hits to ioCollector
49 /// @param inShape Shape to test
50 /// @param inShapeScale Scale in local space of shape
51 /// @param inCenterOfMassTransform Center of mass transform for the shape
52 /// @param inCollideShapeSettings Settings
53 /// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. mShapePositionCOM since floats are most accurate near the origin
54 /// @param ioCollector Collector that receives the hits
55 /// @param inShapeFilter Filter that allows you to reject collisions
56 void CollideShape(const Shape *inShape, Vec3Arg inShapeScale, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
57
58 /// Cast a shape and report any hits to ioCollector
59 /// @param inShapeCast The shape cast and its position and direction
60 /// @param inShapeCastSettings Settings for the shape cast
61 /// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. mShapePositionCOM or inShapeCast.mCenterOfMassStart.GetTranslation() since floats are most accurate near the origin
62 /// @param ioCollector Collector that receives the hits
63 /// @param inShapeFilter Filter that allows you to reject collisions
64 void CastShape(const RShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
65
66 /// Collect the leaf transformed shapes of all leaf shapes of this shape
67 /// inBox is the world space axis aligned box which leaf shapes should collide with
68 void CollectTransformedShapes(const AABox &inBox, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
69
70 /// Use the context from Shape
71 using GetTrianglesContext = Shape::GetTrianglesContext;
72
73 /// To start iterating over triangles, call this function first.
74 /// To get the actual triangles call GetTrianglesNext.
75 /// @param ioContext A temporary buffer and should remain untouched until the last call to GetTrianglesNext.
76 /// @param inBox The world space bounding in which you want to get the triangles.
77 /// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. inBox.GetCenter() since floats are most accurate near the origin
78 void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, RVec3Arg inBaseOffset) const;
79
80 /// Call this repeatedly to get all triangles in the box.
81 /// outTriangleVertices should be large enough to hold 3 * inMaxTriangleRequested entries
82 /// outMaterials (if it is not null) should contain inMaxTrianglesRequested entries
83 /// The function returns the amount of triangles that it found (which will be <= inMaxTrianglesRequested), or 0 if there are no more triangles.
84 /// Note that the function can return a value < inMaxTrianglesRequested and still have more triangles to process (triangles can be returned in blocks)
85 /// Note that the function may return triangles outside of the requested box, only coarse culling is performed on the returned triangles
86 int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const;
87
88 /// Get/set the scale of the shape as a Vec3
89 inline Vec3 GetShapeScale() const { return Vec3::sLoadFloat3Unsafe(mShapeScale); }
90 inline void SetShapeScale(Vec3Arg inScale) { inScale.StoreFloat3(&mShapeScale); }
91
92 /// Calculates the transform for this shape's center of mass (excluding scale)
93 inline RMat44 GetCenterOfMassTransform() const { return RMat44::sRotationTranslation(mShapeRotation, mShapePositionCOM); }
94
95 /// Calculates the inverse of the transform for this shape's center of mass (excluding scale)
96 inline RMat44 GetInverseCenterOfMassTransform() const { return RMat44::sInverseRotationTranslation(mShapeRotation, mShapePositionCOM); }
97
98 /// Sets the world transform (including scale) of this transformed shape (not from the center of mass but in the space the shape was created)
99 inline void SetWorldTransform(RVec3Arg inPosition, QuatArg inRotation, Vec3Arg inScale)
100 {
101 mShapePositionCOM = inPosition + inRotation * (inScale * mShape->GetCenterOfMass());
102 mShapeRotation = inRotation;
103 SetShapeScale(inScale);
104 }
105
106 /// Sets the world transform (including scale) of this transformed shape (not from the center of mass but in the space the shape was created)
107 inline void SetWorldTransform(RMat44Arg inTransform)
108 {
109 Vec3 scale;
110 RMat44 rot_trans = inTransform.Decompose(scale);
111 SetWorldTransform(rot_trans.GetTranslation(), rot_trans.GetQuaternion(), scale);
112 }
113
114 /// Calculates the world transform including scale of this shape (not from the center of mass but in the space the shape was created)
115 inline RMat44 GetWorldTransform() const
116 {
117 RMat44 transform = RMat44::sRotation(mShapeRotation).PreScaled(GetShapeScale());
118 transform.SetTranslation(mShapePositionCOM - transform.Multiply3x3(mShape->GetCenterOfMass()));
119 return transform;
120 }
121
122 /// Get the world space bounding box for this transformed shape
123 AABox GetWorldSpaceBounds() const { return mShape != nullptr? mShape->GetWorldSpaceBounds(GetCenterOfMassTransform(), GetShapeScale()) : AABox(); }
124
125 /// Make inSubShapeID relative to mShape. When mSubShapeIDCreator is not empty, this is needed in order to get the correct path to the sub shape.
126 inline SubShapeID MakeSubShapeIDRelativeToShape(const SubShapeID &inSubShapeID) const
127 {
128 // Take off the sub shape ID part that comes from mSubShapeIDCreator and validate that it is the same
129 SubShapeID sub_shape_id;
130 uint num_bits_written = mSubShapeIDCreator.GetNumBitsWritten();
131 JPH_IF_ENABLE_ASSERTS(uint32 root_id =) inSubShapeID.PopID(num_bits_written, sub_shape_id);
132 JPH_ASSERT(root_id == (mSubShapeIDCreator.GetID().GetValue() & ((1 << num_bits_written) - 1)));
133 return sub_shape_id;
134 }
135
136 /// Get surface normal of a particular sub shape and its world space surface position on this body.
137 /// Note: When you have a CollideShapeResult or ShapeCastResult you should use -mPenetrationAxis.Normalized() as contact normal as GetWorldSpaceSurfaceNormal will only return face normals (and not vertex or edge normals).
138 inline Vec3 GetWorldSpaceSurfaceNormal(const SubShapeID &inSubShapeID, RVec3Arg inPosition) const
139 {
140 RMat44 inv_com = GetInverseCenterOfMassTransform();
141 Vec3 scale = GetShapeScale(); // See comment at ScaledShape::GetSurfaceNormal for the math behind the scaling of the normal
142 return inv_com.Multiply3x3Transposed(mShape->GetSurfaceNormal(MakeSubShapeIDRelativeToShape(inSubShapeID), Vec3(inv_com * inPosition) / scale) / scale).Normalized();
143 }
144
145 /// Get the vertices of the face that faces inDirection the most (includes any convex radius). Note that this function can only return faces of
146 /// convex shapes or triangles, which is why a sub shape ID to get to that leaf must be provided.
147 /// @param inSubShapeID Sub shape ID of target shape
148 /// @param inDirection Direction that the face should be facing (in world space)
149 /// @param inBaseOffset The vertices will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. mShapePositionCOM since floats are most accurate near the origin
150 /// @param outVertices Resulting face. Note the returned face can have a single point if the shape doesn't have polygons to return (e.g. because it's a sphere). The face will be returned in world space.
151 void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, RVec3Arg inBaseOffset, Shape::SupportingFace &outVertices) const
152 {
153 Mat44 com = GetCenterOfMassTransform().PostTranslated(-inBaseOffset).ToMat44();
154 mShape->GetSupportingFace(MakeSubShapeIDRelativeToShape(inSubShapeID), com.Multiply3x3Transposed(inDirection), GetShapeScale(), com, outVertices);
155 }
156
157 /// Get material of a particular sub shape
158 inline const PhysicsMaterial *GetMaterial(const SubShapeID &inSubShapeID) const
159 {
160 return mShape->GetMaterial(MakeSubShapeIDRelativeToShape(inSubShapeID));
161 }
162
163 /// Get the user data of a particular sub shape
164 inline uint64 GetSubShapeUserData(const SubShapeID &inSubShapeID) const
165 {
166 return mShape->GetSubShapeUserData(MakeSubShapeIDRelativeToShape(inSubShapeID));
167 }
168
169 /// Get the direct child sub shape and its transform for a sub shape ID.
170 /// @param inSubShapeID Sub shape ID that indicates the path to the leaf shape
171 /// @param outRemainder The remainder of the sub shape ID after removing the sub shape
172 /// @return Direct child sub shape and its transform, note that the body ID and sub shape ID will be invalid
173 TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, SubShapeID &outRemainder) const
174 {
175 TransformedShape ts = mShape->GetSubShapeTransformedShape(inSubShapeID, Vec3::sZero(), mShapeRotation, GetShapeScale(), outRemainder);
176 ts.mShapePositionCOM += mShapePositionCOM;
177 return ts;
178 }
179
180 /// Helper function to return the body id from a transformed shape. If the transformed shape is null an invalid body ID will be returned.
181 inline static BodyID sGetBodyID(const TransformedShape *inTS) { return inTS != nullptr? inTS->mBodyID : BodyID(); }
182
183 RVec3 mShapePositionCOM; ///< Center of mass world position of the shape
184 Quat mShapeRotation; ///< Rotation of the shape
185 RefConst<Shape> mShape; ///< The shape itself
186 Float3 mShapeScale { 1, 1, 1 }; ///< Not stored as Vec3 to get a nicely packed structure
187 BodyID mBodyID; ///< Optional body ID from which this shape comes
188 SubShapeIDCreator mSubShapeIDCreator; ///< Optional sub shape ID creator for the shape (can be used when expanding compound shapes into multiple transformed shapes)
189 };
190
191 static_assert(JPH_CPU_ADDRESS_BITS != 64 || JPH_RVECTOR_ALIGNMENT < 16 || sizeof(TransformedShape) == JPH_IF_SINGLE_PRECISION_ELSE(64, 96), "Not properly packed");
192 static_assert(alignof(TransformedShape) == max(JPH_VECTOR_ALIGNMENT, JPH_RVECTOR_ALIGNMENT), "Not properly aligned");
193
194 JPH_NAMESPACE_END