载入中...
搜索中...
未找到
Box3DWorldQueries.cpp
浏览该文件的文档.
1// eve-hot-path
2#include <algorithm>
3#include <cfloat>
4#include <cmath>
5#include <utility>
6#include "physics/Joint3D.h"
11namespace eve::physics::box3d {
12using namespace world3d_detail;
13
14namespace {
15int sourceTriangleIndex(b3ShapeId shapeId, int backendIndex) {
16 const b3ShapeType type = b3Shape_GetType(shapeId);
17 return type == b3_meshShape || type == b3_heightShape ? backendIndex : -1;
18}
19} // namespace
20
21bool WorldBackend::do_sphereCast(float x1, float y1, float z1, float x2, float y2, float z2, float radius,
22 uint64_t maskBits, int ignoredBodyId, CameraSphereHit3D *out) const {
23 if (out) *out = CameraSphereHit3D{};
24 if (!out || !isValid() || radius < 0.f) return false;
25
26 struct Collector {
27 CameraSphereHit3D *out = nullptr;
28 int ignoredBodyId = -1;
29 static float callback(b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t, int, int,
30 void *context) {
31 auto *self = static_cast<Collector *>(context);
32 Body3D *body = bodyFromShape(shapeId);
33 if (!body || body->getId() == self->ignoredBodyId) return -1.f;
34 if (!self->out->hit || fraction < self->out->fraction) {
35 self->out->hit = true;
36 self->out->bodyId = body->getId();
37 self->out->fraction = fraction;
38 self->out->x = static_cast<float>(point.x);
39 self->out->y = static_cast<float>(point.y);
40 self->out->z = static_cast<float>(point.z);
41 self->out->nx = normal.x;
42 self->out->ny = normal.y;
43 self->out->nz = normal.z;
44 }
45 return fraction;
46 }
47 } collector{out, ignoredBodyId};
48
49 const b3Vec3 point{0.f, 0.f, 0.f};
50 const b3ShapeProxy proxy{&point, 1, radius};
51 b3QueryFilter filter = b3DefaultQueryFilter();
52 filter.maskBits = maskBits;
53 b3World_CastShape(worldId_, b3Pos{x1, y1, z1}, &proxy, b3Vec3{x2 - x1, y2 - y1, z2 - z1}, filter,
54 &Collector::callback, &collector);
55 return out->hit;
56}
57
58eve::Result<CameraSphereHit3D> WorldBackend::sphereCast(float x1, float y1, float z1, float x2, float y2, float z2,
59 float radius, uint64_t maskBits, int ignoredBodyId) const {
60 return checked("physics.world3d.sphereCast", [&] {
62 do_sphereCast(x1, y1, z1, x2, y2, z2, radius, maskBits, ignoredBodyId, &hit);
64 });
65}
66
67int WorldBackend::do_rayCastFiltered(float x1, float y1, float z1, float x2, float y2, float z2, uint64_t maskBits) {
68 b3QueryFilter filter = b3DefaultQueryFilter();
69 filter.maskBits = maskBits;
70 do_rayCastAllInternal(x1, y1, z1, x2, y2, z2, 1, filter);
71 return owner_->rayHitBodyId_;
72}
73
74eve::Result<int> WorldBackend::rayCastFiltered(float x1, float y1, float z1, float x2, float y2, float z2,
75 uint64_t maskBits) {
76 return checked("physics.world3d.rayCastFiltered",
77 [&] { return eve::Result<int>::success(do_rayCastFiltered(x1, y1, z1, x2, y2, z2, maskBits)); });
78}
79
80eve::Result<RayHit3D> WorldBackend::do_rayCastOwned(float x1, float y1, float z1, float x2, float y2, float z2,
82 if (!isValid())
83 return ownedQueryFailure<RayHit3D>(eve::DiagnosticCode::StaleHandle, "physics world is no longer valid",
84 "world");
85 try {
86 ScopedQueryState3D queryState(*owner_, filter);
88 result.world = owner_->runtimeHandle_;
89 if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(z1) || !std::isfinite(x2) ||
90 !std::isfinite(y2) || !std::isfinite(z2))
91 return ownedQueryFailure<RayHit3D>(eve::DiagnosticCode::InvalidArgument, "ray endpoints must be finite",
92 "ray");
93 struct Collector {
94 WorldBackend *world = nullptr;
95 RayHit3D *result = nullptr;
96 static float callback(b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t materialId,
97 int triangleIndex, int, void *context) {
98 auto *self = static_cast<Collector *>(context);
99 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return -1.f;
102 if (!body || !shape || !body->isValid() || !shape->isValid()) return -1.f;
103 RayHit3D candidate;
104 candidate.hit = true;
105 candidate.world = self->result->world;
106 candidate.body = body->runtimeHandle();
107 candidate.shape = shape->runtimeHandle();
108 candidate.bodyId = body->getId();
109 candidate.shapeId = shape->getId();
110 candidate.shapeTag = shape->getTag();
111 candidate.materialId = static_cast<int>(static_cast<std::uint32_t>(materialId));
112 candidate.triangleIndex = sourceTriangleIndex(shapeId, triangleIndex);
113 candidate.x = static_cast<float>(point.x);
114 candidate.y = static_cast<float>(point.y);
115 candidate.z = static_cast<float>(point.z);
116 candidate.normalX = normal.x;
117 candidate.normalY = normal.y;
118 candidate.normalZ = normal.z;
119 candidate.fraction = fraction;
120 if (!self->result->hit || fraction < self->result->fraction ||
121 (fraction == self->result->fraction && candidate.shapeId < self->result->shapeId))
122 *self->result = candidate;
123 return self->result->fraction;
124 }
125 } collector{this, &result};
126 b3World_CastRay(worldId_, b3Pos{x1, y1, z1}, b3Vec3{x2 - x1, y2 - y1, z2 - z1}, do_makeQueryFilter(),
127 &Collector::callback, &collector);
128 if (!result.hit) return eve::Result<RayHit3D>::success(std::move(result));
129 if (result.body.isInvalid() || result.shape.isInvalid())
130 return ownedQueryFailure<RayHit3D>(eve::DiagnosticCode::InvariantViolation,
131 "ray hit could not be mapped to live generation-qualified handles",
132 "hit");
133 return eve::Result<RayHit3D>::success(std::move(result));
134 } catch (const std::exception &error) {
135 return ownedQueryFailure<RayHit3D>(eve::DiagnosticCode::InvalidArgument, error.what(), "ray");
136 }
137}
138
139eve::Result<RayHit3D> WorldBackend::rayCastOwned(float x1, float y1, float z1, float x2, float y2, float z2,
141 return do_rayCastOwned(x1, y1, z1, x2, y2, z2, filter);
142}
143
144int WorldBackend::do_rayCastAll(float x1, float y1, float z1, float x2, float y2, float z2, int maxHits) {
145 return do_rayCastAllInternal(x1, y1, z1, x2, y2, z2, maxHits, do_makeQueryFilter());
146}
147
148eve::Result<int> WorldBackend::rayCastAll(float x1, float y1, float z1, float x2, float y2, float z2, int maxHits) {
149 return checked("physics.world3d.rayCastAll",
150 [&] { return eve::Result<int>::success(do_rayCastAll(x1, y1, z1, x2, y2, z2, maxHits)); });
151}
152
153int WorldBackend::do_rayCastAllInternal(float x1, float y1, float z1, float x2, float y2, float z2, int maxHits,
154 b3QueryFilter filter) {
155 owner_->rayHitBodyId_ = -1;
156 owner_->rayHitShapeId_ = -1;
157 owner_->rayHitShapeTag_ = 0;
158 owner_->rayHitMaterialId_ = 0;
159 owner_->rayHitTriangleIndex_ = -1;
160 owner_->rayHitX_ = 0.f;
161 owner_->rayHitY_ = 0.f;
162 owner_->rayHitZ_ = 0.f;
163 owner_->rayHitNormalX_ = 0.f;
164 owner_->rayHitNormalY_ = 0.f;
165 owner_->rayHitNormalZ_ = 0.f;
166 owner_->rayHitFraction_ = 0.f;
167 owner_->rayResults_.clear();
168 if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(z1) || !std::isfinite(x2) || !std::isfinite(y2) ||
169 !std::isfinite(z2))
170 throw eve::Exception("World3D.rayCastAll: endpoints must be finite");
171 constexpr int maxRayResults = 4096;
172 if (maxHits < 1 || maxHits > maxRayResults)
173 throw eve::Exception("World3D.rayCastAll: maxHits must be in [1, 4096]");
174 if (!isValid()) return 0;
175
176 b3Pos origin{x1, y1, z1};
177 b3Vec3 translation{x2 - x1, y2 - y1, z2 - z1};
178 struct RayCollector {
179 WorldBackend *world = nullptr;
180 int capacity = 0;
181
182 static bool better(const RayResult &a, const RayResult &b) {
183 return a.fraction < b.fraction || (a.fraction == b.fraction && a.shapeId < b.shapeId);
184 }
185
186 float clipFraction() const {
187 if (static_cast<int>(world->owner_->rayResults_.size()) < capacity) return 1.f;
188 const auto worst =
189 std::max_element(world->owner_->rayResults_.begin(), world->owner_->rayResults_.end(), better);
190 return worst->fraction;
191 }
192
193 static float callback(b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t materialId,
194 int triangleIndex, int, void *context) {
195 auto *self = static_cast<RayCollector *>(context);
196 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return -1.f;
197 Body3D *body = bodyFromShape(shapeId);
198 Shape3D *shape = shapeFromShape(shapeId);
199 if (!body || !shape) return -1.f;
200
201 RayResult candidate{body->getId(),
202 shape->getId(),
203 shape->getTag(),
204 static_cast<int>(static_cast<uint32_t>(materialId)),
205 sourceTriangleIndex(shapeId, triangleIndex),
206 static_cast<float>(point.x),
207 static_cast<float>(point.y),
208 static_cast<float>(point.z),
209 normal.x,
210 normal.y,
211 normal.z,
212 fraction};
213 auto &results = self->world->owner_->rayResults_;
214 if (static_cast<int>(results.size()) < self->capacity) {
215 results.push_back(candidate);
216 } else {
217 auto worst = std::max_element(results.begin(), results.end(), better);
218 if (better(candidate, *worst)) *worst = candidate;
219 }
220 return self->clipFraction();
221 }
222 } collector{this, maxHits};
223 owner_->rayResults_.reserve(static_cast<size_t>(maxHits));
224 b3World_CastRay(worldId_, origin, translation, filter, &RayCollector::callback, &collector);
225 std::sort(owner_->rayResults_.begin(), owner_->rayResults_.end(), RayCollector::better);
226 if (!owner_->rayResults_.empty()) {
227 const RayResult &hit = owner_->rayResults_.front();
228 owner_->rayHitBodyId_ = hit.bodyId;
229 owner_->rayHitShapeId_ = hit.shapeId;
230 owner_->rayHitShapeTag_ = hit.shapeTag;
231 owner_->rayHitMaterialId_ = hit.materialId;
232 owner_->rayHitTriangleIndex_ = hit.triangleIndex;
233 owner_->rayHitX_ = hit.x;
234 owner_->rayHitY_ = hit.y;
235 owner_->rayHitZ_ = hit.z;
236 owner_->rayHitNormalX_ = hit.normalX;
237 owner_->rayHitNormalY_ = hit.normalY;
238 owner_->rayHitNormalZ_ = hit.normalZ;
239 owner_->rayHitFraction_ = hit.fraction;
240 }
241 return static_cast<int>(owner_->rayResults_.size());
242}
243
244int WorldBackend::do_queryAABB(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
245 owner_->queryBodyIds_.clear();
246 owner_->queryShapes_.clear();
247 if (!isValid()) return 0;
248
249 struct Collector {
250 WorldBackend *world = nullptr;
251 std::vector<int> *bodyIds = nullptr;
252 std::vector<std::pair<int, int>> *shapes = nullptr;
253 std::unordered_set<int> seen;
254
255 static bool callback(b3ShapeId shapeId, void *context) {
256 auto *self = static_cast<Collector *>(context);
257 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return true;
258 Body3D *b = bodyFromShape(shapeId);
259 Shape3D *shape = shapeFromShape(shapeId);
260 if (!b || !shape) return true;
261 int id = b->getId();
262 if (self->seen.insert(id).second) self->bodyIds->push_back(id);
263 self->shapes->emplace_back(shape->getId(), shape->getTag());
264 return true;
265 }
266 } cb;
267 cb.world = this;
268 cb.bodyIds = &owner_->queryBodyIds_;
269 cb.shapes = &owner_->queryShapes_;
270
271 b3AABB aabb;
272 aabb.lowerBound = b3Vec3{std::min(minX, maxX), std::min(minY, maxY), std::min(minZ, maxZ)};
273 aabb.upperBound = b3Vec3{std::max(minX, maxX), std::max(minY, maxY), std::max(minZ, maxZ)};
274 b3QueryFilter filter = do_makeQueryFilter();
275 b3World_OverlapAABB(worldId_, aabb, filter, &Collector::callback, &cb);
276 std::sort(owner_->queryBodyIds_.begin(), owner_->queryBodyIds_.end());
277 std::sort(owner_->queryShapes_.begin(), owner_->queryShapes_.end());
278 return static_cast<int>(owner_->queryBodyIds_.size());
279}
280
281eve::Result<int> WorldBackend::queryAABB(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
282 return checked("physics.world3d.queryAABB",
283 [&] { return eve::Result<int>::success(do_queryAABB(minX, minY, minZ, maxX, maxY, maxZ)); });
284}
285
286eve::Result<BroadPhaseAabb3D> WorldBackend::do_queryAabbBroadPhaseOwned(float minX, float minY, float minZ, float maxX,
287 float maxY, float maxZ, QueryFilter3D filter) {
288 if (!isValid())
289 return ownedQueryFailure<BroadPhaseAabb3D>(eve::DiagnosticCode::StaleHandle, "physics world is no longer valid",
290 "world");
291 if (!std::isfinite(minX) || !std::isfinite(minY) || !std::isfinite(minZ) || !std::isfinite(maxX) ||
292 !std::isfinite(maxY) || !std::isfinite(maxZ))
293 return ownedQueryFailure<BroadPhaseAabb3D>(eve::DiagnosticCode::InvalidArgument,
294 "broad-phase AABB must be finite", "aabb");
295 try {
296 ScopedQueryState3D queryState(*owner_, filter);
298 struct Collector {
299 WorldBackend *world = nullptr;
300 BroadPhaseAabb3D *result = nullptr;
301
302 static bool less(const BroadPhaseHit3D &lhs, const BroadPhaseHit3D &rhs) noexcept {
303 return lhs.bodyId != rhs.bodyId ? lhs.bodyId < rhs.bodyId : lhs.shapeId < rhs.shapeId;
304 }
305
306 static bool callback(b3ShapeId shapeId, void *context) {
307 auto *self = static_cast<Collector *>(context);
308 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return true;
311 if (!body || !shape || !body->isValid() || !shape->isValid()) return true;
312 BroadPhaseHit3D hit{body->runtimeHandle(), shape->runtimeHandle(), body->getId(),
313 shape->getId(), shape->getTag(), shape->getMaterialId()};
314 auto &output = *self->result;
315 if (output.count < BroadPhaseAabb3D::Capacity) {
316 output.hits[output.count++] = hit;
317 } else {
318 output.truncated = true;
319 auto worst = std::max_element(output.hits.begin(), output.hits.end(), less);
320 if (less(hit, *worst)) *worst = hit;
321 }
322 return true;
323 }
324 } collector{this, &result};
325 b3AABB bounds;
326 bounds.lowerBound = {std::min(minX, maxX), std::min(minY, maxY), std::min(minZ, maxZ)};
327 bounds.upperBound = {std::max(minX, maxX), std::max(minY, maxY), std::max(minZ, maxZ)};
328 b3World_OverlapAABB(worldId_, bounds, do_makeQueryFilter(), &Collector::callback, &collector);
329 std::sort(result.hits.begin(), result.hits.begin() + static_cast<std::ptrdiff_t>(result.count),
330 Collector::less);
332 } catch (const std::exception &error) {
333 return ownedQueryFailure<BroadPhaseAabb3D>(eve::DiagnosticCode::InvalidArgument, error.what(), "aabb");
334 }
335}
336
337eve::Result<BroadPhaseAabb3D> WorldBackend::queryAabbBroadPhaseOwned(float minX, float minY, float minZ, float maxX,
338 float maxY, float maxZ, QueryFilter3D filter) {
339 return do_queryAabbBroadPhaseOwned(minX, minY, minZ, maxX, maxY, maxZ, filter);
340}
341
342int WorldBackend::do_overlapProxy(b3Pos origin, const b3ShapeProxy &proxy) {
343 owner_->queryBodyIds_.clear();
344 owner_->queryShapes_.clear();
345 if (!isValid()) return 0;
346
347 struct Collector {
348 WorldBackend *world = nullptr;
349 std::vector<int> *bodyIds = nullptr;
350 std::vector<std::pair<int, int>> *shapes = nullptr;
351 std::unordered_set<int> seen;
352
353 static bool callback(b3ShapeId shapeId, void *context) {
354 auto *self = static_cast<Collector *>(context);
355 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return true;
358 if (body && shape) {
359 if (self->seen.insert(body->getId()).second) self->bodyIds->push_back(body->getId());
360 self->shapes->emplace_back(shape->getId(), shape->getTag());
361 }
362 return true;
363 }
364 } collector;
365 collector.world = this;
366 collector.bodyIds = &owner_->queryBodyIds_;
367 collector.shapes = &owner_->queryShapes_;
368 b3QueryFilter filter = do_makeQueryFilter();
369 b3World_OverlapShape(worldId_, origin, &proxy, filter, &Collector::callback, &collector);
370 // Broad-phase traversal order is unspecified; stable ids make script behavior deterministic.
371 std::sort(owner_->queryBodyIds_.begin(), owner_->queryBodyIds_.end());
372 std::sort(owner_->queryShapes_.begin(), owner_->queryShapes_.end());
373 return static_cast<int>(owner_->queryBodyIds_.size());
374}
375
376int WorldBackend::do_querySphere(float x, float y, float z, float radius) {
377 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || !(radius >= 0.f) || !std::isfinite(radius))
378 throw eve::Exception("World3D.querySphere: coordinates and radius must be finite; radius >= 0");
379 const b3Vec3 point = b3Vec3_zero;
380 const b3ShapeProxy proxy{&point, 1, radius};
381 return do_overlapProxy(b3Pos{x, y, z}, proxy);
382}
383
385 return checked("physics.world3d.querySphere",
386 [&] { return eve::Result<int>::success(do_querySphere(x, y, z, radius)); });
387}
388
389int WorldBackend::do_queryCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius) {
390 if (!std::isfinite(ax) || !std::isfinite(ay) || !std::isfinite(az) || !std::isfinite(bx) || !std::isfinite(by) ||
391 !std::isfinite(bz) || !(radius >= 0.f) || !std::isfinite(radius))
392 throw eve::Exception("World3D.queryCapsule: coordinates and radius must be finite; radius >= 0");
393 // Relative points preserve Box3D's large-world precision.
394 const b3Vec3 points[2] = {b3Vec3_zero, b3Vec3{bx - ax, by - ay, bz - az}};
395 const b3ShapeProxy proxy{points, 2, radius};
396 return do_overlapProxy(b3Pos{ax, ay, az}, proxy);
397}
398
399eve::Result<int> WorldBackend::queryCapsule(float ax, float ay, float az, float bx, float by, float bz, float radius) {
400 return checked("physics.world3d.queryCapsule",
401 [&] { return eve::Result<int>::success(do_queryCapsule(ax, ay, az, bx, by, bz, radius)); });
402}
403
404eve::Result<CapsuleOverlap3D> WorldBackend::do_queryCapsuleOwned(float ax, float ay, float az, float bx, float by,
405 float bz, float radius, QueryFilter3D filter) {
406 if (!isValid())
407 return ownedQueryFailure<CapsuleOverlap3D>(eve::DiagnosticCode::StaleHandle, "physics world is no longer valid",
408 "world");
409 try {
410 ScopedQueryState3D queryState(*owner_, filter);
411 if (!std::isfinite(ax) || !std::isfinite(ay) || !std::isfinite(az) || !std::isfinite(bx) ||
412 !std::isfinite(by) || !std::isfinite(bz) || !std::isfinite(radius) || radius < 0.f)
413 return ownedQueryFailure<CapsuleOverlap3D>(eve::DiagnosticCode::InvalidArgument,
414 "capsule coordinates and radius are invalid", "capsule");
416 result.world = owner_->runtimeHandle_;
417 struct Collector {
418 WorldBackend *world = nullptr;
419 std::array<int, 256> bodyIds{};
420 std::size_t count = 0;
421 static bool callback(b3ShapeId shapeId, void *context) {
422 auto *self = static_cast<Collector *>(context);
423 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return true;
425 if (!body || !body->isValid()) return true;
426 const int bodyId = body->getId();
427 if (std::find(self->bodyIds.begin(), self->bodyIds.begin() + static_cast<std::ptrdiff_t>(self->count),
428 bodyId) != self->bodyIds.begin() + static_cast<std::ptrdiff_t>(self->count))
429 return true;
430 if (self->count < self->bodyIds.size()) self->bodyIds[self->count++] = bodyId;
431 return true;
432 }
433 } collector{this};
434 const b3Vec3 points[2] = {b3Vec3_zero, b3Vec3{bx - ax, by - ay, bz - az}};
435 const b3ShapeProxy proxy{points, 2, radius};
436 b3World_OverlapShape(worldId_, b3Pos{ax, ay, az}, &proxy, do_makeQueryFilter(), &Collector::callback,
437 &collector);
438 result.bodyCount = static_cast<int>(collector.count);
440 } catch (const std::exception &error) {
441 return ownedQueryFailure<CapsuleOverlap3D>(eve::DiagnosticCode::InvalidArgument, error.what(), "capsule");
442 }
443}
444
445eve::Result<CapsuleOverlap3D> WorldBackend::queryCapsuleOwned(float ax, float ay, float az, float bx, float by,
446 float bz, float radius, QueryFilter3D filter) {
447 return do_queryCapsuleOwned(ax, ay, az, bx, by, bz, radius, filter);
448}
449
450int WorldBackend::do_queryBox(float x, float y, float z, float width, float height, float depth, float qx, float qy,
451 float qz, float qw) {
452 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
453 throw eve::Exception("World3D.queryBox: center must be finite");
454 const b3Quat rotation = normalizedQueryQuat(qx, qy, qz, qw, "World3D.queryBox");
455 b3Vec3 points[8];
456 makeBoxProxyPoints(points, width, height, depth, rotation, "World3D.queryBox");
457 const b3ShapeProxy proxy{points, 8, 0.f};
458 return do_overlapProxy(b3Pos{x, y, z}, proxy);
459}
460
461eve::Result<int> WorldBackend::queryBox(float x, float y, float z, float width, float height, float depth, float qx,
462 float qy, float qz, float qw) {
463 return checked("physics.world3d.queryBox", [&] {
464 return eve::Result<int>::success(do_queryBox(x, y, z, width, height, depth, qx, qy, qz, qw));
465 });
466}
467
468int WorldBackend::do_castProxyAll(b3Pos origin, const b3ShapeProxy &proxy, b3Vec3 translation, int maxHits) {
469 owner_->shapeCastBodyId_ = -1;
470 owner_->shapeCastShapeId_ = -1;
471 owner_->shapeCastShapeTag_ = 0;
472 owner_->shapeCastMaterialId_ = 0;
473 owner_->shapeCastTriangleIndex_ = -1;
474 owner_->shapeCastX_ = owner_->shapeCastY_ = owner_->shapeCastZ_ = 0.f;
475 owner_->shapeCastNormalX_ = owner_->shapeCastNormalY_ = owner_->shapeCastNormalZ_ = 0.f;
476 owner_->shapeCastFraction_ = 0.f;
477 owner_->shapeCastResults_.clear();
478 constexpr int maxShapeCastResults = 4096;
479 if (maxHits < 1 || maxHits > maxShapeCastResults)
480 throw eve::Exception("World3D Shape Cast: maxHits must be in [1, 4096]");
481 if (!isValid()) return 0;
482
483 struct CastCollector {
484 WorldBackend *world = nullptr;
485 int capacity = 0;
486
487 static bool better(const ShapeCastResult &a, const ShapeCastResult &b) {
488 return a.fraction < b.fraction || (a.fraction == b.fraction && a.shapeId < b.shapeId);
489 }
490
491 float clipFraction() const {
492 if (static_cast<int>(world->owner_->shapeCastResults_.size()) < capacity) return 1.f;
493 const auto worst = std::max_element(world->owner_->shapeCastResults_.begin(),
494 world->owner_->shapeCastResults_.end(), better);
495 return worst->fraction;
496 }
497
498 static float callback(b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t materialId,
499 int triangleIndex, int, void *context) {
500 auto *self = static_cast<CastCollector *>(context);
501 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return -1.f;
502 Body3D *body = bodyFromShape(shapeId);
503 Shape3D *shape = shapeFromShape(shapeId);
504 if (!body || !shape) return -1.f;
505
506 ShapeCastResult candidate{body->getId(),
507 shape->getId(),
508 shape->getTag(),
509 static_cast<int>(static_cast<uint32_t>(materialId)),
510 sourceTriangleIndex(shapeId, triangleIndex),
511 static_cast<float>(point.x),
512 static_cast<float>(point.y),
513 static_cast<float>(point.z),
514 normal.x,
515 normal.y,
516 normal.z,
517 fraction};
518 auto &results = self->world->owner_->shapeCastResults_;
519 if (static_cast<int>(results.size()) < self->capacity) {
520 results.push_back(candidate);
521 } else {
522 auto worst = std::max_element(results.begin(), results.end(), better);
523 if (better(candidate, *worst)) *worst = candidate;
524 }
525 return self->clipFraction();
526 }
527 } collector{this, maxHits};
528 owner_->shapeCastResults_.reserve(static_cast<size_t>(maxHits));
529 b3QueryFilter filter = do_makeQueryFilter();
530 b3World_CastShape(worldId_, origin, &proxy, translation, filter, &CastCollector::callback, &collector);
531 std::sort(owner_->shapeCastResults_.begin(), owner_->shapeCastResults_.end(), CastCollector::better);
532 if (!owner_->shapeCastResults_.empty()) {
533 const ShapeCastResult &hit = owner_->shapeCastResults_.front();
534 owner_->shapeCastBodyId_ = hit.bodyId;
535 owner_->shapeCastShapeId_ = hit.shapeId;
536 owner_->shapeCastShapeTag_ = hit.shapeTag;
537 owner_->shapeCastMaterialId_ = hit.materialId;
538 owner_->shapeCastTriangleIndex_ = hit.triangleIndex;
539 owner_->shapeCastX_ = hit.x;
540 owner_->shapeCastY_ = hit.y;
541 owner_->shapeCastZ_ = hit.z;
542 owner_->shapeCastNormalX_ = hit.normalX;
543 owner_->shapeCastNormalY_ = hit.normalY;
544 owner_->shapeCastNormalZ_ = hit.normalZ;
545 owner_->shapeCastFraction_ = hit.fraction;
546 }
547 return static_cast<int>(owner_->shapeCastResults_.size());
548}
549
550int WorldBackend::do_castSphereAll(float x, float y, float z, float radius, float dx, float dy, float dz, int maxHits) {
551 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || !(radius >= 0.f) || !std::isfinite(radius) ||
552 !std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dz))
553 throw eve::Exception("World3D.castSphere: all values must be finite; radius >= 0");
554 const b3Vec3 point = b3Vec3_zero;
555 const b3ShapeProxy proxy{&point, 1, radius};
556 return do_castProxyAll(b3Pos{x, y, z}, proxy, b3Vec3{dx, dy, dz}, maxHits);
557}
558
559eve::Result<int> WorldBackend::castSphereAll(float x, float y, float z, float radius, float dx, float dy, float dz,
560 int maxHits) {
561 return checked("physics.world3d.castSphereAll",
562 [&] { return eve::Result<int>::success(do_castSphereAll(x, y, z, radius, dx, dy, dz, maxHits)); });
563}
564
565int WorldBackend::do_castCapsuleAll(float ax, float ay, float az, float bx, float by, float bz, float radius, float dx,
566 float dy, float dz, int maxHits) {
567 if (!std::isfinite(ax) || !std::isfinite(ay) || !std::isfinite(az) || !std::isfinite(bx) || !std::isfinite(by) ||
568 !std::isfinite(bz) || !(radius >= 0.f) || !std::isfinite(radius) || !std::isfinite(dx) || !std::isfinite(dy) ||
569 !std::isfinite(dz))
570 throw eve::Exception("World3D.castCapsule: all values must be finite; radius >= 0");
571 const b3Vec3 points[2] = {b3Vec3_zero, b3Vec3{bx - ax, by - ay, bz - az}};
572 const b3ShapeProxy proxy{points, 2, radius};
573 return do_castProxyAll(b3Pos{ax, ay, az}, proxy, b3Vec3{dx, dy, dz}, maxHits);
574}
575
576eve::Result<int> WorldBackend::castCapsuleAll(float ax, float ay, float az, float bx, float by, float bz, float radius,
577 float dx, float dy, float dz, int maxHits) {
578 return checked("physics.world3d.castCapsuleAll", [&] {
579 return eve::Result<int>::success(do_castCapsuleAll(ax, ay, az, bx, by, bz, radius, dx, dy, dz, maxHits));
580 });
581}
582
583int WorldBackend::do_castBoxAll(float x, float y, float z, float width, float height, float depth, float qx, float qy,
584 float qz, float qw, float dx, float dy, float dz, int maxHits) {
585 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || !std::isfinite(dx) || !std::isfinite(dy) ||
586 !std::isfinite(dz))
587 throw eve::Exception("World3D.castBox: center and translation must be finite");
588 const b3Quat rotation = normalizedQueryQuat(qx, qy, qz, qw, "World3D.castBox");
589 b3Vec3 points[8];
590 makeBoxProxyPoints(points, width, height, depth, rotation, "World3D.castBox");
591 const b3ShapeProxy proxy{points, 8, 0.f};
592 return do_castProxyAll(b3Pos{x, y, z}, proxy, b3Vec3{dx, dy, dz}, maxHits);
593}
594
595eve::Result<int> WorldBackend::castBoxAll(float x, float y, float z, float width, float height, float depth, float qx,
596 float qy, float qz, float qw, float dx, float dy, float dz, int maxHits) {
597 return checked("physics.world3d.castBoxAll", [&] {
599 do_castBoxAll(x, y, z, width, height, depth, qx, qy, qz, qw, dx, dy, dz, maxHits));
600 });
601}
602
603int WorldBackend::do_closestPoint(float x, float y, float z, float maxDistance) {
604 owner_->closestBodyId_ = -1;
605 owner_->closestShapeId_ = -1;
606 owner_->closestShapeTag_ = 0;
607 owner_->closestX_ = owner_->closestY_ = owner_->closestZ_ = 0.f;
608 owner_->closestNormalX_ = owner_->closestNormalY_ = owner_->closestNormalZ_ = 0.f;
609 owner_->closestDistance_ = 0.f;
610 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || !(maxDistance >= 0.f) ||
611 !std::isfinite(maxDistance))
612 throw eve::Exception("World3D.closestPoint: target must be finite; maxDistance finite and >= 0");
613 constexpr double floatLimit = static_cast<double>(FLT_MAX);
614 const double distance = static_cast<double>(maxDistance);
615 if (distance * distance > floatLimit || std::fabs(static_cast<double>(x)) + distance > floatLimit ||
616 std::fabs(static_cast<double>(y)) + distance > floatLimit ||
617 std::fabs(static_cast<double>(z)) + distance > floatLimit)
618 throw eve::Exception("World3D.closestPoint: search bounds are too large");
619 if (!isValid()) return -1;
620
621 struct ClosestCollector {
622 WorldBackend *world = nullptr;
623 b3Vec3 target = b3Vec3_zero;
624 float bestDistanceSquared = 0.f;
625 int bodyId = -1;
626 int stableShapeId = -1;
627 int shapeTag = 0;
628 b3Vec3 point = b3Vec3_zero;
629
630 static bool callback(b3ShapeId shapeId, void *context) {
631 auto *self = static_cast<ClosestCollector *>(context);
632 if (self->world->do_shouldIgnoreQueryShape(shapeId)) return true;
635 if (!body || !shape) return true;
636 const b3Vec3 point = b3Shape_GetClosestPoint(shapeId, self->target);
637 const b3Vec3 delta = self->target - point;
638 const float distanceSquared = b3LengthSquared(delta);
639 const int bodyId = body->getId();
640 const int stableShapeId = shape->getId();
641 constexpr float tieTolerance = 1e-7f;
642 if (distanceSquared < self->bestDistanceSquared - tieTolerance ||
643 (std::fabs(distanceSquared - self->bestDistanceSquared) <= tieTolerance &&
644 (self->bodyId < 0 || bodyId < self->bodyId ||
645 (bodyId == self->bodyId && stableShapeId < self->stableShapeId)))) {
646 self->bestDistanceSquared = distanceSquared;
647 self->bodyId = bodyId;
648 self->stableShapeId = stableShapeId;
649 self->shapeTag = shape->getTag();
650 self->point = point;
651 }
652 return true;
653 }
654 } collector;
655 collector.world = this;
656 collector.target = b3Vec3{x, y, z};
657 collector.bestDistanceSquared = maxDistance * maxDistance;
658
659 const b3Vec3 extent{maxDistance, maxDistance, maxDistance};
660 const b3AABB bounds{collector.target - extent, collector.target + extent};
661 const b3QueryFilter filter = do_makeQueryFilter();
662 b3World_OverlapAABB(worldId_, bounds, filter, &ClosestCollector::callback, &collector);
663 if (collector.bodyId < 0) return -1;
664
665 owner_->closestBodyId_ = collector.bodyId;
666 owner_->closestShapeId_ = collector.stableShapeId;
667 owner_->closestShapeTag_ = collector.shapeTag;
668 owner_->closestX_ = collector.point.x;
669 owner_->closestY_ = collector.point.y;
670 owner_->closestZ_ = collector.point.z;
671 owner_->closestDistance_ = std::sqrt(std::max(0.f, collector.bestDistanceSquared));
672 if (owner_->closestDistance_ > 1e-6f) {
673 const float inverseDistance = 1.f / owner_->closestDistance_;
674 owner_->closestNormalX_ = (x - owner_->closestX_) * inverseDistance;
675 owner_->closestNormalY_ = (y - owner_->closestY_) * inverseDistance;
676 owner_->closestNormalZ_ = (z - owner_->closestZ_) * inverseDistance;
677 }
678 return owner_->closestBodyId_;
679}
680
681eve::Result<int> WorldBackend::closestPoint(float x, float y, float z, float maxDistance) {
682 return checked("physics.world3d.closestPoint",
683 [&] { return eve::Result<int>::success(do_closestPoint(x, y, z, maxDistance)); });
684}
685
686} // namespace eve::physics::box3d
double z
double y
double x
LogicalId target
std::string output
std::uint32_t capacity
ShaderImageInput shape
std::uint32_t height
std::uint32_t width
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
float distance
Texture * normal
glm::dvec3 origin
glm::dvec3 dx
glm::dvec3 dz
std::string error
Definition Package.cpp:174
std::shared_ptr< const std::vector< glm::vec2 > > points
bool hit
std::string body
RenderSystem3D::GpuOpaqueCollector collector
std::string filter
ScriptStructure out
float dy
Definition Shadow.cpp:151
int count
std::uint32_t depth
const VegetationPresetContext & context
float fraction
int shapeId
ViewPreparation callback
glm::vec3 point
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
3D shape (box/sphere/capsule) attached to a Body3D with material settings. Created via Body3D::new*Sh...
Definition Shape3D.h:34
eve::Result< BroadPhaseAabb3D > queryAabbBroadPhaseOwned(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, QueryFilter3D filter) override
queryAabbBroadPhaseOwned; uses the class ownership, thread and failure contract.
eve::Result< int > queryAABB(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) override
queryAABB; 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< RayHit3D > rayCastOwned(float x1, float y1, float z1, float x2, float y2, float z2, QueryFilter3D filter) override
rayCastOwned; 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 > querySphere(float x, float y, float z, float radius) override
querySphere; 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.
bool isValid() const noexcept override
Native world liveness.
eve::Result< int > rayCastAll(float x1, float y1, float z1, float x2, float y2, float z2, int maxHits) override
rayCastAll; uses the class ownership, thread and failure contract.
eve::Result< int > rayCastFiltered(float x1, float y1, float z1, float x2, float y2, float z2, uint64_t maskBits) override
rayCastFiltered; uses the class ownership, thread and failure contract.
eve::Result< int > closestPoint(float x, float y, float z, float maxDistance) override
closestPoint; 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.
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 > 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< 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.
Body3D * bodyFromShape(b3ShapeId shapeId)
Resolves a native Box3D user-data observer for an immediate internal call.
void makeBoxProxyPoints(b3Vec3(&points)[8], float width, float height, float depth, b3Quat q, const char *operation)
Shape3D * shapeFromShape(b3ShapeId shapeId)
Resolves a native Box3D user-data observer for an immediate internal call.
b3Quat normalizedQueryQuat(float qx, float qy, float qz, float qw, const char *operation)
Fixed-capacity deterministic result of one AABB broad-phase query.
One generation-qualified shape returned by an owning broad-phase query.
CameraSphereHit3D public API.
Definition World3DTypes.h:5
Owning summary of a capsule overlap query.
Query filter applied atomically for one owning query operation.
Owning snapshot of the closest ray intersection.
PhysicsShapeHandle shape
PhysicsBodyHandle body
PhysicsWorldHandle world
glm::vec4 bounds