Ragdolls.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 "AnimatedModel.h"
  23. #include "Camera.h"
  24. #include "CollisionShape.h"
  25. #include "CoreEvents.h"
  26. #include "CreateRagdoll.h"
  27. #include "DebugRenderer.h"
  28. #include "Engine.h"
  29. #include "File.h"
  30. #include "FileSystem.h"
  31. #include "Font.h"
  32. #include "Graphics.h"
  33. #include "Input.h"
  34. #include "Light.h"
  35. #include "Material.h"
  36. #include "Model.h"
  37. #include "Octree.h"
  38. #include "PhysicsWorld.h"
  39. #include "Renderer.h"
  40. #include "ResourceCache.h"
  41. #include "RigidBody.h"
  42. #include "Text.h"
  43. #include "UI.h"
  44. #include "Zone.h"
  45. #include "Ragdolls.h"
  46. #include "DebugNew.h"
  47. // Expands to this example's entry-point
  48. DEFINE_APPLICATION_MAIN(Ragdolls)
  49. Ragdolls::Ragdolls(Context* context) :
  50. Sample(context),
  51. yaw_(0.0f),
  52. pitch_(0.0f),
  53. drawDebug_(false)
  54. {
  55. // Register an object factory for our custom CreateRagdoll component so that we can create them to scene nodes
  56. context->RegisterFactory<CreateRagdoll>();
  57. }
  58. void Ragdolls::Start()
  59. {
  60. // Execute base class startup
  61. Sample::Start();
  62. // Create the scene content
  63. CreateScene();
  64. // Create the UI content
  65. CreateInstructions();
  66. // Setup the viewport for displaying the scene
  67. SetupViewport();
  68. // Hook up to the frame update and render post-update events
  69. SubscribeToEvents();
  70. }
  71. void Ragdolls::CreateScene()
  72. {
  73. ResourceCache* cache = GetSubsystem<ResourceCache>();
  74. scene_ = new Scene(context_);
  75. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  76. // Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  77. // exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  78. // Finally, create a DebugRenderer component so that we can draw physics debug geometry
  79. scene_->CreateComponent<Octree>();
  80. scene_->CreateComponent<PhysicsWorld>();
  81. scene_->CreateComponent<DebugRenderer>();
  82. // Create a Zone component for ambient lighting & fog control
  83. Node* zoneNode = scene_->CreateChild("Zone");
  84. Zone* zone = zoneNode->CreateComponent<Zone>();
  85. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  86. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  87. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  88. zone->SetFogStart(100.0f);
  89. zone->SetFogEnd(300.0f);
  90. // Create a directional light to the world. Enable cascaded shadows on it
  91. Node* lightNode = scene_->CreateChild("DirectionalLight");
  92. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  93. Light* light = lightNode->CreateComponent<Light>();
  94. light->SetLightType(LIGHT_DIRECTIONAL);
  95. light->SetCastShadows(true);
  96. light->SetShadowBias(BiasParameters(0.0001f, 0.5f));
  97. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  98. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  99. {
  100. // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
  101. Node* floorNode = scene_->CreateChild("Floor");
  102. floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));
  103. floorNode->SetScale(Vector3(500.0f, 1.0f, 500.0f));
  104. StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
  105. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  106. floorObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  107. // Make the floor physical by adding RigidBody and CollisionShape components
  108. RigidBody* body = floorNode->CreateComponent<RigidBody>();
  109. // We will be spawning spherical objects in this sample. The ground also needs non-zero rolling friction so that
  110. // the spheres will eventually come to rest
  111. body->SetRollingFriction(0.15f);
  112. CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
  113. // 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
  114. // rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  115. shape->SetBox(Vector3::ONE);
  116. }
  117. // Create animated models
  118. for (int z = -1; z <= 1; ++z)
  119. {
  120. for (int x = -4; x <= 4; ++x)
  121. {
  122. Node* modelNode = scene_->CreateChild("Jack");
  123. modelNode->SetPosition(Vector3(x * 5.0f, 0.0f, z * 5.0f));
  124. modelNode->SetRotation(Quaternion(0.0f, 180.0f, 0.0f));
  125. AnimatedModel* modelObject = modelNode->CreateComponent<AnimatedModel>();
  126. modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  127. modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  128. modelObject->SetCastShadows(true);
  129. // Create a rigid body and a collision shape. These will act as a trigger for transforming the
  130. // model into a ragdoll when hit by a moving object
  131. RigidBody* body = modelNode->CreateComponent<RigidBody>();
  132. // The phantom mode makes the rigid body only detect collisions, but impart no forces on the
  133. // colliding objects
  134. body->SetPhantom(true);
  135. CollisionShape* shape = modelNode->CreateComponent<CollisionShape>();
  136. // Create the capsule shape with an offset so that it is correctly aligned with the model, which
  137. // has its origin at the feet
  138. shape->SetCapsule(0.7f, 2.0f, Vector3(0.0f, 1.0f, 0.0f));
  139. // Create a custom component that reacts to collisions and creates the ragdoll
  140. modelNode->CreateComponent<CreateRagdoll>();
  141. }
  142. }
  143. // Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside
  144. // the scene, because we want it to be unaffected by scene load/save
  145. cameraNode_ = new Node(context_);
  146. Camera* camera = cameraNode_->CreateComponent<Camera>();
  147. camera->SetFarClip(300.0f);
  148. // Set an initial position for the camera scene node above the floor
  149. cameraNode_->SetPosition(Vector3(0.0f, 3.0f, -20.0f));
  150. }
  151. void Ragdolls::CreateInstructions()
  152. {
  153. ResourceCache* cache = GetSubsystem<ResourceCache>();
  154. UI* ui = GetSubsystem<UI>();
  155. // Construct new Text object, set string to display and font to use
  156. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  157. instructionText->SetText(
  158. "Use WASD keys and mouse to move\n"
  159. "LMB to spawn physics objects\n"
  160. "F5 to save scene, F7 to load\n"
  161. "Space to toggle physics debug geometry"
  162. );
  163. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  164. // The text has multiple rows. Center them in relation to each other
  165. instructionText->SetTextAlignment(HA_CENTER);
  166. // Position the text relative to the screen center
  167. instructionText->SetHorizontalAlignment(HA_CENTER);
  168. instructionText->SetVerticalAlignment(VA_CENTER);
  169. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  170. }
  171. void Ragdolls::SetupViewport()
  172. {
  173. Renderer* renderer = GetSubsystem<Renderer>();
  174. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  175. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  176. renderer->SetViewport(0, viewport);
  177. }
  178. void Ragdolls::MoveCamera(float timeStep)
  179. {
  180. // Do not move if the UI has a focused element (the console)
  181. if (GetSubsystem<UI>()->GetFocusElement())
  182. return;
  183. Input* input = GetSubsystem<Input>();
  184. // Movement speed as world units per second
  185. const float MOVE_SPEED = 20.0f;
  186. // Mouse sensitivity as degrees per pixel
  187. const float MOUSE_SENSITIVITY = 0.1f;
  188. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  189. IntVector2 mouseMove = input->GetMouseMove();
  190. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  191. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  192. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  193. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  194. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  195. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  196. if (input->GetKeyDown('W'))
  197. cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
  198. if (input->GetKeyDown('S'))
  199. cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
  200. if (input->GetKeyDown('A'))
  201. cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
  202. if (input->GetKeyDown('D'))
  203. cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
  204. // "Shoot" a physics object with left mousebutton
  205. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  206. SpawnObject();
  207. // Toggle physics debug geometry with space
  208. if (input->GetKeyPress(KEY_SPACE))
  209. drawDebug_ = !drawDebug_;
  210. }
  211. void Ragdolls::SpawnObject()
  212. {
  213. ResourceCache* cache = GetSubsystem<ResourceCache>();
  214. Node* boxNode = scene_->CreateChild("Sphere");
  215. boxNode->SetPosition(cameraNode_->GetPosition());
  216. boxNode->SetRotation(cameraNode_->GetRotation());
  217. boxNode->SetScale(0.25f);
  218. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  219. boxObject->SetModel(cache->GetResource<Model>("Models/Sphere.mdl"));
  220. boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
  221. boxObject->SetCastShadows(true);
  222. RigidBody* body = boxNode->CreateComponent<RigidBody>();
  223. body->SetMass(1.0f);
  224. body->SetRollingFriction(0.15f);
  225. CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
  226. shape->SetSphere(1.0f);
  227. const float OBJECT_VELOCITY = 10.0f;
  228. // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  229. // to overcome gravity better
  230. body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
  231. }
  232. void Ragdolls::SubscribeToEvents()
  233. {
  234. // Subscribe HandleUpdate() function for processing update events
  235. SubscribeToEvent(E_UPDATE, HANDLER(Ragdolls, HandleUpdate));
  236. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  237. // debug geometry
  238. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(Ragdolls, HandlePostRenderUpdate));
  239. }
  240. void Ragdolls::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. // Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  248. // directory
  249. Input* input = GetSubsystem<Input>();
  250. if (input->GetKeyPress(KEY_F5))
  251. {
  252. File saveFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/Ragdolls.xml", FILE_WRITE);
  253. scene_->SaveXML(saveFile);
  254. }
  255. if (input->GetKeyPress(KEY_F7))
  256. {
  257. File loadFile(context_, GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Scenes/Ragdolls.xml", FILE_READ);
  258. scene_->LoadXML(loadFile);
  259. }
  260. }
  261. void Ragdolls::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. }