PhysicsStressTest.cpp 13 KB

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