06_SkeletalAnimation.as 10 KB

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