Billboards.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include <Atomic/Core/CoreEvents.h>
  24. #include <Atomic/Engine/Engine.h>
  25. #include <Atomic/Graphics/BillboardSet.h>
  26. #include <Atomic/Graphics/Camera.h>
  27. #include <Atomic/Graphics/DebugRenderer.h>
  28. #include <Atomic/Graphics/Graphics.h>
  29. #include <Atomic/Graphics/Light.h>
  30. #include <Atomic/Graphics/Material.h>
  31. #include <Atomic/Graphics/Model.h>
  32. #include <Atomic/Graphics/Octree.h>
  33. #include <Atomic/Graphics/Renderer.h>
  34. #include <Atomic/Graphics/Texture2D.h>
  35. #include <Atomic/Graphics/StaticModel.h>
  36. #include <Atomic/Graphics/Zone.h>
  37. #include <Atomic/Input/Input.h>
  38. #include <Atomic/Resource/ResourceCache.h>
  39. #include <Atomic/Scene/Scene.h>
  40. #include <Atomic/UI/UI.h>
  41. #include "Billboards.h"
  42. #include <Atomic/DebugNew.h>
  43. Billboards::Billboards(Context* context) :
  44. Sample(context),
  45. drawDebug_(false)
  46. {
  47. }
  48. void Billboards::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 and render post-update events
  59. SubscribeToEvents();
  60. // Set the mouse mode to use in the sample
  61. Sample::InitMouseMode(MM_ABSOLUTE);
  62. }
  63. void Billboards::CreateScene()
  64. {
  65. ResourceCache* cache = GetSubsystem<ResourceCache>();
  66. scene_ = new Scene(context_);
  67. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  68. // Also create a DebugRenderer component so that we can draw debug geometry
  69. scene_->CreateComponent<Octree>();
  70. scene_->CreateComponent<DebugRenderer>();
  71. // Create a Zone component for ambient lighting & fog control
  72. Node* zoneNode = scene_->CreateChild("Zone");
  73. Zone* zone = zoneNode->CreateComponent<Zone>();
  74. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  75. zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
  76. zone->SetFogStart(100.0f);
  77. zone->SetFogEnd(300.0f);
  78. // Create a directional light without shadows
  79. Node* lightNode = scene_->CreateChild("DirectionalLight");
  80. lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
  81. Light* light = lightNode->CreateComponent<Light>();
  82. light->SetLightType(LIGHT_DIRECTIONAL);
  83. light->SetColor(Color(0.2f, 0.2f, 0.2f));
  84. light->SetSpecularIntensity(1.0f);
  85. // Create a "floor" consisting of several tiles
  86. for (int y = -5; y <= 5; ++y)
  87. {
  88. for (int x = -5; x <= 5; ++x)
  89. {
  90. Node* floorNode = scene_->CreateChild("FloorTile");
  91. floorNode->SetPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
  92. floorNode->SetScale(Vector3(20.0f, 1.0f, 20.f));
  93. StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
  94. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  95. floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  96. }
  97. }
  98. // Create groups of mushrooms, which act as shadow casters
  99. const unsigned NUM_MUSHROOMGROUPS = 25;
  100. const unsigned NUM_MUSHROOMS = 25;
  101. for (unsigned i = 0; i < NUM_MUSHROOMGROUPS; ++i)
  102. {
  103. // First create a scene node for the group. The individual mushrooms nodes will be created as children
  104. Node* groupNode = scene_->CreateChild("MushroomGroup");
  105. groupNode->SetPosition(Vector3(Random(190.0f) - 95.0f, 0.0f, Random(190.0f) - 95.0f));
  106. for (unsigned j = 0; j < NUM_MUSHROOMS; ++j)
  107. {
  108. Node* mushroomNode = groupNode->CreateChild("Mushroom");
  109. mushroomNode->SetPosition(Vector3(Random(25.0f) - 12.5f, 0.0f, Random(25.0f) - 12.5f));
  110. mushroomNode->SetRotation(Quaternion(0.0f, Random() * 360.0f, 0.0f));
  111. mushroomNode->SetScale(1.0f + Random() * 4.0f);
  112. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  113. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  114. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  115. mushroomObject->SetCastShadows(true);
  116. }
  117. }
  118. // Create billboard sets (floating smoke)
  119. const unsigned NUM_BILLBOARDNODES = 25;
  120. const unsigned NUM_BILLBOARDS = 10;
  121. for (unsigned i = 0; i < NUM_BILLBOARDNODES; ++i)
  122. {
  123. Node* smokeNode = scene_->CreateChild("Smoke");
  124. smokeNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(20.0f) + 10.0f, Random(200.0f) - 100.0f));
  125. BillboardSet* billboardObject = smokeNode->CreateComponent<BillboardSet>();
  126. billboardObject->SetNumBillboards(NUM_BILLBOARDS);
  127. billboardObject->SetMaterial(cache->GetResource<Material>("Materials/LitSmoke.xml"));
  128. billboardObject->SetSorted(true);
  129. for (unsigned j = 0; j < NUM_BILLBOARDS; ++j)
  130. {
  131. Billboard* bb = billboardObject->GetBillboard(j);
  132. bb->position_ = Vector3(Random(12.0f) - 6.0f, Random(8.0f) - 4.0f, Random(12.0f) - 6.0f);
  133. bb->size_ = Vector2(Random(2.0f) + 3.0f, Random(2.0f) + 3.0f);
  134. bb->rotation_ = Random() * 360.0f;
  135. bb->enabled_ = true;
  136. }
  137. // After modifying the billboards, they need to be "commited" so that the BillboardSet updates its internals
  138. billboardObject->Commit();
  139. }
  140. // Create shadow casting spotlights
  141. const unsigned NUM_LIGHTS = 9;
  142. for (unsigned i = 0; i < NUM_LIGHTS; ++i)
  143. {
  144. Node* lightNode = scene_->CreateChild("SpotLight");
  145. Light* light = lightNode->CreateComponent<Light>();
  146. float angle = 0.0f;
  147. Vector3 position((i % 3) * 60.0f - 60.0f, 45.0f, (i / 3) * 60.0f - 60.0f);
  148. 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);
  149. lightNode->SetPosition(position);
  150. lightNode->SetDirection(Vector3(Sin(angle), -1.5f, Cos(angle)));
  151. light->SetLightType(LIGHT_SPOT);
  152. light->SetRange(90.0f);
  153. light->SetRampTexture(cache->GetResource<Texture2D>("Textures/RampExtreme.png"));
  154. light->SetFov(45.0f);
  155. light->SetColor(color);
  156. light->SetSpecularIntensity(1.0f);
  157. light->SetCastShadows(true);
  158. light->SetShadowBias(BiasParameters(0.00002f, 0.0f));
  159. // Configure shadow fading for the lights. When they are far away enough, the lights eventually become unshadowed for
  160. // better GPU performance. Note that we could also set the maximum distance for each object to cast shadows
  161. light->SetShadowFadeDistance(100.0f); // Fade start distance
  162. light->SetShadowDistance(125.0f); // Fade end distance, shadows are disabled
  163. // Set half resolution for the shadow maps for increased performance
  164. light->SetShadowResolution(0.5f);
  165. // The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  166. // for better shadow depth resolution
  167. light->SetShadowNearFarRatio(0.01f);
  168. }
  169. // Create the camera. Limit far clip distance to match the fog
  170. cameraNode_ = scene_->CreateChild("Camera");
  171. Camera* camera = cameraNode_->CreateComponent<Camera>();
  172. camera->SetFarClip(300.0f);
  173. // Set an initial position for the camera scene node above the plane
  174. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  175. }
  176. void Billboards::CreateInstructions()
  177. {
  178. SimpleCreateInstructions (
  179. "Use WASD keys and mouse/touch to move\n"
  180. "Space to toggle debug geometry"
  181. );
  182. }
  183. void Billboards::SetupViewport()
  184. {
  185. Renderer* renderer = GetSubsystem<Renderer>();
  186. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  187. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  188. renderer->SetViewport(0, viewport);
  189. }
  190. void Billboards::SubscribeToEvents()
  191. {
  192. // Subscribe HandleUpdate() function for processing update events
  193. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(Billboards, HandleUpdate));
  194. // Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  195. // debug geometry
  196. SubscribeToEvent(E_POSTRENDERUPDATE, ATOMIC_HANDLER(Billboards, HandlePostRenderUpdate));
  197. }
  198. void Billboards::MoveCamera(float timeStep)
  199. {
  200. Input* input = GetSubsystem<Input>();
  201. // Movement speed as world units per second
  202. const float MOVE_SPEED = 20.0f;
  203. // Mouse sensitivity as degrees per pixel
  204. const float MOUSE_SENSITIVITY = 0.1f;
  205. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  206. IntVector2 mouseMove = input->GetMouseMove();
  207. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  208. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  209. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  210. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  211. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  212. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  213. if (input->GetKeyDown(KEY_W))
  214. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  215. if (input->GetKeyDown(KEY_S))
  216. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  217. if (input->GetKeyDown(KEY_A))
  218. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  219. if (input->GetKeyDown(KEY_D))
  220. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  221. // Toggle debug geometry with space
  222. if (input->GetKeyPress(KEY_SPACE))
  223. drawDebug_ = !drawDebug_;
  224. }
  225. void Billboards::AnimateScene(float timeStep)
  226. {
  227. // Get the light and billboard scene nodes
  228. PODVector<Node*> lightNodes;
  229. PODVector<Node*> billboardNodes;
  230. scene_->GetChildrenWithComponent<Light>(lightNodes);
  231. scene_->GetChildrenWithComponent<BillboardSet>(billboardNodes);
  232. const float LIGHT_ROTATION_SPEED = 20.0f;
  233. const float BILLBOARD_ROTATION_SPEED = 50.0f;
  234. // Rotate the lights around the world Y-axis
  235. for (unsigned i = 0; i < lightNodes.Size(); ++i)
  236. lightNodes[i]->Rotate(Quaternion(0.0f, LIGHT_ROTATION_SPEED * timeStep, 0.0f), TS_WORLD);
  237. // Rotate the individual billboards within the billboard sets, then recommit to make the changes visible
  238. for (unsigned i = 0; i < billboardNodes.Size(); ++i)
  239. {
  240. BillboardSet* billboardObject = billboardNodes[i]->GetComponent<BillboardSet>();
  241. for (unsigned j = 0; j < billboardObject->GetNumBillboards(); ++j)
  242. {
  243. Billboard* bb = billboardObject->GetBillboard(j);
  244. bb->rotation_ += BILLBOARD_ROTATION_SPEED * timeStep;
  245. }
  246. billboardObject->Commit();
  247. }
  248. }
  249. void Billboards::HandleUpdate(StringHash eventType, VariantMap& eventData)
  250. {
  251. using namespace Update;
  252. // Take the frame time step, which is stored as a float
  253. float timeStep = eventData[P_TIMESTEP].GetFloat();
  254. // Move the camera and animate the scene, scale movement with time step
  255. MoveCamera(timeStep);
  256. AnimateScene(timeStep);
  257. }
  258. void Billboards::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  259. {
  260. // If draw debug mode is enabled, draw viewport debug geometry. This time use depth test, as otherwise the result becomes
  261. // hard to interpret due to large object count
  262. if (drawDebug_)
  263. GetSubsystem<Renderer>()->DrawDebugGeometry(true);
  264. }