08_Decals.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. -- Decals example.
  2. -- This sample demonstrates:
  3. -- - Performing a raycast to the octree and adding a decal to the hit location
  4. -- - Defining a Cursor UI element which stays inside the window and can be shown/hidden
  5. -- - Marking suitable (large) objects as occluders for occlusion culling
  6. -- - Displaying renderer debug geometry to see the effect of occlusion
  7. require "LuaScripts/Utilities/Sample"
  8. local scene_ = nil
  9. local cameraNode = nil
  10. local yaw = 0.0
  11. local pitch = 0.0
  12. local drawDebug = false
  13. local context = GetContext()
  14. local cache = GetCache()
  15. local input = GetInput()
  16. local graphics = GetGraphics()
  17. local renderer = GetRenderer()
  18. local ui = GetUI()
  19. function Start()
  20. -- Execute the common startup for samples
  21. SampleStart()
  22. -- Create the scene content
  23. CreateScene()
  24. -- Create the UI content
  25. CreateUI()
  26. -- Setup the viewport for displaying the scene
  27. SetupViewport()
  28. -- Hook up to the frame update and render post-update events
  29. SubscribeToEvents()
  30. end
  31. function CreateScene()
  32. scene_ = Scene(context)
  33. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  34. -- Also create a DebugRenderer component so that we can draw debug geometry
  35. scene_:CreateComponent("Octree")
  36. scene_:CreateComponent("DebugRenderer")
  37. -- Create scene node & StaticModel component for showing a static plane
  38. local planeNode = scene_:CreateChild("Plane")
  39. planeNode.scale = Vector3(100.0, 1.0, 100.0)
  40. local planeObject = planeNode:CreateComponent("StaticModel")
  41. planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
  42. planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  43. -- Create a Zone component for ambient lighting & fog control
  44. local zoneNode = scene_:CreateChild("Zone")
  45. local zone = zoneNode:CreateComponent("Zone")
  46. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  47. zone.ambientColor = Color(0.15, 0.15, 0.15)
  48. zone.fogColor = Color(0.5, 0.5, 0.7)
  49. zone.fogStart = 100.0
  50. zone.fogEnd = 300.0
  51. -- Create a directional light to the world. Enable cascaded shadows on it
  52. local lightNode = scene_:CreateChild("DirectionalLight")
  53. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  54. local light = lightNode:CreateComponent("Light")
  55. light.lightType = LIGHT_DIRECTIONAL
  56. light.castShadows = true
  57. light.shadowBias = BiasParameters(0.00025, 0.5)
  58. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  59. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  60. -- Create some mushrooms
  61. local NUM_MUSHROOMS = 240
  62. for i = 1, NUM_MUSHROOMS do
  63. local mushroomNode = scene_:CreateChild("Mushroom")
  64. mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)
  65. mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  66. mushroomNode:SetScale(0.5 + Random(2.0))
  67. local mushroomObject = mushroomNode:CreateComponent("StaticModel")
  68. mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  69. mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  70. mushroomObject.castShadows = true
  71. end
  72. -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  73. -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  74. local NUM_BOXES = 20
  75. for i = 1, NUM_BOXES do
  76. local boxNode = scene_:CreateChild("Box")
  77. local size = 1.0 + Random(10.0)
  78. boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0)
  79. boxNode:SetScale(size)
  80. local boxObject = boxNode:CreateComponent("StaticModel")
  81. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  82. boxObject.material = cache:GetResource("Material", "Materials/Stone.xml")
  83. boxObject.castShadows = true
  84. if size >= 3.0 then
  85. boxObject.occluder = true
  86. end
  87. end
  88. -- Create the camera. Limit far clip distance to match the fog
  89. cameraNode = scene_:CreateChild("Camera")
  90. local camera = cameraNode:CreateComponent("Camera")
  91. camera.farClip = 300.0
  92. -- Set an initial position for the camera scene node above the plane
  93. cameraNode.position = Vector3(0.0, 5.0, 0.0)
  94. end
  95. function CreateUI()
  96. -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  97. -- control the camera, and when visible, it will point the raycast target
  98. local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
  99. local cursor = ui.root:CreateChild("Cursor")
  100. cursor:SetStyleAuto(style)
  101. ui.cursor = cursor
  102. -- Set starting position of the cursor at the rendering window center
  103. cursor:SetPosition(graphics.width / 2, graphics.height / 2)
  104. -- Construct new Text object, set string to display and font to use
  105. local instructionText = ui.root:CreateChild("Text")
  106. instructionText.text =
  107. "Use WASD keys to move\n"..
  108. "LMB to paint decals, RMB to rotate view\n"..
  109. "Space to toggle debug geometry\n"..
  110. "7 to toggle occlusion culling"
  111. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  112. -- The text has multiple rows. Center them in relation to each other
  113. instructionText.textAlignment = HA_CENTER
  114. -- Position the text relative to the screen center
  115. instructionText.horizontalAlignment = HA_CENTER
  116. instructionText.verticalAlignment = VA_CENTER
  117. instructionText:SetPosition(0, ui.root.height / 4)
  118. end
  119. function SetupViewport()
  120. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  121. local viewport = Viewport:new(context, scene_, cameraNode:GetComponent("Camera"))
  122. renderer:SetViewport(0, viewport)
  123. end
  124. function SubscribeToEvents()
  125. -- Subscribe HandleUpdate() function for processing update events
  126. SubscribeToEvent("Update", "HandleUpdate")
  127. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  128. -- debug geometry
  129. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  130. end
  131. function MoveCamera(timeStep)
  132. -- Right mouse button controls mouse cursor visibility: hide when pressed
  133. ui.cursor.visible = not input:GetMouseButtonDown(MOUSEB_RIGHT)
  134. -- Do not move if the UI has a focused element (the console)
  135. if ui.focusElement ~= nil then
  136. return
  137. end
  138. -- Movement speed as world units per second
  139. local MOVE_SPEED = 20.0
  140. -- Mouse sensitivity as degrees per pixel
  141. local MOUSE_SENSITIVITY = 0.1
  142. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  143. -- Only move the camera when the cursor is hidden
  144. if not ui.cursor.visible then
  145. local mouseMove = input.mouseMove
  146. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  147. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  148. pitch = Clamp(pitch, -90.0, 90.0)
  149. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  150. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  151. end
  152. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  153. if input:GetKeyDown(KEY_W) then
  154. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  155. end
  156. if input:GetKeyDown(KEY_S) then
  157. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  158. end
  159. if input:GetKeyDown(KEY_A) then
  160. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  161. end
  162. if input:GetKeyDown(KEY_D) then
  163. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  164. end
  165. -- Toggle debug geometry with space
  166. if input:GetKeyPress(KEY_SPACE) then
  167. drawDebug = not drawDebug
  168. end
  169. -- Paint decal with the left mousebutton cursor must be visible
  170. if ui.cursor.visible and input:GetMouseButtonPress(MOUSEB_LEFT) then
  171. PaintDecal()
  172. end
  173. end
  174. function PaintDecal()
  175. local result, hitPos, hitDrawable = Raycast(250.0)
  176. if result then
  177. -- Check if target scene node already has a DecalSet component. If not, create now
  178. local targetNode = hitDrawable:GetNode()
  179. local decal = targetNode:GetComponent("DecalSet")
  180. if decal == nil then
  181. decal = targetNode:CreateComponent("DecalSet")
  182. decal.material = cache:GetResource("Material", "Materials/UrhoDecal.xml")
  183. end
  184. -- Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  185. -- use full texture UV's (0,0) to (1,1). Note that if we create several decals to a large object (such as the ground
  186. -- plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  187. -- undesirable, it may be necessary to create more than one DecalSet based on the distance
  188. decal:AddDecal(hitDrawable, hitPos, cameraNode.rotation, 0.5, 1.0, 1.0, Vector2(0.0, 0.0), Vector2(1.0, 1.0))
  189. end
  190. end
  191. function Raycast(maxDistance)
  192. local hitPos = nil
  193. local hitDrawable = nil
  194. local pos = ui.cursorPosition
  195. -- Check the cursor is visible and there is no UI element in front of the cursor
  196. if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then
  197. return false, nil, nil
  198. end
  199. local camera = cameraNode:GetComponent("Camera")
  200. local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height)
  201. -- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  202. local octree = scene_:GetComponent("Octree")
  203. local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY)
  204. if result.drawable ~= nil then
  205. -- Calculate hit position in world space
  206. hitPos = cameraRay.origin + cameraRay.direction * result.distance
  207. hitDrawable = result.drawable
  208. return true, hitPos, hitDrawable
  209. end
  210. return false, nil, nil
  211. end
  212. function HandleUpdate(eventType, eventData)
  213. -- Take the frame time step, which is stored as a float
  214. local timeStep = eventData:GetFloat("TimeStep")
  215. -- Move the camera, scale movement with time step
  216. MoveCamera(timeStep)
  217. end
  218. function HandlePostRenderUpdate(eventType, eventData)
  219. -- If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
  220. if drawDebug then
  221. renderer:DrawDebugGeometry(false)
  222. end
  223. end