This commit is contained in:
pandamicro 2015-07-15 14:26:19 +08:00
commit 3c08b497ba
266 changed files with 6086 additions and 4132 deletions

1
.gitignore vendored
View File

@ -146,3 +146,4 @@ tests/cpp-tests/Resources/audio
/*/*/prebuilt-mk/Android.mk
/*/*/*/prebuilt-mk/Android.mk
/*/*/*/*/prebuilt-mk/Android.mk
*.xcscmblueprint

View File

@ -883,6 +883,10 @@
688669711AE8E8B500C2CFD9 /* SpritePolygonTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6886696F1AE8E8B500C2CFD9 /* SpritePolygonTest.cpp */; };
688669721AE8E8B500C2CFD9 /* SpritePolygonTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6886696F1AE8E8B500C2CFD9 /* SpritePolygonTest.cpp */; };
826294431AAF071500CB7CF7 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 826294421AAF071500CB7CF7 /* Security.framework */; };
94D793D91B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */; };
94D793DA1B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */; };
94D793DB1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */; };
94D793DC1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */; };
A05FCACA177C124500BE600E /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C64822165F391E007D4F18 /* Cocoa.framework */; };
A07A521E1783A1D20073F6A7 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C6482E165F399D007D4F18 /* libz.dylib */; };
A07A521F1783A1D20073F6A7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C64832165F3AFD007D4F18 /* Foundation.framework */; };
@ -1945,6 +1949,10 @@
70A7F72D191D3E4900F0F206 /* shaderTest.psh.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = shaderTest.psh.h; sourceTree = "<group>"; };
70A7F730191D421B00F0F206 /* ShaderTest.vsh.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ShaderTest.vsh.h; sourceTree = "<group>"; };
826294421AAF071500CB7CF7 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "Bug-CCDrawNode.cpp"; sourceTree = "<group>"; };
94D793D61B4B7A3600F60F10 /* Bug-CCDrawNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bug-CCDrawNode.h"; sourceTree = "<group>"; };
94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "Bug-PageViewLayout.cpp"; sourceTree = "<group>"; };
94D793D81B4B7A3600F60F10 /* Bug-PageViewLayout.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bug-PageViewLayout.h"; sourceTree = "<group>"; };
A035A71117822E9E00987F6C /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; };
A07A52291783A1D20073F6A7 /* cpp-tests iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "cpp-tests iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
A07A52B71783AE6D0073F6A7 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; };
@ -2733,6 +2741,10 @@
1AC3597618CECF0B00F37B72 /* BugsTest */ = {
isa = PBXGroup;
children = (
94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */,
94D793D61B4B7A3600F60F10 /* Bug-CCDrawNode.h */,
94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */,
94D793D81B4B7A3600F60F10 /* Bug-PageViewLayout.h */,
1AC3597718CECF0B00F37B72 /* Bug-1159.cpp */,
1AC3597818CECF0B00F37B72 /* Bug-1159.h */,
1AC3597918CECF0B00F37B72 /* Bug-1174.cpp */,
@ -5388,6 +5400,7 @@
1AC35BEB18CECF0C00F37B72 /* CCControlSliderTest.cpp in Sources */,
1AC35C4D18CECF0C00F37B72 /* SpineTest.cpp in Sources */,
3E92EA821921A1400094CD21 /* Sprite3DTest.cpp in Sources */,
94D793DB1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */,
1AC35C1D18CECF0C00F37B72 /* NewRendererTest.cpp in Sources */,
1AC35B6718CECF0C00F37B72 /* AnimationsTestLayer.cpp in Sources */,
29080DB7191B595E0066F8DF /* UIListViewTest_Editor.cpp in Sources */,
@ -5533,6 +5546,7 @@
1AC35B2518CECF0C00F37B72 /* ActionsProgressTest.cpp in Sources */,
1AC35B6518CECF0C00F37B72 /* EffectsTest.cpp in Sources */,
1AC35B7118CECF0C00F37B72 /* TestHeaderLayer.cpp in Sources */,
94D793D91B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */,
29080D93191B595E0066F8DF /* CustomImageTest.cpp in Sources */,
1AC35B2118CECF0C00F37B72 /* ActionManagerTest.cpp in Sources */,
1AC35C3D18CECF0C00F37B72 /* PhysicsTest.cpp in Sources */,
@ -5673,6 +5687,7 @@
1AC35B2818CECF0C00F37B72 /* ActionsTest.cpp in Sources */,
1AC35C4A18CECF0C00F37B72 /* ShaderTest.cpp in Sources */,
B609E67419C18DAD003D0074 /* BillBoardTest.cpp in Sources */,
94D793DC1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */,
C04F935B1941B05400E9FEAB /* TileMapTest2.cpp in Sources */,
1AC35B4418CECF0C00F37B72 /* Bug-624.cpp in Sources */,
1AC35BF818CECF0C00F37B72 /* SocketIOTest.cpp in Sources */,
@ -5781,6 +5796,7 @@
1AC35BEA18CECF0C00F37B72 /* CCControlSceneManager.cpp in Sources */,
182C5CBB1A95B30500C30D34 /* CocosStudio3DTest.cpp in Sources */,
1AC35B7418CECF0C00F37B72 /* TimelineCallbackTestLayer.cpp in Sources */,
94D793DA1B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */,
29080D9E191B595E0066F8DF /* CustomParticleWidgetReader.cpp in Sources */,
1AC35BFC18CECF0C00F37B72 /* NotificationCenterTest.cpp in Sources */,
29FBBBFF196A9ECD00E65826 /* CocostudioParserJsonTest.cpp in Sources */,

View File

@ -40,6 +40,7 @@ Action::Action()
:_originalTarget(nullptr)
,_target(nullptr)
,_tag(Action::INVALID_TAG)
,_flags(0)
{
}

View File

@ -143,6 +143,16 @@ public:
* @param tag Used to identify the action easily.
*/
inline void setTag(int tag) { _tag = tag; }
/** Returns a flag field that is used to group the actions easily.
*
* @return A tag.
*/
inline unsigned int getFlags() const { return _flags; }
/** Changes the flag field that is used to group the actions easily.
*
* @param tag Used to identify the action easily.
*/
inline void setFlags(unsigned int flags) { _flags = flags; }
CC_CONSTRUCTOR_ACCESS:
Action();
@ -159,6 +169,8 @@ protected:
Node *_target;
/** The action tag. An identifier of the action. */
int _tag;
/** The action flag field. To categorize action into certain groups.*/
unsigned int _flags;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Action);

View File

@ -46,7 +46,7 @@ NS_CC_BEGIN
bool ActionEase::initWithAction(ActionInterval *action)
{
CCASSERT(action != nullptr, "");
CCASSERT(action != nullptr, "action couldn't be nullptr!");
if (ActionInterval::initWithDuration(action->getDuration()))
{

View File

@ -57,13 +57,13 @@ void GridAction::startWithTarget(Node *target)
if (targetGrid && targetGrid->getReuseGrid() > 0)
{
if (targetGrid->isActive() && targetGrid->getGridSize().width == _gridSize.width
&& targetGrid->getGridSize().height == _gridSize.height /*&& dynamic_cast<GridBase*>(targetGrid) != nullptr*/)
&& targetGrid->getGridSize().height == _gridSize.height)
{
targetGrid->reuse();
}
else
{
CCASSERT(0, "");
CCASSERT(0, "Invalid grid parameters!");
}
}
else
@ -93,7 +93,7 @@ GridAction* GridAction::reverse() const
GridBase* GridAction::getGrid()
{
// Abstract class needs implementation
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement this method!");
return nullptr;
}

View File

@ -134,13 +134,13 @@ void ActionInterval::setAmplitudeRate(float amp)
{
CC_UNUSED_PARAM(amp);
// Abstract class needs implementation
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement this method!");
}
float ActionInterval::getAmplitudeRate()
{
// Abstract class needs implementation
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement this method!");
return 0;
}
@ -248,8 +248,8 @@ Sequence* Sequence::create(const Vector<FiniteTimeAction*>& arrayOfActions)
bool Sequence::initWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo)
{
CCASSERT(actionOne != nullptr, "");
CCASSERT(actionTwo != nullptr, "");
CCASSERT(actionOne != nullptr, "actionOne can't be nullptr!");
CCASSERT(actionTwo != nullptr, "actionTwo can't be nullptr!");
float d = actionOne->getDuration() + actionTwo->getDuration();
ActionInterval::initWithDuration(d);
@ -504,7 +504,7 @@ RepeatForever *RepeatForever::create(ActionInterval *action)
bool RepeatForever::initWithAction(ActionInterval *action)
{
CCASSERT(action != nullptr, "");
CCASSERT(action != nullptr, "action can't be nullptr!");
action->retain();
_innerAction = action;
return true;
@ -645,8 +645,8 @@ Spawn* Spawn::createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *
bool Spawn::initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2)
{
CCASSERT(action1 != nullptr, "");
CCASSERT(action2 != nullptr, "");
CCASSERT(action1 != nullptr, "action1 can't be nullptr!");
CCASSERT(action2 != nullptr, "action2 can't be nullptr!");
bool ret = false;
@ -2189,8 +2189,8 @@ ReverseTime* ReverseTime::create(FiniteTimeAction *action)
bool ReverseTime::initWithAction(FiniteTimeAction *action)
{
CCASSERT(action != nullptr, "");
CCASSERT(action != _other, "");
CCASSERT(action != nullptr, "action can't be nullptr!");
CCASSERT(action != _other, "action doesn't equal to _other!");
if (ActionInterval::initWithDuration(action->getDuration()))
{
@ -2270,6 +2270,7 @@ Animate::Animate()
, _executedLoops(0)
, _animation(nullptr)
, _frameDisplayedEvent(nullptr)
, _currFrameIndex(0)
{
}
@ -2383,7 +2384,8 @@ void Animate::update(float t)
float splitTime = _splitTimes->at(i);
if( splitTime <= t ) {
AnimationFrame* frame = frames.at(i);
_currFrameIndex = i;
AnimationFrame* frame = frames.at(_currFrameIndex);
frameToDisplay = frame->getSpriteFrame();
static_cast<Sprite*>(_target)->setSpriteFrame(frameToDisplay);

View File

@ -1439,6 +1439,11 @@ public:
Animation* getAnimation() { return _animation; }
const Animation* getAnimation() const { return _animation; }
/**
* Gets the index of sprite frame currently displayed.
* @return int the index of sprite frame currently displayed.
*/
int getCurrentFrameIndex() { return _currFrameIndex; }
//
// Overrides
//
@ -1462,6 +1467,7 @@ protected:
std::vector<float>* _splitTimes;
int _nextFrame;
SpriteFrame* _origFrame;
int _currFrameIndex;
unsigned int _executedLoops;
Animation* _animation;

View File

@ -168,8 +168,8 @@ void ActionManager::resumeTargets(const Vector<Node*>& targetsToResume)
void ActionManager::addAction(Action *action, Node *target, bool paused)
{
CCASSERT(action != nullptr, "");
CCASSERT(target != nullptr, "");
CCASSERT(action != nullptr, "action can't be nullptr!");
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
// we should convert it to Ref*, because we save it as Ref*
@ -186,7 +186,7 @@ void ActionManager::addAction(Action *action, Node *target, bool paused)
actionAllocWithHashElement(element);
CCASSERT(! ccArrayContainsObject(element->actions, action), "");
CCASSERT(! ccArrayContainsObject(element->actions, action), "action already be added!");
ccArrayAppendObject(element->actions, action);
action->startWithTarget(target);
@ -265,8 +265,8 @@ void ActionManager::removeAction(Action *action)
void ActionManager::removeActionByTag(int tag, Node *target)
{
CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(target != nullptr, "");
CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!");
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);
@ -289,8 +289,8 @@ void ActionManager::removeActionByTag(int tag, Node *target)
void ActionManager::removeAllActionsByTag(int tag, Node *target)
{
CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(target != nullptr, "");
CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!");
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);
@ -315,13 +315,44 @@ void ActionManager::removeAllActionsByTag(int tag, Node *target)
}
}
void ActionManager::removeActionsByFlags(unsigned int flags, Node *target)
{
if (flags == 0)
{
return;
}
CCASSERT(target != nullptr, "target can't be nullptr!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);
if (element)
{
auto limit = element->actions->num;
for (int i = 0; i < limit;)
{
Action *action = (Action*)element->actions->arr[i];
if ((action->getFlags() & flags) != 0 && action->getOriginalTarget() == target)
{
removeActionAtIndex(i, element);
--limit;
}
else
{
++i;
}
}
}
}
// get
// FIXME: 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
Action* ActionManager::getActionByTag(int tag, const Node *target) const
{
CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!");
tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element);

View File

@ -114,6 +114,14 @@ public:
*/
void removeAllActionsByTag(int tag, Node *target);
/** Removes all actions matching at least one bit in flags and the target.
*
* @param flags The flag field to match the actions' flags based on bitwise AND.
* @param target A certain target.
* @js NA
*/
void removeActionsByFlags(unsigned int flags, Node *target);
/** Gets an action given its tag an a target.
*
* @param tag The action's tag.

View File

@ -238,7 +238,7 @@ Vec2 Camera::project(const Vec3& src) const
Vec4 clipPos;
getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
CCASSERT(clipPos.w != 0.0f, "");
CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
float ndcX = clipPos.x / clipPos.w;
float ndcY = clipPos.y / clipPos.w;
@ -255,7 +255,7 @@ Vec2 Camera::projectGL(const Vec3& src) const
Vec4 clipPos;
getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
CCASSERT(clipPos.w != 0.0f, "");
CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
float ndcX = clipPos.x / clipPos.w;
float ndcY = clipPos.y / clipPos.w;

View File

@ -374,7 +374,9 @@ void DrawNode::onDrawGLLine(const Mat4 &transform, uint32_t flags)
auto glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR);
glProgram->use();
glProgram->setUniformsForBuiltins(transform);
GL::blendFunc(_blendFunc.src, _blendFunc.dst);
if (_dirtyGLLine)
{
glBindBuffer(GL_ARRAY_BUFFER, _vboGLLine);
@ -415,7 +417,9 @@ void DrawNode::onDrawGLPoint(const Mat4 &transform, uint32_t flags)
auto glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_COLOR_TEXASPOINTSIZE);
glProgram->use();
glProgram->setUniformsForBuiltins(transform);
GL::blendFunc(_blendFunc.src, _blendFunc.dst);
if (_dirtyGLPoint)
{
glBindBuffer(GL_ARRAY_BUFFER, _vboGLPoint);

View File

@ -204,7 +204,7 @@ bool FontAtlas::prepareLetterDefinitions(const std::u16string& utf16String)
if (bitmapHeight > _currLineHeight)
{
_currLineHeight = bitmapHeight + 1;
_currLineHeight = static_cast<int>(bitmapHeight) + 1;
}
if (_currentPageOrigX + tempDef.width > CacheTextureWidth)
{

View File

@ -137,9 +137,28 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize)
if (FT_New_Memory_Face(getFTLibrary(), s_cacheFontData[fontName].data.getBytes(), s_cacheFontData[fontName].data.getSize(), 0, &face ))
return false;
//we want to use unicode
if (FT_Select_Charmap(face, FT_ENCODING_UNICODE))
return false;
{
int foundIndex = -1;
for (int charmapIndex = 0; charmapIndex < face->num_charmaps; charmapIndex++)
{
if (face->charmaps[charmapIndex]->encoding != FT_ENCODING_NONE)
{
foundIndex = charmapIndex;
break;
}
}
if (foundIndex == -1)
{
return false;
}
if (FT_Select_Charmap(face, face->charmaps[foundIndex]->encoding))
{
return false;
}
}
// set the requested font size
int dpi = 72;

View File

@ -245,17 +245,17 @@ void GridBase::afterDraw(cocos2d::Node *target)
void GridBase::blit(void)
{
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement it.");
}
void GridBase::reuse(void)
{
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement it!");
}
void GridBase::calculateVertexPoints(void)
{
CCASSERT(0, "");
CCASSERT(0, "Subclass should implement it.");
}
// implementation of Grid3D

View File

@ -162,7 +162,7 @@ Label* Label::create(const std::string& text, const std::string& font, float fon
Label* Label::createWithSystemFont(const std::string& text, const std::string& font, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */)
{
auto ret = new (std::nothrow) Label(nullptr,hAlignment,vAlignment);
auto ret = new (std::nothrow) Label(hAlignment,vAlignment);
if (ret)
{
@ -182,7 +182,7 @@ Label* Label::createWithSystemFont(const std::string& text, const std::string& f
Label* Label::createWithTTF(const std::string& text, const std::string& fontFile, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */)
{
auto ret = new (std::nothrow) Label(nullptr,hAlignment,vAlignment);
auto ret = new (std::nothrow) Label(hAlignment,vAlignment);
if (ret && FileUtils::getInstance()->isFileExist(fontFile))
{
@ -202,9 +202,9 @@ Label* Label::createWithTTF(const std::string& text, const std::string& fontFile
return nullptr;
}
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */)
Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */)
{
auto ret = new (std::nothrow) Label(nullptr,alignment);
auto ret = new (std::nothrow) Label(hAlignment);
if (ret && FileUtils::getInstance()->isFileExist(ttfConfig.fontFilePath) && ret->setTTFConfig(ttfConfig))
{
@ -219,9 +219,9 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text,
return nullptr;
}
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */)
Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& hAlignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */)
{
auto ret = new (std::nothrow) Label(nullptr,alignment);
auto ret = new (std::nothrow) Label(hAlignment);
if (ret && ret->setBMFontFilePath(bmfontFilePath,imageOffset))
{
@ -326,36 +326,18 @@ bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHe
return true;
}
Label::Label(FontAtlas *atlas /* = nullptr */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
TextVAlignment vAlignment /* = TextVAlignment::TOP */,bool useDistanceField /* = false */,bool useA8Shader /* = false */)
: _isOpacityModifyRGB(false)
, _contentDirty(false)
, _fontAtlas(atlas)
, _textSprite(nullptr)
, _compatibleMode(false)
Label::Label(TextHAlignment hAlignment /* = TextHAlignment::LEFT */,
TextVAlignment vAlignment /* = TextVAlignment::TOP */)
: _textSprite(nullptr)
, _shadowNode(nullptr)
, _fontAtlas(nullptr)
, _reusedLetter(nullptr)
, _additionalKerning(0.0f)
, _commonLineHeight(0.0f)
, _lineBreakWithoutSpaces(false)
, _horizontalKernings(nullptr)
, _maxLineWidth(0.0f)
, _labelDimensions(Size::ZERO)
, _labelWidth(0.0f)
, _labelHeight(0.0f)
, _hAlignment(hAlignment)
, _vAlignment(vAlignment)
, _currNumLines(-1)
, _fontScale(1.0f)
, _useDistanceField(useDistanceField)
, _useA8Shader(useA8Shader)
, _effectColorF(Color4F::BLACK)
, _uniformEffectColor(0)
, _shadowDirty(false)
, _blendFunc(BlendFunc::ALPHA_PREMULTIPLIED)
, _insideBounds(true)
{
setAnchorPoint(Vec2::ANCHOR_MIDDLE);
reset();
_hAlignment = hAlignment;
_vAlignment = vAlignment;
_purgeTextureListener = EventListenerCustom::create(FontAtlas::CMD_PURGE_FONTATLAS, [this](EventCustom* event){
if (_fontAtlas && _currentLabelType == LabelType::TTF && event->getUserData() == _fontAtlas)
@ -394,27 +376,27 @@ Label::~Label()
if (_fontAtlas)
{
Node::removeAllChildrenWithCleanup(true);
CC_SAFE_RELEASE_NULL(_reusedLetter);
_batchNodes.clear();
FontAtlasCache::releaseFontAtlas(_fontAtlas);
}
_eventDispatcher->removeEventListener(_purgeTextureListener);
_eventDispatcher->removeEventListener(_resetTextureListener);
CC_SAFE_RELEASE_NULL(_reusedLetter);
CC_SAFE_RELEASE_NULL(_textSprite);
CC_SAFE_RELEASE_NULL(_shadowNode);
}
void Label::reset()
{
TTFConfig temp;
_fontConfig = temp;
_systemFontDirty = false;
_systemFont = "Helvetica";
_systemFontSize = 12;
CC_SAFE_RELEASE_NULL(_textSprite);
CC_SAFE_RELEASE_NULL(_shadowNode);
Node::removeAllChildrenWithCleanup(true);
CC_SAFE_RELEASE_NULL(_reusedLetter);
_letters.clear();
_batchNodes.clear();
_lettersInfo.clear();
if (_fontAtlas)
{
FontAtlasCache::releaseFontAtlas(_fontAtlas);
@ -423,21 +405,53 @@ void Label::reset()
_currentLabelType = LabelType::STRING_TEXTURE;
_currLabelEffect = LabelEffect::NORMAL;
_shadowBlurRadius = 0;
_contentDirty = false;
_currNumLines = 0;
_limitShowCount = 0;
_currentUTF16String.clear();
_originalUTF8String.clear();
Node::removeAllChildrenWithCleanup(true);
_textSprite = nullptr;
_shadowNode = nullptr;
TTFConfig temp;
_fontConfig = temp;
_outlineSize = 0.f;
_bmFontPath = "";
_systemFontDirty = false;
_systemFont = "Helvetica";
_systemFontSize = 12;
CC_SAFE_RELEASE_NULL(_reusedLetter);
if (_horizontalKernings)
{
delete[] _horizontalKernings;
_horizontalKernings = nullptr;
}
_additionalKerning = 0.f;
_commonLineHeight = 0.f;
_maxLineWidth = 0.f;
_labelDimensions.width = 0.f;
_labelDimensions.height = 0.f;
_labelWidth = 0.f;
_labelHeight = 0.f;
_lineBreakWithoutSpaces = false;
_hAlignment = TextHAlignment::LEFT;
_vAlignment = TextVAlignment::TOP;
_effectColorF = Color4F::BLACK;
_textColor = Color4B::WHITE;
_textColorF = Color4F::WHITE;
setColor(Color3B::WHITE);
_shadowDirty = false;
_shadowEnabled = false;
_shadowBlurRadius = 0.f;
_correctionScale = 1.f;
_useDistanceField = false;
_useA8Shader = false;
_clipEnabled = false;
_blendFuncDirty = false;
_blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_isOpacityModifyRGB = false;
_insideBounds = true;
}
void Label::updateShaderProgram()
@ -481,6 +495,7 @@ void Label::setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false *
if (_fontAtlas)
{
_batchNodes.clear();
FontAtlasCache::releaseFontAtlas(_fontAtlas);
_fontAtlas = nullptr;
}
@ -538,7 +553,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig)
updateShaderProgram();
if(ttfConfig.distanceFieldEnabled)
{
this->setFontScale(1.0f * ttfConfig.fontSize / DistanceFieldFontSize);
this->setCorrectionScale(1.0f * ttfConfig.fontSize / DistanceFieldFontSize);
}
}
@ -623,7 +638,7 @@ void Label::setScale(float scale)
{
if (_useDistanceField)
{
scale *= _fontScale;
scale *= _correctionScale;
}
Node::setScale(scale);
}
@ -632,7 +647,7 @@ void Label::setScaleX(float scaleX)
{
if (_useDistanceField)
{
scaleX *= _fontScale;
scaleX *= _correctionScale;
}
Node::setScaleX(scaleX);
}
@ -641,7 +656,7 @@ void Label::setScaleY(float scaleY)
{
if (_useDistanceField)
{
scaleY *= _fontScale;
scaleY *= _correctionScale;
}
Node::setScaleY(scaleY);
}
@ -650,7 +665,7 @@ float Label::getScaleY() const
{
if (_useDistanceField)
{
return _scaleY / _fontScale;
return _scaleY / _correctionScale;
}
else
{
@ -662,7 +677,7 @@ float Label::getScaleX() const
{
if (_useDistanceField)
{
return _scaleX / _fontScale;
return _scaleX / _correctionScale;
}
else
{
@ -781,19 +796,7 @@ void Label::updateQuads()
_reusedRect.size.width = letterDef.width;
_reusedRect.origin.x = letterDef.U;
_reusedRect.origin.y = letterDef.V;
if (_labelHeight > 0.f)
{
if (_lettersInfo[ctr].position.y > _contentSize.height)
{
auto clipTop = _lettersInfo[ctr].position.y - _contentSize.height;
_reusedRect.origin.y += clipTop;
_lettersInfo[ctr].position.y -= clipTop;
}
if (_lettersInfo[ctr].position.y - letterDef.height < 0.f)
{
_reusedRect.size.height = _lettersInfo[ctr].position.y < 0.f ? 0.f : _lettersInfo[ctr].position.y;
}
}
_reusedLetter->setTextureRect(_reusedRect,false,_reusedRect.size);
_reusedLetter->setPosition(_lettersInfo[ctr].position);
@ -848,11 +851,10 @@ void Label::enableGlow(const Color4B& glowColor)
_contentDirty = true;
}
_currLabelEffect = LabelEffect::GLOW;
_effectColor = glowColor;
_effectColorF.r = _effectColor.r / 255.0f;
_effectColorF.g = _effectColor.g / 255.0f;
_effectColorF.b = _effectColor.b / 255.0f;
_effectColorF.a = _effectColor.a / 255.0f;
_effectColorF.r = glowColor.r / 255.0f;
_effectColorF.g = glowColor.g / 255.0f;
_effectColorF.b = glowColor.b / 255.0f;
_effectColorF.a = glowColor.a / 255.0f;
updateShaderProgram();
}
}
@ -876,9 +878,12 @@ void Label::enableOutline(const Color4B& outlineColor,int outlineSize /* = -1 */
setTTFConfig(_fontConfig);
}
}
else if (_effectColor != outlineColor || _outlineSize != outlineSize)
else if (_effectColorF != outlineColor || _outlineSize != outlineSize)
{
_effectColor = outlineColor;
_effectColorF.r = outlineColor.r / 255.f;
_effectColorF.g = outlineColor.g / 255.f;
_effectColorF.b = outlineColor.b / 255.f;
_effectColorF.a = outlineColor.a / 255.f;
_outlineSize = outlineSize;
_currLabelEffect = LabelEffect::OUTLINE;
_contentDirty = true;
@ -895,7 +900,6 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const
_shadowOffset.width = offset.width * contentScaleFactor;
_shadowOffset.height = offset.height * contentScaleFactor;
//TODO: support blur for shadow
_shadowBlurRadius = 0;
_shadowColor3B.r = shadowColor.r;
_shadowColor3B.g = shadowColor.g;
@ -904,13 +908,14 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const
if (!_systemFontDirty && !_contentDirty && _textSprite)
{
auto fontDef = _getFontDefinition();
if (_shadowNode)
{
if (shadowColor != _shadowColor4F)
{
_shadowNode->release();
_shadowNode = nullptr;
createShadowSpriteForSystemFont();
createShadowSpriteForSystemFont(fontDef);
}
else
{
@ -919,7 +924,7 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const
}
else
{
createShadowSpriteForSystemFont();
createShadowSpriteForSystemFont(fontDef);
}
}
@ -981,59 +986,18 @@ void Label::disableEffect(LabelEffect effect)
}
}
void Label::setFontScale(float fontScale)
void Label::setCorrectionScale(float correctionScale)
{
_fontScale = fontScale * CC_CONTENT_SCALE_FACTOR();
Node::setScale(_fontScale);
_correctionScale = correctionScale * CC_CONTENT_SCALE_FACTOR();
Node::setScale(_correctionScale);
}
void Label::createSpriteForSystemFont()
void Label::createSpriteForSystemFont(const FontDefinition& fontDef)
{
_currentLabelType = LabelType::STRING_TEXTURE;
if (!_compatibleMode)
{
_fontDefinition._fontName = _systemFont;
_fontDefinition._fontSize = _systemFontSize;
_fontDefinition._alignment = _hAlignment;
_fontDefinition._vertAlignment = _vAlignment;
_fontDefinition._dimensions.width = _labelWidth;
_fontDefinition._dimensions.height = _labelHeight;
_fontDefinition._fontFillColor.r = _textColor.r;
_fontDefinition._fontFillColor.g = _textColor.g;
_fontDefinition._fontFillColor.b = _textColor.b;
_fontDefinition._fontAlpha = _textColor.a;
_fontDefinition._shadow._shadowEnabled = false;
if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0)
{
_fontDefinition._stroke._strokeEnabled = true;
_fontDefinition._stroke._strokeSize = _outlineSize;
_fontDefinition._stroke._strokeColor.r = _effectColor.r;
_fontDefinition._stroke._strokeColor.g = _effectColor.g;
_fontDefinition._stroke._strokeColor.b = _effectColor.b;
_fontDefinition._stroke._strokeAlpha = _effectColor.a;
}
else
{
_fontDefinition._stroke._strokeEnabled = false;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (_fontDefinition._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
_fontDefinition._stroke._strokeEnabled = false;
#endif
}
auto texture = new (std::nothrow) Texture2D;
texture->initWithString(_originalUTF8String.c_str(), _fontDefinition);
texture->initWithString(_originalUTF8String.c_str(), fontDef);
_textSprite = Sprite::createWithTexture(texture);
//set camera mask using label's camera mask, because _textSprite may be null when setting camera mask to label
@ -1051,16 +1015,16 @@ void Label::createSpriteForSystemFont()
_textSprite->updateDisplayedOpacity(_displayedOpacity);
}
void Label::createShadowSpriteForSystemFont()
void Label::createShadowSpriteForSystemFont(const FontDefinition& fontDef)
{
if (!_fontDefinition._stroke._strokeEnabled && _fontDefinition._fontFillColor == _shadowColor3B
&& (_fontDefinition._fontAlpha == _shadowOpacity))
if (!fontDef._stroke._strokeEnabled && fontDef._fontFillColor == _shadowColor3B
&& (fontDef._fontAlpha == _shadowOpacity))
{
_shadowNode = Sprite::createWithTexture(_textSprite->getTexture());
}
else
{
auto shadowFontDefinition = _fontDefinition;
FontDefinition shadowFontDefinition = fontDef;
shadowFontDefinition._fontFillColor.r = _shadowColor3B.r;
shadowFontDefinition._fontFillColor.g = _shadowColor3B.g;
shadowFontDefinition._fontFillColor.b = _shadowColor3B.b;
@ -1107,20 +1071,35 @@ void Label::setCameraMask(unsigned short mask, bool applyChildren)
void Label::setFontDefinition(const FontDefinition& textDefinition)
{
_fontDefinition = textDefinition;
_systemFont = textDefinition._fontName;
_systemFontSize = textDefinition._fontSize;
_hAlignment = textDefinition._alignment;
_vAlignment = textDefinition._vertAlignment;
setDimensions(textDefinition._dimensions.width, textDefinition._dimensions.height);
Color4B textColor = Color4B(textDefinition._fontFillColor);
textColor.a = textDefinition._fontAlpha;
setTextColor(textColor);
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (_fontDefinition._stroke._strokeEnabled)
if (textDefinition._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
_fontDefinition._stroke._strokeEnabled = false;
#endif
if (_fontDefinition._shadow._shadowEnabled)
_outlineSize = 0.f;
#else
if (textDefinition._stroke._strokeEnabled && textDefinition._stroke._strokeSize > 0.f)
{
_fontDefinition._shadow._shadowEnabled = false;
enableShadow(Color4B(0,0,0,255 * _fontDefinition._shadow._shadowOpacity),_fontDefinition._shadow._shadowOffset,_fontDefinition._shadow._shadowBlur);
Color4B outlineColor = Color4B(textDefinition._stroke._strokeColor);
outlineColor.a = textDefinition._stroke._strokeAlpha;
enableOutline(outlineColor, textDefinition._stroke._strokeSize);
}
#endif
if (textDefinition._shadow._shadowEnabled)
{
enableShadow(Color4B(0, 0, 0, 255 * textDefinition._shadow._shadowOpacity),
textDefinition._shadow._shadowOffset, textDefinition._shadow._shadowBlur);
}
_compatibleMode = true;
}
void Label::updateContent()
@ -1155,10 +1134,11 @@ void Label::updateContent()
}
else
{
createSpriteForSystemFont();
auto fontDef = _getFontDefinition();
createSpriteForSystemFont(fontDef);
if (_shadowEnabled)
{
createShadowSpriteForSystemFont();
createShadowSpriteForSystemFont(fontDef);
}
}
_contentDirty = false;
@ -1296,8 +1276,7 @@ void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t pare
uint32_t flags = processParentFlags(parentTransform, parentFlags);
if (!_originalUTF8String.empty() && _shadowEnabled && _shadowBlurRadius <= 0
&& (_shadowDirty || (flags & FLAGS_DIRTY_MASK)))
if (!_originalUTF8String.empty() && _shadowEnabled && (_shadowDirty || (flags & FLAGS_DIRTY_MASK)))
{
_position.x += _shadowOffset.width;
_position.y += _shadowOffset.height;
@ -1525,11 +1504,6 @@ int Label::getStringLength() const
}
// RGBA protocol
bool Label::isOpacityModifyRGB() const
{
return _isOpacityModifyRGB;
}
void Label::setOpacityModifyRGB(bool isOpacityModifyRGB)
{
if (isOpacityModifyRGB != _isOpacityModifyRGB)
@ -1571,20 +1545,16 @@ void Label::setTextColor(const Color4B &color)
{
CCASSERT(_currentLabelType == LabelType::TTF || _currentLabelType == LabelType::STRING_TEXTURE, "Only supported system font and ttf!");
if (_currentLabelType == LabelType::STRING_TEXTURE && _textColor != color)
{
_contentDirty = true;
}
_textColor = color;
_textColorF.r = _textColor.r / 255.0f;
_textColorF.g = _textColor.g / 255.0f;
_textColorF.b = _textColor.b / 255.0f;
_textColorF.a = _textColor.a / 255.0f;
if (_currentLabelType == LabelType::STRING_TEXTURE)
{
if (_fontDefinition._fontFillColor.r != _textColor.r || _fontDefinition._fontFillColor.g != _textColor.g
|| _fontDefinition._fontFillColor.b != _textColor.b || _fontDefinition._fontAlpha != _textColor.a)
{
_contentDirty = true;
}
}
}
void Label::updateColor()
@ -1679,4 +1649,44 @@ void Label::removeChild(Node* child, bool cleanup /* = true */)
}
}
FontDefinition Label::_getFontDefinition() const
{
FontDefinition systemFontDef;
systemFontDef._fontName = _systemFont;
systemFontDef._fontSize = _systemFontSize;
systemFontDef._alignment = _hAlignment;
systemFontDef._vertAlignment = _vAlignment;
systemFontDef._dimensions.width = _labelWidth;
systemFontDef._dimensions.height = _labelHeight;
systemFontDef._fontFillColor.r = _textColor.r;
systemFontDef._fontFillColor.g = _textColor.g;
systemFontDef._fontFillColor.b = _textColor.b;
systemFontDef._fontAlpha = _textColor.a;
systemFontDef._shadow._shadowEnabled = false;
if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0.f)
{
systemFontDef._stroke._strokeEnabled = true;
systemFontDef._stroke._strokeSize = _outlineSize;
systemFontDef._stroke._strokeColor.r = _effectColorF.r * 255;
systemFontDef._stroke._strokeColor.g = _effectColorF.g * 255;
systemFontDef._stroke._strokeColor.b = _effectColorF.b * 255;
systemFontDef._stroke._strokeAlpha = _effectColorF.a * 255;
}
else
{
systemFontDef._stroke._strokeEnabled = false;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (systemFontDef._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
systemFontDef._stroke._strokeEnabled = false;
#endif
return systemFontDef;
}
NS_CC_END

View File

@ -162,7 +162,8 @@ public:
* @return An automatically released Label object.
* @see TTFConfig setTTFConfig setMaxLineWidth
*/
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0);
static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text,
TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0);
/**
* Allocates and initializes a Label, with a bitmap font file.
@ -441,7 +442,7 @@ public:
virtual const BlendFunc& getBlendFunc() const override { return _blendFunc; }
virtual void setBlendFunc(const BlendFunc &blendFunc) override;
virtual bool isOpacityModifyRGB() const override;
virtual bool isOpacityModifyRGB() const override { return _isOpacityModifyRGB; }
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB) override;
virtual void updateDisplayedColor(const Color3B& parentColor) override;
virtual void updateDisplayedOpacity(GLubyte parentOpacity) override;
@ -455,7 +456,6 @@ public:
virtual std::string getDescription() const override;
virtual const Size& getContentSize() const override;
virtual Rect getBoundingBox() const override;
virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
@ -469,13 +469,8 @@ public:
CC_DEPRECATED_ATTRIBUTE static Label* create(const std::string& text, const std::string& font, float fontSize,
const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP);
CC_DEPRECATED_ATTRIBUTE virtual void setFontDefinition(const FontDefinition& textDefinition);
CC_DEPRECATED_ATTRIBUTE const FontDefinition& getFontDefinition() const { return _fontDefinition; }
/**
* @deprecated Use `getLineHeight` instead.
*/
CC_DEPRECATED_ATTRIBUTE FontDefinition getFontDefinition() const { return _getFontDefinition(); }
CC_DEPRECATED_ATTRIBUTE int getCommonLineHeight() const { return (int)getLineHeight();}
CC_CONSTRUCTOR_ACCESS:
@ -483,8 +478,8 @@ CC_CONSTRUCTOR_ACCESS:
* Constructor of Label.
* @js NA
*/
Label(FontAtlas *atlas = nullptr, TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP,bool useDistanceField = false,bool useA8Shader = false);
Label(TextHAlignment hAlignment = TextHAlignment::LEFT,
TextVAlignment vAlignment = TextVAlignment::TOP);
/**
* Destructor of Label.
@ -494,132 +489,124 @@ CC_CONSTRUCTOR_ACCESS:
virtual ~Label();
protected:
void onDraw(const Mat4& transform, bool transformUpdated);
void onDrawShadow(GLProgram* glProgram);
struct LetterInfo
{
FontLetterDefinition def;
Vec2 position;
Size contentSize;
int atlasIndex;
};
enum class LabelType {
enum class LabelType {
TTF,
BMFONT,
CHARMAP,
STRING_TEXTURE
};
virtual void setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false);
virtual void setFontAtlas(FontAtlas* atlas, bool distanceFieldEnabled = false, bool useA8Shader = false);
bool recordLetterInfo(const cocos2d::Vec2& point,const FontLetterDefinition& letterDef, int spriteIndex);
bool recordPlaceholderInfo(int spriteIndex);
void setFontScale(float fontScale);
virtual void alignText();
bool computeHorizontalKernings(const std::u16string& stringToRender);
void setCorrectionScale(float fontScale);
void computeStringNumLines();
void onDraw(const Mat4& transform, bool transformUpdated);
void onDrawShadow(GLProgram* glProgram);
void drawSelf(Renderer* renderer, uint32_t flags);
virtual void alignText();
bool computeHorizontalKernings(const std::u16string& stringToRender);
bool recordLetterInfo(const cocos2d::Vec2& point,const FontLetterDefinition& letterDef, int spriteIndex);
bool recordPlaceholderInfo(int spriteIndex);
void updateQuads();
virtual void updateColor() override;
void createSpriteForSystemFont(const FontDefinition& fontDef);
void createShadowSpriteForSystemFont(const FontDefinition& fontDef);
virtual void updateShaderProgram();
void createSpriteForSystemFont();
void createShadowSpriteForSystemFont();
void reset();
void drawSelf(Renderer* renderer, uint32_t flags);
FontDefinition _getFontDefinition() const;
virtual void updateColor() override;
LabelType _currentLabelType;
bool _contentDirty;
std::u16string _currentUTF16String;
std::string _originalUTF8String;
int _currNumLines;
std::string _bmFontPath;
bool _isOpacityModifyRGB;
bool _contentDirty;
TTFConfig _fontConfig;
float _outlineSize;
bool _systemFontDirty;
std::string _systemFont;
float _systemFontSize;
LabelType _currentLabelType;
Vector<SpriteBatchNode*> _batchNodes;
FontAtlas * _fontAtlas;
std::vector<LetterInfo> _lettersInfo;
EventListenerCustom* _purgeTextureListener;
EventListenerCustom* _resetTextureListener;
TTFConfig _fontConfig;
//compatibility with older LabelTTF
float _systemFontSize;
Sprite* _textSprite;
FontDefinition _fontDefinition;
bool _compatibleMode;
Sprite* _shadowNode;
FontAtlas* _fontAtlas;
Vector<SpriteBatchNode*> _batchNodes;
std::vector<LetterInfo> _lettersInfo;
//! used for optimization
Sprite *_reusedLetter;
Rect _reusedRect;
int _limitShowCount;
float _additionalKerning;
//layout relevant properties.
float _commonLineHeight;
bool _lineBreakWithoutSpaces;
int * _horizontalKernings;
float _additionalKerning;
int* _horizontalKernings;
bool _lineBreakWithoutSpaces;
float _maxLineWidth;
Size _labelDimensions;
Size _labelDimensions;
float _labelWidth;
float _labelHeight;
TextHAlignment _hAlignment;
TextVAlignment _vAlignment;
int _currNumLines;
std::u16string _currentUTF16String;
std::string _originalUTF8String;
//the correction scale for distance field.
float _correctionScale;
float _fontScale;
LabelEffect _currLabelEffect;
Color4F _effectColorF;
Color4B _textColor;
Color4F _textColorF;
CustomCommand _customCommand;
Mat4 _shadowTransform;
GLuint _uniformEffectColor;
GLuint _uniformTextColor;
bool _useDistanceField;
bool _useA8Shader;
LabelEffect _currLabelEffect;
Color4B _effectColor;
Color4F _effectColorF;
GLuint _uniformEffectColor;
GLuint _uniformTextColor;
CustomCommand _customCommand;
bool _shadowDirty;
bool _shadowEnabled;
Size _shadowOffset;
int _shadowBlurRadius;
Mat4 _shadowTransform;
bool _shadowDirty;
bool _shadowEnabled;
Size _shadowOffset;
Color4F _shadowColor4F;
Color3B _shadowColor3B;
GLubyte _shadowOpacity;
Sprite* _shadowNode;
int _outlineSize;
Color4B _textColor;
Color4F _textColorF;
float _shadowBlurRadius;
bool _clipEnabled;
bool _blendFuncDirty;
BlendFunc _blendFunc;
/// whether or not the sprite was inside bounds the previous frame
/// whether or not the label was inside bounds the previous frame
bool _insideBounds;
bool _isOpacityModifyRGB;
std::unordered_map<int, Sprite*> _letters;
EventListenerCustom* _purgeTextureListener;
EventListenerCustom* _resetTextureListener;
private:
CC_DISALLOW_COPY_AND_ASSIGN(Label);

View File

@ -223,9 +223,11 @@ void LabelTTF::setTextDefinition(const FontDefinition& theDefinition)
_contentDirty = true;
}
const FontDefinition& LabelTTF::getTextDefinition() const
const FontDefinition& LabelTTF::getTextDefinition()
{
return _renderLabel->getFontDefinition();
auto fontDef = _renderLabel->getFontDefinition();
memcpy(&_fontDef, &fontDef, sizeof(FontDefinition));
return _fontDef;
}
void LabelTTF::setBlendFunc(const BlendFunc &blendFunc)

View File

@ -100,7 +100,7 @@ public:
void setTextDefinition(const FontDefinition& theDefinition);
/** get the text definition used by this label */
const FontDefinition& getTextDefinition() const;
const FontDefinition& getTextDefinition();
@ -163,6 +163,7 @@ public:
protected:
Label* _renderLabel;
bool _contentDirty;
FontDefinition _fontDef;
};

View File

@ -316,7 +316,7 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel)
auto labelHeightPixel = theLabel->_labelHeight * contentScaleFactor;
if (totalHeight > labelHeightPixel)
{
int numLines = MIN(ceil(labelHeightPixel / theLabel->_commonLineHeight), theLabel->_currNumLines);
int numLines = labelHeightPixel / theLabel->_commonLineHeight;
totalHeight = numLines * theLabel->_commonLineHeight;
}
switch (theLabel->_vAlignment)
@ -379,7 +379,7 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel)
nextFontPositionY -= theLabel->_commonLineHeight;
theLabel->recordPlaceholderInfo(i);
if(nextFontPositionY < 0.f)
if (nextFontPositionY < theLabel->_commonLineHeight)
break;
lineStart = true;

View File

@ -376,11 +376,11 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
int rowColumns = 0;
for(const auto &child : _children) {
CCASSERT(row < rows.size(), "");
CCASSERT(row < rows.size(), "row should less than rows.size()!");
rowColumns = rows[row].asInt();
// can not have zero columns on a row
CCASSERT(rowColumns, "");
CCASSERT(rowColumns, "rowColumns can't be 0.");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
@ -397,7 +397,7 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
}
// check if too many rows/columns for available menu items
CCASSERT(! columnsOccupied, "");
CCASSERT(! columnsOccupied, "columnsOccupied should be 0.");
Size winSize = Director::getInstance()->getWinSize();
@ -472,11 +472,11 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
for(const auto &child : _children) {
// check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
CCASSERT(column < columns.size(), "column should be less than columns.size().");
columnRows = columns[column].asInt();
// can't have zero rows on a column
CCASSERT(columnRows, "");
CCASSERT(columnRows, "columnRows can't be 0.");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
@ -499,7 +499,7 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
}
// check if too many rows/columns for available menu items.
CCASSERT(! rowsOccupied, "");
CCASSERT(! rowsOccupied, "rowsOccupied should be 0.");
Size winSize = Director::getInstance()->getWinSize();

View File

@ -1576,6 +1576,14 @@ void Node::stopAllActionsByTag(int tag)
_actionManager->removeAllActionsByTag(tag, this);
}
void Node::stopActionsByFlags(unsigned int flags)
{
if (flags > 0)
{
_actionManager->removeActionsByFlags(flags, this);
}
}
Action * Node::getActionByTag(int tag)
{
CCASSERT( tag != Action::INVALID_TAG, "Invalid tag");

View File

@ -1228,6 +1228,13 @@ public:
*/
void stopAllActionsByTag(int tag);
/**
* Removes all actions from the running action list by its flags.
*
* @param flags A flag field that removes actions based on bitwise AND.
*/
void stopActionsByFlags(unsigned int flags);
/**
* Gets an action from the running action list by its tag.
*

View File

@ -384,7 +384,7 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string&
else if( dictionary.find("textureImageData") != dictionary.end() )
{
std::string textureData = dictionary.at("textureImageData").asString();
CCASSERT(!textureData.empty(), "");
CCASSERT(!textureData.empty(), "textureData can't be empty!");
auto dataLen = textureData.size();
if (dataLen != 0)

View File

@ -205,7 +205,7 @@ bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName)
bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame)
{
CCASSERT(spriteFrame != nullptr, "");
CCASSERT(spriteFrame != nullptr, "spriteFrame can't be nullptr!");
bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect());
setSpriteFrame(spriteFrame);
@ -673,7 +673,7 @@ void Sprite::addChild(Node *child, int zOrder, int tag)
{
Sprite* childSprite = dynamic_cast<Sprite*>(child);
CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "childSprite's texture name should be equal to _textureAtlas's texture name!");
//put it in descendants array of batch node
_batchNode->appendChild(childSprite);
@ -694,7 +694,8 @@ void Sprite::addChild(Node *child, int zOrder, const std::string &name)
{
Sprite* childSprite = dynamic_cast<Sprite*>(child);
CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "");
CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(),
"childSprite's texture name should be equal to _textureAtlas's texture name.");
//put it in descendants array of batch node
_batchNode->appendChild(childSprite);

View File

@ -454,7 +454,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
// Y
int y = attributeDict["y"].asInt();
Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().x - attributeDict["height"].asInt());
Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().y - attributeDict["height"].asInt());
p = CC_POINT_PIXELS_TO_POINTS(p);
dict["x"] = Value(p.x);
dict["y"] = Value(p.y);
@ -643,7 +643,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name)
ssize_t sizeHint = s.width * s.height * sizeof(unsigned int);
ssize_t CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint);
CCASSERT(inflatedLen == sizeHint, "");
CCASSERT(inflatedLen == sizeHint, "inflatedLen should be equal to sizeHint!");
free(buffer);
buffer = nullptr;

View File

@ -216,73 +216,24 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeD
else
mtlPath = fullPath.substr(0, fullPath.find_last_of("\\/") + 1).c_str();
ObjLoader::shapes_t shapes;
auto ret = ObjLoader::LoadObj(shapes, fullPath.c_str(), mtlPath.c_str());
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str());
if (ret.empty())
{
//fill data
MeshData* meshdata = new (std::nothrow) MeshData();
MeshVertexAttrib attrib;
attrib.size = 3;
attrib.type = GL_FLOAT;
if (shapes.positions.size())
{
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
bool hasnormal = false, hastex = false;
if (shapes.normals.size())
{
hasnormal = true;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL;
attrib.attribSizeBytes = attrib.size * sizeof(float);;
meshdata->attribs.push_back(attrib);
}
if (shapes.texcoords.size())
{
hastex = true;
attrib.size = 2;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
auto vertexNum = shapes.positions.size() / 3;
for(unsigned int i = 0; i < vertexNum; i++)
{
meshdata->vertex.push_back(shapes.positions[i * 3]);
meshdata->vertex.push_back(shapes.positions[i * 3 + 1]);
meshdata->vertex.push_back(shapes.positions[i * 3 + 2]);
if (hasnormal)
{
meshdata->vertex.push_back(shapes.normals[i * 3]);
meshdata->vertex.push_back(shapes.normals[i * 3 + 1]);
meshdata->vertex.push_back(shapes.normals[i * 3 + 2]);
}
if (hastex)
{
meshdata->vertex.push_back(shapes.texcoords[i * 2]);
meshdata->vertex.push_back(shapes.texcoords[i * 2 + 1]);
}
}
meshdatas.meshDatas.push_back(meshdata);
//convert material
int i = 0;
char str[20];
std::string dir = "";
auto last = fullPath.rfind("/");
if (last != -1)
dir = fullPath.substr(0, last + 1);
for (const auto& it : shapes.shapes)
{
for (auto& material : materials) {
NMaterialData materialdata;
NTextureData tex;
tex.filename = it.material.diffuse_texname.empty() ? it.material.diffuse_texname : dir + it.material.diffuse_texname;
tex.filename = material.diffuse_texname.empty() ? material.diffuse_texname : dir + material.diffuse_texname;
tex.type = NTextureData::Usage::Diffuse;
tex.wrapS = GL_CLAMP_TO_EDGE;
tex.wrapT = GL_CLAMP_TO_EDGE;
@ -290,19 +241,91 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeD
sprintf(str, "%d", i++);
materialdata.textures.push_back(tex);
materialdata.id = str;
material.name = str;
materialdatas.materials.push_back(materialdata);
meshdata->subMeshIndices.push_back(it.mesh.indices);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), it.mesh.indices));
meshdata->subMeshIds.push_back(str);
auto node = new (std::nothrow) NodeData();
auto modelnode = new (std::nothrow) ModelData();
modelnode->matrialId = str;
modelnode->subMeshId = str;
node->id = it.name;
node->modelNodeDatas.push_back(modelnode);
nodedatas.nodes.push_back(node);
}
//convert mesh
i = 0;
for (auto& shape : shapes) {
auto mesh = shape.mesh;
MeshData* meshdata = new (std::nothrow) MeshData();
MeshVertexAttrib attrib;
attrib.size = 3;
attrib.type = GL_FLOAT;
if (mesh.positions.size())
{
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
bool hasnormal = false, hastex = false;
if (mesh.normals.size())
{
hasnormal = true;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL;
attrib.attribSizeBytes = attrib.size * sizeof(float);;
meshdata->attribs.push_back(attrib);
}
if (mesh.texcoords.size())
{
hastex = true;
attrib.size = 2;
attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD;
attrib.attribSizeBytes = attrib.size * sizeof(float);
meshdata->attribs.push_back(attrib);
}
auto vertexNum = mesh.positions.size() / 3;
for(unsigned int k = 0; k < vertexNum; k++)
{
meshdata->vertex.push_back(mesh.positions[k * 3]);
meshdata->vertex.push_back(mesh.positions[k * 3 + 1]);
meshdata->vertex.push_back(mesh.positions[k * 3 + 2]);
if (hasnormal)
{
meshdata->vertex.push_back(mesh.normals[k * 3]);
meshdata->vertex.push_back(mesh.normals[k * 3 + 1]);
meshdata->vertex.push_back(mesh.normals[k * 3 + 2]);
}
if (hastex)
{
meshdata->vertex.push_back(mesh.texcoords[k * 2]);
meshdata->vertex.push_back(mesh.texcoords[k * 2 + 1]);
}
}
//split into submesh according to material
std::map<int, std::vector<unsigned short> > subMeshMap;
for (size_t k = 0; k < mesh.material_ids.size(); k++) {
int id = mesh.material_ids[k];
size_t idx = k * 3;
subMeshMap[id].push_back(mesh.indices[idx]);
subMeshMap[id].push_back(mesh.indices[idx + 1]);
subMeshMap[id].push_back(mesh.indices[idx + 2]);
}
auto node = new (std::nothrow) NodeData();
node->id = shape.name;
for (auto& submesh : subMeshMap) {
meshdata->subMeshIndices.push_back(submesh.second);
meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), submesh.second));
sprintf(str, "%d", i++);
meshdata->subMeshIds.push_back(str);
auto modelnode = new (std::nothrow) ModelData();
modelnode->matrialId = submesh.first == -1 ? "" : materials[submesh.first].name;
modelnode->subMeshId = str;
node->modelNodeDatas.push_back(modelnode);
}
nodedatas.nodes.push_back(node);
meshdatas.meshDatas.push_back(meshdata);
}
return true;
}
CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str());

View File

@ -273,6 +273,9 @@ void Mesh::setTexture(Texture2D* tex)
// Texture must be saved for future use
// it doesn't matter if the material is already set or not
// This functionality is added for compatibility issues
if (tex == nullptr)
tex = getDummyTexture();
if (tex != _texture)
{
CC_SAFE_RETAIN(tex);

File diff suppressed because it is too large Load Diff

View File

@ -1,40 +1,19 @@
//
// Copyright 2012-2013, Syoyo Fujita.
// Copyright 2012-2015, Syoyo Fujita.
//
// Licensed under 2-clause BSD liecense.
//
// copied from Syoyo Fujita
// https://github.com/syoyo/tinyobjloader
#ifndef __CCOBJLOADER_H__
#define __CCOBJLOADER_H__
//https://github.com/syoyo/tinyobjloader
#ifndef _TINY_OBJ_LOADER_H
#define _TINY_OBJ_LOADER_H
#include <string>
#include <vector>
#include <map>
#include "base/ccTypes.h"
NS_CC_BEGIN
/**
* @addtogroup _3d
* @{
*/
/**
* @brief .obj file Loader
* @js NA
* @lua NA
**/
class ObjLoader
{
public:
/**
* model's material struct
**/
typedef struct
{
namespace tinyobj {
typedef struct {
std::string name;
float ambient[3];
@ -43,8 +22,8 @@ public:
float transmittance[3];
float emission[3];
float shininess;
float ior; // index of refraction
float dissolve; // 1 == opaque; 0 == fully transparent
float ior; // index of refraction
float dissolve; // 1 == opaque; 0 == fully transparent
// illumination model (see http://www.fileformat.info/format/material/)
int illum;
@ -55,61 +34,62 @@ public:
std::map<std::string, std::string> unknown_parameter;
} material_t;
/**
* model's indices struct
**/
typedef struct
{
std::vector<unsigned short> indices;
typedef struct {
std::vector<float> positions;
std::vector<float> normals;
std::vector<float> texcoords;
std::vector<unsigned short> indices;
std::vector<int> material_ids; // per-mesh material ID
} mesh_t;
/**
* model's shape struct
**/
typedef struct
{
std::string name;
material_t material;
mesh_t mesh;
typedef struct {
std::string name;
mesh_t mesh;
} shape_t;
/**
* model's shapes struct
**/
typedef struct
{
std::vector<float> positions;
std::vector<float> normals;
std::vector<float> texcoords;
class MaterialReader {
public:
MaterialReader() {}
virtual ~MaterialReader() {}
std::vector<shape_t> shapes;
void reset()
{
positions.clear();
normals.clear();
texcoords.clear();
shapes.clear();
}
}shapes_t;
virtual std::string operator()(const std::string &matId,
std::vector<material_t> &materials,
std::map<std::string, int> &matMap) = 0;
};
/**
* Loads .obj from a file.
* @param shapes will be filled with parsed shape data
* @param filename the .obj file path .
* @param mtl_basepath It's optional, and used for base path for .mtl file
* @return The function returns error string, return empty string when loading .obj success.
*/
static std::string LoadObj(
shapes_t& shapes, // [output]
const char* filename,
const char* mtl_basepath = NULL);
class MaterialFileReader : public MaterialReader {
public:
MaterialFileReader(const std::string &mtl_basepath)
: m_mtlBasePath(mtl_basepath) {}
virtual ~MaterialFileReader() {}
virtual std::string operator()(const std::string &matId,
std::vector<material_t> &materials,
std::map<std::string, int> &matMap);
private:
std::string m_mtlBasePath;
};
/// Loads .obj from a file.
/// 'shapes' will be filled with parsed shape data
/// The function returns error string.
/// Returns empty string when loading .obj success.
/// 'mtl_basepath' is optional, and used for base path for .mtl file.
std::string LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output]
const char *filename, const char *mtl_basepath = NULL);
/// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve
/// std::istream for materials.
/// Returns empty string when loading .obj success.
std::string LoadObj(std::vector<shape_t> &shapes, // [output]
std::vector<material_t> &materials, // [output]
std::istream &inStream, MaterialReader &readMatFn);
/// Loads materials into std::map
/// Returns an empty string if successful
std::string LoadMtl(std::map<std::string, int> &material_map,
std::vector<material_t> &materials, std::istream &inStream);
}
};
// end of 3d group
/// @}
NS_CC_END
#endif // _TINY_OBJ_LOADER_H
#endif // _TINY_OBJ_LOADER_H

View File

@ -352,8 +352,7 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c
if (modeldata->matrialId == "" && materialdatas.materials.size())
{
const NTextureData* textureData = materialdatas.materials[0].getTextureData(NTextureData::Usage::Diffuse);
if (!textureData->filename.empty())
mesh->setTexture(textureData->filename);
mesh->setTexture(textureData->filename);
}
else
{
@ -361,9 +360,10 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c
if(materialData)
{
const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse);
if(textureData && !textureData->filename.empty())
if(textureData)
{
auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename);
mesh->setTexture(textureData->filename);
auto tex = mesh->getTexture();
if(tex)
{
Texture2D::TexParams texParams;
@ -372,10 +372,8 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c
texParams.wrapS = textureData->wrapS;
texParams.wrapT = textureData->wrapT;
tex->setTexParameters(texParams);
mesh->setTexture(tex);
mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr);
}
}
}
}
@ -506,9 +504,10 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m
if(materialData)
{
const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse);
if(textureData && !textureData->filename.empty())
if(textureData)
{
auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename);
mesh->setTexture(textureData->filename);
auto tex = mesh->getTexture();
if(tex)
{
Texture2D::TexParams texParams;
@ -517,10 +516,8 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m
texParams.wrapS = textureData->wrapS;
texParams.wrapT = textureData->wrapT;
tex->setTexParameters(texParams);
mesh->setTexture(tex);
mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr);
}
}
}
}
@ -982,7 +979,10 @@ static GLProgramState* getGLProgramStateForAttribs(MeshVertexData* meshVertexDat
}
else
{
shader = GLProgram::SHADER_3D_POSITION;
if (hasNormal && usesLight)
shader = GLProgram::SHADER_3D_POSITION_NORMAL;
else
shader = GLProgram::SHADER_3D_POSITION;
}
CCASSERT(shader, "Couldn't find shader for sprite");

View File

@ -23,6 +23,7 @@
****************************************************************************/
#include "platform/CCPlatformConfig.h"
#include <condition_variable>
#if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
@ -61,8 +62,110 @@ AudioEngine::ProfileHelper* AudioEngine::_defaultProfileHelper = nullptr;
std::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::_audioIDInfoMap;
AudioEngineImpl* AudioEngine::_audioEngineImpl = nullptr;
AudioEngine::AudioEngineThreadPool* AudioEngine::s_threadPool = nullptr;
class AudioEngine::AudioEngineThreadPool
{
public:
AudioEngineThreadPool(bool detach)
: _numThread(6)
, _detach(detach)
{
s_threadPool = this;
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, index)));
if (_detach)
{
_threads[index].detach();
}
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, _numThread)));
if (_detach)
{
_threads[_numThread].detach();
}
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.notify_all();
if (!_detach)
{
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
}
private:
std::vector<std::thread> _threads;
std::vector< std::function<void()> > _tasks;
void threadFunc(int index)
{
while (s_threadPool == this) {
std::function<void()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
bool _detach;
};
void AudioEngine::end()
{
if (s_threadPool)
{
s_threadPool->destroy();
delete s_threadPool;
s_threadPool = nullptr;
}
delete _audioEngineImpl;
_audioEngineImpl = nullptr;
@ -82,6 +185,18 @@ bool AudioEngine::lazyInit()
}
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
if (_audioEngineImpl && s_threadPool == nullptr)
{
s_threadPool = new (std::nothrow) AudioEngineThreadPool(true);
}
#elif CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID
if (_audioEngineImpl && s_threadPool == nullptr)
{
s_threadPool = new (std::nothrow) AudioEngineThreadPool(false);
}
#endif
return true;
}
@ -415,4 +530,28 @@ AudioProfile* AudioEngine::getProfile(const std::string &name)
}
}
void AudioEngine::preload(const std::string& filePath)
{
lazyInit();
if (_audioEngineImpl)
{
if (!FileUtils::getInstance()->isFileExist(filePath)){
return;
}
_audioEngineImpl->preload(filePath);
}
}
void AudioEngine::addTask(const std::function<void()> &task)
{
lazyInit();
if (_audioEngineImpl && s_threadPool)
{
s_threadPool->addTask(task);
}
}
#endif

