06_SkeletalAnimation.as 10 KB

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