Merge branch 'develop' of https://github.com/cocos2d/cocos2d-x into iss2771_physical

This commit is contained in:
boyu0 2013-11-15 16:38:58 +08:00
commit 988630c12f
361 changed files with 10076 additions and 11823 deletions

5
.gitignore vendored
View File

@ -100,3 +100,8 @@ tools/jenkins_scripts/mac/android/userconf.ini
# CTags
tags
# ignore files, created with make-all-linux-project script
/lib
/build/linux-build

16
AUTHORS
View File

@ -10,6 +10,7 @@ Core Developers:
Qingkui Hu (samuele3hu)
Huabing Xu (dabingnn)
Bo Yu (boyu0)
Wenhai Lin(Dhilan007)
Developers:
@ -594,9 +595,12 @@ Developers:
[Android] added EGL_RENDERABLE_TYPE to OpenGL attributes
Android: add xlargeScreens="true" to supports-screens
Trigger onKeyReleased only after the key has been released.
Makes Colors are now comparable and explicit convertible
bmanGH
Use gl caching functions in TexturePVR::createGLTexture()
Configuration of VAO in runtime
Add setUniformLocationWithMatrix2fv, setUniformLocationWithMatrix3fv mothed into GLProgram class
metadao
make create_project.py more pythonic and fix some typoes
@ -612,6 +616,7 @@ Developers:
Added support of passing array to cc.Sequence.create and cc.Spawn.create.
Fixed a bug that sys.localStorage.getItem() does not support non-ascii string.
Fixed a memory leak in XMLHttpRequest.
Fixed a bug that wrong convention to jsval in cccolor4f_to_jsval and cccolor3b_to_jsval.
Keita Obo (ktaobo)
Avoid unnecessary object duplication for Scale9Sprite.
@ -629,6 +634,7 @@ Developers:
Fixed a bug that CCBReader can't play sequence automatically in JSB.
Could not set next animation in CCBAnimationCompleted callback.
Fixed missing to add JSAutoCompartment when invoking JS functions from C++.
CCBReader: To set anchor point to 0,0 when created by loader
lite3
Fixed a bug that Node's anchor point was changed after being added to ScrollView.
@ -642,6 +648,16 @@ Developers:
ledyba
Fixed a bug that EventListeners can't be removed sometimes.
Fixed a bug that the data size has to be specified when parsing XML using TinyXML.
Closed X display after getting DPI on Linux.
Luis Parravicini (luisparravicini)
Fixed typos in create_project.py.
xhcnb
Device::setAccelerometerEnabled needs to be invoked before adding ACC listener.
bopohaa
Fixed a bug that Webp test crashes.
Retired Core Developers:
WenSheng Yang

View File

@ -14,8 +14,19 @@ cocos2d-x-3.0alpha1 @??? 2013
[FIX] When parsing XML using TinyXML, the data size has to be specified.
[FIX] Parameter type: const char* -> const string&
[FIX] Armature: many bug fixed, add more samples, add function to skip some frames when playing animation
[FIX] Configuration of VAO in runtime
[FIX] Webp Test Crashes.
[FIX] TransitionScenePageTurn: z fighting
[FIX] AssetsManager: Adding test whether the file directory exists when uncompressing file entry,if does not exist then create directory
[FIX] CCBReader: To set anchor point to 0,0 when loading Scale9Sprite
[NEW] Arm64 support.
[NEW] Added Mouse Support For Desktop Platforms.
[NEW] Point: Adds ANCHOR_XXX constants like ANCHOR_MIDDLE, ANCHOR_TOP_RIGHT, etc.
[NEW] Sprite: Override setScale(float scaleX, float scaleY)
[NEW] External: added | operator for Control::EventType
[NEW] Android & iOS screen size change support
[NEW] GLProgram: setUniformLocationWithMatrix2fv, setUniformLocationWithMatrix3fv
[NEW] Color[3|4][B|F]: comparable and explicit convertible
[Android]
[FIX] Added EGL_RENDERABLE_TYPE to OpenGL attributes
[FIX] Fixed application will crash when pause and resume.
@ -30,6 +41,7 @@ cocos2d-x-3.0alpha1 @??? 2013
[FIX] Can't click the area that outside of keyboard to close keyboard when using EditBox.
[Linux]
[NEW] Used CMake to build linux projects.
[FIX] Closed X display after getting DPI on Linux.
[Desktop]
[FIX] Trigger onKeyReleased only after the key has been released.
[Javascript binding]
@ -37,6 +49,8 @@ cocos2d-x-3.0alpha1 @??? 2013
[FIX] sys.localStorage.getItem() does not support non-ascii string.
[FIX] cc.Scheduler.schedule(target, func) without repeat argument couldn't repeat schedule forever on device.
[FIX] CCBReader can't play sequence automatically in JSB.
[NEW] main.js -> cocos2d-jsb.js
[FIX] Wrong convention to jsval in cccolor4f_to_jsval and cccolor3b_to_jsval
[Lua Binding]
[NEW] Added Armature lua binding and added test samples.

View File

@ -97,11 +97,15 @@ $ open samples.xcodeproj
* For Linux
```
$ cd cocos2d-x
$ cmake CMakeLists.txt
$ cd cocos2d-x/build
$ ./install-deps-linux.sh
$ cmake ..
$ make
```
You may meet building errors when building libGLFW.so. It is because libGL.so directs to an error target,
you should make it to direct to a correct one. `install-deps-linux.sh` only has to be run onece.
* For Windows
Open the `cocos2d-x/build/cocos2d-win32.vc2012.sln`

View File

@ -1,91 +0,0 @@
PLATFORM ?= linux
all:
chipmunk:
$(MAKE) -C ../external/chipmunk/proj.$(PLATFORM)
chipmunk-clean:
$(MAKE) -C ../external/chipmunk/proj.$(PLATFORM) clean
box2d:
$(MAKE) -C ../external/Box2D/proj.$(PLATFORM)
box2d-clean:
$(MAKE) -C ../external/Box2D/proj.$(PLATFORM) clean
cocos2dx: chipmunk
$(MAKE) -C ../cocos/2d
cocos2dx-clean:
$(MAKE) -C ../cocos/2d clean
audio: cocos2dx
$(MAKE) -C ../cocos/audio/proj.$(PLATFORM)
audio-clean:
$(MAKE) -C ../cocos/audio/proj.$(PLATFORM) clean
gui:
$(MAKE) -C ../cocos/gui
gui-clean:
$(MAKE) -C ../cocos/gui clean
network: cocos2dx
$(MAKE) -C ../cocos/network
network-clean:
$(MAKE) -C ../cocos/network clean
cocosbuilder:
$(MAKE) -C ../cocos/editor-support/cocosbuilder
cocosbuilder-clean:
$(MAKE) -C ../cocos/editor-support/cocosbuilder clean
spine:
$(MAKE) -C ../cocos/editor-support/spine
spine-clean:
$(MAKE) -C ../cocos/editor-support/spine clean
cocostudio:
$(MAKE) -C ../cocos/editor-support/cocostudio
cocostudio-clean:
$(MAKE) -C ../cocos/editor-support/cocostudio clean
extensions: chipmunk audio box2d
$(MAKE) -C ../extensions/proj.$(PLATFORM)
extensions-clean:
$(MAKE) -C ../extensions/proj.$(PLATFORM) clean
lua: extensions cocosbuilder cocostudio
$(MAKE) -C ../cocos/scripting/lua/bindings
lua-clean:
$(MAKE) -C ../cocos/scripting/lua/bindings clean
hellocpp: cocos2dx
$(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM)
hellocpp-clean:
$(MAKE) -C ../samples/Cpp/HelloCpp/proj.$(PLATFORM) clean
testcpp: cocos2dx audio extensions cocostudio gui cocosbuilder spine network
$(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM)
testcpp-clean:
$(MAKE) -C ../samples/Cpp/TestCpp/proj.$(PLATFORM) clean
simplegame: cocos2dx audio
$(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM)
simplegame-clean:
$(MAKE) -C ../samples/Cpp/SimpleGame/proj.$(PLATFORM) clean
all: chipmunk audio extensions cocos2dx lua hellocpp testcpp simplegame
clean: cocos2dx-clean box2d-clean chipmunk-clean audio-clean extensions-clean lua-clean hellocpp-clean testcpp-clean simplegame-clean
hellolua: cocos2dx lua
$(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM)
hellolua-clean:
$(MAKE) -C ../samples/Lua/HelloLua/proj.$(PLATFORM) clean
testlua: cocos2dx lua
$(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM)
testlua-clean:
$(MAKE) -C ../samples/Lua/TestLua/proj.$(PLATFORM) clean
all: hellolua testlua
clean: hellolua-clean testlua-clean
.PHONY: all clean

View File

@ -15,11 +15,12 @@ ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES
def usage():
print "%prog [-n ndk-build-parameter] target\n\
valid target are [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon\
|crystalcraze|moonwarriors|testjavascript|watermelonwithme], of course you can use 'cpp'\
to build all cpp samples, 'lua' to build all lua samples, 'jsb' to build all javascript samples,\
and 'all' for all samples"
print """%s [-n ndk-build-parameter] target.
Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon
|crystalcraze|moonwarriors|testjavascript|watermelonwithme]
You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely.""" % sys.argv[0]
def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
@ -95,7 +96,8 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param):
command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path)
else:
command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path)
os.system(command)
if os.system(command) != 0:
raise Exception("Build project [ " + app_android_root + " ] fails!")
def copy_files(src, dst):
@ -131,13 +133,26 @@ def copy_resources(target, app_android_root):
resources_dir = os.path.join(app_android_root, "../../Shared/games/CocosDragonJS/Published files Android")
if target == "crystalcraze":
resources_dir = os.path.join(app_android_root, "../../Shared/games/CrystalCraze/Published-Android")
if target == "moonwarriors":
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res")
if target == "testjavascript":
resources_dir = os.path.join(app_android_root, "../../Shared/tests/")
if target == "watermelonwithme":
resources_dir = os.path.join(app_android_root, "../../Shared/games/WatermelonWithMe")
copy_files(resources_dir, assets_dir)
if target != "moonwarriors":
copy_files(resources_dir, assets_dir)
else:
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res")
dst_dir = os.path.join(assets_dir, "res")
os.mkdir(dst_dir)
copy_files(resources_dir, dst_dir)
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/src")
dst_dir = os.path.join(assets_dir, "src")
os.mkdir(dst_dir)
copy_files(resources_dir, dst_dir)
resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors")
for item in os.listdir(resources_dir):
path = os.path.join(resources_dir, item)
if item.endswith('.js') and os.path.isfile(path):
shutil.copy(path, assets_dir)
# AssetsManager test should also copy javascript files
if target == "assetsmanager":
@ -205,4 +220,8 @@ if __name__ == '__main__':
if len(args) == 0:
usage()
else:
build_samples(args, opts.ndk_build_param)
try:
build_samples(args, opts.ndk_build_param)
except Exception as e:
print e
sys.exit(1)

View File

@ -1 +1 @@
30ca6c02884f9bc20405b3e657b444c0153bead7
e1cdac55b4aa56ff532e0d23fe27272510058a42

View File

@ -1 +1 @@
3ff18018375c71f683a484652678740cc6395eaf
9490bdedbc6e817240a1661c6bcbcafc9095c267

View File

@ -1,24 +0,0 @@
#!/bin/bash
# This script will perform a clean linux build of all targets in both
# debug and release configurations. It will also ensure that all the required
# packages are installed. For day-to-day work on the linux port it is
# faster/better to simply use 'make' either at the top level or in the subpject
# you are working on.
# Exit of first error.
set -e
# Change directory to the location of this script
cd $(dirname ${BASH_SOURCE[0]})
[ -z "$COCOS2DX_USEAPT" ] && COCOS2DX_USEAPT=true
if $COCOS2DX_USEAPT; then
./install-deps-linux.sh
fi
mkdir -p linux-build
cd linux-build
cmake ../..
make -j10

View File

@ -203,7 +203,7 @@ Sequence* Sequence::create(Array* arrayOfActions)
Sequence* pRet = NULL;
do
{
unsigned int count = arrayOfActions->count();
long count = arrayOfActions->count();
CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
@ -576,7 +576,7 @@ Spawn* Spawn::create(Array *arrayOfActions)
Spawn* pRet = NULL;
do
{
unsigned int count = arrayOfActions->count();
long count = arrayOfActions->count();
CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
if (count > 1)
@ -2100,7 +2100,7 @@ void Animate::update(float t)
}
Array* frames = _animation->getFrames();
int numberOfFrames = frames->count();
long numberOfFrames = frames->count();
SpriteFrame *frameToDisplay = NULL;
for( int i=_nextFrame; i < numberOfFrames; i++ ) {

View File

@ -123,7 +123,7 @@ void ActionManager::removeActionAtIndex(long index, tHashElement *element)
void ActionManager::pauseTarget(Object *target)
{
tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, element);
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
element->paused = true;
@ -133,7 +133,7 @@ void ActionManager::pauseTarget(Object *target)
void ActionManager::resumeTarget(Object *target)
{
tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, element);
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
element->paused = false;
@ -176,14 +176,14 @@ void ActionManager::addAction(Action *action, Node *target, bool paused)
tHashElement *element = NULL;
// we should convert it to Object*, because we save it as Object*
Object *tmp = target;
HASH_FIND_INT(_targets, &tmp, element);
HASH_FIND_PTR(_targets, &tmp, element);
if (! element)
{
element = (tHashElement*)calloc(sizeof(*element), 1);
element->paused = paused;
target->retain();
element->target = target;
HASH_ADD_INT(_targets, target, element);
HASH_ADD_PTR(_targets, target, element);
}
actionAllocWithHashElement(element);
@ -215,7 +215,7 @@ void ActionManager::removeAllActionsFromTarget(Object *target)
}
tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, element);
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
if (ccArrayContainsObject(element->actions, element->currentAction) && (! element->currentActionSalvaged))
@ -250,7 +250,7 @@ void ActionManager::removeAction(Action *action)
tHashElement *element = NULL;
Object *target = action->getOriginalTarget();
HASH_FIND_INT(_targets, &target, element);
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
long i = ccArrayGetIndexOfObject(element->actions, action);
@ -271,7 +271,7 @@ void ActionManager::removeActionByTag(int tag, Object *target)
CCASSERT(target != NULL, "");
tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, element);
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
@ -298,7 +298,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const
CCASSERT(tag != Action::INVALID_TAG, "");
tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, element);
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
@ -327,10 +327,10 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const
// XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer
// and, it is not possible to get the address of a reference
unsigned int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const
long ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const
{
tHashElement *element = NULL;
HASH_FIND_INT(_targets, &target, element);
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
return element->actions ? element->actions->num : 0;

View File

@ -102,7 +102,7 @@ public:
* - If you are running 1 Sequence of 7 actions, it will return 1.
* - If you are running 7 Sequences of 2 actions, it will return 7.
*/
unsigned int getNumberOfRunningActionsInTarget(const Object *target) const;
long getNumberOfRunningActionsInTarget(const Object *target) const;
/** @deprecated use getNumberOfRunningActionsInTarget() instead */
CC_DEPRECATED_ATTRIBUTE inline unsigned int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); }

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "CCTexture2D.h"
#include "ccMacros.h"
#include "CCSpriteFrame.h"
#include "CCDirector.h"
NS_CC_BEGIN
@ -176,7 +177,7 @@ void Animation::addSpriteFrame(SpriteFrame *pFrame)
void Animation::addSpriteFrameWithFile(const char *filename)
{
Texture2D *texture = TextureCache::getInstance()->addImage(filename);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
Rect rect = Rect::ZERO;
rect.size = texture->getContentSize();
SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect);

View File

@ -76,7 +76,7 @@ AtlasNode * AtlasNode::create(const std::string& tile, long tileWidth, long tile
bool AtlasNode::initWithTileFile(const std::string& tile, long tileWidth, long tileHeight, long itemsToRender)
{
CCASSERT(tile.size() > 0, "file size should not be empty");
Texture2D *texture = TextureCache::getInstance()->addImage(tile);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(tile);
return initWithTexture(texture, tileWidth, tileHeight, itemsToRender);
}
@ -245,12 +245,12 @@ TextureAtlas * AtlasNode::getTextureAtlas() const
return _textureAtlas;
}
unsigned int AtlasNode::getQuadsToDraw() const
long AtlasNode::getQuadsToDraw() const
{
return _quadsToDraw;
}
void AtlasNode::setQuadsToDraw(unsigned int uQuadsToDraw)
void AtlasNode::setQuadsToDraw(long uQuadsToDraw)
{
_quadsToDraw = uQuadsToDraw;
}

View File

@ -77,8 +77,8 @@ public:
void setTextureAtlas(TextureAtlas* textureAtlas);
TextureAtlas* getTextureAtlas() const;
void setQuadsToDraw(unsigned int quadsToDraw);
unsigned int getQuadsToDraw() const;
void setQuadsToDraw(long quadsToDraw);
long getQuadsToDraw() const;
// Overrides

View File

@ -259,7 +259,11 @@ bool Configuration::supportsDiscardFramebuffer() const
bool Configuration::supportsShareableVAO() const
{
return _supportsShareableVAO;
#if CC_TEXTURE_ATLAS_USE_VAO
return _supportsShareableVAO;
#else
return false;
#endif
}
//

View File

@ -145,6 +145,8 @@ bool Director::init(void)
_scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
_eventDispatcher = new EventDispatcher();
//init TextureCache
initTextureCache();
// create autorelease pool
PoolManager::sharedPoolManager()->push();
@ -359,6 +361,29 @@ void Director::setOpenGLView(EGLView *pobOpenGLView)
}
}
TextureCache* Director::getTextureCache() const
{
return _textureCache;
}
void Director::initTextureCache()
{
#ifdef EMSCRIPTEN
_textureCache = new TextureCacheEmscripten();
#else
_textureCache = new TextureCache();
#endif // EMSCRIPTEN
}
void Director::destroyTextureCache()
{
if (_textureCache)
{
_textureCache->waitForQuit();
CC_SAFE_RELEASE_NULL(_textureCache);
}
}
void Director::setViewport()
{
if (_openGLView)
@ -437,7 +462,7 @@ void Director::purgeCachedData(void)
if (s_SharedDirector->getOpenGLView())
{
SpriteFrameCache::getInstance()->removeUnusedSpriteFrames();
TextureCache::getInstance()->removeUnusedTextures();
_textureCache->removeUnusedTextures();
}
FileUtils::getInstance()->purgeCachedEntries();
}
@ -693,7 +718,6 @@ void Director::purgeDirector()
DrawPrimitives::free();
AnimationCache::destroyInstance();
SpriteFrameCache::destroyInstance();
TextureCache::destroyInstance();
ShaderCache::destroyInstance();
FileUtils::destroyInstance();
Configuration::destroyInstance();
@ -704,6 +728,8 @@ void Director::purgeDirector()
GL::invalidateStateCache();
destroyTextureCache();
CHECK_GL_ERROR_DEBUG();
// OpenGL view
@ -841,14 +867,13 @@ void Director::getFPSImageData(unsigned char** datapointer, long* length)
void Director::createStatsLabel()
{
Texture2D *texture = nullptr;
TextureCache *textureCache = TextureCache::getInstance();
if (_FPSLabel && _SPFLabel)
{
CC_SAFE_RELEASE_NULL(_FPSLabel);
CC_SAFE_RELEASE_NULL(_SPFLabel);
CC_SAFE_RELEASE_NULL(_drawsLabel);
textureCache->removeTextureForKey("/cc_fps_images");
_textureCache->removeTextureForKey("/cc_fps_images");
FileUtils::getInstance()->purgeCachedEntries();
}
@ -865,7 +890,7 @@ void Director::createStatsLabel()
return;
}
texture = textureCache->addImage(image, "/cc_fps_images");
texture = _textureCache->addImage(image, "/cc_fps_images");
CC_SAFE_RELEASE(image);
/*

View File

@ -54,6 +54,7 @@ class Node;
class Scheduler;
class ActionManager;
class EventDispatcher;
class TextureCache;
/**
@brief Class that creates and handles the main Window and manages how
@ -137,6 +138,8 @@ public:
inline EGLView* getOpenGLView() { return _openGLView; }
void setOpenGLView(EGLView *pobOpenGLView);
TextureCache* getTextureCache() const;
inline bool isNextDeltaTimeZero() { return _nextDeltaTimeZero; }
void setNextDeltaTimeZero(bool nextDeltaTimeZero);
@ -381,6 +384,10 @@ protected:
/** calculates delta time since last time it was called */
void calculateDeltaTime();
//textureCache creation or release
void initTextureCache();
void destroyTextureCache();
protected:
/** Scheduler associated with this director
@since v2.0
@ -403,6 +410,9 @@ protected:
/* The EGLView, where everything is rendered */
EGLView *_openGLView;
//texture cache belongs to this director
TextureCache *_textureCache;
double _animationInterval;
double _oldAnimationInterval;

View File

@ -25,6 +25,7 @@
#include "CCGL.h"
#include "CCNotificationCenter.h"
#include "CCEventType.h"
#include "CCConfiguration.h"
NS_CC_BEGIN
@ -114,11 +115,12 @@ DrawNode::~DrawNode()
glDeleteBuffers(1, &_vbo);
_vbo = 0;
#if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &_vao);
GL::bindVAO(0);
_vao = 0;
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
glDeleteVertexArrays(1, &_vao);
GL::bindVAO(0);
_vao = 0;
}
#if CC_ENABLE_CACHE_TEXTURE_DATA
NotificationCenter::getInstance()->removeObserver(this, EVNET_COME_TO_FOREGROUND);
@ -159,10 +161,11 @@ bool DrawNode::init()
ensureCapacity(512);
#if CC_TEXTURE_ATLAS_USE_VAO
glGenVertexArrays(1, &_vao);
GL::bindVAO(_vao);
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
glGenVertexArrays(1, &_vao);
GL::bindVAO(_vao);
}
glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
@ -179,9 +182,10 @@ bool DrawNode::init()
glBindBuffer(GL_ARRAY_BUFFER, 0);
#if CC_TEXTURE_ATLAS_USE_VAO
GL::bindVAO(0);
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
GL::bindVAO(0);
}
CHECK_GL_ERROR_DEBUG();
@ -206,21 +210,24 @@ void DrawNode::render()
glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)*_bufferCapacity, _buffer, GL_STREAM_DRAW);
_dirty = false;
}
#if CC_TEXTURE_ATLAS_USE_VAO
GL::bindVAO(_vao);
#else
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
if (Configuration::getInstance()->supportsShareableVAO())
{
GL::bindVAO(_vao);
}
else
{
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
// vertex
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices));
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
// vertex
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices));
// color
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors));
// color
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors));
// texcood
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords));
#endif
// texcood
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords));
}
glDrawArrays(GL_TRIANGLES, 0, _bufferCount);
glBindBuffer(GL_ARRAY_BUFFER, 0);

