2
0

PhysicsStressTest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Engine/Engine.h>
  5. #include <Urho3D/Graphics/Camera.h>
  6. #include <Urho3D/Graphics/DebugRenderer.h>
  7. #include <Urho3D/Graphics/Graphics.h>
  8. #include <Urho3D/Graphics/Light.h>
  9. #include <Urho3D/Graphics/Material.h>
  10. #include <Urho3D/Graphics/Model.h>
  11. #include <Urho3D/Graphics/Octree.h>
  12. #include <Urho3D/Graphics/Renderer.h>
  13. #include <Urho3D/Graphics/StaticModel.h>
  14. #include <Urho3D/Graphics/Zone.h>
  15. #include <Urho3D/Input/Input.h>
  16. #include <Urho3D/IO/File.h>
  17. #include <Urho3D/IO/FileSystem.h>
  18. #include <Urho3D/Physics/CollisionShape.h>
  19. #include <Urho3D/Physics/PhysicsWorld.h>
  20. #include <Urho3D/Physics/RigidBody.h>
  21. #include <Urho3D/Resource/ResourceCache.h>
  22. #include <Urho3D/Scene/Scene.h>
  23. #include <Urho3D/UI/Font.h>
  24. #include <Urho3D/UI/Text.h>
  25. #include <Urho3D/UI/UI.h>
  26. #include "PhysicsStressTest.h"
  27. #include <Urho3D/DebugNew.h>
  28. URHO3D_DEFINE_APPLICATION_MAIN(PhysicsStressTest)
  29. PhysicsStressTest::PhysicsStressTest(Context* context) :
  30. Sample(context),
  31. drawDebug_(false)
  32. {
  33. }
  34. void PhysicsStressTest::Start()
  35. {
  36. // Execute base class startup
  37. Sample::Start();
  38. // Create the scene content
  39. CreateScene();
  40. // Create the UI content
  41. CreateInstructions();
  42. // Setup the viewport for displaying the scene
  43. SetupViewport();
  44. // Hook up to the frame update and render post-update events
  45. SubscribeToEvents();
  46. // Set the mouse mode to use in the sample
  47. Sample::InitMouseMode(MM_RELATIVE);
  48. }
  49. void PhysicsStressTest::CreateScene()
  50. {
  51. auto* cache = GetSubsystem<ResourceCache>();
  52. scene_ = new Scene(context_);
  53. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  54. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  55. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  56. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  57. scene_->CreateComponent<Octree>();
  58. scene_->CreateComponent<PhysicsWorld>();
  59. scene_->CreateComponent<DebugRenderer>();
  60. // Create a Zone component for ambient lighting & fog control
  61. Node* zoneNode = scene_->CreateChild("Zone");
  62. auto* zone = zoneNode->CreateComponent<Zone>();
  63. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  64. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  65. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  66. zone->SetFogStart(100.0f);
  67. zone->SetFogEnd(300.0f);
  68. // Create a directional light to the world. Enable cascaded shadows on it
  69. Node* lightNode = scene_->CreateChild("DirectionalLight");
  70. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  71. auto* light = lightNode->CreateComponent<Light>();
  72. light->SetLightType(LIGHT_DIRECTIONAL);
  73. light->SetCastShadows(true);
  74. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  75. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  76. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  77. {
  78. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  79. Node* floorNode = scene_->CreateChild("Floor");
  80. floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  81. floorNode->SetScale(Vector3(500.0f, 1.0f, 500.0f));
  82. auto* floorObject = floorNode->CreateComponent<StaticModel>();
  83. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  84. floorObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  85. // Make the floor physical by adding RigidBody and CollisionShape components
  86. /*RigidBody* body = */floorNode->CreateComponent<RigidBody>();
  87. auto* shape = floorNode->CreateComponent<CollisionShape>();
  88. shape->SetBox(Vector3::ONE);
  89. }
  90. {
  91. // Create static mushrooms with triangle mesh collision
  92. const unsigned NUM_MUSHROOMS = 50;
  93. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  94. {
  95. Node* mushroomNode = scene_->CreateChild("Mushroom");
  96. mushroomNode->SetPosition(Vector3(Random(400.0f) - 200.0f, 0.0f, Random(400.0f) - 200.0f));
  97. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  98. mushroomNode->SetScale(5.0f + Random(5.0f));
  99. auto* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  100. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  101. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  102. mushroomObject->SetCastShadows(true);
  103. /*RigidBody* body = */mushroomNode->CreateComponent<RigidBody>();
  104. auto* shape = mushroomNode->CreateComponent<CollisionShape>();
  105. // By default the highest LOD level will be used, the LOD level can be passed as an optional parameter
  106. shape->SetTriangleMesh(mushroomObject->GetModel());
  107. }
  108. }
  109. {
  110. // Create a large amount of falling physics objects
  111. const unsigned NUM_OBJECTS = 1000;
  112. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  113. {
  114. Node* boxNode = scene_->CreateChild("Box");
  115. boxNode->SetPosition(Vector3(0.0f, i * 2.0f + 100.0f, 0.0f));
  116. auto* boxObject = boxNode->CreateComponent<StaticModel>();
  117. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  118. boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
  119. boxObject->SetCastShadows(true);
  120. // Give the RigidBody mass to make it movable and also adjust friction
  121. auto* body = boxNode->CreateComponent<RigidBody>();
  122. body->SetMass(1.0f);
  123. body->SetFriction(1.0f);
  124. // Disable collision event signaling to reduce CPU load of the physics simulation
  125. body->SetCollisionEventMode(COLLISION_NEVER);
  126. auto* shape = boxNode->CreateComponent<CollisionShape>();
  127. shape->SetBox(Vector3::ONE);
  128. }
  129. }
  130. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  131. // the scene, because we want it to be unaffected by scene load / save
  132. cameraNode_ = new Node(context_);
  133. auto* camera = cameraNode_->CreateComponent<Camera>();
  134. camera->SetFarClip(300.0f);
  135. // Set an initial position for the camera scene node above the floor
  136. cameraNode_->SetPosition(Vector3(0.0f, 3.0f, -20.0f));
  137. }
  138. void PhysicsStressTest::CreateInstructions()
  139. {
  140. auto* cache = GetSubsystem<ResourceCache>();
  141. auto* ui = GetSubsystem<UI>();
  142. // Construct new Text object, set string to display and font to use
  143. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  144. instructionText->SetText(
  145. "Use WASD keys and mouse/touch to move\n"
  146. "LMB to spawn physics objects\n"
  147. "F5 to save scene, F7 to load\n"
  148. "Space to toggle physics debug geometry"
  149. );
  150. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  151. // The text has multiple rows. Center them in relation to each other
  152. instructionText->SetTextAlignment(HA_CENTER);
  153. // Position the text relative to the screen center
  154. instructionText->SetHorizontalAlignment(HA_CENTER);
  155. instructionText->SetVerticalAlignment(VA_CENTER);
  156. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  157. }
  158. void PhysicsStressTest::SetupViewport()
  159. {
  160. auto* renderer = GetSubsystem<Renderer>();
  161. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  162. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  163. renderer->SetViewport(0, viewport);
  164. }
  165. void PhysicsStressTest::SubscribeToEvents()
  166. {
  167. // Subscribe HandleUpdate() function for processing update events
  168. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(PhysicsStressTest, HandleUpdate));
  169. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  170. // debug geometry
  171. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(PhysicsStressTest, HandlePostRenderUpdate));
  172. }
  173. void PhysicsStressTest::MoveCamera(float timeStep)
  174. {
  175. // Do not move if the UI has a focused element (the console)
  176. if (GetSubsystem<UI>()->GetFocusElement())
  177. return;
  178. auto* input = GetSubsystem<Input>();
  179. // Movement speed as world units per second
  180. const float MOVE_SPEED = 20.0f;
  181. // Mouse sensitivity as degrees per pixel
  182. const float MOUSE_SENSITIVITY = 0.1f;
  183. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  184. IntVector2 mouseMove = input->GetMouseMove();
  185. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  186. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  187. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  188. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  189. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  190. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  191. if (input->GetKeyDown(KEY_W))
  192. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  193. if (input->GetKeyDown(KEY_S))
  194. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  195. if (input->GetKeyDown(KEY_A))
  196. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  197. if (input->GetKeyDown(KEY_D))
  198. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  199. // "Shoot" a physics object with left mousebutton
  200. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  201. SpawnObject();
  202. // Check for loading / saving the scene
  203. if (input->GetKeyPress(KEY_F5))
  204. {
  205. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/PhysicsStressTest.xml", FILE_WRITE);
  206. scene_->SaveXML(saveFile);
  207. }
  208. if (input->GetKeyPress(KEY_F7))
  209. {
  210. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/PhysicsStressTest.xml", FILE_READ);
  211. scene_->LoadXML(loadFile);
  212. }
  213. // Toggle physics debug geometry with space
  214. if (input->GetKeyPress(KEY_SPACE))
  215. drawDebug_ = !drawDebug_;
  216. }
  217. void PhysicsStressTest::SpawnObject()
  218. {
  219. auto* cache = GetSubsystem<ResourceCache>();
  220. // Create a smaller box at camera position
  221. Node* boxNode = scene_->CreateChild("SmallBox");
  222. boxNode->SetPosition(cameraNode_->GetPosition());
  223. boxNode->SetRotation(cameraNode_->GetRotation());
  224. boxNode->SetScale(0.25f);
  225. auto* boxObject = boxNode->CreateComponent<StaticModel>();
  226. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  227. boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
  228. boxObject->SetCastShadows(true);
  229. // Create physics components, use a smaller mass also
  230. auto* body = boxNode->CreateComponent<RigidBody>();
  231. body->SetMass(0.25f);
  232. body->SetFriction(0.75f);
  233. auto* shape = boxNode->CreateComponent<CollisionShape>();
  234. shape->SetBox(Vector3::ONE);
  235. const float OBJECT_VELOCITY = 10.0f;
  236. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  237. // to overcome gravity better
  238. body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
  239. }
  240. void PhysicsStressTest::HandleUpdate(StringHash eventType, VariantMap& eventData)
  241. {
  242. using namespace Update;
  243. // Take the frame time step, which is stored as a float
  244. float timeStep = eventData[P_TIMESTEP].GetFloat();
  245. // Move the camera, scale movement with time step
  246. MoveCamera(timeStep);
  247. }
  248. void PhysicsStressTest::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  249. {
  250. // If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  251. if (drawDebug_)
  252. scene_->GetComponent<PhysicsWorld>()->DrawDebugGeometry(true);
  253. }