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

This commit is contained in:
Dhilan007 2014-03-11 16:16:07 +08:00
commit b72d009eac
93 changed files with 6659 additions and 368 deletions

View File

@ -1,6 +1,7 @@
language: cpp
env:
matrix:
- GEN_BINDING=YES
- GEN_COCOS_FILES=YES
- PLATFORM=linux DEBUG=1 CC_COMPILER=gcc CXX_COMPILER=g++
- PLATFORM=linux DEBUG=1 CC_COMPILER=clang CXX_COMPILER=clang++

View File

@ -1 +1 @@
9d96920492b534e8c2a60312607d083fc3c87f81
727d9ca089cf00365014b23ae2cf63341316ba7d

View File

@ -231,7 +231,7 @@ void ClippingNode::visit(Renderer *renderer, const kmMat4 &parentTransform, bool
#else
// since glAlphaTest do not exists in OES, use a shader that writes
// pixel only if greater than an alpha threshold
GLProgram *program = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST);
GLProgram *program = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV);
GLint alphaValueLocation = glGetUniformLocation(program->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
// set our alphaThreshold
program->use();

View File

@ -49,6 +49,7 @@ typedef struct _hashUniformEntry
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR = "ShaderPositionTextureColor";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP = "ShaderPositionTextureColor_noMVP";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST = "ShaderPositionTextureColorAlphaTest";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV = "ShaderPositionTextureColorAlphaTest_NoMV";
const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor";
const char* GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP = "ShaderPositionColor_noMVP";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture";

View File

@ -82,6 +82,7 @@ public:
static const char* SHADER_NAME_POSITION_TEXTURE_COLOR;
static const char* SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP;
static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST;
static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV;
static const char* SHADER_NAME_POSITION_COLOR;
static const char* SHADER_NAME_POSITION_COLOR_NO_MVP;
static const char* SHADER_NAME_POSITION_TEXTURE;

View File

@ -36,6 +36,7 @@ enum {
kShaderType_PositionTextureColor,
kShaderType_PositionTextureColor_noMVP,
kShaderType_PositionTextureColorAlphaTest,
kShaderType_PositionTextureColorAlphaTestNoMV,
kShaderType_PositionColor,
kShaderType_PositionColor_noMVP,
kShaderType_PositionTexture,
@ -118,6 +119,10 @@ void ShaderCache::loadDefaultShaders()
loadDefaultShader(p, kShaderType_PositionTextureColorAlphaTest);
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST, p) );
// Position Texture Color alpha test
p = new GLProgram();
loadDefaultShader(p, kShaderType_PositionTextureColorAlphaTestNoMV);
_programs.insert( std::make_pair(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV, p) );
//
// Position, Color shader
//
@ -199,6 +204,10 @@ void ShaderCache::reloadDefaultShaders()
p->reset();
loadDefaultShader(p, kShaderType_PositionTextureColorAlphaTest);
// Position Texture Color alpha test
p = getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV);
p->reset();
loadDefaultShader(p, kShaderType_PositionTextureColorAlphaTestNoMV);
//
// Position, Color shader
//
@ -288,6 +297,15 @@ void ShaderCache::loadDefaultShader(GLProgram *p, int type)
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS);
break;
case kShaderType_PositionTextureColorAlphaTestNoMV:
p->initWithByteArrays(ccPositionTextureColor_noMVP_vert, ccPositionTextureColorAlphaTest_frag);
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS);
break;
case kShaderType_PositionColor:
p->initWithByteArrays(ccPositionColor_vert ,ccPositionColor_frag);

View File

@ -43,440 +43,461 @@ ActionNode::ActionNode()
, _object(nullptr)
, _frameArrayNum(0)
{
_frameArrayNum = (int)kKeyframeMax;
for(int i = 0; i < _frameArrayNum; i++)
{
_frameArray.push_back( new cocos2d::Vector<ActionFrame*>());
}
_frameArrayNum = (int)kKeyframeMax;
for(int i = 0; i < _frameArrayNum; i++)
{
_frameArray.push_back( new cocos2d::Vector<ActionFrame*>());
}
}
ActionNode::~ActionNode()
{
if (_action == nullptr)
{
CC_SAFE_RELEASE_NULL(_actionSpawn);
}
else
{
CC_SAFE_RELEASE_NULL(_action);
}
if (_action == nullptr)
{
CC_SAFE_RELEASE_NULL(_actionSpawn);
}
else
{
CC_SAFE_RELEASE_NULL(_action);
}
for (auto object : _frameArray)
{
object->clear();
CC_SAFE_DELETE(object);
}
_frameArray.clear();
_frameArray.clear();
}
void ActionNode::initWithDictionary(const rapidjson::Value& dic, Ref* root)
{
setActionTag(DICTOOL->getIntValue_json(dic, "ActionTag"));
int actionFrameCount = DICTOOL->getArrayCount_json(dic, "actionframelist");
for (int i=0; i<actionFrameCount; i++) {
setActionTag(DICTOOL->getIntValue_json(dic, "ActionTag"));
int actionFrameCount = DICTOOL->getArrayCount_json(dic, "actionframelist");
for (int i=0; i<actionFrameCount; i++)
{
const rapidjson::Value& actionFrameDic = DICTOOL->getDictionaryFromArray_json(dic, "actionframelist", i);
int frameInex = DICTOOL->getIntValue_json(actionFrameDic,"frameid");
const rapidjson::Value& actionFrameDic = DICTOOL->getDictionaryFromArray_json(dic, "actionframelist", i);
int frameInex = DICTOOL->getIntValue_json(actionFrameDic,"frameid");
int frameTweenType = DICTOOL->getIntValue_json(actionFrameDic,"tweenType");
bool existPosition = DICTOOL->checkObjectExist_json(actionFrameDic,"positionx");
if (existPosition)
{
float positionX = DICTOOL->getFloatValue_json(actionFrameDic, "positionx");
float positionY = DICTOOL->getFloatValue_json(actionFrameDic, "positiony");
ActionMoveFrame* actionFrame = new ActionMoveFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setPosition(Point(positionX, positionY));
auto cActionArray = _frameArray.at((int)kKeyframeMove);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
std::vector<float> frameTweenParameter;
int frameTweenParameterNum = DICTOOL->getArrayCount_json(actionFrameDic, "tweenParameter");
bool existScale = DICTOOL->checkObjectExist_json(actionFrameDic,"scalex");
if (existScale)
{
float scaleX = DICTOOL->getFloatValue_json(actionFrameDic, "scalex");
float scaleY = DICTOOL->getFloatValue_json(actionFrameDic, "scaley");
ActionScaleFrame* actionFrame = new ActionScaleFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setScaleX(scaleX);
actionFrame->setScaleY(scaleY);
auto cActionArray = _frameArray.at((int)kKeyframeScale);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
for (int j = 0; j < frameTweenParameterNum; j++)
{
float value = DICTOOL->getFloatValueFromArray_json(actionFrameDic, "tweenParameter", j);
frameTweenParameter.push_back(value);
}
bool existRotation = DICTOOL->checkObjectExist_json(actionFrameDic,"rotation");
if (existRotation)
{
float rotation = DICTOOL->getFloatValue_json(actionFrameDic, "rotation");
ActionRotationFrame* actionFrame = new ActionRotationFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setRotation(rotation);
auto cActionArray = _frameArray.at((int)kKeyframeRotate);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
bool existOpacity = DICTOOL->checkObjectExist_json(actionFrameDic,"opacity");
if (existOpacity)
{
int opacity = DICTOOL->getIntValue_json(actionFrameDic, "opacity");
ActionFadeFrame* actionFrame = new ActionFadeFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setOpacity(opacity);
auto cActionArray = _frameArray.at((int)kKeyframeTint);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
bool existPosition = DICTOOL->checkObjectExist_json(actionFrameDic,"positionx");
if (existPosition)
{
float positionX = DICTOOL->getFloatValue_json(actionFrameDic, "positionx");
float positionY = DICTOOL->getFloatValue_json(actionFrameDic, "positiony");
ActionMoveFrame* actionFrame = new ActionMoveFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setEasingType(frameTweenType);
actionFrame->setEasingParameter(frameTweenParameter);
actionFrame->setPosition(Point(positionX, positionY));
auto cActionArray = _frameArray.at((int)kKeyframeMove);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
bool existColor = DICTOOL->checkObjectExist_json(actionFrameDic,"colorr");
if (existColor)
{
int colorR = DICTOOL->getIntValue_json(actionFrameDic, "colorr");
int colorG = DICTOOL->getIntValue_json(actionFrameDic, "colorg");
int colorB = DICTOOL->getIntValue_json(actionFrameDic, "colorb");
ActionTintFrame* actionFrame = new ActionTintFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setColor(Color3B(colorR,colorG,colorB));
auto cActionArray = _frameArray.at((int)kKeyframeFade);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
}
initActionNodeFromRoot(root);
bool existScale = DICTOOL->checkObjectExist_json(actionFrameDic,"scalex");
if (existScale)
{
float scaleX = DICTOOL->getFloatValue_json(actionFrameDic, "scalex");
float scaleY = DICTOOL->getFloatValue_json(actionFrameDic, "scaley");
ActionScaleFrame* actionFrame = new ActionScaleFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setEasingType(frameTweenType);
actionFrame->setEasingParameter(frameTweenParameter);
actionFrame->setScaleX(scaleX);
actionFrame->setScaleY(scaleY);
auto cActionArray = _frameArray.at((int)kKeyframeScale);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
bool existRotation = DICTOOL->checkObjectExist_json(actionFrameDic,"rotation");
if (existRotation)
{
float rotation = DICTOOL->getFloatValue_json(actionFrameDic, "rotation");
ActionRotationFrame* actionFrame = new ActionRotationFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setEasingType(frameTweenType);
actionFrame->setEasingParameter(frameTweenParameter);
actionFrame->setRotation(rotation);
auto cActionArray = _frameArray.at((int)kKeyframeRotate);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
bool existOpacity = DICTOOL->checkObjectExist_json(actionFrameDic,"opacity");
if (existOpacity)
{
int opacity = DICTOOL->getIntValue_json(actionFrameDic, "opacity");
ActionFadeFrame* actionFrame = new ActionFadeFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setEasingType(frameTweenType);
actionFrame->setEasingParameter(frameTweenParameter);
actionFrame->setOpacity(opacity);
auto cActionArray = _frameArray.at((int)kKeyframeTint);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
bool existColor = DICTOOL->checkObjectExist_json(actionFrameDic,"colorr");
if (existColor)
{
int colorR = DICTOOL->getIntValue_json(actionFrameDic, "colorr");
int colorG = DICTOOL->getIntValue_json(actionFrameDic, "colorg");
int colorB = DICTOOL->getIntValue_json(actionFrameDic, "colorb");
ActionTintFrame* actionFrame = new ActionTintFrame();
actionFrame->setFrameIndex(frameInex);
actionFrame->setEasingType(frameTweenType);
actionFrame->setEasingParameter(frameTweenParameter);
actionFrame->setColor(Color3B(colorR,colorG,colorB));
auto cActionArray = _frameArray.at((int)kKeyframeFade);
cActionArray->pushBack(actionFrame);
actionFrame->release();
}
}
initActionNodeFromRoot(root);
}
void ActionNode::initActionNodeFromRoot(Ref* root)
{
Node* rootNode = dynamic_cast<Node*>(root);
if (rootNode != nullptr)
{
Widget* rootWidget = dynamic_cast<Widget*>(root);
if (rootWidget != nullptr)
{
Widget* widget = Helper::seekActionWidgetByActionTag(rootWidget, getActionTag());
if (widget != nullptr)
{
setObject(widget);
}
}
Node* rootNode = dynamic_cast<Node*>(root);
if (rootNode != nullptr)
{
Widget* rootWidget = dynamic_cast<Widget*>(root);
if (rootWidget != nullptr)
{
Widget* widget = Helper::seekActionWidgetByActionTag(rootWidget, getActionTag());
if (widget != nullptr)
{
setObject(widget);
}
}
}
}
void ActionNode::setUnitTime(float fTime)
{
_fUnitTime = fTime;
this->refreshActionProperty();
_fUnitTime = fTime;
this->refreshActionProperty();
}
float ActionNode::getUnitTime()
{
return _fUnitTime;
return _fUnitTime;
}
void ActionNode::setActionTag(int tag)
{
_actionTag = tag;
_actionTag = tag;
}
int ActionNode::getActionTag()
{
return _actionTag;
return _actionTag;
}
void ActionNode::setObject(Ref* node)
{
_object = node;
_object = node;
}
Ref* ActionNode::getObject()
{
return _object;
return _object;
}
Node* ActionNode::getActionNode()
{
Node* cNode = dynamic_cast<Node*>(_object);
if (cNode != nullptr)
{
return cNode;
}
else
{
Widget* rootWidget = dynamic_cast<Widget*>(_object);
if (rootWidget != nullptr)
{
return rootWidget;
}
}
return nullptr;
Node* cNode = dynamic_cast<Node*>(_object);
if (cNode != nullptr)
{
return cNode;
}
else
{
Widget* rootWidget = dynamic_cast<Widget*>(_object);
if (rootWidget != nullptr)
{
return rootWidget;
}
}
return nullptr;
}
void ActionNode::insertFrame(int index, ActionFrame* frame)
{
if (frame == nullptr)
{
return;
}
int frameType = frame->getFrameType();
if(frameType < _frameArray.size())
{
auto cArray = _frameArray.at(frameType);
cArray->insert(index, frame);
}
if (frame == nullptr)
{
return;
}
int frameType = frame->getFrameType();
if(frameType < _frameArray.size())
{
auto cArray = _frameArray.at(frameType);
cArray->insert(index, frame);
}
}
void ActionNode::addFrame(ActionFrame* frame)
{
if (frame == nullptr)
{
return;
}
int frameType = frame->getFrameType();
if (frame == nullptr)
{
return;
}
int frameType = frame->getFrameType();
if(frameType < _frameArray.size())
{
auto cArray = _frameArray.at(frameType);
cArray->pushBack(frame);
}
if(frameType < _frameArray.size())
{
auto cArray = _frameArray.at(frameType);
cArray->pushBack(frame);
}
}
void ActionNode::deleteFrame(ActionFrame* frame)
{
if (frame == nullptr)
{
return;
}
int frameType = frame->getFrameType();
if(frameType < _frameArray.size())
{
auto cArray = _frameArray.at(frameType);
cArray->eraseObject(frame);
}
if (frame == nullptr)
{
return;
}
int frameType = frame->getFrameType();
if(frameType < _frameArray.size())
{
auto cArray = _frameArray.at(frameType);
cArray->eraseObject(frame);
}
}
void ActionNode::clearAllFrame()
{
for(auto array : _frameArray)
{
array->clear();
}
for(auto array : _frameArray)
{
array->clear();
}
}
Spawn * ActionNode::refreshActionProperty()
{
if ( _object == nullptr )
{
return nullptr;
}
Vector<FiniteTimeAction*> cSpawnArray;
if ( _object == nullptr )
{
return nullptr;
}
Vector<FiniteTimeAction*> cSpawnArray;
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->size() <= 0)
{
continue;
}
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->size() <= 0)
{
continue;
}
Vector<FiniteTimeAction*> cSequenceArray;
auto frameCount = cArray->size();
for (int i = 0; i < frameCount; i++)
{
auto frame = cArray->at(i);
if (i == 0)
{
}
else
{
auto srcFrame = cArray->at(i-1);
float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex()) * getUnitTime();
Action* cAction = frame->getAction(duration);
if(cAction != nullptr)
cSequenceArray.pushBack(static_cast<FiniteTimeAction*>(cAction));
}
}
Sequence* cSequence = Sequence::create(cSequenceArray);
if (cSequence != nullptr)
{
cSpawnArray.pushBack(cSequence);
}
}
Vector<FiniteTimeAction*> cSequenceArray;
auto frameCount = cArray->size();
for (int i = 0; i < frameCount; i++)
{
auto frame = cArray->at(i);
if (i == 0)
{
}
else
{
auto srcFrame = cArray->at(i-1);
float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex()) * getUnitTime();
Action* cAction = frame->getAction(duration);
if(cAction != nullptr)
cSequenceArray.pushBack(static_cast<FiniteTimeAction*>(cAction));
}
}
Sequence* cSequence = Sequence::create(cSequenceArray);
if (cSequence != nullptr)
{
cSpawnArray.pushBack(cSequence);
}
}
if (_action == nullptr)
{
CC_SAFE_RELEASE_NULL(_actionSpawn);
}
else
{
CC_SAFE_RELEASE_NULL(_action);
}
if (_action == nullptr)
{
CC_SAFE_RELEASE_NULL(_actionSpawn);
}
else
{
CC_SAFE_RELEASE_NULL(_action);
}
_actionSpawn = Spawn::create(cSpawnArray);
CC_SAFE_RETAIN(_actionSpawn);
return _actionSpawn;
_actionSpawn = Spawn::create(cSpawnArray);
CC_SAFE_RETAIN(_actionSpawn);
return _actionSpawn;
}
void ActionNode::playAction()
{
if ( _object == nullptr || _actionSpawn == nullptr)
{
return;
}
if ( _object == nullptr || _actionSpawn == nullptr)
{
return;
}
if (_action!=nullptr)
{
_action->release();
}
if (_action!=nullptr)
{
_action->release();
}
_action = Sequence::create(_actionSpawn, nullptr);
_action->retain();
_action = Sequence::create(_actionSpawn, nullptr);
_action->retain();
this->runAction();
this->runAction();
}
void ActionNode::runAction()
{
Node* cNode = this->getActionNode();
if (cNode != nullptr && _action != nullptr)
{
cNode->runAction(_action);
}
Node* cNode = this->getActionNode();
if (cNode != nullptr && _action != nullptr)
{
cNode->runAction(_action);
}
}
void ActionNode::stopAction()
{
Node* cNode = this->getActionNode();
if (cNode != nullptr && _action != nullptr)
{
cNode->stopAction(_action);
}
Node* cNode = this->getActionNode();
if (cNode != nullptr && _action != nullptr)
{
cNode->stopAction(_action);
}
}
int ActionNode::getFirstFrameIndex()
{
int frameindex = 99999;
bool bFindFrame = false;
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->empty())
{
continue;
}
bFindFrame = true;
auto frame = cArray->at(0);
int iFrameIndex = frame->getFrameIndex();
int frameindex = 99999;
bool bFindFrame = false;
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->empty())
{
continue;
}
bFindFrame = true;
auto frame = cArray->at(0);
int iFrameIndex = frame->getFrameIndex();
if (frameindex > iFrameIndex)
{
frameindex = iFrameIndex;
}
}
if (!bFindFrame)
{
frameindex = 0;
}
return frameindex;
if (frameindex > iFrameIndex)
{
frameindex = iFrameIndex;
}
}
if (!bFindFrame)
{
frameindex = 0;
}
return frameindex;
}
int ActionNode::getLastFrameIndex()
{
int frameindex = -1;
bool bFindFrame = false;
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->empty())
{
continue;
}
bFindFrame = true;
ssize_t lastInex = cArray->size() - 1;
auto frame = cArray->at(lastInex);
int iFrameIndex = frame->getFrameIndex();
int frameindex = -1;
bool bFindFrame = false;
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->empty())
{
continue;
}
bFindFrame = true;
ssize_t lastInex = cArray->size() - 1;
auto frame = cArray->at(lastInex);
int iFrameIndex = frame->getFrameIndex();
if (frameindex < iFrameIndex)
{
frameindex = iFrameIndex;
}
}
if (!bFindFrame)
{
frameindex = 0;
}
return frameindex;
if (frameindex < iFrameIndex)
{
frameindex = iFrameIndex;
}
}
if (!bFindFrame)
{
frameindex = 0;
}
return frameindex;
}
bool ActionNode::updateActionToTimeLine(float fTime)
{
bool bFindFrame = false;
bool bFindFrame = false;
ActionFrame* srcFrame = nullptr;
// ActionFrame* destFrame = nullptr;
ActionFrame* srcFrame = nullptr;
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->empty())
{
continue;
}
ssize_t frameCount = cArray->size();
for (int i = 0; i < frameCount; i++)
{
auto frame = cArray->at(i);
for (int n = 0; n < _frameArrayNum; n++)
{
auto cArray = _frameArray.at(n);
if (cArray->empty())
{
continue;
}
ssize_t frameCount = cArray->size();
for (int i = 0; i < frameCount; i++)
{
auto frame = cArray->at(i);
if (frame->getFrameIndex()*getUnitTime() == fTime)
{
this->easingToFrame(1.0f,1.0f,nullptr,frame);
bFindFrame = true;
break;
}
else if (frame->getFrameIndex()*getUnitTime() > fTime)
{
if (i == 0)
{
this->easingToFrame(1.0f,1.0f,nullptr,frame);
bFindFrame = false;
}
else
{
srcFrame = cArray->at(i-1);
float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex())*getUnitTime();
float delaytime = fTime - srcFrame->getFrameIndex()*getUnitTime();
this->easingToFrame(duration,1.0f,nullptr,srcFrame);
//float easingTime = ActionFrameEasing::bounceTime(delaytime);
this->easingToFrame(duration,delaytime/duration,srcFrame,frame);
bFindFrame = true;
}
break;
}
}
}
return bFindFrame;
if (frame->getFrameIndex()*getUnitTime() == fTime)
{
this->easingToFrame(1.0f,1.0f,nullptr,frame);
bFindFrame = true;
break;
}
else if (frame->getFrameIndex()*getUnitTime() > fTime)
{
if (i == 0)
{
this->easingToFrame(1.0f,1.0f,nullptr,frame);
bFindFrame = false;
}
else
{
srcFrame = cArray->at(i-1);
float duration = (frame->getFrameIndex() - srcFrame->getFrameIndex())*getUnitTime();
float delaytime = fTime - srcFrame->getFrameIndex()*getUnitTime();
this->easingToFrame(duration,1.0f,nullptr,srcFrame);
//float easingTime = ActionFrameEasing::bounceTime(delaytime);
this->easingToFrame(duration,delaytime/duration,srcFrame,frame);
bFindFrame = true;
}
break;
}
}
}
return bFindFrame;
}
void ActionNode::easingToFrame(float duration,float delayTime,ActionFrame* srcFrame,ActionFrame* destFrame)
{
Action* cAction = destFrame->getAction(duration,srcFrame);
Node* cNode = this->getActionNode();
if (cAction == nullptr || cNode == nullptr)
{
return;
}
cAction->startWithTarget(cNode);
cAction->update(delayTime);
Action* cAction = destFrame->getAction(duration,srcFrame);
Node* cNode = this->getActionNode();
if (cAction == nullptr || cNode == nullptr)
{
return;
}
cAction->startWithTarget(cNode);
cAction->update(delayTime);
}
bool ActionNode::isActionDoneOnce()
{
if (_action == nullptr)
{
return true;
}
return _action->isDone();
if (_action == nullptr)
{
return true;
}
return _action->isDone();
}
}

