SensorTest.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/General/SensorTest.h>
  5. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  6. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  7. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  8. #include <Utils/RagdollLoader.h>
  9. #include <Utils/Log.h>
  10. #include <Layers.h>
  11. #include <Renderer/DebugRendererImp.h>
  12. JPH_IMPLEMENT_RTTI_VIRTUAL(SensorTest)
  13. {
  14. JPH_ADD_BASE_CLASS(SensorTest, Test)
  15. }
  16. SensorTest::~SensorTest()
  17. {
  18. // Destroy the ragdoll
  19. mRagdoll->RemoveFromPhysicsSystem();
  20. mRagdoll = nullptr;
  21. }
  22. void SensorTest::Initialize()
  23. {
  24. // Floor
  25. CreateFloor();
  26. {
  27. // A static sensor that attrects dynamic bodies that enter its area
  28. BodyCreationSettings sensor_settings(new SphereShape(10.0f), Vec3(0, 10, 0), Quat::sIdentity(), EMotionType::Static, Layers::SENSOR);
  29. sensor_settings.mIsSensor = true;
  30. mSensorID[StaticAttractor] = mBodyInterface->CreateAndAddBody(sensor_settings, EActivation::DontActivate);
  31. }
  32. {
  33. // A static sensor that only detects active bodies
  34. BodyCreationSettings sensor_settings(new BoxShape(Vec3::sReplicate(5.0f)), Vec3(-10, 5, 0), Quat::sIdentity(), EMotionType::Static, Layers::SENSOR);
  35. sensor_settings.mIsSensor = true;
  36. mSensorID[StaticSensor] = mBodyInterface->CreateAndAddBody(sensor_settings, EActivation::DontActivate);
  37. }
  38. {
  39. // A kinematic sensor that also detects sleeping bodies
  40. BodyCreationSettings sensor_settings(new BoxShape(Vec3::sReplicate(5.0f)), Vec3(10, 5, 0), Quat::sIdentity(), EMotionType::Kinematic, Layers::SENSOR);
  41. sensor_settings.mIsSensor = true;
  42. mSensorID[KinematicSensor] = mBodyInterface->CreateAndAddBody(sensor_settings, EActivation::Activate);
  43. }
  44. // Dynamic bodies
  45. for (int i = 0; i < 10; ++i)
  46. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.1f, 0.5f, 0.2f)), Vec3(-15.0f + i * 3.0f, 25, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING), EActivation::Activate);
  47. // Load ragdoll
  48. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sLoad("Assets/Human.tof", EMotionType::Dynamic);
  49. if (ragdoll_settings == nullptr)
  50. FatalError("Could not load ragdoll");
  51. // Load animation
  52. Ref<SkeletalAnimation> animation;
  53. if (!ObjectStreamIn::sReadObject("Assets/Human/Dead_Pose1.tof", animation))
  54. FatalError("Could not open animation");
  55. // Create pose
  56. SkeletonPose ragdoll_pose;
  57. ragdoll_pose.SetSkeleton(ragdoll_settings->GetSkeleton());
  58. animation->Sample(0.0f, ragdoll_pose);
  59. SkeletonPose::JointState &root = ragdoll_pose.GetJoint(0);
  60. root.mTranslation = Vec3(0, 30, 0);
  61. ragdoll_pose.CalculateJointMatrices();
  62. // Create ragdoll
  63. mRagdoll = ragdoll_settings->CreateRagdoll(1, 0, mPhysicsSystem);
  64. mRagdoll->SetPose(ragdoll_pose);
  65. mRagdoll->AddToPhysicsSystem(EActivation::Activate);
  66. // Create kinematic body
  67. BodyCreationSettings kinematic_settings(new BoxShape(Vec3(0.25f, 0.5f, 1.0f)), Vec3(-20, 10, 0), Quat::sIdentity(), EMotionType::Kinematic, Layers::MOVING);
  68. Body &kinematic = *mBodyInterface->CreateBody(kinematic_settings);
  69. mKinematicBodyID = kinematic.GetID();
  70. mBodyInterface->AddBody(kinematic.GetID(), EActivation::Activate);
  71. }
  72. void SensorTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  73. {
  74. // Update time
  75. mTime += inParams.mDeltaTime;
  76. // Move kinematic body
  77. Vec3 kinematic_pos = Vec3(-20.0f * cos(mTime), 10, 0);
  78. mBodyInterface->MoveKinematic(mKinematicBodyID, kinematic_pos, Quat::sIdentity(), inParams.mDeltaTime);
  79. // Draw if body is in sensor
  80. Color sensor_color[] = { Color::sRed, Color::sGreen, Color::sBlue };
  81. for (int sensor = 0; sensor < NumSensors; ++sensor)
  82. for (const BodyAndCount &body_and_count : mBodiesInSensor[sensor])
  83. {
  84. AABox bounds = mBodyInterface->GetTransformedShape(body_and_count.mBodyID).GetWorldSpaceBounds();
  85. bounds.ExpandBy(Vec3::sReplicate(0.01f * sensor));
  86. mDebugRenderer->DrawWireBox(bounds, sensor_color[sensor]);
  87. }
  88. // Apply forces to dynamic bodies in sensor
  89. lock_guard lock(mMutex);
  90. Vec3 center(0, 10, 0);
  91. float centrifugal_force = 10.0f;
  92. Vec3 gravity = mPhysicsSystem->GetGravity();
  93. for (const BodyAndCount &body_and_count : mBodiesInSensor[StaticAttractor])
  94. {
  95. BodyLockWrite body_lock(mPhysicsSystem->GetBodyLockInterface(), body_and_count.mBodyID);
  96. if (body_lock.Succeeded())
  97. {
  98. Body &body = body_lock.GetBody();
  99. if (body.IsKinematic())
  100. continue;
  101. // Calculate centrifugal acceleration
  102. Vec3 acceleration = center - body.GetPosition();
  103. float length = acceleration.Length();
  104. if (length > 0.0f)
  105. acceleration *= centrifugal_force / length;
  106. else
  107. acceleration = Vec3::sZero();
  108. // Draw acceleration
  109. mDebugRenderer->DrawArrow(body.GetPosition(), body.GetPosition() + acceleration, Color::sGreen, 0.1f);
  110. // Cancel gravity
  111. acceleration -= gravity;
  112. // Apply as force
  113. body.AddForce(acceleration / body.GetMotionProperties()->GetInverseMass());
  114. }
  115. }
  116. }
  117. void SensorTest::OnContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings)
  118. {
  119. for (int sensor = 0; sensor < NumSensors; ++sensor)
  120. {
  121. BodyID sensor_id = mSensorID[sensor];
  122. // Check which body is the sensor
  123. BodyID body_id;
  124. if (inBody1.GetID() == sensor_id)
  125. body_id = inBody2.GetID();
  126. else if (inBody2.GetID() == sensor_id)
  127. body_id = inBody1.GetID();
  128. else
  129. continue;
  130. lock_guard lock(mMutex);
  131. // Add to list and make sure that the list remains sorted for determinism (contacts can be added from multiple threads)
  132. BodyAndCount body_and_count { body_id, 1 };
  133. BodiesInSensor &bodies_in_sensor = mBodiesInSensor[sensor];
  134. BodiesInSensor::iterator b = lower_bound(bodies_in_sensor.begin(), bodies_in_sensor.end(), body_and_count);
  135. if (b != bodies_in_sensor.end() && b->mBodyID == body_id)
  136. {
  137. // This is the right body, increment reference
  138. b->mCount++;
  139. return;
  140. }
  141. bodies_in_sensor.insert(b, body_and_count);
  142. }
  143. }
  144. void SensorTest::OnContactRemoved(const SubShapeIDPair &inSubShapePair)
  145. {
  146. for (int sensor = 0; sensor < NumSensors; ++sensor)
  147. {
  148. BodyID sensor_id = mSensorID[sensor];
  149. // Check which body is the sensor
  150. BodyID body_id;
  151. if (inSubShapePair.GetBody1ID() == sensor_id)
  152. body_id = inSubShapePair.GetBody2ID();
  153. else if (inSubShapePair.GetBody2ID() == sensor_id)
  154. body_id = inSubShapePair.GetBody1ID();
  155. else
  156. continue;
  157. lock_guard lock(mMutex);
  158. // Remove from list
  159. BodyAndCount body_and_count { body_id, 1 };
  160. BodiesInSensor &bodies_in_sensor = mBodiesInSensor[sensor];
  161. BodiesInSensor::iterator b = lower_bound(bodies_in_sensor.begin(), bodies_in_sensor.end(), body_and_count);
  162. if (b != bodies_in_sensor.end() && b->mBodyID == body_id)
  163. {
  164. // This is the right body, increment reference
  165. JPH_ASSERT(b->mCount > 0);
  166. b->mCount--;
  167. // When last reference remove from the list
  168. if (b->mCount == 0)
  169. bodies_in_sensor.erase(b);
  170. return;
  171. }
  172. JPH_ASSERT(false, "Body pair not found");
  173. }
  174. }
  175. void SensorTest::SaveState(StateRecorder &inStream) const
  176. {
  177. inStream.Write(mTime);
  178. for (const BodiesInSensor &b : mBodiesInSensor)
  179. inStream.Write(b);
  180. }
  181. void SensorTest::RestoreState(StateRecorder &inStream)
  182. {
  183. inStream.Read(mTime);
  184. for (BodiesInSensor &b : mBodiesInSensor)
  185. inStream.Read(b);
  186. }