Water.cpp 11 KB

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