23_Water.as 9.9 KB

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