Sample.inl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. //
  2. // Copyright (c) 2008-2020 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 <Urho3D/Engine/Application.h>
  23. #include <Urho3D/Graphics/Camera.h>
  24. #include <Urho3D/Engine/Console.h>
  25. #include <Urho3D/UI/Cursor.h>
  26. #include <Urho3D/Engine/DebugHud.h>
  27. #include <Urho3D/Engine/Engine.h>
  28. #include <Urho3D/Engine/EngineDefs.h>
  29. #include <Urho3D/IO/FileSystem.h>
  30. #include <Urho3D/Graphics/Graphics.h>
  31. #include <Urho3D/Input/Input.h>
  32. #include <Urho3D/Input/InputEvents.h>
  33. #include <Urho3D/Graphics/Renderer.h>
  34. #include <Urho3D/Resource/ResourceCache.h>
  35. #include <Urho3D/Scene/Scene.h>
  36. #include <Urho3D/Scene/SceneEvents.h>
  37. #include <Urho3D/UI/Sprite.h>
  38. #include <Urho3D/Graphics/Texture2D.h>
  39. #include <Urho3D/Core/Timer.h>
  40. #include <Urho3D/UI/UI.h>
  41. #include <Urho3D/Resource/XMLFile.h>
  42. #include <Urho3D/IO/Log.h>
  43. Sample::Sample(Context* context) :
  44. Application(context),
  45. yaw_(0.0f),
  46. pitch_(0.0f),
  47. touchEnabled_(false),
  48. useMouseMode_(MM_ABSOLUTE),
  49. screenJoystickIndex_(M_MAX_UNSIGNED),
  50. screenJoystickSettingsIndex_(M_MAX_UNSIGNED),
  51. paused_(false)
  52. {
  53. }
  54. void Sample::Setup()
  55. {
  56. // Modify engine startup parameters
  57. engineParameters_[EP_WINDOW_TITLE] = GetTypeName();
  58. engineParameters_[EP_LOG_NAME] = GetSubsystem<FileSystem>()->GetAppPreferencesDir("urho3d", "logs") + GetTypeName() + ".log";
  59. engineParameters_[EP_FULL_SCREEN] = false;
  60. engineParameters_[EP_HEADLESS] = false;
  61. engineParameters_[EP_SOUND] = false;
  62. engineParameters_[EP_WINDOW_HEIGHT] = 600;
  63. engineParameters_[EP_WINDOW_WIDTH] = 800;
  64. engineParameters_[EP_LOG_LEVEL] = LOG_INFO;
  65. engineParameters_[EP_MONITOR] = 1;
  66. // Construct a search path to find the resource prefix with two entries:
  67. // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree
  68. // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location
  69. if (!engineParameters_.Contains(EP_RESOURCE_PREFIX_PATHS))
  70. engineParameters_[EP_RESOURCE_PREFIX_PATHS] = ";../share/Resources;../share/Urho3D/Resources";
  71. }
  72. void Sample::Start()
  73. {
  74. if (GetPlatform() == "Android" || GetPlatform() == "iOS")
  75. // On mobile platform, enable touch by adding a screen joystick
  76. InitTouchInput();
  77. else if (GetSubsystem<Input>()->GetNumJoysticks() == 0)
  78. // On desktop platform, do not detect touch when we already got a joystick
  79. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Sample, HandleTouchBegin));
  80. // Create logo
  81. CreateLogo();
  82. // Set custom window Title & Icon
  83. SetWindowTitleAndIcon();
  84. // Create console and debug HUD
  85. CreateConsoleAndDebugHud();
  86. // Subscribe key down event
  87. SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(Sample, HandleKeyDown));
  88. // Subscribe key up event
  89. SubscribeToEvent(E_KEYUP, URHO3D_HANDLER(Sample, HandleKeyUp));
  90. // Subscribe scene update event
  91. SubscribeToEvent(E_SCENEUPDATE, URHO3D_HANDLER(Sample, HandleSceneUpdate));
  92. }
  93. void Sample::Stop()
  94. {
  95. engine_->DumpResources(true);
  96. }
  97. void Sample::InitTouchInput()
  98. {
  99. touchEnabled_ = true;
  100. ResourceCache* cache = GetSubsystem<ResourceCache>();
  101. Input* input = GetSubsystem<Input>();
  102. XMLFile* layout = cache->GetResource<XMLFile>("UI/ScreenJoystick_Samples.xml");
  103. const String& patchString = GetScreenJoystickPatchString();
  104. if (!patchString.Empty())
  105. {
  106. // Patch the screen joystick layout further on demand
  107. SharedPtr<XMLFile> patchFile(new XMLFile(context_));
  108. if (patchFile->FromString(patchString))
  109. layout->Patch(patchFile);
  110. }
  111. screenJoystickIndex_ = (unsigned)input->AddScreenJoystick(layout, cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
  112. input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, true);
  113. }
  114. void Sample::InitMouseMode(MouseMode mode)
  115. {
  116. useMouseMode_ = mode;
  117. Input* input = GetSubsystem<Input>();
  118. if (GetPlatform() != "Web")
  119. {
  120. if (useMouseMode_ == MM_FREE)
  121. input->SetMouseVisible(true);
  122. Console* console = GetSubsystem<Console>();
  123. if (useMouseMode_ != MM_ABSOLUTE)
  124. {
  125. input->SetMouseMode(useMouseMode_);
  126. if (console && console->IsVisible())
  127. input->SetMouseMode(MM_ABSOLUTE, true);
  128. }
  129. }
  130. else
  131. {
  132. input->SetMouseVisible(true);
  133. SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(Sample, HandleMouseModeRequest));
  134. SubscribeToEvent(E_MOUSEMODECHANGED, URHO3D_HANDLER(Sample, HandleMouseModeChange));
  135. }
  136. }
  137. void Sample::SetLogoVisible(bool enable)
  138. {
  139. if (logoSprite_)
  140. logoSprite_->SetVisible(enable);
  141. }
  142. void Sample::CreateLogo()
  143. {
  144. // Get logo texture
  145. ResourceCache* cache = GetSubsystem<ResourceCache>();
  146. Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/FishBoneLogo.png");
  147. if (!logoTexture)
  148. return;
  149. // Create logo sprite and add to the UI layout
  150. UI* ui = GetSubsystem<UI>();
  151. logoSprite_ = ui->GetRoot()->CreateChild<Sprite>();
  152. // Set logo sprite texture
  153. logoSprite_->SetTexture(logoTexture);
  154. int textureWidth = logoTexture->GetWidth();
  155. int textureHeight = logoTexture->GetHeight();
  156. // Set logo sprite scale
  157. logoSprite_->SetScale(256.0f / textureWidth);
  158. // Set logo sprite size
  159. logoSprite_->SetSize(textureWidth, textureHeight);
  160. // Set logo sprite hot spot
  161. logoSprite_->SetHotSpot(textureWidth, textureHeight);
  162. // Set logo sprite alignment
  163. logoSprite_->SetAlignment(HA_RIGHT, VA_BOTTOM);
  164. // Make logo not fully opaque to show the scene underneath
  165. logoSprite_->SetOpacity(0.9f);
  166. // Set a low priority for the logo so that other UI elements can be drawn on top
  167. logoSprite_->SetPriority(-100);
  168. }
  169. void Sample::SetWindowTitleAndIcon()
  170. {
  171. ResourceCache* cache = GetSubsystem<ResourceCache>();
  172. Graphics* graphics = GetSubsystem<Graphics>();
  173. Image* icon = cache->GetResource<Image>("Textures/UrhoIcon.png");
  174. graphics->SetWindowIcon(icon);
  175. graphics->SetWindowTitle("Urho3D Sample");
  176. }
  177. void Sample::CreateConsoleAndDebugHud()
  178. {
  179. // Get default style
  180. ResourceCache* cache = GetSubsystem<ResourceCache>();
  181. XMLFile* xmlFile = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  182. // Create console
  183. Console* console = engine_->CreateConsole();
  184. console->SetDefaultStyle(xmlFile);
  185. console->GetBackground()->SetOpacity(0.8f);
  186. console->SetNumHistoryRows(1000);
  187. console->SetNumBufferedRows(100);
  188. // Create debug HUD.
  189. DebugHud* debugHud = engine_->CreateDebugHud();
  190. debugHud->SetDefaultStyle(xmlFile);
  191. }
  192. void Sample::HandleKeyUp(StringHash /*eventType*/, VariantMap& eventData)
  193. {
  194. using namespace KeyUp;
  195. int key = eventData[P_KEY].GetInt();
  196. // Close console (if open) or exit when ESC is pressed
  197. if (key == KEY_ESCAPE)
  198. {
  199. Console* console = GetSubsystem<Console>();
  200. if (console->IsVisible())
  201. console->SetVisible(false);
  202. else
  203. {
  204. if (GetPlatform() == "Web")
  205. {
  206. GetSubsystem<Input>()->SetMouseVisible(true);
  207. if (useMouseMode_ != MM_ABSOLUTE)
  208. GetSubsystem<Input>()->SetMouseMode(MM_FREE);
  209. }
  210. else
  211. engine_->Exit();
  212. }
  213. }
  214. }
  215. void Sample::HandleKeyDown(StringHash /*eventType*/, VariantMap& eventData)
  216. {
  217. using namespace KeyDown;
  218. int key = eventData[P_KEY].GetInt();
  219. // Toggle console with F1
  220. if (key == KEY_F1)
  221. GetSubsystem<Console>()->Toggle();
  222. // Toggle debug HUD with F2
  223. else if (key == KEY_F2)
  224. GetSubsystem<DebugHud>()->ToggleAll();
  225. // Common rendering quality controls, only when UI has no focused element
  226. else if (!GetSubsystem<UI>()->GetFocusElement())
  227. {
  228. Renderer* renderer = GetSubsystem<Renderer>();
  229. // Preferences / Pause
  230. if (key == KEY_SELECT && touchEnabled_)
  231. {
  232. paused_ = !paused_;
  233. Input* input = GetSubsystem<Input>();
  234. if (screenJoystickSettingsIndex_ == M_MAX_UNSIGNED)
  235. {
  236. // Lazy initialization
  237. ResourceCache* cache = GetSubsystem<ResourceCache>();
  238. screenJoystickSettingsIndex_ = (unsigned)input->AddScreenJoystick(cache->GetResource<XMLFile>("UI/ScreenJoystickSettings_Samples.xml"), cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
  239. }
  240. else
  241. input->SetScreenJoystickVisible(screenJoystickSettingsIndex_, paused_);
  242. }
  243. // Texture quality
  244. else if (key == '1')
  245. {
  246. auto quality = (unsigned)renderer->GetTextureQuality();
  247. ++quality;
  248. if (quality > QUALITY_HIGH)
  249. quality = QUALITY_LOW;
  250. renderer->SetTextureQuality((MaterialQuality)quality);
  251. }
  252. // Material quality
  253. else if (key == '2')
  254. {
  255. auto quality = (unsigned)renderer->GetMaterialQuality();
  256. ++quality;
  257. if (quality > QUALITY_HIGH)
  258. quality = QUALITY_LOW;
  259. renderer->SetMaterialQuality((MaterialQuality)quality);
  260. }
  261. // Specular lighting
  262. else if (key == '3')
  263. renderer->SetSpecularLighting(!renderer->GetSpecularLighting());
  264. // Shadow rendering
  265. else if (key == '4')
  266. renderer->SetDrawShadows(!renderer->GetDrawShadows());
  267. // Shadow map resolution
  268. else if (key == '5')
  269. {
  270. int shadowMapSize = renderer->GetShadowMapSize();
  271. shadowMapSize *= 2;
  272. if (shadowMapSize > 2048)
  273. shadowMapSize = 512;
  274. renderer->SetShadowMapSize(shadowMapSize);
  275. }
  276. // Shadow depth and filtering quality
  277. else if (key == '6')
  278. {
  279. ShadowQuality quality = renderer->GetShadowQuality();
  280. quality = (ShadowQuality)(quality + 1);
  281. if (quality > SHADOWQUALITY_BLUR_VSM)
  282. quality = SHADOWQUALITY_SIMPLE_16BIT;
  283. renderer->SetShadowQuality(quality);
  284. }
  285. // Occlusion culling
  286. else if (key == '7')
  287. {
  288. bool occlusion = renderer->GetMaxOccluderTriangles() > 0;
  289. occlusion = !occlusion;
  290. renderer->SetMaxOccluderTriangles(occlusion ? 5000 : 0);
  291. }
  292. // Instancing
  293. else if (key == '8')
  294. renderer->SetDynamicInstancing(!renderer->GetDynamicInstancing());
  295. // Take screenshot
  296. else if (key == '9')
  297. {
  298. Graphics* graphics = GetSubsystem<Graphics>();
  299. Image screenshot(context_);
  300. graphics->TakeScreenShot(screenshot);
  301. // Here we save in the Data folder with date and time appended
  302. screenshot.SavePNG(GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Screenshot_" +
  303. Time::GetTimeStamp().Replaced(':', '_').Replaced('.', '_').Replaced(' ', '_') + ".png");
  304. }
  305. }
  306. }
  307. void Sample::HandleSceneUpdate(StringHash /*eventType*/, VariantMap& eventData)
  308. {
  309. // Move the camera by touch, if the camera node is initialized by descendant sample class
  310. if (touchEnabled_ && cameraNode_)
  311. {
  312. Input* input = GetSubsystem<Input>();
  313. for (unsigned i = 0; i < input->GetNumTouches(); ++i)
  314. {
  315. TouchState* state = input->GetTouch(i);
  316. if (!state->touchedElement_) // Touch on empty space
  317. {
  318. if (state->delta_.x_ ||state->delta_.y_)
  319. {
  320. Camera* camera = cameraNode_->GetComponent<Camera>();
  321. if (!camera)
  322. return;
  323. Graphics* graphics = GetSubsystem<Graphics>();
  324. yaw_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.x_;
  325. pitch_ += TOUCH_SENSITIVITY * camera->GetFov() / graphics->GetHeight() * state->delta_.y_;
  326. // Construct new orientation for the camera scene node from yaw and pitch; roll is fixed to zero
  327. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  328. }
  329. else
  330. {
  331. // Move the cursor to the touch position
  332. Cursor* cursor = GetSubsystem<UI>()->GetCursor();
  333. if (cursor && cursor->IsVisible())
  334. cursor->SetPosition(state->position_);
  335. }
  336. }
  337. }
  338. }
  339. }
  340. void Sample::HandleTouchBegin(StringHash /*eventType*/, VariantMap& eventData)
  341. {
  342. // On some platforms like Windows the presence of touch input can only be detected dynamically
  343. InitTouchInput();
  344. UnsubscribeFromEvent("TouchBegin");
  345. }
  346. // If the user clicks the canvas, attempt to switch to relative mouse mode on web platform
  347. void Sample::HandleMouseModeRequest(StringHash /*eventType*/, VariantMap& eventData)
  348. {
  349. Console* console = GetSubsystem<Console>();
  350. if (console && console->IsVisible())
  351. return;
  352. Input* input = GetSubsystem<Input>();
  353. if (useMouseMode_ == MM_ABSOLUTE)
  354. input->SetMouseVisible(false);
  355. else if (useMouseMode_ == MM_FREE)
  356. input->SetMouseVisible(true);
  357. input->SetMouseMode(useMouseMode_);
  358. }
  359. void Sample::HandleMouseModeChange(StringHash /*eventType*/, VariantMap& eventData)
  360. {
  361. Input* input = GetSubsystem<Input>();
  362. bool mouseLocked = eventData[MouseModeChanged::P_MOUSELOCKED].GetBool();
  363. input->SetMouseVisible(!mouseLocked);
  364. }