Merge remote-tracking branch 'upstream/develop' into develop

Conflicts:
	cocos/scripting/auto-generated
	tools/bindings-generator
This commit is contained in:
bmanGH 2014-01-20 12:18:36 +08:00
commit 7513e8d643
271 changed files with 5778 additions and 1592 deletions

View File

@ -94,6 +94,7 @@ Developers:
use tinyxml2 to replace libxml2 use tinyxml2 to replace libxml2
Added Mingw-crt Support without breaking VS SDK Added Mingw-crt Support without breaking VS SDK
CMake support for windows. CMake support for windows.
Added support for x64 target of windows.
mchinen mchinen
fix emulator issue for OpenGL ES 2.0 on Android fix emulator issue for OpenGL ES 2.0 on Android
@ -718,6 +719,12 @@ Developers:
Pisces000221 Pisces000221
Corrected a few mistakes in the README file of project-creator. Corrected a few mistakes in the README file of project-creator.
hbbalfred
Fixed a bug that crash if file doesn't exist when using FileUtils::getStringFromFile.
liang8305
Use multiple processes according the number of cores to build android project
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang
Author of windows port, CCTextField, Author of windows port, CCTextField,

View File

@ -1,11 +1,37 @@
cocos2d-x-3.0final ?.? ? cocos2d-x-3.0beta2 ?.? ?
[All] [All]
[FIX] Crash was triggered if there is not `textureFileName`section in particle plist file. [NEW] Adds performance test for Containers(Vector<>, Array, Map<K,V>, Dictionary).
[NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier.
[NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands
[NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly
[NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use.
[NEW] Label: Integrates LabelAtlas into new Label.
[NEW] Node: Added `setGlobalZOrder()`. Useful to change the Node's render order. Node::setZOrder() -> Node::setLocalZOrder()
[NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10%
[NEW] LuaBindings: Bindings-generator supports to bind namespace for lua.
[FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work.
[FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile.
[FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong.
[FIX] Label: Crash when using unknown characters.
[FIX] Console: log(format, va_args) is private to prevent possible resolution errors
[FIX] Configuration: dumpInfo() -> getInfo()
[FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlSlider doesn't support to set selected thumb sprite.
[FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] ControlButton doesn't support to set scale ratio of touchdown state.
[FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file.
[FIX] Renderer: Uses a float as key with only the depth. Viewport, opaque are not needed now
[FIX] Renderer Performance Fix: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster
[FIX] Renderer Performance Fix: Sprite and SpriteBatchNode (and subclasses) has much better performance
[FIX] Renderer Performance Fix: When note using VAO, call glBufferData() instead of glBufferSubData().
[FIX] Renderer Performance Fix: Doesn't sort z=0 elements. It also uses sort() instead of stable_sort() for z!=0.
[FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well
[FIX] Tests: TestCpp works with CMake on Windows.
[FIX] Tests: Sprites Performance Test has 4 new tests
[FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected
[FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo()
[FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes.
[NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [FIX] Windows: There will be some compilation errors when using x64 target on Windows.
[FIX] TestCpp works by using CMake on Windows.
cocos2d-x-3.0beta Jan.7 2014 cocos2d-x-3.0beta Jan.7 2014
[All] [All]
[NEW] New label: shadow, outline, glow support [NEW] New label: shadow, outline, glow support

View File

@ -12,6 +12,16 @@ LUA_SAMPLES = ['hellolua', 'testlua']
JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme'] JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme']
ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES
def get_num_of_cpu():
''' The build process can be accelerated by running multiple concurrent job processes using the -j-option.
'''
try:
from numpy.distutils import cpuinfo
return cpuinfo.cpu._getNCPUs()
except Exception:
print "Can't know cpuinfo, use default 1 cpu"
return 1
def check_environment_variables(): def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building ''' Checking the environment NDK_ROOT, which will be used for building
''' '''
@ -94,10 +104,12 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,an
else: else:
ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root)
num_of_cpu = get_num_of_cpu()
if ndk_build_param == None: if ndk_build_param == None:
command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path)
else: else:
command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_build_param, ndk_module_path)
print command
if os.system(command) != 0: if os.system(command) != 0:
raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!")
elif android_platform is not None: elif android_platform is not None:

View File

@ -1 +1 @@
3d6ada05d55194dd8e4c10ed8316add7c0d8705c 63e6598ea5798bf42bbd22c2295e65f7c739695a

View File

@ -1 +1 @@
2efefc01ff97bda1498d1d4a850ea1881f751f7c 447e7ba37294e6da0df2e02f5a62f30fb15e3272

View File

@ -47,6 +47,7 @@ CCEventListenerTouch.cpp \
CCEventMouse.cpp \ CCEventMouse.cpp \
CCEventTouch.cpp \ CCEventTouch.cpp \
CCFont.cpp \ CCFont.cpp \
CCFontCharMap.cpp \
CCFontAtlas.cpp \ CCFontAtlas.cpp \
CCFontAtlasCache.cpp \ CCFontAtlasCache.cpp \
CCFontAtlasFactory.cpp \ CCFontAtlasFactory.cpp \
@ -122,6 +123,7 @@ renderer/CCFrustum.cpp \
renderer/CCGroupCommand.cpp \ renderer/CCGroupCommand.cpp \
renderer/CCMaterialManager.cpp \ renderer/CCMaterialManager.cpp \
renderer/CCQuadCommand.cpp \ renderer/CCQuadCommand.cpp \
renderer/CCBatchCommand.cpp \
renderer/CCRenderCommand.cpp \ renderer/CCRenderCommand.cpp \
renderer/CCRenderer.cpp \ renderer/CCRenderer.cpp \
renderer/CCRenderMaterial.cpp \ renderer/CCRenderMaterial.cpp \

View File

@ -34,7 +34,7 @@ THE SOFTWARE.
#include "ccGLStateCache.h" #include "ccGLStateCache.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
// external // external
@ -152,13 +152,13 @@ void AtlasNode::draw(void)
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
_quadCommand.init(0, _quadCommand.init(
_vertexZ, _globalZOrder,
_textureAtlas->getTexture()->getName(), _textureAtlas->getTexture()->getName(),
shader, shader,
_blendFunc, _blendFunc,
_textureAtlas->getQuads(), _textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(), _quadsToDraw,
_modelViewTransform); _modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);

View File

@ -31,9 +31,10 @@
#include "CCShaderCache.h" #include "CCShaderCache.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCDrawingPrimitives.h" #include "CCDrawingPrimitives.h"
#include "CCRenderer.h"
#include "CCGroupCommand.h" #include "renderer/CCRenderer.h"
#include "CCCustomCommand.h" #include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -209,12 +210,12 @@ void ClippingNode::visit()
Renderer* renderer = Director::getInstance()->getRenderer(); Renderer* renderer = Director::getInstance()->getRenderer();
_groupCommand.init(0,_vertexZ); _groupCommand.init(_globalZOrder);
renderer->addCommand(&_groupCommand); renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID()); renderer->pushGroup(_groupCommand.getRenderQueueID());
_beforeVisitCmd.init(0,_vertexZ); _beforeVisitCmd.init(_globalZOrder);
_beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this); _beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this);
renderer->addCommand(&_beforeVisitCmd); renderer->addCommand(&_beforeVisitCmd);
if (_alphaThreshold < 1) if (_alphaThreshold < 1)
@ -237,7 +238,7 @@ void ClippingNode::visit()
} }
_stencil->visit(); _stencil->visit();
_afterDrawStencilCmd.init(0,_vertexZ); _afterDrawStencilCmd.init(_globalZOrder);
_afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this); _afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this);
renderer->addCommand(&_afterDrawStencilCmd); renderer->addCommand(&_afterDrawStencilCmd);
@ -267,7 +268,7 @@ void ClippingNode::visit()
this->draw(); this->draw();
} }
_afterVisitCmd.init(0,_vertexZ); _afterVisitCmd.init(_globalZOrder);
_afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this); _afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this);
renderer->addCommand(&_afterVisitCmd); renderer->addCommand(&_afterVisitCmd);

View File

@ -31,13 +31,13 @@ THE SOFTWARE.
#include "CCDictionary.h" #include "CCDictionary.h"
#include "CCInteger.h" #include "CCInteger.h"
#include "CCBool.h" #include "CCBool.h"
#include "cocos2d.h"
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
using namespace std; using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
extern const char* cocos2dVersion();
Configuration* Configuration::s_sharedConfiguration = nullptr; Configuration* Configuration::s_sharedConfiguration = nullptr;
@ -88,24 +88,20 @@ Configuration::~Configuration()
{ {
} }
void Configuration::dumpInfo() const std::string Configuration::getInfo() const
{ {
// Dump
Value forDump = Value(_valueDict);
CCLOG("%s", forDump.getDescription().c_str());
// And Dump some warnings as well // And Dump some warnings as well
#if CC_ENABLE_PROFILERS #if CC_ENABLE_PROFILERS
CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)"); CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)\n");
printf("\n");
#endif #endif
#if CC_ENABLE_GL_STATE_CACHE == 0 #if CC_ENABLE_GL_STATE_CACHE == 0
CCLOG(""); CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)\n");
CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)");
printf("\n");
#endif #endif
// Dump
Value forDump = Value(_valueDict);
return forDump.getDescription();
} }
void Configuration::gatherGPUInfo() void Configuration::gatherGPUInfo()

View File

@ -122,8 +122,8 @@ public:
/** sets a new key/value pair in the configuration dictionary */ /** sets a new key/value pair in the configuration dictionary */
void setValue(const std::string& key, const Value& value); void setValue(const std::string& key, const Value& value);
/** dumps the current configuration on the console */ /** returns the Configuration info */
void dumpInfo() const; std::string getInfo() const;
/** gathers OpenGL / GPU information */ /** gathers OpenGL / GPU information */
void gatherGPUInfo(); void gatherGPUInfo();

View File

@ -60,9 +60,10 @@ THE SOFTWARE.
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
#include "CCEventCustom.h" #include "CCEventCustom.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "CCConsole.h"
#include "renderer/CCFrustum.h" #include "renderer/CCFrustum.h"
#include "CCConsole.h"
/** /**
Position of the FPS Position of the FPS
@ -377,7 +378,7 @@ void Director::setOpenGLView(EGLView *openGLView)
// Configuration. Gather GPU info // Configuration. Gather GPU info
Configuration *conf = Configuration::getInstance(); Configuration *conf = Configuration::getInstance();
conf->gatherGPUInfo(); conf->gatherGPUInfo();
conf->dumpInfo(); CCLOG("%s\n",conf->getInfo().c_str());
// EAGLView is not a Object // EAGLView is not a Object
delete _openGLView; // [openGLView_ release] delete _openGLView; // [openGLView_ release]

View File

@ -26,9 +26,9 @@
#include "CCGL.h" #include "CCGL.h"
#include "CCEventType.h" #include "CCEventType.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
#include "renderer/CCRenderer.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCRenderer.h"
#include "CCEventListenerCustom.h" #include "CCEventListenerCustom.h"
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
@ -241,7 +241,7 @@ void DrawNode::render()
void DrawNode::draw() void DrawNode::draw()
{ {
_customCommand.init(0, _vertexZ); _customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this); _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
} }

View File

@ -28,6 +28,7 @@
#include "CCFontFNT.h" #include "CCFontFNT.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "CCFontCharMap.h"
#include "edtaa3func.h" #include "edtaa3func.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -116,6 +117,21 @@ Font* Font::createWithFNT(const std::string& fntFilePath)
return FontFNT::create(fntFilePath); return FontFNT::create(fntFilePath);
} }
Font* Font::createWithCharMap(const std::string& plistFile)
{
return FontCharMap::create(plistFile);
}
Font* Font::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
return FontCharMap::create(texture,itemWidth,itemHeight,startCharMap);
}
Font* Font::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
return FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap);
}
unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height)
{ {
unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread); unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread);

View File

@ -28,7 +28,6 @@
#include <string> #include <string>
#include "cocos2d.h"
#include "CCLabel.h" #include "CCLabel.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -46,6 +45,10 @@ public:
static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
static Font* createWithFNT(const std::string& fntFilePath); static Font* createWithFNT(const std::string& fntFilePath);
static Font * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static Font * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static Font * createWithCharMap(const std::string& plistFile);
static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height); static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height);
void setDistanceFieldEnabled(bool distanceFieldEnabled); void setDistanceFieldEnabled(bool distanceFieldEnabled);
bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;}

View File

@ -22,10 +22,12 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocos2d.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
#include "CCFont.h" #include "CCFont.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "ccUTF8.h"
#include "CCDirector.h"
#define PAGE_WIDTH 1024 #define PAGE_WIDTH 1024
#define PAGE_HEIGHT 1024 #define PAGE_HEIGHT 1024
@ -100,6 +102,7 @@ bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontL
} }
else else
{ {
outDefinition.validDefinition = false;
return false; return false;
} }
} }
@ -128,7 +131,6 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
Rect tempRect; Rect tempRect;
FontLetterDefinition tempDef; FontLetterDefinition tempDef;
tempDef.offsetX = 0;
tempDef.anchorX = 0.0f; tempDef.anchorX = 0.0f;
tempDef.anchorY = 1.0f; tempDef.anchorY = 1.0f;
@ -141,6 +143,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.height = 0; tempDef.height = 0;
tempDef.U = 0; tempDef.U = 0;
tempDef.V = 0; tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0; tempDef.offsetY = 0;
tempDef.textureID = 0; tempDef.textureID = 0;
} }
@ -150,6 +153,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.letteCharUTF16 = utf16String[i]; tempDef.letteCharUTF16 = utf16String[i];
tempDef.width = tempRect.size.width + _letterPadding; tempDef.width = tempRect.size.width + _letterPadding;
tempDef.height = _currentPageLineHeight - 1; tempDef.height = _currentPageLineHeight - 1;
tempDef.offsetX = tempRect.origin.x;
tempDef.offsetY = tempRect.origin.y; tempDef.offsetY = tempRect.origin.y;
tempDef.commonLineHeight = _currentPageLineHeight; tempDef.commonLineHeight = _currentPageLineHeight;

View File

@ -26,11 +26,14 @@
#define _CCFontAtlas_h_ #define _CCFontAtlas_h_
#include <unordered_map> #include <unordered_map>
#include "CCPlatformMacros.h"
#include "CCObject.h"
NS_CC_BEGIN NS_CC_BEGIN
//fwd //fwd
class Font; class Font;
class Texture2D;
struct FontLetterDefinition struct FontLetterDefinition
{ {

View File

@ -23,6 +23,8 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include <sstream>
#include "CCFontAtlasCache.h" #include "CCFontAtlasCache.h"
#include "CCFontAtlasFactory.h" #include "CCFontAtlasFactory.h"
@ -69,6 +71,65 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName)
return tempAtlas; return tempAtlas;
} }
FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile)
{
std::string atlasName = generateFontName(plistFile, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromCharMap(plistFile);
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
tempAtlas->retain();
}
return tempAtlas;
}
FontAtlas * FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
char tmp[30];
sprintf(tmp,"name:%u_%d_%d_%d",texture->getName(),itemWidth,itemHeight,startCharMap);
std::string atlasName = generateFontName(tmp, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromCharMap(texture,itemWidth,itemHeight,startCharMap);
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
tempAtlas->retain();
}
return tempAtlas;
}
FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
std::string atlasName = generateFontName(charMapFile, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas )
{
tempAtlas = FontAtlasFactory::createAtlasFromCharMap(charMapFile,itemWidth,itemHeight,startCharMap);
if (tempAtlas)
_atlasMap[atlasName] = tempAtlas;
}
else
{
tempAtlas->retain();
}
return tempAtlas;
}
std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField) std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField)
{ {
std::string tempName(fontFileName); std::string tempName(fontFileName);

View File

@ -29,23 +29,24 @@
#include <iostream> #include <iostream>
#include <unordered_map> #include <unordered_map>
#include "cocos2d.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
#include "CCLabel.h"
NS_CC_BEGIN NS_CC_BEGIN
class CC_DLL FontAtlasCache class CC_DLL FontAtlasCache
{ {
public: public:
static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false);
static FontAtlas * getFontAtlasFNT(const std::string& fontFileName); static FontAtlas * getFontAtlasFNT(const std::string& fontFileName);
static FontAtlas * getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * getFontAtlasCharMap(const std::string& plistFile);
static bool releaseFontAtlas(FontAtlas *atlas); static bool releaseFontAtlas(FontAtlas *atlas);
private: private:
static std::string generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField); static std::string generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField);
static std::unordered_map<std::string, FontAtlas *> _atlasMap; static std::unordered_map<std::string, FontAtlas *> _atlasMap;
}; };

View File

@ -60,4 +60,46 @@ FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath)
} }
} }
FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& plistFile)
{
Font *font = Font::createWithCharMap(plistFile);
if(font)
{
return font->createFontAtlas();
}
else
{
return nullptr;
}
}
FontAtlas * FontAtlasFactory::createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
Font *font = Font::createWithCharMap(texture,itemWidth,itemHeight,startCharMap);
if(font)
{
return font->createFontAtlas();
}
else
{
return nullptr;
}
}
FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
Font *font = Font::createWithCharMap(charMapFile,itemWidth,itemHeight,startCharMap);
if(font)
{
return font->createFontAtlas();
}
else
{
return nullptr;
}
}
NS_CC_END NS_CC_END

View File

@ -26,8 +26,8 @@
#ifndef _CCFontAtlasFactory_h_ #ifndef _CCFontAtlasFactory_h_
#define _CCFontAtlasFactory_h_ #define _CCFontAtlasFactory_h_
#include "cocos2d.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
#include "CCLabel.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -40,6 +40,10 @@ public:
static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false);
static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath); static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath);
static FontAtlas * createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontAtlas * createAtlasFromCharMap(const std::string& plistFile);
private: private:
}; };

171
cocos/2d/CCFontCharMap.cpp Normal file
View File

@ -0,0 +1,171 @@
/****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
#include "CCFontCharMap.h"
#include "CCFontAtlas.h"
NS_CC_BEGIN
FontCharMap * FontCharMap::create(const std::string& plistFile)
{
std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile);
std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/";
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(pathStr.c_str());
CCASSERT(dict["version"].asInt() == 1, "Unsupported version. Upgrade cocos2d version");
std::string textureFilename = relPathStr + dict["textureFilename"].asString();
unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR();
unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR();
unsigned int startChar = dict["firstChar"].asInt();
Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(textureFilename);
if (!tempTexture)
{
return nullptr;
}
FontCharMap *tempFont = new FontCharMap(tempTexture,width,height,startChar);
if (!tempFont)
{
return nullptr;
}
tempFont->autorelease();
return tempFont;
}
FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile);
if (!tempTexture)
{
return nullptr;
}
FontCharMap *tempFont = new FontCharMap(tempTexture,itemWidth,itemHeight,startCharMap);
if (!tempFont)
{
return nullptr;
}
tempFont->autorelease();
return tempFont;
}
FontCharMap* FontCharMap::create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
FontCharMap *tempFont = new FontCharMap(texture,itemWidth,itemHeight,startCharMap);
if (!tempFont)
{
return nullptr;
}
tempFont->autorelease();
return tempFont;
}
FontCharMap::~FontCharMap()
{
}
Size * FontCharMap::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const
{
if (!text)
return 0;
outNumLetters = cc_wcslen(text);
if (!outNumLetters)
return 0;
Size *sizes = new Size[outNumLetters];
if (!sizes)
return 0;
int advance = _itemWidth * CC_CONTENT_SCALE_FACTOR();
for (int c = 0; c < outNumLetters; ++c)
{
sizes[c].width = advance;
}
return sizes;
}
Rect FontCharMap::getRectForChar(unsigned short theChar) const
{
return _charRect;
}
FontAtlas * FontCharMap::createFontAtlas()
{
FontAtlas *tempAtlas = new FontAtlas(*this);
if (!tempAtlas)
return nullptr;
Size s = _texture->getContentSize();
int itemsPerColumn = (int)(s.height / _itemHeight);
int itemsPerRow = (int)(s.width / _itemWidth);
tempAtlas->setCommonLineHeight(_itemHeight);
FontLetterDefinition tempDefinition;
tempDefinition.textureID = 0;
tempDefinition.anchorX = 0.5f;
tempDefinition.anchorY = 0.5f;
tempDefinition.offsetX = 0.0f;
tempDefinition.offsetY = 0.0f;
tempDefinition.validDefinition = true;
tempDefinition.width = _itemWidth;
tempDefinition.height = _itemHeight;
int charId = _mapStartChar;
float itemWidthInPixels = _itemWidth * CC_CONTENT_SCALE_FACTOR();
float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR();
for (int row = 0; row < itemsPerColumn; ++row)
{
for (int col = 0; col < itemsPerRow; ++col)
{
tempDefinition.letteCharUTF16 = charId;
tempDefinition.U = _itemWidth * col;
tempDefinition.V = _itemHeight * row;
tempAtlas->addLetterDefinition(tempDefinition);
charId++;
}
}
tempAtlas->addTexture(*_texture,0);
return tempAtlas;
}
NS_CC_END

70
cocos/2d/CCFontCharMap.h Normal file
View File

@ -0,0 +1,70 @@
/****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
#ifndef _CCFontCharMap_h_
#define _CCFontCharMap_h_
#include "cocos2d.h"
#include "CCFont.h"
NS_CC_BEGIN
class FontCharMap : public Font
{
public:
static FontCharMap * create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static FontCharMap * create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static FontCharMap * create(const std::string& plistFile);
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override;
virtual Rect getRectForChar(unsigned short theChar) const override;
virtual FontAtlas *createFontAtlas() override;
protected:
FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap)
:_texture(texture)
,_mapStartChar(startCharMap)
,_itemWidth(itemWidth)
,_itemHeight(itemHeight)
,_charRect(0,0,itemWidth,itemHeight)
{}
/**
* @js NA
* @lua NA
*/
virtual ~FontCharMap();
private:
Texture2D* _texture;
int _mapStartChar;
int _itemWidth;
int _itemHeight;
Rect _charRect;
};
NS_CC_END
#endif /* defined(_CCFontCharMap_h_) */

View File

@ -23,8 +23,9 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocos2d.h"
#include "CCFontDefinition.h" #include "CCFontDefinition.h"
#include "CCDirector.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -221,7 +222,6 @@ FontAtlas * FontDefinitionTTF::createFontAtlas()
if ( item.second.validDefinition ) if ( item.second.validDefinition )
{ {
FontLetterDefinition tempDefinition = item.second; FontLetterDefinition tempDefinition = item.second;
tempDefinition.offsetX = 0;
tempDefinition.anchorX = 0.0f; tempDefinition.anchorX = 0.0f;
tempDefinition.anchorY = 1.0f; tempDefinition.anchorY = 1.0f;
retAtlas->addLetterDefinition(tempDefinition); retAtlas->addLetterDefinition(tempDefinition);

View File

@ -25,6 +25,10 @@
#include "CCFontFNT.h" #include "CCFontFNT.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
#include "CCLabelBMFont.h"
#include "CCDirector.h"
#include "CCTextureCache.h"
#include "ccUTF8.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -26,11 +26,12 @@
#ifndef _CCFontFNT_h_ #ifndef _CCFontFNT_h_
#define _CCFontFNT_h_ #define _CCFontFNT_h_
#include "cocos2d.h"
#include "CCFont.h" #include "CCFont.h"
NS_CC_BEGIN NS_CC_BEGIN
class CCBMFontConfiguration;
class FontFNT : public Font class FontFNT : public Font
{ {

View File

@ -31,6 +31,7 @@ THE SOFTWARE.
#include "CCTextImage.h" #include "CCTextImage.h"
#include "CCFont.h" #include "CCFont.h"
#include "CCFontDefinition.h" #include "CCFontDefinition.h"
#include "platform/CCFileUtils.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -175,7 +176,7 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const
return false; return false;
// store result in the passed rectangle // store result in the passed rectangle
outRect.origin.x = 0; outRect.origin.x = _fontRef->glyph->metrics.horiBearingX >> 6;
outRect.origin.y = - (_fontRef->glyph->metrics.horiBearingY >> 6); outRect.origin.y = - (_fontRef->glyph->metrics.horiBearingY >> 6);
outRect.size.width = (_fontRef->glyph->metrics.width >> 6); outRect.size.width = (_fontRef->glyph->metrics.width >> 6);
outRect.size.height = (_fontRef->glyph->metrics.height >> 6); outRect.size.height = (_fontRef->glyph->metrics.height >> 6);
@ -267,7 +268,7 @@ Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLe
int advance = 0; int advance = 0;
int kerning = 0; int kerning = 0;
advance = getAdvanceForChar(text[c]) - getBearingXForChar(text[c]); advance = getAdvanceForChar(text[c]);
if (c < (outNumLetters-1)) if (c < (outNumLetters-1))
kerning = getHorizontalKerningForChars(text[c], text[c+1]); kerning = getHorizontalKerningForChars(text[c], text[c+1]);
@ -294,7 +295,7 @@ int FontFreeType::getAdvanceForChar(unsigned short theChar) const
return 0; return 0;
// get to the advance for this glyph // get to the advance for this glyph
return (static_cast<int>(_fontRef->glyph->advance.x >> 6)); return (static_cast<int>(_fontRef->glyph->metrics.horiAdvance >> 6));
} }
int FontFreeType::getBearingXForChar(unsigned short theChar) const int FontFreeType::getBearingXForChar(unsigned short theChar) const

View File

@ -27,67 +27,85 @@
#include "CCFontDefinition.h" #include "CCFontDefinition.h"
#include "CCFontAtlasCache.h" #include "CCFontAtlasCache.h"
#include "CCLabelTextFormatter.h" #include "CCLabelTextFormatter.h"
#include "CCSprite.h"
#include "CCShaderCache.h"
#include "ccUTF8.h"
#include "CCSpriteFrame.h"
#include "CCDirector.h"
#include "renderer/CCRenderer.h"
#define DISTANCEFIELD_ATLAS_FONTSIZE 50 #define DISTANCEFIELD_ATLAS_FONTSIZE 50
NS_CC_BEGIN NS_CC_BEGIN
Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) Label* Label::create()
{ {
FontAtlas *tmpAtlas = nullptr; Label *ret = new Label();
if(useDistanceField)
tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), DISTANCEFIELD_ATLAS_FONTSIZE, glyphs, customGlyphs,true);
else
tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs,false);
if (!tmpAtlas)
return nullptr;
// create the actual label
Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize, useDistanceField,true);
if (templabel)
{
if(useDistanceField)
templabel->setFontSize(fontSize);
templabel->setText(label, lineSize, alignment, false);
return templabel;
}
return nullptr;
}
Label* Label::createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment, int lineSize)
{
FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath.c_str());
if (!tmpAtlas)
return 0;
Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize);
if (templabel)
{
templabel->setText(label, lineSize, alignment, false);
return templabel;
}
else
{
return 0;
}
return 0;
}
Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize, bool useDistanceField,bool useA8Shader)
{
Label *ret = new Label(atlas, alignment, useDistanceField,useA8Shader);
if (!ret) if (!ret)
return 0; return nullptr;
if( ret->init() ) ret->autorelease();
return ret;
}
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setTTFConfig(ttfConfig))
{
if(ttfConfig.distanceFieldEnabled)
ret->setFontSize(ttfConfig.fontSize);
ret->setString(text,alignment,lineSize);
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
}
Label* Label::createWithTTF(const std::string& text, const std::string& fontFilePath, int fontSize, int lineSize /* = 0 */, TextHAlignment alignment /* = TextHAlignment::CENTER */, GlyphCollection glyphs /* = GlyphCollection::NEHE */, const char *customGlyphs /* = 0 */, bool useDistanceField /* = false */)
{
TTFConfig ttfConfig(fontFilePath.c_str(),fontSize,glyphs,customGlyphs,useDistanceField);
return createWithTTF(ttfConfig,text,alignment,lineSize);
}
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setBMFontFilePath(bmfontFilePath))
{
ret->setString(text,alignment,lineSize);
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
}
Label* Label::createWithCharMap(const std::string& plistFile)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setCharMap(plistFile))
{ {
ret->autorelease(); ret->autorelease();
return ret; return ret;
@ -95,21 +113,86 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li
else else
{ {
delete ret; delete ret;
return 0; return nullptr;
}
} }
Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setCharMap(texture,itemWidth,itemHeight,startCharMap))
{
ret->autorelease();
return ret; return ret;
} }
else
{
delete ret;
return nullptr;
}
}
Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
Label *ret = new Label();
if (!ret)
return nullptr;
if (ret->setCharMap(charMapFile,itemWidth,itemHeight,startCharMap))
{
ret->autorelease();
return ret;
}
else
{
delete ret;
return nullptr;
}
}
bool Label::setCharMap(const std::string& plistFile)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(texture,itemWidth,itemHeight,startCharMap);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile,itemWidth,itemHeight,startCharMap);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader) Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader)
: _reusedLetter(nullptr) : _reusedLetter(nullptr)
, _multilineEnable(true)
, _commonLineHeight(0.0f) , _commonLineHeight(0.0f)
, _lineBreakWithoutSpaces(false) , _lineBreakWithoutSpaces(false)
, _width(0.0f) , _width(0.0f)
, _alignment(alignment) , _alignment(alignment)
, _currentUTF16String(0) , _currentUTF16String(nullptr)
, _originalUTF16String(0) , _originalUTF16String(nullptr)
, _advances(nullptr) , _advances(nullptr)
, _fontAtlas(atlas) , _fontAtlas(atlas)
, _isOpacityModifyRGB(true) , _isOpacityModifyRGB(true)
@ -118,6 +201,7 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,b
, _fontSize(0) , _fontSize(0)
, _uniformEffectColor(0) , _uniformEffectColor(0)
{ {
_cascadeColorEnabled = true;
} }
Label::~Label() Label::~Label()
@ -136,58 +220,109 @@ bool Label::init()
{ {
bool ret = true; bool ret = true;
if(_fontAtlas) if(_fontAtlas)
{
if (_reusedLetter == nullptr)
{ {
_reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0));
_reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB);
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
_reusedLetter->retain(); _reusedLetter->retain();
} }
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
}
if (_useDistanceField) if (_useDistanceField)
setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK); setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK);
else if(_useA8Shader) else if(_useA8Shader)
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR)); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR));
else else
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
return ret; return ret;
} }
void Label::setString(const std::string &stringToRender) bool Label::initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false */, bool useA8Shader /* = false */)
{ {
_multilineEnable = true; FontAtlas *oldAtlas = _fontAtlas;
setText(stringToRender, _width, TextHAlignment::CENTER, false); bool oldDistanceFieldEnable = _useDistanceField;
bool oldA8ShaderEnabel = _useA8Shader;
_fontAtlas = atlas;
_useDistanceField = distanceFieldEnabled;
_useA8Shader = useA8Shader;
bool ret = Label::init();
if (oldAtlas)
{
if (ret)
{
FontAtlasCache::releaseFontAtlas(oldAtlas);
}
else
{
_fontAtlas = oldAtlas;
_useDistanceField = oldDistanceFieldEnable;
_useA8Shader = oldA8ShaderEnabel;
Label::init();
FontAtlasCache::releaseFontAtlas(atlas);
}
} }
void Label::setString(const std::string &stringToRender,bool multilineEnable) if (_fontAtlas)
{ {
_multilineEnable = multilineEnable; _commonLineHeight = _fontAtlas->getCommonLineHeight();
setText(stringToRender, _width, TextHAlignment::CENTER, false); if (_currentUTF16String)
{
alignText();
}
} }
bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) return ret;
}
bool Label::setTTFConfig(const TTFConfig& ttfConfig)
{ {
if (!_fontAtlas) FontAtlas *newAtlas = nullptr;
if(ttfConfig.distanceFieldEnabled)
newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, DISTANCEFIELD_ATLAS_FONTSIZE, ttfConfig.glyphs, ttfConfig.customGlyphs,true);
else
newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, ttfConfig.fontSize, ttfConfig.glyphs, ttfConfig.customGlyphs,false);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas,ttfConfig.distanceFieldEnabled,true);
}
bool Label::setBMFontFilePath(const std::string& bmfontFilePath)
{
FontAtlas *newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath);
if (!newAtlas)
return false;
return initWithFontAtlas(newAtlas);
}
bool Label::setString(const std::string& text, const TextHAlignment& alignment /* = TextHAlignment::CENTER */, float lineWidth /* = -1 */, bool lineBreakWithoutSpaces /* = false */)
{
if (!_fontAtlas || _commonLineHeight <= 0)
return false; return false;
// carloX // carloX
// reset the string // reset the string
resetCurrentString(); resetCurrentString();
if(lineWidth >= 0)
{
_width = lineWidth; _width = lineWidth;
}
_alignment = alignment; _alignment = alignment;
_lineBreakWithoutSpaces = lineBreakWithoutSpaces; _lineBreakWithoutSpaces = lineBreakWithoutSpaces;
// store locally common line height unsigned short* utf16String = cc_utf8_to_utf16(text.c_str());
_commonLineHeight = _fontAtlas->getCommonLineHeight();
if (_commonLineHeight <= 0)
return false;
// int numLetter = 0;
unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str());
if(!utf16String) if(!utf16String)
return false; return false;
_cascadeColorEnabled = true;
setCurrentString(utf16String); setCurrentString(utf16String);
setOriginalString(utf16String); setOriginalString(utf16String);
@ -299,7 +434,7 @@ void Label::alignText()
_textureAtlas->removeAllQuads(); _textureAtlas->removeAllQuads();
_fontAtlas->prepareLetterDefinitions(_currentUTF16String); _fontAtlas->prepareLetterDefinitions(_currentUTF16String);
LabelTextFormatter::createStringSprites(this); LabelTextFormatter::createStringSprites(this);
if(_multilineEnable && LabelTextFormatter::multilineText(this) ) if(_width > 0 && LabelTextFormatter::multilineText(this) )
LabelTextFormatter::createStringSprites(this); LabelTextFormatter::createStringSprites(this);
LabelTextFormatter::alignText(this); LabelTextFormatter::alignText(this);
@ -531,7 +666,7 @@ void Label::onDraw()
void Label::draw() void Label::draw()
{ {
_customCommand.init(0, _vertexZ); _customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(Label::onDraw, this); _customCommand.func = CC_CALLBACK_0(Label::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
} }

View File

@ -54,23 +54,51 @@ enum class LabelEffect {
struct FontLetterDefinition; struct FontLetterDefinition;
class FontAtlas; class FontAtlas;
typedef struct _ttfConfig
{
std::string fontFilePath;
int fontSize;
GlyphCollection glyphs;
const char *customGlyphs;
bool distanceFieldEnabled;
_ttfConfig(const char* filePath,int size = 36, const GlyphCollection& glyphCollection = GlyphCollection::NEHE,
const char *customGlyphCollection = nullptr,bool useDistanceField = false)
:fontFilePath(filePath)
,fontSize(size)
,glyphs(glyphCollection)
,customGlyphs(customGlyphCollection)
,distanceFieldEnabled(useDistanceField)
{}
}TTFConfig;
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelTextFormatProtocol class CC_DLL Label : public SpriteBatchNode, public LabelTextFormatProtocol
{ {
public: public:
static Label* create();
// static create CC_DEPRECATED_ATTRIBUTE static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false);
static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false); static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::CENTER, int lineWidth = 0);
static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::CENTER, int lineWidth = 0);
bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); static Label * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
static Label * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
static Label * createWithCharMap(const std::string& plistFile);
bool setTTFConfig(const TTFConfig& ttfConfig);
bool setBMFontFilePath(const std::string& bmfontFilePath);
bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap);
bool setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap);
bool setCharMap(const std::string& plistFile);
bool setString(const std::string& text, const TextHAlignment& alignment = TextHAlignment::CENTER, float lineWidth = -1, bool lineBreakWithoutSpaces = false);
//only support for TTF
void setLabelEffect(LabelEffect effect,const Color3B& effectColor); void setLabelEffect(LabelEffect effect,const Color3B& effectColor);
virtual void setString(const std::string &stringToRender) override;
void setString(const std::string &stringToRender,bool multilineEnable);
virtual void setAlignment(TextHAlignment alignment); virtual void setAlignment(TextHAlignment alignment);
virtual void setWidth(float width); virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
@ -116,7 +144,7 @@ public:
virtual void setLabelContentSize(const Size &newSize) override; virtual void setLabelContentSize(const Size &newSize) override;
// carloX // carloX
virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; } virtual const std::string& getString() const { static std::string _ret("not implemented"); return _ret; }
void addChild(Node * child, int zOrder=0, int tag=0) override; void addChild(Node * child, int zOrder=0, int tag=0) override;
virtual std::string getDescription() const override; virtual std::string getDescription() const override;
@ -127,14 +155,14 @@ private:
/** /**
* @js NA * @js NA
*/ */
Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField = false,bool useA8Shader = false); Label(FontAtlas *atlas = nullptr, TextHAlignment alignment = TextHAlignment::CENTER, bool useDistanceField = false,bool useA8Shader = false);
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
~Label(); ~Label();
static Label* createWithAtlas(FontAtlas *atlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0, bool useDistanceField = false,bool useA8Shader = false); bool initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false);
void setFontSize(int fontSize); void setFontSize(int fontSize);
@ -151,12 +179,10 @@ private:
virtual void updateColor() override; virtual void updateColor() override;
//! used for optimization //! used for optimization
Sprite *_reusedLetter; Sprite *_reusedLetter;
std::vector<LetterInfo> _lettersInfo; std::vector<LetterInfo> _lettersInfo;
bool _multilineEnable;
float _commonLineHeight; float _commonLineHeight;
bool _lineBreakWithoutSpaces; bool _lineBreakWithoutSpaces;
float _width; float _width;

View File

@ -275,8 +275,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch
unsigned long remains = size; unsigned long remains = size;
unsigned char version = pData[3]; CCASSERT(pData[3] == 3, "Only version 3 is supported");
CCASSERT(version == 3, "Only version 3 is supported");
pData += 4; remains -= 4; pData += 4; remains -= 4;
@ -343,8 +342,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch
*/ */
const char *value = (const char *)pData; const char *value = (const char *)pData;
size_t len = strlen(value); CCASSERT(strlen(value) < blockSize, "Block size should be less then string");
CCASSERT(len < blockSize, "Block size should be less then string");
_atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile); _atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile);
} }

View File

@ -25,11 +25,16 @@
#ifndef _CCLabelTextFormatProtocol_h_ #ifndef _CCLabelTextFormatProtocol_h_
#define _CCLabelTextFormatProtocol_h_ #define _CCLabelTextFormatProtocol_h_
#include "CCFontAtlas.h"
#include <vector> #include <vector>
#include "CCFontAtlas.h"
#include "CCGeometry.h"
#include "ccTypes.h"
NS_CC_BEGIN NS_CC_BEGIN
class Sprite;
struct LetterInfo struct LetterInfo
{ {
@ -46,13 +51,13 @@ public:
virtual ~LabelTextFormatProtocol() {} virtual ~LabelTextFormatProtocol() {}
virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) = 0; virtual bool recordLetterInfo(const Point& point,unsigned short int theChar, int spriteIndex) = 0;
virtual bool recordPlaceholderInfo(int spriteIndex) = 0; virtual bool recordPlaceholderInfo(int spriteIndex) = 0;
virtual std::vector<LetterInfo> *getLettersInfo() = 0; virtual std::vector<LetterInfo> *getLettersInfo() = 0;
virtual float getLetterPosXLeft(int index) const = 0; virtual float getLetterPosXLeft(int index) const = 0;
virtual float getLetterPosXRight(int index) const = 0; virtual float getLetterPosXRight(int index) const = 0;
// sprite related stuff // sprite related stuff
virtual cocos2d::Sprite *getLetter(int ID) = 0; virtual Sprite *getLetter(int ID) = 0;
// font related stuff // font related stuff
virtual int getCommonLineHeight() const = 0; virtual int getCommonLineHeight() const = 0;
@ -60,7 +65,7 @@ public:
virtual int getXOffsetForChar(unsigned short c) const = 0; virtual int getXOffsetForChar(unsigned short c) const = 0;
virtual int getYOffsetForChar(unsigned short c) const = 0; virtual int getYOffsetForChar(unsigned short c) const = 0;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0; virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0;
virtual cocos2d::Rect getRectForChar(unsigned short c) const = 0; virtual Rect getRectForChar(unsigned short c) const = 0;
// string related stuff // string related stuff
virtual int getStringNumLines() const = 0; virtual int getStringNumLines() const = 0;

View File

@ -25,9 +25,9 @@
#include <vector> #include <vector>
#include "cocos2d.h"
#include "ccUTF8.h" #include "ccUTF8.h"
#include "CCLabelTextFormatter.h" #include "CCLabelTextFormatter.h"
#include "CCDirector.h"
using namespace std; using namespace std;
@ -68,15 +68,19 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
while (info->def.validDefinition == false) while (info->def.validDefinition == false)
{ {
justSkipped++; justSkipped++;
info = &leterInfo->at( j+skip+justSkipped ); tIndex = j+skip+justSkipped;
if(tIndex < strLen)
info = &leterInfo->at( tIndex );
else
break;
} }
skip += justSkipped; skip += justSkipped;
tIndex = j + skip; tIndex = j + skip;
if (i >= stringLength) if (tIndex >= stringLength)
break; break;
unsigned short character = strWhole[i]; unsigned short character = strWhole[tIndex];
if (!isStartOfWord) if (!isStartOfWord)
{ {
@ -241,8 +245,6 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
continue; continue;
} }
int index = static_cast<int>(i + lineLength - 1 + lineNumber); int index = static_cast<int>(i + lineLength - 1 + lineNumber);
if(currentChar == 0)
index -= 1;
if (index < 0) continue; if (index < 0) continue;
LetterInfo* info = &leterInfo->at( index ); LetterInfo* info = &leterInfo->at( index );

View File

@ -44,8 +44,8 @@ THE SOFTWARE.
#include "CCEventListenerAcceleration.h" #include "CCEventListenerAcceleration.h"
#include "platform/CCDevice.h" #include "platform/CCDevice.h"
#include "CCScene.h" #include "CCScene.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -565,7 +565,7 @@ void LayerColor::updateColor()
void LayerColor::draw() void LayerColor::draw()
{ {
_customCommand.init(0, _vertexZ); _customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this); _customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand); Director::getInstance()->getRenderer()->addCommand(&_customCommand);

View File

@ -31,8 +31,8 @@ THE SOFTWARE.
#include "ccMacros.h" #include "ccMacros.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCVertex.h" #include "CCVertex.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -359,7 +359,7 @@ void MotionStreak::draw()
if(_nuPoints <= 1) if(_nuPoints <= 1)
return; return;
kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV); kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV);
_customCommand.init(0,_vertexZ); _customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this); _customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand); Director::getInstance()->getRenderer()->addCommand(&_customCommand);

View File

@ -108,7 +108,8 @@ Node::Node(void)
, _inverseDirty(true) , _inverseDirty(true)
// children (lazy allocs) // children (lazy allocs)
// lazy alloc // lazy alloc
, _ZOrder(0) , _localZOrder(0)
, _globalZOrder(0)
, _parent(nullptr) , _parent(nullptr)
// "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
, _tag(Node::INVALID_TAG) , _tag(Node::INVALID_TAG)
@ -212,28 +213,21 @@ void Node::setSkewY(float newSkewY)
_transformDirty = _inverseDirty = true; _transformDirty = _inverseDirty = true;
} }
/// zOrder getter
int Node::getZOrder() const
{
return _ZOrder;
}
/// zOrder setter : private method /// zOrder setter : private method
/// used internally to alter the zOrder variable. DON'T call this method manually /// used internally to alter the zOrder variable. DON'T call this method manually
void Node::_setZOrder(int z) void Node::_setLocalZOrder(int z)
{ {
_ZOrder = z; _localZOrder = z;
} }
void Node::setZOrder(int z) void Node::setLocalZOrder(int z)
{ {
_localZOrder = z;
if (_parent) if (_parent)
{ {
_parent->reorderChild(this, z); _parent->reorderChild(this, z);
} }
// should set "_ZOrder" after reorderChild, because the implementation of reorderChild subclass of Node, such as Sprite,
// will return when _ZOrder value is not changed
_setZOrder(z);
_eventDispatcher->setDirtyForNode(this); _eventDispatcher->setDirtyForNode(this);
} }
@ -246,9 +240,10 @@ float Node::getVertexZ() const
/// vertexZ setter /// vertexZ setter
void Node::setVertexZ(float var) void Node::setVertexZ(float zOrder)
{ {
_vertexZ = var; _vertexZ = zOrder;
setGlobalZOrder(zOrder);
} }
@ -650,7 +645,7 @@ void Node::addChild(Node *child, int zOrder)
void Node::addChild(Node *child) void Node::addChild(Node *child)
{ {
CCASSERT( child != nullptr, "Argument must be non-nil"); CCASSERT( child != nullptr, "Argument must be non-nil");
this->addChild(child, child->_ZOrder, child->_tag); this->addChild(child, child->_localZOrder, child->_tag);
} }
void Node::removeFromParent() void Node::removeFromParent()
@ -767,7 +762,7 @@ void Node::insertChild(Node* child, int z)
{ {
_reorderChildDirty = true; _reorderChildDirty = true;
_children.pushBack(child); _children.pushBack(child);
child->_setZOrder(z); child->_setLocalZOrder(z);
} }
void Node::reorderChild(Node *child, int zOrder) void Node::reorderChild(Node *child, int zOrder)
@ -775,7 +770,7 @@ void Node::reorderChild(Node *child, int zOrder)
CCASSERT( child != nullptr, "Child must be non-nil"); CCASSERT( child != nullptr, "Child must be non-nil");
_reorderChildDirty = true; _reorderChildDirty = true;
child->setOrderOfArrival(s_globalOrderOfArrival++); child->setOrderOfArrival(s_globalOrderOfArrival++);
child->_setZOrder(zOrder); child->_setLocalZOrder(zOrder);
} }
void Node::sortAllChildren() void Node::sortAllChildren()
@ -816,7 +811,7 @@ void Node::visit()
{ {
auto node = _children.at(i); auto node = _children.at(i);
if ( node && node->_ZOrder < 0 ) if ( node && node->_localZOrder < 0 )
node->visit(); node->visit();
else else
break; break;

View File

@ -161,43 +161,72 @@ public:
/// @name Setters & Getters for Graphic Peroperties /// @name Setters & Getters for Graphic Peroperties
/** /**
* Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array. LocalZOrder is the 'key' used to sort the node relative to its siblings.
*
* The Z order of node is relative to its siblings. The Node's parent will sort all its children based ont the LocalZOrder value.
* It is not related to the OpenGL's z property. This one only affects the draw order of itself and its siblings. If two nodes have the same LocalZOrder, then the node that was added first to the children's array will be in front of the other node in the array.
* Lower Z order number are drawn before higher numbers.
* Please refer to `setVertexZ(float)` for the difference. Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order )
* And Nodes that have LocalZOder values < 0 are the "left" subtree
* @param zOrder Z order of this node. While Nodes with LocalZOder >=0 are the "right" subtree.
@see `setGlobalZOrder`
@see `setVertexZ`
*/ */
virtual void setZOrder(int zOrder); virtual void setLocalZOrder(int zOrder);
/*
* Sets the z order which stands for the drawing order CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int zOrder) { setLocalZOrder(zOrder); }
* /* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing.
* This is an internal method. Don't call it outside the framework.
* The difference between setZOrder(int) and _setOrder(int) is:
* - _setZOrder(int) is a pure setter for _ZOrder memeber variable
* - setZOrder(int) firstly changes _ZOrder, then recorder this node in its parent's chilren array.
*/ */
virtual void _setZOrder(int z); virtual void _setLocalZOrder(int z);
/** /**
* Gets the Z order of this node. * Gets the local Z order of this node.
* *
* @see `setZOrder(int)` * @see `setLocalZOrder(int)`
* *
* @return The Z order. * @return The local (relative to its siblings) Z order.
*/ */
virtual int getZOrder() const; virtual int getLocalZOrder() const { return _localZOrder; }
CC_DEPRECATED_ATTRIBUTE virtual int getZOrder() const { return getLocalZOrder(); }
/** /**
* Sets the real OpenGL Z vertex. Defines the oder in which the nodes are renderer.
Nodes that have a Global Z Order lower, are renderer first.
In case two or more nodes have the same Global Z Order, the oder is not guaranteed.
The only exception if the Nodes have a Global Z Order == 0. In that case, the Scene Graph order is used.
By default, all nodes have a Global Z Order = 0. That means that by default, the Scene Graph order is used to render the nodes.
Global Z Order is useful when you need to render nodes in an order different than the Scene Graph order.
Limitations: Global Z Order can't be used used by Nodes that have SpriteBatchNode as one of their acenstors.
And if ClippingNode is one of the ancestors, then "global Z order" will be relative to the ClippingNode.
@see `setLocalZOrder()`
@see `setVertexZ()`
@since v3.0
*/
virtual void setGlobalZOrder(float zOrder) { _globalZOrder = zOrder; }
/**
* Returns the Node's Global Z Order.
* *
* Differences between openGL Z vertex and cocos2d Z order: * @see `setGlobalZOrder(int)`
* - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children
* - OpenGL Z might require to set 2D projection
* - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: `vertexZ = 0`
* *
* @warning Use it at your own risk since it might break the cocos2d parent-children z order * @return The node's global Z order
*/
virtual float getGlobalZOrder() const { return _globalZOrder; }
/**
* Sets the 'z' value in the OpenGL Depth Buffer.
*
* The OpenGL depth buffer and depth testing are disabled by default. You need to turn them on
* in order to use this property correctly.
*
* `setVertexZ()` also sets the `setGlobalZValue()` with the vertexZ value.
*
* @see `setGlobalZValue()`
* *
* @param vertexZ OpenGL Z vertex of this node. * @param vertexZ OpenGL Z vertex of this node.
*/ */
@ -1411,7 +1440,6 @@ protected:
float _scaleX; ///< scaling factor on x-axis float _scaleX; ///< scaling factor on x-axis
float _scaleY; ///< scaling factor on y-axis float _scaleY; ///< scaling factor on y-axis
float _vertexZ; ///< OpenGL real Z vertex
Point _position; ///< position of the node Point _position; ///< position of the node
@ -1433,7 +1461,11 @@ protected:
mutable bool _transformDirty; ///< transform dirty flag mutable bool _transformDirty; ///< transform dirty flag
mutable bool _inverseDirty; ///< inverse transform dirty flag mutable bool _inverseDirty; ///< inverse transform dirty flag
int _ZOrder; ///< z-order value that affects the draw order
int _localZOrder; ///< Local order (relative to its siblings) used to sort the node
float _globalZOrder; ///< Global order used to sort the node
float _vertexZ; ///< OpenGL real Z vertex
Vector<Node*> _children; ///< array of children nodes Vector<Node*> _children; ///< array of children nodes
Node *_parent; ///< weak reference to parent node Node *_parent; ///< weak reference to parent node

View File

@ -25,9 +25,9 @@
#include "CCNodeGrid.h" #include "CCNodeGrid.h"
#include "CCGrid.h" #include "CCGrid.h"
#include "CCGroupCommand.h" #include "renderer/CCGroupCommand.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -92,7 +92,7 @@ void NodeGrid::visit()
Renderer* renderer = Director::getInstance()->getRenderer(); Renderer* renderer = Director::getInstance()->getRenderer();
_groupCommand.init(0,_vertexZ); _groupCommand.init(_globalZOrder);
renderer->addCommand(&_groupCommand); renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID()); renderer->pushGroup(_groupCommand.getRenderQueueID());
@ -104,7 +104,7 @@ void NodeGrid::visit()
_nodeGrid->set2DProjection(); _nodeGrid->set2DProjection();
} }
_gridBeginCommand.init(0,_vertexZ); _gridBeginCommand.init(_globalZOrder);
_gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this); _gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this);
renderer->addCommand(&_gridBeginCommand); renderer->addCommand(&_gridBeginCommand);
@ -152,7 +152,7 @@ void NodeGrid::visit()
director->setProjection(beforeProjectionType); director->setProjection(beforeProjectionType);
} }
_gridEndCommand.init(0,_vertexZ); _gridEndCommand.init(_globalZOrder);
_gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this); _gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this);
renderer->addCommand(&_gridEndCommand); renderer->addCommand(&_gridEndCommand);

View File

@ -44,7 +44,7 @@
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
#include "CCProfiling.h" #include "CCProfiling.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -197,7 +197,7 @@ int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag)
_children.insert(pos, child); _children.insert(pos, child);
child->setTag(aTag); child->setTag(aTag);
child->_setZOrder(z); child->_setLocalZOrder(z);
child->setParent(this); child->setParent(this);
@ -264,7 +264,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
} }
} }
child->_setZOrder(zOrder); child->_setLocalZOrder(zOrder);
} }
void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z) void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z)
@ -382,26 +382,14 @@ void ParticleBatchNode::draw(void)
return; return;
} }
// CC_NODE_DRAW_SETUP(); _batchCommand.init(
// _globalZOrder,
// GL::blendFunc( _blendFunc.src, _blendFunc.dst );
//
// _textureAtlas->drawQuads();
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
kmMat4 mv;
kmGLGetMatrix(KM_GL_MODELVIEW, &mv);
_quadCommand.init(0,
_vertexZ,
_textureAtlas->getTexture()->getName(), _textureAtlas->getTexture()->getName(),
shader, _shaderProgram,
_blendFunc, _blendFunc,
_textureAtlas->getQuads(), _textureAtlas,
_textureAtlas->getTotalQuads(), _modelViewTransform);
mv); Director::getInstance()->getRenderer()->addCommand(&_batchCommand);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
CC_PROFILER_STOP("CCParticleBatchNode - draw"); CC_PROFILER_STOP("CCParticleBatchNode - draw");
} }

View File

@ -32,7 +32,7 @@
#include "CCNode.h" #include "CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCBatchCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -146,7 +146,7 @@ private:
/** the blend function used for drawing the quads */ /** the blend function used for drawing the quads */
BlendFunc _blendFunc; BlendFunc _blendFunc;
// quad command // quad command
QuadCommand _quadCommand; BatchCommand _batchCommand;
}; };
// end of particle_nodes group // end of particle_nodes group

View File

@ -38,9 +38,9 @@ THE SOFTWARE.
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCEventType.h" #include "CCEventType.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
// extern // extern
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -439,7 +439,7 @@ void ParticleSystemQuad::draw()
auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
_quadCommand.init(0, _vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); _quadCommand.init(_globalZOrder, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand); Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
} }

View File

@ -33,8 +33,8 @@ THE SOFTWARE.
#include "CCDirector.h" #include "CCDirector.h"
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCDrawingPrimitives.h" #include "CCDrawingPrimitives.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
// extern // extern
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -555,7 +555,7 @@ void ProgressTimer::draw()
if( ! _vertexData || ! _sprite) if( ! _vertexData || ! _sprite)
return; return;
_customCommand.init(0, _vertexZ); _customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this); _customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand); Director::getInstance()->getRenderer()->addCommand(&_customCommand);
} }

View File

@ -38,9 +38,9 @@ THE SOFTWARE.
#include "CCEventType.h" #include "CCEventType.h"
#include "CCGrid.h" #include "CCGrid.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "CCGroupCommand.h" #include "renderer/CCGroupCommand.h"
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
// extern // extern
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -322,7 +322,7 @@ void RenderTexture::beginWithClear(float r, float g, float b, float a, float dep
this->begin(); this->begin();
//clear screen //clear screen
_beginWithClearCommand.init(0, _vertexZ); _beginWithClearCommand.init(_globalZOrder);
_beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); _beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand); Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand);
} }
@ -340,7 +340,7 @@ void RenderTexture::clearDepth(float depthValue)
this->begin(); this->begin();
_clearDepthCommand.init(0, _vertexZ); _clearDepthCommand.init(_globalZOrder);
_clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this); _clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this);
Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand); Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand);
@ -605,7 +605,7 @@ void RenderTexture::draw()
begin(); begin();
//clear screen //clear screen
_clearCommand.init(0, _vertexZ); _clearCommand.init(_globalZOrder);
_clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); _clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this);
Director::getInstance()->getRenderer()->addCommand(&_clearCommand); Director::getInstance()->getRenderer()->addCommand(&_clearCommand);
@ -648,13 +648,13 @@ void RenderTexture::begin()
(float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 );
kmGLMultMatrix(&orthoMatrix); kmGLMultMatrix(&orthoMatrix);
_groupCommand.init(0, _vertexZ); _groupCommand.init(_globalZOrder);
Renderer *renderer = Director::getInstance()->getRenderer(); Renderer *renderer = Director::getInstance()->getRenderer();
renderer->addCommand(&_groupCommand); renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID()); renderer->pushGroup(_groupCommand.getRenderQueueID());
_beginCommand.init(0, _vertexZ); _beginCommand.init(_globalZOrder);
_beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this); _beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this);
Director::getInstance()->getRenderer()->addCommand(&_beginCommand); Director::getInstance()->getRenderer()->addCommand(&_beginCommand);
@ -662,7 +662,7 @@ void RenderTexture::begin()
void RenderTexture::end() void RenderTexture::end()
{ {
_endCommand.init(0, _vertexZ); _endCommand.init(_globalZOrder);
_endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this); _endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this);
Renderer *renderer = Director::getInstance()->getRenderer(); Renderer *renderer = Director::getInstance()->getRenderer();

View File

@ -45,9 +45,9 @@ THE SOFTWARE.
#include "CCAffineTransform.h" #include "CCAffineTransform.h"
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCProfiling.h" #include "CCProfiling.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
#include "CCFrustum.h" #include "renderer/CCFrustum.h"
// external // external
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -243,8 +243,6 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
// zwoptex default values // zwoptex default values
_offsetPosition = Point::ZERO; _offsetPosition = Point::ZERO;
_hasChildren = false;
// clean the Quad // clean the Quad
memset(&_quad, 0, sizeof(_quad)); memset(&_quad, 0, sizeof(_quad));
@ -672,7 +670,7 @@ void Sprite::updateTransform(void)
void Sprite::draw(void) void Sprite::draw(void)
{ {
//TODO implement z order //TODO implement z order
_quadCommand.init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform);
// if(culling()) // if(culling())
{ {
@ -767,18 +765,12 @@ void Sprite::addChild(Node *child, int zOrder, int tag)
} }
//CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check
Node::addChild(child, zOrder, tag); Node::addChild(child, zOrder, tag);
_hasChildren = true;
} }
void Sprite::reorderChild(Node *child, int zOrder) void Sprite::reorderChild(Node *child, int zOrder)
{ {
CCASSERT(child != nullptr, ""); CCASSERT(child != nullptr, "child must be non null");
CCASSERT(_children.contains(child), ""); CCASSERT(_children.contains(child), "child does not belong to this");
if (zOrder == child->getZOrder())
{
return;
}
if( _batchNode && ! _reorderChildDirty) if( _batchNode && ! _reorderChildDirty)
{ {
@ -813,8 +805,6 @@ void Sprite::removeAllChildrenWithCleanup(bool cleanup)
} }
Node::removeAllChildrenWithCleanup(cleanup); Node::removeAllChildrenWithCleanup(cleanup);
_hasChildren = false;
} }
void Sprite::sortAllChildren() void Sprite::sortAllChildren()
@ -882,9 +872,7 @@ void Sprite::setDirtyRecursively(bool bValue)
{ {
_recursiveDirty = bValue; _recursiveDirty = bValue;
setDirty(bValue); setDirty(bValue);
// recursively set dirty
if (_hasChildren)
{
for(const auto &child: _children) { for(const auto &child: _children) {
Sprite* sp = dynamic_cast<Sprite*>(child); Sprite* sp = dynamic_cast<Sprite*>(child);
if (sp) if (sp)
@ -893,14 +881,13 @@ void Sprite::setDirtyRecursively(bool bValue)
} }
} }
} }
}
// XXX HACK: optimization // XXX HACK: optimization
#define SET_DIRTY_RECURSIVELY() { \ #define SET_DIRTY_RECURSIVELY() { \
if (! _recursiveDirty) { \ if (! _recursiveDirty) { \
_recursiveDirty = true; \ _recursiveDirty = true; \
setDirty(true); \ setDirty(true); \
if ( _hasChildren) \ if (!_children.empty()) \
setDirtyRecursively(true); \ setDirtyRecursively(true); \
} \ } \
} }

View File

@ -538,7 +538,6 @@ protected:
bool _dirty; /// Whether the sprite needs to be updated bool _dirty; /// Whether the sprite needs to be updated
bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated
bool _hasChildren; /// Whether the sprite contains children
bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible
kmMat4 _transformToBatch; kmMat4 _transformToBatch;

View File

@ -43,7 +43,7 @@ THE SOFTWARE.
#include "CCProfiling.h" #include "CCProfiling.h"
#include "CCLayer.h" #include "CCLayer.h"
#include "CCScene.h" #include "CCScene.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCQuadCommand.h"
// external // external
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -99,7 +99,7 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, ssize_t capacity)
_descendants.reserve(capacity); _descendants.reserve(capacity);
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
return true; return true;
} }
@ -356,18 +356,14 @@ void SpriteBatchNode::draw()
for(const auto &child: _children) for(const auto &child: _children)
child->updateTransform(); child->updateTransform();
kmMat4 mv; _batchCommand.init(
kmGLGetMatrix(KM_GL_MODELVIEW, &mv); _globalZOrder,
_quadCommand.init(0,
_vertexZ,
_textureAtlas->getTexture()->getName(), _textureAtlas->getTexture()->getName(),
_shaderProgram, _shaderProgram,
_blendFunc, _blendFunc,
_textureAtlas->getQuads(), _textureAtlas,
_textureAtlas->getTotalQuads(), _modelViewTransform);
mv); Director::getInstance()->getRenderer()->addCommand(&_batchCommand);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
} }
void SpriteBatchNode::increaseAtlasCapacity(void) void SpriteBatchNode::increaseAtlasCapacity(void)

View File

@ -35,7 +35,7 @@ THE SOFTWARE.
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCTextureAtlas.h" #include "CCTextureAtlas.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "renderer/CCQuadCommand.h" #include "renderer/CCBatchCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -189,7 +189,7 @@ protected:
TextureAtlas *_textureAtlas; TextureAtlas *_textureAtlas;
BlendFunc _blendFunc; BlendFunc _blendFunc;
QuadCommand _quadCommand; // quad command BatchCommand _batchCommand; // render command
// all descendants: children, grand children, etc... // all descendants: children, grand children, etc...
// There is not need to retain/release these objects, since they are already retained by _children // There is not need to retain/release these objects, since they are already retained by _children

View File

@ -174,7 +174,7 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
if (layerInfo->_visible) if (layerInfo->_visible)
{ {
TMXLayer *child = parseLayer(layerInfo, mapInfo); TMXLayer *child = parseLayer(layerInfo, mapInfo);
addChild((Node*)child, idx, idx); addChild(child, idx, idx);
// update content size with the max size // update content size with the max size
const Size& childSize = child->getContentSize(); const Size& childSize = child->getContentSize();

View File

@ -28,10 +28,10 @@
#include <vector> #include <vector>
#include <string> #include <string>
#include "cocos2d.h"
#include "CCTextImage.h" #include "CCTextImage.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "CCFont.h" #include "CCFont.h"
#include "ccUTF8.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -295,7 +295,7 @@ bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth
return true; return true;
} }
int TextImage::getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize) int TextImage::getNumGlyphsFittingInSize(std::unordered_map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize)
{ {
if (!strUTF8) if (!strUTF8)
return 0; return 0;

View File

@ -23,15 +23,19 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#ifndef _TextImage_h_ #ifndef _CCTextImage_h_
#define _TextImage_h_ #define _CCTextImage_h_
//#include "CCFont.h"
#include <vector> #include <vector>
#include <unordered_map>
#include "CCPlatformMacros.h"
#include "CCGeometry.h"
NS_CC_BEGIN NS_CC_BEGIN
class Font; class Font;
class Texture2D;
/** @brief GlyphDef defines one single glyph (character) in a text image /** @brief GlyphDef defines one single glyph (character) in a text image
* *
@ -43,22 +47,28 @@ class CC_DLL GlyphDef
{ {
public: public:
GlyphDef() : _validGlyph(false) { /*do nothing*/ } GlyphDef() : _validGlyph(false) {}
GlyphDef(unsigned short int letterUTF8, const Rect &rect) { _gliphRect = rect; _uTF16Letter = letterUTF8; } GlyphDef(unsigned short int letterUTF8, const Rect &rect) {
_gliphRect = rect;
_uTF16Letter = letterUTF8;
}
void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; } void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; }
void setRect(const Rect & theRect) { _gliphRect = theRect; } void setRect(const Rect & theRect) { _gliphRect = theRect; }
unsigned short int getUTF8Letter() { return _uTF16Letter; }
unsigned short int getUTF8Letter() const { return _uTF16Letter; }
const Rect& getRect() const { return _gliphRect; } const Rect& getRect() const { return _gliphRect; }
void setPadding(float padding) { _padding = padding; } void setPadding(float padding) { _padding = padding; }
float getPadding() { return _padding; } float getPadding() const { return _padding; }
void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; } void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; }
float getCommonHeight() { return _commonHeight; } float getCommonHeight() const { return _commonHeight; }
void setValid(bool isValid) { _validGlyph = isValid; } void setValid(bool isValid) { _validGlyph = isValid; }
bool isValid() { return _validGlyph; } bool isValid() const { return _validGlyph; }
private:
protected:
Rect _gliphRect; Rect _gliphRect;
unsigned short int _uTF16Letter; unsigned short int _uTF16Letter;
float _padding; float _padding;
@ -87,14 +97,12 @@ public:
int getNumGlyph() const { return static_cast<int>(_glyphs.size()); } int getNumGlyph() const { return static_cast<int>(_glyphs.size()); }
const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; } const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; }
private: protected:
float _x; float _x;
float _y; float _y;
float _width; float _width;
float _height; float _height;
std::vector<GlyphDef> _glyphs; std::vector<GlyphDef> _glyphs;
}; };
/** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page) /** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page)
@ -126,8 +134,7 @@ public:
Texture2D *getPageTexture(); Texture2D *getPageTexture();
void preparePageTexture(bool releaseRAWData = true); void preparePageTexture(bool releaseRAWData = true);
private: protected:
bool generatePageTexture(bool releasePageData = false); bool generatePageTexture(bool releasePageData = false);
int _pageNum; int _pageNum;
@ -136,7 +143,6 @@ private:
unsigned char * _pageData; unsigned char * _pageData;
Texture2D* _pageTexture; Texture2D* _pageTexture;
std::vector<TextLineDef*> _lines; std::vector<TextLineDef*> _lines;
}; };
/** @brief CCTextFontPages collection of pages (TextPageDef) /** @brief CCTextFontPages collection of pages (TextPageDef)
@ -160,8 +166,7 @@ public:
int getNumPages() const { return static_cast<int>(_pages.size()); } int getNumPages() const { return static_cast<int>(_pages.size()); }
TextPageDef* getPageAt(int index) const { return _pages[index]; } TextPageDef* getPageAt(int index) const { return _pages[index]; }
private: protected:
std::vector<TextPageDef*> _pages; std::vector<TextPageDef*> _pages;
}; };
@ -187,19 +192,18 @@ public:
TextFontPagesDef* getPages() const { return _fontPages; } TextFontPagesDef* getPages() const { return _fontPages; }
Font* getFont() const { return _font; } Font* getFont() const { return _font; }
private: protected:
bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true); bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true);
bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false); bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false);
bool generateTextGlyphs(const char * text); bool generateTextGlyphs(const char * text);
int getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize); int getNumGlyphsFittingInSize(std::unordered_map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize);
bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight); bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight);
unsigned char * preparePageGlyphData(TextPageDef *thePage); unsigned char * preparePageGlyphData(TextPageDef *thePage);
// glyph rendering // glyph rendering
unsigned char * renderGlyphData(TextPageDef *thePage); unsigned char * renderGlyphData(TextPageDef *thePage);
std::map<unsigned short int, GlyphDef> _textGlyphs; std::unordered_map<unsigned short int, GlyphDef> _textGlyphs;
TextFontPagesDef* _fontPages; TextFontPagesDef* _fontPages;
Font* _font; Font* _font;
}; };
@ -208,4 +212,4 @@ private:
NS_CC_END NS_CC_END
#endif #endif // _CCTextImage_h_

View File

@ -97,7 +97,7 @@ void TextureCache::addImageAsync(const std::string &path, std::function<void(Tex
{ {
Texture2D *texture = nullptr; Texture2D *texture = nullptr;
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str()); std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
auto it = _textures.find(fullpath); auto it = _textures.find(fullpath);
if( it != _textures.end() ) if( it != _textures.end() )
@ -290,7 +290,7 @@ Texture2D * TextureCache::addImage(const std::string &path)
// MUTEX: // MUTEX:
// Needed since addImageAsync calls this method from a different thread // Needed since addImageAsync calls this method from a different thread
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str()); std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
if (fullpath.size() == 0) if (fullpath.size() == 0)
{ {
return nullptr; return nullptr;
@ -307,7 +307,7 @@ Texture2D * TextureCache::addImage(const std::string &path)
image = new Image(); image = new Image();
CC_BREAK_IF(nullptr == image); CC_BREAK_IF(nullptr == image);
bool bRet = image->initWithImageFile(fullpath.c_str()); bool bRet = image->initWithImageFile(fullpath);
CC_BREAK_IF(!bRet); CC_BREAK_IF(!bRet);
texture = new Texture2D(); texture = new Texture2D();
@ -417,16 +417,30 @@ void TextureCache::removeTexture(Texture2D* texture)
void TextureCache::removeTextureForKey(const std::string &textureKeyName) void TextureCache::removeTextureForKey(const std::string &textureKeyName)
{ {
auto it = _textures.find(textureKeyName); std::string key = textureKeyName;
auto it = _textures.find(key);
if( it == _textures.end() ) {
key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
it = _textures.find(key);
}
if( it != _textures.end() ) { if( it != _textures.end() ) {
(it->second)->release(); (it->second)->release();
_textures.erase(it); _textures.erase(it);
} }
} }
Texture2D* TextureCache::getTextureForKey(const std::string &key) const Texture2D* TextureCache::getTextureForKey(const std::string &textureKeyName) const
{ {
std::string key = textureKeyName;
auto it = _textures.find(key); auto it = _textures.find(key);
if( it == _textures.end() ) {
key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
it = _textures.find(key);
}
if( it != _textures.end() ) if( it != _textures.end() )
return it->second; return it->second;
return nullptr; return nullptr;
@ -448,20 +462,28 @@ void TextureCache::waitForQuit()
if (_loadingThread) _loadingThread->join(); if (_loadingThread) _loadingThread->join();
} }
void TextureCache::dumpCachedTextureInfo() const std::string TextureCache::getCachedTextureInfo() const
{ {
char buffer[16386];
char buftmp[4096];
memset(buffer,0,sizeof(buffer));
unsigned int count = 0; unsigned int count = 0;
unsigned int totalBytes = 0; unsigned int totalBytes = 0;
for( auto it = _textures.begin(); it != _textures.end(); ++it ) { for( auto it = _textures.begin(); it != _textures.end(); ++it ) {
memset(buftmp,0,sizeof(buftmp));
Texture2D* tex = it->second; Texture2D* tex = it->second;
unsigned int bpp = tex->getBitsPerPixelForFormat(); unsigned int bpp = tex->getBitsPerPixelForFormat();
// Each texture takes up width * height * bytesPerPixel bytes. // Each texture takes up width * height * bytesPerPixel bytes.
auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
totalBytes += bytes; totalBytes += bytes;
count++; count++;
log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
it->first.c_str(), it->first.c_str(),
(long)tex->retainCount(), (long)tex->retainCount(),
(long)tex->getName(), (long)tex->getName(),
@ -469,9 +491,13 @@ void TextureCache::dumpCachedTextureInfo() const
(long)tex->getPixelsHigh(), (long)tex->getPixelsHigh(),
(long)bpp, (long)bpp,
(long)bytes / 1024); (long)bytes / 1024);
strcat(buffer, buftmp);
} }
log("cocos2d: TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f)); snprintf(buftmp, sizeof(buftmp)-1, "TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)\n", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
strcat(buffer, buftmp);
return std::string(buffer);
} }
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA

View File

@ -163,7 +163,7 @@ public:
* *
* @since v1.0 * @since v1.0
*/ */
void dumpCachedTextureInfo() const; std::string getCachedTextureInfo() const;
//wait for texture cahe to quit befor destroy instance //wait for texture cahe to quit befor destroy instance
//called by director, please do not called outside //called by director, please do not called outside

View File

@ -98,23 +98,23 @@ void TransitionPageTurn::draw()
if( _isInSceneOnTop ) { if( _isInSceneOnTop ) {
_outSceneProxy->visit(); _outSceneProxy->visit();
_enableOffsetCmd.init(0, _vertexZ); _enableOffsetCmd.init(_globalZOrder);
_enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd);
_inSceneProxy->visit(); _inSceneProxy->visit();
_disableOffsetCmd.init(0, _vertexZ); _disableOffsetCmd.init(_globalZOrder);
_disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd);
} else { } else {
_inSceneProxy->visit(); _inSceneProxy->visit();
_enableOffsetCmd.init(0, _vertexZ); _enableOffsetCmd.init(_globalZOrder);
_enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd);
_outSceneProxy->visit(); _outSceneProxy->visit();
_disableOffsetCmd.init(0, _vertexZ); _disableOffsetCmd.init(_globalZOrder);
_disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this);
Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd);
} }

View File

@ -71,6 +71,7 @@ set(COCOS2D_SRC
CCFontDefinition.cpp CCFontDefinition.cpp
CCFontFNT.cpp CCFontFNT.cpp
CCFontFreeType.cpp CCFontFreeType.cpp
CCFontCharMap.cpp
CCLabel.cpp CCLabel.cpp
CCLabelAtlas.cpp CCLabelAtlas.cpp
CCLabelBMFont.cpp CCLabelBMFont.cpp
@ -144,6 +145,7 @@ set(COCOS2D_SRC
renderer/CCGroupCommand.cpp renderer/CCGroupCommand.cpp
renderer/CCMaterialManager.cpp renderer/CCMaterialManager.cpp
renderer/CCQuadCommand.cpp renderer/CCQuadCommand.cpp
renderer/CCBatchCommand.cpp
renderer/CCRenderCommand.cpp renderer/CCRenderCommand.cpp
renderer/CCRenderer.cpp renderer/CCRenderer.cpp
renderer/CCRenderMaterial.cpp renderer/CCRenderMaterial.cpp

View File

@ -73,7 +73,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, ssize_t extra)
{ {
while (arr->max < arr->num + extra) while (arr->max < arr->num + extra)
{ {
CCLOG("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].", CCLOGINFO("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].",
static_cast<int>(arr->max), static_cast<int>(arr->max),
static_cast<int>(arr->max*2)); static_cast<int>(arr->max*2));

View File

@ -44,7 +44,6 @@ namespace
static bool s_vertexAttribColor = false; static bool s_vertexAttribColor = false;
static bool s_vertexAttribTexCoords = false; static bool s_vertexAttribTexCoords = false;
#if CC_ENABLE_GL_STATE_CACHE #if CC_ENABLE_GL_STATE_CACHE
#define kMaxActiveTexture 16 #define kMaxActiveTexture 16
@ -55,6 +54,8 @@ namespace
static GLenum s_blendingDest = -1; static GLenum s_blendingDest = -1;
static int s_GLServerState = 0; static int s_GLServerState = 0;
static GLuint s_VAO = 0; static GLuint s_VAO = 0;
static GLenum s_activeTexture = -1;
#endif // CC_ENABLE_GL_STATE_CACHE #endif // CC_ENABLE_GL_STATE_CACHE
} }
@ -159,7 +160,7 @@ void bindTexture2DN(GLuint textureUnit, GLuint textureId)
if (s_currentBoundTexture[textureUnit] != textureId) if (s_currentBoundTexture[textureUnit] != textureId)
{ {
s_currentBoundTexture[textureUnit] = textureId; s_currentBoundTexture[textureUnit] = textureId;
glActiveTexture(GL_TEXTURE0 + textureUnit); activeTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_2D, textureId); glBindTexture(GL_TEXTURE_2D, textureId);
} }
#else #else
@ -186,6 +187,18 @@ void deleteTextureN(GLuint textureUnit, GLuint textureId)
glDeleteTextures(1, &textureId); glDeleteTextures(1, &textureId);
} }
void activeTexture(GLenum texture)
{
#if CC_ENABLE_GL_STATE_CACHE
if(s_activeTexture != texture) {
s_activeTexture = texture;
glActiveTexture(s_activeTexture);
}
#else
glActiveTexture(texture);
#endif
}
void bindVAO(GLuint vaoId) void bindVAO(GLuint vaoId)
{ {
if (Configuration::getInstance()->supportsShareableVAO()) if (Configuration::getInstance()->supportsShareableVAO())

View File

@ -129,6 +129,12 @@ void CC_DLL deleteTexture(GLuint textureId);
*/ */
void CC_DLL deleteTextureN(GLuint textureUnit, GLuint textureId); void CC_DLL deleteTextureN(GLuint textureUnit, GLuint textureId);
/** Select active texture unit.
If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly.
@since v3.0
*/
void CC_DLL activeTexture(GLenum texture);
/** If the vertex array is not already bound, it binds it. /** If the vertex array is not already bound, it binds it.
If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly.
@since v2.0.0 @since v2.0.0

View File

@ -279,7 +279,7 @@ cc_utf8_get_char (const char * p)
unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1 */, int* rUtf16Size/* = nullptr */) unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1 */, int* rUtf16Size/* = nullptr */)
{ {
unsigned short len = cc_utf8_strlen(str_old, length); long len = cc_utf8_strlen(str_old, length);
if (rUtf16Size != nullptr) { if (rUtf16Size != nullptr) {
*rUtf16Size = len; *rUtf16Size = len;
} }

View File

@ -25,7 +25,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocos2d.h" #include "CCPlatformMacros.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -248,6 +248,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="CCFontAtlas.cpp" /> <ClCompile Include="CCFontAtlas.cpp" />
<ClCompile Include="CCFontAtlasCache.cpp" /> <ClCompile Include="CCFontAtlasCache.cpp" />
<ClCompile Include="CCFontAtlasFactory.cpp" /> <ClCompile Include="CCFontAtlasFactory.cpp" />
<ClCompile Include="CCFontCharMap.cpp" />
<ClCompile Include="CCFontDefinition.cpp" /> <ClCompile Include="CCFontDefinition.cpp" />
<ClCompile Include="CCFontFNT.cpp" /> <ClCompile Include="CCFontFNT.cpp" />
<ClCompile Include="CCFontFreeType.cpp" /> <ClCompile Include="CCFontFreeType.cpp" />
@ -317,6 +318,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClCompile Include="platform\win32\CCFileUtilsWin32.cpp" /> <ClCompile Include="platform\win32\CCFileUtilsWin32.cpp" />
<ClCompile Include="platform\win32\CCImage.cpp" /> <ClCompile Include="platform\win32\CCImage.cpp" />
<ClCompile Include="platform\win32\CCStdC.cpp" /> <ClCompile Include="platform\win32\CCStdC.cpp" />
<ClCompile Include="renderer\CCBatchCommand.cpp" />
<ClCompile Include="renderer\CCCustomCommand.cpp" /> <ClCompile Include="renderer\CCCustomCommand.cpp" />
<ClCompile Include="renderer\CCFrustum.cpp" /> <ClCompile Include="renderer\CCFrustum.cpp" />
<ClCompile Include="renderer\CCGroupCommand.cpp" /> <ClCompile Include="renderer\CCGroupCommand.cpp" />
@ -428,6 +430,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="CCFontAtlas.h" /> <ClInclude Include="CCFontAtlas.h" />
<ClInclude Include="CCFontAtlasCache.h" /> <ClInclude Include="CCFontAtlasCache.h" />
<ClInclude Include="CCFontAtlasFactory.h" /> <ClInclude Include="CCFontAtlasFactory.h" />
<ClInclude Include="CCFontCharMap.h" />
<ClInclude Include="CCFontDefinition.h" /> <ClInclude Include="CCFontDefinition.h" />
<ClInclude Include="CCFontFNT.h" /> <ClInclude Include="CCFontFNT.h" />
<ClInclude Include="CCFontFreeType.h" /> <ClInclude Include="CCFontFreeType.h" />
@ -521,6 +524,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou
<ClInclude Include="platform\win32\CCGL.h" /> <ClInclude Include="platform\win32\CCGL.h" />
<ClInclude Include="platform\win32\CCPlatformDefine.h" /> <ClInclude Include="platform\win32\CCPlatformDefine.h" />
<ClInclude Include="platform\win32\CCStdC.h" /> <ClInclude Include="platform\win32\CCStdC.h" />
<ClInclude Include="renderer\CCBatchCommand.h" />
<ClInclude Include="renderer\CCCustomCommand.h" /> <ClInclude Include="renderer\CCCustomCommand.h" />
<ClInclude Include="renderer\CCFrustum.h" /> <ClInclude Include="renderer\CCFrustum.h" />
<ClInclude Include="renderer\CCGroupCommand.h" /> <ClInclude Include="renderer\CCGroupCommand.h" />

View File

@ -598,6 +598,12 @@
<ClCompile Include="renderer\CCRenderMaterial.cpp"> <ClCompile Include="renderer\CCRenderMaterial.cpp">
<Filter>renderer</Filter> <Filter>renderer</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="renderer\CCBatchCommand.cpp">
<Filter>renderer</Filter>
</ClCompile>
<ClCompile Include="CCFontCharMap.cpp">
<Filter>label_nodes</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\physics\CCPhysicsBody.h"> <ClInclude Include="..\physics\CCPhysicsBody.h">
@ -1207,5 +1213,11 @@
<ClInclude Include="renderer\CCRenderMaterial.h"> <ClInclude Include="renderer\CCRenderMaterial.h">
<Filter>renderer</Filter> <Filter>renderer</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="renderer\CCBatchCommand.h">
<Filter>renderer</Filter>
</ClInclude>
<ClInclude Include="CCFontCharMap.h">
<Filter>label_nodes</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -547,6 +547,8 @@ static Data getData(const std::string& filename, bool forString)
std::string FileUtils::getStringFromFile(const std::string& filename) std::string FileUtils::getStringFromFile(const std::string& filename)
{ {
Data data = getData(filename, true); Data data = getData(filename, true);
if (data.isNull())
return "";
std::string ret((const char*)data.getBytes()); std::string ret((const char*)data.getBytes());
return ret; return ret;
} }

View File

@ -327,6 +327,9 @@ public:
*/ */
virtual ValueVector getValueVectorFromFile(const std::string& filename); virtual ValueVector getValueVectorFromFile(const std::string& filename);
/** Returns the full path cache */
const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; }
protected: protected:
/** /**
* The default constructor. * The default constructor.

View File

@ -89,7 +89,9 @@ public class Cocos2dxHelper {
jobs.add(r); jobs.add(r);
} }
private static boolean sInited = false;
public static void init(final Activity activity) { public static void init(final Activity activity) {
if (!sInited) {
final ApplicationInfo applicationInfo = activity.getApplicationInfo(); final ApplicationInfo applicationInfo = activity.getApplicationInfo();
initListener(); initListener();
@ -121,6 +123,9 @@ public class Cocos2dxHelper {
//Cocos2dxHelper.nativeSetAssetManager(sAssetManager); //Cocos2dxHelper.nativeSetAssetManager(sAssetManager);
Cocos2dxBitmap.setContext(activity); Cocos2dxBitmap.setContext(activity);
sActivity = activity; sActivity = activity;
sInited = true;
}
} }
public static void initListener() { public static void initListener() {

View File

@ -0,0 +1,69 @@
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
#include "renderer/CCBatchCommand.h"
#include "ccGLStateCache.h"
#include "CCTextureAtlas.h"
NS_CC_BEGIN
BatchCommand::BatchCommand()
: _textureID(0)
, _blendType(BlendFunc::DISABLE)
, _textureAtlas(nullptr)
{
_type = RenderCommand::Type::BATCH_COMMAND;
_shader = nullptr;
}
void BatchCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform)
{
_globalOrder = globalOrder;
_textureID = textureID;
_blendType = blendType;
_shader = shader;
_textureAtlas = textureAtlas;
_mv = modelViewTransform;
}
BatchCommand::~BatchCommand()
{
}
void BatchCommand::execute()
{
// Set material
_shader->use();
_shader->setUniformsForBuiltins(_mv);
GL::bindTexture2D(_textureID);
GL::blendFunc(_blendType.src, _blendType.dst);
// Draw
_textureAtlas->drawQuads();
}
NS_CC_END

View File

@ -0,0 +1,68 @@
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
#ifndef _CC_BATCHCOMMAND_H_
#define _CC_BATCHCOMMAND_H_
#include "CCRenderCommand.h"
#include "CCGLProgram.h"
#include "CCRenderCommandPool.h"
#include "kazmath/kazmath.h"
NS_CC_BEGIN
class TextureAtlas;
#define CC_NO_TEXTURE 0
class BatchCommand : public RenderCommand
{
public:
BatchCommand();
~BatchCommand();
void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform);
void execute();
protected:
int32_t _materialID;
//Maternal
GLuint _textureID;
GLProgram* _shader;
// GLuint _shaderID;
BlendFunc _blendType;
TextureAtlas *_textureAtlas;
// ModelView transform
kmMat4 _mv;
};
NS_CC_END
#endif //_CC_BATCHCOMMAND_H_

View File

@ -22,23 +22,19 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCCustomCommand.h" #include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
CustomCommand::CustomCommand() CustomCommand::CustomCommand()
:RenderCommand() : func(nullptr)
, func(nullptr)
, _viewport(0)
, _depth(0)
{ {
_type = RenderCommand::Type::CUSTOM_COMMAND; _type = RenderCommand::Type::CUSTOM_COMMAND;
} }
void CustomCommand::init(int viewport, int32_t depth) void CustomCommand::init(float globalOrder)
{ {
_viewport = viewport; _globalOrder = globalOrder;
_depth = depth;
} }
CustomCommand::~CustomCommand() CustomCommand::~CustomCommand()
@ -46,17 +42,6 @@ CustomCommand::~CustomCommand()
} }
int64_t CustomCommand::generateID()
{
_id = 0;
_id = (int64_t)_viewport << 61
| (int64_t)1 << 60 // translucent
| (int64_t)_depth << 36;
return _id;
}
void CustomCommand::execute() void CustomCommand::execute()
{ {
if(func) if(func)

View File

@ -39,14 +39,7 @@ public:
public: public:
void init(int viewport, int32_t depth); void init(float depth);
// +----------+----------+-----+-----------------------------------+
// | | | | | |
// | ViewPort | Transluc | | Depth | |
// | 3 bits | 1 bit | | 24 bits | |
// +----------+----------+-----+----------------+------------------+
virtual int64_t generateID();
void execute(); void execute();
@ -54,8 +47,6 @@ public:
std::function<void()> func; std::function<void()> func;
protected: protected:
int _viewport;
int32_t _depth;
}; };
NS_CC_END NS_CC_END

View File

@ -22,7 +22,7 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCFrustum.h" #include "renderer/CCFrustum.h"
#include "CCConsole.h" #include "CCConsole.h"
#include <stdlib.h> #include <stdlib.h>

View File

@ -23,8 +23,8 @@
****************************************************************************/ ****************************************************************************/
#include "CCGroupCommand.h" #include "renderer/CCGroupCommand.h"
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "CCDirector.h" #include "CCDirector.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -86,18 +86,14 @@ void GroupCommandManager::releaseGroupID(int groupID)
} }
GroupCommand::GroupCommand() GroupCommand::GroupCommand()
:RenderCommand()
, _viewport(0)
, _depth(0)
{ {
_type = RenderCommand::Type::GROUP_COMMAND; _type = RenderCommand::Type::GROUP_COMMAND;
_renderQueueID = GroupCommandManager::getInstance()->getGroupID(); _renderQueueID = GroupCommandManager::getInstance()->getGroupID();
} }
void GroupCommand::init(int viewport, int32_t depth) void GroupCommand::init(float globalOrder)
{ {
_viewport = viewport; _globalOrder = globalOrder;
_depth = depth;
GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID);
_renderQueueID = GroupCommandManager::getInstance()->getGroupID(); _renderQueueID = GroupCommandManager::getInstance()->getGroupID();
} }
@ -107,15 +103,4 @@ GroupCommand::~GroupCommand()
GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID);
} }
int64_t GroupCommand::generateID()
{
_id = 0;
_id = (int64_t)_viewport << 61
| (int64_t)1 << 60 // translucent
| (int64_t)_depth << 36;
return _id;
}
NS_CC_END NS_CC_END

View File

@ -56,23 +56,11 @@ public:
GroupCommand(); GroupCommand();
~GroupCommand(); ~GroupCommand();
public: void init(float depth);
void init(int viewport, int32_t depth); inline int getRenderQueueID() const {return _renderQueueID;}
// +----------+----------+-----+-----------------------------------+
// | | | | | |
// | ViewPort | Transluc | | Depth | |
// | 3 bits | 1 bit | | 24 bits | |
// +----------+----------+-----+----------------+------------------+
virtual int64_t generateID() override;
inline bool isTranslucent() {return true;}
inline int getRenderQueueID() {return _renderQueueID;}
protected: protected:
int _viewport;
int32_t _depth;
int _renderQueueID; int _renderQueueID;
}; };

View File

@ -29,88 +29,36 @@
NS_CC_BEGIN NS_CC_BEGIN
QuadCommand::QuadCommand() QuadCommand::QuadCommand()
:RenderCommand() :_textureID(0)
,_viewport(0)
,_depth(0)
,_textureID(0)
,_blendType(BlendFunc::DISABLE) ,_blendType(BlendFunc::DISABLE)
,_quadCount(0) ,_quadsCount(0)
,_capacity(0)
{ {
_type = RenderCommand::Type::QUAD_COMMAND; _type = RenderCommand::Type::QUAD_COMMAND;
_shader = nullptr; _shader = nullptr;
_quad = nullptr; _quads = nullptr;
} }
void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) void QuadCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv)
{ {
_viewport = viewport; _globalOrder = globalOrder;
_depth = depth;
_textureID = textureID; _textureID = textureID;
_blendType = blendType; _blendType = blendType;
_quadCount = quadCount;
_shader = shader; _shader = shader;
if(quadCount > _capacity ) { _quadsCount = quadCount;
//TODO find a better way to manage quads, current way will result in memory be wasted _quads = quad;
// _quad = (V3F_C4B_T2F_Quad*)malloc(sizeof(V3F_C4B_T2F_Quad) * quadCount);
_quad = (V3F_C4B_T2F_Quad*) realloc(_quad, sizeof(*quad) * quadCount );
_capacity = quadCount;
}
_quadCount = quadCount; _mv = mv;
memcpy(_quad, quad, sizeof(V3F_C4B_T2F_Quad) * quadCount);
for(int i=0; i<quadCount; ++i) { generateMaterialID();
V3F_C4B_T2F_Quad *q = &_quad[i];
kmVec3 vec1, out1;
vec1.x = q->bl.vertices.x;
vec1.y = q->bl.vertices.y;
vec1.z = q->bl.vertices.z;
kmVec3Transform(&out1, &vec1, &mv);
q->bl.vertices.x = out1.x;
q->bl.vertices.y = out1.y;
q->bl.vertices.z = out1.z;
kmVec3 vec2, out2;
vec2.x = q->br.vertices.x;
vec2.y = q->br.vertices.y;
vec2.z = q->br.vertices.z;
kmVec3Transform(&out2, &vec2, &mv);
q->br.vertices.x = out2.x;
q->br.vertices.y = out2.y;
q->br.vertices.z = out2.z;
kmVec3 vec3, out3;
vec3.x = q->tr.vertices.x;
vec3.y = q->tr.vertices.y;
vec3.z = q->tr.vertices.z;
kmVec3Transform(&out3, &vec3, &mv);
q->tr.vertices.x = out3.x;
q->tr.vertices.y = out3.y;
q->tr.vertices.z = out3.z;
kmVec3 vec4, out4;
vec4.x = q->tl.vertices.x;
vec4.y = q->tl.vertices.y;
vec4.z = q->tl.vertices.z;
kmVec3Transform(&out4, &vec4, &mv);
q->tl.vertices.x = out4.x;
q->tl.vertices.y = out4.y;
q->tl.vertices.z = out4.z;
}
} }
QuadCommand::~QuadCommand() QuadCommand::~QuadCommand()
{ {
free(_quad);
} }
int64_t QuadCommand::generateID() void QuadCommand::generateMaterialID()
{ {
_id = 0;
//Generate Material ID //Generate Material ID
//TODO fix shader ID generation //TODO fix shader ID generation
CCASSERT(_shader->getProgram() < pow(2,10), "ShaderID is greater than 2^10"); CCASSERT(_shader->getProgram() < pow(2,10), "ShaderID is greater than 2^10");
@ -148,19 +96,12 @@ int64_t QuadCommand::generateID()
// | Shader ID (10 bits) | Blend ID (4 bits) | Texture ID (18 bits) | // | Shader ID (10 bits) | Blend ID (4 bits) | Texture ID (18 bits) |
// +---------------------+-------------------+----------------------+ // +---------------------+-------------------+----------------------+
_materialID = (int32_t)_shader->getProgram() << 22 _materialID = (uint32_t)_shader->getProgram() << 22
| (int32_t)blendID << 18 | (uint32_t)blendID << 18
| (int32_t)_textureID << 0; | (uint32_t)_textureID << 0;
//Generate RenderCommandID
_id = (int64_t)_viewport << 61
| (int64_t)1 << 60 //translucent
| (int64_t)_depth << 36;
return _id;
} }
void QuadCommand::useMaterial() void QuadCommand::useMaterial() const
{ {
_shader->use(); _shader->use();

View File

@ -41,41 +41,31 @@ public:
QuadCommand(); QuadCommand();
~QuadCommand(); ~QuadCommand();
void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quads, ssize_t quadCount,
const kmMat4& mv); const kmMat4& mv);
// +----------+----------+-----+-----------------------------------+ void useMaterial() const;
// | | | | | |
// | ViewPort | Transluc | | Depth | Material ID |
// | 3 bits | 1 bit | | 24 bits | 24 bit2 |
// +----------+----------+-----+----------------+------------------+
virtual int64_t generateID();
void useMaterial();
//TODO use material to decide if it is translucent //TODO use material to decide if it is translucent
inline bool isTranslucent() const { return true; } inline bool isTranslucent() const { return true; }
inline int32_t getMaterialID() const { return _materialID; } void generateMaterialID();
inline uint32_t getMaterialID() const { return _materialID; }
inline GLuint getTextureID() const { return _textureID; } inline GLuint getTextureID() const { return _textureID; }
inline V3F_C4B_T2F_Quad* getQuad() const { return _quad; } inline V3F_C4B_T2F_Quad* getQuads() const { return _quads; }
inline ssize_t getQuadCount() const { return _quadCount; } inline ssize_t getQuadCount() const { return _quadsCount; }
inline GLProgram* getShader() const { return _shader; } inline GLProgram* getShader() const { return _shader; }
inline BlendFunc getBlendType() const { return _blendType; } inline BlendFunc getBlendType() const { return _blendType; }
inline const kmMat4& getModelView() const { return _mv; }
protected: protected:
int32_t _materialID; uint32_t _materialID;
//Key Data
int _viewport; /// Which view port it belongs to
//TODO use material to determine if it's translucent
int32_t _depth;
//Maternal //Maternal
GLuint _textureID; GLuint _textureID;
@ -85,9 +75,10 @@ protected:
BlendFunc _blendType; BlendFunc _blendType;
V3F_C4B_T2F_Quad* _quad; V3F_C4B_T2F_Quad* _quads;
ssize_t _quadCount; ssize_t _quadsCount;
ssize_t _capacity;
kmMat4 _mv;
}; };
NS_CC_END NS_CC_END

View File

@ -28,9 +28,9 @@
NS_CC_BEGIN NS_CC_BEGIN
RenderCommand::RenderCommand() RenderCommand::RenderCommand()
: _type(RenderCommand::Type::UNKNOWN_COMMAND)
, _globalOrder(0)
{ {
_id = 0;
_type = RenderCommand::Type::UNKNOWN_COMMAND;
} }
RenderCommand::~RenderCommand() RenderCommand::~RenderCommand()
@ -57,9 +57,7 @@ void printBits(ssize_t const size, void const * const ptr)
void RenderCommand::printID() void RenderCommand::printID()
{ {
printf("CommandID: "); printf("Command Depth: %f\n", _globalOrder);
printBits(sizeof(_id), &_id);
printf("\n");
} }
NS_CC_END NS_CC_END

View File

@ -33,25 +33,27 @@
NS_CC_BEGIN NS_CC_BEGIN
//TODO make RenderCommand inherent from Object /** Base class of the RenderCommand hierarchy.
The Renderer knows how to render RenderCommands.
*/
class RenderCommand class RenderCommand
{ {
public: public:
enum class Type enum class Type
{ {
UNKNOWN_COMMAND,
QUAD_COMMAND, QUAD_COMMAND,
CUSTOM_COMMAND, CUSTOM_COMMAND,
BATCH_COMMAND,
GROUP_COMMAND, GROUP_COMMAND,
UNKNOWN_COMMAND,
}; };
virtual int64_t generateID() = 0;
/** Get Render Command Id */ /** Get Render Command Id */
virtual inline int64_t getID() { return _id; } inline float getGlobalOrder() const { return _globalOrder; }
virtual inline Type getType() { return _type; } /** Returns the Command type */
inline Type getType() const { return _type; }
protected: protected:
RenderCommand(); RenderCommand();
@ -59,9 +61,11 @@ protected:
void printID(); void printID();
//Generated IDs // Type used in order to avoid dynamic cast, faster
int64_t _id; /// used for sorting render commands
Type _type; Type _type;
// commands are sort by depth
float _globalOrder;
}; };
NS_CC_END NS_CC_END

View File

@ -22,23 +22,80 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCRenderer.h" #include "renderer/CCRenderer.h"
#include "renderer/CCQuadCommand.h"
#include "renderer/CCBatchCommand.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCGroupCommand.h"
#include "CCShaderCache.h" #include "CCShaderCache.h"
#include "ccGLStateCache.h" #include "ccGLStateCache.h"
#include "CCCustomCommand.h"
#include "renderer/CCQuadCommand.h"
#include "CCGroupCommand.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
#include "CCEventListenerCustom.h" #include "CCEventListenerCustom.h"
#include "CCEventType.h" #include "CCEventType.h"
#include <algorithm> // for std::stable_sort #include <algorithm>
NS_CC_BEGIN NS_CC_BEGIN
using namespace std;
bool compareRenderCommand(RenderCommand* a, RenderCommand* b)
{
return a->getGlobalOrder() < b->getGlobalOrder();
}
void RenderQueue::push_back(RenderCommand* command)
{
float z = command->getGlobalOrder();
if(z < 0)
_queueNegZ.push_back(command);
else if(z > 0)
_queuePosZ.push_back(command);
else
_queue0.push_back(command);
}
ssize_t RenderQueue::size() const
{
return _queueNegZ.size() + _queue0.size() + _queuePosZ.size();
}
void RenderQueue::sort()
{
// Don't sort _queue0, it already comes sorted
std::sort(std::begin(_queueNegZ), std::end(_queueNegZ), compareRenderCommand);
std::sort(std::begin(_queuePosZ), std::end(_queuePosZ), compareRenderCommand);
}
RenderCommand* RenderQueue::operator[](ssize_t index) const
{
if(index < _queueNegZ.size())
return _queueNegZ[index];
index -= _queueNegZ.size();
if(index < _queue0.size())
return _queue0[index];
index -= _queue0.size();
if(index < _queuePosZ.size())
return _queuePosZ[index];
CCASSERT(false, "invalid index");
return nullptr;
}
void RenderQueue::clear()
{
_queueNegZ.clear();
_queue0.clear();
_queuePosZ.clear();
}
//
//
//
#define DEFAULT_RENDER_QUEUE 0 #define DEFAULT_RENDER_QUEUE 0
Renderer::Renderer() Renderer::Renderer()
@ -176,13 +233,14 @@ void Renderer::mapBuffers()
void Renderer::addCommand(RenderCommand* command) void Renderer::addCommand(RenderCommand* command)
{ {
command->generateID(); int renderQueue =_commandGroupStack.top();
_renderGroups[_commandGroupStack.top()].push_back(command); addCommand(command, renderQueue);
} }
void Renderer::addCommand(RenderCommand* command, int renderQueue) void Renderer::addCommand(RenderCommand* command, int renderQueue)
{ {
command->generateID(); CCASSERT(renderQueue >=0, "Invalid render queue");
CCASSERT(command->getType() != RenderCommand::Type::UNKNOWN_COMMAND, "Invalid Command Type");
_renderGroups[renderQueue].push_back(command); _renderGroups[renderQueue].push_back(command);
} }
@ -203,11 +261,6 @@ int Renderer::createRenderQueue()
return (int)_renderGroups.size() - 1; return (int)_renderGroups.size() - 1;
} }
bool compareRenderCommand(RenderCommand* a, RenderCommand* b)
{
return a->getID() < b->getID();
}
void Renderer::render() void Renderer::render()
{ {
//Uncomment this once everything is rendered by new renderer //Uncomment this once everything is rendered by new renderer
@ -219,9 +272,9 @@ void Renderer::render()
{ {
//Process render commands //Process render commands
//1. Sort render commands based on ID //1. Sort render commands based on ID
for (auto it = _renderGroups.begin(); it != _renderGroups.end(); ++it) for (auto &renderqueue : _renderGroups)
{ {
std::stable_sort((*it).begin(), (*it).end(), compareRenderCommand); renderqueue.sort();
} }
while(!_renderStack.empty()) while(!_renderStack.empty())
@ -242,31 +295,41 @@ void Renderer::render()
if(commandType == RenderCommand::Type::QUAD_COMMAND) if(commandType == RenderCommand::Type::QUAD_COMMAND)
{ {
QuadCommand* cmd = static_cast<QuadCommand*>(command); auto cmd = static_cast<QuadCommand*>(command);
ssize_t cmdQuadCount = cmd->getQuadCount(); ssize_t cmdQuadCount = cmd->getQuadCount();
//Batch quads //Batch quads
if(_numQuads + cmdQuadCount > VBO_SIZE) if(_numQuads + cmdQuadCount > VBO_SIZE)
{ {
CCASSERT(cmdQuadCount < VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command"); CCASSERT(cmdQuadCount>=0 && cmdQuadCount<VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command");
//Draw batched quads if VBO is full //Draw batched quads if VBO is full
_lastCommand --;
drawBatchedQuads(); drawBatchedQuads();
_lastCommand ++;
} }
memcpy(_quads + _numQuads, cmd->getQuad(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount); memcpy(_quads + _numQuads, cmd->getQuads(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount);
convertToWorldCoordiantes(_quads + _numQuads, cmdQuadCount, cmd->getModelView());
_numQuads += cmdQuadCount; _numQuads += cmdQuadCount;
} }
else if(commandType == RenderCommand::Type::CUSTOM_COMMAND) else if(commandType == RenderCommand::Type::CUSTOM_COMMAND)
{ {
flush(); flush();
CustomCommand* cmd = static_cast<CustomCommand*>(command); auto cmd = static_cast<CustomCommand*>(command);
cmd->execute();
}
else if(commandType == RenderCommand::Type::BATCH_COMMAND)
{
flush();
auto cmd = static_cast<BatchCommand*>(command);
cmd->execute(); cmd->execute();
} }
else if(commandType == RenderCommand::Type::GROUP_COMMAND) else if(commandType == RenderCommand::Type::GROUP_COMMAND)
{ {
flush(); flush();
GroupCommand* cmd = static_cast<GroupCommand*>(command); auto cmd = static_cast<GroupCommand*>(command);
_renderStack.top().currentIndex = i + 1; _renderStack.top().currentIndex = i + 1;
@ -279,6 +342,7 @@ void Renderer::render()
} }
else else
{ {
CCASSERT(true, "Invalid command");
flush(); flush();
} }
} }
@ -317,6 +381,29 @@ void Renderer::render()
_lastMaterialID = 0; _lastMaterialID = 0;
} }
void Renderer::convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView)
{
// kmMat4 matrixP, mvp;
// kmGLGetMatrix(KM_GL_PROJECTION, &matrixP);
// kmMat4Multiply(&mvp, &matrixP, &modelView);
for(ssize_t i=0; i<quantity; ++i) {
V3F_C4B_T2F_Quad *q = &quads[i];
kmVec3 *vec1 = (kmVec3*)&q->bl.vertices;
kmVec3Transform(vec1, vec1, &modelView);
kmVec3 *vec2 = (kmVec3*)&q->br.vertices;
kmVec3Transform(vec2, vec2, &modelView);
kmVec3 *vec3 = (kmVec3*)&q->tr.vertices;
kmVec3Transform(vec3, vec3, &modelView);
kmVec3 *vec4 = (kmVec3*)&q->tl.vertices;
kmVec3Transform(vec4, vec4, &modelView);
}
}
void Renderer::drawBatchedQuads() void Renderer::drawBatchedQuads()
{ {
//TODO we can improve the draw performance by insert material switching command before hand. //TODO we can improve the draw performance by insert material switching command before hand.
@ -336,6 +423,13 @@ void Renderer::drawBatchedQuads()
//Set VBO data //Set VBO data
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// option 1: subdata
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] );
// option 2: data
// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW);
// option 3: orphaning + glMapBuffer
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (_numQuads), nullptr, GL_DYNAMIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (_numQuads), nullptr, GL_DYNAMIC_DRAW);
void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(buf, _quads, sizeof(_quads[0])* (_numQuads)); memcpy(buf, _quads, sizeof(_quads[0])* (_numQuads));
@ -351,7 +445,7 @@ void Renderer::drawBatchedQuads()
#define kQuadSize sizeof(_quads[0].bl) #define kQuadSize sizeof(_quads[0].bl)
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(_quads[0]) * _numQuads , _quads); glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _numQuads , _quads, GL_DYNAMIC_DRAW);
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
@ -368,12 +462,12 @@ void Renderer::drawBatchedQuads()
} }
//Start drawing verties in batch //Start drawing verties in batch
for(size_t i = _firstCommand; i <= _lastCommand; i++) for(ssize_t i = _firstCommand; i <= _lastCommand; i++)
{ {
RenderCommand* command = _renderGroups[_renderStack.top().renderQueueID][i]; auto command = _renderGroups[_renderStack.top().renderQueueID][i];
if (command->getType() == RenderCommand::Type::QUAD_COMMAND) if (command->getType() == RenderCommand::Type::QUAD_COMMAND)
{ {
QuadCommand* cmd = static_cast<QuadCommand*>(command); auto cmd = static_cast<QuadCommand*>(command);
if(_lastMaterialID != cmd->getMaterialID()) if(_lastMaterialID != cmd->getMaterialID())
{ {
//Draw quads //Draw quads
@ -414,7 +508,7 @@ void Renderer::drawBatchedQuads()
} }
_firstCommand = _lastCommand; _firstCommand = _lastCommand + 1;
_numQuads = 0; _numQuads = 0;
} }

View File

@ -37,12 +37,31 @@ NS_CC_BEGIN
class EventListenerCustom; class EventListenerCustom;
typedef std::vector<RenderCommand*> RenderQueue; /** Class that knows how to sort the Commands.
Since the commands that have z==0 are "pushed back" in
the correct order, the only Commands that need to be sorted,
are the ones that have z <0 and z >0.
And that is what this class does.
*/
class RenderQueue {
public:
void push_back(RenderCommand* command);
ssize_t size() const;
void sort();
RenderCommand* operator[](ssize_t index) const;
void clear();
protected:
std::vector<RenderCommand*> _queueNegZ;
std::vector<RenderCommand*> _queue0;
std::vector<RenderCommand*> _queuePosZ;
};
struct RenderStackElement struct RenderStackElement
{ {
int renderQueueID; int renderQueueID;
size_t currentIndex; ssize_t currentIndex;
}; };
class Renderer class Renderer
@ -75,18 +94,21 @@ protected:
void mapBuffers(); void mapBuffers();
void drawBatchedQuads(); void drawBatchedQuads();
//Draw the previews queued quads and flush previous context //Draw the previews queued quads and flush previous context
void flush(); void flush();
void convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView);
std::stack<int> _commandGroupStack; std::stack<int> _commandGroupStack;
std::stack<RenderStackElement> _renderStack; std::stack<RenderStackElement> _renderStack;
std::vector<RenderQueue> _renderGroups; std::vector<RenderQueue> _renderGroups;
int _lastMaterialID; uint32_t _lastMaterialID;
size_t _firstCommand; ssize_t _firstCommand;
size_t _lastCommand; ssize_t _lastCommand;
V3F_C4B_T2F_Quad _quads[VBO_SIZE]; V3F_C4B_T2F_Quad _quads[VBO_SIZE];
GLushort _indices[6 * VBO_SIZE]; GLushort _indices[6 * VBO_SIZE];

View File

@ -50,6 +50,9 @@
#include "CCScheduler.h" #include "CCScheduler.h"
#include "CCScene.h" #include "CCScene.h"
#include "CCPlatformConfig.h" #include "CCPlatformConfig.h"
#include "platform/CCFileUtils.h"
#include "CCConfiguration.h"
#include "CCTextureCache.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -61,7 +64,7 @@ NS_CC_BEGIN
static ssize_t mydprintf(int sock, const char *format, ...) static ssize_t mydprintf(int sock, const char *format, ...)
{ {
va_list args; va_list args;
char buf[1024]; char buf[16386];
va_start(args, format); va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args); vsnprintf(buf, sizeof(buf), format, args);
@ -92,6 +95,33 @@ static void printSceneGraphBoot(int fd)
mydprintf(fd, "Total Nodes: %d\n", total); mydprintf(fd, "Total Nodes: %d\n", total);
} }
static void printFileUtils(int fd)
{
FileUtils* fu = FileUtils::getInstance();
mydprintf(fd, "\nSearch Paths:\n");
auto list = fu->getSearchPaths();
for( const auto &item : list) {
mydprintf(fd, "%s\n", item.c_str());
}
mydprintf(fd, "\nResolution Order:\n");
list = fu->getSearchResolutionsOrder();
for( const auto &item : list) {
mydprintf(fd, "%s\n", item.c_str());
}
mydprintf(fd, "\nWriteble Path:\n");
mydprintf(fd, "%s\n", fu->getWritablePath().c_str());
mydprintf(fd, "\nFull Path Cache:\n");
auto cache = fu->getFullPathCache();
for( const auto &item : cache) {
mydprintf(fd, "%s -> %s\n", item.first.c_str(), item.second.c_str());
}
}
#if defined(__MINGW32__) #if defined(__MINGW32__)
static const char* inet_ntop(int af, const void* src, char* dst, int cnt) static const char* inet_ntop(int af, const void* src, char* dst, int cnt)
{ {
@ -114,24 +144,7 @@ static const char* inet_ntop(int af, const void* src, char* dst, int cnt)
// Free functions to log // Free functions to log
// //
// XXX: Deprecated static void _log(const char *format, va_list args)
void CCLog(const char * format, ...)
{
va_list args;
va_start(args, format);
log(format, args);
va_end(args);
}
void log(const char * format, ...)
{
va_list args;
va_start(args, format);
log(format, args);
va_end(args);
}
void log(const char *format, va_list args)
{ {
char buf[MAX_LOG_LENGTH]; char buf[MAX_LOG_LENGTH];
@ -159,6 +172,22 @@ void log(const char *format, va_list args)
Director::getInstance()->getConsole()->log(buf); Director::getInstance()->getConsole()->log(buf);
} }
// XXX: Deprecated
void CCLog(const char * format, ...)
{
va_list args;
va_start(args, format);
_log(format, args);
va_end(args);
}
void log(const char * format, ...)
{
va_list args;
va_start(args, format);
_log(format, args);
va_end(args);
}
// //
// Console code // Console code
@ -174,6 +203,7 @@ Console::Console()
{ {
// VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'. // VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'.
Command commands[] = { Command commands[] = {
{ "config", std::bind(&Console::commandConfig, this, std::placeholders::_1, std::placeholders::_2) },
{ "debug msg on", [&](int fd, const char* command) { { "debug msg on", [&](int fd, const char* command) {
_sendDebugStrings = true; _sendDebugStrings = true;
} }, } },
@ -181,6 +211,7 @@ Console::Console()
_sendDebugStrings = false; _sendDebugStrings = false;
} }, } },
{ "exit", std::bind(&Console::commandExit, this, std::placeholders::_1, std::placeholders::_2) }, { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1, std::placeholders::_2) },
{ "fileutils dump", std::bind(&Console::commandFileUtilsDump, this, std::placeholders::_1, std::placeholders::_2) },
{ "fps on", [](int fd, const char* command) { { "fps on", [](int fd, const char* command) {
Director *dir = Director::getInstance(); Director *dir = Director::getInstance();
Scheduler *sched = dir->getScheduler(); Scheduler *sched = dir->getScheduler();
@ -193,6 +224,7 @@ Console::Console()
} }, } },
{ "help", std::bind(&Console::commandHelp, this, std::placeholders::_1, std::placeholders::_2) }, { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1, std::placeholders::_2) },
{ "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1, std::placeholders::_2) }, { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1, std::placeholders::_2) },
{ "textures", std::bind(&Console::commandTextures, this, std::placeholders::_1, std::placeholders::_2) },
}; };
_maxCommands = sizeof(commands)/sizeof(commands[0]); _maxCommands = sizeof(commands)/sizeof(commands[0]);
@ -340,6 +372,31 @@ void Console::commandSceneGraph(int fd, const char *command)
sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) ); sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) );
} }
void Console::commandFileUtilsDump(int fd, const char *command)
{
Scheduler *sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread( std::bind(&printFileUtils, fd) );
}
void Console::commandConfig(int fd, const char *command)
{
Scheduler *sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread( [&](){
mydprintf(fd, "%s", Configuration::getInstance()->getInfo().c_str());
}
);
}
void Console::commandTextures(int fd, const char *command)
{
Scheduler *sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread( [&](){
mydprintf(fd, "%s", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str());
}
);
}
bool Console::parseCommand(int fd) bool Console::parseCommand(int fd)
{ {
auto r = readline(fd); auto r = readline(fd);

View File

@ -58,7 +58,6 @@ static const int MAX_LOG_LENGTH = 16*1024;
@brief Output Debug message. @brief Output Debug message.
*/ */
void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2); void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2);
void CC_DLL log(const char * format, va_list args);
/** Console is helper class that lets the developer control the game from TCP connection. /** Console is helper class that lets the developer control the game from TCP connection.
Console will spawn a new thread that will listen to a specified TCP port. Console will spawn a new thread that will listen to a specified TCP port.
@ -109,6 +108,9 @@ protected:
void commandHelp(int fd, const char *command); void commandHelp(int fd, const char *command);
void commandExit(int fd, const char *command); void commandExit(int fd, const char *command);
void commandSceneGraph(int fd, const char *command); void commandSceneGraph(int fd, const char *command);
void commandFileUtilsDump(int fd, const char *command);
void commandConfig(int fd, const char *command);
void commandTextures(int fd, const char *command);
// file descriptor: socket, console, etc. // file descriptor: socket, console, etc.
int _listenfd; int _listenfd;

View File

@ -25,10 +25,17 @@
#ifndef __CCMAP_H__ #ifndef __CCMAP_H__
#define __CCMAP_H__ #define __CCMAP_H__
#define USE_STD_UNORDERED_MAP 1
#include "ccMacros.h" #include "ccMacros.h"
#include "CCObject.h" #include "CCObject.h"
#include <vector> #include <vector>
#if USE_STD_UNORDERED_MAP
#include <unordered_map> #include <unordered_map>
#else
#include <map>
#endif
NS_CC_BEGIN NS_CC_BEGIN
@ -44,7 +51,11 @@ public:
// ------------------------------------------ // ------------------------------------------
// Iterators // Iterators
// ------------------------------------------ // ------------------------------------------
#if USE_STD_UNORDERED_MAP
typedef std::unordered_map<K, V> RefMap; typedef std::unordered_map<K, V> RefMap;
#else
typedef std::map<K, V> RefMap;
#endif
typedef typename RefMap::iterator iterator; typedef typename RefMap::iterator iterator;
typedef typename RefMap::const_iterator const_iterator; typedef typename RefMap::const_iterator const_iterator;
@ -104,25 +115,39 @@ public:
/** Sets capacity of the map */ /** Sets capacity of the map */
void reserve(ssize_t capacity) void reserve(ssize_t capacity)
{ {
#if USE_STD_UNORDERED_MAP
_data.reserve(capacity); _data.reserve(capacity);
#endif
} }
/** Returns the number of buckets in the Map container. */ /** Returns the number of buckets in the Map container. */
ssize_t bucketCount() const ssize_t bucketCount() const
{ {
#if USE_STD_UNORDERED_MAP
return _data.bucket_count(); return _data.bucket_count();
#else
return 0;
#endif
} }
/** Returns the number of elements in bucket n. */ /** Returns the number of elements in bucket n. */
ssize_t bucketSize(ssize_t n) const ssize_t bucketSize(ssize_t n) const
{ {
#if USE_STD_UNORDERED_MAP
return _data.bucket_size(n); return _data.bucket_size(n);
#else
return 0;
#endif
} }
/** Returns the bucket number where the element with key k is located. */ /** Returns the bucket number where the element with key k is located. */
ssize_t bucket(const K& k) const ssize_t bucket(const K& k) const
{ {
#if USE_STD_UNORDERED_MAP
return _data.bucket(k); return _data.bucket(k);
#else
return 0;
#endif
} }
/** The number of elements in the map. */ /** The number of elements in the map. */
@ -147,6 +172,8 @@ public:
if (!_data.empty()) if (!_data.empty())
{ {
keys.reserve(_data.size());
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{ {
keys.push_back(iter->first); keys.push_back(iter->first);
@ -160,6 +187,10 @@ public:
{ {
std::vector<K> keys; std::vector<K> keys;
if (!_data.empty())
{
keys.reserve(_data.size() / 10);
for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)
{ {
if (iter->second == object) if (iter->second == object)
@ -167,6 +198,9 @@ public:
keys.push_back(iter->first); keys.push_back(iter->first);
} }
} }
}
keys.shrink_to_fit();
return keys; return keys;
} }

View File

@ -1,7 +1,11 @@
#ifndef __CCB_CCBANIMATION_MANAGER_H__ #ifndef __CCB_CCBANIMATION_MANAGER_H__
#define __CCB_CCBANIMATION_MANAGER_H__ #define __CCB_CCBANIMATION_MANAGER_H__
#include "cocos2d.h" #include "CCMap.h"
#include "CCActionInterval.h"
#include "CCActionInstant.h"
#include "CCActionEase.h"
#include "extensions/ExtensionMacros.h" #include "extensions/ExtensionMacros.h"
#include "CCBSequence.h" #include "CCBSequence.h"
#include "CCBSequenceProperty.h" #include "CCBSequenceProperty.h"

View File

@ -1,7 +1,9 @@
#ifndef __CCB_KEYFRAME_H__ #ifndef __CCB_KEYFRAME_H__
#define __CCB_KEYFRAME_H__ #define __CCB_KEYFRAME_H__
#include "cocos2d.h" #include "CCObject.h"
#include "CCValue.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCBMEMBERVARIABLEASSIGNER_H_ #ifndef _CCB_CCBMEMBERVARIABLEASSIGNER_H_
#define _CCB_CCBMEMBERVARIABLEASSIGNER_H_ #define _CCB_CCBMEMBERVARIABLEASSIGNER_H_
#include "cocos2d.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,7 +1,13 @@
#include "CCBReader.h" #include <ctype.h>
#include <algorithm> #include <algorithm>
#include "CCDirector.h"
#include "platform/CCFileUtils.h"
#include "CCScene.h"
#include "CCTextureCache.h"
#include "CCSpriteFrameCache.h"
#include "CCBReader.h"
#include "CCNodeLoader.h" #include "CCNodeLoader.h"
#include "CCNodeLoaderLibrary.h" #include "CCNodeLoaderLibrary.h"
#include "CCNodeLoaderListener.h" #include "CCNodeLoaderListener.h"
@ -11,7 +17,7 @@
#include "CCBSequenceProperty.h" #include "CCBSequenceProperty.h"
#include "CCBKeyframe.h" #include "CCBKeyframe.h"
#include <ctype.h>
using namespace std; using namespace std;
using namespace cocos2d; using namespace cocos2d;

View File

@ -1,9 +1,12 @@
#ifndef _CCB_CCBREADER_H_ #ifndef _CCB_CCBREADER_H_
#define _CCB_CCBREADER_H_ #define _CCB_CCBREADER_H_
#include "cocos2d.h"
#include <string> #include <string>
#include <vector> #include <vector>
#include "CCNode.h"
#include "CCData.h"
#include "CCMap.h"
#include "CCBSequence.h" #include "CCBSequence.h"
#include "extensions/GUI/CCControlExtension/CCControl.h" #include "extensions/GUI/CCControlExtension/CCControl.h"

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCBSELECTORRESOLVER_H_ #ifndef _CCB_CCBSELECTORRESOLVER_H_
#define _CCB_CCBSELECTORRESOLVER_H_ #define _CCB_CCBSELECTORRESOLVER_H_
#include "cocos2d.h"
#include "extensions//GUI/CCControlExtension/CCInvocation.h" #include "extensions//GUI/CCControlExtension/CCInvocation.h"

View File

@ -2,7 +2,8 @@
#define __CCB_CCSEQUENCE_H__ #define __CCB_CCSEQUENCE_H__
#include <string> #include <string>
#include "cocos2d.h"
#include "CCObject.h"
#include "CCBSequenceProperty.h" #include "CCBSequenceProperty.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,7 +1,8 @@
#ifndef __CCB_SEQUENCE_PROPERTY_H__ #ifndef __CCB_SEQUENCE_PROPERTY_H__
#define __CCB_SEQUENCE_PROPERTY_H__ #define __CCB_SEQUENCE_PROPERTY_H__
#include "cocos2d.h" #include "CCObject.h"
#include "CCVector.h"
#include "CCBKeyframe.h" #include "CCBKeyframe.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCLABELBMFONTLOADER_H_ #ifndef _CCB_CCLABELBMFONTLOADER_H_
#define _CCB_CCLABELBMFONTLOADER_H_ #define _CCB_CCLABELBMFONTLOADER_H_
#include "CCObject.h"
#include "CCLabelBMFont.h"
#include "CCNodeLoader.h" #include "CCNodeLoader.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCLABELTTFLOADER_H_ #ifndef _CCB_CCLABELTTFLOADER_H_
#define _CCB_CCLABELTTFLOADER_H_ #define _CCB_CCLABELTTFLOADER_H_
#include "CCObject.h"
#include "CCLabelTTF.h"
#include "CCNodeLoader.h" #include "CCNodeLoader.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCMENUITEMLOADER_H_ #ifndef _CCB_CCMENUITEMLOADER_H_
#define _CCB_CCMENUITEMLOADER_H_ #define _CCB_CCMENUITEMLOADER_H_
#include "CCObject.h"
#include "CCMenuItem.h"
#include "CCLayerLoader.h" #include "CCLayerLoader.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -2,6 +2,8 @@
#define _CCB_CCMENULOADER_H_ #define _CCB_CCMENULOADER_H_
#include "CCLayerLoader.h" #include "CCLayerLoader.h"
#include "CCObject.h"
#include "CCMenu.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,7 +1,6 @@
#ifndef __CCB_CCNODE_RELATIVEPOSITIONING_H__ #ifndef __CCB_CCNODE_RELATIVEPOSITIONING_H__
#define __CCB_CCNODE_RELATIVEPOSITIONING_H__ #define __CCB_CCNODE_RELATIVEPOSITIONING_H__
#include "cocos2d.h"
#include "CCBReader.h" #include "CCBReader.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,9 +1,12 @@
#include "cocos2d.h"
#include "CCNodeLoader.h" #include "CCNodeLoader.h"
#include "CCBSelectorResolver.h" #include "CCBSelectorResolver.h"
#include "CCBMemberVariableAssigner.h" #include "CCBMemberVariableAssigner.h"
#include "CCBAnimationManager.h" #include "CCBAnimationManager.h"
#include "CCNode+CCBRelativePositioning.h" #include "CCNode+CCBRelativePositioning.h"
using namespace std; using namespace std;
using namespace cocos2d; using namespace cocos2d;
using namespace cocos2d::extension; using namespace cocos2d::extension;

View File

@ -2,7 +2,6 @@
#define _CCB_CCNODELOADER_H_ #define _CCB_CCNODELOADER_H_
#include "extensions/GUI/CCControlExtension/CCInvocation.h" #include "extensions/GUI/CCControlExtension/CCInvocation.h"
#include "cocos2d.h"
#include "CCBReader.h" #include "CCBReader.h"
#include "extensions/GUI/CCControlExtension/CCControl.h" #include "extensions/GUI/CCControlExtension/CCControl.h"

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCNODELOADERLIBRARY_H_ #ifndef _CCB_CCNODELOADERLIBRARY_H_
#define _CCB_CCNODELOADERLIBRARY_H_ #define _CCB_CCNODELOADERLIBRARY_H_
#include "cocos2d.h"
#include "CCBReader.h" #include "CCBReader.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,7 +1,6 @@
#ifndef _CCB_CCNODELOADERLISTENER_H_ #ifndef _CCB_CCNODELOADERLISTENER_H_
#define _CCB_CCNODELOADERLISTENER_H_ #define _CCB_CCNODELOADERLISTENER_H_
#include "cocos2d.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -1,6 +1,9 @@
#ifndef _CCB_CCPARTICLESYSTEMQUADLOADER_H_ #ifndef _CCB_CCPARTICLESYSTEMQUADLOADER_H_
#define _CCB_CCPARTICLESYSTEMQUADLOADER_H_ #define _CCB_CCPARTICLESYSTEMQUADLOADER_H_
#include "CCObject.h"
#include "CCParticleSystemQuad.h"
#include "CCNodeLoader.h" #include "CCNodeLoader.h"
namespace cocosbuilder { namespace cocosbuilder {

View File

@ -25,7 +25,6 @@ THE SOFTWARE.
#ifndef __ActionEaseEx_H__ #ifndef __ActionEaseEx_H__
#define __ActionEaseEx_H__ #define __ActionEaseEx_H__
#include "cocos2d.h"
#include "cocostudio/CocoStudio.h" #include "cocostudio/CocoStudio.h"
namespace cocostudio { namespace cocostudio {

View File

@ -25,7 +25,8 @@ THE SOFTWARE.
#ifndef __ActionFRAME_H__ #ifndef __ActionFRAME_H__
#define __ActionFRAME_H__ #define __ActionFRAME_H__
#include "cocos2d.h" #include "CCGeometry.h"
#include "CCActionInterval.h"
namespace cocostudio { namespace cocostudio {

View File

@ -25,7 +25,7 @@ THE SOFTWARE.
#ifndef __ActionFrameEasing_H__ #ifndef __ActionFrameEasing_H__
#define __ActionFrameEasing_H__ #define __ActionFrameEasing_H__
#include "cocos2d.h" #include "CCObject.h"
namespace cocostudio { namespace cocostudio {

View File

@ -25,7 +25,6 @@ THE SOFTWARE.
#ifndef __ActionMANAGER_H__ #ifndef __ActionMANAGER_H__
#define __ActionMANAGER_H__ #define __ActionMANAGER_H__
#include "cocos2d.h"
#include "cocostudio/CCActionObject.h" #include "cocostudio/CCActionObject.h"
#include "cocostudio/DictionaryHelper.h" #include "cocostudio/DictionaryHelper.h"

Some files were not shown because too many files have changed in this diff Show More