View File

@ -217,11 +217,11 @@ void Button::loadTextureNormal(const char* normal,TextureResType texType)
}
}
_normalTextureSize = _buttonNormalRenderer->getContentSize();
normalTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_buttonNormalRenderer);
normalTextureScaleChangedWithSize();
_normalTextureLoaded = true;
}
@ -265,11 +265,11 @@ void Button::loadTexturePressed(const char* selected,TextureResType texType)
}
}
_pressedTextureSize = _buttonClickedRenderer->getContentSize();
pressedTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_buttonDisableRenderer);
pressedTextureScaleChangedWithSize();
_pressedTextureLoaded = true;
}
@ -313,11 +313,11 @@ void Button::loadTextureDisabled(const char* disabled,TextureResType texType)
}
}
_disabledTextureSize = _buttonDisableRenderer->getContentSize();
disabledTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_buttonDisableRenderer);
disabledTextureScaleChangedWithSize();
_disabledTextureLoaded = true;
}

View File

@ -130,11 +130,11 @@ void CheckBox::loadTextureBackGround(const char *backGround,TextureResType texTy
default:
break;
}
backGroundTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_backGroundBoxRenderer);
backGroundTextureScaleChangedWithSize();
}
void CheckBox::loadTextureBackGroundSelected(const char *backGroundSelected,TextureResType texType)
@ -156,11 +156,11 @@ void CheckBox::loadTextureBackGroundSelected(const char *backGroundSelected,Text
default:
break;
}
backGroundSelectedTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_backGroundSelectedBoxRenderer);
backGroundSelectedTextureScaleChangedWithSize();
}
void CheckBox::loadTextureFrontCross(const char *cross,TextureResType texType)
@ -182,11 +182,11 @@ void CheckBox::loadTextureFrontCross(const char *cross,TextureResType texType)
default:
break;
}
frontCrossTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_frontCrossRenderer);
frontCrossTextureScaleChangedWithSize();
}
void CheckBox::loadTextureBackGroundDisabled(const char *backGroundDisabled,TextureResType texType)
@ -208,11 +208,11 @@ void CheckBox::loadTextureBackGroundDisabled(const char *backGroundDisabled,Text
default:
break;
}
backGroundDisabledTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_backGroundBoxDisabledRenderer);
backGroundDisabledTextureScaleChangedWithSize();
}
void CheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,TextureResType texType)
@ -234,11 +234,11 @@ void CheckBox::loadTextureFrontCrossDisabled(const char *frontCrossDisabled,Text
default:
break;
}
frontCrossDisabledTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_frontCrossDisabledRenderer);
frontCrossDisabledTextureScaleChangedWithSize();
}
void CheckBox::onTouchEnded(Touch *touch, Event *unusedEvent)

View File

@ -112,11 +112,11 @@ void ImageView::loadTexture(const char *fileName, TextureResType texType)
break;
}
_imageTextureSize = _imageRenderer->getContentSize();
imageTextureScaleChangedWithSize();
updateAnchorPoint();
updateFlippedX();
updateFlippedY();
updateRGBAToRenderer(_imageRenderer);
imageTextureScaleChangedWithSize();
}
void ImageView::setTextureRect(const Rect &rect)

View File

