06_SkeletalAnimation.as 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Skeletal animation example.
  2. // This sample demonstrates:
  3. // - Populating a 3D scene with skeletally animated AnimatedModel components
  4. // - Moving the animated models and advancing their animation using a script object
  5. // - Enabling a cascaded shadow map on a directional light, which allows high-quality shadows
  6. // over a large area (typically used in outdoor scenes for shadows cast by sunlight)
  7. // - Displaying renderer debug geometry
  8. #include "Scripts/Utilities/Sample.as"
  9. Scene@ scene_;
  10. Node@ cameraNode;
  11. float yaw = 0.0f;
  12. float pitch = 0.0f;
  13. bool drawDebug = false;
  14. void Start()
  15. {
  16. // Execute the common startup for samples
  17. SampleStart();
  18. // Create the scene content
  19. CreateScene();
  20. // Create the UI content
  21. CreateInstructions();
  22. // Setup the viewport for displaying the scene
  23. SetupViewport();
  24. // Hook up to the frame update and render post-update events
  25. SubscribeToEvents();
  26. }
  27. void CreateScene()
  28. {
  29. scene_ = Scene();
  30. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  31. // Also create a DebugRenderer component so that we can draw debug geometry
  32. scene_.CreateComponent("Octree");
  33. scene_.CreateComponent("DebugRenderer");
  34. // Create scene node & StaticModel component for showing a static plane
  35. Node@ planeNode = scene_.CreateChild("Plane");
  36. planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
  37. StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
  38. planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
  39. planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
  40. // Create a Zone component for ambient lighting & fog control
  41. Node@ zoneNode = scene_.CreateChild("Zone");
  42. Zone@ zone = zoneNode.CreateComponent("Zone");
  43. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  44. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  45. zone.fogColor = Color(0.5f, 0.5f, 0.7f);
  46. zone.fogStart = 100.0f;
  47. zone.fogEnd = 300.0f;
  48. // Create a directional light to the world. Enable cascaded shadows on it
  49. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  50. lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
  51. Light@ light = lightNode.CreateComponent("Light");
  52. light.lightType = LIGHT_DIRECTIONAL;
  53. light.castShadows = true;
  54. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  55. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  56. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  57. // Create animated models
  58. const uint NUM_MODELS = 100;
  59. const float MODEL_MOVE_SPEED = 2.0f;
  60. const float MODEL_ROTATE_SPEED = 100.0f;
  61. const BoundingBox bounds(Vector3(-47.0f, 0.0f, -47.0f), Vector3(47.0f, 0.0f, 47.0f));
  62. for (uint i = 0; i < NUM_MODELS; ++i)
  63. {
  64. Node@ modelNode = scene_.CreateChild("Jack");
  65. modelNode.position = Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f);
  66. modelNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
  67. AnimatedModel@ modelObject = modelNode.CreateComponent("AnimatedModel");
  68. modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
  69. modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
  70. modelObject.castShadows = true;
  71. // Create an AnimationState for a walk animation. Its time position will need to be manually updated to advance the
  72. // animation, The alternative would be to use an AnimationController component which updates the animation automatically,
  73. // but we need to update the model's position manually in any case
  74. Animation@ walkAnimation = cache.GetResource("Animation", "Models/Jack_Walk.ani");
  75. AnimationState@ state = modelObject.AddAnimationState(walkAnimation);
  76. // Enable full blending weight and looping
  77. state.weight = 1.0f;
  78. state.looped = true;
  79. // Create our Mover script object that will move & animate the model during each frame's update. Here we use a shortcut
  80. // script-only API function, CreateScriptObject, which creates a ScriptInstance component into the scene node, then uses
  81. // it to instantiate the object (using the script file & class name provided)
  82. Mover@ mover = cast<Mover>(modelNode.CreateScriptObject(scriptFile, "Mover"));
  83. mover.SetParameters(MODEL_MOVE_SPEED, MODEL_ROTATE_SPEED, bounds);
  84. }
  85. // Create the camera. Limit far clip distance to match the fog
  86. cameraNode = scene_.CreateChild("Camera");
  87. Camera@ camera = cameraNode.CreateComponent("Camera");
  88. camera.farClip = 300.0f;
  89. // Set an initial position for the camera scene node above the plane
  90. cameraNode.position = Vector3(0.0f, 5.0f, 0.0f);
  91. }
  92. void CreateInstructions()
  93. {
  94. // Construct new Text object, set string to display and font to use
  95. Text@ instructionText = ui.root.CreateChild("Text");
  96. instructionText.text =
  97. "Use WASD keys and mouse to move\n"
  98. "Space to toggle debug geometry";
  99. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  100. // The text has multiple rows. Center them in relation to each other
  101. instructionText.textAlignment = HA_CENTER;
  102. // Position the text relative to the screen center
  103. instructionText.horizontalAlignment = HA_CENTER;
  104. instructionText.verticalAlignment = VA_CENTER;
  105. instructionText.SetPosition(0, ui.root.height / 4);
  106. }
  107. void SetupViewport()
  108. {
  109. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  110. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  111. renderer.viewports[0] = viewport;
  112. }
  113. void SubscribeToEvents()
  114. {
  115. // Subscribe HandleUpdate() function for processing update events
  116. SubscribeToEvent("Update", "HandleUpdate");
  117. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, sent after Renderer subsystem is
  118. // done with defining the draw calls for the viewports (but before actually executing them.) We will request debug geometry
  119. // rendering during that event
  120. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
  121. }
  122. void MoveCamera(float timeStep)
  123. {
  124. // Do not move if the UI has a focused element (the console)
  125. if (ui.focusElement !is null)
  126. return;
  127. // Movement speed as world units per second
  128. const float MOVE_SPEED = 20.0f;
  129. // Mouse sensitivity as degrees per pixel
  130. const float MOUSE_SENSITIVITY = 0.1f;
  131. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  132. IntVector2 mouseMove = input.mouseMove;
  133. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  134. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  135. pitch = Clamp(pitch, -90.0f, 90.0f);
  136. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  137. cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
  138. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  139. if (input.keyDown['W'])
  140. cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, 1.0f) * MOVE_SPEED * timeStep);
  141. if (input.keyDown['S'])
  142. cameraNode.TranslateRelative(Vector3(0.0f, 0.0f, -1.0f) * MOVE_SPEED * timeStep);
  143. if (input.keyDown['A'])
  144. cameraNode.TranslateRelative(Vector3(-1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  145. if (input.keyDown['D'])
  146. cameraNode.TranslateRelative(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
  147. // Toggle debug geometry with space
  148. if (input.keyPress[KEY_SPACE])
  149. drawDebug = !drawDebug;
  150. }
  151. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  152. {
  153. // Take the frame time step, which is stored as a float
  154. float timeStep = eventData["TimeStep"].GetFloat();
  155. // Move the camera, scale movement with time step
  156. MoveCamera(timeStep);
  157. }
  158. void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  159. {
  160. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  161. // bones. Note that debug geometry has to be separately requested each frame. Disable depth test so that we can see the
  162. // bones properly
  163. if (drawDebug)
  164. renderer.DrawDebugGeometry(false);
  165. }
  166. // Mover script object class
  167. class Mover : ScriptObject
  168. {
  169. float moveSpeed = 0.0f;
  170. float rotationSpeed = 0.0f;
  171. BoundingBox bounds;
  172. void SetParameters(float moveSpeed_, float rotationSpeed_, const BoundingBox& bounds_)
  173. {
  174. moveSpeed = moveSpeed_;
  175. rotationSpeed = rotationSpeed_;
  176. bounds = bounds_;
  177. }
  178. void Update(float timeStep)
  179. {
  180. node.TranslateRelative(Vector3(0.0f, 0.0f, 1.0f) * moveSpeed * timeStep);
  181. // If in risk of going outside the plane, rotate the model right
  182. Vector3 pos = node.position;
  183. if (pos.x < bounds.min.x || pos.x > bounds.max.x || pos.z < bounds.min.z || pos.z > bounds.max.z)
  184. node.Yaw(rotationSpeed * timeStep);
  185. // Get the model's first (only) animation state and advance its time
  186. AnimatedModel@ model = node.GetComponent("AnimatedModel");
  187. AnimationState@ state = model.GetAnimationState(0);
  188. if (state !is null)
  189. state.AddTime(timeStep);
  190. }
  191. }