Sample.inl 14 KB

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