Water.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/CoreEvents.h>
  24. #include <Atomic/Engine/Engine.h>
  25. #include <Atomic/Graphics/Camera.h>
  26. #include <Atomic/Graphics/Graphics.h>
  27. #include <Atomic/Graphics/Light.h>
  28. #include <Atomic/Graphics/Material.h>
  29. #include <Atomic/Graphics/Model.h>
  30. #include <Atomic/Graphics/Octree.h>
  31. #include <Atomic/Graphics/Renderer.h>
  32. #include <Atomic/Graphics/RenderSurface.h>
  33. #include <Atomic/Graphics/Skybox.h>
  34. #include <Atomic/Graphics/Terrain.h>
  35. #include <Atomic/Graphics/Texture2D.h>
  36. #include <Atomic/Graphics/Zone.h>
  37. #include <Atomic/Input/Input.h>
  38. #include <Atomic/IO/File.h>
  39. #include <Atomic/IO/FileSystem.h>
  40. #include <Atomic/Resource/ResourceCache.h>
  41. #include <Atomic/Scene/Scene.h>
  42. #include <Atomic/UI/UI.h>
  43. #include "Water.h"
  44. #include <Atomic/DebugNew.h>
  45. Water::Water(Context* context) :
  46. Sample(context)
  47. {
  48. }
  49. void Water::Start()
  50. {
  51. // Execute base class startup
  52. Sample::Start();
  53. // Create the scene content
  54. CreateScene();
  55. // Create the UI content
  56. CreateInstructions();
  57. // Setup the viewport for displaying the scene
  58. SetupViewport();
  59. // Hook up to the frame update event
  60. SubscribeToEvents();
  61. // Set the mouse mode to use in the sample
  62. Sample::InitMouseMode(MM_RELATIVE);
  63. }
  64. void Water::CreateScene()
  65. {
  66. ResourceCache* cache = GetSubsystem<ResourceCache>();
  67. scene_ = new Scene(context_);
  68. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  69. scene_->CreateComponent<Octree>();
  70. // Create a Zone component for ambient lighting & fog control
  71. Node* zoneNode = scene_->CreateChild("Zone");
  72. Zone* zone = zoneNode->CreateComponent<Zone>();
  73. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  74. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  75. zone->SetFogColor(Color(1.0f, 1.0f, 1.0f));
  76. zone->SetFogStart(500.0f);
  77. zone->SetFogEnd(750.0f);
  78. // Create a directional light to the world. Enable cascaded shadows on it
  79. Node* lightNode = scene_->CreateChild("DirectionalLight");
  80. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  81. Light* light = lightNode->CreateComponent<Light>();
  82. light->SetLightType(LIGHT_DIRECTIONAL);
  83. light->SetCastShadows(true);
  84. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  85. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  86. light->SetSpecularIntensity(0.5f);
  87. // Apply slightly overbright lighting to match the skybox
  88. light->SetColor(Color(1.2f, 1.2f, 1.2f));
  89. // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  90. // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  91. // generate the necessary 3D texture coordinates for cube mapping
  92. Node* skyNode = scene_->CreateChild("Sky");
  93. skyNode->SetScale(500.0f); // The scale actually does not matter
  94. Skybox* skybox = skyNode->CreateComponent<Skybox>();
  95. skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  96. skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
  97. // Create heightmap terrain
  98. Node* terrainNode = scene_->CreateChild("Terrain");
  99. terrainNode->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
  100. Terrain* terrain = terrainNode->CreateComponent<Terrain>();
  101. terrain->SetPatchSize(64);
  102. terrain->SetSpacing(Vector3(2.0f, 0.5f, 2.0f)); // Spacing between vertices and vertical resolution of the height map
  103. terrain->SetSmoothing(true);
  104. terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
  105. terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
  106. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  107. // terrain patches and other objects behind it
  108. terrain->SetOccluder(true);
  109. // Create 1000 boxes in the terrain. Always face outward along the terrain normal
  110. unsigned NUM_OBJECTS = 1000;
  111. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  112. {
  113. Node* objectNode = scene_->CreateChild("Box");
  114. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  115. position.y_ = terrain->GetHeight(position) + 2.25f;
  116. objectNode->SetPosition(position);
  117. // Create a rotation quaternion from up vector to terrain normal
  118. objectNode->SetRotation(Quaternion(Vector3(0.0f, 1.0f, 0.0f), terrain->GetNormal(position)));
  119. objectNode->SetScale(5.0f);
  120. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  121. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  122. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  123. object->SetCastShadows(true);
  124. }
  125. // Create a water plane object that is as large as the terrain
  126. waterNode_ = scene_->CreateChild("Water");
  127. waterNode_->SetScale(Vector3(2048.0f, 1.0f, 2048.0f));
  128. waterNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  129. StaticModel* water = waterNode_->CreateComponent<StaticModel>();
  130. water->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  131. water->SetMaterial(cache->GetResource<Material>("Materials/Water.xml"));
  132. // Set a different viewmask on the water plane to be able to hide it from the reflection camera
  133. water->SetViewMask(0x80000000);
  134. // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  135. // the scene, because we want it to be unaffected by scene load / save
  136. cameraNode_ = new Node(context_);
  137. Camera* camera = cameraNode_->CreateComponent<Camera>();
  138. camera->SetFarClip(750.0f);
  139. // Set an initial position for the camera scene node above the ground
  140. cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -20.0f));
  141. }
  142. void Water::CreateInstructions()
  143. {
  144. SimpleCreateInstructions("Use WASD keys and mouse/touch to move");
  145. }
  146. void Water::SetupViewport()
  147. {
  148. Graphics* graphics = GetSubsystem<Graphics>();
  149. Renderer* renderer = GetSubsystem<Renderer>();
  150. ResourceCache* cache = GetSubsystem<ResourceCache>();
  151. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  152. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  153. renderer->SetViewport(0, viewport);
  154. // Create a mathematical plane to represent the water in calculations
  155. waterPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition());
  156. // Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
  157. waterClipPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition() -
  158. Vector3(0.0f, 0.1f, 0.0f));
  159. // Create camera for water reflection
  160. // It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
  161. // its position when rendering
  162. reflectionCameraNode_ = cameraNode_->CreateChild();
  163. Camera* reflectionCamera = reflectionCameraNode_->CreateComponent<Camera>();
  164. reflectionCamera->SetFarClip(750.0);
  165. reflectionCamera->SetViewMask(0x7fffffff); // Hide objects with only bit 31 in the viewmask (the water plane)
  166. reflectionCamera->SetAutoAspectRatio(false);
  167. reflectionCamera->SetUseReflection(true);
  168. reflectionCamera->SetReflectionPlane(waterPlane_);
  169. reflectionCamera->SetUseClipping(true); // Enable clipping of geometry behind water plane
  170. reflectionCamera->SetClipPlane(waterClipPlane_);
  171. // The water reflection texture is rectangular. Set reflection camera aspect ratio to match
  172. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  173. // View override flags could be used to optimize reflection rendering. For example disable shadows
  174. //reflectionCamera->SetViewOverrideFlags(VO_DISABLE_SHADOWS);
  175. // Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
  176. // texture unit of the water material
  177. int texSize = 1024;
  178. SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
  179. renderTexture->SetSize(texSize, texSize, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
  180. renderTexture->SetFilterMode(FILTER_BILINEAR);
  181. RenderSurface* surface = renderTexture->GetRenderSurface();
  182. SharedPtr<Viewport> rttViewport(new Viewport(context_, scene_, reflectionCamera));
  183. surface->SetViewport(0, rttViewport);
  184. Material* waterMat = cache->GetResource<Material>("Materials/Water.xml");
  185. waterMat->SetTexture(TU_DIFFUSE, renderTexture);
  186. }
  187. void Water::SubscribeToEvents()
  188. {
  189. // Subscribe HandleUpdate() function for processing update events
  190. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(Water, HandleUpdate));
  191. }
  192. void Water::MoveCamera(float timeStep)
  193. {
  194. Input* input = GetSubsystem<Input>();
  195. // Movement speed as world units per second
  196. const float MOVE_SPEED = 20.0f;
  197. // Mouse sensitivity as degrees per pixel
  198. const float MOUSE_SENSITIVITY = 0.1f;
  199. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  200. IntVector2 mouseMove = input->GetMouseMove();
  201. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  202. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  203. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  204. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  205. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  206. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  207. if (input->GetKeyDown(KEY_W))
  208. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  209. if (input->GetKeyDown(KEY_S))
  210. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  211. if (input->GetKeyDown(KEY_A))
  212. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  213. if (input->GetKeyDown(KEY_D))
  214. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  215. // In case resolution has changed, adjust the reflection camera aspect ratio
  216. Graphics* graphics = GetSubsystem<Graphics>();
  217. Camera* reflectionCamera = reflectionCameraNode_->GetComponent<Camera>();
  218. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  219. }
  220. void Water::HandleUpdate(StringHash eventType, VariantMap& eventData)
  221. {
  222. using namespace Update;
  223. // Take the frame time step, which is stored as a float
  224. float timeStep = eventData[P_TIMESTEP].GetFloat();
  225. // Move the camera, scale movement with time step
  226. MoveCamera(timeStep);
  227. }