HugeObjectCount.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. //
  2. // Copyright (c) 2008-2021 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/Core/Profiler.h>
  24. #include <Urho3D/Engine/Engine.h>
  25. #include <Urho3D/Graphics/Camera.h>
  26. #include <Urho3D/Graphics/Graphics.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/StaticModelGroup.h>
  32. #include <Urho3D/Graphics/Zone.h>
  33. #include <Urho3D/Input/Input.h>
  34. #include <Urho3D/Resource/ResourceCache.h>
  35. #include <Urho3D/Scene/Scene.h>
  36. #include <Urho3D/UI/Font.h>
  37. #include <Urho3D/UI/Text.h>
  38. #include <Urho3D/UI/UI.h>
  39. #include "HugeObjectCount.h"
  40. #include <Urho3D/DebugNew.h>
  41. URHO3D_DEFINE_APPLICATION_MAIN(HugeObjectCount)
  42. HugeObjectCount::HugeObjectCount(Context* context) :
  43. Sample(context),
  44. animate_(false),
  45. useGroups_(false)
  46. {
  47. }
  48. void HugeObjectCount::Start()
  49. {
  50. // Execute base class startup
  51. Sample::Start();
  52. // Create the scene content
  53. CreateScene();
  54. // Create the UI content
  55. CreateInstructions();
  56. // Setup the viewport for displaying the scene
  57. SetupViewport();
  58. // Hook up to the frame update events
  59. SubscribeToEvents();
  60. // Set the mouse mode to use in the sample
  61. Sample::InitMouseMode(MM_RELATIVE);
  62. }
  63. void HugeObjectCount::CreateScene()
  64. {
  65. auto* cache = GetSubsystem<ResourceCache>();
  66. if (!scene_)
  67. scene_ = new Scene(context_);
  68. else
  69. {
  70. scene_->Clear();
  71. boxNodes_.Clear();
  72. }
  73. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  74. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  75. scene_->CreateComponent<Octree>();
  76. // Create a Zone for ambient light & fog control
  77. Node* zoneNode = scene_->CreateChild("Zone");
  78. auto* zone = zoneNode->CreateComponent<Zone>();
  79. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  80. zone->SetFogColor(Color(0.2f, 0.2f, 0.2f));
  81. zone->SetFogStart(200.0f);
  82. zone->SetFogEnd(300.0f);
  83. // Create a directional light
  84. Node* lightNode = scene_->CreateChild("DirectionalLight");
  85. lightNode->SetDirection(Vector3(-0.6f, -1.0f, -0.8f)); // The direction vector does not need to be normalized
  86. auto* light = lightNode->CreateComponent<Light>();
  87. light->SetLightType(LIGHT_DIRECTIONAL);
  88. if (!useGroups_)
  89. {
  90. light->SetColor(Color(0.7f, 0.35f, 0.0f));
  91. // Create individual box StaticModels in the scene
  92. for (int y = -125; y < 125; ++y)
  93. {
  94. for (int x = -125; x < 125; ++x)
  95. {
  96. Node* boxNode = scene_->CreateChild("Box");
  97. boxNode->SetPosition(Vector3(x * 0.3f, 0.0f, y * 0.3f));
  98. boxNode->SetScale(0.25f);
  99. auto* boxObject = boxNode->CreateComponent<StaticModel>();
  100. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  101. boxNodes_.Push(SharedPtr<Node>(boxNode));
  102. }
  103. }
  104. }
  105. else
  106. {
  107. light->SetColor(Color(0.6f, 0.6f, 0.6f));
  108. light->SetSpecularIntensity(1.5f);
  109. // Create StaticModelGroups in the scene
  110. StaticModelGroup* lastGroup = nullptr;
  111. for (int y = -125; y < 125; ++y)
  112. {
  113. for (int x = -125; x < 125; ++x)
  114. {
  115. // Create new group if no group yet, or the group has already "enough" objects. The tradeoff is between culling
  116. // accuracy and the amount of CPU processing needed for all the objects. Note that the group's own transform
  117. // does not matter, and it does not render anything if instance nodes are not added to it
  118. if (!lastGroup || lastGroup->GetNumInstanceNodes() >= 25 * 25)
  119. {
  120. Node* boxGroupNode = scene_->CreateChild("BoxGroup");
  121. lastGroup = boxGroupNode->CreateComponent<StaticModelGroup>();
  122. lastGroup->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  123. }
  124. Node* boxNode = scene_->CreateChild("Box");
  125. boxNode->SetPosition(Vector3(x * 0.3f, 0.0f, y * 0.3f));
  126. boxNode->SetScale(0.25f);
  127. boxNodes_.Push(SharedPtr<Node>(boxNode));
  128. lastGroup->AddInstanceNode(boxNode);
  129. }
  130. }
  131. }
  132. // Create the camera. Create it outside the scene so that we can clear the whole scene without affecting it
  133. if (!cameraNode_)
  134. {
  135. cameraNode_ = new Node(context_);
  136. cameraNode_->SetPosition(Vector3(0.0f, 10.0f, -100.0f));
  137. auto* camera = cameraNode_->CreateComponent<Camera>();
  138. camera->SetFarClip(300.0f);
  139. }
  140. }
  141. void HugeObjectCount::CreateInstructions()
  142. {
  143. auto* cache = GetSubsystem<ResourceCache>();
  144. auto* ui = GetSubsystem<UI>();
  145. // Construct new Text object, set string to display and font to use
  146. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  147. instructionText->SetText(
  148. "Use WASD keys and mouse/touch to move\n"
  149. "Space to toggle animation\n"
  150. "G to toggle object group optimization"
  151. );
  152. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  153. // The text has multiple rows. Center them in relation to each other
  154. instructionText->SetTextAlignment(HA_CENTER);
  155. // Position the text relative to the screen center
  156. instructionText->SetHorizontalAlignment(HA_CENTER);
  157. instructionText->SetVerticalAlignment(VA_CENTER);
  158. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  159. }
  160. void HugeObjectCount::SetupViewport()
  161. {
  162. auto* renderer = GetSubsystem<Renderer>();
  163. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  164. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  165. renderer->SetViewport(0, viewport);
  166. }
  167. void HugeObjectCount::SubscribeToEvents()
  168. {
  169. // Subscribe HandleUpdate() function for processing update events
  170. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HugeObjectCount, HandleUpdate));
  171. }
  172. void HugeObjectCount::MoveCamera(float timeStep)
  173. {
  174. // Do not move if the UI has a focused element (the console)
  175. if (GetSubsystem<UI>()->GetFocusElement())
  176. return;
  177. auto* input = GetSubsystem<Input>();
  178. // Movement speed as world units per second
  179. const float MOVE_SPEED = 20.0f;
  180. // Mouse sensitivity as degrees per pixel
  181. const float MOUSE_SENSITIVITY = 0.1f;
  182. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  183. IntVector2 mouseMove = input->GetMouseMove();
  184. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  185. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  186. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  187. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  188. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  189. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  190. if (input->GetKeyDown(KEY_W))
  191. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  192. if (input->GetKeyDown(KEY_S))
  193. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  194. if (input->GetKeyDown(KEY_A))
  195. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  196. if (input->GetKeyDown(KEY_D))
  197. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  198. }
  199. void HugeObjectCount::AnimateObjects(float timeStep)
  200. {
  201. URHO3D_PROFILE(AnimateObjects);
  202. const float ROTATE_SPEED = 15.0f;
  203. // Rotate about the Z axis (roll)
  204. Quaternion rotateQuat(ROTATE_SPEED * timeStep, Vector3::FORWARD);
  205. for (unsigned i = 0; i < boxNodes_.Size(); ++i)
  206. boxNodes_[i]->Rotate(rotateQuat);
  207. }
  208. void HugeObjectCount::HandleUpdate(StringHash eventType, VariantMap& eventData)
  209. {
  210. using namespace Update;
  211. // Take the frame time step, which is stored as a float
  212. float timeStep = eventData[P_TIMESTEP].GetFloat();
  213. // Toggle animation with space
  214. auto* input = GetSubsystem<Input>();
  215. if (input->GetKeyPress(KEY_SPACE))
  216. animate_ = !animate_;
  217. // Toggle grouped / ungrouped mode
  218. if (input->GetKeyPress(KEY_G))
  219. {
  220. useGroups_ = !useGroups_;
  221. CreateScene();
  222. }
  223. // Move the camera, scale movement with time step
  224. MoveCamera(timeStep);
  225. // Animate scene if enabled
  226. if (animate_)
  227. AnimateObjects(timeStep);
  228. }