View File

@ -57,7 +57,7 @@ public:
CUSTOM
};
typedef int ListenerID;
typedef std::size_t ListenerID;
protected:
/** Constructor */

View File

@ -75,10 +75,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::create()
bool EventListenerTouchOneByOne::checkAvailable()
{
if (onTouchBegan == nullptr && onTouchMoved == nullptr
&& onTouchEnded == nullptr && onTouchCancelled == nullptr)
if (onTouchBegan == nullptr)
{
CCASSERT(false, "Invalid TouchEventListener.");
CCASSERT(false, "Invalid EventListenerTouchOneByOne!");
return false;
}
@ -150,7 +149,7 @@ bool EventListenerTouchAllAtOnce::checkAvailable()
if (onTouchesBegan == nullptr && onTouchesMoved == nullptr
&& onTouchesEnded == nullptr && onTouchesCancelled == nullptr)
{
CCASSERT(false, "Invalid TouchEventListener.");
CCASSERT(false, "Invalid EventListenerTouchAllAtOnce!");
return false;
}

View File

@ -34,7 +34,7 @@ FontFNT * FontFNT::create(const std::string& fntFilePath)
return nullptr;
// add the texture
Texture2D *tempTexture = TextureCache::getInstance()->addImage(newConf->getAtlasName());
Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(newConf->getAtlasName());
if (!tempTexture)
{
delete newConf;
@ -198,7 +198,7 @@ FontAtlas * FontFNT::createFontAtlas()
// add the texture (only one texture for now)
Texture2D *tempTexture = TextureCache::getInstance()->addImage(_configuration->getAtlasName());
Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName());
if (!tempTexture)
return 0;

View File

@ -87,11 +87,11 @@ FT_Library FontFreeType::getFTLibrary()
return _FTlibrary;
}
FontFreeType::FontFreeType(bool dynamicGlyphCollection)
: _letterPadding(5),
_ttfData(nullptr),
_dynamicGlyphCollection(dynamicGlyphCollection),
_fontRef(nullptr)
FontFreeType::FontFreeType(bool dynamicGlyphCollection)
: _fontRef(nullptr),
_letterPadding(5),
_ttfData(nullptr),
_dynamicGlyphCollection(dynamicGlyphCollection)
{
}
@ -136,7 +136,7 @@ FontFreeType::~FontFreeType()
}
if (_ttfData)
{
delete _ttfData;
free(_ttfData);
_ttfData = nullptr;
}
}

View File

@ -515,6 +515,24 @@ void GLProgram::setUniformLocationWith4fv(GLint location, GLfloat* floats, unsig
}
}
void GLProgram::setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) {
bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*4*numberOfMatrices);
if( updated )
{
glUniformMatrix2fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
}
}
void GLProgram::setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) {
bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*9*numberOfMatrices);
if( updated )
{
glUniformMatrix3fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
}
}
void GLProgram::setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices)
{

View File

@ -198,6 +198,12 @@ public:
/** calls glUniform4fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWith4fv(GLint location, GLfloat* floats, unsigned int numberOfArrays);
/** calls glUniformMatrix2fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices);
/** calls glUniformMatrix3fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices);
/** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices);

View File

@ -93,12 +93,13 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li
}
Label::Label(FontAtlas *atlas, TextHAlignment alignment)
: _currentUTF16String(0)
, _originalUTF16String(0)
, _fontAtlas(atlas)
, _alignment(alignment)
: _reusedLetter(nullptr)
, _lineBreakWithoutSpaces(false)
, _alignment(alignment)
, _currentUTF16String(0)
, _originalUTF16String(0)
, _advances(0)
, _fontAtlas(atlas)
, _displayedColor(Color3B::WHITE)
, _realColor(Color3B::WHITE)
, _cascadeColorEnabled(true)
@ -106,7 +107,6 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment)
, _displayedOpacity(255)
, _realOpacity(255)
, _isOpacityModifyRGB(true)
,_reusedLetter(nullptr)
{
}
@ -386,7 +386,7 @@ Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const F
bool Label::recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex)
{
if (spriteIndex >= _lettersInfo.size())
if (static_cast<std::size_t>(spriteIndex) >= _lettersInfo.size())
{
LetterInfo tmpInfo;
_lettersInfo.push_back(tmpInfo);
@ -402,7 +402,7 @@ bool Label::recordLetterInfo(const cocos2d::Point& point,unsigned short int theC
bool Label::recordPlaceholderInfo(int spriteIndex)
{
if (spriteIndex >= _lettersInfo.size())
if (static_cast<std::size_t>(spriteIndex) >= _lettersInfo.size())
{
LetterInfo tmpInfo;
_lettersInfo.push_back(tmpInfo);

View File

@ -83,38 +83,38 @@ public:
// CCLabelTextFormat protocol implementation
virtual std::vector<LetterInfo> *getLettersInfo() override { return &_lettersInfo; };
virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override;
virtual bool recordPlaceholderInfo(int spriteIndex) override;
virtual float getLetterPosXLeft( int index ) const override;
virtual float getLetterPosXRight( int index ) const override;
virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override;
virtual bool recordPlaceholderInfo(int spriteIndex) override;
virtual float getLetterPosXLeft( int index ) const override;
virtual float getLetterPosXRight( int index ) const override;
virtual Sprite * getLetter(int ID) override;
virtual Sprite * getLetter(int ID) override;
// font related stuff
virtual int getCommonLineHeight() const override;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override;
virtual int getXOffsetForChar(unsigned short c) const override;
virtual int getYOffsetForChar(unsigned short c) const override;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override;
virtual Rect getRectForChar(unsigned short c) const override;
virtual int getCommonLineHeight() const override;
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override;
virtual int getXOffsetForChar(unsigned short c) const override;
virtual int getYOffsetForChar(unsigned short c) const override;
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override;
virtual Rect getRectForChar(unsigned short c) const override;
// string related stuff
virtual int getStringNumLines() const override;
virtual int getStringLenght() const override;
virtual unsigned short getCharAtStringPosition(int position) const override;
virtual unsigned short * getUTF8String() const override;
virtual void assignNewUTF8String(unsigned short *newString) override;
virtual TextHAlignment getTextAlignment() const override;
virtual int getStringNumLines() const override;
virtual int getStringLenght() const override;
virtual unsigned short getCharAtStringPosition(int position) const override;
virtual unsigned short * getUTF8String() const override;
virtual void assignNewUTF8String(unsigned short *newString) override;
virtual TextHAlignment getTextAlignment() const override;
// label related stuff
virtual float getMaxLineWidth() const override;
virtual bool breakLineWithoutSpace() const override;
virtual Size getLabelContentSize() const override;
virtual void setLabelContentSize(const Size &newSize) override;
virtual float getMaxLineWidth() const override;
virtual bool breakLineWithoutSpace() const override;
virtual Size getLabelContentSize() const override;
virtual void setLabelContentSize(const Size &newSize) override;
// carloX
const char * getString() const { return "not implemented"; }
void addChild(Node * child, int zOrder=0, int tag=0);
virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; }
void addChild(Node * child, int zOrder=0, int tag=0) override;
private:
/**

View File

@ -56,7 +56,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& cha
bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, long itemWidth, long itemHeight, long startCharMap)
{
Texture2D *texture = TextureCache::getInstance()->addImage(charMapFile);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(charMapFile);
return initWithString(string, texture, itemWidth, itemHeight, startCharMap);
}
@ -127,9 +127,9 @@ void LabelAtlas::updateAtlasValues()
itemHeightInPixels = _itemHeight;
}
CCASSERT( n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length");
CCASSERT( static_cast<long>(n) <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length");
V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads();
for(int i = 0; i < n; i++) {
for(long i = 0; i < static_cast<long>(n); i++) {
unsigned char a = s[i] - _mapStartChar;
float row = (float) (a % _itemsPerRow);
@ -177,8 +177,8 @@ void LabelAtlas::updateAtlasValues()
}
if (n > 0 ){
_textureAtlas->setDirty(true);
int totalQuads = _textureAtlas->getTotalQuads();
if (n > totalQuads) {
long totalQuads = _textureAtlas->getTotalQuads();
if (static_cast<long>(n) > totalQuads) {
_textureAtlas->increaseTotalQuadsWith(n - totalQuads);
}
}
@ -188,7 +188,7 @@ void LabelAtlas::updateAtlasValues()
void LabelAtlas::setString(const std::string &label)
{
size_t len = label.size();
if (len > _textureAtlas->getTotalQuads())
if (static_cast<long>(len) > _textureAtlas->getTotalQuads())
{
_textureAtlas->resizeCapacity(len);
}
@ -203,9 +203,9 @@ void LabelAtlas::setString(const std::string &label)
_quadsToDraw = len;
}
const char* LabelAtlas::getString(void) const
const std::string& LabelAtlas::getString(void) const
{
return _string.c_str();
return _string;
}
//CCLabelAtlas - draw

View File

@ -87,11 +87,12 @@ public:
// super methods
virtual void updateAtlasValues();
virtual void setString(const std::string &label);
virtual const char* getString(void) const;
virtual void setString(const std::string &label) override;
virtual const std::string& getString(void) const override;
#if CC_LABELATLAS_DEBUG_DRAW
virtual void draw();
virtual void draw() override;
#endif
protected:

View File

@ -202,7 +202,7 @@ std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const std::string
{
size_t pos = strLeft.find('\n');
if (pos != (int)std::string::npos)
if (pos != std::string::npos)
{
// the data is more than a line.get one line
line = strLeft.substr(0, pos);
@ -486,7 +486,7 @@ bool LabelBMFont::initWithString(const std::string& theString, const std::string
_fntFile = fntFile;
texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName());
texture = Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName());
}
else
{
@ -767,9 +767,9 @@ void LabelBMFont::setString(unsigned short *newString, bool needUpdateLabel)
}
}
const char* LabelBMFont::getString(void) const
const std::string& LabelBMFont::getString() const
{
return _initialStringUTF8.c_str();
return _initialStringUTF8;
}
void LabelBMFont::setCString(const char *label)
@ -1073,9 +1073,9 @@ void LabelBMFont::updateLabel()
int size = multiline_string.size();
unsigned short* str_new = new unsigned short[size + 1];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
{
str_new[i] = multiline_string[i];
str_new[j] = multiline_string[j];
}
str_new[size] = '\0';
@ -1213,7 +1213,7 @@ void LabelBMFont::setFntFile(const char* fntFile)
CC_SAFE_RELEASE(_configuration);
_configuration = newConf;
this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName()));
this->setTexture(Director::getInstance()->getTextureCache()->addImage(_configuration->getAtlasName()));
this->createFontChars();
}
}

View File

@ -228,10 +228,10 @@ public:
/** updates the font chars based on the string to render */
void createFontChars();
// super method
virtual void setString(const std::string& newString);
virtual void setString(const std::string& newString) override;
virtual void setString(const std::string& newString, bool needUpdateLabel);
virtual const char* getString() const;
virtual const std::string& getString() const override;
virtual void setCString(const char *label);
virtual void setAnchorPoint(const Point& var);
virtual void updateLabel();

View File

@ -180,9 +180,9 @@ void LabelTTF::setString(const std::string &string)
}
}
const char* LabelTTF::getString(void) const
const std::string& LabelTTF::getString() const
{
return _string.c_str();
return _string;
}
const char* LabelTTF::description() const

View File

@ -144,8 +144,8 @@ public:
/** changes the string to render
* @warning Changing the string is as expensive as creating a new LabelTTF. To obtain better performance use LabelAtlas
*/
virtual void setString(const std::string &label);
virtual const char* getString(void) const;
virtual void setString(const std::string &label) override;
virtual const std::string& getString(void) const override;
TextHAlignment getHorizontalAlignment() const;
void setHorizontalAlignment(TextHAlignment alignment);

View File

@ -200,9 +200,9 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
int size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
{
strNew[i] = multiline_string[i];
strNew[j] = multiline_string[j];
}
strNew[size] = 0;

View File

@ -28,7 +28,7 @@ THE SOFTWARE.
#include "CCGLProgram.h"
#include "CCShaderCache.h"
#include "ccMacros.h"
#include "CCDirector.h"
#include "CCVertex.h"
NS_CC_BEGIN
@ -93,7 +93,7 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co
{
CCASSERT(path != NULL, "Invalid filename");
Texture2D *texture = TextureCache::getInstance()->addImage(path);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path);
return initWithFade(fade, minSeg, stroke, color, texture);
}

View File

@ -237,11 +237,13 @@ void Node::_setZOrder(int z)
void Node::setZOrder(int z)
{
_setZOrder(z);
if (_parent)
{
_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);
}

View File

@ -82,22 +82,22 @@ bool nodeComparisonLess(Object* p1, Object* p2);
class EventListener;
/** @brief Node is the main element. Anything that gets drawn or contains things that get drawn is a Node.
The most popular Nodes are: Scene, Layer, Sprite, Menu.
/** @brief Node is the base element of the Scene Graph. Element of the Scene Graph must be Node objects or subclasses of it.
The most common Node objects are: Scene, Layer, Sprite, Menu.
The main features of a Node are:
- They can contain other Node nodes (addChild, getChildByTag, removeChild, etc)
- They can schedule periodic callback (schedule, unschedule, etc)
- They can execute actions (runAction, stopAction, etc)
- They can contain other Node objects (`addChild`, `getChildByTag`, `removeChild`, etc)
- They can schedule periodic callback (`schedule`, `unschedule`, etc)
- They can execute actions (`runAction`, `stopAction`, etc)
Some Node nodes provide extra functionality for them or their children.
Some Node objects provide extra functionality for them or their children.
Subclassing a Node usually means (one/all) of:
- overriding init to initialize resources and schedule callbacks
- create callbacks to handle the advancement of time
- overriding draw to render the node
Features of Node:
Properties of Node:
- position
- scale (x, y)
- rotation (in degrees, clockwise)
@ -117,7 +117,7 @@ class EventListener;
- anchorPoint: (x=0,y=0)
Limitations:
- A Node is a "void" object. It doesn't have a texture
- A Node is a "invisible" object. If you want to draw something on the screen, you should use a Sprite instead. Or subclass Node and override `draw`.
Order in transformations with grid disabled
-# The node will be translated (position)
@ -189,15 +189,15 @@ public:
/**
* Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array.
*
* The Z order of node is relative to its "brothers": children of the same parent.
* It's nothing to do with OpenGL's z vertex. This one only affects the draw order of nodes in cocos2d.
* The larger number it is, the later this node will be drawn in each message loop.
* Please refer to setVertexZ(float) for the difference.
* The Z order of node is relative to its siblings.
* It is not related to the OpenGL's z property. This one only affects the draw order of itself and its siblings.
* Lower Z order number are drawn before higher numbers.
* Please refer to `setVertexZ(float)` for the difference.
*
* @param zOrder Z order of this node.
*/
virtual void setZOrder(int zOrder);
/**
/*
* Sets the z order which stands for the drawing order
*
* This is an internal method. Don't call it outside the framework.
@ -209,7 +209,7 @@ public:
/**
* Gets the Z order of this node.
*
* @see setZOrder(int)
* @see `setZOrder(int)`
*
* @return The Z order.
*/
@ -221,7 +221,7 @@ public:
* Differences between openGL Z vertex and cocos2d Z order:
* - 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
* - 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
*
@ -267,7 +267,7 @@ public:
/**
* Returns the scale factor on Y axis of this node
*
* @see setScaleY(float)
* @see `setScaleY(float)`
*
* @return The scale factor on Y axis.
*/
@ -285,7 +285,7 @@ public:
/**
* Gets the scale factor of the node, when X and Y have the same scale factor.
*
* @warning Assert when _scaleX != _scaleY.
* @warning Assert when `_scaleX != _scaleY`
* @see setScale(float)
*
* @return The scale factor of the node.
@ -305,13 +305,13 @@ public:
/**
* Changes the position (x,y) of the node in OpenGL coordinates
*
* Usually we use Point(x,y) to compose Point object.
* Usually we use `Point(x,y)` to compose Point object.
* The original point (0,0) is at the left-bottom corner of screen.
* For example, this codesnip sets the node in the center of screen.
* @code
* Size size = Director::getInstance()->getWinSize();
* node->setPosition( Point(size.width/2, size.height/2) )
* @endcode
@code
Size size = Director::getInstance()->getWinSize();
node->setPosition( Point(size.width/2, size.height/2) )
@endcode
*
* @param position The position (x,y) of the node in OpenGL coordinates
*/
@ -334,11 +334,11 @@ public:
* This method is binded to lua and javascript.
* Passing a number is 10 times faster than passing a object from lua to c++
*
* @code
* // sample code in lua
* local pos = node::getPosition() -- returns Point object from C++
* node:setPosition(x, y) -- pass x, y coordinate to C++
* @endcode
@code
// sample code in lua
local pos = node::getPosition() -- returns Point object from C++
node:setPosition(x, y) -- pass x, y coordinate to C++
@endcode
*
* @param x X coordinate for position
* @param y Y coordinate for position
@ -347,10 +347,8 @@ public:
/**
* Gets position in a more efficient way, returns two number instead of a Point object
*
* @see setPosition(float, float)
* @code
* @see `setPosition(float, float)`
* In js,out value not return
* @endcode
*/
virtual void getPosition(float* x, float* y) const;
/**
@ -376,7 +374,7 @@ public:
/**
* Returns the X skew angle of the node in degrees.
*
* @see setSkewX(float)
* @see `setSkewX(float)`
*
* @return The X skew angle of the node in degrees.
*/
@ -396,7 +394,7 @@ public:
/**
* Returns the Y skew angle of the node in degrees.
*
* @see setSkewY(float)
* @see `setSkewY(float)`
*
* @return The Y skew angle of the node in degrees.
*/
@ -418,7 +416,7 @@ public:
/**
* Returns the anchor point in percent.
*
* @see setAnchorPoint(const Point&)
* @see `setAnchorPoint(const Point&)`
*
* @return The anchor point of node.
*/
@ -427,7 +425,7 @@ public:
* Returns the anchorPoint in absolute pixels.
*
* @warning You can only read it. If you wish to modify it, use anchorPoint instead.
* @see getAnchorPoint()
* @see `getAnchorPoint()`
*
* @return The anchor point in absolute pixels.
*/
@ -446,7 +444,7 @@ public:
/**
* Returns the untransformed size of the node.
*
* @see setContentSize(const Size&)
* @see `setContentSize(const Size&)`
*
* @return The untransformed size of the node.
*/
@ -464,7 +462,7 @@ public:
/**
* Determines if the node is visible
*
* @see setVisible(bool)
* @see `setVisible(bool)`
*
* @return true if the node is visible, false if the node is hidden.
*/
@ -483,7 +481,7 @@ public:
/**
* Returns the rotation of the node in degrees.
*
* @see setRotation(float)
* @see `setRotation(float)`
*
* @return The rotation of the node in degrees.
*/
@ -502,7 +500,7 @@ public:
/**
* Gets the X rotation (angle) of the node in degrees which performs a horizontal rotation skew.
*
* @see setRotationX(float)
* @see `setRotationX(float)`
*
* @return The X rotation in degrees.
*/
@ -521,7 +519,7 @@ public:
/**
* Gets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew.
*
* @see setRotationY(float)
* @see `setRotationY(float)`
*
* @return The Y rotation in degrees.
*/
@ -542,7 +540,7 @@ public:
/**
* Returns the arrival order, indecates which children is added previously.
*
* @see setOrderOfArrival(unsigned int)
* @see `setOrderOfArrival(unsigned int)`
*
* @return The arrival order.
*/
@ -573,7 +571,7 @@ public:
/**
* Gets whether the anchor point will be (0,0) when you position this node.
*
* @see ignoreAnchorPointForPosition(bool)
* @see `ignoreAnchorPointForPosition(bool)`
*
* @return true if the anchor point will be (0,0) when you position this node.
*/
@ -625,13 +623,13 @@ public:
*
* Composing a "tree" structure is a very important feature of Node
* Here's a sample code of traversing children array:
* @code
* Node* node = NULL;
* CCARRAY_FOREACH(parent->getChildren(), node)
* {
* node->setPosition(0,0);
* }
* @endcode
@code
Node* node = NULL;
CCARRAY_FOREACH(parent->getChildren(), node)
{
node->setPosition(0,0);
}
@endcode
* This sample code traverses all children nodes, and set their position to (0,0)
*
* @return An array of children
@ -655,7 +653,7 @@ public:
/**
* Returns a pointer to the parent node
*
* @see setParent(Node*)
* @see `setParent(Node*)`
*
* @returns A pointer to the parnet node
*/
@ -668,7 +666,7 @@ public:
/**
* Removes this node itself from its parent node with a cleanup.
* If the node orphan, then nothing happens.
* @see removeFromParentAndCleanup(bool)
* @see `removeFromParentAndCleanup(bool)`
*/
virtual void removeFromParent();
/**
@ -698,7 +696,7 @@ public:
/**
* Removes all children from the container with a cleanup.
*
* @see removeAllChildrenWithCleanup(bool)
* @see `removeAllChildrenWithCleanup(bool)`
*/
virtual void removeAllChildren();
/**
@ -761,32 +759,32 @@ public:
* Returns a tag that is used to identify the node easily.
*
* You can set tags to node then identify them easily.
* @code
* #define TAG_PLAYER 1
* #define TAG_MONSTER 2
* #define TAG_BOSS 3
* // set tags
* node1->setTag(TAG_PLAYER);
* node2->setTag(TAG_MONSTER);
* node3->setTag(TAG_BOSS);
* parent->addChild(node1);
* parent->addChild(node2);
* parent->addChild(node3);
* // identify by tags
* Node* node = NULL;
* CCARRAY_FOREACH(parent->getChildren(), node)
* {
* switch(node->getTag())
* {
* case TAG_PLAYER:
* break;
* case TAG_MONSTER:
* break;
* case TAG_BOSS:
* break;
* }
* }
* @endcode
@code
#define TAG_PLAYER 1
#define TAG_MONSTER 2
#define TAG_BOSS 3
// set tags
node1->setTag(TAG_PLAYER);
node2->setTag(TAG_MONSTER);
node3->setTag(TAG_BOSS);
parent->addChild(node1);
parent->addChild(node2);
parent->addChild(node3);
// identify by tags
Node* node = NULL;
CCARRAY_FOREACH(parent->getChildren(), node)
{
switch(node->getTag())
{
case TAG_PLAYER:
break;
case TAG_MONSTER:
break;
case TAG_BOSS:
break;
}
}
@endcode
*
* @return A interger that identifies the node.
*/
@ -820,7 +818,7 @@ public:
* Sets a custom user data pointer
*
* You can set everything in UserData pointer, a data block, a structure or an object, etc.
* @warning Don't forget to release the memroy manually,
* @warning Don't forget to release the memory manually,
* especially before you change this data pointer, and before this node is autoreleased.
*
* @param userData A custom user data pointer
@ -875,9 +873,9 @@ public:
*
* Since v2.0, each rendering node must set its shader program.
* It should be set in initialize phase.
* @code
* node->setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
* @endcode
@code
node->setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
@endcode
*
* @param shaderProgram The shader program which fetchs from ShaderCache.
*/
@ -888,11 +886,11 @@ public:
/**
* Returns a camera object that lets you move the node using a gluLookAt
*
* @code
* Camera* camera = node->getCamera();
* camera->setEye(0, 0, 415/2);
* camera->setCenter(0, 0, 0);
* @endcode
@code
Camera* camera = node->getCamera();
camera->setEye(0, 0, 415/2);
camera->setCenter(0, 0, 0);
@endcode
*
* @return A Camera object that lets you move the node using a gluLookAt
*/
@ -966,10 +964,10 @@ public:
/**
* Override this method to draw your own node.
* The following GL states will be enabled by default:
* - glEnableClientState(GL_VERTEX_ARRAY);
* - glEnableClientState(GL_COLOR_ARRAY);
* - glEnableClientState(GL_TEXTURE_COORD_ARRAY);
* - glEnable(GL_TEXTURE_2D);
* - `glEnableClientState(GL_VERTEX_ARRAY);`
* - `glEnableClientState(GL_COLOR_ARRAY);`
* - `glEnableClientState(GL_TEXTURE_COORD_ARRAY);`
* - `glEnable(GL_TEXTURE_2D);`
* AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE
* But if you enable any other GL state, you should disable it after drawing your node.
*/
@ -986,7 +984,7 @@ public:
* The returned box is relative only to its parent.
*
* @note This method returns a temporaty variable, so it can't returns const Rect&
* @todo Rename to getBoundingBox() in the future versions.
* @todo Rename to `getBoundingBox()` in the future versions.
*
* @return A "local" axis aligned boudning box of the node.
*/
@ -1049,7 +1047,7 @@ public:
/**
* Gets an action from the running action list by its tag.
*
* @see setTag(int), getTag().
* @see `setTag(int)`, `getTag()`.
*
* @return The action object with the given tag.
*/
@ -1135,12 +1133,12 @@ public:
* Schedules a custom selector.
*
* If the selector is already scheduled, then the interval parameter will be updated without scheduling it again.
* @code
* // firstly, implement a schedule function
* void MyNode::TickMe(float dt);
* // wrap this function into a selector via schedule_selector marco.
* this->schedule(schedule_selector(MyNode::TickMe), 0, 0, 0);
* @endcode
@code
// firstly, implement a schedule function
void MyNode::TickMe(float dt);
// wrap this function into a selector via schedule_selector marco.
this->schedule(schedule_selector(MyNode::TickMe), 0, 0, 0);
@endcode
*
* @param selector The SEL_SCHEDULE selector to be scheduled.
* @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead.
@ -1152,7 +1150,7 @@ public:
/**
* Schedules a custom selector with an interval time in seconds.
* @see schedule(SEL_SCHEDULE, float, unsigned int, float)
* @see `schedule(SEL_SCHEDULE, float, unsigned int, float)`
*
* @param selector The SEL_SCHEDULE selector to be scheduled.
* @param interval Callback interval time in seconds. 0 means tick every frame,
@ -1162,7 +1160,7 @@ public:
/**
* Schedules a selector that runs only once, with a delay of 0 or larger
* @see schedule(SEL_SCHEDULE, float, unsigned int, float)
* @see `schedule(SEL_SCHEDULE, float, unsigned int, float)`
*
* @param selector The SEL_SCHEDULE selector to be scheduled.
* @param delay The amount of time that the first tick will wait before execution.
@ -1181,7 +1179,7 @@ public:
/**
* Unschedules a custom selector.
* @see schedule(SEL_SCHEDULE, float, unsigned int, float)
* @see `schedule(SEL_SCHEDULE, float, unsigned int, float)`
*
* @param selector A function wrapped as a selector
* @lua NA
@ -1242,7 +1240,7 @@ public:
*
* This method is moved from Sprite, so it's no longer specific to Sprite.
* As the result, you apply SpriteBatchNode's optimization on your customed Node.
* e.g., batchNode->addChild(myCustomNode), while you can only addChild(sprite) before.
* e.g., `batchNode->addChild(myCustomNode)`, while you can only addChild(sprite) before.
*/
virtual void updateTransform();
@ -1323,48 +1321,48 @@ public:
*
* @note The additional transform will be concatenated at the end of getNodeToParentTransform.
* It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn't).
* @code
// create a batchNode
SpriteBatchNode* batch= SpriteBatchNode::create("Icon-114.png");
this->addChild(batch);
// create two sprites, spriteA will be added to batchNode, they are using different textures.
Sprite* spriteA = Sprite::createWithTexture(batch->getTexture());
Sprite* spriteB = Sprite::create("Icon-72.png");
@code
// create a batchNode
SpriteBatchNode* batch= SpriteBatchNode::create("Icon-114.png");
this->addChild(batch);
batch->addChild(spriteA);
// We can't make spriteB as spriteA's child since they use different textures. So just add it to layer.
// But we want to simulate `parent-child` relationship for these two node.
this->addChild(spriteB);
// create two sprites, spriteA will be added to batchNode, they are using different textures.
Sprite* spriteA = Sprite::createWithTexture(batch->getTexture());
Sprite* spriteB = Sprite::create("Icon-72.png");
//position
spriteA->setPosition(Point(200, 200));
// Gets the spriteA's transform.
AffineTransform t = spriteA->getNodeToParentTransform();
// Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t);
batch->addChild(spriteA);
//scale
spriteA->setScale(2);
// Gets the spriteA's transform.
t = spriteA->getNodeToParentTransform();
// Sets the additional transform to spriteB, spriteB's scale will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t);
// We can't make spriteB as spriteA's child since they use different textures. So just add it to layer.
// But we want to simulate `parent-child` relationship for these two node.
this->addChild(spriteB);
//rotation
spriteA->setRotation(20);
// Gets the spriteA's transform.
t = spriteA->getNodeToParentTransform();
// Sets the additional transform to spriteB, spriteB's rotation will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t);
* @endcode
//position
spriteA->setPosition(Point(200, 200));
// Gets the spriteA's transform.
AffineTransform t = spriteA->getNodeToParentTransform();
// Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t);
//scale
spriteA->setScale(2);
// Gets the spriteA's transform.
t = spriteA->getNodeToParentTransform();
// Sets the additional transform to spriteB, spriteB's scale will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t);
//rotation
spriteA->setRotation(20);
// Gets the spriteA's transform.
t = spriteA->getNodeToParentTransform();
// Sets the additional transform to spriteB, spriteB's rotation will based on its pseudo parent i.e. spriteA.
spriteB->setAdditionalTransform(t);
@endcode
*/
void setAdditionalTransform(const AffineTransform& additionalTransform);

