CCApplication-win32.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  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 "platform/CCApplication.h"
  23. #include "platform/CCStdC.h" // need it to include Windows.h
  24. #include <algorithm>
  25. #include <shellapi.h>
  26. #include <MMSystem.h>
  27. #include "platform/CCFileUtils.h"
  28. #include "platform/desktop/CCGLView-desktop.h"
  29. #include "renderer/gfx/DeviceGraphics.h"
  30. #include "scripting/js-bindings/jswrapper/SeApi.h"
  31. #include "scripting/js-bindings/event/EventDispatcher.h"
  32. #include "base/CCScheduler.h"
  33. #include "base/CCAutoreleasePool.h"
  34. #include "base/CCGLUtils.h"
  35. #include "audio/include/AudioEngine.h"
  36. #define CAST_VIEW(view) ((GLView*)view)
  37. namespace
  38. {
  39. /**
  40. @brief This function changes the PVRFrame show/hide setting in register.
  41. @param bEnable If true show the PVRFrame window, otherwise hide.
  42. */
  43. void PVRFrameEnableControlWindow(bool bEnable)
  44. {
  45. HKEY hKey = 0;
  46. // Open PVRFrame control key, if not exist create it.
  47. if(ERROR_SUCCESS != RegCreateKeyExW(HKEY_CURRENT_USER,
  48. L"Software\\Imagination Technologies\\PVRVFRame\\STARTUP\\",
  49. 0,
  50. 0,
  51. REG_OPTION_NON_VOLATILE,
  52. KEY_ALL_ACCESS,
  53. 0,
  54. &hKey,
  55. nullptr))
  56. {
  57. return;
  58. }
  59. const WCHAR* wszValue = L"hide_gui";
  60. const WCHAR* wszNewData = (bEnable) ? L"NO" : L"YES";
  61. WCHAR wszOldData[256] = {0};
  62. DWORD dwSize = sizeof(wszOldData);
  63. LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, nullptr, (LPBYTE)wszOldData, &dwSize);
  64. if (ERROR_FILE_NOT_FOUND == status // the key not exist
  65. || (ERROR_SUCCESS == status // or the hide_gui value is exist
  66. && 0 != wcscmp(wszNewData, wszOldData))) // but new data and old data not equal
  67. {
  68. dwSize = sizeof(WCHAR) * (wcslen(wszNewData) + 1);
  69. RegSetValueEx(hKey, wszValue, 0, REG_SZ, (const BYTE *)wszNewData, dwSize);
  70. }
  71. RegCloseKey(hKey);
  72. }
  73. bool setCanvasCallback(se::Object* global)
  74. {
  75. auto viewSize = cocos2d::Application::getInstance()->getViewSize();
  76. se::ScriptEngine* se = se::ScriptEngine::getInstance();
  77. uint8_t devicePixelRatio = cocos2d::Application::getInstance()->getScreenScale();
  78. char commandBuf[200] = {0};
  79. sprintf(commandBuf, "window.innerWidth = %d; window.innerHeight = %d;",
  80. (int)(viewSize.x / devicePixelRatio),
  81. (int)(viewSize.y / devicePixelRatio));
  82. se->evalString(commandBuf);
  83. cocos2d::ccViewport(0, 0, viewSize.x, viewSize.y);
  84. glDepthMask(GL_TRUE);
  85. return true;
  86. }
  87. }
  88. NS_CC_BEGIN
  89. Application* Application::_instance = nullptr;
  90. std::shared_ptr<Scheduler> Application::_scheduler = nullptr;
  91. Application::Application(const std::string& name, int width, int height)
  92. {
  93. Application::_instance = this;
  94. _scheduler = std::make_shared<Scheduler>();
  95. createView(name, width, height);
  96. _renderTexture = new RenderTexture(width, height);
  97. EventDispatcher::init();
  98. se::ScriptEngine::getInstance();
  99. }
  100. Application::~Application()
  101. {
  102. #if USE_AUDIO
  103. AudioEngine::end();
  104. #endif
  105. EventDispatcher::destroy();
  106. se::ScriptEngine::destroyInstance();
  107. delete CAST_VIEW(_view);
  108. _view = nullptr;
  109. delete _renderTexture;
  110. _renderTexture = nullptr;
  111. Application::_instance = nullptr;
  112. }
  113. const cocos2d::Vec2& Application::getViewSize() const
  114. {
  115. return _viewSize;
  116. }
  117. void Application::updateViewSize(int width, int height)
  118. {
  119. _viewSize.x = width;
  120. _viewSize.y = height;
  121. }
  122. void Application::start()
  123. {
  124. if (!_view)
  125. return;
  126. PVRFrameEnableControlWindow(false);
  127. ///////////////////////////////////////////////////////////////////////////
  128. /////////////// changing timer resolution
  129. ///////////////////////////////////////////////////////////////////////////
  130. UINT TARGET_RESOLUTION = 1; // 1 millisecond target resolution
  131. TIMECAPS tc;
  132. UINT wTimerRes = 0;
  133. if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(TIMECAPS)))
  134. {
  135. wTimerRes = std::min(std::max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
  136. timeBeginPeriod(wTimerRes);
  137. }
  138. float dt = 0.f;
  139. const DWORD _16ms = 16;
  140. // Main message loop:
  141. LARGE_INTEGER nFreq;
  142. LARGE_INTEGER nLast;
  143. LARGE_INTEGER nNow;
  144. LONGLONG actualInterval = 0LL; // actual frame internal
  145. LONGLONG desiredInterval = 0LL; // desired frame internal, 1 / fps
  146. LONG waitMS = 0L;
  147. QueryPerformanceCounter(&nLast);
  148. QueryPerformanceFrequency(&nFreq);
  149. se::ScriptEngine* se = se::ScriptEngine::getInstance();
  150. while (!CAST_VIEW(_view)->windowShouldClose())
  151. {
  152. desiredInterval = (LONGLONG)(1.0 / _fps * nFreq.QuadPart);
  153. if (!_isStarted)
  154. {
  155. auto scheduler = Application::getInstance()->getScheduler();
  156. scheduler->removeAllFunctionsToBePerformedInCocosThread();
  157. scheduler->unscheduleAll();
  158. se::ScriptEngine::getInstance()->cleanup();
  159. cocos2d::PoolManager::getInstance()->getCurrentPool()->clear();
  160. cocos2d::EventDispatcher::init();
  161. ccInvalidateStateCache();
  162. se->addRegisterCallback(setCanvasCallback);
  163. if(!applicationDidFinishLaunching())
  164. return;
  165. _isStarted = true;
  166. }
  167. // should be invoked at the begin of rendering a frame
  168. if (_isDownsampleEnabled)
  169. _renderTexture->prepare();
  170. CAST_VIEW(_view)->pollEvents();
  171. if(_isStarted)
  172. {
  173. QueryPerformanceCounter(&nNow);
  174. actualInterval = nNow.QuadPart - nLast.QuadPart;
  175. if (actualInterval >= desiredInterval)
  176. {
  177. nLast.QuadPart = nNow.QuadPart;
  178. dt = (float)actualInterval / nFreq.QuadPart;
  179. _scheduler->update(dt);
  180. EventDispatcher::dispatchTickEvent(dt);
  181. if (_isDownsampleEnabled)
  182. _renderTexture->draw();
  183. CAST_VIEW(_view)->swapBuffers();
  184. PoolManager::getInstance()->getCurrentPool()->clear();
  185. }
  186. else
  187. {
  188. // The precision of timer on Windows is set to highest (1ms) by 'timeBeginPeriod' from above code,
  189. // but it's still not precise enough. For example, if the precision of timer is 1ms,
  190. // Sleep(3) may make a sleep of 2ms or 4ms. Therefore, we subtract 1ms here to make Sleep time shorter.
  191. // If 'waitMS' is equal or less than 1ms, don't sleep and run into next loop to
  192. // boost CPU to next frame accurately.
  193. waitMS = (desiredInterval - actualInterval) * 1000LL / nFreq.QuadPart - 1L;
  194. if (waitMS > 1L)
  195. Sleep(waitMS);
  196. }
  197. }
  198. else
  199. {
  200. Sleep(_16ms);
  201. }
  202. }
  203. if (wTimerRes != 0)
  204. timeEndPeriod(wTimerRes);
  205. }
  206. void Application::restart()
  207. {
  208. _isStarted = false;
  209. }
  210. void Application::end()
  211. {
  212. glfwSetWindowShouldClose(CAST_VIEW(_view)->getGLFWWindow(), 1);
  213. }
  214. void Application::setPreferredFramesPerSecond(int fps)
  215. {
  216. _fps = fps;
  217. }
  218. Application::LanguageType Application::getCurrentLanguage() const
  219. {
  220. LanguageType ret = LanguageType::ENGLISH;
  221. LCID localeID = GetUserDefaultLCID();
  222. unsigned short primaryLanguageID = localeID & 0xFF;
  223. switch (primaryLanguageID)
  224. {
  225. case LANG_CHINESE:
  226. ret = LanguageType::CHINESE;
  227. break;
  228. case LANG_ENGLISH:
  229. ret = LanguageType::ENGLISH;
  230. break;
  231. case LANG_FRENCH:
  232. ret = LanguageType::FRENCH;
  233. break;
  234. case LANG_ITALIAN:
  235. ret = LanguageType::ITALIAN;
  236. break;
  237. case LANG_GERMAN:
  238. ret = LanguageType::GERMAN;
  239. break;
  240. case LANG_SPANISH:
  241. ret = LanguageType::SPANISH;
  242. break;
  243. case LANG_DUTCH:
  244. ret = LanguageType::DUTCH;
  245. break;
  246. case LANG_RUSSIAN:
  247. ret = LanguageType::RUSSIAN;
  248. break;
  249. case LANG_KOREAN:
  250. ret = LanguageType::KOREAN;
  251. break;
  252. case LANG_JAPANESE:
  253. ret = LanguageType::JAPANESE;
  254. break;
  255. case LANG_HUNGARIAN:
  256. ret = LanguageType::HUNGARIAN;
  257. break;
  258. case LANG_PORTUGUESE:
  259. ret = LanguageType::PORTUGUESE;
  260. break;
  261. case LANG_ARABIC:
  262. ret = LanguageType::ARABIC;
  263. break;
  264. case LANG_NORWEGIAN:
  265. ret = LanguageType::NORWEGIAN;
  266. break;
  267. case LANG_POLISH:
  268. ret = LanguageType::POLISH;
  269. break;
  270. case LANG_TURKISH:
  271. ret = LanguageType::TURKISH;
  272. break;
  273. case LANG_UKRAINIAN:
  274. ret = LanguageType::UKRAINIAN;
  275. break;
  276. case LANG_ROMANIAN:
  277. ret = LanguageType::ROMANIAN;
  278. break;
  279. case LANG_BULGARIAN:
  280. ret = LanguageType::BULGARIAN;
  281. break;
  282. }
  283. return ret;
  284. }
  285. std::string Application::getCurrentLanguageCode() const
  286. {
  287. LANGID lid = GetUserDefaultUILanguage();
  288. const LCID locale_id = MAKELCID(lid, SORT_DEFAULT);
  289. int length = GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, nullptr, 0);
  290. char *tempCode = new char[length];
  291. GetLocaleInfoA(locale_id, LOCALE_SISO639LANGNAME, tempCode, length);
  292. std::string code = tempCode;
  293. delete tempCode;
  294. return code;
  295. }
  296. bool Application::isDisplayStats() {
  297. se::AutoHandleScope hs;
  298. se::Value ret;
  299. char commandBuf[100] = "cc.debug.isDisplayStats();";
  300. se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret);
  301. return ret.toBoolean();
  302. }
  303. void Application::setDisplayStats(bool isShow) {
  304. se::AutoHandleScope hs;
  305. char commandBuf[100] = {0};
  306. sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false");
  307. se::ScriptEngine::getInstance()->evalString(commandBuf);
  308. }
  309. float Application::getScreenScale() const
  310. {
  311. return CAST_VIEW(_view)->getScale();
  312. }
  313. GLint Application::getMainFBO() const
  314. {
  315. return CAST_VIEW(_view)->getMainFBO();
  316. }
  317. Application::Platform Application::getPlatform() const
  318. {
  319. return Platform::WINDOWS;
  320. }
  321. bool Application::openURL(const std::string &url)
  322. {
  323. WCHAR *temp = new WCHAR[url.size() + 1];
  324. int wchars_num = MultiByteToWideChar(CP_UTF8, 0, url.c_str(), url.size() + 1, temp, url.size() + 1);
  325. HINSTANCE r = ShellExecuteW(NULL, L"open", temp, NULL, NULL, SW_SHOWNORMAL);
  326. delete[] temp;
  327. return (size_t)r>32;
  328. }
  329. void Application::copyTextToClipboard(const std::string &text)
  330. {
  331. //TODO
  332. }
  333. bool Application::applicationDidFinishLaunching()
  334. {
  335. return true;
  336. }
  337. void Application::onPause()
  338. {
  339. }
  340. void Application::onResume()
  341. {
  342. }
  343. void Application::setMultitouch(bool)
  344. {
  345. }
  346. void Application::onCreateView(PixelFormat& pixelformat, DepthFormat& depthFormat, int& multisamplingCount)
  347. {
  348. pixelformat = PixelFormat::RGBA8;
  349. depthFormat = DepthFormat::DEPTH24_STENCIL8;
  350. multisamplingCount = 0;
  351. }
  352. void Application::createView(const std::string& name, int width, int height)
  353. {
  354. int multisamplingCount = 0;
  355. PixelFormat pixelformat;
  356. DepthFormat depthFormat;
  357. onCreateView(pixelformat,
  358. depthFormat,
  359. multisamplingCount);
  360. _view = new GLView(this, name, 0, 0, width, height, pixelformat, depthFormat, multisamplingCount);
  361. }
  362. std::string Application::getSystemVersion()
  363. {
  364. // REFINE
  365. return std::string("unknown Windows version");
  366. }
  367. NS_CC_END