@ -44,11 +44,11 @@ PhysicsContact::PhysicsContact()
, _eventCode(EventCode::NONE)
, _info(nullptr)
, _notificationEnable(true)
, _begin(false)
, _result(true)
, _data(nullptr)
, _contactInfo(nullptr)
, _contactData(nullptr)
, _preContactData(nullptr)
{
}
@ -57,6 +57,7 @@ PhysicsContact::~PhysicsContact()
{
CC_SAFE_DELETE(_info);
CC_SAFE_DELETE(_contactData);
CC_SAFE_DELETE(_preContactData);
}
PhysicsContact* PhysicsContact::construct(PhysicsShape* a, PhysicsShape* b)
@ -96,7 +97,8 @@ void PhysicsContact::generateContactData()
}
cpArbiter* arb = static_cast<cpArbiter*>(_contactInfo);
CC_SAFE_DELETE(_contactData);
CC_SAFE_DELETE(_preContactData);
_preContactData = _contactData;
_contactData = new PhysicsContactData();
_contactData->count = cpArbiterGetCount(arb);
for (int i=0; i<_contactData->count && i<PhysicsContactData::POINT_MAX; ++i)
@ -108,15 +110,13 @@ void PhysicsContact::generateContactData()
}
// PhysicsContactPreSolve implementation
PhysicsContactPreSolve::PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo)
: _preContactData(data)
, _contactInfo(contactInfo)
PhysicsContactPreSolve::PhysicsContactPreSolve(void* contactInfo)
: _contactInfo(contactInfo)
{
}
PhysicsContactPreSolve::~PhysicsContactPreSolve()
{
CC_SAFE_DELETE(_preContactData);
}
float PhysicsContactPreSolve::getRestitution() const
@ -217,7 +217,6 @@ void EventListenerPhysicsContact::onEvent(EventCustom* event)
if (onContactBegin != nullptr
&& hitTest(contact->getShapeA(), contact->getShapeB()))
{
contact->_begin = true;
contact->generateContactData();
ret = onContactBegin(*contact);
}
@ -232,8 +231,7 @@ void EventListenerPhysicsContact::onEvent(EventCustom* event)
if (onContactPreSolve != nullptr
&& hitTest(contact->getShapeA(), contact->getShapeB()))
{
PhysicsContactPreSolve solve(contact->_begin ? nullptr : contact->_contactData, contact->_contactInfo);
contact->_begin = false;
PhysicsContactPreSolve solve(contact->_contactInfo);
contact->generateContactData();
ret = onContactPreSolve(*contact, solve);

View File

@ -78,6 +78,8 @@ public:
inline PhysicsShape* getShapeB() const { return _shapeB; }
/** get contact data */
inline const PhysicsContactData* getContactData() const { return _contactData; }
/** get previous contact data */
inline const PhysicsContactData* getPreContactData() const { return _preContactData; }
/** get data. */
inline void* getData() const { return _data; }
/**
@ -112,12 +114,12 @@ private:
EventCode _eventCode;
PhysicsContactInfo* _info;
bool _notificationEnable;
bool _begin;
bool _result;
void* _data;
void* _contactInfo;
PhysicsContactData* _contactData;
PhysicsContactData* _preContactData;
friend class EventListenerPhysicsContact;
friend class PhysicsWorldCallback;
@ -146,14 +148,10 @@ public:
void ignore();
private:
PhysicsContactPreSolve(PhysicsContactData* data, void* contactInfo);
PhysicsContactPreSolve(void* contactInfo);
~PhysicsContactPreSolve();
private:
float _elasticity;
float _friction;
Point _surfaceVelocity;
PhysicsContactData* _preContactData;
void* _contactInfo;
friend class EventListenerPhysicsContact;

View File

@ -78,6 +78,12 @@
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#Node] getChildByName
-- @param self
-- @param #string str
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- @function [parent=#Node] updateDisplayedOpacity
-- @param self
@ -204,6 +210,11 @@
-- @param self
-- @param #cc.Node node
--------------------------------
-- @function [parent=#Node] getName
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @function [parent=#Node] getRotation3D
-- @param self
@ -379,6 +390,11 @@
-- @param #int int
-- @return Action#Action ret (return value: cc.Action)
--------------------------------
-- @function [parent=#Node] setName
-- @param self
-- @param #string str
--------------------------------
-- overload function: setAdditionalTransform(cc.AffineTransform)
--

View File

@ -11,6 +11,11 @@
-- @param self
-- @return PhysicsContact::EventCode#PhysicsContact::EventCode ret (return value: cc.PhysicsContact::EventCode)
--------------------------------
-- @function [parent=#PhysicsContact] getPreContactData
-- @param self
-- @return PhysicsContactData#PhysicsContactData ret (return value: cc.PhysicsContactData)
--------------------------------
-- @function [parent=#PhysicsContact] getShapeA
-- @param self

View File

@ -1 +1 @@
b13893cb4ba1a930cf74e33ea68728455cb31f4a
0a7af9a7041d3864365f2f28e3ad16c35c24f34b

View File

@ -1532,6 +1532,9 @@ int register_all_cocos2dx(lua_State* tolua_S);

View File

@ -1 +1 @@
6f6bb7571ab92f9757a753c243a5061fd64a3fbd
9ee0235aac42ea657853d56947716b3fc8fee2c2

View File

@ -261,6 +261,7 @@ int register_all_cocos2dx_physics(lua_State* tolua_S);
#endif // __cocos2dx_physics_h__

View File

@ -25,6 +25,13 @@ THE SOFTWARE.
****************************************************************************"""
'''
This script will install environment variables needed to by cocos2d-x. It will set these envrironment variables:
* COCOS_CONSOLE_ROOT: used to run cocos console tools, more information about cocos console tools please refer to
https://github.com/cocos2d/cocos2d-console
* NDK_ROOT: used to build android native codes
* ANDROID_SDK_ROOT: used to generate applicatoin on Android through commands
* ANT_ROOT: used to generate applicatoin on Android through commands
On Max OS X, when start a shell, it will read these files and execute commands in sequence:
~/.bash_profile
@ -44,17 +51,18 @@ Will create ~/.bash_profile when none of them exist, and add environment variabl
import os
import sys
import fileinput
import subprocess
from optparse import OptionParser
COCOS_CONSOLE_ROOT = 'COCOS_CONSOLE_ROOT'
NDK_ROOT = 'NDK_ROOT'
ANDROID_SDK_ROOT = 'ANDROID_SDK_ROOT'
ANT_ROOT = 'ANT_ROOT'
class SetEnvVar(object):
def __init__(self, ndk=None, android_sdk=None):
def __init__(self):
self.current_absolute_path = os.path.dirname(os.path.realpath(__file__))
self.android_sdk_root = android_sdk
self.file_used_for_setup = ''
def _isWindows(self):
@ -124,7 +132,7 @@ class SetEnvVar(object):
file.write('export %s=%s\n' % (key, value))
file.write('export PATH=$%s:$PATH\n' % key)
if key == ANDROID_SDK_ROOT:
file.write('export PATH=$%s/sdk/tools:$%s/sdk/platform-tools:$PATH\n' % (key, key))
file.write('export PATH=$%s/tools:$%s/platform-tools:$PATH\n' % (key, key))
file.close()
return True
@ -183,7 +191,7 @@ class SetEnvVar(object):
_winreg.CloseKey(env)
return False
def _get_input_value(self, sys_var):
def _get_input_value(self):
return raw_input('\tPlease enter its path (or press Enter to skip): ')
@ -263,12 +271,26 @@ class SetEnvVar(object):
if not android_sdk_root:
return False
android_path = os.path.join(android_sdk_root, 'sdk/tools/android')
android_path = os.path.join(android_sdk_root, 'tools/android')
if os.path.isfile(android_path):
return True
else:
return False
def _is_ant_root_valid(self, ant_root):
ant_path = ''
if self._isWindows():
ant_path = os.path.join(ant_root, 'ant.exe')
else:
ant_path = os.path.join(ant_root, 'ant')
if os.path.isfile(ant_path):
return True
else:
return False
def set_console_root(self):
print ""
@ -284,7 +306,7 @@ class SetEnvVar(object):
return False
def set_environment_variables(self, ndk_root, android_sdk_root):
def set_environment_variables(self, ndk_root, android_sdk_root, ant_root):
print '\nSetting up cocos2d-x...'
@ -303,9 +325,9 @@ class SetEnvVar(object):
if not ndk_root and not ndk_root_found:
print "NOT FOUND"
ndk_root = self._get_input_value(NDK_ROOT)
ndk_root = self._get_input_value()
if ndk_root != "" and not self._is_ndk_root_valid(ndk_root) and not ndk_root_found:
if ndk_root and not self._is_ndk_root_valid(ndk_root) and not ndk_root_found:
print 'Error: %s is not a valid path of NDK_ROOT. Ignoring it.' % ndk_root
if ndk_root_found:
@ -329,9 +351,9 @@ class SetEnvVar(object):
if not android_sdk_root and not android_sdk_root_found:
print "NOT FOUND"
android_sdk_root = self._get_input_value(ANDROID_SDK_ROOT)
android_sdk_root = self._get_input_value()
if android_sdk_root != "" and not self._is_android_sdk_root_valid(android_sdk_root) and not android_sdk_root_found:
if android_sdk_root and not self._is_android_sdk_root_valid(android_sdk_root) and not android_sdk_root_found:
print 'Error: %s is not a valid path of ANDROID_SDK_ROOT. Ignoring it.' % android_sdk_root
if android_sdk_root_found:
@ -344,12 +366,36 @@ class SetEnvVar(object):
print ' -> Added: %s = %s' % (ANDROID_SDK_ROOT, android_sdk_root)
#
# ANT_ROOT
#
print ""
print '-> Looking for ANT_ROOT envrironment variable...',
ant_root_added = False
ant_found = self._find_environment_variable(ANT_ROOT)
if not ant_root and not ant_found:
print 'NOT FOUND'
ant_root = self._get_input_value()
if ant_root and not self._is_ant_root_valid(ant_root) and not ant_found:
print 'Error: %s is not a valid path of ANT_ROOT. Ignoring it.' % ant_root
if ant_found:
print 'FOUND'
else:
if ant_root and self._is_ant_root_valid(ant_root):
if self._set_environment_variable(ANT_ROOT, ant_root):
ant_root_added = True
print 'ADDED'
print ' -> Added: %s = %s' % (ANT_ROOT, ant_root)
if self._isWindows():
target = 'registry'
else:
target = self.file_used_for_setup
if console_added or ndk_root_added or android_sdk_root_added:
if console_added or ndk_root_added or android_sdk_root_added or ant_root_added:
print '\nSet up successfull:'
if console_added:
@ -358,15 +404,23 @@ class SetEnvVar(object):
print '\tNDK_ROOT was added into %s' % target
if android_sdk_root_added:
print '\tANDROID_SDK_ROOT was added into %s' % target
if ant_root_added:
print '\tANT_ROOT was added into %s' % target
else:
print '\nCOCOS_CONSOLE_ROOT was already added. Edit "%s" for manual changes' % target
print '\nCOCOS_CONSOLE_ROOT was already added. Edit "%s" for manual changes' % target
if self._isWindows():
print '\nPlease restart the terminal to make added system variables take effect'
else:
print '\nPlease execute command: "source %s" to make added system variables take effect' % target
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-n', '--ndkroot', dest='ndk_root', help='directory of ndk root')
parser.add_option('-a', '--androidsdkroot', dest='android_sdk_root', help='directory of android sdk root')
parser.add_option('-t', '--antroot', dest='ant_root', help='directory of ant root')
opts, args = parser.parse_args()
# set environment variables
env = SetEnvVar()
env.set_environment_variables(opts.ndk_root, opts.android_sdk_root)
env.set_environment_variables(opts.ndk_root, opts.android_sdk_root, opts.ant_root)

View File

@ -0,0 +1,66 @@
#include "AppDelegate.h"
#include "CCLuaEngine.h"
#include "SimpleAudioEngine.h"
#include "cocos2d.h"
#include "Runtime.h"
using namespace CocosDenshion;
USING_NS_CC;
using namespace std;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
SimpleAudioEngine::end();
}
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLView::createWithRect("Test Lua", Rect(0,0,900,640));
director->setOpenGLView(glview);
}
glview->setDesignResolutionSize(480, 320, ResolutionPolicy::NO_BORDER);
// turn on display FPS
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
#ifdef COCOS2D_DEBUG
startRuntime();
#else
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
engine->executeScriptFile("src/main.lua");
#endif
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
Director::getInstance()->stopAnimation();
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
Director::getInstance()->startAnimation();
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}

View File

@ -0,0 +1,38 @@
#ifndef __APP_DELEGATE_H__
#define __APP_DELEGATE_H__
#include "cocos2d.h"
/**
@brief The cocos2d Application.
The reason for implement as private inheritance is to hide some interface call by Director.
*/
class AppDelegate : private cocos2d::Application
{
public:
AppDelegate();
virtual ~AppDelegate();
/**
@brief Implement Director and Scene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
*/
virtual bool applicationDidFinishLaunching();
/**
@brief The function be called when the application enter background
@param the pointer of the application
*/
virtual void applicationDidEnterBackground();
/**
@brief The function be called when the application enter foreground
@param the pointer of the application
*/
virtual void applicationWillEnterForeground();
};
#endif // __APP_DELEGATE_H__

View File

@ -0,0 +1,588 @@
/****************************************************************************
Copyright (c) 2013 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 "Runtime.h"
#include "lua_debugger.h"
#include "CCLuaEngine.h"
#include "cocos2d.h"
#ifdef _WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#endif
#include <vector>
#include <string>
using namespace std;
using namespace cocos2d;
extern string getIPAddress();
extern string getProjSearchPath();
void startScript(string strDebugArg)
{
// register lua engine
auto engine = LuaEngine::getInstance();
if (!strDebugArg.empty())
{
engine->executeString(strDebugArg.c_str());
}
cocos2d::log("debug args = %s",strDebugArg.c_str());
engine->executeScriptFile("src/main.lua");
}
void reloadScript()
{
LuaEngine::getInstance()->reload("src/main.lua");
}
class VisibleRect
{
public:
static Rect getVisibleRect();
static Point left();
static Point right();
static Point top();
static Point bottom();
static Point center();
static Point leftTop();
static Point rightTop();
static Point leftBottom();
static Point rightBottom();
private:
static void lazyInit();
static Rect s_visibleRect;
};
Rect VisibleRect::s_visibleRect;
void VisibleRect::lazyInit()
{
// no lazy init
// Useful if we change the resolution in runtime
s_visibleRect = Director::getInstance()->getOpenGLView()->getVisibleRect();
}
Rect VisibleRect::getVisibleRect()
{
lazyInit();
return s_visibleRect;
}
Point VisibleRect::left()
{
lazyInit();
return Point(s_visibleRect.origin.x, s_visibleRect.origin.y+s_visibleRect.size.height/2);
}
Point VisibleRect::right()
{
lazyInit();
return Point(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y+s_visibleRect.size.height/2);
}
Point VisibleRect::top()
{
lazyInit();
return Point(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y+s_visibleRect.size.height);
}
Point VisibleRect::bottom()
{
lazyInit();
return Point(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y);
}
Point VisibleRect::center()
{
lazyInit();
return Point(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y+s_visibleRect.size.height/2);
}
Point VisibleRect::leftTop()
{
lazyInit();
return Point(s_visibleRect.origin.x, s_visibleRect.origin.y+s_visibleRect.size.height);
}
Point VisibleRect::rightTop()
{
lazyInit();
return Point(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y+s_visibleRect.size.height);
}
Point VisibleRect::leftBottom()
{
lazyInit();
return s_visibleRect.origin;
}
Point VisibleRect::rightBottom()
{
lazyInit();
return Point(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y);
}
class ConnectWaitLayer: public Layer
{
public:
ConnectWaitLayer()
{
string strip = getIPAddress();
char szIPAddress[512]={0};
sprintf(szIPAddress, "LocalIP: %s",strip.c_str());
auto label = LabelTTF::create(szIPAddress, "Arial", 24);
addChild(label, 9999);
label->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y - 30) );
auto labelwait = LabelTTF::create("wait transfer files ...", "Arial", 22);
addChild(labelwait, 10000);
labelwait->setPosition( Point(VisibleRect::center().x, VisibleRect::center().y) );
auto labelPlay = LabelTTF::create("play", "Arial", 20);
auto menuItem = MenuItemLabel::create(labelPlay, CC_CALLBACK_1(ConnectWaitLayer::playerCallback, this));
auto menu = Menu::create(menuItem, NULL);
menu->setPosition( Point::ZERO );
menuItem->setPosition( Point( VisibleRect::right().x - 50, VisibleRect::bottom().y + 25) );
addChild(menu, 1);
//_scheduler = CCDirector::sharedDirector()->getScheduler();
//scheduleUpdate();
}
void playerCallback(Object* sender)
{
startScript("");
}
};
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <io.h>
#include <WS2tcpip.h>
#define bzero(a, b) memset(a, 0, b);
#else
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/un.h>
#endif
class FileServer
{
public:
FileServer()
{
_listenfd = -1;
_running = false;
_endThread = false;
_writepath = FileUtils::getInstance()->getWritablePath();
}
bool listenOnTCP(int port);
void stop();
private:
bool recv_file(int fd);
void addClient();
void loop();
// file descriptor: socket, console, etc.
int _listenfd;
int _maxfd;
std::vector<int> _fds;
std::thread _thread;
fd_set _read_set;
bool _running;
bool _endThread;
std::string _writepath;
};
bool FileServer::listenOnTCP(int port)
{
int listenfd, n;
const int on = 1;
struct addrinfo hints, *res, *ressave;
char serv[30];
snprintf(serv, sizeof(serv)-1, "%d", port );
serv[sizeof(serv)-1]=0;
bzero(&hints, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_INET; // AF_UNSPEC: Do we need IPv6 ?
hints.ai_socktype = SOCK_STREAM;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
WSADATA wsaData;
n = WSAStartup(MAKEWORD(2, 2),&wsaData);
#endif
if ( (n = getaddrinfo(NULL, serv, &hints, &res)) != 0) {
fprintf(stderr,"net_listen error for %s: %s", serv, gai_strerror(n));
return false;
}
ressave = res;
do {
listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (listenfd < 0)
continue; /* error, try next one */
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
if (::bind(listenfd, res->ai_addr, res->ai_addrlen) == 0)
break; /* success */
close(listenfd); /* bind error, close and try next one */
} while ( (res = res->ai_next) != NULL);
if (res == NULL) {
perror("net_listen:");
freeaddrinfo(ressave);
return false;
}
listen(listenfd, 1);
if (res->ai_family == AF_INET)
{
char buf[INET_ADDRSTRLEN] = "";
struct sockaddr_in *sin = (struct sockaddr_in*) res->ai_addr;
if( inet_ntop(res->ai_family, &sin->sin_addr, buf, sizeof(buf)) != NULL )
cocos2d::log("Console: listening on %s : %d", buf, ntohs(sin->sin_port));
else
perror("inet_ntop");
} else if (res->ai_family == AF_INET6)
{
char buf[INET6_ADDRSTRLEN] = "";
struct sockaddr_in6 *sin = (struct sockaddr_in6*) res->ai_addr;
if( inet_ntop(res->ai_family, &sin->sin6_addr, buf, sizeof(buf)) != NULL )
cocos2d::log("Console: listening on %s : %d", buf, ntohs(sin->sin6_port));
else
perror("inet_ntop");
}
freeaddrinfo(ressave);
_listenfd = listenfd;
_thread = std::thread( std::bind( &FileServer::loop, this) );
return true;
}
void FileServer::stop()
{
if( _running ) {
_endThread = true;
_thread.join();
}
}
string& replace_all(string& str,const string& old_value,const string& new_value)
{
while(true)
{
int pos=0;
if((pos=str.find(old_value,0))!=string::npos)
str.replace(pos,old_value.length(),new_value);
else break;
}
return str;
}
bool CreateDir(const char *sPathName)
{
char DirName[256]={0};
strcpy(DirName, sPathName);
int i,len = strlen(DirName);
if(DirName[len-1]!='/')
strcat(DirName, "/");
len = strlen(DirName);
for(i=1; i<len; i++)
{
if(DirName[i]=='/')
{
DirName[i] = 0;
if(access(DirName, NULL)!=0 )
{
#ifdef _WIN32
if(mkdir(DirName/*, 0755*/)==-1)
#else
if(mkdir(DirName, 0755)==-1)
#endif
{
perror("mkdir error");
return false;
}
}
DirName[i] = '/';
}
}
return true;
}
bool FileServer::recv_file(int fd)
{
char buffer[1024]={0};
char namelen[4]={0};
if (recv(fd, namelen, 4,0)<=0) {
return false;
}
if (recv(fd, buffer, atoi(namelen),0)<=0) {
return false;
}
char fullfilename[1024]={0};
sprintf(fullfilename,"%s%s",_writepath.c_str(),buffer);
string file(fullfilename);
file=replace_all(file,"\\","/");
sprintf(fullfilename, "%s", file.c_str());
cocos2d::log("recv fullfilename = %s",fullfilename);
CreateDir(file.substr(0,file.find_last_of("/")).c_str());
FILE *fp =fopen(fullfilename, "wb");
int length =0;
while ((length=recv(fd, fullfilename, sizeof(fullfilename),0)) > 0) {
fwrite(fullfilename, sizeof(char), length,fp);
}
fclose(fp);
return true;
}
void FileServer::addClient()
{
struct sockaddr client;
socklen_t client_len;
/* new client */
client_len = sizeof( client );
int fd = accept(_listenfd, (struct sockaddr *)&client, &client_len );
// add fd to list of FD
if( fd != -1 ) {
FD_SET(fd, &_read_set);
_fds.push_back(fd);
_maxfd = std::max(_maxfd,fd);
}
}
void FileServer::loop()
{
fd_set copy_set;
struct timeval timeout, timeout_copy;
_running = true;
FD_ZERO(&_read_set);
FD_SET(_listenfd, &_read_set);
_maxfd = _listenfd;
timeout.tv_sec = 0;
/* 0.016 seconds. Wake up once per frame at 60PFS */
timeout.tv_usec = 16000;
while(!_endThread) {
copy_set = _read_set;
timeout_copy = timeout;
int nready = select(_maxfd+1, &copy_set, NULL, NULL, &timeout_copy);
if( nready == -1 )
{
/* error */
if(errno != EINTR)
log("Abnormal error in select()\n");
continue;
}
else if( nready == 0 )
{
/* timeout. do somethig ? */
}
else
{
/* new client */
if(FD_ISSET(_listenfd, &copy_set)) {
addClient();
if(--nready <= 0)
continue;
}
/* data from client */
std::vector<int> to_remove;
for(const auto &fd: _fds) {
if(FD_ISSET(fd,&copy_set)) {
if( ! recv_file(fd) ) {
to_remove.push_back(fd);
}
if(--nready <= 0)
break;
}
}
/* remove closed conections */
for(int fd: to_remove) {
FD_CLR(fd, &_read_set);
_fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end());
}
}
}
// clean up: ignore stdin, stdout and stderr
for(const auto &fd: _fds )
close(fd);
close(_listenfd);
_running = false;
}
class ConsoleCustomCommand
{
public:
ConsoleCustomCommand():_fileserver(nullptr)
{
_writepath = FileUtils::getInstance()->getWritablePath();
cocos2d::Console *_console = Director::getInstance()->getConsole();
static struct Console::Command commands[] = {
{"shutdownapp","exit runtime app",std::bind(&ConsoleCustomCommand::onShutDownApp, this, std::placeholders::_1, std::placeholders::_2)},
{"start-logic","run game logic script.Arg:[debugArg]",std::bind(&ConsoleCustomCommand::onRunLogicScript, this, std::placeholders::_1, std::placeholders::_2)},
{"reload","reload script.Args:[filepath]",std::bind(&ConsoleCustomCommand::onReloadScriptFile, this, std::placeholders::_1, std::placeholders::_2)},
};
for (int i=0;i< sizeof(commands)/sizeof(Console::Command);i++) {
_console->addCommand(commands[i]);
}
_console->listenOnTCP(5678);
_fileserver=new FileServer();
_fileserver->listenOnTCP(6666);
}
~ConsoleCustomCommand()
{
_fileserver->stop();
if (_fileserver) {
delete _fileserver;
_fileserver = nullptr;
}
}
void onRunLogicScript(int fd, const std::string &args)
{
Director::getInstance()->getScheduler()->performFunctionInCocosThread([=](){
char szDebugArg[1024]={0};
sprintf(szDebugArg, "require('debugger')(%s,'%s')",args.c_str(),_writepath.c_str());
startScript(szDebugArg);
});
}
void onReloadScriptFile(int fd,const std::string &args)
{
Director::getInstance()->getScheduler()->performFunctionInCocosThread([](){
reloadScript();
});
}
void onShutDownApp(int fd, const std::string &args)
{
Director::getInstance()->getScheduler()->performFunctionInCocosThread([](){
exit(0);
});
}
private:
FileServer* _fileserver;
string _writepath;
};
void startRuntime()
{
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
luaopen_debugger(engine->getLuaStack()->getLuaState());
static ConsoleCustomCommand s_customCommand;
vector<string> searchPathArray;
searchPathArray=FileUtils::getInstance()->getSearchPaths();
vector<string> writePathArray;
writePathArray.push_back(FileUtils::getInstance()->getWritablePath());
FileUtils::getInstance()->setSearchPaths(writePathArray);
for (unsigned i = 0; i < searchPathArray.size(); i++)
{
FileUtils::getInstance()->addSearchPath(searchPathArray[i]);
}
auto scene = Scene::create();
auto layer = new ConnectWaitLayer();
layer->autorelease();
auto director = Director::getInstance();
scene->addChild(layer);
director->runWithScene(scene);
}
// SimulatorConfig
SimulatorConfig *SimulatorConfig::s_sharedInstance = NULL;
SimulatorConfig *SimulatorConfig::getInstance(void)
{
if (!s_sharedInstance)
{
s_sharedInstance = new SimulatorConfig();
}
return s_sharedInstance;
}
SimulatorConfig::SimulatorConfig(void)
{
m_screenSizeArray.push_back(SimulatorScreenSize("iPhone 3Gs (480x320)", 480, 320));
m_screenSizeArray.push_back(SimulatorScreenSize("iPhone 4 (960x640)", 960, 640));
m_screenSizeArray.push_back(SimulatorScreenSize("iPhone 5 (1136x640)", 1136, 640));
m_screenSizeArray.push_back(SimulatorScreenSize("iPad (1024x768)", 1024, 768));
m_screenSizeArray.push_back(SimulatorScreenSize("iPad Retina (2048x1536)", 2048, 1536));
m_screenSizeArray.push_back(SimulatorScreenSize("Android (800x480)", 800, 480));
m_screenSizeArray.push_back(SimulatorScreenSize("Android (854x480)", 854, 480));
m_screenSizeArray.push_back(SimulatorScreenSize("Android (960x540)", 960, 540));
m_screenSizeArray.push_back(SimulatorScreenSize("Android (1024x600)", 1024, 600));
m_screenSizeArray.push_back(SimulatorScreenSize("Android (1280x720)", 1280, 720));
m_screenSizeArray.push_back(SimulatorScreenSize("Android (1280x800)", 1280, 800));
m_screenSizeArray.push_back(SimulatorScreenSize("Android (1920x1080)", 1920, 1080));
}
int SimulatorConfig::getScreenSizeCount(void)
{
return (int)m_screenSizeArray.size();
}
const SimulatorScreenSize SimulatorConfig::getScreenSize(int index)
{
return m_screenSizeArray.at(index);
}

View File

@ -0,0 +1,68 @@
/****************************************************************************
Copyright (c) 2013 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.
****************************************************************************/
#ifndef _RUNTIME__H_
#define _RUNTIME__H_
#include <string>
#include <vector>
using namespace std;
void startRuntime();
void reloadScript();
// SimulatorConfig
typedef struct _SimulatorScreenSize {
string title;
int width;
int height;
_SimulatorScreenSize(const string title_, int width_, int height_)
{
title = title_;
width = width_;
height = height_;
}
} SimulatorScreenSize;
typedef vector<SimulatorScreenSize> ScreenSizeArray;
class SimulatorConfig
{
public:
static SimulatorConfig *getInstance(void);
// predefined screen size
int getScreenSizeCount(void);
const SimulatorScreenSize getScreenSize(int index);
private:
SimulatorConfig(void);
static SimulatorConfig *s_sharedInstance;
ScreenSizeArray m_screenSizeArray;
};
#endif // _RUNTIME__H_

View File

