Physics.cpp 13 KB

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