View File

@ -111,7 +111,7 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, unsigned int capacity)
*/
bool ParticleBatchNode::initWithFile(const char* fileImage, unsigned int capacity)
{
Texture2D *tex = TextureCache::getInstance()->addImage(fileImage);
Texture2D *tex = Director::getInstance()->getTextureCache()->addImage(fileImage);
return initWithTexture(tex, capacity);
}

View File

@ -42,7 +42,7 @@ static Texture2D* getDefaultTexture()
{
bool bRet = false;
const char* key = "/__firePngData";
texture = TextureCache::getInstance()->getTextureForKey(key);
texture = Director::getInstance()->getTextureCache()->getTextureForKey(key);
CC_BREAK_IF(texture != NULL);
pImage = new Image();
@ -50,7 +50,7 @@ static Texture2D* getDefaultTexture()
bRet = pImage->initWithImageData(__firePngData, sizeof(__firePngData));
CC_BREAK_IF(!bRet);
texture = TextureCache::getInstance()->addImage(pImage, key);
texture = Director::getInstance()->getTextureCache()->addImage(pImage, key);
} while (0);
CC_SAFE_RELEASE(pImage);

View File

@ -81,15 +81,15 @@ NS_CC_BEGIN
//
ParticleSystem::ParticleSystem()
: _configName("")
, _isBlendAdditive(false)
: _isBlendAdditive(false)
, _isAutoRemoveOnFinish(false)
, _plistFile("")
, _elapsed(0)
, _particles(NULL)
, _particles(nullptr)
, _configName("")
, _emitCounter(0)
, _particleIdx(0)
, _batchNode(NULL)
, _batchNode(nullptr)
, _atlasIndex(0)
, _transformSystemDirty(false)
, _allocatedParticles(0)
@ -113,11 +113,11 @@ ParticleSystem::ParticleSystem()
, _endSpinVar(0)
, _emissionRate(0)
, _totalParticles(0)
, _texture(NULL)
, _texture(nullptr)
, _blendFunc(BlendFunc::ALPHA_PREMULTIPLIED)
, _opacityModifyRGB(false)
, _positionType(PositionType::FREE)
, _yCoordFlipped(0)
, _positionType(PositionType::FREE)
{
modeA.gravity = Point::ZERO;
modeA.speed = 0;
@ -374,7 +374,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
// set not pop-up message box when load image failed
bool bNotify = FileUtils::getInstance()->isPopupNotify();
FileUtils::getInstance()->setPopupNotify(false);
tex = TextureCache::getInstance()->addImage(textureName.c_str());
tex = Director::getInstance()->getTextureCache()->addImage(textureName.c_str());
// reset the value of UIImage notify
FileUtils::getInstance()->setPopupNotify(bNotify);
}
@ -396,17 +396,17 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
CCASSERT( buffer != NULL, "CCParticleSystem: error decoding textureImageData");
CC_BREAK_IF(!buffer);
int deflatedLen = ZipUtils::ccInflateMemory(buffer, decodeLen, &deflated);
int deflatedLen = ZipUtils::inflateMemory(buffer, decodeLen, &deflated);
CCASSERT( deflated != NULL, "CCParticleSystem: error ungzipping textureImageData");
CC_BREAK_IF(!deflated);
// For android, we should retain it in VolatileTexture::addImage which invoked in TextureCache::getInstance()->addUIImage()
// For android, we should retain it in VolatileTexture::addImage which invoked in Director::getInstance()->getTextureCache()->addUIImage()
image = new Image();
bool isOK = image->initWithImageData(deflated, deflatedLen);
CCASSERT(isOK, "CCParticleSystem: error init image with Data");
CC_BREAK_IF(!isOK);
setTexture(TextureCache::getInstance()->addImage(image, textureName.c_str()));
setTexture(Director::getInstance()->getTextureCache()->addImage(image, textureName.c_str()));
image->release();
}
@ -420,8 +420,8 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const std::strin
bRet = true;
}
} while (0);
CC_SAFE_DELETE_ARRAY(buffer);
CC_SAFE_DELETE_ARRAY(deflated);
free(buffer);
free(deflated);
return bRet;
}

View File

@ -37,6 +37,7 @@ THE SOFTWARE.
#include "TransformUtils.h"
#include "CCNotificationCenter.h"
#include "CCEventType.h"
#include "CCConfiguration.h"
// extern
#include "kazmath/GL/matrix.h"
@ -57,11 +58,14 @@ bool ParticleSystemQuad::initWithTotalParticles(unsigned int numberOfParticles)
}
initIndices();
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
}
else
{
setupVBO();
}
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
@ -81,9 +85,7 @@ bool ParticleSystemQuad::initWithTotalParticles(unsigned int numberOfParticles)
ParticleSystemQuad::ParticleSystemQuad()
:_quads(NULL)
,_indices(NULL)
#if CC_TEXTURE_ATLAS_USE_VAO
,_VAOname(0)
#endif
{
memset(_buffersVBO, 0, sizeof(_buffersVBO));
}
@ -95,10 +97,11 @@ ParticleSystemQuad::~ParticleSystemQuad()
CC_SAFE_FREE(_quads);
CC_SAFE_FREE(_indices);
glDeleteBuffers(2, &_buffersVBO[0]);
#if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &_VAOname);
GL::bindVAO(0);
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
glDeleteVertexArrays(1, &_VAOname);
GL::bindVAO(0);
}
}
#if CC_ENABLE_CACHE_TEXTURE_DATA
@ -355,47 +358,48 @@ void ParticleSystemQuad::draw()
CCASSERT( _particleIdx == _particleCount, "Abnormal error in particle quad");
#if CC_TEXTURE_ATLAS_USE_VAO
//
// Using VBO and VAO
//
GL::bindVAO(_VAOname);
if (Configuration::getInstance()->supportsShareableVAO())
{
//
// Using VBO and VAO
//
GL::bindVAO(_VAOname);
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
#endif
glDrawElements(GL_TRIANGLES, (GLsizei) _particleIdx*6, GL_UNSIGNED_SHORT, 0);
glDrawElements(GL_TRIANGLES, (GLsizei) _particleIdx*6, GL_UNSIGNED_SHORT, 0);
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
}
else
{
//
// Using VBO without VAO
//
#else
//
// Using VBO without VAO
//
#define kQuadSize sizeof(_quads[0].bl)
#define kQuadSize sizeof(_quads[0].bl)
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// vertices
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices));
// colors
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors));
// tex coords
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// vertices
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices));
// colors
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors));
// tex coords
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glDrawElements(GL_TRIANGLES, (GLsizei) _particleIdx*6, GL_UNSIGNED_SHORT, 0);
glDrawElements(GL_TRIANGLES, (GLsizei) _particleIdx*6, GL_UNSIGNED_SHORT, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
CC_INCREMENT_GL_DRAWS(1);
CHECK_GL_ERROR_DEBUG();
@ -454,11 +458,14 @@ void ParticleSystemQuad::setTotalParticles(int tp)
}
initIndices();
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
}
else
{
setupVBO();
}
}
else
{
@ -468,7 +475,6 @@ void ParticleSystemQuad::setTotalParticles(int tp)
resetSystem();
}
#if CC_TEXTURE_ATLAS_USE_VAO
void ParticleSystemQuad::setupVBOandVAO()
{
// clean VAO
@ -508,7 +514,6 @@ void ParticleSystemQuad::setupVBOandVAO()
CHECK_GL_ERROR_DEBUG();
}
#else
void ParticleSystemQuad::setupVBO()
{
@ -527,15 +532,16 @@ void ParticleSystemQuad::setupVBO()
CHECK_GL_ERROR_DEBUG();
}
#endif
void ParticleSystemQuad::listenBackToForeground(Object *obj)
{
#if CC_TEXTURE_ATLAS_USE_VAO
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
#else
}
else
{
setupVBO();
#endif
}
}
bool ParticleSystemQuad::allocMemory()
@ -578,11 +584,14 @@ void ParticleSystemQuad::setBatchNode(ParticleBatchNode * batchNode)
allocMemory();
initIndices();
setTexture(oldBatch->getTexture());
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
}
else
{
setupVBO();
}
}
// OLD: was it self render ? cleanup
else if( !oldBatch )
@ -597,11 +606,12 @@ void ParticleSystemQuad::setBatchNode(ParticleBatchNode * batchNode)
glDeleteBuffers(2, &_buffersVBO[0]);
memset(_buffersVBO, 0, sizeof(_buffersVBO));
#if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &_VAOname);
GL::bindVAO(0);
_VAOname = 0;
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
glDeleteVertexArrays(1, &_VAOname);
GL::bindVAO(0);
_VAOname = 0;
}
}
}
}

View File

@ -135,20 +135,15 @@ public:
virtual void setTotalParticles(int tp) override;
private:
#if CC_TEXTURE_ATLAS_USE_VAO
void setupVBOandVAO();
#else
void setupVBO();
#endif
bool allocMemory();
protected:
V3F_C4B_T2F_Quad *_quads; // quads to be rendered
GLushort *_indices; // indices
#if CC_TEXTURE_ATLAS_USE_VAO
GLuint _VAOname;
#endif
GLuint _buffersVBO[2]; //0: vertex 1: indices
};

View File

@ -101,12 +101,12 @@ void Profiler::displayTimers()
// implementation of ProfilingTimer
ProfilingTimer::ProfilingTimer()
: numberOfCalls(0)
, _averageTime1(0)
: _averageTime1(0)
, _averageTime2(0)
, totalTime(0)
, minTime(100000000)
, maxTime(0)
, totalTime(0)
, numberOfCalls(0)
{
}
@ -166,7 +166,7 @@ void ProfilingEndTimingBlock(const char *timerName)
CCASSERT(timer, "CCProfilingTimer not found");
long duration = chrono::duration_cast<chrono::microseconds>(now - timer->_startTime).count();
long duration = static_cast<long>(chrono::duration_cast<chrono::microseconds>(now - timer->_startTime).count());
timer->totalTime += duration;
timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f;

View File

