1
0

ccUtils.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /****************************************************************************
  2. Copyright (c) 2010 cocos2d-x.org
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "base/ccUtils.h"
  22. #include <cmath>
  23. #include <stdlib.h>
  24. #include "md5/md5.h"
  25. #include "base/CCDirector.h"
  26. #include "base/CCAsyncTaskPool.h"
  27. #include "base/CCEventDispatcher.h"
  28. #include "base/base64.h"
  29. #include "renderer/CCCustomCommand.h"
  30. #include "renderer/CCRenderer.h"
  31. #include "renderer/CCTextureCache.h"
  32. #include "platform/CCImage.h"
  33. #include "platform/CCFileUtils.h"
  34. #include "2d/CCSprite.h"
  35. #include "2d/CCRenderTexture.h"
  36. NS_CC_BEGIN
  37. int ccNextPOT(int x)
  38. {
  39. x = x - 1;
  40. x = x | (x >> 1);
  41. x = x | (x >> 2);
  42. x = x | (x >> 4);
  43. x = x | (x >> 8);
  44. x = x | (x >>16);
  45. return x + 1;
  46. }
  47. namespace utils
  48. {
  49. /**
  50. * Capture screen implementation, don't use it directly.
  51. */
  52. void onCaptureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename)
  53. {
  54. static bool startedCapture = false;
  55. if (startedCapture)
  56. {
  57. CCLOG("Screen capture is already working");
  58. if (afterCaptured)
  59. {
  60. afterCaptured(false, filename);
  61. }
  62. return;
  63. }
  64. else
  65. {
  66. startedCapture = true;
  67. }
  68. auto glView = Director::getInstance()->getOpenGLView();
  69. auto frameSize = glView->getFrameSize();
  70. #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
  71. frameSize = frameSize * glView->getFrameZoomFactor() * glView->getRetinaFactor();
  72. #endif
  73. int width = static_cast<int>(frameSize.width);
  74. int height = static_cast<int>(frameSize.height);
  75. bool succeed = false;
  76. std::string outputFile = "";
  77. do
  78. {
  79. std::shared_ptr<GLubyte> buffer(new GLubyte[width * height * 4], [](GLubyte* p){ CC_SAFE_DELETE_ARRAY(p); });
  80. if (!buffer)
  81. {
  82. break;
  83. }
  84. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  85. glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer.get());
  86. std::shared_ptr<GLubyte> flippedBuffer(new GLubyte[width * height * 4], [](GLubyte* p) { CC_SAFE_DELETE_ARRAY(p); });
  87. if (!flippedBuffer)
  88. {
  89. break;
  90. }
  91. for (int row = 0; row < height; ++row)
  92. {
  93. memcpy(flippedBuffer.get() + (height - row - 1) * width * 4, buffer.get() + row * width * 4, width * 4);
  94. }
  95. Image* image = new (std::nothrow) Image;
  96. if (image)
  97. {
  98. image->initWithRawData(flippedBuffer.get(), width * height * 4, width, height, 8);
  99. if (FileUtils::getInstance()->isAbsolutePath(filename))
  100. {
  101. outputFile = filename;
  102. }
  103. else
  104. {
  105. CCASSERT(filename.find("/") == std::string::npos, "The existence of a relative path is not guaranteed!");
  106. outputFile = FileUtils::getInstance()->getWritablePath() + filename;
  107. }
  108. // Save image in AsyncTaskPool::TaskType::TASK_IO thread, and call afterCaptured in mainThread
  109. static bool succeedSaveToFile = false;
  110. std::function<void(void*)> mainThread = [afterCaptured, outputFile](void* /*param*/)
  111. {
  112. if (afterCaptured)
  113. {
  114. afterCaptured(succeedSaveToFile, outputFile);
  115. }
  116. startedCapture = false;
  117. };
  118. AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_IO, mainThread, nullptr, [image, outputFile]()
  119. {
  120. succeedSaveToFile = image->saveToFile(outputFile);
  121. delete image;
  122. });
  123. }
  124. else
  125. {
  126. CCLOG("Malloc Image memory failed!");
  127. if (afterCaptured)
  128. {
  129. afterCaptured(succeed, outputFile);
  130. }
  131. startedCapture = false;
  132. }
  133. } while (0);
  134. }
  135. /*
  136. * Capture screen interface
  137. */
  138. static EventListenerCustom* s_captureScreenListener;
  139. static CustomCommand s_captureScreenCommand;
  140. void captureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename)
  141. {
  142. if (s_captureScreenListener)
  143. {
  144. CCLOG("Warning: CaptureScreen has been called already, don't call more than once in one frame.");
  145. return;
  146. }
  147. s_captureScreenCommand.init(std::numeric_limits<float>::max());
  148. s_captureScreenCommand.func = std::bind(onCaptureScreen, afterCaptured, filename);
  149. s_captureScreenListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_AFTER_DRAW, [](EventCustom* /*event*/) {
  150. auto director = Director::getInstance();
  151. director->getEventDispatcher()->removeEventListener((EventListener*)(s_captureScreenListener));
  152. s_captureScreenListener = nullptr;
  153. director->getRenderer()->addCommand(&s_captureScreenCommand);
  154. director->getRenderer()->render();
  155. });
  156. }
  157. Image* captureNode(Node* startNode, float scale)
  158. { // The best snapshot API, support Scene and any Node
  159. auto& size = startNode->getContentSize();
  160. Director::getInstance()->setNextDeltaTimeZero(true);
  161. RenderTexture* finalRtx = nullptr;
  162. auto rtx = RenderTexture::create(size.width, size.height, Texture2D::PixelFormat::RGBA8888, GL_DEPTH24_STENCIL8);
  163. // rtx->setKeepMatrix(true);
  164. Point savedPos = startNode->getPosition();
  165. Point anchor;
  166. if (!startNode->isIgnoreAnchorPointForPosition()) {
  167. anchor = startNode->getAnchorPoint();
  168. }
  169. startNode->setPosition(Point(size.width * anchor.x, size.height * anchor.y));
  170. rtx->begin();
  171. startNode->visit();
  172. rtx->end();
  173. startNode->setPosition(savedPos);
  174. if (std::abs(scale - 1.0f) < 1e-6f/* no scale */)
  175. finalRtx = rtx;
  176. else {
  177. /* scale */
  178. auto finalRect = Rect(0, 0, size.width, size.height);
  179. Sprite *sprite = Sprite::createWithTexture(rtx->getSprite()->getTexture(), finalRect);
  180. sprite->setAnchorPoint(Point(0, 0));
  181. sprite->setFlippedY(true);
  182. finalRtx = RenderTexture::create(size.width * scale, size.height * scale, Texture2D::PixelFormat::RGBA8888, GL_DEPTH24_STENCIL8);
  183. sprite->setScale(scale); // or use finalRtx->setKeepMatrix(true);
  184. finalRtx->begin();
  185. sprite->visit();
  186. finalRtx->end();
  187. }
  188. Director::getInstance()->getRenderer()->render();
  189. return finalRtx->newImage();
  190. }
  191. std::vector<Node*> findChildren(const Node &node, const std::string &name)
  192. {
  193. std::vector<Node*> vec;
  194. node.enumerateChildren(name, [&vec](Node* nodeFound) -> bool {
  195. vec.push_back(nodeFound);
  196. return false;
  197. });
  198. return vec;
  199. }
  200. #define MAX_ITOA_BUFFER_SIZE 256
  201. double atof(const char* str)
  202. {
  203. if (str == nullptr)
  204. {
  205. return 0.0;
  206. }
  207. char buf[MAX_ITOA_BUFFER_SIZE];
  208. strncpy(buf, str, MAX_ITOA_BUFFER_SIZE);
  209. // strip string, only remain 7 numbers after '.'
  210. char* dot = strchr(buf, '.');
  211. if (dot != nullptr && dot - buf + 8 < MAX_ITOA_BUFFER_SIZE)
  212. {
  213. dot[8] = '\0';
  214. }
  215. return ::atof(buf);
  216. }
  217. double gettime()
  218. {
  219. struct timeval tv;
  220. gettimeofday(&tv, nullptr);
  221. return (double)tv.tv_sec + (double)tv.tv_usec/1000000;
  222. }
  223. long long getTimeInMilliseconds()
  224. {
  225. struct timeval tv;
  226. gettimeofday (&tv, nullptr);
  227. return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
  228. }
  229. Rect getCascadeBoundingBox(Node *node)
  230. {
  231. Rect cbb;
  232. Size contentSize = node->getContentSize();
  233. // check all children bounding box, get maximize box
  234. Node* child = nullptr;
  235. bool merge = false;
  236. for(auto object : node->getChildren())
  237. {
  238. child = dynamic_cast<Node*>(object);
  239. if (!child->isVisible()) continue;
  240. const Rect box = getCascadeBoundingBox(child);
  241. if (box.size.width <= 0 || box.size.height <= 0) continue;
  242. if (!merge)
  243. {
  244. cbb = box;
  245. merge = true;
  246. }
  247. else
  248. {
  249. cbb.merge(box);
  250. }
  251. }
  252. // merge content size
  253. if (contentSize.width > 0 && contentSize.height > 0)
  254. {
  255. const Rect box = RectApplyAffineTransform(Rect(0, 0, contentSize.width, contentSize.height), node->getNodeToWorldAffineTransform());
  256. if (!merge)
  257. {
  258. cbb = box;
  259. }
  260. else
  261. {
  262. cbb.merge(box);
  263. }
  264. }
  265. return cbb;
  266. }
  267. Sprite* createSpriteFromBase64Cached(const char* base64String, const char* key)
  268. {
  269. Texture2D* texture = Director::getInstance()->getTextureCache()->getTextureForKey(key);
  270. if (texture == nullptr)
  271. {
  272. unsigned char* decoded;
  273. int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded);
  274. Image *image = new (std::nothrow) Image();
  275. bool imageResult = image->initWithImageData(decoded, length);
  276. CCASSERT(imageResult, "Failed to create image from base64!");
  277. free(decoded);
  278. if (!imageResult) {
  279. CC_SAFE_RELEASE_NULL(image);
  280. return nullptr;
  281. }
  282. texture = Director::getInstance()->getTextureCache()->addImage(image, key);
  283. image->release();
  284. }
  285. Sprite* sprite = Sprite::createWithTexture(texture);
  286. return sprite;
  287. }
  288. Sprite* createSpriteFromBase64(const char* base64String)
  289. {
  290. unsigned char* decoded;
  291. int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded);
  292. Image *image = new (std::nothrow) Image();
  293. bool imageResult = image->initWithImageData(decoded, length);
  294. CCASSERT(imageResult, "Failed to create image from base64!");
  295. free(decoded);
  296. if (!imageResult) {
  297. CC_SAFE_RELEASE_NULL(image);
  298. return nullptr;
  299. }
  300. Texture2D *texture = new (std::nothrow) Texture2D();
  301. texture->initWithImage(image);
  302. texture->setAliasTexParameters();
  303. image->release();
  304. Sprite* sprite = Sprite::createWithTexture(texture);
  305. texture->release();
  306. return sprite;
  307. }
  308. Node* findChild(Node* levelRoot, const std::string& name)
  309. {
  310. if (levelRoot == nullptr || name.empty())
  311. return nullptr;
  312. // Find this node
  313. auto target = levelRoot->getChildByName(name);
  314. if (target != nullptr)
  315. return target;
  316. // Find recursively
  317. for (auto& child : levelRoot->getChildren())
  318. {
  319. target = findChild(child, name);
  320. if (target != nullptr)
  321. return target;
  322. }
  323. return nullptr;
  324. }
  325. Node* findChild(Node* levelRoot, int tag)
  326. {
  327. if (levelRoot == nullptr || tag == Node::INVALID_TAG)
  328. return nullptr;
  329. // Find this node
  330. auto target = levelRoot->getChildByTag(tag);
  331. if (target != nullptr)
  332. return target;
  333. // Find recursively
  334. for (auto& child : levelRoot->getChildren())
  335. {
  336. target = findChild(child, tag);
  337. if (target != nullptr)
  338. return target;
  339. }
  340. return nullptr;
  341. }
  342. std::string getFileMD5Hash(const std::string &filename)
  343. {
  344. static const unsigned int MD5_DIGEST_LENGTH = 16;
  345. Data d;
  346. FileUtils::getInstance()->getContents(filename, &d);
  347. md5_state_t state;
  348. md5_byte_t digest[MD5_DIGEST_LENGTH];
  349. char hexOutput[(MD5_DIGEST_LENGTH << 1) + 1] = {0};
  350. md5_init(&state);
  351. md5_append(&state, (const md5_byte_t *)d.getBytes(), (int)d.getSize());
  352. md5_finish(&state, digest);
  353. for (int di = 0; di < 16; ++di)
  354. sprintf(hexOutput + di * 2, "%02x", digest[di]);
  355. return hexOutput;
  356. }
  357. }
  358. NS_CC_END