23_Water.lua 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. -- Water example.
  2. -- This sample demonstrates:
  3. -- - Creating a large plane to represent a water body for rendering
  4. -- - Setting up a second camera to render reflections on the water surface
  5. require "LuaScripts/Utilities/Sample"
  6. local scene_ = nil
  7. local cameraNode = nil
  8. local reflectionCameraNode = nil
  9. local waterNode = nil
  10. local waterPlane = Plane()
  11. local waterClipPlane = Plane()
  12. local yaw = 0.0
  13. local pitch = 0.0
  14. local context = GetContext()
  15. local cache = GetCache()
  16. local fileSystem = GetFileSystem()
  17. local graphics = GetGraphics()
  18. local input = GetInput()
  19. local renderer = GetRenderer()
  20. local ui = GetUI()
  21. function Start()
  22. -- Execute the common startup for samples
  23. SampleStart()
  24. -- Create the scene content
  25. CreateScene()
  26. -- Create the UI content
  27. CreateInstructions()
  28. -- Setup the viewport for displaying the scene
  29. SetupViewport()
  30. -- Hook up to the frame update event
  31. SubscribeToEvents()
  32. end
  33. function CreateScene()
  34. scene_ = Scene(context)
  35. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  36. scene_:CreateComponent("Octree")
  37. -- Create a Zone component for ambient lighting & fog control
  38. local zoneNode = scene_:CreateChild("Zone")
  39. local zone = zoneNode:CreateComponent("Zone")
  40. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  41. zone.ambientColor = Color(0.15, 0.15, 0.15)
  42. zone.fogColor = Color(1.0, 1.0, 1.0)
  43. zone.fogStart = 500.0
  44. zone.fogEnd = 750.0
  45. -- Create a directional light to the world. Enable cascaded shadows on it
  46. local lightNode = scene_:CreateChild("DirectionalLight")
  47. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  48. local light = lightNode:CreateComponent("Light")
  49. light.lightType = LIGHT_DIRECTIONAL
  50. light.castShadows = true
  51. light.shadowBias = BiasParameters(0.00025, 0.5)
  52. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  53. light.specularIntensity = 0.5;
  54. -- Apply slightly overbright lighting to match the skybox
  55. light.color = Color(1.2, 1.2, 1.2);
  56. -- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  57. -- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  58. -- generate the necessary 3D texture coordinates for cube mapping
  59. local skyNode = scene_:CreateChild("Sky")
  60. skyNode:SetScale(500.0) -- The scale actually does not matter
  61. local skybox = skyNode:CreateComponent("Skybox")
  62. skybox.model = cache:GetResource("Model", "Models/Box.mdl")
  63. skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
  64. -- Create heightmap terrain
  65. local terrainNode = scene_:CreateChild("Terrain")
  66. terrainNode.position = Vector3(0.0, 0.0, 0.0)
  67. local terrain = terrainNode:CreateComponent("Terrain")
  68. terrain.patchSize = 64
  69. terrain.spacing = Vector3(2.0, 0.5, 2.0) -- Spacing between vertices and vertical resolution of the height map
  70. terrain.smoothing = true
  71. terrain.heightMap = cache:GetResource("Image", "Textures/HeightMap.png")
  72. terrain.material = cache:GetResource("Material", "Materials/Terrain.xml")
  73. -- The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  74. -- terrain patches and other objects behind it
  75. terrain.occluder = true
  76. -- Create 1000 boxes in the terrain. Always face outward along the terrain normal
  77. local NUM_OBJECTS = 1000
  78. for i = 1, NUM_OBJECTS do
  79. local objectNode = scene_:CreateChild("Box")
  80. local position = Vector3(Random(2000.0) - 1000.0, 0.0, Random(2000.0) - 1000.0)
  81. position.y = terrain:GetHeight(position) + 2.25
  82. objectNode.position = position
  83. -- Create a rotation quaternion from up vector to terrain normal
  84. objectNode.rotation = Quaternion(Vector3(0.0, 1.0, 0.0), terrain:GetNormal(position))
  85. objectNode:SetScale(5.0)
  86. local object = objectNode:CreateComponent("StaticModel")
  87. object.model = cache:GetResource("Model", "Models/Box.mdl")
  88. object.material = cache:GetResource("Material", "Materials/Stone.xml")
  89. object.castShadows = true
  90. end
  91. -- Create a water plane object that is as large as the terrain
  92. waterNode = scene_:CreateChild("Water")
  93. waterNode.scale = Vector3(2048.0, 1.0, 2048.0)
  94. waterNode.position = Vector3(0.0, 5.0, 0.0)
  95. local water = waterNode:CreateComponent("StaticModel")
  96. water.model = cache:GetResource("Model", "Models/Plane.mdl")
  97. water.material = cache:GetResource("Material", "Materials/Water.xml")
  98. -- Set a different viewmask on the water plane to be able to hide it from the reflection camera
  99. water.viewMask = 0x80000000
  100. -- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  101. -- the scene, because we want it to be unaffected by scene load / save
  102. cameraNode = Node(context)
  103. local camera = cameraNode:CreateComponent("Camera")
  104. camera.farClip = 750.0
  105. -- Set an initial position for the camera scene node above the floor
  106. cameraNode.position = Vector3(0.0, 7.0, -20.0)
  107. end
  108. function CreateInstructions()
  109. -- Construct new Text object, set string to display and font to use
  110. local instructionText = ui.root:CreateChild("Text")
  111. instructionText:SetText("Use WASD keys and mouse to move")
  112. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  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. -- Create a mathematical plane to represent the water in calculations
  124. waterPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition)
  125. -- Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
  126. waterClipPlane = Plane(waterNode.worldRotation * Vector3(0.0, 1.0, 0.0), waterNode.worldPosition -
  127. Vector3(0.0, 0.1, 0.0))
  128. -- Create camera for water reflection
  129. -- It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
  130. -- its position when rendering
  131. reflectionCameraNode = cameraNode:CreateChild()
  132. local reflectionCamera = reflectionCameraNode:CreateComponent("Camera")
  133. reflectionCamera.farClip = 750.0
  134. reflectionCamera.viewMask = 0x7fffffff -- Hide objects with only bit 31 in the viewmask (the water plane)
  135. reflectionCamera.autoAspectRatio = false
  136. reflectionCamera.useReflection = true
  137. reflectionCamera.reflectionPlane = waterPlane
  138. reflectionCamera.useClipping = true -- Enable clipping of geometry behind water plane
  139. reflectionCamera.clipPlane = waterClipPlane
  140. -- The water reflection texture is rectangular. Set reflection camera aspect ratio to match
  141. reflectionCamera.aspectRatio = graphics.width / graphics.height
  142. -- View override flags could be used to optimize reflection rendering. For example disable shadows
  143. --reflectionCamera.viewOverrideFlags = VO_DISABLE_SHADOWS
  144. -- Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
  145. -- texture unit of the water material
  146. local texSize = 1024
  147. local renderTexture = Texture2D:new(context)
  148. renderTexture:SetSize(texSize, texSize, Graphics:GetRGBFormat(), TEXTURE_RENDERTARGET)
  149. renderTexture.filterMode = FILTER_BILINEAR
  150. local surface = renderTexture.renderSurface
  151. local rttViewport = Viewport:new(context, scene_, reflectionCamera)
  152. surface:SetViewport(0, rttViewport)
  153. local waterMat = cache:GetResource("Material", "Materials/Water.xml")
  154. waterMat:SetTexture(TU_DIFFUSE, renderTexture)
  155. end
  156. function SubscribeToEvents()
  157. -- Subscribe HandleUpdate() function for processing update events
  158. SubscribeToEvent("Update", "HandleUpdate")
  159. end
  160. function MoveCamera(timeStep)
  161. -- Do not move if the UI has a focused element (the console)
  162. if ui.focusElement ~= nil then
  163. return
  164. end
  165. -- Movement speed as world units per second
  166. local MOVE_SPEED = 20.0
  167. -- Mouse sensitivity as degrees per pixel
  168. local MOUSE_SENSITIVITY = 0.1
  169. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  170. local mouseMove = input.mouseMove
  171. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  172. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  173. pitch = Clamp(pitch, -90.0, 90.0)
  174. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  175. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  176. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  177. if input:GetKeyDown(KEY_W) then
  178. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  179. end
  180. if input:GetKeyDown(KEY_S) then
  181. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  182. end
  183. if input:GetKeyDown(KEY_A) then
  184. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  185. end
  186. if input:GetKeyDown(KEY_D) then
  187. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  188. end
  189. -- In case resolution has changed, adjust the reflection camera aspect ratio
  190. local reflectionCamera = reflectionCameraNode:GetComponent("Camera")
  191. reflectionCamera.aspectRatio = graphics.width / graphics.height
  192. end
  193. function HandleUpdate(eventType, eventData)
  194. -- Take the frame time step, which is stored as a float
  195. local timeStep = eventData:GetFloat("TimeStep")
  196. -- Move the camera, scale movement with time step
  197. MoveCamera(timeStep)
  198. end