MultipleViewports.cpp 11 KB

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