Ajout de Jolt Physics + 1ere version des factory entitecomposants - camera, transform, rigidbody, collider, renderer

This commit is contained in:
Tom Ray
2026-03-22 00:28:03 +01:00
parent 6695d46bcd
commit 48348936a8
1147 changed files with 214331 additions and 353 deletions

View File

@@ -0,0 +1,267 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2025 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
// Jolt includes
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
#include <Jolt/Physics/Collision/Shape/MeshShape.h>
#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
#include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
#include <Jolt/Physics/Character/CharacterVirtual.h>
#include <Jolt/Physics/Body/BodyCreationSettings.h>
// Local includes
#include "PerformanceTestScene.h"
#include "Layers.h"
// A scene that drops a number of virtual characters on a scene and simulates them
class CharacterVirtualScene : public PerformanceTestScene, public CharacterContactListener
{
public:
virtual const char * GetName() const override
{
return "CharacterVirtual";
}
virtual bool Load(const String &inAssetPath) override
{
const int n = 100;
const float cell_size = 0.5f;
const float max_height = 2.0f;
float center = n * cell_size / 2;
// Create vertices
const int num_vertices = (n + 1) * (n + 1);
VertexList vertices;
vertices.resize(num_vertices);
for (int x = 0; x <= n; ++x)
for (int z = 0; z <= n; ++z)
{
float height = Sin(float(x) * 20.0f / n) * Cos(float(z) * 20.0f / n);
vertices[z * (n + 1) + x] = Float3(cell_size * x, max_height * height, cell_size * z);
}
// Create regular grid of triangles
const int num_triangles = n * n * 2;
IndexedTriangleList indices;
indices.resize(num_triangles);
IndexedTriangle *next = indices.data();
for (int x = 0; x < n; ++x)
for (int z = 0; z < n; ++z)
{
int start = (n + 1) * z + x;
next->mIdx[0] = start;
next->mIdx[1] = start + n + 1;
next->mIdx[2] = start + 1;
next++;
next->mIdx[0] = start + 1;
next->mIdx[1] = start + n + 1;
next->mIdx[2] = start + n + 2;
next++;
}
// Create mesh
BodyCreationSettings mesh(new MeshShapeSettings(vertices, indices), RVec3(Real(-center), 0, Real(-center)), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
mWorld.push_back(mesh);
// Create pyramid stairs
for (int i = 0; i < 10; ++i)
{
float width = 4.0f - 0.4f * i;
BodyCreationSettings step(new BoxShape(Vec3(width, 0.5f * cStairsStepHeight, width)), RVec3(-4.0_r, -1.0_r + Real(i * cStairsStepHeight), 0), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
mWorld.push_back(step);
}
// Create wall consisting of vertical pillars
Ref<Shape> wall = new BoxShape(Vec3(0.1f, 2.5f, 0.1f), 0.0f);
for (int z = 0; z < 10; ++z)
{
BodyCreationSettings bcs(wall, RVec3(2.0_r, 1.0_r, 2.0_r + 0.2_r * z), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
mWorld.push_back(bcs);
}
// Create some dynamic boxes
Ref<Shape> box = new BoxShape(Vec3::sReplicate(0.25f));
for (int x = 0; x < 10; ++x)
for (int z = 0; z < 10; ++z)
{
BodyCreationSettings bcs(box, RVec3(4.0_r * x - 20.0_r, 5.0_r, 4.0_r * z - 20.0_r), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
bcs.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
bcs.mMassPropertiesOverride.mMass = 1.0f;
mWorld.push_back(bcs);
}
return true;
}
virtual void StartTest(PhysicsSystem &inPhysicsSystem, EMotionQuality inMotionQuality) override
{
// Construct bodies
BodyInterface &bi = inPhysicsSystem.GetBodyInterface();
for (BodyCreationSettings &bcs : mWorld)
if (bcs.mMotionType == EMotionType::Dynamic)
{
bcs.mMotionQuality = inMotionQuality;
bi.CreateAndAddBody(bcs, EActivation::Activate);
}
else
bi.CreateAndAddBody(bcs, EActivation::DontActivate);
// Construct characters
CharacterID::sSetNextCharacterID();
RefConst<Shape> standing_shape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cCharacterHeightStanding, cCharacterRadiusStanding)).Create().Get();
RefConst<Shape> inner_standing_shape = RotatedTranslatedShapeSettings(Vec3(0, 0.5f * cCharacterHeightStanding + cCharacterRadiusStanding, 0), Quat::sIdentity(), new CapsuleShape(0.5f * cInnerShapeFraction * cCharacterHeightStanding, cInnerShapeFraction * cCharacterRadiusStanding)).Create().Get();
for (int y = 0; y < cNumCharactersY; ++y)
for (int x = 0; x < cNumCharactersX; ++x)
{
Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
settings->mShape = standing_shape;
settings->mSupportingVolume = Plane(Vec3::sAxisY(), -cCharacterRadiusStanding); // Accept contacts that touch the lower sphere of the capsule
settings->mInnerBodyShape = inner_standing_shape;
settings->mInnerBodyLayer = Layers::MOVING;
Ref<CharacterVirtual> character = new CharacterVirtual(settings, RVec3(4.0_r * x - 20.0_r, 2.0_r, 4.0_r * y - 20.0_r), Quat::sIdentity(), 0, &inPhysicsSystem);
character->SetCharacterVsCharacterCollision(&mCharacterVsCharacterCollision);
character->SetListener(this);
mCharacters.push_back(character);
mCharacterVsCharacterCollision.Add(character);
}
// Start at time 0
mTime = 0.0f;
mHash = HashBytes(nullptr, 0);
}
virtual void UpdateTest(PhysicsSystem &inPhysicsSystem, TempAllocator &ioTempAllocator, float inDeltaTime) override
{
// Change direction every 2 seconds
mTime += inDeltaTime;
uint64 count = uint64(mTime / 2.0f) * cNumCharactersX * cNumCharactersY;
for (CharacterVirtual *ch : mCharacters)
{
// Calculate new vertical velocity
Vec3 new_velocity;
if (ch->GetGroundState() == CharacterVirtual::EGroundState::OnGround // If on ground
&& ch->GetLinearVelocity().GetY() < 0.1f) // And not moving away from ground
new_velocity = Vec3::sZero();
else
new_velocity = ch->GetLinearVelocity() * Vec3(0, 1, 0);
new_velocity += inPhysicsSystem.GetGravity() * inDeltaTime;
// Deterministic random input
uint64 hash = Hash<uint64> {} (count);
int x = int(hash % 10);
int y = int((hash / 10) % 10);
int speed = int((hash / 100) % 10);
// Determine target position
RVec3 target = RVec3(4.0_r * x - 20.0_r, 5.0_r, 4.0_r * y - 20.0_r);
// Determine new character velocity
Vec3 direction = Vec3(target - ch->GetPosition()).NormalizedOr(Vec3::sZero());
direction.SetY(0);
new_velocity += (5.0f + 0.5f * speed) * direction;
ch->SetLinearVelocity(new_velocity);
// Update the character position
CharacterVirtual::ExtendedUpdateSettings update_settings;
ch->ExtendedUpdate(inDeltaTime,
inPhysicsSystem.GetGravity(),
update_settings,
inPhysicsSystem.GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
inPhysicsSystem.GetDefaultLayerFilter(Layers::MOVING),
{ },
{ },
ioTempAllocator);
++count;
}
}
virtual void UpdateHash(uint64 &ioHash) const override
{
// Hash the contact callback hash
HashCombine(ioHash, mHash);
// Hash the state of all characters
for (const CharacterVirtual *ch : mCharacters)
HashCombine(ioHash, ch->GetPosition());
}
virtual void StopTest(PhysicsSystem &inPhysicsSystem) override
{
for (const CharacterVirtual *ch : mCharacters)
mCharacterVsCharacterCollision.Remove(ch);
mCharacters.clear();
}
// See: CharacterContactListener
virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
{
HashCombine(mHash, 1);
HashCombine(mHash, inCharacter->GetID());
HashCombine(mHash, inBodyID2);
HashCombine(mHash, inSubShapeID2.GetValue());
HashCombine(mHash, inContactPosition);
HashCombine(mHash, inContactNormal);
}
virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
{
HashCombine(mHash, 2);
HashCombine(mHash, inCharacter->GetID());
HashCombine(mHash, inBodyID2);
HashCombine(mHash, inSubShapeID2.GetValue());
HashCombine(mHash, inContactPosition);
HashCombine(mHash, inContactNormal);
}
virtual void OnContactRemoved(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) override
{
HashCombine(mHash, 3);
HashCombine(mHash, inCharacter->GetID());
HashCombine(mHash, inBodyID2);
HashCombine(mHash, inSubShapeID2.GetValue());
}
virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
{
HashCombine(mHash, 4);
HashCombine(mHash, inCharacter->GetID());
HashCombine(mHash, inOtherCharacter->GetID());
HashCombine(mHash, inSubShapeID2.GetValue());
HashCombine(mHash, inContactPosition);
HashCombine(mHash, inContactNormal);
}
virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) override
{
HashCombine(mHash, 5);
HashCombine(mHash, inCharacter->GetID());
HashCombine(mHash, inOtherCharacter->GetID());
HashCombine(mHash, inSubShapeID2.GetValue());
HashCombine(mHash, inContactPosition);
HashCombine(mHash, inContactNormal);
}
virtual void OnCharacterContactRemoved(const CharacterVirtual *inCharacter, const CharacterID &inOtherCharacterID, const SubShapeID &inSubShapeID2) override
{
HashCombine(mHash, 6);
HashCombine(mHash, inCharacter->GetID());
HashCombine(mHash, inOtherCharacterID);
HashCombine(mHash, inSubShapeID2.GetValue());
}
private:
static constexpr int cNumCharactersX = 10;
static constexpr int cNumCharactersY = 10;
static constexpr float cCharacterHeightStanding = 1.35f;
static constexpr float cCharacterRadiusStanding = 0.3f;
static constexpr float cInnerShapeFraction = 0.9f;
static constexpr float cStairsStepHeight = 0.3f;
float mTime = 0.0f;
uint64 mHash = 0;
Array<BodyCreationSettings> mWorld;
Array<Ref<CharacterVirtual>> mCharacters;
CharacterVsCharacterCollisionSimple mCharacterVsCharacterCollision;
};

View File

@@ -0,0 +1,122 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
// Jolt includes
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
#include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
#include <Jolt/Physics/Collision/Shape/MeshShape.h>
#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
#include <Jolt/Physics/Body/BodyCreationSettings.h>
// Local includes
#include "PerformanceTestScene.h"
#include "Layers.h"
// A scene that drops a number of convex shapes on a sloping terrain made out of a mesh shape
class ConvexVsMeshScene : public PerformanceTestScene
{
public:
virtual const char * GetName() const override
{
return "ConvexVsMesh";
}
virtual bool Load(const String &inAssetPath) override
{
const int n = 100;
const float cell_size = 3.0f;
const float max_height = 5.0f;
float center = n * cell_size / 2;
// Create vertices
const int num_vertices = (n + 1) * (n + 1);
VertexList vertices;
vertices.resize(num_vertices);
for (int x = 0; x <= n; ++x)
for (int z = 0; z <= n; ++z)
{
float height = Sin(float(x) * 50.0f / n) * Cos(float(z) * 50.0f / n);
vertices[z * (n + 1) + x] = Float3(cell_size * x, max_height * height, cell_size * z);
}
// Create regular grid of triangles
const int num_triangles = n * n * 2;
IndexedTriangleList indices;
indices.resize(num_triangles);
IndexedTriangle *next = indices.data();
for (int x = 0; x < n; ++x)
for (int z = 0; z < n; ++z)
{
int start = (n + 1) * z + x;
next->mIdx[0] = start;
next->mIdx[1] = start + n + 1;
next->mIdx[2] = start + 1;
next++;
next->mIdx[0] = start + 1;
next->mIdx[1] = start + n + 1;
next->mIdx[2] = start + n + 2;
next++;
}
// Create mesh shape settings
Ref<MeshShapeSettings> mesh_shape_settings = new MeshShapeSettings(vertices, indices);
mesh_shape_settings->mMaxTrianglesPerLeaf = 4;
// Create mesh shape creation settings
mMeshSettings.mMotionType = EMotionType::Static;
mMeshSettings.mObjectLayer = Layers::NON_MOVING;
mMeshSettings.mPosition = RVec3(Real(-center), Real(max_height), Real(-center));
mMeshSettings.mFriction = 0.5f;
mMeshSettings.mRestitution = 0.6f;
mMeshSettings.SetShapeSettings(mesh_shape_settings);
// Create other shapes
mShapes = {
new BoxShape(Vec3(0.5f, 0.75f, 1.0f)),
new SphereShape(0.5f),
new CapsuleShape(0.75f, 0.5f),
ConvexHullShapeSettings({ Vec3(0, 1, 0), Vec3(1, 0, 0), Vec3(-1, 0, 0), Vec3(0, 0, 1), Vec3(0, 0, -1) }).Create().Get(),
};
return true;
}
virtual void StartTest(PhysicsSystem &inPhysicsSystem, EMotionQuality inMotionQuality) override
{
// Reduce the solver iteration count, the scene doesn't have any constraints so we don't need the default amount of iterations
PhysicsSettings settings = inPhysicsSystem.GetPhysicsSettings();
settings.mNumVelocitySteps = 4;
settings.mNumPositionSteps = 1;
inPhysicsSystem.SetPhysicsSettings(settings);
// Create background
BodyInterface &bi = inPhysicsSystem.GetBodyInterface();
bi.CreateAndAddBody(mMeshSettings, EActivation::DontActivate);
// Construct bodies
for (int x = -10; x <= 10; ++x)
for (int y = 0; y < (int)mShapes.size(); ++y)
for (int z = -10; z <= 10; ++z)
{
BodyCreationSettings creation_settings;
creation_settings.mMotionType = EMotionType::Dynamic;
creation_settings.mMotionQuality = inMotionQuality;
creation_settings.mObjectLayer = Layers::MOVING;
creation_settings.mPosition = RVec3(7.5_r * x, 15.0_r + 2.0_r * y, 7.5_r * z);
creation_settings.mFriction = 0.5f;
creation_settings.mRestitution = 0.6f;
creation_settings.SetShape(mShapes[y]);
bi.CreateAndAddBody(creation_settings, EActivation::Activate);
}
}
private:
BodyCreationSettings mMeshSettings;
Array<Ref<Shape>> mShapes;
};

View File

@@ -0,0 +1,118 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2024 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
// Jolt includes
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
#include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
#include <Jolt/Physics/Collision/Shape/MeshShape.h>
#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
#include <Jolt/Physics/Body/BodyCreationSettings.h>
// Local includes
#include "PerformanceTestScene.h"
#include "Layers.h"
// A scene that first finds the largest possible mesh and then simulates some objects on it
class LargeMeshScene : public PerformanceTestScene
{
public:
virtual const char * GetName() const override
{
return "LargeMeshScene";
}
virtual bool Load(const String &inAssetPath) override
{
// Create mesh shape creation settings
mMeshCreationSettings.mMotionType = EMotionType::Static;
mMeshCreationSettings.mObjectLayer = Layers::NON_MOVING;
mMeshCreationSettings.mPosition = RVec3::sZero();
mMeshCreationSettings.mFriction = 0.5f;
mMeshCreationSettings.mRestitution = 0.6f;
Trace("Finding the largest possible mesh, this will take some time!");
Trace("N, Num Triangles, Mesh Size, Size / Triangle, SubShapeID Bits, Time");
for (int i = 1; ; ++i)
{
const int n = 500 * i;
const float cell_size = 1.0f;
const float max_height = 50.0f;
// Create heights
MeshShapeSettings settings;
float center = n * cell_size / 2;
settings.mTriangleVertices.reserve((n + 1)*(n + 1));
for (int x = 0; x <= n; ++x)
for (int z = 0; z <= n; ++z)
settings.mTriangleVertices.push_back(Float3(cell_size * x - center, max_height * Sin(float(x) * 50.0f / n) * Cos(float(z) * 50.0f / n), cell_size * z - center));
// Create regular grid of triangles
settings.mIndexedTriangles.reserve(2 * n * n);
for (int x = 0; x < n; ++x)
for (int z = 0; z < n; ++z)
{
settings.mIndexedTriangles.push_back(IndexedTriangle(x + z * (n + 1), x + 1 + z * (n + 1), x + (z + 1)*(n + 1)));
settings.mIndexedTriangles.push_back(IndexedTriangle(x + 1 + z * (n + 1), x + 1 + (z + 1)*(n + 1), x + (z + 1)*(n + 1)));
}
// Start measuring
chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
// Create the mesh shape
Shape::ShapeResult result = settings.Create();
// Stop measuring
chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
chrono::nanoseconds duration = chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
if (result.HasError())
{
// Break when we get an error
Trace("Mesh creation failed with error: %s", result.GetError().c_str());
break;
}
else
{
// Trace stats
RefConst<Shape> shape = result.Get();
Shape::Stats stats = shape->GetStats();
Trace("%u, %u, %llu, %.1f, %d, %.3f", n, stats.mNumTriangles, (uint64)stats.mSizeBytes, double(stats.mSizeBytes) / double(stats.mNumTriangles), shape->GetSubShapeIDBitsRecursive(), 1.0e-9 * double(duration.count()));
// Set this shape as the best shape so far
mMeshCreationSettings.SetShape(shape);
}
}
return true;
}
virtual void StartTest(PhysicsSystem &inPhysicsSystem, EMotionQuality inMotionQuality) override
{
// Create background
BodyInterface &bi = inPhysicsSystem.GetBodyInterface();
bi.CreateAndAddBody(mMeshCreationSettings, EActivation::DontActivate);
// Construct bodies
BodyCreationSettings creation_settings;
creation_settings.mMotionType = EMotionType::Dynamic;
creation_settings.mMotionQuality = inMotionQuality;
creation_settings.mObjectLayer = Layers::MOVING;
creation_settings.mFriction = 0.5f;
creation_settings.mRestitution = 0.6f;
creation_settings.SetShape(new BoxShape(Vec3(0.5f, 0.75f, 1.0f)));
for (int x = -10; x <= 10; ++x)
for (int y = 0; y < 10; ++y)
for (int z = -10; z <= 10; ++z)
{
creation_settings.mPosition = RVec3(7.5_r * x, 55.0_r + 2.0_r * y, 7.5_r * z);
bi.CreateAndAddBody(creation_settings, EActivation::Activate);
}
}
private:
BodyCreationSettings mMeshCreationSettings;
};

View File

@@ -0,0 +1,100 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/ObjectLayer.h>
#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>
/// Layer that objects can be in, determines which other objects it can collide with
namespace Layers
{
static constexpr ObjectLayer NON_MOVING = 0;
static constexpr ObjectLayer MOVING = 1;
static constexpr ObjectLayer NUM_LAYERS = 2;
};
/// Class that determines if two object layers can collide
class ObjectLayerPairFilterImpl : public ObjectLayerPairFilter
{
public:
virtual bool ShouldCollide(ObjectLayer inObject1, ObjectLayer inObject2) const override
{
switch (inObject1)
{
case Layers::NON_MOVING:
return inObject2 == Layers::MOVING; // Non moving only collides with moving
case Layers::MOVING:
return true; // Moving collides with everything
default:
JPH_ASSERT(false);
return false;
}
}
};
/// Broadphase layers
namespace BroadPhaseLayers
{
static constexpr BroadPhaseLayer NON_MOVING(0);
static constexpr BroadPhaseLayer MOVING(1);
static constexpr uint NUM_LAYERS(2);
};
/// BroadPhaseLayerInterface implementation
class BPLayerInterfaceImpl final : public BroadPhaseLayerInterface
{
public:
BPLayerInterfaceImpl()
{
// Create a mapping table from object to broad phase layer
mObjectToBroadPhase[Layers::NON_MOVING] = BroadPhaseLayers::NON_MOVING;
mObjectToBroadPhase[Layers::MOVING] = BroadPhaseLayers::MOVING;
}
virtual uint GetNumBroadPhaseLayers() const override
{
return BroadPhaseLayers::NUM_LAYERS;
}
virtual BroadPhaseLayer GetBroadPhaseLayer(ObjectLayer inLayer) const override
{
JPH_ASSERT(inLayer < Layers::NUM_LAYERS);
return mObjectToBroadPhase[inLayer];
}
#if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
virtual const char * GetBroadPhaseLayerName(BroadPhaseLayer inLayer) const override
{
switch ((BroadPhaseLayer::Type)inLayer)
{
case (BroadPhaseLayer::Type)BroadPhaseLayers::NON_MOVING: return "NON_MOVING";
case (BroadPhaseLayer::Type)BroadPhaseLayers::MOVING: return "MOVING";
default: JPH_ASSERT(false); return "INVALID";
}
}
#endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
private:
BroadPhaseLayer mObjectToBroadPhase[Layers::NUM_LAYERS];
};
/// Class that determines if an object layer can collide with a broadphase layer
class ObjectVsBroadPhaseLayerFilterImpl : public ObjectVsBroadPhaseLayerFilter
{
public:
virtual bool ShouldCollide(ObjectLayer inLayer1, BroadPhaseLayer inLayer2) const override
{
switch (inLayer1)
{
case Layers::NON_MOVING:
return inLayer2 == BroadPhaseLayers::MOVING;
case Layers::MOVING:
return true;
default:
JPH_ASSERT(false);
return false;
}
}
};

View File

@@ -0,0 +1,81 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2025 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
// Jolt includes
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
#include <Jolt/Physics/Body/BodyCreationSettings.h>
// Local includes
#include "PerformanceTestScene.h"
#include "Layers.h"
// A scene that creates the max number of bodies that Jolt supports and simulates them
class MaxBodiesScene : public PerformanceTestScene
{
public:
virtual const char * GetName() const override
{
return "MaxBodies";
}
virtual size_t GetTempAllocatorSizeMB() const override
{
return 8192;
}
virtual uint GetMaxBodies() const override
{
return PhysicsSystem::cMaxBodiesLimit;
}
virtual uint GetMaxBodyPairs() const override
{
return PhysicsSystem::cMaxBodyPairsLimit;
}
virtual uint GetMaxContactConstraints() const override
{
return PhysicsSystem::cMaxContactConstraintsLimit;
}
virtual void StartTest(PhysicsSystem &inPhysicsSystem, EMotionQuality inMotionQuality) override
{
BodyInterface &bi = inPhysicsSystem.GetBodyInterface();
// Reduce the solver iteration count in the interest of performance
PhysicsSettings settings = inPhysicsSystem.GetPhysicsSettings();
settings.mNumVelocitySteps = 4;
settings.mNumPositionSteps = 1;
inPhysicsSystem.SetPhysicsSettings(settings);
// Create the bodies
uint num_bodies = inPhysicsSystem.GetMaxBodies();
uint num_constraints = 0;
BodyIDVector body_ids;
body_ids.reserve(num_bodies);
uint num_per_axis = uint(pow(float(num_bodies), 1.0f / 3.0f)) + 1;
Vec3 half_extent = Vec3::sReplicate(0.5f);
BodyCreationSettings bcs(new BoxShape(half_extent), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
bcs.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
bcs.mMassPropertiesOverride.SetMassAndInertiaOfSolidBox(2.0f * half_extent, 1000.0f);
for (uint z = 0; z < num_per_axis && body_ids.size() < num_bodies; ++z)
for (uint y = 0; y < num_per_axis && body_ids.size() < num_bodies; ++y)
for (uint x = 0; x < num_per_axis && body_ids.size() < num_bodies; ++x)
{
// When we reach the limit of contact constraints, start placing the boxes further apart so they don't collide
bcs.mPosition = RVec3(num_constraints < PhysicsSystem::cMaxContactConstraintsLimit? Real(x) : 2.0_r * x, 2.0_r * y, 2.0_r * z);
body_ids.push_back(bi.CreateBody(bcs)->GetID());
// From the 2nd box onwards in a row, we will get a contact constraint
if (x > 0)
++num_constraints;
}
// Add the bodies to the simulation
BodyInterface::AddState state = bi.AddBodiesPrepare(body_ids.data(), num_bodies);
bi.AddBodiesFinalize(body_ids.data(), num_bodies, state, EActivation::Activate);
}
};

View File

@@ -0,0 +1,19 @@
# Root
set(PERFORMANCE_TEST_ROOT ${PHYSICS_REPO_ROOT}/PerformanceTest)
# Source files
set(PERFORMANCE_TEST_SRC_FILES
${PERFORMANCE_TEST_ROOT}/PyramidScene.h
${PERFORMANCE_TEST_ROOT}/PerformanceTest.cpp
${PERFORMANCE_TEST_ROOT}/PerformanceTest.cmake
${PERFORMANCE_TEST_ROOT}/PerformanceTestScene.h
${PERFORMANCE_TEST_ROOT}/RagdollScene.h
${PERFORMANCE_TEST_ROOT}/ConvexVsMeshScene.h
${PERFORMANCE_TEST_ROOT}/CharacterVirtualScene.h
${PERFORMANCE_TEST_ROOT}/LargeMeshScene.h
${PERFORMANCE_TEST_ROOT}/Layers.h
${PERFORMANCE_TEST_ROOT}/MaxBodiesScene.h
)
# Group source files
source_group(TREE ${PERFORMANCE_TEST_ROOT} FILES ${PERFORMANCE_TEST_SRC_FILES})

View File

@@ -0,0 +1,517 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
// Jolt includes
#include <Jolt/Jolt.h>
#include <Jolt/ConfigurationString.h>
#include <Jolt/RegisterTypes.h>
#include <Jolt/Core/Factory.h>
#include <Jolt/Core/TempAllocator.h>
#include <Jolt/Core/JobSystemThreadPool.h>
#include <Jolt/Physics/PhysicsSettings.h>
#include <Jolt/Physics/PhysicsSystem.h>
#include <Jolt/Physics/Collision/NarrowPhaseStats.h>
#include <Jolt/Physics/StateRecorderImpl.h>
#include <Jolt/Physics/DeterminismLog.h>
#ifdef JPH_DEBUG_RENDERER
#include <Jolt/Renderer/DebugRendererRecorder.h>
#include <Jolt/Core/StreamWrapper.h>
#endif // JPH_DEBUG_RENDERER
#ifdef JPH_PLATFORM_ANDROID
#include <android/log.h>
#include <android_native_app_glue.h>
#endif // JPH_PLATFORM_ANDROID
// STL includes
JPH_SUPPRESS_WARNINGS_STD_BEGIN
#include <iostream>
#include <thread>
#include <chrono>
#include <memory>
#include <cstdarg>
#include <filesystem>
JPH_SUPPRESS_WARNINGS_STD_END
using namespace JPH;
using namespace JPH::literals;
using namespace std;
// Disable common warnings triggered by Jolt
JPH_SUPPRESS_WARNINGS
// Local includes
#include "RagdollScene.h"
#include "ConvexVsMeshScene.h"
#include "PyramidScene.h"
#include "LargeMeshScene.h"
#include "CharacterVirtualScene.h"
#include "MaxBodiesScene.h"
// Time step for physics
constexpr float cDeltaTime = 1.0f / 60.0f;
static void TraceImpl(const char *inFMT, ...)
{
// Format the message
va_list list;
va_start(list, inFMT);
char buffer[1024];
vsnprintf(buffer, sizeof(buffer), inFMT, list);
va_end(list);
// Print to the TTY
#ifndef JPH_PLATFORM_ANDROID
cout << buffer << endl;
#else
__android_log_write(ANDROID_LOG_INFO, "Jolt", buffer);
#endif
}
// Program entry point
int main(int argc, char** argv)
{
// Install callbacks
Trace = TraceImpl;
// Register allocation hook
RegisterDefaultAllocator();
// Helper function that creates the default scene
#ifdef JPH_OBJECT_STREAM
auto create_ragdoll_scene = []{ return unique_ptr<PerformanceTestScene>(new RagdollScene(4, 10, 0.6f)); };
#else
auto create_ragdoll_scene = []{ return unique_ptr<PerformanceTestScene>(new ConvexVsMeshScene); };
#endif // JPH_OBJECT_STREAM
// Parse command line parameters
int specified_quality = -1;
int specified_threads = -1;
uint max_iterations = 500;
bool disable_sleep = false;
bool enable_profiler = false;
#ifdef JPH_DEBUG_RENDERER
bool enable_debug_renderer = false;
#endif // JPH_DEBUG_RENDERER
bool enable_per_frame_recording = false;
bool record_state = false;
bool validate_state = false;
unique_ptr<PerformanceTestScene> scene;
const char *validate_hash = nullptr;
int repeat = 1;
for (int argidx = 1; argidx < argc; ++argidx)
{
const char *arg = argv[argidx];
if (strncmp(arg, "-s=", 3) == 0)
{
// Parse scene
if (strcmp(arg + 3, "Ragdoll") == 0)
scene = create_ragdoll_scene();
#ifdef JPH_OBJECT_STREAM
else if (strcmp(arg + 3, "RagdollSinglePile") == 0)
scene = unique_ptr<PerformanceTestScene>(new RagdollScene(1, 160, 0.4f));
#endif // JPH_OBJECT_STREAM
else if (strcmp(arg + 3, "ConvexVsMesh") == 0)
scene = unique_ptr<PerformanceTestScene>(new ConvexVsMeshScene);
else if (strcmp(arg + 3, "Pyramid") == 0)
scene = unique_ptr<PerformanceTestScene>(new PyramidScene);
else if (strcmp(arg + 3, "LargeMesh") == 0)
scene = unique_ptr<PerformanceTestScene>(new LargeMeshScene);
else if (strcmp(arg + 3, "CharacterVirtual") == 0)
scene = unique_ptr<PerformanceTestScene>(new CharacterVirtualScene);
else if (strcmp(arg + 3, "MaxBodies") == 0)
scene = unique_ptr<MaxBodiesScene>(new MaxBodiesScene);
else
{
Trace("Invalid scene");
return 1;
}
}
else if (strncmp(arg, "-i=", 3) == 0)
{
// Parse max iterations
max_iterations = (uint)atoi(arg + 3);
}
else if (strncmp(arg, "-q=", 3) == 0)
{
// Parse quality
if (strcmp(arg + 3, "Discrete") == 0)
specified_quality = 0;
else if (strcmp(arg + 3, "LinearCast") == 0)
specified_quality = 1;
else
{
Trace("Invalid quality");
return 1;
}
}
else if (strncmp(arg, "-t=max", 6) == 0)
{
// Default to number of threads on the system
specified_threads = thread::hardware_concurrency();
}
else if (strncmp(arg, "-t=", 3) == 0)
{
// Parse threads
specified_threads = atoi(arg + 3);
}
else if (strcmp(arg, "-no_sleep") == 0)
{
disable_sleep = true;
}
else if (strcmp(arg, "-p") == 0)
{
enable_profiler = true;
}
#ifdef JPH_DEBUG_RENDERER
else if (strcmp(arg, "-r") == 0)
{
enable_debug_renderer = true;
}
#endif // JPH_DEBUG_RENDERER
else if (strcmp(arg, "-f") == 0)
{
enable_per_frame_recording = true;
}
else if (strcmp(arg, "-rs") == 0)
{
record_state = true;
}
else if (strcmp(arg, "-vs") == 0)
{
validate_state = true;
}
else if (strncmp(arg, "-validate_hash=", 15) == 0)
{
validate_hash = arg + 15;
}
else if (strncmp(arg, "-repeat=", 8) == 0)
{
// Parse repeat count
repeat = atoi(arg + 8);
}
else if (strcmp(arg, "-h") == 0)
{
// Print usage
Trace("Usage:\n"
"-s=<scene>: Select scene (Ragdoll, RagdollSinglePile, ConvexVsMesh, Pyramid)\n"
"-i=<num physics steps>: Number of physics steps to simulate (default 500)\n"
"-q=<quality>: Test only with specified quality (Discrete, LinearCast)\n"
"-t=<num threads>: Test only with N threads (default is to iterate over 1 .. num hardware threads)\n"
"-t=max: Test with the number of threads available on the system\n"
"-p: Write out profiles\n"
"-r: Record debug renderer output for JoltViewer\n"
"-f: Record per frame timings\n"
"-no_sleep: Disable sleeping\n"
"-rs: Record state\n"
"-vs: Validate state\n"
"-validate_hash=<hash>: Validate hash (return 0 if successful, 1 if failed)\n"
"-repeat=<num>: Repeat all tests <num> times");
return 0;
}
}
// Create a factory
Factory::sInstance = new Factory();
// Register all Jolt physics types
RegisterTypes();
// Show used instruction sets
Trace(GetConfigurationString());
// If no scene was specified use the default scene
if (scene == nullptr)
scene = create_ragdoll_scene();
// Output scene we're running
Trace("Running scene: %s", scene->GetName());
// Create temp allocator
TempAllocatorImpl temp_allocator(scene->GetTempAllocatorSizeMB() * 1024 * 1024);
// Find the asset path
bool found = false;
filesystem::path asset_path(argv[0]);
filesystem::path root_path = asset_path.root_path();
while (asset_path != root_path)
{
asset_path = asset_path.parent_path();
if (filesystem::exists(asset_path / "Assets"))
{
found = true;
break;
}
}
if (!found) // Note that argv[0] can be a relative path like './PerformanceTest' so we also scan up using '..'
for (int i = 0; i < 5; ++i)
{
asset_path /= "..";
if (filesystem::exists(asset_path / "Assets"))
{
found = true;
break;
}
}
if (!found)
asset_path = "Assets";
else
asset_path /= "Assets";
asset_path /= "";
// Load the scene
if (!scene->Load(String(asset_path.string())))
return 1;
// Create mapping table from object layer to broadphase layer
BPLayerInterfaceImpl broad_phase_layer_interface;
// Create class that filters object vs broadphase layers
ObjectVsBroadPhaseLayerFilterImpl object_vs_broadphase_layer_filter;
// Create class that filters object vs object layers
ObjectLayerPairFilterImpl object_vs_object_layer_filter;
// Start profiling this program
JPH_PROFILE_START("Main");
// Trace header
Trace("Motion Quality, Thread Count, Steps / Second, Hash");
// Repeat test
for (int r = 0; r < repeat; ++r)
{
// Iterate motion qualities
for (uint mq = 0; mq < 2; ++mq)
{
// Skip quality if another was specified
if (specified_quality != -1 && mq != (uint)specified_quality)
continue;
// Determine motion quality
EMotionQuality motion_quality = mq == 0? EMotionQuality::Discrete : EMotionQuality::LinearCast;
String motion_quality_str = mq == 0? "Discrete" : "LinearCast";
// Determine which thread counts to test
Array<uint> thread_permutations;
if (specified_threads > 0)
thread_permutations.push_back((uint)specified_threads - 1);
else
for (uint num_threads = 0; num_threads < thread::hardware_concurrency(); ++num_threads)
thread_permutations.push_back(num_threads);
// Test thread permutations
for (uint num_threads : thread_permutations)
{
// Create job system with desired number of threads
JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, num_threads);
// Create physics system
PhysicsSystem physics_system;
physics_system.Init(scene->GetMaxBodies(), 0, scene->GetMaxBodyPairs(), scene->GetMaxContactConstraints(), broad_phase_layer_interface, object_vs_broadphase_layer_filter, object_vs_object_layer_filter);
// Start test scene
scene->StartTest(physics_system, motion_quality);
// Disable sleeping if requested
if (disable_sleep)
{
const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
BodyIDVector body_ids;
physics_system.GetBodies(body_ids);
for (BodyID id : body_ids)
{
BodyLockWrite lock(bli, id);
if (lock.Succeeded())
{
Body &body = lock.GetBody();
if (!body.IsStatic())
body.SetAllowSleeping(false);
}
}
}
// Optimize the broadphase to prevent an expensive first frame
physics_system.OptimizeBroadPhase();
// A tag used to identify the test
String tag = ToLower(motion_quality_str) + "_th" + ConvertToString(num_threads + 1);
#ifdef JPH_DEBUG_RENDERER
// Open renderer output
ofstream renderer_file;
if (enable_debug_renderer)
renderer_file.open(("performance_test_" + tag + ".jor").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
StreamOutWrapper renderer_stream(renderer_file);
DebugRendererRecorder renderer(renderer_stream);
#endif // JPH_DEBUG_RENDERER
// Open per frame timing output
ofstream per_frame_file;
if (enable_per_frame_recording)
{
per_frame_file.open(("per_frame_" + tag + ".csv").c_str(), ofstream::out | ofstream::trunc);
per_frame_file << "Frame, Time (ms)" << endl;
}
ofstream record_state_file;
ifstream validate_state_file;
if (record_state)
record_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
else if (validate_state)
validate_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ifstream::in | ifstream::binary);
chrono::nanoseconds total_duration(0);
// Step the world for a fixed amount of iterations
for (uint iterations = 0; iterations < max_iterations; ++iterations)
{
JPH_PROFILE_NEXTFRAME();
JPH_DET_LOG("Iteration: " << iterations);
// Start measuring
chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
// Update the test
scene->UpdateTest(physics_system, temp_allocator, cDeltaTime);
// Do a physics step
physics_system.Update(cDeltaTime, 1, &temp_allocator, &job_system);
// Stop measuring
chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
chrono::nanoseconds duration = chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
total_duration += duration;
#ifdef JPH_DEBUG_RENDERER
if (enable_debug_renderer)
{
// Draw the state of the world
BodyManager::DrawSettings settings;
physics_system.DrawBodies(settings, &renderer);
// Mark end of frame
renderer.EndFrame();
}
#endif // JPH_DEBUG_RENDERER
// Record time taken this iteration
if (enable_per_frame_recording)
per_frame_file << iterations << ", " << (1.0e-6 * duration.count()) << endl;
// Dump profile information every 100 iterations
if (enable_profiler && iterations % 100 == 0)
{
JPH_PROFILE_DUMP(tag + "_it" + ConvertToString(iterations));
}
if (record_state)
{
// Record state
StateRecorderImpl recorder;
physics_system.SaveState(recorder);
// Write to file
string data = recorder.GetData();
uint32 size = uint32(data.size());
record_state_file.write((char *)&size, sizeof(size));
record_state_file.write(data.data(), size);
}
else if (validate_state)
{
// Read state
uint32 size = 0;
validate_state_file.read((char *)&size, sizeof(size));
string data;
data.resize(size);
validate_state_file.read(data.data(), size);
// Copy to validator
StateRecorderImpl validator;
validator.WriteBytes(data.data(), size);
// Validate state
validator.SetValidating(true);
physics_system.RestoreState(validator);
}
#ifdef JPH_ENABLE_DETERMINISM_LOG
const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
BodyIDVector body_ids;
physics_system.GetBodies(body_ids);
for (BodyID id : body_ids)
{
BodyLockRead lock(bli, id);
const Body &body = lock.GetBody();
if (!body.IsStatic())
JPH_DET_LOG(id << ": p: " << body.GetPosition() << " r: " << body.GetRotation() << " v: " << body.GetLinearVelocity() << " w: " << body.GetAngularVelocity());
}
#endif // JPH_ENABLE_DETERMINISM_LOG
}
// Calculate hash of all positions and rotations of the bodies
uint64 hash = HashBytes(nullptr, 0); // Ensure we start with the proper seed
BodyInterface &bi = physics_system.GetBodyInterfaceNoLock();
BodyIDVector body_ids;
physics_system.GetBodies(body_ids);
for (BodyID id : body_ids)
{
RVec3 pos = bi.GetPosition(id);
hash = HashBytes(&pos, 3 * sizeof(Real), hash);
Quat rot = bi.GetRotation(id);
hash = HashBytes(&rot, sizeof(Quat), hash);
}
// Let the scene hash its own state
scene->UpdateHash(hash);
// Convert hash to string
stringstream hash_stream;
hash_stream << "0x" << hex << hash << dec;
string hash_str = hash_stream.str();
// Stop test scene
scene->StopTest(physics_system);
// Trace stat line
Trace("%s, %d, %f, %s", motion_quality_str.c_str(), num_threads + 1, double(max_iterations) / (1.0e-9 * total_duration.count()), hash_str.c_str());
// Check hash code
if (validate_hash != nullptr && hash_str != validate_hash)
{
Trace("Fail hash validation. Was: %s, expected: %s", hash_str.c_str(), validate_hash);
return 1;
}
}
}
}
#ifdef JPH_TRACK_NARROWPHASE_STATS
NarrowPhaseStat::sReportStats();
#endif // JPH_TRACK_NARROWPHASE_STATS
// Unregisters all types with the factory and cleans up the default material
UnregisterTypes();
// Destroy the factory
delete Factory::sInstance;
Factory::sInstance = nullptr;
// End profiling this program
JPH_PROFILE_END();
return 0;
}
#ifdef JPH_PLATFORM_ANDROID
// Main entry point for android
void android_main(struct android_app *ioApp)
{
// Run the regular main function
const char *args[] = { "Unused", "-s=ConvexVsMesh", "-t=max" };
main(size(args), (char **)args);
}
#endif // JPH_PLATFORM_ANDROID

View File

@@ -0,0 +1,43 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
// Base class for a test scene to test performance
class PerformanceTestScene
{
public:
// Virtual destructor
virtual ~PerformanceTestScene() { }
// Get name of test for debug purposes
virtual const char * GetName() const = 0;
// Get the number of MB that the temp allocator should preallocate
virtual size_t GetTempAllocatorSizeMB() const { return 32; }
// Get the max number of bodies to support in the physics system
virtual uint GetMaxBodies() const { return 10240; }
// Get the max number of body pairs to support in the physics system
virtual uint GetMaxBodyPairs() const { return 65536; }
// Get the max number of contact constraints to support in the physics system
virtual uint GetMaxContactConstraints() const { return 20480; }
// Load assets for the scene
virtual bool Load([[maybe_unused]] const String &inAssetPath) { return true; }
// Start a new test by adding objects to inPhysicsSystem
virtual void StartTest(PhysicsSystem &inPhysicsSystem, EMotionQuality inMotionQuality) = 0;
// Step the test
virtual void UpdateTest([[maybe_unused]] PhysicsSystem &inPhysicsSystem, [[maybe_unused]] TempAllocator &ioTempAllocator, [[maybe_unused]] float inDeltaTime) { }
// Update the hash with the state of the scene
virtual void UpdateHash([[maybe_unused]] uint64 &ioHash) const { }
// Stop a test and remove objects from inPhysicsSystem
virtual void StopTest(PhysicsSystem &inPhysicsSystem) { }
};

View File

@@ -0,0 +1,48 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2023 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
// Jolt includes
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
// Local includes
#include "PerformanceTestScene.h"
#include "Layers.h"
// A scene that creates a pyramid of boxes to create a very large island
class PyramidScene : public PerformanceTestScene
{
public:
virtual const char * GetName() const override
{
return "Pyramid";
}
virtual void StartTest(PhysicsSystem &inPhysicsSystem, EMotionQuality inMotionQuality) override
{
BodyInterface &bi = inPhysicsSystem.GetBodyInterface();
// Floor
bi.CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(50.0f, 1.0f, 50.0f), 0.0f), RVec3(Vec3(0.0f, -1.0f, 0.0f)), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::DontActivate);
const float cBoxSize = 2.0f;
const float cBoxSeparation = 0.5f;
const float cHalfBoxSize = 0.5f * cBoxSize;
const int cPyramidHeight = 15;
RefConst<Shape> box_shape = new BoxShape(Vec3::sReplicate(cHalfBoxSize), 0.0f); // No convex radius to force more collisions
// Pyramid
for (int i = 0; i < cPyramidHeight; ++i)
for (int j = i / 2; j < cPyramidHeight - (i + 1) / 2; ++j)
for (int k = i / 2; k < cPyramidHeight - (i + 1) / 2; ++k)
{
RVec3 position(Real(-cPyramidHeight + cBoxSize * j + (i & 1? cHalfBoxSize : 0.0f)), Real(1.0f + (cBoxSize + cBoxSeparation) * i), Real(-cPyramidHeight + cBoxSize * k + (i & 1? cHalfBoxSize : 0.0f)));
BodyCreationSettings settings(box_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
settings.mAllowSleeping = false; // No sleeping to force the large island to stay awake
bi.CreateAndAddBody(settings, EActivation::Activate);
}
}
};

