23_Water.lua 9.7 KB

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