View File

@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
Copyright (c) 2014-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
@ -432,4 +432,9 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (i
_audioPlayers[audioID]._finishCallback = callback;
}
void AudioEngineImpl::preload(const std::string& filePath)
{
CCLOG("Preload not support on Anroid");
}
#endif

View File

@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
Copyright (c) 2014-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
@ -88,6 +88,7 @@ public:
void uncache(const std::string& filePath){}
void uncacheAll(){}
void preload(const std::string& filePath);
void update(float dt);
private:

View File

@ -38,8 +38,6 @@ NS_CC_BEGIN
namespace experimental{
#define MAX_AUDIOINSTANCES 24
class AudioEngineThreadPool;
class AudioEngineImpl : public cocos2d::Ref
{
public:
@ -61,14 +59,12 @@ public:
void uncache(const std::string& filePath);
void uncacheAll();
AudioCache* preload(const std::string& filePath);
void update(float dt);
private:
void _play2d(AudioCache *cache, int audioID);
AudioEngineThreadPool* _threadPool;
ALuint _alSources[MAX_AUDIOINSTANCES];
//source,used

View File

@ -42,93 +42,6 @@ using namespace cocos2d::experimental;
static ALCdevice *s_ALDevice = nullptr;
static ALCcontext *s_ALContext = nullptr;
namespace cocos2d {
namespace experimental {
class AudioEngineThreadPool
{
public:
AudioEngineThreadPool()
: _running(true)
, _numThread(6)
{
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,index) ) );
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,_numThread) ) );
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
_running = false;
_sleepCondition.notify_all();
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
private:
bool _running;
std::vector<std::thread> _threads;
std::vector< std::function<void ()> > _tasks;
void threadFunc(int index)
{
while (_running) {
std::function<void ()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
};
}
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
@interface AudioEngineSessionHandler : NSObject
{
@ -220,8 +133,7 @@ static id s_AudioEngineSessionHandler = nullptr;
#endif
AudioEngineImpl::AudioEngineImpl()
: _threadPool(nullptr)
, _lazyInitLoop(true)
: _lazyInitLoop(true)
, _currentAudioID(0)
{
@ -240,10 +152,7 @@ AudioEngineImpl::~AudioEngineImpl()
if (s_ALDevice) {
alcCloseDevice(s_ALDevice);
}
if (_threadPool) {
_threadPool->destroy();
delete _threadPool;
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
[s_AudioEngineSessionHandler release];
#endif
@ -275,7 +184,6 @@ bool AudioEngineImpl::init()
_alSourceUsed[_alSources[i]] = false;
}
_threadPool = new (std::nothrow) AudioEngineThreadPool();
ret = true;
}
}while (false);
@ -283,6 +191,24 @@ bool AudioEngineImpl::init()
return ret;
}
AudioCache* AudioEngineImpl::preload(const std::string& filePath)
{
AudioCache* audioCache = nullptr;
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
}
return audioCache;
}
int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
{
if (s_ALDevice == nullptr) {
@ -303,16 +229,9 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume
return AudioEngine::INVALID_AUDIO_ID;
}
AudioCache* audioCache = nullptr;
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
_threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
AudioCache* audioCache = preload(filePath);
if (audioCache == nullptr) {
return AudioEngine::INVALID_AUDIO_ID;
}
auto player = &_audioPlayers[_currentAudioID];

View File

@ -281,8 +281,14 @@ public:
*/
static AudioProfile* getProfile(const std::string &profileName);
/**
* Preload audio file.
* @param filePath The file path of an audio.
*/
static void preload(const std::string& filePath);
protected:
static void addTask(const std::function<void()> &task);
static void remove(int audioID);
struct ProfileHelper
@ -335,6 +341,9 @@ protected:
static ProfileHelper* _defaultProfileHelper;
static AudioEngineImpl* _audioEngineImpl;
class AudioEngineThreadPool;
static AudioEngineThreadPool* s_threadPool;
friend class AudioEngineImpl;
};

