Sample.inl 14 KB

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