Billboards.cpp 13 KB

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