View File

@@ -0,0 +1,144 @@
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
// Jolt includes
#include <Jolt/Physics/Ragdoll/Ragdoll.h>
#include <Jolt/Physics/PhysicsScene.h>
#include <Jolt/Physics/Collision/CastResult.h>
#include <Jolt/Physics/Collision/RayCast.h>
#include <Jolt/ObjectStream/ObjectStreamIn.h>
// Local includes
#include "PerformanceTestScene.h"
#include "Layers.h"
#ifdef JPH_OBJECT_STREAM
// A scene that loads a part of a Horizon Zero Dawn level and drops many ragdolls on the terrain (motors enabled)
class RagdollScene : public PerformanceTestScene
{
public:
RagdollScene(int inNumPilesPerAxis, int inPileSize, float inVerticalSeparation) : mNumPilesPerAxis(inNumPilesPerAxis), mPileSize(inPileSize), mVerticalSeparation(inVerticalSeparation) { }
virtual const char * GetName() const override
{
return mNumPilesPerAxis == 1? "RagdollSinglePile" : "Ragdoll";
}
virtual bool Load(const String &inAssetPath) override
{
// Load ragdoll
if (!ObjectStreamIn::sReadObject((inAssetPath + "Human.tof").c_str(), mRagdollSettings))
{
cerr << "Unable to load ragdoll" << endl;
return false;
}
for (BodyCreationSettings &body : mRagdollSettings->mParts)
body.mObjectLayer = Layers::MOVING;
// Init ragdoll
mRagdollSettings->GetSkeleton()->CalculateParentJointIndices();
mRagdollSettings->Stabilize();
mRagdollSettings->CalculateBodyIndexToConstraintIndex();
mRagdollSettings->CalculateConstraintIndexToBodyIdxPair();
// Load animation
if (!ObjectStreamIn::sReadObject((inAssetPath + "Human/dead_pose1.tof").c_str(), mAnimation))
{
cerr << "Unable to load animation" << endl;
return false;
}
// Sample pose
mPose.SetSkeleton(mRagdollSettings->GetSkeleton());
mAnimation->Sample(0.0f, mPose);
// Read the background scene
if (!ObjectStreamIn::sReadObject((inAssetPath + "terrain2.bof").c_str(), mBackground))
{
cerr << "Unable to load terrain" << endl;
return false;
}
for (BodyCreationSettings &body : mBackground->GetBodies())
body.mObjectLayer = Layers::NON_MOVING;
mBackground->FixInvalidScales();
return true;
}
virtual void StartTest(PhysicsSystem &inPhysicsSystem, EMotionQuality inMotionQuality) override
{
// Test configuration
const Real cHorizontalSeparation = 4.0_r;
// Set motion quality on ragdoll
for (BodyCreationSettings &body : mRagdollSettings->mParts)
body.mMotionQuality = inMotionQuality;
// Add background geometry
mBackground->CreateBodies(&inPhysicsSystem);
// Create ragdoll piles
CollisionGroup::GroupID group_id = 1;
for (int row = 0; row < mNumPilesPerAxis; ++row)
for (int col = 0; col < mNumPilesPerAxis; ++col)
{
// Determine start location of ray
RVec3 start(cHorizontalSeparation * (col - (mNumPilesPerAxis - 1) / 2.0_r), 100, cHorizontalSeparation * (row - (mNumPilesPerAxis - 1) / 2.0_r));
// Cast ray down to terrain
RayCastResult hit;
Vec3 ray_direction(0, -200, 0);
RRayCast ray { start, ray_direction };
if (inPhysicsSystem.GetNarrowPhaseQuery().CastRay(ray, hit, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::NON_MOVING), SpecifiedObjectLayerFilter(Layers::NON_MOVING)))
start = ray.GetPointOnRay(hit.mFraction);
for (int i = 0; i < mPileSize; ++i)
{
// Create ragdoll
Ref<Ragdoll> ragdoll = mRagdollSettings->CreateRagdoll(group_id++, 0, &inPhysicsSystem);
// Override root
SkeletonPose pose_copy = mPose;
pose_copy.SetRootOffset(start);
SkeletonPose::JointState &root = pose_copy.GetJoint(0);
root.mTranslation = Vec3(0, mVerticalSeparation * (i + 1), 0);
float angle = 2.0f * JPH_PI * float(i) / float(mPileSize);
root.mRotation = Quat::sRotation(Vec3::sAxisY(), angle) * root.mRotation;
pose_copy.CalculateJointMatrices();
// Drive to pose
ragdoll->SetPose(pose_copy);
ragdoll->DriveToPoseUsingMotors(pose_copy);
ragdoll->AddToPhysicsSystem(EActivation::Activate);
// Keep reference
mRagdolls.push_back(ragdoll);
}
}
}
virtual void StopTest(PhysicsSystem &inPhysicsSystem) override
{
// Remove ragdolls
for (Ragdoll *ragdoll : mRagdolls)
ragdoll->RemoveFromPhysicsSystem();
mRagdolls.clear();
}
private:
int mNumPilesPerAxis;
int mPileSize;
float mVerticalSeparation;
Ref<RagdollSettings> mRagdollSettings;
Ref<SkeletalAnimation> mAnimation;
SkeletonPose mPose;
Ref<PhysicsScene> mBackground;
Array<Ref<Ragdoll>> mRagdolls;
};
#endif // JPH_OBJECT_STREAM