RenderToTexture.cpp 11 KB

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