@ -0,0 +1,436 @@
#! /usr/bin/env python
# coding=utf-8
# filename=build_runtime.py
import os
import re
import sys
import shutil
import platform
import subprocess
if platform.system() == 'Windows':
import _winreg
def checkParams():
"""Custom and check param list.
"""
from optparse import OptionParser
# set the parser to parse input params
# the correspond variable name of "-x, --xxx" is parser.xxx
if platform.system() == "Darwin":
parser = OptionParser(
usage="Usage: %prog -p <android|ios|mac>\n\
Sample: %prog -p ios"
)
parser.add_option(
"-p",
"--platform",
metavar="PLATFORM",
type="choice",
choices=["android", "ios", "mac"],
help="Set build runtime's platform"
)
elif platform.system() == "Windows":
parser = OptionParser(
usage="Usage: %prog -p <win32|android>\n\
Sample: %prog -p win32"
)
parser.add_option(
"-p",
"--platform",
metavar="PLATFORM",
type="choice",
choices=["win32", "android"],
help="Set build runtime's platform"
)
parser.add_option(
"-u",
"--pure",
dest="pure",
action="store_true",
help="parameter for copy resource"
)
# parse the params
(opts, args) = parser.parse_args()
if not opts.platform:
parser.error("-p or --platform is not specified")
if not opts.pure:
return opts.platform, None
return opts.platform, opts.pure
class BuildRuntime:
def __init__(self, platform, pure):
self.projectPath = None
self.projectName = None
self.runtimePlatform = platform
self.pure = pure
scriptPath = os.path.abspath(os.path.dirname(__file__))
if platform == 'win32':
self.projectPath = os.path.join(scriptPath, "proj.win32")
elif platform == 'android':
self.projectPath = os.path.join(scriptPath, "proj.android")
elif platform == 'ios':
self.projectPath = os.path.join(scriptPath, "proj.ios_mac")
elif platform == 'mac':
self.projectPath = os.path.join(scriptPath, "proj.ios_mac")
def buildRuntime(self):
if self.runtimePlatform == 'win32':
self.win32Runtime()
elif self.runtimePlatform == 'android':
self.androidRuntime()
if self.runtimePlatform == 'ios':
self.iosRuntime()
if self.runtimePlatform == 'mac':
self.macRuntime()
def macRuntime(self):
commands = [
"xcodebuild",
"-version"
]
child = subprocess.Popen(commands, stdout=subprocess.PIPE)
xcode = None
version = None
for line in child.stdout:
if 'Xcode' in line:
xcode, version = str.split(line, ' ')
child.wait()
if xcode is None:
print ("Xcode wasn't installed")
return False
if version <= '5':
print ("Update xcode please")
return False
res = self.checkFileByExtention(".xcodeproj")
if not res:
print ("Can't find the \".xcodeproj\" file")
return False
projectPath = os.path.join(self.projectPath, self.projectName)
pbxprojectPath = os.path.join(projectPath, "project.pbxproj")
print(pbxprojectPath)
f = file(pbxprojectPath)
contents = f.read()
section = re.search(
r"Begin PBXProject section.*End PBXProject section",
contents,
re.S
)
if section is None:
print ("Can't find Mac target")
return False
targets = re.search(r"targets = (.*);", section.group(), re.S)
if targets is None:
print ("Can't find Mac target")
return False
targetName = None
names = re.split("\*", targets.group())
for name in names:
if "Mac" in name:
targetName = str.strip(name)
if targetName is None:
print ("Can't find Mac target")
return False
macFolder = os.path.join(self.projectPath, "..", "..", "..", "runtime", "mac")
if os.path.isdir(macFolder):
shutil.rmtree(macFolder)
commands = [
"xcodebuild",
"-project",
projectPath,
"-configuration",
"Debug",
"-target",
targetName,
"CONFIGURATION_BUILD_DIR=%s" % (macFolder)
]
child = subprocess.Popen(commands, stdout=subprocess.PIPE)
for line in child.stdout:
print (line)
child.wait()
filelist = os.listdir(macFolder)
for filename in filelist:
name, extention = os.path.splitext(filename)
if extention == '.a':
filename = os.path.join(macFolder, filename)
os.remove(filename)
if extention == '.app':
filename = os.path.join(macFolder, filename)
if ' ' in name:
newname = os.path.join(macFolder, name[:name.find(' ')]+extention)
os.rename(filename, newname)
def iosRuntime(self):
commands = [
"xcodebuild",
"-version"
]
child = subprocess.Popen(commands, stdout=subprocess.PIPE)
xcode = None
version = None
for line in child.stdout:
if 'Xcode' in line:
xcode, version = str.split(line, ' ')
child.wait()
if xcode is None:
print ("Xcode wasn't installed")
return False
if version <= '5':
print ("Update xcode please")
return False
res = self.checkFileByExtention(".xcodeproj")
if not res:
print ("Can't find the \".xcodeproj\" file")
return False
projectPath = os.path.join(self.projectPath, self.projectName)
pbxprojectPath = os.path.join(projectPath, "project.pbxproj")
print(pbxprojectPath)
f = file(pbxprojectPath)
contents = f.read()
section = re.search(r"Begin PBXProject section.*End PBXProject section", contents, re.S)
if section is None:
print ("Can't find iOS target")
return False
targets = re.search(r"targets = (.*);", section.group(), re.S)
if targets is None:
print ("Can't find iOS target")
return False
targetName = None
names = re.split("\*", targets.group())
for name in names:
if "iOS" in name:
targetName = str.strip(name)
if targetName is None:
print ("Can't find iOS target")
return False
iosFolder = os.path.join(self.projectPath, "..", "..","..", "runtime", "ios")
if os.path.isdir(iosFolder):
filelist = os.listdir(iosFolder)
for filename in filelist:
if ".app" in filename:
f = os.path.join(iosFolder, filename)
shutil.rmtree(f)
commands = [
"xcodebuild",
"-project",
projectPath,
"-configuration",
"Debug",
"-target",
targetName,
"-sdk",
"iphonesimulator",
"CONFIGURATION_BUILD_DIR=%s" % (iosFolder)
]
child = subprocess.Popen(commands, stdout=subprocess.PIPE)
for line in child.stdout:
print (line)
child.wait()
filelist = os.listdir(iosFolder)
for filename in filelist:
name, extention = os.path.splitext(filename)
if extention == '.a':
filename = os.path.join(iosFolder, filename)
os.remove(filename)
if extention == '.app':
filename = os.path.join(iosFolder, filename)
newname = os.path.join(iosFolder, name[:name.find(' ')]+extention)
os.rename(filename, newname)
def androidRuntime(self):
try:
SDK_ROOT = os.environ['ANDROID_SDK_ROOT']
except Exception:
print ("ANDROID_SDK_ROOT not defined.\
Please define ANDROID_SDK_ROOT in your environment")
return False
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print ("NDK_ROOT not defined.\
Please define NDK_ROOT in your environment")
return False
platformsPath = os.path.join(SDK_ROOT,"platforms")
if not os.path.isdir(platformsPath):
print ("Can't find android platforms")
return False
projectProperties = os.path.join(self.projectPath, "project.properties")
androidVersion = None
if os.path.isfile(projectProperties):
f = file(projectProperties, 'r')
while True:
line = f.readline()
if "target=" in line and not "#" in line:
androidVersion = line[line.find('-')+1:]
break
if len(line) == 0:
break
if androidVersion is None:
platforms = os.listdir(platformsPath)
versions = []
for platform in platforms:
if "android-" in platform:
version = platform[platform.find('-')+1:]
versions.append(version)
versions = [x for x in map(float, versions) if x > 10.0]
if len(versions) == 0:
print ("Please update your android sdk")
return False
androidVersion = min(versions)
if androidVersion is None or int(androidVersion) < 10:
print ("Please update your android sdk or reset android sdk version in the project.properties file")
return False
buildNative = os.path.join(self.projectPath, "build_native.py")
if not os.path.isdir(self.projectPath) or not os.path.isfile(buildNative):
print ("Can't find the build_native.py")
return False
sys.path.append(self.projectPath)
from build_native import build
build(None, str(int(androidVersion)), None, self.pure)
def win32Runtime(self):
try:
vs = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\VisualStudio"
)
msbuild = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\MSBuild\ToolsVersions"
)
except WindowsError:
print ("Visual Studio wasn't installed")
return False
vsPath = None
i = 0
try:
while True:
version = _winreg.EnumKey(vs, i)
try:
if float(version) >= 11.0:
key = _winreg.OpenKey(vs, r"SxS\VS7")
vsPath,type = _winreg.QueryValueEx(key, version)
except:
pass
i += 1
except WindowsError:
pass
if vsPath is None:
print("Can't find the Visual Studio's path in the regedit")
return False
msbuildPath = None
i = 0
try:
while True:
version = _winreg.EnumKey(msbuild,i)
try:
if float(version) >= 4.0:
key = _winreg.OpenKey(msbuild, version)
msbuildPath, type = _winreg.QueryValueEx(
key,
"MSBuildToolsPath"
)
except:
pass
i += 1
except WindowsError:
pass
if msbuildPath is None:
print ("Can't find the MSBuildTools' path in the regedit")
return False
res = self.checkFileByExtention(".sln")
if not res:
print ("Can't find the \".sln\" file")
return False
msbuildPath = os.path.join(msbuildPath, "MSBuild.exe")
projectPath = os.path.join(self.projectPath, self.projectName)
commands = [
msbuildPath,
projectPath,
"/maxcpucount:4",
"/t:build",
"/p:configuration=Debug"
]
child = subprocess.Popen(commands, stdout=subprocess.PIPE)
for line in child.stdout:
print (line)
child.wait()
return True
def checkFileByExtention(self, ext, path=None):
filelist = ""
if path is None:
filelist = os.listdir(self.projectPath)
else:
filelist = os.listdir(path)
for file in filelist:
name, extention = os.path.splitext(file)
if extention == ext:
self.projectName = file
return True
return False
if __name__ == '__main__':
platform, pure = checkParams();
buildRuntime = BuildRuntime(platform, pure)
buildRuntime.buildRuntime()

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>HelloLua</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,4 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.source=1.6

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.cocos2dx.hellolua"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9"/>
<uses-feature android:glEsVersion="0x00020000" />
<application android:label="@string/app_name"
android:icon="@drawable/icon">
<activity android:name="org.cocos2dx.lua.Cocos2dxActivity"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:configChanges="orientation">
<!-- Tell NativeActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="cocos2dlua" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<supports-screens android:anyDensity="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

View File

@ -0,0 +1,17 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked into Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.

View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="HelloLua" default="debug">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>

View File

