Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Physics3DModuleEntry.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
19
20#include <Jolt/Physics/Body/BodyCreationSettings.h>
21#include <Jolt/Physics/Collision/CastResult.h>
22#include <Jolt/Physics/Collision/RayCast.h>
23#include <Jolt/Physics/Collision/Shape/BoxShape.h>
24#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
25#include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
26#include <Jolt/Physics/Collision/Shape/MeshShape.h>
27#include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
28#include <Jolt/Physics/Collision/Shape/SphereShape.h>
29#include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
30#include <Jolt/Physics/Character/CharacterVirtual.h>
31#include <Jolt/Physics/Collision/CollideShape.h>
32#include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
33#include <Jolt/Physics/Collision/CollisionDispatch.h>
34#include <Jolt/Physics/Collision/ContactListener.h>
35#include <limits>
36#include <Jolt/Physics/Collision/ShapeCast.h>
37#include <Jolt/RegisterTypes.h>
38
39#include <cstddef>
40#include <algorithm>
41#include <cmath>
42#include <vector>
43
44using namespace JPH;
47
48namespace esengine::physics3d {
50 static Context instance;
51 return instance;
52}
54 static LayerMatrix instance;
55 return instance;
56}
57} // namespace esengine::physics3d
58
59namespace {
60
61Context& g() { return esengine::physics3d::ctx(); }
62
65constexpr JPH::uint TEMP_ARENA_BYTES = 8 * 1024 * 1024;
66
70constexpr uint32_t CHARACTER_ID_TAG = 0x80000000u;
71
72EMotionType motionTypeOf(int value) {
73 switch (value) {
74 case 1: return EMotionType::Kinematic;
75 case 2: return EMotionType::Dynamic;
76 default: return EMotionType::Static;
77 }
78}
79
80ObjectLayer layerOf(EMotionType motion, uint32_t layer) {
81 return esengine::physics3d::Layers::of(layer, motion != EMotionType::Static);
82}
83
87struct BodyMotion {
88 int motion = 0;
89 float gravityScale = 1.0f;
90 float linearDamping = 0.0f;
91 float angularDamping = 0.0f;
92 int fixedRotation = 0;
93 uint32_t layer = 0;
94 int continuous = 0;
95};
96
98uint32_t entityOfBody(const BodyID& id) {
99 auto found = g().entityOf.find(id.GetIndexAndSequenceNumber());
100 return found == g().entityOf.end() ? 0u : found->second;
101}
102
107class ContactRecorder final : public ContactListener {
108public:
109 void OnContactAdded(const Body& body1, const Body& body2, const ContactManifold& manifold,
110 ContactSettings&) override {
111 const uint32_t a = body1.GetID().GetIndexAndSequenceNumber();
112 const uint32_t b = body2.GetID().GetIndexAndSequenceNumber();
113 const uint32_t entityA = entityOfBody(body1.GetID());
114 const uint32_t entityB = entityOfBody(body2.GetID());
115 if (entityA == 0 && entityB == 0) return;
116
117 const bool aIsSensor = g().sensorBodies.count(a) != 0;
118 const bool bIsSensor = g().sensorBodies.count(b) != 0;
119 if (aIsSensor || bIsSensor) {
120 // The sensor is named first, so a listener never has to work out
121 // which of the two it subscribed to.
122 g().sensorEnterBuffer.push_back(static_cast<float>(aIsSensor ? entityA : entityB));
123 g().sensorEnterBuffer.push_back(static_cast<float>(aIsSensor ? entityB : entityA));
124 return;
125 }
126 const RVec3 point = manifold.GetWorldSpaceContactPointOn1(0);
127 const Vec3 normal = manifold.mWorldSpaceNormal;
128 g().contactEnterBuffer.insert(g().contactEnterBuffer.end(), {
129 static_cast<float>(entityA), static_cast<float>(entityB),
130 normal.GetX(), normal.GetY(), normal.GetZ(),
131 static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),
132 static_cast<float>(point.GetZ()),
133 });
134 // Read before the solver has answered the contact: what the two were doing as they met. The normal points from
135 // the first into the second, so the first closing on the second is a positive speed.
136 const Vec3 closing = body1.GetPointVelocity(point) - body2.GetPointVelocity(point);
137 g().contactEnterSpeedBuffer.push_back(closing.Dot(normal));
138 // A static or kinematic body is pushed by nothing: it gives no inverse mass to the meeting.
139 const auto inverse = [](const Body& body) { return body.IsDynamic() ? body.GetMotionProperties()->GetInverseMass() : 0.0f; };
140 const float both = inverse(body1) + inverse(body2);
141 g().contactEnterMassBuffer.push_back(both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity());
142 }
143
144 void OnContactRemoved(const SubShapeIDPair& pair) override {
145 const uint32_t a = pair.GetBody1ID().GetIndexAndSequenceNumber();
146 const uint32_t b = pair.GetBody2ID().GetIndexAndSequenceNumber();
147 const uint32_t entityA = entityOfBody(pair.GetBody1ID());
148 const uint32_t entityB = entityOfBody(pair.GetBody2ID());
149 if (entityA == 0 && entityB == 0) return;
150
151 const bool aIsSensor = g().sensorBodies.count(a) != 0;
152 const bool bIsSensor = g().sensorBodies.count(b) != 0;
153 std::vector<float>& out = (aIsSensor || bIsSensor) ? g().sensorExitBuffer
154 : g().contactExitBuffer;
155 if (aIsSensor || bIsSensor) {
156 out.push_back(static_cast<float>(aIsSensor ? entityA : entityB));
157 out.push_back(static_cast<float>(aIsSensor ? entityB : entityA));
158 } else {
159 out.push_back(static_cast<float>(entityA));
160 out.push_back(static_cast<float>(entityB));
161 }
162 }
163};
164
165ContactRecorder& recorder() {
166 static ContactRecorder instance;
167 return instance;
168}
169
171uint32_t addBody(uint32_t entity, const Ref<Shape>& shape, float px, float py, float pz,
172 float qx, float qy, float qz, float qw, const BodyMotion& how,
173 float friction, float restitution, int isSensor,
174 float cx = 0.0f, float cy = 0.0f, float cz = 0.0f, float mass = 0.0f) {
175 if (!g().isValid()) return 0;
176 // A collider off the entity's origin: the shape is carried by a translated wrapper, so the body (and what a dynamic one rotates about)
177 // stays at the entity.
178 Ref<Shape> placed = shape;
179 // `> 0` is false for NaN too, so a caller that leaves the offset off gets a body at the origin.
180 if (cx * cx + cy * cy + cz * cz > 0.0f) {
181 const ShapeSettings::ShapeResult r = RotatedTranslatedShapeSettings(Vec3(cx, cy, cz), Quat::sIdentity(), shape).Create();
182 if (r.IsValid()) placed = r.Get();
183 }
184 const EMotionType motionType = motionTypeOf(how.motion);
185 BodyCreationSettings settings(placed, RVec3(px, py, pz), Quat(qx, qy, qz, qw).Normalized(),
186 motionType, layerOf(motionType, how.layer));
187 settings.mFriction = friction;
188 settings.mRestitution = restitution;
189 settings.mIsSensor = isSensor != 0;
190 settings.mGravityFactor = how.gravityScale;
191 settings.mLinearDamping = how.linearDamping;
192 settings.mAngularDamping = how.angularDamping;
193 if (mass > 0.0f && std::isfinite(mass) && motionType != EMotionType::Static) {
194 settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
195 settings.mMassPropertiesOverride.mMass = mass;
196 }
197 // What keeps a character upright: the solver may move it and never turn it.
198 if (how.fixedRotation != 0) {
199 settings.mAllowedDOFs = EAllowedDOFs::TranslationX | EAllowedDOFs::TranslationY
200 | EAllowedDOFs::TranslationZ;
201 }
202 // Discrete collision only asks where a body IS at the end of a step, so
203 // anything that crosses more than its own thickness in one step arrives on the
204 // far side of a wall having never touched it.
205 if (how.continuous != 0) settings.mMotionQuality = EMotionQuality::LinearCast;
206 BodyInterface& bodies = g().system->GetBodyInterface();
207 const BodyID id = bodies.CreateAndAddBody(
208 settings, motionType == EMotionType::Static ? EActivation::DontActivate
209 : EActivation::Activate);
210 if (id.IsInvalid()) return 0;
211 g().entityOf[id.GetIndexAndSequenceNumber()] = entity;
212 if (isSensor != 0) g().sensorBodies.insert(id.GetIndexAndSequenceNumber());
213 return id.GetIndexAndSequenceNumber();
214}
215
216} // namespace
217
218extern "C" {
219
220// World lifecycle
221
223void physics3d_init(float gx, float gy, float gz, uint32_t maxBodies) {
224 if (g().isValid()) return;
225 RegisterDefaultAllocator();
226 // Factory and type registry are process-wide, so a world built after a
227 // shutdown must not register them twice.
228 if (Factory::sInstance == nullptr) {
229 Factory::sInstance = new Factory();
230 RegisterTypes();
231 }
232 g().factory = Factory::sInstance;
233 g().temp = new TempAllocatorImpl(TEMP_ARENA_BYTES);
234 g().jobs = new JobSystemSingleThreaded(cMaxPhysicsJobs);
235 g().system = new PhysicsSystem();
236 const uint32_t bodies = maxBodies > 0 ? maxBodies : 1024;
237 g().system->Init(bodies, 0, bodies * 2, bodies * 2, g().broadPhaseLayers,
238 g().objectVsBroadPhase, g().objectPairs);
239 g().system->SetGravity(Vec3(gx, gy, gz));
240 g().system->SetContactListener(&recorder());
241}
242
245 if (!g().isValid()) return;
246 delete g().system;
247 delete g().jobs;
248 delete g().temp;
249 g().system = nullptr;
250 g().jobs = nullptr;
251 g().temp = nullptr;
252 g().characterVsCharacter.mCharacters.clear();
253 g().characters.clear();
254 g().sensorBodies.clear();
255 g().contactEnterBuffer.clear();
256 g().contactEnterSpeedBuffer.clear();
257 g().contactEnterMassBuffer.clear();
258 g().contactExitBuffer.clear();
259 g().sensorEnterBuffer.clear();
260 g().sensorExitBuffer.clear();
261 g().entityOf.clear();
262 g().transformBuffer.clear();
263 g().queryBuffer.clear();
264 // Factory/RegisterTypes are deliberately left standing: they are process-wide
265 // and a second world would only re-register the same types.
266}
267
269int physics3d_isReady() { return g().isValid() ? 1 : 0; }
270
278void physics3d_setLayerMask(uint32_t layer, uint32_t mask) {
281 }
282}
283
285void physics3d_setSolver(int velocityIterations, int positionIterations, int allowSleep,
286 float bounceThreshold) {
287 if (!g().isValid()) return;
288 // From Jolt's own defaults, not from what is set now: 0 means "Jolt's value", so a
289 // setting cleared after being changed goes back rather than staying where it was.
290 const PhysicsSettings jolt;
291 PhysicsSettings settings = g().system->GetPhysicsSettings();
292 settings.mNumVelocitySteps = velocityIterations > 0 ? static_cast<JPH::uint>(velocityIterations) : jolt.mNumVelocitySteps;
293 settings.mNumPositionSteps = positionIterations > 0 ? static_cast<JPH::uint>(positionIterations) : jolt.mNumPositionSteps;
294 settings.mAllowSleeping = allowSleep != 0;
295 settings.mMinVelocityForRestitution = bounceThreshold > 0.0f ? bounceThreshold : jolt.mMinVelocityForRestitution;
296 g().system->SetPhysicsSettings(settings);
297}
298
301void physics3d_step(float dt, int collisionSteps) {
302 if (!g().isValid() || dt <= 0.0f) return;
303 // No character moved this step: what the last one met has been read, and is not told again.
304 if (g().characterHitsStale) g().characterHitBuffer.clear();
305 g().solverStep = dt / static_cast<float>(std::max(collisionSteps, 1));
306 // Cleared before the step, not after: the listener fires DURING Update, and a
307 // buffer emptied afterwards would publish nothing.
308 g().contactEnterBuffer.clear();
309 g().contactEnterSpeedBuffer.clear();
310 g().contactEnterMassBuffer.clear();
311 g().contactExitBuffer.clear();
312 g().sensorEnterBuffer.clear();
313 g().sensorExitBuffer.clear();
314 g().system->Update(dt, collisionSteps > 0 ? collisionSteps : 1, g().temp, g().jobs);
315
316 BodyIDVector active;
317 g().system->GetActiveBodies(EBodyType::RigidBody, active);
318 const BodyInterface& bodies = g().system->GetBodyInterfaceNoLock();
319 std::vector<float>& out = g().transformBuffer;
320 out.clear();
321 out.reserve(active.size() * 8);
322 for (const BodyID& id : active) {
323 auto owner = g().entityOf.find(id.GetIndexAndSequenceNumber());
324 if (owner == g().entityOf.end()) continue;
325 RVec3 position;
326 Quat rotation;
327 bodies.GetPositionAndRotation(id, position, rotation);
328 out.push_back(static_cast<float>(owner->second));
329 out.push_back(static_cast<float>(position.GetX()));
330 out.push_back(static_cast<float>(position.GetY()));
331 out.push_back(static_cast<float>(position.GetZ()));
332 out.push_back(rotation.GetX());
333 out.push_back(rotation.GetY());
334 out.push_back(rotation.GetZ());
335 out.push_back(rotation.GetW());
336 }
337 g().characterHitsStale = true;
338}
339
344 if (g().isValid()) g().system->OptimizeBroadPhase();
345}
346
347// Bodies
348
352uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count,
353 float px, float py, float pz, float qx, float qy, float qz, float qw,
354 int motion, float gravityScale, float linearDamping, float angularDamping,
355 int fixedRotation, uint32_t layer, int continuous,
356 float friction, float restitution, int isSensor, float mass) {
357 if (!g().isValid() || partsPtr == 0 || count == 0 || count > 16384) return 0;
358 const float* parts = reinterpret_cast<const float*>(partsPtr);
359 StaticCompoundShapeSettings settings;
360 for (uint32_t i = 0; i < count; ++i) {
361 const float* p = parts + i * 11;
362 for (uint32_t j = 0; j < 11; ++j) if (!std::isfinite(p[j])) return 0;
363 Ref<Shape> shape;
364 if (p[0] == 0 && p[1] > 0 && p[2] > 0 && p[3] > 0) {
365 const float convex = std::min(0.05f, std::min(p[1], std::min(p[2], p[3])) * 0.1f);
366 shape = new BoxShape(Vec3(p[1], p[2], p[3]), convex);
367 } else if (p[0] == 1 && p[1] > 0) shape = new SphereShape(p[1]);
368 else if (p[0] == 2 && p[1] > 0 && p[2] >= 0) {
369 if (p[2] == 0) shape = new SphereShape(p[1]);
370 else shape = new CapsuleShape(p[2], p[1]);
371 } else return 0;
372 Quat rotation(p[7], p[8], p[9], p[10]);
373 if (rotation.LengthSq() < 1.0e-12f) return 0;
374 settings.AddShape(Vec3(p[4], p[5], p[6]), rotation.Normalized(), shape);
375 }
376 const auto result = settings.Create();
377 if (result.HasError()) return 0;
378 return addBody(entity, result.Get(), px, py, pz, qx, qy, qz, qw,
379 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
380 friction, restitution, isSensor, 0, 0, 0, mass);
381}
382
384uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz,
385 float px, float py, float pz,
386 float qx, float qy, float qz, float qw,
387 int motion, float gravityScale, float linearDamping,
388 float angularDamping, int fixedRotation, uint32_t layer,
389 int continuous, float friction, float restitution, int isSensor,
390 float cx, float cy, float cz) {
391 return addBody(entity, new BoxShape(Vec3(hx, hy, hz)), px, py, pz, qx, qy, qz, qw,
392 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
393 continuous},
394 friction, restitution, isSensor, cx, cy, cz);
395}
396
398uint32_t physics3d_addSphere(uint32_t entity, float radius,
399 float px, float py, float pz,
400 float qx, float qy, float qz, float qw,
401 int motion, float gravityScale, float linearDamping,
402 float angularDamping, int fixedRotation, uint32_t layer,
403 int continuous, float friction, float restitution, int isSensor,
404 float cx, float cy, float cz) {
405 return addBody(entity, new SphereShape(radius), px, py, pz, qx, qy, qz, qw,
406 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
407 continuous},
408 friction, restitution, isSensor, cx, cy, cz);
409}
410
414uint32_t physics3d_addCapsule(uint32_t entity, float radius, float halfHeight,
415 float px, float py, float pz,
416 float qx, float qy, float qz, float qw,
417 int motion, float gravityScale, float linearDamping,
418 float angularDamping, int fixedRotation, uint32_t layer,
419 int continuous, float friction, float restitution, int isSensor,
420 float cx, float cy, float cz) {
421 return addBody(entity, new CapsuleShape(halfHeight, radius), px, py, pz, qx, qy, qz, qw,
422 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
423 continuous},
424 friction, restitution, isSensor, cx, cy, cz);
425}
426
437uint32_t physics3d_addMeshBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount,
438 uintptr_t indexPtr, uint32_t indexCount,
439 float px, float py, float pz,
440 float qx, float qy, float qz, float qw,
441 uint32_t layer, float friction, float restitution) {
442 if (!g().isValid() || vertexCount == 0 || indexCount < 3 || indexCount % 3 != 0) return 0;
443 const float* positions = reinterpret_cast<const float*>(vertexPtr);
444 const uint32_t* indices = reinterpret_cast<const uint32_t*>(indexPtr);
445 if (positions == nullptr || indices == nullptr) return 0;
446
447 VertexList vertices;
448 vertices.reserve(vertexCount);
449 for (uint32_t i = 0; i < vertexCount; ++i) {
450 vertices.push_back(Float3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
451 }
452 IndexedTriangleList triangles;
453 triangles.reserve(indexCount / 3);
454 for (uint32_t i = 0; i + 2 < indexCount; i += 3) {
455 if (indices[i] >= vertexCount || indices[i + 1] >= vertexCount
456 || indices[i + 2] >= vertexCount) {
457 return 0; // an index past the vertices would read whatever follows them
458 }
459 triangles.push_back(IndexedTriangle(indices[i], indices[i + 1], indices[i + 2], 0));
460 }
461
462 MeshShapeSettings settings(std::move(vertices), std::move(triangles));
463 settings.SetEmbedded();
464 ShapeSettings::ShapeResult shape = settings.Create();
465 if (shape.HasError()) return 0;
466 return addBody(entity, shape.Get(), px, py, pz, qx, qy, qz, qw,
467 {0, 1.0f, 0.0f, 0.0f, 0, layer}, friction, restitution, 0);
468}
469
478uint32_t physics3d_addConvexBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount,
479 float px, float py, float pz,
480 float qx, float qy, float qz, float qw,
481 int motion, float gravityScale, float linearDamping,
482 float angularDamping, int fixedRotation, uint32_t layer,
483 int continuous, float friction, float restitution,
484 int isSensor) {
485 // Three points are a triangle and enclose nothing; a hull needs a volume.
486 if (!g().isValid() || vertexCount < 4) return 0;
487 const float* positions = reinterpret_cast<const float*>(vertexPtr);
488 if (positions == nullptr) return 0;
489
490 Array<Vec3> points;
491 points.reserve(vertexCount);
492 for (uint32_t i = 0; i < vertexCount; ++i) {
493 points.push_back(Vec3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
494 }
495 ConvexHullShapeSettings settings(points);
496 settings.SetEmbedded();
497 ShapeSettings::ShapeResult shape = settings.Create();
498 // Degenerate input — every point on a plane, or all of them the same — has no
499 // hull, and a body with no shape is an invisible point that falls forever.
500 if (shape.HasError()) return 0;
501 return addBody(entity, shape.Get(), px, py, pz, qx, qy, qz, qw,
502 {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
503 continuous},
504 friction, restitution, isSensor);
505}
506
508void physics3d_removeBody(uint32_t bodyId) {
509 if (!g().isValid() || bodyId == 0) return;
510 const BodyID id(bodyId);
511 BodyInterface& bodies = g().system->GetBodyInterface();
512 bodies.RemoveBody(id);
513 bodies.DestroyBody(id);
514 g().entityOf.erase(bodyId);
515 g().sensorBodies.erase(bodyId);
516}
517
519void physics3d_setTransform(uint32_t bodyId, float px, float py, float pz,
520 float qx, float qy, float qz, float qw) {
521 if (!g().isValid() || bodyId == 0) return;
522 g().system->GetBodyInterface().SetPositionAndRotation(
523 BodyID(bodyId), RVec3(px, py, pz), Quat(qx, qy, qz, qw).Normalized(),
524 EActivation::Activate);
525}
526
528void physics3d_setLinearVelocity(uint32_t bodyId, float vx, float vy, float vz) {
529 if (!g().isValid() || bodyId == 0) return;
530 g().system->GetBodyInterface().SetLinearVelocity(BodyID(bodyId), Vec3(vx, vy, vz));
531}
532
534void physics3d_setMass(uint32_t bodyId, float mass) {
535 if (!g().isValid() || bodyId == 0 || !(mass > 0.0f) || !std::isfinite(mass)) return;
536 const BodyLockWrite lock(g().system->GetBodyLockInterface(), BodyID(bodyId));
537 if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return;
538 Body& body = lock.GetBody();
539 // The shape's own mass properties, as the density gave them, brought to the mass asked: its inertia comes along.
540 MassProperties props = body.GetShape()->GetMassProperties();
541 props.ScaleToMass(mass);
542 MotionProperties* motion = body.GetMotionProperties();
543 motion->SetMassProperties(motion->GetAllowedDOFs(), props);
544}
545
549int physics3d_getBodyState(uint32_t bodyId) {
550 if (!g().isValid() || bodyId == 0) return 0;
551 const BodyInterface& bodies = g().system->GetBodyInterface();
552 const BodyID id(bodyId);
553 if (!bodies.IsAdded(id)) return 0;
554 RVec3 position;
555 Quat rotation;
556 bodies.GetPositionAndRotation(id, position, rotation);
557 const Vec3 velocity = bodies.GetLinearVelocity(id);
558 g().queryBuffer = {
559 static_cast<float>(position.GetX()), static_cast<float>(position.GetY()),
560 static_cast<float>(position.GetZ()), rotation.GetX(), rotation.GetY(),
561 rotation.GetZ(), rotation.GetW(), velocity.GetX(), velocity.GetY(), velocity.GetZ(),
562 };
563 return 1;
564}
565
569int physics3d_getBodyDynamics(uint32_t bodyId) {
570 if (!g().isValid() || bodyId == 0) return 0;
571 const BodyLockRead lock(g().system->GetBodyLockInterface(), BodyID(bodyId));
572 if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return 0;
573 const Body& body = lock.GetBody();
574 const float inverseMass = body.GetMotionProperties()->GetInverseMass();
575 if (!(inverseMass > 0.0f)) return 0;
576 const Vec3 spin = body.GetAngularVelocity();
577 g().queryBuffer = { 1.0f / inverseMass, spin.GetX(), spin.GetY(), spin.GetZ() };
578 return 1;
579}
580
584void physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz) {
585 if (!g().isValid() || bodyId == 0) return;
586 // A point that is not a number is its centre of mass: pushed there, it turns nothing.
587 if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz), RVec3(px, py, pz));
588 else g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz));
589}
590
592void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz) {
593 if (!g().isValid() || bodyId == 0) return;
594 BodyInterface& bodies = g().system->GetBodyInterface();
595 if (bodies.GetMotionType(BodyID(bodyId)) != EMotionType::Dynamic) return;
596 if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) bodies.AddImpulse(BodyID(bodyId), Vec3(ix, iy, iz), RVec3(px, py, pz));
597 else bodies.AddImpulse(BodyID(bodyId), Vec3(ix, iy, iz));
598}
599
601void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz) {
602 if (!g().isValid() || bodyId == 0) return;
603 BodyInterface& bodies = g().system->GetBodyInterface();
604 if (bodies.GetMotionType(BodyID(bodyId)) != EMotionType::Dynamic) return;
605 bodies.AddAngularImpulse(BodyID(bodyId), Vec3(ix, iy, iz));
606}
607
609void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz) {
610 if (!g().isValid() || bodyId == 0) return;
611 BodyInterface& bodies = g().system->GetBodyInterface();
612 if (bodies.GetMotionType(BodyID(bodyId)) == EMotionType::Static) return;
613 bodies.SetAngularVelocity(BodyID(bodyId), Vec3(wx, wy, wz));
614 bodies.ActivateBody(BodyID(bodyId));
615}
616
618void physics3d_setGravity(float gx, float gy, float gz) {
619 if (!g().isValid()) return;
620 g().system->SetGravity(Vec3(gx, gy, gz));
621}
622
624void physics3d_setAwake(uint32_t bodyId, int awake) {
625 if (!g().isValid() || bodyId == 0) return;
626 BodyInterface& bodies = g().system->GetBodyInterface();
627 if (bodies.GetMotionType(BodyID(bodyId)) == EMotionType::Static) return;
628 if (awake) bodies.ActivateBody(BodyID(bodyId)); else bodies.DeactivateBody(BodyID(bodyId));
629}
630
632int physics3d_isAwake(uint32_t bodyId) {
633 if (!g().isValid() || bodyId == 0) return 0;
634 return g().system->GetBodyInterface().IsActive(BodyID(bodyId)) ? 1 : 0;
635}
636
638int physics3d_getBodyMassData(uint32_t bodyId) {
639 if (!g().isValid() || bodyId == 0) return 0;
640 const BodyLockRead lock(g().system->GetBodyLockInterface(), BodyID(bodyId));
641 if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return 0;
642 const Body& body = lock.GetBody();
643 const MotionProperties* motion = body.GetMotionProperties();
644 const float inverseMass = motion->GetInverseMass();
645 if (!(inverseMass > 0.0f)) return 0;
646 const RVec3 centre = body.GetCenterOfMassPosition();
647 // About the body's own axes, not Jolt's principal ones, which it orders as it likes: a twist about an axis alone
648 // turns it by inverse-inertia along that axis, and the moment is its inverse.
649 const Mat44 inverse = motion->GetLocalSpaceInverseInertia();
650 const auto moment = [](float i) { return i > 0.0f ? 1.0f / i : std::numeric_limits<float>::infinity(); };
651 g().queryBuffer = { 1.0f / inverseMass,
652 static_cast<float>(centre.GetX()), static_cast<float>(centre.GetY()), static_cast<float>(centre.GetZ()),
653 moment(inverse(0, 0)), moment(inverse(1, 1)), moment(inverse(2, 2)) };
654 return 1;
655}
656
659void physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz) {
660 if (!g().isValid() || bodyId == 0) return;
661 g().system->GetBodyInterface().AddTorque(BodyID(bodyId), Vec3(tx, ty, tz));
662}
663
664// Characters
665
672uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
673 float px, float py, float pz, float maxSlope, float mass,
674 uint32_t layer, float pushForce) {
675 if (!g().isValid()) return 0;
676 Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
677 settings->mShape = new CapsuleShape(halfHeight, radius);
678 settings->mMaxSlopeAngle = maxSlope;
679 settings->mMass = mass;
680 // Nothing gets out of a swept character's way on its own: this is the force
681 // it may spend shoving what it walks into.
682 settings->mMaxStrength = pushForce;
683 // The plane below which contacts do not hold the character up. Without it a
684 // contact anywhere on the capsule — including the top — reads as ground.
685 settings->mSupportingVolume = Plane(Vec3::sAxisY(), -radius);
686 auto character = std::make_unique<CharacterVirtual>(
687 settings, RVec3(px, py, pz), Quat::sIdentity(), g().system);
688 // Every character checks against every other one. Brute force, which is what
689 // Jolt offers and what a crowd of the size a scene authors costs nothing at.
690 character->SetCharacterVsCharacterCollision(&g().characterVsCharacter);
691 g().characterVsCharacter.Add(character.get());
692 const uint32_t id = g().nextCharacterId++;
693 g().characterLayers[id] = layer;
694 g().characters[id] = std::move(character);
695 g().entityOf[id | CHARACTER_ID_TAG] = entity;
696 return id;
697}
698
700void physics3d_removeCharacter(uint32_t characterId) {
701 auto found = g().characters.find(characterId);
702 if (found != g().characters.end()) g().characterVsCharacter.Remove(found->second.get());
703 g().characters.erase(characterId);
704 g().characterLayers.erase(characterId);
705 g().characterTouching.erase(characterId);
706 g().entityOf.erase(characterId | CHARACTER_ID_TAG);
707}
708
718static void noteCharacterMeetings(uint32_t characterId, const CharacterVirtual& character, Vec3Arg velocity) {
719 if (g().characterHitsStale) { g().characterHitBuffer.clear(); g().characterHitsStale = false; }
720 std::vector<uint32_t>& touching = g().characterTouching[characterId];
721 std::vector<uint32_t> now;
722 const auto self = g().entityOf.find(characterId | CHARACTER_ID_TAG);
723 const float own = character.GetMass() > 0.0f ? 1.0f / character.GetMass() : 0.0f;
724 for (const auto& contact : character.GetActiveContacts()) {
725 if (!contact.mHadCollision || contact.mWasDiscarded || contact.mBodyB.IsInvalid()) continue;
726 const uint32_t key = contact.mBodyB.GetIndexAndSequenceNumber();
727 if (std::find(now.begin(), now.end(), key) != now.end()) continue;
728 now.push_back(key);
729 if (std::find(touching.begin(), touching.end(), key) != touching.end()) continue;
730 float other = 0.0f;
731 {
732 const BodyLockRead lock(g().system->GetBodyLockInterface(), contact.mBodyB);
733 if (lock.Succeeded() && lock.GetBody().IsDynamic()) other = lock.GetBody().GetMotionProperties()->GetInverseMass();
734 }
735 const float both = own + other;
736 const auto owner = g().entityOf.find(key);
737 // The normal points toward the character: closing on what it met is moving against it.
738 const float closing = -(velocity - contact.mLinearVelocity).Dot(contact.mContactNormal);
739 g().characterHitBuffer.insert(g().characterHitBuffer.end(), {
740 self == g().entityOf.end() ? 0.0f : static_cast<float>(self->second),
741 owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),
742 static_cast<float>(contact.mPosition.GetX()), static_cast<float>(contact.mPosition.GetY()), static_cast<float>(contact.mPosition.GetZ()),
743 contact.mContactNormal.GetX(), contact.mContactNormal.GetY(), contact.mContactNormal.GetZ(),
744 std::max(closing, 0.0f), both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity(),
745 });
746 }
747 touching.swap(now);
748}
749
751void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,
752 float dt, float stepUp, float stepDown) {
753 g().queryBuffer.clear();
754 auto found = g().characters.find(characterId);
755 if (!g().isValid() || found == g().characters.end()) return;
756 CharacterVirtual& character = *found->second;
757
758 // A CharacterVirtual does not fall on its own — its gravity parameter only
759 // pushes down on what it stands on, and the vertical speed is the caller's.
760 // Carried here so `vy = 0` means "walk", not "hang in the air".
761 float vertical = character.GetLinearVelocity().GetY();
762 if (vy != 0.0f) {
763 vertical = vy; // a jump, or a deliberate dive
764 } else if (character.GetGroundState() == CharacterVirtual::EGroundState::OnGround) {
765 vertical = 0.0f;
766 } else {
767 vertical += g().system->GetGravity().GetY() * dt;
768 }
769 character.SetLinearVelocity(Vec3(vx, vertical, vz));
770 // Where it stood before the sweep. GetLinearVelocity afterwards returns what
771 // we PUT there — ExtendedUpdate moves the character without rewriting it — so
772 // the only honest answer is the ground it covered over the time it had.
773 const RVec3 startedAt = character.GetPosition();
774 CharacterVirtual::ExtendedUpdateSettings settings;
775 settings.mWalkStairsStepUp = Vec3(0, stepUp, 0);
776 settings.mStickToFloorStepDown = Vec3(0, -stepDown, 0);
777 const ObjectLayer objectLayer = esengine::physics3d::Layers::of(
778 g().characterLayers.count(characterId) ? g().characterLayers[characterId] : 0, true);
779 character.ExtendedUpdate(dt, g().system->GetGravity(), settings,
780 g().system->GetDefaultBroadPhaseLayerFilter(objectLayer),
781 g().system->GetDefaultLayerFilter(objectLayer),
782 {}, {}, *g().temp);
783
784 noteCharacterMeetings(characterId, character, Vec3(vx, vertical, vz));
785
786 const RVec3 position = character.GetPosition();
787 const Vec3 normal = character.GetGroundNormal();
788 // The velocity it REACHED, not the one it was given: a character shoving a
789 // wall keeps the velocity it asked for and covers no ground, and gameplay
790 // reading the request back would never know the difference.
791 const Vec3 velocity = dt > 0.0f
792 ? Vec3((position - startedAt) / dt)
793 : Vec3::sZero();
794 g().queryBuffer = {
795 static_cast<float>(position.GetX()), static_cast<float>(position.GetY()),
796 static_cast<float>(position.GetZ()),
797 static_cast<float>(character.GetGroundState()),
798 normal.GetX(), normal.GetY(), normal.GetZ(),
799 velocity.GetX(), velocity.GetY(), velocity.GetZ(),
800 };
801}
802
811void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, float pz) {
812 auto found = g().characters.find(characterId);
813 if (found == g().characters.end()) return;
814 found->second->SetPosition(RVec3(px, py, pz));
815 found->second->SetLinearVelocity(Vec3::sZero());
816}
817
818// Queries
819
820namespace {
821
825class MaskLayerFilter final : public ObjectLayerFilter {
826public:
827 explicit MaskLayerFilter(uint32_t mask) : mask_(mask == 0 ? 0xFFFFFFFFu : mask) {}
828 bool ShouldCollide(ObjectLayer layer) const override {
829 return (mask_ & (1u << esengine::physics3d::Layers::indexOf(layer))) != 0;
830 }
831private:
832 uint32_t mask_;
833};
834
836void pushEntityHit(uint32_t entity, RVec3Arg point) {
837 g().queryBuffer.push_back(static_cast<float>(entity));
838 g().queryBuffer.push_back(static_cast<float>(point.GetX()));
839 g().queryBuffer.push_back(static_cast<float>(point.GetY()));
840 g().queryBuffer.push_back(static_cast<float>(point.GetZ()));
841}
842
843void pushHit(const BodyID& id, RVec3Arg point) {
844 auto owner = g().entityOf.find(id.GetIndexAndSequenceNumber());
845 pushEntityHit(owner == g().entityOf.end() ? 0u : owner->second, point);
846}
847
849bool layerPasses(uint32_t mask, uint32_t layerIndex) {
850 return ((mask == 0 ? 0xFFFFFFFFu : mask) & (1u << layerIndex)) != 0;
851}
852
860int collideCharacters(const Shape* shape, RMat44Arg transform,
861 const CollideShapeSettings& settings, uint32_t layerMask) {
862 int found = 0;
863 for (const auto& entry : g().characters) {
864 const auto layer = g().characterLayers.find(entry.first);
865 if (!layerPasses(layerMask, layer == g().characterLayers.end() ? 0u : layer->second)) {
866 continue;
867 }
868 const auto owner = g().entityOf.find(entry.first | CHARACTER_ID_TAG);
869 if (owner == g().entityOf.end()) continue;
870
871 ClosestHitCollisionCollector<CollideShapeCollector> collector;
872 CollisionDispatch::sCollideShapeVsShape(
873 shape, entry.second->GetShape(),
874 Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f),
875 transform, entry.second->GetCenterOfMassTransform(),
876 SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
877 if (!collector.HadHit()) continue;
878 pushEntityHit(owner->second, collector.mHit.mContactPointOn2);
879 found++;
880 }
881 return found;
882}
883
885int collideShape(const Shape* shape, float px, float py, float pz, uint32_t layerMask) {
886 g().queryBuffer.clear();
887 if (!g().isValid() || shape == nullptr) return 0;
888 AllHitCollisionCollector<CollideShapeCollector> collector;
889 const CollideShapeSettings settings;
890 const RMat44 transform = RMat44::sTranslation(RVec3(px, py, pz));
891 const MaskLayerFilter filter(layerMask);
892 g().system->GetNarrowPhaseQuery().CollideShape(
893 shape, Vec3::sReplicate(1.0f), transform, settings, RVec3::sZero(), collector,
894 {}, filter);
895 for (const CollideShapeResult& hit : collector.mHits) {
896 pushHit(hit.mBodyID2, hit.mContactPointOn2);
897 }
898 return static_cast<int>(collector.mHits.size())
899 + collideCharacters(shape, transform, settings, layerMask);
900}
901
902} // namespace
903
910int physics3d_overlapSphere(float px, float py, float pz, float radius, uint32_t layerMask) {
911 if (radius <= 0.0f) { g().queryBuffer.clear(); return 0; }
912 const SphereShape shape(radius);
913 return collideShape(&shape, px, py, pz, layerMask);
914}
915
918int physics3d_overlapBox(float px, float py, float pz, float hx, float hy, float hz,
919 uint32_t layerMask) {
920 if (hx <= 0.0f || hy <= 0.0f || hz <= 0.0f) { g().queryBuffer.clear(); return 0; }
921 const BoxShape shape(Vec3(hx, hy, hz));
922 return collideShape(&shape, px, py, pz, layerMask);
923}
924
931static int castShapeQuery(const Shape& shape, RMat44Arg start, Vec3Arg direction, uint32_t layerMask);
932
934int physics3d_sphereCast(float px, float py, float pz, float radius,
935 float dx, float dy, float dz, uint32_t layerMask) {
936 g().queryBuffer.clear();
937 if (!g().isValid() || radius <= 0.0f) return 0;
938 const SphereShape shape(radius);
939 return castShapeQuery(shape, RMat44::sTranslation(RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);
940}
941
943static Quat turnOf(float qx, float qy, float qz, float qw) {
944 const Quat q(qx, qy, qz, qw);
945 const float length = q.Length();
946 return std::isfinite(length) && length > 1e-6f ? q / length : Quat::sIdentity();
947}
948
950int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz,
951 float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {
952 g().queryBuffer.clear();
953 if (!g().isValid() || !(hx > 0.0f) || !(hy > 0.0f) || !(hz > 0.0f)) return 0;
954 // Rounded no more than its thinnest side allows: a box a centimetre thick is still a box.
955 const BoxShape shape(Vec3(hx, hy, hz), std::min({0.05f, hx, hy, hz}));
956 return castShapeQuery(shape, RMat44::sRotationTranslation(turnOf(qx, qy, qz, qw), RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);
957}
958
960int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight,
961 float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {
962 g().queryBuffer.clear();
963 if (!g().isValid() || !(radius > 0.0f) || !(halfHeight >= 0.0f)) return 0;
964 if (halfHeight == 0.0f) return physics3d_sphereCast(px, py, pz, radius, dx, dy, dz, layerMask);
965 const CapsuleShape shape(halfHeight, radius);
966 return castShapeQuery(shape, RMat44::sRotationTranslation(turnOf(qx, qy, qz, qw), RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);
967}
968
971static int castShapeQuery(const Shape& shape, RMat44Arg start, Vec3Arg direction, uint32_t layerMask) {
972 const RShapeCast cast(&shape, Vec3::sReplicate(1.0f), start, direction);
973 ClosestHitCollisionCollector<CastShapeCollector> collector;
974 const ShapeCastSettings settings;
975 const MaskLayerFilter filter(layerMask);
976 g().system->GetNarrowPhaseQuery().CastShape(cast, settings, RVec3::sZero(), collector,
977 {}, filter);
978 if (!collector.HadHit()) return 0;
979
980 const ShapeCastResult& hit = collector.mHit;
981 auto owner = g().entityOf.find(hit.mBodyID2.GetIndexAndSequenceNumber());
982 const RVec3 point = hit.mContactPointOn2;
983 const Vec3 normal = -hit.mPenetrationAxis.Normalized();
984 g().queryBuffer = {
985 owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),
986 hit.mFraction,
987 static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),
988 static_cast<float>(point.GetZ()),
989 normal.GetX(), normal.GetY(), normal.GetZ(),
990 };
991 return 1;
992}
993
997int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz,
998 uint32_t layerMask) {
999 g().queryBuffer.clear();
1000 if (!g().isValid()) return 0;
1001 const RRayCast ray{RVec3(ox, oy, oz), Vec3(dx, dy, dz)};
1002 RayCastResult hit;
1003 const MaskLayerFilter filter(layerMask);
1004 if (!g().system->GetNarrowPhaseQuery().CastRay(ray, hit, {}, filter)) return 0;
1005
1006 const RVec3 point = ray.GetPointOnRay(hit.mFraction);
1007 const BodyLockRead lock(g().system->GetBodyLockInterface(), hit.mBodyID);
1008 Vec3 normal = Vec3::sZero();
1009 if (lock.Succeeded()) {
1010 normal = lock.GetBody().GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, point);
1011 }
1012 auto owner = g().entityOf.find(hit.mBodyID.GetIndexAndSequenceNumber());
1013 g().queryBuffer = {
1014 owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),
1015 hit.mFraction,
1016 static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),
1017 static_cast<float>(point.GetZ()),
1018 normal.GetX(), normal.GetY(), normal.GetZ(),
1019 };
1020 return 1;
1021}
1022
1024int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits) {
1025 g().queryBuffer.clear();
1026 if (!g().isValid() || maxHits == 0) return 0;
1027 const Vec3 direction(dx, dy, dz);
1028 if (!(direction.LengthSq() > 0.0f)) return 0;
1029 const MaskLayerFilter filter(layerMask);
1030 const RayCastSettings settings;
1031 // Where the line goes into each body, from its start; and where it comes out, by going in from its end.
1032 AllHitCollisionCollector<CastRayCollector> forward, backward;
1033 g().system->GetNarrowPhaseQuery().CastRay(RRayCast{RVec3(ox, oy, oz), direction}, settings, forward, {}, filter);
1034 g().system->GetNarrowPhaseQuery().CastRay(RRayCast{RVec3(ox, oy, oz) + direction, -direction}, settings, backward, {}, filter);
1035 struct Crossing { BodyID body; SubShapeID part; float entry; float exit; };
1036 std::vector<Crossing> crossings;
1037 for (const RayCastResult& hit : forward.mHits) {
1038 auto same = std::find_if(crossings.begin(), crossings.end(), [&](const Crossing& c) { return c.body == hit.mBodyID; });
1039 if (same == crossings.end()) crossings.push_back({hit.mBodyID, hit.mSubShapeID2, hit.mFraction, 1.0f});
1040 else if (hit.mFraction < same->entry) { same->entry = hit.mFraction; same->part = hit.mSubShapeID2; }
1041 }
1042 for (Crossing& c : crossings) {
1043 float exit = 1.0f;
1044 for (const RayCastResult& hit : backward.mHits) if (hit.mBodyID == c.body) exit = std::min(exit, 1.0f - hit.mFraction);
1045 // A body the line ends inside is met by the backward line at once: it comes out nowhere short of the end.
1046 c.exit = std::max(exit, c.entry);
1047 }
1048 std::sort(crossings.begin(), crossings.end(), [](const Crossing& a, const Crossing& b) { return a.entry < b.entry; });
1049 if (crossings.size() > maxHits) crossings.resize(maxHits);
1050 for (const Crossing& c : crossings) {
1051 const RVec3 point = RVec3(ox, oy, oz) + Vec3(direction * c.entry);
1052 Vec3 normal = Vec3::sZero();
1053 const BodyLockRead lock(g().system->GetBodyLockInterface(), c.body);
1054 if (lock.Succeeded()) normal = lock.GetBody().GetWorldSpaceSurfaceNormal(c.part, point);
1055 auto owner = g().entityOf.find(c.body.GetIndexAndSequenceNumber());
1056 g().queryBuffer.insert(g().queryBuffer.end(), {
1057 owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second), c.entry, c.exit,
1058 static_cast<float>(point.GetX()), static_cast<float>(point.GetY()), static_cast<float>(point.GetZ()),
1059 normal.GetX(), normal.GetY(), normal.GetZ(),
1060 });
1061 }
1062 return static_cast<int>(crossings.size());
1063}
1064
1072int physics3d_raycastWith(float ox, float oy, float oz, float dx, float dy, float dz,
1073 uint32_t layerMask, uint32_t flags) {
1074 const int worldHit = physics3d_raycast(ox, oy, oz, dx, dy, dz, layerMask);
1075 if ((flags & 1u) == 0 || !g().isValid()) return worldHit;
1076 float best = worldHit ? g().queryBuffer[1] : 1.0f;
1077 const RRayCast ray{RVec3(ox, oy, oz), Vec3(dx, dy, dz)};
1078 uint32_t entity = 0;
1079 Vec3 normal = Vec3::sZero();
1080 bool found = false;
1081 for (const auto& entry : g().characters) {
1082 const auto layer = g().characterLayers.find(entry.first);
1083 if (!layerPasses(layerMask, layer == g().characterLayers.end() ? 0u : layer->second)) continue;
1084 const auto owner = g().entityOf.find(entry.first | CHARACTER_ID_TAG);
1085 if (owner == g().entityOf.end()) continue;
1086 const RMat44 com = entry.second->GetCenterOfMassTransform();
1087 const RayCast local(ray.Transformed(com.InversedRotationTranslation()));
1088 RayCastResult hit;
1089 hit.mFraction = best;
1090 const Shape* shape = entry.second->GetShape();
1091 if (!shape->CastRay(local, SubShapeIDCreator(), hit) || hit.mFraction >= best) continue;
1092 best = hit.mFraction;
1093 entity = owner->second;
1094 normal = com.Multiply3x3(shape->GetSurfaceNormal(hit.mSubShapeID2, local.GetPointOnRay(best))).NormalizedOr(Vec3::sAxisY());
1095 found = true;
1096 }
1097 if (!found) return worldHit;
1098 const RVec3 point = ray.GetPointOnRay(best);
1099 g().queryBuffer = {
1100 static_cast<float>(entity), best,
1101 static_cast<float>(point.GetX()), static_cast<float>(point.GetY()), static_cast<float>(point.GetZ()),
1102 normal.GetX(), normal.GetY(), normal.GetZ(),
1103 };
1104 return 1;
1105}
1106
1107// Readback
1108
1111 return reinterpret_cast<uintptr_t>(g().transformBuffer.data());
1112}
1113
1116 return g().transformBuffer.size() * sizeof(float);
1117}
1118
1121 return reinterpret_cast<uintptr_t>(g().characterHitBuffer.data());
1122}
1123
1126 return g().characterHitBuffer.size() * sizeof(float);
1127}
1128
1131 return reinterpret_cast<uintptr_t>(g().contactEnterMassBuffer.data());
1132}
1133
1136 return g().contactEnterMassBuffer.size() * sizeof(float);
1137}
1138
1141 return reinterpret_cast<uintptr_t>(g().contactEnterSpeedBuffer.data());
1142}
1143
1146 return g().contactEnterSpeedBuffer.size() * sizeof(float);
1147}
1148
1151 return reinterpret_cast<uintptr_t>(g().contactEnterBuffer.data());
1152}
1153
1156 return g().contactEnterBuffer.size() * sizeof(float);
1157}
1158
1161 return reinterpret_cast<uintptr_t>(g().contactExitBuffer.data());
1162}
1163
1166 return g().contactExitBuffer.size() * sizeof(float);
1167}
1168
1171 return reinterpret_cast<uintptr_t>(g().sensorEnterBuffer.data());
1172}
1173
1176 return g().sensorEnterBuffer.size() * sizeof(float);
1177}
1178
1181 return reinterpret_cast<uintptr_t>(g().sensorExitBuffer.data());
1182}
1183
1186 return g().sensorExitBuffer.size() * sizeof(float);
1187}
1188
1191 return reinterpret_cast<uintptr_t>(g().queryBuffer.data());
1192}
1193
1196 return g().queryBuffer.size() * sizeof(float);
1197}
1198
1199} // extern "C"
#define EMSCRIPTEN_KEEPALIVE
The Jolt module's entry points, declared once for both platforms.
The one 3D world a frame steps, and the layer scheme Jolt asks for.
void physics3d_setSolver(int velocityIterations, int positionIterations, int allowSleep, float bounceThreshold)
uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float cx, float cy, float cz)
int physics3d_overlapBox(float px, float py, float pz, float hx, float hy, float hz, uint32_t layerMask)
The same for a box, given its half-extents.
uintptr_t physics3d_sensorEnters()
int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask)
size_t physics3d_queryResultBytes()
size_t physics3d_sensorEntersBytes()
void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz)
void physics3d_removeCharacter(uint32_t characterId)
uintptr_t physics3d_queryResult()
void physics3d_setAwake(uint32_t bodyId, int awake)
uint32_t physics3d_addCapsule(uint32_t entity, float radius, float halfHeight, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float cx, float cy, float cz)
int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits)
uint32_t physics3d_addMeshBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount, uintptr_t indexPtr, uint32_t indexCount, float px, float py, float pz, float qx, float qy, float qz, float qw, uint32_t layer, float friction, float restitution)
Registers imported geometry as a collider.
size_t physics3d_sensorExitsBytes()
size_t physics3d_contactEnterMassesBytes()
uint32_t physics3d_addConvexBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor)
Registers the convex hull of imported geometry as a collider.
uintptr_t physics3d_characterHits()
void physics3d_setTransform(uint32_t bodyId, float px, float py, float pz, float qx, float qy, float qz, float qw)
void physics3d_setMass(uint32_t bodyId, float mass)
void physics3d_init(float gx, float gy, float gz, uint32_t maxBodies)
size_t physics3d_contactExitsBytes()
uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float mass)
void physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz)
void physics3d_shutdown()
size_t physics3d_contactEnterSpeedsBytes()
int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz, float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask)
void physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz)
A torque of (tx, ty, tz) newton metres, over the next step.
void physics3d_step(float dt, int collisionSteps)
Advance the world, then refill the transform buffer with every active body.
size_t physics3d_contactEntersBytes()
void physics3d_removeBody(uint32_t bodyId)
int physics3d_isReady()
int physics3d_isAwake(uint32_t bodyId)
uint32_t physics3d_addSphere(uint32_t entity, float radius, float px, float py, float pz, float qx, float qy, float qz, float qw, int motion, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, uint32_t layer, int continuous, float friction, float restitution, int isSensor, float cx, float cy, float cz)
void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, float pz)
Puts a character somewhere, rather than moving it there.
static void noteCharacterMeetings(uint32_t characterId, const CharacterVirtual &character, Vec3Arg velocity)
Moves a character by its velocity for one step.
int physics3d_getBodyDynamics(uint32_t bodyId)
void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz, float dt, float stepUp, float stepDown)
uintptr_t physics3d_contactEnters()
uintptr_t physics3d_transforms()
int physics3d_getBodyMassData(uint32_t bodyId)
void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz)
int physics3d_overlapSphere(float px, float py, float pz, float radius, uint32_t layerMask)
Everything a sphere at this position overlaps.
uintptr_t physics3d_sensorExits()
size_t physics3d_characterHitsBytes()
int physics3d_getBodyState(uint32_t bodyId)
uintptr_t physics3d_contactEnterSpeeds()
void physics3d_setLinearVelocity(uint32_t bodyId, float vx, float vy, float vz)
int physics3d_raycastWith(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t flags)
The world's nearest hit, or a character's when one is nearer and flags bit 0 asks for them.
int physics3d_sphereCast(float px, float py, float pz, float radius, float dx, float dy, float dz, uint32_t layerMask)
void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz)
void physics3d_optimize()
void physics3d_setGravity(float gx, float gy, float gz)
uintptr_t physics3d_contactExits()
static Quat turnOf(float qx, float qy, float qz, float qw)
A turn that is not one - zero, or not a number - is no turn.
int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight, float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask)
static int castShapeQuery(const Shape &shape, RMat44Arg start, Vec3Arg direction, uint32_t layerMask)
Sweeps a sphere along a path and reports the first thing it meets.
void physics3d_setLayerMask(uint32_t layer, uint32_t mask)
Declares which layers layer layer collides with.
uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight, float px, float py, float pz, float maxSlope, float mass, uint32_t layer, float pushForce)
Registers a character: an upright capsule swept against the world.
uintptr_t physics3d_contactEnterMasses()
size_t physics3d_transformsBytes()
static constexpr JPH::ObjectLayer of(JPH::uint layer, bool moving)
static constexpr JPH::uint indexOf(JPH::ObjectLayer layer)
static constexpr JPH::uint COUNT
uint32_t entityOf(const physx::PxActor *actor)
The entity an actor speaks for, or 0.
What the module knows about a body beyond what PhysX holds.
Everything one world owns. Built by physics3d_init, torn down by shutdown.
JPH::uint32 masks[Layers::COUNT]