DynamicGeometry.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 "Camera.h"
  23. #include "CoreEvents.h"
  24. #include "Engine.h"
  25. #include "Font.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Input.h"
  29. #include "Light.h"
  30. #include "Log.h"
  31. #include "Model.h"
  32. #include "Octree.h"
  33. #include "Profiler.h"
  34. #include "Renderer.h"
  35. #include "ResourceCache.h"
  36. #include "Scene.h"
  37. #include "StaticModel.h"
  38. #include "Text.h"
  39. #include "VertexBuffer.h"
  40. #include "UI.h"
  41. #include "Zone.h"
  42. #include "DynamicGeometry.h"
  43. #include "DebugNew.h"
  44. DEFINE_APPLICATION_MAIN(DynamicGeometry)
  45. DynamicGeometry::DynamicGeometry(Context* context) :
  46. Sample(context),
  47. animate_(true),
  48. time_(0.0f)
  49. {
  50. }
  51. void DynamicGeometry::Start()
  52. {
  53. // Execute base class startup
  54. Sample::Start();
  55. // Create the scene content
  56. CreateScene();
  57. // Create the UI content
  58. CreateInstructions();
  59. // Setup the viewport for displaying the scene
  60. SetupViewport();
  61. // Hook up to the frame update events
  62. SubscribeToEvents();
  63. }
  64. void DynamicGeometry::CreateScene()
  65. {
  66. ResourceCache* cache = GetSubsystem<ResourceCache>();
  67. scene_ = new Scene(context_);
  68. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  69. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  70. scene_->CreateComponent<Octree>();
  71. // Create a Zone for ambient light & fog control
  72. Node* zoneNode = scene_->CreateChild("Zone");
  73. Zone* zone = zoneNode->CreateComponent<Zone>();
  74. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  75. zone->SetFogColor(Color(0.2f, 0.2f, 0.2f));
  76. zone->SetFogStart(200.0f);
  77. zone->SetFogEnd(300.0f);
  78. // Create a directional light
  79. Node* lightNode = scene_->CreateChild("DirectionalLight");
  80. lightNode->SetDirection(Vector3(-0.6f, -1.0f, -0.8f)); // The direction vector does not need to be normalized
  81. Light* light = lightNode->CreateComponent<Light>();
  82. light->SetLightType(LIGHT_DIRECTIONAL);
  83. light->SetColor(Color(0.4f, 1.0f, 0.4f));
  84. light->SetSpecularIntensity(1.5f);
  85. // Get the original model and its unmodified vertices, which are used as source data for the animation
  86. Model* originalModel = cache->GetResource<Model>("Models/Box.mdl");
  87. if (!originalModel)
  88. {
  89. LOGERROR("Model not found, cannot initialize example scene");
  90. return;
  91. }
  92. // Get the vertex buffer from the first geometry's first LOD level
  93. VertexBuffer* buffer = originalModel->GetGeometry(0, 0)->GetVertexBuffer(0);
  94. const unsigned char* vertexData = (const unsigned char*)buffer->Lock(0, buffer->GetVertexCount());
  95. if (vertexData)
  96. {
  97. unsigned numVertices = buffer->GetVertexCount();
  98. unsigned vertexSize = buffer->GetVertexSize();
  99. // Copy the original vertex positions
  100. for (unsigned i = 0; i < numVertices; ++i)
  101. {
  102. const Vector3& src = *reinterpret_cast<const Vector3*>(vertexData + i * vertexSize);
  103. originalVertices_.Push(src);
  104. }
  105. buffer->Unlock();
  106. // Detect duplicate vertices to allow seamless animation
  107. vertexDuplicates_.Resize(originalVertices_.Size());
  108. for (unsigned i = 0; i < originalVertices_.Size(); ++i)
  109. {
  110. vertexDuplicates_[i] = i; // Assume not a duplicate
  111. for (unsigned j = 0; j < i; ++j)
  112. {
  113. if (originalVertices_[i].Equals(originalVertices_[j]))
  114. {
  115. vertexDuplicates_[i] = j;
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. else
  122. {
  123. LOGERROR("Failed to lock the model vertex buffer to get original vertices");
  124. return;
  125. }
  126. // Create StaticModels in the scene. Clone the model for each so that we can modify the vertex data individually
  127. for (int y = -1; y <= 1; ++y)
  128. {
  129. for (int x = -1; x <= 1; ++x)
  130. {
  131. Node* node = scene_->CreateChild("Object");
  132. node->SetPosition(Vector3(x * 2.0f, 0.0f, y * 2.0f));
  133. StaticModel* object = node->CreateComponent<StaticModel>();
  134. SharedPtr<Model> cloneModel = originalModel->Clone();
  135. object->SetModel(cloneModel);
  136. // Store the cloned vertex buffer that we will modify when animating
  137. animatingBuffers_.Push(SharedPtr<VertexBuffer>(cloneModel->GetGeometry(0, 0)->GetVertexBuffer(0)));
  138. }
  139. }
  140. // Create the camera
  141. cameraNode_ = new Node(context_);
  142. cameraNode_->SetPosition(Vector3(0.0f, 2.0f, -20.0f));
  143. Camera* camera = cameraNode_->CreateComponent<Camera>();
  144. camera->SetFarClip(300.0f);
  145. }
  146. void DynamicGeometry::CreateInstructions()
  147. {
  148. ResourceCache* cache = GetSubsystem<ResourceCache>();
  149. UI* ui = GetSubsystem<UI>();
  150. // Construct new Text object, set string to display and font to use
  151. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  152. instructionText->SetText(
  153. "Use WASD keys and mouse/touch to move\n"
  154. "Space to toggle animation"
  155. );
  156. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  157. // The text has multiple rows. Center them in relation to each other
  158. instructionText->SetTextAlignment(HA_CENTER);
  159. // Position the text relative to the screen center
  160. instructionText->SetHorizontalAlignment(HA_CENTER);
  161. instructionText->SetVerticalAlignment(VA_CENTER);
  162. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  163. }
  164. void DynamicGeometry::SetupViewport()
  165. {
  166. Renderer* renderer = GetSubsystem<Renderer>();
  167. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  168. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  169. renderer->SetViewport(0, viewport);
  170. }
  171. void DynamicGeometry::SubscribeToEvents()
  172. {
  173. // Subscribe HandleUpdate() function for processing update events
  174. SubscribeToEvent(E_UPDATE, HANDLER(DynamicGeometry, HandleUpdate));
  175. }
  176. void DynamicGeometry::MoveCamera(float timeStep)
  177. {
  178. // Do not move if the UI has a focused element (the console)
  179. if (GetSubsystem<UI>()->GetFocusElement())
  180. return;
  181. Input* input = GetSubsystem<Input>();
  182. // Movement speed as world units per second
  183. const float MOVE_SPEED = 20.0f;
  184. // Mouse sensitivity as degrees per pixel
  185. const float MOUSE_SENSITIVITY = 0.1f;
  186. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  187. IntVector2 mouseMove = input->GetMouseMove();
  188. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  189. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  190. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  191. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  192. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  193. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  194. if (input->GetKeyDown('W'))
  195. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  196. if (input->GetKeyDown('S'))
  197. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  198. if (input->GetKeyDown('A'))
  199. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  200. if (input->GetKeyDown('D'))
  201. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  202. }
  203. void DynamicGeometry::AnimateObjects(float timeStep)
  204. {
  205. PROFILE(AnimateObjects);
  206. time_ += timeStep * 100.0f;
  207. // Repeat for each of the cloned vertex buffers
  208. for (unsigned i = 0; i < animatingBuffers_.Size(); ++i)
  209. {
  210. float startPhase = time_ + i * 30.0f;
  211. VertexBuffer* buffer = animatingBuffers_[i];
  212. // Lock the vertex buffer for update and rewrite positions with sine wave modulated ones
  213. // Cannot use discard lock as there is other data (normals, UVs) that we are not overwriting
  214. unsigned char* vertexData = (unsigned char*)buffer->Lock(0, buffer->GetVertexCount());
  215. if (vertexData)
  216. {
  217. unsigned vertexSize = buffer->GetVertexSize();
  218. unsigned numVertices = buffer->GetVertexCount();
  219. for (unsigned j = 0; j < numVertices; ++j)
  220. {
  221. // If there are duplicate vertices, animate them in phase of the original
  222. float phase = startPhase + vertexDuplicates_[j] * 10.0f;
  223. Vector3& src = originalVertices_[j];
  224. Vector3& dest = *reinterpret_cast<Vector3*>(vertexData + j * vertexSize);
  225. dest.x_ = src.x_ * (1.0f + 0.1f * Sin(phase));
  226. dest.y_ = src.y_ * (1.0f + 0.1f * Sin(phase + 60.0f));
  227. dest.z_ = src.z_ * (1.0f + 0.1f * Sin(phase + 120.0f));
  228. }
  229. buffer->Unlock();
  230. }
  231. }
  232. }
  233. void DynamicGeometry::HandleUpdate(StringHash eventType, VariantMap& eventData)
  234. {
  235. using namespace Update;
  236. // Take the frame time step, which is stored as a float
  237. float timeStep = eventData[P_TIMESTEP].GetFloat();
  238. // Toggle animation with space
  239. Input* input = GetSubsystem<Input>();
  240. if (input->GetKeyPress(KEY_SPACE))
  241. animate_ = !animate_;
  242. // Move the camera, scale movement with time step
  243. MoveCamera(timeStep);
  244. // Animate objects' vertex data if enabled
  245. if (animate_)
  246. AnimateObjects(timeStep);
  247. }