@ -0,0 +1,193 @@
#!/usr/bin/python
# build_native.py
# Build native codes
import sys
import os, os.path
import shutil
from optparse import OptionParser
def get_num_of_cpu():
''' The build process can be accelerated by running multiple concurrent job processes using the -j-option.
'''
try:
platform = sys.platform
if platform == 'win32':
if 'NUMBER_OF_PROCESSORS' in os.environ:
return int(os.environ['NUMBER_OF_PROCESSORS'])
else:
return 1
else:
from numpy.distutils import cpuinfo
return cpuinfo.cpu._getNCPUs()
except Exception:
print "Can't know cpuinfo, use default 1 cpu"
return 1
def check_environment_variables_sdk():
''' Checking the environment ANDROID_SDK_ROOT, which will be used for building
'''
try:
SDK_ROOT = os.environ['ANDROID_SDK_ROOT']
except Exception:
print "ANDROID_SDK_ROOT not defined. Please define ANDROID_SDK_ROOT in your environment"
sys.exit(1)
return SDK_ROOT
def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
'''
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print "NDK_ROOT not defined. Please define NDK_ROOT in your environment"
sys.exit(1)
return NDK_ROOT
def select_toolchain_version():
'''Because ndk-r8e uses gcc4.6 as default. gcc4.6 doesn't support c++11. So we should select gcc4.7 when
using ndk-r8e. But gcc4.7 is removed in ndk-r9, so we should determine whether gcc4.7 exist.
Conclution:
ndk-r8e -> use gcc4.7
ndk-r9 -> use gcc4.8
'''
ndk_root = check_environment_variables()
if os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.8")):
os.environ['NDK_TOOLCHAIN_VERSION'] = '4.8'
print "The Selected NDK toolchain version was 4.8 !"
elif os.path.isdir(os.path.join(ndk_root,"toolchains/arm-linux-androideabi-4.7")):
os.environ['NDK_TOOLCHAIN_VERSION'] = '4.7'
print "The Selected NDK toolchain version was 4.7 !"
else:
print "Couldn't find the gcc toolchain."
exit(1)
def check_ant_variables():
''' Checking the environment ANT, which will be used for package
'''
try:
ANT_PATH = os.environ['ANT_PATH']
except Exception:
print "ANT_PATH not defined. Please define ANT_PATH in your environment"
sys.exit(1)
return ANT_PATH
def do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,android_platform,build_mode):
ndk_path = os.path.join(ndk_root, "ndk-build")
# windows should use ";" to seperate module paths
platform = sys.platform
if platform == 'win32':
ndk_module_path = 'NDK_MODULE_PATH=%s/..;%s/../external;%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root, cocos_root, cocos_root)
else:
ndk_module_path = 'NDK_MODULE_PATH=%s/..:%s/../external:%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root, cocos_root, cocos_root)
num_of_cpu = get_num_of_cpu()
if ndk_build_param == None:
command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path)
else:
command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path)
if os.system(command) != 0:
raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!")
elif android_platform is not None:
sdk_tool_path = os.path.join(sdk_root, "tools/android")
cocoslib_path = os.path.join(cocos_root, "cocos/2d/platform/android/java")
command = '%s update lib-project -t %s -p %s' % (sdk_tool_path,android_platform,cocoslib_path)
if os.system(command) != 0:
raise Exception("update cocos lib-project [ " + cocoslib_path + " ] fails!")
command = '%s update project -t %s -p %s -s' % (sdk_tool_path,android_platform,app_android_root)
if os.system(command) != 0:
raise Exception("update project [ " + app_android_root + " ] fails!")
ant_path=check_ant_variables()
ant_path = os.path.join(ant_path, "ant")
buildfile_path = os.path.join(app_android_root, "build.xml")
command = '%s clean %s -f %s -Dsdk.dir=%s' % (ant_path,build_mode,buildfile_path,sdk_root)
os.system(command)
def copy_files(src, dst):
for item in os.listdir(src):
path = os.path.join(src, item)
# Android can not package the file that ends with ".gz"
if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path):
shutil.copy(path, dst)
if os.path.isdir(path):
new_dst = os.path.join(dst, item)
os.makedirs(new_dst)
copy_files(path, new_dst)
def copy_resources(app_android_root, build_mode, pure):
# remove app_android_root/assets if it exists
assets_dir = os.path.join(app_android_root, "assets")
if os.path.isdir(assets_dir):
shutil.rmtree(assets_dir)
# copy resources
os.mkdir(assets_dir)
if pure is None:
assets_res_dir = assets_dir + "/res";
assets_scripts_dir = assets_dir + "/scripts";
os.mkdir(assets_res_dir);
os.mkdir(assets_scripts_dir);
resources_dir = os.path.join(app_android_root, "../../../res")
copy_files(resources_dir, assets_res_dir)
resources_dir = os.path.join(app_android_root, "../../../src")
copy_files(resources_dir, assets_scripts_dir)
# lua project should copy lua script
resources_dir = os.path.join(app_android_root, "../../lua-bindings/bindings/script")
copy_files(resources_dir, assets_dir)
def build(ndk_build_param,android_platform,build_mode,pure):
ndk_root = check_environment_variables()
sdk_root = None
select_toolchain_version()
current_dir = os.path.dirname(os.path.realpath(__file__))
cocos_root = os.path.join(current_dir, "../../lua-bindings/cocos2d-x")
app_android_root = current_dir
copy_resources(app_android_root, build_mode, pure)
if android_platform is not None:
sdk_root = check_environment_variables_sdk()
if android_platform.isdigit():
android_platform = 'android-'+android_platform
else:
print 'please use vaild android platform'
exit(1)
if build_mode is None:
build_mode = 'debug'
elif build_mode != 'release':
build_mode = 'debug'
do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,android_platform,build_mode)
# -------------- main --------------
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-n", "--ndk", dest="ndk_build_param", help='parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform",
help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]')
parser.add_option("-b", "--build", dest="build_mode",
help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
parser.add_option("-u", "--pure", dest="pure", help='parameter for copy resource')
(opts, args) = parser.parse_args()
build(opts.ndk_build_param,opts.android_platform,opts.build_mode,opts.pure)

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="custom_rules">
<target name="-post-build">
<!-- delete temp files -->
<delete>
<fileset dir="${out.absolute.dir}" includes="build.prop resources.ap_ ${dex.file.name}* ${resource.package.file.name}* ${ant.project.name}-release-unaligned.apk ${ant.project.name}-release-unsigned.apk*"/>
</delete>
<!-- rename final apk file -->
<property name="apk.final.name" value="${out.absolute.dir}/../../../../runtime/android/${ant.project.name}" />
<move file="${out.final.file}" tofile="${apk.final.name}.apk" />
</target>
</project>

View File

@ -0,0 +1,24 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := cocos2dlua_shared
LOCAL_MODULE_FILENAME := libcocos2dlua
LOCAL_SRC_FILES := hellolua/main.cpp \
hellolua/Runtime_android.cpp \
../../Classes/AppDelegate.cpp \
../../Classes/Runtime.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \
$(LOCAL_PATH)/../../cocos2d/external/lua/tolua
LOCAL_STATIC_LIBRARIES := curl_static_prebuilt
LOCAL_WHOLE_STATIC_LIBRARIES := cocos_lua_static
include $(BUILD_SHARED_LIBRARY)
$(call import-module,bindings)

View File

@ -0,0 +1,4 @@
APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char
APP_CPPFLAGS += -fexceptions

View File

@ -0,0 +1,54 @@
#include <jni.h>
#include <android/log.h>
#include "jni/JniHelper.h"
#include <string>
#include <vector>
using namespace std;
using namespace cocos2d;
string getSDCardPath();
string getProjSearchPath()
{
extern std::string getPackageNameJNI();
string searchPath = getSDCardPath();
searchPath += "/";
searchPath += getPackageNameJNI();
return searchPath;
}
vector<string> getSearchPath()
{
extern std::string getPackageNameJNI();
vector<string> searchPathArray;
searchPathArray.push_back(getProjSearchPath());
return searchPathArray;
}
string getSDCardPath()
{
JniMethodInfo t;
string sdcardPath("");
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lua/Cocos2dxActivity", "getSDCardPath", "()Ljava/lang/String;")) {
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
sdcardPath = JniHelper::jstring2string(str);
t.env->DeleteLocalRef(str);
}
return sdcardPath;
}
string getIPAddress()
{
JniMethodInfo t;
string IPAddress("");
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lua/Cocos2dxActivity", "getLocalIpAddress", "()Ljava/lang/String;")) {
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
IPAddress = JniHelper::jstring2string(str);
t.env->DeleteLocalRef(str);
}
return IPAddress;
}

View File

@ -0,0 +1,16 @@
#include "AppDelegate.h"
#include "cocos2d.h"
#include "CCEventType.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>
#define LOG_TAG "main"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
using namespace cocos2d;
void cocos_android_app_init (struct android_app* app) {
LOGD("cocos_android_app_init");
AppDelegate *pAppDelegate = new AppDelegate();
}

View File

@ -0,0 +1,20 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -0,0 +1,13 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "ant.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-10
android.library.reference.1=../../lua-bindings/cocos2d-x/cocos/2d/platform/android/java

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloLua</string>
</resources>

View File

@ -0,0 +1,88 @@
package org.cocos2dx.lua;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import android.app.NativeActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class Cocos2dxActivity extends NativeActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//For supports translucency
//1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp
/*const EGLint attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
//EGL_BLUE_SIZE, 5, -->delete
//EGL_GREEN_SIZE, 6, -->delete
//EGL_RED_SIZE, 5, -->delete
EGL_BUFFER_SIZE, 32, //-->new field
EGL_DEPTH_SIZE, 16,
EGL_STENCIL_SIZE, 8,
EGL_NONE
};*/
//2.Set the format of window
// getWindow().setFormat(PixelFormat.TRANSLUCENT);
if(!isWifiConnected())
{
Toast.makeText(this, "wifi is closed!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
}
private boolean isWifiConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
}
return false;
}
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("WifiPreference IpAddress", ex.toString());
}
return null;
}
public static String getSDCardPath() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String strSDCardPathString = Environment.getExternalStorageDirectory().getPath();
return strSDCardPathString;
}
return null;
}
}

View File

@ -0,0 +1,47 @@
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <string>
#include <vector>
using namespace std;
string getProjSearchPath()
{
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
if (bundlePath != nil) {
return [bundlePath UTF8String];
}
return "";
}
vector<string> getSearchPath()
{
vector<string> searchPathArray;
return searchPathArray;
}
string getIPAddress()
{
BOOL success;
struct ifaddrs * addrs;
const struct ifaddrs * cursor;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
// the second test keeps from picking up the loopback address
if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
{
NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
if ([name isEqualToString:@"en0"]) // Wi-Fi adapter
return [[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]UTF8String];
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return "";
}

View File

@ -0,0 +1,35 @@
/****************************************************************************
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
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.
****************************************************************************/
@class RootViewController;
@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate,UIApplicationDelegate>
{
UIWindow *window;
RootViewController *viewController;
}
@end

View File

@ -0,0 +1,144 @@
/****************************************************************************
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
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.
****************************************************************************/
#import <UIKit/UIKit.h>
#import "cocos2d.h"
#import "AppController.h"
#import "AppDelegate.h"
#import "RootViewController.h"
#import "CCEAGLView.h"
@implementation AppController
#pragma mark -
#pragma mark Application lifecycle
// cocos2d application instance
static AppDelegate s_sharedApplication;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 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: 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)
{
// warning: addSubView doesn't work on iOS6
[window addSubview: viewController.view];
}
else
{
// use this method on ios6
[window setRootViewController:viewController];
}
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden: YES];
// IMPORTANT: Setting the GLView should be done after creating the RootViewController
cocos2d::GLView *glview = cocos2d::GLView::createWithEAGLView(eaglView);
cocos2d::Director::getInstance()->setOpenGLView(glview);
cocos2d::Application::getInstance()->run();
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
cocos2d::Director::getInstance()->pause();
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
cocos2d::Director::getInstance()->resume();
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
cocos2d::Application::getInstance()->applicationDidEnterBackground();
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
cocos2d::Application::getInstance()->applicationWillEnterForeground();
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
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();
}
- (void)dealloc {
[super dealloc];
}
@end

View File

@ -0,0 +1 @@
66c6d1cead373b45218424f6a82f370897e443e4

View File

@ -0,0 +1 @@
84689888a14a2123d2b39f7f2f61be8c15207479

View File

@ -0,0 +1,8 @@
//
// Prefix header for all source files of the 'HelloLua' target in the 'HelloLua' project
//
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif

View File

@ -0,0 +1,33 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2010 Ricardo Quesada
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.
****************************************************************************/
#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController {
}
- (BOOL)prefersStatusBarHidden;
@end

View File

@ -0,0 +1,105 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2010 Ricardo Quesada
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.
****************************************************************************/
#import "RootViewController.h"
#import "cocos2d.h"
#import "CCEAGLView.h"
@implementation RootViewController
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
// Override to allow orientations other than the default portrait orientation.
// This method is deprecated on ios6
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return UIInterfaceOrientationIsLandscape( interfaceOrientation );
}
// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
- (NSUInteger) supportedInterfaceOrientations{
#ifdef __IPHONE_6_0
return UIInterfaceOrientationMaskAllButUpsideDown;
#endif
}
- (BOOL) shouldAutorotate {
return YES;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]);
cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height);
}
//fix not hide status on ios7
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end

View File

@ -0,0 +1,16 @@
//
// main.m
// HelloLua
//
// Copyright __MyCompanyName__ 2011. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"AppController");
[pool release];
return retVal;
}

View File

@ -0,0 +1 @@
2040fc6fe624353ae1d3db50cd3d450f4fda5afc

View File

@ -0,0 +1,146 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="4514" systemVersion="13B42" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
<dependencies>
<deployment version="1060" defaultVersion="1090" identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="4514"/>
</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"/>
<menu title="AMainMenu" systemMenu="main" id="29">
<items>
<menuItem title="Cocos-player" id="GS6-Lb-ftA">
<menu key="submenu" title="Cocos-player" systemMenu="apple" id="YN2-V8-ty0">
<items>
<menuItem title="About Cocos-player" id="HhF-Es-coQ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-1" id="tSA-7z-LPk"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="OzD-Nm-tPt">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Services" id="TOj-vg-cDm">
<menu key="submenu" title="Services" systemMenu="services" id="e98-We-UX5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="muN-Hw-eeZ">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Hide Cocos-player" keyEquivalent="h" id="sH6-na-PTL">
<connections>
<action selector="hide:" target="-3" id="SGN-0p-7lH"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="XG8-CE-veT">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-3" id="iJd-Ba-eXG"/>
</connections>
</menuItem>
<menuItem title="Show All" id="IqD-3v-zQT">
<connections>
<action selector="unhideAllApplications:" target="-3" id="DR8-By-ymv"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="GU5-eI-OTq">
<modifierMask key="keyEquivalentModifierMask" command="YES"/>
</menuItem>
<menuItem title="Quit Cocos-player" keyEquivalent="q" id="7Z7-ot-jqY">
<connections>
<action selector="terminate:" target="-3" id="DyL-yF-GYq"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="83">
<menu key="submenu" title="File" id="81">
<items>
<menuItem title="ChangeProject" id="UUd-nT-0Tr">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="onChangeProject:" target="-1" id="KV1-nK-nLn"/>
</connections>
</menuItem>
<menuItem title="Close" keyEquivalent="w" id="611">
<connections>
<action selector="onFileClose:" target="-1" id="661"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="295" userLabel="Menu Item - View">
<menu key="submenu" title="View" id="296" userLabel="Menu - View">
<items>
<menuItem isSeparatorItem="YES" id="579"/>
<menuItem title="Portait" state="on" id="592">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="onScreenPortait:" target="-1" id="667"/>
</connections>
</menuItem>
<menuItem title="Landscape" id="593">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="onScreenLandscape:" target="-1" id="647"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="594"/>
<menuItem title="Actual (100%)" state="on" tag="100" keyEquivalent="0" id="595">
<connections>
<action selector="onScreenZoomOut:" target="-1" id="yUj-fN-Rh7"/>
</connections>
</menuItem>
<menuItem title="Zoom Out (75%)" tag="75" keyEquivalent="6" id="pqR-xy-5ip">
<connections>
<action selector="onScreenZoomOut:" target="-1" id="yps-LZ-egB"/>
</connections>
</menuItem>
<menuItem title="Zoom Out (50%)" tag="50" keyEquivalent="5" id="596">
<connections>
<action selector="onScreenZoomOut:" target="-1" id="654"/>
</connections>
</menuItem>
<menuItem title="Zoom Out (25%)" tag="25" keyEquivalent="4" id="QB8-6D-hAr">
<connections>
<action selector="onScreenZoomOut:" target="-1" id="DSu-if-D2T"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Control" id="Heh-SD-KHE">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Control" id="ysx-9J-ekz">
<items>
<menuItem title="Reload" id="hfu-OP-8X3">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="onReloadScript:" target="-1" id="ar6-Pq-fmZ"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="490">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="491"/>
</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>

View File

@ -0,0 +1,8 @@
#import <Cocoa/Cocoa.h>
@interface NSApplication (SheetAdditions)
- (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow didEndBlock:(void (^)(NSInteger returnCode))block;
@end

View File

@ -0,0 +1,22 @@
#import "NSAppSheetAdditions.h"
@implementation NSApplication (SheetAdditions)
- (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow didEndBlock:(void (^)(NSInteger returnCode))block
{
[self beginSheet:sheet
modalForWindow:docWindow
modalDelegate:self
didEndSelector:@selector(my_blockSheetDidEnd:returnCode:contextInfo:)
contextInfo:Block_copy(block)];
}
- (void)my_blockSheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
void (^block)(NSInteger returnCode) = contextInfo;
block(returnCode);
Block_release(block);
}
@end

View File

@ -0,0 +1,7 @@
//
// Prefix header for all source files of the 'Paralaxer' target in the 'Paralaxer' project
//
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#endif

View File

@ -0,0 +1,50 @@
/****************************************************************************
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>
#include "AppDelegate.h"
@interface AppController : NSObject <NSApplicationDelegate, NSWindowDelegate>
{
NSWindow *window;
NSMenu *menu;
NSFileHandle *fileHandle;
//console pipe
NSPipe *pipe;
NSFileHandle *pipeReadHandle;
}
@property (nonatomic, assign) IBOutlet NSMenu* menu;
- (IBAction) onChangeProject:(id)sender;
- (IBAction) onFileClose:(id)sender;
- (IBAction) onScreenPortait:(id)sender;
- (IBAction) onScreenLandscape:(id)sender;
- (IBAction) onScreenZoomOut:(id)sender;
- (IBAction) onReloadScript:(id)sender;
@end

View File

@ -0,0 +1,283 @@
/****************************************************************************
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.
****************************************************************************/
#import "SimulatorApp.h"
#import "WorkSpaceDialogController.h"
#import "NSAppSheetAdditions.h"
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <string>
#include <vector>
#include "AppDelegate.h"
#include "glfw3.h"
#include "glfw3native.h"
#include "Runtime.h"
#include "cocos2d.h"
using namespace cocos2d;
bool g_landscape=false;
CCSize g_screenSize;
GLView* g_eglView=NULL;
using namespace std;
using namespace cocos2d;
@implementation AppController
@synthesize menu;
-(void) dealloc
{
CCDirector::sharedDirector()->end();
[super dealloc];
}
#pragma mark -
#pragma delegates
- (void) applicationDidFinishLaunching:(NSNotification *)aNotification
{
AppDelegate app;
[self createSimulator:[NSString stringWithUTF8String:"HelloJavascript"] viewWidth:960 viewHeight:640 factor:1.0];
int ret = Application::getInstance()->run();
}
#pragma mark -
#pragma mark functions
- (void) createSimulator:(NSString*)viewName viewWidth:(float)width viewHeight:(float)height factor:(float)frameZoomFactor
{
if (g_eglView)
{
return;
}
g_eglView = GLView::createWithRect([viewName cStringUsingEncoding:NSUTF8StringEncoding],cocos2d::Rect(0.0f,0.0f,width,height),frameZoomFactor);
auto director = Director::getInstance();
director->setOpenGLView(g_eglView);
g_landscape = false;
g_screenSize.width = width;
g_screenSize.height = height;
if (width > height)
{
g_landscape = true;
}
window = glfwGetCocoaWindow(g_eglView->getWindow());
[NSApp setDelegate: self];
[self createViewMenu];
[self updateMenu];
[window center];
[window becomeFirstResponder];
[window makeKeyAndOrderFront:self];
}
- (void) createViewMenu
{
NSMenu *submenu = [[[window menu] itemWithTitle:@"View"] submenu];
for (int i = SimulatorConfig::getInstance()->getScreenSizeCount() - 1; i >= 0; --i)
{
SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(i);
NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[NSString stringWithCString:size.title.c_str() encoding:NSUTF8StringEncoding]
action:@selector(onViewChangeFrameSize:)
keyEquivalent:@""] autorelease];
[item setTag:i];
[submenu insertItem:item atIndex:0];
}
}
- (void) updateMenu
{
NSMenu *menuScreen = [[[window menu] itemWithTitle:@"View"] submenu];
NSMenuItem *itemPortait = [menuScreen itemWithTitle:@"Portait"];
NSMenuItem *itemLandscape = [menuScreen itemWithTitle:@"Landscape"];
if (g_landscape)
{
[itemPortait setState:NSOffState];
[itemLandscape setState:NSOnState];
}
else
{
[itemPortait setState:NSOnState];
[itemLandscape setState:NSOffState];
}
int scale = 100;
NSMenuItem *itemZoom100 = [menuScreen itemWithTitle:@"Actual (100%)"];
NSMenuItem *itemZoom75 = [menuScreen itemWithTitle:@"Zoom Out (75%)"];
NSMenuItem *itemZoom50 = [menuScreen itemWithTitle:@"Zoom Out (50%)"];
NSMenuItem *itemZoom25 = [menuScreen itemWithTitle:@"Zoom Out (25%)"];
[itemZoom100 setState:NSOffState];
[itemZoom75 setState:NSOffState];
[itemZoom50 setState:NSOffState];
[itemZoom25 setState:NSOffState];
if (scale == 100)
{
[itemZoom100 setState:NSOnState];
}
else if (scale == 75)
{
[itemZoom75 setState:NSOnState];
}
else if (scale == 50)
{
[itemZoom50 setState:NSOnState];
}
else if (scale == 25)
{
[itemZoom25 setState:NSOnState];
}
int width = g_screenSize.width;
int height = g_screenSize.height;
if (height > width)
{
int w = width;
width = height;
height = w;
}
int count = SimulatorConfig::getInstance()->getScreenSizeCount();
for (int i = 0; i < count; ++i)
{
bool bSel = false;
SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(i);
if (size.width == width && size.height == height)
{
bSel = true;
}
NSMenuItem *itemView = [menuScreen itemWithTitle:[NSString stringWithUTF8String:size.title.c_str()]];
[itemView setState:(bSel? NSOnState : NSOffState)];
}
//[window setTitle:[NSString stringWithFormat:@"quick-x-player (%0.0f%%)", projectConfig.getFrameScale() * 100]];
}
- (void) updateView
{
if (g_landscape)
{
glfwSetWindowSize(g_eglView->getWindow(),g_screenSize.width,g_screenSize.height);
}
else
{
glfwSetWindowSize(g_eglView->getWindow(),g_screenSize.height,g_screenSize.width);
}
[self updateMenu];
}
- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication
{
return YES;
}
- (BOOL) applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag
{
return NO;
}
- (void) windowWillClose:(NSNotification *)notification
{
[[NSRunningApplication currentApplication] terminate];
}
- (IBAction) onChangeProject:(id)sender
{
WorkSpaceDialogController *controller = [[WorkSpaceDialogController alloc] initWithWindowNibName:@"WorkSpaceDialog"];
[NSApp beginSheet:controller.window modalForWindow:window didEndBlock:^(NSInteger returnCode) {
if (returnCode == NSRunStoppedResponse)
{
CCLOG("1111");
}
[controller release];
}];
}
- (IBAction) onFileClose:(id)sender
{
[[NSApplication sharedApplication] terminate:self];
}
- (IBAction) onScreenPortait:(id)sender
{
g_landscape = false;
[self updateView];
}
- (IBAction) onScreenLandscape:(id)sender
{
g_landscape = true;
[self updateView];
}
- (IBAction) onReloadScript:(id)sender
{
reloadScript();
}
- (IBAction) onViewChangeFrameSize:(id)sender
{
NSInteger index = [sender tag];
if (index >= 0 && index < SimulatorConfig::getInstance()->getScreenSizeCount())
{
SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(index);
g_screenSize.width = size.width;
g_screenSize.height = size.height;
[self updateView];
}
}
- (IBAction) onScreenZoomOut:(id)sender
{
if ([sender state] == NSOnState) return;
float scale = (float)[sender tag] / 100.0f;
[self setZoom:scale];
}
@end

View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="4514" systemVersion="13B42" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
<dependencies>
<deployment defaultVersion="1090" identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="4514"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="WorkSpaceDialogController">
<connections>
<outlet property="textFieldProjectDirectory" destination="9" id="307"/>
<outlet property="window" destination="1" id="308"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application"/>
<window title="Change Project" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" restorable="NO" oneShot="NO" showsToolbarButton="NO" wantsToBeColor="NO" visibleAtLaunch="NO" animationBehavior="default" id="1">
<windowStyleMask key="styleMask" titled="YES" closable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="196" y="240" width="650" height="150"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1058"/>
<view key="contentView" id="2">
<rect key="frame" x="0.0" y="0.0" width="650" height="150"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="3">
<rect key="frame" x="17" y="113" width="626" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Choose Project Directory:" id="4">
<font key="font" metaFont="system"/>
<color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="9">
<rect key="frame" x="20" y="83" width="516" height="22"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" selectable="YES" editable="YES" sendsActionOnEndEditing="YES" state="on" borderStyle="bezel" drawsBackground="YES" usesSingleLineMode="YES" id="10">
<font key="font" metaFont="system"/>
<color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="15">
<rect key="frame" x="538" y="77" width="108" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Select..." bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="16">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="browseProjectDirectory:" target="-2" id="315"/>
</connections>
</button>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="290">
<rect key="frame" x="538" y="22" width="109" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Open Project" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="291">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="onOpenProject:" target="-2" id="OsS-1W-RIl"/>
</connections>
</button>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="h9P-cE-Nn4">
<rect key="frame" x="13" y="32" width="82" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Cancel" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="IHP-6G-mVo">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
<string key="keyEquivalent" base64-UTF8="YES">
Gw
</string>
</buttonCell>
<connections>
<action selector="onCancel:" target="-2" id="NeH-n8-xBM"/>
</connections>
</button>
</subviews>
</view>
</window>
</objects>
</document>

View File

@ -0,0 +1,22 @@
#import <Cocoa/Cocoa.h>
@interface WorkSpaceDialogController : NSWindowController
{
NSTextField *textFieldProjectDirectory;
NSTextField *textFieldScriptFile;
NSButton *buttonOpenProject;
}
@property (nonatomic, assign) IBOutlet NSTextField *textFieldProjectDirectory;
@property (nonatomic, assign) IBOutlet NSTextField *textFieldScriptFile;
@property (nonatomic, assign) IBOutlet NSButton *buttonOpenProject;
- (IBAction) browseProjectDirectory:(id)sender;
- (IBAction) onCancel:(id)sender;
- (IBAction) onOpenProject:(id)sender;
@end

View File

@ -0,0 +1,95 @@
#import "WorkSpaceDialogController.h"
#pragma mark -
@implementation WorkSpaceDialogController
@synthesize textFieldProjectDirectory;
@synthesize textFieldScriptFile;
@synthesize buttonOpenProject;
NSString* projectPath=nil;
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
// Initialization code here.
}
return self;
}
- (void)dealloc
{
[super dealloc];
NSLog(@"[WorkSpaceDialogController 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.
[self.window makeFirstResponder:textFieldProjectDirectory];
if (projectPath)
{
[textFieldProjectDirectory setStringValue:projectPath];
}
}
#pragma mark -
#pragma mark functions
- (NSString*) browseFolder:(NSString*)title
{
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setTitle:title];
[openDlg setCanChooseDirectories:YES];
[openDlg setCanChooseFiles:NO];
[openDlg setCanHide:YES];
[openDlg setCanCreateDirectories:NO];
[openDlg setCanSelectHiddenExtension:NO];
[openDlg setAllowsMultipleSelection:NO];
if ([openDlg runModal] == NSFileHandlingPanelOKButton)
{
NSURL *url = [openDlg.URLs objectAtIndex:0];
return [url path];
}
return nil;
}
#pragma mark -
#pragma mark outlet
- (IBAction) browseProjectDirectory:(id)sender
{
NSString *path = [self browseFolder:@"Choose Project Directory"];
if (path)
{
[textFieldProjectDirectory setStringValue:path];
}
}
- (IBAction) onCancel:(id)sender
{
[self close];
[NSApp endSheet:self.window returnCode:NSRunAbortedResponse];
}
- (IBAction) onOpenProject:(id)sender
{
if([[textFieldProjectDirectory stringValue] isEqualToString:@""])
{
NSRunAlertPanel(@"Waring",
@"Project path empty!",
@"OK", NULL, NULL);
return;
}
projectPath = [textFieldProjectDirectory stringValue];
}
@end

View File

@ -0,0 +1,7 @@
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}

View File

@ -0,0 +1,99 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "HelloLua.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}"
ProjectSection(ProjectDependencies) = postProject
{21B2C324-891F-48EA-AD1A-5AE13DE12E28} = {21B2C324-891F-48EA-AD1A-5AE13DE12E28}
{B7C2A162-DEC9-4418-972E-240AB3CBFCAE} = {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}
{DDC3E27F-004D-4DD4-9DD3-931A013D2159} = {DDC3E27F-004D-4DD4-9DD3-931A013D2159}
{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}
{207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\..\lua-bindings\cocos2d-x\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}"
ProjectSection(ProjectDependencies) = postProject
{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}
{207BC7A9-CCF1-4F2F-A04D-45F72242AE25} = {207BC7A9-CCF1-4F2F-A04D-45F72242AE25}
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6} = {F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\..\lua-bindings\cocos2d-x\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\lua-bindings\cocos2d-x\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\..\lua-bindings\cocos2d-x\cocos\audio\proj.win32\CocosDenshion.vcxproj", "{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libNetwork", "..\..\lua-bindings\cocos2d-x\cocos\network\proj.win32\libNetwork.vcxproj", "{DF2638C0-8128-4847-867C-6EAFE3DEE7B5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosBuilder", "..\..\lua-bindings\cocos2d-x\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj", "{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosStudio", "..\..\lua-bindings\cocos2d-x\cocos\editor-support\cocostudio\proj.win32\libCocosStudio.vcxproj", "{B57CF53F-2E49-4031-9822-047CC0E6BDE2}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libGUI", "..\..\lua-bindings\cocos2d-x\cocos\gui\proj.win32\libGUI.vcxproj", "{7E06E92C-537A-442B-9E4A-4761C84F8A1A}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\..\lua-bindings\cocos2d-x\cocos\editor-support\spine\proj.win32\libSpine.vcxproj", "{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\..\lua-bindings\bindings\proj.win32\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLocalStorage", "..\..\lua-bindings\cocos2d-x\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj", "{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.ActiveCfg = Debug|Win32
{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Debug|Win32.Build.0 = Debug|Win32
{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.ActiveCfg = Release|Win32
{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}.Release|Win32.Build.0 = Release|Win32
{21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.ActiveCfg = Debug|Win32
{21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Debug|Win32.Build.0 = Debug|Win32
{21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.ActiveCfg = Release|Win32
{21B2C324-891F-48EA-AD1A-5AE13DE12E28}.Release|Win32.Build.0 = Release|Win32
{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.ActiveCfg = Debug|Win32
{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Debug|Win32.Build.0 = Debug|Win32
{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.ActiveCfg = Release|Win32
{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}.Release|Win32.Build.0 = Release|Win32
{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.ActiveCfg = Debug|Win32
{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|Win32.Build.0 = Debug|Win32
{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32
{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.ActiveCfg = Debug|Win32
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Debug|Win32.Build.0 = Debug|Win32
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.ActiveCfg = Release|Win32
{F8EDD7FA-9A51-4E80-BAEB-860825D2EAC6}.Release|Win32.Build.0 = Release|Win32
{DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Debug|Win32.ActiveCfg = Debug|Win32
{DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Debug|Win32.Build.0 = Debug|Win32
{DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Release|Win32.ActiveCfg = Release|Win32
{DF2638C0-8128-4847-867C-6EAFE3DEE7B5}.Release|Win32.Build.0 = Release|Win32
{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Debug|Win32.ActiveCfg = Debug|Win32
{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Debug|Win32.Build.0 = Debug|Win32
{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Release|Win32.ActiveCfg = Release|Win32
{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}.Release|Win32.Build.0 = Release|Win32
{B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Debug|Win32.ActiveCfg = Debug|Win32
{B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Debug|Win32.Build.0 = Debug|Win32
{B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Release|Win32.ActiveCfg = Release|Win32
{B57CF53F-2E49-4031-9822-047CC0E6BDE2}.Release|Win32.Build.0 = Release|Win32
{7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Debug|Win32.ActiveCfg = Debug|Win32
{7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Debug|Win32.Build.0 = Debug|Win32
{7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Release|Win32.ActiveCfg = Release|Win32
{7E06E92C-537A-442B-9E4A-4761C84F8A1A}.Release|Win32.Build.0 = Release|Win32
{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Debug|Win32.ActiveCfg = Debug|Win32
{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Debug|Win32.Build.0 = Debug|Win32
{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Release|Win32.ActiveCfg = Release|Win32
{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Release|Win32.Build.0 = Release|Win32
{DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.ActiveCfg = Debug|Win32
{DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Debug|Win32.Build.0 = Debug|Win32
{DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.ActiveCfg = Release|Win32
{DDC3E27F-004D-4DD4-9DD3-931A013D2159}.Release|Win32.Build.0 = Release|Win32
{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Debug|Win32.ActiveCfg = Debug|Win32
{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Debug|Win32.Build.0 = Debug|Win32
{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Release|Win32.ActiveCfg = Release|Win32
{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,231 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}</ProjectGuid>
<ProjectName>HelloLua</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '10.0'">v100</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '11.0'">v110</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '11.0' and exists('$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A')">v110_xp</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '10.0'">v100</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '11.0'">v110</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '11.0' and exists('$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A')">v110_xp</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\lua-bindings\cocos2d-x\cocos\2d\cocos2dx.props" />
<Import Project="..\..\lua-bindings\cocos2d-x\cocos\2d\cocos2d_headers.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="..\..\lua-bindings\cocos2d-x\cocos\2d\cocos2dx.props" />
<Import Project="..\..\lua-bindings\cocos2d-x\cocos\2d\cocos2d_headers.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)$(Configuration).win32\</OutDir>
<IntDir>$(Configuration).win32\</IntDir>
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(IncludePath)</IncludePath>
<SourcePath>$(SourcePath);</SourcePath>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(SolutionDir)$(Configuration).win32\</OutDir>
<IntDir>$(Configuration).win32\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LibraryPath>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LibraryPath>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>$(ProjectDir)..\Classes;$(EngineRoot)..\bindings\auto;$(EngineRoot)..\bindings\manual;$(EngineRoot)cocos\audio\include;$(EngineRoot)..\external\lua;$(EngineRoot)..\external\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<MinimalRebuild>false</MinimalRebuild>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_WINDOWS;STRICT;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS_DEBUG;COCOS2D_DEBUG=1;GLFW_EXPOSE_NATIVE_WIN32;GLFW_EXPOSE_NATIVE_WGL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>libcurl_imp.lib;lua51.lib;websockets.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
<ResourceCompile>
<Culture>0x0409</Culture>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<TargetEnvironment>Win32</TargetEnvironment>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<HeaderFileName>HelloLua.h</HeaderFileName>
<InterfaceIdentifierFileName>HelloLua_i.c</InterfaceIdentifierFileName>
<ProxyFileName>HelloLua_p.c</ProxyFileName>
<GenerateStublessProxies>true</GenerateStublessProxies>
<TypeLibraryName>$(IntDir)/HelloLua.tlb</TypeLibraryName>
<DllDataFileName>
</DllDataFileName>
</Midl>
<PreBuildEvent>
<Command>if not exist "$(OutDir)" mkdir "$(OutDir)"
if exist "$(OutDir)\Resource" rd /s /q "$(OutDir)\Resource"
mkdir "$(OutDir)\Resource"
mkdir "$(OutDir)\Resource\src"
mkdir "$(OutDir)\Resource\res"
xcopy "$(ProjectDir)..\..\lua-bindings\bindings\script" "$(OutDir)\Resource" /e /Y
xcopy "$(ProjectDir)..\..\..\src" "$(OutDir)\Resource\src" /e /Y
xcopy "$(ProjectDir)..\..\..\res" "$(OutDir)\Resource\res" /e /Y</Command>
<Message>copy files</Message>
</PreBuildEvent>
<PreLinkEvent>
<Command>if not exist "$(OutDir)" mkdir "$(OutDir)"
xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)"</Command>
</PreLinkEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>$(ProjectDir)..\Classes;$(EngineRoot)..\bindings\auto;$(EngineRoot)..\bindings\manual;$(EngineRoot)cocos\audio\include;$(EngineRoot)..\external\lua;$(EngineRoot)..\external\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<ExceptionHandling>
</ExceptionHandling>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<PreprocessorDefinitions>WIN32;_WINDOWS;STRICT;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGSNDEBUG;GLFW_EXPOSE_NATIVE_WIN32;GLFW_EXPOSE_NATIVE_WGL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
<AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>libcurl_imp.lib;lua51.lib;websockets.lib;%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
<ResourceCompile>
<Culture>0x0409</Culture>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<TargetEnvironment>Win32</TargetEnvironment>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<HeaderFileName>HelloLua.h</HeaderFileName>
<InterfaceIdentifierFileName>HelloLua_i.c</InterfaceIdentifierFileName>
<ProxyFileName>HelloLua_p.c</ProxyFileName>
<GenerateStublessProxies>true</GenerateStublessProxies>
<TypeLibraryName>$(IntDir)/HelloLua.tlb</TypeLibraryName>
<DllDataFileName>
</DllDataFileName>
</Midl>
<PreBuildEvent>
<Command>if not exist "$(OutDir)" mkdir "$(OutDir)"
if exist "$(OutDir)\Resource" rd /s /q "$(OutDir)\Resource"
mkdir "$(OutDir)\Resource"
mkdir "$(OutDir)\Resource\src"
mkdir "$(OutDir)\Resource\res"
xcopy "$(ProjectDir)..\..\lua-bindings\bindings\script" "$(OutDir)\Resource" /e /Y
xcopy "$(ProjectDir)..\..\..\src" "$(OutDir)\Resource\src" /e /Y
xcopy "$(ProjectDir)..\..\..\res" "$(OutDir)\Resource\res" /e /Y</Command>
<Message>copy files</Message>
</PreBuildEvent>
<PreLinkEvent>
<Command>if not exist "$(OutDir)" mkdir "$(OutDir)"
xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)"</Command>
</PreLinkEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\Classes\AppDelegate.h" />
<ClInclude Include="..\Classes\Runtime.h" />
<ClInclude Include="main.h" />
<ClInclude Include="SimulatorWindow.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\Classes\AppDelegate.cpp" />
<ClCompile Include="..\Classes\Runtime.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="Runtime_win32.cpp" />
<ClCompile Include="SimulatorWindow.cpp" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="game.rc" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\2d\cocos2d.vcxproj">
<Project>{98a51ba8-fc3a-415b-ac8f-8c7bd464e93e}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\audio\proj.win32\CocosDenshion.vcxproj">
<Project>{f8edd7fa-9a51-4e80-baeb-860825d2eac6}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj">
<Project>{811c0dab-7b96-4bd3-a154-b7572b58e4ab}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\editor-support\cocostudio\proj.win32\libCocosStudio.vcxproj">
<Project>{b57cf53f-2e49-4031-9822-047cc0e6bde2}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\editor-support\spine\proj.win32\libSpine.vcxproj">
<Project>{b7c2a162-dec9-4418-972e-240ab3cbfcae}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\gui\proj.win32\libGUI.vcxproj">
<Project>{7e06e92c-537a-442b-9e4a-4761c84f8a1a}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\network\proj.win32\libNetwork.vcxproj">
<Project>{df2638c0-8128-4847-867c-6eafe3dee7b5}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\bindings\proj.win32\liblua.vcxproj">
<Project>{ddc3e27f-004d-4dd4-9dd3-931a013d2159}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj">
<Project>{632a8f38-d0f0-4d22-86b3-d69f5e6bf63a}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\extensions\proj.win32\libExtensions.vcxproj">
<Project>{21b2c324-891f-48ea-ad1a-5ae13de12e28}</Project>
</ProjectReference>
<ProjectReference Include="..\..\lua-bindings\cocos2d-x\external\chipmunk\proj.win32\chipmunk.vcxproj">
<Project>{207bc7a9-ccf1-4f2f-a04d-45f72242ae25}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Classes">
<UniqueIdentifier>{fc5cb953-2953-4968-83b3-39e3ff951754}</UniqueIdentifier>
</Filter>
<Filter Include="win32">
<UniqueIdentifier>{037a9a02-b906-4cc5-ad98-304acd4e25ee}</UniqueIdentifier>
</Filter>
<Filter Include="resource">
<UniqueIdentifier>{2d1d0979-58cd-4ab6-b91c-13650158f1fa}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Classes\AppDelegate.h">
<Filter>Classes</Filter>
</ClInclude>
<ClInclude Include="main.h">
<Filter>win32</Filter>
</ClInclude>
<ClInclude Include="SimulatorWindow.h">
<Filter>win32</Filter>
</ClInclude>
<ClInclude Include="..\Classes\Runtime.h">
<Filter>Classes</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\Classes\AppDelegate.cpp">
<Filter>Classes</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>win32</Filter>
</ClCompile>
<ClCompile Include="SimulatorWindow.cpp">
<Filter>win32</Filter>
</ClCompile>
<ClCompile Include="Runtime_win32.cpp">
<Filter>win32</Filter>
</ClCompile>
<ClCompile Include="..\Classes\Runtime.cpp">
<Filter>Classes</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="game.rc">
<Filter>resource</Filter>
</ResourceCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ShowAllFiles>false</ShowAllFiles>
<LocalDebuggerWorkingDirectory Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)/Resource</LocalDebuggerWorkingDirectory>
<LocalDebuggerWorkingDirectory Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)/Resource</LocalDebuggerWorkingDirectory>
<DebuggerFlavor Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">WindowsLocalDebugger</DebuggerFlavor>
<DebuggerFlavor Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,52 @@
#include <io.h>
#include <direct.h>
#include <stdio.h>
#include <vector>
#include <string>
#include "cocos2d.h"
using namespace std;
string getProjSearchPath()
{
extern std::string getCurAppPath(void);
string searchPath = getCurAppPath();
searchPath += "/../..";
char fuldir[MAX_PATH]={0};
_fullpath(fuldir,searchPath.c_str(),MAX_PATH);
return fuldir;
}
vector<string> getSearchPath()
{
extern std::string getCurAppPath(void);
vector<string> searchPathArray;
string searchPathRes = getCurAppPath();
searchPathRes += "/Resources";
searchPathArray.push_back(getProjSearchPath());
searchPathArray.push_back(searchPathRes);
return searchPathArray;
}
string getIPAddress()
{
WSADATA wsaData;
char name[155]={0};
char *ip=nullptr;
PHOSTENT hostinfo;
if ( WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 )
{
if( gethostname ( name, sizeof(name)) == 0)
{
if((hostinfo = gethostbyname(name)) != NULL)
{
ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
}
}
WSACleanup( );
}
return ip;
}

View File

@ -0,0 +1,246 @@
/****************************************************************************
Copyright (c) 2013 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 "SimulatorWindow.h"
#include "cocos2d.h"
#include "glfw3native.h"
#include "resource.h"
#include "Runtime.h"
#include <string>
#include <vector>
using namespace std;
using namespace cocos2d;
WNDPROC g_oldProc=NULL;
bool g_landscape=false;
CCSize g_screenSize;
GLView* g_eglView=NULL;
INT_PTR CALLBACK AboutDialogCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
void createViewMenu()
{
HMENU menu = GetMenu(glfwGetWin32Window(g_eglView->getWindow()));
HMENU viewMenu = GetSubMenu(menu, 1);
for (int i = SimulatorConfig::getInstance()->getScreenSizeCount() - 1; i >= 0; --i)
{
SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(i);
wstring menuName;
menuName.assign(size.title.begin(), size.title.end());
MENUITEMINFO item;
ZeroMemory(&item, sizeof(item));
item.cbSize = sizeof(item);
item.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
item.fType = MFT_STRING;
item.wID = ID_VIEW_SIZE + i;
item.dwTypeData = (LPTSTR)menuName.c_str();
item.cch = menuName.length();
InsertMenuItem(viewMenu, 0, TRUE, &item);
}
}
void updateMenu()
{
HMENU menu = GetMenu(glfwGetWin32Window(g_eglView->getWindow()));
HMENU viewMenu = GetSubMenu(menu, 1);
if (g_landscape)
{
CheckMenuItem(viewMenu, ID_VIEW_PORTRAIT, MF_BYCOMMAND | MF_UNCHECKED);
CheckMenuItem(viewMenu, ID_VIEW_LANDSCAPE, MF_BYCOMMAND | MF_CHECKED);
}
else
{
CheckMenuItem(viewMenu, ID_VIEW_PORTRAIT, MF_BYCOMMAND | MF_CHECKED);
CheckMenuItem(viewMenu, ID_VIEW_LANDSCAPE, MF_BYCOMMAND | MF_UNCHECKED);
}
int width = g_screenSize.width;
int height = g_screenSize.height;
if (height > width)
{
int w = width;
width = height;
height = w;
}
int count = SimulatorConfig::getInstance()->getScreenSizeCount();
for (int i = 0; i < count; ++i)
{
bool bSel = false;
SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(i);
if (size.width == width && size.height == height)
{
bSel = true;
}
CheckMenuItem(viewMenu, i, MF_BYPOSITION | (bSel? MF_CHECKED : MF_UNCHECKED));
}
}
/*@brief updateView*/
void updateView()
{
if (g_landscape)
{
glfwSetWindowSize(g_eglView->getWindow(),g_screenSize.width,g_screenSize.height);
}
else
{
glfwSetWindowSize(g_eglView->getWindow(),g_screenSize.height,g_screenSize.width);
}
updateMenu();
}
void onViewChangeOrientation(int viewMenuID)
{
if (viewMenuID == ID_VIEW_PORTRAIT && g_landscape)
{
g_landscape = false;
updateView();
}
else if (viewMenuID == ID_VIEW_LANDSCAPE && !g_landscape)
{
g_landscape = true;
updateView();
}
}
void onViewChangeFrameSize(int viewMenuID)
{
int index = viewMenuID - ID_VIEW_SIZE;
if (index >= 0 && index < SimulatorConfig::getInstance()->getScreenSizeCount())
{
SimulatorScreenSize size = SimulatorConfig::getInstance()->getScreenSize(index);
g_screenSize.width = size.width;
g_screenSize.height = size.height;
updateView();
}
}
void onHelpAbout()
{
DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG_ABOUT), glfwGetWin32Window(g_eglView->getWindow()), AboutDialogCallback);
}
/*@brief new windows process*/
LRESULT CALLBACK SNewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
switch (message)
{
case WM_COMMAND:
{
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
switch (wmId)
{
case ID_FILE_EXIT:
exit(0);
break;
case ID_VIEW_PORTRAIT:
case ID_VIEW_LANDSCAPE:
onViewChangeOrientation(wmId);
break;
case ID_CONTROL_RELOAD:
reloadScript();
break;
case ID_HELP_ABOUT:
onHelpAbout();
default:
if (wmId >= ID_VIEW_SIZE && wmId <= ID_VIEW_SIZE + SimulatorConfig::getInstance()->getScreenSizeCount() - 1)
{
onViewChangeFrameSize(wmId);
break;
}
return 0;
}
}
break;
}
return g_oldProc(hWnd, message, wParam, lParam);
}
/*@brief AboutDialog Callback*/
INT_PTR CALLBACK AboutDialogCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
void createSimulator(const char* viewName, float width, float height, float frameZoomFactor)
{
if (g_eglView)
{
return;
}
g_eglView = GLView::createWithRect(viewName,Rect(0,0,width,height),frameZoomFactor);
auto director = Director::getInstance();
director->setOpenGLView(g_eglView);
g_landscape = false;
g_screenSize.width = width;
g_screenSize.height = height;
if (width > height)
{
g_landscape = true;
}
HWND hWnd=glfwGetWin32Window(g_eglView->getWindow());
HMENU hMenu = LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_MENU_COCOS));
SetMenu(hWnd, hMenu);
createViewMenu();
updateMenu();
g_oldProc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)SNewWndProc);
if (g_oldProc==0)
{
printf("SetWindowLong NewWndProc Error:%d\n",GetLastError());
}
}

View File

@ -0,0 +1,33 @@
/****************************************************************************
Copyright (c) 2013 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.
****************************************************************************/
#ifndef __SIMULATOR_WINDOW_H_
#define __SIMULATOR_WINDOW_H_
/************************
@brief create Simulator
*********************************/
void createSimulator(const char* viewName, float width, float height,float frameZoomFactor = 1.0f);
#endif /* __PROJECT_CONFIG_H_ */

View File

@ -0,0 +1,188 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// Chinese (Simplified, PRC) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS)
LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED
#pragma code_page(936)
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
2 TEXTINCLUDE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Menu
//
IDR_MENU_COCOS MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM SEPARATOR
MENUITEM "E&xit", ID_FILE_EXIT
END
POPUP "&View"
BEGIN
MENUITEM SEPARATOR
MENUITEM "&Portrait", ID_VIEW_PORTRAIT
MENUITEM "&Landscape", ID_VIEW_LANDSCAPE
MENUITEM SEPARATOR
MENUITEM "&Custom", ID_VIEW_CUSTOM
END
POPUP "&Control"
BEGIN
MENUITEM "Reload", ID_CONTROL_RELOAD
END
POPUP "&Help"
BEGIN
MENUITEM "&About ...", ID_HELP_ABOUT
END
END
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_DIALOG_ABOUT DIALOGEX 0, 0, 243, 94
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About Simulator"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,173,69,63,18
LTEXT "Cocos2d-x-Simulator",IDC_STATIC,29,17,169,25
END
IDD_DIALOG_VIEWCUSTOM DIALOGEX 0, 0, 179, 98
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Custom"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,47,77,50,14
PUSHBUTTON "Cancel",IDCANCEL,104,77,50,14
LTEXT "Width£º",IDC_STATIC,15,14,30,8
LTEXT "Height£º",IDC_STATIC,15,36,36,12
EDITTEXT IDC_EDIT_WIDTH,60,15,89,14,ES_AUTOHSCROLL
EDITTEXT IDC_EDIT_HEIGHT,62,36,87,14,ES_AUTOHSCROLL
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_DIALOG_ABOUT, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 236
TOPMARGIN, 7
BOTTOMMARGIN, 87
END
IDD_DIALOG_VIEWCUSTOM, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 172
TOPMARGIN, 7
BOTTOMMARGIN, 91
END
END
#endif // APSTUDIO_INVOKED
#endif // Chinese (Simplified, PRC) resources
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
GLFW_ICON ICON "res\\game.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "FileDescription", "game Module"
VALUE "FileVersion", "1, 0, 0, 1"
VALUE "InternalName", "game"
VALUE "LegalCopyright", "Copyright "
VALUE "OriginalFilename", "game.exe"
VALUE "ProductName", "game Module"
VALUE "ProductVersion", "1, 0, 0, 1"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@ -0,0 +1,59 @@
#include "main.h"
#include "AppDelegate.h"
#include "cocos2d.h"
#include "SimulatorWindow.h"
USING_NS_CC;
// uncomment below line, open debug console
#define USE_WIN32_CONSOLE
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
#ifdef USE_WIN32_CONSOLE
AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
#endif
// create the application instance
AppDelegate app;
createSimulator("HelloLua",960,640);
int ret = Application::getInstance()->run();
#ifdef USE_WIN32_CONSOLE
FreeConsole();
#endif
return ret;
}
std::string getCurAppPath(void)
{
TCHAR szAppDir[MAX_PATH]={0};
if (!GetModuleFileName(NULL,szAppDir,MAX_PATH))
return "";
int nEnd=0;
for (int i=0;szAppDir[i];i++)
{
if(szAppDir[i]=='\\')
nEnd = i;
}
szAppDir[nEnd] = 0;
int iLen = 2*wcslen(szAppDir);
char* chRtn = new char[iLen+1];
wcstombs(chRtn,szAppDir,iLen+1);
std::string strPath = chRtn;
delete [] chRtn;
chRtn=NULL;
char fuldir[MAX_PATH]={0};
_fullpath(fuldir,strPath.c_str(),MAX_PATH);
return fuldir;
}

View File

@ -0,0 +1,10 @@
#ifndef __MAIN_H__
#define __MAIN_H__
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <tchar.h>
#endif // __WINMAIN_H__

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

View File

@ -0,0 +1,37 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by game.RC
//
#define IDS_PROJNAME 100
#define IDR_TESTLUA 100
#define IDR_MENU_COCOS 201
#define IDD_DIALOG1 202
#define IDD_DIALOG_ABOUT 202
#define IDD_DIALOG_VIEWCUSTOM 203
#define IDC_EDIT_WIDTH 1000
#define IDC_EDIT2 1001
#define IDC_EDIT_HEIGHT 1001
#define ID_VIEW_SIZE 30001
#define ID_FILE_NEW_WINDOW 32771
#define ID_VIEW_PORTRAIT 32775
#define ID_VIEW_LANDSCAPE 32776
#define ID_VIEW_CUSTOM 32777
#define ID_HELP_ABOUT 32778
#define ID_FILE_EXIT 32779
#define ID_Menu 32780
#define ID_Menu32781 32781
#define ID_TEST_RESET 32782
#define ID_CONTROL 32783
#define ID_CONTROL_RELOAD 32784
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 201
#define _APS_NEXT_COMMAND_VALUE 32785
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@ -0,0 +1 @@
aec1c0a8c8068377fddca5ddd32084d8c3c3c419

View File

@ -0,0 +1 @@
d7290c34702d1c6bdb368acb060d93b42d5deff8

Binary file not shown.

View File

@ -0,0 +1,3 @@
function myadd(x, y)
return x + y
end

View File

@ -0,0 +1,220 @@
require "Cocos2d"
-- cclog
cclog = function(...)
print(string.format(...))
end
-- for CCLuaEngine traceback
function __G__TRACKBACK__(msg)
cclog("----------------------------------------")
cclog("LUA ERROR: " .. tostring(msg) .. "\n")
cclog(debug.traceback())
cclog("----------------------------------------")
end
local function main()
-- avoid memory leak
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
cc.FileUtils:getInstance():addSearchResolutionsOrder("src");
cc.FileUtils:getInstance():addSearchResolutionsOrder("res");
--support debug
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or
(cc.PLATFORM_OS_ANDROID == targetPlatform) or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or
(cc.PLATFORM_OS_MAC == targetPlatform) then
cclog("result is ")
--require('debugger')()
end
require "hello2"
cclog("result is " .. myadd(1, 1))
---------------
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
-- add the moving dog
local function creatDog()
local frameWidth = 105
local frameHeight = 95
-- create dog animate
local textureDog = cc.TextureCache:getInstance():addImage("dog.png")
local rect = cc.rect(0, 0, frameWidth, frameHeight)
local frame0 = cc.SpriteFrame:createWithTexture(textureDog, rect)
rect = cc.rect(frameWidth, 0, frameWidth, frameHeight)
local frame1 = cc.SpriteFrame:createWithTexture(textureDog, rect)
local spriteDog = cc.Sprite:createWithSpriteFrame(frame0)
spriteDog.isPaused = false
spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3)
--[[
local animFrames = CCArray:create()
animFrames:addObject(frame0)
animFrames:addObject(frame1)
]]--
local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.5)
local animate = cc.Animate:create(animation);
spriteDog:runAction(cc.RepeatForever:create(animate))
-- moving dog at every frame
local function tick()
if spriteDog.isPaused then return end
local x, y = spriteDog:getPosition()
if x > origin.x + visibleSize.width then
x = origin.x
else
x = x + 1
end
spriteDog:setPositionX(x)
end
cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false)
return spriteDog
end
-- create farm
local function createLayerFarm()
local layerFarm = cc.Layer:create()
-- add in farm background
local bg = cc.Sprite:create("farm.jpg")
bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2)
layerFarm:addChild(bg)
-- add land sprite
for i = 0, 3 do
for j = 0, 1 do
local spriteLand = cc.Sprite:create("land.png")
spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2)
layerFarm:addChild(spriteLand)
end
end
-- add crop
local frameCrop = cc.SpriteFrame:create("crop.png", cc.rect(0, 0, 105, 95))
for i = 0, 3 do
for j = 0, 1 do
local spriteCrop = cc.Sprite:createWithSpriteFrame(frameCrop);
spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2)
layerFarm:addChild(spriteCrop)
end
end
-- add moving dog
local spriteDog = creatDog()
layerFarm:addChild(spriteDog)
-- handing touch events
local touchBeginPoint = nil
local function onTouchBegan(touch, event)
local location = touch:getLocation()
cclog("onTouchBegan: %0.2f, %0.2f", location.x, location.y)
touchBeginPoint = {x = location.x, y = location.y}
spriteDog.isPaused = true
-- CCTOUCHBEGAN event must return true
return true
end
local function onTouchMoved(touch, event)
local location = touch:getLocation()
cclog("onTouchMoved: %0.2f, %0.2f", location.x, location.y)
if touchBeginPoint then
local cx, cy = layerFarm:getPosition()
layerFarm:setPosition(cx + location.x - touchBeginPoint.x,
cy + location.y - touchBeginPoint.y)
touchBeginPoint = {x = location.x, y = location.y}
end
end
local function onTouchEnded(touch, event)
local location = touch:getLocation()
cclog("onTouchEnded: %0.2f, %0.2f", location.x, location.y)
touchBeginPoint = nil
spriteDog.isPaused = false
end
local listener = cc.EventListenerTouchOneByOne:create()
listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )
listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED )
listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED )
local eventDispatcher = layerFarm:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layerFarm)
return layerFarm
end
-- create menu
local function createLayerMenu()
local layerMenu = cc.Layer:create()
local menuPopup, menuTools, effectID
local function menuCallbackClosePopup()
-- stop test sound effect
cc.SimpleAudioEngine:getInstance():stopEffect(effectID)
menuPopup:setVisible(false)
end
local function menuCallbackOpenPopup()
-- loop test sound effect
local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav")
effectID = cc.SimpleAudioEngine:getInstance():playEffect(effectPath)
menuPopup:setVisible(true)
end
-- add a popup menu
local menuPopupItem = cc.MenuItemImage:create("menu2.png", "menu2.png")
menuPopupItem:setPosition(0, 0)
menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup)
menuPopup = cc.Menu:create(menuPopupItem)
menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)
menuPopup:setVisible(false)
layerMenu:addChild(menuPopup)
-- add the left-bottom "tools" menu to invoke menuPopup
local menuToolsItem = cc.MenuItemImage:create("menu1.png", "menu1.png")
menuToolsItem:setPosition(0, 0)
menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup)
menuTools = cc.Menu:create(menuToolsItem)
local itemWidth = menuToolsItem:getContentSize().width
local itemHeight = menuToolsItem:getContentSize().height
menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2)
layerMenu:addChild(menuTools)
return layerMenu
end
-- play background music, preload effect
-- uncomment below for the BlackBerry version
-- local bgMusicPath = CCFileUtils:getInstance():fullPathForFilename("background.ogg")
local bgMusicPath = cc.FileUtils:getInstance():fullPathForFilename("background.mp3")
cc.SimpleAudioEngine:getInstance():playMusic(bgMusicPath, true)
local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav")
cc.SimpleAudioEngine:getInstance():preloadEffect(effectPath)
-- run
local sceneGame = cc.Scene:create()
sceneGame:addChild(createLayerFarm())
sceneGame:addChild(createLayerMenu())
if cc.Director:getInstance():getRunningScene() then
cc.Director:getInstance():replaceScene(sceneGame)
else
cc.Director:getInstance():runWithScene(sceneGame)
end
end
xpcall(main, __G__TRACKBACK__)

@ -1 +1 @@
Subproject commit edac62683a544f8a1f43ffb8744c98f003daf80d
Subproject commit 39738950219adba48ae97e853673278337df4658

View File

@ -2,7 +2,7 @@
import os
genbindings_dirs = ['tojs', 'tolua']
genbindings_dirs = ['tolua']
for item in genbindings_dirs:
os.chdir("tools/" + item)
os.system('python genbindings.py')

View File

@ -14,6 +14,12 @@ def main():
#parse to json obj
payload = json.loads(payload_str)
issue = payload['issue']
#get pull number
pr_num = issue['number']
print 'pr_num:' + str(pr_num)
payload_forword = {"number":pr_num}
comment = payload['comment']
#get comment body
comment_body = comment['body']
@ -23,12 +29,6 @@ def main():
if result is None:
print 'skip build for pull request #' + str(pr_num)
return(0)
issue = payload['issue']
#get pull number
pr_num = issue['number']
print 'pr_num:' + str(pr_num)
payload_forword = {"number":pr_num}
#build for pull request action 'open' and 'synchronize', skip 'close'
action = issue['state']

View File

@ -93,7 +93,7 @@ def main():
os.system(git_update_submodule)
# Generate binding glue codes
# os.system("python tools/jenkins-scripts/gen_jsb.py")
os.system("python tools/jenkins-scripts/gen_jsb.py")
#make temp dir
print "current dir is" + os.environ['WORKSPACE']

57
tools/tolua/README.mdown Normal file
View File

@ -0,0 +1,57 @@
How to Use bindings-generator
==================
On Windows:
------------
* Make sure that you have installed `android-ndk-r9b`.
* Download python2.7.3 (32bit) from (http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi).
* Add the installed path of python (e.g. C:\Python27) to windows environment variable named 'PATH'.
* Download pyyaml from http://pyyaml.org/download/pyyaml/PyYAML-3.10.win32-py2.7.exe and install it.
* Download pyCheetah from https://raw.github.com/dumganhar/cocos2d-x/download/downloads/Cheetah.zip, unzip it to "C:\Python27\Lib\site-packages"
* Set environment variables (`NDK_ROOT`)
* Go to "cocos2d-x/tools/tolua" folder, and run "genbindings.py". The generated codes will be under "cocos\scripting\auto-generated\js-bindings".
On MAC:
----------
* The OSX 10.9 has a built-in python2.7 and if your os don't have python2.7 then use [Homebrew](http://brew.sh/) to install the python and use pip install the python dependencies.
<pre>
brew install python
</pre>
* Install python dependices by pip.
<pre>
sudo easy_install pip
sudo pip install PyYAML
sudo pip install Cheetah
</pre>
* Download [64bit ndk-r9b-x86_64](http://dl.google.com/android/ndk/android-ndk-r9b-darwin-x86_64.tar.bz2) from [google](http://developer.android.com/tools/sdk/ndk/index.html)
* Run
<pre>
export NDK_ROOT=/path/to/android-ndk-r9b
./genbindings.py
</pre>
On Ubuntu Linux 12.04 64bit
------------
* Install python
<pre>
sudo apt-get install python2.7
</pre>
* Install python dependices by pip.
<pre>
sudo apt-get install python-pip
sudo pip install PyYAML
sudo pip install Cheetah
</pre>
* Download [64bit ndk-r9b-x86_64]( https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64.tar.bz2) from [google](http://developer.android.com/tools/sdk/ndk/index.html)
* Go to "cocos2d-x/tools/tolua", Run
<pre>
export NDK_ROOT=/path/to/android-ndk-r9b
./genbindings.py
</pre>

154
tools/tolua/cocos2dx.ini Normal file
View File

@ -0,0 +1,154 @@
[cocos2d-x]
# the prefix to be added to the generated functions. You might or might not use this in your own
# templates
prefix = cocos2dx
# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
# all classes will be embedded in that namespace
target_namespace = cc
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include
android_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include
clang_flags = -nostdinc -x c++ -std=c++11
cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath
cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT
cxxgenerator_headers =
# extra arguments for clang
extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
# what headers to parse
headers = %(cocosdir)s/cocos/2d/cocos2d.h %(cocosdir)s/cocos/audio/include/SimpleAudioEngine.h
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak ^Ref$ UserDefault GLViewProtocol GLView Image Event(?!.*(Physics).*).* Component
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
# add a single "*" as functions. See bellow for several examples. A special class name is "*", which
# will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes.
skip = Node::[setGLServerState description getUserObject .*UserData getGLServerState .*schedule getPosition$ setContentSize setAnchorPoint],
Sprite::[getQuad getBlendFunc ^setPosition$ setBlendFunc],
SpriteBatchNode::[getBlendFunc setBlendFunc getDescendants],
MotionStreak::[getBlendFunc setBlendFunc draw update],
AtlasNode::[getBlendFunc setBlendFunc],
ParticleBatchNode::[getBlendFunc setBlendFunc],
LayerColor::[getBlendFunc setBlendFunc],
ParticleSystem::[getBlendFunc setBlendFunc],
DrawNode::[getBlendFunc setBlendFunc drawPolygon listenBackToForeground],
Director::[getAccelerometer (g|s)et.*Dispatcher getOpenGLView getProjection getFrustum getRenderer],
Layer.*::[didAccelerate (g|s)etBlendFunc keyPressed keyReleased],
Menu.*::[.*Target getSubItems create initWithItems alignItemsInRows alignItemsInColumns],
MenuItem.*::[create setCallback initWithCallback],
Label::[getLettersInfo createWithTTF setTTFConfig],
Copying::[*],
LabelProtocol::[*],
LabelTextFormatProtocol::[*],
.*Delegate::[*],
PoolManager::[*],
Texture2D::[initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData getPixelFormatInfoMap],
Set::[begin end acceptVisitor],
IMEDispatcher::[*],
SAXParser::[*],
Thread::[*],
Profiler::[*],
ProfilingTimer::[*],
CallFunc::[create initWithFunction],
SAXDelegator::[*],
Color3bObject::[*],
TouchDispatcher::[*],
EGLTouchDelegate::[*],
ScriptEngineManager::[*],
KeypadHandler::[*],
Invocation::[*],
SchedulerScriptHandlerEntry::[*],
Size::[*],
Point::[*],
PointArray::[*],
Rect::[*],
String::[*],
Data::[*],
Dictionary::[*],
Array::[*],
Range::[*],
EventListenerVector::[*],
EventListener.*::[create],
EventTouch::[(s|g)etTouches],
NotificationObserver::[*],
Image::[initWithString initWithImageData initWithRawData],
Sequence::[create],
Spawn::[create],
GLProgram::[getProgram setUniformLocationWith2f.* setUniformLocationWith1f.* setUniformLocationWith3f.* setUniformLocationWith4f.*],
Grid3DAction::[create actionWith.* vertex originalVertex (g|s)etVertex getOriginalVertex],
Grid3D::[vertex originalVertex (g|s)etVertex getOriginalVertex],
TiledGrid3DAction::[create actionWith.* tile originalTile getOriginalTile (g|s)etTile],
TiledGrid3D::[tile originalTile getOriginalTile (g|s)etTile],
TMXLayer::[getTiles],
TMXMapInfo::[startElement endElement textHandler],
ParticleSystemQuad::[postStep setBatchNode draw setTexture$ setTotalParticles updateQuadWithParticle setupIndices listenBackToForeground initWithTotalParticles particleWithFile node],
LayerMultiplex::[create layerWith.* initWithLayers],
CatmullRom.*::[create actionWithDuration],
Bezier.*::[create actionWithDuration],
CardinalSpline.*::[create actionWithDuration setPoints],
Scheduler::[pause resume unschedule schedule update isTargetPaused isScheduled],
TextureCache::[addPVRTCImage addImageAsync],
Timer::[getSelector createWithScriptHandler],
*::[copyWith.* onEnter.* onExit.* ^description$ getObjectType (g|s)etDelegate onTouch.* onAcc.* onKey.* onRegisterTouchListener],
FileUtils::[(g|s)etSearchResolutionsOrder$ (g|s)etSearchPaths$ getFileData getDataFromFile getFullPathCache],
Application::[^application.* ^run$],
Camera::[getEyeXYZ getCenterXYZ getUpXYZ],
ccFontDefinition::[*],
Ref::[autorelease isEqual acceptVisitor update],
UserDefault::[getInstance (s|g)etDataForKey],
GLViewProtocol::[setTouchDelegate],
GLView::[end swapBuffers],
NewTextureAtlas::[*],
DisplayLinkDirector::[mainLoop setAnimationInterval startAnimation stopAnimation],
RenderTexture::[listenToBackground listenToForeground],
TMXTiledMap::[getPropertiesForGID],
EventDispatcher::[dispatchCustomEvent],
EventCustom::[getUserData setUserData],
Component::[serialize]
rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames getSpriteFrameByName=getSpriteFrame],
ProgressTimer::[setReverseProgress=setReverseDirection],
AnimationCache::[addAnimationsWithFile=addAnimations],
LayerGradient::[initWithColor=init],
LayerColor::[initWithColor=init],
GLProgram::[initWithVertexShaderByteArray=initWithString initWithVertexShaderFilename=init setUniformLocationWith1i=setUniformLocationI32],
Node::[removeFromParentAndCleanup=removeFromParent removeAllChildrenWithCleanup=removeAllChildren],
LabelAtlas::[create=_create],
Sprite::[initWithFile=init],
SpriteBatchNode::[initWithFile=init],
Touch::[getID=getId],
SimpleAudioEngine::[preloadBackgroundMusic=preloadMusic setBackgroundMusicVolume=setMusicVolume getBackgroundMusicVolume=getMusicVolume playBackgroundMusic=playMusic stopBackgroundMusic=stopMusic pauseBackgroundMusic=pauseMusic resumeBackgroundMusic=resumeMusic rewindBackgroundMusic=rewindMusic isBackgroundMusicPlaying=isMusicPlaying willPlayBackgroundMusic=willPlayMusic],
FileUtils::[loadFilenameLookupDictionaryFromFile=loadFilenameLookup],
Director::[end=endToLua]
rename_classes = ParticleSystemQuad::ParticleSystem,
SimpleAudioEngine::AudioEngine
# for all class names, should we remove something when registering in the target VM?
remove_prefix =
# classes for which there will be no "parent" lookup
classes_have_no_parents = Director SimpleAudioEngine FileUtils TMXMapInfo Application
# base classes which will be skipped when their sub-classes found them.
base_classes_to_skip = Clonable
# classes that create no constructor
# Set is special and we will use a hand-written constructor
abstract_classes = Action FiniteTimeAction ActionInterval ActionEase EaseRateAction EaseElastic EaseBounce ActionInstant GridAction Grid3DAction TiledGrid3DAction Director SpriteFrameCache TransitionEaseScene Set SimpleAudioEngine FileUtils Application ClippingNode Label GLViewProtocol GLView EventAcceleration DisplayLinkDirector Component
# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'.
script_control_cpp = no

View File

@ -0,0 +1,74 @@
[cocos2dx_extension]
# the prefix to be added to the generated functions. You might or might not use this in your own
# templates
prefix = cocos2dx_extension
# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
# all classes will be embedded in that namespace
target_namespace = cc
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include
android_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include
clang_flags = -nostdinc -x c++ -std=c++11
cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s
cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT
cxxgenerator_headers =
# extra arguments for clang
extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
# what headers to parse
headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/cocosbuilder/CocosBuilder.h
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* EditBox$ ScrollView$ TableView$ TableViewCell$
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
# add a single "*" as functions. See bellow for several examples. A special class name is "*", which
# will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes.
skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getCCBMemberVariableAssigner readFloat getCCBSelectorResolver toLowerCase lastPathComponent deletePathExtension endsWith concat getResolutionScale getAnimatedProperties readBool readInt addOwnerCallbackNode addDocumentCallbackName readCachedString readNodeGraphFromData addDocumentCallbackNode getLoadedSpriteSheet initWithData readFileWithCleanUp getOwner$ readNodeGraphFromFile createSceneWithNodeGraphFromFile getAnimationManagers$ setAnimationManagers],
CCBAnimationManager::[setAnimationCompletedCallback setCallFunc addNode],
.*Delegate::[*],
.*Loader.*::[*],
*::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType (g|s)etDelegate .*HSV],
EditBox::[(g|s)etDelegate ^keyboard.* touchDownAction getScriptEditBoxHandler registerScriptEditBoxHandler unregisterScriptEditBoxHandler],
AssetsManager::[(g|s)etDelegate],
AssetsManagerDelegateProtocol::[*],
Control::[removeHandleOfControlEvent addHandleOfControlEvent],
ControlUtils::[*],
ControlSwitchSprite::[*],
ScrollView::[(g|s)etDelegate$],
TableView::[create (g|s)etDataSource$ (g|s)etDelegate]
rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager]
rename_classes = CCBReader::_Reader,
CCBAnimationManager::AnimationManager
# for all class names, should we remove something when registering in the target VM?
remove_prefix =
# classes for which there will be no "parent" lookup
classes_have_no_parents =
# base classes which will be skipped when their sub-classes found them.
base_classes_to_skip = Ref ProcessBase
# classes that create no constructor
# Set is special and we will use a hand-written constructor
abstract_classes = ArmatureDataManager
# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'.
script_control_cpp = no

View File

@ -0,0 +1,68 @@
[cocos2dx_gui]
# the prefix to be added to the generated functions. You might or might not use this in your own
# templates
prefix = cocos2dx_ui
# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
# all classes will be embedded in that namespace
target_namespace = ccui
# the native namespace in which this module locates, this parameter is used for avoid conflict of the same class name in different modules, as "cocos2d::Label" <-> "cocos2d::ui::Label".
cpp_namespace = cocos2d::ui
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include
android_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include
clang_flags = -nostdinc -x c++ -std=c++11
cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s
cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT
cxxgenerator_headers =
# extra arguments for clang
extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
# what headers to parse
headers = %(cocosdir)s/cocos/gui/CocosGUI.h
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = Helper Widget Layer Layout RootWidget Button CheckBox ImageView Text TextAtlas TextBMFont LoadingBar Slider Switch TextField ScrollView ListView PageView LayoutParameter LinearLayoutParameter RelativeLayoutParameter
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
# add a single "*" as functions. See bellow for several examples. A special class name is "*", which
# will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes.
skip = *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener (s|g)etBlendFunc ccTouch.*],
Widget::[(s|g)etUserObject],
Layer::[getInputManager],
LayoutParameter::[(s|g)etMargin],
Helper::[init],
ImageView::[doubleClickEvent checkDoubleClick]
rename_functions =
rename_classes =
# for all class names, should we remove something when registering in the target VM?
remove_prefix =
# classes for which there will be no "parent" lookup
classes_have_no_parents = Helper
# base classes which will be skipped when their sub-classes found them.
base_classes_to_skip = Ref
# classes that create no constructor
# Set is special and we will use a hand-written constructor
abstract_classes = Helper
# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'.
script_control_cpp = no

View File

@ -0,0 +1,68 @@
[cocos2dx_physics]
# the prefix to be added to the generated functions. You might or might not use this in your own
# templates
prefix = cocos2dx_physics
# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
# all classes will be embedded in that namespace
target_namespace = cc
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include
android_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include
clang_flags = -nostdinc -x c++ -std=c++11
cocos_headers = -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath -I%(cocosdir)s/cocos/physics
cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT -DCC_USE_PHYSICS=1
cxxgenerator_headers =
# extra arguments for clang
extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
# what headers to parse
headers = %(cocosdir)s/cocos/2d/cocos2d.h
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = Event(.*(Physics).*) Physics.*
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
# add a single "*" as functions. See bellow for several examples. A special class name is "*", which
# will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes.
skip = PhysicsBody::[getJoints createPolygon createEdgeChain createEdgePolygon],
PhysicsShape::[recenterPoints getPolyonCenter],
PhysicsShapeBox::[^getPoints$],
PhysicsShapeEdgeBox::[^getPoints$],
PhysicsShapePolygon::[create calculateArea calculateMoment ^getPoints$],
PhysicsShapeEdgePolygon::[create ^getPoints$],
PhysicsShapeEdgeChain::[create ^getPoints$],
PhysicsWorld::[getScene queryPoint queryRect rayCast],
PhysicsContact::[getData setData]
rename_functions =
rename_classes =
# for all class names, should we remove something when registering in the target VM?
remove_prefix =
# classes for which there will be no "parent" lookup
classes_have_no_parents = PhysicsWorld PhysicsJoint PhysicsContactPreSolve PhysicsContactPostSolve
# base classes which will be skipped when their sub-classes found them.
base_classes_to_skip =
# classes that create no constructor
# Set is special and we will use a hand-written constructor
abstract_classes =
# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'.
script_control_cpp = no

View File

@ -0,0 +1,61 @@
[cocos2dx_spine]
# the prefix to be added to the generated functions. You might or might not use this in your own
# templates
prefix = cocos2dx_spine
# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
# all classes will be embedded in that namespace
target_namespace = sp
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include
android_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include
clang_flags = -nostdinc -x c++ -std=c++11
cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s
cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT
cxxgenerator_headers =
# extra arguments for clang
extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
# what headers to parse
headers = %(cocosdir)s/cocos/editor-support/spine/spine-cocos2dx.h
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = Skeleton SkeletonAnimation
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
# add a single "*" as functions. See bellow for several examples. A special class name is "*", which
# will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes.
skip = Skeleton::[findBone findSlot getAttachment setAttachment update draw createWith.*],
SkeletonAnimation::[addAnimationState setAnimationStateData update createWith.* (s|g)etBlendFunc]
rename_functions =
rename_classes =
# for all class names, should we remove something when registering in the target VM?
remove_prefix =
# classes for which there will be no "parent" lookup
classes_have_no_parents =
# base classes which will be skipped when their sub-classes found them.
base_classes_to_skip = Ref ProcessBase
# classes that create no constructor
# Set is special and we will use a hand-written constructor
abstract_classes = Skeleton SkeletonAnimation
# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'.
script_control_cpp = no

View File

@ -0,0 +1,79 @@
[cocos2dx_studio]
# the prefix to be added to the generated functions. You might or might not use this in your own
# templates
prefix = cocos2dx_studio
# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
# all classes will be embedded in that namespace
target_namespace = ccs
# the native namespace in which this module locates, this parameter is used for avoid conflict of the same class name in different modules, as "cocos2d::Label" <-> "cocos2d::gui::Label".
cpp_namespace = cocostudio
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include
android_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/lib/clang/3.3/include
clang_flags = -nostdinc -x c++ -std=c++11
cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/2d -I%(cocosdir)s/cocos/base -I%(cocosdir)s/cocos/gui -I%(cocosdir)s/cocos/physics -I%(cocosdir)s/cocos/2d/platform -I%(cocosdir)s/cocos/2d/platform/android -I%(cocosdir)s/cocos/math/kazmath -I%(cocosdir)s/extensions -I%(cocosdir)s/external -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s
cocos_flags = -DANDROID -DCOCOS2D_JAVASCRIPT
cxxgenerator_headers =
# extra arguments for clang
extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
# what headers to parse
headers = %(cocosdir)s/cocos/editor-support/cocostudio/CocoStudio.h
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = Armature ArmatureAnimation Skin Bone ArmatureDataManager \w+Data$ ActionManagerEx ComAudio ComController ComAttribute ComRender BatchNode SceneReader GUIReader ActionObject Tween DisplayManager
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
# add a single "*" as functions. See bellow for several examples. A special class name is "*", which
# will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes.
skip = *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* (s|g)etBlendFunc (s|g)etUserObject add\w*EventListener],
ArmatureDataManager::[CCArmatureDataManager ~CCArmatureDataManager],
Armature::[createBone updateBlendType setBody getShapeList ^getBody$],
Skin::[(s|g)etSkinData],
ArmatureAnimation::[updateHandler updateFrameData frameEvent setMovementEventCallFunc setFrameEventCallFunc],
Bone::[(s|g)etIgnoreMovementBoneData],
ActionManagerEx::[initWithDictionary],
ActionObject::[initWithDictionary],
DisplayManager::[initDisplayList (s|g)etCurrentDecorativeDisplay getDecorativeDisplayByIndex],
Tween::[(s|g)etMovementBoneData],
GUIReader::[storeFileDesignSize getFileDesignSize getParseCallBackMap getParseObjectMap],
ActionNode::[initWithDictionary],
ActionObject::[initWithDictionary],
BaseData::[copy subtract]
rename_functions = GUIReader::[shareReader=getInstance purgeGUIReader=destroyInstance],
ActionManagerEx::[shareManager=getInstance purgeActionManager=destroyInstance],
SceneReader::[purgeSceneReader=destroyInstance]
rename_classes =
# for all class names, should we remove something when registering in the target VM?
remove_prefix =
# classes for which there will be no "parent" lookup
classes_have_no_parents =
# base classes which will be skipped when their sub-classes found them.
base_classes_to_skip = Ref ProcessBase
# classes that create no constructor
# Set is special and we will use a hand-written constructor
abstract_classes = ArmatureDataManager ComAttribute ComRender ComAudio ActionManagerEx SceneReader GUIReader BatchNode
# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'.
script_control_cpp = no

165
tools/tolua/genbindings.py Executable file
View File

@ -0,0 +1,165 @@
#!/usr/bin/python
# This script is used to generate luabinding glue codes.
# Android ndk version must be ndk-r9b.
import sys
import os, os.path
import shutil
import ConfigParser
import subprocess
import re
from contextlib import contextmanager
def _check_ndk_root_env():
''' Checking the environment NDK_ROOT, which will be used for building
'''
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print "NDK_ROOT not defined. Please define NDK_ROOT in your environment."
sys.exit(1)
return NDK_ROOT
def _check_python_bin_env():
''' Checking the environment PYTHON_BIN, which will be used for building
'''
try:
PYTHON_BIN = os.environ['PYTHON_BIN']
except Exception:
print "PYTHON_BIN not defined, use current python."
PYTHON_BIN = sys.executable
return PYTHON_BIN
class CmdError(Exception):
pass
@contextmanager
def _pushd(newDir):
previousDir = os.getcwd()
os.chdir(newDir)
yield
os.chdir(previousDir)
def _run_cmd(command):
ret = subprocess.call(command, shell=True)
if ret != 0:
message = "Error running command"
raise CmdError(message)
def main():
cur_platform= '??'
llvm_path = '??'
ndk_root = _check_ndk_root_env()
# del the " in the path
ndk_root = re.sub(r"\"", "", ndk_root)
python_bin = _check_python_bin_env()
platform = sys.platform
if platform == 'win32':
cur_platform = 'windows'
elif platform == 'darwin':
cur_platform = platform
elif 'linux' in platform:
cur_platform = 'linux'
else:
print 'Your platform is not supported!'
sys.exit(1)
if platform == 'win32':
x86_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.3/prebuilt', '%s' % cur_platform))
else:
x86_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.3/prebuilt', '%s-%s' % (cur_platform, 'x86')))
x64_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.3/prebuilt', '%s-%s' % (cur_platform, 'x86_64')))
if os.path.isdir(x86_llvm_path):
llvm_path = x86_llvm_path
elif os.path.isdir(x64_llvm_path):
llvm_path = x64_llvm_path
else:
print 'llvm toolchain not found!'
print 'path: %s or path: %s are not valid! ' % (x86_llvm_path, x64_llvm_path)
sys.exit(1)
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
cocos_root = os.path.abspath(os.path.join(project_root, ''))
cxx_generator_root = os.path.abspath(os.path.join(project_root, 'tools/bindings-generator'))
# save config to file
config = ConfigParser.ConfigParser()
config.set('DEFAULT', 'androidndkdir', ndk_root)
config.set('DEFAULT', 'clangllvmdir', llvm_path)
config.set('DEFAULT', 'cocosdir', cocos_root)
config.set('DEFAULT', 'cxxgeneratordir', cxx_generator_root)
config.set('DEFAULT', 'extra_flags', '')
# To fix parse error on windows, we must difine __WCHAR_MAX__ and undefine __MINGW32__ .
if platform == 'win32':
config.set('DEFAULT', 'extra_flags', '-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__')
conf_ini_file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'userconf.ini'))
print 'generating userconf.ini...'
with open(conf_ini_file, 'w') as configfile:
config.write(configfile)
# set proper environment variables
if 'linux' in platform or platform == 'darwin':
os.putenv('LD_LIBRARY_PATH', '%s/libclang' % cxx_generator_root)
if platform == 'win32':
path_env = os.environ['PATH']
os.putenv('PATH', r'%s;%s\libclang;%s\tools\win32;' % (path_env, cxx_generator_root, cxx_generator_root))
try:
tolua_root = '%s/tools/tolua' % project_root
output_dir = '%s/cocos/scripting/lua-bindings/auto' % project_root
cmd_args = {'cocos2dx.ini' : ('cocos2d-x', 'lua_cocos2dx_auto'), \
'cocos2dx_extension.ini' : ('cocos2dx_extension', 'lua_cocos2dx_extension_auto'), \
'cocos2dx_gui.ini' : ('cocos2dx_gui', 'lua_cocos2dx_gui_auto'), \
'cocos2dx_studio.ini' : ('cocos2dx_studio', 'lua_cocos2dx_studio_auto'), \
'cocos2dx_spine.ini' : ('cocos2dx_spine', 'lua_cocos2dx_spine_auto'), \
'cocos2dx_physics.ini' : ('cocos2dx_physics', 'lua_cocos2dx_physics_auto'), \
}
target = 'lua'
generator_py = '%s/generator.py' % cxx_generator_root
for key in cmd_args.keys():
args = cmd_args[key]
cfg = '%s/%s' % (tolua_root, key)
print 'Generating bindings for %s...' % (key[:-4])
command = '%s %s %s -s %s -t %s -o %s -n %s' % (python_bin, generator_py, cfg, args[0], target, output_dir, args[1])
_run_cmd(command)
if platform == 'win32':
with _pushd(output_dir):
_run_cmd('dos2unix *')
print '---------------------------------'
print 'Generating lua bindings succeeds.'
print '---------------------------------'
except Exception as e:
if e.__class__.__name__ == 'CmdError':
print '---------------------------------'
print 'Generating lua bindings fails.'
print '---------------------------------'
sys.exit(1)
else:
raise
# -------------- main --------------
if __name__ == '__main__':
main()

View File

@ -45,7 +45,7 @@ install_nacl_sdk()
if [ "$GEN_COCOS_FILES"x = "YES"x ]; then
exit 0
elif [ "$GEN_JSB"x = "YES"x ]; then
elif [ "$GEN_BINDING"x = "YES"x ]; then
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
exit 0
fi

View File

@ -0,0 +1,129 @@
#!/bin/bash
# Generate Lua bindings for Cocos2D-X
# ... using Android NDK system headers
# ... and push these changes to remote repos
# Dependencies
#
# For bindings generator:
# (see tools/tolua/genbindings.py for the defaults used if the environment is not customized)
#
# * $PYTHON_BIN
# * $CLANG_ROOT
# * $NDK_ROOT
#
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$DIR/../.."
TOLUA_ROOT="$PROJECT_ROOT/tools/tolua"
AUTO_GENERATED_DIR="$PROJECT_ROOT/cocos/scripting/lua-bindings/auto"
COMMITTAG="[AUTO]: updating luabinding automatically"
ELAPSEDSECS=`date +%s`
COCOS_BRANCH="update_lua_bindings_$ELAPSEDSECS"
COCOS_ROBOT_REMOTE="https://${GH_USER}:${GH_PASSWORD}@github.com/${GH_USER}/cocos2d-x.git"
PULL_REQUEST_REPO="https://api.github.com/repos/cocos2d/cocos2d-x/pulls"
# Exit on error
set -e
if [ "$PLATFORM"x = "ios"x ]; then
mkdir -p $HOME/bin
pushd $HOME/bin
curl -O http://pyyaml.org/download/pyyaml/PyYAML-3.10.zip
unzip PyYAML-3.10.zip 2> /dev/null > /dev/null
cd PyYAML-3.10
sudo python setup.py install 2> /dev/null > /dev/null
cd ..
curl -O https://pypi.python.org/packages/source/C/Cheetah/Cheetah-2.4.4.tar.gz
tar xzf Cheetah-2.4.4.tar.gz
cd Cheetah-2.4.4
sudo python setup.py install 2> /dev/null > /dev/null
popd
elif [ $(command -v apt-get) ]; then
sudo apt-get --force-yes --yes install python-yaml python-cheetah
fi
generate_bindings_glue_codes()
{
echo "Create auto-generated luabinding glue codes."
pushd "$TOLUA_ROOT"
./genbindings.py
popd
}
if [ "$GEN_BINDING"x != "YES"x ]; then
generate_bindings_glue_codes
exit 0
fi
pushd "$PROJECT_ROOT"
#Set git user for cocos2d-lua repo
git config user.email ${GH_EMAIL}
git config user.name ${GH_USER}
popd
rm -rf "$AUTO_GENERATED_DIR"
mkdir "$AUTO_GENERATED_DIR"
# 1. Generate LUA bindings
generate_bindings_glue_codes
echo
echo Bindings generated successfully
echo
echo
echo Using "'$COMMITTAG'" in the commit messages
echo
echo Using "$ELAPSEDSECS" in the branch names for pseudo-uniqueness
# 2. In Bindings repo, Check if there are any files that are different from the index
pushd "$PROJECT_ROOT"
# Run status to record the output in the log
git status
echo
echo Comparing with HEAD ...
echo
# Don't exit on non-zero return value
set +e
git diff --stat --exit-code
DIFF_RETVAL=$?
if [ $DIFF_RETVAL -eq 0 ]
then
echo
echo "No differences in generated files"
echo "Exiting with success."
echo
exit 0
else
echo
echo "Generated files differ from HEAD. Continuing."
echo
fi
# Exit on error
set -e
git add -f --all "$AUTO_GENERATED_DIR"
git checkout -b "$COCOS_BRANCH"
git commit -m "$COMMITTAG"
#Set remotes
git remote add upstream "$COCOS_ROBOT_REMOTE" 2> /dev/null > /dev/null
echo "Pushing to Robot's repo ..."
git push -fq upstream "$COCOS_BRANCH" 2> /dev/null
# 7.
echo "Sending Pull Request to base repo ..."
curl --user "${GH_USER}:${GH_PASSWORD}" --request POST --data "{ \"title\": \"$COMMITTAG\", \"body\": \"\", \"head\": \"${GH_USER}:${COCOS_BRANCH}\", \"base\": \"${TRAVIS_BRANCH}\"}" "${PULL_REQUEST_REPO}" 2> /dev/null > /dev/null
popd

View File

@ -13,8 +13,31 @@ if [ -z "$PYTHON_BIN" ]; then
export PYTHON_BIN=/usr/bin/python
fi
if [ "$GEN_BINDING"x = "YES"x ]; then
# Re-generation of the javascript bindings can perform push of the new
# version back to github. We don't do this for pull requests, or if
# GH_USER/GH_EMAIL/GH_PASSWORD environment variables are not set correctly
# by the encoded variables in the .travis.yml file. (e.g. if cloned repo's
# want to use travis).
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
exit 0
fi
if [ -z "${GH_EMAIL}" ]; then
echo "GH_EMAIL not set"
exit 1
fi
if [ -z "${GH_USER}" ]; then
echo "GH_USER not set"
exit 1
fi
if [ -z "${GH_PASSWORD}" ]; then
echo "GH_USER not set"
exit 1
fi
if [ "$GEN_COCOS_FILES"x = "YES"x ]; then
cd $COCOS2DX_ROOT/tools/travis-scripts
./generate-bindings.sh
elif [ "$GEN_COCOS_FILES"x = "YES"x ]; then
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
exit 0
fi
@ -39,6 +62,7 @@ elif [ "$PLATFORM"x = "android"x ]; then
# Generate binding glue codes
echo "Generating bindings glue codes ..."
cd $COCOS2DX_ROOT/tools/travis-scripts
./generate-bindings.sh
./generate-cocosfiles.sh
cd $COCOS2DX_ROOT
@ -66,6 +90,7 @@ elif [ "$PLATFORM"x = "linux"x ]; then
# Generate binding glue codes
echo "Generating bindings glue codes ..."
cd $COCOS2DX_ROOT/tools/travis-scripts
./generate-bindings.sh
./generate-cocosfiles.sh
echo "Building cocos2d-x"
@ -79,6 +104,7 @@ elif [ "$PLATFORM"x = "emscripten"x ]; then
# Generate binding glue codes
echo "Generating bindings glue codes ..."
cd $COCOS2DX_ROOT/tools/travis-scripts
./generate-bindings.sh
./generate-cocosfiles.sh
cd $COCOS2DX_ROOT/build
@ -88,6 +114,7 @@ elif [ "$PLATFORM"x = "emscripten"x ]; then
EMCC_DEBUG=1 make PLATFORM=emscripten -j 8
elif [ "$PLATFORM"x = "ios"x ]; then
cd $COCOS2DX_ROOT/tools/travis-scripts
./generate-bindings.sh
./generate-cocosfiles.sh
cd $COCOS2DX_ROOT