Water.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // Copyright (c) 2008-2013 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 "Camera.h"
  23. #include "CoreEvents.h"
  24. #include "Engine.h"
  25. #include "File.h"
  26. #include "FileSystem.h"
  27. #include "Font.h"
  28. #include "Graphics.h"
  29. #include "Input.h"
  30. #include "Light.h"
  31. #include "Material.h"
  32. #include "Model.h"
  33. #include "Octree.h"
  34. #include "Renderer.h"
  35. #include "RenderSurface.h"
  36. #include "ResourceCache.h"
  37. #include "Scene.h"
  38. #include "Skybox.h"
  39. #include "StaticModel.h"
  40. #include "Terrain.h"
  41. #include "Text.h"
  42. #include "Texture2D.h"
  43. #include "UI.h"
  44. #include "Zone.h"
  45. #include "Water.h"
  46. #include "DebugNew.h"
  47. DEFINE_APPLICATION_MAIN(Water)
  48. Water::Water(Context* context) :
  49. Sample(context),
  50. yaw_(0.0f),
  51. pitch_(0.0f)
  52. {
  53. }
  54. void Water::Start()
  55. {
  56. // Execute base class startup
  57. Sample::Start();
  58. // Create the scene content
  59. CreateScene();
  60. // Create the UI content
  61. CreateInstructions();
  62. // Setup the viewport for displaying the scene
  63. SetupViewport();
  64. // Hook up to the frame update event
  65. SubscribeToEvents();
  66. }
  67. void Water::CreateScene()
  68. {
  69. ResourceCache* cache = GetSubsystem<ResourceCache>();
  70. scene_ = new Scene(context_);
  71. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  72. scene_->CreateComponent<Octree>();
  73. // Create a Zone component for ambient lighting & fog control
  74. Node* zoneNode = scene_->CreateChild("Zone");
  75. Zone* zone = zoneNode->CreateComponent<Zone>();
  76. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  77. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  78. zone->SetFogColor(Color(1.0f, 1.0f, 1.0f));
  79. zone->SetFogStart(500.0f);
  80. zone->SetFogEnd(750.0f);
  81. // Create a directional light to the world. Enable cascaded shadows on it
  82. Node* lightNode = scene_->CreateChild("DirectionalLight");
  83. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  84. Light* light = lightNode->CreateComponent<Light>();
  85. light->SetLightType(LIGHT_DIRECTIONAL);
  86. light->SetCastShadows(true);
  87. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  88. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  89. light->SetSpecularIntensity(0.5f);
  90. // Apply slightly overbright lighting to match the skybox
  91. light->SetColor(Color(1.2f, 1.2f, 1.2f));
  92. // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  93. // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  94. // generate the necessary 3D texture coordinates for cube mapping
  95. Node* skyNode = scene_->CreateChild("Sky");
  96. skyNode->SetScale(500.0f); // The scale actually does not matter
  97. Skybox* skybox = skyNode->CreateComponent<Skybox>();
  98. skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  99. skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
  100. // Create heightmap terrain
  101. Node* terrainNode = scene_->CreateChild("Terrain");
  102. terrainNode->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
  103. Terrain* terrain = terrainNode->CreateComponent<Terrain>();
  104. terrain->SetPatchSize(64);
  105. terrain->SetSpacing(Vector3(2.0f, 0.5f, 2.0f)); // Spacing between vertices and vertical resolution of the height map
  106. terrain->SetSmoothing(true);
  107. terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
  108. terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
  109. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  110. // terrain patches and other objects behind it
  111. terrain->SetOccluder(true);
  112. // Create 1000 boxes in the terrain. Always face outward along the terrain normal
  113. unsigned NUM_OBJECTS = 1000;
  114. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  115. {
  116. Node* objectNode = scene_->CreateChild("Box");
  117. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  118. position.y_ = terrain->GetHeight(position) + 2.25f;
  119. objectNode->SetPosition(position);
  120. // Create a rotation quaternion from up vector to terrain normal
  121. objectNode->SetRotation(Quaternion(Vector3(0.0f, 1.0f, 0.0f), terrain->GetNormal(position)));
  122. objectNode->SetScale(5.0f);
  123. StaticModel* object = objectNode->CreateComponent<StaticModel>();
  124. object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  125. object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  126. object->SetCastShadows(true);
  127. }
  128. // Create a water plane object that is as large as the terrain
  129. waterNode_ = scene_->CreateChild("Water");
  130. waterNode_->SetScale(Vector3(2048.0f, 1.0f, 2048.0f));
  131. waterNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  132. StaticModel* water = waterNode_->CreateComponent<StaticModel>();
  133. water->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  134. water->SetMaterial(cache->GetResource<Material>("Materials/Water.xml"));
  135. // Set a different viewmask on the water plane to be able to hide it from the reflection camera
  136. water->SetViewMask(0x80000000);
  137. // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  138. // the scene, because we want it to be unaffected by scene load / save
  139. cameraNode_ = new Node(context_);
  140. Camera* camera = cameraNode_->CreateComponent<Camera>();
  141. camera->SetFarClip(750.0f);
  142. // Set an initial position for the camera scene node above the ground
  143. cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -20.0f));
  144. }
  145. void Water::CreateInstructions()
  146. {
  147. ResourceCache* cache = GetSubsystem<ResourceCache>();
  148. UI* ui = GetSubsystem<UI>();
  149. // Construct new Text object, set string to display and font to use
  150. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  151. instructionText->SetText("Use WASD keys and mouse to move");
  152. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  153. instructionText->SetTextAlignment(HA_CENTER);
  154. // Position the text relative to the screen center
  155. instructionText->SetHorizontalAlignment(HA_CENTER);
  156. instructionText->SetVerticalAlignment(VA_CENTER);
  157. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  158. }
  159. void Water::SetupViewport()
  160. {
  161. Graphics* graphics = GetSubsystem<Graphics>();
  162. Renderer* renderer = GetSubsystem<Renderer>();
  163. ResourceCache* cache = GetSubsystem<ResourceCache>();
  164. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  165. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  166. renderer->SetViewport(0, viewport);
  167. // Create a mathematical plane to represent the water in calculations
  168. waterPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition());
  169. // Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
  170. waterClipPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition() -
  171. Vector3(0.0f, 0.1f, 0.0f));
  172. // Create camera for water reflection
  173. // It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
  174. // its position when rendering
  175. reflectionCameraNode_ = cameraNode_->CreateChild();
  176. Camera* reflectionCamera = reflectionCameraNode_->CreateComponent<Camera>();
  177. reflectionCamera->SetFarClip(750.0);
  178. reflectionCamera->SetViewMask(0x7fffffff); // Hide objects with only bit 31 in the viewmask (the water plane)
  179. reflectionCamera->SetAutoAspectRatio(false);
  180. reflectionCamera->SetUseReflection(true);
  181. reflectionCamera->SetReflectionPlane(waterPlane_);
  182. reflectionCamera->SetUseClipping(true); // Enable clipping of geometry behind water plane
  183. reflectionCamera->SetClipPlane(waterClipPlane_);
  184. // The water reflection texture is rectangular. Set reflection camera aspect ratio to match
  185. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  186. // View override flags could be used to optimize reflection rendering. For example disable shadows
  187. //reflectionCamera->SetViewOverrideFlags(VO_DISABLE_SHADOWS);
  188. // Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
  189. // texture unit of the water material
  190. int texSize = 1024;
  191. SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
  192. renderTexture->SetSize(texSize, texSize, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
  193. renderTexture->SetFilterMode(FILTER_BILINEAR);
  194. RenderSurface* surface = renderTexture->GetRenderSurface();
  195. SharedPtr<Viewport> rttViewport(new Viewport(context_, scene_, reflectionCamera));
  196. surface->SetViewport(0, rttViewport);
  197. Material* waterMat = cache->GetResource<Material>("Materials/Water.xml");
  198. waterMat->SetTexture(TU_DIFFUSE, renderTexture);
  199. }
  200. void Water::SubscribeToEvents()
  201. {
  202. // Subscribe HandleUpdate() function for processing update events
  203. SubscribeToEvent(E_UPDATE, HANDLER(Water, HandleUpdate));
  204. }
  205. void Water::MoveCamera(float timeStep)
  206. {
  207. // Do not move if the UI has a focused element (the console)
  208. if (GetSubsystem<UI>()->GetFocusElement())
  209. return;
  210. Input* input = GetSubsystem<Input>();
  211. // Movement speed as world units per second
  212. const float MOVE_SPEED = 20.0f;
  213. // Mouse sensitivity as degrees per pixel
  214. const float MOUSE_SENSITIVITY = 0.1f;
  215. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  216. IntVector2 mouseMove = input->GetMouseMove();
  217. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  218. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  219. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  220. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  221. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  222. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  223. if (input->GetKeyDown('W'))
  224. cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
  225. if (input->GetKeyDown('S'))
  226. cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
  227. if (input->GetKeyDown('A'))
  228. cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
  229. if (input->GetKeyDown('D'))
  230. cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
  231. // In case resolution has changed, adjust the reflection camera aspect ratio
  232. Graphics* graphics = GetSubsystem<Graphics>();
  233. Camera* reflectionCamera = reflectionCameraNode_->GetComponent<Camera>();
  234. reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
  235. }
  236. void Water::HandleUpdate(StringHash eventType, VariantMap& eventData)
  237. {
  238. using namespace Update;
  239. // Take the frame time step, which is stored as a float
  240. float timeStep = eventData[P_TIMESTEP].GetFloat();
  241. // Move the camera, scale movement with time step
  242. MoveCamera(timeStep);
  243. }