Billboards.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Engine/Engine.h>
  5. #include <Urho3D/Graphics/BillboardSet.h>
  6. #include <Urho3D/Graphics/Camera.h>
  7. #include <Urho3D/Graphics/DebugRenderer.h>
  8. #include <Urho3D/Graphics/Graphics.h>
  9. #include <Urho3D/Graphics/Light.h>
  10. #include <Urho3D/Graphics/Material.h>
  11. #include <Urho3D/Graphics/Model.h>
  12. #include <Urho3D/Graphics/Octree.h>
  13. #include <Urho3D/Graphics/Renderer.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 "Billboards.h"
  23. #include <Urho3D/DebugNew.h>
  24. URHO3D_DEFINE_APPLICATION_MAIN(Billboards)
  25. Billboards::Billboards(Context* context) :
  26. Sample(context),
  27. drawDebug_(false)
  28. {
  29. }
  30. void Billboards::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 viewport for displaying the scene
  39. SetupViewport();
  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 Billboards::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 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.1f, 0.1f, 0.1f));
  58. zone->SetFogStart(100.0f);
  59. zone->SetFogEnd(300.0f);
  60. // Create a directional light without shadows
  61. Node* lightNode = scene_->CreateChild("DirectionalLight");
  62. lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
  63. auto* light = lightNode->CreateComponent<Light>();
  64. light->SetLightType(LIGHT_DIRECTIONAL);
  65. light->SetColor(Color(0.2f, 0.2f, 0.2f));
  66. light->SetSpecularIntensity(1.0f);
  67. // Create a "floor" consisting of several tiles
  68. for (int y = -5; y <= 5; ++y)
  69. {
  70. for (int x = -5; x <= 5; ++x)
  71. {
  72. Node* floorNode = scene_->CreateChild("FloorTile");
  73. floorNode->SetPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
  74. floorNode->SetScale(Vector3(20.0f, 1.0f, 20.f));
  75. auto* floorObject = floorNode->CreateComponent<StaticModel>();
  76. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  77. floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  78. }
  79. }
  80. // Create groups of mushrooms, which act as shadow casters
  81. const unsigned NUM_MUSHROOMGROUPS = 25;
  82. const unsigned NUM_MUSHROOMS = 25;
  83. for (unsigned i = 0; i < NUM_MUSHROOMGROUPS; ++i)
  84. {
  85. // First create a scene node for the group. The individual mushrooms nodes will be created as children
  86. Node* groupNode = scene_->CreateChild("MushroomGroup");
  87. groupNode->SetPosition(Vector3(Random(190.0f) - 95.0f, 0.0f, Random(190.0f) - 95.0f));
  88. for (unsigned j = 0; j < NUM_MUSHROOMS; ++j)
  89. {
  90. Node* mushroomNode = groupNode->CreateChild("Mushroom");
  91. mushroomNode->SetPosition(Vector3(Random(25.0f) - 12.5f, 0.0f, Random(25.0f) - 12.5f));
  92. mushroomNode->SetRotation(Quaternion(0.0f, Random() * 360.0f, 0.0f));
  93. mushroomNode->SetScale(1.0f + Random() * 4.0f);
  94. auto* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  95. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  96. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  97. mushroomObject->SetCastShadows(true);
  98. }
  99. }
  100. // Create billboard sets (floating smoke)
  101. const unsigned NUM_BILLBOARDNODES = 25;
  102. const unsigned NUM_BILLBOARDS = 10;
  103. for (unsigned i = 0; i < NUM_BILLBOARDNODES; ++i)
  104. {
  105. Node* smokeNode = scene_->CreateChild("Smoke");
  106. smokeNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(20.0f) + 10.0f, Random(200.0f) - 100.0f));
  107. auto* billboardObject = smokeNode->CreateComponent<BillboardSet>();
  108. billboardObject->SetNumBillboards(NUM_BILLBOARDS);
  109. billboardObject->SetMaterial(cache->GetResource<Material>("Materials/LitSmoke.xml"));
  110. billboardObject->SetSorted(true);
  111. for (unsigned j = 0; j < NUM_BILLBOARDS; ++j)
  112. {
  113. Billboard* bb = billboardObject->GetBillboard(j);
  114. bb->position_ = Vector3(Random(12.0f) - 6.0f, Random(8.0f) - 4.0f, Random(12.0f) - 6.0f);
  115. bb->size_ = Vector2(Random(2.0f) + 3.0f, Random(2.0f) + 3.0f);
  116. bb->rotation_ = Random() * 360.0f;
  117. bb->enabled_ = true;
  118. }
  119. // After modifying the billboards, they need to be "committed" so that the BillboardSet updates its internals
  120. billboardObject->Commit();
  121. }
  122. // Create shadow casting spotlights
  123. const unsigned NUM_LIGHTS = 9;
  124. for (unsigned i = 0; i < NUM_LIGHTS; ++i)
  125. {
  126. Node* lightNode = scene_->CreateChild("SpotLight");
  127. auto* light = lightNode->CreateComponent<Light>();
  128. float angle = 0.0f;
  129. Vector3 position((i % 3) * 60.0f - 60.0f, 45.0f, (i / 3.f) * 60.0f - 60.0f);
  130. Color color(((i + 1) & 1u) * 0.5f + 0.5f, (((i + 1) >> 1u) & 1u) * 0.5f + 0.5f, (((i + 1) >> 2u) & 1u) * 0.5f + 0.5f);
  131. lightNode->SetPosition(position);
  132. lightNode->SetDirection(Vector3(Sin(angle), -1.5f, Cos(angle)));
  133. light->SetLightType(LIGHT_SPOT);
  134. light->SetRange(90.0f);
  135. light->SetRampTexture(cache->GetResource<Texture2D>("Textures/RampExtreme.png"));
  136. light->SetFov(45.0f);
  137. light->SetColor(color);
  138. light->SetSpecularIntensity(1.0f);
  139. light->SetCastShadows(true);
  140. light->SetShadowBias(BiasParameters(0.00002f, 0.0f));
  141. // Configure shadow fading for the lights. When they are far away enough, the lights eventually become unshadowed for
  142. // better GPU performance. Note that we could also set the maximum distance for each object to cast shadows
  143. light->SetShadowFadeDistance(100.0f); // Fade start distance
  144. light->SetShadowDistance(125.0f); // Fade end distance, shadows are disabled
  145. // Set half resolution for the shadow maps for increased performance
  146. light->SetShadowResolution(0.5f);
  147. // The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  148. // for better shadow depth resolution
  149. light->SetShadowNearFarRatio(0.01f);
  150. }
  151. // Create the camera. Limit far clip distance to match the fog
  152. cameraNode_ = scene_->CreateChild("Camera");
  153. auto* camera = cameraNode_->CreateComponent<Camera>();
  154. camera->SetFarClip(300.0f);
  155. // Set an initial position for the camera scene node above the plane
  156. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  157. }
  158. void Billboards::CreateInstructions()
  159. {
  160. auto* cache = GetSubsystem<ResourceCache>();
  161. auto* ui = GetSubsystem<UI>();
  162. // Construct new Text object, set string to display and font to use
  163. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  164. instructionText->SetText(
  165. "Use WASD keys and mouse/touch to move\n"
  166. "Space to toggle debug geometry"
  167. );
  168. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  169. // The text has multiple rows. Center them in relation to each other
  170. instructionText->SetTextAlignment(HA_CENTER);
  171. // Position the text relative to the screen center
  172. instructionText->SetHorizontalAlignment(HA_CENTER);
  173. instructionText->SetVerticalAlignment(VA_CENTER);
  174. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  175. }
  176. void Billboards::SetupViewport()
  177. {
  178. auto* renderer = GetSubsystem<Renderer>();
  179. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  180. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  181. renderer->SetViewport(0, viewport);
  182. }
  183. void Billboards::SubscribeToEvents()
  184. {
  185. // Subscribe HandleUpdate() function for processing update events
  186. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Billboards, HandleUpdate));
  187. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  188. // debug geometry
  189. SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Billboards, HandlePostRenderUpdate));
  190. }
  191. void Billboards::MoveCamera(float timeStep)
  192. {
  193. // Do not move if the UI has a focused element (the console)
  194. if (GetSubsystem<UI>()->GetFocusElement())
  195. return;
  196. auto* input = GetSubsystem<Input>();
  197. // Movement speed as world units per second
  198. const float MOVE_SPEED = 20.0f;
  199. // Mouse sensitivity as degrees per pixel
  200. const float MOUSE_SENSITIVITY = 0.1f;
  201. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  202. IntVector2 mouseMove = input->GetMouseMove();
  203. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  204. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  205. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  206. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  207. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  208. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  209. if (input->GetKeyDown(KEY_W))
  210. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  211. if (input->GetKeyDown(KEY_S))
  212. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  213. if (input->GetKeyDown(KEY_A))
  214. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  215. if (input->GetKeyDown(KEY_D))
  216. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  217. // Toggle debug geometry with space
  218. if (input->GetKeyPress(KEY_SPACE))
  219. drawDebug_ = !drawDebug_;
  220. }
  221. void Billboards::AnimateScene(float timeStep)
  222. {
  223. // Get the light and billboard scene nodes
  224. Vector<Node*> lightNodes;
  225. Vector<Node*> billboardNodes;
  226. scene_->GetChildrenWithComponent<Light>(lightNodes);
  227. scene_->GetChildrenWithComponent<BillboardSet>(billboardNodes);
  228. const float LIGHT_ROTATION_SPEED = 20.0f;
  229. const float BILLBOARD_ROTATION_SPEED = 50.0f;
  230. // Rotate the lights around the world Y-axis
  231. for (Node* lightNode : lightNodes)
  232. lightNode->Rotate(Quaternion(0.0f, LIGHT_ROTATION_SPEED * timeStep, 0.0f), TransformSpace::World);
  233. // Rotate the individual billboards within the billboard sets, then recommit to make the changes visible
  234. for (i32 i = 0; i < billboardNodes.Size(); ++i)
  235. {
  236. BillboardSet* billboardObject = billboardNodes[i]->GetComponent<BillboardSet>();
  237. for (unsigned j = 0; j < billboardObject->GetNumBillboards(); ++j)
  238. {
  239. Billboard* bb = billboardObject->GetBillboard(j);
  240. bb->rotation_ += BILLBOARD_ROTATION_SPEED * timeStep;
  241. }
  242. billboardObject->Commit();
  243. }
  244. }
  245. void Billboards::HandleUpdate(StringHash eventType, VariantMap& eventData)
  246. {
  247. using namespace Update;
  248. // Take the frame time step, which is stored as a float
  249. float timeStep = eventData[P_TIMESTEP].GetFloat();
  250. // Move the camera and animate the scene, scale movement with time step
  251. MoveCamera(timeStep);
  252. AnimateScene(timeStep);
  253. }
  254. void Billboards::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  255. {
  256. // If draw debug mode is enabled, draw viewport debug geometry. This time use depth test, as otherwise the result becomes
  257. // hard to interpret due to large object count
  258. if (drawDebug_)
  259. GetSubsystem<Renderer>()->DrawDebugGeometry(true);
  260. }