@ -238,7 +238,7 @@ public:
* @js NA
* @lua NA
*/
virtual const char* getString() const = 0;
virtual const std::string& getString() const = 0;
};
/**

View File

@ -102,11 +102,11 @@ void RenderTexture::listenToBackground(cocos2d::Object *obj)
if (_UITextureImage)
{
const Size& s = _texture->getContentSizeInPixels();
VolatileTexture::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
VolatileTextureMgr::addDataTexture(_texture, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
if ( _textureCopy )
{
VolatileTexture::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
VolatileTextureMgr::addDataTexture(_textureCopy, _UITextureImage->getData(), s.width * s.height * 4, Texture2D::PixelFormat::RGBA8888, s);
}
}
else

View File

@ -133,12 +133,12 @@ void Scene::addChildToPhysicsWorld(Node* child)
if (_physicsWorld)
{
std::function<void(Object*)> addToPhysicsWorldFunc = nullptr;
addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* child) -> void
addToPhysicsWorldFunc = [this, &addToPhysicsWorldFunc](Object* obj) -> void
{
if (dynamic_cast<Node*>(child) != nullptr)
if (dynamic_cast<Node*>(obj) != nullptr)
{
Node* node = dynamic_cast<Node*>(child);
Node* node = dynamic_cast<Node*>(obj);
if (node->getPhysicsBody())
{
@ -161,7 +161,11 @@ void Scene::update(float delta)
{
Node::update(delta);
_physicsWorld->update(delta);
if (nullptr != _physicsWorld)
{
_physicsWorld->update(delta);
}
}
#endif

View File

@ -294,7 +294,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in
CCASSERT(target, "Argument target must be non-NULL");
tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element);
HASH_FIND_PTR(_hashForTimers, &target, element);
if (! element)
{
@ -304,7 +304,7 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Object *target, float in
{
target->retain();
}
HASH_ADD_INT(_hashForTimers, target, element);
HASH_ADD_PTR(_hashForTimers, target, element);
// Is this the 1st element ? Then set the pause level to all the selectors of this target
element->paused = paused;
@ -352,7 +352,7 @@ void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Object *target)
//CCASSERT(selector);
tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element);
HASH_FIND_PTR(_hashForTimers, &target, element);
if (element)
{
@ -448,7 +448,7 @@ void Scheduler::priorityIn(tListEntry **list, Object *target, int priority, bool
target->retain();
pHashElement->list = list;
pHashElement->entry = listElement;
HASH_ADD_INT(_hashForUpdates, target, pHashElement);
HASH_ADD_PTR(_hashForUpdates, target, pHashElement);
}
void Scheduler::appendIn(_listEntry **list, Object *target, bool paused)
@ -467,14 +467,14 @@ void Scheduler::appendIn(_listEntry **list, Object *target, bool paused)
target->retain();
pHashElement->list = list;
pHashElement->entry = listElement;
HASH_ADD_INT(_hashForUpdates, target, pHashElement);
HASH_ADD_PTR(_hashForUpdates, target, pHashElement);
}
void Scheduler::scheduleUpdateForTarget(Object *target, int priority, bool paused)
{
tHashUpdateEntry *pHashElement = NULL;
HASH_FIND_INT(_hashForUpdates, &target, pHashElement);
HASH_FIND_PTR(_hashForUpdates, &target, pHashElement);
if (pHashElement)
{
#if COCOS2D_DEBUG >= 1
@ -509,7 +509,7 @@ bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Object *target)
CCASSERT(target, "Argument target must be non-NULL");
tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element);
HASH_FIND_PTR(_hashForTimers, &target, element);
if (!element)
{
@ -541,7 +541,7 @@ void Scheduler::removeUpdateFromHash(struct _listEntry *entry)
{
tHashUpdateEntry *element = NULL;
HASH_FIND_INT(_hashForUpdates, &entry->target, element);
HASH_FIND_PTR(_hashForUpdates, &entry->target, element);
if (element)
{
// list entry
@ -567,7 +567,7 @@ void Scheduler::unscheduleUpdateForTarget(const Object *target)
}
tHashUpdateEntry *element = NULL;
HASH_FIND_INT(_hashForUpdates, &target, element);
HASH_FIND_PTR(_hashForUpdates, &target, element);
if (element)
{
if (_updateHashLocked)
@ -601,31 +601,31 @@ void Scheduler::unscheduleAllWithMinPriority(int nMinPriority)
}
// Updates selectors
tListEntry *pEntry, *pTmp;
tListEntry *entry, *tmp;
if(nMinPriority < 0)
{
DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp)
DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
{
if(pEntry->priority >= nMinPriority)
if(entry->priority >= nMinPriority)
{
unscheduleUpdateForTarget(pEntry->target);
unscheduleUpdateForTarget(entry->target);
}
}
}
if(nMinPriority <= 0)
{
DL_FOREACH_SAFE(_updates0List, pEntry, pTmp)
DL_FOREACH_SAFE(_updates0List, entry, tmp)
{
unscheduleUpdateForTarget(pEntry->target);
unscheduleUpdateForTarget(entry->target);
}
}
DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp)
DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
{
if(pEntry->priority >= nMinPriority)
if(entry->priority >= nMinPriority)
{
unscheduleUpdateForTarget(pEntry->target);
unscheduleUpdateForTarget(entry->target);
}
}
@ -645,7 +645,7 @@ void Scheduler::unscheduleAllForTarget(Object *target)
// Custom Selectors
tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element);
HASH_FIND_PTR(_hashForTimers, &target, element);
if (element)
{
@ -702,7 +702,7 @@ void Scheduler::resumeTarget(Object *target)
// custom selectors
tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element);
HASH_FIND_PTR(_hashForTimers, &target, element);
if (element)
{
element->paused = false;
@ -710,7 +710,7 @@ void Scheduler::resumeTarget(Object *target)
// update selector
tHashUpdateEntry *elementUpdate = NULL;
HASH_FIND_INT(_hashForUpdates, &target, elementUpdate);
HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate)
{
CCASSERT(elementUpdate->entry != NULL, "");
@ -724,7 +724,7 @@ void Scheduler::pauseTarget(Object *target)
// custom selectors
tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element);
HASH_FIND_PTR(_hashForTimers, &target, element);
if (element)
{
element->paused = true;
@ -732,7 +732,7 @@ void Scheduler::pauseTarget(Object *target)
// update selector
tHashUpdateEntry *elementUpdate = NULL;
HASH_FIND_INT(_hashForUpdates, &target, elementUpdate);
HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate)
{
CCASSERT(elementUpdate->entry != NULL, "");
@ -746,7 +746,7 @@ bool Scheduler::isTargetPaused(Object *target)
// Custom selectors
tHashTimerEntry *element = NULL;
HASH_FIND_INT(_hashForTimers, &target, element);
HASH_FIND_PTR(_hashForTimers, &target, element);
if( element )
{
return element->paused;
@ -754,7 +754,7 @@ bool Scheduler::isTargetPaused(Object *target)
// We should check update selectors if target does not have custom selectors
tHashUpdateEntry *elementUpdate = NULL;
HASH_FIND_INT(_hashForUpdates, &target, elementUpdate);
HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if ( elementUpdate )
{
return elementUpdate->entry->paused;
@ -836,32 +836,32 @@ void Scheduler::update(float dt)
}
// Iterate over all the Updates' selectors
tListEntry *pEntry, *pTmp;
tListEntry *entry, *tmp;
// updates with priority < 0
DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp)
DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
{
if ((! pEntry->paused) && (! pEntry->markedForDeletion))
if ((! entry->paused) && (! entry->markedForDeletion))
{
pEntry->target->update(dt);
entry->target->update(dt);
}
}
// updates with priority == 0
DL_FOREACH_SAFE(_updates0List, pEntry, pTmp)
DL_FOREACH_SAFE(_updates0List, entry, tmp)
{
if ((! pEntry->paused) && (! pEntry->markedForDeletion))
if ((! entry->paused) && (! entry->markedForDeletion))
{
pEntry->target->update(dt);
entry->target->update(dt);
}
}
// updates with priority > 0
DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp)
DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
{
if ((! pEntry->paused) && (! pEntry->markedForDeletion))
if ((! entry->paused) && (! entry->markedForDeletion))
{
pEntry->target->update(dt);
entry->target->update(dt);
}
}
@ -909,43 +909,43 @@ void Scheduler::update(float dt)
{
for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--)
{
SchedulerScriptHandlerEntry* pEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->getObjectAtIndex(i));
if (pEntry->isMarkedForDeletion())
SchedulerScriptHandlerEntry* eachEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->getObjectAtIndex(i));
if (eachEntry->isMarkedForDeletion())
{
_scriptHandlerEntries->removeObjectAtIndex(i);
}
else if (!pEntry->isPaused())
else if (!eachEntry->isPaused())
{
pEntry->getTimer()->update(dt);
eachEntry->getTimer()->update(dt);
}
}
}
// delete all updates that are marked for deletion
// updates with priority < 0
DL_FOREACH_SAFE(_updatesNegList, pEntry, pTmp)
DL_FOREACH_SAFE(_updatesNegList, entry, tmp)
{
if (pEntry->markedForDeletion)
if (entry->markedForDeletion)
{
this->removeUpdateFromHash(pEntry);
this->removeUpdateFromHash(entry);
}
}
// updates with priority == 0
DL_FOREACH_SAFE(_updates0List, pEntry, pTmp)
DL_FOREACH_SAFE(_updates0List, entry, tmp)
{
if (pEntry->markedForDeletion)
if (entry->markedForDeletion)
{
this->removeUpdateFromHash(pEntry);
this->removeUpdateFromHash(entry);
}
}
// updates with priority > 0
DL_FOREACH_SAFE(_updatesPosList, pEntry, pTmp)
DL_FOREACH_SAFE(_updatesPosList, entry, tmp)
{
if (pEntry->markedForDeletion)
if (entry->markedForDeletion)
{
this->removeUpdateFromHash(pEntry);
this->removeUpdateFromHash(entry);
}
}

View File

@ -212,6 +212,8 @@ enum ScriptEventType
kCommonEvent,
kTableViewEvent,//Now it's only used in LuaBinding
kAssetsManagerEvent,//Now it's only used in Lua Binding
kCocoStudioEventListener,//Now it's only used in Lua Binding
kArmatureWrapper,//Now it's only used in Lua Binding
};
struct BasicScriptData

View File

@ -219,7 +219,7 @@ bool Sprite::initWithFile(const std::string& filename)
{
CCASSERT(filename.size()>0, "Invalid filename for sprite");
Texture2D *texture = TextureCache::getInstance()->addImage(filename);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
if (texture)
{
Rect rect = Rect::ZERO;
@ -237,7 +237,7 @@ bool Sprite::initWithFile(const std::string &filename, const Rect& rect)
{
CCASSERT(filename.size()>0, "Invalid filename");
Texture2D *texture = TextureCache::getInstance()->addImage(filename);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
if (texture)
{
return initWithTexture(texture, rect);
@ -284,7 +284,7 @@ Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey)
CCASSERT(pImage != NULL);
// XXX: possible bug. See issue #349. New API should be added
Texture2D *texture = TextureCache::getInstance()->addCGImage(pImage, pszKey);
Texture2D *texture = Director::getInstance()->getTextureCache()->addCGImage(pImage, pszKey);
const Size& size = texture->getContentSize();
Rect rect = Rect(0 ,0, size.width, size.height);
@ -840,6 +840,12 @@ void Sprite::setScale(float fScale)
SET_DIRTY_RECURSIVELY();
}
void Sprite::setScale(float scaleX, float scaleY)
{
Node::setScale(scaleX, scaleY);
SET_DIRTY_RECURSIVELY();
}
void Sprite::setVertexZ(float fVertexZ)
{
Node::setVertexZ(fVertexZ);
@ -1107,7 +1113,7 @@ void Sprite::setTexture(Texture2D *texture)
if (NULL == texture)
{
// Gets the texture by key firstly.
texture = TextureCache::getInstance()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY);
texture = Director::getInstance()->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY);
// If texture wasn't in cache, create it from RAW data.
if (NULL == texture)
@ -1116,7 +1122,7 @@ void Sprite::setTexture(Texture2D *texture)
bool isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8);
CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully.");
texture = TextureCache::getInstance()->addImage(image, CC_2x2_WHITE_IMAGE_KEY);
texture = Director::getInstance()->getTextureCache()->addImage(image, CC_2x2_WHITE_IMAGE_KEY);
CC_SAFE_RELEASE(image);
}
}

View File

@ -24,8 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __SPITE_NODE_CCSPRITE_H__
#define __SPITE_NODE_CCSPRITE_H__
#ifndef __SPRITE_NODE_CCSPRITE_H__
#define __SPRITE_NODE_CCSPRITE_H__
#include "CCNode.h"
#include "CCProtocols.h"
@ -54,7 +54,7 @@ struct transformValues_;
* @{
*/
/**
/**
* Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) )
*
* Sprite can be created with an image, or with a sub-rectangle of an image.
@ -88,14 +88,14 @@ public:
/// @{
/// @name Creators
/**
* Creates an empty sprite without texture. You can call setTexture method subsequently.
*
* @return An empty sprite object that is marked as autoreleased.
*/
static Sprite* create();
/**
* Creates a sprite with an image filename.
*
@ -106,7 +106,7 @@ public:
* @return A valid sprite object that is marked as autoreleased.
*/
static Sprite* create(const std::string& filename);
/**
* Creates a sprite with an image filename and a rect.
*
@ -115,7 +115,7 @@ public:
* @return A valid sprite object that is marked as autoreleased.
*/
static Sprite* create(const std::string& filename, const Rect& rect);
/**
* Creates a sprite with an exsiting texture contained in a Texture2D object
* After creation, the rect will be the size of the texture, and the offset will be (0,0).
@ -124,7 +124,7 @@ public:
* @return A valid sprite object that is marked as autoreleased.
*/
static Sprite* createWithTexture(Texture2D *texture);
/**
* Creates a sprite with a texture and a rect.
*
@ -136,7 +136,7 @@ public:
* @return A valid sprite object that is marked as autoreleased.
*/
static Sprite* createWithTexture(Texture2D *texture, const Rect& rect);
/**
* Creates a sprite with an sprite frame.
*
@ -144,7 +144,7 @@ public:
* @return A valid sprite object that is marked as autoreleased.
*/
static Sprite* createWithSpriteFrame(SpriteFrame *pSpriteFrame);
/**
* Creates a sprite with an sprite frame name.
*
@ -155,31 +155,31 @@ public:
* @return A valid sprite object that is marked as autoreleased.
*/
static Sprite* createWithSpriteFrameName(const std::string& spriteFrameName);
/// @} end of creators group
/// @{
/// @name Initializers
/**
* Default constructor
* @js ctor
*/
Sprite(void);
/**
* Default destructor
* @js NA
* @lua NA
*/
virtual ~Sprite(void);
/**
* Initializes an empty sprite with nothing init.
*/
virtual bool init(void);
/**
* Initializes a sprite with a texture.
*
@ -190,7 +190,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithTexture(Texture2D *texture);
/**
* Initializes a sprite with a texture and a rect.
*
@ -202,7 +202,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithTexture(Texture2D *texture, const Rect& rect);
/**
* Initializes a sprite with a texture and a rect in points, optionally rotated.
*
@ -215,7 +215,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithTexture(Texture2D *texture, const Rect& rect, bool rotated);
/**
* Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this sprite
*
@ -223,7 +223,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithSpriteFrame(SpriteFrame *pSpriteFrame);
/**
* Initializes a sprite with an sprite frame name.
*
@ -234,7 +234,7 @@ public:
* @return true if the sprite is initialized properly, false otherwise.
*/
virtual bool initWithSpriteFrameName(const std::string& spriteFrameName);
/**
* Initializes a sprite with an image filename.
*
@ -248,7 +248,7 @@ public:
* @lua init
*/
virtual bool initWithFile(const std::string& filename);
/**
* Initializes a sprite with an image filename, and a rect.
*
@ -263,17 +263,17 @@ public:
* @lua init
*/
virtual bool initWithFile(const std::string& filename, const Rect& rect);
/// @} end of initializers
/// @{
/// @name BatchNode methods
/**
* Updates the quad according the rotation, position, scale values.
* Updates the quad according the rotation, position, scale values.
*/
virtual void updateTransform(void);
/**
* Returns the batch node object if this sprite is rendered by SpriteBatchNode
*
@ -292,26 +292,26 @@ public:
* @endcode
*/
virtual void setBatchNode(SpriteBatchNode *spriteBatchNode);
/// @} end of BatchNode methods
/// @{
/// @name Texture methods
/**
* Updates the texture rect of the Sprite in points.
* It will call setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize) with \p rotated = false, and \p utrimmedSize = rect.size.
*/
virtual void setTextureRect(const Rect& rect);
/**
* Sets the texture rect, rectRotated and untrimmed size of the Sprite in points.
* It will update the texture coordinates and the vertex rectangle.
*/
virtual void setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize);
/**
* Sets the vertex rect.
* It will be called internally by setTextureRect.
@ -319,34 +319,34 @@ public:
* Do not call it manually. Use setTextureRect instead.
*/
virtual void setVertexRect(const Rect& rect);
/// @} end of texture methods
/// @} end of texture methods
/// @{
/// @name Frames methods
/**
* Sets a new display frame to the Sprite.
*/
virtual void setDisplayFrame(SpriteFrame *pNewFrame);
/**
* Returns whether or not a SpriteFrame is being displayed
*/
virtual bool isFrameDisplayed(SpriteFrame *pFrame) const;
/** @deprecated Use getDisplayFrame() instead */
CC_DEPRECATED_ATTRIBUTE virtual SpriteFrame* displayFrame() { return getDisplayFrame(); };
/**
* Returns the current displayed frame.
*/
virtual SpriteFrame* getDisplayFrame();
/// @} End of frames methods
/// @{
/// @name Animation methods
@ -356,23 +356,23 @@ public:
*/
virtual void setDisplayFrameWithAnimationName(const std::string& animationName, int frameIndex);
/// @}
/// @{
/// @name Sprite Properties' setter/getters
/**
/**
* Whether or not the Sprite needs to be updated in the Atlas.
*
* @return true if the sprite needs to be updated in the Atlas, false otherwise.
*/
virtual bool isDirty(void) const { return _dirty; }
/**
/**
* Makes the Sprite to be updated in the Atlas.
*/
virtual void setDirty(bool bDirty) { _dirty = bDirty; }
/**
* Returns the quad (tex coords, vertex coords and color) information.
* @js NA
@ -380,24 +380,24 @@ public:
*/
inline V3F_C4B_T2F_Quad getQuad(void) const { return _quad; }
/**
/**
* Returns whether or not the texture rectangle is rotated.
*/
inline bool isTextureRectRotated(void) const { return _rectRotated; }
/**
* Returns the index used on the TextureAtlas.
/**
* Returns the index used on the TextureAtlas.
*/
inline int getAtlasIndex(void) const { return _atlasIndex; }
/**
/**
* Sets the index used on the TextureAtlas.
* @warning Don't modify this value unless you know what you are doing
*/
inline void setAtlasIndex(int atlasIndex) { _atlasIndex = atlasIndex; }
/**
* Returns the rect of the Sprite in points
/**
* Returns the rect of the Sprite in points
*/
inline const Rect& getTextureRect(void) { return _rect; }
@ -405,19 +405,19 @@ public:
* Gets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode
*/
inline TextureAtlas* getTextureAtlas(void) { return _textureAtlas; }
/**
* Sets the weak reference of the TextureAtlas when the sprite is rendered using via SpriteBatchNode
*/
inline void setTextureAtlas(TextureAtlas *pobTextureAtlas) { _textureAtlas = pobTextureAtlas; }
/**
/**
* Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex.
*/
inline const Point& getOffsetPosition(void) const { return _offsetPosition; }
/**
/**
* Returns the flag which indicates whether the sprite is flipped horizontally or not.
*
* It only flips the texture of the sprite, and not the texture of the sprite's children.
@ -425,48 +425,48 @@ public:
* If you want to flip the anchorPoint too, and/or to flip the children too use:
* sprite->setScaleX(sprite->getScaleX() * -1);
*
* @return true if the sprite is flipped horizaontally, false otherwise.
* @return true if the sprite is flipped horizontally, false otherwise.
*/
bool isFlippedX(void) const;
/**
* Sets whether the sprite should be flipped horizontally or not.
*
* @param bFlipX true if the sprite should be flipped horizaontally, false otherwise.
* @param flippedX true if the sprite should be flipped horizontally, false otherwise.
*/
void setFlippedX(bool flippedX);
/** @deprecated Use isFlippedX() instead
/** @deprecated Use isFlippedX() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE bool isFlipX() { return isFlippedX(); };
/** @deprecated Use setFlippedX() instead */
CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); };
/**
CC_DEPRECATED_ATTRIBUTE void setFlipX(bool flippedX) { setFlippedX(flippedX); };
/**
* Return the flag which indicates whether the sprite is flipped vertically or not.
*
*
* It only flips the texture of the sprite, and not the texture of the sprite's children.
* Also, flipping the texture doesn't alter the anchorPoint.
* If you want to flip the anchorPoint too, and/or to flip the children too use:
* sprite->setScaleY(sprite->getScaleY() * -1);
*
* @return true if the sprite is flipped vertically, flase otherwise.
*
* @return true if the sprite is flipped vertically, false otherwise.
*/
bool isFlippedY(void) const;
/**
* Sets whether the sprite should be flipped vertically or not.
*
* @param bFlipY true if the sprite should be flipped vertically, flase otherwise.
* @param flippedY true if the sprite should be flipped vertically, false otherwise.
*/
void setFlippedY(bool flippedY);
/// @} End of Sprite properties getter/setters
/** @deprecated Use isFlippedY() instead */
CC_DEPRECATED_ATTRIBUTE bool isFlipY() { return isFlippedY(); };
/** @deprecated Use setFlippedY() instead */
CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); };
CC_DEPRECATED_ATTRIBUTE void setFlipY(bool flippedY) { setFlippedY(flippedY); };
//
// Overrides
@ -494,6 +494,7 @@ public:
/// @name Functions inherited from Node
virtual void setScaleX(float scaleX) override;
virtual void setScaleY(float scaleY) override;
virtual void setScale(float scaleX, float scaleY) override;
/**
* @js NA
* @lua NA
@ -542,13 +543,13 @@ protected:
TextureAtlas* _textureAtlas; /// SpriteBatchNode texture atlas (weak reference)
int _atlasIndex; /// Absolute (real) Index on the SpriteSheet
SpriteBatchNode* _batchNode; /// Used batch node (weak reference)
bool _dirty; /// Whether the sprite 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
AffineTransform _transformToBatch;
//
// Data used when the sprite is self-rendered
//
@ -574,8 +575,8 @@ protected:
bool _opacityModifyRGB;
// image is flipped
bool _flippedX; /// Whether the sprite is flipped horizaontally or not.
bool _flippedY; /// Whether the sprite is flipped vertically or not.
bool _flippedX; /// Whether the sprite is flipped horizontally or not
bool _flippedY; /// Whether the sprite is flipped vertically or not
};
@ -584,4 +585,4 @@ protected:
NS_CC_END
#endif // __SPITE_NODE_CCSPRITE_H__
#endif // __SPRITE_NODE_CCSPRITE_H__

View File

@ -114,7 +114,7 @@ bool SpriteBatchNode::init()
*/
bool SpriteBatchNode::initWithFile(const char* fileImage, long capacity)
{
Texture2D *texture2D = TextureCache::getInstance()->addImage(fileImage);
Texture2D *texture2D = Director::getInstance()->getTextureCache()->addImage(fileImage);
return initWithTexture(texture2D, capacity);
}
@ -598,8 +598,8 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
{
auto next = std::next(it);
std::for_each(next, _descendants.end(), [](Sprite *sprite) {
sprite->setAtlasIndex( sprite->getAtlasIndex() - 1 );
std::for_each(next, _descendants.end(), [](Sprite *spr) {
spr->setAtlasIndex( spr->getAtlasIndex() - 1 );
});
_descendants.erase(it);

View File

@ -180,7 +180,7 @@ Texture2D* SpriteFrame::getTexture(void)
}
if( _textureFilename.length() > 0 ) {
return TextureCache::getInstance()->addImage(_textureFilename.c_str());
return Director::getInstance()->getTextureCache()->addImage(_textureFilename.c_str());
}
// no texture or texture filename
return NULL;

View File

@ -37,6 +37,7 @@ THE SOFTWARE.
#include "CCString.h"
#include "CCArray.h"
#include "CCDictionary.h"
#include "CCDirector.h"
#include <vector>
using namespace std;
@ -215,7 +216,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist, Text
void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName)
{
CCASSERT(textureFileName.size()>0, "texture name should not be null");
Texture2D *texture = TextureCache::getInstance()->addImage(textureFileName);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(textureFileName);
if (texture)
{
@ -265,7 +266,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const std::string& pszPlist)
CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str());
}
Texture2D *texture = TextureCache::getInstance()->addImage(texturePath.c_str());
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(texturePath.c_str());
if (texture)
{

View File

@ -58,7 +58,7 @@ bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *la
Texture2D *texture = NULL;
if( tilesetInfo )
{
texture = TextureCache::getInstance()->addImage(tilesetInfo->_sourceImage.c_str());
texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage.c_str());
}
if (SpriteBatchNode::initWithTexture(texture, (unsigned int)capacity))

View File

@ -27,6 +27,7 @@ THE SOFTWARE.
#include "CCTMXXMLParser.h"
#include "CCTMXLayer.h"
#include "CCSprite.h"
#include <algorithm>
NS_CC_BEGIN

View File

@ -66,7 +66,7 @@ TMXLayerInfo::~TMXLayerInfo()
CC_SAFE_RELEASE(_properties);
if( _ownTiles && _tiles )
{
delete [] _tiles;
free(_tiles);
_tiles = NULL;
}
}
@ -757,12 +757,12 @@ void TMXMapInfo::endElement(void *ctx, const char *name)
// int sizeHint = s.width * s.height * sizeof(uint32_t);
int sizeHint = (int)(s.width * s.height * sizeof(unsigned int));
int inflatedLen = ZipUtils::ccInflateMemoryWithHint(buffer, len, &deflated, sizeHint);
int inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint);
CCASSERT(inflatedLen == sizeHint, "");
inflatedLen = (size_t)&inflatedLen; // XXX: to avoid warnings in compiler
delete [] buffer;
free(buffer);
buffer = NULL;
if( ! deflated )

View File

