SkeletalAnimation.cpp 10 KB

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