View File

@ -26,7 +26,7 @@
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#include "AudioEngine-win32.h"
#include <condition_variable>
#ifdef OPENAL_PLAIN_INCLUDES
#include "alc.h"
#include "alext.h"
@ -47,95 +47,9 @@ static ALCdevice *s_ALDevice = nullptr;
static ALCcontext *s_ALContext = nullptr;
static bool MPG123_LAZYINIT = true;
namespace cocos2d {
namespace experimental {
class AudioEngineThreadPool
{
public:
AudioEngineThreadPool()
: _running(true)
, _numThread(6)
{
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,index) ) );
_threads[index].detach();
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,_numThread) ) );
_threads[_numThread].detach();
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
_running = false;
_sleepCondition.notify_all();
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
private:
bool _running;
std::vector<std::thread> _threads;
std::vector< std::function<void ()> > _tasks;
void threadFunc(int index)
{
while (_running) {
std::function<void ()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
};
}
}
AudioEngineImpl::AudioEngineImpl()
: _lazyInitLoop(true)
, _currentAudioID(0)
, _threadPool(nullptr)
{
}
@ -155,10 +69,6 @@ AudioEngineImpl::~AudioEngineImpl()
alcCloseDevice(s_ALDevice);
s_ALDevice = nullptr;
}
if (_threadPool) {
_threadPool->destroy();
delete _threadPool;
}
mpg123_exit();
MPG123_LAZYINIT = true;
@ -186,7 +96,6 @@ bool AudioEngineImpl::init()
_alSourceUsed[_alSources[i]] = false;
}
_threadPool = new (std::nothrow) AudioEngineThreadPool();
ret = true;
}
}while (false);
@ -194,6 +103,54 @@ bool AudioEngineImpl::init()
return ret;
}
AudioCache* AudioEngineImpl::preload(const std::string& filePath)
{
AudioCache* audioCache = nullptr;
do
{
auto it = _audioCaches.find(filePath);
if (it != _audioCaches.end())
{
audioCache = &it->second;
break;
}
auto ext = strchr(filePath.c_str(), '.');
AudioCache::FileFormat fileFormat = AudioCache::FileFormat::UNKNOWN;
if (_stricmp(ext, ".ogg") == 0){
fileFormat = AudioCache::FileFormat::OGG;
}
else if (_stricmp(ext, ".mp3") == 0){
fileFormat = AudioCache::FileFormat::MP3;
if (MPG123_LAZYINIT){
auto error = mpg123_init();
if (error == MPG123_OK){
MPG123_LAZYINIT = false;
}
else{
log("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
break;
}
}
}
else{
log("unsupported media type:%s\n", ext);
break;
}
audioCache = &_audioCaches[filePath];
audioCache->_fileFormat = fileFormat;
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache));
} while (false);
return audioCache;
}
int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
{
bool availableSourceExist = false;
@ -209,48 +166,10 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume
return AudioEngine::INVALID_AUDIO_ID;
}
AudioCache* audioCache = nullptr;
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
auto ext = strchr(filePath.c_str(), '.');
bool eraseCache = true;
if (_stricmp(ext, ".ogg") == 0){
audioCache->_fileFormat = AudioCache::FileFormat::OGG;
eraseCache = false;
}
else if (_stricmp(ext, ".mp3") == 0){
audioCache->_fileFormat = AudioCache::FileFormat::MP3;
if (MPG123_LAZYINIT){
auto error = mpg123_init();
if(error == MPG123_OK){
MPG123_LAZYINIT = false;
eraseCache = false;
}
else{
log("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
}
}
else{
eraseCache = false;
}
}
else{
log("unsupported media type:%s\n", ext);
}
if (eraseCache){
_audioCaches.erase(filePath);
return AudioEngine::INVALID_AUDIO_ID;
}
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
_threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
AudioCache* audioCache = preload(filePath);
if (audioCache == nullptr)
{
return AudioEngine::INVALID_AUDIO_ID;
}
auto player = &_audioPlayers[_currentAudioID];

View File

@ -38,8 +38,6 @@ NS_CC_BEGIN
namespace experimental{
#define MAX_AUDIOINSTANCES 32
class AudioEngineThreadPool;
class CC_DLL AudioEngineImpl : public cocos2d::Ref
{
public:
@ -61,14 +59,13 @@ public:
void uncache(const std::string& filePath);
void uncacheAll();
AudioCache* preload(const std::string& filePath);
void update(float dt);
private:
void _play2d(AudioCache *cache, int audioID);
AudioEngineThreadPool* _threadPool;
ALuint _alSources[MAX_AUDIOINSTANCES];
//source,used

View File

@ -21,101 +21,13 @@
#if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
#include "AudioEngine-winrt.h"
#include <condition_variable>
using namespace cocos2d;
using namespace cocos2d::experimental;
namespace cocos2d {
namespace experimental {
class AudioEngineThreadPool
{
public:
AudioEngineThreadPool()
: _running(true)
, _numThread(6)
{
_threads.reserve(_numThread);
_tasks.reserve(_numThread);
for (int index = 0; index < _numThread; ++index) {
_tasks.push_back(nullptr);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, index)));
}
}
void addTask(const std::function<void()> &task){
_taskMutex.lock();
int targetIndex = -1;
for (int index = 0; index < _numThread; ++index) {
if (_tasks[index] == nullptr) {
targetIndex = index;
_tasks[index] = task;
break;
}
}
if (targetIndex == -1) {
_tasks.push_back(task);
_threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, _numThread)));
_numThread++;
}
_taskMutex.unlock();
_sleepCondition.notify_all();
}
void destroy()
{
_running = false;
_sleepCondition.notify_all();
for (int index = 0; index < _numThread; ++index) {
_threads[index].join();
}
}
private:
bool _running;
std::vector<std::thread> _threads;
std::vector< std::function<void()> > _tasks;
void threadFunc(int index)
{
while (_running) {
std::function<void()> task = nullptr;
_taskMutex.lock();
task = _tasks[index];
_taskMutex.unlock();
if (nullptr == task)
{
std::unique_lock<std::mutex> lk(_sleepMutex);
_sleepCondition.wait(lk);
continue;
}
task();
_taskMutex.lock();
_tasks[index] = nullptr;
_taskMutex.unlock();
}
}
int _numThread;
std::mutex _taskMutex;
std::mutex _sleepMutex;
std::condition_variable _sleepCondition;
};
}
}
AudioEngineImpl::AudioEngineImpl()
: _lazyInitLoop(true)
, _currentAudioID(0)
, _threadPool(nullptr)
{
}
@ -123,64 +35,63 @@ AudioEngineImpl::AudioEngineImpl()
AudioEngineImpl::~AudioEngineImpl()
{
_audioCaches.clear();
if (_threadPool) {
_threadPool->destroy();
delete _threadPool;
}
}
bool AudioEngineImpl::init()
{
bool ret = false;
if (nullptr == _threadPool) {
_threadPool = new (std::nothrow) AudioEngineThreadPool();
}
ret = true;
return ret;
}
int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume)
AudioCache* AudioEngineImpl::preload(const std::string& filePath)
{
AudioCache* audioCache = nullptr;
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
do
{
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
FileFormat fileFormat = FileFormat::UNKNOWN;
auto ext = filePath.substr(filePath.rfind('.'));
transform(ext.begin(), ext.end(), ext.begin(), tolower);
auto ext = filePath.substr(filePath.rfind('.'));
transform(ext.begin(), ext.end(), ext.begin(), tolower);
bool eraseCache = true;
if (ext.compare(".wav") == 0){
fileFormat = FileFormat::WAV;
}
else if (ext.compare(".ogg") == 0){
fileFormat = FileFormat::OGG;
}
else if (ext.compare(".mp3") == 0){
fileFormat = FileFormat::MP3;
}
else{
log("unsupported media type:%s\n", ext.c_str());
break;
}
if (ext.compare(".wav") == 0){
audioCache->_fileFormat = FileFormat::WAV;
eraseCache = false;
}
else if (ext.compare(".ogg") == 0){
audioCache->_fileFormat = FileFormat::OGG;
eraseCache = false;
}
else if (ext.compare(".mp3") == 0){
audioCache->_fileFormat = FileFormat::MP3;
eraseCache = false;
}
else{
log("unsupported media type:%s\n", ext.c_str());
}
audioCache = &_audioCaches[filePath];
audioCache->_fileFormat = fileFormat;
if (eraseCache){
_audioCaches.erase(filePath);
return AudioEngine::INVALID_AUDIO_ID;
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
audioCache->_fileFullPath = fullPath;
AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
}
} while (false);
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
audioCache->_fileFullPath = fullPath;
_threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache));
}
else {
audioCache = &it->second;
return audioCache;
}
int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume)
{
auto audioCache = preload(filePath);
if (audioCache == nullptr)
{
return AudioEngine::INVALID_AUDIO_ID;
}
auto player = &_audioPlayers[_currentAudioID];

View File

@ -35,9 +35,6 @@ NS_CC_BEGIN
namespace experimental{
#define MAX_AUDIOINSTANCES 32
class AudioEngineThreadPool;
class CC_DLL AudioEngineImpl : public cocos2d::Ref
{
public:
@ -58,6 +55,7 @@ NS_CC_BEGIN
void setFinishCallback(int audioID, const std::function<void(int, const std::string &)> &callback);
void uncache(const std::string& filePath);
void uncacheAll();
AudioCache* preload(const std::string& filePath);
void update(float dt);
private:
@ -72,7 +70,6 @@ NS_CC_BEGIN
std::vector<int> _toRemoveAudioIDs;
bool _lazyInitLoop;
int _currentAudioID;
AudioEngineThreadPool* _threadPool;
};
}

View File

@ -50,7 +50,7 @@ Configuration::Configuration()
, _maxDirLightInShader(1)
, _maxPointLightInShader(1)
, _maxSpotLightInShader(1)
, _animate3DQuality(Animate3DQuality::QUALITY_HIGH)
, _animate3DQuality(Animate3DQuality::QUALITY_LOW)
{
}

View File

@ -123,12 +123,12 @@ static bool isFloat( std::string myString ) {
static ssize_t mydprintf(int sock, const char *format, ...)
{
va_list args;
char buf[16386];
char buf[16386];
va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
return send(sock, buf, strlen(buf),0);
va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
return send(sock, buf, strlen(buf),0);
}
static void sendPrompt(int fd)
@ -235,20 +235,53 @@ void SendLogToWindow(const char *log)
static void _log(const char *format, va_list args)
{
char buf[MAX_LOG_LENGTH];
int bufferSize = MAX_LOG_LENGTH;
char* buf = nullptr;
do
{
buf = new (std::nothrow) char[bufferSize];
if (buf == nullptr)
return; // not enough memory
int ret = vsnprintf(buf, bufferSize - 3, format, args);
if (ret < 0)
{
bufferSize *= 2;
delete [] buf;
}
else
break;
} while (true);
vsnprintf(buf, MAX_LOG_LENGTH-3, format, args);
strcat(buf, "\n");
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf);
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf);
#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
WCHAR wszBuf[MAX_LOG_LENGTH] = {0};
MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf));
OutputDebugStringW(wszBuf);
WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, buf, sizeof(buf), nullptr, FALSE);
printf("%s", buf);
int pos = 0;
int len = strlen(buf);
char tempBuf[MAX_LOG_LENGTH + 1] = { 0 };
WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 };
do
{
std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf);
tempBuf[MAX_LOG_LENGTH] = 0;
MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf));
OutputDebugStringW(wszBuf);
WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, tempBuf, sizeof(tempBuf), nullptr, FALSE);
printf("%s", tempBuf);
pos += MAX_LOG_LENGTH;
} while (pos < len);
SendLogToWindow(buf);
fflush(stdout);
#else
@ -258,7 +291,7 @@ static void _log(const char *format, va_list args)
#endif
Director::getInstance()->getConsole()->log(buf);
delete [] buf;
}
// FIXME: Deprecated
@ -290,7 +323,7 @@ Console::Console()
, _bindAddress("")
{
// VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'.
Command commands[] = {
Command commands[] = {
{ "allocator", "Display allocator diagnostics for all allocators", std::bind(&Console::commandAllocator, this, std::placeholders::_1, std::placeholders::_2) },
{ "config", "Print the Configuration object", std::bind(&Console::commandConfig, this, std::placeholders::_1, std::placeholders::_2) },
{ "debugmsg", "Whether or not to forward the debug messages on the console. Args: [on | off]", [&](int fd, const std::string& args) {
@ -326,10 +359,10 @@ Console::Console()
};
;
for (int i = 0; i < sizeof(commands)/sizeof(commands[0]); ++i)
{
_commands[commands[i].name] = commands[i];
}
for (int i = 0; i < sizeof(commands)/sizeof(commands[0]); ++i)
{
_commands[commands[i].name] = commands[i];
}
}
Console::~Console()
@ -1190,7 +1223,7 @@ void Console::loop()
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
closesocket(_listenfd);
WSACleanup();
WSACleanup();
#else
close(_listenfd);
#endif

View File

@ -1027,7 +1027,8 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event)
return true;
}
CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(), "");
CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(),
"touchesIter ID should be equal to mutableTouchesIter's ID.");
if (isClaimed && listener->_isRegistered && listener->_needSwallow)
{

View File

@ -89,7 +89,7 @@ EventListenerAcceleration* EventListenerAcceleration::clone()
bool EventListenerAcceleration::checkAvailable()
{
CCASSERT(onAccelerationEvent, "");
CCASSERT(onAccelerationEvent, "onAccelerationEvent can't be nullptr!");
return true;
}

View File

@ -300,7 +300,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float in
}
else
{
CCASSERT(element->paused == paused, "");
CCASSERT(element->paused == paused, "element's paused should be paused!");
}
if (element->timers == nullptr)
@ -694,7 +694,7 @@ void Scheduler::unscheduleScriptEntry(unsigned int scheduleScriptEntryID)
void Scheduler::resumeTarget(void *target)
{
CCASSERT(target != nullptr, "");
CCASSERT(target != nullptr, "target can't be nullptr!");
// custom selectors
tHashTimerEntry *element = nullptr;
@ -709,14 +709,14 @@ void Scheduler::resumeTarget(void *target)
HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate)
{
CCASSERT(elementUpdate->entry != nullptr, "");
CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!");
elementUpdate->entry->paused = false;
}
}
void Scheduler::pauseTarget(void *target)
{
CCASSERT(target != nullptr, "");
CCASSERT(target != nullptr, "target can't be nullptr!");
// custom selectors
tHashTimerEntry *element = nullptr;
@ -731,7 +731,7 @@ void Scheduler::pauseTarget(void *target)
HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate);
if (elementUpdate)
{
CCASSERT(elementUpdate->entry != nullptr, "");
CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!");
elementUpdate->entry->paused = true;
}
}
@ -1001,7 +1001,7 @@ void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, uns
}
else
{
CCASSERT(element->paused == paused, "");
CCASSERT(element->paused == paused, "element's paused should be paused.");
}
if (element->timers == nullptr)