@ -53,8 +53,8 @@ static int _calcCharCount(const char * pszText)
TextFieldTTF::TextFieldTTF()
: _delegate(0)
, _charCount(0)
, _inputText(new std::string)
, _placeHolder(new std::string) // prevent LabelTTF initWithString assertion
, _inputText("")
, _placeHolder("") // prevent LabelTTF initWithString assertion
, _secureTextEntry(false)
{
_colorSpaceHolder.r = _colorSpaceHolder.g = _colorSpaceHolder.b = 127;
@ -62,43 +62,41 @@ TextFieldTTF::TextFieldTTF()
TextFieldTTF::~TextFieldTTF()
{
CC_SAFE_DELETE(_inputText);
CC_SAFE_DELETE(_placeHolder);
}
//////////////////////////////////////////////////////////////////////////
// static constructor
//////////////////////////////////////////////////////////////////////////
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize)
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize)
{
TextFieldTTF *pRet = new TextFieldTTF();
if(pRet && pRet->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize))
TextFieldTTF *ret = new TextFieldTTF();
if(ret && ret->initWithPlaceHolder("", dimensions, alignment, fontName, fontSize))
{
pRet->autorelease();
if (placeholder)
ret->autorelease();
if (placeholder.size()>0)
{
pRet->setPlaceHolder(placeholder);
ret->setPlaceHolder(placeholder);
}
return pRet;
return ret;
}
CC_SAFE_DELETE(pRet);
CC_SAFE_DELETE(ret);
return NULL;
}
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize)
TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize)
{
TextFieldTTF *pRet = new TextFieldTTF();
if(pRet && pRet->initWithString("", fontName, fontSize))
TextFieldTTF *ret = new TextFieldTTF();
if(ret && ret->initWithString("", fontName, fontSize))
{
pRet->autorelease();
if (placeholder)
ret->autorelease();
if (placeholder.size()>0)
{
pRet->setPlaceHolder(placeholder);
ret->setPlaceHolder(placeholder);
}
return pRet;
return ret;
}
CC_SAFE_DELETE(pRet);
CC_SAFE_DELETE(ret);
return NULL;
}
@ -106,23 +104,15 @@ TextFieldTTF * TextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, c
// initialize
//////////////////////////////////////////////////////////////////////////
bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize)
bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize)
{
if (placeholder)
{
CC_SAFE_DELETE(_placeHolder);
_placeHolder = new std::string(placeholder);
}
return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize, dimensions, alignment);
_placeHolder = placeholder;
return LabelTTF::initWithString(_placeHolder, fontName, fontSize, dimensions, alignment);
}
bool TextFieldTTF::initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize)
bool TextFieldTTF::initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize)
{
if (placeholder)
{
CC_SAFE_DELETE(_placeHolder);
_placeHolder = new std::string(placeholder);
}
return LabelTTF::initWithString(_placeHolder->c_str(), fontName, fontSize);
_placeHolder = std::string(placeholder);
return LabelTTF::initWithString(_placeHolder, fontName, fontSize);
}
//////////////////////////////////////////////////////////////////////////
@ -190,9 +180,9 @@ void TextFieldTTF::insertText(const char * text, int len)
}
_charCount += _calcCharCount(sInsert.c_str());
std::string sText(*_inputText);
std::string sText(_inputText);
sText.append(sInsert);
setString(sText.c_str());
setString(sText);
}
if ((int)sInsert.npos == nPos) {
@ -211,7 +201,7 @@ void TextFieldTTF::insertText(const char * text, int len)
void TextFieldTTF::deleteBackward()
{
int nStrLen = _inputText->length();
int nStrLen = _inputText.length();
if (! nStrLen)
{
// there is no string
@ -221,12 +211,12 @@ void TextFieldTTF::deleteBackward()
// get the delete byte number
int nDeleteLen = 1; // default, erase 1 byte
while(0x80 == (0xC0 & _inputText->at(nStrLen - nDeleteLen)))
while(0x80 == (0xC0 & _inputText.at(nStrLen - nDeleteLen)))
{
++nDeleteLen;
}
if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText->c_str() + nStrLen - nDeleteLen, nDeleteLen))
if (_delegate && _delegate->onTextFieldDeleteBackward(this, _inputText.c_str() + nStrLen - nDeleteLen, nDeleteLen))
{
// delegate doesn't wan't to delete backwards
return;
@ -235,21 +225,20 @@ void TextFieldTTF::deleteBackward()
// if all text deleted, show placeholder string
if (nStrLen <= nDeleteLen)
{
CC_SAFE_DELETE(_inputText);
_inputText = new std::string;
_inputText = "";
_charCount = 0;
LabelTTF::setString(_placeHolder->c_str());
LabelTTF::setString(_placeHolder);
return;
}
// set new input text
std::string sText(_inputText->c_str(), nStrLen - nDeleteLen);
setString(sText.c_str());
std::string sText(_inputText.c_str(), nStrLen - nDeleteLen);
setString(sText);
}
const char * TextFieldTTF::getContentText()
{
return _inputText->c_str();
return _inputText.c_str();
}
void TextFieldTTF::draw()
@ -258,7 +247,7 @@ void TextFieldTTF::draw()
{
return;
}
if (_inputText->length())
if (_inputText.length())
{
LabelTTF::draw();
return;
@ -286,22 +275,20 @@ void TextFieldTTF::setColorSpaceHolder(const Color3B& color)
//////////////////////////////////////////////////////////////////////////
// input text property
void TextFieldTTF::setString(const char *text)
void TextFieldTTF::setString(const std::string &text)
{
static char bulletString[] = {(char)0xe2, (char)0x80, (char)0xa2, (char)0x00};
std::string displayText;
int length;
CC_SAFE_DELETE(_inputText);
if (text)
if (text.length()>0)
{
_inputText = new std::string(text);
displayText = *_inputText;
_inputText = text;
displayText = _inputText;
if (_secureTextEntry)
{
displayText = "";
length = _inputText->length();
length = _inputText.length();
while (length)
{
displayText.append(bulletString);
@ -311,40 +298,39 @@ void TextFieldTTF::setString(const char *text)
}
else
{
_inputText = new std::string;
_inputText = "";
}
// if there is no input text, display placeholder instead
if (! _inputText->length())
if (! _inputText.length())
{
LabelTTF::setString(_placeHolder->c_str());
LabelTTF::setString(_placeHolder);
}
else
{
LabelTTF::setString(displayText.c_str());
LabelTTF::setString(displayText);
}
_charCount = _calcCharCount(_inputText->c_str());
_charCount = _calcCharCount(_inputText.c_str());
}
const char* TextFieldTTF::getString(void) const
const std::string& TextFieldTTF::getString() const
{
return _inputText->c_str();
return _inputText;
}
// place holder text property
void TextFieldTTF::setPlaceHolder(const char * text)
void TextFieldTTF::setPlaceHolder(const std::string& text)
{
CC_SAFE_DELETE(_placeHolder);
_placeHolder = (text) ? new std::string(text) : new std::string;
if (! _inputText->length())
_placeHolder = text;
if (! _inputText.length())
{
LabelTTF::setString(_placeHolder->c_str());
LabelTTF::setString(_placeHolder);
}
}
const char * TextFieldTTF::getPlaceHolder(void)
const std::string& TextFieldTTF::getPlaceHolder() const
{
return _placeHolder->c_str();
return _placeHolder;
}
// secureTextEntry

View File

@ -109,13 +109,13 @@ public:
//char * description();
/** creates a TextFieldTTF from a fontname, alignment, dimension and font size */
static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize);
static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize);
/** creates a LabelTTF from a fontname and font size */
static TextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize);
static TextFieldTTF * textFieldWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize);
/** initializes the TextFieldTTF with a font name, alignment, dimension and font size */
bool initWithPlaceHolder(const char *placeholder, const Size& dimensions, TextHAlignment alignment, const char *fontName, float fontSize);
bool initWithPlaceHolder(const std::string& placeholder, const Size& dimensions, TextHAlignment alignment, const std::string& fontName, float fontSize);
/** initializes the TextFieldTTF with a font name and font size */
bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize);
bool initWithPlaceHolder(const std::string& placeholder, const std::string& fontName, float fontSize);
/**
@brief Open keyboard and receive input text.
@ -147,21 +147,21 @@ public:
// input text property
public:
virtual void setString(const char *text);
virtual const char* getString(void) const;
virtual void setString(const std::string& text) override;
virtual const std::string& getString() const override;
protected:
TextFieldDelegate * _delegate;
int _charCount;
std::string * _inputText;
std::string _inputText;
// place holder text property
// place holder text displayed when there is no text in the text field.
public:
virtual void setPlaceHolder(const char * text);
virtual const char * getPlaceHolder(void);
virtual void setPlaceHolder(const std::string& text);
virtual const std::string& getPlaceHolder(void) const;
protected:
std::string * _placeHolder;
std::string _placeHolder;
Color3B _colorSpaceHolder;
public:
virtual void setSecureTextEntry(bool value);
@ -176,11 +176,11 @@ protected:
// IMEDelegate interface
//////////////////////////////////////////////////////////////////////////
virtual bool canAttachWithIME();
virtual bool canDetachWithIME();
virtual void insertText(const char * text, int len);
virtual void deleteBackward();
virtual const char * getContentText();
virtual bool canAttachWithIME() override;
virtual bool canDetachWithIME() override;
virtual void insertText(const char * text, int len) override;
virtual void deleteBackward() override;
virtual const char * getContentText() override;
private:
class LengthStack;
LengthStack * _lens;

View File

@ -130,7 +130,7 @@ TextFontPagesDef::~TextFontPagesDef()
}
}
TextImage::TextImage(): _font(0), _fontPages(0)
TextImage::TextImage(): _fontPages(0), _font(0)
{
}

View File

@ -434,7 +434,7 @@ Texture2D::Texture2D()
Texture2D::~Texture2D()
{
#if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTexture::removeTexture(this);
VolatileTextureMgr::removeTexture(this);
#endif
CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name);
@ -622,8 +622,8 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat
CHECK_GL_ERROR_DEBUG(); // clean possible GL error
// Specify OpenGL texture image
int width = pixelsWide;
int height = pixelsHigh;
long width = pixelsWide;
long height = pixelsHigh;
for (int i = 0; i < mipmapsNum; ++i)
{
@ -641,7 +641,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat
if (i > 0 && (width != height || ccNextPOT(width) != width ))
{
CCLOG("cocos2d: Texture2D. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%u != height=%u", i, width, height);
CCLOG("cocos2d: Texture2D. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%ld != height=%ld", i, width, height);
}
GLenum err = glGetError();
@ -1041,7 +1041,7 @@ bool Texture2D::initWithString(const char *text, const FontDefinition& textDefin
{
#if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture data
VolatileTexture::addStringTexture(this, text, textDefinition);
VolatileTextureMgr::addStringTexture(this, text, textDefinition);
#endif
bool bRet = false;
@ -1243,7 +1243,7 @@ void Texture2D::PVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied)
void Texture2D::generateMipmap()
{
CCASSERT( _pixelsWide == ccNextPOT(_pixelsWide) && _pixelsHigh == ccNextPOT(_pixelsHigh), "Mipmap texture only works in POT textures");
CCASSERT( static_cast<unsigned long>(_pixelsWide) == ccNextPOT(_pixelsWide) && static_cast<unsigned long>(_pixelsHigh) == ccNextPOT(_pixelsHigh), "Mipmap texture only works in POT textures");
GL::bindTexture2D( _name );
glGenerateMipmap(GL_TEXTURE_2D);
_hasMipmaps = true;
@ -1256,8 +1256,8 @@ bool Texture2D::hasMipmaps() const
void Texture2D::setTexParameters(const TexParams &texParams)
{
CCASSERT( (_pixelsWide == ccNextPOT(_pixelsWide) || texParams.wrapS == GL_CLAMP_TO_EDGE) &&
(_pixelsHigh == ccNextPOT(_pixelsHigh) || texParams.wrapT == GL_CLAMP_TO_EDGE),
CCASSERT( (static_cast<unsigned long>(_pixelsWide) == ccNextPOT(_pixelsWide) || texParams.wrapS == GL_CLAMP_TO_EDGE) &&
(static_cast<unsigned long>(_pixelsHigh) == ccNextPOT(_pixelsHigh) || texParams.wrapT == GL_CLAMP_TO_EDGE),
"GL_CLAMP_TO_EDGE should be used in NPOT dimensions");
GL::bindTexture2D( _name );
@ -1267,7 +1267,7 @@ void Texture2D::setTexParameters(const TexParams &texParams)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams.wrapT );
#if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTexture::setTexParameters(this, texParams);
VolatileTextureMgr::setTexParameters(this, texParams);
#endif
}
@ -1287,7 +1287,7 @@ void Texture2D::setAliasTexParameters()
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
#if CC_ENABLE_CACHE_TEXTURE_DATA
TexParams texParams = {(GLuint)(_hasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST),GL_NEAREST,GL_NONE,GL_NONE};
VolatileTexture::setTexParameters(this, texParams);
VolatileTextureMgr::setTexParameters(this, texParams);
#endif
}
@ -1307,7 +1307,7 @@ void Texture2D::setAntiAliasTexParameters()
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
#if CC_ENABLE_CACHE_TEXTURE_DATA
TexParams texParams = {(GLuint)(_hasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR),GL_LINEAR,GL_NONE,GL_NONE};
VolatileTexture::setTexParameters(this, texParams);
VolatileTextureMgr::setTexParameters(this, texParams);
#endif
}

View File

@ -32,7 +32,9 @@ THE SOFTWARE.
#include "ccGLStateCache.h"
#include "CCNotificationCenter.h"
#include "CCEventType.h"
#include "CCDirector.h"
#include "CCGL.h"
#include "CCConfiguration.h"
// support
#include "CCTexture2D.h"
#include "CCString.h"
@ -60,10 +62,11 @@ TextureAtlas::~TextureAtlas()
glDeleteBuffers(2, _buffersVBO);
#if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &_VAOname);
GL::bindVAO(0);
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
glDeleteVertexArrays(1, &_VAOname);
GL::bindVAO(0);
}
CC_SAFE_RELEASE(_texture);
#if CC_ENABLE_CACHE_TEXTURE_DATA
@ -71,12 +74,12 @@ TextureAtlas::~TextureAtlas()
#endif
}
int TextureAtlas::getTotalQuads() const
long TextureAtlas::getTotalQuads() const
{
return _totalQuads;
}
int TextureAtlas::getCapacity() const
long TextureAtlas::getCapacity() const
{
return _capacity;
}
@ -134,7 +137,7 @@ TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, long capacity
bool TextureAtlas::initWithFile(const char * file, long capacity)
{
// retained in property
Texture2D *texture = TextureCache::getInstance()->addImage(file);
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file);
if (texture)
{
@ -190,11 +193,14 @@ bool TextureAtlas::initWithTexture(Texture2D *texture, long capacity)
this->setupIndices();
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
}
else
{
setupVBO();
}
_dirty = true;
@ -203,11 +209,14 @@ bool TextureAtlas::initWithTexture(Texture2D *texture, long capacity)
void TextureAtlas::listenBackToForeground(Object *obj)
{
#if CC_TEXTURE_ATLAS_USE_VAO
setupVBOandVAO();
#else
setupVBO();
#endif
if (Configuration::getInstance()->supportsShareableVAO())
{
setupVBOandVAO();
}
else
{
setupVBO();
}
// set _dirty to true to force it rebinding buffer
_dirty = true;
@ -215,7 +224,7 @@ void TextureAtlas::listenBackToForeground(Object *obj)
const char* TextureAtlas::description() const
{
return String::createWithFormat("<TextureAtlas | totalQuads = %u>", _totalQuads)->getCString();
return String::createWithFormat("<TextureAtlas | totalQuads = %ld>", _totalQuads)->getCString();
}
@ -248,7 +257,6 @@ void TextureAtlas::setupIndices()
//TextureAtlas - VAO / VBO specific
#if CC_TEXTURE_ATLAS_USE_VAO
void TextureAtlas::setupVBOandVAO()
{
glGenVertexArrays(1, &_VAOname);
@ -283,14 +291,13 @@ void TextureAtlas::setupVBOandVAO()
CHECK_GL_ERROR_DEBUG();
}
#else // CC_TEXTURE_ATLAS_USE_VAO
void TextureAtlas::setupVBO()
{
glGenBuffers(2, &_buffersVBO[0]);
mapBuffers();
}
#endif // ! // CC_TEXTURE_ATLAS_USE_VAO
void TextureAtlas::mapBuffers()
{
@ -356,7 +363,7 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount)
CCASSERT( _totalQuads <= _capacity, "invalid totalQuads");
// issue #575. index can be > totalQuads
int remaining = (_totalQuads-1) - index - amount;
long remaining = (_totalQuads-1) - index - amount;
// last object doesn't need to be moved
if( remaining > 0)
@ -366,9 +373,9 @@ void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, long index, long amount)
}
int max = index + amount;
long max = index + amount;
int j = 0;
for (int i = index; i < max ; i++)
for (long i = index; i < max ; i++)
{
_quads[index] = quads[j];
index++;
@ -389,9 +396,9 @@ void TextureAtlas::insertQuadFromIndex(long oldIndex, long newIndex)
}
// because it is ambiguous in iphone, so we implement abs ourselves
// unsigned int howMany = abs( oldIndex - newIndex);
int howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex);
int dst = oldIndex;
int src = oldIndex + 1;
long howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex);
long dst = oldIndex;
long src = oldIndex + 1;
if( oldIndex > newIndex)
{
dst = newIndex+1;
@ -411,7 +418,7 @@ void TextureAtlas::removeQuadAtIndex(long index)
{
CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index");
int remaining = (_totalQuads-1) - index;
long remaining = (_totalQuads-1) - index;
// last object doesn't need to be moved
if( remaining )
@ -430,7 +437,7 @@ void TextureAtlas::removeQuadsAtIndex(long index, long amount)
{
CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds");
int remaining = (_totalQuads) - (index + amount);
long remaining = (_totalQuads) - (index + amount);
_totalQuads -= amount;
@ -455,7 +462,7 @@ bool TextureAtlas::resizeCapacity(long newCapacity)
{
return true;
}
int oldCapactiy = _capacity;
long oldCapactiy = _capacity;
// update capacity and totolQuads
_totalQuads = MIN(_totalQuads, newCapacity);
_capacity = newCapacity;
@ -574,8 +581,8 @@ void TextureAtlas::fillWithEmptyQuadsFromIndex(long index, long amount)
V3F_C4B_T2F_Quad quad;
memset(&quad, 0, sizeof(quad));
int to = index + amount;
for (int i = index ; i < to ; i++)
long to = index + amount;
for (long i = index ; i < to ; i++)
{
_quads[i] = quad;
}
@ -603,90 +610,89 @@ void TextureAtlas::drawNumberOfQuads(long numberOfQuads, long start)
GL::bindTexture2D(_texture->getName());
#if CC_TEXTURE_ATLAS_USE_VAO
//
// Using VBO and VAO
//
// XXX: update is done in draw... perhaps it should be done in a timer
if (_dirty)
if (Configuration::getInstance()->supportsShareableVAO())
{
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]) * (numberOfQuads-start), NULL, GL_DYNAMIC_DRAW);
void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(buf, _quads, sizeof(_quads[0])* (numberOfQuads-start));
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//
// Using VBO and VAO
//
_dirty = false;
}
// XXX: update is done in draw... perhaps it should be done in a timer
if (_dirty)
{
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]) * (numberOfQuads-start), NULL, GL_DYNAMIC_DRAW);
void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(buf, _quads, sizeof(_quads[0])* (numberOfQuads-start));
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
GL::bindVAO(_VAOname);
_dirty = false;
}
GL::bindVAO(_VAOname);
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
#endif
#if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP
glDrawElements(GL_TRIANGLE_STRIP, (GLsizei) numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])) );
glDrawElements(GL_TRIANGLE_STRIP, (GLsizei) numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])) );
#else
glDrawElements(GL_TRIANGLES, (GLsizei) numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])) );
glDrawElements(GL_TRIANGLES, (GLsizei) numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])) );
#endif // CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP
#if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
// glBindVertexArray(0);
#else // ! CC_TEXTURE_ATLAS_USE_VAO
//
// Using VBO without VAO
//
}
else
{
//
// Using VBO without VAO
//
#define kQuadSize sizeof(_quads[0].bl)
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// XXX: update is done in draw... perhaps it should be done in a timer
if (_dirty)
{
glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * numberOfQuads , &_quads[start] );
_dirty = false;
}
// XXX: update is done in draw... perhaps it should be done in a timer
if (_dirty)
{
glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * numberOfQuads , &_quads[start] );
_dirty = false;
}
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
// vertices
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, vertices));
// vertices
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, vertices));
// colors
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, colors));
// colors
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, colors));
// tex coords
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, texCoords));
// tex coords
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
#if CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP
glDrawElements(GL_TRIANGLE_STRIP, (GLsizei)numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])));
glDrawElements(GL_TRIANGLE_STRIP, (GLsizei)numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])));
#else
glDrawElements(GL_TRIANGLES, (GLsizei)numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])));
glDrawElements(GL_TRIANGLES, (GLsizei)numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])));
#endif // CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif // CC_TEXTURE_ATLAS_USE_VAO
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
CC_INCREMENT_GL_DRAWS(1);
CHECK_GL_ERROR_DEBUG();

View File

@ -197,10 +197,10 @@ public:
const char* description() const;
/** Gets the quantity of quads that are going to be drawn */
int getTotalQuads() const;
long getTotalQuads() const;
/** Gets the quantity of quads that can be stored with the current texture atlas size */
int getCapacity() const;
long getCapacity() const;
/** Gets the texture of the texture atlas */
Texture2D* getTexture() const;
@ -217,23 +217,18 @@ public:
private:
void setupIndices();
void mapBuffers();
#if CC_TEXTURE_ATLAS_USE_VAO
void setupVBOandVAO();
#else
void setupVBO();
#endif
protected:
GLushort* _indices;
#if CC_TEXTURE_ATLAS_USE_VAO
GLuint _VAOname;
#endif
GLuint _buffersVBO[2]; //0: vertex 1: indices
bool _dirty; //indicates whether or not the array buffer of the VBO needs to be updated
/** quantity of quads that are going to be drawn */
int _totalQuads;
long _totalQuads;
/** quantity of quads that can be stored with the current texture atlas size */
int _capacity;
long _capacity;
/** Texture of the texture atlas */
Texture2D* _texture;
/** Quads that are going to be rendered */

View File

