Runtime.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /****************************************************************************
  2. Copyright (c) 2013 cocos2d-x.org
  3. http://www.cocos2d-x.org
  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. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #include "Runtime.h"
  21. #include "FileServer.h"
  22. #include "ConnectWaitLayer.h"
  23. #include "ConsoleCommand.h"
  24. #include "cocos2d.h"
  25. #include "ConfigParser.h"
  26. #include "RuntimeCCSImpl.h" // TODO: move to ide-support
  27. #if ((CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC))
  28. #include "DeviceEx.h"
  29. #include "network/CCHTTPRequest.h"
  30. #include "xxhash/xxhash.h"
  31. #endif
  32. std::string g_projectPath;
  33. void recvBuf(int fd, char *pbuf, unsigned long bufsize)
  34. {
  35. unsigned long leftLength = bufsize;
  36. while (leftLength != 0)
  37. {
  38. size_t recvlen = recv(fd, pbuf + bufsize - leftLength, leftLength ,0);
  39. if (recvlen <= 0)
  40. {
  41. usleep(1);
  42. continue;
  43. }
  44. leftLength -= recvlen;
  45. }
  46. }
  47. void sendBuf(int fd, const char *pbuf, unsigned long bufsize)
  48. {
  49. unsigned long leftLength = bufsize;
  50. while (leftLength != 0)
  51. {
  52. size_t sendlen = send(fd, pbuf + bufsize - leftLength, leftLength ,0);
  53. if (sendlen <= 0)
  54. {
  55. usleep(1);
  56. continue;
  57. }
  58. leftLength -= sendlen;
  59. }
  60. }
  61. std::string& replaceAll(std::string& str, const std::string& old_value, const std::string& new_value)
  62. {
  63. size_t start = 0;
  64. while(true)
  65. {
  66. size_t pos = 0;
  67. if((pos = str.find(old_value, start)) != std::string::npos) {
  68. str.replace(pos, old_value.length(), new_value);
  69. start = pos + new_value.length();
  70. }
  71. else break;
  72. }
  73. return str;
  74. }
  75. const char* getRuntimeVersion()
  76. {
  77. return "2.0";
  78. }
  79. //////////////////////// Loader ////////////////////
  80. void resetDesignResolution()
  81. {
  82. cocos2d::Size size = ConfigParser::getInstance()->getInitViewSize();
  83. if (!ConfigParser::getInstance()->isLanscape())
  84. {
  85. if (size.width > size.height)
  86. std::swap(size.width, size.height);
  87. }
  88. else
  89. {
  90. if (size.width < size.height)
  91. std::swap(size.width, size.height);
  92. }
  93. Director::getInstance()->getOpenGLView()->setDesignResolutionSize(size.width, size.height, ResolutionPolicy::EXACT_FIT);
  94. }
  95. //
  96. // RuntimeEngine
  97. //
  98. RuntimeEngine::RuntimeEngine()
  99. : _runtime(nullptr)
  100. , _eventTrackingEnable(false)
  101. , _launchEvent("empty")
  102. {
  103. }
  104. RuntimeEngine* RuntimeEngine::getInstance()
  105. {
  106. static RuntimeEngine *instance = nullptr;
  107. if (!instance)
  108. {
  109. instance = new RuntimeEngine();
  110. instance->addRuntime(RuntimeCCSImpl::create(), kRuntimeEngineCCS);
  111. }
  112. return instance;
  113. }
  114. void RuntimeEngine::setupRuntime()
  115. {
  116. //
  117. // 1. get project type fron config.json
  118. // 2. init Lua / Js runtime
  119. //
  120. updateConfigParser();
  121. auto entryFile = ConfigParser::getInstance()->getEntryFile();
  122. #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
  123. ConfigParser::getInstance()->readConfig();
  124. entryFile = ConfigParser::getInstance()->getEntryFile();
  125. #endif
  126. // Lua
  127. if ((entryFile.rfind(".lua") != std::string::npos) ||
  128. (entryFile.rfind(".luac") != std::string::npos))
  129. {
  130. _launchEvent = "lua";
  131. _runtime = _runtimes[kRuntimeEngineLua];
  132. }
  133. // Js
  134. else if ((entryFile.rfind(".js") != std::string::npos) ||
  135. (entryFile.rfind(".jsc") != std::string::npos))
  136. {
  137. _launchEvent = "js";
  138. _runtime = _runtimes[kRuntimeEngineJs];
  139. }
  140. // csb
  141. else if ((entryFile.rfind(".csb") != std::string::npos))
  142. {
  143. _launchEvent = "ccs";
  144. _runtime = _runtimes[kRuntimeEngineCCS];
  145. }
  146. // csd
  147. else if ((entryFile.rfind(".csd") != std::string::npos))
  148. {
  149. _launchEvent = "ccs";
  150. _runtime = _runtimes[kRuntimeEngineCCS];
  151. }
  152. }
  153. void RuntimeEngine::setProjectConfig(const ProjectConfig &config)
  154. {
  155. _project = config;
  156. setProjectPath(_project.getProjectDir());
  157. }
  158. const ProjectConfig &RuntimeEngine::getProjectConfig()
  159. {
  160. return _project;
  161. }
  162. void RuntimeEngine::setProjectPath(const std::string &workPath)
  163. {
  164. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
  165. vector<std::string> searchPathArray = FileUtils::getInstance()->getSearchPaths();
  166. if (workPath.empty())
  167. {
  168. std::string appPath = std::string("");
  169. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
  170. TCHAR szAppDir[MAX_PATH] = { 0 };
  171. if (GetModuleFileName(NULL, szAppDir, MAX_PATH))
  172. {
  173. int nEnd = 0;
  174. for (int i = 0; szAppDir[i]; i++)
  175. {
  176. if (szAppDir[i] == '\\')
  177. nEnd = i;
  178. }
  179. szAppDir[nEnd] = 0;
  180. int iLen = 2 * wcslen(szAppDir);
  181. char* chRtn = new char[iLen + 1];
  182. wcstombs(chRtn, szAppDir, iLen + 1);
  183. std::string strPath = chRtn;
  184. delete[] chRtn;
  185. chRtn = NULL;
  186. char fuldir[MAX_PATH] = { 0 };
  187. _fullpath(fuldir, strPath.c_str(), MAX_PATH);
  188. appPath = fuldir;
  189. }
  190. #elif (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
  191. appPath.append("/../../../");
  192. #endif
  193. appPath = replaceAll(appPath, "\\", "/");
  194. g_projectPath = appPath;
  195. }
  196. else
  197. {
  198. g_projectPath = workPath;
  199. }
  200. // add project's root directory to search path
  201. searchPathArray.insert(searchPathArray.begin(), g_projectPath);
  202. if (!_project.getFirstSearchPath().empty())
  203. {
  204. searchPathArray.insert(searchPathArray.begin(), _project.getFirstSearchPath().begin(), _project.getFirstSearchPath().end());
  205. }
  206. // add writable path to search path
  207. searchPathArray.insert(searchPathArray.begin(), FileServer::getShareInstance()->getWritePath());
  208. FileUtils::getInstance()->setSearchPaths(searchPathArray);
  209. #endif
  210. }
  211. void RuntimeEngine::startScript(const std::string &args)
  212. {
  213. resetDesignResolution();
  214. if (_runtime)
  215. {
  216. _runtime->startScript(args);
  217. }
  218. trackLaunchEvent();
  219. }
  220. void RuntimeEngine::start()
  221. {
  222. #if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
  223. _project.setDebuggerType(kCCRuntimeDebuggerCodeIDE);
  224. #endif
  225. // set search path
  226. string path = FileUtils::getInstance()->fullPathForFilename(_project.getScriptFileRealPath().c_str());
  227. size_t pos;
  228. while ((pos = path.find_first_of("\\")) != std::string::npos)
  229. {
  230. path.replace(pos, 1, "/");
  231. }
  232. size_t p = path.find_last_of("/");
  233. string workdir;
  234. if (p != path.npos)
  235. {
  236. workdir = path.substr(0, p);
  237. FileUtils::getInstance()->addSearchPath(workdir);
  238. }
  239. // update search pathes
  240. FileUtils::getInstance()->addSearchPath(_project.getProjectDir());
  241. auto &customizedPathes = _project.getSearchPath();
  242. for (auto &path : customizedPathes)
  243. {
  244. FileUtils::getInstance()->addSearchPath(path);
  245. }
  246. //
  247. if (_project.getDebuggerType() == kCCRuntimeDebuggerNone)
  248. {
  249. setupRuntime();
  250. startScript("");
  251. }
  252. else
  253. {
  254. startNetwork();
  255. }
  256. }
  257. void RuntimeEngine::end()
  258. {
  259. if (_runtime)
  260. {
  261. _runtime->end();
  262. }
  263. // delete all runtimes
  264. for (auto it = _runtimes.begin(); it != _runtimes.end(); it++)
  265. {
  266. CC_SAFE_DELETE(it->second);
  267. }
  268. ConsoleCommand::purge();
  269. FileServer::getShareInstance()->stop();
  270. ConfigParser::purge();
  271. // FileServer::purge();
  272. }
  273. void RuntimeEngine::setEventTrackingEnable(bool enable)
  274. {
  275. _eventTrackingEnable = enable;
  276. }
  277. void RuntimeEngine::addRuntime(RuntimeProtocol *runtime, int type)
  278. {
  279. if (_runtimes.find(type) == _runtimes.end())
  280. {
  281. _runtimes.insert(std::make_pair(type, runtime));
  282. }
  283. else
  284. {
  285. CCLOG("RuntimeEngine already has Runtime type %d.", type);
  286. }
  287. }
  288. RuntimeProtocol* RuntimeEngine::getRuntime()
  289. {
  290. return _runtime;
  291. }
  292. //
  293. // private
  294. //
  295. void RuntimeEngine::showUI()
  296. {
  297. auto scene = Scene::create();
  298. auto connectLayer = new ConnectWaitLayer();
  299. connectLayer->autorelease();
  300. auto director = Director::getInstance();
  301. scene->addChild(connectLayer);
  302. director->runWithScene(scene);
  303. }
  304. bool RuntimeEngine::startNetwork()
  305. {
  306. ConsoleCommand::getShareInstance()->init();
  307. showUI();
  308. return true;
  309. }
  310. void RuntimeEngine::updateConfigParser()
  311. {
  312. // set entry file
  313. auto parser = ConfigParser::getInstance();
  314. string entryFile(_project.getScriptFileRealPath());
  315. if (entryFile.find(_project.getProjectDir()) != string::npos)
  316. {
  317. entryFile.erase(0, _project.getProjectDir().length());
  318. }
  319. std::replace(entryFile.begin(), entryFile.end(), '\\', '/');
  320. parser->setEntryFile(entryFile);
  321. parser->setBindAddress(_project.getBindAddress());
  322. }
  323. //
  324. // NOTE: track event on windows / mac platform
  325. //
  326. void RuntimeEngine::trackEvent(const std::string &eventName)
  327. {
  328. if (!_eventTrackingEnable)
  329. {
  330. return ;
  331. }
  332. #if ((CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC))
  333. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
  334. const char *platform = "win";
  335. #elif (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
  336. const char *platform = "mac";
  337. #else
  338. const char *platform = "UNKNOWN";
  339. #endif
  340. char cidBuf[64] = {0};
  341. auto guid = player::DeviceEx::getInstance()->getUserGUID();
  342. snprintf(cidBuf, sizeof(cidBuf), "%x", XXH32(guid.c_str(), (int)guid.length(), 0));
  343. auto request = extra::HTTPRequest::createWithUrl(NULL,
  344. "http://www.google-analytics.com/collect",
  345. kCCHTTPRequestMethodPOST);
  346. request->addPOSTValue("v", "1");
  347. request->addPOSTValue("tid", "UA-58200293-1");
  348. request->addPOSTValue("cid", cidBuf);
  349. request->addPOSTValue("t", "event");
  350. request->addPOSTValue("an", "simulator");
  351. request->addPOSTValue("av", cocos2dVersion());
  352. request->addPOSTValue("ec", platform);
  353. request->addPOSTValue("ea", eventName.c_str());
  354. request->start();
  355. #endif // ((CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC))
  356. }
  357. void RuntimeEngine::trackLaunchEvent()
  358. {
  359. trackEvent(_launchEvent);
  360. }