MultipleViewports.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. //
  2. // Copyright (c) 2008-2015 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/DebugRenderer.h>
  26. #include <Urho3D/Graphics/Graphics.h>
  27. #include <Urho3D/Graphics/Light.h>
  28. #include <Urho3D/Graphics/Material.h>
  29. #include <Urho3D/Graphics/Model.h>
  30. #include <Urho3D/Graphics/Octree.h>
  31. #include <Urho3D/Graphics/Renderer.h>
  32. #include <Urho3D/Graphics/RenderPath.h>
  33. #include <Urho3D/Graphics/StaticModel.h>
  34. #include <Urho3D/Graphics/Zone.h>
  35. #include <Urho3D/Input/Input.h>
  36. #include <Urho3D/Resource/ResourceCache.h>
  37. #include <Urho3D/Scene/Scene.h>
  38. #include <Urho3D/UI/Font.h>
  39. #include <Urho3D/UI/Text.h>
  40. #include <Urho3D/UI/UI.h>
  41. #include "MultipleViewports.h"
  42. #include <Urho3D/DebugNew.h>
  43. DEFINE_APPLICATION_MAIN(MultipleViewports)
  44. MultipleViewports::MultipleViewports(Context* context) :
  45. Sample(context),
  46. drawDebug_(false)
  47. {
  48. }
  49. void MultipleViewports::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 viewports for displaying the scene
  58. SetupViewports();
  59. // Hook up to the frame update and render post-update events
  60. SubscribeToEvents();
  61. }
  62. void MultipleViewports::CreateScene()
  63. {
  64. ResourceCache* cache = GetSubsystem<ResourceCache>();
  65. scene_ = new Scene(context_);
  66. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  67. // Also create a DebugRenderer component so that we can draw debug geometry
  68. scene_->CreateComponent<Octree>();
  69. scene_->CreateComponent<DebugRenderer>();
  70. // Create scene node & StaticModel component for showing a static plane
  71. Node* planeNode = scene_->CreateChild("Plane");
  72. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  73. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  74. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  75. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  76. // Create a Zone component for ambient lighting & fog control
  77. Node* zoneNode = scene_->CreateChild("Zone");
  78. Zone* zone = zoneNode->CreateComponent<Zone>();
  79. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  80. zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));
  81. zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
  82. zone->SetFogStart(100.0f);
  83. zone->SetFogEnd(300.0f);
  84. // Create a directional light to the world. Enable cascaded shadows on it
  85. Node* lightNode = scene_->CreateChild("DirectionalLight");
  86. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));
  87. Light* light = lightNode->CreateComponent<Light>();
  88. light->SetLightType(LIGHT_DIRECTIONAL);
  89. light->SetCastShadows(true);
  90. light->SetShadowBias(BiasParameters(0.00025f, 0.5f));
  91. // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  92. light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));
  93. // Create some mushrooms
  94. const unsigned NUM_MUSHROOMS = 240;
  95. for (unsigned i = 0; i < NUM_MUSHROOMS; ++i)
  96. {
  97. Node* mushroomNode = scene_->CreateChild("Mushroom");
  98. mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  99. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  100. mushroomNode->SetScale(0.5f + Random(2.0f));
  101. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  102. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  103. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  104. mushroomObject->SetCastShadows(true);
  105. }
  106. // Create randomly sized boxes. If boxes are big enough, make them occluders
  107. const unsigned NUM_BOXES = 20;
  108. for (unsigned i = 0; i < NUM_BOXES; ++i)
  109. {
  110. Node* boxNode = scene_->CreateChild("Box");
  111. float size = 1.0f + Random(10.0f);
  112. boxNode->SetPosition(Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f));
  113. boxNode->SetScale(size);
  114. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  115. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  116. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  117. boxObject->SetCastShadows(true);
  118. if (size >= 3.0f)
  119. boxObject->SetOccluder(true);
  120. }
  121. // Create the cameras. Limit far clip distance to match the fog
  122. cameraNode_ = scene_->CreateChild("Camera");
  123. Camera* camera = cameraNode_->CreateComponent<Camera>();
  124. camera->SetFarClip(300.0f);
  125. // Parent the rear camera node to the front camera node and turn it 180 degrees to face backward
  126. // Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles
  127. rearCameraNode_ = cameraNode_->CreateChild("RearCamera");
  128. rearCameraNode_->Rotate(Quaternion(180.0f, Vector3::UP));
  129. Camera* rearCamera = rearCameraNode_->CreateComponent<Camera>();
  130. rearCamera->SetFarClip(300.0f);
  131. // Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's
  132. // "view override flags" for this. We could also disable eg. shadows or force low material quality
  133. // if we wanted
  134. rearCamera->SetViewOverrideFlags(VO_DISABLE_OCCLUSION);
  135. // Set an initial position for the front camera scene node above the plane
  136. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  137. }
  138. void MultipleViewports::CreateInstructions()
  139. {
  140. ResourceCache* cache = GetSubsystem<ResourceCache>();
  141. UI* ui = GetSubsystem<UI>();
  142. // Construct new Text object, set string to display and font to use
  143. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  144. instructionText->SetText(
  145. "Use WASD keys and mouse/touch to move\n"
  146. "B to toggle bloom, F to toggle FXAA\n"
  147. "Space to toggle debug geometry\n"
  148. );
  149. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  150. // The text has multiple rows. Center them in relation to each other
  151. instructionText->SetTextAlignment(HA_CENTER);
  152. // Position the text relative to the screen center
  153. instructionText->SetHorizontalAlignment(HA_CENTER);
  154. instructionText->SetVerticalAlignment(VA_CENTER);
  155. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  156. }
  157. void MultipleViewports::SetupViewports()
  158. {
  159. Graphics* graphics = GetSubsystem<Graphics>();
  160. Renderer* renderer = GetSubsystem<Renderer>();
  161. renderer->SetNumViewports(2);
  162. // Set up the front camera viewport
  163. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  164. renderer->SetViewport(0, viewport);
  165. // Clone the default render path so that we do not interfere with the other viewport, then add
  166. // bloom and FXAA post process effects to the front viewport. Render path commands can be tagged
  167. // for example with the effect name to allow easy toggling on and off. We start with the effects
  168. // disabled.
  169. ResourceCache* cache = GetSubsystem<ResourceCache>();
  170. SharedPtr<RenderPath> effectRenderPath = viewport->GetRenderPath()->Clone();
  171. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/Bloom.xml"));
  172. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml"));
  173. // Make the bloom mixing parameter more pronounced
  174. effectRenderPath->SetShaderParameter("BloomMix", Vector2(0.9f, 0.6f));
  175. effectRenderPath->SetEnabled("Bloom", false);
  176. effectRenderPath->SetEnabled("FXAA2", false);
  177. viewport->SetRenderPath(effectRenderPath);
  178. // Set up the rear camera viewport on top of the front view ("rear view mirror")
  179. // The viewport index must be greater in that case, otherwise the view would be left behind
  180. SharedPtr<Viewport> rearViewport(new Viewport(context_, scene_, rearCameraNode_->GetComponent<Camera>(),
  181. IntRect(graphics->GetWidth() * 2 / 3, 32, graphics->GetWidth() - 32, graphics->GetHeight() / 3)));
  182. renderer->SetViewport(1, rearViewport);
  183. }
  184. void MultipleViewports::SubscribeToEvents()
  185. {
  186. // Subscribe HandleUpdate() method for processing update events
  187. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(MultipleViewports, HandleUpdate));
  188. // Subscribe HandlePostRenderUpdate() method for processing the post-render update event, during which we request
  189. // debug geometry
  190. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(MultipleViewports, HandlePostRenderUpdate));
  191. }
  192. void MultipleViewports::MoveCamera(float timeStep)
  193. {
  194. // Do not move if the UI has a focused element (the console)
  195. if (GetSubsystem<UI>()->GetFocusElement())
  196. return;
  197. Input* input = GetSubsystem<Input>();
  198. // Movement speed as world units per second
  199. const float MOVE_SPEED = 20.0f;
  200. // Mouse sensitivity as degrees per pixel
  201. const float MOUSE_SENSITIVITY = 0.1f;
  202. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  203. IntVector2 mouseMove = input->GetMouseMove();
  204. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  205. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  206. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  207. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  208. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  209. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  210. if (input->GetKeyDown('W'))
  211. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  212. if (input->GetKeyDown('S'))
  213. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  214. if (input->GetKeyDown('A'))
  215. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  216. if (input->GetKeyDown('D'))
  217. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  218. // Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected
  219. RenderPath* effectRenderPath = GetSubsystem<Renderer>()->GetViewport(0)->GetRenderPath();
  220. if (input->GetKeyPress('B'))
  221. effectRenderPath->ToggleEnabled("Bloom");
  222. if (input->GetKeyPress('F'))
  223. effectRenderPath->ToggleEnabled("FXAA2");
  224. // Toggle debug geometry with space
  225. if (input->GetKeyPress(KEY_SPACE))
  226. drawDebug_ = !drawDebug_;
  227. }
  228. void MultipleViewports::HandleUpdate(StringHash eventType, VariantMap& eventData)
  229. {
  230. using namespace Update;
  231. // Take the frame time step, which is stored as a float
  232. float timeStep = eventData[P_TIMESTEP].GetFloat();
  233. // Move the camera, scale movement with time step
  234. MoveCamera(timeStep);
  235. }
  236. void MultipleViewports::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  237. {
  238. // If draw debug mode is enabled, draw viewport debug geometry, which will show eg. drawable bounding boxes and skeleton
  239. // bones. Disable depth test so that we can see the effect of occlusion
  240. if (drawDebug_)
  241. GetSubsystem<Renderer>()->DrawDebugGeometry(false);
  242. }