@ -51,19 +51,9 @@ NS_CC_BEGIN
// implementation TextureCache
TextureCache* TextureCache::_sharedTextureCache = nullptr;
TextureCache * TextureCache::getInstance()
{
if (!_sharedTextureCache)
{
#ifdef EMSCRIPTEN
_sharedTextureCache = new TextureCacheEmscripten();
#else
_sharedTextureCache = new TextureCache();
#endif // EMSCRIPTEN
}
return _sharedTextureCache;
return Director::getInstance()->getTextureCache();
}
TextureCache::TextureCache()
@ -73,7 +63,6 @@ TextureCache::TextureCache()
, _needQuit(false)
, _asyncRefCount(0)
{
CCASSERT(_sharedTextureCache == nullptr, "Attempted to allocate a second instance of a singleton.");
}
TextureCache::~TextureCache()
@ -84,20 +73,19 @@ TextureCache::~TextureCache()
(it->second)->release();
CC_SAFE_DELETE(_loadingThread);
_sharedTextureCache = nullptr;
}
void TextureCache::destroyInstance()
{
if (_sharedTextureCache)
{
// notify sub thread to quick
_sharedTextureCache->_needQuit = true;
_sharedTextureCache->_sleepCondition.notify_one();
if (_sharedTextureCache->_loadingThread) _sharedTextureCache->_loadingThread->join();
CC_SAFE_RELEASE_NULL(_sharedTextureCache);
}
}
TextureCache * TextureCache::sharedTextureCache()
{
return Director::getInstance()->getTextureCache();
}
void TextureCache::purgeSharedTextureCache()
{
}
const char* TextureCache::description() const
@ -260,7 +248,7 @@ void TextureCache::addImageAsyncCallBack(float dt)
#if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name
VolatileTexture::addImageTexture(texture, filename);
VolatileTextureMgr::addImageTexture(texture, filename);
#endif
// cache the texture. retain it, since it is added in the map
_textures.insert( std::make_pair(filename, texture) );
@ -320,7 +308,7 @@ Texture2D * TextureCache::addImage(const std::string &path)
{
#if CC_ENABLE_CACHE_TEXTURE_DATA
// cache the texture file name
VolatileTexture::addImageTexture(texture, fullpath.c_str());
VolatileTextureMgr::addImageTexture(texture, fullpath.c_str());
#endif
// texture already retained, no need to re-retain it
_textures.insert( std::make_pair(fullpath, texture) );
@ -370,7 +358,7 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key)
} while (0);
#if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTexture::addImage(texture, image);
VolatileTextureMgr::addImage(texture, image);
#endif
return texture;
@ -438,9 +426,18 @@ Texture2D* TextureCache::getTextureForKey(const std::string &key) const
void TextureCache::reloadAllTextures()
{
#if CC_ENABLE_CACHE_TEXTURE_DATA
VolatileTexture::reloadAllTextures();
#endif
//will do nothing
// #if CC_ENABLE_CACHE_TEXTURE_DATA
// VolatileTextureMgr::reloadAllTextures();
// #endif
}
void TextureCache::waitForQuit()
{
// notify sub thread to quick
_needQuit = true;
_sleepCondition.notify_one();
if (_loadingThread) _loadingThread->join();
}
void TextureCache::dumpCachedTextureInfo() const
@ -453,7 +450,7 @@ void TextureCache::dumpCachedTextureInfo() const
Texture2D* tex = it->second;
unsigned int bpp = tex->getBitsPerPixelForFormat();
// Each texture takes up width * height * bytesPerPixel bytes.
unsigned int bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
long bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
totalBytes += bytes;
count++;
log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB",
@ -471,8 +468,8 @@ void TextureCache::dumpCachedTextureInfo() const
#if CC_ENABLE_CACHE_TEXTURE_DATA
std::list<VolatileTexture*> VolatileTexture::_textures;
bool VolatileTexture::_isReloading = false;
std::list<VolatileTexture*> VolatileTextureMgr::_textures;
bool VolatileTextureMgr::_isReloading = false;
VolatileTexture::VolatileTexture(Texture2D *t)
: _texture(t)
@ -487,16 +484,14 @@ VolatileTexture::VolatileTexture(Texture2D *t)
_texParams.magFilter = GL_LINEAR;
_texParams.wrapS = GL_CLAMP_TO_EDGE;
_texParams.wrapT = GL_CLAMP_TO_EDGE;
_textures.push_back(this);
}
VolatileTexture::~VolatileTexture()
{
_textures.remove(this);
CC_SAFE_RELEASE(_uiImage);
}
void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName)
void VolatileTextureMgr::addImageTexture(Texture2D *tt, const char* imageFileName)
{
if (_isReloading)
{
@ -505,20 +500,20 @@ void VolatileTexture::addImageTexture(Texture2D *tt, const char* imageFileName)
VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = kImageFile;
vt->_cashedImageType = VolatileTexture::kImageFile;
vt->_fileName = imageFileName;
vt->_pixelFormat = tt->getPixelFormat();
}
void VolatileTexture::addImage(Texture2D *tt, Image *image)
void VolatileTextureMgr::addImage(Texture2D *tt, Image *image)
{
VolatileTexture *vt = findVolotileTexture(tt);
image->retain();
vt->_uiImage = image;
vt->_cashedImageType = kImage;
vt->_cashedImageType = VolatileTexture::kImage;
}
VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt)
VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt)
{
VolatileTexture *vt = 0;
auto i = _textures.begin();
@ -535,12 +530,13 @@ VolatileTexture* VolatileTexture::findVolotileTexture(Texture2D *tt)
if (! vt)
{
vt = new VolatileTexture(tt);
_textures.push_back(vt);
}
return vt;
}
void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize)
void VolatileTextureMgr::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize)
{
if (_isReloading)
{
@ -549,14 +545,14 @@ void VolatileTexture::addDataTexture(Texture2D *tt, void* data, int dataLen, Tex
VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = kImageData;
vt->_cashedImageType = VolatileTexture::kImageData;
vt->_textureData = data;
vt->_dataLen = dataLen;
vt->_pixelFormat = pixelFormat;
vt->_textureSize = contentSize;
}
void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition)
void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition)
{
if (_isReloading)
{
@ -565,12 +561,12 @@ void VolatileTexture::addStringTexture(Texture2D *tt, const char* text, const Fo
VolatileTexture *vt = findVolotileTexture(tt);
vt->_cashedImageType = kString;
vt->_cashedImageType = VolatileTexture::kString;
vt->_text = text;
vt->_fontDefinition = fontDefinition;
}
void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams)
void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams)
{
VolatileTexture *vt = findVolotileTexture(t);
@ -584,7 +580,7 @@ void VolatileTexture::setTexParameters(Texture2D *t, const Texture2D::TexParams
vt->_texParams.wrapT = texParams.wrapT;
}
void VolatileTexture::removeTexture(Texture2D *t)
void VolatileTextureMgr::removeTexture(Texture2D *t)
{
auto i = _textures.begin();
while (i != _textures.end())
@ -592,13 +588,14 @@ void VolatileTexture::removeTexture(Texture2D *t)
VolatileTexture *vt = *i++;
if (vt->_texture == t)
{
_textures.remove(vt);
delete vt;
break;
}
}
}
void VolatileTexture::reloadAllTextures()
void VolatileTextureMgr::reloadAllTextures()
{
_isReloading = true;
@ -611,7 +608,7 @@ void VolatileTexture::reloadAllTextures()
switch (vt->_cashedImageType)
{
case kImageFile:
case VolatileTexture::kImageFile:
{
Image* image = new Image();
long size = 0;
@ -625,11 +622,11 @@ void VolatileTexture::reloadAllTextures()
Texture2D::setDefaultAlphaPixelFormat(oldPixelFormat);
}
CC_SAFE_DELETE_ARRAY(pBuffer);
free(pBuffer);
CC_SAFE_RELEASE(image);
}
break;
case kImageData:
case VolatileTexture::kImageData:
{
vt->_texture->initWithData(vt->_textureData,
vt->_dataLen,
@ -639,12 +636,12 @@ void VolatileTexture::reloadAllTextures()
vt->_textureSize);
}
break;
case kString:
case VolatileTexture::kString:
{
vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition);
}
break;
case kImage:
case VolatileTexture::kImage:
{
vt->_texture->initWithImage(vt->_uiImage);
}

View File

@ -50,6 +50,10 @@ NS_CC_BEGIN
* @addtogroup textures
* @{
*/
/*
* from version 3.0, TextureCache will never to treated as a singleton, it will be owned by director.
* all call by TextureCache::getInstance() should be replaced by Director::getInstance()->getTextureCache()
*/
/** @brief Singleton that handles the loading of textures
* Once the texture is loaded, the next time it will return
@ -59,23 +63,24 @@ class CC_DLL TextureCache : public Object
{
public:
/** Returns the shared instance of the cache */
static TextureCache * getInstance();
CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance();
/** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache() { return TextureCache::getInstance(); }
CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache();
/** purges the cache. It releases the retained instance.
@since v0.99.0
*/
static void destroyInstance();
CC_DEPRECATED_ATTRIBUTE static void destroyInstance();
/** @deprecated Use destroyInstance() instead */
CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache() { return TextureCache::destroyInstance(); }
CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache();
/** Reload all textures
It's only useful when the value of CC_ENABLE_CACHE_TEXTURE_DATA is 1
should not call it, called by frame work
now the function do nothing, use VolatileTextureMgr::reloadAllTextures
*/
static void reloadAllTextures();
CC_DEPRECATED_ATTRIBUTE static void reloadAllTextures();
public:
/**
@ -158,6 +163,10 @@ public:
*/
void dumpCachedTextureInfo() const;
//wait for texture cahe to quit befor destroy instance
//called by director, please do not called outside
void waitForQuit();
private:
void addImageAsyncCallBack(float dt);
void loadImage();
@ -196,8 +205,6 @@ protected:
int _asyncRefCount;
std::unordered_map<std::string, Texture2D*> _textures;
static TextureCache *_sharedTextureCache;
};
#if CC_ENABLE_CACHE_TEXTURE_DATA
@ -212,7 +219,7 @@ class VolatileTexture
kImage,
}ccCachedImageType;
public:
private:
VolatileTexture(Texture2D *t);
/**
* @js NA
@ -220,25 +227,8 @@ public:
*/
~VolatileTexture();
static void addImageTexture(Texture2D *tt, const char* imageFileName);
static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition);
static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize);
static void addImage(Texture2D *tt, Image *image);
static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams);
static void removeTexture(Texture2D *t);
static void reloadAllTextures();
public:
static std::list<VolatileTexture*> _textures;
static bool _isReloading;
private:
// find VolatileTexture by Texture2D*
// if not found, create a new one
static VolatileTexture* findVolotileTexture(Texture2D *tt);
protected:
friend class VolatileTextureMgr;
Texture2D *_texture;
Image *_uiImage;
@ -257,6 +247,26 @@ protected:
FontDefinition _fontDefinition;
};
class VolatileTextureMgr
{
public:
static void addImageTexture(Texture2D *tt, const char* imageFileName);
static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition);
static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize);
static void addImage(Texture2D *tt, Image *image);
static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams);
static void removeTexture(Texture2D *t);
static void reloadAllTextures();
public:
static std::list<VolatileTexture*> _textures;
static bool _isReloading;
private:
// find VolatileTexture by Texture2D*
// if not found, create a new one
static VolatileTexture* findVolotileTexture(Texture2D *tt);
};
#endif
// end of textures group

View File

