08_Decals.lua 12 KB

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