Sample.inl 15 KB

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