@ -32,6 +32,9 @@ THE SOFTWARE.
NS_CC_BEGIN
float TransitionPageTurn::POLYGON_OFFSET_FACTOR = -20.f;
float TransitionPageTurn::POLYGON_OFFSET_UNITS = -20.f;
TransitionPageTurn::TransitionPageTurn()
{
}
@ -67,6 +70,27 @@ void TransitionPageTurn::sceneOrder()
_isInSceneOnTop = _back;
}
void TransitionPageTurn::draw()
{
Scene::draw();
if( _isInSceneOnTop ) {
_outScene->visit();
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS);
_inScene->visit();
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0);
} else {
_inScene->visit();
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(POLYGON_OFFSET_FACTOR, POLYGON_OFFSET_UNITS);
_outScene->visit();
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0, 0);
}
}
void TransitionPageTurn::onEnter()
{
TransitionScene::onEnter();

View File

@ -64,6 +64,11 @@ public:
* @lua NA
*/
virtual ~TransitionPageTurn();
//
// Overrides
//
virtual void draw() override;
/**
* Creates a base transition with duration and incoming scene.
@ -83,8 +88,9 @@ protected:
virtual void sceneOrder() override;
protected:
bool _back;
bool _back;
static float POLYGON_OFFSET_FACTOR;
static float POLYGON_OFFSET_UNITS;
};
// end of transition group

View File

@ -59,7 +59,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle
*doc = xmlDoc;
//CCFileData data(UserDefault::getInstance()->getXMLFilePath().c_str(),"rt");
long nSize;
const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize);
char* pXmlBuffer = (char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize);
//const char* pXmlBuffer = (const char*)data.getBuffer();
if(NULL == pXmlBuffer)
{
@ -67,7 +67,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLEle
break;
}
xmlDoc->Parse(pXmlBuffer, nSize);
delete[] pXmlBuffer;
free(pXmlBuffer);
// get root node
*rootNode = xmlDoc->RootElement();
if (NULL == *rootNode)
@ -323,7 +323,7 @@ Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue)
if (decodedData) {
ret = Data::create(decodedData, decodedDataLen);
delete decodedData;
free(decodedData);
}
}
@ -408,7 +408,8 @@ void UserDefault::setDataForKey(const char* pKey, const Data& value) {
setValueForKey(pKey, encodedData);
if (encodedData) delete encodedData;
if (encodedData)
free(encodedData);
}
UserDefault* UserDefault::getInstance()
@ -479,7 +480,7 @@ bool UserDefault::createXMLFile()
{
return false;
}
tinyxml2::XMLDeclaration *pDeclaration = pDoc->NewDeclaration("1.0");
tinyxml2::XMLDeclaration *pDeclaration = pDoc->NewDeclaration(nullptr);
if (NULL==pDeclaration)
{
return false;

View File

@ -74,7 +74,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc
tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();
*doc = xmlDoc;
long size;
const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size);
char* pXmlBuffer = (char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size);
//const char* pXmlBuffer = (const char*)data.getBuffer();
if(NULL == pXmlBuffer)
{
@ -82,7 +82,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc
break;
}
xmlDoc->Parse(pXmlBuffer);
delete[] pXmlBuffer;
free(pXmlBuffer);
// get root node
rootNode = xmlDoc->RootElement();
if (NULL == rootNode)
@ -394,7 +394,7 @@ Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue)
// set value in NSUserDefaults
setDataForKey(pKey, ret);
delete decodedData;
free(decodedData);
flush();

View File

@ -74,8 +74,8 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc
{
tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();
*doc = xmlDoc;
unsigned long nSize;
const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize);
long size;
char* pXmlBuffer = (char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &size);
//const char* pXmlBuffer = (const char*)data.getBuffer();
if(NULL == pXmlBuffer)
{
@ -83,7 +83,7 @@ static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDoc
break;
}
xmlDoc->Parse(pXmlBuffer);
delete[] pXmlBuffer;
free(pXmlBuffer);
// get root node
rootNode = xmlDoc->RootElement();
if (NULL == rootNode)
@ -367,10 +367,7 @@ Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue)
// set value in NSUserDefaults
setDataForKey(pKey, ret);
CC_SAFE_DELETE_ARRAY(decodedData);
delete decodedData;
free(decodedData);
flush();
// delete xmle node
@ -392,9 +389,8 @@ Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue)
string encodedStr = getStringForKeyJNI(pKey, encodedDefaultData);
if (encodedDefaultData) {
delete encodedDefaultData;
}
if (encodedDefaultData)
free(encodedDefaultData);
CCLOG("ENCODED STRING: --%s--%d", encodedStr.c_str(), encodedStr.length());
@ -408,6 +404,7 @@ Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue)
if (decodedData && decodedDataLen) {
ret = Data::create(decodedData, decodedDataLen);
free(decodedData);
}
CCLOG("RETURNED %p!", ret);
@ -475,9 +472,8 @@ void UserDefault::setDataForKey(const char* pKey, const Data& value)
return setStringForKeyJNI(pKey, encodedData);
if (encodedData) {
delete encodedData;
}
if (encodedData)
free(encodedData);
}
// XXX: deprecated

View File

@ -1,204 +0,0 @@
TARGET = libcocos2d.so
INCLUDES =
SOURCES = \
CCAction.cpp \
CCActionCamera.cpp \
CCActionEase.cpp \
CCActionGrid.cpp \
CCActionGrid3D.cpp \
CCActionInstant.cpp \
CCActionInterval.cpp \
CCActionManager.cpp \
CCActionPageTurn3D.cpp \
CCActionProgressTimer.cpp \
CCActionTiledGrid.cpp \
CCActionCatmullRom.cpp \
CCActionTween.cpp \
CCAtlasNode.cpp \
CCNode.cpp \
../base/CCAffineTransform.cpp \
../base/CCAutoreleasePool.cpp \
../base/CCGeometry.cpp \
../base/CCNS.cpp \
../base/CCObject.cpp \
../base/CCSet.cpp \
../base/CCArray.cpp \
../base/CCDictionary.cpp \
../base/CCString.cpp \
../base/CCDataVisitor.cpp \
../base/CCData.cpp \
CCEventAcceleration.cpp \
CCEventListenerAcceleration.cpp \
CCEvent.cpp \
CCEventDispatcher.cpp \
CCEventListener.cpp \
CCEventKeyboard.cpp \
CCEventListenerKeyboard.cpp \
CCEventMouse.cpp \
CCEventListenerMouse.cpp \
CCTouch.cpp \
CCEventTouch.cpp \
CCEventListenerTouch.cpp \
CCEventCustom.cpp \
CCEventListenerCustom.cpp \
CCDrawingPrimitives.cpp \
CCDrawNode.cpp \
CCGrabber.cpp \
CCGrid.cpp \
CCFont.cpp \
CCFontAtlas.cpp \
CCFontAtlasCache.cpp \
CCFontAtlasFactory.cpp \
CCFontDefinition.cpp \
CCFontFNT.cpp \
CCFontFreeType.cpp \
CCLabel.cpp \
CCLabelAtlas.cpp \
CCLabelBMFont.cpp \
CCLabelTTF.cpp \
CCLabelTextFormatter.cpp \
CCTextImage.cpp \
CCLayer.cpp \
CCScene.cpp \
CCTransition.cpp \
CCTransitionPageTurn.cpp \
CCTransitionProgress.cpp \
CCMenu.cpp \
CCMenuItem.cpp \
CCMotionStreak.cpp \
CCProgressTimer.cpp \
CCClippingNode.cpp \
CCRenderTexture.cpp \
CCParticleExamples.cpp \
CCParticleSystem.cpp \
CCParticleSystemQuad.cpp \
CCParticleBatchNode.cpp \
../physics/box2d/CCPhysicsContactInfo_box2d.cpp \
../physics/box2d/CCPhysicsJointInfo_box2d.cpp \
../physics/box2d/CCPhysicsShapeInfo_box2d.cpp \
../physics/box2d/CCPhysicsBodyInfo_box2d.cpp \
../physics/box2d/CCPhysicsWorldInfo_box2d.cpp \
../physics/chipmunk/CCPhysicsContactInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsJointInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsShapeInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsBodyInfo_chipmunk.cpp \
../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \
../physics/CCPhysicsBody.cpp \
../physics/CCPhysicsContact.cpp \
../physics/CCPhysicsShape.cpp \
../physics/CCPhysicsJoint.cpp \
../physics/CCPhysicsWorld.cpp \
../platform/CCSAXParser.cpp \
../platform/CCThread.cpp \
../platform/CCEGLViewProtocol.cpp \
../platform/CCFileUtils.cpp \
../platform/linux/CCStdC.cpp \
../platform/linux/CCFileUtilsLinux.cpp \
../platform/linux/CCCommon.cpp \
../platform/linux/CCApplication.cpp \
../platform/linux/CCEGLView.cpp \
../platform/linux/CCImage.cpp \
../platform/linux/CCDevice.cpp \
../base/etc1.cpp \
../base/s3tc.cpp \
../base/atitc.cpp \
CCScriptSupport.cpp \
CCAnimation.cpp \
CCAnimationCache.cpp \
CCSprite.cpp \
CCSpriteBatchNode.cpp \
CCSpriteFrame.cpp \
CCSpriteFrameCache.cpp \
ccUTF8.cpp \
CCProfiling.cpp \
CCUserDefault.cpp \
TransformUtils.cpp \
base64.cpp \
ccUtils.cpp \
CCVertex.cpp \
CCNotificationCenter.cpp \
TGAlib.cpp \
../../external/tinyxml2/tinyxml2.cpp \
ZipUtils.cpp \
../../external/unzip/ioapi.cpp \
../../external/unzip/unzip.cpp \
ccCArray.cpp \
CCComponent.cpp \
CCComponentContainer.cpp \
CCIMEDispatcher.cpp \
CCTextFieldTTF.cpp \
CCTexture2D.cpp \
CCTextureAtlas.cpp \
CCTextureCache.cpp \
CCParallaxNode.cpp \
CCTMXLayer.cpp \
CCTMXObjectGroup.cpp \
CCTMXTiledMap.cpp \
CCTMXXMLParser.cpp \
CCTileMapAtlas.cpp \
CCGLProgram.cpp \
ccGLStateCache.cpp \
CCShaderCache.cpp \
ccShaders.cpp \
../math/kazmath/src/aabb.c \
../math/kazmath/src/plane.c \
../math/kazmath/src/vec2.c \
../math/kazmath/src/mat3.c \
../math/kazmath/src/quaternion.c \
../math/kazmath/src/vec3.c \
../math/kazmath/src/mat4.c \
../math/kazmath/src/ray2.c \
../math/kazmath/src/vec4.c \
../math/kazmath/src/neon_matrix_impl.c \
../math/kazmath/src/utility.c \
../math/kazmath/src/GL/mat4stack.c \
../math/kazmath/src/GL/matrix.c \
CCCamera.cpp \
CCConfiguration.cpp \
CCDirector.cpp \
CCScheduler.cpp \
ccFPSImages.c \
ccTypes.cpp \
cocos2d.cpp \
CCDeprecated.cpp
COCOS_ROOT = ../..
include cocos2dx.mk
CXXFLAGS += -Wno-sequence-point
CCFLAGS += -Wno-sequence-point
STATICLIBS += $(LIB_DIR)/libchipmunk.a
TARGET := $(LIB_DIR)/$(TARGET)
all: $(TARGET)
$(TARGET): $(OBJECTS) $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_LINK)$(CXX) $(CXXFLAGS) $(OBJECTS) -shared -o $@ $(SHAREDLIBS) $(STATICLIBS) $(LIBS)
$(OBJ_DIR)/%.o: %.cpp $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: ../%.cpp $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: ../../%.cpp $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CXX)$(CXX) $(CXXFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: %.c $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@
$(OBJ_DIR)/%.o: ../%.c $(CORE_MAKEFILE_LIST)
@mkdir -p $(@D)
$(LOG_CC)$(CC) $(CCFLAGS) $(INCLUDES) $(DEFINES) -c $< -o $@

View File

@ -270,7 +270,7 @@ tImageTGA * tgaLoad(const char *filename)
}
} while(0);
CC_SAFE_DELETE_ARRAY(pBuffer);
free(pBuffer);
return info;
}

View File

@ -39,7 +39,7 @@ bool ZipUtils::s_bEncryptionKeyIsValid = false;
// --------------------- ZipUtils ---------------------
inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, long len)
inline void ZipUtils::decodeEncodedPvr(unsigned int *data, long len)
{
const int enclen = 1024;
const int securelen = 512;
@ -47,10 +47,10 @@ inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, long len)
// check if key was set
// make sure to call caw_setkey_part() for all 4 key parts
CCASSERT(s_uEncryptedPvrKeyParts[0] != 0, "Cocos2D: CCZ file is encrypted but key part 0 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
CCASSERT(s_uEncryptedPvrKeyParts[1] != 0, "Cocos2D: CCZ file is encrypted but key part 1 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
CCASSERT(s_uEncryptedPvrKeyParts[2] != 0, "Cocos2D: CCZ file is encrypted but key part 2 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
CCASSERT(s_uEncryptedPvrKeyParts[3] != 0, "Cocos2D: CCZ file is encrypted but key part 3 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
CCASSERT(s_uEncryptedPvrKeyParts[0] != 0, "Cocos2D: CCZ file is encrypted but key part 0 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
CCASSERT(s_uEncryptedPvrKeyParts[1] != 0, "Cocos2D: CCZ file is encrypted but key part 1 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
CCASSERT(s_uEncryptedPvrKeyParts[2] != 0, "Cocos2D: CCZ file is encrypted but key part 2 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
CCASSERT(s_uEncryptedPvrKeyParts[3] != 0, "Cocos2D: CCZ file is encrypted but key part 3 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
// create long key
if(!s_bEncryptionKeyIsValid)
@ -108,7 +108,7 @@ inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, long len)
}
}
inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, long len)
inline unsigned int ZipUtils::checksumPvr(const unsigned int *data, long len)
{
unsigned int cs = 0;
const int cslen = 128;
@ -127,13 +127,13 @@ inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, long len)
// Should buffer factor be 1.5 instead of 2 ?
#define BUFFER_INC_FACTOR (2)
int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint)
int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint)
{
/* ret value */
int err = Z_OK;
long bufferSize = outLenghtHint;
*out = new unsigned char[bufferSize];
*out = (unsigned char*)malloc(bufferSize);
z_stream d_stream; /* decompression stream */
d_stream.zalloc = (alloc_func)0;
@ -192,10 +192,10 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned
return err;
}
int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint)
int ZipUtils::inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint)
{
long outLength = 0;
int err = ccInflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint);
int err = inflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint);
if (err != Z_OK || *out == NULL) {
if (err == Z_MEM_ERROR)
@ -214,22 +214,24 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned
{
CCLOG("cocos2d: ZipUtils: Unknown error while decompressing map data!");
}
delete[] *out;
*out = NULL;
if(*out) {
free(*out);
*out = NULL;
}
outLength = 0;
}
return outLength;
}
int ZipUtils::ccInflateMemory(unsigned char *in, long inLength, unsigned char **out)
int ZipUtils::inflateMemory(unsigned char *in, long inLength, unsigned char **out)
{
// 256k for hint
return ccInflateMemoryWithHint(in, inLength, out, 256 * 1024);
return inflateMemoryWithHint(in, inLength, out, 256 * 1024);
}
int ZipUtils::ccInflateGZipFile(const char *path, unsigned char **out)
int ZipUtils::inflateGZipFile(const char *path, unsigned char **out)
{
int len;
unsigned int offset = 0;
@ -299,7 +301,7 @@ int ZipUtils::ccInflateGZipFile(const char *path, unsigned char **out)
return offset;
}
bool ZipUtils::ccIsCCZFile(const char *path)
bool ZipUtils::isCCZFile(const char *path)
{
// load file into memory
unsigned char* compressed = NULL;
@ -307,18 +309,21 @@ bool ZipUtils::ccIsCCZFile(const char *path)
long fileLen = 0;
compressed = FileUtils::getInstance()->getFileData(path, "rb", &fileLen);
if(NULL == compressed || 0 == fileLen)
if(compressed == NULL || fileLen == 0)
{
CCLOG("cocos2d: ZipUtils: loading file failed");
return false;
}
return ccIsCCZBuffer(compressed, fileLen);
bool ret = isCCZBuffer(compressed, fileLen);
free(compressed);
return ret;
}
bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, long len)
bool ZipUtils::isCCZBuffer(const unsigned char *buffer, long len)
{
if (len < sizeof(struct CCZHeader))
if (static_cast<size_t>(len) < sizeof(struct CCZHeader))
{
return false;
}
@ -328,7 +333,7 @@ bool ZipUtils::ccIsCCZBuffer(const unsigned char *buffer, long len)
}
bool ZipUtils::ccIsGZipFile(const char *path)
bool ZipUtils::isGZipFile(const char *path)
{
// load file into memory
unsigned char* compressed = NULL;
@ -342,10 +347,12 @@ bool ZipUtils::ccIsGZipFile(const char *path)
return false;
}
return ccIsGZipBuffer(compressed, fileLen);
bool ret = isGZipBuffer(compressed, fileLen);
free(compressed);
return ret;
}
bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, long len)
bool ZipUtils::isGZipBuffer(const unsigned char *buffer, long len)
{
if (len < 2)
{
@ -356,7 +363,7 @@ bool ZipUtils::ccIsGZipBuffer(const unsigned char *buffer, long len)
}
int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsigned char **out)
int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, long bufferLen, unsigned char **out)
{
struct CCZHeader *header = (struct CCZHeader*) buffer;
@ -402,11 +409,11 @@ int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, long bufferLen, un
unsigned int* ints = (unsigned int*)(buffer+12);
int enclen = (bufferLen-12)/4;
ccDecodeEncodedPvr(ints, enclen);
decodeEncodedPvr(ints, enclen);
#if COCOS2D_DEBUG > 0
// verify checksum in debug mode
unsigned int calculated = ccChecksumPvr(ints, enclen);
unsigned int calculated = checksumPvr(ints, enclen);
unsigned int required = CC_SWAP_INT32_BIG_TO_HOST( header->reserved );
if(calculated != required)
@ -446,7 +453,7 @@ int ZipUtils::ccInflateCCZBuffer(const unsigned char *buffer, long bufferLen, un
return len;
}
int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out)
int ZipUtils::inflateCCZFile(const char *path, unsigned char **out)
{
CCAssert(out, "");
CCAssert(&*out, "");
@ -463,10 +470,12 @@ int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out)
return -1;
}
return ccInflateCCZBuffer(compressed, fileLen, out);
int ret = inflateCCZBuffer(compressed, fileLen, out);
free(compressed);
return ret;
}
void ZipUtils::ccSetPvrEncryptionKeyPart(int index, unsigned int value)
void ZipUtils::setPvrEncryptionKeyPart(int index, unsigned int value)
{
CCASSERT(index >= 0, "Cocos2d: key part index cannot be less than 0");
CCASSERT(index <= 3, "Cocos2d: key part index cannot be greater than 3");
@ -478,12 +487,12 @@ void ZipUtils::ccSetPvrEncryptionKeyPart(int index, unsigned int value)
}
}
void ZipUtils::ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4)
void ZipUtils::setPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4)
{
ccSetPvrEncryptionKeyPart(0, keyPart1);
ccSetPvrEncryptionKeyPart(1, keyPart2);
ccSetPvrEncryptionKeyPart(2, keyPart3);
ccSetPvrEncryptionKeyPart(3, keyPart4);
setPvrEncryptionKeyPart(0, keyPart1);
setPvrEncryptionKeyPart(1, keyPart2);
setPvrEncryptionKeyPart(2, keyPart3);
setPvrEncryptionKeyPart(3, keyPart4);
}
// --------------------- ZipFile ---------------------
@ -582,14 +591,12 @@ bool ZipFile::fileExists(const std::string &fileName) const
return ret;
}
unsigned char *ZipFile::getFileData(const std::string &fileName, long *pSize)
unsigned char *ZipFile::getFileData(const std::string &fileName, long *size)
{
unsigned char * pBuffer = NULL;
if (pSize)
{
*pSize = 0;
}
unsigned char * buffer = NULL;
if (size)
*size = 0;
do
{
CC_BREAK_IF(!_data->zipFile);
@ -606,18 +613,18 @@ unsigned char *ZipFile::getFileData(const std::string &fileName, long *pSize)
nRet = unzOpenCurrentFile(_data->zipFile);
CC_BREAK_IF(UNZ_OK != nRet);
pBuffer = new unsigned char[fileInfo.uncompressed_size];
int CC_UNUSED nSize = unzReadCurrentFile(_data->zipFile, pBuffer, fileInfo.uncompressed_size);
buffer = (unsigned char*)malloc(fileInfo.uncompressed_size);
int CC_UNUSED nSize = unzReadCurrentFile(_data->zipFile, buffer, fileInfo.uncompressed_size);
CCASSERT(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
if (pSize)
if (size)
{
*pSize = fileInfo.uncompressed_size;
*size = fileInfo.uncompressed_size;
}
unzCloseCurrentFile(_data->zipFile);
} while (0);
return pBuffer;
return buffer;
}
NS_CC_END

View File

@ -27,6 +27,7 @@ THE SOFTWARE.
#include <string>
#include "CCPlatformConfig.h"
#include "CCPlatformDefine.h"
#include "CCPlatformMacros.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCFileUtilsAndroid.h"
@ -64,7 +65,8 @@ namespace cocos2d
*
@since v0.8.1
*/
static int ccInflateMemory(unsigned char *in, long inLength, unsigned char **out);
CC_DEPRECATED_ATTRIBUTE static int ccInflateMemory(unsigned char *in, long inLength, unsigned char **out) { return inflateMemory(in, inLength, out); }
static int inflateMemory(unsigned char *in, long inLength, unsigned char **out);
/**
* Inflates either zlib or gzip deflated memory. The inflated memory is
@ -76,7 +78,8 @@ namespace cocos2d
*
@since v1.0.0
*/
static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLenghtHint);
CC_DEPRECATED_ATTRIBUTE static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint) { return inflateMemoryWithHint(in, inLength, out, outLengthHint); }
static int inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long outLengthHint);
/** inflates a GZip file into memory
*
@ -84,7 +87,8 @@ namespace cocos2d
*
* @since v0.99.5
*/
static int ccInflateGZipFile(const char *filename, unsigned char **out);
CC_DEPRECATED_ATTRIBUTE static int ccInflateGZipFile(const char *filename, unsigned char **out) { return inflateGZipFile(filename, out); }
static int inflateGZipFile(const char *filename, unsigned char **out);
/** test a file is a GZip format file or not
*
@ -92,7 +96,8 @@ namespace cocos2d
*
* @since v3.0
*/
static bool ccIsGZipFile(const char *filename);
CC_DEPRECATED_ATTRIBUTE static bool ccIsGZipFile(const char *filename) { return isGZipFile(filename); }
static bool isGZipFile(const char *filename);
/** test the buffer is GZip format or not
*
@ -100,7 +105,8 @@ namespace cocos2d
*
* @since v3.0
*/
static bool ccIsGZipBuffer(const unsigned char *buffer, long len);
CC_DEPRECATED_ATTRIBUTE static bool ccIsGZipBuffer(const unsigned char *buffer, long len) { return isGZipBuffer(buffer, len); }
static bool isGZipBuffer(const unsigned char *buffer, long len);
/** inflates a CCZ file into memory
*
@ -108,7 +114,8 @@ namespace cocos2d
*
* @since v0.99.5
*/
static int ccInflateCCZFile(const char *filename, unsigned char **out);
CC_DEPRECATED_ATTRIBUTE static int ccInflateCCZFile(const char *filename, unsigned char **out) { return inflateCCZFile(filename, out); }
static int inflateCCZFile(const char *filename, unsigned char **out);
/** inflates a buffer with CCZ format into memory
*
@ -116,7 +123,8 @@ namespace cocos2d
*
* @since v3.0
*/
static int ccInflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out);
CC_DEPRECATED_ATTRIBUTE static int ccInflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out) { return inflateCCZBuffer(buffer, len, out); }
static int inflateCCZBuffer(const unsigned char *buffer, long len, unsigned char **out);
/** test a file is a CCZ format file or not
*
@ -124,7 +132,8 @@ namespace cocos2d
*
* @since v3.0
*/
static bool ccIsCCZFile(const char *filename);
CC_DEPRECATED_ATTRIBUTE static bool ccIsCCZFile(const char *filename) { return isCCZFile(filename); }
static bool isCCZFile(const char *filename);
/** test the buffer is CCZ format or not
*
@ -132,7 +141,8 @@ namespace cocos2d
*
* @since v3.0
*/
static bool ccIsCCZBuffer(const unsigned char *buffer, long len);
CC_DEPRECATED_ATTRIBUTE static bool ccIsCCZBuffer(const unsigned char *buffer, long len) { return isCCZBuffer(buffer, len); }
static bool isCCZBuffer(const unsigned char *buffer, long len);
/** Sets the pvr.ccz encryption key parts separately for added
* security.
@ -141,10 +151,10 @@ namespace cocos2d
* 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function 4
* different times, preferably from 4 different source files, as follows
*
* ZipUtils::ccSetPvrEncryptionKeyPart(0, 0xaaaaaaaa);
* ZipUtils::ccSetPvrEncryptionKeyPart(1, 0xbbbbbbbb);
* ZipUtils::ccSetPvrEncryptionKeyPart(2, 0xcccccccc);
* ZipUtils::ccSetPvrEncryptionKeyPart(3, 0xdddddddd);
* ZipUtils::setPvrEncryptionKeyPart(0, 0xaaaaaaaa);
* ZipUtils::setPvrEncryptionKeyPart(1, 0xbbbbbbbb);
* ZipUtils::setPvrEncryptionKeyPart(2, 0xcccccccc);
* ZipUtils::setPvrEncryptionKeyPart(3, 0xdddddddd);
*
* Splitting the key into 4 parts and calling the function
* from 4 different source files increases the difficulty to
@ -152,15 +162,16 @@ namespace cocos2d
* is *never* 100% secure and the key code can be cracked by
* knowledgable persons.
*
* IMPORTANT: Be sure to call ccSetPvrEncryptionKey or
* ccSetPvrEncryptionKeyPart with all of the key parts *before* loading
* IMPORTANT: Be sure to call setPvrEncryptionKey or
* setPvrEncryptionKeyPart with all of the key parts *before* loading
* the spritesheet or decryption will fail and the spritesheet
* will fail to load.
*
* @param index part of the key [0..3]
* @param value value of the key part
*/
static void ccSetPvrEncryptionKeyPart(int index, unsigned int value);
CC_DEPRECATED_ATTRIBUTE static void ccSetPvrEncryptionKeyPart(int index, unsigned int value) { setPvrEncryptionKeyPart(index, value); }
static void setPvrEncryptionKeyPart(int index, unsigned int value);
/** Sets the pvr.ccz encryption key.
*
@ -168,14 +179,14 @@ namespace cocos2d
* 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function with
* the key split into 4 parts as follows
*
* ZipUtils::ccSetPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd);
* ZipUtils::setPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd);
*
* Note that using this function makes it easier to reverse engineer and
* discover the complete key because the key parts are present in one
* function call.
*
* IMPORTANT: Be sure to call ccSetPvrEncryptionKey or
* ccSetPvrEncryptionKeyPart with all of the key parts *before* loading
* IMPORTANT: Be sure to call setPvrEncryptionKey or
* setPvrEncryptionKeyPart with all of the key parts *before* loading
* the spritesheet or decryption will fail and the spritesheet
* will fail to load.
*
@ -184,13 +195,13 @@ namespace cocos2d
* @param keyPart3 the key value part 3.
* @param keyPart4 the key value part 4.
*/
static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4);
CC_DEPRECATED_ATTRIBUTE static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4) { setPvrEncryptionKey(keyPart1, keyPart2, keyPart3, keyPart4); }
static void setPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4);
private:
static int ccInflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength,
long outLenghtHint);
static inline void ccDecodeEncodedPvr (unsigned int *data, long len);
static inline unsigned int ccChecksumPvr(const unsigned int *data, long len);
static int inflateMemoryWithHint(unsigned char *in, long inLength, unsigned char **out, long *outLength, long outLenghtHint);
static inline void decodeEncodedPvr (unsigned int *data, long len);
static inline unsigned int checksumPvr(const unsigned int *data, long len);
static unsigned int s_uEncryptedPvrKeyParts[4];
static unsigned int s_uEncryptionKey[1024];
@ -249,7 +260,7 @@ namespace cocos2d
* @param fileName File name
* @param[out] pSize If the file read operation succeeds, it will be the data size, otherwise 0.
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
* @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
*
* @since v2.0.5
*/

View File