View File

@ -252,8 +252,8 @@ int ZipUtils::inflateGZipFile(const char *path, unsigned char **out)
int len;
unsigned int offset = 0;
CCASSERT(out, "");
CCASSERT(&*out, "");
CCASSERT(out, "out can't be nullptr.");
CCASSERT(&*out, "&*out can't be nullptr.");
gzFile inFile = gzopen(path, "rb");
if( inFile == nullptr ) {

View File

@ -128,7 +128,7 @@ CCBReader::~CCBReader()
void CCBReader::setCCBRootPath(const char* ccbRootPath)
{
CCASSERT(ccbRootPath != nullptr, "");
CCASSERT(ccbRootPath != nullptr, "ccbRootPath can't be nullptr!");
_CCBRootPath = ccbRootPath;
}

View File

@ -99,11 +99,11 @@ void NodeLoader::parseProperties(Node * pNode, Node * pParent, CCBReader * ccbRe
__Array *extraPropsNames = static_cast<__Array*>(pNode->getUserObject());
if (! extraPropsNames)
{
extraPropsNames = Array::create();
extraPropsNames = __Array::create();
pNode->setUserObject(extraPropsNames);
}
extraPropsNames->addObject(String::create(propertyName));
extraPropsNames->addObject(__String::create(propertyName));
}
switch(type)
@ -968,7 +968,8 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader
auto& ownerCallbackNodes = reader->getOwnerCallbackNodes();
if (!ownerCallbackNames.empty() && !ownerCallbackNodes.empty())
{
CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(), "");
CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(),
"ownerCallbackNames size should equal to ownerCallbackNodes size.");
ssize_t nCount = ownerCallbackNames.size();
for (ssize_t i = 0 ; i < nCount; i++)
@ -982,7 +983,8 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader
auto ownerOutletNodes = reader->getOwnerOutletNodes();
if (!ownerOutletNames.empty() && !ownerOutletNodes.empty())
{
CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(), "");
CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(),
"ownerOutletNames size should be equal to ownerOutletNodes's size.");
ssize_t nCount = ownerOutletNames.size();
for (ssize_t i = 0 ; i < nCount; i++)

View File

@ -611,7 +611,7 @@ Node* CSLoader::loadSprite(const rapidjson::Value& json)
if(!sprite)
{
sprite = CCSprite::create();
sprite = Sprite::create();
CCLOG("filePath is empty. Create a sprite with no texture");
}
}
@ -844,7 +844,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string &fileName, const ccNod
if (csBuildId)
{
CCASSERT(strcmp(_csBuildID.c_str(), csBuildId->c_str()) == 0,
String::createWithFormat("%s%s%s%s%s%s%s%s%s%s",
StringUtils::format("%s%s%s%s%s%s%s%s%s%s",
"The reader build id of your Cocos exported file(",
csBuildId->c_str(),
") and the reader build id in your Cocos2d-x(",
@ -854,7 +854,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string &fileName, const ccNod
csBuildId->c_str(),
")from ",
"http://www.cocos2d-x.org/filedown/cocos-reader",
" and replace it in your Cocos2d-x")->getCString());
" and replace it in your Cocos2d-x").c_str());
}
// decode plist

View File

@ -137,7 +137,7 @@ bool Armature::init(const std::string& name)
ArmatureData *armatureData = armatureDataManager->getArmatureData(name);
CCASSERT(armatureData, "");
CCASSERT(armatureData, "armatureData doesn't exists!");
_armatureData = armatureData;

View File

@ -246,7 +246,7 @@ void DisplayManager::changeDisplayWithIndex(int index, bool force)
setCurrentDecorativeDisplay(decoDisplay);
}
void CCDisplayManager::changeDisplayWithName(const std::string& name, bool force)
void DisplayManager::changeDisplayWithName(const std::string& name, bool force)
{
for (int i = 0; i<_decoDisplayList.size(); i++)
{

View File

@ -493,7 +493,7 @@ Widget* WidgetPropertiesReader0250::createWidget(const rapidjson::Value& data, c
const char* file = DICTOOL->getStringValueFromArray_json(data, "textures", i);
std::string tp = fullPath;
tp.append(file);
CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str());
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str());
}
float fileDesignWidth = DICTOOL->getFloatValue_json(data, "designWidth");
float fileDesignHeight = DICTOOL->getFloatValue_json(data, "designHeight");
@ -713,7 +713,7 @@ void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(Widget*widg
if (useMergedTexture)
{
button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST);
button->loadTextures(normalFileName, pressedFileName, disabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -733,7 +733,7 @@ void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(Widget*widg
{
if (useMergedTexture)
{
button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST);
button->loadTextures(normalFileName, pressedFileName, disabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -794,7 +794,7 @@ void WidgetPropertiesReader0250::setPropsForCheckBoxFromJsonDictionary(Widget*wi
if (useMergedTexture)
{
checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,TextureResType::PLIST);
checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -829,7 +829,7 @@ void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(Widget*w
{
if (useMergedTexture)
{
imageView->loadTexture(imageFileName,TextureResType::PLIST);
imageView->loadTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -856,7 +856,7 @@ void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(Widget*w
{
if (useMergedTexture)
{
imageView->loadTexture(imageFileName,TextureResType::PLIST);
imageView->loadTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -974,7 +974,7 @@ void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(Widget*widg
float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight");
if (useMergedTexture)
{
panel->setBackGroundImage(imageFileName,TextureResType::PLIST);
panel->setBackGroundImage(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -987,7 +987,7 @@ void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(Widget*widg
if (useMergedTexture)
{
panel->setBackGroundImage(imageFileName,TextureResType::PLIST);
panel->setBackGroundImage(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1029,7 +1029,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadBarTexture(imageFileName,TextureResType::PLIST);
slider->loadBarTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1044,7 +1044,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadBarTexture(imageFileName,TextureResType::PLIST);
slider->loadBarTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1065,7 +1065,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,TextureResType::PLIST);
slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,Widget::TextureResType::PLIST);
}
else
{
@ -1078,7 +1078,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
slider->loadProgressBarTexture(imageFileName, TextureResType::PLIST);
slider->loadProgressBarTexture(imageFileName, Widget::TextureResType::PLIST);
}
else
{
@ -1147,7 +1147,7 @@ void WidgetPropertiesReader0250::setPropsForLoadingBarFromJsonDictionary(Widget
const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr;
if (useMergedTexture)
{
loadingBar->loadTexture(imageFileName,TextureResType::PLIST);
loadingBar->loadTexture(imageFileName,Widget::TextureResType::PLIST);
}
else
{

View File

@ -79,7 +79,7 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName,
else if(file_extension == ".CSB")
{
do {
std::string binaryFilePath = CCFileUtils::getInstance()->fullPathForFilename(fileName);
std::string binaryFilePath = FileUtils::getInstance()->fullPathForFilename(fileName);
auto fileData = FileUtils::getInstance()->getDataFromFile(binaryFilePath);
auto fileDataBytes = fileData.getBytes();
CC_BREAK_IF(fileData.isNull());
@ -429,7 +429,7 @@ cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *
{
if (pRender == nullptr || attachComponent == AttachComponentType::EMPTY_NODE)
{
gb = CCNode::create();
gb = Node::create();
if (pRender != nullptr)
{
_vecComs.push_back(pRender);

View File

@ -185,10 +185,10 @@ void TriggerObj::serialize(const rapidjson::Value &val)
if(con == nullptr)
{
CCLOG("class %s can not be implemented!", classname);
CCASSERT(con != nullptr, "");
CCASSERT(con != nullptr, "con can't be nullptr!");
}
CCASSERT(con != nullptr, "");
CCASSERT(con != nullptr, "con can't be nullptr!");
con->serialize(subDict);
con->init();
_cons.pushBack(con);
@ -207,7 +207,7 @@ void TriggerObj::serialize(const rapidjson::Value &val)
if(act == nullptr)
{
CCLOG("class %s can not be implemented!", classname);
CCASSERT(act != nullptr, "");
CCASSERT(act != nullptr, "act can't be nullptr!");
}
act->serialize(subDict);
act->init();

View File

@ -238,15 +238,12 @@ namespace cocostudio
setPropsWithFlatBuffers(tmx, (Table*)gameMapOptions);
}
}
//else
//{
// Node* node = Node::create();
// setPropsWithFlatBuffers(node, (Table*)gameMapOptions);
// auto label = Label::create();
// label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString());
// node->addChild(label);
// return node;
//}
else
{
Node* node = Node::create();
setPropsWithFlatBuffers(node, (Table*)gameMapOptions);
return node;
}
return tmx;
}

View File

@ -153,11 +153,11 @@ namespace cocostudio
void ParticleReader::setPropsWithFlatBuffers(cocos2d::Node *node,
const flatbuffers::Table *particleOptions)
{
auto particle = static_cast<ParticleSystemQuad*>(node);
auto particle = dynamic_cast<ParticleSystemQuad*>(node);
auto options = (ParticleSystemOptions*)particleOptions;
auto f_blendFunc = options->blendFunc();
if (f_blendFunc)
if (particle && f_blendFunc)
{
cocos2d::BlendFunc blendFunc = cocos2d::BlendFunc::ALPHA_PREMULTIPLIED;
blendFunc.src = f_blendFunc->src();
@ -208,15 +208,12 @@ namespace cocostudio
particle->setPositionType(ParticleSystem::PositionType::GROUPED);
}
}
//else
//{
// Node* node = Node::create();
// setPropsWithFlatBuffers(node, (Table*)particleOptions);
// auto label = Label::create();
// label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString());
// node->addChild(label);
// return node;
//}
else
{
Node* node = Node::create();
setPropsWithFlatBuffers(node, (Table*)particleOptions);
return node;
}
return particle;
}

View File

@ -466,7 +466,7 @@ namespace cocostudio
auto options = (SliderOptions*)sliderOptions;
int percent = options->percent();
slider->setPercent(percent);
//slider->setPercent(percent);
bool imageFileExist = false;
std::string imageErrorFilePath = "";
@ -798,7 +798,7 @@ namespace cocostudio
auto widgetReader = WidgetReader::getInstance();
widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions());
slider->setPercent(percent);
}
Node* SliderReader::createNodeWithFlatBuffers(const flatbuffers::Table *sliderOptions)

View File

@ -125,6 +125,7 @@ namespace cocostudio
else if(value == "USER1") cameraFlag = 1 << 1;
else if(value == "USER2") cameraFlag = 1 << 2;
else if(value == "USER3") cameraFlag = 1 << 3;
else if(value == "USER4") cameraFlag = 1 << 4;
}
attribute = attribute->Next();

View File

@ -91,10 +91,10 @@ public:
bool setAttachment (const std::string& slotName, const char* attachmentName);
// --- BlendProtocol
virtual void setBlendFunc (const cocos2d::BlendFunc& blendFunc);
virtual const cocos2d::BlendFunc& getBlendFunc () const;
virtual void setOpacityModifyRGB (bool value);
virtual bool isOpacityModifyRGB () const;
virtual void setBlendFunc (const cocos2d::BlendFunc& blendFunc)override;
virtual const cocos2d::BlendFunc& getBlendFunc () const override;
virtual void setOpacityModifyRGB (bool value)override;
virtual bool isOpacityModifyRGB () const override;
CC_CONSTRUCTOR_ACCESS:
SkeletonRenderer ();

View File

@ -49,8 +49,8 @@ public:
NavMeshDebugDraw();
virtual ~NavMeshDebugDraw();
virtual void depthMask(bool state);
virtual void texture(bool state){};
virtual void depthMask(bool state)override;
virtual void texture(bool state)override{};
virtual void begin(duDebugDrawPrimitives prim, float size = 1.0f) override;
virtual void vertex(const float* pos, unsigned int color) override;

View File

@ -41,24 +41,12 @@ THE SOFTWARE.
#endif
#include <sys/stat.h>
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
#include <regex>
#endif
NS_CC_BEGIN
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include <ftw.h>
#endif
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT)
#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
#endif
// Implement DictMaker
#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
NS_CC_BEGIN
typedef enum
{
SAX_NONE = 0,
@ -540,7 +528,6 @@ static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, t
}
#else
NS_CC_BEGIN
/* The subclass FileUtilsApple should override these two method. */
ValueMap FileUtils::getValueMapFromFile(const std::string& filename) {return ValueMap();}
@ -550,6 +537,7 @@ bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath) {return
#endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */
// Implement FileUtils
FileUtils* FileUtils::s_sharedFileUtils = nullptr;
void FileUtils::destroyInstance()
@ -584,7 +572,6 @@ bool FileUtils::writeStringToFile(std::string dataStr, const std::string& fullPa
bool FileUtils::writeDataToFile(Data retData, const std::string& fullPath)
{
unsigned char* buffer = nullptr;
size_t size = 0;
const char* mode = "wb";
@ -1038,36 +1025,6 @@ bool FileUtils::isAbsolutePath(const std::string& path) const
return (path[0] == '/');
}
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wdirPath(dirPath.begin(), dirPath.end());
if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
unsigned long fAttrib = GetFileAttributesA(dirPath.c_str());
if (fAttrib != INVALID_FILE_ATTRIBUTES &&
(fAttrib & FILE_ATTRIBUTE_DIRECTORY))
{
return true;
}
return false;
#else
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
{
return S_ISDIR(st.st_mode);
}
return false;
#endif
}
bool FileUtils::isDirectoryExist(const std::string& dirPath) const
{
CCASSERT(!dirPath.empty(), "Invalid path");
@ -1098,7 +1055,60 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const
}
}
}
return false;
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
// windows os implement should override in platform specific FileUtiles class
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
CCASSERT(false, "FileUtils not support isDirectoryExistInternal");
return false;
}
bool FileUtils::createDirectory(const std::string& path)
{
CCASSERT(false, "FileUtils not support createDirectory");
return false;
}
bool FileUtils::removeDirectory(const std::string& path)
{
CCASSERT(false, "FileUtils not support removeDirectory");
return false;
}
bool FileUtils::removeFile(const std::string &path)
{
CCASSERT(false, "FileUtils not support removeFile");
return false;
}
bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
{
CCASSERT(false, "FileUtils not support renameFile");
return false;
}
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
CCASSERT(false, "getSuitableFOpen should be override by platform FileUtils");
return filenameUtf8;
}
#else
// default implements for unix like os
#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const
{
struct stat st;
if (stat(dirPath.c_str(), &st) == 0)
{
return S_ISDIR(st.st_mode);
}
return false;
}
@ -1135,47 +1145,6 @@ bool FileUtils::createDirectory(const std::string& path)
}
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wpath(path.begin(), path.end());
if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad)))
{
subpath = "";
for(unsigned int i = 0 ; i < dirs.size() ; ++i)
{
subpath += dirs[i];
if (i > 0 && !isDirectoryExist(subpath))
{
std::wstring wsubpath(subpath.begin(), subpath.end());
BOOL ret = CreateDirectory(wsubpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
return false;
}
}
}
}
return true;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES)
{
subpath = "";
for (unsigned int i = 0; i < dirs.size(); ++i)
{
subpath += dirs[i];
if (!isDirectoryExist(subpath))
{
BOOL ret = CreateDirectoryA(subpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
return false;
}
}
}
}
return true;
#else
DIR *dir = NULL;
// Create path recursively
@ -1204,22 +1173,8 @@ bool FileUtils::createDirectory(const std::string& path)
}
}
return true;
#endif
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
auto ret = remove(fpath);
if (ret)
{
log("Fail to remove: %s ",fpath);
}
return ret;
}
#endif
bool FileUtils::removeDirectory(const std::string& path)
{
if (path.size() > 0 && path[path.size() - 1] != '/')
@ -1228,58 +1183,6 @@ bool FileUtils::removeDirectory(const std::string& path)
return false;
}
// Remove downloaded files
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::wstring wpath = std::wstring(path.begin(), path.end());
std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd;
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret=true;
if (search!=INVALID_HANDLE_VALUE)
{
BOOL find=true;
while (find)
{
//. ..
if(wfd.cFileName[0]!='.')
{
std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
temp += '/';
ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end()));
}
else
{
SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFile(temp.c_str());
}
}
find = FindNextFile(search, &wfd);
}
FindClose(search);
}
if (ret && RemoveDirectory(wpath.c_str()))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
std::string command = "cmd /c rd /s /q ";
// Path may include space.
command += "\"" + path + "\"";
if (WinExec(command.c_str(), SW_HIDE) > 31)
return true;
else
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
return false;
else
return true;
#else
std::string command = "rm -r ";
// Path may include space.
command += "\"" + path + "\"";
@ -1287,44 +1190,15 @@ bool FileUtils::removeDirectory(const std::string& path)
return true;
else
return false;
#endif
}
bool FileUtils::removeFile(const std::string &path)
{
// Remove downloaded file
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::wstring wpath(path.begin(), path.end());
if (DeleteFile(wpath.c_str()))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
std::string command = "cmd /c del /q ";
std::string win32path = path;
int len = win32path.length();
for (int i = 0; i < len; ++i)
{
if (win32path[i] == '/')
{
win32path[i] = '\\';
}
}
command += win32path;
if (WinExec(command.c_str(), SW_HIDE) > 31)
return true;
else
return false;
#else
if (remove(path.c_str())) {
return false;
} else {
return true;
}
#endif
}
bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
@ -1333,41 +1207,6 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname,
std::string oldPath = path + oldname;
std::string newPath = path + name;
// Rename a file
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
if (MoveFileEx(std::wstring(_old.begin(), _old.end()).c_str(),
std::wstring(_new.begin(), _new.end()).c_str(),
MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH))
{
return true;
}
return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
if(FileUtils::getInstance()->isFileExist(_new))
{
if (!DeleteFileA(_new.c_str()))
{
CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError());
}
}
if (MoveFileA(_old.c_str(), _new.c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError());
return false;
}
#else
int errorCode = rename(oldPath.c_str(), newPath.c_str());
if (0 != errorCode)
@ -1376,9 +1215,15 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname,
return false;
}
return true;
#endif
}
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
return filenameUtf8;
}
#endif
long FileUtils::getFileSize(const std::string &filepath)
{
CCASSERT(!filepath.empty(), "Invalid path");
@ -1422,68 +1267,5 @@ bool FileUtils::isPopupNotify() const
return s_popupNotify;
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
static std::wstring StringUtf8ToWideChar(const std::string& strUtf8)
{
std::wstring ret;
if (!strUtf8.empty())
{
int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0);
if (nNum)
{
WCHAR* wideCharString = new WCHAR[nNum + 1];
wideCharString[0] = 0;
nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1);
ret = wideCharString;
delete[] wideCharString;
}
else
{
CCLOG("Wrong convert to WideChar code:0x%x", GetLastError());
}
}
return ret;
}
static std::string UTF8StringToMultiByte(const std::string& strUtf8)
{
std::string ret;
if (!strUtf8.empty())
{
std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* ansiString = new char[nNum + 1];
ansiString[0] = 0;
nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
ret = ansiString;
delete[] ansiString;
}
else
{
CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
}
}
return ret;
}
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
return UTF8StringToMultiByte(filenameUtf8);
}
#else
std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const
{
return filenameUtf8;
}
#endif
NS_CC_END

View File

@ -77,7 +77,7 @@ void Application::setAnimationInterval(float interval)
{
JniMethodInfo methodInfo;
if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxRenderer", "setAnimationInterval",
"(D)V"))
"(F)V"))
{
CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__);
}

View File

