Sample.inl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 "Application.h"
  23. #include "Camera.h"
  24. #include "Console.h"
  25. #include "Cursor.h"
  26. #include "DebugHud.h"
  27. #include "Engine.h"
  28. #include "FileSystem.h"
  29. #include "Graphics.h"
  30. #include "Input.h"
  31. #include "InputEvents.h"
  32. #include "Renderer.h"
  33. #include "ResourceCache.h"
  34. #include "Scene.h"
  35. #include "SceneEvents.h"
  36. #include "Sprite.h"
  37. #include "Texture2D.h"
  38. #include "Timer.h"
  39. #include "UI.h"
  40. #include "XMLFile.h"
  41. Sample::Sample(Context* context) :
  42. Application(context),
  43. yaw_(0.0f),
  44. pitch_(0.0f),
  45. touchEnabled_(false),
  46. screenJoystickIndex_(M_MAX_UNSIGNED),
  47. screenJoystickSettingsIndex_(M_MAX_UNSIGNED),
  48. paused_(false)
  49. {
  50. }
  51. void Sample::Setup()
  52. {
  53. // Modify engine startup parameters
  54. engineParameters_["WindowTitle"] = GetTypeName();
  55. engineParameters_["LogName"] = GetSubsystem<FileSystem>()->GetAppPreferencesDir("urho3d", "logs") + GetTypeName() + ".log";
  56. engineParameters_["FullScreen"] = false;
  57. engineParameters_["Headless"] = false;
  58. }
  59. void Sample::Start()
  60. {
  61. if (GetPlatform() == "Android" || GetPlatform() == "iOS")
  62. // On mobile platform, enable touch by adding a screen joystick
  63. InitTouchInput();
  64. else if (GetSubsystem<Input>()->GetNumJoysticks() == 0)
  65. // On desktop platform, do not detect touch when we already got a joystick
  66. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(Sample, HandleTouchBegin));
  67. // Create logo
  68. CreateLogo();
  69. // Set custom window Title & Icon
  70. SetWindowTitleAndIcon();
  71. // Create console and debug HUD
  72. CreateConsoleAndDebugHud();
  73. // Subscribe key down event
  74. SubscribeToEvent(E_KEYDOWN, HANDLER(Sample, HandleKeyDown));
  75. // Subscribe scene update event
  76. SubscribeToEvent(E_SCENEUPDATE, HANDLER(Sample, HandleSceneUpdate));
  77. }
  78. void Sample::Stop()
  79. {
  80. engine_->DumpResources(true);
  81. }
  82. void Sample::InitTouchInput()
  83. {
  84. touchEnabled_ = true;
  85. ResourceCache* cache = GetSubsystem<ResourceCache>();
  86. Input* input = GetSubsystem<Input>();
  87. XMLFile* layout = cache->GetResource<XMLFile>("UI/ScreenJoystick_Samples.xml");
  88. const String& patchString = GetScreenJoystickPatchString();
  89. if (!patchString.Empty())
  90. {
  91. // Patch the screen joystick layout further on demand
  92. SharedPtr<XMLFile> patchFile(new XMLFile(context_));
  93. if (patchFile->FromString(patchString))
  94. layout->Patch(patchFile);
  95. }
  96. screenJoystickIndex_ = input->AddScreenJoystick(layout, cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
  97. input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, true);
  98. }
  99. void Sample::SetLogoVisible(bool enable)
  100. {
  101. if (logoSprite_)
  102. logoSprite_->SetVisible(enable);
  103. }
  104. void Sample::CreateLogo()
  105. {
  106. // Get logo texture
  107. ResourceCache* cache = GetSubsystem<ResourceCache>();
  108. Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/LogoLarge.png");
  109. if (!logoTexture)
  110. return;
  111. // Create logo sprite and add to the UI layout
  112. UI* ui = GetSubsystem<UI>();
  113. logoSprite_ = ui->GetRoot()->CreateChild<Sprite>();
  114. // Set logo sprite texture
  115. logoSprite_->SetTexture(logoTexture);
  116. int textureWidth = logoTexture->GetWidth();
  117. int textureHeight = logoTexture->GetHeight();
  118. // Set logo sprite scale
  119. logoSprite_->SetScale(256.0f / textureWidth);
  120. // Set logo sprite size
  121. logoSprite_->SetSize(textureWidth, textureHeight);
  122. // Set logo sprite hot spot
  123. logoSprite_->SetHotSpot(0, textureHeight);
  124. // Set logo sprite alignment
  125. logoSprite_->SetAlignment(HA_LEFT, VA_BOTTOM);
  126. // Make logo not fully opaque to show the scene underneath
  127. logoSprite_->SetOpacity(0.75f);
  128. // Set a low priority for the logo so that other UI elements can be drawn on top
  129. logoSprite_->SetPriority(-100);
  130. }
  131. void Sample::SetWindowTitleAndIcon()
  132. {
  133. ResourceCache* cache = GetSubsystem<ResourceCache>();
  134. Graphics* graphics = GetSubsystem<Graphics>();
  135. Image* icon = cache->GetResource<Image>("Textures/UrhoIcon.png");
  136. graphics->SetWindowIcon(icon);
  137. graphics->SetWindowTitle("Urho3D Sample");
  138. }
  139. void Sample::CreateConsoleAndDebugHud()
  140. {
  141. // Get default style
  142. ResourceCache* cache = GetSubsystem<ResourceCache>();
  143. XMLFile* xmlFile = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  144. // Create console
  145. Console* console = engine_->CreateConsole();
  146. console->SetDefaultStyle(xmlFile);
  147. console->GetBackground()->SetOpacity(0.8f);
  148. // Create debug HUD.
  149. DebugHud* debugHud = engine_->CreateDebugHud();
  150. debugHud->SetDefaultStyle(xmlFile);
  151. }
  152. void Sample::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  153. {
  154. using namespace KeyDown;
  155. int key = eventData[P_KEY].GetInt();
  156. // Close console (if open) or exit when ESC is pressed
  157. if (key == KEY_ESC)
  158. {
  159. Console* console = GetSubsystem<Console>();
  160. if (console->IsVisible())
  161. console->SetVisible(false);
  162. else
  163. engine_->Exit();
  164. }
  165. // Toggle console with F1
  166. else if (key == KEY_F1)
  167. GetSubsystem<Console>()->Toggle();
  168. // Toggle debug HUD with F2
  169. else if (key == KEY_F2)
  170. GetSubsystem<DebugHud>()->ToggleAll();
  171. // Common rendering quality controls, only when UI has no focused element
  172. else if (!GetSubsystem<UI>()->GetFocusElement())
  173. {
  174. Renderer* renderer = GetSubsystem<Renderer>();
  175. // Preferences / Pause
  176. if (key == KEY_SELECT && touchEnabled_)
  177. {
  178. paused_ = !paused_;
  179. Input* input = GetSubsystem<Input>();
  180. if (screenJoystickSettingsIndex_ == M_MAX_UNSIGNED)
  181. {
  182. // Lazy initialization
  183. ResourceCache* cache = GetSubsystem<ResourceCache>();
  184. screenJoystickSettingsIndex_ = input->AddScreenJoystick(cache->GetResource<XMLFile>("UI/ScreenJoystickSettings_Samples.xml"), cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
  185. }
  186. else
  187. input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, paused_);
  188. }
  189. // Texture quality
  190. else if (key == '1')
  191. {
  192. int quality = renderer->GetTextureQuality();
  193. ++quality;
  194. if (quality > QUALITY_HIGH)
  195. quality = QUALITY_LOW;
  196. renderer->SetTextureQuality(quality);
  197. }
  198. // Material quality
  199. else if (key == '2')
  200. {
  201. int quality = renderer->GetMaterialQuality();
  202. ++quality;
  203. if (quality > QUALITY_HIGH)
  204. quality = QUALITY_LOW;
  205. renderer->SetMaterialQuality(quality);
  206. }
  207. // Specular lighting
  208. else if (key == '3')
  209. renderer->SetSpecularLighting(!renderer->GetSpecularLighting());
  210. // Shadow rendering
  211. else if (key == '4')
  212. renderer->SetDrawShadows(!renderer->GetDrawShadows());
  213. // Shadow map resolution
  214. else if (key == '5')
  215. {
  216. int shadowMapSize = renderer->GetShadowMapSize();
  217. shadowMapSize *= 2;
  218. if (shadowMapSize > 2048)
  219. shadowMapSize = 512;
  220. renderer->SetShadowMapSize(shadowMapSize);
  221. }
  222. // Shadow depth and filtering quality
  223. else if (key == '6')
  224. {
  225. int quality = renderer->GetShadowQuality();
  226. ++quality;
  227. if (quality > SHADOWQUALITY_HIGH_24BIT)
  228. quality = SHADOWQUALITY_LOW_16BIT;
  229. renderer->SetShadowQuality(quality);
  230. }
  231. // Occlusion culling
  232. else if (key == '7')
  233. {
  234. bool occlusion = renderer->GetMaxOccluderTriangles() > 0;
  235. occlusion = !occlusion;
  236. renderer->SetMaxOccluderTriangles(occlusion ? 5000 : 0);
  237. }
  238. // Instancing
  239. else if (key == '8')
  240. renderer->SetDynamicInstancing(!renderer->GetDynamicInstancing());
  241. // Take screenshot
  242. else if (key == '9')
  243. {
  244. Graphics* graphics = GetSubsystem<Graphics>();
  245. Image screenshot(context_);
  246. graphics->TakeScreenShot(screenshot);
  247. // Here we save in the Data folder with date and time appended
  248. screenshot.SavePNG(GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Screenshot_" +
  249. Time::GetTimeStamp().Replaced(':', '_').Replaced('.', '_').Replaced(' ', '_') + ".png");
  250. }
  251. }
  252. }
  253. void Sample::HandleSceneUpdate(StringHash eventType, VariantMap& eventData)
  254. {
  255. // Move the camera by touch, if the camera node is initialized by descendant sample class
  256. if (touchEnabled_ && cameraNode_)
  257. {
  258. Input* input = GetSubsystem<Input>();
  259. for (unsigned i = 0; i < input->GetNumTouches(); ++i)
  260. {
  261. TouchState* state = input->GetTouch(i);
  262. if (!state->touchedElement_) // Touch on empty space
  263. {
  264. if (state->delta_.x_ ||state->delta_.y_)
  265. {
  266. Camera* camera = cameraNode_->GetComponent<Camera>();
  267. if (!camera)
  268. return;
  269. Graphics* graphics = GetSubsystem<Graphics>();
  270. yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_;
  271. pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_;
  272. // Construct new orientation for the camera scene node from yaw and pitch; roll is fixed to zero
  273. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  274. }
  275. else
  276. {
  277. // Move the cursor to the touch position
  278. Cursor* cursor = GetSubsystem<UI>()->GetCursor();
  279. if (cursor && cursor->IsVisible())
  280. cursor->SetPosition(state->position_);
  281. }
  282. }
  283. }
  284. }
  285. }
  286. void Sample::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  287. {
  288. // On some platforms like Windows the presence of touch input can only be detected dynamically
  289. InitTouchInput();
  290. UnsubscribeFromEvent("TouchBegin");
  291. }