Merge branch 'develop' into develop_nutty_modifylayout_add_Boxes

This commit is contained in:
CaiWenzhi 2014-04-17 14:23:08 +08:00
commit ed4fcd5d1a
40 changed files with 596 additions and 221 deletions

6
.gitignore vendored
View File

@ -111,3 +111,9 @@ CMakeCache.txt
CMakeFiles
Makefile
cmake_install.cmake
# Ignore files generated by console
build/build/
cocos/scripting/lua-bindings/proj.ios_mac/build/
tests/*/runtime/
tests/*/publish/

View File

@ -817,12 +817,16 @@ Developers:
iSevenDays
Fixed a bug that the result of 'malloc' is incompatible with type 'unsigned char *' in Image::saveImageToPNG
Fixed a potential memory leak in CCEditBoxImplIOS.mm
Fixed incompatible pointer conversion in external/chipmunk/src/cpArray.c
ololomax
Fixed a potential crash in SceneReader::createNodeWithSceneFile
gaoxiaosong
Fixed a warning in cpCollision.c
sachingarg05
Re-added orientation change callback in java activity
Retired Core Developers:
WenSheng Yang

View File

@ -1 +1 @@
3dec43835640892d3595d2063489624cf216dd73
5c54d396206175b71038b1b99d2db31443421952

View File

@ -76,7 +76,11 @@ ClippingNode::ClippingNode()
ClippingNode::~ClippingNode()
{
CC_SAFE_RELEASE(_stencil);
if (_stencil)
{
_stencil->stopAllActions();
_stencil->release();
}
}
ClippingNode* ClippingNode::create()
@ -291,9 +295,9 @@ Node* ClippingNode::getStencil() const
void ClippingNode::setStencil(Node *stencil)
{
CC_SAFE_RETAIN(stencil);
CC_SAFE_RELEASE(_stencil);
_stencil = stencil;
CC_SAFE_RETAIN(_stencil);
}
GLfloat ClippingNode::getAlphaThreshold() const

View File