@ -33,6 +33,7 @@ THE SOFTWARE.
#include "android/asset_manager_jni.h"
#include "jni/CocosPlayClient.h"
#include <stdlib.h>
#include <sys/stat.h>
#define LOG_TAG "CCFileUtils-android.cpp"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
@ -187,6 +188,59 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const
return bFound;
}
bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) const
{
if (dirPath.empty())
{
return false;
}
const char* s = dirPath.c_str();
bool startWithAssets = (dirPath.find("assets/") == 0);
int lenOfAssets = 7;
std::string tmpStr;
if (cocosplay::isEnabled() && !cocosplay::isDemo())
{
// redirect assets/*** path to cocosplay resource dir
tmpStr.append(_defaultResRootPath);
if ('/' != tmpStr[tmpStr.length() - 1])
{
tmpStr += '/';
}
tmpStr.append(s + lenOfAssets);
}
// find absolute path in flash memory
if (s[0] == '/')
{
CCLOG("find in flash memory dirPath(%s)", s);
struct stat st;
if (stat(s, &st) == 0)
{
return S_ISDIR(st.st_mode);
}
}
// find it in apk's assets dir
// Found "assets/" at the beginning of the path and we don't want it
CCLOG("find in apk dirPath(%s)", s);
if (startWithAssets)
{
s += lenOfAssets;
}
if (FileUtilsAndroid::assetmanager)
{
AAssetDir* aa = AAssetManager_openDir(FileUtilsAndroid::assetmanager, s);
if (aa && AAssetDir_getNextFileName(aa))
{
AAssetDir_close(aa);
return true;
}
}
return false;
}
bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const
{
// On Android, there are two situations for full path.

View File

@ -81,7 +81,8 @@ public:
virtual bool isAbsolutePath(const std::string& strPath) const;
private:
virtual bool isFileExistInternal(const std::string& strFilePath) const;
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
virtual bool isDirectoryExistInternal(const std::string& dirPath) const override;
Data getData(const std::string& filename, bool forString);
static AAssetManager* assetmanager;

View File

@ -36,271 +36,271 @@ import android.view.MotionEvent;
import android.util.Log;
public abstract class GameControllerActivity extends Cocos2dxActivity implements InputDeviceListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Constants
// ===========================================================
private final static String TAG = GameControllerActivity.class.getSimpleName();
private final static String TAG = GameControllerActivity.class.getSimpleName();
public static final int DRIVERTYPE_NIBIRU = 0;
public static final int DRIVERTYPE_MOGA = 1;
public static final int DRIVERTYPE_OUYA = 2;
public static final int DRIVERTYPE_STANDARD = 3;
public static final int DRIVERTYPE_UNKNOWN = 4;
// ===========================================================
// Fields
// ===========================================================
private static GameControllerActivity sGameControllerActivity;
private InputManagerCompat mInputManager = null;
protected GameControllerHelper mControllerHelper = null;
protected GameControllerDelegate mControllerNibiru = null;
protected GameControllerDelegate mControllerMoga = null;
protected GameControllerDelegate mControllerOuya = null;
public void connectController(int driveType){
try {
ClassLoader loader = sGameControllerActivity.getClassLoader();
Class<?> controllerDelegate = null;
if (driveType == DRIVERTYPE_MOGA) {
if (mControllerMoga != null) {
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerMoga");
} else if (driveType == DRIVERTYPE_NIBIRU) {
if (mControllerNibiru != null) {
mControllerNibiru.onCreate(sGameControllerActivity);
mControllerNibiru.onResume();
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerNibiru");
} else if (driveType == DRIVERTYPE_OUYA) {
if (mControllerOuya != null) {
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerOuya");
}
GameControllerDelegate instance = (GameControllerDelegate)controllerDelegate.newInstance();
sGameControllerActivity.setGameControllerInstance(instance, driveType);
if (driveType == DRIVERTYPE_NIBIRU) {
Method method = controllerDelegate.getDeclaredMethod("onResume");
method.invoke(instance);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void setGameControllerInstance(GameControllerDelegate controllerDelegate, int driveType) {
if (driveType == DRIVERTYPE_NIBIRU) {
mControllerNibiru = controllerDelegate;
}else if (driveType == DRIVERTYPE_MOGA) {
mControllerMoga = controllerDelegate;
}
else if (driveType == DRIVERTYPE_OUYA) {
mControllerOuya = controllerDelegate;
}
controllerDelegate.setControllerEventListener(mControllerEventListener);
controllerDelegate.onCreate(sGameControllerActivity);
}
public GameControllerDelegate getGameControllerDelegate(int driveType){
if (driveType == DRIVERTYPE_NIBIRU) {
return mControllerNibiru;
}else if (driveType == DRIVERTYPE_MOGA) {
return mControllerMoga;
}
else if (driveType == DRIVERTYPE_OUYA) {
return mControllerOuya;
}
return null;
}
ControllerEventListener mControllerEventListener = new ControllerEventListener() {
@Override
public void onButtonEvent(String vendorName, int controller, int button,
boolean isPressed, float value, boolean isAnalog) {
GameControllerAdapter.onButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
}
@Override
public void onAxisEvent(String vendorName, int controller, int axisID,
float value, boolean isAnalog) {
GameControllerAdapter.onAxisEvent(vendorName, controller, axisID, value, isAnalog);
}
public static final int DRIVERTYPE_NIBIRU = 0;
public static final int DRIVERTYPE_MOGA = 1;
public static final int DRIVERTYPE_OUYA = 2;
public static final int DRIVERTYPE_STANDARD = 3;
public static final int DRIVERTYPE_UNKNOWN = 4;
// ===========================================================
// Fields
// ===========================================================
private static GameControllerActivity sGameControllerActivity;
private InputManagerCompat mInputManager = null;
protected GameControllerHelper mControllerHelper = null;
protected GameControllerDelegate mControllerNibiru = null;
protected GameControllerDelegate mControllerMoga = null;
protected GameControllerDelegate mControllerOuya = null;
public void connectController(int driveType){
try {
ClassLoader loader = sGameControllerActivity.getClassLoader();
Class<?> controllerDelegate = null;
if (driveType == DRIVERTYPE_MOGA) {
if (mControllerMoga != null) {
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerMoga");
} else if (driveType == DRIVERTYPE_NIBIRU) {
if (mControllerNibiru != null) {
mControllerNibiru.onCreate(sGameControllerActivity);
mControllerNibiru.onResume();
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerNibiru");
} else if (driveType == DRIVERTYPE_OUYA) {
if (mControllerOuya != null) {
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerOuya");
}
GameControllerDelegate instance = (GameControllerDelegate)controllerDelegate.newInstance();
sGameControllerActivity.setGameControllerInstance(instance, driveType);
if (driveType == DRIVERTYPE_NIBIRU) {
Method method = controllerDelegate.getDeclaredMethod("onResume");
method.invoke(instance);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void setGameControllerInstance(GameControllerDelegate controllerDelegate, int driveType) {
if (driveType == DRIVERTYPE_NIBIRU) {
mControllerNibiru = controllerDelegate;
}else if (driveType == DRIVERTYPE_MOGA) {
mControllerMoga = controllerDelegate;
}
else if (driveType == DRIVERTYPE_OUYA) {
mControllerOuya = controllerDelegate;
}
controllerDelegate.setControllerEventListener(mControllerEventListener);
controllerDelegate.onCreate(sGameControllerActivity);
}
public GameControllerDelegate getGameControllerDelegate(int driveType){
if (driveType == DRIVERTYPE_NIBIRU) {
return mControllerNibiru;
}else if (driveType == DRIVERTYPE_MOGA) {
return mControllerMoga;
}
else if (driveType == DRIVERTYPE_OUYA) {
return mControllerOuya;
}
return null;
}
ControllerEventListener mControllerEventListener = new ControllerEventListener() {
@Override
public void onButtonEvent(String vendorName, int controller, int button,
boolean isPressed, float value, boolean isAnalog) {
GameControllerAdapter.onButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
}
@Override
public void onAxisEvent(String vendorName, int controller, int axisID,
float value, boolean isAnalog) {
GameControllerAdapter.onAxisEvent(vendorName, controller, axisID, value, isAnalog);
}
@Override
public void onConnected(String vendorName, int controller) {
GameControllerAdapter.onConnected(vendorName, controller);
}
@Override
public void onConnected(String vendorName, int controller) {
GameControllerAdapter.onConnected(vendorName, controller);
}
@Override
public void onDisconnected(String vendorName, int controller) {
GameControllerAdapter.onDisconnected(vendorName, controller);
}
};
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sGameControllerActivity = this;
mInputManager = InputManagerCompat.Factory.getInputManager(this);
mInputManager.registerInputDeviceListener(this, null);
if (mControllerNibiru != null) {
mControllerNibiru.onCreate(this);
}
if (mControllerMoga != null) {
mControllerMoga.onCreate(this);
}
if (mControllerOuya != null) {
mControllerOuya.onCreate(this);
}
if (mControllerHelper == null) {
mControllerHelper = new GameControllerHelper(this);
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public void onDisconnected(String vendorName, int controller) {
GameControllerAdapter.onDisconnected(vendorName, controller);
}
};
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sGameControllerActivity = this;
mInputManager = InputManagerCompat.Factory.getInputManager(this);
mInputManager.registerInputDeviceListener(this, null);
if (mControllerNibiru != null) {
mControllerNibiru.onCreate(this);
}
if (mControllerMoga != null) {
mControllerMoga.onCreate(this);
}
if (mControllerOuya != null) {
mControllerOuya.onCreate(this);
}
if (mControllerHelper == null) {
mControllerHelper = new GameControllerHelper(this);
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchKeyEvent(event);
}
if (handled == false && mControllerMoga != null) {
handled |= mControllerMoga.dispatchKeyEvent(event);
}
if (handled == false && mControllerOuya != null) {
handled |= mControllerOuya.dispatchKeyEvent(event);
}
if (handled == false) {
handled |= mControllerHelper.dispatchKeyEvent(event);
}
return handled || super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchGenericMotionEvent(event);
}
if (handled == false && mControllerMoga != null) {
handled |= mControllerMoga.dispatchGenericMotionEvent(event);
}
if (handled == false && mControllerOuya != null) {
handled |= mControllerOuya.dispatchGenericMotionEvent(event);
}
if (handled == false) {
handled |= mControllerHelper.dispatchGenericMotionEvent(event);
}
return handled || super.dispatchGenericMotionEvent(event);
}
@Override
public void onInputDeviceAdded(int deviceId) {
Log.d(TAG,"onInputDeviceAdded:" + deviceId);
mControllerHelper.onInputDeviceAdded(deviceId);
}
/*
* This is an unusual case. Input devices don't typically change, but they
* certainly can --- for example a device may have different modes. We use
* this to make sure that the ship has an up-to-date InputDevice.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceChanged(int)
*/
@Override
public void onInputDeviceChanged(int deviceId) {
Log.w(TAG,"onInputDeviceChanged:" + deviceId);
}
/*
* Remove any ship associated with the ID.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceRemoved(int)
*/
@Override
public void onInputDeviceRemoved(int deviceId) {
Log.d(TAG,"onInputDeviceRemoved:" + deviceId);
mControllerHelper.onInputDeviceRemoved(deviceId);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchKeyEvent(event);
}
if (handled == false && mControllerMoga != null) {
handled |= mControllerMoga.dispatchKeyEvent(event);
}
if (handled == false && mControllerOuya != null) {
handled |= mControllerOuya.dispatchKeyEvent(event);
}
if (handled == false) {
handled |= mControllerHelper.dispatchKeyEvent(event);
}
return handled || super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchGenericMotionEvent(event);
}
if (handled == false && mControllerMoga != null) {
handled |= mControllerMoga.dispatchGenericMotionEvent(event);
}
if (handled == false && mControllerOuya != null) {
handled |= mControllerOuya.dispatchGenericMotionEvent(event);
}
if (handled == false) {
handled |= mControllerHelper.dispatchGenericMotionEvent(event);
}
return handled || super.dispatchGenericMotionEvent(event);
}
@Override
public void onInputDeviceAdded(int deviceId) {
Log.d(TAG,"onInputDeviceAdded:" + deviceId);
mControllerHelper.onInputDeviceAdded(deviceId);
}
/*
* This is an unusual case. Input devices don't typically change, but they
* certainly can --- for example a device may have different modes. We use
* this to make sure that the ship has an up-to-date InputDevice.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceChanged(int)
*/
@Override
public void onInputDeviceChanged(int deviceId) {
Log.w(TAG,"onInputDeviceChanged:" + deviceId);
}
/*
* Remove any ship associated with the ID.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceRemoved(int)
*/
@Override
public void onInputDeviceRemoved(int deviceId) {
Log.d(TAG,"onInputDeviceRemoved:" + deviceId);
mControllerHelper.onInputDeviceRemoved(deviceId);
}
@Override
protected void onResume() {
super.onResume();
if (mControllerNibiru != null) {
mControllerNibiru.onResume();
}
if (mControllerMoga != null) {
mControllerMoga.onResume();
}
if (mControllerOuya != null) {
mControllerOuya.onResume();
}
GameControllerHelper.gatherControllers(mControllerHelper.mGameController);
}
@Override
protected void onPause() {
if (mControllerNibiru != null) {
mControllerNibiru.onPause();
}
if (mControllerMoga != null) {
mControllerMoga.onPause();
}
if (mControllerOuya != null) {
mControllerOuya.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
if (mControllerNibiru != null) {
mControllerNibiru.onDestroy();
}
if (mControllerMoga != null) {
mControllerMoga.onDestroy();
}
if (mControllerOuya != null) {
mControllerOuya.onDestroy();
}
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
if (mControllerNibiru != null) {
mControllerNibiru.onResume();
}
if (mControllerMoga != null) {
mControllerMoga.onResume();
}
if (mControllerOuya != null) {
mControllerOuya.onResume();
}
GameControllerHelper.gatherControllers(mControllerHelper.mGameController);
}
@Override
protected void onPause() {
if (mControllerNibiru != null) {
mControllerNibiru.onPause();
}
if (mControllerMoga != null) {
mControllerMoga.onPause();
}
if (mControllerOuya != null) {
mControllerOuya.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
if (mControllerNibiru != null) {
mControllerNibiru.onDestroy();
}
if (mControllerMoga != null) {
mControllerMoga.onDestroy();
}
if (mControllerOuya != null) {
mControllerOuya.onDestroy();
}
super.onDestroy();
}
}

View File

@ -10,248 +10,248 @@ import android.view.MotionEvent;
public class GameControllerHelper {
public static final String StandardControllerName = "Standard";
SparseIntArray ControllerKeyMap;
private static final int AXIS_X = 0;
private static final int AXIS_Y = 1;
private static final int AXIS_Z = 11;
private static final int AXIS_RZ = 14;
private static final int AXIS_LTRIGGER = 17;
private static final int AXIS_RTRIGGER = 18;
public static final int AXIS_GAS = 22;
private static final int AXIS_BRAKE = 23;
private static final int AXIS_THROTTLE = 19;
public GameControllerHelper(GameControllerActivity activity){
ControllerKeyMap = new SparseIntArray(25);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_C, GameControllerDelegate.BUTTON_C);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Z, GameControllerDelegate.BUTTON_Z);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_UP, GameControllerDelegate.BUTTON_DPAD_UP);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN, GameControllerDelegate.BUTTON_DPAD_DOWN);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT, GameControllerDelegate.BUTTON_DPAD_LEFT);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT, GameControllerDelegate.BUTTON_DPAD_RIGHT);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_CENTER, GameControllerDelegate.BUTTON_DPAD_CENTER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL, GameControllerDelegate.BUTTON_LEFT_THUMBSTICK);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR, GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1, GameControllerDelegate.BUTTON_LEFT_SHOULDER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1, GameControllerDelegate.BUTTON_RIGHT_SHOULDER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, GameControllerDelegate.BUTTON_LEFT_TRIGGER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, GameControllerDelegate.BUTTON_RIGHT_TRIGGER);
ControllerKeyMap.put(AXIS_X, GameControllerDelegate.THUMBSTICK_LEFT_X);
ControllerKeyMap.put(AXIS_Y, GameControllerDelegate.THUMBSTICK_LEFT_Y);
ControllerKeyMap.put(AXIS_Z, GameControllerDelegate.THUMBSTICK_RIGHT_X);
ControllerKeyMap.put(AXIS_RZ, GameControllerDelegate.THUMBSTICK_RIGHT_Y);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, GameControllerDelegate.BUTTON_START);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, GameControllerDelegate.BUTTON_SELECT);
}
private float mOldLeftThumbstickX = 0.0f;
private float mOldLeftThumbstickY = 0.0f;
private float mOldRightThumbstickX = 0.0f;
private float mOldRightThumbstickY = 0.0f;
private float mOldLeftTrigger = 0.0f;
private float mOldRightTrigger = 0.0f;
private float mOldThrottle = 0.0f;
private float mOldBrake = 0.0f;
private float mOldGas = 0.0f;
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
int eventSource = event.getSource();
public static final String StandardControllerName = "Standard";
SparseIntArray ControllerKeyMap;
private static final int AXIS_X = 0;
private static final int AXIS_Y = 1;
private static final int AXIS_Z = 11;
private static final int AXIS_RZ = 14;
private static final int AXIS_LTRIGGER = 17;
private static final int AXIS_RTRIGGER = 18;
public static final int AXIS_GAS = 22;
private static final int AXIS_BRAKE = 23;
private static final int AXIS_THROTTLE = 19;
public GameControllerHelper(GameControllerActivity activity){
ControllerKeyMap = new SparseIntArray(25);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_C, GameControllerDelegate.BUTTON_C);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Z, GameControllerDelegate.BUTTON_Z);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_UP, GameControllerDelegate.BUTTON_DPAD_UP);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN, GameControllerDelegate.BUTTON_DPAD_DOWN);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT, GameControllerDelegate.BUTTON_DPAD_LEFT);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT, GameControllerDelegate.BUTTON_DPAD_RIGHT);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_CENTER, GameControllerDelegate.BUTTON_DPAD_CENTER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL, GameControllerDelegate.BUTTON_LEFT_THUMBSTICK);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR, GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1, GameControllerDelegate.BUTTON_LEFT_SHOULDER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1, GameControllerDelegate.BUTTON_RIGHT_SHOULDER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, GameControllerDelegate.BUTTON_LEFT_TRIGGER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, GameControllerDelegate.BUTTON_RIGHT_TRIGGER);
ControllerKeyMap.put(AXIS_X, GameControllerDelegate.THUMBSTICK_LEFT_X);
ControllerKeyMap.put(AXIS_Y, GameControllerDelegate.THUMBSTICK_LEFT_Y);
ControllerKeyMap.put(AXIS_Z, GameControllerDelegate.THUMBSTICK_RIGHT_X);
ControllerKeyMap.put(AXIS_RZ, GameControllerDelegate.THUMBSTICK_RIGHT_Y);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, GameControllerDelegate.BUTTON_START);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, GameControllerDelegate.BUTTON_SELECT);
}
private float mOldLeftThumbstickX = 0.0f;
private float mOldLeftThumbstickY = 0.0f;
private float mOldRightThumbstickX = 0.0f;
private float mOldRightThumbstickY = 0.0f;
private float mOldLeftTrigger = 0.0f;
private float mOldRightTrigger = 0.0f;
private float mOldThrottle = 0.0f;
private float mOldBrake = 0.0f;
private float mOldGas = 0.0f;
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
int eventSource = event.getSource();
if ( ((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
if(mGameController.get(deviceId) == null){
gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
float newAXIS_LX = event.getAxisValue(AXIS_X);
if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true);
mOldLeftThumbstickX = newAXIS_LX;
handled = true;
}
float newAXIS_LY = event.getAxisValue(AXIS_Y);
if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true);
mOldLeftThumbstickY = newAXIS_LY;
handled = true;
}
float newAXIS_RX = event.getAxisValue(AXIS_Z);
if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true);
mOldRightThumbstickX = newAXIS_RX;
handled = true;
}
float newAXIS_RY = event.getAxisValue(AXIS_RZ);
if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true);
mOldRightThumbstickY = newAXIS_RY;
handled = true;
}
float newAXIS_LTRIGGER = event.getAxisValue(AXIS_LTRIGGER);
if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_LTRIGGER, true);
mOldLeftTrigger = newAXIS_LTRIGGER;
handled = true;
}
float newAXIS_RTRIGGER = event.getAxisValue(AXIS_RTRIGGER);
if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_RTRIGGER, true);
mOldRightTrigger = newAXIS_RTRIGGER;
handled = true;
}
float newAXIS_BRAKE = event.getAxisValue(AXIS_BRAKE);
if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_BRAKE, true);
mOldBrake = newAXIS_BRAKE;
handled = true;
}
float newAXIS_THROTTLE = event.getAxisValue(AXIS_THROTTLE);
if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_THROTTLE, true);
mOldThrottle = newAXIS_THROTTLE;
handled = true;
}
float newAXIS_GAS = event.getAxisValue(AXIS_GAS);
if (Float.compare(newAXIS_GAS , mOldGas) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_GAS, true);
mOldGas = newAXIS_GAS;
handled = true;
}
}
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
if(mGameController.get(deviceId) == null){
gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
float newAXIS_LX = event.getAxisValue(AXIS_X);
if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true);
mOldLeftThumbstickX = newAXIS_LX;
handled = true;
}
float newAXIS_LY = event.getAxisValue(AXIS_Y);
if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true);
mOldLeftThumbstickY = newAXIS_LY;
handled = true;
}
float newAXIS_RX = event.getAxisValue(AXIS_Z);
if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true);
mOldRightThumbstickX = newAXIS_RX;
handled = true;
}
float newAXIS_RY = event.getAxisValue(AXIS_RZ);
if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true);
mOldRightThumbstickY = newAXIS_RY;
handled = true;
}
float newAXIS_LTRIGGER = event.getAxisValue(AXIS_LTRIGGER);
if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_LTRIGGER, true);
mOldLeftTrigger = newAXIS_LTRIGGER;
handled = true;
}
float newAXIS_RTRIGGER = event.getAxisValue(AXIS_RTRIGGER);
if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_RTRIGGER, true);
mOldRightTrigger = newAXIS_RTRIGGER;
handled = true;
}
float newAXIS_BRAKE = event.getAxisValue(AXIS_BRAKE);
if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_BRAKE, true);
mOldBrake = newAXIS_BRAKE;
handled = true;
}
float newAXIS_THROTTLE = event.getAxisValue(AXIS_THROTTLE);
if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_THROTTLE, true);
mOldThrottle = newAXIS_THROTTLE;
handled = true;
}
float newAXIS_GAS = event.getAxisValue(AXIS_GAS);
if (Float.compare(newAXIS_GAS , mOldGas) != 0) {
GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_GAS, true);
mOldGas = newAXIS_GAS;
handled = true;
}
}
}
return handled;
}
private static SparseArray<ArrayList<Integer>> mControllerExtendKey = new SparseArray<ArrayList<Integer>>();
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
int eventSource = event.getSource();
int keyCode = event.getKeyCode();
int controllerKey = ControllerKeyMap.get(keyCode);
if (((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
if(mGameController.get(deviceId) == null){
gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
if (controllerKey == 0) {
if (mControllerExtendKey.get(deviceId) != null && mControllerExtendKey.get(deviceId).contains(keyCode)) {
controllerKey = keyCode;
}else {
return false;
}
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
handled = true;
GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,true, 1.0f, false);
}else if (action == KeyEvent.ACTION_UP) {
handled = true;
GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,false, 0.0f, false);
}
}
return handled;
return handled;
}
private static SparseArray<ArrayList<Integer>> mControllerExtendKey = new SparseArray<ArrayList<Integer>>();
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
int eventSource = event.getSource();
int keyCode = event.getKeyCode();
int controllerKey = ControllerKeyMap.get(keyCode);
if (((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
if(mGameController.get(deviceId) == null){
gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
if (controllerKey == 0) {
if (mControllerExtendKey.get(deviceId) != null && mControllerExtendKey.get(deviceId).contains(keyCode)) {
controllerKey = keyCode;
}else {
return false;
}
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
handled = true;
GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,true, 1.0f, false);
}else if (action == KeyEvent.ACTION_UP) {
handled = true;
GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,false, 0.0f, false);
}
}
return handled;
}
public static void receiveExternalKeyEvent(int deviceId,int externalKeyCode,boolean receive) {
if (receive) {
if (mControllerExtendKey.get(deviceId) == null) {
mControllerExtendKey.put(deviceId, new ArrayList<Integer>());
}
mControllerExtendKey.get(deviceId).add(externalKeyCode);
} else {
if (mControllerExtendKey.get(deviceId) != null) {
mControllerExtendKey.get(deviceId).remove(Integer.valueOf(externalKeyCode));
}
}
}
SparseArray<String> mGameController = new SparseArray<String>();
void onInputDeviceAdded(int deviceId){
try {
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
String deviceName = device.getName();
mGameController.append(deviceId, deviceName);
GameControllerAdapter.onConnected(deviceName, deviceId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
void onInputDeviceChanged(int deviceId){
gatherControllers(mGameController);
}
void onInputDeviceRemoved(int deviceId) {
if (mGameController.get(deviceId) != null) {
GameControllerAdapter.onDisconnected(mGameController.get(deviceId), deviceId);
mGameController.delete(deviceId);
}
}
static void gatherControllers(SparseArray<String> controllers){
int controllerCount = controllers.size();
for (int i = 0; i < controllerCount; i++) {
try {
int controllerDeveceId = controllers.keyAt(i);
InputDevice device = InputDevice.getDevice(controllerDeveceId);
if (device == null) {
GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId);
controllers.delete(controllerDeveceId);
}
} catch (Exception e) {
int controllerDeveceId = controllers.keyAt(i);
GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId);
controllers.delete(controllerDeveceId);
e.printStackTrace();
}
}
}
public static void receiveExternalKeyEvent(int deviceId,int externalKeyCode,boolean receive) {
if (receive) {
if (mControllerExtendKey.get(deviceId) == null) {
mControllerExtendKey.put(deviceId, new ArrayList<Integer>());
}
mControllerExtendKey.get(deviceId).add(externalKeyCode);
} else {
if (mControllerExtendKey.get(deviceId) != null) {
mControllerExtendKey.get(deviceId).remove(Integer.valueOf(externalKeyCode));
}
}
}
SparseArray<String> mGameController = new SparseArray<String>();
void onInputDeviceAdded(int deviceId){
try {
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
String deviceName = device.getName();
mGameController.append(deviceId, deviceName);
GameControllerAdapter.onConnected(deviceName, deviceId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
void onInputDeviceChanged(int deviceId){
gatherControllers(mGameController);
}
void onInputDeviceRemoved(int deviceId) {
if (mGameController.get(deviceId) != null) {
GameControllerAdapter.onDisconnected(mGameController.get(deviceId), deviceId);
mGameController.delete(deviceId);
}
}
static void gatherControllers(SparseArray<String> controllers){
int controllerCount = controllers.size();
for (int i = 0; i < controllerCount; i++) {
try {
int controllerDeveceId = controllers.keyAt(i);
InputDevice device = InputDevice.getDevice(controllerDeveceId);
if (device == null) {
GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId);
controllers.delete(controllerDeveceId);
}
} catch (Exception e) {
int controllerDeveceId = controllers.keyAt(i);
GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId);
controllers.delete(controllerDeveceId);
e.printStackTrace();
}
}
}
}

View File

@ -14,205 +14,205 @@ import com.bda.controller.StateEvent;
public class GameControllerMoga implements ControllerListener, GameControllerDelegate {
private static final String mVendorName = "Moga";
private float mOldLeftThumbstickX = 0.0f;
private float mOldLeftThumbstickY = 0.0f;
private float mOldRightThumbstickX = 0.0f;
private float mOldRightThumbstickY = 0.0f;
private float mOldLeftTrigger = 0.0f;
private float mOldRightTrigger = 0.0f;
private static final String mVendorName = "Moga";
private float mOldLeftThumbstickX = 0.0f;
private float mOldLeftThumbstickY = 0.0f;
private float mOldRightThumbstickX = 0.0f;
private float mOldRightThumbstickY = 0.0f;
private float mOldLeftTrigger = 0.0f;
private float mOldRightTrigger = 0.0f;
private SparseIntArray mKeyMap = null;
private SparseIntArray mKeyMap = null;
public GameControllerMoga() {
mKeyMap = new SparseIntArray(20);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1,
GameControllerDelegate.BUTTON_LEFT_SHOULDER);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1,
GameControllerDelegate.BUTTON_RIGHT_SHOULDER);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2,
GameControllerDelegate.BUTTON_LEFT_TRIGGER);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2,
GameControllerDelegate.BUTTON_RIGHT_TRIGGER);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_UP,
GameControllerDelegate.BUTTON_DPAD_UP);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN,
GameControllerDelegate.BUTTON_DPAD_DOWN);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT,
GameControllerDelegate.BUTTON_DPAD_LEFT);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT,
GameControllerDelegate.BUTTON_DPAD_RIGHT);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START,
GameControllerDelegate.BUTTON_START);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT,
GameControllerDelegate.BUTTON_SELECT);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START,
GameControllerDelegate.BUTTON_START);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL,
GameControllerDelegate.BUTTON_LEFT_THUMBSTICK);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR,
GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK);
}
public void onKeyEvent(KeyEvent event) {
int keycode = event.getKeyCode();
if (keycode == KeyEvent.KEYCODE_BUTTON_L2
|| keycode == KeyEvent.KEYCODE_BUTTON_R2) {
return;
}
boolean isPressed = event.getAction() == KeyEvent.ACTION_DOWN;
boolean isAnalog = false;
public GameControllerMoga() {
mKeyMap = new SparseIntArray(20);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1,
GameControllerDelegate.BUTTON_LEFT_SHOULDER);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1,
GameControllerDelegate.BUTTON_RIGHT_SHOULDER);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2,
GameControllerDelegate.BUTTON_LEFT_TRIGGER);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2,
GameControllerDelegate.BUTTON_RIGHT_TRIGGER);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_UP,
GameControllerDelegate.BUTTON_DPAD_UP);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN,
GameControllerDelegate.BUTTON_DPAD_DOWN);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT,
GameControllerDelegate.BUTTON_DPAD_LEFT);
mKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT,
GameControllerDelegate.BUTTON_DPAD_RIGHT);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START,
GameControllerDelegate.BUTTON_START);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT,
GameControllerDelegate.BUTTON_SELECT);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START,
GameControllerDelegate.BUTTON_START);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL,
GameControllerDelegate.BUTTON_LEFT_THUMBSTICK);
mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR,
GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK);
}
public void onKeyEvent(KeyEvent event) {
int keycode = event.getKeyCode();
if (keycode == KeyEvent.KEYCODE_BUTTON_L2
|| keycode == KeyEvent.KEYCODE_BUTTON_R2) {
return;
}
boolean isPressed = event.getAction() == KeyEvent.ACTION_DOWN;
boolean isAnalog = false;
if (keycode == KeyEvent.KEYCODE_BUTTON_THUMBL
|| keycode == KeyEvent.KEYCODE_BUTTON_THUMBR) {
isAnalog = true;
}
if (keycode == KeyEvent.KEYCODE_BUTTON_THUMBL
|| keycode == KeyEvent.KEYCODE_BUTTON_THUMBR) {
isAnalog = true;
}
if (mKeyMap.get(keycode, Integer.MIN_VALUE) != Integer.MIN_VALUE && mControllerEventListener != null) {
mControllerEventListener.onButtonEvent(mVendorName,
event.getControllerId(), mKeyMap.get(keycode), isPressed,
isPressed ? 1.0f : 0.0f, isAnalog);
}
}
if (mKeyMap.get(keycode, Integer.MIN_VALUE) != Integer.MIN_VALUE && mControllerEventListener != null) {
mControllerEventListener.onButtonEvent(mVendorName,
event.getControllerId(), mKeyMap.get(keycode), isPressed,
isPressed ? 1.0f : 0.0f, isAnalog);
}
}
@Override
public void onMotionEvent(MotionEvent event) {
if (mControllerEventListener == null) {
return;
}
int controllerId = event.getControllerId();
float newLeftThumbstickX = event.getAxisValue(MotionEvent.AXIS_X);
if (newLeftThumbstickX != mOldLeftThumbstickX) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_LEFT_X,
newLeftThumbstickX, true);
mOldLeftThumbstickX = newLeftThumbstickX;
}
@Override
public void onMotionEvent(MotionEvent event) {
if (mControllerEventListener == null) {
return;
}
int controllerId = event.getControllerId();
float newLeftThumbstickX = event.getAxisValue(MotionEvent.AXIS_X);
if (newLeftThumbstickX != mOldLeftThumbstickX) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_LEFT_X,
newLeftThumbstickX, true);
mOldLeftThumbstickX = newLeftThumbstickX;
}
float newLeftThumbstickY = event.getAxisValue(MotionEvent.AXIS_Y);
if (newLeftThumbstickY != mOldLeftThumbstickY) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_LEFT_Y,
newLeftThumbstickY, true);
mOldLeftThumbstickY = newLeftThumbstickY;
}
float newLeftThumbstickY = event.getAxisValue(MotionEvent.AXIS_Y);
if (newLeftThumbstickY != mOldLeftThumbstickY) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_LEFT_Y,
newLeftThumbstickY, true);
mOldLeftThumbstickY = newLeftThumbstickY;
}
float newRightThumbstickX = event.getAxisValue(MotionEvent.AXIS_Z);
if (newRightThumbstickX != mOldRightThumbstickX) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_RIGHT_X,
newRightThumbstickX, true);
mOldRightThumbstickX = newRightThumbstickX;
}
float newRightThumbstickX = event.getAxisValue(MotionEvent.AXIS_Z);
if (newRightThumbstickX != mOldRightThumbstickX) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_RIGHT_X,
newRightThumbstickX, true);
mOldRightThumbstickX = newRightThumbstickX;
}
float newRightThumbstickY = event.getAxisValue(MotionEvent.AXIS_RZ);
if (newRightThumbstickY != mOldRightThumbstickY) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_RIGHT_Y,
newRightThumbstickY, true);
mOldRightThumbstickY = newRightThumbstickY;
}
float newLeftTrigger = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
if (newLeftTrigger != mOldLeftTrigger) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.BUTTON_LEFT_TRIGGER,
newLeftTrigger, true);
mOldLeftTrigger = newLeftTrigger;
}
float newRightTrigger = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
if (newRightTrigger != mOldRightTrigger) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.BUTTON_RIGHT_TRIGGER,
newRightTrigger, true);
mOldRightTrigger = newRightTrigger;
}
}
float newRightThumbstickY = event.getAxisValue(MotionEvent.AXIS_RZ);
if (newRightThumbstickY != mOldRightThumbstickY) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.THUMBSTICK_RIGHT_Y,
newRightThumbstickY, true);
mOldRightThumbstickY = newRightThumbstickY;
}
float newLeftTrigger = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
if (newLeftTrigger != mOldLeftTrigger) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.BUTTON_LEFT_TRIGGER,
newLeftTrigger, true);
mOldLeftTrigger = newLeftTrigger;
}
float newRightTrigger = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
if (newRightTrigger != mOldRightTrigger) {
mControllerEventListener.onAxisEvent(mVendorName,
controllerId,
GameControllerDelegate.BUTTON_RIGHT_TRIGGER,
newRightTrigger, true);
mOldRightTrigger = newRightTrigger;
}
}
@Override
public void onStateEvent(StateEvent event) {
if (mControllerEventListener != null) {
switch (event.getState()) {
case StateEvent.STATE_CONNECTION:
switch (event.getAction()) {
case StateEvent.ACTION_DISCONNECTED:
// disconnected from controller
mControllerEventListener.onDisconnected(mVendorName,
event.getControllerId());
break;
case StateEvent.ACTION_CONNECTED:
// connected to controller
mControllerEventListener.onConnected(mVendorName,
event.getControllerId());
break;
case StateEvent.ACTION_CONNECTING:
// attempting to connect to controller
break;
}
break;
case StateEvent.STATE_POWER_LOW:
if (event.getAction() == StateEvent.ACTION_TRUE) {
// controller has entered low power state
} else {
// controller has entered normal power state
}
break;
}
}
}
@Override
public void onStateEvent(StateEvent event) {
if (mControllerEventListener != null) {
switch (event.getState()) {
case StateEvent.STATE_CONNECTION:
switch (event.getAction()) {
case StateEvent.ACTION_DISCONNECTED:
// disconnected from controller
mControllerEventListener.onDisconnected(mVendorName,
event.getControllerId());
break;
case StateEvent.ACTION_CONNECTED:
// connected to controller
mControllerEventListener.onConnected(mVendorName,
event.getControllerId());
break;
case StateEvent.ACTION_CONNECTING:
// attempting to connect to controller
break;
}
break;
case StateEvent.STATE_POWER_LOW:
if (event.getAction() == StateEvent.ACTION_TRUE) {
// controller has entered low power state
} else {
// controller has entered normal power state
}
break;
}
}
}
private Controller mController = null;
private Controller mController = null;
public void onCreate(Context context) {
mController = Controller.getInstance(context);
mController.init();
mController.setListener(this, new Handler());
}
public void onCreate(Context context) {
mController = Controller.getInstance(context);
mController.init();
mController.setListener(this, new Handler());
}
public void onPause() {
mController.onPause();
}
public void onPause() {
mController.onPause();
}
public void onResume() {
mController.onResume();
}
public void onResume() {
mController.onResume();
}
public void onDestroy() {
mController.exit();
}
private ControllerEventListener mControllerEventListener;
@Override
public void setControllerEventListener(ControllerEventListener listener) {
mControllerEventListener = listener;
}
public void onDestroy() {
mController.exit();
}
private ControllerEventListener mControllerEventListener;
@Override
public void setControllerEventListener(ControllerEventListener listener) {
mControllerEventListener = listener;
}
@Override
public boolean dispatchKeyEvent(android.view.KeyEvent event) {
return false;
}
@Override
public boolean dispatchKeyEvent(android.view.KeyEvent event) {
return false;
}
@Override
public boolean dispatchGenericMotionEvent(android.view.MotionEvent event) {
return false;
}
@Override
public boolean dispatchGenericMotionEvent(android.view.MotionEvent event) {
return false;
}
}

