SkeletalAnimation.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //
  2. // Copyright (c) 2008-2014 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 "Animation.h"
  23. #include "AnimatedModel.h"
  24. #include "AnimationState.h"
  25. #include "Camera.h"
  26. #include "CoreEvents.h"
  27. #include "DebugRenderer.h"
  28. #include "Engine.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 "Mover.h"
  36. #include "Octree.h"
  37. #include "Renderer.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "Text.h"
  41. #include "UI.h"
  42. #include "Zone.h"
  43. #include "SkeletalAnimation.h"
  44. #include "DebugNew.h"
  45. DEFINE_APPLICATION_MAIN(SkeletalAnimation)
  46. SkeletalAnimation::SkeletalAnimation(Context* context) :
  47. Sample(context),
  48. drawDebug_(false)
  49. {
  50. // Register an object factory for our custom Mover component so that we can create them to scene nodes
  51. context->RegisterFactory<Mover>();
  52. }
  53. void SkeletalAnimation::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 SkeletalAnimation::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. // Also create a DebugRenderer component so that we can draw debug geometry
  72. scene_->CreateComponent<Octree>();
  73. scene_->CreateComponent<DebugRenderer>();
  74. // Create scene node & StaticModel component for showing a static plane
  75. Node* planeNode = scene_->CreateChild("Plane");
  76. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  77. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  78. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  79. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  80. // Create a Zone component for ambient lighting & fog control
  81. Node* zoneNode = scene_->CreateChild("Zone");
  82. Zone* zone = zoneNode->CreateComponent<Zone>();
  83. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  84. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  85. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  86. zone->SetFogStart(100.0f);
  87. zone->SetFogEnd(300.0f);
  88. // Create a directional light to the world. Enable cascaded shadows on it
  89. Node* lightNode = scene_->CreateChild("DirectionalLight");
  90. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  91. Light* light = lightNode->CreateComponent<Light>();
  92. light->SetLightType(LIGHT_DIRECTIONAL);
  93. light->SetCastShadows(true);
  94. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  95. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  96. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  97. // Create animated models
  98. const unsigned NUM_MODELS = 100;
  99. const float MODEL_MOVE_SPEED = 2.0f;
  100. const float MODEL_ROTATE_SPEED = 100.0f;
  101. const BoundingBox bounds(Vector3(-47.0f, 0.0f, -47.0f), Vector3(47.0f, 0.0f, 47.0f));
  102. for (unsigned i = 0; i < NUM_MODELS; ++i)
  103. {
  104. Node* modelNode = scene_->CreateChild("Jack");
  105. modelNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  106. modelNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  107. AnimatedModel* modelObject = modelNode->CreateComponent<AnimatedModel>();
  108. modelObject->SetModel(cache->GetResource<Model>("Models/Jack.mdl"));
  109. modelObject->SetMaterial(cache->GetResource<Material>("Materials/Jack.xml"));
  110. modelObject->SetCastShadows(true);
  111. // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  112. // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  113. // but we need to update the model's position manually in any case
  114. Animation* walkAnimation = cache->GetResource<Animation>("Models/Jack_Walk.ani");
  115. AnimationState* state = modelObject->AddAnimationState(walkAnimation);
  116. // The state would fail to create (return null) if the animation was not found
  117. if (state)
  118. {
  119. // Enable full blending weight and looping
  120. state->SetWeight(1.0f);
  121. state->SetLooped(true);
  122. }
  123. // Create our custom Mover component that will move & animate the model during each frame's update
  124. Mover* mover = modelNode->CreateComponent<Mover>();
  125. mover->SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds);
  126. }
  127. // Create the camera. Limit far clip distance to match the fog
  128. cameraNode_ = scene_->CreateChild("Camera");
  129. Camera* camera = cameraNode_->CreateComponent<Camera>();
  130. camera->SetFarClip(300.0f);
  131. // Set an initial position for the camera scene node above the plane
  132. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  133. }
  134. void SkeletalAnimation::CreateInstructions()
  135. {
  136. ResourceCache* cache = GetSubsystem<ResourceCache>();
  137. UI* ui = GetSubsystem<UI>();
  138. // Construct new Text object, set string to display and font to use
  139. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  140. instructionText->SetText(
  141. "Use WASD keys and mouse/touch to move\n"
  142. "Space to toggle debug geometry"
  143. );
  144. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  145. // The text has multiple rows. Center them in relation to each other
  146. instructionText->SetTextAlignment(HA_CENTER);
  147. // Position the text relative to the screen center
  148. instructionText->SetHorizontalAlignment(HA_CENTER);
  149. instructionText->SetVerticalAlignment(VA_CENTER);
  150. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  151. }
  152. void SkeletalAnimation::SetupViewport()
  153. {
  154. Renderer* renderer = GetSubsystem<Renderer>();
  155. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  156. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  157. renderer->SetViewport(0, viewport);
  158. }
  159. void SkeletalAnimation::SubscribeToEvents()
  160. {
  161. // Subscribe HandleUpdate() function for processing update events
  162. SubscribeToEvent(E_UPDATE, HANDLER(SkeletalAnimation, HandleUpdate));
  163. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, sent after Renderer subsystem is
  164. // done with defining the draw calls for the viewports (but before actually executing them.) We will request debug geometry
  165. // rendering during that event
  166. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SkeletalAnimation, HandlePostRenderUpdate));
  167. }
  168. void SkeletalAnimation::MoveCamera(float timeStep)
  169. {
  170. // Do not move if the UI has a focused element (the console)
  171. if (GetSubsystem<UI>()->GetFocusElement())
  172. return;
  173. Input* input = GetSubsystem<Input>();
  174. // Movement speed as world units per second
  175. const float MOVE_SPEED = 20.0f;
  176. // Mouse sensitivity as degrees per pixel
  177. const float MOUSE_SENSITIVITY = 0.1f;
  178. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  179. IntVector2 mouseMove = input->GetMouseMove();
  180. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  181. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  182. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  183. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  184. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  185. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  186. if (input->GetKeyDown('W'))
  187. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  188. if (input->GetKeyDown('S'))
  189. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  190. if (input->GetKeyDown('A'))
  191. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  192. if (input->GetKeyDown('D'))
  193. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  194. // Toggle debug geometry with space
  195. if (input->GetKeyPress(KEY_SPACE))
  196. drawDebug_ = !drawDebug_;
  197. }
  198. void SkeletalAnimation::HandleUpdate(StringHash eventType, VariantMap& eventData)
  199. {
  200. using namespace Update;
  201. // Take the frame time step, which is stored as a float
  202. float timeStep = eventData[P_TIMESTEP].GetFloat();
  203. // Move the camera, scale movement with time step
  204. MoveCamera(timeStep);
  205. }
  206. void SkeletalAnimation::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  207. {
  208. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  209. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  210. // bones properly
  211. if (drawDebug_)
  212. GetSubsystem<Renderer>()->DrawDebugGeometry(false);
  213. }