Merge branch 'develop' of github.com:cocos-creator/cocos2d-x-lite into develop

This commit is contained in:
Nan Wang
2016-07-19 10:56:13 +08:00
127 changed files with 3287 additions and 6489 deletions
@@ -1487,6 +1487,14 @@
ED9C6A9618599AD8000A5232 /* CCNodeGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = ED9C6A9318599AD8000A5232 /* CCNodeGrid.h */; };
ED9C6A9718599AD8000A5232 /* CCNodeGrid.h in Headers */ = {isa = PBXBuildFile; fileRef = ED9C6A9318599AD8000A5232 /* CCNodeGrid.h */; };
EDE5DFF81C0D6B3F0014147A /* libwebsockets.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EDE5DFF71C0D6B3F0014147A /* libwebsockets.a */; };
FAC8F25C1D339EB70061CEDD /* CCTMXLayer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FAC8F2581D339EB70061CEDD /* CCTMXLayer.cpp */; };
FAC8F25D1D339EB70061CEDD /* CCTMXLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = FAC8F2591D339EB70061CEDD /* CCTMXLayer.h */; };
FAC8F25E1D339EB70061CEDD /* CCTMXTiledMap.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FAC8F25A1D339EB70061CEDD /* CCTMXTiledMap.cpp */; };
FAC8F25F1D339EB70061CEDD /* CCTMXTiledMap.h in Headers */ = {isa = PBXBuildFile; fileRef = FAC8F25B1D339EB70061CEDD /* CCTMXTiledMap.h */; };
FAC8F2601D339EBF0061CEDD /* CCTMXLayer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FAC8F2581D339EB70061CEDD /* CCTMXLayer.cpp */; };
FAC8F2611D339EC20061CEDD /* CCTMXLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = FAC8F2591D339EB70061CEDD /* CCTMXLayer.h */; };
FAC8F2621D339EC50061CEDD /* CCTMXTiledMap.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FAC8F25A1D339EB70061CEDD /* CCTMXTiledMap.cpp */; };
FAC8F2631D339EC80061CEDD /* CCTMXTiledMap.h in Headers */ = {isa = PBXBuildFile; fileRef = FAC8F25B1D339EB70061CEDD /* CCTMXTiledMap.h */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -2310,6 +2318,10 @@
ED9C6A9218599AD8000A5232 /* CCNodeGrid.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; lineEnding = 0; path = CCNodeGrid.cpp; sourceTree = "<group>"; xcLanguageSpecificationIdentifier = xcode.lang.cpp; };
ED9C6A9318599AD8000A5232 /* CCNodeGrid.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCNodeGrid.h; sourceTree = "<group>"; };
EDE5DFF71C0D6B3F0014147A /* libwebsockets.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libwebsockets.a; path = ../external/ios/libs/libwebsockets.a; sourceTree = "<group>"; };
FAC8F2581D339EB70061CEDD /* CCTMXLayer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCTMXLayer.cpp; sourceTree = "<group>"; };
FAC8F2591D339EB70061CEDD /* CCTMXLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXLayer.h; sourceTree = "<group>"; };
FAC8F25A1D339EB70061CEDD /* CCTMXTiledMap.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCTMXTiledMap.cpp; sourceTree = "<group>"; };
FAC8F25B1D339EB70061CEDD /* CCTMXTiledMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCTMXTiledMap.h; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -2739,6 +2751,10 @@
1A5702DF180BCE610088DEC7 /* tilemap-parallax-nodes */ = {
isa = PBXGroup;
children = (
FAC8F2581D339EB70061CEDD /* CCTMXLayer.cpp */,
FAC8F2591D339EB70061CEDD /* CCTMXLayer.h */,
FAC8F25A1D339EB70061CEDD /* CCTMXTiledMap.cpp */,
FAC8F25B1D339EB70061CEDD /* CCTMXTiledMap.h */,
B24AA981195A675C007B4522 /* CCFastTMXLayer.cpp */,
B24AA982195A675C007B4522 /* CCFastTMXLayer.h */,
B24AA983195A675C007B4522 /* CCFastTMXTiledMap.cpp */,
@@ -3948,6 +3964,7 @@
B29A7E1919EE1B7700872B35 /* Event.h in Headers */,
15AE18AA19AAD33D00C27E9E /* CocosBuilder.h in Headers */,
BA679B3A1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h in Headers */,
FAC8F25F1D339EB70061CEDD /* CCTMXTiledMap.h in Headers */,
50ABC0071926664800A911A9 /* CCApplicationProtocol.h in Headers */,
B29A7E1D19EE1B7700872B35 /* PolygonBatch.h in Headers */,
50ABBD4E1925AB0000A911A9 /* MathUtil.h in Headers */,
@@ -4048,6 +4065,7 @@
15AE18A919AAD33D00C27E9E /* CCSpriteLoader.h in Headers */,
50693C601B6BF2AE005C5820 /* CCDownloader.h in Headers */,
50ABBEC91925AB6F00A911A9 /* firePngData.h in Headers */,
FAC8F25D1D339EB70061CEDD /* CCTMXLayer.h in Headers */,
503DD8F51926B0DB00CD74DD /* CCIMEDelegate.h in Headers */,
50ABBD5A1925AB0000A911A9 /* Vec2.h in Headers */,
15AE1BDB19AAE01E00C27E9E /* CCControlSwitch.h in Headers */,
@@ -4323,6 +4341,7 @@
B29A7E2019EE1B7700872B35 /* BoneData.h in Headers */,
503DD8F61926B0DB00CD74DD /* CCIMEDelegate.h in Headers */,
1A570228180BCC1A0088DEC7 /* CCParticleExamples.h in Headers */,
FAC8F2631D339EC80061CEDD /* CCTMXTiledMap.h in Headers */,
1A57022C180BCC1A0088DEC7 /* CCParticleSystem.h in Headers */,
15AE1BAC19AADFDF00C27E9E /* UILayout.h in Headers */,
1A570230180BCC1A0088DEC7 /* CCParticleSystemQuad.h in Headers */,
@@ -4383,6 +4402,7 @@
BA679B3B1CEC373000F875FA /* CCEventListenerAssetsManagerEx.h in Headers */,
15AE18AC19AAD33D00C27E9E /* CCBAnimationManager.h in Headers */,
292DB14219B4574100A80320 /* UIEditBoxImpl.h in Headers */,
FAC8F2611D339EC20061CEDD /* CCTMXLayer.h in Headers */,
1A570303180BCE890088DEC7 /* CCParallaxNode.h in Headers */,
50ABBE2A1925AB6F00A911A9 /* CCAutoreleasePool.h in Headers */,
1A57030F180BCF190088DEC7 /* CCComponent.h in Headers */,
@@ -4664,8 +4684,10 @@
1A570089180BC5A10088DEC7 /* CCActionProgressTimer.cpp in Sources */,
1A57008D180BC5A10088DEC7 /* CCActionTiledGrid.cpp in Sources */,
1A570091180BC5A10088DEC7 /* CCActionTween.cpp in Sources */,
FAC8F25C1D339EB70061CEDD /* CCTMXLayer.cpp in Sources */,
15AE188419AAD33D00C27E9E /* CCBSequence.cpp in Sources */,
50ABBEBF1925AB6F00A911A9 /* CCValue.cpp in Sources */,
FAC8F25E1D339EB70061CEDD /* CCTMXTiledMap.cpp in Sources */,
1A570098180BC5C10088DEC7 /* CCAtlasNode.cpp in Sources */,
1A57009E180BC5D20088DEC7 /* CCNode.cpp in Sources */,
B257B460198A353E00D9A687 /* CCPrimitiveCommand.cpp in Sources */,
@@ -4979,6 +5001,7 @@
1A570072180BC5A10088DEC7 /* CCActionGrid.cpp in Sources */,
ED3057C21BEC78A80083C3ED /* xxhash.c in Sources */,
52B47A301A5349A3004E4C60 /* HttpClient-apple.mm in Sources */,
FAC8F2601D339EBF0061CEDD /* CCTMXLayer.cpp in Sources */,
ED30578C1BEC77510083C3ED /* ioapi.cpp in Sources */,
B29A7E1619EE1B7700872B35 /* BoundingBoxAttachment.c in Sources */,
DABC9FAA19E7DFA900FA252C /* CCClippingRectangleNode.cpp in Sources */,
@@ -5083,6 +5106,7 @@
15AE1B7C19AADA9A00C27E9E /* UISlider.cpp in Sources */,
B29A7DE219EE1B7700872B35 /* MeshAttachment.c in Sources */,
15AE1BAD19AADFDF00C27E9E /* UILayoutParameter.cpp in Sources */,
FAC8F2621D339EC50061CEDD /* CCTMXTiledMap.cpp in Sources */,
B29A7DDE19EE1B7700872B35 /* BoneData.c in Sources */,
1A5701C8180BCB5A0088DEC7 /* CCLabelTextFormatter.cpp in Sources */,
291901461B05895600F8B4BA /* CCNinePatchImageParser.cpp in Sources */,
+6
View File
@@ -2338,7 +2338,9 @@ void Animate::stop()
{
if (_animation->getRestoreOriginalFrame() && _target)
{
auto blend = static_cast<Sprite*>(_target)->getBlendFunc();
static_cast<Sprite*>(_target)->setSpriteFrame(_origFrame);
static_cast<Sprite*>(_target)->setBlendFunc(blend);
}
ActionInterval::stop();
@@ -2373,12 +2375,16 @@ void Animate::update(float t)
if( splitTime <= t )
{
auto blend = static_cast<Sprite*>(_target)->getBlendFunc();
_currFrameIndex = i;
AnimationFrame* frame = frames.at(_currFrameIndex);
frameToDisplay = frame->getSpriteFrame();
CCASSERT(_target, "Animate::update error: _target should not null");
if(_target)
{
static_cast<Sprite*>(_target)->setSpriteFrame(frameToDisplay);
static_cast<Sprite*>(_target)->setBlendFunc(blend);
}
const ValueMap& dict = frame->getUserInfo();
if ( !dict.empty() )
+22 -2
View File
@@ -280,9 +280,29 @@ Node* ClippingNode::getStencil() const
void ClippingNode::setStencil(Node *stencil)
{
CC_SAFE_RETAIN(stencil);
CC_SAFE_RELEASE(_stencil);
//early out if the stencil is already set
if (_stencil == stencil)
return;
//cleanup current stencil
if(_stencil != nullptr && _stencil->isRunning())
{
_stencil->onExitTransitionDidStart();
_stencil->onExit();
}
CC_SAFE_RELEASE_NULL(_stencil);
//initialise new stencil
_stencil = stencil;
CC_SAFE_RETAIN(_stencil);
if(_stencil != nullptr && this->isRunning())
{
_stencil->onEnter();
if(this->_isTransitionFinished)
{
_stencil->onEnterTransitionDidFinish();
}
}
}
bool ClippingNode::hasContent() const
+2
View File
@@ -41,6 +41,7 @@ THE SOFTWARE.
#include "base/CCString.h"
NS_CC_BEGIN
namespace experimental {
const int TMXLayer::FAST_TMX_ORIENTATION_ORTHO = 0;
const int TMXLayer::FAST_TMX_ORIENTATION_HEX = 1;
@@ -868,6 +869,7 @@ std::string TMXLayer::getDescription() const
return StringUtils::format("<FastTMXLayer | tag = %d, size = %d,%d>", _tag, (int)_mapTileSize.width, (int)_mapTileSize.height);
}
} //end of namespace experimental
NS_CC_END
+2 -1
View File
@@ -40,6 +40,7 @@ class Texture2D;
class Sprite;
struct _ccCArray;
namespace experimental{
/**
* @addtogroup _2d
@@ -358,7 +359,7 @@ public:
// end of tilemap_parallax_nodes group
/// @}
} //end of namespace experimental
NS_CC_END
#endif //__CCTMX_LAYER2_H__
+2
View File
@@ -26,6 +26,7 @@ THE SOFTWARE.
#include "base/CCString.h"
NS_CC_BEGIN
namespace experimental {
// implementation FastTMXTiledMap
@@ -259,6 +260,7 @@ std::string TMXTiledMap::getDescription() const
return StringUtils::format("<FastTMXTiledMap | Tag = %d, Layers = %d", _tag, static_cast<int>(_children.size()));
}
} //end of namespace experimental
NS_CC_END
+2
View File
@@ -32,6 +32,7 @@ NS_CC_BEGIN
class TMXLayerInfo;
class TMXTilesetInfo;
class TMXMapInfo;
namespace experimental {
class TMXLayer;
/**
@@ -242,6 +243,7 @@ private:
// end of tilemap_parallax_nodes group
/** @} */
} //end of namespace experimental
NS_CC_END
+1
View File
@@ -319,6 +319,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat
_sprite->setFlippedY(true);
_sprite->setBlendFunc( BlendFunc::ALPHA_PREMULTIPLIED );
_sprite->setOpacityModifyRGB(true);
glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
+779
View File
@@ -0,0 +1,779 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "2d/CCTMXLayer.h"
#include "2d/CCTMXTiledMap.h"
#include "2d/CCSprite.h"
#include "base/CCDirector.h"
#include "base/ccUTF8.h"
#include "renderer/CCTextureCache.h"
#include "renderer/CCGLProgram.h"
#include "base/CCString.h"
NS_CC_BEGIN
// TMXLayer - init & alloc & dealloc
TMXLayer * TMXLayer::create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
{
TMXLayer *ret = new (std::nothrow) TMXLayer();
if (ret->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
{
// FIXME:: is 35% a good estimate ?
Size size = layerInfo->_layerSize;
float totalNumberOfTiles = size.width * size.height;
float capacity = totalNumberOfTiles * 0.35f + 1; // 35 percent is occupied ?
Texture2D *texture = nullptr;
if( tilesetInfo )
{
texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage);
}
if (nullptr == texture)
return false;
if (SpriteBatchNode::initWithTexture(texture, static_cast<ssize_t>(capacity)))
{
// layerInfo
_layerName = layerInfo->_name;
_layerSize = size;
_tiles = layerInfo->_tiles;
_opacity = layerInfo->_opacity;
setProperties(layerInfo->getProperties());
_contentScaleFactor = Director::getInstance()->getContentScaleFactor();
// tilesetInfo
_tileSet = tilesetInfo;
CC_SAFE_RETAIN(_tileSet);
// mapInfo
_mapTileSize = mapInfo->getTileSize();
_layerOrientation = mapInfo->getOrientation();
_staggerAxis = mapInfo->getStaggerAxis();
_staggerIndex = mapInfo->getStaggerIndex();
_hexSideLength = mapInfo->getHexSideLength();
// offset (after layer orientation is set);
Vec2 offset = this->calculateLayerOffset(layerInfo->_offset);
this->setPosition(CC_POINT_PIXELS_TO_POINTS(offset));
_atlasIndexArray = ccCArrayNew(totalNumberOfTiles);
this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(Size(_layerSize.width * _mapTileSize.width, _layerSize.height * _mapTileSize.height)));
_useAutomaticVertexZ = false;
_vertexZvalue = 0;
return true;
}
return false;
}
TMXLayer::TMXLayer()
:_layerName("")
,_opacity(0)
,_vertexZvalue(0)
,_useAutomaticVertexZ(false)
,_reusedTile(nullptr)
,_atlasIndexArray(nullptr)
,_contentScaleFactor(1.0f)
,_layerSize(Size::ZERO)
,_mapTileSize(Size::ZERO)
,_tiles(nullptr)
,_tileSet(nullptr)
,_layerOrientation(TMXOrientationOrtho)
,_staggerAxis(TMXStaggerAxis_Y)
,_staggerIndex(TMXStaggerIndex_Even)
,_hexSideLength(0)
{}
TMXLayer::~TMXLayer()
{
CC_SAFE_RELEASE(_tileSet);
CC_SAFE_RELEASE(_reusedTile);
if (_atlasIndexArray)
{
ccCArrayFree(_atlasIndexArray);
_atlasIndexArray = nullptr;
}
CC_SAFE_DELETE_ARRAY(_tiles);
}
void TMXLayer::releaseMap()
{
if (_tiles)
{
delete [] _tiles;
_tiles = nullptr;
}
if (_atlasIndexArray)
{
ccCArrayFree(_atlasIndexArray);
_atlasIndexArray = nullptr;
}
}
// TMXLayer - setup Tiles
void TMXLayer::setupTiles()
{
// Optimization: quick hack that sets the image size on the tileset
_tileSet->_imageSize = _textureAtlas->getTexture()->getContentSizeInPixels();
// By default all the tiles are aliased
// pros:
// - easier to render
// cons:
// - difficult to scale / rotate / etc.
_textureAtlas->getTexture()->setAliasTexParameters();
//CFByteOrder o = CFByteOrderGetCurrent();
// Parse cocos2d properties
this->parseInternalProperties();
for (int y=0; y < _layerSize.height; y++)
{
for (int x=0; x < _layerSize.width; x++)
{
int pos = static_cast<int>(x + _layerSize.width * y);
int gid = _tiles[ pos ];
// gid are stored in little endian.
// if host is big endian, then swap
//if( o == CFByteOrderBigEndian )
// gid = CFSwapInt32( gid );
/* We support little endian.*/
// FIXME:: gid == 0 --> empty tile
if (gid != 0)
{
this->appendTileForGID(gid, Vec2(x, y));
}
}
}
}
// TMXLayer - Properties
Value TMXLayer::getProperty(const std::string& propertyName) const
{
if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName);
return Value();
}
void TMXLayer::parseInternalProperties()
{
// if cc_vertex=automatic, then tiles will be rendered using vertexz
auto vertexz = getProperty("cc_vertexz");
if (!vertexz.isNull())
{
std::string vertexZStr = vertexz.asString();
// If "automatic" is on, then parse the "cc_alpha_func" too
if (vertexZStr == "automatic")
{
_useAutomaticVertexZ = true;
auto alphaFuncVal = getProperty("cc_alpha_func");
float alphaFuncValue = alphaFuncVal.asFloat();
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));
GLint alphaValueLocation = glGetUniformLocation(getGLProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
// NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
// use shader program to set uniform
getGLProgram()->use();
getGLProgram()->setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
CHECK_GL_ERROR_DEBUG();
}
else
{
_vertexZvalue = vertexz.asInt();
}
}
}
void TMXLayer::setupTileSprite(Sprite* sprite, const Vec2& pos, int gid)
{
sprite->setPosition(getPositionAt(pos));
sprite->setPositionZ((float)getVertexZForPos(pos));
sprite->setAnchorPoint(Vec2::ZERO);
sprite->setOpacity(_opacity);
//issue 1264, flip can be undone as well
sprite->setFlippedX(false);
sprite->setFlippedY(false);
sprite->setRotation(0.0f);
sprite->setAnchorPoint(Vec2(0,0));
// Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles.
if (gid & kTMXTileDiagonalFlag)
{
// put the anchor in the middle for ease of rotation.
sprite->setAnchorPoint(Vec2(0.5f,0.5f));
sprite->setPosition(getPositionAt(pos).x + sprite->getContentSize().height/2,
getPositionAt(pos).y + sprite->getContentSize().width/2 );
int flag = gid & (kTMXTileHorizontalFlag | kTMXTileVerticalFlag );
// handle the 4 diagonally flipped states.
if (flag == kTMXTileHorizontalFlag)
{
sprite->setRotation(90.0f);
}
else if (flag == kTMXTileVerticalFlag)
{
sprite->setRotation(270.0f);
}
else if (flag == (kTMXTileVerticalFlag | kTMXTileHorizontalFlag) )
{
sprite->setRotation(90.0f);
sprite->setFlippedX(true);
}
else
{
sprite->setRotation(270.0f);
sprite->setFlippedX(true);
}
}
else
{
if (gid & kTMXTileHorizontalFlag)
{
sprite->setFlippedX(true);
}
if (gid & kTMXTileVerticalFlag)
{
sprite->setFlippedY(true);
}
}
}
Sprite* TMXLayer::reusedTileWithRect(const Rect& rect)
{
if (! _reusedTile)
{
_reusedTile = Sprite::createWithTexture(_textureAtlas->getTexture(), rect);
_reusedTile->setBatchNode(this);
_reusedTile->retain();
}
else
{
// FIXME: HACK: Needed because if "batch node" is nil,
// then the Sprite'squad will be reset
_reusedTile->setBatchNode(nullptr);
// Re-init the sprite
_reusedTile->setTextureRect(rect, false, rect.size);
// restore the batch node
_reusedTile->setBatchNode(this);
}
return _reusedTile;
}
// TMXLayer - obtaining tiles/gids
Sprite * TMXLayer::getTileAt(const Vec2& pos)
{
CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
Sprite *tile = nullptr;
int gid = this->getTileGIDAt(pos);
// if GID == 0, then no tile is present
if (gid)
{
int z = (int)(pos.x + pos.y * _layerSize.width);
tile = static_cast<Sprite*>(this->getChildByTag(z));
// tile not created yet. create it
if (! tile)
{
Rect rect = _tileSet->getRectForGID(gid);
rect = CC_RECT_PIXELS_TO_POINTS(rect);
tile = Sprite::createWithTexture(this->getTexture(), rect);
tile->setBatchNode(this);
tile->setPosition(getPositionAt(pos));
tile->setPositionZ((float)getVertexZForPos(pos));
tile->setAnchorPoint(Vec2::ZERO);
tile->setOpacity(_opacity);
ssize_t indexForZ = atlasIndexForExistantZ(z);
this->addSpriteWithoutQuad(tile, static_cast<int>(indexForZ), z);
}
}
return tile;
}
uint32_t TMXLayer::getTileGIDAt(const Vec2& pos, TMXTileFlags* flags/* = nullptr*/)
{
CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
ssize_t idx = static_cast<int>(((int) pos.x + (int) pos.y * _layerSize.width));
// Bits on the far end of the 32-bit global tile ID are used for tile flags
uint32_t tile = _tiles[idx];
// issue1264, flipped tiles can be changed dynamically
if (flags)
{
*flags = (TMXTileFlags)(tile & kTMXFlipedAll);
}
return (tile & kTMXFlippedMask);
}
// TMXLayer - adding helper methods
Sprite * TMXLayer::insertTileForGID(uint32_t gid, const Vec2& pos)
{
if (gid != 0 && (static_cast<int>((gid & kTMXFlippedMask)) - _tileSet->_firstGid) >= 0)
{
Rect rect = _tileSet->getRectForGID(gid);
rect = CC_RECT_PIXELS_TO_POINTS(rect);
intptr_t z = (intptr_t)((int) pos.x + (int) pos.y * _layerSize.width);
Sprite *tile = reusedTileWithRect(rect);
setupTileSprite(tile, pos, gid);
// get atlas index
ssize_t indexForZ = atlasIndexForNewZ(static_cast<int>(z));
// Optimization: add the quad without adding a child
this->insertQuadFromSprite(tile, indexForZ);
// insert it into the local atlasindex array
ccCArrayInsertValueAtIndex(_atlasIndexArray, (void*)z, indexForZ);
// update possible children
for(const auto &child : _children) {
Sprite* sp = static_cast<Sprite*>(child);
ssize_t ai = sp->getAtlasIndex();
if ( ai >= indexForZ )
{
sp->setAtlasIndex(ai+1);
}
}
_tiles[z] = gid;
return tile;
}
return nullptr;
}
Sprite * TMXLayer::updateTileForGID(uint32_t gid, const Vec2& pos)
{
Rect rect = _tileSet->getRectForGID(gid);
rect = Rect(rect.origin.x / _contentScaleFactor, rect.origin.y / _contentScaleFactor, rect.size.width/ _contentScaleFactor, rect.size.height/ _contentScaleFactor);
int z = (int)((int) pos.x + (int) pos.y * _layerSize.width);
Sprite *tile = reusedTileWithRect(rect);
setupTileSprite(tile ,pos ,gid);
// get atlas index
ssize_t indexForZ = atlasIndexForExistantZ(z);
tile->setAtlasIndex(indexForZ);
tile->setDirty(true);
tile->updateTransform();
_tiles[z] = gid;
return tile;
}
// used only when parsing the map. useless after the map was parsed
// since lot's of assumptions are no longer true
Sprite * TMXLayer::appendTileForGID(uint32_t gid, const Vec2& pos)
{
if (gid != 0 && (static_cast<int>((gid & kTMXFlippedMask)) - _tileSet->_firstGid) >= 0)
{
Rect rect = _tileSet->getRectForGID(gid);
rect = CC_RECT_PIXELS_TO_POINTS(rect);
intptr_t z = (intptr_t)(pos.x + pos.y * _layerSize.width);
Sprite *tile = reusedTileWithRect(rect);
setupTileSprite(tile ,pos ,gid);
// optimization:
// The difference between appendTileForGID and insertTileforGID is that append is faster, since
// it appends the tile at the end of the texture atlas
ssize_t indexForZ = _atlasIndexArray->num;
// don't add it using the "standard" way.
insertQuadFromSprite(tile, indexForZ);
// append should be after addQuadFromSprite since it modifies the quantity values
ccCArrayInsertValueAtIndex(_atlasIndexArray, (void*)z, indexForZ);
return tile;
}
return nullptr;
}
// TMXLayer - atlasIndex and Z
static inline int compareInts(const void * a, const void * b)
{
return ((*(int*)a) - (*(int*)b));
}
ssize_t TMXLayer::atlasIndexForExistantZ(int z)
{
int key=z;
int *item = (int*)bsearch((void*)&key, (void*)&_atlasIndexArray->arr[0], _atlasIndexArray->num, sizeof(void*), compareInts);
CCASSERT(item, "TMX atlas index not found. Shall not happen");
ssize_t index = ((size_t)item - (size_t)_atlasIndexArray->arr) / sizeof(void*);
return index;
}
ssize_t TMXLayer::atlasIndexForNewZ(int z)
{
// FIXME:: This can be improved with a sort of binary search
ssize_t i=0;
for (i=0; i< _atlasIndexArray->num ; i++)
{
ssize_t val = (size_t) _atlasIndexArray->arr[i];
if (z < val)
{
break;
}
}
return i;
}
// TMXLayer - adding / remove tiles
void TMXLayer::setTileGID(uint32_t gid, const Vec2& pos)
{
setTileGID(gid, pos, (TMXTileFlags)0);
}
void TMXLayer::setTileGID(uint32_t gid, const Vec2& pos, TMXTileFlags flags)
{
CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
CCASSERT(gid == 0 || (int)gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" );
TMXTileFlags currentFlags;
uint32_t currentGID = getTileGIDAt(pos, &currentFlags);
if (currentGID != gid || currentFlags != flags)
{
uint32_t gidAndFlags = gid | flags;
// setting gid=0 is equal to remove the tile
if (gid == 0)
{
removeTileAt(pos);
}
// empty tile. create a new one
else if (currentGID == 0)
{
insertTileForGID(gidAndFlags, pos);
}
// modifying an existing tile with a non-empty tile
else
{
int z = (int) pos.x + (int) pos.y * _layerSize.width;
Sprite *sprite = static_cast<Sprite*>(getChildByTag(z));
if (sprite)
{
Rect rect = _tileSet->getRectForGID(gid);
rect = CC_RECT_PIXELS_TO_POINTS(rect);
sprite->setTextureRect(rect, false, rect.size);
if (flags)
{
setupTileSprite(sprite, sprite->getPosition(), gidAndFlags);
}
_tiles[z] = gidAndFlags;
}
else
{
updateTileForGID(gidAndFlags, pos);
}
}
}
}
void TMXLayer::addChild(Node * child, int zOrder, int tag)
{
CC_UNUSED_PARAM(child);
CC_UNUSED_PARAM(zOrder);
CC_UNUSED_PARAM(tag);
CCASSERT(0, "addChild: is not supported on TMXLayer. Instead use setTileGID:at:/tileAt:");
}
void TMXLayer::removeChild(Node* node, bool cleanup)
{
Sprite *sprite = (Sprite*)node;
// allows removing nil objects
if (! sprite)
{
return;
}
CCASSERT(_children.contains(sprite), "Tile does not belong to TMXLayer");
ssize_t atlasIndex = sprite->getAtlasIndex();
ssize_t zz = (ssize_t)_atlasIndexArray->arr[atlasIndex];
_tiles[zz] = 0;
ccCArrayRemoveValueAtIndex(_atlasIndexArray, atlasIndex);
SpriteBatchNode::removeChild(sprite, cleanup);
}
void TMXLayer::removeTileAt(const Vec2& pos)
{
CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
int gid = getTileGIDAt(pos);
if (gid)
{
int z = pos.x + pos.y * _layerSize.width;
ssize_t atlasIndex = atlasIndexForExistantZ(z);
// remove tile from GID map
_tiles[z] = 0;
// remove tile from atlas position array
ccCArrayRemoveValueAtIndex(_atlasIndexArray, atlasIndex);
// remove it from sprites and/or texture atlas
Sprite *sprite = (Sprite*)getChildByTag(z);
if (sprite)
{
SpriteBatchNode::removeChild(sprite, true);
}
else
{
_textureAtlas->removeQuadAtIndex(atlasIndex);
// update possible children
for(const auto &obj : _children) {
Sprite* child = static_cast<Sprite*>(obj);
ssize_t ai = child->getAtlasIndex();
if ( ai >= atlasIndex )
{
child->setAtlasIndex(ai-1);
}
}
}
}
}
//CCTMXLayer - obtaining positions, offset
Vec2 TMXLayer::calculateLayerOffset(const Vec2& pos)
{
Vec2 ret;
switch (_layerOrientation)
{
case TMXOrientationOrtho:
ret.set( pos.x * _mapTileSize.width, -pos.y *_mapTileSize.height);
break;
case TMXOrientationIso:
ret.set((_mapTileSize.width /2) * (pos.x - pos.y),
(_mapTileSize.height /2 ) * (-pos.x - pos.y));
break;
case TMXOrientationHex:
{
if(_staggerAxis == TMXStaggerAxis_Y)
{
int diffX = (_staggerIndex == TMXStaggerIndex_Even) ? _mapTileSize.width/2 : 0;
ret.set(pos.x * _mapTileSize.width + diffX, -pos.y * (_mapTileSize.height - (_mapTileSize.width - _hexSideLength) / 2));
}
else if(_staggerAxis == TMXStaggerAxis_X)
{
int diffY = (_staggerIndex == TMXStaggerIndex_Odd) ? _mapTileSize.height/2 : 0;
ret.set(pos.x * (_mapTileSize.width - (_mapTileSize.width - _hexSideLength) / 2), -pos.y * _mapTileSize.height + diffY);
}
break;
}
case TMXOrientationStaggered:
{
float diffX = 0;
if ((int)std::abs(pos.y) % 2 == 1)
{
diffX = _mapTileSize.width/2;
}
ret.set(pos.x * _mapTileSize.width + diffX,
(-pos.y) * _mapTileSize.height/2);
}
break;
}
return ret;
}
Vec2 TMXLayer::getPositionAt(const Vec2& pos)
{
Vec2 ret;
switch (_layerOrientation)
{
case TMXOrientationOrtho:
ret = getPositionForOrthoAt(pos);
break;
case TMXOrientationIso:
ret = getPositionForIsoAt(pos);
break;
case TMXOrientationHex:
ret = getPositionForHexAt(pos);
break;
case TMXOrientationStaggered:
ret = getPositionForStaggeredAt(pos);
break;
}
ret = CC_POINT_PIXELS_TO_POINTS( ret );
return ret;
}
Vec2 TMXLayer::getPositionForOrthoAt(const Vec2& pos)
{
return Vec2(pos.x * _mapTileSize.width,
(_layerSize.height - pos.y - 1) * _mapTileSize.height);
}
Vec2 TMXLayer::getPositionForIsoAt(const Vec2& pos)
{
return Vec2(_mapTileSize.width /2 * (_layerSize.width + pos.x - pos.y - 1),
_mapTileSize.height /2 * ((_layerSize.height * 2 - pos.x - pos.y) - 2));
}
Vec2 TMXLayer::getPositionForHexAt(const Vec2& pos)
{
Vec2 xy;
Vec2 offset = _tileSet->_tileOffset;
int odd_even = (_staggerIndex == TMXStaggerIndex_Odd) ? 1 : -1;
switch (_staggerAxis)
{
case TMXStaggerAxis_Y:
{
float diffX = 0;
if ((int)pos.y % 2 == 1)
{
diffX = _mapTileSize.width/2 * odd_even;
}
xy = Vec2(pos.x * _mapTileSize.width+diffX+offset.x,
(_layerSize.height - pos.y - 1) * (_mapTileSize.height-(_mapTileSize.height-_hexSideLength)/2)-offset.y);
break;
}
case TMXStaggerAxis_X:
{
float diffY = 0;
if ((int)pos.x % 2 == 1)
{
diffY = _mapTileSize.height/2 * -odd_even;
}
xy = Vec2(pos.x * (_mapTileSize.width-(_mapTileSize.width-_hexSideLength)/2)+offset.x,
(_layerSize.height - pos.y - 1) * _mapTileSize.height + diffY-offset.y);
break;
}
}
return xy;
}
Vec2 TMXLayer::getPositionForStaggeredAt(const Vec2 &pos)
{
float diffX = 0;
if ((int)pos.y % 2 == 1)
{
diffX = _mapTileSize.width/2;
}
return Vec2(pos.x * _mapTileSize.width + diffX,
(_layerSize.height - pos.y - 1) * _mapTileSize.height/2);
}
int TMXLayer::getVertexZForPos(const Vec2& pos)
{
int ret = 0;
int maxVal = 0;
if (_useAutomaticVertexZ)
{
switch (_layerOrientation)
{
case TMXOrientationIso:
maxVal = static_cast<int>(_layerSize.width + _layerSize.height);
ret = static_cast<int>(-(maxVal - (pos.x + pos.y)));
break;
case TMXOrientationOrtho:
ret = static_cast<int>(-(_layerSize.height-pos.y));
break;
case TMXOrientationStaggered:
ret = static_cast<int>(-(_layerSize.height-pos.y));
break;
case TMXOrientationHex:
ret = static_cast<int>(-(_layerSize.height-pos.y));
break;
default:
CCASSERT(0, "TMX invalid value");
break;
}
}
else
{
ret = _vertexZvalue;
}
return ret;
}
std::string TMXLayer::getDescription() const
{
return StringUtils::format("<TMXLayer | tag = %d, size = %d,%d>", _tag, (int)_mapTileSize.width, (int)_mapTileSize.height);
}
NS_CC_END
+361
View File
@@ -0,0 +1,361 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCTMX_LAYER_H__
#define __CCTMX_LAYER_H__
#include "2d/CCSpriteBatchNode.h"
#include "2d/CCTMXXMLParser.h"
#include "base/ccCArray.h"
NS_CC_BEGIN
class TMXMapInfo;
class TMXLayerInfo;
class TMXTilesetInfo;
struct _ccCArray;
/**
* @addtogroup _2d
* @{
*/
/** @brief TMXLayer represents the TMX layer.
* It is a subclass of SpriteBatchNode. By default the tiles are rendered using a TextureAtlas.
* If you modify a tile on runtime, then, that tile will become a Sprite, otherwise no Sprite objects are created.
* The benefits of using Sprite objects as tiles are:
* - tiles (Sprite) can be rotated/scaled/moved with a nice API.
* If the layer contains a property named "cc_vertexz" with an integer (in can be positive or negative),
* then all the tiles belonging to the layer will use that value as their OpenGL vertex Z for depth.
* On the other hand, if the "cc_vertexz" property has the "automatic" value, then the tiles will use an automatic vertex Z value.
* Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled after drawing them. The used alpha func will be:
* glAlphaFunc( GL_GREATER, value ).
* "value" by default is 0, but you can change it from Tiled by adding the "cc_alpha_func" property to the layer.
* The value 0 should work for most cases, but if you have tiles that are semi-transparent, then you might want to use a different
* value, like 0.5.
* For further information, please see the programming guide:
* http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
* @since v0.8.1
* Tiles can have tile flags for additional properties. At the moment only flip horizontal and flip vertical are used. These bit flags are defined in TMXXMLParser.h.
* @since 1.1
*/
class CC_DLL TMXLayer : public SpriteBatchNode
{
public:
/** Creates a TMXLayer with an tileset info, a layer info and a map info.
*
* @param tilesetInfo An tileset info.
* @param layerInfo A layer info.
* @param mapInfo A map info.
* @return An autorelease object.
*/
static TMXLayer * create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
/**
* @js ctor
*/
TMXLayer();
/**
* @js NA
* @lua NA
*/
virtual ~TMXLayer();
/** Initializes a TMXLayer with a tileset info, a layer info and a map info.
*
* @param tilesetInfo An tileset info.
* @param layerInfo A layer info.
* @param mapInfo A map info.
* @return If initializes successfully, it will return true.
*/
bool initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
/** Dealloc the map that contains the tile position from memory.
* Unless you want to know at runtime the tiles positions, you can safely call this method.
* If you are going to call layer->tileGIDAt() then, don't release the map.
*/
void releaseMap();
/** Returns the tile (Sprite) at a given a tile coordinate.
* The returned Sprite will be already added to the TMXLayer. Don't add it again.
* The Sprite can be treated like any other Sprite: rotated, scaled, translated, opacity, color, etc.
* You can remove either by calling:
* - layer->removeChild(sprite, cleanup);
* - or layer->removeTileAt(Vec2(x,y));
*
* @param tileCoordinate A tile coordinate.
* @return Returns the tile (Sprite) at a given a tile coordinate.
*/
Sprite* getTileAt(const Vec2& tileCoordinate);
/**
* @js NA
*/
CC_DEPRECATED_ATTRIBUTE Sprite* tileAt(const Vec2& tileCoordinate) { return getTileAt(tileCoordinate); };
/** Returns the tile gid at a given tile coordinate. It also returns the tile flags.
* This method requires the tile map has not been previously released (eg. don't call [layer releaseMap]).
*
* @param tileCoordinate The tile coordinate.
* @param flags Tile flags.
* @return Returns the tile gid at a given tile coordinate. It also returns the tile flags.
*/
uint32_t getTileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags = nullptr);
/**
* @js NA
*/
CC_DEPRECATED_ATTRIBUTE uint32_t tileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags = nullptr){
return getTileGIDAt(tileCoordinate, flags);
};
/** Sets the tile gid (gid = tile global id) at a given tile coordinate.
* The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
* If a tile is already placed at that position, then it will be removed.
*
* @param gid The tile gid.
* @param tileCoordinate The tile coordinate.
*/
void setTileGID(uint32_t gid, const Vec2& tileCoordinate);
/** Sets the tile gid (gid = tile global id) at a given tile coordinate.
* The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor -> Tileset Mgr +1.
* If a tile is already placed at that position, then it will be removed.
* Use withFlags if the tile flags need to be changed as well.
*
* @param gid The tile gid.
* @param tileCoordinate The tile coordinate.
* @param flags The tile flags.
*/
void setTileGID(uint32_t gid, const Vec2& tileCoordinate, TMXTileFlags flags);
/** Removes a tile at given tile coordinate.
*
* @param tileCoordinate The tile coordinate.
*/
void removeTileAt(const Vec2& tileCoordinate);
/** Returns the position in points of a given tile coordinate.
*
* @param tileCoordinate The tile coordinate.
* @return The position in points of a given tile coordinate.
*/
Vec2 getPositionAt(const Vec2& tileCoordinate);
/**
* @js NA
*/
CC_DEPRECATED_ATTRIBUTE Vec2 positionAt(const Vec2& tileCoordinate) { return getPositionAt(tileCoordinate); };
/** Return the value for the specific property name.
*
* @param propertyName The specific property name.
* @return Return the value for the specific property name.
*/
Value getProperty(const std::string& propertyName) const;
/**
* @js NA
*/
CC_DEPRECATED_ATTRIBUTE Value propertyNamed(const std::string& propertyName) const { return getProperty(propertyName); };
/** Creates the tiles. */
void setupTiles();
/** Get the layer name.
*
* @return The layer name.
*/
inline const std::string& getLayerName(){ return _layerName; }
/** Set the layer name.
*
* @param layerName The layer name.
*/
inline void setLayerName(const std::string& layerName){ _layerName = layerName; }
/** Size of the layer in tiles.
*
* @return Size of the layer in tiles.
*/
inline const Size& getLayerSize() const { return _layerSize; };
/** Set size of the layer in tiles.
*
* @param size Size of the layer in tiles.
*/
inline void setLayerSize(const Size& size) { _layerSize = size; };
/** Size of the map's tile (could be different from the tile's size).
*
* @return The size of the map's tile.
*/
inline const Size& getMapTileSize() const { return _mapTileSize; };
/** Set the size of the map's tile.
*
* @param size The size of the map's tile.
*/
inline void setMapTileSize(const Size& size) { _mapTileSize = size; };
/** Pointer to the map of tiles.
* @js NA
* @lua NA
* @return Pointer to the map of tiles.
*/
uint32_t* getTiles() const { return _tiles; };
/** Set a pointer to the map of tiles.
*
* @param tiles A pointer to the map of tiles.
*/
void setTiles(uint32_t* tiles) { _tiles = tiles; };
/** Tileset information for the layer.
*
* @return Tileset information for the layer.
*/
inline TMXTilesetInfo* getTileSet() const { return _tileSet; };
/** Set tileset information for the layer.
*
* @param info The tileset information for the layer.
* @js NA
*/
inline void setTileSet(TMXTilesetInfo* info) {
CC_SAFE_RETAIN(info);
CC_SAFE_RELEASE(_tileSet);
_tileSet = info;
};
/** Layer orientation, which is the same as the map orientation.
*
* @return Layer orientation, which is the same as the map orientation.
*/
inline int getLayerOrientation() const { return _layerOrientation; };
/** Set layer orientation, which is the same as the map orientation.
*
* @param orientation Layer orientation,which is the same as the map orientation.
*/
inline void setLayerOrientation(int orientation) { _layerOrientation = orientation; };
/** Properties from the layer. They can be added using Tiled.
*
* @return Properties from the layer. They can be added using Tiled.
*/
inline const ValueMap& getProperties() const { return _properties; };
/** Properties from the layer. They can be added using Tiled.
*
* @return Properties from the layer. They can be added using Tiled.
*/
inline ValueMap& getProperties() { return _properties; };
/** Set an Properties from to layer.
*
* @param properties It is used to set the layer Properties.
*/
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
//
// Override
//
/** TMXLayer doesn't support adding a Sprite manually.
@warning addChild(z, tag); is not supported on TMXLayer. Instead of setTileGID.
*/
using SpriteBatchNode::addChild;
virtual void addChild(Node * child, int zOrder, int tag) override;
// super method
void removeChild(Node* child, bool cleanup) override;
/**
* @js NA
*/
virtual std::string getDescription() const override;
protected:
Vec2 getPositionForIsoAt(const Vec2& pos);
Vec2 getPositionForOrthoAt(const Vec2& pos);
Vec2 getPositionForHexAt(const Vec2& pos);
Vec2 getPositionForStaggeredAt(const Vec2& pos);
Vec2 calculateLayerOffset(const Vec2& offset);
/* optimization methods */
Sprite* appendTileForGID(uint32_t gid, const Vec2& pos);
Sprite* insertTileForGID(uint32_t gid, const Vec2& pos);
Sprite* updateTileForGID(uint32_t gid, const Vec2& pos);
/* The layer recognizes some special properties, like cc_vertexz */
void parseInternalProperties();
void setupTileSprite(Sprite* sprite, const Vec2& pos, int gid);
Sprite* reusedTileWithRect(const Rect& rect);
int getVertexZForPos(const Vec2& pos);
// index
ssize_t atlasIndexForExistantZ(int z);
ssize_t atlasIndexForNewZ(int z);
//! name of the layer
std::string _layerName;
//! TMX Layer supports opacity
unsigned char _opacity;
//! Only used when vertexZ is used
int _vertexZvalue;
bool _useAutomaticVertexZ;
//! used for optimization
Sprite *_reusedTile;
ccCArray *_atlasIndexArray;
// used for retina display
float _contentScaleFactor;
/** size of the layer in tiles */
Size _layerSize;
/** size of the map's tile (could be different from the tile's size) */
Size _mapTileSize;
/** pointer to the map of tiles */
uint32_t* _tiles;
/** Tileset information for the layer */
TMXTilesetInfo* _tileSet;
/** Layer orientation, which is the same as the map orientation */
int _layerOrientation;
/** Stagger Axis */
int _staggerAxis;
/** Stagger Index */
int _staggerIndex;
/** Hex side length*/
int _hexSideLength;
/** properties from the layer. They can be added using Tiled */
ValueMap _properties;
};
// end of tilemap_parallax_nodes group
/** @} */
NS_CC_END
#endif //__CCTMX_LAYER_H__
+285
View File
@@ -0,0 +1,285 @@
/****************************************************************************
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "2d/CCTMXTiledMap.h"
#include "2d/CCTMXXMLParser.h"
#include "2d/CCTMXLayer.h"
#include "2d/CCSprite.h"
#include "base/ccUTF8.h"
#include "base/CCString.h"
NS_CC_BEGIN
// implementation TMXTiledMap
TMXTiledMap * TMXTiledMap::create(const std::string& tmxFile)
{
TMXTiledMap *ret = new (std::nothrow) TMXTiledMap();
if (ret->initWithTMXFile(tmxFile))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
TMXTiledMap* TMXTiledMap::createWithXML(const std::string& tmxString, const std::string& resourcePath)
{
TMXTiledMap *ret = new (std::nothrow) TMXTiledMap();
if (ret->initWithXML(tmxString, resourcePath))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool TMXTiledMap::initWithTMXFile(const std::string& tmxFile)
{
CCASSERT(tmxFile.size()>0, "TMXTiledMap: tmx file should not be empty");
_tmxFile = tmxFile;
setContentSize(Size::ZERO);
TMXMapInfo *mapInfo = TMXMapInfo::create(tmxFile);
if (! mapInfo)
{
return false;
}
CCASSERT( !mapInfo->getTilesets().empty(), "TMXTiledMap: Map not found. Please check the filename.");
buildWithMapInfo(mapInfo);
return true;
}
bool TMXTiledMap::initWithXML(const std::string& tmxString, const std::string& resourcePath)
{
_tmxFile = tmxString;
setContentSize(Size::ZERO);
TMXMapInfo *mapInfo = TMXMapInfo::createWithXML(tmxString, resourcePath);
CCASSERT( !mapInfo->getTilesets().empty(), "TMXTiledMap: Map not found. Please check the filename.");
buildWithMapInfo(mapInfo);
return true;
}
TMXTiledMap::TMXTiledMap()
:_mapSize(Size::ZERO)
,_tileSize(Size::ZERO)
,_tmxFile("")
, _tmxLayerNum(0)
{
}
TMXTiledMap::~TMXTiledMap()
{
}
// private
TMXLayer * TMXTiledMap::parseLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
{
TMXTilesetInfo *tileset = tilesetForLayer(layerInfo, mapInfo);
if (tileset == nullptr)
return nullptr;
TMXLayer *layer = TMXLayer::create(tileset, layerInfo, mapInfo);
if (nullptr != layer)
{
// tell the layerinfo to release the ownership of the tiles map.
layerInfo->_ownTiles = false;
layer->setupTiles();
}
return layer;
}
TMXTilesetInfo * TMXTiledMap::tilesetForLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
{
Size size = layerInfo->_layerSize;
auto& tilesets = mapInfo->getTilesets();
if (tilesets.size()>0)
{
TMXTilesetInfo* tileset = nullptr;
for (auto iter = tilesets.crbegin(); iter != tilesets.crend(); ++iter)
{
tileset = *iter;
if (tileset)
{
for( int y=0; y < size.height; y++ )
{
for( int x=0; x < size.width; x++ )
{
int pos = static_cast<int>(x + size.width * y);
int gid = layerInfo->_tiles[ pos ];
// gid are stored in little endian.
// if host is big endian, then swap
//if( o == CFByteOrderBigEndian )
// gid = CFSwapInt32( gid );
/* We support little endian.*/
// FIXME:: gid == 0 --> empty tile
if( gid != 0 )
{
// Optimization: quick return
// if the layer is invalid (more than 1 tileset per layer) an CCAssert will be thrown later
if( (gid & kTMXFlippedMask) >= tileset->_firstGid )
return tileset;
}
}
}
}
}
}
// If all the tiles are 0, return empty tileset
CCLOG("cocos2d: Warning: TMX Layer '%s' has no tiles", layerInfo->_name.c_str());
return nullptr;
}
void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo)
{
_mapSize = mapInfo->getMapSize();
_tileSize = mapInfo->getTileSize();
_mapOrientation = mapInfo->getOrientation();
_objectGroups = mapInfo->getObjectGroups();
_properties = mapInfo->getProperties();
_tileProperties = mapInfo->getTileProperties();
int idx = 0;
auto& layers = mapInfo->getLayers();
for (const auto &layerInfo : layers) {
if (layerInfo->_visible) {
TMXLayer *child = parseLayer(layerInfo, mapInfo);
if (child == nullptr) {
idx++;
continue;
}
addChild(child, idx, idx);
// update content size with the max size
const Size& childSize = child->getContentSize();
Size currentSize = this->getContentSize();
currentSize.width = std::max(currentSize.width, childSize.width);
currentSize.height = std::max(currentSize.height, childSize.height);
this->setContentSize(currentSize);
idx++;
}
}
_tmxLayerNum = idx;
}
// public
TMXLayer * TMXTiledMap::getLayer(const std::string& layerName) const
{
CCASSERT(layerName.size() > 0, "Invalid layer name!");
for (auto& child : _children)
{
TMXLayer* layer = dynamic_cast<TMXLayer*>(child);
if(layer)
{
if(layerName.compare( layer->getLayerName()) == 0)
{
return layer;
}
}
}
// layer not found
return nullptr;
}
TMXObjectGroup * TMXTiledMap::getObjectGroup(const std::string& groupName) const
{
CCASSERT(groupName.size() > 0, "Invalid group name!");
if (_objectGroups.size()>0)
{
TMXObjectGroup* objectGroup = nullptr;
for (auto iter = _objectGroups.cbegin(); iter != _objectGroups.cend(); ++iter)
{
objectGroup = *iter;
if (objectGroup && objectGroup->getGroupName() == groupName)
{
return objectGroup;
}
}
}
// objectGroup not found
return nullptr;
}
Value TMXTiledMap::getProperty(const std::string& propertyName) const
{
if (_properties.find(propertyName) != _properties.end())
return _properties.at(propertyName);
return Value();
}
Value TMXTiledMap::getPropertiesForGID(int GID) const
{
if (_tileProperties.find(GID) != _tileProperties.end())
return _tileProperties.at(GID);
return Value();
}
bool TMXTiledMap::getPropertiesForGID(int GID, Value** value)
{
if (_tileProperties.find(GID) != _tileProperties.end()) {
*value = &_tileProperties.at(GID);
return true;
} else {
return false;
}
}
std::string TMXTiledMap::getDescription() const
{
return StringUtils::format("<TMXTiledMap | Tag = %d, Layers = %d", _tag, static_cast<int>(_children.size()));
}
int TMXTiledMap::getLayerNum()
{
return _tmxLayerNum;
}
NS_CC_END
+331
View File
@@ -0,0 +1,331 @@
/****************************************************************************
Copyright (c) 2009-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCTMX_TILE_MAP_H__
#define __CCTMX_TILE_MAP_H__
#include "2d/CCNode.h"
#include "2d/CCTMXObjectGroup.h"
#include "base/CCValue.h"
NS_CC_BEGIN
class TMXLayer;
class TMXLayerInfo;
class TMXTilesetInfo;
class TMXMapInfo;
/**
* @addtogroup _2d
* @{
*/
/** Possible orientations of the TMX map. */
enum
{
/** Orthogonal orientation. */
TMXOrientationOrtho,
/** Hexagonal orientation. */
TMXOrientationHex,
/** Isometric orientation. */
TMXOrientationIso,
/** Isometric staggered orientation. */
TMXOrientationStaggered,
};
/** Possible stagger axis of the TMX map. */
enum
{
/** Stagger Axis x. */
TMXStaggerAxis_X,
/** Stagger Axis y. */
TMXStaggerAxis_Y,
};
/** Possible stagger index of the TMX map. */
enum
{
/** Stagger Index: Odd */
TMXStaggerIndex_Odd,
/** Stagger Index: Even */
TMXStaggerIndex_Even,
};
/** @brief TMXTiledMap knows how to parse and render a TMX map.
* It adds support for the TMX tiled map format used by http://www.mapeditor.org
* It supports isometric, hexagonal and orthogonal tiles.
* It also supports object groups, objects, and properties.
* Features:
* - Each tile will be treated as an Sprite.
* - The sprites are created on demand. They will be created only when you call "layer->tileAt(position)".
* - Each tile can be rotated / moved / scaled / tinted / "opaqued", since each tile is a Sprite.
* - Tiles can be added/removed in runtime.
* - The z-order of the tiles can be modified in runtime.
* - Each tile has an anchorPoint of (0,0).
* - The anchorPoint of the TMXTileMap is (0,0).
* - The TMX layers will be added as a child.
* - The TMX layers will be aliased by default.
* - The tileset image will be loaded using the TextureCache.
* - Each tile will have a unique tag.
* - Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z.
* - Each object group will be treated as an MutableArray.
* - Object class which will contain all the properties in a dictionary.
* - Properties can be assigned to the Map, Layer, Object Group, and Object.
* Limitations:
* - It only supports one tileset per layer.
* - Embedded images are not supported.
* - It only supports the XML format (the JSON format is not supported).
* Technical description:
* Each layer is created using an TMXLayer (subclass of SpriteBatchNode). If you have 5 layers, then 5 TMXLayer will be created,
* unless the layer visibility is off. In that case, the layer won't be created at all.
* You can obtain the layers (TMXLayer objects) at runtime by:
* - map->getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer, etc...
* - map->getLayer(name_of_the_layer);
* Each object group is created using a TMXObjectGroup which is a subclass of MutableArray.
* You can obtain the object groups at runtime by:
* - map->getObjectGroup(name_of_the_object_group);
* Each object is a TMXObject.
* Each property is stored as a key-value pair in an MutableDictionary.
* You can obtain the properties at runtime by:
* map->getProperty(name_of_the_property);
* layer->getProperty(name_of_the_property);
* objectGroup->getProperty(name_of_the_property);
* object->getProperty(name_of_the_property);
* @since v0.8.1
*/
class CC_DLL TMXTiledMap : public Node
{
public:
/** Creates a TMX Tiled Map with a TMX file.
*
* @param tmxFile A TMX file.
* @return An autorelease object.
*/
static TMXTiledMap* create(const std::string& tmxFile);
/** Initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources.
*
* @param tmxString A TMX formatted XML string.
* @param resourcePath The path to TMX resources.
* @return An autorelease object.
* @js NA
*/
static TMXTiledMap* createWithXML(const std::string& tmxString, const std::string& resourcePath);
/** Return the TMXLayer for the specific layer.
*
* @param layerName A specific layer.
* @return The TMXLayer for the specific layer.
*/
TMXLayer* getLayer(const std::string& layerName) const;
/**
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE TMXLayer* layerNamed(const std::string& layerName) const { return getLayer(layerName); };
/** Return the TMXObjectGroup for the specific group.
*
* @param groupName The group Name.
* @return A Type of TMXObjectGroup.
*/
TMXObjectGroup* getObjectGroup(const std::string& groupName) const;
/**
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE TMXObjectGroup* objectGroupNamed(const std::string& groupName) const { return getObjectGroup(groupName); };
/** Return the value for the specific property name.
*
* @param propertyName The specific property name.
* @return Return the value for the specific property name.
*/
Value getProperty(const std::string& propertyName) const;
/**
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE Value propertyNamed(const char *propertyName) const { return getProperty(propertyName); };
/** Return properties dictionary for tile GID.
*
* @param GID The tile GID.
* @return Return properties dictionary for tile GID.
*/
Value getPropertiesForGID(int GID) const;
CC_DEPRECATED_ATTRIBUTE Value propertiesForGID(int GID) const { return getPropertiesForGID(GID); };
/** Assigns properties to argument value, returns true if it did found properties
* for that GID and did assigned a value, else it returns false.
*
* @param GID The tile GID.
* @param value Argument value.
* @return Return true if it did found properties for that GID and did assigned a value, else it returns false.
*/
bool getPropertiesForGID(int GID, Value** value);
/** The map's size property measured in tiles.
*
* @return The map's size property measured in tiles.
*/
inline const Size& getMapSize() const { return _mapSize; };
/** Set the map's size property measured in tiles.
*
* @param mapSize The map's size property measured in tiles.
*/
inline void setMapSize(const Size& mapSize) { _mapSize = mapSize; };
/** The tiles's size property measured in pixels.
*
* @return The tiles's size property measured in pixels.
*/
inline const Size& getTileSize() const { return _tileSize; };
/** Set the tiles's size property measured in pixels.
*
* @param tileSize The tiles's size property measured in pixels.
*/
inline void setTileSize(const Size& tileSize) { _tileSize = tileSize; };
/** Map orientation.
*
* @return Map orientation.
*/
inline int getMapOrientation() const { return _mapOrientation; };
/** Set map orientation.
*
* @param mapOrientation The map orientation.
*/
inline void setMapOrientation(int mapOrientation) { _mapOrientation = mapOrientation; };
/** Get the Object groups.
*
* @return The object groups.
*/
inline const Vector<TMXObjectGroup*>& getObjectGroups() const { return _objectGroups; };
inline Vector<TMXObjectGroup*>& getObjectGroups() { return _objectGroups; };
/** Set the object groups.
*
* @param groups The object groups.
*/
inline void setObjectGroups(const Vector<TMXObjectGroup*>& groups) {
_objectGroups = groups;
};
/** Properties.
*
* @return Properties.
*/
inline ValueMap& getProperties() { return _properties; };
/** Set the properties.
*
* @param properties A Type of ValueMap to set the properties.
*/
inline void setProperties(const ValueMap& properties) {
_properties = properties;
};
/** Get the description.
* @js NA
*/
virtual std::string getDescription() const override;
int getLayerNum();
const std::string& getResourceFile() const { return _tmxFile; }
CC_CONSTRUCTOR_ACCESS:
/**
* @js ctor
*/
TMXTiledMap();
/**
* @js NA
* @lua NA
*/
virtual ~TMXTiledMap();
/** initializes a TMX Tiled Map with a TMX file */
bool initWithTMXFile(const std::string& tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */
bool initWithXML(const std::string& tmxString, const std::string& resourcePath);
protected:
TMXLayer * parseLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
TMXTilesetInfo * tilesetForLayer(TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo);
void buildWithMapInfo(TMXMapInfo* mapInfo);
/** the map's size property measured in tiles */
Size _mapSize;
/** the tiles's size property measured in pixels */
Size _tileSize;
/** map orientation */
int _mapOrientation;
/** object groups */
Vector<TMXObjectGroup*> _objectGroups;
/** properties */
ValueMap _properties;
//! tile properties
ValueMapIntKey _tileProperties;
std::string _tmxFile;
int _tmxLayerNum;
static const int TMXLayerTag = 32768;
private:
CC_DISALLOW_COPY_AND_ASSIGN(TMXTiledMap);
};
// end of tilemap_parallax_nodes group
/// @}
NS_CC_END
#endif //__CCTMX_TILE_MAP_H__
+30 -5
View File
@@ -29,7 +29,7 @@ THE SOFTWARE.
#include "2d/CCTMXXMLParser.h"
#include <unordered_map>
#include <sstream>
#include "2d/CCFastTMXTiledMap.h"
#include "2d/CCTMXTiledMap.h"
#include "base/ZipUtils.h"
#include "base/base64.h"
#include "base/CCDirector.h"
@@ -233,21 +233,37 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
}
std::string orientationStr = attributeDict["orientation"].asString();
if (orientationStr == "orthogonal") {
tmxMapInfo->setOrientation(0);
tmxMapInfo->setOrientation(TMXOrientationOrtho);
}
else if (orientationStr == "isometric") {
tmxMapInfo->setOrientation(2);
tmxMapInfo->setOrientation(TMXOrientationIso);
}
else if (orientationStr == "hexagonal") {
tmxMapInfo->setOrientation(1);
tmxMapInfo->setOrientation(TMXOrientationHex);
}
else if (orientationStr == "staggered") {
tmxMapInfo->setOrientation(3);
tmxMapInfo->setOrientation(TMXOrientationStaggered);
}
else {
CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", tmxMapInfo->getOrientation());
}
std::string staggerAxisStr = attributeDict["staggeraxis"].asString();
if (staggerAxisStr == "x") {
tmxMapInfo->setStaggerAxis(TMXStaggerAxis_X);
}
else if (staggerAxisStr == "y") {
tmxMapInfo->setStaggerAxis(TMXStaggerAxis_Y);
}
std::string staggerIndex = attributeDict["staggerindex"].asString();
if (staggerIndex == "odd") {
tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Odd);
}
else if (staggerIndex == "even") {
tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even);
}
float hexSideLength = attributeDict["hexsidelength"].asFloat();
tmxMapInfo->setHexSideLength(hexSideLength);
Size s;
s.width = attributeDict["width"].asFloat();
s.height = attributeDict["height"].asFloat();
@@ -266,6 +282,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
std::string externalTilesetFilename = attributeDict["source"].asString();
if (externalTilesetFilename != "")
{
_externalTilesetFilename = externalTilesetFilename;
// Tileset file will be relative to the map file. So we need to convert it to an absolute path
if (_TMXFileName.find_last_of("/") != string::npos)
{
@@ -382,12 +399,20 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
// The parent element is now "objectgroup"
tmxMapInfo->setParentElement(TMXPropertyObjectGroup);
}
else if (elementName == "tileoffset")
{
TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back();
double tileOffsetX = attributeDict["x"].asDouble();
double tileOffsetY = attributeDict["y"].asDouble();
tileset->_tileOffset = Vec2(tileOffsetX, tileOffsetY);
}
else if (elementName == "image")
{
TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back();
// build full path
std::string imagename = attributeDict["source"].asString();
tileset->_originSourceImage = imagename;
if (_TMXFileName.find_last_of("/") != string::npos)
{
+13
View File
@@ -136,10 +136,12 @@ public:
Size _tileSize;
int _spacing;
int _margin;
Vec2 _tileOffset;
//! filename containing the tiles (should be spritesheet / texture atlas)
std::string _sourceImage;
//! size in pixels of the image
Size _imageSize;
std::string _originSourceImage;
public:
/**
* @js ctor
@@ -201,7 +203,13 @@ public:
/// map orientation
inline int getOrientation() const { return _orientation; };
inline void setOrientation(int orientation) { _orientation = orientation; };
inline int getStaggerAxis() const { return _staggerAxis; };
inline void setStaggerAxis(int staggerAxis) { _staggerAxis = staggerAxis; };
inline int getStaggerIndex() const { return _staggerIndex; };
inline void setStaggerIndex(int staggerIndex) { _staggerIndex = staggerIndex; };
inline int getHexSideLength() const { return _hexSideLength; };
inline void setHexSideLength(int hexSideLength) { _hexSideLength = hexSideLength; };
/// map width & height
inline const Size& getMapSize() const { return _mapSize; };
inline void setMapSize(const Size& mapSize) { _mapSize = mapSize; };
@@ -276,12 +284,16 @@ public:
inline void setCurrentString(const std::string& currentString){ _currentString = currentString; }
inline const std::string& getTMXFileName() const { return _TMXFileName; }
inline void setTMXFileName(const std::string& fileName){ _TMXFileName = fileName; }
inline const std::string& getExternalTilesetFileName() const { return _externalTilesetFilename; }
protected:
void internalInit(const std::string& tmxFileName, const std::string& resourcePath);
/// map orientation
int _orientation;
int _staggerAxis;
int _staggerIndex;
int _hexSideLength;
/// map width & height
Size _mapSize;
/// tiles width & height
@@ -315,6 +327,7 @@ protected:
ValueMapIntKey _tileProperties;
int _currentFirstGID;
bool _recordFirstGID;
std::string _externalTilesetFilename;
};
// end of tilemap_parallax_nodes group
+10
View File
@@ -296,7 +296,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32\libs\*.*" "$(OutDir)"
<ClCompile Include="..\editor-support\cocostudio\CocoStudio.cpp" />
<ClCompile Include="..\editor-support\cocostudio\DictionaryHelper.cpp" />
<ClCompile Include="..\editor-support\cocostudio\WidgetCallBackHandlerProtocol.cpp" />
<ClCompile Include="..\editor-support\creator\CCGraphicsNode.cpp" />
<ClCompile Include="..\editor-support\creator\CCScale9Sprite.cpp" />
<ClCompile Include="..\editor-support\creator\Triangulate.cpp" />
<ClCompile Include="..\math\CCAffineTransform.cpp" />
<ClCompile Include="..\math\CCGeometry.cpp" />
<ClCompile Include="..\math\CCVertex.cpp" />
@@ -434,7 +436,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32\libs\*.*" "$(OutDir)"
<ClCompile Include="CCSpriteFrameCache.cpp" />
<ClCompile Include="CCTextFieldTTF.cpp" />
<ClCompile Include="CCTileMapAtlas.cpp" />
<ClCompile Include="CCTMXLayer.cpp" />
<ClCompile Include="CCTMXObjectGroup.cpp" />
<ClCompile Include="CCTMXTiledMap.cpp" />
<ClCompile Include="CCTMXXMLParser.cpp" />
<ClCompile Include="CCTransition.cpp" />
<ClCompile Include="CCTransitionPageTurn.cpp" />
@@ -611,7 +615,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32\libs\*.*" "$(OutDir)"
<ClInclude Include="..\editor-support\cocostudio\CSParse3DBinary_generated.h" />
<ClInclude Include="..\editor-support\cocostudio\DictionaryHelper.h" />
<ClInclude Include="..\editor-support\cocostudio\WidgetCallBackHandlerProtocol.h" />
<ClInclude Include="..\editor-support\creator\CCGraphicsNode.h" />
<ClInclude Include="..\editor-support\creator\CCScale9Sprite.h" />
<ClInclude Include="..\editor-support\creator\Triangulate.h" />
<ClInclude Include="..\math\CCAffineTransform.h" />
<ClInclude Include="..\math\CCGeometry.h" />
<ClInclude Include="..\math\CCMath.h" />
@@ -762,7 +768,9 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32\libs\*.*" "$(OutDir)"
<ClInclude Include="CCSpriteFrameCache.h" />
<ClInclude Include="CCTextFieldTTF.h" />
<ClInclude Include="CCTileMapAtlas.h" />
<ClInclude Include="CCTMXLayer.h" />
<ClInclude Include="CCTMXObjectGroup.h" />
<ClInclude Include="CCTMXTiledMap.h" />
<ClInclude Include="CCTMXXMLParser.h" />
<ClInclude Include="CCTransition.h" />
<ClInclude Include="CCTransitionPageTurn.h" />
@@ -770,6 +778,8 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32\libs\*.*" "$(OutDir)"
<ClInclude Include="CCTweenFunction.h" />
</ItemGroup>
<ItemGroup>
<None Include="..\editor-support\creator\CCGraphicsNode.frag" />
<None Include="..\editor-support\creator\CCGraphicsNode.vert" />
<None Include="..\math\Mat4.inl" />
<None Include="..\math\MathUtil.inl" />
<None Include="..\math\MathUtilNeon.inl" />
@@ -301,9 +301,15 @@
<ClCompile Include="CCTileMapAtlas.cpp">
<Filter>2d</Filter>
</ClCompile>
<ClCompile Include="CCTMXLayer.cpp">
<Filter>2d</Filter>
</ClCompile>
<ClCompile Include="CCTMXObjectGroup.cpp">
<Filter>2d</Filter>
</ClCompile>
<ClCompile Include="CCTMXTiledMap.cpp">
<Filter>2d</Filter>
</ClCompile>
<ClCompile Include="CCTMXXMLParser.cpp">
<Filter>2d</Filter>
</ClCompile>
@@ -1001,6 +1007,12 @@
<ClCompile Include="..\..\extensions\assets-manager\Manifest.cpp">
<Filter>extension\AssetManager</Filter>
</ClCompile>
<ClCompile Include="..\editor-support\creator\CCGraphicsNode.cpp">
<Filter>creator</Filter>
</ClCompile>
<ClCompile Include="..\editor-support\creator\Triangulate.cpp">
<Filter>creator</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\cocos2d.h" />
@@ -1163,9 +1175,15 @@
<ClInclude Include="CCTileMapAtlas.h">
<Filter>2d</Filter>
</ClInclude>
<ClInclude Include="CCTMXLayer.h">
<Filter>2d</Filter>
</ClInclude>
<ClInclude Include="CCTMXObjectGroup.h">
<Filter>2d</Filter>
</ClInclude>
<ClInclude Include="CCTMXTiledMap.h">
<Filter>2d</Filter>
</ClInclude>
<ClInclude Include="CCTMXXMLParser.h">
<Filter>2d</Filter>
</ClInclude>
@@ -1980,6 +1998,12 @@
<ClInclude Include="..\..\extensions\assets-manager\Manifest.h">
<Filter>extension\AssetManager</Filter>
</ClInclude>
<ClInclude Include="..\editor-support\creator\CCGraphicsNode.h">
<Filter>creator</Filter>
</ClInclude>
<ClInclude Include="..\editor-support\creator\Triangulate.h">
<Filter>creator</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="..\math\Mat4.inl">
@@ -2004,5 +2028,11 @@
<Filter>math</Filter>
</None>
<None Include="cocos2d.def" />
<None Include="..\editor-support\creator\CCGraphicsNode.frag">
<Filter>creator</Filter>
</None>
<None Include="..\editor-support\creator\CCGraphicsNode.vert">
<Filter>creator</Filter>
</None>
</ItemGroup>
</Project>
+2
View File
@@ -72,7 +72,9 @@ cocos2d.cpp \
2d/CCSpriteBatchNode.cpp \
2d/CCSpriteFrame.cpp \
2d/CCSpriteFrameCache.cpp \
2d/CCTMXLayer.cpp \
2d/CCTMXObjectGroup.cpp \
2d/CCTMXTiledMap.cpp \
2d/CCTMXXMLParser.cpp \
2d/CCTextFieldTTF.cpp \
2d/CCTileMapAtlas.cpp \
+1 -1
View File
@@ -103,7 +103,7 @@ void AudioCache::readDataTask()
AudioBufferList theDataBuffer;
ExtAudioFileRef extRef = nullptr;
NSString *fileFullPath = [[NSString alloc] initWithCString:_fileFullPath.c_str() encoding:[NSString defaultCStringEncoding]];
NSString *fileFullPath = [[NSString alloc] initWithCString:_fileFullPath.c_str() encoding:NSUTF8StringEncoding];
auto fileURL = (CFURLRef)[[NSURL alloc] initFileURLWithPath:fileFullPath];
[fileFullPath release];
+1 -1
View File
@@ -145,7 +145,7 @@ void AudioPlayer::rotateBufferThread(int offsetFrame)
ALint bufferProcessed = 0;
ExtAudioFileRef extRef = nullptr;
NSString *fileFullPath = [[NSString alloc] initWithCString:_audioCache->_fileFullPath.c_str() encoding:[NSString defaultCStringEncoding]];
NSString *fileFullPath = [[NSString alloc] initWithCString:_audioCache->_fileFullPath.c_str() encoding:NSUTF8StringEncoding];
auto fileURL = (CFURLRef)[[NSURL alloc] initFileURLWithPath:fileFullPath];
[fileFullPath release];
char* tmpBuffer = (char*)malloc(_audioCache->_queBufferBytes);
+2
View File
@@ -223,7 +223,9 @@ THE SOFTWARE.
// tilemap_parallax_nodes
#include "2d/CCParallaxNode.h"
#include "2d/CCTMXLayer.h"
#include "2d/CCTMXObjectGroup.h"
#include "2d/CCTMXTiledMap.h"
#include "2d/CCTMXXMLParser.h"
#include "2d/CCTileMapAtlas.h"
#include "2d/CCFastTMXLayer.h"
@@ -25,7 +25,7 @@ THE SOFTWARE.
#include "cocostudio/CCComRender.h"
#include "cocostudio/CocoStudio.h"
#include "platform/CCFileUtils.h"
#include "2d/CCFastTMXTiledMap.h"
#include "2d/CCTMXTiledMap.h"
#include "2d/CCParticleSystemQuad.h"
#include "2d/CCSpriteFrameCache.h"
@@ -271,7 +271,7 @@ void GraphicsNode::rect(float x, float y, float w, float h)
_curPath->complex = false;
}
void GraphicsNode::roundedRect(float x, float y, float w, float h, float r)
void GraphicsNode::roundRect(float x, float y, float w, float h, float r)
{
if (r < 0.1f) {
rect(x,y,w,h);
@@ -119,7 +119,7 @@ typedef struct Command Command;
typedef std::vector< Command* > CommandVector;
class GraphicsNode: public cocos2d::Node
class CC_DLL GraphicsNode : public cocos2d::Node
{
public:
@@ -162,7 +162,7 @@ public:
void arc(float cx, float cy, float r, float startAngle, float endAngle, bool counterclockwise);
void rect(float x, float y, float w, float h);
void roundedRect(float x, float y, float w, float h, float r);
void roundRect(float x, float y, float w, float h, float r);
void ellipse(float cx, float cy, float rx, float ry);
void circle(float cx, float cy, float r);
+8
View File
@@ -1343,5 +1343,13 @@ std::string FileUtils::getFileExtension(const std::string& filePath) const
return fileExtension;
}
void FileUtils::valueMapCompact(ValueMap &valueMap)
{
}
void FileUtils::valueVectorCompact(ValueVector &valueVector)
{
}
NS_CC_END
+6
View File
@@ -531,6 +531,12 @@ protected:
* @return The full path of the file, if the file can't be found, it will return an empty string.
*/
virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const;
/**
* Remove null value key (for iOS)
*/
virtual void valueMapCompact(ValueMap& valueMap);
virtual void valueVectorCompact(ValueVector& valueVector);
/** Dictionary used to lookup filenames based on a key.
* It is used internally by the following methods:
+1 -1
View File
@@ -152,7 +152,7 @@ void GLView::updateDesignResolutionSize()
auto director = Director::DirectorInstance;
director->_winSizeInPoints = getDesignResolutionSize();
director->_isStatusLabelUpdated = true;
director->setGLDefaultValues();
director->setProjection(director->getProjection());
}
}
@@ -132,6 +132,42 @@ public class Cocos2dxEditBox extends EditText {
this.setLayoutParams(layoutParams);
}
public void setInputTextAlignment(int hAlign, int vAlign) {
int gravity;
switch (hAlign) {
case 0:
gravity = Gravity.LEFT;
break;
case 1:
gravity = Gravity.CENTER_HORIZONTAL;
break;
case 2:
gravity = Gravity.RIGHT;
break;
default:
gravity = Gravity.LEFT;
break;
}
switch (vAlign) {
case 0:
gravity = gravity | Gravity.TOP;
break;
case 1:
gravity = gravity | Gravity.CENTER_VERTICAL;
break;
case 2:
gravity = gravity | Gravity.BOTTOM;
break;
default:
gravity = gravity | Gravity.CENTER_VERTICAL;
break;
}
this.setGravity(gravity);
}
public float getOpenGLViewScaleX() {
return mScaleX;
}
@@ -175,10 +211,11 @@ public class Cocos2dxEditBox extends EditText {
}
public void setInputMode(int inputMode){
this.setInputTextAlignment(0, 1);
switch (inputMode) {
case kEditBoxInputModeAny:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
this.setInputTextAlignment(0, 0);
break;
case kEditBoxInputModeEmailAddr:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
@@ -128,6 +128,7 @@ public class Cocos2dxEditBoxHelper {
Cocos2dxActivity.ROOT_LAYOUT.addView(editBox, lParams);
editBox.setTag(false);
editBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
@@ -135,20 +136,20 @@ public class Cocos2dxEditBoxHelper {
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
//The optimization can't be turn on due to unknown keyboard hide in some custom keyboard
// Cocos2dxActivity.ROOT_LAYOUT.setEnableForceDoLayout(false);
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString());
}
});
}
//http://stackoverflow.com/questions/21713246/addtextchangedlistener-and-ontextchanged-are-always-called-when-android-fragment
@Override
public void afterTextChanged(Editable s) {
public void afterTextChanged(final Editable s) {
if(!s.toString().equals("") && (Boolean)editBox.getTag()) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString());
}
});
}
}
});
@@ -158,6 +159,7 @@ public class Cocos2dxEditBoxHelper {
@Override
public void onFocusChange(View v, boolean hasFocus) {
editBox.setTag(true);
if (hasFocus) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
@@ -34,6 +34,7 @@ public class Cocos2dxWebView extends WebView {
this.getSettings().setSupportZoom(false);
this.getSettings().setDomStorageEnabled(true);
this.getSettings().setJavaScriptEnabled(true);
// `searchBoxJavaBridge_` has big security risk. http://jvn.jp/en/jp/JVN53768697
@@ -63,6 +63,8 @@ public:
virtual bool removeDirectory(const std::string& dirPath) override;
private:
bool isFileExistInternal(const std::string& filePath,bool& isDirectory) const;
virtual void valueMapCompact(ValueMap& valueMap) override;
virtual void valueVectorCompact(ValueVector& valueVector) override;
NSBundle* getBundle() const;
NSBundle* _bundle;
@@ -478,6 +478,7 @@ bool FileUtilsApple::writeToFile(const ValueMap& dict, const std::string &fullPa
bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath)
{
valueMapCompact(const_cast<ValueMap&>(dict));
//CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];
@@ -489,9 +490,7 @@ bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& ful
NSString *file = [NSString stringWithUTF8String:fullPath.c_str()];
// do it atomically
[nsDict writeToFile:file atomically:YES];
return true;
return [nsDict writeToFile:file atomically:YES];
}
bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath)
@@ -529,5 +528,57 @@ ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename)
return ret;
}
void FileUtilsApple::valueMapCompact(ValueMap& valueMap)
{
auto itr = valueMap.begin();
while(itr != valueMap.end()){
auto vtype = itr->second.getType();
switch(vtype){
case Value::Type::NONE:{
itr = valueMap.erase(itr);
continue;
}
break;
case Value::Type::MAP:{
valueMapCompact(itr->second.asValueMap());
}
break;
case Value::Type::VECTOR:{
valueVectorCompact(itr->second.asValueVector());
}
break;
default:
break;
}
itr++;
}
}
void FileUtilsApple::valueVectorCompact(ValueVector& valueVector)
{
auto itr = valueVector.begin();
while(itr != valueVector.end()){
auto vtype = (*itr).getType();
switch(vtype){
case Value::Type::NONE:{
itr = valueVector.erase(itr);
continue;
}
break;
case Value::Type::MAP:{
valueMapCompact((*itr).asValueMap());
}
break;
case Value::Type::VECTOR:{
valueVectorCompact((*itr).asValueVector());
}
break;
default:
break;
}
itr++;
}
}
NS_CC_END
+9 -11
View File
@@ -100,18 +100,16 @@ bool cocos2d::Image::saveToFile(const std::string& filename, bool isToRGB)
CGColorSpaceRelease(colorSpaceRef);
CGDataProviderRelease(provider);
NSData *data;
if (saveToPNG)
{
data = UIImagePNGRepresentation(image);
// NOTE: Prevent memory leak. Requires ARC enabled.
@autoreleasepool {
NSData *data;
if (saveToPNG) {
data = UIImagePNGRepresentation(image);
} else {
data = UIImageJPEGRepresentation(image, 1.0f);
}
[data writeToFile:[NSString stringWithUTF8String:filename.c_str()] atomically:YES];
}
else
{
data = UIImageJPEGRepresentation(image, 1.0f);
}
[data writeToFile:[NSString stringWithUTF8String:filename.c_str()] atomically:YES];
[image release];
+5 -4
View File
@@ -333,11 +333,12 @@ void Renderer::mapBuffers()
// Avoid changing the element buffer for whatever VAO might be bound.
GL::bindVAO(0);
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(_verts[0]) * VBO_SIZE, _verts, GL_DYNAMIC_DRAW);
// fix performance issue on some Android devices
// glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// glBufferData(GL_ARRAY_BUFFER, sizeof(_verts[0]) * VBO_SIZE, _verts, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, _quadbuffersVBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(_quadVerts[0]) * VBO_SIZE, _quadVerts, GL_DYNAMIC_DRAW);
// glBindBuffer(GL_ARRAY_BUFFER, _quadbuffersVBO[0]);
// glBufferData(GL_ARRAY_BUFFER, sizeof(_quadVerts[0]) * VBO_SIZE, _quadVerts, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
+3 -2
View File
@@ -84,11 +84,12 @@ std::string TextureCache::getDescription() const
struct TextureCache::AsyncStruct
{
public:
AsyncStruct(const std::string& fn, std::function<void(Texture2D*)> f) : filename(fn), callback(f), loadSuccess(false) {}
AsyncStruct(const std::string& fn, std::function<void(Texture2D*)> f) : filename(fn), callback(f), pixelFormat(Texture2D::getDefaultAlphaPixelFormat()), loadSuccess(false) {}
std::string filename;
std::function<void(Texture2D*)> callback;
Image image;
Texture2D::PixelFormat pixelFormat;
bool loadSuccess;
};
@@ -271,7 +272,7 @@ void TextureCache::addImageAsyncCallBack(float dt)
// generate texture in render thread
texture = new (std::nothrow) Texture2D();
texture->initWithImage(image);
texture->initWithImage(image, asyncStruct->pixelFormat);
//parse 9-patch info
this->parseNinePatchImage(image, texture, asyncStruct->filename);
#if CC_ENABLE_CACHE_TEXTURE_DATA
+1 -1
View File
@@ -119,7 +119,7 @@ static void SetBlending(GLenum sfactor, GLenum dfactor)
RenderState::StateBlock::_defaultState->setBlend(true);
RenderState::StateBlock::_defaultState->setBlendSrc((RenderState::Blend)sfactor);
RenderState::StateBlock::_defaultState->setBlendSrc((RenderState::Blend)dfactor);
RenderState::StateBlock::_defaultState->setBlendDst((RenderState::Blend)dfactor);
}
}
@@ -20097,15 +20097,25 @@ TMXTilesetInfo : function (
cc.TMXMapInfo = {
/**
* @method setObjectGroups
* @param {Array} arg0
* @method setCurrentString
* @param {String} arg0
*/
setObjectGroups : function (
array
setCurrentString : function (
str
)
{
},
/**
* @method getHexSideLength
* @return {int}
*/
getHexSideLength : function (
)
{
return 0;
},
/**
* @method setTileSize
* @param {size_object} arg0
@@ -20139,13 +20149,13 @@ getOrientation : function (
},
/**
* @method isStoringCharacters
* @return {bool}
* @method setObjectGroups
* @param {Array} arg0
*/
isStoringCharacters : function (
setObjectGroups : function (
array
)
{
return false;
},
/**
@@ -20212,6 +20222,26 @@ getLayers : function(
return new Array();
},
/**
* @method getStaggerAxis
* @return {int}
*/
getStaggerAxis : function (
)
{
return 0;
},
/**
* @method setHexSideLength
* @param {int} arg0
*/
setHexSideLength : function (
int
)
{
},
/**
* @method getTilesets
* @return {Array|Array}
@@ -20296,6 +20326,26 @@ getTileProperties : function (
return map_object;
},
/**
* @method isStoringCharacters
* @return {bool}
*/
isStoringCharacters : function (
)
{
return false;
},
/**
* @method getExternalTilesetFileName
* @return {String}
*/
getExternalTilesetFileName : function (
)
{
return ;
},
/**
* @method getObjectGroups
* @return {Array|Array}
@@ -20317,11 +20367,11 @@ getTMXFileName : function (
},
/**
* @method setCurrentString
* @param {String} arg0
* @method setStaggerIndex
* @param {int} arg0
*/
setCurrentString : function (
str
setStaggerIndex : function (
int
)
{
},
@@ -20366,6 +20416,16 @@ size
{
},
/**
* @method getCurrentString
* @return {String}
*/
getCurrentString : function (
)
{
return ;
},
/**
* @method setStoringCharacters
* @param {bool} arg0
@@ -20376,6 +20436,16 @@ bool
{
},
/**
* @method setStaggerAxis
* @param {int} arg0
*/
setStaggerAxis : function (
int
)
{
},
/**
* @method getMapSize
* @return {size_object}
@@ -20407,13 +20477,13 @@ getProperties : function(
},
/**
* @method getCurrentString
* @return {String}
* @method getStaggerIndex
* @return {int}
*/
getCurrentString : function (
getStaggerIndex : function (
)
{
return ;
return 0;
},
/**
@@ -20463,90 +20533,6 @@ TMXMapInfo : function (
};
/**
* @class TileMapAtlas
*/
cc.TileMapAtlas = {
/**
* @method initWithTileFile
* @param {String} arg0
* @param {String} arg1
* @param {int} arg2
* @param {int} arg3
* @return {bool}
*/
initWithTileFile : function (
str,
str,
int,
int
)
{
return false;
},
/**
* @method releaseMap
*/
releaseMap : function (
)
{
},
/**
* @method getTileAt
* @param {vec2_object} arg0
* @return {color3b_object}
*/
getTileAt : function (
vec2
)
{
return cc.Color3B;
},
/**
* @method setTile
* @param {color3b_object} arg0
* @param {vec2_object} arg1
*/
setTile : function (
color3b,
vec2
)
{
},
/**
* @method create
* @param {String} arg0
* @param {String} arg1
* @param {int} arg2
* @param {int} arg3
* @return {cc.TileMapAtlas}
*/
create : function (
str,
str,
int,
int
)
{
return cc.TileMapAtlas;
},
/**
* @method TileMapAtlas
* @constructor
*/
TileMapAtlas : function (
)
{
},
};
/**
* @class TMXLayer
*/
@@ -20556,7 +20542,7 @@ cc.TMXLayer = {
* @method getTileGIDAt
* @param {vec2_object} arg0
* @param {cc.TMXTileFlags_} arg1
* @return {int}
* @return {unsigned int}
*/
getTileGIDAt : function (
vec2,
@@ -20566,16 +20552,6 @@ tmxtileflags_
return 0;
},
/**
* @method getTexture
* @return {cc.Texture2D}
*/
getTexture : function (
)
{
return cc.Texture2D;
},
/**
* @method getPositionAt
* @param {vec2_object} arg0
@@ -20598,22 +20574,6 @@ int
{
},
/**
* @method initWithTilesetInfo
* @param {cc.TMXTilesetInfo} arg0
* @param {cc.TMXLayerInfo} arg1
* @param {cc.TMXMapInfo} arg2
* @return {bool}
*/
initWithTilesetInfo : function (
tmxtilesetinfo,
tmxlayerinfo,
map
)
{
return false;
},
/**
* @method releaseMap
*/
@@ -20683,13 +20643,19 @@ vec2
},
/**
* @method getProperties
* @return {map_object|map_object}
*/
getProperties : function(
* @method initWithTilesetInfo
* @param {cc.TMXTilesetInfo} arg0
* @param {cc.TMXLayerInfo} arg1
* @param {cc.TMXMapInfo} arg2
* @return {bool}
*/
initWithTilesetInfo : function (
tmxtilesetinfo,
tmxlayerinfo,
map
)
{
return map_object;
return false;
},
/**
@@ -20700,23 +20666,9 @@ setupTiles : function (
{
},
/**
* @method setupTileSprite
* @param {cc.Sprite} arg0
* @param {vec2_object} arg1
* @param {int} arg2
*/
setupTileSprite : function (
sprite,
vec2,
int
)
{
},
/**
* @method setTileGID
* @param {int|int} int
* @param {unsigned int|unsigned int} int
* @param {vec2_object|vec2_object} vec2
* @param {cc.TMXTileFlags_} tmxtileflags_
*/
@@ -20790,6 +20742,16 @@ getTileSet : function (
return cc.TMXTilesetInfo;
},
/**
* @method getProperties
* @return {map_object|map_object}
*/
getProperties : function(
)
{
return map_object;
},
/**
* @method getTileAt
* @param {vec2_object} arg0
@@ -20856,6 +20818,16 @@ str
return cc.Value;
},
/**
* @method getLayerNum
* @return {int}
*/
getLayerNum : function (
)
{
return 0;
},
/**
* @method setMapSize
* @param {size_object} arg0
@@ -20889,17 +20861,13 @@ getObjectGroups : function(
},
/**
* @method initWithXML
* @param {String} arg0
* @param {String} arg1
* @return {bool}
* @method getResourceFile
* @return {String}
*/
initWithXML : function (
str,
str
getResourceFile : function (
)
{
return false;
return ;
},
/**
@@ -20934,6 +20902,20 @@ getMapSize : function (
return cc.Size;
},
/**
* @method initWithXML
* @param {String} arg0
* @param {String} arg1
* @return {bool}
*/
initWithXML : function (
str,
str
)
{
return false;
},
/**
* @method getProperties
* @return {map_object}
@@ -20946,14 +20928,16 @@ getProperties : function (
/**
* @method getPropertiesForGID
* @param {int} arg0
* @return {cc.Value}
*/
getPropertiesForGID : function (
int
* @param {int|int} int
* @param {cc.Value} value
* @return {bool|cc.Value}
*/
getPropertiesForGID : function(
int,
value
)
{
return cc.Value;
return false;
},
/**
@@ -21045,6 +21029,90 @@ TMXTiledMap : function (
};
/**
* @class TileMapAtlas
*/
cc.TileMapAtlas = {
/**
* @method initWithTileFile
* @param {String} arg0
* @param {String} arg1
* @param {int} arg2
* @param {int} arg3
* @return {bool}
*/
initWithTileFile : function (
str,
str,
int,
int
)
{
return false;
},
/**
* @method releaseMap
*/
releaseMap : function (
)
{
},
/**
* @method getTileAt
* @param {vec2_object} arg0
* @return {color3b_object}
*/
getTileAt : function (
vec2
)
{
return cc.Color3B;
},
/**
* @method setTile
* @param {color3b_object} arg0
* @param {vec2_object} arg1
*/
setTile : function (
color3b,
vec2
)
{
},
/**
* @method create
* @param {String} arg0
* @param {String} arg1
* @param {int} arg2
* @param {int} arg3
* @return {cc.TileMapAtlas}
*/
create : function (
str,
str,
int,
int
)
{
return cc.TileMapAtlas;
},
/**
* @method TileMapAtlas
* @constructor
*/
TileMapAtlas : function (
)
{
},
};
/**
* @class SimpleAudioEngine
*/
File diff suppressed because it is too large Load Diff
@@ -3637,17 +3637,20 @@ bool js_cocos2dx_TMXMapInfo_constructor(JSContext *cx, uint32_t argc, jsval *vp)
void js_cocos2dx_TMXMapInfo_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_TMXMapInfo(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_TMXMapInfo_setObjectGroups(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setCurrentString(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getHexSideLength(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_initWithTMXFile(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_isStoringCharacters(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setObjectGroups(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setLayers(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_parseXMLFile(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getParentElement(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setTMXFileName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_parseXMLString(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getLayers(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getStaggerAxis(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setHexSideLength(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getTilesets(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getParentGID(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setParentElement(JSContext *cx, uint32_t argc, jsval *vp);
@@ -3656,23 +3659,87 @@ bool js_cocos2dx_TMXMapInfo_setParentGID(JSContext *cx, uint32_t argc, jsval *vp
bool js_cocos2dx_TMXMapInfo_getLayerAttribs(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getTileProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_isStoringCharacters(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getExternalTilesetFileName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getObjectGroups(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getTMXFileName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setCurrentString(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setStaggerIndex(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setTileProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setMapSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getCurrentString(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setStoringCharacters(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setStaggerAxis(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getMapSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setTilesets(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getCurrentString(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_getStaggerIndex(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_setLayerAttribs(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_createWithXML(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXMapInfo_TMXMapInfo(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_cocos2d_TMXLayer_class;
extern JSObject *jsb_cocos2d_TMXLayer_prototype;
bool js_cocos2dx_TMXLayer_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_TMXLayer_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_TMXLayer(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_TMXLayer_getTileGIDAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getPositionAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setLayerOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_releaseMap(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getLayerSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setMapTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getLayerOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setLayerName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_removeTileAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_initWithTilesetInfo(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setupTiles(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setTileGID(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getMapTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getProperty(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setLayerSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getLayerName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setTileSet(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getTileSet(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getTileAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_TMXLayer(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_cocos2d_TMXTiledMap_class;
extern JSObject *jsb_cocos2d_TMXTiledMap_prototype;
bool js_cocos2dx_TMXTiledMap_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_TMXTiledMap_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_TMXTiledMap(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_TMXTiledMap_setObjectGroups(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getProperty(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getLayerNum(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setMapSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getObjectGroup(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getObjectGroups(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getResourceFile(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_initWithTMXFile(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getMapSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_initWithXML(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getPropertiesForGID(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getLayer(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getMapOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setMapOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_createWithXML(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_TMXTiledMap(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_cocos2d_TileMapAtlas_class;
extern JSObject *jsb_cocos2d_TileMapAtlas_prototype;
@@ -3687,66 +3754,6 @@ bool js_cocos2dx_TileMapAtlas_setTile(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TileMapAtlas_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TileMapAtlas_TileMapAtlas(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_cocos2d_TMXLayer_class;
extern JSObject *jsb_cocos2d_TMXLayer_prototype;
bool js_cocos2dx_TMXLayer_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_TMXLayer_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_TMXLayer(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_TMXLayer_getTileGIDAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getTexture(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getPositionAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setLayerOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_initWithTilesetInfo(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_releaseMap(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getLayerSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setMapTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getLayerOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setLayerName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_removeTileAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setupTiles(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setupTileSprite(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setTileGID(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getMapTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getProperty(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setLayerSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getLayerName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_setTileSet(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getTileSet(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_getTileAt(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXLayer_TMXLayer(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_cocos2d_TMXTiledMap_class;
extern JSObject *jsb_cocos2d_TMXTiledMap_prototype;
bool js_cocos2dx_TMXTiledMap_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_TMXTiledMap_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_TMXTiledMap(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_TMXTiledMap_setObjectGroups(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getProperty(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setMapSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getObjectGroup(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getObjectGroups(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_initWithXML(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_initWithTMXFile(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getMapSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getPropertiesForGID(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setTileSize(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setProperties(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getLayer(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_getMapOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_setMapOrientation(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_create(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_createWithXML(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_TMXTiledMap_TMXTiledMap(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_CocosDenshion_SimpleAudioEngine_class;
extern JSObject *jsb_CocosDenshion_SimpleAudioEngine_prototype;
@@ -975,14 +975,14 @@ bool js_creator_GraphicsNode_lineTo(JSContext *cx, uint32_t argc, jsval *vp)
JS_ReportError(cx, "js_creator_GraphicsNode_lineTo : wrong number of arguments: %d, was expecting %d", argc, 2);
return false;
}
bool js_creator_GraphicsNode_roundedRect(JSContext *cx, uint32_t argc, jsval *vp)
bool js_creator_GraphicsNode_roundRect(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);
creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_roundedRect : Invalid Native Object");
JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_roundRect : Invalid Native Object");
if (argc == 5) {
double arg0 = 0;
double arg1 = 0;
@@ -994,13 +994,13 @@ bool js_creator_GraphicsNode_roundedRect(JSContext *cx, uint32_t argc, jsval *vp
ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2);
ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3);
ok &= JS::ToNumber( cx, args.get(4), &arg4) && !isnan(arg4);
JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_roundedRect : Error processing arguments");
cobj->roundedRect(arg0, arg1, arg2, arg3, arg4);
JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_roundRect : Error processing arguments");
cobj->roundRect(arg0, arg1, arg2, arg3, arg4);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_creator_GraphicsNode_roundedRect : wrong number of arguments: %d, was expecting %d", argc, 5);
JS_ReportError(cx, "js_creator_GraphicsNode_roundRect : wrong number of arguments: %d, was expecting %d", argc, 5);
return false;
}
bool js_creator_GraphicsNode_stroke(JSContext *cx, uint32_t argc, jsval *vp)
@@ -1664,7 +1664,7 @@ void js_register_creator_GraphicsNode(JSContext *cx, JS::HandleObject global) {
JS_FN("quadraticCurveTo", js_creator_GraphicsNode_quadraticCurveTo, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("moveTo", js_creator_GraphicsNode_moveTo, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("lineTo", js_creator_GraphicsNode_lineTo, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("roundedRect", js_creator_GraphicsNode_roundedRect, 5, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("roundRect", js_creator_GraphicsNode_roundRect, 5, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("stroke", js_creator_GraphicsNode_stroke, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("arc", js_creator_GraphicsNode_arc, 6, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setLineJoin", js_creator_GraphicsNode_setLineJoin, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
@@ -54,7 +54,7 @@ void register_all_creator(JSContext* cx, JS::HandleObject obj);
bool js_creator_GraphicsNode_quadraticCurveTo(JSContext *cx, uint32_t argc, jsval *vp);
bool js_creator_GraphicsNode_moveTo(JSContext *cx, uint32_t argc, jsval *vp);
bool js_creator_GraphicsNode_lineTo(JSContext *cx, uint32_t argc, jsval *vp);
bool js_creator_GraphicsNode_roundedRect(JSContext *cx, uint32_t argc, jsval *vp);
bool js_creator_GraphicsNode_roundRect(JSContext *cx, uint32_t argc, jsval *vp);
bool js_creator_GraphicsNode_stroke(JSContext *cx, uint32_t argc, jsval *vp);
bool js_creator_GraphicsNode_arc(JSContext *cx, uint32_t argc, jsval *vp);
bool js_creator_GraphicsNode_setLineJoin(JSContext *cx, uint32_t argc, jsval *vp);
@@ -926,7 +926,7 @@ void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorRepor
__android_log_print(ANDROID_LOG_ERROR, "cocos js error:", "%s line:%u msg:%s",
fileName.c_str(), report->lineno, msg.c_str());
#else
printf("%s:%u:%s\n", fileName.c_str(), report->lineno, msg.c_str());
cocos2d::log("%s:%u:%s\n", fileName.c_str(), report->lineno, msg.c_str());
#endif
// Should clear pending exception, otherwise it will trigger infinite loop
if (JS_IsExceptionPending(cx)) {
@@ -1664,21 +1664,26 @@ bool ScriptingCore::callFunctionName(JS::HandleObject thisObj, const char* funcN
void SimpleRunLoop::update(float dt)
{
g_qMutex.lock();
size_t size = g_queue.size();
g_qMutex.unlock();
auto sc = ScriptingCore::getInstance();
while (size > 0)
std::string message;
size_t messageCount = 0;
while (true)
{
g_qMutex.lock();
auto first = g_queue.begin();
std::string str = *first;
g_queue.erase(first);
size = g_queue.size();
messageCount = g_queue.size();
if (messageCount > 0)
{
auto first = g_queue.begin();
message = *first;
g_queue.erase(first);
--messageCount;
}
g_qMutex.unlock();
sc->debugProcessInput(str);
if (!message.empty())
ScriptingCore::getInstance()->debugProcessInput(message);
if (messageCount == 0)
break;
}
}
@@ -1696,21 +1701,26 @@ void ScriptingCore::debugProcessInput(const std::string& str)
static bool NS_ProcessNextEvent()
{
g_qMutex.lock();
size_t size = g_queue.size();
g_qMutex.unlock();
auto sc = ScriptingCore::getInstance();
while (size > 0)
std::string message;
size_t messageCount = 0;
while (true)
{
g_qMutex.lock();
auto first = g_queue.begin();
std::string str = *first;
g_queue.erase(first);
size = g_queue.size();
messageCount = g_queue.size();
if (messageCount > 0)
{
auto first = g_queue.begin();
message = *first;
g_queue.erase(first);
--messageCount;
}
g_qMutex.unlock();
sc->debugProcessInput(str);
if (!message.empty())
ScriptingCore::getInstance()->debugProcessInput(message);
if (messageCount == 0)
break;
}
// std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
@@ -1850,6 +1860,11 @@ static void serverEntryPoint(unsigned int port)
listen(s, 1);
#define MAX_RECEIVED_SIZE 1024
#define BUF_SIZE MAX_RECEIVED_SIZE + 1
char buf[BUF_SIZE] = {0};
int readBytes = 0;
while (true) {
clientSocket = accept(s, NULL, NULL);
@@ -1866,10 +1881,8 @@ static void serverEntryPoint(unsigned int port)
inData = "connected";
// process any input, send any output
clearBuffers();
char buf[1024] = {0};
int readBytes = 0;
while ((readBytes = (int)::recv(clientSocket, buf, sizeof(buf), 0)) > 0)
while ((readBytes = (int)::recv(clientSocket, buf, MAX_RECEIVED_SIZE, 0)) > 0)
{
buf[readBytes] = '\0';
// TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf);
@@ -1883,6 +1896,9 @@ static void serverEntryPoint(unsigned int port)
cc_closesocket(clientSocket);
}
} // while(true)
#undef BUF_SIZE
#undef MAX_RECEIVED_SIZE
}
bool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, jsval* vp)
@@ -700,22 +700,25 @@ static bool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSConte
return false;
}
__JSDownloaderDelegator::__JSDownloaderDelegator(JSContext *cx, const std::string &url, int callbackIndex)
__JSDownloaderDelegator::__JSDownloaderDelegator(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback)
: _cx(cx)
, _url(url)
, _callbackIndex(callbackIndex)
{
_obj.construct(_cx, obj);
_jsCallback.construct(_cx, callback);
}
__JSDownloaderDelegator::~__JSDownloaderDelegator()
{
_obj.destroyIfConstructed();
_jsCallback.destroyIfConstructed();
_downloader->onTaskError = (nullptr);
_downloader->onDataTaskSuccess = (nullptr);
}
__JSDownloaderDelegator *__JSDownloaderDelegator::create(JSContext *cx, const std::string &url, int callbackIndex)
__JSDownloaderDelegator *__JSDownloaderDelegator::create(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback)
{
__JSDownloaderDelegator *delegate = new (std::nothrow) __JSDownloaderDelegator(cx, url, callbackIndex);
__JSDownloaderDelegator *delegate = new (std::nothrow) __JSDownloaderDelegator(cx, obj, url, callback);
delegate->autorelease();
return delegate;
}
@@ -784,19 +787,15 @@ void __JSDownloaderDelegator::onError()
{
Director::getInstance()->getScheduler()->performFunctionInCocosThread([this]
{
auto sc = ScriptingCore::getInstance();
JS::RootedObject globalObj(_cx, sc->getGlobalObject());
JS::RootedValue runtimeValue(_cx);
JS_GetProperty(_cx, globalObj, "jsb", &runtimeValue);
JS::RootedObject runtimeObj(_cx, runtimeValue.toObjectOrNull());
jsval valArr[3];
valArr[0] = INT_TO_JSVAL(_callbackIndex);
valArr[1] = BOOLEAN_TO_JSVAL(false);
JS::RootedValue retVal(_cx);
JS_CallFunctionName(_cx, runtimeObj, "onDownloadRemoteFile", JS::HandleValueArray::fromMarkedLocation(2, valArr), &retVal);
JS::RootedValue callback(_cx, OBJECT_TO_JSVAL(_jsCallback.ref()));
if (!callback.isNull()) {
JS::RootedObject global(_cx, ScriptingCore::getInstance()->getGlobalObject());
JSAutoCompartment ac(_cx, global);
jsval succeed = BOOLEAN_TO_JSVAL(false);
JS::RootedValue retval(_cx);
JS_CallFunctionValue(_cx, global, callback, JS::HandleValueArray::fromMarkedLocation(1, &succeed), &retval);
}
release();
});
}
@@ -809,11 +808,10 @@ void __JSDownloaderDelegator::onSuccess(Texture2D *tex)
JS::RootedObject global(_cx, ScriptingCore::getInstance()->getGlobalObject());
JSAutoCompartment ac(_cx, global);
jsval valArr[3];
valArr[0] = INT_TO_JSVAL(_callbackIndex);
jsval valArr[2];
if (tex)
{
valArr[1] = BOOLEAN_TO_JSVAL(true);
valArr[0] = BOOLEAN_TO_JSVAL(true);
js_proxy_t* p = jsb_get_native_proxy(tex);
if (!p)
{
@@ -823,23 +821,20 @@ void __JSDownloaderDelegator::onSuccess(Texture2D *tex)
p = jsb_new_proxy(tex, obj);
JS::AddNamedObjectRoot(_cx, &p->obj, "cocos2d::Texture2D");
}
valArr[2] = OBJECT_TO_JSVAL(p->obj);
valArr[1] = OBJECT_TO_JSVAL(p->obj);
}
else
{
valArr[1] = BOOLEAN_TO_JSVAL(false);
valArr[2] = JSVAL_NULL;
valArr[0] = BOOLEAN_TO_JSVAL(false);
valArr[1] = JSVAL_NULL;
}
auto sc = ScriptingCore::getInstance();
JS::RootedObject globalObj(_cx, sc->getGlobalObject());
JS::RootedValue runtimeValue(_cx);
JS_GetProperty(_cx, globalObj, "jsb", &runtimeValue);
JS::RootedObject runtimeObj(_cx, runtimeValue.toObjectOrNull());
JS::RootedValue retVal(_cx);
JS_CallFunctionName(_cx, runtimeObj, "onDownloadRemoteFile", JS::HandleValueArray::fromMarkedLocation(3, valArr), &retVal);
JS::RootedValue callback(_cx, OBJECT_TO_JSVAL(_jsCallback.ref()));
if (!callback.isNull())
{
JS::RootedValue retval(_cx);
JS_CallFunctionValue(_cx, global, callback, JS::HandleValueArray::fromMarkedLocation(2, valArr), &retval);
}
release();
}
}
@@ -854,17 +849,15 @@ bool js_load_remote_image(JSContext *cx, uint32_t argc, jsval *vp)
std::string url;
bool ok = jsval_to_std_string(cx, args.get(0), &url);
JSB_PRECONDITION2(ok, cx, false, "js_load_remote_image : Error processing arguments");
int callbackIndex;
jsval_to_int(cx, args.get(1), &callbackIndex);
JSB_PRECONDITION2(ok, cx, false, "js_load_remote_image : Error processing arguments");
__JSDownloaderDelegator *delegate = __JSDownloaderDelegator::create(cx, url, callbackIndex);
JS::RootedObject callback(cx, args.get(1).toObjectOrNull());
__JSDownloaderDelegator *delegate = __JSDownloaderDelegator::create(cx, obj, url, callback);
delegate->downloadAsync();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_load_remote_image : wrong number of arguments");
return false;
}
@@ -905,6 +898,6 @@ void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject glob
JS::RootedObject jsbObj(cx);
get_or_create_js_obj(cx, global, "jsb", &jsbObj);
JS_DefineFunction(cx, jsbObj, "__loadRemoteImg", js_load_remote_image, 2, JSPROP_READONLY | JSPROP_PERMANENT);
JS_DefineFunction(cx, jsbObj, "loadRemoteImg", js_load_remote_image, 2, JSPROP_READONLY | JSPROP_PERMANENT);
}
@@ -36,10 +36,10 @@ public:
void downloadAsync();
void download();
static __JSDownloaderDelegator *create(JSContext *cx, const std::string &url, int callbackIndex);
static __JSDownloaderDelegator *create(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback);
protected:
__JSDownloaderDelegator(JSContext *cx, const std::string &url, int callbackIndex);
__JSDownloaderDelegator(JSContext *cx, JS::HandleObject obj, const std::string &url, JS::HandleObject callback);
~__JSDownloaderDelegator();
void startDownload();
@@ -50,7 +50,8 @@ private:
std::shared_ptr<cocos2d::network::Downloader> _downloader;
std::string _url;
JSContext *_cx;
int _callbackIndex;
mozilla::Maybe<JS::PersistentRootedObject> _jsCallback;
mozilla::Maybe<JS::PersistentRootedObject> _obj;
};
void register_all_cocos2dx_extension_manual(JSContext* cx, JS::HandleObject global);
@@ -28,6 +28,8 @@
using namespace spine;
std::unordered_map<spTrackEntry*, jsval> _spTrackEntryMap;
jsval speventdata_to_jsval(JSContext* cx, spEventData& v)
{
JS::RootedObject tmp(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr()));
@@ -278,11 +280,35 @@ jsval sptrackentry_to_jsval(JSContext* cx, spTrackEntry& v)
JS::RootedValue nextVal(cx);
if (v.next)
nextVal = sptrackentry_to_jsval(cx, *v.next);
{
auto nextPtr = v.next;
auto entry = _spTrackEntryMap.find(nextPtr);
if (entry == _spTrackEntryMap.end())
{
_spTrackEntryMap.emplace(nextPtr, nextVal.get());
nextVal = sptrackentry_to_jsval(cx, *v.next);
}
else
{
nextVal.set(entry->second);
}
}
JS::RootedValue previousVal(cx);
if (v.previous)
previousVal = sptrackentry_to_jsval(cx, *v.previous);
{
auto previousPtr = v.previous;
auto entry = _spTrackEntryMap.find(previousPtr);
if (entry == _spTrackEntryMap.end())
{
_spTrackEntryMap.emplace(previousPtr, previousVal.get());
previousVal = sptrackentry_to_jsval(cx, *previousPtr);
}
else
{
previousVal.set(entry->second);
}
}
JS::RootedValue jsanimation(cx, spanimation_to_jsval(cx, *v.animation));
bool ok = JS_DefineProperty(cx, tmp, "delay", v.delay, JSPROP_ENUMERATE | JSPROP_PERMANENT) &&
@@ -449,6 +475,7 @@ bool jsb_cocos2dx_spine_getCurrent(JSContext *cx, uint32_t argc, jsval *vp)
if (ret)
{
jsret = sptrackentry_to_jsval(cx, *ret);
_spTrackEntryMap.clear();
}
} while (0);
@@ -462,6 +489,7 @@ bool jsb_cocos2dx_spine_getCurrent(JSContext *cx, uint32_t argc, jsval *vp)
if (ret)
{
jsret = sptrackentry_to_jsval(cx, *ret);
_spTrackEntryMap.clear();
}
} while (0);
@@ -498,6 +526,7 @@ bool jsb_cocos2dx_spine_setAnimation(JSContext *cx, uint32_t argc, jsval *vp)
if (ret)
{
jsret = sptrackentry_to_jsval(cx, *ret);
_spTrackEntryMap.clear();
}
} while(0);
@@ -535,6 +564,7 @@ bool jsb_cocos2dx_spine_addAnimation(JSContext *cx, uint32_t argc, jsval *vp)
if (ret)
{
jsret = sptrackentry_to_jsval(cx, *ret);
_spTrackEntryMap.clear();
}
} while(0);
@@ -560,6 +590,7 @@ bool jsb_cocos2dx_spine_addAnimation(JSContext *cx, uint32_t argc, jsval *vp)
if (ret)
{
jsret = sptrackentry_to_jsval(cx, *ret);
_spTrackEntryMap.clear();
}
} while(0);
@@ -132,8 +132,7 @@ cc.isValidValue = function(obj) {
* @returns {boolean}
*/
cc.isObject = function(obj) {
return (obj && obj.__nativeObj !== undefined) ||
( typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]' );
return ( obj !== null && typeof obj === "object" );
};
/**
@@ -28,7 +28,6 @@
@interface CCUISingleLineTextField : NSTextField<CCUITextInput>
{
NSMutableDictionary* _placeholderAttributes;
}
@end
@@ -26,6 +26,78 @@
#import "ui/UIEditBox/Mac/CCUISingleLineTextField.h"
#include "ui/UIEditBox/Mac/CCUITextFieldFormatter.h"
@interface RSVerticallyCenteredTextFieldCell : NSTextFieldCell
{
BOOL mIsEditingOrSelecting;
}
@end
@implementation RSVerticallyCenteredTextFieldCell
- (NSRect)drawingRectForBounds:(NSRect)theRect
{
// Get the parent's idea of where we should draw
NSRect newRect = [super drawingRectForBounds:theRect];
// When the text field is being
// edited or selected, we have to turn off the magic because it screws up
// the configuration of the field editor. We sneak around this by
// intercepting selectWithFrame and editWithFrame and sneaking a
// reduced, centered rect in at the last minute.
if (mIsEditingOrSelecting == NO)
{
// Get our ideal size for current text
NSSize textSize = [self cellSizeForBounds:theRect];
// Center that in the proposed rect
float heightDelta = newRect.size.height - textSize.height;
if (heightDelta > 0)
{
newRect.size.height -= heightDelta;
newRect.origin.y += (heightDelta / 2);
}
}
return newRect;
}
- (void)selectWithFrame:(NSRect)aRect
inView:(NSView *)controlView
editor:(NSText *)textObj
delegate:(id)anObject
start:(long)selStart
length:(long)selLength
{
aRect = [self drawingRectForBounds:aRect];
mIsEditingOrSelecting = YES;
[super selectWithFrame:aRect
inView:controlView
editor:textObj
delegate:anObject
start:selStart
length:selLength];
mIsEditingOrSelecting = NO;
}
- (void)editWithFrame:(NSRect)aRect
inView:(NSView *)controlView
editor:(NSText *)textObj
delegate:(id)anObject
event:(NSEvent *)theEvent
{
aRect = [self drawingRectForBounds:aRect];
mIsEditingOrSelecting = YES;
[super editWithFrame:aRect
inView:controlView
editor:textObj
delegate:anObject
event:theEvent];
mIsEditingOrSelecting = NO;
}
@end
@interface CCUISingleLineTextField()
@property (nonatomic, retain) NSMutableDictionary *placeholderAttributes;
@@ -35,44 +107,35 @@
{
}
@synthesize placeholderAttributes = _placeholderAttributes;
-(id) initWithFrame:(NSRect)frameRect
{
if ([super initWithFrame:frameRect]) {
NSFont* font = [NSFont systemFontOfSize:frameRect.size.height * 3 /2];
self.placeholderAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
[NSColor grayColor], NSForegroundColorAttributeName,
nil];
[self setLineBreakMode:NSLineBreakByTruncatingTail];
}
return self;
}
- (void)dealloc
+(void)load
{
self.placeholderAttributes = nil;
[self setCellClass:[RSVerticallyCenteredTextFieldCell class]];
}
- (void)dealloc
{
[super dealloc];
}
-(void)ccui_setPlaceholderFont:(NSFont *)font
{
[self.placeholderAttributes setObject:font forKey:NSFontAttributeName];
//TODO:
}
-(void)ccui_setPlaceholder:(NSString *)text
{
NSAttributedString *as = [[NSAttributedString alloc] initWithString:text
attributes:self.placeholderAttributes];
[[self cell] setPlaceholderAttributedString:as];
[as release];
//TODO:
}
-(NSString*)ccui_placeholder
@@ -82,17 +145,18 @@
-(NSFont*)ccui_placeholderFont
{
return [self.placeholderAttributes objectForKey:NSFontAttributeName];
//FIXME:
return [NSFont systemFontOfSize:self.bounds.size.height * 3.0 / 2.0];
}
-(NSColor*)ccui_placeholderColor
{
return [self.placeholderAttributes objectForKey:NSForegroundColorAttributeName];
return [NSColor whiteColor];
}
-(void)ccui_setPlaceholderColor:(NSColor *)color
{
[self.placeholderAttributes setObject:color forKey:NSForegroundColorAttributeName];
//TODO:
}
- (NSString *)ccui_text
@@ -79,24 +79,45 @@ void EditBoxImplCommon::initInactiveLabels(const Size& size)
const char* pDefaultFontName = this->getNativeDefaultFontName();
_label = Label::create();
_label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
_label->setAnchorPoint(Vec2(0,1));
_label->setOverflow(Label::Overflow::CLAMP);
_label->setColor(Color3B::WHITE);
_label->setVisible(false);
_editBox->addChild(_label, kLabelZOrder);
_labelPlaceHolder = Label::create();
_labelPlaceHolder->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
_labelPlaceHolder->setAnchorPoint(Vec2(0,1));
_labelPlaceHolder->setColor(Color3B::GRAY);
_editBox->addChild(_labelPlaceHolder, kLabelZOrder);
setFont(pDefaultFontName, size.height*2/3);
setPlaceholderFont(pDefaultFontName, size.height*2/3);
}
void EditBoxImplCommon::placeInactiveLabels()
void EditBoxImplCommon::placeInactiveLabels(const Size& size)
{
_label->setPosition(CC_EDIT_BOX_PADDING, _contentSize.height / 2.0f);
_labelPlaceHolder->setPosition(CC_EDIT_BOX_PADDING, _contentSize.height / 2.0f);
_label->setDimensions(size.width, size.height);
auto placeholderSize = _labelPlaceHolder->getContentSize();
if(_editBoxInputMode == EditBox::InputMode::ANY){
_label->setPosition(Vec2(CC_EDIT_BOX_PADDING, size.height - CC_EDIT_BOX_PADDING));
_label->setVerticalAlignment(TextVAlignment::TOP);
_label->enableWrap(true);
_labelPlaceHolder->setPosition(Vec2(CC_EDIT_BOX_PADDING, size.height - CC_EDIT_BOX_PADDING));
_labelPlaceHolder->setVerticalAlignment(TextVAlignment::TOP);
}
else {
_label->enableWrap(false);
_label->setPosition(Vec2(CC_EDIT_BOX_PADDING, size.height));
_label->setVerticalAlignment(TextVAlignment::CENTER);
_labelPlaceHolder->setPosition(Vec2(CC_EDIT_BOX_PADDING,
(size.height + placeholderSize.height) / 2));
_labelPlaceHolder->setVerticalAlignment(TextVAlignment::CENTER);
}
}
void EditBoxImplCommon::setInactiveText(const char* pText)
@@ -168,6 +189,7 @@ void EditBoxImplCommon::setInputMode(EditBox::InputMode inputMode)
{
_editBoxInputMode = inputMode;
this->setNativeInputMode(inputMode);
this->placeInactiveLabels(_editBox->getContentSize());
}
void EditBoxImplCommon::setMaxLength(int maxLength)
@@ -249,7 +271,7 @@ void EditBoxImplCommon::setContentSize(const Size& size)
{
_contentSize = size;
CCLOG("[Edit text] content size = (%f, %f)", size.width, size.height);
placeInactiveLabels();
placeInactiveLabels(size);
}
void EditBoxImplCommon::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
@@ -116,7 +116,7 @@ public:
private:
void initInactiveLabels(const Size& size);
void setInactiveText(const char* pText);
void placeInactiveLabels();
void placeInactiveLabels(const Size& size);
virtual void doAnimationWhenKeyboardMove(float duration, float distance)override {};
Label* _label;
Label* _labelPlaceHolder;
@@ -82,8 +82,13 @@ CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25;
- (UILabel *)placeHolderLabel
{
if (_placeHolderLabel == nil) {
auto glview = cocos2d::Director::DirectorInstance->getOpenGLView();
float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor();
_placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
_placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding,
padding,
self.bounds.size.width - padding * 2,
0)];
_placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
_placeHolderLabel.numberOfLines = 0;
_placeHolderLabel.font = self.font;
+2
View File
@@ -1223,6 +1223,8 @@ void Widget::copyProperties(Widget *widget)
setFlippedY(widget->isFlippedY());
setColor(widget->getColor());
setOpacity(widget->getOpacity());
setCascadeColorEnabled(widget->isCascadeColorEnabled());
setCascadeOpacityEnabled(widget->isCascadeOpacityEnabled());
_touchEventCallback = widget->_touchEventCallback;
_touchEventListener = widget->_touchEventListener;
_touchEventSelector = widget->_touchEventSelector;
+12 -10
View File
@@ -11,7 +11,7 @@ var fs = require('fs-extra');
gulp.task('make-cocos2d-x', gulpSequence('gen-cocos2d-x', 'upload-cocos2d-x'));
gulp.task('make-prebuilt', gulpSequence('gen-libs', 'collect-prebuilt-mk', 'archive-prebuilt-mk', 'archive-prebuilt', 'upload-prebuilt', 'upload-prebuilt-mk'));
gulp.task('make-simulator', gulpSequence('update-simulator-config', 'archive-simulator', 'upload-simulator'));
gulp.task('make-simulator', gulpSequence('update-simulator-config', 'update-simulator-dll', 'archive-simulator', 'upload-simulator'));
function execSync(cmd, workPath) {
var execOptions = {
@@ -159,11 +159,11 @@ gulp.task('gen-simulator', function (cb) {
});
gulp.task('collect-prebuilt-mk', function () {
fs.removeSync('./prebuilt_mk');
return gulp.src([
'**/prebuilt-mk/Android.mk',
], {
base: './',
ignore: './prebuilt_mk/**/*'
base: './'
}).pipe(gulp.dest('prebuilt_mk'));
});
@@ -172,6 +172,14 @@ gulp.task('update-simulator-config', ['update-simulator-script'], function (cb)
fs.copy('./tools/simulator/config.json', destPath, cb);
});
gulp.task('update-simulator-dll', function (cb) {
if (process.platform === 'win32') {
downloadSimulatorDLL(cb);
} else {
cb();
}
});
gulp.task('update-simulator-script', function (cb) {
var simulatorPath = process.platform === 'win32' ? './simulator/win32' : './simulator/mac/Simulator.app/Contents/Resources';
var destPath = simulatorPath + '/script';
@@ -191,13 +199,7 @@ gulp.task('update-simulator-script', function (cb) {
if (!fs.existsSync(simulatorPath)) {
console.error(`Cant\'t find simulator dir [${simulatorPath}]`);
} else {
if (process.platform === 'win32') {
downloadSimulatorDLL(function () {
updateScript(cb);
});
} else {
updateScript(cb);
}
updateScript(cb);
}
});
+4
View File
@@ -116,8 +116,12 @@
"cocos/2d/CCSpriteFrame.h",
"cocos/2d/CCSpriteFrameCache.cpp",
"cocos/2d/CCSpriteFrameCache.h",
"cocos/2d/CCTMXLayer.cpp",
"cocos/2d/CCTMXLayer.h",
"cocos/2d/CCTMXObjectGroup.cpp",
"cocos/2d/CCTMXObjectGroup.h",
"cocos/2d/CCTMXTiledMap.cpp",
"cocos/2d/CCTMXTiledMap.h",
"cocos/2d/CCTMXXMLParser.cpp",
"cocos/2d/CCTMXXMLParser.h",
"cocos/2d/CCTextFieldTTF.cpp",
@@ -1,4 +1,3 @@
{
"engine_type": "prebuilt",
"engine_version": "cocos2d-x-3.10"
"engine_type": "prebuilt"
}
@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>HelloJavascript</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
<nature>org.ccdt.cocosproject</nature>
<nature>org.ccdt.jsdt.core.jsNature</nature>
</natures>
<cocosprojecttemplate>
<version>1.2</version>
</cocosprojecttemplate>
<linkedResources>
<link>
<name>script</name>
<type>2</type>
<locationURI>PROJECT_LOC/frameworks/js-bindings/bindings/script</locationURI>
</link>
</linkedResources>
</projectDescription>
@@ -1,5 +0,0 @@
{
"engineVersion": "cocos2d-x-3.10",
"runtimeVersion": "1.8",
"templateVersion": "1.8"
}
@@ -1,21 +1,8 @@
{
"do_default":{
"exclude_from_template":[
"frameworks/runtime-src",
"res-landscape",
"res-portrait"
"frameworks/runtime-src"
],
"append_from_template": {
"from": "res-landscape",
"to": ""
},
"project_replace_project_name":{
"src_project_name":"HelloJavascript",
"files":[
"config.json",
".project"
]
},
"append_dir":[
{
"from": "cocos/scripting/js-bindings/script",
@@ -33,6 +20,7 @@
"exclude":[
"proj.android/bin",
"proj.android/assets",
"proj.android/libs",
"proj.ios_mac/HelloJavascript.xcodeproj/project.xcworkspace",
"proj.ios_mac/HelloJavascript.xcodeproj/xcuserdata",
"proj.win32/Debug.win32",
@@ -41,20 +29,6 @@
]
},
"append_dir":[
{
"from":"tools/bindings-generator",
"to":"tools/bindings-generator",
"exclude":[
".git"
]
},
{
"from":"tools",
"to":"tools",
"include":[
"tojs"
]
},
{
"from":"cocos/platform/android/java/src",
"to":"frameworks/runtime-src/proj.android/src",
@@ -78,13 +52,11 @@
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.user",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.sln",
"frameworks/runtime-src/proj.ios_mac/PROJECT_NAME.xcodeproj"
]
]
},
"project_replace_project_name":{
"src_project_name":"HelloJavascript",
"files":[
"config.json",
".project",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.filters",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.user",
@@ -96,7 +68,6 @@
"frameworks/runtime-src/proj.android/res/values/strings.xml",
"frameworks/runtime-src/proj.ios_mac/ios/main.m",
"frameworks/runtime-src/proj.ios_mac/ios/Prefix.pch",
"frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm",
"frameworks/runtime-src/proj.ios_mac/PROJECT_NAME.xcodeproj/project.pbxproj",
"frameworks/runtime-src/Classes/AppDelegate.cpp"
]
@@ -119,34 +90,6 @@
"frameworks/runtime-src/proj.ios_mac/ios/Info.plist"
]
}
},
"change_orientation": {
"append_from_template": {
"from": "res-portrait",
"to": ""
},
"modify_files": [
{
"file_path": "main.js",
"pattern": "setDesignResolutionSize\\(\\s*(\\d+),\\s*(\\d+),(.*)\\)",
"replace_string": "setDesignResolutionSize(\\2, \\1,\\3)"
},
{
"file_path": "frameworks/runtime-src/proj.ios_mac/ios/Info.plist",
"pattern": "UIInterfaceOrientationLandscapeRight",
"replace_string": "UIInterfaceOrientationPortrait"
},
{
"file_path": "frameworks/runtime-src/proj.ios_mac/ios/Info.plist",
"pattern": "UIInterfaceOrientationLandscapeLeft",
"replace_string": "UIInterfaceOrientationPortraitUpsideDown"
},
{
"file_path": "frameworks/runtime-src/proj.android/AndroidManifest.xml",
"pattern": "android:screenOrientation=\\\".*\\\"",
"replace_string": "android:screenOrientation=\"portrait\""
}
]
}
}
}
@@ -1,16 +1,8 @@
#include "AppDelegate.h"
#include "SimpleAudioEngine.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_LINUX)
#include "ide-support/CodeIDESupport.h"
#endif
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#include "runtime/Runtime.h"
#include "ide-support/RuntimeJsImpl.h"
#else
#include "js_module_register.h"
#endif
USING_NS_CC;
using namespace CocosDenshion;
@@ -21,23 +13,13 @@ AppDelegate::AppDelegate()
AppDelegate::~AppDelegate()
{
SimpleAudioEngine::end();
ScriptEngineManager::destroyInstance();
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
RuntimeEngine::getInstance()->end();
#endif
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
@@ -45,29 +27,19 @@ bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
#if(CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
glview = cocos2d::GLViewImpl::create("raphael");
#else
glview = cocos2d::GLViewImpl::createWithRect("raphael", Rect(0,0,900,640));
#endif
director->setOpenGLView(glview);
}
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
// for getIPAddress
extern void setActivityPathForAndroid(const std::string &path);
setActivityPathForAndroid("org/cocos2dx/javascript/AppActivity");
#endif
auto runtimeEngine = RuntimeEngine::getInstance();
auto jsRuntime = RuntimeJsImpl::create();
runtimeEngine->addRuntime(jsRuntime, kRuntimeEngineJs);
runtimeEngine->start();
// js need special debug port
if (runtimeEngine->getProjectConfig().getDebuggerType() != kCCRuntimeDebuggerNone)
{
jsRuntime->startWithDebugger();
}
#else
js_module_register();
ScriptingCore* sc = ScriptingCore::getInstance();
@@ -76,11 +48,9 @@ bool AppDelegate::applicationDidFinishLaunching()
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
sc->enableDebugger();
#endif
ScriptEngineProtocol *engine = ScriptingCore::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
ScriptEngineManager::getInstance()->setScriptEngine(sc);
ScriptingCore::getInstance()->runScript("main.js");
#endif
return true;
}
@@ -91,7 +61,7 @@ void AppDelegate::applicationDidEnterBackground()
director->stopAnimation();
director->getEventDispatcher()->dispatchCustomEvent("game_on_hide");
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
SimpleAudioEngine::getInstance()->pauseAllEffects();
SimpleAudioEngine::getInstance()->pauseAllEffects();
}
// this function will be called when the app is active again
@@ -103,4 +73,3 @@ void AppDelegate::applicationWillEnterForeground()
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
SimpleAudioEngine::getInstance()->resumeAllEffects();
}
@@ -9,7 +9,7 @@
#ifndef _APP_DELEGATE_H_
#define _APP_DELEGATE_H_
#include "cocos2d.h"
#include "platform/CCApplication.h"
/**
@brief The cocos2d Application.
@@ -43,5 +43,5 @@ public:
virtual void applicationWillEnterForeground();
};
#endif // __APP_DELEGATE_H__
#endif // _APP_DELEGATE_H_
@@ -1,7 +0,0 @@
#ifndef __CODE_IDE_SUPPORT_H__
#define __CODE_IDE_SUPPORT_H__
// define 1 to open Cocos Code IDE support, 0 to disable
#define CC_CODE_IDE_DEBUG_SUPPORT 0
#endif /* __CODE_IDE_SUPPORT_H__ */
@@ -1,309 +0,0 @@
//
// RuntimeJsImpl.cpp
// Simulator
//
//
#include "RuntimeJsImpl.h"
#include "cocos2d.h" // 2dx engine
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#include "runtime/ConfigParser.h" // config
#include "runtime/Runtime.h"
#include "runtime/FileServer.h"
// js
#include "scripting/js-bindings/manual/ScriptingCore.h"
#include "js_module_register.h"
USING_NS_CC;
static const char *RUNTIME_JS_BOOT_SCRIPT = "script/jsb_boot.js";
static bool reloadScript(const string& file)
{
auto director = Director::getInstance();
FontFNT::purgeCachedData();
if (director->getOpenGLView())
{
SpriteFrameCache::getInstance()->removeSpriteFrames();
director->getTextureCache()->removeAllTextures();
}
FileUtils::getInstance()->purgeCachedEntries();
//director->getScheduler()->unscheduleAll();
//director->getScheduler()->scheduleUpdate(director->getActionManager(), Scheduler::PRIORITY_SYSTEM, false);
string modulefile = file;
if (modulefile.empty())
{
modulefile = ConfigParser::getInstance()->getEntryFile().c_str();
}
return ScriptingCore::getInstance()->runScript(modulefile.c_str());
}
bool runtime_FileUtils_addSearchPath(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::FileUtils* cobj = (cocos2d::FileUtils *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "cocos2dx_FileUtils_addSearchPath : Invalid Native Object");
if (argc == 1 || argc == 2) {
std::string arg0;
bool arg1 = false;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "cocos2dx_FileUtils_addSearchPath : Error processing arguments");
if (argc == 2)
{
arg1 = JS::ToBoolean(JS::RootedValue(cx, args.get(1)));
}
if (! FileUtils::getInstance()->isAbsolutePath(arg0))
{
// add write path to search path
if (FileServer::getShareInstance()->getIsUsingWritePath())
{
cobj->addSearchPath(FileServer::getShareInstance()->getWritePath() + arg0, arg1);
} else
{
cobj->addSearchPath(arg0, arg1);
}
#if(CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
// add project path to search path
cobj->addSearchPath(RuntimeEngine::getInstance()->getRuntime()->getProjectPath() + arg0, arg1);
#endif
}
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "cocos2dx_FileUtils_addSearchPath : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool runtime_FileUtils_setSearchPaths(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::FileUtils* cobj = (cocos2d::FileUtils *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_FileUtils_setSearchPaths : Invalid Native Object");
if (argc == 1) {
std::vector<std::string> vecPaths, writePaths;
ok &= jsval_to_std_vector_string(cx, args.get(0), &vecPaths);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_FileUtils_setSearchPaths : Error processing arguments");
std::vector<std::string> originPath; // for IOS platform.
std::vector<std::string> projPath; // for Desktop platform.
for (int i = 0; i < vecPaths.size(); i++)
{
if (!FileUtils::getInstance()->isAbsolutePath(vecPaths[i]))
{
originPath.push_back(vecPaths[i]); // for IOS platform.
projPath.push_back(RuntimeEngine::getInstance()->getRuntime()->getProjectPath()+vecPaths[i]); //for Desktop platform.
writePaths.push_back(FileServer::getShareInstance()->getWritePath() + vecPaths[i]);
}
}
#if(CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
vecPaths.insert(vecPaths.end(), projPath.begin(), projPath.end());
#endif
if (FileServer::getShareInstance()->getIsUsingWritePath())
{
vecPaths.insert(vecPaths.end(), writePaths.begin(), writePaths.end());
} else
{
vecPaths.insert(vecPaths.end(), originPath.begin(), originPath.end());
}
cobj->setSearchPaths(vecPaths);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_FileUtils_setSearchPaths : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
void register_FileUtils(JSContext *cx, JS::HandleObject global)
{
JS::RootedValue nsval(cx);
JS::RootedObject ns(cx);
JS_GetProperty(cx, global, "cc", &nsval);
if (nsval == JSVAL_VOID) {
return;
}
else {
ns.set(nsval.toObjectOrNull());
}
JS::RootedObject proto(cx, get_jsb_cocos2d_FileUtils_prototype());
JS_DefineFunction(cx, proto, "addSearchPath", runtime_FileUtils_addSearchPath, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE);
JS_DefineFunction(cx, proto, "setSearchPaths", runtime_FileUtils_setSearchPaths, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE);
}
RuntimeJsImpl* RuntimeJsImpl::create()
{
RuntimeJsImpl *instance = new RuntimeJsImpl();
return instance;
}
bool RuntimeJsImpl::initJsEnv()
{
if (_hasStarted)
{
return true;
}
js_module_register();
ScriptingCore::getInstance()->addRegisterCallback(register_FileUtils);
ScriptingCore::getInstance()->start();
_hasStarted = true;
ScriptEngineProtocol *engine = ScriptingCore::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
return true;
}
bool RuntimeJsImpl::startWithDebugger()
{
initJsEnv();
int debugPort = 5086;
#if(CC_PLATFORM_MAC == CC_TARGET_PLATFORM || CC_PLATFORM_WIN32 == CC_TARGET_PLATFORM)
debugPort = ConfigParser::getInstance()->getDebugPort();
#endif
ScriptingCore::getInstance()->enableDebugger(debugPort);
return true;
}
void RuntimeJsImpl::startScript(const std::string& path)
{
loadScriptFile(path);
}
void RuntimeJsImpl::onStartDebuger(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse)
{
if (loadScriptFile(ConfigParser::getInstance()->getEntryFile()))
{
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}
else
{
dReplyParse.AddMember("code",1,dReplyParse.GetAllocator());
}
}
void RuntimeJsImpl::onClearCompile(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse)
{
if (dArgParse.HasMember("modulefiles") && dArgParse["modulefiles"].Size() != 0)
{
const rapidjson::Value& objectfiles = dArgParse["modulefiles"];
for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++)
{
ScriptingCore::getInstance()->cleanScript(objectfiles[i].GetString());
}
}
else
{
std::unordered_map<std::string, JSScript*> filenameScript = ScriptingCore::getInstance()->getFileScript();
filenameScript.clear();
}
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}
void RuntimeJsImpl::onPrecompile(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse)
{
const rapidjson::Value& objectfiles = dArgParse["modulefiles"];
for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++)
{
ScriptingCore* sc = ScriptingCore::getInstance();
JSContext* gc = sc->getGlobalContext();
sc->compileScript(objectfiles[i].GetString(),
JS::RootedObject(gc, sc->getGlobalObject()),
gc);
}
dReplyParse.AddMember("code",0,dReplyParse.GetAllocator());
}
void RuntimeJsImpl::onReload(const rapidjson::Document &dArgParse, rapidjson::Document &dReplyParse)
{
if (dArgParse.HasMember("modulefiles")){
auto& allocator = dReplyParse.GetAllocator();
rapidjson::Value bodyvalue(rapidjson::kObjectType);
const rapidjson::Value& objectfiles = dArgParse["modulefiles"];
for (rapidjson::SizeType i = 0; i < objectfiles.Size(); i++){
if (!reloadScript(objectfiles[i].GetString())) {
bodyvalue.AddMember(rapidjson::Value(objectfiles[i].GetString(), allocator)
, rapidjson::Value(1)
, allocator);
}
}
if (0 == objectfiles.Size())
{
reloadScript("");
}
dReplyParse.AddMember("body", bodyvalue, dReplyParse.GetAllocator());
}else
{
reloadScript("");
}
dReplyParse.AddMember("code", 0, dReplyParse.GetAllocator());
}
void RuntimeJsImpl::onRemove(const std::string &filename)
{
ScriptingCore::getInstance()->cleanScript(filename.c_str());
}
void RuntimeJsImpl::end()
{
ScriptEngineManager::destroyInstance();
RuntimeProtocol::end();
}
// private
RuntimeJsImpl::RuntimeJsImpl()
: _hasStarted(false)
{
}
bool RuntimeJsImpl::loadScriptFile(const std::string& path)
{
std::string filepath = path;
if (filepath.empty())
{
filepath = ConfigParser::getInstance()->getEntryFile();
}
CCLOG("------------------------------------------------");
CCLOG("LOAD Js FILE: %s", filepath.c_str());
CCLOG("------------------------------------------------");
initJsEnv();
auto engine = ScriptingCore::getInstance();
engine->runScript(RUNTIME_JS_BOOT_SCRIPT);
ScriptEngineManager::getInstance()->setScriptEngine(engine);
return ScriptingCore::getInstance()->runScript(filepath.c_str());
}
#endif // (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
@@ -1,39 +0,0 @@
//
// RuntimeJsImpl.h
// Simulator
//
//
#ifndef __Simulator__RuntimeJsImpl__
#define __Simulator__RuntimeJsImpl__
#include "CodeIDESupport.h"
#include "cocos2d.h"
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#include "runtime/RuntimeProtocol.h"
class RuntimeJsImpl : public RuntimeProtocol
{
public:
static RuntimeJsImpl* create();
void startScript(const std::string& file);
void onStartDebuger(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
void onClearCompile(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
void onPrecompile(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
void onReload(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
void onRemove(const std::string &filename);
void end();
bool startWithDebugger();
private:
RuntimeJsImpl();
bool initJsEnv();
bool loadScriptFile(const std::string& file);
bool _hasStarted;
};
#endif // (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#endif /* defined(__Simulator__RuntimeLua__) */
@@ -1,70 +0,0 @@
#include "json/document.h"
#include "json/filestream.h"
#include "json/stringbuffer.h"
#include "json/writer.h"
#include "SimpleConfigParser.h"
// SimpleConfigParser
SimpleConfigParser *SimpleConfigParser::s_sharedSimpleConfigParserInstance = NULL;
SimpleConfigParser *SimpleConfigParser::getInstance(void)
{
if (!s_sharedSimpleConfigParserInstance)
{
s_sharedSimpleConfigParserInstance = new SimpleConfigParser();
s_sharedSimpleConfigParserInstance->readConfig();
}
return s_sharedSimpleConfigParserInstance;
}
void SimpleConfigParser::purge()
{
CC_SAFE_DELETE(s_sharedSimpleConfigParserInstance);
}
void SimpleConfigParser::readConfig(const string &filepath)
{
string fullPathFile = filepath;
// read config file
if (fullPathFile.empty())
{
fullPathFile = FileUtils::getInstance()->fullPathForFilename(CONFIG_FILE);
}
string fileContent = FileUtils::getInstance()->getStringFromFile(fullPathFile);
if(fileContent.empty())
return;
if (_docRootjson.Parse<0>(fileContent.c_str()).HasParseError()) {
cocos2d::log("read json file %s failed because of %d", fullPathFile.c_str(), _docRootjson.GetParseError());
return;
}
if (_docRootjson.HasMember("init_cfg"))
{
if(_docRootjson["init_cfg"].IsObject())
{
const rapidjson::Value& objectInitView = _docRootjson["init_cfg"];
if (objectInitView.HasMember("isLandscape") && objectInitView["isLandscape"].IsBool())
{
_isLandscape = objectInitView["isLandscape"].GetBool();
}
}
}
}
SimpleConfigParser::SimpleConfigParser(void) :
_isLandscape(true)
{
}
rapidjson::Document& SimpleConfigParser::getConfigJsonRoot()
{
return _docRootjson;
}
bool SimpleConfigParser::isLanscape()
{
return _isLandscape;
}
@@ -1,31 +0,0 @@
#ifndef __SIMPLE_CONFIG_PARSER_H__
#define __SIMPLE_CONFIG_PARSER_H__
#include <string>
#include <vector>
#include "cocos2d.h"
#include "json/document.h"
using namespace std;
USING_NS_CC;
#define CONFIG_FILE "config.json"
class SimpleConfigParser
{
public:
static SimpleConfigParser *getInstance(void);
static void purge();
void readConfig(const string &filepath = "");
bool isLanscape();
rapidjson::Document& getConfigJsonRoot();
private:
SimpleConfigParser(void);
static SimpleConfigParser *s_sharedSimpleConfigParserInstance;
bool _isLandscape;
rapidjson::Document _docRootjson;
};
#endif // __SIMPLE_CONFIG_PARSER_H__
@@ -1,29 +0,0 @@
{
"zh-CN": {
"View": "视图(&V)",
"Exit": "退出(&X)",
"File": "文件(&F)",
"Portrait": "竖屏",
"Landscape": "横屏",
"Refresh": "刷新(重启)",
"Zoom Out": "缩放",
"Simulator": "模拟器",
"Open File": "打开文件",
"Open Project": "打开工程",
"Error": "错误",
"Help": "帮助(&H)",
"About": "关于(&A)"
},
"zh-Hans": {
"View": "视图",
"Exit": "退出",
"File": "文件",
"Portrait": "竖屏",
"Landscape": "横屏",
"Refresh": "刷新(重启)",
"Zoom Out": "缩放",
"Simulator": "模拟器",
"Help": "帮助(&H)",
"About": "关于(&A)"
}
}
@@ -1,12 +0,0 @@
#ifndef __JS_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_JS_MODULE_REGISTER_H__
#define __JS_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_JS_MODULE_REGISTER_H__
#include "scripting/js-bindings/manual/ScriptingCore.h"
#include "js-BindingsExport.h"
CC_JS_DLL int js_module_register();
CC_JS_DLL JSObject* get_jsb_cocos2d_FileUtils_prototype();
#endif // __JS_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_JS_MODULE_REGISTER_H__
@@ -12,17 +12,13 @@ endif
LOCAL_SRC_FILES := \
../../Classes/AppDelegate.cpp \
../../Classes/ide-support/SimpleConfigParser.cpp \
../../Classes/ide-support/RuntimeJsImpl.cpp \
hellojavascript/main.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \
LOCAL_STATIC_LIBRARIES := cocos2d_js_static
LOCAL_STATIC_LIBRARIES += cocos2d_simulator_static
include $(BUILD_SHARED_LIBRARY)
$(call import-module,scripting/js-bindings/proj.android/prebuilt-mk)
$(call import-module,tools/simulator/libsimulator/proj.android/prebuilt-mk)
@@ -3,7 +3,6 @@
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>
#include "ide-support/SimpleConfigParser.h"
#define LOG_TAG "main"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
@@ -14,16 +13,3 @@ void cocos_android_app_init (JNIEnv* env) {
LOGD("cocos_android_app_init");
AppDelegate *pAppDelegate = new AppDelegate();
}
extern "C"
{
bool Java_org_cocos2dx_javascript_AppActivity_nativeIsDebug(JNIEnv *env, jobject thisz)
{
#if (COCOS2D_DEBUG > 0)
return true;
#else
return false;
#endif
}
}
@@ -8,5 +8,5 @@
# project structure.
# Project target.
target=android-16
target=android-19
@@ -1,59 +0,0 @@
/****************************************************************************
Copyright (c) 2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.chukong.cocosplay.client;
import android.app.Activity;
public class CocosPlayClient {
public static boolean init(Activity activity, boolean isDemo) {
return false;
}
public static boolean isEnabled() {
return false;
}
public static boolean isDemo() {
return false;
}
public static boolean isNotifyFileLoadedEnabled() {
return false;
}
public static void notifyFileLoaded(String filePath) {
}
public static void updateAssets(String filePath) {
}
public static String getGameRoot() {
return "";
}
public static native String[] getSearchPaths();
}
@@ -1,10 +0,0 @@
package com.enhance.gameservice;
interface IGameTuningService
{
int setPreferredResolution(int resolution);
int setFramePerSecond(int fps);
int boostUp(int seconds);
int getAbstractTemperature();
int setGamePowerSaving(boolean enable);
}
@@ -28,34 +28,21 @@ package org.cocos2dx.javascript;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import android.content.pm.ActivityInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.WindowManager;
// For JS and JAVA reflection test, you can delete it if it's your own project
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
// -------------------------------------
// The name of .so is specified in AndroidMenifest.xml. NativityActivity will load it automatically for you.
// You can use "System.loadLibrary()" to load other .so files.
public class AppActivity extends Cocos2dxActivity {
public class AppActivity extends Cocos2dxActivity{
static String hostIPAdress = "0.0.0.0";
private static AppActivity app = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
app = this;
if(nativeIsDebug()){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
hostIPAdress = getHostIpAddress();
}
@Override
@@ -67,19 +54,6 @@ public class AppActivity extends Cocos2dxActivity{
return glSurfaceView;
}
public String getHostIpAddress() {
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));
}
public static String getLocalIpAddress() {
return hostIPAdress;
}
private static native boolean nativeIsDebug();
// For JS and JAVA reflection test, you can delete it if it's your own project
public static void showAlertDialog(final String title,final String message) {
// Here be sure to use runOnUiThread
@@ -92,5 +66,5 @@ public class AppActivity extends Cocos2dxActivity{
alertDialog.show();
}
});
}
}
}
@@ -12,10 +12,8 @@
1AD7E0A818C9DB93004817A6 /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6BF21418C9DB5900FB0E1C /* main.js */; };
1AD7E0A918C9DBE3004817A6 /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6BF21418C9DB5900FB0E1C /* main.js */; };
1AE159EC18C9DF3600FCA372 /* project.json in Resources */ = {isa = PBXBuildFile; fileRef = 1A1A081B18C9DF05005C6854 /* project.json */; };
1BFE40C9B3992EFC7694ECAD /* libsimulator iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = B369480BACF7CC3BFAF3B77A /* libsimulator iOS.a */; };
294D7D781D0D6667002CE7B7 /* CoreText.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 294D7D771D0D6667002CE7B7 /* CoreText.framework */; };
3B67481F942374033A420049 /* libjscocos2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = DCAA4417880B45A57D3DBA4A /* libjscocos2d iOS.a */; };
471C47CE8C319E15D42CFACA /* libsimulator Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DBD455C8FDA2F3E10BCC26C /* libsimulator Mac.a */; };
4EF7467CB50B6A7F2A970566 /* libcocos2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 403C4AA98CE6BA7FB917B960 /* libcocos2d iOS.a */; };
502380DC17EBB88200990C9B /* libcurl.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 502380DB17EBB88200990C9B /* libcurl.dylib */; };
5091731A17ECDF7A00D62437 /* Icon-29.png in Resources */ = {isa = PBXBuildFile; fileRef = 5091731417ECDF7A00D62437 /* Icon-29.png */; };
@@ -54,21 +52,6 @@
8EFD4931BFDBAFBB1B85B6CB /* script in Resources */ = {isa = PBXBuildFile; fileRef = 05D54E28ADAB15C7633DA54B /* script */; };
9BC548CABC4F606F82D43E76 /* script in Resources */ = {isa = PBXBuildFile; fileRef = 05D54E28ADAB15C7633DA54B /* script */; };
9F20C9E61A5BD38A006FB50B /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9F20C9E11A5BBE85006FB50B /* Security.framework */; };
9FD1E6B11A51361B0009A6C5 /* ConsoleWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9FD1E69E1A51361B0009A6C5 /* ConsoleWindow.xib */; };
9FD1E6B21A51361B0009A6C5 /* ConsoleWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6A01A51361B0009A6C5 /* ConsoleWindowController.m */; };
9FD1E6B31A51361B0009A6C5 /* DeviceEx-mac.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6A11A51361B0009A6C5 /* DeviceEx-mac.mm */; };
9FD1E6B41A51361B0009A6C5 /* OpenUDIDMac.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6A41A51361B0009A6C5 /* OpenUDIDMac.m */; };
9FD1E6B51A51361B0009A6C5 /* PlayerEditBoxServiceMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6A61A51361B0009A6C5 /* PlayerEditBoxServiceMac.mm */; };
9FD1E6B61A51361B0009A6C5 /* PlayerFileDialogServiceMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6A81A51361B0009A6C5 /* PlayerFileDialogServiceMac.mm */; };
9FD1E6B71A51361B0009A6C5 /* PlayerMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6AA1A51361B0009A6C5 /* PlayerMac.mm */; };
9FD1E6B81A51361B0009A6C5 /* PlayerMenuServiceMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6AC1A51361B0009A6C5 /* PlayerMenuServiceMac.mm */; };
9FD1E6B91A51361B0009A6C5 /* PlayerMessageBoxServiceMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6AE1A51361B0009A6C5 /* PlayerMessageBoxServiceMac.mm */; };
9FD1E6BA1A51361B0009A6C5 /* PlayerTaskServiceMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = 9FD1E6B01A51361B0009A6C5 /* PlayerTaskServiceMac.mm */; };
9FD1E6BD1A51362E0009A6C5 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9FD1E6BB1A51362E0009A6C5 /* MainMenu.xib */; };
9FFEB9A91A6AB7F70095C43A /* lang in Resources */ = {isa = PBXBuildFile; fileRef = 9FFEB9A01A6AB7F70095C43A /* lang */; };
9FFEB9AC1A6AB7F70095C43A /* RuntimeJsImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9FFEB9A31A6AB7F70095C43A /* RuntimeJsImpl.cpp */; };
9FFEB9AD1A6AB7F70095C43A /* RuntimeJsImpl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9FFEB9A31A6AB7F70095C43A /* RuntimeJsImpl.cpp */; };
9FFEB9C21A6B86360095C43A /* SimpleConfigParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9FFEB9C01A6B86360095C43A /* SimpleConfigParser.cpp */; };
A92275421517C094001B78AA /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275411517C094001B78AA /* QuartzCore.framework */; };
A92275441517C094001B78AA /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275431517C094001B78AA /* OpenGLES.framework */; };
A92275461517C094001B78AA /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275451517C094001B78AA /* OpenAL.framework */; };
@@ -80,12 +63,11 @@
BA4E718719EB6E7900932425 /* MediaPlayer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BA4E718619EB6E7900932425 /* MediaPlayer.framework */; };
C03780EB18BEE0E400FE4F13 /* src in Resources */ = {isa = PBXBuildFile; fileRef = C03780EA18BEE0E400FE4F13 /* src */; };
C03780EC18BEE0E400FE4F13 /* src in Resources */ = {isa = PBXBuildFile; fileRef = C03780EA18BEE0E400FE4F13 /* src */; };
C03C8B4B18A770DD00723415 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = C03C8B4818A770DD00723415 /* main.m */; };
C03C8B4B18A770DD00723415 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C03C8B4818A770DD00723415 /* main.cpp */; };
C05D1C171923467600B808A4 /* config.json in Resources */ = {isa = PBXBuildFile; fileRef = C05D1C161923467600B808A4 /* config.json */; };
C05D1C181923467600B808A4 /* config.json in Resources */ = {isa = PBXBuildFile; fileRef = C05D1C161923467600B808A4 /* config.json */; };
C0799CB918BAE62000E9C828 /* res in Resources */ = {isa = PBXBuildFile; fileRef = C0799CB518BAE62000E9C828 /* res */; };
C0799CBA18BAE62000E9C828 /* res in Resources */ = {isa = PBXBuildFile; fileRef = C0799CB518BAE62000E9C828 /* res */; };
C0C2F37418AA0C66003976DA /* SimulatorApp.mm in Sources */ = {isa = PBXBuildFile; fileRef = C0C2F37318AA0C66003976DA /* SimulatorApp.mm */; };
D454520C156E22BD00887EB5 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = D454520B156E22BD00887EB5 /* libz.dylib */; };
D4545227156E28EF00887EB5 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D4545215156E28EF00887EB5 /* AppDelegate.cpp */; };
D6B061241803AB9F0077942B /* CoreMotion.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6B061231803AB9F0077942B /* CoreMotion.framework */; };
@@ -102,7 +84,6 @@
1A6BF21418C9DB5900FB0E1C /* main.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = main.js; path = ../../../main.js; sourceTree = "<group>"; };
1A82F5FA169AC92500C4B13A /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; };
1A96A4F2174A3432008653A9 /* libcurl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcurl.a; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos2dx/platform/third_party/ios/libraries/libcurl.a"; sourceTree = "<group>"; };
1DBD455C8FDA2F3E10BCC26C /* libsimulator Mac.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libsimulator Mac.a"; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/prebuilt/mac/libsimulator Mac.a"; sourceTree = "<absolute>"; };
294D7D771D0D6667002CE7B7 /* CoreText.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreText.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/CoreText.framework; sourceTree = DEVELOPER_DIR; };
403C4AA98CE6BA7FB917B960 /* libcocos2d iOS.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libcocos2d iOS.a"; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/prebuilt/ios/libcocos2d iOS.a"; sourceTree = "<absolute>"; };
502380DB17EBB88200990C9B /* libcurl.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcurl.dylib; path = usr/lib/libcurl.dylib; sourceTree = SDKROOT; };
@@ -138,33 +119,6 @@
509D4AEA17EBB82600697056 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
87D4C4441AB2187000F68C44 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
9F20C9E11A5BBE85006FB50B /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; };
9FD1E69E1A51361B0009A6C5 /* ConsoleWindow.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = ConsoleWindow.xib; sourceTree = "<group>"; };
9FD1E69F1A51361B0009A6C5 /* ConsoleWindowController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ConsoleWindowController.h; sourceTree = "<group>"; };
9FD1E6A01A51361B0009A6C5 /* ConsoleWindowController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ConsoleWindowController.m; sourceTree = "<group>"; };
9FD1E6A11A51361B0009A6C5 /* DeviceEx-mac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "DeviceEx-mac.mm"; sourceTree = "<group>"; };
9FD1E6A31A51361B0009A6C5 /* OpenUDIDMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OpenUDIDMac.h; sourceTree = "<group>"; };
9FD1E6A41A51361B0009A6C5 /* OpenUDIDMac.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OpenUDIDMac.m; sourceTree = "<group>"; };
9FD1E6A51A51361B0009A6C5 /* PlayerEditBoxServiceMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlayerEditBoxServiceMac.h; sourceTree = "<group>"; };
9FD1E6A61A51361B0009A6C5 /* PlayerEditBoxServiceMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PlayerEditBoxServiceMac.mm; sourceTree = "<group>"; };
9FD1E6A71A51361B0009A6C5 /* PlayerFileDialogServiceMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlayerFileDialogServiceMac.h; sourceTree = "<group>"; };
9FD1E6A81A51361B0009A6C5 /* PlayerFileDialogServiceMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PlayerFileDialogServiceMac.mm; sourceTree = "<group>"; };
9FD1E6A91A51361B0009A6C5 /* PlayerMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlayerMac.h; sourceTree = "<group>"; };
9FD1E6AA1A51361B0009A6C5 /* PlayerMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PlayerMac.mm; sourceTree = "<group>"; };
9FD1E6AB1A51361B0009A6C5 /* PlayerMenuServiceMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlayerMenuServiceMac.h; sourceTree = "<group>"; };
9FD1E6AC1A51361B0009A6C5 /* PlayerMenuServiceMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PlayerMenuServiceMac.mm; sourceTree = "<group>"; };
9FD1E6AD1A51361B0009A6C5 /* PlayerMessageBoxServiceMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlayerMessageBoxServiceMac.h; sourceTree = "<group>"; };
9FD1E6AE1A51361B0009A6C5 /* PlayerMessageBoxServiceMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PlayerMessageBoxServiceMac.mm; sourceTree = "<group>"; };
9FD1E6AF1A51361B0009A6C5 /* PlayerTaskServiceMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlayerTaskServiceMac.h; sourceTree = "<group>"; };
9FD1E6B01A51361B0009A6C5 /* PlayerTaskServiceMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PlayerTaskServiceMac.mm; sourceTree = "<group>"; };
9FD1E6BC1A51362E0009A6C5 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
9FD1E6BE1A5136370009A6C5 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = "zh-Hans"; path = "zh-Hans.lproj/MainMenu.xib"; sourceTree = "<group>"; };
9FFEB99F1A6AB7F70095C43A /* CodeIDESupport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CodeIDESupport.h; sourceTree = "<group>"; };
9FFEB9A01A6AB7F70095C43A /* lang */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = lang; sourceTree = "<group>"; };
9FFEB9A31A6AB7F70095C43A /* RuntimeJsImpl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RuntimeJsImpl.cpp; sourceTree = "<group>"; };
9FFEB9A41A6AB7F70095C43A /* RuntimeJsImpl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RuntimeJsImpl.h; sourceTree = "<group>"; };
9FFEB9A71A6AB7F70095C43A /* js_module_register.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = js_module_register.h; sourceTree = "<group>"; };
9FFEB9C01A6B86360095C43A /* SimpleConfigParser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SimpleConfigParser.cpp; sourceTree = "<group>"; };
9FFEB9C11A6B86360095C43A /* SimpleConfigParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleConfigParser.h; sourceTree = "<group>"; };
A922753D1517C094001B78AA /* HelloJavascript-mobile.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "HelloJavascript-mobile.app"; sourceTree = BUILT_PRODUCTS_DIR; };
A92275411517C094001B78AA /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; };
A92275431517C094001B78AA /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; };
@@ -174,14 +128,11 @@
A922754B1517C094001B78AA /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
A922754D1517C094001B78AA /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
A922754F1517C094001B78AA /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
B369480BACF7CC3BFAF3B77A /* libsimulator iOS.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libsimulator iOS.a"; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/prebuilt/ios/libsimulator iOS.a"; sourceTree = "<absolute>"; };
BA4E718619EB6E7900932425 /* MediaPlayer.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MediaPlayer.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.0.sdk/System/Library/Frameworks/MediaPlayer.framework; sourceTree = DEVELOPER_DIR; };
C03780EA18BEE0E400FE4F13 /* src */ = {isa = PBXFileReference; lastKnownFileType = folder; name = src; path = ../../../src; sourceTree = "<group>"; };
C03C8B4818A770DD00723415 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
C03C8B4818A770DD00723415 /* main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = "<group>"; };
C05D1C161923467600B808A4 /* config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; name = config.json; path = ../../../config.json; sourceTree = "<group>"; };
C0799CB518BAE62000E9C828 /* res */ = {isa = PBXFileReference; lastKnownFileType = folder; name = res; path = ../../../res; sourceTree = "<group>"; };
C0C2F37218AA0C66003976DA /* SimulatorApp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimulatorApp.h; sourceTree = "<group>"; };
C0C2F37318AA0C66003976DA /* SimulatorApp.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = SimulatorApp.mm; sourceTree = "<group>"; };
D454520B156E22BD00887EB5 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; };
D4545215156E28EF00887EB5 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AppDelegate.cpp; sourceTree = "<group>"; };
D4545216156E28EF00887EB5 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
@@ -211,7 +162,6 @@
509D4A9117EBB24E00697056 /* CoreGraphics.framework in Frameworks */,
71594E66B292DCD17FD02A63 /* libcocos2d Mac.a in Frameworks */,
F762461E9EC2A6E8307FCD40 /* libjscocos2d Mac.a in Frameworks */,
471C47CE8C319E15D42CFACA /* libsimulator Mac.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -236,7 +186,6 @@
A92275501517C094001B78AA /* CoreGraphics.framework in Frameworks */,
4EF7467CB50B6A7F2A970566 /* libcocos2d iOS.a in Frameworks */,
3B67481F942374033A420049 /* libjscocos2d iOS.a in Frameworks */,
1BFE40C9B3992EFC7694ECAD /* libsimulator iOS.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -260,7 +209,6 @@
children = (
403C4AA98CE6BA7FB917B960 /* libcocos2d iOS.a */,
DCAA4417880B45A57D3DBA4A /* libjscocos2d iOS.a */,
B369480BACF7CC3BFAF3B77A /* libsimulator iOS.a */,
);
name = "ios-libs";
sourceTree = "<group>";
@@ -288,11 +236,7 @@
509D4ACA17EBB2BE00697056 /* mac */ = {
isa = PBXGroup;
children = (
9FD1E69D1A51361B0009A6C5 /* service */,
C0C2F37218AA0C66003976DA /* SimulatorApp.h */,
C0C2F37318AA0C66003976DA /* SimulatorApp.mm */,
C03C8B4818A770DD00723415 /* main.m */,
9FD1E6BB1A51362E0009A6C5 /* MainMenu.xib */,
C03C8B4818A770DD00723415 /* main.cpp */,
509D4ACB17EBB2BE00697056 /* Icon.icns */,
509D4ACC17EBB2BE00697056 /* Info.plist */,
509D4ACE17EBB2BE00697056 /* Prefix.pch */,
@@ -305,57 +249,10 @@
children = (
07FC49C5830602CCA699BE78 /* libcocos2d Mac.a */,
180D448EA05BC67C8F36F0F3 /* libjscocos2d Mac.a */,
1DBD455C8FDA2F3E10BCC26C /* libsimulator Mac.a */,
);
name = "mac-libs";
sourceTree = "<group>";
};
9FD1E69D1A51361B0009A6C5 /* service */ = {
isa = PBXGroup;
children = (
9FD1E69E1A51361B0009A6C5 /* ConsoleWindow.xib */,
9FD1E69F1A51361B0009A6C5 /* ConsoleWindowController.h */,
9FD1E6A01A51361B0009A6C5 /* ConsoleWindowController.m */,
9FD1E6A11A51361B0009A6C5 /* DeviceEx-mac.mm */,
9FD1E6A21A51361B0009A6C5 /* openudid */,
9FD1E6A51A51361B0009A6C5 /* PlayerEditBoxServiceMac.h */,
9FD1E6A61A51361B0009A6C5 /* PlayerEditBoxServiceMac.mm */,
9FD1E6A71A51361B0009A6C5 /* PlayerFileDialogServiceMac.h */,
9FD1E6A81A51361B0009A6C5 /* PlayerFileDialogServiceMac.mm */,
9FD1E6A91A51361B0009A6C5 /* PlayerMac.h */,
9FD1E6AA1A51361B0009A6C5 /* PlayerMac.mm */,
9FD1E6AB1A51361B0009A6C5 /* PlayerMenuServiceMac.h */,
9FD1E6AC1A51361B0009A6C5 /* PlayerMenuServiceMac.mm */,
9FD1E6AD1A51361B0009A6C5 /* PlayerMessageBoxServiceMac.h */,
9FD1E6AE1A51361B0009A6C5 /* PlayerMessageBoxServiceMac.mm */,
9FD1E6AF1A51361B0009A6C5 /* PlayerTaskServiceMac.h */,
9FD1E6B01A51361B0009A6C5 /* PlayerTaskServiceMac.mm */,
);
path = service;
sourceTree = "<group>";
};
9FD1E6A21A51361B0009A6C5 /* openudid */ = {
isa = PBXGroup;
children = (
9FD1E6A31A51361B0009A6C5 /* OpenUDIDMac.h */,
9FD1E6A41A51361B0009A6C5 /* OpenUDIDMac.m */,
);
path = openudid;
sourceTree = "<group>";
};
9FFEB99E1A6AB7F70095C43A /* ide-support */ = {
isa = PBXGroup;
children = (
9FFEB9C01A6B86360095C43A /* SimpleConfigParser.cpp */,
9FFEB9C11A6B86360095C43A /* SimpleConfigParser.h */,
9FFEB99F1A6AB7F70095C43A /* CodeIDESupport.h */,
9FFEB9A01A6AB7F70095C43A /* lang */,
9FFEB9A31A6AB7F70095C43A /* RuntimeJsImpl.cpp */,
9FFEB9A41A6AB7F70095C43A /* RuntimeJsImpl.h */,
);
path = "ide-support";
sourceTree = "<group>";
};
A92275321517C094001B78AA = {
isa = PBXGroup;
children = (
@@ -437,8 +334,6 @@
D4545214156E28EF00887EB5 /* Classes */ = {
isa = PBXGroup;
children = (
9FFEB99E1A6AB7F70095C43A /* ide-support */,
9FFEB9A71A6AB7F70095C43A /* js_module_register.h */,
D4545215156E28EF00887EB5 /* AppDelegate.cpp */,
D4545216156E28EF00887EB5 /* AppDelegate.h */,
);
@@ -518,14 +413,11 @@
buildActionMask = 2147483647;
files = (
1AC22EDE18CA0E11007112B9 /* project.json in Resources */,
9FD1E6B11A51361B0009A6C5 /* ConsoleWindow.xib in Resources */,
1AD7E0A918C9DBE3004817A6 /* main.js in Resources */,
C05D1C181923467600B808A4 /* config.json in Resources */,
C0799CBA18BAE62000E9C828 /* res in Resources */,
509D4ACF17EBB2BE00697056 /* Icon.icns in Resources */,
9FFEB9A91A6AB7F70095C43A /* lang in Resources */,
C03780EC18BEE0E400FE4F13 /* src in Resources */,
9FD1E6BD1A51362E0009A6C5 /* MainMenu.xib in Resources */,
8EFD4931BFDBAFBB1B85B6CB /* script in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -582,19 +474,8 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
9FD1E6B61A51361B0009A6C5 /* PlayerFileDialogServiceMac.mm in Sources */,
9FD1E6B51A51361B0009A6C5 /* PlayerEditBoxServiceMac.mm in Sources */,
9FD1E6B21A51361B0009A6C5 /* ConsoleWindowController.m in Sources */,
9FD1E6B71A51361B0009A6C5 /* PlayerMac.mm in Sources */,
509D4A8117EBB24E00697056 /* AppDelegate.cpp in Sources */,
9FD1E6BA1A51361B0009A6C5 /* PlayerTaskServiceMac.mm in Sources */,
C0C2F37418AA0C66003976DA /* SimulatorApp.mm in Sources */,
9FD1E6B41A51361B0009A6C5 /* OpenUDIDMac.m in Sources */,
9FD1E6B91A51361B0009A6C5 /* PlayerMessageBoxServiceMac.mm in Sources */,
9FD1E6B31A51361B0009A6C5 /* DeviceEx-mac.mm in Sources */,
C03C8B4B18A770DD00723415 /* main.m in Sources */,
9FD1E6B81A51361B0009A6C5 /* PlayerMenuServiceMac.mm in Sources */,
9FFEB9AD1A6AB7F70095C43A /* RuntimeJsImpl.cpp in Sources */,
C03C8B4B18A770DD00723415 /* main.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -603,28 +484,14 @@
buildActionMask = 2147483647;
files = (
509D4AC917EBB2AB00697056 /* RootViewController.mm in Sources */,
9FFEB9AC1A6AB7F70095C43A /* RuntimeJsImpl.cpp in Sources */,
D4545227156E28EF00887EB5 /* AppDelegate.cpp in Sources */,
509D4AC817EBB2AB00697056 /* main.m in Sources */,
9FFEB9C21A6B86360095C43A /* SimpleConfigParser.cpp in Sources */,
509D4ABC17EBB2AB00697056 /* AppController.mm in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
9FD1E6BB1A51362E0009A6C5 /* MainMenu.xib */ = {
isa = PBXVariantGroup;
children = (
9FD1E6BC1A51362E0009A6C5 /* Base */,
9FD1E6BE1A5136370009A6C5 /* zh-Hans */,
);
name = MainMenu.xib;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
509D4AA817EBB24E00697056 /* Debug */ = {
isa = XCBuildConfiguration;
@@ -762,6 +629,7 @@
LIBRARY_SEARCH_PATHS = " /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/prebuilt/ios";
OTHER_LDFLAGS = "";
SDKROOT = iphoneos;
STRIP_PNG_TEXT = NO;
TARGETED_DEVICE_FAMILY = "1,2";
USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/ios /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/auto /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/manual /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources";
VALID_ARCHS = "arm64 armv7";
@@ -793,6 +661,7 @@
LIBRARY_SEARCH_PATHS = " /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/prebuilt/ios";
OTHER_LDFLAGS = "";
SDKROOT = iphoneos;
STRIP_PNG_TEXT = NO;
TARGETED_DEVICE_FAMILY = "1,2";
USER_HEADER_SEARCH_PATHS = "$(inherited) /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos/platform/ios /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/auto /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/plugin/jsbindings/manual /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/include/spidermonkey /Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/sources";
VALID_ARCHS = "arm64 armv7";
@@ -1,19 +1,19 @@
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -25,7 +25,7 @@
@class RootViewController;
@interface AppController : NSObject <UIApplicationDelegate>
@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate,UIApplicationDelegate>
{
UIWindow *window;
RootViewController *viewController;
@@ -1,19 +1,19 @@
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -41,30 +41,26 @@ static AppDelegate s_sharedApplication;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
cocos2d::Application *app = cocos2d::Application::getInstance();
app->initGLContextAttrs();
cocos2d::GLViewImpl::convertAttrs();
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]
pixelFormat: (NSString*)cocos2d::GLViewImpl::_pixelFormat
depthFormat: cocos2d::GLViewImpl::_depthFormat
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0 ];
pixelFormat: kEAGLColorFormatRGBA8
depthFormat: GL_DEPTH24_STENCIL8_OES
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0 ];
[eaglView setMultipleTouchEnabled:YES];
// Use RootViewController manage CCEAGLView
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
viewController.view = eaglView;
// Set RootViewController to window
if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
@@ -78,14 +74,14 @@ static AppDelegate s_sharedApplication;
}
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden: YES];
// IMPORTANT: Setting the GLView should be done after creating the RootViewController
cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView);
cocos2d::Director::getInstance()->setOpenGLView(glview);
app->run();
cocos2d::Application::getInstance()->run();
return YES;
}
@@ -135,7 +131,7 @@ static AppDelegate s_sharedApplication;
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
cocos2d::Director::getInstance()->purgeCachedData();
cocos2d::Director::getInstance()->purgeCachedData();
}
@@ -1,201 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="6254" systemVersion="14B25" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
<dependencies>
<deployment version="1080" identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="6254"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="AppController">
<connections>
<outlet property="delegate" destination="536" id="537"/>
<outlet property="menu" destination="29" id="650"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<menu title="AMainMenu" systemMenu="main" id="29">
<items>
<menuItem title="Simulator" id="56">
<menu key="submenu" title="Simulator" systemMenu="apple" id="57">
<items>
<menuItem title="About simulator" id="58">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-2" id="142"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="236">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Preferences…" keyEquivalent="," id="129"/>
<menuItem isSeparatorItem="YES" id="143">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Services" id="131">
<menu key="submenu" title="Services" systemMenu="services" id="130"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="144">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Hide simulator" keyEquivalent="h" id="134">
<connections>
<action selector="hide:" target="-1" id="367"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="145">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-1" id="368"/>
</connections>
</menuItem>
<menuItem title="Show All" id="150">
<connections>
<action selector="unhideAllApplications:" target="-1" id="370"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="149">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Quit simulator" keyEquivalent="q" id="136">
<connections>
<action selector="onFileClose:" target="-1" id="UyZ-bV-2zL"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="Sqe-GR-erP">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="k0V-hR-upN">
<items>
<menuItem title="Undo" keyEquivalent="z" id="Ueo-Yj-fzm">
<connections>
<action selector="undo:" target="-1" id="Ex2-6U-hZI"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="x6z-iQ-VK2">
<connections>
<action selector="redo:" target="-1" id="KEx-Aj-tYn"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="COi-E7-7M4"/>
<menuItem title="Cut" keyEquivalent="x" id="NAk-12-pg4">
<connections>
<action selector="cut:" target="-1" id="Owu-Ie-Kfg"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="XOY-ya-lNt">
<connections>
<action selector="copy:" target="-1" id="aIB-pV-N2w"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="ul0-51-Ibd">
<connections>
<action selector="paste:" target="-1" id="7rk-Tb-7hI"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="Zvy-7g-x4q">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="-1" id="oM4-kj-hTQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="Xyz-QC-wlG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="-1" id="idJ-aN-6bB"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="4fT-JL-N6e">
<connections>
<action selector="selectAll:" target="-1" id="pAH-rW-PaD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="osB-R6-2jE"/>
<menuItem title="Find" id="bms-8x-7Yb">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="AXr-4L-lcV">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="GS8-y9-yQY">
<connections>
<action selector="performFindPanelAction:" target="-1" id="jVT-dG-Frl"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="RJc-P7-Ibq">
<connections>
<action selector="performFindPanelAction:" target="-1" id="yLp-2a-Nuk"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="f5k-Su-hK0">
<connections>
<action selector="performFindPanelAction:" target="-1" id="uoF-9Z-ef7"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="9Zj-Be-aBN">
<connections>
<action selector="performFindPanelAction:" target="-1" id="8hs-AK-0U8"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="4tD-ef-pd8">
<connections>
<action selector="centerSelectionInVisibleArea:" target="-1" id="8xc-J0-7iQ"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="83"/>
<menuItem title="Player" id="633">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem title="Screen" id="295"/>
<menuItem title="Window" id="19">
<menu key="submenu" title="Window" systemMenu="window" id="XuB-dT-g0h">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="YrK-j5-jxq">
<connections>
<action selector="performMiniaturize:" target="-1" id="3wr-0O-cTq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="0NY-jh-tsl">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Bring All to Front" id="opb-EX-EXV">
<connections>
<action selector="arrangeInFront:" target="-1" id="oT1-07-BON"/>
</connections>
</menuItem>
<menuItem title="Always On Top" keyEquivalent="a" id="nXh-Uq-d6d">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="onWindowAlwaysOnTop:" target="-1" id="IM6-Km-MGj"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="490">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="UaO-03-xh1">
<items>
<menuItem title="simulator Help" keyEquivalent="?" id="StN-Og-Ms8">
<connections>
<action selector="showHelp:" target="-1" id="l0h-I0-XAk"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<customObject id="420" customClass="NSFontManager"/>
<customObject id="536" customClass="AppController">
<connections>
<outlet property="menu" destination="29" id="550"/>
</connections>
</customObject>
</objects>
</document>
@@ -1,59 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <string>
#import <Cocoa/Cocoa.h>
#import "ConsoleWindowController.h"
#include "ProjectConfig/ProjectConfig.h"
#include "ProjectConfig/SimulatorConfig.h"
#include "AppDelegate.h"
@interface AppController : NSObject <NSApplicationDelegate, NSWindowDelegate, NSFileManagerDelegate>
{
NSWindow *_window;
NSMenu *menu;
AppDelegate *_app;
ProjectConfig _project;
int _debugLogFile;
std::string _entryPath;
//log file
ConsoleWindowController *_consoleController;
NSFileHandle *_fileHandle;
//console pipe
NSPipe *_pipe;
NSFileHandle *_pipeReadHandle;
}
@property (nonatomic, assign) IBOutlet NSMenu* menu;
-(BOOL)application:(NSApplication*)app openFile:(NSString*)path;
-(IBAction)onFileClose:(id)sender;
-(IBAction)onWindowAlwaysOnTop:(id)sender;
@end
@@ -1,735 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <string>
#include <vector>
#import "SimulatorApp.h"
#include "AppDelegate.h"
#include "glfw3.h"
#include "glfw3native.h"
#include "runtime/Runtime.h"
#include "runtime/ConfigParser.h"
#include "cocos2d.h"
#include "CodeIDESupport.h"
#include "platform/mac/PlayerMac.h"
#include "AppEvent.h"
#include "AppLang.h"
#if (GLFW_VERSION_MAJOR >= 3) && (GLFW_VERSION_MINOR >= 1)
#define PLAYER_SUPPORT_DROP 1
#else
#define PLAYER_SUPPORT_DROP 0
#endif
using namespace std;
using namespace cocos2d;
static id SIMULATOR = nullptr;
@implementation AppController
@synthesize menu;
std::string getCurAppPath(void)
{
return [[[NSBundle mainBundle] bundlePath] UTF8String];
}
std::string getCurAppName(void)
{
string appName = [[[NSProcessInfo processInfo] processName] UTF8String];
int found = appName.find(" ");
if (found!=std::string::npos)
appName = appName.substr(0,found);
return appName;
}
#if (PLAYER_SUPPORT_DROP > 0)
static void glfwDropFunc(GLFWwindow *window, int count, const char **files)
{
AppEvent forwardEvent(kAppEventDropName, APP_EVENT_DROP);
std::string firstFile(files[0]);
forwardEvent.setDataString(firstFile);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&forwardEvent);
}
#endif
-(void) dealloc
{
Director::getInstance()->end();
player::PlayerProtocol::getInstance()->purgeInstance();
[super dealloc];
}
#pragma mark -
#pragma delegates
-(BOOL)application:(NSApplication*)app openFile:(NSString*)path
{
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isDirectory = NO;
if (![fm fileExistsAtPath:path isDirectory:&isDirectory])
{
return NO;
}
if (isDirectory)
{
// check src folder
if ([fm fileExistsAtPath:[path stringByAppendingString:@"/src/main.lua"]])
{
_project.setProjectDir([path cStringUsingEncoding:NSUTF8StringEncoding]);
_entryPath = "$(PROJDIR)/src/main.lua";
}
else if ([fm fileExistsAtPath:[path stringByAppendingString:@"/src/main.js"]])
{
_project.setProjectDir([path cStringUsingEncoding:NSUTF8StringEncoding]);
_entryPath = "$(PROJDIR)/src/main.js";
}
}
else
{
_project.setProjectDir([path cStringUsingEncoding:NSUTF8StringEncoding]);
_entryPath = [path cStringUsingEncoding:NSUTF8StringEncoding];
}
return YES;
}
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
SIMULATOR = self;
player::PlayerMac::create();
_debugLogFile = 0;
[self parseCocosProjectConfig:&_project];
[self updateProjectFromCommandLineArgs:&_project];
if (_entryPath.length())
{
_project.setScriptFile(_entryPath);
}
[self createWindowAndGLView];
[self startup];
}
#pragma mark -
#pragma mark functions
- (BOOL) windowShouldClose:(id)sender
{
return YES;
}
- (void) windowWillClose:(NSNotification *)notification
{
[[NSRunningApplication currentApplication] terminate];
}
- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication
{
return YES;
}
- (NSMutableArray*) makeCommandLineArgsFromProjectConfig
{
return [self makeCommandLineArgsFromProjectConfig:kProjectConfigAll];
}
- (NSMutableArray*) makeCommandLineArgsFromProjectConfig:(unsigned int)mask
{
_project.setWindowOffset(Vec2(_window.frame.origin.x, _window.frame.origin.y));
vector<string> args = _project.makeCommandLineVector();
NSMutableArray *commandArray = [NSMutableArray arrayWithCapacity:args.size()];
for (auto &path : args)
{
[commandArray addObject:[NSString stringWithUTF8String:path.c_str()]];
}
return commandArray;
}
- (void) parseCocosProjectConfig:(ProjectConfig*)config
{
// get project directory
ProjectConfig tmpConfig;
NSArray *nsargs = [[NSProcessInfo processInfo] arguments];
long n = [nsargs count];
if (n >= 2)
{
vector<string> args;
for (int i = 0; i < [nsargs count]; ++i)
{
string arg = [[nsargs objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding];
if (arg.length()) args.push_back(arg);
}
if (args.size() && args.at(1).at(0) == '/')
{
// FIXME:
// for Code IDE before RC2
tmpConfig.setProjectDir(args.at(1));
}
tmpConfig.parseCommandLine(args);
}
// set project directory as search root path
string solutionDir = tmpConfig.getProjectDir();
string spath = solutionDir;
if (!solutionDir.empty())
{
for (int i = 0; i < solutionDir.size(); ++i)
{
if (solutionDir[i] == '\\')
{
solutionDir[i] = '/';
}
}
spath = solutionDir;
if (spath[spath.length() - 1] == '/') {
spath = spath.substr(0, spath.length() - 1);
}
string strExtention = FileUtils::getInstance()->getFileExtension(spath);
int pos = -1;
if(strExtention.compare(".csd") == 0)
{
pos = spath.rfind('/');
if(pos > 0)
spath = spath.substr(0, pos);
}
pos = spath.rfind('/');
if(pos > 0)
spath = spath.substr(0, pos+1);
FileUtils::getInstance()->addSearchPath(spath);
FileUtils::getInstance()->setDefaultResourceRootPath(solutionDir);
FileUtils::getInstance()->addSearchPath(solutionDir);
FileUtils::getInstance()->addSearchPath(tmpConfig.getProjectDir());
}
else
{
FileUtils::getInstance()->setDefaultResourceRootPath(tmpConfig.getProjectDir());
}
// parse config.json
auto parser = ConfigParser::getInstance();
auto configPath = spath.append(CONFIG_FILE);
if(!FileUtils::getInstance()->isFileExist(configPath))
configPath = solutionDir.append(CONFIG_FILE);
parser->readConfig(configPath);
// set information
config->setConsolePort(parser->getConsolePort());
config->setFileUploadPort(parser->getUploadPort());
config->setFrameSize(parser->getInitViewSize());
if (parser->isLanscape())
{
config->changeFrameOrientationToLandscape();
}
else
{
config->changeFrameOrientationToPortait();
}
config->setScriptFile(parser->getEntryFile());
}
- (void) updateProjectFromCommandLineArgs:(ProjectConfig*)config
{
NSArray *nsargs = [[NSProcessInfo processInfo] arguments];
long n = [nsargs count];
if (n >= 2)
{
vector<string> args;
for (int i = 0; i < [nsargs count]; ++i)
{
string arg = [[nsargs objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding];
if (arg.length()) args.push_back(arg);
}
if (args.size() && args.at(1).at(0) == '/')
{
// for Code IDE before RC2
config->setProjectDir(args.at(1));
config->setDebuggerType(kCCRuntimeDebuggerCodeIDE);
}
config->parseCommandLine(args);
}
}
- (bool) launch:(NSArray*)args
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSMutableDictionary *configuration = [NSMutableDictionary dictionaryWithObject:args forKey:NSWorkspaceLaunchConfigurationArguments];
NSError *error = [[[NSError alloc] init] autorelease];
[[NSWorkspace sharedWorkspace] launchApplicationAtURL:url
options:NSWorkspaceLaunchNewInstance
configuration:configuration
error:&error];
if (error.code != 0)
{
NSLog(@"Failed to launch app: %@", [error localizedDescription]);
}
return (error.code==0);
}
- (void) relaunch:(NSArray*)args
{
if ([self launch:args])
{
[[NSApplication sharedApplication] terminate:self];
}
else
{
NSLog(@"RELAUNCH: %@", args);
}
}
- (void) relaunch
{
[self relaunch:[self makeCommandLineArgsFromProjectConfig]];
}
- (float) titleBarHeight
{
NSRect frame = NSMakeRect (0, 0, 100, 100);
NSRect contentRect;
contentRect = [NSWindow contentRectForFrameRect: frame
styleMask: NSTitledWindowMask];
return (frame.size.height - contentRect.size.height);
}
- (void) createWindowAndGLView
{
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
// create console window **MUST** before create opengl view
#if (CC_CODE_IDE_DEBUG_SUPPORT == 1)
if (_project.isShowConsole())
{
[self openConsoleWindow];
CCLOG("%s\n",Configuration::getInstance()->getInfo().c_str());
}
#endif
float frameScale = _project.getFrameScale();
// get frame size
cocos2d::Size frameSize = _project.getFrameSize();
ConfigParser::getInstance()->setInitViewSize(frameSize);
// check screen workarea size
NSRect workarea = [NSScreen mainScreen].visibleFrame;
float workareaWidth = workarea.size.width;
float workareaHeight = workarea.size.height - [self titleBarHeight];
CCLOG("WORKAREA WIDTH %0.2f, HEIGHT %0.2f", workareaWidth, workareaHeight);
while (true && frameScale > 0.25f)
{
if (frameSize.width * frameScale > workareaWidth || frameSize.height * frameScale > workareaHeight)
{
frameScale = frameScale - 0.25f;
}
else
{
break;
}
}
if (frameScale < 0.25f) frameScale = 0.25f;
_project.setFrameScale(frameScale);
CCLOG("FRAME SCALE = %0.2f", frameScale);
// check window offset
Vec2 pos = _project.getWindowOffset();
if (pos.x < 0) pos.x = 0;
if (pos.y < 0) pos.y = 0;
// create opengl view
const cocos2d::Rect frameRect = cocos2d::Rect(0, 0, frameSize.width, frameSize.height);
std::stringstream title;
title << "Cocos Simulator (" << _project.getFrameScale() * 100 << "%)";
GLViewImpl *eglView = GLViewImpl::createWithRect(title.str(), frameRect, frameScale);
auto director = Director::getInstance();
director->setOpenGLView(eglView);
_window = eglView->getCocoaWindow();
[[NSApplication sharedApplication] setDelegate: self];
[_window center];
[self setZoom:_project.getFrameScale()];
if (pos.x != 0 && pos.y != 0)
{
[_window setFrameOrigin:NSMakePoint(pos.x, pos.y)];
}
#if (PLAYER_SUPPORT_DROP > 0)
glfwSetDropCallback(eglView->getWindow(), glfwDropFunc);
#endif
}
- (void) adjustEditMenuIndex
{
NSApplication *thisApp = [NSApplication sharedApplication];
NSMenu *mainMenu = [thisApp mainMenu];
NSMenuItem *editMenuItem = [mainMenu itemWithTitle:@"Edit"];
if (editMenuItem)
{
NSUInteger index = 2;
if (index > [mainMenu itemArray].count)
index = [mainMenu itemArray].count;
[[editMenuItem menu] removeItem:editMenuItem];
[mainMenu insertItem:editMenuItem atIndex:index];
}
}
- (void) startup
{
FileUtils::getInstance()->setPopupNotify(false);
_project.dump();
const string projectDir = _project.getProjectDir();
if (projectDir.length())
{
FileUtils::getInstance()->setDefaultResourceRootPath(projectDir);
if (_project.isWriteDebugLogToFile())
{
[self writeDebugLogToFile:_project.getDebugLogFilePath()];
}
}
const string writablePath = _project.getWritableRealPath();
if (writablePath.length())
{
FileUtils::getInstance()->setWritablePath(writablePath.c_str());
}
// path for looking Lang file, Studio Default images
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
FileUtils::getInstance()->addSearchPath(resourcePath.UTF8String);
// app
_app = new AppDelegate();
[self setupUI];
[self adjustEditMenuIndex];
RuntimeEngine::getInstance()->setProjectConfig(_project);
Application::getInstance()->run();
CC_SAFE_DELETE(_app);
// After run, application needs to be terminated immediately.
[NSApp terminate: self];
}
- (void) setupUI
{
auto menuBar = player::PlayerProtocol::getInstance()->getMenuService();
// VIEW
menuBar->addItem("VIEW_MENU", tr("View"));
SimulatorConfig *config = SimulatorConfig::getInstance();
int current = config->checkScreenSize(_project.getFrameSize());
for (int i = 0; i < config->getScreenSizeCount(); i++)
{
SimulatorScreenSize size = config->getScreenSize(i);
std::stringstream menuId;
menuId << "VIEWSIZE_ITEM_MENU_" << i;
auto menuItem = menuBar->addItem(menuId.str(), size.title.c_str(), "VIEW_MENU");
if (i == current)
{
menuItem->setChecked(true);
}
}
menuBar->addItem("DIRECTION_MENU_SEP", "-", "VIEW_MENU");
menuBar->addItem("DIRECTION_PORTRAIT_MENU", tr("Portrait"), "VIEW_MENU")
->setChecked(_project.isPortraitFrame());
menuBar->addItem("DIRECTION_LANDSCAPE_MENU", tr("Landscape"), "VIEW_MENU")
->setChecked(_project.isLandscapeFrame());
menuBar->addItem("VIEW_SCALE_MENU_SEP", "-", "VIEW_MENU");
std::vector<player::PlayerMenuItem*> scaleMenuVector;
auto scale100Menu = menuBar->addItem("VIEW_SCALE_MENU_100", tr("Zoom Out").append(" (100%)"), "VIEW_MENU");
scale100Menu->setShortcut("super+0");
auto scale75Menu = menuBar->addItem("VIEW_SCALE_MENU_75", tr("Zoom Out").append(" (75%)"), "VIEW_MENU");
scale75Menu->setShortcut("super+7");
auto scale50Menu = menuBar->addItem("VIEW_SCALE_MENU_50", tr("Zoom Out").append(" (50%)"), "VIEW_MENU");
scale50Menu->setShortcut("super+6");
auto scale25Menu = menuBar->addItem("VIEW_SCALE_MENU_25", tr("Zoom Out").append(" (25%)"), "VIEW_MENU");
scale25Menu->setShortcut("super+5");
int frameScale = int(_project.getFrameScale() * 100);
if (frameScale == 100)
{
scale100Menu->setChecked(true);
}
else if (frameScale == 75)
{
scale75Menu->setChecked(true);
}
else if (frameScale == 50)
{
scale50Menu->setChecked(true);
}
else if (frameScale == 25)
{
scale25Menu->setChecked(true);
}
else
{
scale100Menu->setChecked(true);
}
scaleMenuVector.push_back(scale100Menu);
scaleMenuVector.push_back(scale75Menu);
scaleMenuVector.push_back(scale50Menu);
scaleMenuVector.push_back(scale25Menu);
menuBar->addItem("REFRESH_MENU_SEP", "-", "VIEW_MENU");
menuBar->addItem("REFRESH_MENU", tr("Refresh"), "VIEW_MENU")->setShortcut("super+r");
ProjectConfig &project = _project;
auto dispatcher = Director::getInstance()->getEventDispatcher();
auto window = _window;
dispatcher->addEventListenerWithFixedPriority(EventListenerCustom::create(kAppEventName, [&project, scaleMenuVector, window](EventCustom* event){
auto menuEvent = dynamic_cast<AppEvent*>(event);
if (menuEvent)
{
rapidjson::Document dArgParse;
dArgParse.Parse<0>(menuEvent->getDataString().c_str());
if (dArgParse.HasMember("name"))
{
string strcmd = dArgParse["name"].GetString();
if (strcmd == "menuClicked")
{
player::PlayerMenuItem *menuItem = static_cast<player::PlayerMenuItem*>(menuEvent->getUserData());
if (menuItem)
{
if (menuItem->isChecked())
{
return ;
}
string data = dArgParse["data"].GetString();
if ((data == "CLOSE_MENU") || (data == "EXIT_MENU"))
{
Director::getInstance()->end();
}
else if (data == "REFRESH_MENU")
{
[SIMULATOR relaunch];
}
else if (data.find("VIEW_SCALE_MENU_") == 0) // begin with VIEW_SCALE_MENU_
{
string tmp = data.erase(0, strlen("VIEW_SCALE_MENU_"));
float scale = atof(tmp.c_str()) / 100.0f;
[SIMULATOR setZoom:scale];
// update scale menu state
for (auto &it : scaleMenuVector)
{
it->setChecked(false);
}
menuItem->setChecked(true);
}
else if (data.find("VIEWSIZE_ITEM_MENU_") == 0) // begin with VIEWSIZE_ITEM_MENU_
{
string tmp = data.erase(0, strlen("VIEWSIZE_ITEM_MENU_"));
int index = atoi(tmp.c_str());
SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(index);
if (project.isLandscapeFrame())
{
std::swap(size.width, size.height);
}
project.setFrameSize(cocos2d::Size(size.width, size.height));
[SIMULATOR relaunch];
}
else if (data == "DIRECTION_PORTRAIT_MENU")
{
project.changeFrameOrientationToPortait();
[SIMULATOR relaunch];
}
else if (data == "DIRECTION_LANDSCAPE_MENU")
{
project.changeFrameOrientationToLandscape();
[SIMULATOR relaunch];
}
}
}
}
}
}), 1);
// drop
AppDelegate *app = _app;
auto listener = EventListenerCustom::create(kAppEventDropName, [&project, app](EventCustom* event)
{
AppEvent *dropEvent = dynamic_cast<AppEvent*>(event);
if (dropEvent)
{
string dirPath = dropEvent->getDataString() + "/";
string configFilePath = dirPath + CONFIG_FILE;
if (FileUtils::getInstance()->isDirectoryExist(dirPath) &&
FileUtils::getInstance()->isFileExist(configFilePath))
{
// parse config.json
ConfigParser::getInstance()->readConfig(configFilePath);
project.setProjectDir(dirPath);
project.setScriptFile(ConfigParser::getInstance()->getEntryFile());
project.setWritablePath(dirPath);
RuntimeEngine::getInstance()->setProjectConfig(project);
// app->setProjectConfig(project);
// app->reopenProject();
}
}
});
dispatcher->addEventListenerWithFixedPriority(listener, 1);
}
- (void) openConsoleWindow
{
if (!_consoleController)
{
_consoleController = [[ConsoleWindowController alloc] initWithWindowNibName:@"ConsoleWindow"];
}
[_consoleController.window orderFrontRegardless];
//set console pipe
_pipe = [NSPipe pipe] ;
_pipeReadHandle = [_pipe fileHandleForReading] ;
int outfd = [[_pipe fileHandleForWriting] fileDescriptor];
if (dup2(outfd, fileno(stderr)) != fileno(stderr) || dup2(outfd, fileno(stdout)) != fileno(stdout))
{
perror("Unable to redirect output");
// [self showAlert:@"Unable to redirect output to console!" withTitle:@"player error"];
}
else
{
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handleNotification:) name: NSFileHandleReadCompletionNotification object: _pipeReadHandle] ;
[_pipeReadHandle readInBackgroundAndNotify] ;
}
}
- (bool) writeDebugLogToFile:(const string)path
{
if (_debugLogFile) return true;
//log to file
if(_fileHandle) return true;
NSString *fPath = [NSString stringWithCString:path.c_str() encoding:[NSString defaultCStringEncoding]];
[[NSFileManager defaultManager] createFileAtPath:fPath contents:nil attributes:nil] ;
_fileHandle = [NSFileHandle fileHandleForWritingAtPath:fPath];
[_fileHandle retain];
return true;
}
- (void)handleNotification:(NSNotification *)note
{
//NSLog(@"Received notification: %@", note);
[_pipeReadHandle readInBackgroundAndNotify] ;
NSData *data = [[note userInfo] objectForKey:NSFileHandleNotificationDataItem];
NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
if (str)
{
//show log to console
[_consoleController trace:str];
if(_fileHandle!=nil)
{
[_fileHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
}
}
}
- (void) setZoom:(float)scale
{
Director::getInstance()->getOpenGLView()->setFrameZoomFactor(scale);
_project.setFrameScale(scale);
std::stringstream title;
title << "Cocos " << tr("Simulator") << " (" << _project.getFrameScale() * 100 << "%)";
[_window setTitle:[NSString stringWithUTF8String:title.str().c_str()]];
}
- (BOOL) applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag
{
return NO;
}
#pragma mark -
-(IBAction)onFileClose:(id)sender
{
CC_SAFE_DELETE(_app);
[[NSApplication sharedApplication] terminate:self];
}
-(IBAction)onWindowAlwaysOnTop:(id)sender
{
NSInteger state = [sender state];
if (state == NSOffState)
{
[_window setLevel:NSFloatingWindowLevel];
[sender setState:NSOnState];
}
else
{
[_window setLevel:NSNormalWindowLevel];
[sender setState:NSOffState];
}
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
CC_SAFE_DELETE(_app);
[[NSApplication sharedApplication] terminate:self];
}
@end
@@ -1,7 +0,0 @@
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
@@ -1,110 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="6254" systemVersion="14B25" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="6254"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="ConsoleWindowController">
<connections>
<outlet property="checkScroll" destination="50" id="70"/>
<outlet property="textView" destination="6" id="20"/>
<outlet property="topCheckBox" destination="60" id="69"/>
<outlet property="window" destination="1" id="3"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<window title="Console" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" oneShot="NO" animationBehavior="default" id="1">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="40" y="40" width="854" height="400"/>
<rect key="screenRect" x="0.0" y="0.0" width="2560" height="1417"/>
<view key="contentView" id="2">
<rect key="frame" x="0.0" y="0.0" width="854" height="400"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<scrollView horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="5">
<rect key="frame" x="-1" y="-1" width="854" height="371"/>
<clipView key="contentView" id="ddW-qo-Qe9">
<rect key="frame" x="1" y="1" width="837" height="369"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textView editable="NO" importsGraphics="NO" richText="NO" findStyle="panel" verticallyResizable="YES" allowsNonContiguousLayout="YES" id="6">
<rect key="frame" x="0.0" y="0.0" width="837" height="369"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<size key="minSize" width="837" height="369"/>
<size key="maxSize" width="888" height="10000000"/>
<color key="insertionPointColor" white="0.0" alpha="1" colorSpace="calibratedWhite"/>
<size key="minSize" width="837" height="369"/>
<size key="maxSize" width="888" height="10000000"/>
</textView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</clipView>
<scroller key="horizontalScroller" hidden="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="7">
<rect key="frame" x="-100" y="-100" width="87" height="18"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
<scroller key="verticalScroller" verticalHuggingPriority="750" doubleValue="1" horizontal="NO" id="8">
<rect key="frame" x="838" y="1" width="15" height="369"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
</scrollView>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="46">
<rect key="frame" x="-1" y="367" width="73" height="32"/>
<buttonCell key="cell" type="push" title="Clear" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="47">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="onClear:" target="-2" id="57"/>
</connections>
</button>
<button translatesAutoresizingMaskIntoConstraints="NO" id="50">
<rect key="frame" x="731" y="376" width="113" height="18"/>
<constraints>
<constraint firstAttribute="width" constant="109" id="56"/>
</constraints>
<buttonCell key="cell" type="check" title="scroll bottom" bezelStyle="regularSquare" imagePosition="left" state="on" inset="2" id="51">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="onScrollChange:" target="-2" id="59"/>
</connections>
</button>
<button translatesAutoresizingMaskIntoConstraints="NO" id="60">
<rect key="frame" x="632" y="375" width="95" height="18"/>
<constraints>
<constraint firstAttribute="width" constant="91" id="64"/>
</constraints>
<buttonCell key="cell" type="check" title="always top" bezelStyle="regularSquare" imagePosition="left" inset="2" id="61">
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="onTopChange:" target="-2" id="67"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstAttribute="trailing" secondItem="5" secondAttribute="trailing" constant="1" id="41"/>
<constraint firstAttribute="bottom" secondItem="5" secondAttribute="bottom" constant="-1" id="42"/>
<constraint firstItem="5" firstAttribute="top" secondItem="2" secondAttribute="top" constant="30" id="43"/>
<constraint firstItem="5" firstAttribute="leading" secondItem="2" secondAttribute="leading" constant="-1" id="44"/>
<constraint firstItem="46" firstAttribute="leading" secondItem="2" secondAttribute="leading" constant="5" id="49"/>
<constraint firstItem="50" firstAttribute="baseline" secondItem="46" secondAttribute="baseline" id="52"/>
<constraint firstAttribute="trailing" secondItem="50" secondAttribute="trailing" constant="12" id="53"/>
<constraint firstItem="5" firstAttribute="top" secondItem="50" secondAttribute="bottom" constant="8" symbolic="YES" id="54"/>
<constraint firstItem="60" firstAttribute="centerY" secondItem="46" secondAttribute="centerY" id="63"/>
<constraint firstItem="50" firstAttribute="leading" secondItem="60" secondAttribute="trailing" constant="8" symbolic="YES" id="66"/>
</constraints>
</view>
<connections>
<outlet property="delegate" destination="-2" id="4"/>
</connections>
</window>
</objects>
</document>
@@ -1,23 +0,0 @@
#import <Cocoa/Cocoa.h>
@interface ConsoleWindowController : NSWindowController
{
NSTextView *textView;
IBOutlet NSButton *checkScroll;
IBOutlet NSButton *topCheckBox;
NSMutableArray *linesCount;
NSUInteger traceCount;
}
@property (assign) IBOutlet NSTextView *textView;
- (void) trace:(NSString*)msg;
- (IBAction)onClear:(id)sender;
- (IBAction)onScrollChange:(id)sender;
- (IBAction)onTopChange:(id)sender;
@end
@@ -1,100 +0,0 @@
#import "ConsoleWindowController.h"
@interface ConsoleWindowController ()
@end
#define SKIP_LINES_COUNT 3
#define MAX_LINE_LEN 4096
#define MAX_LINES_COUNT 200
@implementation ConsoleWindowController
@synthesize textView;
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self)
{
// Initialization code here.
linesCount = [[NSMutableArray arrayWithCapacity:MAX_LINES_COUNT + 1] retain];
}
return self;
}
- (void)dealloc
{
[linesCount release];
[super dealloc];
}
- (void)windowDidLoad
{
[super windowDidLoad];
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
- (void) trace:(NSString*)msg
{
if (traceCount >= SKIP_LINES_COUNT && [msg length] > MAX_LINE_LEN)
{
msg = [NSString stringWithFormat:@"%@ ...", [msg substringToIndex:MAX_LINE_LEN - 4]];
}
traceCount++;
NSFont *font = [NSFont fontWithName:@"Monaco" size:12.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSAttributedString *string = [[NSAttributedString alloc] initWithString:msg attributes:attrsDictionary];
NSNumber *len = [NSNumber numberWithUnsignedInteger:[string length]];
[linesCount addObject:len];
NSTextStorage *storage = [textView textStorage];
[storage beginEditing];
[storage appendAttributedString:string];
if ([linesCount count] >= MAX_LINES_COUNT)
{
len = [linesCount objectAtIndex:0];
[storage deleteCharactersInRange:NSMakeRange(0, [len unsignedIntegerValue])];
[linesCount removeObjectAtIndex:0];
}
[storage endEditing];
[self changeScroll];
}
- (void) changeScroll
{
BOOL scroll = [checkScroll state] == NSOnState;
if(scroll)
{
[self.textView scrollRangeToVisible: NSMakeRange(self.textView.string.length, 0)];
}
}
- (IBAction)onClear:(id)sender
{
NSTextStorage *storage = [textView textStorage];
[storage setAttributedString:[[[NSAttributedString alloc] initWithString:@""] autorelease]];
}
- (IBAction)onScrollChange:(id)sender
{
[self changeScroll];
}
- (IBAction)onTopChange:(id)sender
{
BOOL isTop = [topCheckBox state] == NSOnState;
if(isTop)
{
[self.window setLevel:NSFloatingWindowLevel];
}
else
{
[self.window setLevel:NSNormalWindowLevel];
}
}
@end
@@ -1,70 +0,0 @@
#include "DeviceEx.h"
#import "openudid/OpenUDIDMac.h"
using namespace std;
PLAYER_NS_BEGIN
DeviceEx *DeviceEx::getInstance()
{
static DeviceEx *instance = NULL;
if (!instance)
{
instance = new DeviceEx();
instance->init();
}
return instance;
}
std::string DeviceEx::getCurrentUILangName()
{
return _uiLangName;
}
std::string DeviceEx::getUserGUID()
{
return _userGUID;
}
////////// private //////////
DeviceEx::DeviceEx()
: _uiLangName("en")
{
}
void DeviceEx::init()
{
makeUILangName();
makeUserGUID();
}
void DeviceEx::makeUILangName()
{
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defs objectForKey:@"AppleLanguages"];
if ([languages count] > 0)
{
NSString *lang = [languages objectAtIndex:0];
_uiLangName = lang.UTF8String;
}
}
std::string DeviceEx::makeUserGUID()
{
if (_userGUID.length() <= 0)
{
_userGUID = string([[OpenUDIDMac value] cStringUsingEncoding:NSUTF8StringEncoding]);
if (_userGUID.length() <= 0)
{
_userGUID = "guid-fixed-1234567890";
}
}
return _userGUID;
}
PLAYER_NS_END
@@ -1,62 +0,0 @@
//
// EditBoxServiceMac.h
// player
//
#ifndef __player__EditBoxServiceMac__
#define __player__EditBoxServiceMac__
#include "PlayerEditBoxServiceProtocol.h"
@interface EditBoxServiceImplMac : NSObject <NSTextFieldDelegate>
{
NSTextField* textField_;
void* editBox_;
BOOL editState_;
NSMutableDictionary* placeholderAttributes_;
}
@property(nonatomic, retain) NSTextField* textField;
@property(nonatomic, retain) NSMutableDictionary* placeholderAttributes;
@property(nonatomic, readonly, getter = isEditState) BOOL editState;
@property(nonatomic, assign) void* editBox;
-(id) initWithFrame: (NSRect) frameRect editBox: (void*) editBox;
-(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance;
-(void) setPosition:(NSPoint) pos;
-(void) setContentSize:(NSSize) size;
-(void) visit;
-(void) openKeyboard;
-(void) closeKeyboard;
@end
PLAYER_NS_BEGIN
class PlayerEditBoxServiceMac : public PlayerEditBoxServiceProtocol
{
public:
PlayerEditBoxServiceMac();
virtual ~PlayerEditBoxServiceMac();
// overwrite
virtual void showSingleLineEditBox(const cocos2d::Rect &rect) ;
virtual void showMultiLineEditBox(const cocos2d::Rect &rect) ;
virtual void hide() ;
virtual void setText(const std::string &text);
virtual void setFont(const std::string &name, int size);
virtual void setFontColor(const cocos2d::Color3B &color);
virtual void setFormator(int formator);
private:
void show();
private:
EditBoxServiceImplMac* _sysEdit;
};
PLAYER_NS_END
#endif
@@ -1,219 +0,0 @@
#include "PlayerEditBoxServiceMac.h"
#include "cocos2d.h"
#include "glfw3native.h"
// internal
@implementation EditBoxServiceImplMac
@synthesize textField = textField_;
@synthesize placeholderAttributes = placeholderAttributes_;
@synthesize editState = editState_;
@synthesize editBox = editBox_;
- (id) getNSWindow
{
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
return glview->getCocoaWindow();
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[textField_ removeFromSuperview];
[textField_ release];
[placeholderAttributes_ release];
[super dealloc];
}
-(id) initWithFrame: (NSRect) frameRect editBox: (void*) editBox
{
self = [super init];
if (self)
{
editState_ = NO;
self.textField = [[[NSTextField alloc] initWithFrame:frameRect] autorelease];
NSColor *newColor = [NSColor colorWithCalibratedRed:255 / 255.0f green:0 blue:0 alpha:1.0f];
self.textField.textColor = newColor;
NSFont *font = [NSFont systemFontOfSize:10]; //TODO need to delete hard code here.
textField_.font = font;
[self setupTextField:textField_];
self.editBox = editBox;
self.placeholderAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
[NSColor grayColor], NSForegroundColorAttributeName,
nil];
[[[self getNSWindow] contentView] addSubview:textField_];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onTextDidChanged:)
name:NSControlTextDidEndEditingNotification
object:nil];
}
return self;
}
- (void)onTextDidChanged:(NSNotification *) notification
{
// hide first
[self.textField setHidden:YES];
}
- (void)setupTextField:(NSTextField *)textField
{
[textField setTextColor:[NSColor whiteColor]];
[textField setBackgroundColor:[NSColor clearColor]];
[textField setBordered:NO];
[textField setHidden:NO];
[textField setWantsLayer:YES];
[textField setDelegate:self];
}
-(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance
{
[[[self getNSWindow] contentView] doAnimationWhenKeyboardMoveWithDuration:duration distance:distance];
}
-(void) setPosition:(NSPoint) pos
{
NSRect frame = [textField_ frame];
frame.origin = pos;
[textField_ setFrame:frame];
}
-(void) setContentSize:(NSSize) size
{
[self.textField setFrameSize:size];
}
-(void) visit
{
}
-(void) openKeyboard
{
if ([textField_ superview]) {
[textField_ becomeFirstResponder];
}
}
-(void) closeKeyboard
{
if ([textField_ superview]) {
[textField_ resignFirstResponder];
}
}
- (BOOL)textFieldShouldReturn:(NSTextField *)sender
{
if (sender == textField_) {
[sender resignFirstResponder];
}
return NO;
}
-(void)animationSelector
{
}
- (BOOL) control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
return NO;
}
@end
PLAYER_NS_BEGIN;
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
PlayerEditBoxServiceMac::PlayerEditBoxServiceMac()
{
_handler = 0;
NSRect rect = NSMakeRect(0, 0, 100, 20);
_sysEdit = [[EditBoxServiceImplMac alloc] initWithFrame:rect editBox:this];
}
PlayerEditBoxServiceMac::~PlayerEditBoxServiceMac()
{
[_sysEdit release];
}
void PlayerEditBoxServiceMac::showSingleLineEditBox(const cocos2d::Rect &rect)
{
[[_sysEdit.textField cell] setLineBreakMode:NSLineBreakByTruncatingTail];
[[_sysEdit.textField cell] setTruncatesLastVisibleLine:YES];
[_sysEdit setPosition:NSMakePoint(rect.origin.x, rect.origin.y)];
[_sysEdit setContentSize:NSMakeSize(rect.size.width, rect.size.height)];
show();
}
void PlayerEditBoxServiceMac::showMultiLineEditBox(const cocos2d::Rect &rect)
{
[[_sysEdit.textField cell] setLineBreakMode:NSLineBreakByCharWrapping];
[[_sysEdit.textField cell] setTruncatesLastVisibleLine:NO];
[_sysEdit setPosition:NSMakePoint(rect.origin.x, rect.origin.y)];
[_sysEdit setContentSize:NSMakeSize(rect.size.width, rect.size.height)];
show();
}
void PlayerEditBoxServiceMac::setText(const std::string &text)
{
_sysEdit.textField.stringValue = [NSString stringWithUTF8String:text.c_str()];
}
void PlayerEditBoxServiceMac::setFont(const std::string &name, int size)
{
NSString *fntName = [NSString stringWithUTF8String:name.c_str()];
NSFont *textFont = [NSFont fontWithName:fntName size:size];
if (textFont != nil)
{
[_sysEdit.textField setFont:textFont];
}
}
void PlayerEditBoxServiceMac::setFontColor(const cocos2d::Color3B &color)
{
NSColor *textColor = [NSColor colorWithCalibratedRed:color.r / 255.0f green:color.g / 255.0f blue:color.b / 255.0f alpha:1.0f];
_sysEdit.textField.textColor = textColor;
}
// hide editbox
void PlayerEditBoxServiceMac::hide()
{
[_sysEdit.textField setHidden:YES];
[_sysEdit closeKeyboard];
}
void PlayerEditBoxServiceMac::show()
{
[_sysEdit.textField setHidden:NO];
[_sysEdit openKeyboard];
}
void PlayerEditBoxServiceMac::setFormator(int formator)
{
CCLOG("Not support yet.");
}
PLAYER_NS_END;
@@ -1,29 +0,0 @@
#ifndef __PLAY_FILE_DIALOG_SERVICE_MAC_H
#define __PLAY_FILE_DIALOG_SERVICE_MAC_H
#include "PlayerMacros.h"
#include "PlayerFileDialogServiceProtocol.h"
PLAYER_NS_BEGIN
class PlayerFileDialogServiceMac : public PlayerFileDialogServiceProtocol
{
public:
virtual std::string openFile(const std::string &title,
const std::string &directory,
const std::string &extensions) const;
virtual std::vector<std::string> openMultiple(const std::string &title,
const std::string &directory,
const std::string &extensions) const;
virtual std::string saveFile(const std::string &title,
const std::string &path) const;
virtual std::string openDirectory(const std::string &title,
const std::string &directory)const;
};
PLAYER_NS_END
#endif // __PLAY_FILE_DIALOG_SERVICE_MAC_H
@@ -1,174 +0,0 @@
#include "PlayerFileDialogServiceMac.h"
#include "glfw3.h"
#include "glfw3native.h"
#define VALIDATE_FRAMEBUFFER { \
NSOpenGLContext *__context = glfwGetNSGLContext(glfwGetCurrentContext()); \
[__context makeCurrentContext]; \
}
PLAYER_NS_BEGIN
std::string PlayerFileDialogServiceMac::openFile(const std::string &title,
const std::string &directory,
const std::string &extensions) const
{
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setTitle:[NSString stringWithUTF8String:title.c_str()]];
[openDlg setCanChooseDirectories:NO];
[openDlg setCanChooseFiles:YES];
[openDlg setCanHide:YES];
[openDlg setCanCreateDirectories:NO];
[openDlg setCanSelectHiddenExtension:NO];
[openDlg setAllowsMultipleSelection:NO];
if (directory.length()) {
[openDlg setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:directory.c_str()]]];
}
if (extensions.length())
{
NSMutableArray *fileTypes = [NSMutableArray array];
NSString *buff = [NSString stringWithUTF8String:extensions.c_str()];
NSArray *extensionArray = [buff componentsSeparatedByString:@";"];
for (NSString *oneExtension in extensionArray) {
NSArray *tmpData = [oneExtension componentsSeparatedByString:@"|"];
if ([tmpData count] > 1)
{
NSString *suffixString = [tmpData objectAtIndex:1];
suffixString = [suffixString stringByReplacingOccurrencesOfString:@"*." withString:@""];
[fileTypes addObjectsFromArray:[suffixString componentsSeparatedByString:@","]];
}
}
[openDlg setAllowedFileTypes:fileTypes];
}
std::string filePath;
if ([openDlg runModal] == NSFileHandlingPanelOKButton)
{
NSURL *url = [openDlg.URLs objectAtIndex:0];
filePath = [[url path] UTF8String];
}
[openDlg close];
VALIDATE_FRAMEBUFFER
return filePath;
}
std::string PlayerFileDialogServiceMac::openDirectory( const std::string &title,
const std::string &directory) const
{
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setTitle:[NSString stringWithUTF8String:title.c_str()]];
[openDlg setCanChooseDirectories:YES];
[openDlg setCanChooseFiles:NO];
[openDlg setCanHide:YES];
[openDlg setCanCreateDirectories:NO];
[openDlg setCanSelectHiddenExtension:NO];
[openDlg setAllowsMultipleSelection:NO];
if (directory.length()) {
[openDlg setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:directory.c_str()]]];
}
std::string path;
if ([openDlg runModal] == NSFileHandlingPanelOKButton)
{
NSURL *url = [openDlg.URLs objectAtIndex:0];
path = [[url path] UTF8String];
}
[openDlg close];
VALIDATE_FRAMEBUFFER
return path;
}
std::vector<std::string> PlayerFileDialogServiceMac::openMultiple( const std::string &title,
const std::string &directory,
const std::string &extensions) const
{
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setTitle:[NSString stringWithUTF8String:title.c_str()]];
[openDlg setCanChooseDirectories:YES];
[openDlg setCanChooseFiles:YES];
[openDlg setCanHide:YES];
[openDlg setCanCreateDirectories:NO];
[openDlg setCanSelectHiddenExtension:NO];
[openDlg setAllowsMultipleSelection:YES];
if (directory.length()) {
[openDlg setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:directory.c_str()]]];
}
if (extensions.length())
{
NSMutableArray *fileTypes = [NSMutableArray array];
NSString *buff = [NSString stringWithUTF8String:extensions.c_str()];
NSArray *extensionArray = [buff componentsSeparatedByString:@";"];
for (NSString *oneExtension in extensionArray) {
NSArray *tmpData = [oneExtension componentsSeparatedByString:@"|"];
if ([tmpData count] > 1)
{
NSString *suffixString = [tmpData objectAtIndex:1];
suffixString = [suffixString stringByReplacingOccurrencesOfString:@"*." withString:@""];
[fileTypes addObjectsFromArray:[suffixString componentsSeparatedByString:@","]];
}
}
[openDlg setAllowedFileTypes:fileTypes];
}
std::vector<std::string> pathes;
if ([openDlg runModal] == NSFileHandlingPanelOKButton)
{
for (NSURL *url in openDlg.URLs) {
pathes.push_back([[url path] UTF8String]);
}
}
[openDlg close];
VALIDATE_FRAMEBUFFER
return pathes;
}
std::string PlayerFileDialogServiceMac::saveFile(const std::string &title,
const std::string &path) const
{
NSSavePanel* saveDlg = [NSSavePanel savePanel];
[saveDlg setTitle:[NSString stringWithUTF8String:title.c_str()]];
[saveDlg setCanHide:YES];
[saveDlg setCanCreateDirectories:NO];
[saveDlg setCanSelectHiddenExtension:NO];
// set directory
NSString *tempPath = [NSString stringWithUTF8String:path.c_str()];
NSString *directory = [tempPath stringByDeletingLastPathComponent];
if (directory)
{
[saveDlg setDirectoryURL:[NSURL fileURLWithPath:directory]];
}
// set filename
[saveDlg setNameFieldStringValue:[tempPath lastPathComponent]];
std::string filePath;
if ([saveDlg runModal] == NSFileHandlingPanelOKButton)
{
NSURL *url = saveDlg.URL;
filePath = [[url path] UTF8String];
}
[saveDlg close];
VALIDATE_FRAMEBUFFER
return filePath;
}
PLAYER_NS_END
@@ -1,52 +0,0 @@
#ifndef __PLAYER_MAC_H_
#define __PLAYER_MAC_H_
#include "PlayerProtocol.h"
#include "PlayerEditBoxServiceMac.h"
#include "PlayerFileDialogServiceMac.h"
#include "PlayerMenuServiceMac.h"
#include "PlayerMessageBoxServiceMac.h"
#include "PlayerTaskServiceMac.h"
#include "PlayerUtils.h"
#include "ProjectConfig/ProjectConfig.h"
PLAYER_NS_BEGIN
class PlayerMac : public PlayerProtocol
{
public:
static PlayerMac *create();
virtual ~PlayerMac();
virtual PlayerFileDialogServiceProtocol *getFileDialogService();
virtual PlayerMessageBoxServiceProtocol *getMessageBoxService();
virtual PlayerMenuServiceProtocol *getMenuService();
virtual PlayerEditBoxServiceProtocol *getEditBoxService();
virtual PlayerTaskServiceProtocol *getTaskService();
void quit();
void relaunch();
void openNewPlayer();
void openNewPlayerWithProjectConfig(const ProjectConfig& config);
void openProjectWithProjectConfig(const ProjectConfig& config);
void setController(id controller);
int getPositionX();
int getPositionY();
protected:
PlayerMac();
PlayerMenuServiceMac *_menuService;
PlayerMessageBoxServiceMac *_messageBoxService;
PlayerFileDialogServiceMac *_fileDialogService;
PlayerEditBoxServiceMac *_editBoxService;
PlayerTaskServiceMac *_taskService;
id _appController;
};
PLAYER_NS_END
#endif // __PLAYER_MAC_H_
@@ -1,135 +0,0 @@
#include "PlayerMac.h"
PLAYER_NS_BEGIN
using namespace cocos2d;
PlayerMac* PlayerMac::create()
{
return new PlayerMac();
}
PlayerMac::PlayerMac()
: PlayerProtocol()
, _fileDialogService(nullptr)
, _messageBoxService(nullptr)
, _menuService(nullptr)
, _editBoxService(nullptr)
, _appController(nullptr)
, _taskService(nullptr)
{
}
PlayerMac::~PlayerMac()
{
CC_SAFE_DELETE(_fileDialogService);
CC_SAFE_DELETE(_fileDialogService);
CC_SAFE_DELETE(_messageBoxService);
CC_SAFE_DELETE(_menuService);
CC_SAFE_DELETE(_editBoxService);
CC_SAFE_DELETE(_taskService);
}
PlayerFileDialogServiceProtocol *PlayerMac::getFileDialogService()
{
if (!_fileDialogService)
{
_fileDialogService = new PlayerFileDialogServiceMac();
}
return _fileDialogService;
}
PlayerMessageBoxServiceProtocol *PlayerMac::getMessageBoxService()
{
if (!_messageBoxService)
{
_messageBoxService = new PlayerMessageBoxServiceMac();
}
return _messageBoxService;
}
PlayerMenuServiceProtocol *PlayerMac::getMenuService()
{
if (!_menuService)
{
_menuService = new PlayerMenuServiceMac();
}
return _menuService;
}
PlayerEditBoxServiceProtocol *PlayerMac::getEditBoxService()
{
if (!_editBoxService)
{
_editBoxService = new PlayerEditBoxServiceMac();
}
return _editBoxService;
}
PlayerTaskServiceProtocol *PlayerMac::getTaskService()
{
if (!_taskService)
{
_taskService = new PlayerTaskServiceMac();
}
return _taskService;
}
void PlayerMac::quit()
{
cocos2d::Director::getInstance()->end();
}
void PlayerMac::relaunch()
{
if (_appController && [_appController respondsToSelector:NSSelectorFromString(@"relaunch")])
{
[_appController performSelector:NSSelectorFromString(@"relaunch")];
}
}
void PlayerMac::openNewPlayer()
{
}
void PlayerMac::openNewPlayerWithProjectConfig(const ProjectConfig& config)
{
if (_appController && [_appController respondsToSelector:NSSelectorFromString(@"launch:")])
{
NSString *commandLine = [NSString stringWithCString:config.makeCommandLine().c_str()
encoding:NSUTF8StringEncoding];
NSArray *arguments = [NSMutableArray arrayWithArray:[commandLine componentsSeparatedByString:@" "]];
[_appController performSelector:NSSelectorFromString(@"launch:") withObject:arguments];
}
}
void PlayerMac::openProjectWithProjectConfig(const ProjectConfig& config)
{
this->openNewPlayerWithProjectConfig(config);
this->quit();
}
void PlayerMac::setController(id controller)
{
_appController = controller;
}
int PlayerMac::getPositionX()
{
NSWindow *window = dynamic_cast<GLViewImpl*>(Director::getInstance()->getOpenGLView())->getCocoaWindow();
return window.frame.origin.x;
}
int PlayerMac::getPositionY()
{
NSWindow *window = dynamic_cast<GLViewImpl*>(Director::getInstance()->getOpenGLView())->getCocoaWindow();
return window.frame.origin.y;
}
PLAYER_NS_END
@@ -1,82 +0,0 @@
#ifndef __PLAYER_MENU_SERVICE_MAC_H_
#define __PLAYER_MENU_SERVICE_MAC_H_
#include <unordered_map>
#include "cocos2d.h"
#include "PlayerMacros.h"
#include "PlayerMenuServiceProtocol.h"
//
// Menu item Helper
//
PLAYER_NS_BEGIN
class PlayerMenuItemMac;
PLAYER_NS_END
@interface NNMenuItem : NSMenuItem <NSMenuDelegate>
{
int scriptHandler;
player::PlayerMenuItemMac *macMenuItem;
}
@property (nonatomic) int scriptHandler;
@property (nonatomic) const player::PlayerMenuItemMac *macMenuItem;
+(id) createMenuItem:(const player::PlayerMenuItemMac *) macMenuItem;
@end
//
// PlayerMenuItemMac
//
PLAYER_NS_BEGIN
class PlayerMenuItemMac : public PlayerMenuItem
{
public:
static PlayerMenuItemMac *create(const std::string &menuId, const std::string &title);
virtual ~PlayerMenuItemMac();
virtual void setTitle(const std::string &title);
virtual void setEnabled(bool enabled);
virtual void setChecked(bool checked);
virtual void setShortcut(const std::string &shortcut);
protected:
PlayerMenuItemMac();
PlayerMenuItemMac *_parent;
NNMenuItem *_menuItem;
NSMenu *_menu;
cocos2d::Vector<PlayerMenuItemMac*> _children;
friend class PlayerMenuServiceMac;
};
class PlayerMenuServiceMac : public PlayerMenuServiceProtocol
{
public:
PlayerMenuServiceMac();
virtual ~PlayerMenuServiceMac();
virtual PlayerMenuItem *addItem(const std::string &menuId, const std::string &title, const std::string &parentId, int order = MAX_ORDER);
virtual PlayerMenuItem *addItem(const std::string &menuId, const std::string &title);
virtual PlayerMenuItem *getItem(const std::string &menuId);
virtual bool removeItem(const std::string &menuId);
virtual void setMenuBarEnabled(bool enabled);
private:
bool removeItemInternal(const std::string &menuId, bool isUpdateChildrenOrder);
void updateChildrenOrder(PlayerMenuItemMac *parent);
private:
PlayerMenuItemMac _root;
std::unordered_map<std::string, PlayerMenuItemMac*> _items;
};
PLAYER_NS_END
#endif // __PLAYER_MENU_SERVICE_MAC_H_
@@ -1,370 +0,0 @@
#include "PlayerMenuServiceMac.h"
#include "PlayerUtils.h"
#include "cocos2d.h"
#include "AppEvent.h"
USING_NS_CC;
/////////////////////////////////////// menu helper //////////////////////////////////////////////
static bool __G_IS_MENUBAR_ENABLED__ = true; // WTF
@implementation NNMenuItem
@synthesize scriptHandler;
@synthesize macMenuItem;
+(id) createMenuItem:(const player::PlayerMenuItemMac *) macMenuItem
{
if (macMenuItem->getTitle().compare("-") == 0)
{
return [NSMenuItem separatorItem];
}
else
{
return [[[NNMenuItem alloc] initWithMenuItem:macMenuItem] autorelease];
}
return NULL;
}
-(id) initWithMenuItem:(const player::PlayerMenuItemMac *) menuItem
{
NSString *title = [NSString stringWithUTF8String:menuItem->getTitle().c_str()];
title = [title stringByReplacingOccurrencesOfString:@"&" withString:@""];
if ([super initWithTitle:title action:@selector(onClicked:) keyEquivalent:@""])
{
self.target = self;
}
self.macMenuItem = menuItem;
return self;
}
-(void) setShortcut:(std::string) shortcut
{
std::vector <std::string> fields = player::splitString(shortcut, std::string("+"));
NSUInteger mask = [self keyEquivalentModifierMask];
for (auto cut : fields)
{
if (cut == kPlayerSuperModifyKey)
{
mask |= NSCommandKeyMask;
}
else if (cut == kPlayerShiftModifyKey)
{
mask |= NSShiftKeyMask;
}
else if (cut == kPlayerCtrlModifyKey)
{
mask |= NSControlKeyMask;
}
else if (cut == kPlayerAltModifyKey)
{
mask |= NSAlternateKeyMask;
}
else
{
if (cut.length() == 1)
{
[self setKeyEquivalent:[NSString stringWithUTF8String:cut.c_str()]];
}
else
{
CCLOG("[modifyItem] shortcut (%s) is invalid.", shortcut.c_str());
}
}
}
if (mask != 0)
{
[self setKeyEquivalentModifierMask:mask];
}
}
-(void) onClicked:(id)sender
{
AppEvent event(kAppEventName, APP_EVENT_MENU);
std::stringstream buf;
buf << "{\"data\":\"" << self.macMenuItem->getMenuId().c_str() << "\"";
buf << ",\"name\":" << "\"menuClicked\"" << "}";
event.setDataString(buf.str());
event.setUserData((void*)self.macMenuItem);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
-(BOOL) validateMenuItem:(NSMenuItem *)menuItem
{
return __G_IS_MENUBAR_ENABLED__;
}
@end
PLAYER_NS_BEGIN
//
PlayerMenuItemMac *PlayerMenuItemMac::create(const std::string &menuId, const std::string &title)
{
PlayerMenuItemMac *item = new PlayerMenuItemMac();
item->_menuId = menuId;
item->_title = title;
item->autorelease();
return item;
}
PlayerMenuItemMac::PlayerMenuItemMac()
: _parent(nullptr)
, _menuItem(nullptr)
, _menu(nullptr)
{
}
PlayerMenuItemMac::~PlayerMenuItemMac()
{
CC_SAFE_RELEASE(_parent);
if (_menuItem)
{
[_parent->_menu removeItem:_menuItem];
}
CCLOG("PlayerMenuItemWin::~PlayerMenuItemWin() - %s", _menuId.c_str());
}
void PlayerMenuItemMac::setTitle(const std::string &title)
{
if (title.length() == 0)
{
CCLOG("MenuServiceWin::setTitle() - can not set menu title to empty, menu id (%s)", _menuId.c_str());
return;
}
_menuItem.title = [NSString stringWithUTF8String:title.c_str()];
if (_menu)
{
_menu.title = _menuItem.title;
}
_title = title;
}
void PlayerMenuItemMac::setEnabled(bool enabled)
{
_isEnabled = enabled;
if (enabled)
{
[_menuItem setAction:@selector(onClicked:)];
}
else
{
[_menuItem setAction:nil];
}
}
void PlayerMenuItemMac::setChecked(bool checked)
{
_isChecked = checked;
[_menuItem setState:checked ? NSOnState : NSOffState];
}
void PlayerMenuItemMac::setShortcut(const std::string &shortcut)
{
_shortcut = shortcut;
[_menuItem setShortcut:shortcut];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
PlayerMenuServiceMac::PlayerMenuServiceMac()
{
// @TODO: build menu with **EDIT** menu
NSApplication *thisApp = [NSApplication sharedApplication];
_root._menu = [thisApp mainMenu];
}
PlayerMenuServiceMac::~PlayerMenuServiceMac()
{
log("~PlayerMenuServiceMac");
_items.clear();
}
PlayerMenuItem* PlayerMenuServiceMac::addItem(const std::string &menuId, const std::string &title,
const std::string &parentId, int order)
{
if (menuId.length() == 0 || title.length() == 0)
{
CCLOG("PlayerMenuServiceMac::addItem() - menuId and title must is non-empty");
return nullptr;
}
// check menu id is exists
if (_items.find(menuId) != _items.end())
{
CCLOG("PlayerMenuServiceMac::addItem() - menu id (%s) is exists", menuId.c_str());
return nullptr;
}
// set parent
PlayerMenuItemMac *parent = &_root;
if (parentId.length())
{
// query parent menu
auto it = _items.find(parentId);
if (it != _items.end())
{
parent = it->second;
}
}
if (!parent->_menu)
{
NSMenu *nsmenu = [[NSMenu alloc] initWithTitle:[parent->_menuItem title]];
[parent->_parent->_menu setSubmenu:nsmenu forItem:parent->_menuItem];
parent->_menu = nsmenu;
parent->_isGroup = true;
}
// create new menu item
PlayerMenuItemMac *item = PlayerMenuItemMac::create(menuId, title);
item->_parent = parent;
item->_parent->retain();
// check new menu item position
int childSize = (int) [parent->_menu itemArray].count;
childSize = (int) parent->_children.size();
if (order > childSize)
{
order = childSize;
}
else if (order < 0)
{
order = 0;
}
// add menu item to menu bar
int newIndex = order;
if (parent == &_root)
{
newIndex += 1;
}
NNMenuItem *newItem = [NNMenuItem createMenuItem:item];
[parent->_menu insertItem:newItem atIndex:newIndex];
item->_menuItem = newItem;
// update menu state
parent->_children.insert(order, item);
_items[item->_menuId] = item;
updateChildrenOrder(parent);
return item;
}
PlayerMenuItem* PlayerMenuServiceMac::addItem(const std::string &menuId, const std::string &title)
{
return addItem(menuId, title, "");
}
PlayerMenuItem* PlayerMenuServiceMac::getItem(const std::string &menuId)
{
auto it = _items.find(menuId);
if (it == _items.end())
{
CCLOG("MenuServiceWin::getItem() - Invalid menu id (%s)", menuId.c_str());
return nullptr;
}
return it->second;
}
bool PlayerMenuServiceMac::removeItem(const std::string &menuId)
{
return removeItemInternal(menuId, true);;
}
void PlayerMenuServiceMac::setMenuBarEnabled(bool enabled)
{
__G_IS_MENUBAR_ENABLED__ = enabled;
}
#pragma mark - private -
bool PlayerMenuServiceMac::removeItemInternal(const std::string &menuId, bool isUpdateChildrenOrder)
{
auto it = _items.find(menuId);
if (it == _items.end())
{
CCLOG("MenuServiceWin::removeItem() - Invalid menu id (%s)", menuId.c_str());
return false;
}
PlayerMenuItemMac *item = it->second;
if (item->_children.size() == 0)
{
// remove item from parent
bool removed = false;
auto *theChildren = &item->_parent->_children;
for (auto it = theChildren->begin(); it != theChildren->end(); ++it)
{
if ((*it)->_menuItem == item->_menuItem)
{
theChildren->erase(it);
removed = true;
break;
}
}
if (!removed)
{
CCLOG("MenuServiceWin::removeItem() - remove menu item (%s) failed, not found command id from parent->children", item->_menuId.c_str());
}
// remove menu id mapping
_items.erase(menuId);
if (isUpdateChildrenOrder)
{
updateChildrenOrder(item->_parent);
}
return true;
}
else
{
// remove all children
while (item->_children.size() != 0)
{
PlayerMenuItemMac *child = *item->_children.begin();
if (!removeItemInternal(child->_menuId.c_str(), false))
{
break;
return false;
}
}
return removeItemInternal(menuId, true);
}
return false;
}
void PlayerMenuServiceMac::updateChildrenOrder(PlayerMenuItemMac *parent)
{
auto *children = &parent->_children;
int order = 0;
for (auto it = children->begin(); it != children->end(); ++it)
{
(*it)->_order = order;
order++;
}
}
PLAYER_NS_END
@@ -1,29 +0,0 @@
#ifndef __PLAYER_MessageBoxServiceMac_h
#define __PLAYER_MessageBoxServiceMac_h
#include <vector>
#include "PlayerMacros.h"
#include "PlayerMessageBoxServiceProtocol.h"
PLAYER_NS_BEGIN
class PlayerMessageBoxServiceMac : public PlayerMessageBoxServiceProtocol
{
public:
virtual int showMessageBox(const std::string &title,
const std::string &message,
int buttonsType = BUTTONS_OK);
protected:
struct MessageBoxInfo
{
std::string title;
const int buttonId;
};
std::vector<MessageBoxInfo> getTitles(int buttons);
};
PLAYER_NS_END
#endif // __PLAYER_MessageBoxServiceMac_h
@@ -1,58 +0,0 @@
#include "PlayerMessageBoxServiceMac.h"
PLAYER_NS_BEGIN
int PlayerMessageBoxServiceMac::showMessageBox(const std::string &title,
const std::string &message,
int buttonsType)
{
NSAlert *alert = [[NSAlert alloc] init];
auto titles = getTitles(buttonsType);
for (auto& title : titles)
{
[alert addButtonWithTitle:[NSString stringWithUTF8String:title.title.c_str()]];
}
[alert setMessageText:[NSString stringWithUTF8String:title.c_str()]];
[alert setInformativeText:[NSString stringWithUTF8String:message.c_str()]];
[alert setAlertStyle:NSWarningAlertStyle];
int index = (int)[alert runModal] - NSAlertFirstButtonReturn;
return titles.at(index).buttonId;
}
std::vector<PlayerMessageBoxServiceMac::MessageBoxInfo> PlayerMessageBoxServiceMac::getTitles(int buttons)
{
std::vector<PlayerMessageBoxServiceMac::MessageBoxInfo> titles;
switch (buttons) {
case BUTTONS_OK:
titles.push_back({"OK", BUTTON_OK});
break;
case BUTTONS_OK_CANCEL:
titles.push_back({"OK", BUTTON_OK});
titles.push_back({"Cancel", BUTTON_CANCEL});
break;
case BUTTONS_YES_NO:
titles.push_back({"Yes", BUTTON_YES});
titles.push_back({"No", BUTTON_NO});
break;
case BUTTONS_YES_NO_CANCEL:
titles.push_back({"Yes", BUTTON_YES});
titles.push_back({"No", BUTTON_NO});
titles.push_back({"Cancel", BUTTON_CANCEL});
break;
default:
break;
}
return titles;
}
PLAYER_NS_END
@@ -1,81 +0,0 @@
#ifndef __PLAYER_TASK_SERVICE_MAC_H_
#define __PLAYER_TASK_SERVICE_MAC_H_
#include <sstream>
#include "PlayerTaskServiceProtocol.h"
PLAYER_NS_BEGIN
class PlayerTaskMac;
PLAYER_NS_END
@interface PlayerTaskPrivate : NSObject
{
NSFileHandle *fileHandle;
// compatible code
NSTask *_buildTask;
BOOL _isRunning;
int _exitCode;
NSString *_output;
}
@property (assign) NSTask *buildTask;
@property (assign) BOOL isRunning;
@property (assign) int exitCode;
@property (retain) NSString *output;
- (void) runScriptAsyn:(NSString *)absScriptPath withArguments:(NSArray *) arguments;
@end
PLAYER_NS_BEGIN
class PlayerTaskMac : public PlayerTask
{
public:
static PlayerTaskMac *create(const std::string &name,
const std::string &executePath,
const std::string &commandLineArguments);
virtual ~PlayerTaskMac();
virtual bool run();
virtual void stop();
virtual void runInTerminal();
// check task status
virtual void update(float dt);
void appendOutput(const char *data);
protected:
PlayerTaskMac(const std::string &name,
const std::string &executePath,
const std::string &commandLineArguments);
void cleanup();
std::u16string makeCommandLine() const;
PlayerTaskPrivate *_taskPrivate;
};
class PlayerTaskServiceMac : public PlayerTaskServiceProtocol
{
public:
PlayerTaskServiceMac();
virtual ~PlayerTaskServiceMac();
virtual PlayerTask *createTask(const std::string &name,
const std::string &executePath,
const std::string &commandLineArguments);
virtual PlayerTask *getTask(const std::string &name);
virtual void removeTask(const std::string &name);
protected:
cocos2d::Map<std::string, PlayerTaskMac*> _tasks;
};
PLAYER_NS_END
#endif // __PLAYER_TASK_SERVICE_MAC_H_
@@ -1,246 +0,0 @@
#include "PlayerTaskServiceMac.h"
@implementation PlayerTaskPrivate
@synthesize buildTask = _buildTask;
@synthesize isRunning = _isRunning;
@synthesize exitCode = _exitCode;
@synthesize output = _output;
-(id) init
{
if ((self = [super init])) {
_isRunning = NO;
_exitCode = 0;
}
return self;
}
-(void) dealloc
{
[_output release];
[super dealloc];
}
-(void)performSelectorInBackground:(SEL)selector withObjects:(id)object, ...
{
NSMethodSignature *signature = [self methodSignatureForSelector:selector];
// setup the invocation
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = self;
invocation.selector = selector;
// associate the arguments
va_list objects;
va_start(objects, object);
unsigned int objectCounter = 2;
for (id obj = object; obj != nil; obj = va_arg(objects, id))
{
[invocation setArgument:&obj atIndex:objectCounter++];
}
va_end(objects);
// make sure to invoke on a background queue
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithInvocation:invocation];
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
[backgroundQueue addOperation:operation];
}
- (void) runScriptAsyn:(NSString *)absScriptPath withArguments:(NSArray *) arguments
{
_isRunning = YES;
[self performSelectorInBackground:@selector(runScriptSync:withArguments:)
withObjects:absScriptPath, arguments, nil];
}
- (void) runScriptSync:(NSString *)absScriptPath withArguments:(NSArray *)arguments
{
if (!absScriptPath)
{
CCLOG("Please check your script (%s)", absScriptPath.UTF8String);
return ;
}
_buildTask = [[NSTask alloc] init];
[_buildTask setLaunchPath:absScriptPath];
if (!arguments)
{
arguments = [NSArray array];
}
[_buildTask setArguments:arguments];
//
NSPipe *pipe;
pipe = [NSPipe pipe];
[_buildTask setStandardOutput: pipe];
fileHandle = [pipe fileHandleForReading];
//
[_buildTask launch];
[_buildTask waitUntilExit];
NSData *data;
data = [fileHandle readDataToEndOfFile];
_output = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
_isRunning = NO;
_exitCode = [_buildTask terminationStatus];
[fileHandle closeFile];
[_buildTask release];
_buildTask = nil;
}
@end
PLAYER_NS_BEGIN
PlayerTaskMac *PlayerTaskMac::create(const std::string &name, const std::string &executePath, const std::string &commandLineArguments)
{
PlayerTaskMac *task = new PlayerTaskMac(name, executePath, commandLineArguments);
task->autorelease();
return task;
}
PlayerTaskMac::PlayerTaskMac(const std::string &name,
const std::string &executePath,
const std::string &commandLineArguments)
: PlayerTask(name, executePath, commandLineArguments)
{
_taskPrivate = [[PlayerTaskPrivate alloc] init];
}
PlayerTaskMac::~PlayerTaskMac()
{
cleanup();
}
bool PlayerTaskMac::run()
{
if (!isIdle())
{
CCLOG("PlayerTaskMac::run() - task is not idle");
return false;
}
NSString *commandLine = [NSString stringWithCString:_commandLineArguments.c_str()
encoding:NSUTF8StringEncoding];
[_taskPrivate runScriptAsyn:[NSString stringWithUTF8String:_executePath.data()]
withArguments:[NSMutableArray arrayWithArray:[commandLine componentsSeparatedByString:@" "]]];
_state = STATE_RUNNING;
cocos2d::Director::getInstance()->getScheduler()->scheduleUpdate(this, 0, false);
return true;
}
void PlayerTaskMac::runInTerminal()
{
NSString *s = [NSString stringWithFormat:
@"tell application \"Terminal\" to do script \"%s %s\"", _executePath.c_str(), _commandLineArguments.c_str()];
NSAppleScript *as = [[NSAppleScript alloc] initWithSource: s];
[as executeAndReturnError:nil];
}
void PlayerTaskMac::stop()
{
cleanup();
}
void PlayerTaskMac::update(float dt)
{
_lifetime += dt;
if (_taskPrivate.isRunning)
{
return ;
}
cocos2d::Director::getInstance()->getScheduler()->unscheduleAllForTarget(this);
cleanup();
}
void PlayerTaskMac::appendOutput(const char *data)
{
_output.append(data);
}
void PlayerTaskMac::cleanup()
{
_state = STATE_COMPLETED;
[NSObject cancelPreviousPerformRequestsWithTarget:_taskPrivate];
[_taskPrivate.buildTask interrupt];
_resultCode = _taskPrivate.exitCode;
_output.append(_taskPrivate.output.UTF8String);
[_taskPrivate release];
_taskPrivate = nil;
CCLOG("\nCMD: (exit code: %d) %s", _resultCode, _output.c_str());
cocos2d::Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(_name);
}
std::u16string PlayerTaskMac::makeCommandLine() const
{
std::stringstream buf;
buf << "\"";
buf << _executePath;
buf << "\" ";
buf << _commandLineArguments;
std::u16string u16command;
cocos2d::StringUtils::UTF8ToUTF16(buf.str(), u16command);
return u16command;
}
PlayerTaskServiceMac::PlayerTaskServiceMac()
{
}
PlayerTaskServiceMac::~PlayerTaskServiceMac()
{
for (auto it = _tasks.begin(); it != _tasks.end(); ++it)
{
it->second->stop();
}
}
PlayerTask *PlayerTaskServiceMac::createTask(const std::string &name,
const std::string &executePath,
const std::string &commandLineArguments)
{
CCASSERT(_tasks.find(name) == _tasks.end(), "Task already exists.");
PlayerTaskMac *task = PlayerTaskMac::create(name, executePath, commandLineArguments);
_tasks.insert(name, task);
return task;
}
PlayerTask *PlayerTaskServiceMac::getTask(const std::string &name)
{
auto it = _tasks.find(name);
return it != _tasks.end() ? it->second : nullptr;
}
void PlayerTaskServiceMac::removeTask(const std::string &name)
{
auto it = _tasks.find(name);
if (it != _tasks.end())
{
if (!it->second->isCompleted())
{
it->second->stop();
}
_tasks.erase(it);
}
}
PLAYER_NS_END
@@ -1,65 +0,0 @@
//
// OpenUDID.h
// openudid
//
// initiated by Yann Lechelle (cofounder @Appsfire) on 8/28/11.
// Copyright 2011 OpenUDID.org
//
// Main branches
// iOS code: https://github.com/ylechelle/OpenUDID
//
/*
!!! IMPORTANT !!!
IF YOU ARE GOING TO INTEGRATE OpenUDID INSIDE A (STATIC) LIBRARY,
PLEASE MAKE SURE YOU REFACTOR THE OpenUDID CLASS WITH A PREFIX OF YOUR OWN,
E.G. ACME_OpenUDID. THIS WILL AVOID CONFUSION BY DEVELOPERS WHO ARE ALSO
USING OpenUDID IN THEIR OWN CODE.
!!! IMPORTANT !!!
*/
/*
http://en.wikipedia.org/wiki/Zlib_License
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#import <Foundation/Foundation.h>
//
// Usage:
// #include "OpenUDID.h"
// NSString* openUDID = [OpenUDID value];
//
#define kOpenUDIDErrorNone 0
#define kOpenUDIDErrorOptedOut 1
#define kOpenUDIDErrorCompromised 2
@interface OpenUDIDMac : NSObject {
}
+ (NSString*) value;
+ (NSString*) valueWithError:(NSError**)error;
+ (void) setOptOut:(BOOL)optOutValue;
@end
@@ -1,383 +0,0 @@
//
// OpenUDIDMac.m
// openudid
//
// initiated by Yann Lechelle (cofounder @Appsfire) on 8/28/11.
// Copyright 2011 OpenUDID.org
//
// Initiators/root branches
// iOS code: https://github.com/ylechelle/OpenUDID
// Android code: https://github.com/vieux/OpenUDID
//
// Contributors:
// https://github.com/ylechelle/OpenUDID/contributors
//
/*
http://en.wikipedia.org/wiki/Zlib_License
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#if __has_feature(objc_arc)
#error This file uses the classic non-ARC retain/release model; hints below...
// to selectively compile this file as non-ARC, do as follows:
// https://img.skitch.com/20120717-g3ag5h9a6ehkgpmpjiuen3qpwp.png
#endif
#import "OpenUDIDMac.h"
#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#import <UIKit/UIPasteboard.h>
#import <UIKit/UIKit.h>
#else
#import <AppKit/NSPasteboard.h>
#endif
#define OpenUDIDLog(fmt, ...)
//#define OpenUDIDLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
//#define OpenUDIDLog(fmt, ...) NSLog((@"[Line %d] " fmt), __LINE__, ##__VA_ARGS__);
static NSString * kOpenUDIDSessionCache = nil;
static NSString * const kOpenUDIDKey = @"OpenUDID";
static NSString * const kOpenUDIDSlotKey = @"OpenUDID_slot";
static NSString * const kOpenUDIDAppUIDKey = @"OpenUDID_appUID";
static NSString * const kOpenUDIDTSKey = @"OpenUDID_createdTS";
static NSString * const kOpenUDIDOOTSKey = @"OpenUDID_optOutTS";
static NSString * const kOpenUDIDDomain = @"org.OpenUDID";
static NSString * const kOpenUDIDSlotPBPrefix = @"org.OpenUDID.slot.";
static int const kOpenUDIDRedundancySlots = 100;
@interface OpenUDIDMac (Private)
+ (void) _setDict:(id)dict forPasteboard:(id)pboard;
+ (NSMutableDictionary*) _getDictFromPasteboard:(id)pboard;
+ (NSString*) _generateFreshOpenUDID;
@end
@implementation OpenUDIDMac
// Archive a NSDictionary inside a pasteboard of a given type
// Convenience method to support iOS & Mac OS X
//
+ (void) _setDict:(id)dict forPasteboard:(id)pboard {
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
[pboard setData:[NSKeyedArchiver archivedDataWithRootObject:dict] forPasteboardType:kOpenUDIDDomain];
#else
[pboard setData:[NSKeyedArchiver archivedDataWithRootObject:dict] forType:kOpenUDIDDomain];
#endif
}
// Retrieve an NSDictionary from a pasteboard of a given type
// Convenience method to support iOS & Mac OS X
//
+ (NSMutableDictionary*) _getDictFromPasteboard:(id)pboard {
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
id item = [pboard dataForPasteboardType:kOpenUDIDDomain];
#else
id item = [pboard dataForType:kOpenUDIDDomain];
#endif
if (item) {
@try{
item = [NSKeyedUnarchiver unarchiveObjectWithData:item];
} @catch(NSException* e) {
OpenUDIDLog(@"Unable to unarchive item %@ on pasteboard!", [pboard name]);
item = nil;
}
}
// return an instance of a MutableDictionary
return [NSMutableDictionary dictionaryWithDictionary:(item == nil || [item isKindOfClass:[NSDictionary class]]) ? item : nil];
}
// Private method to create and return a new OpenUDID
// Theoretically, this function is called once ever per application when calling [OpenUDID value] for the first time.
// After that, the caching/pasteboard/redundancy mechanism inside [OpenUDID value] returns a persistent and cross application OpenUDID
//
+ (NSString*) _generateFreshOpenUDID {
NSString* _openUDID = nil;
// August 2011: One day, this may no longer be allowed in iOS. When that is, just comment this line out.
// March 25th 2012: this day has come, let's remove this "outlawed" call...
#if TARGET_OS_IPHONE
// if([UIDevice instancesRespondToSelector:@selector(uniqueIdentifier)]){
// _openUDID = [[UIDevice currentDevice] uniqueIdentifier];
// }
#endif
// Next we generate a UUID.
// UUIDs (Universally Unique Identifiers), also known as GUIDs (Globally Unique Identifiers) or IIDs
// (Interface Identifiers), are 128-bit values guaranteed to be unique. A UUID is made unique over
// both space and time by combining a value unique to the computer on which it was generated—usually the
// Ethernet hardware address—and a value representing the number of 100-nanosecond intervals since
// October 15, 1582 at 00:00:00.
// We then hash this UUID with md5 to get 32 bytes, and then add 4 extra random bytes
// Collision is possible of course, but unlikely and suitable for most industry needs (e.g. aggregate tracking)
//
if (_openUDID==nil) {
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef cfstring = CFUUIDCreateString(kCFAllocatorDefault, uuid);
const char *cStr = CFStringGetCStringPtr(cfstring,CFStringGetFastestEncoding(cfstring));
unsigned char result[16];
CC_MD5( cStr, (unsigned int)strlen(cStr), result );
CFRelease(uuid);
_openUDID = [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%08x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15],
(unsigned int)(arc4random() % NSUIntegerMax)];
}
// Call to other developers in the Open Source community:
//
// feel free to suggest better or alternative "UDID" generation code above.
// NOTE that the goal is NOT to find a better hash method, but rather, find a decentralized (i.e. not web-based)
// 160 bits / 20 bytes random string generator with the fewest possible collisions.
//
return _openUDID;
}
// Main public method that returns the OpenUDID
// This method will generate and store the OpenUDID if it doesn't exist, typically the first time it is called
// It will return the null udid (forty zeros) if the user has somehow opted this app out (this is subject to 3rd party implementation)
// Otherwise, it will register the current app and return the OpenUDID
//
+ (NSString*) value {
return [OpenUDIDMac valueWithError:nil];
}
+ (NSString*) valueWithError:(NSError **)error {
if (kOpenUDIDSessionCache!=nil) {
if (error!=nil)
*error = [NSError errorWithDomain:kOpenUDIDDomain
code:kOpenUDIDErrorNone
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"OpenUDID in cache from first call",@"description", nil]];
return kOpenUDIDSessionCache;
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// The AppUID will uniquely identify this app within the pastebins
//
NSString * appUID = (NSString *) [defaults objectForKey:kOpenUDIDAppUIDKey];
if(appUID == nil)
{
// generate a new uuid and store it in user defaults
CFUUIDRef uuid = CFUUIDCreate(NULL);
appUID = (NSString *) CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
}
NSString* openUDID = nil;
NSString* myRedundancySlotPBid = nil;
NSDate* optedOutDate = nil;
BOOL optedOut = NO;
BOOL saveLocalDictToDefaults = NO;
BOOL isCompromised = NO;
// Do we have a local copy of the OpenUDID dictionary?
// This local copy contains a copy of the openUDID, myRedundancySlotPBid (and unused in this block, the local bundleid, and the timestamp)
//
id localDict = [defaults objectForKey:kOpenUDIDKey];
if ([localDict isKindOfClass:[NSDictionary class]]) {
localDict = [NSMutableDictionary dictionaryWithDictionary:localDict]; // we might need to set/overwrite the redundancy slot
openUDID = [localDict objectForKey:kOpenUDIDKey];
myRedundancySlotPBid = [localDict objectForKey:kOpenUDIDSlotKey];
optedOutDate = [localDict objectForKey:kOpenUDIDOOTSKey];
optedOut = optedOutDate!=nil;
OpenUDIDLog(@"localDict = %@",localDict);
}
// Here we go through a sequence of slots, each of which being a UIPasteboard created by each participating app
// The idea behind this is to both multiple and redundant representations of OpenUDIDs, as well as serve as placeholder for potential opt-out
//
NSString* availableSlotPBid = nil;
NSMutableDictionary* frequencyDict = [NSMutableDictionary dictionaryWithCapacity:kOpenUDIDRedundancySlots];
for (int n=0; n<kOpenUDIDRedundancySlots; n++) {
NSString* slotPBid = [NSString stringWithFormat:@"%@%d",kOpenUDIDSlotPBPrefix,n];
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
UIPasteboard* slotPB = [UIPasteboard pasteboardWithName:slotPBid create:NO];
#else
NSPasteboard* slotPB = [NSPasteboard pasteboardWithName:slotPBid];
#endif
OpenUDIDLog(@"SlotPB name = %@",slotPBid);
if (slotPB==nil) {
// assign availableSlotPBid to be the first one available
if (availableSlotPBid==nil) availableSlotPBid = slotPBid;
} else {
NSDictionary* dict = [OpenUDIDMac _getDictFromPasteboard:slotPB];
NSString* oudid = [dict objectForKey:kOpenUDIDKey];
OpenUDIDLog(@"SlotPB dict = %@",dict);
if (oudid==nil) {
// availableSlotPBid could inside a non null slot where no oudid can be found
if (availableSlotPBid==nil) availableSlotPBid = slotPBid;
} else {
// increment the frequency of this oudid key
int count = [[frequencyDict valueForKey:oudid] intValue];
[frequencyDict setObject:[NSNumber numberWithInt:++count] forKey:oudid];
}
// if we have a match with the app unique id,
// then let's look if the external UIPasteboard representation marks this app as OptedOut
NSString* gid = [dict objectForKey:kOpenUDIDAppUIDKey];
if (gid!=nil && [gid isEqualToString:appUID]) {
myRedundancySlotPBid = slotPBid;
// the local dictionary is prime on the opt-out subject, so ignore if already opted-out locally
if (optedOut) {
optedOutDate = [dict objectForKey:kOpenUDIDOOTSKey];
optedOut = optedOutDate!=nil;
}
}
}
}
// sort the Frequency dict with highest occurence count of the same OpenUDID (redundancy, failsafe)
// highest is last in the list
//
NSArray* arrayOfUDIDs = [frequencyDict keysSortedByValueUsingSelector:@selector(compare:)];
NSString* mostReliableOpenUDID = (arrayOfUDIDs!=nil && [arrayOfUDIDs count]>0)? [arrayOfUDIDs lastObject] : nil;
OpenUDIDLog(@"Freq Dict = %@\nMost reliable %@",frequencyDict,mostReliableOpenUDID);
// if openUDID was not retrieved from the local preferences, then let's try to get it from the frequency dictionary above
//
if (openUDID==nil) {
if (mostReliableOpenUDID==nil) {
// this is the case where this app instance is likely to be the first one to use OpenUDID on this device
// we create the OpenUDID, legacy or semi-random (i.e. most certainly unique)
//
openUDID = [OpenUDIDMac _generateFreshOpenUDID];
} else {
// or we leverage the OpenUDID shared by other apps that have already gone through the process
//
openUDID = mostReliableOpenUDID;
}
// then we create a local representation
//
if (localDict==nil) {
localDict = [NSMutableDictionary dictionaryWithCapacity:4];
[localDict setObject:openUDID forKey:kOpenUDIDKey];
[localDict setObject:appUID forKey:kOpenUDIDAppUIDKey];
[localDict setObject:[NSDate date] forKey:kOpenUDIDTSKey];
if (optedOut) [localDict setObject:optedOutDate forKey:kOpenUDIDTSKey];
saveLocalDictToDefaults = YES;
}
}
else {
// Sanity/tampering check
//
if (mostReliableOpenUDID!=nil && ![mostReliableOpenUDID isEqualToString:openUDID])
isCompromised = YES;
}
// Here we store in the available PB slot, if applicable
//
OpenUDIDLog(@"Available Slot %@ Existing Slot %@",availableSlotPBid,myRedundancySlotPBid);
if (availableSlotPBid!=nil && (myRedundancySlotPBid==nil || [availableSlotPBid isEqualToString:myRedundancySlotPBid])) {
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
UIPasteboard* slotPB = [UIPasteboard pasteboardWithName:availableSlotPBid create:YES];
[slotPB setPersistent:YES];
#else
NSPasteboard* slotPB = [NSPasteboard pasteboardWithName:availableSlotPBid];
#endif
// save slotPBid to the defaults, and remember to save later
//
if (localDict) {
[localDict setObject:availableSlotPBid forKey:kOpenUDIDSlotKey];
saveLocalDictToDefaults = YES;
}
// Save the local dictionary to the corresponding UIPasteboard slot
//
if (openUDID && localDict)
[OpenUDIDMac _setDict:localDict forPasteboard:slotPB];
}
// Save the dictionary locally if applicable
//
if (localDict && saveLocalDictToDefaults)
[defaults setObject:localDict forKey:kOpenUDIDKey];
// If the UIPasteboard external representation marks this app as opted-out, then to respect privacy, we return the ZERO OpenUDID, a sequence of 40 zeros...
// This is a *new* case that developers have to deal with. Unlikely, statistically low, but still.
// To circumvent this and maintain good tracking (conversion ratios, etc.), developers are invited to calculate how many of their users have opted-out from the full set of users.
// This ratio will let them extrapolate convertion ratios more accurately.
//
if (optedOut) {
if (error!=nil) *error = [NSError errorWithDomain:kOpenUDIDDomain
code:kOpenUDIDErrorOptedOut
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Application with unique id %@ is opted-out from OpenUDID as of %@",appUID,optedOutDate],@"description", nil]];
kOpenUDIDSessionCache = [[NSString stringWithFormat:@"%040x",0] retain];
return kOpenUDIDSessionCache;
}
// return the well earned openUDID!
//
if (error!=nil) {
if (isCompromised)
*error = [NSError errorWithDomain:kOpenUDIDDomain
code:kOpenUDIDErrorCompromised
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Found a discrepancy between stored OpenUDID (reliable) and redundant copies; one of the apps on the device is most likely corrupting the OpenUDID protocol",@"description", nil]];
else
*error = [NSError errorWithDomain:kOpenUDIDDomain
code:kOpenUDIDErrorNone
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"OpenUDID succesfully retrieved",@"description", nil]];
}
kOpenUDIDSessionCache = [openUDID retain];
return kOpenUDIDSessionCache;
}
+ (void) setOptOut:(BOOL)optOutValue {
// init call
[OpenUDIDMac value];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// load the dictionary from local cache or create one
id dict = [defaults objectForKey:kOpenUDIDKey];
if ([dict isKindOfClass:[NSDictionary class]]) {
dict = [NSMutableDictionary dictionaryWithDictionary:dict];
} else {
dict = [NSMutableDictionary dictionaryWithCapacity:2];
}
// set the opt-out date or remove key, according to parameter
if (optOutValue)
[dict setObject:[NSDate date] forKey:kOpenUDIDOOTSKey];
else
[dict removeObjectForKey:kOpenUDIDOOTSKey];
// store the dictionary locally
[defaults setObject:dict forKey:kOpenUDIDKey];
OpenUDIDLog(@"Local dict after opt-out = %@",dict);
// reset memory cache
kOpenUDIDSessionCache = nil;
}
@end
@@ -1,197 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="6254" systemVersion="14B25" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
<dependencies>
<deployment version="1080" identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="6254"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="AppController">
<connections>
<outlet property="delegate" destination="536" id="537"/>
<outlet property="menu" destination="29" id="650"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<menu title="AMainMenu" systemMenu="main" id="29">
<items>
<menuItem title="模拟器" id="56">
<menu key="submenu" title="模拟器" systemMenu="apple" id="57">
<items>
<menuItem title="关于 模拟器" id="58">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-2" id="142"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="143">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="服务" id="131">
<menu key="submenu" title="服务" systemMenu="services" id="130"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="144">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="隐藏 模拟器" keyEquivalent="h" id="134">
<connections>
<action selector="hide:" target="-1" id="367"/>
</connections>
</menuItem>
<menuItem title="隐藏其他窗口" keyEquivalent="h" id="145">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-1" id="368"/>
</connections>
</menuItem>
<menuItem title="全部显示" id="150">
<connections>
<action selector="unhideAllApplications:" target="-1" id="370"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="149">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="退出 模拟器" keyEquivalent="q" id="136">
<connections>
<action selector="onFileClose:" target="-1" id="UyZ-bV-2zL"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="编辑" id="Sqe-GR-erP">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="编辑" id="k0V-hR-upN">
<items>
<menuItem title="撤销" keyEquivalent="z" id="Ueo-Yj-fzm">
<connections>
<action selector="undo:" target="-1" id="Ex2-6U-hZI"/>
</connections>
</menuItem>
<menuItem title="重做" keyEquivalent="Z" id="x6z-iQ-VK2">
<connections>
<action selector="redo:" target="-1" id="KEx-Aj-tYn"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="COi-E7-7M4"/>
<menuItem title="剪切" keyEquivalent="x" id="NAk-12-pg4">
<connections>
<action selector="cut:" target="-1" id="Owu-Ie-Kfg"/>
</connections>
</menuItem>
<menuItem title="拷贝" keyEquivalent="c" id="XOY-ya-lNt">
<connections>
<action selector="copy:" target="-1" id="aIB-pV-N2w"/>
</connections>
</menuItem>
<menuItem title="粘贴" keyEquivalent="v" id="ul0-51-Ibd">
<connections>
<action selector="paste:" target="-1" id="7rk-Tb-7hI"/>
</connections>
</menuItem>
<menuItem title="粘贴并匹配样式" keyEquivalent="V" id="Zvy-7g-x4q">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="-1" id="oM4-kj-hTQ"/>
</connections>
</menuItem>
<menuItem title="删除" id="Xyz-QC-wlG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="-1" id="idJ-aN-6bB"/>
</connections>
</menuItem>
<menuItem title="选择全部" keyEquivalent="a" id="4fT-JL-N6e">
<connections>
<action selector="selectAll:" target="-1" id="pAH-rW-PaD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="osB-R6-2jE"/>
<menuItem title="查找" id="bms-8x-7Yb">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="查找" id="AXr-4L-lcV">
<items>
<menuItem title="查找" tag="1" keyEquivalent="f" id="GS8-y9-yQY">
<connections>
<action selector="performFindPanelAction:" target="-1" id="jVT-dG-Frl"/>
</connections>
</menuItem>
<menuItem title="查找下一个" tag="2" keyEquivalent="g" id="RJc-P7-Ibq">
<connections>
<action selector="performFindPanelAction:" target="-1" id="yLp-2a-Nuk"/>
</connections>
</menuItem>
<menuItem title="查找上一个" tag="3" keyEquivalent="G" id="f5k-Su-hK0">
<connections>
<action selector="performFindPanelAction:" target="-1" id="uoF-9Z-ef7"/>
</connections>
</menuItem>
<menuItem title="使用查找选择" tag="7" keyEquivalent="e" id="9Zj-Be-aBN">
<connections>
<action selector="performFindPanelAction:" target="-1" id="8hs-AK-0U8"/>
</connections>
</menuItem>
<menuItem title="跳转到选择" keyEquivalent="j" id="4tD-ef-pd8">
<connections>
<action selector="centerSelectionInVisibleArea:" target="-1" id="8xc-J0-7iQ"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="83"/>
<menuItem title="Player" id="633">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem title="Screen" id="295"/>
<menuItem title="窗口" id="19">
<menu key="submenu" title="窗口" systemMenu="window" id="XuB-dT-g0h">
<items>
<menuItem title="最小化" keyEquivalent="m" id="YrK-j5-jxq">
<connections>
<action selector="performMiniaturize:" target="-1" id="3wr-0O-cTq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="0NY-jh-tsl">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="移到最上层" id="opb-EX-EXV">
<connections>
<action selector="arrangeInFront:" target="-1" id="oT1-07-BON"/>
</connections>
</menuItem>
<menuItem title="置顶" keyEquivalent="a" id="nXh-Uq-d6d">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="onWindowAlwaysOnTop:" target="-1" id="IM6-Km-MGj"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="帮助" id="490">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="帮助" systemMenu="help" id="UaO-03-xh1">
<items>
<menuItem title="帮助文档" keyEquivalent="?" id="StN-Og-Ms8">
<connections>
<action selector="showHelp:" target="-1" id="l0h-I0-XAk"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<customObject id="420" customClass="NSFontManager"/>
<customObject id="536" customClass="AppController">
<connections>
<outlet property="menu" destination="29" id="550"/>
</connections>
</customObject>
</objects>
</document>
@@ -139,9 +139,7 @@ xcopy "$(COCOS_X_ROOT)\cocos\scripting\js-bindings\script" "$(LocalDebuggerWorki
xcopy "$(ProjectDir)..\..\..\src" "$(LocalDebuggerWorkingDirectory)\src" /D /E /I /F /Y
xcopy "$(ProjectDir)..\..\..\res" "$(LocalDebuggerWorkingDirectory)\res" /D /E /I /F /Y
copy "$(ProjectDir)..\..\..\main.js" "$(LocalDebuggerWorkingDirectory)" /Y
copy "$(ProjectDir)..\..\..\project.json" "$(LocalDebuggerWorkingDirectory)" /Y
xcopy /Y /Q "$(OutDir)*.dll" "$(LocalDebuggerWorkingDirectory)"
xcopy /Y /Q "$(ProjectDir)..\Classes\ide-support\lang" "$(LocalDebuggerWorkingDirectory)"</Command>
copy "$(ProjectDir)..\..\..\project.json" "$(LocalDebuggerWorkingDirectory)" /Y</Command>
<Outputs>$(TargetName).cab</Outputs>
<Inputs>$(TargetFileName)</Inputs>
</CustomBuildStep>
@@ -198,20 +196,13 @@ xcopy /Y /Q "$(COCOS_X_ROOT)\prebuilt\win32\*.*" "$(OutDir)"
</PreBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\Classes\ide-support\RuntimeJsImpl.cpp" />
<ClCompile Include="..\Classes\ide-support\SimpleConfigParser.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="..\Classes\AppDelegate.cpp" />
<ClCompile Include="SimulatorWin.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Classes\ide-support\CodeIDESupport.h" />
<ClInclude Include="..\Classes\ide-support\RuntimeJsImpl.h" />
<ClInclude Include="..\Classes\ide-support\SimpleConfigParser.h" />
<ClInclude Include="main.h" />
<ClInclude Include="..\Classes\AppDelegate.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="SimulatorWin.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="game.rc" />
@@ -11,9 +11,6 @@
<Filter Include="Classes">
<UniqueIdentifier>{e93a77e1-af1e-4400-87d3-504b62ebdbb0}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\ide-support">
<UniqueIdentifier>{5bec5a39-9bec-42e8-a3e4-823d4eacec56}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
@@ -22,15 +19,6 @@
<ClCompile Include="..\Classes\AppDelegate.cpp">
<Filter>Classes</Filter>
</ClCompile>
<ClCompile Include="..\Classes\ide-support\RuntimeJsImpl.cpp">
<Filter>Classes\ide-support</Filter>
</ClCompile>
<ClCompile Include="..\Classes\ide-support\SimpleConfigParser.cpp">
<Filter>Classes\ide-support</Filter>
</ClCompile>
<ClCompile Include="SimulatorWin.cpp">
<Filter>win32</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Classes\AppDelegate.h">
@@ -40,18 +28,6 @@
<Filter>win32</Filter>
</ClInclude>
<ClInclude Include="resource.h" />
<ClInclude Include="..\Classes\ide-support\CodeIDESupport.h">
<Filter>Classes\ide-support</Filter>
</ClInclude>
<ClInclude Include="..\Classes\ide-support\RuntimeJsImpl.h">
<Filter>Classes\ide-support</Filter>
</ClInclude>
<ClInclude Include="..\Classes\ide-support\SimpleConfigParser.h">
<Filter>Classes\ide-support</Filter>
</ClInclude>
<ClInclude Include="SimulatorWin.h">
<Filter>win32</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="game.rc">

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