axmol/cocos/base/ccUtils.cpp

551 lines
15 KiB
C++
Raw Normal View History

2013-10-14 14:56:57 +08:00
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
2013-10-14 14:56:57 +08:00
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
Squashed commit of the following: commit a794d107ad85667e3d754f0b6251fc864dfbf288 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 14:33:49 2014 -0700 Yeah... everything compiles on win32 and wp8 commit 4740be6e4a0d16f742c27996e7ab2c100adc76af Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 13:58:38 2014 -0700 CCIME moved to base and compiles on Android commit ff3e1bf1eb27a01019f4e1b56d1aebbe2d385f72 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 13:02:57 2014 -0700 compiles Ok for Windows Phone 8 commit 8160a4eb2ecdc61b5bd1cf56b90d2da6f11e3ebd Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 12:25:31 2014 -0700 fixes for Windows Phone 8 commit 418197649efc93032aee0adc205e502101cdb53d Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 11:15:13 2014 -0700 Compiles on Win32 commit 08813ed7cf8ac1079ffadeb1ce78ea9e833e1a33 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 10:08:31 2014 -0700 Compiles on linux! commit 118896521e5b335a5257090b6863f1fb2a2002fe Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 09:30:42 2014 -0700 moves cocos/2d/platform -> cocos/platform commit 4fe9319d7717b0c1bccb2db0156eeb86255a89e0 Merge: bd68ec2 511295e Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Fri May 16 08:24:41 2014 -0700 Merge remote-tracking branch 'cocos2d/v3' into files commit bd68ec2f0e3a826d8b2f4b60564ba65ce766bc56 Author: Ricardo Quesada <ricardoquesada@gmail.com> Date: Thu May 15 19:36:23 2014 -0700 files in the correct directory
2014-05-17 05:36:00 +08:00
#include "base/ccUtils.h"
2014-07-14 20:42:08 +08:00
#include <cmath>
2014-07-14 20:42:08 +08:00
#include <stdlib.h>
#include "md5/md5.h"
2014-07-14 20:42:08 +08:00
#include "base/CCDirector.h"
#include "base/CCAsyncTaskPool.h"
#include "base/CCEventDispatcher.h"
#include "base/base64.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCRenderer.h"
2016-06-06 22:32:50 +08:00
#include "renderer/CCTextureCache.h"
2018-09-11 14:39:30 +08:00
#include "renderer/CCRenderState.h"
#include "platform/CCImage.h"
#include "platform/CCFileUtils.h"
#include "2d/CCSprite.h"
#include "2d/CCRenderTexture.h"
2013-10-14 14:56:57 +08:00
NS_CC_BEGIN
2013-10-14 14:56:57 +08:00
2013-12-05 17:19:01 +08:00
int ccNextPOT(int x)
2013-10-14 14:56:57 +08:00
{
x = x - 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >>16);
return x + 1;
}
2014-05-27 14:29:52 +08:00
namespace utils
{
2014-05-27 14:29:52 +08:00
/**
* Capture screen implementation, don't use it directly.
*/
void onCaptureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename)
{
static bool startedCapture = false;
if (startedCapture)
{
CCLOG("Screen capture is already working");
if (afterCaptured)
{
afterCaptured(false, filename);
}
return;
}
else
{
startedCapture = true;
}
auto glView = Director::getInstance()->getOpenGLView();
auto frameSize = glView->getFrameSize();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
frameSize = frameSize * glView->getFrameZoomFactor() * glView->getRetinaFactor();
#endif
int width = static_cast<int>(frameSize.width);
int height = static_cast<int>(frameSize.height);
bool succeed = false;
std::string outputFile = "";
do
{
std::shared_ptr<GLubyte> buffer(new GLubyte[width * height * 4], [](GLubyte* p){ CC_SAFE_DELETE_ARRAY(p); });
if (!buffer)
{
break;
}
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer.get());
std::shared_ptr<GLubyte> flippedBuffer(new GLubyte[width * height * 4], [](GLubyte* p) { CC_SAFE_DELETE_ARRAY(p); });
if (!flippedBuffer)
{
break;
}
for (int row = 0; row < height; ++row)
{
memcpy(flippedBuffer.get() + (height - row - 1) * width * 4, buffer.get() + row * width * 4, width * 4);
}
Image* image = new (std::nothrow) Image;
if (image)
{
image->initWithRawData(flippedBuffer.get(), width * height * 4, width, height, 8);
if (FileUtils::getInstance()->isAbsolutePath(filename))
{
outputFile = filename;
}
else
{
CCASSERT(filename.find("/") == std::string::npos, "The existence of a relative path is not guaranteed!");
outputFile = FileUtils::getInstance()->getWritablePath() + filename;
}
// Save image in AsyncTaskPool::TaskType::TASK_IO thread, and call afterCaptured in mainThread
static bool succeedSaveToFile = false;
std::function<void(void*)> mainThread = [afterCaptured, outputFile](void* /*param*/)
{
if (afterCaptured)
{
afterCaptured(succeedSaveToFile, outputFile);
}
startedCapture = false;
};
AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_IO, std::move(mainThread), nullptr, [image, outputFile]()
{
succeedSaveToFile = image->saveToFile(outputFile);
delete image;
});
}
else
{
CCLOG("Malloc Image memory failed!");
if (afterCaptured)
{
afterCaptured(succeed, outputFile);
}
startedCapture = false;
}
} while (0);
}
2014-05-27 14:29:52 +08:00
/*
* Capture screen interface
*/
static EventListenerCustom* s_captureScreenListener;
static CustomCommand s_captureScreenCommand;
2014-05-27 14:29:52 +08:00
void captureScreen(const std::function<void(bool, const std::string&)>& afterCaptured, const std::string& filename)
{
if (s_captureScreenListener)
{
CCLOG("Warning: CaptureScreen has been called already, don't call more than once in one frame.");
return;
}
s_captureScreenCommand.init(std::numeric_limits<float>::max());
s_captureScreenCommand.func = std::bind(onCaptureScreen, afterCaptured, filename);
s_captureScreenListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_AFTER_DRAW, [](EventCustom* /*event*/) {
auto director = Director::getInstance();
director->getEventDispatcher()->removeEventListener((EventListener*)(s_captureScreenListener));
s_captureScreenListener = nullptr;
director->getRenderer()->addCommand(&s_captureScreenCommand);
director->getRenderer()->render();
});
2014-05-27 14:29:52 +08:00
}
Image* captureNode(Node* startNode, float scale)
{ // The best snapshot API, support Scene and any Node
auto& size = startNode->getContentSize();
Director::getInstance()->setNextDeltaTimeZero(true);
RenderTexture* finalRtx = nullptr;
auto rtx = RenderTexture::create(size.width, size.height, Texture2D::PixelFormat::RGBA8888, GL_DEPTH24_STENCIL8);
// rtx->setKeepMatrix(true);
Point savedPos = startNode->getPosition();
Point anchor;
if (!startNode->isIgnoreAnchorPointForPosition()) {
anchor = startNode->getAnchorPoint();
}
startNode->setPosition(Point(size.width * anchor.x, size.height * anchor.y));
rtx->begin();
startNode->visit();
rtx->end();
startNode->setPosition(savedPos);
if (std::abs(scale - 1.0f) < 1e-6f/* no scale */)
finalRtx = rtx;
else {
/* scale */
auto finalRect = Rect(0, 0, size.width, size.height);
Sprite *sprite = Sprite::createWithTexture(rtx->getSprite()->getTexture(), finalRect);
sprite->setAnchorPoint(Point(0, 0));
sprite->setFlippedY(true);
finalRtx = RenderTexture::create(size.width * scale, size.height * scale, Texture2D::PixelFormat::RGBA8888, GL_DEPTH24_STENCIL8);
sprite->setScale(scale); // or use finalRtx->setKeepMatrix(true);
finalRtx->begin();
sprite->visit();
finalRtx->end();
}
Director::getInstance()->getRenderer()->render();
return finalRtx->newImage();
}
2014-06-26 14:05:30 +08:00
std::vector<Node*> findChildren(const Node &node, const std::string &name)
{
std::vector<Node*> vec;
node.enumerateChildren(name, [&vec](Node* nodeFound) -> bool {
vec.push_back(nodeFound);
return false;
});
return vec;
}
2014-07-14 20:42:08 +08:00
#define MAX_ITOA_BUFFER_SIZE 256
double atof(const char* str)
{
if (str == nullptr)
{
return 0.0;
}
char buf[MAX_ITOA_BUFFER_SIZE];
strncpy(buf, str, MAX_ITOA_BUFFER_SIZE);
// strip string, only remain 7 numbers after '.'
char* dot = strchr(buf, '.');
if (dot != nullptr && dot - buf + 8 < MAX_ITOA_BUFFER_SIZE)
{
dot[8] = '\0';
}
return ::atof(buf);
}
double gettime()
{
2014-08-04 11:48:23 +08:00
struct timeval tv;
2014-08-04 15:18:01 +08:00
gettimeofday(&tv, nullptr);
2014-08-04 11:48:23 +08:00
return (double)tv.tv_sec + (double)tv.tv_usec/1000000;
}
2014-08-04 15:18:01 +08:00
2015-06-29 11:52:53 +08:00
long long getTimeInMilliseconds()
{
struct timeval tv;
2015-07-06 14:34:32 +08:00
gettimeofday (&tv, nullptr);
return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
2015-06-29 11:52:53 +08:00
}
2014-09-18 15:27:11 +08:00
Rect getCascadeBoundingBox(Node *node)
{
Rect cbb;
Size contentSize = node->getContentSize();
// check all children bounding box, get maximize box
2014-09-18 15:27:11 +08:00
Node* child = nullptr;
bool merge = false;
for(auto object : node->getChildren())
{
child = dynamic_cast<Node*>(object);
if (!child->isVisible()) continue;
2014-09-18 15:40:28 +08:00
const Rect box = getCascadeBoundingBox(child);
2014-09-18 15:27:11 +08:00
if (box.size.width <= 0 || box.size.height <= 0) continue;
if (!merge)
{
cbb = box;
merge = true;
}
else
{
cbb.merge(box);
}
}
// merge content size
if (contentSize.width > 0 && contentSize.height > 0)
{
const Rect box = RectApplyAffineTransform(Rect(0, 0, contentSize.width, contentSize.height), node->getNodeToWorldAffineTransform());
if (!merge)
{
cbb = box;
}
else
{
cbb.merge(box);
}
}
return cbb;
}
2016-06-06 22:32:50 +08:00
Sprite* createSpriteFromBase64Cached(const char* base64String, const char* key)
{
Texture2D* texture = Director::getInstance()->getTextureCache()->getTextureForKey(key);
if (texture == nullptr)
{
unsigned char* decoded;
int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded);
Image *image = new (std::nothrow) Image();
bool imageResult = image->initWithImageData(decoded, length);
CCASSERT(imageResult, "Failed to create image from base64!");
free(decoded);
if (!imageResult) {
CC_SAFE_RELEASE_NULL(image);
return nullptr;
}
2016-06-06 22:32:50 +08:00
texture = Director::getInstance()->getTextureCache()->addImage(image, key);
image->release();
}
Sprite* sprite = Sprite::createWithTexture(texture);
return sprite;
}
Sprite* createSpriteFromBase64(const char* base64String)
{
unsigned char* decoded;
2016-06-06 22:32:50 +08:00
int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded);
Image *image = new (std::nothrow) Image();
bool imageResult = image->initWithImageData(decoded, length);
CCASSERT(imageResult, "Failed to create image from base64!");
free(decoded);
if (!imageResult) {
CC_SAFE_RELEASE_NULL(image);
return nullptr;
}
Texture2D *texture = new (std::nothrow) Texture2D();
texture->initWithImage(image);
texture->setAliasTexParameters();
image->release();
Sprite* sprite = Sprite::createWithTexture(texture);
texture->release();
2016-06-06 22:32:50 +08:00
return sprite;
}
Node* findChild(Node* levelRoot, const std::string& name)
{
if (levelRoot == nullptr || name.empty())
return nullptr;
// Find this node
auto target = levelRoot->getChildByName(name);
if (target != nullptr)
return target;
// Find recursively
for (auto& child : levelRoot->getChildren())
{
target = findChild(child, name);
if (target != nullptr)
return target;
}
return nullptr;
}
Node* findChild(Node* levelRoot, int tag)
{
if (levelRoot == nullptr || tag == Node::INVALID_TAG)
return nullptr;
// Find this node
auto target = levelRoot->getChildByTag(tag);
if (target != nullptr)
return target;
// Find recursively
for (auto& child : levelRoot->getChildren())
{
target = findChild(child, tag);
if (target != nullptr)
return target;
}
return nullptr;
}
std::string getFileMD5Hash(const std::string &filename)
{
Data data;
FileUtils::getInstance()->getContents(filename, &data);
return getDataMD5Hash(data);
}
std::string getDataMD5Hash(const Data &data)
{
static const unsigned int MD5_DIGEST_LENGTH = 16;
if (data.isNull())
{
return std::string();
}
md5_state_t state;
md5_byte_t digest[MD5_DIGEST_LENGTH];
char hexOutput[(MD5_DIGEST_LENGTH << 1) + 1] = { 0 };
md5_init(&state);
md5_append(&state, (const md5_byte_t *)data.getBytes(), (int)data.getSize());
md5_finish(&state, digest);
for (int di = 0; di < 16; ++di)
sprintf(hexOutput + di * 2, "%02x", digest[di]);
return hexOutput;
}
LanguageType getLanguageTypeByISO2(const char* code)
{
// this function is used by all platforms to get system language
// except windows: cocos/platform/win32/CCApplication-win32.cpp
LanguageType ret = LanguageType::ENGLISH;
if (strncmp(code, "zh", 2) == 0)
{
ret = LanguageType::CHINESE;
}
else if (strncmp(code, "ja", 2) == 0)
{
ret = LanguageType::JAPANESE;
}
else if (strncmp(code, "fr", 2) == 0)
{
ret = LanguageType::FRENCH;
}
else if (strncmp(code, "it", 2) == 0)
{
ret = LanguageType::ITALIAN;
}
else if (strncmp(code, "de", 2) == 0)
{
ret = LanguageType::GERMAN;
}
else if (strncmp(code, "es", 2) == 0)
{
ret = LanguageType::SPANISH;
}
else if (strncmp(code, "nl", 2) == 0)
{
ret = LanguageType::DUTCH;
}
else if (strncmp(code, "ru", 2) == 0)
{
ret = LanguageType::RUSSIAN;
}
else if (strncmp(code, "hu", 2) == 0)
{
ret = LanguageType::HUNGARIAN;
}
else if (strncmp(code, "pt", 2) == 0)
{
ret = LanguageType::PORTUGUESE;
}
else if (strncmp(code, "ko", 2) == 0)
{
ret = LanguageType::KOREAN;
}
else if (strncmp(code, "ar", 2) == 0)
{
ret = LanguageType::ARABIC;
}
else if (strncmp(code, "nb", 2) == 0)
{
ret = LanguageType::NORWEGIAN;
}
else if (strncmp(code, "pl", 2) == 0)
{
ret = LanguageType::POLISH;
}
else if (strncmp(code, "tr", 2) == 0)
{
ret = LanguageType::TURKISH;
}
else if (strncmp(code, "uk", 2) == 0)
{
ret = LanguageType::UKRAINIAN;
}
else if (strncmp(code, "ro", 2) == 0)
{
ret = LanguageType::ROMANIAN;
}
else if (strncmp(code, "bg", 2) == 0)
{
ret = LanguageType::BULGARIAN;
}
else if (strncmp(code, "be", 2) == 0)
{
ret = LanguageType::BELARUSIAN;
}
return ret;
}
2018-09-11 14:39:30 +08:00
void setBlending(GLenum sfactor, GLenum dfactor)
{
if (sfactor == GL_ONE && dfactor == GL_ZERO)
{
glDisable(GL_BLEND);
RenderState::StateBlock::_defaultState->setBlend(false);
}
else
{
glEnable(GL_BLEND);
glBlendFunc(sfactor, dfactor);
RenderState::StateBlock::_defaultState->setBlend(true);
RenderState::StateBlock::_defaultState->setBlendSrc((RenderState::Blend)sfactor);
RenderState::StateBlock::_defaultState->setBlendDst((RenderState::Blend)dfactor);
}
}
}
NS_CC_END