载入中...
搜索中...
未找到
JoltWorldVolumes.cpp
浏览该文件的文档.
1// Jolt requires its platform header before any other native header.
2#include <Jolt/Jolt.h>
3
4// Provider implementation dependencies.
5#include <Jolt/Physics/Collision/CastResult.h>
6#include <Jolt/Physics/Collision/RayCast.h>
7#include <Jolt/Physics/Collision/Shape/BoxShape.h>
8#include <algorithm>
9#include "physics/World3D.h"
12namespace eve::physics::jolt {
13namespace {
14eve::Result<QueryVolume> boxVolume(float x, float y, float z, float w, float h, float d, float qx, float qy, float qz,
15 float qw) {
16 JPH::Quat rotation(qx, qy, qz, qw);
17 if (!isFinite(x, y, z) || !isFinite(w, h, d) || w <= 0 || h <= 0 || d <= 0 || !std::isfinite(rotation.LengthSq()) ||
18 rotation.LengthSq() < 1.e-12f)
19 return rejected<QueryVolume>("Invalid box query", eve::DiagnosticCode::InvalidArgument);
20 QueryVolume volume;
21 volume.shape = new JPH::BoxShape({w * .5f, h * .5f, d * .5f}, std::min({.05f, w * .5f, h * .5f, d * .5f}));
22 volume.transform = JPH::RMat44::sRotationTranslation(rotation.Normalized(), {x, y, z});
24}
25} // namespace
27 if (!isValid()) return rejected<int>("World expired", eve::DiagnosticCode::StaleHandle);
28 auto hits = overlapVolume(*state, volume);
29 std::vector<std::pair<int, int>> shapes;
30 std::vector<int> bodies;
31 for (const auto& hit : hits.mHits) {
32 if (!isAcceptedHit(*state, hit.mBodyID2, hit.mSubShapeID2, filter)) continue;
33 auto value = queryHit(*state, hit.mBodyID2, hit.mSubShapeID2, JPH::RVec3::sZero(), JPH::Vec3::sZero(), 0);
34 shapes.emplace_back(value.bodyId, value.shapeId);
35 bodies.push_back(value.bodyId);
36 }
37 std::sort(shapes.begin(), shapes.end());
38 shapes.erase(std::unique(shapes.begin(), shapes.end()), shapes.end());
39 std::sort(bodies.begin(), bodies.end());
40 bodies.erase(std::unique(bodies.begin(), bodies.end()), bodies.end());
41 owner->queryShapes_ = std::move(shapes);
42 owner->queryBodyIds_ = std::move(bodies);
43 return eve::Result<int>::success(static_cast<int>(owner->queryBodyIds_.size()));
44}
45eve::Result<CapsuleOverlap3D> WorldBackend::queryCapsuleOwned(float ax, float ay, float az, float bx, float by,
46 float bz, float radius, QueryFilter3D filter) {
47 auto volume = capsuleVolume(ax, ay, az, bx, by, bz, radius);
49 auto queried = overlapQuery(volume.value(), filter);
50 if (!queried) return eve::Result<CapsuleOverlap3D>::failure(queried.status());
52}
53eve::Result<int> WorldBackend::queryCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius) {
55 ax, ay, az, bx, by, bz, radius,
56 {owner->queryCategoryBits_, owner->queryMaskBits_, owner->queryIgnoredBodyId_, owner->queryIgnoredShapeId_});
57 if (!result) return eve::Result<int>::failure(result.status());
58 return eve::Result<int>::success(result.value().bodyCount);
59}
61 return queryCapsule(x, y, z, x, y, z, radius);
62}
63eve::Result<int> WorldBackend::queryBox(float x, float y, float z, float w, float h, float d, float qx, float qy,
64 float qz, float qw) {
65 auto volume = boxVolume(x, y, z, w, h, d, qx, qy, qz, qw);
66 if (!volume) return eve::Result<int>::failure(volume.status());
67 return overlapQuery(volume.value(), {owner->queryCategoryBits_, owner->queryMaskBits_, owner->queryIgnoredBodyId_,
68 owner->queryIgnoredShapeId_});
69}
70eve::Result<int> WorldBackend::castQuery(const QueryVolume& volume, float dx, float dy, float dz, int maxHits) {
71 if (!isValid()) return rejected<int>("World expired", eve::DiagnosticCode::StaleHandle);
72 if (!isFinite(dx, dy, dz) || maxHits < 1 || maxHits > 4096)
73 return rejected<int>("Invalid cast", eve::DiagnosticCode::InvalidArgument);
74 const QueryFilter3D filter{owner->queryCategoryBits_, owner->queryMaskBits_, owner->queryIgnoredBodyId_,
75 owner->queryIgnoredShapeId_};
76 auto hits = sweepVolume(*state, volume, {dx, dy, dz});
77 std::vector<World3D::ShapeCastResult> values;
78 for (const auto& hit : hits.mHits) {
79 if (!isAcceptedHit(*state, hit.mBodyID2, hit.mSubShapeID2, filter)) continue;
80 auto r =
81 queryHit(*state, hit.mBodyID2, hit.mSubShapeID2, volume.transform.GetTranslation() + hit.mContactPointOn2,
82 -hit.mPenetrationAxis.NormalizedOr(JPH::Vec3::sAxisY()), hit.mFraction);
83 values.push_back({r.bodyId, r.shapeId, r.shapeTag, r.materialId, r.triangleIndex, r.x, r.y, r.z, r.normalX,
84 r.normalY, r.normalZ, r.fraction});
85 }
86 std::sort(values.begin(), values.end(), [](const auto& a, const auto& b) {
87 return std::tie(a.fraction, a.shapeId, a.triangleIndex) < std::tie(b.fraction, b.shapeId, b.triangleIndex);
88 });
89 if (values.size() > size_t(maxHits)) values.resize(size_t(maxHits));
90 const auto first = values.empty() ? World3D::ShapeCastResult{} : values.front();
91 owner->shapeCastResults_ = std::move(values);
92 owner->shapeCastBodyId_ = first.bodyId;
93 owner->shapeCastShapeId_ = first.shapeId;
94 owner->shapeCastShapeTag_ = first.shapeTag;
95 owner->shapeCastMaterialId_ = first.materialId;
96 owner->shapeCastTriangleIndex_ = first.triangleIndex;
97 owner->shapeCastX_ = first.x;
98 owner->shapeCastY_ = first.y;
99 owner->shapeCastZ_ = first.z;
100 owner->shapeCastNormalX_ = first.normalX;
101 owner->shapeCastNormalY_ = first.normalY;
102 owner->shapeCastNormalZ_ = first.normalZ;
103 owner->shapeCastFraction_ = first.fraction;
104 return eve::Result<int>::success(static_cast<int>(owner->shapeCastResults_.size()));
105}
106eve::Result<int> WorldBackend::castCapsuleAll(float ax, float ay, float az, float bx, float by, float bz, float radius,
107 float dx, float dy, float dz, int maxHits) {
108 auto volume = capsuleVolume(ax, ay, az, bx, by, bz, radius);
109 if (!volume) return eve::Result<int>::failure(volume.status());
110 return castQuery(volume.value(), dx, dy, dz, maxHits);
111}
112eve::Result<int> WorldBackend::castSphereAll(float x, float y, float z, float radius, float dx, float dy, float dz,
113 int maxHits) {
114 return castCapsuleAll(x, y, z, x, y, z, radius, dx, dy, dz, maxHits);
115}
116eve::Result<int> WorldBackend::castBoxAll(float x, float y, float z, float w, float h, float d, float qx, float qy,
117 float qz, float qw, float dx, float dy, float dz, int maxHits) {
118 auto volume = boxVolume(x, y, z, w, h, d, qx, qy, qz, qw);
119 if (!volume) return eve::Result<int>::failure(volume.status());
120 return castQuery(volume.value(), dx, dy, dz, maxHits);
121}
122eve::Result<CameraSphereHit3D> WorldBackend::sphereCast(float x, float y, float z, float x2, float y2, float z2,
123 float radius, uint64_t mask, int ignore) const {
124 const float dx = x2 - x, dy = y2 - y, dz = z2 - z;
125 if (!isValid()) return rejected<CameraSphereHit3D>("World expired", eve::DiagnosticCode::StaleHandle);
126 if (!isFinite(dx, dy, dz))
127 return rejected<CameraSphereHit3D>("Invalid sweep", eve::DiagnosticCode::InvalidArgument);
128 if (radius == 0) {
129 if (!isFinite(x, y, z)) return rejected<CameraSphereHit3D>("Invalid ray", eve::DiagnosticCode::InvalidArgument);
130 const JPH::RRayCast ray({x, y, z}, {dx, dy, dz});
131 JPH::AllHitCollisionCollector<JPH::CastRayCollector> hits;
132 state->system.GetNarrowPhaseQuery().CastRay(ray, JPH::RayCastSettings(), hits);
133 hits.Sort();
135 for (const auto& hit : hits.mHits) {
136 const auto* native = state->system.GetBodyLockInterfaceNoLock().TryGetBody(hit.mBodyID);
137 if (!native) continue;
138 const auto* shape = child(*native, hit.mSubShapeID2);
139 if (!shape || !shape->owner || shape->sensor || !(shape->filter.categoryBits & mask)) continue;
140 auto body = shape->body.lock();
141 if (!body || !body->owner || body->owner->getId() == ignore) continue;
142 auto point = ray.GetPointOnRay(hit.mFraction);
143 auto normal = native->GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, point);
144 result = {true,
145 body->owner->getId(),
146 hit.mFraction,
147 float(point.GetX()),
148 float(point.GetY()),
149 float(point.GetZ()),
150 normal.GetX(),
151 normal.GetY(),
152 normal.GetZ()};
153 break;
154 }
156 }
157 auto volume = capsuleVolume(x, y, z, x, y, z, radius);
159 auto hits = sweepVolume(*state, volume.value(), {dx, dy, dz});
161 for (const auto& hit : hits.mHits) {
162 const auto* native = state->system.GetBodyLockInterfaceNoLock().TryGetBody(hit.mBodyID2);
163 if (!native) continue;
164 const auto* shape = child(*native, hit.mSubShapeID2);
165 if (!shape || !shape->owner || shape->sensor || !(shape->filter.categoryBits & mask)) continue;
166 auto body = shape->body.lock();
167 if (!body || !body->owner || body->owner->getId() == ignore) continue;
168 auto normal = -hit.mPenetrationAxis.NormalizedOr(JPH::Vec3::sAxisY());
169 auto point = volume.value().transform.GetTranslation() + hit.mContactPointOn2;
170 result = {true,
171 body->owner->getId(),
172 hit.mFraction,
173 float(point.GetX()),
174 float(point.GetY()),
175 float(point.GetZ()),
176 normal.GetX(),
177 normal.GetY(),
178 normal.GetZ()};
179 break;
180 }
182}
183} // namespace eve::physics::jolt
double z
double y
double x
float w
Definition AnimClip.cpp:738
double volume
int mask
ShaderImageInput shape
double r
std::int32_t first
int h
std::array< float, 4 > rotation
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
glm::dvec3 dx
glm::dvec3 dz
bool hit
std::set< std::string > values
std::string body
Object::Ptr value
float d
std::string filter
float dy
Definition Shadow.cpp:151
glm::vec3 point
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
PhysicsWorldHandle runtimeHandle() const noexcept
Process-local identity used by PhysicsLink; invalid after destruction.
Definition World3D.h:136
eve::Result< int > castCapsuleAll(float ax, float ay, float az, float bx, float by, float bz, float radius, float dx, float dy, float dz, int maxHits) override
castCapsuleAll; uses the class ownership, thread and failure contract.
eve::Result< CapsuleOverlap3D > queryCapsuleOwned(float ax, float ay, float az, float bx, float by, float bz, float radius, QueryFilter3D filter) override
queryCapsuleOwned; uses the class ownership, thread and failure contract.
eve::Result< int > overlapQuery(const QueryVolume &, QueryFilter3D)
Internal synchronous projection of an ephemeral cooked query volume.
eve::Result< int > castQuery(const QueryVolume &, float, float, float, int)
Internal synchronous sweep; owning native data is projected into facade caches.
std::shared_ptr< State > state
Definition JoltWorld.h:17
eve::Result< int > castBoxAll(float x, float y, float z, float width, float height, float depth, float qx, float qy, float qz, float qw, float dx, float dy, float dz, int maxHits) override
castBoxAll; uses the class ownership, thread and failure contract.
eve::Result< int > queryBox(float x, float y, float z, float width, float height, float depth, float qx, float qy, float qz, float qw) override
queryBox; uses the class ownership, thread and failure contract.
eve::Result< int > querySphere(float x, float y, float z, float radius) override
querySphere; uses the class ownership, thread and failure contract.
bool isValid() const noexcept override
Native world liveness.
Definition JoltWorld.cpp:90
eve::Result< int > castSphereAll(float x, float y, float z, float radius, float dx, float dy, float dz, int maxHits) override
castSphereAll; uses the class ownership, thread and failure contract.
eve::Result< CameraSphereHit3D > sphereCast(float x1, float y1, float z1, float x2, float y2, float z2, float radius, uint64_t maskBits, int ignoredBodyId) const override
sphereCast; uses the class ownership, thread and failure contract.
eve::Result< int > queryCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius) override
queryCapsule; uses the class ownership, thread and failure contract.
JPH::AllHitCollisionCollector< JPH::CollideShapeCollector > overlapVolume(const State &state, const QueryVolume &volume, float separation)
Collects owning native records for this synchronous query; no pointers escape.
bool isAcceptedHit(const State &state, JPH::BodyID id, const JPH::SubShapeID &sub, QueryFilter3D filter)
Filters a synchronous native hit, borrowing state only for the call.
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
RayHit3D queryHit(const State &state, JPH::BodyID id, const JPH::SubShapeID &sub, JPH::RVec3Arg point, JPH::Vec3Arg normal, float fraction)
Projects a validated native hit into an owning result on the idle simulation thread.
bool isFinite(float x, float y, float z)
eve::Result< QueryVolume > capsuleVolume(float ax, float ay, float az, float bx, float by, float bz, float radius)
Cooks an ephemeral query capsule; inputs are endpoints in world space.
JPH::AllHitCollisionCollector< JPH::CastShapeCollector > sweepVolume(const State &state, const QueryVolume &volume, JPH::Vec3Arg delta)
Sweeps one ephemeral convex volume; results are local to its starting position.
CameraSphereHit3D public API.
Definition World3DTypes.h:5
Query filter applied atomically for one owning query operation.