RenderToTexture.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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/Camera.h>
  26. #include <Atomic/Graphics/Graphics.h>
  27. #include <Atomic/Graphics/Material.h>
  28. #include <Atomic/Graphics/Model.h>
  29. #include <Atomic/Graphics/Octree.h>
  30. #include <Atomic/Graphics/Renderer.h>
  31. #include <Atomic/Graphics/RenderSurface.h>
  32. #include <Atomic/Graphics/StaticModel.h>
  33. #include <Atomic/Graphics/Technique.h>
  34. #include <Atomic/Graphics/Texture2D.h>
  35. #include <Atomic/Graphics/Zone.h>
  36. #include <Atomic/Input/Input.h>
  37. #include <Atomic/Resource/ResourceCache.h>
  38. #include <Atomic/Scene/Scene.h>
  39. #include <Atomic/UI/UI.h>
  40. #include "RenderToTexture.h"
  41. #include "Rotator.h"
  42. #include <Atomic/DebugNew.h>
  43. RenderToTexture::RenderToTexture(Context* context) :
  44. Sample(context)
  45. {
  46. // Register an object factory for our custom Rotator component so that we can create them to scene nodes
  47. context->RegisterFactory<Rotator>();
  48. }
  49. void RenderToTexture::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 events
  60. SubscribeToEvents();
  61. // Set the mouse mode to use in the sample
  62. Sample::InitMouseMode(MM_RELATIVE);
  63. }
  64. void RenderToTexture::CreateScene()
  65. {
  66. ResourceCache* cache = GetSubsystem<ResourceCache>();
  67. {
  68. // Create the scene which will be rendered to a texture
  69. rttScene_ = new Scene(context_);
  70. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  71. rttScene_->CreateComponent<Octree>();
  72. // Create a Zone for ambient light & fog control
  73. Node* zoneNode = rttScene_->CreateChild("Zone");
  74. Zone* zone = zoneNode->CreateComponent<Zone>();
  75. // Set same volume as the Octree, set a close bluish fog and some ambient light
  76. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  77. zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
  78. zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
  79. zone->SetFogStart(10.0f);
  80. zone->SetFogEnd(100.0f);
  81. // Create randomly positioned and oriented box StaticModels in the scene
  82. const unsigned NUM_OBJECTS = 2000;
  83. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  84. {
  85. Node* boxNode = rttScene_->CreateChild("Box");
  86. boxNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(200.0f) - 100.0f, Random(200.0f) - 100.0f));
  87. // Orient using random pitch, yaw and roll Euler angles
  88. boxNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
  89. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  90. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  91. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  92. // Add our custom Rotator component which will rotate the scene node each frame, when the scene sends its update event.
  93. // Simply set same rotation speed for all objects
  94. Rotator* rotator = boxNode->CreateComponent<Rotator>();
  95. rotator->SetRotationSpeed(Vector3(10.0f, 20.0f, 30.0f));
  96. }
  97. // Create a camera for the render-to-texture scene. Simply leave it at the world origin and let it observe the scene
  98. rttCameraNode_ = rttScene_->CreateChild("Camera");
  99. Camera* camera = rttCameraNode_->CreateComponent<Camera>();
  100. camera->SetFarClip(100.0f);
  101. // Create a point light to the camera scene node
  102. Light* light = rttCameraNode_->CreateComponent<Light>();
  103. light->SetLightType(LIGHT_POINT);
  104. light->SetRange(30.0f);
  105. }
  106. {
  107. // Create the scene in which we move around
  108. scene_ = new Scene(context_);
  109. // Create octree, use also default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  110. scene_->CreateComponent<Octree>();
  111. // Create a Zone component for ambient lighting & fog control
  112. Node* zoneNode = scene_->CreateChild("Zone");
  113. Zone* zone = zoneNode->CreateComponent<Zone>();
  114. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  115. zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
  116. zone->SetFogStart(100.0f);
  117. zone->SetFogEnd(300.0f);
  118. // Create a directional light without shadows
  119. Node* lightNode = scene_->CreateChild("DirectionalLight");
  120. lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
  121. Light* light = lightNode->CreateComponent<Light>();
  122. light->SetLightType(LIGHT_DIRECTIONAL);
  123. light->SetColor(Color(0.2f, 0.2f, 0.2f));
  124. light->SetSpecularIntensity(1.0f);
  125. // Create a "floor" consisting of several tiles
  126. for (int y = -5; y <= 5; ++y)
  127. {
  128. for (int x = -5; x <= 5; ++x)
  129. {
  130. Node* floorNode = scene_->CreateChild("FloorTile");
  131. floorNode->SetPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
  132. floorNode->SetScale(Vector3(20.0f, 1.0f, 20.f));
  133. StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
  134. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  135. floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  136. }
  137. }
  138. // Create a "screen" like object for viewing the second scene. Construct it from two StaticModels, a box for the frame
  139. // and a plane for the actual view
  140. {
  141. Node* boxNode = scene_->CreateChild("ScreenBox");
  142. boxNode->SetPosition(Vector3(0.0f, 10.0f, 0.0f));
  143. boxNode->SetScale(Vector3(21.0f, 16.0f, 0.5f));
  144. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  145. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  146. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  147. Node* screenNode = scene_->CreateChild("Screen");
  148. screenNode->SetPosition(Vector3(0.0f, 10.0f, -0.27f));
  149. screenNode->SetRotation(Quaternion(-90.0f, 0.0f, 0.0f));
  150. screenNode->SetScale(Vector3(20.0f, 0.0f, 15.0f));
  151. StaticModel* screenObject = screenNode->CreateComponent<StaticModel>();
  152. screenObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  153. // Create a renderable texture (1024x768, RGB format), enable bilinear filtering on it
  154. SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
  155. renderTexture->SetSize(1024, 768, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
  156. renderTexture->SetFilterMode(FILTER_BILINEAR);
  157. // Create a new material from scratch, use the diffuse unlit technique, assign the render texture
  158. // as its diffuse texture, then assign the material to the screen plane object
  159. SharedPtr<Material> renderMaterial(new Material(context_));
  160. renderMaterial->SetTechnique(0, cache->GetResource<Technique>("Techniques/DiffUnlit.xml"));
  161. renderMaterial->SetTexture(TU_DIFFUSE, renderTexture);
  162. // Since the screen material is on top of the box model and may Z-fight, use negative depth bias
  163. // to push it forward (particularly necessary on mobiles with possibly less Z resolution)
  164. renderMaterial->SetDepthBias(BiasParameters(-0.001f, 0.0f));
  165. screenObject->SetMaterial(renderMaterial);
  166. // Get the texture's RenderSurface object (exists when the texture has been created in rendertarget mode)
  167. // and define the viewport for rendering the second scene, similarly as how backbuffer viewports are defined
  168. // to the Renderer subsystem. By default the texture viewport will be updated when the texture is visible
  169. // in the main view
  170. RenderSurface* surface = renderTexture->GetRenderSurface();
  171. SharedPtr<Viewport> rttViewport(new Viewport(context_, rttScene_, rttCameraNode_->GetComponent<Camera>()));
  172. surface->SetViewport(0, rttViewport);
  173. }
  174. // Create the camera which we will move around. Limit far clip distance to match the fog
  175. cameraNode_ = scene_->CreateChild("Camera");
  176. Camera* camera = cameraNode_->CreateComponent<Camera>();
  177. camera->SetFarClip(300.0f);
  178. // Set an initial position for the camera scene node above the plane
  179. cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -30.0f));
  180. }
  181. }
  182. void RenderToTexture::CreateInstructions()
  183. {
  184. SimpleCreateInstructions("Use WASD keys and mouse/touch to move");
  185. }
  186. void RenderToTexture::SetupViewport()
  187. {
  188. Renderer* renderer = GetSubsystem<Renderer>();
  189. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  190. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  191. renderer->SetViewport(0, viewport);
  192. }
  193. void RenderToTexture::MoveCamera(float timeStep)
  194. {
  195. Input* input = GetSubsystem<Input>();
  196. // Movement speed as world units per second
  197. const float MOVE_SPEED = 20.0f;
  198. // Mouse sensitivity as degrees per pixel
  199. const float MOUSE_SENSITIVITY = 0.1f;
  200. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  201. IntVector2 mouseMove = input->GetMouseMove();
  202. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  203. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  204. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  205. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  206. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  207. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  208. if (input->GetKeyDown(KEY_W))
  209. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  210. if (input->GetKeyDown(KEY_S))
  211. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  212. if (input->GetKeyDown(KEY_A))
  213. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  214. if (input->GetKeyDown(KEY_D))
  215. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  216. }
  217. void RenderToTexture::SubscribeToEvents()
  218. {
  219. // Subscribe HandleUpdate() function for processing update events
  220. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(RenderToTexture, HandleUpdate));
  221. }
  222. void RenderToTexture::HandleUpdate(StringHash eventType, VariantMap& eventData)
  223. {
  224. using namespace Update;
  225. // Take the frame time step, which is stored as a float
  226. float timeStep = eventData[P_TIMESTEP].GetFloat();
  227. // Move the camera, scale movement with time step
  228. MoveCamera(timeStep);
  229. }