View File

@ -26,16 +26,16 @@ import android.view.MotionEvent;
public class GameControllerNibiru implements OnControllerSeviceListener, OnKeyListener,
OnSimpleStickListener, OnAccListener, OnGyroListener, OnStateListener, GameControllerDelegate {
private static final String TAG = "NibiruTag";
private Context mContext;
private SparseIntArray mKeyMap;
private ControllerEventListener mControllerEventListener = null;
private ControllerService mControllerService = null;
public GameControllerNibiru() {
mKeyMap = new SparseIntArray(20);
private static final String TAG = "NibiruTag";
private Context mContext;
private SparseIntArray mKeyMap;
private ControllerEventListener mControllerEventListener = null;
private ControllerService mControllerService = null;
public GameControllerNibiru() {
mKeyMap = new SparseIntArray(20);
mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_A , GameControllerDelegate.BUTTON_A);
mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_B , GameControllerDelegate.BUTTON_B);
mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_X , GameControllerDelegate.BUTTON_X);
@ -52,188 +52,188 @@ OnSimpleStickListener, OnAccListener, OnGyroListener, OnStateListener, GameContr
mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_SELECT , GameControllerDelegate.BUTTON_SELECT);
mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_THUMBL , GameControllerDelegate.BUTTON_LEFT_THUMBSTICK);
mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_THUMBR , GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK);
}
@Override
public void setControllerEventListener(ControllerEventListener listener) {
mControllerEventListener = listener;
}
public void onCreate(Context context) {
mContext = context;
mControllerService = Controller.getControllerService();
if (mControllerService != null) {
mControllerService.setControllerServiceListener(this);
mControllerService.setStateListener(this);
mControllerService.setKeyListener(this);
mControllerService.setSimpleStickListener(this);
//mControllerService.setAccListener(this);
//mControllerService.setGyroListener(this);
mControllerService.setEnableLR2(true);
mControllerService.setAutoKeyUpMode(false);
mControllerService.checkNibiruInstall(mContext, false);
}
}
public void onPause() {
if (mControllerService != null) {
mControllerService.setEnable(false);
}
}
public void onResume() {
if (mControllerService != null) {
if (mControllerService.isServiceEnable()) {
//onControllerServiceReady(true);
} else {
if (mControllerService.checkNibiruInstall(mContext, false)) {
try {
mControllerService.register(mContext);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
mControllerService.setEnable(true);
}
}
public void onDestroy() {
if( mControllerService != null ){
mControllerService.unregister();
}
}
}
@Override
public void setControllerEventListener(ControllerEventListener listener) {
mControllerEventListener = listener;
}
public void onCreate(Context context) {
mContext = context;
mControllerService = Controller.getControllerService(context);
if (mControllerService != null) {
mControllerService.setControllerServiceListener(this);
mControllerService.setStateListener(this);
mControllerService.setKeyListener(this);
mControllerService.setSimpleStickListener(this);
//mControllerService.setAccListener(this);
//mControllerService.setGyroListener(this);
mControllerService.setEnableL2R2(true);
mControllerService.setAutoKeyUpMode(false);
mControllerService.checkNibiruInstall(mContext, false);
}
}
public void onPause() {
if (mControllerService != null) {
mControllerService.setEnable(false);
}
}
public void onResume() {
if (mControllerService != null) {
if (mControllerService.isServiceEnable()) {
//onControllerServiceReady(true);
} else {
if (mControllerService.checkNibiruInstall(mContext, false)) {
try {
mControllerService.register(mContext);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
mControllerService.setEnable(true);
}
}
public void onDestroy() {
if( mControllerService != null ){
mControllerService.unregister();
}
}
@Override
public void onControllerServiceReady(boolean isSucc) {
if( isSucc )
{
if( !mControllerService.hasDeviceConnected() ){
Bundle bun = new Bundle();
bun.putBoolean(ControllerService.FLAG_IS_SHOW_GAMEPAD_TIP, false);
try {
mControllerService.showDeviceManagerUI(mContext, bun);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onControllerServiceReady(boolean isSucc) {
if( isSucc )
{
if( !mControllerService.hasDeviceConnected() ){
Bundle bun = new Bundle();
bun.putBoolean(ControllerService.FLAG_IS_SHOW_GAMEPAD_TIP, false);
/*try {
mControllerService.showDeviceManagerUI(mContext, bun);
} catch (ControllerServiceException e) {
e.printStackTrace();
}*/
}
}
}
@Override
public void onControllerKeyDown(int playerOrder, int keyCode, ControllerKeyEvent event) {
if (mKeyMap.get(keyCode) == 0) {
Log.e(TAG, "Didn't map the key: " + keyCode);
return;
}
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(),
mKeyMap.get(keyCode), true, 1.0f, false);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onControllerKeyDown(int playerOrder, int keyCode, ControllerKeyEvent event) {
if (mKeyMap.get(keyCode) == 0) {
Log.e(TAG, "Didn't map the key: " + keyCode);
return;
}
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(),
mKeyMap.get(keyCode), true, 1.0f, false);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onControllerKeyUp(int playerOrder, int keyCode, ControllerKeyEvent event) {
if (mKeyMap.get(keyCode) == 0) {
Log.e(TAG, "Didn't map the key: " + keyCode);
return;
}
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(),
mKeyMap.get(keyCode), false, 0.0f, false);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onControllerKeyUp(int playerOrder, int keyCode, ControllerKeyEvent event) {
if (mKeyMap.get(keyCode) == 0) {
Log.e(TAG, "Didn't map the key: " + keyCode);
return;
}
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(),
mKeyMap.get(keyCode), false, 0.0f, false);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onLeftStickChanged(int playerOrder, float x, float y) {
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
String deviceName = controllerDevice.getDeviceName();
int deviceId = controllerDevice.getDeviceId();
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_LEFT_X, x, true);
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_LEFT_Y, y, true);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onLeftStickChanged(int playerOrder, float x, float y) {
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
String deviceName = controllerDevice.getDeviceName();
int deviceId = controllerDevice.getDeviceId();
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_LEFT_X, x, true);
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_LEFT_Y, y, true);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onRightStickChanged(int playerOrder, float x, float y) {
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
String deviceName = controllerDevice.getDeviceName();
int deviceId = controllerDevice.getDeviceId();
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_RIGHT_X, x, true);
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_RIGHT_Y, y, true);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onControllerStateChanged(int playerOrder, int state, ControllerDevice device) {
if (mControllerEventListener != null) {
if (state == ControllerDevice.STATE_CONN)
{
mControllerEventListener.onConnected(device.getDeviceName(), device.getDeviceId());
}
else if (state == ControllerDevice.STATE_DISCONN)
{
mControllerEventListener.onDisconnected(device.getDeviceName(), device.getDeviceId());
}
}
}
@Override
public void onRightStickChanged(int playerOrder, float x, float y) {
if (mControllerEventListener != null) {
try {
ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder);
String deviceName = controllerDevice.getDeviceName();
int deviceId = controllerDevice.getDeviceId();
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_RIGHT_X, x, true);
mControllerEventListener.onAxisEvent(deviceName, deviceId,
GameControllerDelegate.THUMBSTICK_RIGHT_Y, y, true);
} catch (ControllerServiceException e) {
e.printStackTrace();
}
}
}
@Override
public void onControllerStateChanged(int playerOrder, int state, ControllerDevice device) {
if (mControllerEventListener != null) {
if (state == ControllerDevice.STATE_CONN)
{
mControllerEventListener.onConnected(device.getDeviceName(), device.getDeviceId());
}
else if (state == ControllerDevice.STATE_DISCONN)
{
mControllerEventListener.onDisconnected(device.getDeviceName(), device.getDeviceId());
}
}
}
public boolean dispatchGenericMotionEvent(MotionEvent event){
return mControllerService.handleExternalInput(event);
}
public boolean dispatchKeyEvent(KeyEvent event){
return mControllerService.handleExternalInput(event);
}
@Override
public void onControllerAccEvent(int playerOrder, AccEvent event) {
}
public boolean dispatchGenericMotionEvent(MotionEvent event){
return mControllerService.handleExternalInput(event);
}
public boolean dispatchKeyEvent(KeyEvent event){
return mControllerService.handleExternalInput(event);
}
@Override
public void onControllerAccEvent(int playerOrder, AccEvent event) {
}
@Override
public void onControllerGyroEvent(int playerOrder, GyroEvent event) {
}
@Override
public void onControllerGyroEvent(int playerOrder, GyroEvent event) {
}
@Override
public void onBluetoothStateChanged(int state) {
Log.d(TAG, "onBluetoothStateChanged:"+state);
}
@Override
public void onBluetoothStateChanged(int state) {
Log.d(TAG, "onBluetoothStateChanged:"+state);
}
}

View File

@ -11,17 +11,17 @@ import android.view.KeyEvent;
import android.view.MotionEvent;
public class GameControllerOuya implements GameControllerDelegate{
private SparseIntArray mKeyMap;
private SparseArray<String> mGameController = new SparseArray<String>();
public GameControllerOuya(){
mKeyMap = new SparseIntArray(20);
mKeyMap.put(OuyaController.BUTTON_A, GameControllerDelegate.BUTTON_B);
mKeyMap.put(OuyaController.BUTTON_O, GameControllerDelegate.BUTTON_A);
mKeyMap.put(OuyaController.BUTTON_U, GameControllerDelegate.BUTTON_X);
mKeyMap.put(OuyaController.BUTTON_Y, GameControllerDelegate.BUTTON_Y);
private SparseIntArray mKeyMap;
private SparseArray<String> mGameController = new SparseArray<String>();
public GameControllerOuya(){
mKeyMap = new SparseIntArray(20);
mKeyMap.put(OuyaController.BUTTON_A, GameControllerDelegate.BUTTON_B);
mKeyMap.put(OuyaController.BUTTON_O, GameControllerDelegate.BUTTON_A);
mKeyMap.put(OuyaController.BUTTON_U, GameControllerDelegate.BUTTON_X);
mKeyMap.put(OuyaController.BUTTON_Y, GameControllerDelegate.BUTTON_Y);
mKeyMap.put(OuyaController.BUTTON_DPAD_DOWN, GameControllerDelegate.BUTTON_DPAD_DOWN);
mKeyMap.put(OuyaController.BUTTON_DPAD_LEFT, GameControllerDelegate.BUTTON_DPAD_LEFT);
mKeyMap.put(OuyaController.BUTTON_DPAD_RIGHT, GameControllerDelegate.BUTTON_DPAD_RIGHT);
@ -34,150 +34,142 @@ public class GameControllerOuya implements GameControllerDelegate{
}
public void onCreate(Context context) {
OuyaController.init(context);
/*GameControllerAdapter.addRunnableToFrameStartList(new Runnable() {
@Override
public void run() {
OuyaController.startOfFrame();
}
});*/
OuyaController.init(context);
}
private float mOldLeftThumbstickX = 0.0f;
private float mOldLeftThumbstickY = 0.0f;
private float mOldRightThumbstickX = 0.0f;
private float mOldRightThumbstickY = 0.0f;
private float mOldLeftThumbstickY = 0.0f;
private float mOldRightThumbstickX = 0.0f;
private float mOldRightThumbstickY = 0.0f;
private float mOldLeftTrigger = 0.0f;
private float mOldRightTrigger = 0.0f;
private float mOldRightTrigger = 0.0f;
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = OuyaController.onGenericMotionEvent(event);
if (handled && mControllerEventListener != null)
{
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
OuyaController c = OuyaController.getControllerByDeviceId(deviceId);
if (mGameController.get(deviceId) == null) {
GameControllerHelper.gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
float newLeftTrigger = c.getAxisValue(OuyaController.AXIS_L2);
if (Float.compare(newLeftTrigger, mOldLeftTrigger) != 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newLeftTrigger, true);
mOldLeftTrigger = newLeftTrigger;
}
float newRightTrigger = c.getAxisValue(OuyaController.AXIS_R2);
if (Float.compare(newRightTrigger, mOldRightTrigger) != 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newRightTrigger, true);
mOldRightTrigger = newRightTrigger;
}
float newLeftThumbstickX = c.getAxisValue(OuyaController.AXIS_LS_X);
if (Float.compare(newLeftThumbstickX, mOldLeftThumbstickX) != 0) {
if (Float.compare(newLeftThumbstickX, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newLeftThumbstickX, true);
}
mOldLeftThumbstickX = newLeftThumbstickX;
}
float newLeftThumbstickY = c.getAxisValue(OuyaController.AXIS_LS_Y);
if (Float.compare(newLeftThumbstickY, mOldLeftThumbstickY) != 0) {
if (Float.compare(newLeftThumbstickY, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newLeftThumbstickY, true);
}
mOldLeftThumbstickY = newLeftThumbstickY;
}
float newRightThumbstickX = c.getAxisValue(OuyaController.AXIS_RS_X);
if (Float.compare(newRightThumbstickX, mOldRightThumbstickX) != 0) {
if (Float.compare(newRightThumbstickX, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newRightThumbstickX, true);
}
mOldRightThumbstickX = newRightThumbstickX;
}
float newRightThumbstickY = c.getAxisValue(OuyaController.AXIS_RS_Y);
if (Float.compare(newRightThumbstickY, mOldRightThumbstickY) != 0) {
if (Float.compare(newRightThumbstickY, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newRightThumbstickY, true);
}
mOldRightThumbstickY = newRightThumbstickY;
}
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
OuyaController c = OuyaController.getControllerByDeviceId(deviceId);
if (mGameController.get(deviceId) == null) {
GameControllerHelper.gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
float newLeftTrigger = c.getAxisValue(OuyaController.AXIS_L2);
if (Float.compare(newLeftTrigger, mOldLeftTrigger) != 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newLeftTrigger, true);
mOldLeftTrigger = newLeftTrigger;
}
float newRightTrigger = c.getAxisValue(OuyaController.AXIS_R2);
if (Float.compare(newRightTrigger, mOldRightTrigger) != 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newRightTrigger, true);
mOldRightTrigger = newRightTrigger;
}
float newLeftThumbstickX = c.getAxisValue(OuyaController.AXIS_LS_X);
if (Float.compare(newLeftThumbstickX, mOldLeftThumbstickX) != 0) {
if (Float.compare(newLeftThumbstickX, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newLeftThumbstickX, true);
}
mOldLeftThumbstickX = newLeftThumbstickX;
}
float newLeftThumbstickY = c.getAxisValue(OuyaController.AXIS_LS_Y);
if (Float.compare(newLeftThumbstickY, mOldLeftThumbstickY) != 0) {
if (Float.compare(newLeftThumbstickY, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newLeftThumbstickY, true);
}
mOldLeftThumbstickY = newLeftThumbstickY;
}
float newRightThumbstickX = c.getAxisValue(OuyaController.AXIS_RS_X);
if (Float.compare(newRightThumbstickX, mOldRightThumbstickX) != 0) {
if (Float.compare(newRightThumbstickX, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newRightThumbstickX, true);
}
mOldRightThumbstickX = newRightThumbstickX;
}
float newRightThumbstickY = c.getAxisValue(OuyaController.AXIS_RS_Y);
if (Float.compare(newRightThumbstickY, mOldRightThumbstickY) != 0) {
if (Float.compare(newRightThumbstickY, 0.0f) == 0) {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, 0.0f, true);
}else {
mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newRightThumbstickY, true);
}
mOldRightThumbstickY = newRightThumbstickY;
}
}
return handled;
}
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
int action = event.getAction();
int keyCode = event.getKeyCode();
if (action == KeyEvent.ACTION_DOWN) {
handled = OuyaController.onKeyDown(keyCode, event);
}
else if (action == KeyEvent.ACTION_UP) {
handled = OuyaController.onKeyUp(keyCode, event);
}
if (handled && mControllerEventListener != null) {
boolean isAnalog = false;
if (keyCode == KeyEvent.KEYCODE_BUTTON_THUMBL || keyCode == KeyEvent.KEYCODE_BUTTON_THUMBR){
isAnalog = true;
}
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
if (mGameController.get(deviceId) == null) {
GameControllerHelper.gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
if (action == KeyEvent.ACTION_DOWN) {
mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), true, 1.0f, isAnalog);
}else {
mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), false, 0.0f, isAnalog);
}
}
return handled;
boolean handled = false;
int action = event.getAction();
int keyCode = event.getKeyCode();
if (action == KeyEvent.ACTION_DOWN) {
handled = OuyaController.onKeyDown(keyCode, event);
}
else if (action == KeyEvent.ACTION_UP) {
handled = OuyaController.onKeyUp(keyCode, event);
}
if (handled && mControllerEventListener != null) {
boolean isAnalog = false;
if (keyCode == KeyEvent.KEYCODE_BUTTON_THUMBL || keyCode == KeyEvent.KEYCODE_BUTTON_THUMBR){
isAnalog = true;
}
int deviceId = event.getDeviceId();
String deviceName = event.getDevice().getName();
if (mGameController.get(deviceId) == null) {
GameControllerHelper.gatherControllers(mGameController);
mGameController.append(deviceId, deviceName);
}
if (action == KeyEvent.ACTION_DOWN) {
mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), true, 1.0f, isAnalog);
}else {
mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), false, 0.0f, isAnalog);
}
}
return handled;
}
public void onPause() {
public void onPause() {
// show the mouse cursor
OuyaController.showCursor(true);
}
public void onResume() {
}
public void onResume() {
// hide the mouse cursor
OuyaController.showCursor(false);
}
public void onDestroy() {
}
}
public void onDestroy() {
}
private ControllerEventListener mControllerEventListener;
@Override
public void setControllerEventListener(ControllerEventListener listener) {
mControllerEventListener = listener;
}
private ControllerEventListener mControllerEventListener;
@Override
public void setControllerEventListener(ControllerEventListener listener) {
mControllerEventListener = listener;
}
}

View File

@ -44,7 +44,6 @@ import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.opengl.GLSurfaceView;
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// ===========================================================
@ -213,7 +212,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -252,17 +251,25 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
@Override
protected void onResume() {
super.onResume();
Cocos2dxHelper.onResume();
this.mGLSurfaceView.onResume();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
Cocos2dxHelper.onResume();
mGLSurfaceView.onResume();
}
else {
Cocos2dxHelper.onPause();
mGLSurfaceView.onPause();
}
}
@Override
protected void onPause() {
super.onPause();
Cocos2dxHelper.onPause();
this.mGLSurfaceView.onPause();
}
@Override

View File

