StaticScene.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. //
  2. // Copyright (c) 2008-2014 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 "AttributeAnimation.h"
  23. #include "Camera.h"
  24. #include "CoreEvents.h"
  25. #include "Engine.h"
  26. #include "Font.h"
  27. #include "Graphics.h"
  28. #include "Input.h"
  29. #include "Material.h"
  30. #include "Model.h"
  31. #include "Octree.h"
  32. #include "Renderer.h"
  33. #include "ResourceCache.h"
  34. #include "Scene.h"
  35. #include "StaticModel.h"
  36. #include "Text.h"
  37. #include "UI.h"
  38. #include "StaticScene.h"
  39. #include "DebugNew.h"
  40. DEFINE_APPLICATION_MAIN(StaticScene)
  41. StaticScene::StaticScene(Context* context) :
  42. Sample(context),
  43. yaw_(0.0f),
  44. pitch_(0.0f)
  45. {
  46. }
  47. void StaticScene::Start()
  48. {
  49. // Execute base class startup
  50. Sample::Start();
  51. // Create the scene content
  52. CreateScene();
  53. // Create the UI content
  54. CreateInstructions();
  55. // Setup the viewport for displaying the scene
  56. SetupViewport();
  57. // Hook up to the frame update events
  58. SubscribeToEvents();
  59. }
  60. void StaticScene::CreateScene()
  61. {
  62. ResourceCache* cache = GetSubsystem<ResourceCache>();
  63. scene_ = new Scene(context_);
  64. // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
  65. // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
  66. // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
  67. // optimizing manner
  68. scene_->CreateComponent<Octree>();
  69. // Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
  70. // plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
  71. // (100 x 100 world units)
  72. Node* planeNode = scene_->CreateChild("Plane");
  73. planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
  74. StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
  75. planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  76. planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));
  77. // Create a directional light to the world so that we can see something. The light scene node's orientation controls the
  78. // light direction; we will use the SetDirection() function which calculates the orientation from a forward direction vector.
  79. // The light will use default settings (white light, no shadows)
  80. Node* lightNode = scene_->CreateChild("DirectionalLight");
  81. lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f)); // The direction vector does not need to be normalized
  82. Light* light = lightNode->CreateComponent<Light>();
  83. light->SetLightType(LIGHT_DIRECTIONAL);
  84. AttributeAnimation* lightColorAnimation = new AttributeAnimation(context_);
  85. lightColorAnimation->AddKeyFrame(0.0f, Color(1.0f, 1.0f, 1.0f, 1.0f));
  86. lightColorAnimation->AddKeyFrame(1.0f, Color(1.0f, 0.0f, 0.0f, 1.0f));
  87. lightColorAnimation->AddKeyFrame(2.0f, Color(0.0f, 0.0f, 1.0f, 1.0f));
  88. lightColorAnimation->AddKeyFrame(3.0f, Color(1.0f, 1.0f, 1.0f, 1.0f));
  89. light->SetAttributeAnimation("Color", lightColorAnimation);
  90. // Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
  91. // quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
  92. // LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
  93. // see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
  94. // same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
  95. // scene.
  96. const unsigned NUM_OBJECTS = 200;
  97. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  98. {
  99. Node* mushroomNode = scene_->CreateChild("Mushroom");
  100. mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
  101. mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
  102. mushroomNode->SetScale(0.5f + Random(2.0f));
  103. StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
  104. mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
  105. mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
  106. }
  107. // Create a scene node for the camera, which we will move around
  108. // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
  109. cameraNode_ = scene_->CreateChild("Camera");
  110. cameraNode_->CreateComponent<Camera>();
  111. // Set an initial position for the camera scene node above the plane
  112. cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
  113. }
  114. void StaticScene::CreateInstructions()
  115. {
  116. ResourceCache* cache = GetSubsystem<ResourceCache>();
  117. UI* ui = GetSubsystem<UI>();
  118. // Construct new Text object, set string to display and font to use
  119. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  120. instructionText->SetText("Use WASD keys and mouse to move");
  121. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  122. // Position the text relative to the screen center
  123. instructionText->SetHorizontalAlignment(HA_CENTER);
  124. instructionText->SetVerticalAlignment(VA_CENTER);
  125. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  126. }
  127. void StaticScene::SetupViewport()
  128. {
  129. Renderer* renderer = GetSubsystem<Renderer>();
  130. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
  131. // at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
  132. // use, but now we just use full screen and default render path configured in the engine command line options
  133. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  134. renderer->SetViewport(0, viewport);
  135. }
  136. void StaticScene::MoveCamera(float timeStep)
  137. {
  138. // Do not move if the UI has a focused element (the console)
  139. if (GetSubsystem<UI>()->GetFocusElement())
  140. return;
  141. Input* input = GetSubsystem<Input>();
  142. // Movement speed as world units per second
  143. const float MOVE_SPEED = 20.0f;
  144. // Mouse sensitivity as degrees per pixel
  145. const float MOUSE_SENSITIVITY = 0.1f;
  146. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  147. IntVector2 mouseMove = input->GetMouseMove();
  148. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  149. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  150. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  151. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  152. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  153. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  154. // Use the TranslateRelative() function to move relative to the node's orientation. Alternatively we could
  155. // multiply the desired direction with the node's orientation quaternion, and use just Translate()
  156. if (input->GetKeyDown('W'))
  157. cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
  158. if (input->GetKeyDown('S'))
  159. cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
  160. if (input->GetKeyDown('A'))
  161. cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
  162. if (input->GetKeyDown('D'))
  163. cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
  164. }
  165. void StaticScene::SubscribeToEvents()
  166. {
  167. // Subscribe HandleUpdate() function for processing update events
  168. SubscribeToEvent(E_UPDATE, HANDLER(StaticScene, HandleUpdate));
  169. }
  170. void StaticScene::HandleUpdate(StringHash eventType, VariantMap& eventData)
  171. {
  172. using namespace Update;
  173. // Take the frame time step, which is stored as a float
  174. float timeStep = eventData[P_TIMESTEP].GetFloat();
  175. // Move the camera, scale movement with time step
  176. MoveCamera(timeStep);
  177. }