07_Billboards.lua 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. -- Billboard example.
  2. -- This sample demonstrates:
  3. -- - Populating a 3D scene with billboard sets and several shadow casting spotlights
  4. -- - Parenting scene nodes to allow more intuitive creation of groups of objects
  5. -- - Examining rendering performance with a somewhat large object and light count
  6. require "LuaScripts/Utilities/Sample"
  7. local lightNodes = {}
  8. local billboardNodes = {}
  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 a Zone component for ambient lighting & fog control
  30. local zoneNode = scene_:CreateChild("Zone")
  31. local zone = zoneNode:CreateComponent("Zone")
  32. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  33. zone.ambientColor = Color(0.1, 0.1, 0.1)
  34. zone.fogStart = 100.0
  35. zone.fogEnd = 300.0
  36. -- Create a directional light without shadows
  37. local lightNode = scene_:CreateChild("DirectionalLight")
  38. lightNode.direction = Vector3(0.5, -1.0, 0.5)
  39. local light = lightNode:CreateComponent("Light")
  40. light.lightType = LIGHT_DIRECTIONAL
  41. light.color = Color(0.2, 0.2, 0.2)
  42. light.specularIntensity = 1.0
  43. -- Create a "floor" consisting of several tiles
  44. for y = -5, 5 do
  45. for x = -5, 5 do
  46. local floorNode = scene_:CreateChild("FloorTile")
  47. floorNode.position = Vector3(x * 20.5, -0.5, y * 20.5)
  48. floorNode.scale = Vector3(20.0, 1.0, 20.0)
  49. local floorObject = floorNode:CreateComponent("StaticModel")
  50. floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
  51. floorObject.material = cache:GetResource("Material", "Materials/Stone.xml")
  52. end
  53. end
  54. -- Create groups of mushrooms, which act as shadow casters
  55. local NUM_MUSHROOMGROUPS = 25
  56. local NUM_MUSHROOMS = 25
  57. for i = 1, NUM_MUSHROOMGROUPS do
  58. -- First create a scene node for the group. The individual mushrooms nodes will be created as children
  59. local groupNode = scene_:CreateChild("MushroomGroup")
  60. groupNode.position = Vector3(Random(190.0) - 95.0, 0.0, Random(190.0) - 95.0)
  61. for j = 1, NUM_MUSHROOMS do
  62. local mushroomNode = groupNode:CreateChild("Mushroom")
  63. mushroomNode.position = Vector3(Random(25.0) - 12.5, 0.0, Random(25.0) - 12.5)
  64. mushroomNode.rotation = Quaternion(0.0, Random() * 360.0, 0.0)
  65. mushroomNode:SetScale(1.0 + Random() * 4.0)
  66. local mushroomObject = mushroomNode:CreateComponent("StaticModel")
  67. mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  68. mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  69. mushroomObject.castShadows = true
  70. end
  71. end
  72. -- Create billboard sets (floating smoke)
  73. local NUM_BILLBOARDNODES = 25
  74. local NUM_BILLBOARDS = 10
  75. for i = 1, NUM_BILLBOARDNODES do
  76. local smokeNode = scene_:CreateChild("Smoke")
  77. smokeNode.position = Vector3(Random(200.0) - 100.0, Random(20.0) + 10.0, Random(200.0) - 100.0)
  78. local billboardObject = smokeNode:CreateComponent("BillboardSet")
  79. billboardObject.numBillboards = NUM_BILLBOARDS
  80. billboardObject.material = cache:GetResource("Material", "Materials/LitSmoke.xml")
  81. billboardObject.sorted = true
  82. for j = 1, NUM_BILLBOARDS do
  83. local bb = billboardObject:GetBillboard(j - 1)
  84. bb.position = Vector3(Random(12.0) - 6.0, Random(8.0) - 4.0, Random(12.0) - 6.0)
  85. bb.size = Vector2(Random(2.0) + 3.0, Random(2.0) + 3.0)
  86. bb.rotation = Random() * 360.0
  87. bb.enabled = true
  88. end
  89. -- After modifying the billboards, they need to be "committed" so that the BillboardSet updates its internals
  90. billboardObject:Commit()
  91. table.insert(billboardNodes, smokeNode)
  92. end
  93. -- Create shadow casting spotlights
  94. local NUM_LIGHTS = 9
  95. for i = 0, NUM_LIGHTS - 1 do
  96. local lightNode = scene_:CreateChild("SpotLight")
  97. local light = lightNode:CreateComponent("Light")
  98. local angle = 0.0
  99. local position = Vector3((i % 3) * 60.0 - 60.0, 45.0, math.floor(i / 3) * 60.0 - 60.0)
  100. local color = Color(((i + 1) % 2) * 0.5 + 0.5, (math.floor((i + 1) / 2) % 2) * 0.5 + 0.5, (math.floor((i + 1) / 4) % 2) * 0.5 + 0.5)
  101. lightNode.position = position
  102. lightNode.direction = Vector3(math.sin(M_DEGTORAD * angle), -1.5, math.cos(M_DEGTORAD * angle))
  103. light.lightType = LIGHT_SPOT
  104. light.range = 90.0
  105. light.rampTexture = cache:GetResource("Texture2D", "Textures/RampExtreme.png")
  106. light.fov = 45.0
  107. light.color = color
  108. light.specularIntensity = 1.0
  109. light.castShadows = true
  110. light.shadowBias = BiasParameters(0.00002, 0.0)
  111. -- Configure shadow fading for the lights. When they are far away enough, the lights eventually become unshadowed for
  112. -- better GPU performance. Note that we could also set the maximum distance for each object to cast shadows
  113. light.shadowFadeDistance = 100.0 -- Fade start distance
  114. light.shadowDistance = 125.0 -- Fade end distance, shadows are disabled
  115. -- Set half resolution for the shadow maps for increased performance
  116. light.shadowResolution = 0.5
  117. -- The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  118. -- for better shadow depth resolution
  119. light.shadowNearFarRatio = 0.01
  120. table.insert(lightNodes, lightNode)
  121. end
  122. -- Create the camera. Limit far clip distance to match the fog
  123. cameraNode = scene_:CreateChild("Camera")
  124. local camera = cameraNode:CreateComponent("Camera")
  125. camera.farClip = 300.0
  126. -- Set an initial position for the camera scene node above the plane
  127. cameraNode.position = Vector3(0.0, 5.0, 0.0)
  128. end
  129. function CreateInstructions()
  130. -- Construct new Text object, set string to display and font to use
  131. local instructionText = ui.root:CreateChild("Text")
  132. instructionText.text =
  133. "Use WASD keys and mouse to move\n"..
  134. "Space to toggle debug geometry"
  135. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  136. -- The text has multiple rows. Center them in relation to each other
  137. instructionText.textAlignment = HA_CENTER
  138. -- Position the text relative to the screen center
  139. instructionText.horizontalAlignment = HA_CENTER
  140. instructionText.verticalAlignment = VA_CENTER
  141. instructionText:SetPosition(0, ui.root.height / 4)
  142. end
  143. function SetupViewport()
  144. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  145. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  146. renderer:SetViewport(0, viewport)
  147. end
  148. function SubscribeToEvents()
  149. -- Subscribe HandleUpdate() function for processing update events
  150. SubscribeToEvent("Update", "HandleUpdate")
  151. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  152. -- debug geometry
  153. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  154. end
  155. function MoveCamera(timeStep)
  156. -- Do not move if the UI has a focused element (the console)
  157. if ui.focusElement ~= nil then
  158. return
  159. end
  160. -- Movement speed as world units per second
  161. local MOVE_SPEED = 20.0
  162. -- Mouse sensitivity as degrees per pixel
  163. local MOUSE_SENSITIVITY = 0.1
  164. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  165. local mouseMove = input.mouseMove
  166. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  167. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  168. pitch = Clamp(pitch, -90.0, 90.0)
  169. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  170. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  171. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  172. if input:GetKeyDown(KEY_W) then
  173. cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  174. end
  175. if input:GetKeyDown(KEY_S) then
  176. cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  177. end
  178. if input:GetKeyDown(KEY_A) then
  179. cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  180. end
  181. if input:GetKeyDown(KEY_D) then
  182. cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  183. end
  184. -- Toggle debug geometry with space
  185. if input:GetKeyPress(KEY_SPACE) then
  186. drawDebug = not drawDebug
  187. end
  188. end
  189. function AnimateScene(timeStep)
  190. local LIGHT_ROTATION_SPEED = 20.0
  191. local BILLBOARD_ROTATION_SPEED = 50.0
  192. -- Rotate the lights around the world Y-axis
  193. for i, v in ipairs(lightNodes) do
  194. v:Rotate(Quaternion(0.0, LIGHT_ROTATION_SPEED * timeStep, 0.0), TS_WORLD)
  195. end
  196. -- Rotate the individual billboards within the billboard sets, then recommit to make the changes visible
  197. for i, v in ipairs(billboardNodes) do
  198. local billboardObject = v:GetComponent("BillboardSet")
  199. for j = 1, billboardObject.numBillboards do
  200. local bb = billboardObject:GetBillboard(j - 1)
  201. bb.rotation = bb.rotation + BILLBOARD_ROTATION_SPEED * timeStep
  202. end
  203. billboardObject:Commit()
  204. end
  205. end
  206. function HandleUpdate(eventType, eventData)
  207. -- Take the frame time step, which is stored as a float
  208. local timeStep = eventData["TimeStep"]:GetFloat()
  209. -- Move the camera and animate the scene, scale movement with time step
  210. MoveCamera(timeStep)
  211. AnimateScene(timeStep)
  212. end
  213. function HandlePostRenderUpdate(eventType, eventData)
  214. -- If draw debug mode is enabled, draw viewport debug geometry. This time use depth test, as otherwise the result becomes
  215. -- hard to interpret due to large object count
  216. if drawDebug then
  217. renderer:DrawDebugGeometry(true)
  218. end
  219. end
  220. -- Create XML patch instructions for screen joystick layout specific to this sample app
  221. function GetScreenJoystickPatchString()
  222. return
  223. "<patch>" ..
  224. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  225. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
  226. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  227. " <element type=\"Text\">" ..
  228. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  229. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  230. " </element>" ..
  231. " </add>" ..
  232. "</patch>"
  233. end