@ -49,7 +49,7 @@ import android.util.DisplayMetrics;
import android.util.Log; //Enhance API modification
import android.view.Display;
import android.view.WindowManager;
import android.content.ServiceConnection; //Enhance API modification
import android.content.ServiceConnection; //Enhance API modification
import com.enhance.gameservice.IGameTuningService; //Enhance API modification

View File

@ -144,7 +144,7 @@ public class Cocos2dxHttpURLConnection
}
}
//Add header
//Add header
static void addRequestHeader(HttpURLConnection urlConnection, String key, String value) {
urlConnection.setRequestProperty(key, value);
}
@ -181,7 +181,7 @@ public class Cocos2dxHttpURLConnection
}
static String getResponseHeaders(HttpURLConnection http) {
Map<String, List<String>> headers = http.getHeaderFields();
Map<String, List<String>> headers = http.getHeaderFields();
if (null == headers) {
return null;
}

View File

@ -23,5 +23,5 @@
package org.cocos2dx.lib;
public class Cocos2dxJavascriptJavaBridge {
public static native int evalString(String value);
public static native int evalString(String value);
}

View File

@ -147,12 +147,12 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
}
public void handleOnPause() {
/**
* onPause may be invoked before onSurfaceCreated,
* and engine will be initialized correctly after
* onSurfaceCreated is invoked. Can not invoke any
* native method before onSurfaceCreated is invoked
*/
/**
* onPause may be invoked before onSurfaceCreated,
* and engine will be initialized correctly after
* onSurfaceCreated is invoked. Can not invoke any
* native method before onSurfaceCreated is invoked
*/
if (! mNativeInitCompleted)
return;

View File

@ -126,7 +126,7 @@ public class Cocos2dxWebViewHelper {
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null);
webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null);
}
}
});
@ -138,7 +138,7 @@ public class Cocos2dxWebViewHelper {
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.loadDataWithBaseURL(baseUrl, data, null, null, null);
webView.loadDataWithBaseURL(baseUrl, data, null, null, null);
}
}
});

View File

@ -50,13 +50,15 @@ public:
virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const override;
virtual ValueMap getValueMapFromFile(const std::string& filename) override;
virtual ValueMap getValueMapFromData(const char* filedata, int filesize);
virtual ValueMap getValueMapFromData(const char* filedata, int filesize)override;
virtual bool writeToFile(ValueMap& dict, const std::string& fullPath) override;
virtual ValueVector getValueVectorFromFile(const std::string& filename) override;
void setBundle(NSBundle* bundle);
private:
virtual bool isFileExistInternal(const std::string& filePath) const override;
virtual bool removeDirectory(const std::string& dirPath) override;
NSBundle* getBundle() const;
NSBundle* _bundle;
};

View File

@ -27,6 +27,8 @@ THE SOFTWARE.
#include "CCFileUtils-apple.h"
#include <ftw.h>
#include <string>
#include <stack>
@ -392,6 +394,31 @@ bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const
return ret;
}
static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
auto ret = remove(fpath);
if (ret)
{
log("Fail to remove: %s ",fpath);
}
return ret;
}
bool FileUtilsApple::removeDirectory(const std::string& path)
{
if (path.size() > 0 && path[path.size() - 1] != '/')
{
CCLOGERROR("Fail to remove directory, path must termniate with '/': %s", path.c_str());
return false;
}
if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
return false;
else
return true;
}
std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const
{
if (directory[0] != '/')

View File

@ -35,6 +35,7 @@ THE SOFTWARE.
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#ifndef CC_RESOURCE_FOLDER_LINUX
#define CC_RESOURCE_FOLDER_LINUX ("/Resources/")

View File

@ -52,7 +52,7 @@ public:
bool init();
virtual std::string getWritablePath() const;
private:
virtual bool isFileExistInternal(const std::string& strFilePath) const;
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
};
// end of platform group

View File

@ -30,6 +30,7 @@ THE SOFTWARE.
#include "platform/CCCommon.h"
#include <Shlobj.h>
#include <cstdlib>
#include <regex>
using namespace std;
@ -56,6 +57,81 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path)
return ret;
}
static std::wstring StringUtf8ToWideChar(const std::string& strUtf8)
{
std::wstring ret;
if (!strUtf8.empty())
{
int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0);
if (nNum)
{
WCHAR* wideCharString = new WCHAR[nNum + 1];
wideCharString[0] = 0;
nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1);
ret = wideCharString;
delete[] wideCharString;
}
else
{
CCLOG("Wrong convert to WideChar code:0x%x", GetLastError());
}
}
return ret;
}
static std::string StringWideCharToUtf8(const std::wstring& strWideChar)
{
std::string ret;
if (!strWideChar.empty())
{
int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* utf8String = new char[nNum + 1];
utf8String[0] = 0;
nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE);
ret = utf8String;
delete[] utf8String;
}
else
{
CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError());
}
}
return ret;
}
static std::string UTF8StringToMultiByte(const std::string& strUtf8)
{
std::string ret;
if (!strUtf8.empty())
{
std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* ansiString = new char[nNum + 1];
ansiString[0] = 0;
nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
ret = ansiString;
delete[] ansiString;
}
else
{
CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
}
}
return ret;
}
static void _checkPath()
{
if (0 == s_resourcePath.length())
@ -99,6 +175,22 @@ bool FileUtilsWin32::init()
return FileUtils::init();
}
bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const
{
unsigned long fAttrib = GetFileAttributes(StringUtf8ToWideChar(dirPath).c_str());
if (fAttrib != INVALID_FILE_ATTRIBUTES &&
(fAttrib & FILE_ATTRIBUTE_DIRECTORY))
{
return true;
}
return false;
}
std::string FileUtilsWin32::getSuitableFOpen(const std::string& filenameUtf8) const
{
return UTF8StringToMultiByte(filenameUtf8);
}
bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
{
if (0 == strFilePath.length())
@ -112,10 +204,7 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
strPath.insert(0, _defaultResRootPath);
}
WCHAR utf16Buf[CC_MAX_PATH] = {0};
MultiByteToWideChar(CP_UTF8, 0, strPath.c_str(), -1, utf16Buf, sizeof(utf16Buf)/sizeof(utf16Buf[0]));
DWORD attr = GetFileAttributesW(utf16Buf);
DWORD attr = GetFileAttributesW(StringUtf8ToWideChar(strPath).c_str());
if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
return false; // not a file
return true;
@ -162,7 +251,6 @@ static bool checkFileName(const std::string& fullPath, const std::string& filena
CCLOG("%s", msg.c_str());
return false;
}
}
else
{
@ -193,12 +281,9 @@ static Data getData(const std::string& filename, bool forString)
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
// check if the filename uses correct case characters
CC_BREAK_IF(!checkFileName(fullPath, filename));
checkFileName(fullPath, filename);
WCHAR wszBuf[CC_MAX_PATH] = {0};
MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0]));
HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
size = ::GetFileSize(fileHandle, nullptr);
@ -278,12 +363,9 @@ unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const ch
std::string fullPath = fullPathForFilename(filename);
// check if the filename uses correct case characters
CC_BREAK_IF(!checkFileName(fullPath, filename));
checkFileName(fullPath, filename);
WCHAR wszBuf[CC_MAX_PATH] = {0};
MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0]));
HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
*size = ::GetFileSize(fileHandle, nullptr);
@ -340,49 +422,191 @@ string FileUtilsWin32::getWritablePath() const
}
// Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
char full_path[CC_MAX_PATH + 1];
::GetModuleFileNameA(nullptr, full_path, CC_MAX_PATH + 1);
WCHAR full_path[CC_MAX_PATH + 1] = { 0 };
::GetModuleFileName(nullptr, full_path, CC_MAX_PATH + 1);
// Debug app uses executable directory; Non-debug app uses local app data directory
//#ifndef _DEBUG
// Get filename of executable only, e.g. MyGame.exe
char *base_name = strrchr(full_path, '\\');
// Get filename of executable only, e.g. MyGame.exe
WCHAR *base_name = wcsrchr(full_path, '\\');
wstring retPath;
if(base_name)
{
WCHAR app_data_path[CC_MAX_PATH + 1];
if(base_name)
// Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
{
char app_data_path[CC_MAX_PATH + 1];
wstring ret(app_data_path);
// Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
// Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe
ret += base_name;
// Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
ret = ret.substr(0, ret.rfind(L"."));
ret += L"\\";
// Create directory
if (SUCCEEDED(SHCreateDirectoryEx(nullptr, ret.c_str(), nullptr)))
{
string ret((char*)app_data_path);
retPath = ret;
}
}
}
if (retPath.empty())
//#endif // not defined _DEBUG
{
// If fetching of local app data directory fails, use the executable one
retPath = full_path;
// Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe
ret += base_name;
// remove xxx.exe
retPath = retPath.substr(0, retPath.rfind(L"\\") + 1);
}
// Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
ret = ret.substr(0, ret.rfind("."));
return convertPathFormatToUnixStyle(StringWideCharToUtf8(retPath));
}
ret += "\\";
bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
{
CCASSERT(!path.empty(), "Invalid path");
std::string oldPath = path + oldname;
std::string newPath = path + name;
// Create directory
if (SUCCEEDED(SHCreateDirectoryExA(nullptr, ret.c_str(), nullptr)))
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
std::wstring _wNew = StringUtf8ToWideChar(_new);
if (FileUtils::getInstance()->isFileExist(_new))
{
if (!DeleteFile(_wNew.c_str()))
{
CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError());
}
}
if (MoveFile(StringUtf8ToWideChar(_old).c_str(), _wNew.c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError());
return false;
}
}
bool FileUtilsWin32::createDirectory(const std::string& dirPath)
{
CCASSERT(!dirPath.empty(), "Invalid path");
if (isDirectoryExist(dirPath))
return true;
std::wstring path = StringUtf8ToWideChar(dirPath);
// Split the path
size_t start = 0;
size_t found = path.find_first_of(L"/\\", start);
std::wstring subpath;
std::vector<std::wstring> dirs;
if (found != std::wstring::npos)
{
while (true)
{
subpath = path.substr(start, found - start + 1);
if (!subpath.empty())
dirs.push_back(subpath);
start = found + 1;
found = path.find_first_of(L"/\\", start);
if (found == std::wstring::npos)
{
if (start < path.length())
{
return convertPathFormatToUnixStyle(ret);
dirs.push_back(path.substr(start));
}
break;
}
}
}
if ((GetFileAttributes(path.c_str())) == INVALID_FILE_ATTRIBUTES)
{
subpath = L"";
for (unsigned int i = 0; i < dirs.size(); ++i)
{
subpath += dirs[i];
std::string utf8Path = StringWideCharToUtf8(subpath);
if (!isDirectoryExist(utf8Path))
{
BOOL ret = CreateDirectory(subpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError());
return false;
}
}
}
//#endif // not defined _DEBUG
}
return true;
}
// If fetching of local app data directory fails, use the executable one
string ret((char*)full_path);
bool FileUtilsWin32::removeFile(const std::string &filepath)
{
std::regex pat("\\/");
std::string win32path = std::regex_replace(filepath, pat, "\\");
// remove xxx.exe
ret = ret.substr(0, ret.rfind("\\") + 1);
if (DeleteFile(StringUtf8ToWideChar(win32path).c_str()))
{
return true;
}
else
{
CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError());
return false;
}
}
ret = convertPathFormatToUnixStyle(ret);
return ret;
bool FileUtilsWin32::removeDirectory(const std::string& dirPath)
{
std::wstring wpath = StringUtf8ToWideChar(dirPath);
std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd;
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret = true;
if (search != INVALID_HANDLE_VALUE)
{
BOOL find = true;
while (find)
{
//. ..
if (wfd.cFileName[0] != '.')
{
std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
temp += '/';
ret = ret && this->removeDirectory(StringWideCharToUtf8(temp));
}
else
{
SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFile(temp.c_str());
}
}
find = FindNextFile(search, &wfd);
}
FindClose(search);
}
if (ret && RemoveDirectory(wpath.c_str()))
{
return true;
}
return false;
}
NS_CC_END

View File

@ -49,11 +49,53 @@ class CC_DLL FileUtilsWin32 : public FileUtils
public:
/* override funtions */
bool init();
virtual std::string getWritablePath() const;
virtual bool isAbsolutePath(const std::string& strPath) const;
virtual std::string getWritablePath() const override;
virtual bool isAbsolutePath(const std::string& strPath) const override;
virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const override;
protected:
virtual bool isFileExistInternal(const std::string& strFilePath) const;
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
/**
* Renames a file under the given directory.
*
* @param path The parent directory path of the file, it must be an absolute path.
* @param oldname The current name of the file.
* @param name The new name of the file.
* @return True if the file have been renamed successfully, false if not.
*/
virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name) override;
/**
* Checks whether a directory exists without considering search paths and resolution orders.
* @param dirPath The directory (with absolute path) to look up for
* @return Returns true if the directory found at the given absolute path, otherwise returns false
*/
virtual bool isDirectoryExistInternal(const std::string& dirPath) const override;
/**
* Removes a file.
*
* @param filepath The full path of the file, it must be an absolute path.
* @return True if the file have been removed successfully, false if not.
*/
virtual bool removeFile(const std::string &filepath) override;
/**
* Creates a directory.
*
* @param dirPath The path of the directory, it must be an absolute path.
* @return True if the directory have been created successfully, false if not.
*/
virtual bool createDirectory(const std::string& dirPath) override;
/**
* Removes a directory.
*
* @param dirPath The full path of the directory, it must be an absolute path.
* @return True if the directory have been removed successfully, false if not.
*/
virtual bool removeDirectory(const std::string& dirPath) override;
/**
* Gets resource file data
@ -64,7 +106,7 @@ protected:
* @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.
*/
virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override;
CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override;
/**
* Gets string from a file.

View File

@ -23,9 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCFileUtilsWinRT.h"
#include <regex>
#include "CCWinRTUtils.h"
#include "platform/CCCommon.h"
using namespace std;
NS_CC_BEGIN
@ -47,6 +47,80 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path)
return ret;
}
static std::wstring StringUtf8ToWideChar(const std::string& strUtf8)
{
std::wstring ret;
if (!strUtf8.empty())
{
int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0);
if (nNum)
{
WCHAR* wideCharString = new WCHAR[nNum + 1];
wideCharString[0] = 0;
nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1);
ret = wideCharString;
delete[] wideCharString;
}
else
{
CCLOG("Wrong convert to WideChar code:0x%x", GetLastError());
}
}
return ret;
}
static std::string StringWideCharToUtf8(const std::wstring& strWideChar)
{
std::string ret;
if (!strWideChar.empty())
{
int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* utf8String = new char[nNum + 1];
utf8String[0] = 0;
nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE);
ret = utf8String;
delete[] utf8String;
}
else
{
CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError());
}
}
return ret;
}
static std::string UTF8StringToMultiByte(const std::string& strUtf8)
{
std::string ret;
if (!strUtf8.empty())
{
std::wstring strWideChar = StringUtf8ToWideChar(strUtf8);
int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE);
if (nNum)
{
char* ansiString = new char[nNum + 1];
ansiString[0] = 0;
nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE);
ret = ansiString;
delete[] ansiString;
}
else
{
CCLOG("Wrong convert to Ansi code:0x%x", GetLastError());
}
}
return ret;
}
static void _checkPath()
{
@ -72,7 +146,6 @@ FileUtils* FileUtils::getInstance()
return s_sharedFileUtils;
}
CCFileUtilsWinRT::CCFileUtilsWinRT()
{
}
@ -100,6 +173,11 @@ std::string CCFileUtilsWinRT::getFullPathForDirectoryAndFilename(const std::stri
return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
}
std::string CCFileUtilsWinRT::getSuitableFOpen(const std::string& filenameUtf8) const
{
return UTF8StringToMultiByte(filenameUtf8);
}
bool CCFileUtilsWinRT::isFileExistInternal(const std::string& strFilePath) const
{
bool ret = false;
@ -121,6 +199,110 @@ bool CCFileUtilsWinRT::isFileExistInternal(const std::string& strFilePath) const
return ret;
}
bool CCFileUtilsWinRT::isDirectoryExistInternal(const std::string& dirPath) const
{
WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wdirPath(dirPath.begin(), dirPath.end());
if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad))
{
return true;
}
return false;
}
bool CCFileUtilsWinRT::createDirectory(const std::string& path)
{
CCASSERT(!path.empty(), "Invalid path");
if (isDirectoryExist(path))
return true;
// Split the path
size_t start = 0;
size_t found = path.find_first_of("/\\", start);
std::string subpath;
std::vector<std::string> dirs;
if (found != std::string::npos)
{
while (true)
{
subpath = path.substr(start, found - start + 1);
if (!subpath.empty())
dirs.push_back(subpath);
start = found + 1;
found = path.find_first_of("/\\", start);
if (found == std::string::npos)
{
if (start < path.length())
{
dirs.push_back(path.substr(start));
}
break;
}
}
}
WIN32_FILE_ATTRIBUTE_DATA wfad;
std::wstring wpath(path.begin(), path.end());
if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad)))
{
subpath = "";
for (unsigned int i = 0; i < dirs.size(); ++i)
{
subpath += dirs[i];
if (i > 0 && !isDirectoryExist(subpath))
{
std::wstring wsubpath(subpath.begin(), subpath.end());
BOOL ret = CreateDirectory(wsubpath.c_str(), NULL);
if (!ret && ERROR_ALREADY_EXISTS != GetLastError())
{
return false;
}
}
}
}
return true;
}
bool CCFileUtilsWinRT::removeDirectory(const std::string& path)
{
std::wstring wpath = std::wstring(path.begin(), path.end());
std::wstring files = wpath + L"*.*";
WIN32_FIND_DATA wfd;
HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
bool ret = true;
if (search != INVALID_HANDLE_VALUE)
{
BOOL find = true;
while (find)
{
//. ..
if (wfd.cFileName[0] != '.')
{
std::wstring temp = wpath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
temp += '/';
ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end()));
}
else
{
SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
ret = ret && DeleteFile(temp.c_str());
}
}
find = FindNextFile(search, &wfd);
}
FindClose(search);
}
if (ret && RemoveDirectory(wpath.c_str()))
{
return true;
}
return false;
}
bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const
{
if ( strPath.length() > 2
@ -132,6 +314,34 @@ bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const
return false;
}
bool CCFileUtilsWinRT::removeFile(const std::string &path)
{
std::wstring wpath(path.begin(), path.end());
if (DeleteFile(wpath.c_str()))
{
return true;
}
return false;
}
bool CCFileUtilsWinRT::renameFile(const std::string &path, const std::string &oldname, const std::string &name)
{
CCASSERT(!path.empty(), "Invalid path");
std::string oldPath = path + oldname;
std::string newPath = path + name;
std::regex pat("\\/");
std::string _old = std::regex_replace(oldPath, pat, "\\");
std::string _new = std::regex_replace(newPath, pat, "\\");
if (MoveFileEx(std::wstring(_old.begin(), _old.end()).c_str(),
std::wstring(_new.begin(), _new.end()).c_str(),
MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH))
{
return true;
}
return false;
}
static Data getData(const std::string& filename, bool forString)
{
if (filename.empty())

View File

@ -49,13 +49,55 @@ public:
bool init();
virtual std::string getWritablePath() const;
virtual bool isAbsolutePath(const std::string& strPath) const;
virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const override;
virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const override;
virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) const override;
virtual std::string getStringFromFile(const std::string& filename) override;
virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const override;
static std::string getAppPath();
private:
virtual bool isFileExistInternal(const std::string& strFilePath) const;
virtual bool isFileExistInternal(const std::string& strFilePath) const override;
/**
* Renames a file under the given directory.
*
* @param path The parent directory path of the file, it must be an absolute path.
* @param oldname The current name of the file.
* @param name The new name of the file.
* @return True if the file have been renamed successfully, false if not.
*/
virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name) override;
/**
* Checks whether a directory exists without considering search paths and resolution orders.
* @param dirPath The directory (with absolute path) to look up for
* @return Returns true if the directory found at the given absolute path, otherwise returns false
*/
virtual bool isDirectoryExistInternal(const std::string& dirPath) const override;
/**
* Removes a file.
*
* @param filepath The full path of the file, it must be an absolute path.
* @return True if the file have been removed successfully, false if not.
*/
virtual bool removeFile(const std::string &filepath) override;
/**
* Creates a directory.
*
* @param dirPath The path of the directory, it must be an absolute path.
* @return True if the directory have been created successfully, false if not.
*/
virtual bool createDirectory(const std::string& dirPath) override;
/**
* Removes a directory.
*
* @param dirPath The full path of the directory, it must be an absolute path.
* @return True if the directory have been removed successfully, false if not.
*/
virtual bool removeDirectory(const std::string& dirPath) override;
};
// end of platform group

View File

@ -239,7 +239,7 @@ void UniformValue::setVec4v(ssize_t size, const Vec4* pointer)
void UniformValue::setMat4(const Mat4& value)
{
CCASSERT(_uniform->type == GL_FLOAT_MAT4, "");
CCASSERT(_uniform->type == GL_FLOAT_MAT4, "_uniform's type should be equal GL_FLOAT_MAT4.");
memcpy(_value.matrixValue, &value, sizeof(_value.matrixValue));
_type = Type::VALUE;
}

View File