@ -141,7 +141,7 @@ int base64Decode(const unsigned char *in, unsigned int inLength, unsigned char *
unsigned int outLength = 0;
//should be enough to store 6-bit buffers in 8-bit buffers
*out = new unsigned char[(size_t)(inLength * 3.0f / 4.0f + 1)];
*out = (unsigned char*)malloc(inLength * 3.0f / 4.0f + 1);
if( *out ) {
int ret = _base64Decode(in, inLength, *out, &outLength);
@ -150,7 +150,7 @@ int base64Decode(const unsigned char *in, unsigned int inLength, unsigned char *
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
printf("Base64Utils: error decoding");
#endif
delete [] *out;
free(*out);
*out = NULL;
outLength = 0;
}
@ -162,7 +162,7 @@ int base64Encode(const unsigned char *in, unsigned int inLength, char **out) {
unsigned int outLength = inLength * 4 / 3 + (inLength % 3 > 0 ? 4 : 0);
//should be enough to store 8-bit buffers in 6-bit buffers
*out = new char[outLength+1];
*out = (char*)malloc(outLength+1);
if( *out ) {
_base64Encode(in, inLength, *out);
}

View File

@ -37,7 +37,7 @@ namespace cocos2d {
/**
* Decodes a 64base encoded memory. The decoded memory is
* expected to be freed by the caller.
* expected to be freed by the caller by calling `free()`
*
* @returns the length of the out buffer
*
@ -47,7 +47,7 @@ int base64Decode(const unsigned char *in, unsigned int inLength, unsigned char *
/**
* Encodes bytes into a 64base encoded memory with terminating '\0' character.
* The encoded memory is expected to be freed by the caller.
* The encoded memory is expected to be freed by the caller by calling `free()`
*
* @returns the length of the out buffer
*

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "CCGLProgram.h"
#include "CCDirector.h"
#include "ccConfig.h"
#include "CCConfiguration.h"
// extern
#include "kazmath/GL/matrix.h"
@ -50,9 +51,7 @@ static GLuint s_uCurrentBoundTexture[kMaxActiveTexture] = {(GLuint)-1,(GLuin
static GLenum s_eBlendingSource = -1;
static GLenum s_eBlendingDest = -1;
static int s_eGLServerState = 0;
#if CC_TEXTURE_ATLAS_USE_VAO
static GLuint s_uVAO = 0;
#endif
#endif // CC_ENABLE_GL_STATE_CACHE
// GL State Cache functions
@ -78,9 +77,7 @@ void invalidateStateCache( void )
s_eBlendingSource = -1;
s_eBlendingDest = -1;
s_eGLServerState = 0;
#if CC_TEXTURE_ATLAS_USE_VAO
s_uVAO = 0;
#endif
#endif // CC_ENABLE_GL_STATE_CACHE
}
@ -187,19 +184,20 @@ void deleteTextureN(GLuint textureUnit, GLuint textureId)
void bindVAO(GLuint vaoId)
{
#if CC_TEXTURE_ATLAS_USE_VAO
if (Configuration::getInstance()->supportsShareableVAO())
{
#if CC_ENABLE_GL_STATE_CACHE
if (s_uVAO != vaoId)
{
s_uVAO = vaoId;
glBindVertexArray(vaoId);
}
if (s_uVAO != vaoId)
{
s_uVAO = vaoId;
glBindVertexArray(vaoId);
}
#else
glBindVertexArray(vaoId);
glBindVertexArray(vaoId);
#endif // CC_ENABLE_GL_STATE_CACHE
#endif
}
}
//#pragma mark - GL Vertex Attrib functions

View File

@ -26,42 +26,221 @@
NS_CC_BEGIN
Color4B::Color4B(const Color4F &color4F)
: r((GLubyte)(color4F.r * 255.0f)),
g((GLubyte)(color4F.g * 255.0f)),
b((GLubyte)(color4F.b * 255.0f)),
a((GLubyte)(color4F.a * 255.0f))
/**
* Color3B
*/
Color3B::Color3B()
: r(0)
, g(0)
, b(0)
{}
const Color3B Color3B::WHITE(255,255,255);
const Color3B Color3B::YELLOW(255,255,0);
const Color3B Color3B::GREEN(0,255,0);
const Color3B Color3B::BLUE(0,0,255);
const Color3B Color3B::RED(255,0,0);
const Color3B Color3B::MAGENTA(255,0,255);
const Color3B Color3B::BLACK(0,0,0);
const Color3B Color3B::ORANGE(255,127,0);
const Color3B Color3B::GRAY(166,166,166);
Color3B::Color3B(GLubyte _r, GLubyte _g, GLubyte _b)
: r(_r)
, g(_g)
, b(_b)
{}
const Color4B Color4B::WHITE(255,255,255,255);
const Color4B Color4B::YELLOW(255,255,0,255);
const Color4B Color4B::GREEN(0,255,0,255);
const Color4B Color4B::BLUE(0,0,255,255);
const Color4B Color4B::RED(255,0,0,255);
const Color4B Color4B::MAGENTA(255,0,255,255);
const Color4B Color4B::BLACK(0,0,0,255);
const Color4B Color4B::ORANGE(255,127,0,255);
const Color4B Color4B::GRAY(166,166,166,255);
Color3B::Color3B(const Color4B& color)
: r(color.r)
, g(color.g)
, b(color.b)
{}
const Color4F Color4F::WHITE(1,1,1,1);
const Color4F Color4F::YELLOW(1,1,0,1);
const Color4F Color4F::GREEN(0,1,0,1);
const Color4F Color4F::BLUE(0,0,1,1);
const Color4F Color4F::RED(1,0,0,1);
const Color4F Color4F::MAGENTA(1,0,1,1);
const Color4F Color4F::BLACK(0,0,0,1);
const Color4F Color4F::ORANGE(1,0.5f,0,1);
const Color4F Color4F::GRAY(0.65f,0.65f,0.65f,1);
Color3B::Color3B(const Color4F& color)
: r(color.r * 255.0f)
, g(color.g * 255.0f)
, b(color.b * 255.0f)
{}
bool Color3B::operator==(const Color3B& right) const
{
return (r == right.r && g == right.g && b == right.b);
}
bool Color3B::operator==(const Color4B& right) const
{
return (r == right.r && g == right.g && b == right.b && 255 == right.a);
}
bool Color3B::operator==(const Color4F& right) const
{
return (right.a == 1.0f && Color4F(*this) == right);
}
bool Color3B::operator!=(const Color3B& right) const
{
return !(*this == right);
}
bool Color3B::operator!=(const Color4B& right) const
{
return !(*this == right);
}
bool Color3B::operator!=(const Color4F& right) const
{
return !(*this == right);
}
/**
* Color4B
*/
Color4B::Color4B()
: r(0)
, g(0)
, b(0)
, a(0)
{}
Color4B::Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a)
: r(_r)
, g(_g)
, b(_b)
, a(_a)
{}
Color4B::Color4B(const Color3B& color)
: r(color.r * 255)
, g(color.g * 255)
, b(color.b * 255)
, a(255)
{}
Color4B::Color4B(const Color4F& color)
: r(color.r * 255)
, g(color.g * 255)
, b(color.b * 255)
, a(color.a * 255)
{}
bool Color4B::operator==(const Color4B& right) const
{
return (r == right.r && g == right.g && b == right.b && a == right.a);
}
bool Color4B::operator==(const Color3B& right) const
{
return (r == right.r && g == right.g && b == right.b && a == 255);
}
bool Color4B::operator==(const Color4F& right) const
{
return (*this == Color4B(right));
}
bool Color4B::operator!=(const Color4B& right) const
{
return !(*this == right);
}
bool Color4B::operator!=(const Color3B& right) const
{
return !(*this == right);
}
bool Color4B::operator!=(const Color4F& right) const
{
return !(*this == right);
}
/**
* Color4F
*/
Color4F::Color4F()
: r(0.0f)
, g(0.0f)
, b(0.0f)
, a(0.0f)
{}
Color4F::Color4F(float _r, float _g, float _b, float _a)
: r(_r)
, g(_g)
, b(_b)
, a(_a)
{}
Color4F::Color4F(const Color3B& color)
: r(color.r / 255.0f)
, g(color.g / 255.0f)
, b(color.b / 255.0f)
, a(1.0f)
{}
Color4F::Color4F(const Color4B& color)
: r(color.r / 255.0f)
, g(color.g / 255.0f)
, b(color.b / 255.0f)
, a(color.a / 255.0f)
{}
bool Color4F::operator==(const Color4F& right) const
{
return (r == right.r && g == right.g && b == right.b && a == right.a);
}
bool Color4F::operator==(const Color3B& right) const
{
return (a == 1.0f && Color3B(*this) == right);
}
bool Color4F::operator==(const Color4B& right) const
{
return (*this == Color4F(right));
}
bool Color4F::operator!=(const Color4F& right) const
{
return !(*this == right);
}
bool Color4F::operator!=(const Color3B& right) const
{
return !(*this == right);
}
bool Color4F::operator!=(const Color4B& right) const
{
return !(*this == right);
}
/**
* Color constants
*/
const Color3B Color3B::WHITE (255, 255, 255);
const Color3B Color3B::YELLOW (255, 255, 0);
const Color3B Color3B::GREEN ( 0, 255, 0);
const Color3B Color3B::BLUE ( 0, 0, 255);
const Color3B Color3B::RED (255, 0, 0);
const Color3B Color3B::MAGENTA(255, 0, 255);
const Color3B Color3B::BLACK ( 0, 0, 0);
const Color3B Color3B::ORANGE (255, 127, 0);
const Color3B Color3B::GRAY (166, 166, 166);
const Color4B Color4B::WHITE (255, 255, 255, 255);
const Color4B Color4B::YELLOW (255, 255, 0, 255);
const Color4B Color4B::GREEN ( 0, 255, 0, 255);
const Color4B Color4B::BLUE ( 0, 0, 255, 255);
const Color4B Color4B::RED (255, 0, 0, 255);
const Color4B Color4B::MAGENTA(255, 0, 255, 255);
const Color4B Color4B::BLACK ( 0, 0, 0, 255);
const Color4B Color4B::ORANGE (255, 127, 0, 255);
const Color4B Color4B::GRAY (166, 166, 166, 255);
const Color4F Color4F::WHITE ( 1, 1, 1, 1);
const Color4F Color4F::YELLOW ( 1, 1, 0, 1);
const Color4F Color4F::GREEN ( 0, 1, 0, 1);
const Color4F Color4F::BLUE ( 0, 0, 1, 1);
const Color4F Color4F::RED ( 1, 0, 0, 1);
const Color4F Color4F::MAGENTA( 1, 0, 1, 1);
const Color4F Color4F::BLACK ( 0, 0, 0, 1);
const Color4F Color4F::ORANGE ( 1, 0.5f, 0, 1);
const Color4F Color4F::GRAY (0.65f, 0.65f, 0.65f, 1);
const BlendFunc BlendFunc::DISABLE = {GL_ONE, GL_ZERO};
const BlendFunc BlendFunc::ALPHA_PREMULTIPLIED = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA};

View File

@ -31,29 +31,33 @@ THE SOFTWARE.
#include "CCGeometry.h"
#include "CCGL.h"
NS_CC_BEGIN
struct Color4B;
struct Color4F;
/** RGB color composed of bytes 3 bytes
@since v3.0
*/
struct Color3B
{
Color3B(): r(0), g(0), b(0) {}
Color3B(GLubyte _r, GLubyte _g, GLubyte _b)
: r(_r)
, g(_g)
, b(_b)
{}
bool equals(const Color3B &other)
Color3B();
Color3B(GLubyte _r, GLubyte _g, GLubyte _b);
explicit Color3B(const Color4B& color);
explicit Color3B(const Color4F& color);
bool operator==(const Color3B& right) const;
bool operator==(const Color4B& right) const;
bool operator==(const Color4F& right) const;
bool operator!=(const Color3B& right) const;
bool operator!=(const Color4B& right) const;
bool operator!=(const Color4F& right) const;
bool equals(const Color3B& other)
{
return (this->r == other.r &&
this->g == other.g &&
this->b == other.b);
return (*this == other);
}
GLubyte r;
GLubyte g;
GLubyte b;
@ -69,24 +73,22 @@ struct Color3B
const static Color3B GRAY;
};
struct Color4F;
/** RGBA color composed of 4 bytes
@since v3.0
*/
struct Color4B
{
Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a)
: r(_r)
, g(_g)
, b(_b)
, a(_a)
{}
Color4B(): r(0), g(0), b(0), a(0) {}
// This function should use Color4F, so implement it in .cpp file.
explicit Color4B(const Color4F &color4F);
Color4B();
Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a);
explicit Color4B(const Color3B& color);
explicit Color4B(const Color4F& color);
bool operator==(const Color4B& right) const;
bool operator==(const Color3B& right) const;
bool operator==(const Color4F& right) const;
bool operator!=(const Color4B& right) const;
bool operator!=(const Color3B& right) const;
bool operator!=(const Color4F& right) const;
GLubyte r;
GLubyte g;
@ -110,35 +112,21 @@ struct Color4B
*/
struct Color4F
{
Color4F(float _r, float _g, float _b, float _a)
: r(_r)
, g(_g)
, b(_b)
, a(_a)
{}
explicit Color4F(const Color3B &color3B)
: r(color3B.r / 255.0f)
, g(color3B.g / 255.0f)
, b(color3B.b / 255.0f)
, a(1.f)
{}
explicit Color4F(const Color4B &color4B)
: r(color4B.r / 255.0f)
, g(color4B.g / 255.0f)
, b(color4B.b / 255.0f)
, a(color4B.a / 255.0f)
{}
Color4F(): r(0.f), g(0.f), b(0.f), a(0.f) {}
Color4F();
Color4F(float _r, float _g, float _b, float _a);
explicit Color4F(const Color3B& color);
explicit Color4F(const Color4B& color);
bool operator==(const Color4F& right) const;
bool operator==(const Color3B& right) const;
bool operator==(const Color4B& right) const;
bool operator!=(const Color4F& right) const;
bool operator!=(const Color3B& right) const;
bool operator!=(const Color4B& right) const;
bool equals(const Color4F &other)
{
return (this->r == other.r &&
this->g == other.g &&
this->b == other.b &&
this->a == other.a);
return (*this == other);
}
GLfloat r;

View File

@ -354,8 +354,8 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode
for (auto& touch : touchEvent._touches)
{
// delete the touch object.
delete touch;
// release the touch object.
touch->release();
}
}

View File

@ -503,7 +503,7 @@ unsigned char* FileUtils::getFileData(const char* filename, const char* mode, lo
fseek(fp,0,SEEK_END);
*size = ftell(fp);
fseek(fp,0,SEEK_SET);
buffer = new unsigned char[*size];
buffer = (unsigned char*)malloc(*size);
*size = fread(buffer,sizeof(unsigned char), *size,fp);
fclose(fp);
} while (0);
@ -543,7 +543,7 @@ unsigned char* FileUtils::getFileDataFromZip(const char* zipFilePath, const char
nRet = unzOpenCurrentFile(pFile);
CC_BREAK_IF(UNZ_OK != nRet);
buffer = new unsigned char[FileInfo.uncompressed_size];
buffer = (unsigned char*)malloc(FileInfo.uncompressed_size);
int CC_UNUSED nSize = unzReadCurrentFile(pFile, buffer, FileInfo.uncompressed_size);
CCASSERT(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong");

View File

@ -86,7 +86,7 @@ public:
* @param[in] pszMode The read mode of the file.
* @param[out] pSize If the file read operation succeeds, it will be the data size, otherwise 0.
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
* @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
*/
virtual unsigned char* getFileData(const char* filename, const char* mode, long *size);
@ -96,7 +96,7 @@ public:
* @param[in] filename The resource file name which contains the relative path of the zip file.
* @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0.
* @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
* @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned.
*/
virtual unsigned char* getFileDataFromZip(const char* zipFilePath, const char* filename, long *size);

View File

@ -380,8 +380,8 @@ Image::Image()
, _fileType(Format::UNKOWN)
, _renderFormat(Texture2D::PixelFormat::NONE)
, _preMulti(false)
, _hasPremultipliedAlpha(true)
, _numberOfMipmaps(0)
, _hasPremultipliedAlpha(true)
{
}
@ -424,7 +424,7 @@ bool Image::initWithImageFile(const char * strPath)
bRet = initWithImageData(buffer, bufferLen);
}
CC_SAFE_DELETE_ARRAY(buffer);
free(buffer);
#endif // EMSCRIPTEN
return bRet;
@ -444,7 +444,7 @@ bool Image::initWithImageFileThreadSafe(const char *fullpath)
{
ret = initWithImageData(buffer, dataLen);
}
CC_SAFE_DELETE_ARRAY(buffer);
free(buffer);
return ret;
}
@ -460,13 +460,13 @@ bool Image::initWithImageData(const unsigned char * data, long dataLen)
int unpackedLen = 0;
//detecgt and unzip the compress file
if (ZipUtils::ccIsCCZBuffer(data, dataLen))
if (ZipUtils::isCCZBuffer(data, dataLen))
{
unpackedLen = ZipUtils::ccInflateCCZBuffer(data, dataLen, &unpackedData);
unpackedLen = ZipUtils::inflateCCZBuffer(data, dataLen, &unpackedData);
}
else if (ZipUtils::ccIsGZipBuffer(data, dataLen))
else if (ZipUtils::isGZipBuffer(data, dataLen))
{
unpackedLen = ZipUtils::ccInflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData);
unpackedLen = ZipUtils::inflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData);
}
else
{
@ -602,7 +602,7 @@ bool Image::isWebp(const unsigned char * data, int dataLen)
bool Image::isPvr(const unsigned char * data, int dataLen)
{
if (dataLen < sizeof(PVRv2TexHeader) || dataLen < sizeof(PVRv3TexHeader))
if (static_cast<size_t>(dataLen) < sizeof(PVRv2TexHeader) || static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
{
return false;
}
@ -1283,7 +1283,7 @@ bool Image::initWithPVRv2Data(const unsigned char * data, int dataLen)
bool Image::initWithPVRv3Data(const unsigned char * data, int dataLen)
{
if (dataLen < sizeof(PVRv3TexHeader))
if (static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
{
return false;
}
@ -1737,12 +1737,12 @@ bool Image::initWithWebpData(const unsigned char * data, int dataLen)
_width = config.input.width;
_height = config.input.height;
int bufferSize = _width * _height * 4;
_data = new unsigned char[bufferSize];
_dataLen = _width * _height * 4;
_data = new unsigned char[_dataLen];
config.output.u.RGBA.rgba = static_cast<uint8_t*>(_data);
config.output.u.RGBA.stride = _width * 4;
config.output.u.RGBA.size = bufferSize;
config.output.u.RGBA.size = _dataLen;
config.output.is_external_memory = 1;
if (WebPDecode(static_cast<const uint8_t*>(data), dataLen, &config) != VP8_STATUS_OK)

View File

@ -121,7 +121,7 @@ bool SAXParser::parse(const char *pszFile)
{
ret = parse(pBuffer, size);
}
CC_SAFE_DELETE_ARRAY(pBuffer);
free(pBuffer);
return ret;
}

View File

@ -128,4 +128,8 @@ Application::Platform Application::getTargetPlatform()
return Platform::OS_ANDROID;
}
void Application::applicationScreenSizeChanged(int newWidth, int newHeight) {
}
NS_CC_END

View File

@ -50,6 +50,13 @@ public:
*/
virtual Platform getTargetPlatform();
/**
@brief This function will be called when the application screen size is changed.
@param new width
@param new height
*/
virtual void applicationScreenSizeChanged(int newWidth, int newHeight);
protected:
static Application * sm_pSharedApplication;
};

View File

@ -33,23 +33,16 @@ THE SOFTWARE.
#include <android/log.h>
#if CC_TEXTURE_ATLAS_USE_VAO
// <EGL/egl.h> exists since android 2.3
#include <EGL/egl.h>
PFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOESEXT = 0;
PFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOESEXT = 0;
PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOESEXT = 0;
#endif
void initExtensions() {
#if CC_TEXTURE_ATLAS_USE_VAO
glGenVertexArraysOESEXT = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress("glGenVertexArraysOES");
glBindVertexArrayOESEXT = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress("glBindVertexArrayOES");
glDeleteVertexArraysOESEXT = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress("glDeleteVertexArraysOES");
#endif
}
NS_CC_BEGIN

View File

@ -130,21 +130,21 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const
}
unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* pszMode, unsigned long * pSize)
unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* mode, long * size)
{
return doGetFileData(filename, pszMode, pSize, false);
return doGetFileData(filename, mode, size, false);
}
unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize)
unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, long * pSize)
{
return doGetFileData(filename, pszMode, pSize, true);
}
unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync)
unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* mode, long * size, bool forAsync)
{
unsigned char * pData = 0;
unsigned char * data = 0;
if ((! filename) || (! pszMode) || 0 == strlen(filename))
if ((! filename) || (! mode) || 0 == strlen(filename))
{
return 0;
}
@ -153,16 +153,6 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char*
if (fullPath[0] != '/')
{
// fullPathForFilename is not thread safe.
if (forAsync) {
LOGD("Async loading not supported. fullPathForFilename is not thread safe.");
return NULL;
}
string fullPath = fullPathForFilename(filename);
LOGD("full path = %s", fullPath.c_str());
string relativePath = string();
size_t position = fullPath.find("assets/");
@ -189,14 +179,14 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char*
return NULL;
}
off_t size = AAsset_getLength(asset);
off_t fileSize = AAsset_getLength(asset);
pData = new unsigned char[size];
data = (unsigned char*) malloc(fileSize);
int bytesread = AAsset_read(asset, (void*)pData, size);
if (pSize)
int bytesread = AAsset_read(asset, (void*)data, fileSize);
if (size)
{
*pSize = bytesread;
*size = bytesread;
}
AAsset_close(asset);
@ -207,32 +197,32 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char*
{
// read rrom other path than user set it
//CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename);
FILE *fp = fopen(fullPath.c_str(), pszMode);
FILE *fp = fopen(fullPath.c_str(), mode);
CC_BREAK_IF(!fp);
unsigned long size;
long fileSize;
fseek(fp,0,SEEK_END);
size = ftell(fp);
fileSize = ftell(fp);
fseek(fp,0,SEEK_SET);
pData = new unsigned char[size];
size = fread(pData,sizeof(unsigned char), size,fp);
data = (unsigned char*) malloc(fileSize);
fileSize = fread(data,sizeof(unsigned char), fileSize,fp);
fclose(fp);
if (pSize)
if (size)
{
*pSize = size;
*size = fileSize;
}
} while (0);
}
if (! pData)
if (! data)
{
std::string msg = "Get data from file(";
msg.append(filename).append(") failed!");
CCLOG("%s", msg.c_str());
}
return pData;
return data;
}
string FileUtilsAndroid::getWritablePath() const

View File

@ -55,7 +55,7 @@ public:
/* override funtions */
bool init();
virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize);
virtual unsigned char* getFileData(const char* filename, const char* mode, long * size);
virtual std::string getWritablePath() const;
virtual bool isFileExist(const std::string& strFilePath) const;
@ -64,10 +64,10 @@ public:
/** This function is android specific. It is used for TextureCache::addImageAsync().
Don't use it in your codes.
*/
unsigned char* getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize);
unsigned char* getFileDataForAsync(const char* filename, const char* mode, long * size);
private:
unsigned char* doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync);
unsigned char* doGetFileData(const char* filename, const char* mode, long * size, bool forAsync);
static AAssetManager* assetmanager;
};

View File

View File

@ -12,6 +12,7 @@
#include <android/configuration.h>
#include <pthread.h>
#include <chrono>
#include "CCDirector.h"
#include "CCApplication.h"
@ -69,6 +70,9 @@ struct engine {
struct saved_state state;
};
static bool isContentRectChanged = false;
static std::chrono::steady_clock::time_point timeRectChanged;
static struct engine engine;
static char* editboxText = NULL;
@ -127,7 +131,7 @@ static void cocos_init(cocos_dimensions d, struct android_app* app) {
cocos2d::GL::invalidateStateCache();
cocos2d::ShaderCache::getInstance()->reloadDefaultShaders();
cocos2d::DrawPrimitives::init();
cocos2d::TextureCache::reloadAllTextures();
cocos2d::VolatileTextureMgr::reloadAllTextures();
cocos2d::NotificationCenter::getInstance()->postNotification(EVNET_COME_TO_FOREGROUND, NULL);
cocos2d::Director::getInstance()->setGLDefaultValues();
}
@ -558,6 +562,11 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
}
}
static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) {
timeRectChanged = std::chrono::steady_clock::now();
isContentRectChanged = true;
}
/**
* This is the main entry point of a native application that is using
* android_native_app_glue. It runs in its own thread, with its own
@ -586,6 +595,9 @@ void android_main(struct android_app* state) {
engine.state = *(struct saved_state*)state->savedState;
}
// Screen size change support
state->activity->callbacks->onContentRectChanged = onContentRectChanged;
// loop waiting for stuff to do.
while (1) {
@ -673,5 +685,20 @@ void android_main(struct android_app* state) {
} else {
LOG_RENDER_DEBUG("android_main : !engine.animating");
}
// Check if screen size changed
if (isContentRectChanged) {
std::chrono::duration<int, std::milli> duration(
std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(std::chrono::steady_clock::now() - timeRectChanged));
// Wait about 30 ms to get new width and height. Without waiting we can get old values sometime
if (duration.count() > 30) {
isContentRectChanged = false;
int32_t newWidth = ANativeWindow_getWidth(engine.app->window);
int32_t newHeight = ANativeWindow_getHeight(engine.app->window);
cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight);
}
}
}
}

View File

@ -76,6 +76,13 @@ public:
*/
virtual Platform getTargetPlatform();
/**
@brief This function will be called when the application screen size is changed.
@param new width
@param new height
*/
virtual void applicationScreenSizeChanged(int newWidth, int newHeight);
protected:
static Application * sm_pSharedApplication;
};

View File

@ -146,4 +146,8 @@ Application::Platform Application::getTargetPlatform()
}
}
void Application::applicationScreenSizeChanged(int newWidth, int newHeight) {
}
NS_CC_END

View File

@ -37,8 +37,10 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher;
- (id) init
{
_acceleration = new cocos2d::Acceleration();
_motionManager = [[CMMotionManager alloc] init];
if( (self = [super init]) ) {
_acceleration = new cocos2d::Acceleration();
_motionManager = [[CMMotionManager alloc] init];
}
return self;
}

0
cocos/2d/platform/ios/EAGLView.h Executable file → Normal file
View File

View File

@ -237,8 +237,11 @@ static CCEAGLView *__view = 0;
context_ = [renderer_ context];
//discardFramebufferSupported_ = [[Configuration sharedConfiguration] supportsDiscardFramebuffer];
#if GL_EXT_discard_framebuffer == 1
discardFramebufferSupported_ = YES;
#else
discardFramebufferSupported_ = NO;
#endif
CHECK_GL_ERROR();
@ -288,7 +291,7 @@ static CCEAGLView *__view = 0;
glResolveMultisampleFramebufferAPPLE();
}
if( discardFramebufferSupported_)
if(discardFramebufferSupported_)
{
if (multiSampling_)
{

0
cocos/2d/platform/ios/OpenGL_Internal.h Executable file → Normal file
View File

View File

@ -24,6 +24,7 @@ int Device::getDPI()
((double) DisplayWidthMM(dpy,scr)));
dpi = (int) (xres + 0.5);
//printf("dpi = %d\n", dpi);
XCloseDisplay (dpy);
}
return dpi;
}

View File

@ -284,8 +284,8 @@ EGLView* EGLView::s_pEglView = nullptr;
EGLView::EGLView()
: _captured(false)
, _frameZoomFactor(1.0f)
, _supportTouch(false)
, _frameZoomFactor(1.0f)
, _mainWindow(nullptr)
{
CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n");

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