@ -349,9 +349,9 @@ void EventDispatcher::removeEventListenersForTarget(Node* target, bool recursive
{
EventListener * listener = *iter;
if (listener->getSceneGraphPriority() == target)
if (listener->getAssociatedNode() == target)
{
listener->setSceneGraphPriority(nullptr); // Ensure no dangling ptr to the target node.
listener->setAssociatedNode(nullptr); // Ensure no dangling ptr to the target node.
listener->setRegistered(false);
listener->release();
iter = _toAddedListeners.erase(iter);
@ -446,7 +446,7 @@ void EventDispatcher::forceAddEventListener(EventListener* listener)
{
setDirty(listenerID, DirtyFlag::SCENE_GRAPH_PRIORITY);
auto node = listener->getSceneGraphPriority();
auto node = listener->getAssociatedNode();
CCASSERT(node != nullptr, "Invalid scene graph priority!");
associateNodeAndEventListener(node, listener);
@ -470,7 +470,7 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list
if (!listener->checkAvailable())
return;
listener->setSceneGraphPriority(node);
listener->setAssociatedNode(node);
listener->setFixedPriority(0);
listener->setRegistered(true);
@ -493,7 +493,7 @@ void EventDispatcher::debugCheckNodeHasNoEventListenersOnDestruction(Node* node)
for (EventListener * listener : *eventListenerVector->getSceneGraphPriorityListeners())
{
CCASSERT(!listener ||
listener->getSceneGraphPriority() != node,
listener->getAssociatedNode() != node,
"Node should have no event listeners registered for it upon destruction!");
}
}
@ -509,7 +509,7 @@ void EventDispatcher::debugCheckNodeHasNoEventListenersOnDestruction(Node* node)
{
for (EventListener * listener : *keyValuePair.second)
{
CCASSERT(listener->getSceneGraphPriority() != node,
CCASSERT(listener->getAssociatedNode() != node,
"Node should have no event listeners registered for it upon destruction!");
}
}
@ -525,7 +525,7 @@ void EventDispatcher::debugCheckNodeHasNoEventListenersOnDestruction(Node* node)
// Check the to be added list
for (EventListener * listener : _toAddedListeners)
{
CCASSERT(listener->getSceneGraphPriority() != node,
CCASSERT(listener->getAssociatedNode() != node,
"Node should have no event listeners registered for it upon destruction!");
}
@ -549,7 +549,7 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener,
if (!listener->checkAvailable())
return;
listener->setSceneGraphPriority(nullptr);
listener->setAssociatedNode(nullptr);
listener->setFixedPriority(fixedPriority);
listener->setRegistered(true);
listener->setPaused(false);
@ -582,10 +582,10 @@ void EventDispatcher::removeEventListener(EventListener* listener)
{
CC_SAFE_RETAIN(l);
l->setRegistered(false);
if (l->getSceneGraphPriority() != nullptr)
if (l->getAssociatedNode() != nullptr)
{
dissociateNodeAndEventListener(l->getSceneGraphPriority(), l);
l->setSceneGraphPriority(nullptr); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes.
dissociateNodeAndEventListener(l->getAssociatedNode(), l);
l->setAssociatedNode(nullptr); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes.
}
if (_inDispatch == 0)
@ -681,7 +681,7 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority)
auto found = std::find(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener);
if (found != fixedPriorityListeners->end())
{
CCASSERT(listener->getSceneGraphPriority() == nullptr, "Can't set fixed priority with scene graph based listener.");
CCASSERT(listener->getAssociatedNode() == nullptr, "Can't set fixed priority with scene graph based listener.");
if (listener->getFixedPriority() != fixedPriority)
{
@ -782,7 +782,7 @@ void EventDispatcher::dispatchEvent(Event* event)
auto listeners = iter->second;
auto onEvent = [&event](EventListener* listener) -> bool{
event->setCurrentTarget(listener->getSceneGraphPriority());
event->setCurrentTarget(listener->getAssociatedNode());
listener->_onEvent(event);
return event->isStopped();
};
@ -1168,7 +1168,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener
// After sort: priority < 0, > 0
std::sort(sceneGraphListeners->begin(), sceneGraphListeners->end(), [this](const EventListener* l1, const EventListener* l2) {
return _nodePriorityMap[l1->getSceneGraphPriority()] > _nodePriorityMap[l2->getSceneGraphPriority()];
return _nodePriorityMap[l1->getAssociatedNode()] > _nodePriorityMap[l2->getAssociatedNode()];
});
#if DUMP_LISTENER_ITEM_PRIORITY_INFO
@ -1245,10 +1245,10 @@ void EventDispatcher::removeEventListenersForListenerID(const EventListener::Lis
{
auto l = *iter;
l->setRegistered(false);
if (l->getSceneGraphPriority() != nullptr)
if (l->getAssociatedNode() != nullptr)
{
dissociateNodeAndEventListener(l->getSceneGraphPriority(), l);
l->setSceneGraphPriority(nullptr); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes.
dissociateNodeAndEventListener(l->getAssociatedNode(), l);
l->setAssociatedNode(nullptr); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes.
}
if (_inDispatch == 0)

View File

@ -128,13 +128,13 @@ protected:
*/
inline int getFixedPriority() const { return _fixedPriority; };
/** Sets scene graph priority for this listener */
inline void setSceneGraphPriority(Node* node) { _node = node; };
/** Sets the node associated with this listener */
inline void setAssociatedNode(Node* node) { _node = node; };
/** Gets scene graph priority of this listener
* @return nullptr if it's a fixed priority listener, non-nullptr for scene graph priority listener
/** Gets the node associated with this listener
* @return nullptr if it's a fixed priority listener, otherwise return non-nullptr
*/
inline Node* getSceneGraphPriority() const { return _node; };
inline Node* getAssociatedNode() const { return _node; };
///////////////
// Properties

View File

@ -258,6 +258,7 @@ Label::Label(FontAtlas *atlas /* = nullptr */, TextHAlignment hAlignment /* = Te
, _textSprite(nullptr)
, _contentDirty(false)
, _shadowDirty(false)
, _compatibleMode(false)
{
setAnchorPoint(Point::ANCHOR_MIDDLE);
reset();
@ -943,6 +944,7 @@ void Label::setFontDefinition(const FontDefinition& textDefinition)
_fontDefinition._shadow._shadowEnabled = false;
enableShadow(Color4B(0,0,0,255 * _fontDefinition._shadow._shadowOpacity),_fontDefinition._shadow._shadowOffset,_fontDefinition._shadow._shadowBlur);
}
_compatibleMode = true;
}
void Label::updateContent()
@ -968,41 +970,44 @@ void Label::updateContent()
}
else
{
_fontDefinition._fontName = _systemFont;
_fontDefinition._fontSize = _systemFontSize;
_fontDefinition._alignment = _hAlignment;
_fontDefinition._vertAlignment = _vAlignment;
_fontDefinition._dimensions.width = _labelWidth;
_fontDefinition._dimensions.height = _labelHeight;
_fontDefinition._fontFillColor.r = _textColor.r;
_fontDefinition._fontFillColor.g = _textColor.g;
_fontDefinition._fontFillColor.b = _textColor.b;
_fontDefinition._shadow._shadowEnabled = false;
if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0)
if (!_compatibleMode)
{
_fontDefinition._stroke._strokeEnabled = true;
_fontDefinition._stroke._strokeSize = _outlineSize;
_fontDefinition._stroke._strokeColor.r = _effectColor.r;
_fontDefinition._stroke._strokeColor.g = _effectColor.g;
_fontDefinition._stroke._strokeColor.b = _effectColor.b;
}
else
{
_fontDefinition._stroke._strokeEnabled = false;
}
_fontDefinition._fontName = _systemFont;
_fontDefinition._fontSize = _systemFontSize;
_fontDefinition._alignment = _hAlignment;
_fontDefinition._vertAlignment = _vAlignment;
_fontDefinition._dimensions.width = _labelWidth;
_fontDefinition._dimensions.height = _labelHeight;
_fontDefinition._fontFillColor.r = _textColor.r;
_fontDefinition._fontFillColor.g = _textColor.g;
_fontDefinition._fontFillColor.b = _textColor.b;
_fontDefinition._shadow._shadowEnabled = false;
if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0)
{
_fontDefinition._stroke._strokeEnabled = true;
_fontDefinition._stroke._strokeSize = _outlineSize;
_fontDefinition._stroke._strokeColor.r = _effectColor.r;
_fontDefinition._stroke._strokeColor.g = _effectColor.g;
_fontDefinition._stroke._strokeColor.b = _effectColor.b;
}
else
{
_fontDefinition._stroke._strokeEnabled = false;
}
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
if (_fontDefinition._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
_fontDefinition._stroke._strokeEnabled = false;
if (_fontDefinition._stroke._strokeEnabled)
{
CCLOGERROR("Currently only supported on iOS and Android!");
}
_fontDefinition._stroke._strokeEnabled = false;
#endif
}
createSpriteWithFontDefinition();
}

View File

@ -325,6 +325,7 @@ protected:
//compatibility with older LabelTTF
Sprite* _textSprite;
FontDefinition _fontDefinition;
bool _compatibleMode;
//! used for optimization
Sprite *_reusedLetter;

View File

@ -589,7 +589,7 @@ void Sprite::updateTransform(void)
void Sprite::draw(Renderer *renderer, const kmMat4 &transform, bool transformUpdated)
{
// Don't do calculate the culling if the transform was not updated
_insideBounds = transformUpdated ? isInsideBounds() : _insideBounds;
_insideBounds = transformUpdated ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
if(_insideBounds)
{
@ -621,35 +621,6 @@ void Sprite::drawDebugData()
}
#endif //CC_SPRITE_DEBUG_DRAW
// Culling function from cocos2d-iphone CCSprite.m file
bool Sprite::isInsideBounds() const
{
// half size of the screen
Size screen_half = Director::getInstance()->getWinSize();
screen_half.width /= 2;
screen_half.height /= 2;
float hcsx = _contentSize.width / 2;
float hcsy = _contentSize.height / 2;
// convert to world coordinates
float x = hcsx * _modelViewTransform.mat[0] + hcsy * _modelViewTransform.mat[4] + _modelViewTransform.mat[12];
float y = hcsx * _modelViewTransform.mat[1] + hcsy * _modelViewTransform.mat[5] + _modelViewTransform.mat[13];
// center of screen is (0,0)
x -= screen_half.width;
y -= screen_half.height;
// convert content size to world coordinates
float wchw = hcsx * std::max(fabsf(_modelViewTransform.mat[0] + _modelViewTransform.mat[4]), fabsf(_modelViewTransform.mat[0] - _modelViewTransform.mat[4]));
float wchh = hcsy * std::max(fabsf(_modelViewTransform.mat[1] + _modelViewTransform.mat[5]), fabsf(_modelViewTransform.mat[1] - _modelViewTransform.mat[5]));
// compare if it in the positive quadrant of the screen
float tmpx = (fabsf(x)-wchw);
float tmpy = (fabsf(y)-wchh);
return (tmpx < screen_half.width && tmpy < screen_half.height);
}
// Node overrides
void Sprite::addChild(Node *child, int zOrder, int tag)
{

View File

@ -527,8 +527,6 @@ protected:
virtual void setReorderChildDirtyRecursively(void);
virtual void setDirtyRecursively(bool bValue);
bool isInsideBounds() const;
//
// Data used when the sprite is rendered using a SpriteSheet
//
@ -574,7 +572,6 @@ protected:
bool _flippedY; /// Whether the sprite is flipped vertically or not
bool _insideBounds; /// whether or not the sprite was inside bounds the previous frame
private:
CC_DISALLOW_COPY_AND_ASSIGN(Sprite);
};

View File

@ -93,7 +93,7 @@ std::string TextureCache::getDescription() const
return StringUtils::format("<TextureCache | Number of textures = %d>", static_cast<int>(_textures.size()));
}
void TextureCache::addImageAsync(const std::string &path, std::function<void(Texture2D*)> callback)
void TextureCache::addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback)
{
Texture2D *texture = nullptr;

View File

@ -117,7 +117,7 @@ public:
* Supported image extensions: .png, .jpg
* @since v0.8
*/
virtual void addImageAsync(const std::string &filepath, std::function<void(Texture2D*)> callback);
virtual void addImageAsync(const std::string &filepath, const std::function<void(Texture2D*)>& callback);
/** Returns a Texture2D object given an Image.
* If the image was not previously loaded, it will create a new Texture2D object and it will return it.

View File

@ -31,7 +31,7 @@ NS_CC_BEGIN
const char* cocos2dVersion()
{
return "3.0";
return "3.0-rc2";
}
NS_CC_END

View File

@ -75,6 +75,7 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
@Override
public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) {
Cocos2dxRenderer.nativeOnSurfaceChanged(pWidth, pHeight);
}
@Override
@ -118,6 +119,7 @@ public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
private static native boolean nativeKeyDown(final int pKeyCode);
private static native void nativeRender();
private static native void nativeInit(final int pWidth, final int pHeight);
private static native void nativeOnSurfaceChanged(final int pWidth, final int pHeight);
private static native void nativeOnPause();
private static native void nativeOnResume();

View File

@ -79,4 +79,10 @@ void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thi
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnSurfaceChanged(JNIEnv* env, jobject thiz, jint w, jint h)
{
cocos2d::Application::getInstance()->applicationScreenSizeChanged(w, h);
}
}

View File

@ -29,20 +29,6 @@
NS_CC_BEGIN
static GroupCommandManager* s_instance;
GroupCommandManager *GroupCommandManager::getInstance()
{
if(!s_instance)
{
s_instance = new GroupCommandManager();
if(!s_instance->init())
{
CC_SAFE_DELETE(s_instance);
}
}
return s_instance;
}
GroupCommandManager::GroupCommandManager()
{
@ -50,7 +36,7 @@ GroupCommandManager::GroupCommandManager()
GroupCommandManager::~GroupCommandManager()
{
CC_SAFE_RELEASE_NULL(s_instance);
}
bool GroupCommandManager::init()
@ -88,19 +74,20 @@ void GroupCommandManager::releaseGroupID(int groupID)
GroupCommand::GroupCommand()
{
_type = RenderCommand::Type::GROUP_COMMAND;
_renderQueueID = GroupCommandManager::getInstance()->getGroupID();
_renderQueueID = Director::getInstance()->getRenderer()->getGroupCommandManager()->getGroupID();
}
void GroupCommand::init(float globalOrder)
{
_globalOrder = globalOrder;
GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID);
_renderQueueID = GroupCommandManager::getInstance()->getGroupID();
auto manager = Director::getInstance()->getRenderer()->getGroupCommandManager();
manager->releaseGroupID(_renderQueueID);
_renderQueueID = manager->getGroupID();
}
GroupCommand::~GroupCommand()
{
GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID);
Director::getInstance()->getRenderer()->getGroupCommandManager()->releaseGroupID(_renderQueueID);
}
NS_CC_END

View File

@ -37,17 +37,14 @@ NS_CC_BEGIN
class GroupCommandManager : public Ref
{
public:
static GroupCommandManager* getInstance();
~GroupCommandManager();
bool init();
int getGroupID();
void releaseGroupID(int groupID);
protected:
friend class Renderer;
GroupCommandManager();
~GroupCommandManager();
bool init();
std::unordered_map<int, bool> _groupMapping;
};

View File

@ -23,6 +23,9 @@
****************************************************************************/
#include "renderer/CCRenderer.h"
#include <algorithm>
#include "renderer/CCQuadCommand.h"
#include "renderer/CCBatchCommand.h"
#include "renderer/CCCustomCommand.h"
@ -34,15 +37,19 @@
#include "CCEventDispatcher.h"
#include "CCEventListenerCustom.h"
#include "CCEventType.h"
#include <algorithm>
#include "kazmath/kazmath.h"
NS_CC_BEGIN
// helper
bool compareRenderCommand(RenderCommand* a, RenderCommand* b)
{
return a->getGlobalOrder() < b->getGlobalOrder();
}
// queue
void RenderQueue::push_back(RenderCommand* command)
{
float z = command->getGlobalOrder();
@ -92,12 +99,14 @@ void RenderQueue::clear()
_queuePosZ.clear();
}
//
//
//
static const int DEFAULT_RENDER_QUEUE = 0;
//
// constructors, destructors, init
//
//
#define DEFAULT_RENDER_QUEUE 0
Renderer::Renderer()
:_lastMaterialID(0)
,_numQuads(0)
@ -107,6 +116,8 @@ Renderer::Renderer()
,_cacheTextureListener(nullptr)
#endif
{
_groupCommandManager = new GroupCommandManager();
_commandGroupStack.push(DEFAULT_RENDER_QUEUE);
RenderQueue defaultRenderQueue;
@ -117,6 +128,7 @@ Renderer::Renderer()
Renderer::~Renderer()
{
_renderGroups.clear();
_groupCommandManager->release();
glDeleteBuffers(2, _buffersVBO);
@ -494,4 +506,36 @@ void Renderer::flush()
_lastMaterialID = 0;
}
// helpers
bool Renderer::checkVisibility(const kmMat4 &transform, const Size &size)
{
// half size of the screen
Size screen_half = Director::getInstance()->getWinSize();
screen_half.width /= 2;
screen_half.height /= 2;
float hSizeX = size.width/2;
float hSizeY = size.height/2;
kmVec4 v4world, v4local;
kmVec4Fill(&v4local, hSizeX, hSizeY, 0, 1);
kmVec4MultiplyMat4(&v4world, &v4local, &transform);
// center of screen is (0,0)
v4world.x -= screen_half.width;
v4world.y -= screen_half.height;
// convert content size to world coordinates
float wshw = std::max(fabsf(hSizeX * transform.mat[0] + hSizeY * transform.mat[4]), fabsf(hSizeX * transform.mat[0] - hSizeY * transform.mat[4]));
float wshh = std::max(fabsf(hSizeX * transform.mat[1] + hSizeY * transform.mat[5]), fabsf(hSizeX * transform.mat[1] - hSizeY * transform.mat[5]));
// compare if it in the positive quadrant of the screen
float tmpx = (fabsf(v4world.x)-wshw);
float tmpy = (fabsf(v4world.y)-wshh);
bool ret = (tmpx < screen_half.width && tmpy < screen_half.height);
return ret;
}
NS_CC_END

View File

@ -64,6 +64,8 @@ struct RenderStackElement
ssize_t currentIndex;
};
class GroupCommandManager;
/* Class responsible for the rendering in.
Whenever possible prefer to use `QuadCommand` objects since the renderer will automatically batch them.
@ -110,6 +112,11 @@ public:
/* RenderCommands (except) QuadCommand should update this value */
void addDrawnVertices(ssize_t number) { _drawnVertices += number; };
inline GroupCommandManager* getGroupCommandManager() const { return _groupCommandManager; };
/** returns whether or not a rectangle is visible or not */
bool checkVisibility(const kmMat4& transform, const Size& size);
protected:
void setupIndices();
@ -151,6 +158,8 @@ protected:
//the flag for checking whether renderer is rendering
bool _isRendering;
GroupCommandManager* _groupCommandManager;
#if CC_ENABLE_CACHE_TEXTURE_DATA
EventListenerCustom* _cacheTextureListener;
#endif

View File

@ -203,8 +203,10 @@ void Audio::StopBackgroundMusic(bool bReleaseData)
StopSoundEffect(m_backgroundID);
if (bReleaseData)
if (bReleaseData){
UnloadSoundEffect(m_backgroundID);
RemoveFromList(m_backgroundID);
}
}
void Audio::PauseBackgroundMusic()
@ -406,7 +408,8 @@ void Audio::PauseAllSoundEffects()
EffectList::iterator iter;
for (iter = m_soundEffects.begin(); iter != m_soundEffects.end(); iter++)
{
PauseSoundEffect(iter->first);
if (iter->first != m_backgroundID)
PauseSoundEffect(iter->first);
}
}
@ -419,11 +422,12 @@ void Audio::ResumeAllSoundEffects()
EffectList::iterator iter;
for (iter = m_soundEffects.begin(); iter != m_soundEffects.end(); iter++)
{
ResumeSoundEffect(iter->first);
if (iter->first != m_backgroundID)
ResumeSoundEffect(iter->first);
}
}
void Audio::StopAllSoundEffects()
void Audio::StopAllSoundEffects(bool bReleaseData)
{
if (m_engineExperiencedCriticalError) {
return;
@ -432,8 +436,27 @@ void Audio::StopAllSoundEffects()
EffectList::iterator iter;
for (iter = m_soundEffects.begin(); iter != m_soundEffects.end(); iter++)
{
StopSoundEffect(iter->first);
if (iter->first != m_backgroundID){
StopSoundEffect(iter->first);
if (bReleaseData)
{
UnloadSoundEffect(iter->first);
}
}
}
if (bReleaseData)
{
for (iter = m_soundEffects.begin(); iter != m_soundEffects.end();)
{
if (iter->first != m_backgroundID){
m_soundEffects.erase(iter++);
}
else
{
iter++;
}
}
}
}
bool Audio::IsSoundEffectStarted(unsigned int sound)
@ -556,6 +579,8 @@ void Audio::UnloadSoundEffect(const char* pszFilePath)
int sound = Hash(pszFilePath);
UnloadSoundEffect(sound);
RemoveFromList(sound);
}
void Audio::UnloadSoundEffect(unsigned int sound)
@ -575,7 +600,12 @@ void Audio::UnloadSoundEffect(unsigned int sound)
m_soundEffects[sound].m_soundEffectBufferData = nullptr;
m_soundEffects[sound].m_soundEffectSourceVoice = nullptr;
m_soundEffects[sound].m_soundEffectStarted = false;
ZeroMemory(&m_soundEffects[sound].m_audioBuffer, sizeof(m_soundEffects[sound].m_audioBuffer));
ZeroMemory(&m_soundEffects[sound].m_audioBuffer, sizeof(m_soundEffects[sound].m_audioBuffer));
}
void Audio::RemoveFromList( unsigned int sound )
{
m_soundEffects.erase(sound);
}

View File

@ -156,9 +156,12 @@ public:
void PauseAllSoundEffects();
void ResumeAllSoundEffects();
void StopAllSoundEffects();
void StopAllSoundEffects(bool bReleaseData);
void PreloadSoundEffect(const char* pszFilePath, bool isMusic = false);
void UnloadSoundEffect(const char* pszFilePath);
void UnloadSoundEffect(unsigned int sound);
private:
void RemoveFromList(unsigned int sound);
};

View File

@ -63,7 +63,7 @@ SimpleAudioEngine::~SimpleAudioEngine()
void SimpleAudioEngine::end()
{
sharedAudioController()->StopBackgroundMusic(true);
sharedAudioController()->StopAllSoundEffects();
sharedAudioController()->StopAllSoundEffects(true);
sharedAudioController()->ReleaseResources();
s_initialized = false;
}
@ -158,7 +158,7 @@ void SimpleAudioEngine::resumeAllEffects()
void SimpleAudioEngine::stopAllEffects()
{
sharedAudioController()->StopAllSoundEffects();
sharedAudioController()->StopAllSoundEffects(false);
}
void SimpleAudioEngine::preloadBackgroundMusic(const char* pszFilePath)

View File

@ -40,7 +40,9 @@ THE SOFTWARE.
#define IMPLEMENT_CLASS_INFO(className) \
cocos2d::Ref* className::createInstance(void) \
{ \
return new className; \
auto ret = new className; \
ret->autorelease(); \
return ret; \
} \
cocostudio::ObjectFactory::TInfo className::Type(#className, &className::createInstance); \

View File

@ -28,6 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "vec2.h"
#include "vec3.h"
#include "vec4.h"
#include "mat3.h"
#include "mat4.h"
#include "utility.h"

View File

@ -31,6 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "vec4.h"
#include "mat4.h"
#include "neon_matrix_impl.h"
kmVec4* kmVec4Fill(kmVec4* pOut, kmScalar x, kmScalar y, kmScalar z, kmScalar w)
{
@ -137,10 +138,14 @@ kmVec4* kmVec4Div( kmVec4* pOut,const kmVec4* pV1, const kmVec4* pV2 ) {
/// Multiplies a 4D vector by a matrix, the result is stored in pOut, and pOut is returned.
kmVec4* kmVec4MultiplyMat4(kmVec4* pOut, const kmVec4* pV, const struct kmMat4* pM) {
#if defined(__ARM_NEON__) && !defined(__arm64__)
NEON_Matrix4Vector4Mul(&pM->mat[0], (const float*)pV, (float*)pOut);
#else
pOut->x = pV->x * pM->mat[0] + pV->y * pM->mat[4] + pV->z * pM->mat[8] + pV->w * pM->mat[12];
pOut->y = pV->x * pM->mat[1] + pV->y * pM->mat[5] + pV->z * pM->mat[9] + pV->w * pM->mat[13];
pOut->z = pV->x * pM->mat[2] + pV->y * pM->mat[6] + pV->z * pM->mat[10] + pV->w * pM->mat[14];
pOut->w = pV->x * pM->mat[3] + pV->y * pM->mat[7] + pV->z * pM->mat[11] + pV->w * pM->mat[15];
#endif
return pOut;
}

View File

@ -384,7 +384,8 @@ void Slider::setPercent(int percent)
bool Slider::hitTest(const cocos2d::Point &pt)
{
Point nsp = this->_slidBallNormalRenderer->convertToNodeSpace(pt);
Rect ballRect = this->_slidBallNormalRenderer->getTextureRect();
Size ballSize = this->_slidBallNormalRenderer->getContentSize();
Rect ballRect = Rect(0,0, ballSize.width, ballSize.height);
if (ballRect.containsPoint(nsp)) {
return true;
}

View File

@ -52,7 +52,7 @@ cpArrayPush(cpArray *arr, void *object)
{
if(arr->num == arr->max){
arr->max *= 2;
arr->arr = (void **)cprealloc(arr->arr, arr->max*sizeof(void**));
arr->arr = (void **)cprealloc(arr->arr, arr->max*sizeof(void*));
}
arr->arr[arr->num] = object;

View File

@ -60,6 +60,14 @@ NDK_ROOT = 'NDK_ROOT'
ANDROID_SDK_ROOT = 'ANDROID_SDK_ROOT'
ANT_ROOT = 'ANT_ROOT'
def _check_python_version():
major_ver = sys.version_info[0]
if major_ver > 2:
print ("The python version is %d.%d. But python 2.x is required. (Version 2.7 is well tested)\n"
"Download it here: https://www.python.org/" % (major_ver, sys.version_info[1]))
return False
return True
class SetEnvVar(object):
@ -168,7 +176,7 @@ class SetEnvVar(object):
def _set_environment_variable(self, key, value):
print " -> Add %s environment variable..." % key
print(" -> Add %s environment variable..." % key)
ret = False
if self._isWindows():
ret = self._set_environment_variable_win32(key, value)
@ -176,9 +184,9 @@ class SetEnvVar(object):
ret = self._set_environment_variable_unix(key, value)
if ret:
print " ->Added %s=%s\n" % (key, value)
print(" ->Added %s=%s\n" % (key, value))
else:
print " ->Add failed\n"
print(" ->Add failed\n")
return ret
@ -199,7 +207,7 @@ class SetEnvVar(object):
return ret
def _find_environment_variable(self, var):
print " ->Find environment variable %s..." % var
print(" ->Find environment variable %s..." % var)
ret = None
try:
ret = os.environ[var]
@ -227,7 +235,7 @@ class SetEnvVar(object):
0,
_winreg.KEY_READ)
ret = _winreg.QueryValueEx(env, var)
ret = _winreg.QueryValueEx(env, var)[0]
_winreg.CloseKey(env)
except Exception:
if env:
@ -235,9 +243,9 @@ class SetEnvVar(object):
ret = None
if ret is None:
print " ->%s not found\n" % var
print(" ->%s not found\n" % var)
else:
print " ->%s is found : %s\n" % (var, ret)
print(" ->%s is found : %s\n" % (var, ret))
return ret
@ -320,7 +328,7 @@ class SetEnvVar(object):
ret = False
if not ret:
print ' ->Error: "%s" is not a valid path of %s. Ignoring it.' % (value, var_name)
print(' ->Error: "%s" is not a valid path of %s. Ignoring it.' % (value, var_name))
return ret
@ -384,9 +392,9 @@ class SetEnvVar(object):
_winreg.FlushKey(env)
_winreg.CloseKey(env)
print ' ->Remove directory \"%s\" from PATH!\n' % remove_dir
print(' ->Remove directory \"%s\" from PATH!\n' % remove_dir)
except Exception:
print ' ->Remove directory \"%s\" from PATH failed!\n' % remove_dir
print(' ->Remove directory \"%s\" from PATH failed!\n' % remove_dir)
def set_windows_path(self, add_dir):
ret = False
@ -425,13 +433,13 @@ class SetEnvVar(object):
_winreg.CloseKey(env)
if ret:
print " ->Add directory \"%s\" into PATH succeed!\n" % add_dir
print(" ->Add directory \"%s\" into PATH succeed!\n" % add_dir)
else:
print " ->Add directory \"%s\" into PATH failed!\n" % add_dir
print(" ->Add directory \"%s\" into PATH failed!\n" % add_dir)
def set_console_root(self):
print "->Check environment variable %s" % COCOS_CONSOLE_ROOT
print("->Check environment variable %s" % COCOS_CONSOLE_ROOT)
cocos_consle_root = os.path.join(self.current_absolute_path, 'tools', 'cocos2d-console', 'bin')
old_dir = self._find_environment_variable(COCOS_CONSOLE_ROOT)
if old_dir is None:
@ -441,6 +449,10 @@ class SetEnvVar(object):
self._set_environment_variable(COCOS_CONSOLE_ROOT, cocos_consle_root)
else:
if old_dir == cocos_consle_root:
# is same with before, nothing to do
return
# update the environment variable
if self._isWindows():
self.remove_dir_from_win_path(old_dir)
@ -459,7 +471,7 @@ class SetEnvVar(object):
if self._isLinux():
file_list = SetEnvVar.LINUX_CHECK_FILES
print " ->Update variable %s in files %s" % (var_name, str(file_list))
print(" ->Update variable %s in files %s" % (var_name, str(file_list)))
variable_updated = False
for file_name in file_list:
path = os.path.join(home, file_name)
@ -484,11 +496,11 @@ class SetEnvVar(object):
file_obj = open(path, 'w')
file_obj.writelines(lines)
file_obj.close()
print " ->File %s updated!" % path
print(" ->File %s updated!" % path)
# nothing updated, should add variable
if not variable_updated:
print "\n ->No files updated, add variable %s instead!" % var_name
print("\n ->No files updated, add variable %s instead!" % var_name)
ret = self._set_environment_variable(var_name, value)
else:
ret = True
@ -499,18 +511,39 @@ class SetEnvVar(object):
def _force_update_env(self, var_name, value):
ret = False
if self._isWindows():
print " ->Force update environment variable %s" % var_name
print(" ->Force update environment variable %s" % var_name)
ret = self._set_environment_variable_win32(var_name, value)
if not ret:
print " ->Failed!"
print(" ->Failed!")
else:
print " ->Succeed : %s=%s" % (var_name, value)
print(" ->Succeed : %s=%s" % (var_name, value))
else:
ret = self._force_update_unix_env(var_name, value)
return ret
def _get_ant_path(self):
print(" ->Find command ant in system...")
ret = None
if not self._isWindows():
import commands
state, result = commands.getstatusoutput("which ant")
if state == 0:
ret = os.path.dirname(result)
if ret is not None:
print(" ->Path \"%s\" was found\n" % ret)
else:
print(" ->Command ant not found\n")
return ret
def _find_value_from_sys(self, var_name):
if var_name == ANT_ROOT:
return self._get_ant_path()
else:
return None
def set_variable(self, var_name, value):
print "->Check environment variable %s" % var_name
print("->Check environment variable %s" % var_name)
find_value = self._find_environment_variable(var_name)
var_found = (find_value is not None)
action_none = 0
@ -526,6 +559,10 @@ class SetEnvVar(object):
# do nothing
need_action = action_none
else:
if not value:
# find the command path in system
value = self._find_value_from_sys(var_name)
if not value:
value = self._get_input_value(var_name)
@ -558,7 +595,7 @@ class SetEnvVar(object):
def set_environment_variables(self, ndk_root, android_sdk_root, ant_root):
print '\nSetting up cocos2d-x...'
print('\nSetting up cocos2d-x...')
self.file_used_for_setup = self._get_filepath_for_setup()
@ -569,15 +606,17 @@ class SetEnvVar(object):
# tip the backup file
if (self.backup_file is not None) and (os.path.exists(self.backup_file)):
print '\nA backup file \"%s\" is created for \"%s\".' % (self.backup_file, self.file_used_for_setup)
print('\nA backup file \"%s\" is created for \"%s\".' % (self.backup_file, self.file_used_for_setup))
if self._isWindows():
print '\nPlease restart the terminal or restart computer to make added system variables take effect\n'
print('\nPlease restart the terminal or restart computer to make added system variables take effect\n')
else:
print '\nPlease execute command: "source %s" to make added system variables take effect\n' % self.file_used_for_setup
print('\nPlease execute command: "source %s" to make added system variables take effect\n' % self.file_used_for_setup)
if __name__ == '__main__':
if not _check_python_version():
exit()
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')
@ -587,3 +626,12 @@ if __name__ == '__main__':
# set environment variables
env = SetEnvVar()
env.set_environment_variables(opts.ndk_root, opts.android_sdk_root, opts.ant_root)
if env._isWindows():
import ctypes
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x1A
SMTO_ABORTIFHUNG = 0x0002
result = ctypes.c_long()
SendMessageTimeoutW = ctypes.windll.user32.SendMessageTimeoutW
SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment', SMTO_ABORTIFHUNG, 5000, ctypes.byref(result))

View File

@ -70,14 +70,20 @@
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView();
cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView();
if (glview)
{
CCEAGLView *eaglview = (CCEAGLView*) glview->getEAGLView();
CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]);
cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height);
if (eaglview)
{
CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]);
cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height);
}
}
}
//fix not hide status on ios7

View File

@ -472,54 +472,47 @@ std::string NewDrawNodeTest::subtitle() const
NewCullingTest::NewCullingTest()
{
auto s = Director::getInstance()->getWinSize();
Size size = Director::getInstance()->getWinSize();
auto sprite = Sprite::create("Images/btn-about-normal-vertical.png");
sprite->setRotation(5);
sprite->setPosition(Point(size.width/2,size.height/3));
sprite->setScale(2);
addChild(sprite);
std::vector<std::string> images;
images.push_back("Images/grossini_dance_01.png");
images.push_back("Images/grossini_dance_02.png");
images.push_back("Images/grossini_dance_03.png");
images.push_back("Images/grossini_dance_04.png");
images.push_back("Images/grossini_dance_05.png");
images.push_back("Images/grossini_dance_06.png");
images.push_back("Images/grossini_dance_07.png");
images.push_back("Images/grossini_dance_08.png");
images.push_back("Images/grossini_dance_09.png");
images.push_back("Images/grossini_dance_10.png");
images.push_back("Images/grossini_dance_11.png");
images.push_back("Images/grossini_dance_12.png");
images.push_back("Images/grossini_dance_13.png");
images.push_back("Images/grossini_dance_14.png");
images.push_back("Images/grossini.png");
auto parent = Node::create();
parent->setPosition(s.width/2, s.height/2);
addChild(parent);
for(int index = 0; index < 500; ++index)
{
auto parent2 = Node::create();
parent2->setPosition(0,0);
parent->addChild(parent2);
parent2->setPosition(-50,0);
parent2->runAction(RepeatForever::create((JumpBy::create(10, Point(0,0), 400, 1))));
Sprite* sprite = Sprite::create(images[index % images.size()].c_str());
sprite->setPosition(Point(0,0));
//sprite->runAction(RepeatForever::create(RotateBy::create(3, 360)));
sprite->runAction(RepeatForever::create(Sequence::createWithTwoActions(ScaleBy::create(2, 2), ScaleBy::create(2,0.5))));
parent2->addChild(sprite);
}
auto sprite2 = Sprite::create("Images/btn-about-normal-vertical.png");
sprite2->setRotation(-85);
sprite2->setPosition(Point(size.width/2,size.height * 2/3));
sprite2->setScale(2);
addChild(sprite2);
for(int index = 0; index < 500; ++index)
{
auto parent2 = Node::create();
parent->addChild(parent2);
parent2->setPosition(50,0);
parent2->runAction(RepeatForever::create((JumpBy::create(7, Point(0,0), 400, 1))));
Sprite* sprite = Sprite::create(images[index % images.size()].c_str());
sprite->setPosition(Point(0,0));
//sprite->runAction(RepeatForever::create(RotateBy::create(3, 360)));
sprite->runAction(RepeatForever::create(Sequence::createWithTwoActions(ScaleBy::create(2, 2), ScaleBy::create(2,0.5))));
parent2->addChild(sprite);
}
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(NewCullingTest::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(NewCullingTest::onTouchMoved, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}
bool NewCullingTest::onTouchBegan(Touch* touch, Event *event)
{
auto pos = touch->getLocation();
_lastPos = pos;
return true;
}
void NewCullingTest::onTouchMoved(Touch* touch, Event *event)
{
auto pos = touch->getLocation();
auto offset = pos - _lastPos;
auto layerPos = getPosition();
auto newPos = layerPos + offset;
setPosition(newPos);
_lastPos = pos;
}
NewCullingTest::~NewCullingTest()
@ -534,7 +527,7 @@ std::string NewCullingTest::title() const
std::string NewCullingTest::subtitle() const
{
return "Culling";
return "Drag the layer to test the result of culling";
}
VBOFullTest::VBOFullTest()

View File

@ -129,6 +129,9 @@ public:
protected:
NewCullingTest();
virtual ~NewCullingTest();
bool onTouchBegan(Touch* touch, Event *event);
void onTouchMoved(Touch* touch, Event *event);
Point _lastPos;
};
class VBOFullTest : public MultiSceneTest

View File

@ -1076,7 +1076,7 @@ void SchedulerIssue2268::onEnter()
void SchedulerIssue2268::update(float dt)
{
if ( testNode != NULL ) {
if ( testNode != nullptr ) {
// do something with testNode
// at some point we are done, pause the nodes actions and schedulers
@ -1085,13 +1085,13 @@ void SchedulerIssue2268::update(float dt)
// at some other point we are completely done with the node and want to clear it
testNode->unscheduleAllSelectors();
testNode->release();
testNode = NULL;
testNode = nullptr;
}
}
SchedulerIssue2268::~SchedulerIssue2268()
{
CC_SAFE_RELEASE(testNode);
}
std::string SchedulerIssue2268::title() const

View File

@ -1101,12 +1101,14 @@ void TMXIsoVertexZ::onEnter()
// TIP: 2d projection should be used
Director::getInstance()->setProjection(Director::Projection::_2D);
Director::getInstance()->setDepthTest(true);
}
void TMXIsoVertexZ::onExit()
{
// At exit use any other projection.
Director::getInstance()->setProjection(Director::Projection::DEFAULT);
Director::getInstance()->setDepthTest(false);
TileDemo::onExit();
}

@ -1 +1 @@
Subproject commit ae27f3bafbbdda9c32e5b89c79183183486e1299
Subproject commit f5768df8fdd5a5a0069b9634aede93ce13e0c9d6

View File

@ -45,8 +45,15 @@ def autotest(type):
while True:
data = soc.recv(1024)
print data
if data == 'TestEnd':
lastTestInfo = True
break
global lastTestInfo
if len(data) > len('\n') :
lastTestInfo = data
if not data: break
soc.send('director end\r\n')
print 'test end and close socket.'
soc.close()

View File

@ -0,0 +1,32 @@
import os
import json
import requests
import jenkinsapi
from jenkinsapi.jenkins import Jenkins
from jenkinsapi.constants import STATUS_SUCCESS
payload_str = os.environ['payload']
payload_str = payload_str.decode('utf-8','ignore')
#parse to json obj
payload = json.loads(payload_str)
#pr = payload['pull_request']
url = payload['html_url']
print "build pr:" + url
#get comments url
comments_url = payload['comments_url']
J = Jenkins(os.environ['JENKINS_URL'])
target_url = os.environ['BUILD_URL']
build_number = int(os.environ['BUILD_NUMBER'])
data = {}
access_token = os.environ['GITHUB_COMMENT_ACCESS_TOKEN']
Headers = {"Authorization":"token " + access_token}
result = J[os.environ['JOB_NAME']].get_build(build_number).get_status()
if(result == STATUS_SUCCESS):
data['body'] = "Emptytest run Success: " + target_url
else:
data['body'] = "Emptytest run Failure: " + target_url
requests.post(comments_url, data=json.dumps(data), headers=Headers)

View File

@ -0,0 +1,175 @@
#!/usr/bin/python
# create new project by cocos-console
# compile, deploy project and run
# perpose: for emptytest.
# now support: mac- mac/ios/android
# will add: window-android,linux-android
import os
import subprocess
import sys
import json
import time
import socket
payload = {}
#get payload from os env
if os.environ.has_key('payload'):
payload_str = os.environ['payload']
#parse to json obj
global payload
payload = json.loads(payload_str)
print 'payload:',payload
pr_num = 1
#get pull number
if payload.has_key('issue'):
issue = payload['issue']
if issue.has_key('number'):
pr_num = issue['number']
print 'pr_num:' + str(pr_num)
test_name = ['cpp_empty_test']
if os.environ.has_key('TESTS_NAME'):
temp_var = os.environ('TESTS_NAME')
test_name = temp_var.split(', ')
package_name = ['org.cocos2dx.hellocpp']
if os.environ.has_key('PACKAGE_NAME'):
temp_var = os.environ('PACKAGE_NAME')
package_name = temp_var.split(', ')
activity_name = ['org.cocos2dx.cpp.AppActivity']
if os.environ.has_key('ACTIVITY_NAME'):
temp_var = os.environ('ACTIVITY_NAME')
activity_name = temp_var.split(', ')
gIdx = 0
if os.environ.has_key('TEST_INDEX'):
gIdx = os.environ('TEST_INDEX')
arrDevices = []
def getDevices():
cmd = 'adb devices'
info_devices = os.popen(cmd).read()
arr_info = info_devices.split('\n')
del arr_info[0]
count = 0
for device in arr_info:
if len(device) > 0:
count += 1
print 'device ', count,device
deviceInfo = device.split(' ')
global arrDevices
obj = {}
obj['name'] = deviceInfo[0]
arrDevices.append(obj)
return count
def getADBDeviceIP(device_name):
output = os.popen("adb -s "+device_name+" shell netcfg")
configs = output.read().split('\r\n')
for l in configs:
items = l.split()
if len(items)>1 and items[1] == 'UP':
if items[2].find('127.0.0.1') < 0 and items[2].find('0.0.0.0') < 0:
return items[2]
return False
def mapIP():
for device in arrDevices:
ip_d = getADBDeviceIP(device['name'])
if ip_d:
ip_d = ip_d.replace('.30.', '.40.')
device['ip'] = ip_d
info_empty_test = {}
apk_name = 'apk/'+test_name[gIdx]+'/'+test_name[gIdx]+'_'+str(pr_num)+'.apk'
def install_apk():
print 'will install apk:', apk_name
if len(arrDevices) == 0:
print 'no android device.'
return False
info_of_install = []
for device in arrDevices:
name = device['name']
cmd = 'adb -s '+name+' install '+apk_name
print 'install on '+name
info_install = os.popen(cmd).read()
print 'infomation of install apk:', info_install
info_of_install.append(info_install.split('\r\n'))
info_empty_test['install'] = info_of_install
return True
def open_apk(type_of_apk):
print 'will open activity:'
for device in arrDevices:
cmd = 'adb -s '+device['name']+' shell am start -n '+package_name[gIdx]+'/'+activity_name[gIdx]
# print 'start activity:', cmd
info_start = os.popen(cmd).read()
info_start = info_start.split('\n')
# print 'info_start:', info_start
for info in info_start:
if info.find('Error:') > -1:
print 'infomation of open activity:',info
return info
print 'activity is opened.'
return True
PORT = 5678
def socket_status(device_name):
soc = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
try:
print 'will check status of app:', device_name
soc.connect((device_name['ip'], PORT))
cmd = 'resolution\r\n'
# print 'socket cmd :', cmd
soc.send(cmd)
while True:
data = soc.recv(1024)
if len(data):
print data
if data.find('size:') > -1:
print test_name[gIdx]+' is successful!'
return True
if not data:
print test_name[gIdx]+' is crashed!'
break
except Exception, e:
print test_name[gIdx]+' is crashed!'
return False
def uninstall_apk(idx):
# adb shell pm uninstall -n org.cocos2dx.hellolua
print 'will uninstall apk:', package_name[idx]
for device in arrDevices:
cmd = 'adb -s '+device['name']+' shell pm uninstall -n '+package_name[idx]
info_uninstall = os.popen(cmd).read()
print 'uninstall apk:', info_uninstall
return True
def main():
print 'in main:'
getDevices()
if len(arrDevices):
mapIP()
print 'arrDevices:',arrDevices
print 'empty test start:'
install_info = install_apk()
open_info = open_apk(test_name[gIdx])
info_empty_test['open_info'] = open_info
if open_info:
time.sleep(5)
socket_info = socket_status(arrDevices[0])
info_empty_test['socket_info'] = socket_info
if install_info:
time.sleep(5)
info_uninstall = uninstall_apk(gIdx)
print 'info_empty_test:', info_empty_test
print 'empty test end'
# -------------- main --------------
if __name__ == '__main__':
sys_ret = 0
try:
sys_ret = main()
except:
traceback.print_exc()
sys_ret = 1
finally:
sys.exit(sys_ret)

View File

@ -24,13 +24,13 @@ def main():
#get comment body
comment_body = comment['body']
print comment_body
pattern = re.compile("\[ci(\s+)rebuild\]", re.I)
result = pattern.search(comment_body)
#will check 'ci' comment
searchCI = re.search("\[ci.*\]", comment_body)
# will check console/console create
#will check console/console create
searchConsole = re.search('\[console.*\]', comment_body)
if result is None and searchConsole is None:
if searchCI is None and searchConsole is None:
print 'skip build for pull request #' + str(pr_num)
return(0)
@ -57,6 +57,10 @@ def main():
statuses_url = repository['statuses_url']
payload_forword['statuses_url'] = statuses_url
print 'statuses_url: ' + statuses_url
#get comments url
comments_url = repository['comments_url']
payload_forword['comments_url'] = comments_url
print 'comments_url: ' + comments_url
#get pr target branch
branch = repository['base']['ref']
@ -75,16 +79,23 @@ def main():
Headers = {"Authorization":"token " + access_token}
try:
requests.post(statuses_url, data=json.dumps(data), headers=Headers)
if searchCI:
ciOper = searchCI.group()
if('rebuild' in ciOper):
requests.post(statuses_url, data=json.dumps(data), headers=Headers)
except:
traceback.print_exc()
job_trigger_url = ''
if result:
job_trigger_url = os.environ['JOB_TRIGGER_URL']
if searchCI:
ciOper = searchCI.group()
if('rebuild' in ciOper):
job_trigger_url = os.environ['JOB_PULL_REQUEST_BUILD_TRIGGER_URL']
if('emptytest' in ciOper):
job_trigger_url = os.environ['JOB_EMPTYTEST_TRIGGER_URL']
if searchConsole:
consoleOper = searchConsole.group()
job_trigger_url = os.environ['JOB_CONSOLE_TEST_URL']
job_trigger_url = os.environ['JOB_CONSOLE_TEST_TRIGGER_URL']
payload_forword['console'] = consoleOper
print 'job_trigger_url is: ', job_trigger_url

View File

@ -141,8 +141,22 @@ def main():
node_name = os.environ['NODE_NAME']
if(branch == 'develop'):
if(node_name == 'android_mac') or (node_name == 'android_win7'):
#modify tests/cpp-empty-test/Classes/AppDelegate.cpp to support Console
modify_file = 'tests/cpp-empty-test/Classes/AppDelegate.cpp'
data = codecs.open(modify_file, encoding='UTF-8').read()
data = re.sub("director->setDisplayStats\(true\);", "director->setDisplayStats(true); director->getConsole()->listenOnTCP(5678);", data)
codecs.open(modify_file, 'wb', encoding='UTF-8').write(data)
print "Start build android..."
ret = os.system("python build/android-build.py -n -j10 all")
# create and save apk
if(ret == 0):
sample_dir = 'tests/cpp-empty-test/proj.android/'
os.system('android update project -p cocos/2d/platform/android/java/ -t android-13')
os.system('android update project -p ' + sample_dir + ' -t android-13')
os.system('ant debug -f ' + sample_dir + 'build.xml')
local_apk = sample_dir + 'bin/CppEmptyTest-debug.apk'
remote_apk = 'apks/cpp_empty_test/cpp_empty_test_' + str(pr_num) + '.apk'
os.system('tools/jenkins-scripts/upload_apk.sh ' + local_apk + ' ' + remote_apk)
elif(node_name == 'win32_win7'):
ret = subprocess.call('"%VS110COMNTOOLS%..\IDE\devenv.com" "build\cocos2d-win32.vc2012.sln" /Build "Debug|Win32"', shell=True)
elif(node_name == 'ios_mac'):

View File

@ -0,0 +1,9 @@
#!/bin/sh
localfile=$1
remotefile=$2
sftp $FTP_HOME << EOF
put $localfile $remotefile
bye
EOF
echo "upload finished"