@ -670,7 +670,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat
CCLOG("cocos2d: Texture2D. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%d != height=%d", i, width, height);
}
GLenum err = glGetError();
err = glGetError();
if (err != GL_NO_ERROR)
{
CCLOG("cocos2d: Texture2D: Error uploading compressed texture level: %u . glError: 0x%04X", i, err);

View File

@ -171,7 +171,7 @@ bool TextureAtlas::initWithTexture(Texture2D *texture, ssize_t capacity)
CC_SAFE_RETAIN(_texture);
// Re-initialization is not allowed
CCASSERT(_quads == nullptr && _indices == nullptr, "");
CCASSERT(_quads == nullptr && _indices == nullptr, "_quads and _indices should be nullptr.");
_quads = (V3F_C4B_T2F_Quad*)malloc( _capacity * sizeof(V3F_C4B_T2F_Quad) );
_indices = (GLushort *)malloc( _capacity * 6 * sizeof(GLushort) );

View File

@ -896,6 +896,16 @@ func
{
},
/**
* @method stopActionsByFlags
* @param {unsigned int} arg0
*/
stopActionsByFlags : function (
int
)
{
},
/**
* @method setNormalizedPosition
* @param {vec2_object} arg0
@ -3244,6 +3254,16 @@ getTarget : function (
return cc.Node;
},
/**
* @method getFlags
* @return {unsigned int}
*/
getFlags : function (
)
{
return 0;
},
/**
* @method step
* @param {float} arg0
@ -3264,6 +3284,16 @@ int
{
},
/**
* @method setFlags
* @param {unsigned int} arg0
*/
setFlags : function (
int
)
{
},
/**
* @method getTag
* @return {int}
@ -5173,6 +5203,18 @@ ReverseTime : function (
*/
cc.Animate = {
/**
* @method initWithAnimation
* @param {cc.Animation} arg0
* @return {bool}
*/
initWithAnimation : function (
animation
)
{
return false;
},
/**
* @method getAnimation
* @return {cc.Animation|cc.Animation}
@ -5184,15 +5226,13 @@ getAnimation : function(
},
/**
* @method initWithAnimation
* @param {cc.Animation} arg0
* @return {bool}
* @method getCurrentFrameIndex
* @return {int}
*/
initWithAnimation : function (
animation
getCurrentFrameIndex : function (
)
{
return false;
return 0;
},
/**
@ -9533,6 +9573,18 @@ node
{
},
/**
* @method removeActionsByFlags
* @param {unsigned int} arg0
* @param {cc.Node} arg1
*/
removeActionsByFlags : function (
int,
node
)
{
},
/**
* @method removeAllActions
*/

View File

@ -36,14 +36,6 @@ play : function (
{
},
/**
* @method pause
*/
pause : function (
)
{
},
/**
* @method setKeepAspectRatioEnabled
* @param {bool} arg0
@ -54,14 +46,6 @@ bool
{
},
/**
* @method resume
*/
resume : function (
)
{
},
/**
* @method stop
*/

View File

@ -50,16 +50,6 @@ setBonesToSetupPose : function (
{
},
/**
* @method isOpacityModifyRGB
* @return {bool}
*/
isOpacityModifyRGB : function (
)
{
return false;
},
/**
* @method initWithData
* @param {spSkeletonData} arg0
@ -90,16 +80,6 @@ setSlotsToSetupPose : function (
{
},
/**
* @method setOpacityModifyRGB
* @param {bool} arg0
*/
setOpacityModifyRGB : function (
bool
)
{
},
/**
* @method setToSetupPose
*/

View File

@ -2683,6 +2683,16 @@ bool
{
},
/**
* @method setScrollBarOpacity
* @param {unsigned char} arg0
*/
setScrollBarOpacity : function (
char
)
{
},
/**
* @method setScrollBarEnabled
* @param {bool} arg0
@ -2767,6 +2777,16 @@ jumpToBottom : function (
{
},
/**
* @method setInnerContainerPosition
* @param {vec2_object} arg0
*/
setInnerContainerPosition : function (
vec2
)
{
},
/**
* @method setDirection
* @param {ccui.ScrollView::Direction} arg0
@ -2815,6 +2835,16 @@ size
{
},
/**
* @method getInnerContainerPosition
* @return {vec2_object}
*/
getInnerContainerPosition : function (
)
{
return cc.Vec2;
},
/**
* @method getInnerContainerSize
* @return {size_object}
@ -2875,6 +2905,16 @@ bool
{
},
/**
* @method setScrollBarAutoHideEnabled
* @param {bool} arg0
*/
setScrollBarAutoHideEnabled : function (
bool
)
{
},
/**
* @method getScrollBarColor
* @return {color3b_object}
@ -3008,13 +3048,13 @@ bool
},
/**
* @method setScrollBarAutoHideEnabled
* @param {bool} arg0
* @method getScrollBarOpacity
* @return {unsigned char}
*/
setScrollBarAutoHideEnabled : function (
bool
getScrollBarOpacity : function (
)
{
return 0;
},
/**

View File

@ -3532,6 +3532,7 @@ void js_register_cocos2dx_3d_Sprite3D(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { jsb.Sprite3D.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Sprite3DCache_class;

View File

@ -2385,6 +2385,26 @@ bool js_cocos2dx_Node_setOnEnterCallback(JSContext *cx, uint32_t argc, jsval *vp
JS_ReportError(cx, "js_cocos2dx_Node_setOnEnterCallback : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_Node_stopActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Node* cobj = (cocos2d::Node *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Node_stopActionsByFlags : Invalid Native Object");
if (argc == 1) {
unsigned int arg0;
ok &= jsval_to_uint32(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Node_stopActionsByFlags : Error processing arguments");
cobj->stopActionsByFlags(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_Node_stopActionsByFlags : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_Node_setNormalizedPosition(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -4909,6 +4929,7 @@ void js_register_cocos2dx_Node(JSContext *cx, JS::HandleObject global) {
JS_FN("setSkewX", js_cocos2dx_Node_setSkewX, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setGLProgramState", js_cocos2dx_Node_setGLProgramState, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setOnEnterCallback", js_cocos2dx_Node_setOnEnterCallback, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("stopActionsByFlags", js_cocos2dx_Node_stopActionsByFlags, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setNormalizedPosition", js_cocos2dx_Node_setNormalizedPosition, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setonExitTransitionDidStartCallback", js_cocos2dx_Node_setonExitTransitionDidStartCallback, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("convertTouchToNodeSpace", js_cocos2dx_Node_convertTouchToNodeSpace, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
@ -5047,6 +5068,7 @@ void js_register_cocos2dx_Node(JSContext *cx, JS::HandleObject global) {
p->parentProto = NULL;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Node.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d___NodeRGBA_class;
@ -5155,6 +5177,7 @@ void js_register_cocos2dx___NodeRGBA(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.NodeRGBA.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Scene_class;
@ -5458,6 +5481,7 @@ void js_register_cocos2dx_Scene(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Scene.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_GLView_class;
@ -8088,6 +8112,24 @@ bool js_cocos2dx_Action_getTarget(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_cocos2dx_Action_getTarget : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_Action_getFlags(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Action* cobj = (cocos2d::Action *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Action_getFlags : Invalid Native Object");
if (argc == 0) {
unsigned int ret = cobj->getFlags();
jsval jsret = JSVAL_NULL;
jsret = uint32_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_Action_getFlags : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_Action_step(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -8128,6 +8170,26 @@ bool js_cocos2dx_Action_setTag(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_cocos2dx_Action_setTag : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_Action_setFlags(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Action* cobj = (cocos2d::Action *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Action_setFlags : Invalid Native Object");
if (argc == 1) {
unsigned int arg0;
ok &= jsval_to_uint32(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Action_setFlags : Error processing arguments");
cobj->setFlags(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_Action_setFlags : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_Action_getTag(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -8249,8 +8311,10 @@ void js_register_cocos2dx_Action(JSContext *cx, JS::HandleObject global) {
JS_FN("stop", js_cocos2dx_Action_stop, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("update", js_cocos2dx_Action_update, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTarget", js_cocos2dx_Action_getTarget, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getFlags", js_cocos2dx_Action_getFlags, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("step", js_cocos2dx_Action_step, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setTag", js_cocos2dx_Action_setTag, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setFlags", js_cocos2dx_Action_setFlags, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getTag", js_cocos2dx_Action_getTag, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setTarget", js_cocos2dx_Action_setTarget, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isDone", js_cocos2dx_Action_isDone, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
@ -9628,6 +9692,7 @@ void js_register_cocos2dx_SpriteFrame(JSContext *cx, JS::HandleObject global) {
p->parentProto = NULL;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.SpriteFrame.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_AnimationFrame_class;
@ -14715,6 +14780,36 @@ void js_register_cocos2dx_ReverseTime(JSContext *cx, JS::HandleObject global) {
JSClass *jsb_cocos2d_Animate_class;
JSObject *jsb_cocos2d_Animate_prototype;
bool js_cocos2dx_Animate_initWithAnimation(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Animate* cobj = (cocos2d::Animate *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Animate_initWithAnimation : Invalid Native Object");
if (argc == 1) {
cocos2d::Animation* arg0;
do {
if (args.get(0).isNull()) { arg0 = nullptr; break; }
if (!args.get(0).isObject()) { ok = false; break; }
js_proxy_t *jsProxy;
JSObject *tmpObj = args.get(0).toObjectOrNull();
jsProxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocos2d::Animation*)(jsProxy ? jsProxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Animate_initWithAnimation : Error processing arguments");
bool ret = cobj->initWithAnimation(arg0);
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_Animate_initWithAnimation : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -14763,34 +14858,22 @@ bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_cocos2dx_Animate_getAnimation : wrong number of arguments");
return false;
}
bool js_cocos2dx_Animate_initWithAnimation(JSContext *cx, uint32_t argc, jsval *vp)
bool js_cocos2dx_Animate_getCurrentFrameIndex(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::Animate* cobj = (cocos2d::Animate *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Animate_initWithAnimation : Invalid Native Object");
if (argc == 1) {
cocos2d::Animation* arg0;
do {
if (args.get(0).isNull()) { arg0 = nullptr; break; }
if (!args.get(0).isObject()) { ok = false; break; }
js_proxy_t *jsProxy;
JSObject *tmpObj = args.get(0).toObjectOrNull();
jsProxy = jsb_get_js_proxy(tmpObj);
arg0 = (cocos2d::Animation*)(jsProxy ? jsProxy->ptr : NULL);
JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Animate_initWithAnimation : Error processing arguments");
bool ret = cobj->initWithAnimation(arg0);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Animate_getCurrentFrameIndex : Invalid Native Object");
if (argc == 0) {
int ret = cobj->getCurrentFrameIndex();
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
jsret = int32_to_jsval(cx, ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_Animate_initWithAnimation : wrong number of arguments: %d, was expecting %d", argc, 1);
JS_ReportError(cx, "js_cocos2dx_Animate_getCurrentFrameIndex : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_Animate_setAnimation(JSContext *cx, uint32_t argc, jsval *vp)
@ -14909,8 +14992,9 @@ void js_register_cocos2dx_Animate(JSContext *cx, JS::HandleObject global) {
};
static JSFunctionSpec funcs[] = {
JS_FN("getAnimation", js_cocos2dx_Animate_getAnimation, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("initWithAnimation", js_cocos2dx_Animate_initWithAnimation, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getAnimation", js_cocos2dx_Animate_getAnimation, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getCurrentFrameIndex", js_cocos2dx_Animate_getCurrentFrameIndex, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setAnimation", js_cocos2dx_Animate_setAnimation, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
@ -15219,6 +15303,7 @@ void js_register_cocos2dx_TargetedAction(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_ActionInterval_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TargetedAction.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_ActionFloat_class;
@ -15432,6 +15517,7 @@ void js_register_cocos2dx_ActionFloat(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_ActionInterval_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ActionFloat.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Configuration_class;
@ -20403,6 +20489,7 @@ void js_register_cocos2dx_ActionCamera(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_ActionInterval_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ActionCamera.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_OrbitCamera_class;
@ -24019,6 +24106,7 @@ void js_register_cocos2dx_EaseBezierAction(JSContext *cx, JS::HandleObject globa
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseBezierAction.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuadraticActionIn_class;
@ -24163,6 +24251,7 @@ void js_register_cocos2dx_EaseQuadraticActionIn(JSContext *cx, JS::HandleObject
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuadraticActionIn.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuadraticActionOut_class;
@ -24307,6 +24396,7 @@ void js_register_cocos2dx_EaseQuadraticActionOut(JSContext *cx, JS::HandleObject
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuadraticActionOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuadraticActionInOut_class;
@ -24451,6 +24541,7 @@ void js_register_cocos2dx_EaseQuadraticActionInOut(JSContext *cx, JS::HandleObje
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuadraticActionInOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuarticActionIn_class;
@ -24595,6 +24686,7 @@ void js_register_cocos2dx_EaseQuarticActionIn(JSContext *cx, JS::HandleObject gl
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuarticActionIn.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuarticActionOut_class;
@ -24739,6 +24831,7 @@ void js_register_cocos2dx_EaseQuarticActionOut(JSContext *cx, JS::HandleObject g
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuarticActionOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuarticActionInOut_class;
@ -24883,6 +24976,7 @@ void js_register_cocos2dx_EaseQuarticActionInOut(JSContext *cx, JS::HandleObject
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuarticActionInOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuinticActionIn_class;
@ -25027,6 +25121,7 @@ void js_register_cocos2dx_EaseQuinticActionIn(JSContext *cx, JS::HandleObject gl
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuinticActionIn.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuinticActionOut_class;
@ -25171,6 +25266,7 @@ void js_register_cocos2dx_EaseQuinticActionOut(JSContext *cx, JS::HandleObject g
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuinticActionOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseQuinticActionInOut_class;
@ -25315,6 +25411,7 @@ void js_register_cocos2dx_EaseQuinticActionInOut(JSContext *cx, JS::HandleObject
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseQuinticActionInOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseCircleActionIn_class;
@ -25459,6 +25556,7 @@ void js_register_cocos2dx_EaseCircleActionIn(JSContext *cx, JS::HandleObject glo
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseCircleActionIn.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseCircleActionOut_class;
@ -25603,6 +25701,7 @@ void js_register_cocos2dx_EaseCircleActionOut(JSContext *cx, JS::HandleObject gl
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseCircleActionOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseCircleActionInOut_class;
@ -25747,6 +25846,7 @@ void js_register_cocos2dx_EaseCircleActionInOut(JSContext *cx, JS::HandleObject
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseCircleActionInOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseCubicActionIn_class;
@ -25891,6 +25991,7 @@ void js_register_cocos2dx_EaseCubicActionIn(JSContext *cx, JS::HandleObject glob
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseCubicActionIn.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseCubicActionOut_class;
@ -26035,6 +26136,7 @@ void js_register_cocos2dx_EaseCubicActionOut(JSContext *cx, JS::HandleObject glo
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseCubicActionOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_EaseCubicActionInOut_class;
@ -26179,6 +26281,7 @@ void js_register_cocos2dx_EaseCubicActionInOut(JSContext *cx, JS::HandleObject g
p->parentProto = jsb_cocos2d_ActionEase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.EaseCubicActionInOut.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_ActionInstant_class;
@ -29900,6 +30003,36 @@ bool js_cocos2dx_ActionManager_removeActionByTag(JSContext *cx, uint32_t argc, j
JS_ReportError(cx, "js_cocos2dx_ActionManager_removeActionByTag : wrong number of arguments: %d, was expecting %d", argc, 2);
return false;
}
bool js_cocos2dx_ActionManager_removeActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::ActionManager* cobj = (cocos2d::ActionManager *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ActionManager_removeActionsByFlags : Invalid Native Object");
if (argc == 2) {
unsigned int arg0;
cocos2d::Node* arg1;
ok &= jsval_to_uint32(cx, args.get(0), &arg0);
do {
if (args.get(1).isNull()) { arg1 = nullptr; break; }
if (!args.get(1).isObject()) { ok = false; break; }
js_proxy_t *jsProxy;
JSObject *tmpObj = args.get(1).toObjectOrNull();
jsProxy = jsb_get_js_proxy(tmpObj);
arg1 = (cocos2d::Node*)(jsProxy ? jsProxy->ptr : NULL);
JSB_PRECONDITION2( arg1, cx, false, "Invalid Native Object");
} while (0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_ActionManager_removeActionsByFlags : Error processing arguments");
cobj->removeActionsByFlags(arg0, arg1);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_ActionManager_removeActionsByFlags : wrong number of arguments: %d, was expecting %d", argc, 2);
return false;
}
bool js_cocos2dx_ActionManager_removeAllActions(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -30258,6 +30391,7 @@ void js_register_cocos2dx_ActionManager(JSContext *cx, JS::HandleObject global)
static JSFunctionSpec funcs[] = {
JS_FN("getActionByTag", js_cocos2dx_ActionManager_getActionByTag, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeActionByTag", js_cocos2dx_ActionManager_removeActionByTag, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeActionsByFlags", js_cocos2dx_ActionManager_removeActionsByFlags, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("removeAllActions", js_cocos2dx_ActionManager_removeAllActions, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("addAction", js_cocos2dx_ActionManager_addAction, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("resumeTarget", js_cocos2dx_ActionManager_resumeTarget, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
@ -30301,6 +30435,7 @@ void js_register_cocos2dx_ActionManager(JSContext *cx, JS::HandleObject global)
p->parentProto = NULL;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ActionManager.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_PageTurn3D_class;
@ -32937,6 +33072,7 @@ void js_register_cocos2dx_ActionTween(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_ActionInterval_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ActionTween.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_GLProgramState_class;
@ -35685,6 +35821,7 @@ void js_register_cocos2dx_DrawNode(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.DrawNode.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Label_class;
@ -37165,6 +37302,7 @@ void js_register_cocos2dx_Label(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Label.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_LabelAtlas_class;
@ -37484,6 +37622,7 @@ void js_register_cocos2dx_LabelAtlas(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_AtlasNode_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.LabelAtlas.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_LabelBMFont_class;
@ -38022,6 +38161,7 @@ void js_register_cocos2dx_LabelBMFont(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.LabelBMFont.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_LabelTTF_class;
@ -38929,6 +39069,7 @@ void js_register_cocos2dx_LabelTTF(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.LabelTTF.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Layer_class;
@ -39061,6 +39202,7 @@ void js_register_cocos2dx_Layer(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Layer.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d___LayerRGBA_class;
@ -39509,6 +39651,7 @@ void js_register_cocos2dx_LayerColor(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Layer_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.LayerColor.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_LayerGradient_class;
@ -39983,6 +40126,7 @@ void js_register_cocos2dx_LayerGradient(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_LayerColor_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.LayerGradient.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_LayerMultiplex_class;
@ -40185,6 +40329,7 @@ void js_register_cocos2dx_LayerMultiplex(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_Layer_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.LayerMultiplex.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MenuItem_class;
@ -40473,6 +40618,7 @@ void js_register_cocos2dx_MenuItem(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MenuItem.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MenuItemLabel_class;
@ -40758,6 +40904,7 @@ void js_register_cocos2dx_MenuItemLabel(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_MenuItem_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MenuItemLabel.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MenuItemAtlasFont_class;
@ -40927,6 +41074,7 @@ void js_register_cocos2dx_MenuItemAtlasFont(JSContext *cx, JS::HandleObject glob
p->parentProto = jsb_cocos2d_MenuItemLabel_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MenuItemAtlasFont.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MenuItemFont_class;
@ -41234,6 +41382,7 @@ void js_register_cocos2dx_MenuItemFont(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_MenuItemLabel_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MenuItemFont.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MenuItemSprite_class;
@ -41643,6 +41792,7 @@ void js_register_cocos2dx_MenuItemSprite(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_MenuItem_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MenuItemSprite.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MenuItemImage_class;
@ -41914,6 +42064,7 @@ void js_register_cocos2dx_MenuItemImage(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_MenuItemSprite_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MenuItemImage.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MenuItemToggle_class;
@ -42169,6 +42320,7 @@ void js_register_cocos2dx_MenuItemToggle(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_MenuItem_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MenuItemToggle.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Menu_class;
@ -42416,6 +42568,7 @@ void js_register_cocos2dx_Menu(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Layer_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Menu.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_MotionStreak_class;
@ -42932,6 +43085,7 @@ void js_register_cocos2dx_MotionStreak(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.MotionStreak.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_NodeGrid_class;
@ -43645,6 +43799,7 @@ void js_register_cocos2dx_ParticleBatchNode(JSContext *cx, JS::HandleObject glob
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ParticleBatchNode.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_ParticleSystem_class;
@ -45837,6 +45992,7 @@ void js_register_cocos2dx_ParticleSystem(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ParticleSystem.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_ParticleSystemQuad_class;
@ -48525,6 +48681,7 @@ void js_register_cocos2dx_ProgressTimer(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ProgressTimer.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_ProtectedNode_class;
@ -50399,6 +50556,7 @@ void js_register_cocos2dx_Sprite(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Sprite.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_RenderTexture_class;
@ -51200,6 +51358,7 @@ void js_register_cocos2dx_RenderTexture(JSContext *cx, JS::HandleObject global)
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.RenderTexture.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_TransitionEaseScene_class;
@ -51557,6 +51716,7 @@ void js_register_cocos2dx_TransitionScene(JSContext *cx, JS::HandleObject global
p->parentProto = jsb_cocos2d_Scene_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TransitionScene.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_TransitionSceneOriented_class;
@ -58200,6 +58360,7 @@ void js_register_cocos2dx_GridBase(JSContext *cx, JS::HandleObject global) {
p->parentProto = NULL;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.GridBase.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Grid3D_class;
@ -58412,6 +58573,7 @@ void js_register_cocos2dx_Grid3D(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_GridBase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Grid3D.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_TiledGrid3D_class;
@ -58584,6 +58746,7 @@ void js_register_cocos2dx_TiledGrid3D(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_GridBase_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TiledGrid3D.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_BaseLight_class;
@ -60404,6 +60567,7 @@ void js_register_cocos2dx_GLProgram(JSContext *cx, JS::HandleObject global) {
p->parentProto = NULL;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.GLProgram.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_GLProgramCache_class;
@ -63776,6 +63940,7 @@ void js_register_cocos2dx_SpriteBatchNode(JSContext *cx, JS::HandleObject global
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.SpriteBatchNode.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_SpriteFrameCache_class;
@ -64624,6 +64789,7 @@ void js_register_cocos2dx_TextFieldTTF(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Label_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TextFieldTTF.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_ParallaxNode_class;
@ -64869,6 +65035,7 @@ void js_register_cocos2dx_ParallaxNode(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ParallaxNode.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_TMXObjectGroup_class;
@ -66321,6 +66488,7 @@ void js_register_cocos2dx_TMXMapInfo(JSContext *cx, JS::HandleObject global) {
p->parentProto = NULL;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TMXMapInfo.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_TMXLayer_class;
@ -67042,6 +67210,7 @@ void js_register_cocos2dx_TMXLayer(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_SpriteBatchNode_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TMXLayer.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_TMXTiledMap_class;
@ -67605,6 +67774,7 @@ void js_register_cocos2dx_TMXTiledMap(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TMXTiledMap.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_TileMapAtlas_class;
@ -67880,6 +68050,7 @@ void js_register_cocos2dx_TileMapAtlas(JSContext *cx, JS::HandleObject global) {
p->parentProto = jsb_cocos2d_AtlasNode_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TileMapAtlas.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_Component_class;
@ -68165,6 +68336,7 @@ void js_register_cocos2dx_Component(JSContext *cx, JS::HandleObject global) {
p->parentProto = NULL;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.Component.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_ComponentContainer_class;

View File

@ -127,6 +127,7 @@ bool js_cocos2dx_Node_getEventDispatcher(JSContext *cx, uint32_t argc, jsval *vp
bool js_cocos2dx_Node_setSkewX(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Node_setGLProgramState(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Node_setOnEnterCallback(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Node_stopActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Node_setNormalizedPosition(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Node_setonExitTransitionDidStartCallback(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Node_convertTouchToNodeSpace(JSContext *cx, uint32_t argc, jsval *vp);
@ -410,8 +411,10 @@ bool js_cocos2dx_Action_getOriginalTarget(JSContext *cx, uint32_t argc, jsval *v
bool js_cocos2dx_Action_stop(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_update(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_getTarget(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_getFlags(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_step(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_setTag(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_setFlags(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_getTag(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_setTarget(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Action_isDone(JSContext *cx, uint32_t argc, jsval *vp);
@ -810,8 +813,9 @@ bool js_cocos2dx_Animate_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_Animate_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_Animate(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Animate_initWithAnimation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Animate_getCurrentFrameIndex(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Animate_setAnimation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Animate_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_Animate_Animate(JSContext *cx, uint32_t argc, jsval *vp);
@ -1839,6 +1843,7 @@ void js_register_cocos2dx_ActionManager(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_ActionManager_getActionByTag(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_ActionManager_removeActionByTag(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_ActionManager_removeActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_ActionManager_removeAllActions(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_ActionManager_addAction(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_ActionManager_resumeTarget(JSContext *cx, uint32_t argc, jsval *vp);

View File

@ -97,22 +97,6 @@ bool js_cocos2dx_experimental_video_VideoPlayer_play(JSContext *cx, uint32_t arg
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_play : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_pause(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_pause : Invalid Native Object");
if (argc == 0) {
cobj->pause();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_pause : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -133,22 +117,6 @@ bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSCont
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_resume(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_resume : Invalid Native Object");
if (argc == 0) {
cobj->resume();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_resume : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_video_VideoPlayer_stop(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -398,9 +366,7 @@ void js_register_cocos2dx_experimental_video_VideoPlayer(JSContext *cx, JS::Hand
JS_FN("getFileName", js_cocos2dx_experimental_video_VideoPlayer_getFileName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getURL", js_cocos2dx_experimental_video_VideoPlayer_getURL, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("play", js_cocos2dx_experimental_video_VideoPlayer_play, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("pause", js_cocos2dx_experimental_video_VideoPlayer_pause, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setKeepAspectRatioEnabled", js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("resume", js_cocos2dx_experimental_video_VideoPlayer_resume, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("stop", js_cocos2dx_experimental_video_VideoPlayer_stop, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setFullScreenEnabled", js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setFileName", js_cocos2dx_experimental_video_VideoPlayer_setFileName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),

View File

@ -16,9 +16,7 @@ void register_all_cocos2dx_experimental_video(JSContext* cx, JS::HandleObject ob
bool js_cocos2dx_experimental_video_VideoPlayer_getFileName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_getURL(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_play(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_pause(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_resume(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_stop(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_experimental_video_VideoPlayer_setFileName(JSContext *cx, uint32_t argc, jsval *vp);

View File

@ -1566,6 +1566,7 @@ void js_register_cocos2dx_extension_ControlButton(JSContext *cx, JS::HandleObjec
p->parentProto = jsb_cocos2d_extension_Control_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ControlButton.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_ControlHuePicker_class;
@ -2619,6 +2620,7 @@ void js_register_cocos2dx_extension_ControlColourPicker(JSContext *cx, JS::Handl
p->parentProto = jsb_cocos2d_extension_Control_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ControlColourPicker.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_ControlPotentiometer_class;
@ -3197,6 +3199,7 @@ void js_register_cocos2dx_extension_ControlPotentiometer(JSContext *cx, JS::Hand
p->parentProto = jsb_cocos2d_extension_Control_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ControlPotentiometer.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_ControlSlider_class;
@ -4044,6 +4047,7 @@ void js_register_cocos2dx_extension_ControlSlider(JSContext *cx, JS::HandleObjec
p->parentProto = jsb_cocos2d_extension_Control_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ControlSlider.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_ControlStepper_class;
@ -4680,6 +4684,7 @@ void js_register_cocos2dx_extension_ControlStepper(JSContext *cx, JS::HandleObje
p->parentProto = jsb_cocos2d_extension_Control_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ControlStepper.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_ControlSwitch_class;
@ -5193,6 +5198,7 @@ void js_register_cocos2dx_extension_ControlSwitch(JSContext *cx, JS::HandleObjec
p->parentProto = jsb_cocos2d_extension_Control_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ControlSwitch.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_ScrollView_class;
@ -6096,6 +6102,7 @@ void js_register_cocos2dx_extension_ScrollView(JSContext *cx, JS::HandleObject g
p->parentProto = jsb_cocos2d_Layer_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.ScrollView.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_TableViewCell_class;
@ -6285,6 +6292,7 @@ void js_register_cocos2dx_extension_TableViewCell(JSContext *cx, JS::HandleObjec
p->parentProto = jsb_cocos2d_Node_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TableViewCell.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_TableView_class;
@ -6687,6 +6695,7 @@ void js_register_cocos2dx_extension_TableView(JSContext *cx, JS::HandleObject gl
p->parentProto = jsb_cocos2d_extension_ScrollView_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { cc.TableView.extend = cc.Class.extend; })()");
}
JSClass *jsb_cocos2d_extension_EventAssetsManagerEx_class;

View File

@ -145,24 +145,6 @@ bool js_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose(JSContext *cx, uint3
JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
spine::SkeletonRenderer* cobj = (spine::SkeletonRenderer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->isOpacityModifyRGB();
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_spine_SkeletonRenderer_initWithData(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -231,26 +213,6 @@ bool js_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose(JSContext *cx, uint3
JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
spine::SkeletonRenderer* cobj = (spine::SkeletonRenderer *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB : Invalid Native Object");
if (argc == 1) {
bool arg0;
arg0 = JS::ToBoolean(args.get(0));
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB : Error processing arguments");
cobj->setOpacityModifyRGB(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_spine_SkeletonRenderer_setToSetupPose(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@ -914,11 +876,9 @@ void js_register_cocos2dx_spine_SkeletonRenderer(JSContext *cx, JS::HandleObject
JS_FN("getDebugSlotsEnabled", js_cocos2dx_spine_SkeletonRenderer_getDebugSlotsEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setAttachment", js_cocos2dx_spine_SkeletonRenderer_setAttachment, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setBonesToSetupPose", js_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("isOpacityModifyRGB", js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("initWithData", js_cocos2dx_spine_SkeletonRenderer_initWithData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setDebugSlotsEnabled", js_cocos2dx_spine_SkeletonRenderer_setDebugSlotsEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setSlotsToSetupPose", js_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setOpacityModifyRGB", js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setToSetupPose", js_cocos2dx_spine_SkeletonRenderer_setToSetupPose, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getBlendFunc", js_cocos2dx_spine_SkeletonRenderer_getBlendFunc, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("drawSkeleton", js_cocos2dx_spine_SkeletonRenderer_drawSkeleton, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
@ -1883,6 +1843,7 @@ void js_register_cocos2dx_spine_SkeletonAnimation(JSContext *cx, JS::HandleObjec
p->parentProto = jsb_spine_SkeletonRenderer_prototype;
_js_global_type_map.insert(std::make_pair(typeName, p));
}
anonEvaluate(cx, global, "(function () { sp.SkeletonAnimation.extend = cc.Class.extend; })()");
}
void register_all_cocos2dx_spine(JSContext* cx, JS::HandleObject obj) {

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