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