Water.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Core/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/Camera.h>
  25. #include <Urho3D/Graphics/Graphics.h>
  26. #include <Urho3D/Graphics/Light.h>
  27. #include <Urho3D/Graphics/Material.h>
  28. #include <Urho3D/Graphics/Model.h>
  29. #include <Urho3D/Graphics/Octree.h>
  30. #include <Urho3D/Graphics/Renderer.h>
  31. #include <Urho3D/Graphics/RenderSurface.h>
  32. #include <Urho3D/Graphics/Skybox.h>
  33. #include <Urho3D/Graphics/Terrain.h>
  34. #include <Urho3D/Graphics/Texture2D.h>
  35. #include <Urho3D/Graphics/Zone.h>
  36. #include <Urho3D/Input/Input.h>
  37. #include <Urho3D/IO/File.h>
  38. #include <Urho3D/IO/FileSystem.h>
  39. #include <Urho3D/Resource/ResourceCache.h>
  40. #include <Urho3D/Scene/Scene.h>
  41. #include <Urho3D/UI/Font.h>
  42. #include <Urho3D/UI/Text.h>
  43. #include <Urho3D/UI/UI.h>
  44. #include "Water.h"
  45. #include <Urho3D/DebugNew.h>
  46. URHO3D_DEFINE_APPLICATION_MAIN(Water)
  47. Water::Water(Context* context) :
  48. Sample(context)
  49. {
  50. }
  51. void Water::Start()
  52. {
  53. // Execute base class startup
  54. Sample::Start();
  55. // Create the scene content
  56. CreateScene();
  57. // Create the UI content
  58. CreateInstructions();
  59. // Setup the viewport for displaying the scene
  60. SetupViewport();
  61. // Hook up to the frame update event
  62. SubscribeToEvents();
  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. ResourceCache* cache = GetSubsystem<ResourceCache>();
  145. UI* ui = GetSubsystem<UI>();
  146. // Construct new Text object, set string to display and font to use
  147. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  148. instructionText->SetText("Use WASD keys and mouse/touch to move");
  149. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  150. instructionText->SetTextAlignment(HA_CENTER);
  151. // Position the text relative to the screen center
  152. instructionText->SetHorizontalAlignment(HA_CENTER);
  153. instructionText->SetVerticalAlignment(VA_CENTER);
  154. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  155. }
  156. void Water::SetupViewport()
  157. {
  158. Graphics* graphics = GetSubsystem<Graphics>();
  159. Renderer* renderer = GetSubsystem<Renderer>();
  160. ResourceCache* cache = GetSubsystem<ResourceCache>();
  161. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  162. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  163. renderer->SetViewport(0, viewport);
  164. // Create a mathematical plane to represent the water in calculations
  165. waterPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition());
  166. // Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
  167. waterClipPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition() -
  168. Vector3(0.0f, 0.1f, 0.0f));
  169. // Create camera for water reflection
  170. // It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
  171. // its position when rendering
  172. reflectionCameraNode_ = cameraNode_->CreateChild();
  173. Camera* reflectionCamera = reflectionCameraNode_->CreateComponent<Camera>();
  174. reflectionCamera->SetFarClip(750.0);
  175. reflectionCamera->SetViewMask(0x7fffffff); // Hide objects with only bit 31 in the viewmask (the water plane)
  176. reflectionCamera->SetAutoAspectRatio(false);
  177. reflectionCamera->SetUseReflection(true);
  178. reflectionCamera->SetReflectionPlane(waterPlane_);
  179. reflectionCamera->SetUseClipping(true); // Enable clipping of geometry behind water plane
  180. reflectionCamera->SetClipPlane(waterClipPlane_);
  181. // The water reflection texture is rectangular. Set reflection camera aspect ratio to match
  182. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  183. // View override flags could be used to optimize reflection rendering. For example disable shadows
  184. //reflectionCamera->SetViewOverrideFlags(VO_DISABLE_SHADOWS);
  185. // Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
  186. // texture unit of the water material
  187. int texSize = 1024;
  188. SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
  189. renderTexture->SetSize(texSize, texSize, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
  190. renderTexture->SetFilterMode(FILTER_BILINEAR);
  191. RenderSurface* surface = renderTexture->GetRenderSurface();
  192. SharedPtr<Viewport> rttViewport(new Viewport(context_, scene_, reflectionCamera));
  193. surface->SetViewport(0, rttViewport);
  194. Material* waterMat = cache->GetResource<Material>("Materials/Water.xml");
  195. waterMat->SetTexture(TU_DIFFUSE, renderTexture);
  196. }
  197. void Water::SubscribeToEvents()
  198. {
  199. // Subscribe HandleUpdate() function for processing update events
  200. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Water, HandleUpdate));
  201. }
  202. void Water::MoveCamera(float timeStep)
  203. {
  204. // Do not move if the UI has a focused element (the console)
  205. if (GetSubsystem<UI>()->GetFocusElement())
  206. return;
  207. Input* input = GetSubsystem<Input>();
  208. // Movement speed as world units per second
  209. const float MOVE_SPEED = 20.0f;
  210. // Mouse sensitivity as degrees per pixel
  211. const float MOUSE_SENSITIVITY = 0.1f;
  212. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  213. IntVector2 mouseMove = input->GetMouseMove();
  214. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  215. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  216. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  217. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  218. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  219. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  220. if (input->GetKeyDown('W'))
  221. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  222. if (input->GetKeyDown('S'))
  223. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  224. if (input->GetKeyDown('A'))
  225. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  226. if (input->GetKeyDown('D'))
  227. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  228. // In case resolution has changed, adjust the reflection camera aspect ratio
  229. Graphics* graphics = GetSubsystem<Graphics>();
  230. Camera* reflectionCamera = reflectionCameraNode_->GetComponent<Camera>();
  231. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  232. }
  233. void Water::HandleUpdate(StringHash eventType, VariantMap& eventData)
  234. {
  235. using namespace Update;
  236. // Take the frame time step, which is stored as a float
  237. float timeStep = eventData[P_TIMESTEP].GetFloat();
  238. // Move the camera, scale movement with time step
  239. MoveCamera(timeStep);
  240. }