示例#1
0
void Node::setOrderOfArrival(int orderOfArrival)
{
    CCASSERT(orderOfArrival >=0, "Invalid orderOfArrival");
    _orderOfArrival = orderOfArrival;
}
void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, const std::function<bool(EventListener*)>& onEvent)
{
    bool shouldStopPropagation = false;
    auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
    auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
    
    ssize_t i = 0;
    // priority < 0
    if (fixedPriorityListeners)
    {
        CCASSERT(listeners->getGt0Index() <= static_cast<ssize_t>(fixedPriorityListeners->size()), "Out of range exception!");
        
        if (!fixedPriorityListeners->empty())
        {
            for (; i < listeners->getGt0Index(); ++i)
            {
                auto l = fixedPriorityListeners->at(i);
                if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
                {
                    shouldStopPropagation = true;
                    break;
                }
            }
        }
    }
    
    if (sceneGraphPriorityListeners)
    {
        if (!shouldStopPropagation)
        {
            // priority == 0, scene graph priority
            for (auto& l : *sceneGraphPriorityListeners)
            {
                if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
                {
                    shouldStopPropagation = true;
                    break;
                }
            }
        }
    }
    
    if (fixedPriorityListeners)
    {
        if (!shouldStopPropagation)
        {
            // priority > 0
            ssize_t size = fixedPriorityListeners->size();
            for (; i < size; ++i)
            {
                auto l = fixedPriorityListeners->at(i);
                
                if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
                {
                    shouldStopPropagation = true;
                    break;
                }
            }
        }
    }
}
void EventDispatcher::dispatchTouchEvent(EventTouch* event)
{
    sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID);
    sortEventListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
    
    auto oneByOneListeners = getListeners(EventListenerTouchOneByOne::LISTENER_ID);
    auto allAtOnceListeners = getListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
    
    // If there aren't any touch listeners, return directly.
    if (nullptr == oneByOneListeners && nullptr == allAtOnceListeners)
        return;
    
    bool isNeedsMutableSet = (oneByOneListeners && allAtOnceListeners);
    
    const std::vector<Touch*>& originalTouches = event->getTouches();
    std::vector<Touch*> mutableTouches(originalTouches.size());
    std::copy(originalTouches.begin(), originalTouches.end(), mutableTouches.begin());

    //
    // process the target handlers 1st
    //
    if (oneByOneListeners)
    {
        auto mutableTouchesIter = mutableTouches.begin();
        auto touchesIter = originalTouches.begin();
        
        for (; touchesIter != originalTouches.end(); ++touchesIter)
        {
            bool isSwallowed = false;

            auto onTouchEvent = [&](EventListener* l) -> bool { // Return true to break
                EventListenerTouchOneByOne* listener = static_cast<EventListenerTouchOneByOne*>(l);
                
                // Skip if the listener was removed.
                if (!listener->_isRegistered)
                    return false;
             
                event->setCurrentTarget(listener->_node);
                
                bool isClaimed = false;
                std::vector<Touch*>::iterator removedIter;
                
                EventTouch::EventCode eventCode = event->getEventCode();
                
                if (eventCode == EventTouch::EventCode::BEGAN)
                {
                    if (listener->onTouchBegan)
                    {
                        isClaimed = listener->onTouchBegan(*touchesIter, event);
                        if (isClaimed && listener->_isRegistered)
                        {
                            listener->_claimedTouches.push_back(*touchesIter);
                        }
                    }
                }
                else if (listener->_claimedTouches.size() > 0
                         && ((removedIter = std::find(listener->_claimedTouches.begin(), listener->_claimedTouches.end(), *touchesIter)) != listener->_claimedTouches.end()))
                {
                    isClaimed = true;
                    
                    switch (eventCode)
                    {
                        case EventTouch::EventCode::MOVED:
                            if (listener->onTouchMoved)
                            {
                                listener->onTouchMoved(*touchesIter, event);
                            }
                            break;
                        case EventTouch::EventCode::ENDED:
                            if (listener->onTouchEnded)
                            {
                                listener->onTouchEnded(*touchesIter, event);
                            }
                            if (listener->_isRegistered)
                            {
                                listener->_claimedTouches.erase(removedIter);
                            }
                            break;
                        case EventTouch::EventCode::CANCELLED:
                            if (listener->onTouchCancelled)
                            {
                                listener->onTouchCancelled(*touchesIter, event);
                            }
                            if (listener->_isRegistered)
                            {
                                listener->_claimedTouches.erase(removedIter);
                            }
                            break;
                        default:
                            CCASSERT(false, "The eventcode is invalid.");
                            break;
                    }
                }
                
                // If the event was stopped, return directly.
                if (event->isStopped())
                {
                    updateListeners(event);
                    return true;
                }
                
                CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(),
                         "touchesIter ID should be equal to mutableTouchesIter's ID.");
                
                if (isClaimed && listener->_isRegistered && listener->_needSwallow)
                {
                    if (isNeedsMutableSet)
                    {
                        mutableTouchesIter = mutableTouches.erase(mutableTouchesIter);
                        isSwallowed = true;
                    }
                    return true;
                }
                
                return false;
            };
            
            //
            dispatchTouchEventToListeners(oneByOneListeners, onTouchEvent);
            if (event->isStopped())
            {
                return;
            }
            
            if (!isSwallowed)
                ++mutableTouchesIter;
        }
    }
    
    //
    // process standard handlers 2nd
    //
    if (allAtOnceListeners && mutableTouches.size() > 0)
    {
        
        auto onTouchesEvent = [&](EventListener* l) -> bool{
            EventListenerTouchAllAtOnce* listener = static_cast<EventListenerTouchAllAtOnce*>(l);
            // Skip if the listener was removed.
            if (!listener->_isRegistered)
                return false;
            
            event->setCurrentTarget(listener->_node);
            
            switch (event->getEventCode())
            {
                case EventTouch::EventCode::BEGAN:
                    if (listener->onTouchesBegan)
                    {
                        listener->onTouchesBegan(mutableTouches, event);
                    }
                    break;
                case EventTouch::EventCode::MOVED:
                    if (listener->onTouchesMoved)
                    {
                        listener->onTouchesMoved(mutableTouches, event);
                    }
                    break;
                case EventTouch::EventCode::ENDED:
                    if (listener->onTouchesEnded)
                    {
                        listener->onTouchesEnded(mutableTouches, event);
                    }
                    break;
                case EventTouch::EventCode::CANCELLED:
                    if (listener->onTouchesCancelled)
                    {
                        listener->onTouchesCancelled(mutableTouches, event);
                    }
                    break;
                default:
                    CCASSERT(false, "The eventcode is invalid.");
                    break;
            }
            
            // If the event was stopped, return directly.
            if (event->isStopped())
            {
                updateListeners(event);
                return true;
            }
            
            return false;
        };
        
        dispatchTouchEventToListeners(allAtOnceListeners, onTouchesEvent);
        if (event->isStopped())
        {
            return;
        }
    }
    
    updateListeners(event);
}
示例#4
0
bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat format, GLuint depthStencilFormat)
{
    CCASSERT(format != Texture2D::PixelFormat::A8, "only RGB and RGBA formats are valid for a render texture");

    bool ret = false;
    void *data = nullptr;
    do 
    {
        _fullRect = _rtTextureRect = Rect(0,0,w,h);
        //Size size = Director::getInstance()->getWinSizeInPixels();
        //_fullviewPort = Rect(0,0,size.width,size.height);
        w = (int)(w * CC_CONTENT_SCALE_FACTOR());
        h = (int)(h * CC_CONTENT_SCALE_FACTOR());
        _fullviewPort = Rect(0,0,w,h);
        
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);

        // textures must be power of two squared
        int powW = 0;
        int powH = 0;

        if (Configuration::getInstance()->supportsNPOT())
        {
            powW = w;
            powH = h;
        }
        else
        {
            powW = ccNextPOT(w);
            powH = ccNextPOT(h);
        }

        auto dataLen = powW * powH * 4;
        data = malloc(dataLen);
        CC_BREAK_IF(! data);

        memset(data, 0, dataLen);
        _pixelFormat = format;

        _texture = new (std::nothrow) Texture2D();
        if (_texture)
        {
            _texture->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
        }
        else
        {
            break;
        }
        GLint oldRBO;
        glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO);
        
        if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
        {
            _textureCopy = new (std::nothrow) Texture2D();
            if (_textureCopy)
            {
                _textureCopy->initWithData(data, dataLen, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
            }
            else
            {
                break;
            }
        }

        // generate FBO
        glGenFramebuffers(1, &_FBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _FBO);

        // associate texture with FBO
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);

        if (depthStencilFormat != 0)
        {
            //create and attach depth buffer
            glGenRenderbuffers(1, &_depthRenderBufffer);
            glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderBufffer);
            glRenderbufferStorage(GL_RENDERBUFFER, depthStencilFormat, (GLsizei)powW, (GLsizei)powH);
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBufffer);

            // if depth format is the one with stencil part, bind same render buffer as stencil attachment
            if (depthStencilFormat == GL_DEPTH24_STENCIL8)
            {
                glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderBufffer);
            }
        }

        // check if it worked (probably worth doing :) )
        CCASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");

        _texture->setAliasTexParameters();

        // retained
        setSprite(Sprite::createWithTexture(_texture));

        _texture->release();
        _sprite->setFlippedY(true);

        _sprite->setBlendFunc( BlendFunc::ALPHA_PREMULTIPLIED );

        glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
        
        // Disabled by default.
        _autoDraw = false;
        
        // add sprite for backward compatibility
        addChild(_sprite);
        
        ret = true;
    } while (0);
    
    CC_SAFE_FREE(data);
    
    return ret;
}
void EventDispatcher::updateListeners(Event* event)
{
    CCASSERT(_inDispatch > 0, "If program goes here, there should be event in dispatch.");

    if (_inDispatch > 1)
        return;

    auto onUpdateListeners = [this](const EventListener::ListenerID& listenerID)
    {
        auto listenersIter = _listenerMap.find(listenerID);
        if (listenersIter == _listenerMap.end())
            return;

        auto listeners = listenersIter->second;
        
        auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
        auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
        
        if (sceneGraphPriorityListeners)
        {
            for (auto iter = sceneGraphPriorityListeners->begin(); iter != sceneGraphPriorityListeners->end();)
            {
                auto l = *iter;
                if (!l->isRegistered())
                {
                    iter = sceneGraphPriorityListeners->erase(iter);
                    l->release();
                }
                else
                {
                    ++iter;
                }
            }
        }
        
        if (fixedPriorityListeners)
        {
            for (auto iter = fixedPriorityListeners->begin(); iter != fixedPriorityListeners->end();)
            {
                auto l = *iter;
                if (!l->isRegistered())
                {
                    iter = fixedPriorityListeners->erase(iter);
                    l->release();
                }
                else
                {
                    ++iter;
                }
            }
        }
        
        if (sceneGraphPriorityListeners && sceneGraphPriorityListeners->empty())
        {
            listeners->clearSceneGraphListeners();
        }

        if (fixedPriorityListeners && fixedPriorityListeners->empty())
        {
            listeners->clearFixedListeners();
        }
    };

    if (event->getType() == Event::Type::TOUCH)
    {
        onUpdateListeners(EventListenerTouchOneByOne::LISTENER_ID);
        onUpdateListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
    }
    else
    {
        onUpdateListeners(__getListenerID(event));
    }
    
    CCASSERT(_inDispatch == 1, "_inDispatch should be 1 here.");
    
    for (auto iter = _listenerMap.begin(); iter != _listenerMap.end();)
    {
        if (iter->second->empty())
        {
            _priorityDirtyFlagMap.erase(iter->first);
            delete iter->second;
            iter = _listenerMap.erase(iter);
        }
        else
        {
            ++iter;
        }
    }
    
    if (!_toAddedListeners.empty())
    {
        for (auto& listener : _toAddedListeners)
        {
            forceAddEventListener(listener);
        }
        _toAddedListeners.clear();
    }
}
void MotionStreak::setOpacity(GLubyte opacity)
{
    CCASSERT(false, "Set opacity no supported");
}
示例#7
0
void Ref::retain()
{
    CCASSERT(_referenceCount > 0, "reference count should be greater than 0");
    ++_referenceCount;
}
示例#8
0
文件: CCLabel.cpp 项目: adroitly/boom
void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{
    if (! _visible || _originalUTF8String.empty())
    {
        return;
    }
    if (_systemFontDirty)
    {
        updateFont();
    }
    if (_contentDirty)
    {
        updateContent();
    }

    uint32_t flags = processParentFlags(parentTransform, parentFlags);

    if (_shadowEnabled && _shadowBlurRadius <= 0 && (_shadowDirty || (flags & FLAGS_DIRTY_MASK)))
    {
        _position.x += _shadowOffset.width;
        _position.y += _shadowOffset.height;
        _transformDirty = _inverseDirty = true;

        _shadowTransform = transform(parentTransform);

        _position.x -= _shadowOffset.width;
        _position.y -= _shadowOffset.height;
        _transformDirty = _inverseDirty = true;

        _shadowDirty = false;
    }

    if (!isVisitableByVisitingCamera())
    {
        return;
    }

    // IMPORTANT:
    // To ease the migration to v3.0, we still support the Mat4 stack,
    // but it is deprecated and your code should not rely on it
    Director* director = Director::getInstance();
    CCASSERT(nullptr != director, "Director is null when seting matrix stack");
    
    director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
    director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
    

    if (_textSprite)
    {
        drawTextSprite(renderer, flags);
    }
    else
    {
        draw(renderer, _modelViewTransform, flags);
    }

    director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
    
    // FIX ME: Why need to set _orderOfArrival to 0??
    // Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
    // setOrderOfArrival(0);
}
示例#9
0
文件: CCLabel.cpp 项目: adroitly/boom
float Label::getLineHeight() const
{
    CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, "Not supported system font!");
    return _textSprite ? 0.0f : _commonLineHeight;
}
示例#10
0
// cocos2d-x doesn't support Samplers yet. But will be added soon
bool Material::parseSampler(GLProgramState* glProgramState, Properties* samplerProperties)
{
    CCASSERT(samplerProperties->getId(), "Sampler must have an id. The id is the uniform name");
    
    // required
    auto filename = samplerProperties->getString("path");

    auto texture = Director::getInstance()->getTextureCache()->addImage(filename);
    if (!texture) {
        CCLOG("Invalid filepath");
        return false;
    }

    // optionals

    {
        Texture2D::TexParams texParams;

        // mipmap
        bool usemipmap = false;
        const char* mipmap = getOptionalString(samplerProperties, "mipmap", "false");
        if (mipmap && strcasecmp(mipmap, "true")==0) {
            texture->generateMipmap();
            usemipmap = true;
        }

        // valid options: REPEAT, CLAMP
        const char* wrapS = getOptionalString(samplerProperties, "wrapS", "CLAMP_TO_EDGE");
        if (strcasecmp(wrapS, "REPEAT")==0)
            texParams.wrapS = GL_REPEAT;
        else if(strcasecmp(wrapS, "CLAMP_TO_EDGE")==0)
            texParams.wrapS = GL_CLAMP_TO_EDGE;
        else
            CCLOG("Invalid wrapS: %s", wrapS);


        // valid options: REPEAT, CLAMP
        const char* wrapT = getOptionalString(samplerProperties, "wrapT", "CLAMP_TO_EDGE");
        if (strcasecmp(wrapT, "REPEAT")==0)
            texParams.wrapT = GL_REPEAT;
        else if(strcasecmp(wrapT, "CLAMP_TO_EDGE")==0)
            texParams.wrapT = GL_CLAMP_TO_EDGE;
        else
            CCLOG("Invalid wrapT: %s", wrapT);


        // valid options: NEAREST, LINEAR, NEAREST_MIPMAP_NEAREST, LINEAR_MIPMAP_NEAREST, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_LINEAR
        const char* minFilter = getOptionalString(samplerProperties, "minFilter", usemipmap ? "LINEAR_MIPMAP_NEAREST" : "LINEAR");
        if (strcasecmp(minFilter, "NEAREST")==0)
            texParams.minFilter = GL_NEAREST;
        else if(strcasecmp(minFilter, "LINEAR")==0)
            texParams.minFilter = GL_LINEAR;
        else if(strcasecmp(minFilter, "NEAREST_MIPMAP_NEAREST")==0)
            texParams.minFilter = GL_NEAREST_MIPMAP_NEAREST;
        else if(strcasecmp(minFilter, "LINEAR_MIPMAP_NEAREST")==0)
            texParams.minFilter = GL_LINEAR_MIPMAP_NEAREST;
        else if(strcasecmp(minFilter, "NEAREST_MIPMAP_LINEAR")==0)
            texParams.minFilter = GL_NEAREST_MIPMAP_LINEAR;
        else if(strcasecmp(minFilter, "LINEAR_MIPMAP_LINEAR")==0)
            texParams.minFilter = GL_LINEAR_MIPMAP_LINEAR;
        else
            CCLOG("Invalid minFilter: %s", minFilter);

        // valid options: NEAREST, LINEAR
        const char* magFilter = getOptionalString(samplerProperties, "magFilter", "LINEAR");
        if (strcasecmp(magFilter, "NEAREST")==0)
            texParams.magFilter = GL_NEAREST;
        else if(strcasecmp(magFilter, "LINEAR")==0)
            texParams.magFilter = GL_LINEAR;
        else
            CCLOG("Invalid magFilter: %s", magFilter);

        texture->setTexParameters(texParams);
    }

    glProgramState->setUniformTexture(samplerProperties->getId(), texture);
    return true;
}
void CommandMoveLeft::update(float dt) {
	if (!_block)
		return;

	auto body1 = _block->getBody();
	if (!body1) {
		stopBlock();
		return;
	}
	auto body2 = _block->getAttachedBody();
	if (!body2) {
		stopBlock();
		return;
	}
	float32 offset = ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::MOVEOFFSET);
	float32 blockSizeInMeters = _blockSize.width / ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D);

	if (body1->GetFixtureList()->GetFilterData().categoryBits == Block::blockFlags::PASSIVE
		|| body2->GetFixtureList()->GetFilterData().categoryBits == Block::blockFlags::PASSIVE)
		stopBlock();
	
	if (body1->GetFixtureList()->GetFilterData().categoryBits == Block::blockFlags::NEED_TO_STOP
		|| body2->GetFixtureList()->GetFilterData().categoryBits == Block::blockFlags::NEED_TO_STOP) {
		Vec2 posOnField = _block->getPosOnField();
		Sprite *sprite1 = (Sprite*)body1->GetUserData();
		Sprite *sprite2 = (Sprite*)body2->GetUserData();
		Size size = sprite1->getContentSize();
		b2Filter filter;

		if (GameField::getBlock({ posOnField.x - 1, posOnField.y })){
			stopBlock();

			filter = body1->GetFixtureList()->GetFilterData();
			filter.categoryBits = Block::blockFlags::ACTIVE;
			body1->GetFixtureList()->SetFilterData(filter);

			filter = body2->GetFixtureList()->GetFilterData();
			filter.categoryBits = Block::blockFlags::ACTIVE;
			body2->GetFixtureList()->SetFilterData(filter);

			body1->SetTransform(_positionOldFirst, 0);
			body2->SetTransform(_positionOldSecond, 0);

			sprite1->setPosition({ (body1->GetPosition().x 
					* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.width / 2
				, (body1->GetPosition().y 
					* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.height / 2 });
			sprite2->setPosition({ (body2->GetPosition().x 
					* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.width / 2
				, (body2->GetPosition().y 
					* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.height / 2 });

			SimpleUI *simpleUI = MainGameScene::getUI();
			UserInput *input = (UserInput*)simpleUI->getChildrenByName(UserInput::name());
			input->dropInputEvents();

			return;
		}

		if (!_isUndo) {
			body1->SetTransform({ _positionOldFirst.x - blockSizeInMeters, body1->GetPosition().y }, 0);
			body2->SetTransform({ _positionOldSecond.x - blockSizeInMeters, body2->GetPosition().y }, 0);
		}
		else {
			body1->SetTransform({ _positionOldFirst.x + blockSizeInMeters, body1->GetPosition().y }, 0);
			body2->SetTransform({ _positionOldSecond.x + blockSizeInMeters, body2->GetPosition().y }, 0);
		}
		sprite1->setPosition({ (body1->GetPosition().x 
				* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.width / 2
			, (body1->GetPosition().y 
				* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.height / 2 });
		sprite2->setPosition({ (body2->GetPosition().x 
				* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.width / 2
			, (body2->GetPosition().y 
				* ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::SCALE_RATIO_BOX2D)) - size.height / 2 });

		stopBlock();

		filter = body1->GetFixtureList()->GetFilterData();
		filter.categoryBits ^= Block::blockFlags::NEED_TO_STOP;
		filter.categoryBits = Block::blockFlags::STOPPED;
		body1->GetFixtureList()->SetFilterData(filter);
		
		filter = body2->GetFixtureList()->GetFilterData();
		filter.categoryBits ^= Block::blockFlags::NEED_TO_STOP;
		filter.categoryBits = Block::blockFlags::STOPPED;
		body2->GetFixtureList()->SetFilterData(filter);

		body1->SetActive(false);
		body1->SetActive(true);
		body2->SetActive(false);
		body2->SetActive(true);
	}

	if ((_positionOldFirst.x - body1->GetPosition().x) < blockSizeInMeters
			&& !_isUndo
			&& _isExecute) {
		if ((_positionOldFirst.x - (body1->GetPosition().x - offset)) >= blockSizeInMeters) {
			while (offset > 0) {
				offset -= ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::MOVEOFFSET) / 100;
				if ((_positionOldFirst.x - (body1->GetPosition().x - offset)) < blockSizeInMeters) {
					stopBlock();
					body1->SetTransform({ body1->GetPosition().x - offset, body1->GetPosition().y }, 0);
					body2->SetTransform({ body2->GetPosition().x - offset, body2->GetPosition().y }, 0);
					return;
				}
			}
		}
		CCASSERT(offset, "offset can't be 0");
		if (body1->GetLinearVelocity().x > 0
			&& (_positionOldFirst.x - body1->GetPosition().x) < (blockSizeInMeters / 7)) {  
			stopBlock();
			body1->SetTransform(_positionOldFirst, 0);
			body2->SetTransform(_positionOldSecond, 0);
			return;
		}
		body1->SetLinearVelocity({ (float32)(body1->GetLinearVelocity().x - offset), body1->GetLinearVelocity().y });
		body2->SetLinearVelocity({ (float32)(body2->GetLinearVelocity().x - offset), body2->GetLinearVelocity().y });
		_positionOldFirst.y = body1->GetPosition().y;
		_positionOldSecond.y = body2->GetPosition().y;
	}
	else if ((body1->GetPosition().x - _positionOldFirst.x) < blockSizeInMeters
				&& _isUndo
				&& _isExecute) {
		if (((body1->GetPosition().x + offset) - _positionOldFirst.x) >= blockSizeInMeters) {
			while (offset > 0) {
				offset -= (ConstantsRegistry::getValueForKey(ConstantsRegistry::constants::MOVEOFFSET) / 100) * 10;
				if (((body1->GetPosition().x + offset) - _positionOldFirst.x) < blockSizeInMeters) {
					stopBlock();
					body1->SetTransform({ body1->GetPosition().x + offset, body1->GetPosition().y }, 0);
					body2->SetTransform({ body2->GetPosition().x + offset, body2->GetPosition().y }, 0);
					return;
				}
			}
		}
		CCASSERT(offset, "offset can't be 0");
		if (body1->GetLinearVelocity().x < 0
			&& (_positionOldFirst.x - body1->GetPosition().x) < (blockSizeInMeters / 7)) {
			stopBlock();
			body1->SetTransform(_positionOldFirst, 0);
			body2->SetTransform(_positionOldSecond, 0);
			return;
		}
		body1->SetLinearVelocity({ (float32)(body1->GetLinearVelocity().x + offset), body1->GetLinearVelocity().y });
		body2->SetLinearVelocity({ (float32)(body2->GetLinearVelocity().x + offset), body2->GetLinearVelocity().y });
		_positionOldFirst.y = body1->GetPosition().y;
		_positionOldSecond.y = body2->GetPosition().y;
	}
	else
		stopBlock();
}
// Process Response
static void processResponse(HttpResponse* response, char* errorBuffer)
{
    auto request = response->getHttpRequest();
    long responseCode = -1;
    int retValue = 0;

    // Process the request -> get response packet
    switch (request->getRequestType())
    {
    case HttpRequest::Type::GET: // HTTP GET
        retValue = processGetTask(request,
            writeData, 
            response->getResponseData(), 
            &responseCode,
            writeHeaderData,
            response->getResponseHeader(),
            errorBuffer);
        break;

    case HttpRequest::Type::POST: // HTTP POST
        retValue = processPostTask(request,
            writeData, 
            response->getResponseData(), 
            &responseCode,
            writeHeaderData,
            response->getResponseHeader(),
            errorBuffer);
        break;

    case HttpRequest::Type::PUT:
        retValue = processPutTask(request,
            writeData,
            response->getResponseData(),
            &responseCode,
            writeHeaderData,
            response->getResponseHeader(),
            errorBuffer);
        break;

    case HttpRequest::Type::DELETE:
        retValue = processDeleteTask(request,
            writeData,
            response->getResponseData(),
            &responseCode,
            writeHeaderData,
            response->getResponseHeader(),
            errorBuffer);
        break;

    default:
        CCASSERT(true, "CCHttpClient: unknown request type, only GET and POSt are supported");
        break;
    }

    // write data to HttpResponse
    response->setResponseCode(responseCode);

    if (retValue != 0) 
    {
        response->setSucceed(false);
        response->setErrorBuffer(errorBuffer);
    }
    else
    {
        response->setSucceed(true);
    }
}
示例#13
0
void TriggerObj::serialize(const rapidjson::Value &val)
{
    _id = (unsigned int)(DICTOOL->getIntValue_json(val, "id"));
    int count = DICTOOL->getArrayCount_json(val, "conditions");
    for (int i = 0; i < count; ++i)
    {
        const rapidjson::Value &subDict = DICTOOL->getSubDictionary_json(val, "conditions", i);
        const char *classname = DICTOOL->getStringValue_json(subDict, "classname");
        if (classname == nullptr)
        {
            continue;
        }
        BaseTriggerCondition *con = dynamic_cast<BaseTriggerCondition*>(ObjectFactory::getInstance()->createObject(classname));
        if(con == nullptr)
        {
            CCLOG("class %s can not be implemented!", classname);
            CCASSERT(con != nullptr, "");
        }
        
        CCASSERT(con != nullptr, "");
        con->serialize(subDict);
        con->init();
        _cons.pushBack(con);
    }
    
    count = DICTOOL->getArrayCount_json(val, "actions");
    for (int i = 0; i < count; ++i)
    {
        const rapidjson::Value &subDict = DICTOOL->getSubDictionary_json(val, "actions", i);
        const char *classname = DICTOOL->getStringValue_json(subDict, "classname");
        if (classname == nullptr)
        {
            continue;
        }
        BaseTriggerAction *act = dynamic_cast<BaseTriggerAction*>(ObjectFactory::getInstance()->createObject(classname));
        if(act == nullptr)
        {
            CCLOG("class %s can not be implemented!", classname);
            CCASSERT(act != nullptr, "");
        }
        act->serialize(subDict);
        act->init();
        _acts.pushBack(act);
    }

    int length = DICTOOL->getArrayCount_json(val, "events");
    for (int i = 0; i < length; ++i)
    {
        const rapidjson::Value &sub = DICTOOL->getSubDictionary_json(val, "events", i);
        int event = DICTOOL->getIntValue_json(sub, "id");
        if (event < 0)
        {
            continue;
        }

        char* buf = new char[10];
        sprintf(buf, "%d", event);
        std::string custom_event_name(buf);
        CC_SAFE_DELETE_ARRAY(buf);

        EventListenerCustom* listener = EventListenerCustom::create(custom_event_name, [=](EventCustom* evt){
            if (detect())
            {
                done();
            }
        });
        _listeners.pushBack(listener);
        TriggerMng::getInstance()->addEventListenerWithFixedPriority(listener, 1);
    }  
}
示例#14
0
void Node::addChild(Node *child)
{
    CCASSERT( child != nullptr, "Argument must be non-nil");
    this->addChild(child, child->_localZOrder, child->_name);
}
示例#15
0
void Physics3DRigidBody::removeConstraint( unsigned int idx )
{
    CCASSERT(idx < _constraintList.size(), "idx < _constraintList.size()");
    removeConstraint(_constraintList[idx]);
}
示例#16
0
文件: CCLabel.cpp 项目: adroitly/boom
float Label::getAdditionalKerning() const
{
    CCASSERT(_currentLabelType != LabelType::STRING_TEXTURE, "Not supported system font!");

    return _additionalKerning;
}
示例#17
0
Physics3DConstraint* Physics3DRigidBody::getConstraint( unsigned int idx ) const
{
    CCASSERT(idx < _constraintList.size(), "idx < _constraintList.size()");
    return _constraintList[idx];
}
示例#18
0
文件: CCLabel.cpp 项目: adroitly/boom
void Label::addChild(Node * child, int zOrder/* =0 */, int tag/* =0 */)
{
    CCASSERT(0, "addChild: is not supported on Label.");
}
GLubyte MotionStreak::getOpacity(void) const
{
    CCASSERT(false, "Opacity no supported");
    return 0;
}
void ActionTween::startWithTarget(Node *target)
{
    CCASSERT(dynamic_cast<ActionTweenDelegate*>(target), "target must implement ActionTweenDelegate");
    ActionInterval::startWithTarget(target);
    m_fDelta = m_fTo - m_fFrom;
}
void SpriteBatchNode::removeChildAtIndex(ssize_t index, bool doCleanup)
{
    CCASSERT(index>=0 && index < _children.size(), "Invalid index");
    removeChild(_children.at(index), doCleanup);
}
示例#22
0
void ProtectedNode::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{
    // quick return if not visible. children won't be drawn.
    if (!_visible || !isVisitableByVisitingCamera())
    {
        return;
    }
    
    uint32_t flags = processParentFlags(parentTransform, parentFlags);
    
    // IMPORTANT:
    // To ease the migration to v3.0, we still support the Mat4 stack,
    // but it is deprecated and your code should not rely on it
    Director* director = Director::getInstance();
    CCASSERT(nullptr != director, "Director is null when seting matrix stack");
    director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
    director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
    
    int i = 0;      // used by _children
    int j = 0;      // used by _protectedChildren
    
    sortAllChildren();
    sortAllProtectedChildren();
    
    //
    // draw children and protectedChildren zOrder < 0
    //
    for( ; i < _children.size(); i++ )
    {
        auto node = _children.at(i);
        
        if ( node && node->getLocalZOrder() < 0 )
            node->visit(renderer, _modelViewTransform, flags);
        else
            break;
    }
    
    for( ; j < _protectedChildren.size(); j++ )
    {
        auto node = _protectedChildren.at(j);
        
        if ( node && node->getLocalZOrder() < 0 )
            node->visit(renderer, _modelViewTransform, flags);
        else
            break;
    }
    
    //
    // draw self
    //
    if (isVisitableByVisitingCamera())
        this->draw(renderer, _modelViewTransform, flags);
    
    //
    // draw children and protectedChildren zOrder >= 0
    //
    for(auto it=_protectedChildren.cbegin()+j; it != _protectedChildren.cend(); ++it)
        (*it)->visit(renderer, _modelViewTransform, flags);
    
    for(auto it=_children.cbegin()+i; it != _children.cend(); ++it)
        (*it)->visit(renderer, _modelViewTransform, flags);
    
    // FIX ME: Why need to set _orderOfArrival to 0??
    // Please refer to https://github.com/cocos2d/cocos2d-x/pull/6920
    // setOrderOfArrival(0);
    
    director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
示例#23
0
/* get buffer as Image */
Image* RenderTexture::newImage(bool fliimage)
{
    CCASSERT(_pixelFormat == Texture2D::PixelFormat::RGBA8888, "only RGBA8888 can be saved as image");

    if (nullptr == _texture)
    {
        return nullptr;
    }

    const Size& s = _texture->getContentSizeInPixels();

    // to get the image size to save
    //        if the saving image domain exceeds the buffer texture domain,
    //        it should be cut
    int savedBufferWidth = (int)s.width;
    int savedBufferHeight = (int)s.height;

    GLubyte *buffer = nullptr;
    GLubyte *tempData = nullptr;
    Image *image = new (std::nothrow) Image();

    do
    {
        CC_BREAK_IF(! (buffer = new (std::nothrow) GLubyte[savedBufferWidth * savedBufferHeight * 4]));

        if(! (tempData = new (std::nothrow) GLubyte[savedBufferWidth * savedBufferHeight * 4]))
        {
            delete[] buffer;
            buffer = nullptr;
            break;
        }

        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
        glBindFramebuffer(GL_FRAMEBUFFER, _FBO);

        // TODO: move this to configration, so we don't check it every time
        /*  Certain Qualcomm Andreno gpu's will retain data in memory after a frame buffer switch which corrupts the render to the texture. The solution is to clear the frame buffer before rendering to the texture. However, calling glClear has the unintended result of clearing the current texture. Create a temporary texture to overcome this. At the end of RenderTexture::begin(), switch the attached texture to the second one, call glClear, and then switch back to the original texture. This solution is unnecessary for other devices as they don't have the same issue with switching frame buffers.
         */
        if (Configuration::getInstance()->checkForGLExtension("GL_QCOM"))
        {
            // -- bind a temporary texture so we can clear the render buffer without losing our texture
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _textureCopy->getName(), 0);
            CHECK_GL_ERROR_DEBUG();
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getName(), 0);
        }
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glReadPixels(0,0,savedBufferWidth, savedBufferHeight,GL_RGBA,GL_UNSIGNED_BYTE, tempData);
        glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);

        if ( fliimage ) // -- flip is only required when saving image to file
        {
            // to get the actual texture data
            // #640 the image read from rendertexture is dirty
            for (int i = 0; i < savedBufferHeight; ++i)
            {
                memcpy(&buffer[i * savedBufferWidth * 4],
                       &tempData[(savedBufferHeight - i - 1) * savedBufferWidth * 4],
                       savedBufferWidth * 4);
            }

            image->initWithRawData(buffer, savedBufferWidth * savedBufferHeight * 4, savedBufferWidth, savedBufferHeight, 8);
        }
        else
        {
            image->initWithRawData(tempData, savedBufferWidth * savedBufferHeight * 4, savedBufferWidth, savedBufferHeight, 8);
        }
        
    } while (0);

    CC_SAFE_DELETE_ARRAY(buffer);
    CC_SAFE_DELETE_ARRAY(tempData);

    return image;
}
示例#24
0
void TMXFileParser::startElement(void* ctx, const char* name, const char** atts)
{
    class AttributeIterator :
        public Noncopyable
    {
    private:
        const char** m_pAttrStrings;
    public:
        bool operator()(const char*& pKey, const char*& pValue)
        {
            if (m_pAttrStrings && *m_pAttrStrings)
                pKey = *m_pAttrStrings;
            else
                return false;
            ++m_pAttrStrings;
            if (*m_pAttrStrings)
                pValue = *m_pAttrStrings;
            else
                return false;
            ++m_pAttrStrings;
            return true;
        }
    public:
        AttributeIterator(const char** atts)
        : m_pAttrStrings(atts) {}
    };
    
    if (m_bFailed || m_stState.empty())
    {
        m_bFailed = true;
        return;
    }
    
    ParserState s = m_stState.top().first;
    StatePointer p = m_stState.top().second;
    AttributeIterator attrs(atts);
    
    switch (s)
    {
        case ParserState::ParseStart:
            if (::strcmp(name, "map") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "version") == 0)
                    {
                        if (::strcmp(pValue, "1.0") != 0)
                        {
                            PARSEFAILED("unsupported version '%s'.", pValue);
                            break;
                        }
                    }
                    else if (::strcmp(pKey, "orientation") == 0)
                    {
                        if (::strcmp(pValue, "orthogonal") != 0)
                        {
                            PARSEFAILED("unsupported orientation type '%s'.", pValue);
                            break;
                        }
                    }
                    else if (::strcmp(pKey, "renderorder") == 0)
                    {
                        if (::strcmp(pValue, "right-up") != 0)
                        {
                            PARSEFAILED("unsupported render order '%s'.", pValue);
                            break;
                        }
                    }
                    else if (::strcmp(pKey, "width") == 0)
                        p.pFile->m_iWidth = ::atoi(pValue);
                    else if (::strcmp(pKey, "height") == 0)
                        p.pFile->m_iHeight = ::atoi(pValue);
                    else if (::strcmp(pKey, "tilewidth") == 0)
                        p.pFile->m_iTileWidth = ::atoi(pValue);
                    else if (::strcmp(pKey, "tileheight") == 0)
                        p.pFile->m_iTileHeight = ::atoi(pValue);
                    else if (::strcmp(pKey, "nextobjectid") == 0)
                        p.pFile->m_iNextObjectId = ::atoi(pValue);
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                {
                    if (p.pFile->m_iWidth == 0 || p.pFile->m_iHeight == 0 || p.pFile->m_iTileWidth == 0 || p.pFile->m_iTileHeight == 0)
                        PARSEFAILED("invalid map arguments.");
                    else
                        m_stState.push(make_pair(ParserState::ParseMapNode, std::move(p)));
                }
            }
            else
                PARSEFAILED("node 'map' required, but found '%s'.", name);
            break;
        case ParserState::ParseMapNode:
            if (::strcmp(name, "tileset") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                uint32_t iFirstGid = 0;
                string strName;
                uint32_t iTileWidth = 0;
                uint32_t iTileHeight = 0;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "firstgid") == 0)
                        iFirstGid = ::atoi(pValue);
                    else if (::strcmp(pKey, "name") == 0)
                        strName = pValue;
                    else if (::strcmp(pKey, "tilewidth") == 0)
                        iTileWidth = ::atoi(pValue);
                    else if (::strcmp(pKey, "tileheight") == 0)
                        iTileHeight = ::atoi(pValue);
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                {
                    if (iTileWidth != p.pFile->GetTileWidth() || iTileHeight != p.pFile->GetTileHeight())
                        PARSEFAILED("invalid tileset size, w=%d h=%d.", iTileWidth, iTileHeight);
                    else if (p.pFile->GetTileSet(strName.c_str() != nullptr))
                        PARSEFAILED("duplicated tileset name '%s'.", strName.c_str());
                    else
                    {
                        TMXTileSet* pSet = make_ref_temp<TMXTileSet>(iFirstGid, iTileWidth, iTileHeight, strName);
                        p.pFile->m_vecTileSet.push_back(pSet);
                        m_stState.push(make_pair(ParserState::ParseTileSetNode, pSet));
                    }
                }
            }
            else if (::strcmp(name, "layer") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                string strName;
                uint32_t iWidth = 0;
                uint32_t iHeight = 0;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "name") == 0)
                        strName = pValue;
                    else if (::strcmp(pKey, "width") == 0)
                        iWidth = ::atoi(pValue);
                    else if (::strcmp(pKey, "height") == 0)
                        iHeight = ::atoi(pValue);
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                {
                    if (iWidth != p.pFile->GetWidth() || iHeight != p.pFile->GetHeight())
                        PARSEFAILED("invalid layer size, w=%d h=%d.", iWidth, iHeight);
                    else if (p.pFile->GetLayer(strName.c_str()))
                        PARSEFAILED("duplicated layer name '%s'.", strName.c_str());
                    else
                    {
                        TMXMapTiledLayer* pLayer = make_ref_temp<TMXMapTiledLayer>(iWidth, iHeight, strName);
                        p.pFile->m_vecMapLayer.push_back(pLayer);
                        m_stState.push(make_pair(ParserState::ParseLayerNode, pLayer));
                    }
                }
            }
            else if (::strcmp(name, "objectgroup") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                string strName;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "name") == 0)
                        strName = pValue;
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                {
                    if (p.pFile->GetLayer(strName.c_str()))
                        PARSEFAILED("duplicated layer name '%s'.", strName.c_str());
                    else
                    {
                        TMXMapObjectLayer* pLayer = make_ref_temp<TMXMapObjectLayer>(strName);
                        p.pFile->m_vecMapLayer.push_back(pLayer);
                        m_stState.push(make_pair(ParserState::ParseObjectLayerNode, pLayer));
                    }
                }
            }
            else
                PARSEFAILED("unsupported node '%s'.", name);
            break;
        case ParserState::ParseTileSetNode:
            if (::strcmp(name, "image") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "source") == 0)
                    {
                        string tFullPath = FileUtils::getInstance()->fullPathFromRelativeFile(pValue, m_strPath);
                        p.pTileSet->SetTexturePath(tFullPath);
                    }
                    else if (::strcmp(pKey, "width") == 0)
                    {
                        uint32_t iImageWidth = ::atoi(pValue);
                        p.pTileSet->SetWidthCount(iImageWidth / p.pTileSet->GetTileWidth());
                    }
                    else if (::strcmp(pKey, "height") == 0)
                    {
                        uint32_t iImageHeight = ::atoi(pValue);
                        p.pTileSet->SetHeightCount(iImageHeight / p.pTileSet->GetTileHeight());
                    }
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                    m_stState.push(make_pair(ParserState::ParseTileSetImageNode, p.pTileSet));
            }
            else if (::strcmp(name, "tile") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                uint32_t iIndex = 0;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "id") == 0)
                        iIndex = ::atoi(pValue);
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                {
                    TMXCustomPropertyList* pPropList = p.pTileSet->GetTileCustomPropertyList(iIndex);
                    m_stState.push(make_pair(ParserState::ParseTileSetTileNode, pPropList));
                }
            }
            else
                PARSEFAILED("unsupported node '%s'.", name);
            break;
        case ParserState::ParseTileSetImageNode:
            PARSEFAILED("unexpected node '%s'.", name);
            break;
        case ParserState::ParseTileSetTileNode:
            if (::strcmp(name, "properties") == 0)
                m_stState.push(make_pair(ParserState::ParsePropertyListNode, p.pPropertyList));
            else
                PARSEFAILED("unexpected node '%s'.", name);
            break;
        case ParserState::ParseLayerNode:
            if (::strcmp(name, "properties") == 0)
                m_stState.push(make_pair(ParserState::ParsePropertyListNode, p.pTiledLayer->GetCustomPropertyList()));
            else if (::strcmp(name, "data") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "encoding") == 0)
                    {
                        if (::strcmp(pValue, "base64") != 0)
                        {
                            PARSEFAILED("unknown encoding '%s'.", pValue);
                            break;
                        }
                    }
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                    m_stState.push(make_pair(ParserState::ParseLayerDataNode, std::move(p)));
            }
            else
                PARSEFAILED("unexpected node '%s'.", name);
            break;
        case ParserState::ParseLayerDataNode:
            PARSEFAILED("unexpected node '%s'.", name);
            break;
        case ParserState::ParseObjectLayerNode:
            if (::strcmp(name, "properties") == 0)
                m_stState.push(make_pair(ParserState::ParsePropertyListNode, p.pObjectLayer->GetCustomPropertyList()));
            else if (::strcmp(name, "object") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                uint32_t iID = 0;
                int iX = 0;
                int iY = 0;
                uint32_t iWidth = 0;
                uint32_t iHeight = 0;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "id") == 0)
                        iID = ::atoi(pValue);
                    else if (::strcmp(pKey, "x") == 0)
                        iX = ::atoi(pValue);
                    else if (::strcmp(pKey, "y") == 0)
                        iY = ::atoi(pValue);
                    else if (::strcmp(pKey, "width") == 0)
                        iWidth = ::atoi(pValue);
                    else if (::strcmp(pKey, "height") == 0)
                        iHeight = ::atoi(pValue);
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                {
                    TMXMapObject* pObj = make_ref_temp<TMXMapObject>(iID, iX, iY, iWidth, iHeight);
                    p.pObjectLayer->AddObject(pObj);
                    m_stState.push(make_pair(ParserState::ParseObjectLayerObjectNode, pObj));
                }
            }
            else
                PARSEFAILED("unexpected node '%s'.", name);
            break;
        case ParserState::ParseObjectLayerObjectNode:
            if (::strcmp(name, "properties") == 0)
                m_stState.push(make_pair(ParserState::ParsePropertyListNode, p.pObject->GetCustomPropertyList()));
            else
                PARSEFAILED("unexpected node '%s'.", name);
            break;
        case ParserState::ParsePropertyListNode:
            if (::strcmp(name, "property") == 0)
            {
                const char* pKey;
                const char* pValue;
                
                string strPropName;
                string strPropValue;
                
                while (attrs(pKey, pValue))
                {
                    if (::strcmp(pKey, "name") == 0)
                        strPropName = pValue;
                    else if (::strcmp(pKey, "value") == 0)
                        strPropValue = pValue;
                    else
                    {
                        PARSEFAILED("unknown attribute '%s'.", pKey);
                        break;
                    }
                }
                
                if (!m_bFailed)
                {
                    p.pPropertyList->SetProperty(strPropName.c_str(), strPropValue.c_str());
                    m_stState.push(make_pair(ParserState::ParsePropertyListPropertyNode, std::move(p)));
                }
            }
            else
                PARSEFAILED("unexpected node '%s'.", name);
            break;
        case ParserState::ParsePropertyListPropertyNode:
            PARSEFAILED("unexpected node '%s'.", name);
            break;
        default:
            m_bFailed = true;
            CCASSERT(0, "TMXFileParser: unexpected code routine.");
            break;
    }
}
void EventDispatcher::removeEventListener(EventListener* listener)
{
    if (listener == nullptr)
        return;

    bool isFound = false;
    
    auto removeListenerInVector = [&](std::vector<EventListener*>* listeners){
        if (listeners == nullptr)
            return;
        
        for (auto iter = listeners->begin(); iter != listeners->end(); ++iter)
        {
            auto l = *iter;
            if (l == listener)
            {
                CC_SAFE_RETAIN(l);
                l->setRegistered(false);
                if (l->getAssociatedNode() != nullptr)
                {
                    dissociateNodeAndEventListener(l->getAssociatedNode(), l);
                    l->setAssociatedNode(nullptr);  // nullptr out the node pointer so we don't have any dangling pointers to destroyed nodes.
                }
                
                if (_inDispatch == 0)
                {
                    listeners->erase(iter);
                    CC_SAFE_RELEASE(l);
                }
                
                isFound = true;
                break;
            }
        }
    };
    
    for (auto iter = _listenerMap.begin(); iter != _listenerMap.end();)
    {
        auto listeners = iter->second;
        auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
        auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();

        removeListenerInVector(sceneGraphPriorityListeners);
        if (isFound)
        {
            // fixed #4160: Dirty flag need to be updated after listeners were removed.
            setDirty(listener->getListenerID(), DirtyFlag::SCENE_GRAPH_PRIORITY);
        }
        else
        {
            removeListenerInVector(fixedPriorityListeners);
            if (isFound)
            {
                setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRIORITY);
            }
        }
        
#if CC_NODE_DEBUG_VERIFY_EVENT_LISTENERS
        CCASSERT(_inDispatch != 0 ||
                 !sceneGraphPriorityListeners ||
                 std::count(sceneGraphPriorityListeners->begin(), sceneGraphPriorityListeners->end(), listener) == 0,
                 "Listener should be in no lists after this is done if we're not currently in dispatch mode.");
            
        CCASSERT(_inDispatch != 0 ||
                 !fixedPriorityListeners ||
                 std::count(fixedPriorityListeners->begin(), fixedPriorityListeners->end(), listener) == 0,
                 "Listener should be in no lists after this is done if we're not currently in dispatch mode.");
#endif

        if (iter->second->empty())
        {
            _priorityDirtyFlagMap.erase(listener->getListenerID());
            auto list = iter->second;
            iter = _listenerMap.erase(iter);
            CC_SAFE_DELETE(list);
        }
        else
        {
            ++iter;
        }
        
        if (isFound)
            break;
    }

    if (isFound)
    {
        CC_SAFE_RELEASE(listener);
    }
    else
    {
        for(auto iter = _toAddedListeners.begin(); iter != _toAddedListeners.end(); ++iter)
        {
            if (*iter == listener)
            {
                listener->setRegistered(false);
                listener->release();
                _toAddedListeners.erase(iter);
                break;
            }
        }
    }
}
示例#26
0
void TMXFileParser::textHandler(void* ctx, const char* text, int len)
{
    if (m_bFailed || m_stState.empty())
    {
        m_bFailed = true;
        return;
    }
    
    ParserState s = m_stState.top().first;
    StatePointer p = m_stState.top().second;
    
    switch (s)
    {
        case ParserState::ParseStart:
        case ParserState::ParseMapNode:
        case ParserState::ParseTileSetNode:
        case ParserState::ParseTileSetImageNode:
        case ParserState::ParseTileSetTileNode:
        case ParserState::ParseLayerNode:
        case ParserState::ParseObjectLayerNode:
        case ParserState::ParseObjectLayerObjectNode:
        case ParserState::ParsePropertyListNode:
        case ParserState::ParsePropertyListPropertyNode:
            PARSEFAILED("unexpected data.");
            break;
        case ParserState::ParseLayerDataNode:
            // 手动trim
            while (len > 0 && text[len - 1] > 0 && ::isspace(text[len - 1]))
                --len;
            while (len > 0 && text[0] > 0 && ::isspace(text[0]))
            {
                --len;
                ++text;
            }
            
            // 解码base64串
            if (len > 0)
            {
                unsigned char* pOut = nullptr;
                int decodeLen = base64Decode((const unsigned char*)text, len, &pOut);
                if (decodeLen == p.pTiledLayer->GetWidth() * p.pTiledLayer->GetHeight() * sizeof(uint32_t))
                {
                    // 解析图块数据
                    const uint32_t* pGid = reinterpret_cast<uint32_t*>(pOut);
                    for (uint32_t iY = 0; iY < p.pTiledLayer->GetHeight(); ++iY)
                    {
                        for (uint32_t iX = 0; iX < p.pTiledLayer->GetWidth(); ++iX)
                            p.pTiledLayer->SetGidOfXY(iX, p.pTiledLayer->GetHeight() - iY - 1, *(pGid++));
                    }
                    free(pOut);
                }
                else
                {
                    if (pOut)
                        free(pOut);
                    PARSEFAILED("failed to decode map data, size %d mistached.", decodeLen);
                }
            }
            else
            {
                CCLOGWARN("TMXFileParser: empty layer data.");
            }
            break;
        default:
            m_bFailed = true;
            CCASSERT(0, "TMXFileParser: unexpected code routine.");
            break;
    }
}
void EventDispatcher::dispatchTouchEventToListeners(EventListenerVector* listeners, const std::function<bool(EventListener*)>& onEvent)
{
    bool shouldStopPropagation = false;
    auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
    auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
    
    ssize_t i = 0;
    // priority < 0
    if (fixedPriorityListeners)
    {
        CCASSERT(listeners->getGt0Index() <= static_cast<ssize_t>(fixedPriorityListeners->size()), "Out of range exception!");
        
        if (!fixedPriorityListeners->empty())
        {
            for (; i < listeners->getGt0Index(); ++i)
            {
                auto l = fixedPriorityListeners->at(i);
                if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
                {
                    shouldStopPropagation = true;
                    break;
                }
            }
        }
    }
    
    if (sceneGraphPriorityListeners)
    {
        if (!shouldStopPropagation)
        {
            // priority == 0, scene graph priority
            
            // first, get all enabled, unPaused and registered listeners
            std::vector<EventListener*> sceneListeners;
            for (auto& l : *sceneGraphPriorityListeners)
            {
                if (l->isEnabled() && !l->isPaused() && l->isRegistered())
                {
                    sceneListeners.push_back(l);
                }
            }
            // second, for all camera call all listeners
            // get a copy of cameras, prevent it's been modified in linstener callback
            // if camera's depth is greater, process it earler
            auto cameras = Director::getInstance()->getRunningScene()->getCameras();
            Camera* camera;
            for (int j = int(cameras.size()) - 1; j >= 0; --j)
            {
                camera = cameras[j];
                if (camera->isVisible() == false)
                {
                    continue;
                }
                
                Camera::_visitingCamera = camera;
                for (auto& l : sceneListeners)
                {
                    if (onEvent(l))
                    {
                        shouldStopPropagation = true;
                        break;
                    }
                }
                if (shouldStopPropagation)
                {
                    break;
                }
            }
            Camera::_visitingCamera = nullptr;
        }
    }
    
    if (fixedPriorityListeners)
    {
        if (!shouldStopPropagation)
        {
            // priority > 0
            ssize_t size = fixedPriorityListeners->size();
            for (; i < size; ++i)
            {
                auto l = fixedPriorityListeners->at(i);
                
                if (l->isEnabled() && !l->isPaused() && l->isRegistered() && onEvent(l))
                {
                    shouldStopPropagation = true;
                    break;
                }
            }
        }
    }
}
void TileMapAtlas::updateAtlasValueAt(const Point& pos, const Color3B& value, int index)
{
    CCASSERT( index >= 0 && index < _textureAtlas->getCapacity(), "updateAtlasValueAt: Invalid index");

    V3F_C4B_T2F_Quad* quad = &((_textureAtlas->getQuads())[index]);

    int x = pos.x;
    int y = pos.y;
    float row = (float) (value.r % _itemsPerRow);
    float col = (float) (value.r / _itemsPerRow);

    float textureWide = (float) (_textureAtlas->getTexture()->getPixelsWide());
    float textureHigh = (float) (_textureAtlas->getTexture()->getPixelsHigh());

    float itemWidthInPixels = _itemWidth * CC_CONTENT_SCALE_FACTOR();
    float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR();

#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
    float left        = (2 * row * itemWidthInPixels + 1) / (2 * textureWide);
    float right       = left + (itemWidthInPixels * 2 - 2) / (2 * textureWide);
    float top         = (2 * col * itemHeightInPixels + 1) / (2 * textureHigh);
    float bottom      = top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh);
#else
    float left        = (row * itemWidthInPixels) / textureWide;
    float right       = left + itemWidthInPixels / textureWide;
    float top         = (col * itemHeightInPixels) / textureHigh;
    float bottom      = top + itemHeightInPixels / textureHigh;
#endif

    quad->tl.texCoords.u = left;
    quad->tl.texCoords.v = top;
    quad->tr.texCoords.u = right;
    quad->tr.texCoords.v = top;
    quad->bl.texCoords.u = left;
    quad->bl.texCoords.v = bottom;
    quad->br.texCoords.u = right;
    quad->br.texCoords.v = bottom;

    quad->bl.vertices.x = (float) (x * _itemWidth);
    quad->bl.vertices.y = (float) (y * _itemHeight);
    quad->bl.vertices.z = 0.0f;
    quad->br.vertices.x = (float)(x * _itemWidth + _itemWidth);
    quad->br.vertices.y = (float)(y * _itemHeight);
    quad->br.vertices.z = 0.0f;
    quad->tl.vertices.x = (float)(x * _itemWidth);
    quad->tl.vertices.y = (float)(y * _itemHeight + _itemHeight);
    quad->tl.vertices.z = 0.0f;
    quad->tr.vertices.x = (float)(x * _itemWidth + _itemWidth);
    quad->tr.vertices.y = (float)(y * _itemHeight + _itemHeight);
    quad->tr.vertices.z = 0.0f;

    Color4B color(_displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity);
    quad->tr.colors = color;
    quad->tl.colors = color;
    quad->br.colors = color;
    quad->bl.colors = color;

    _textureAtlas->setDirty(true);
    int totalQuads = _textureAtlas->getTotalQuads();
    if (index + 1 > totalQuads) {
        _textureAtlas->increaseTotalQuadsWith(index + 1 - totalQuads);
    }
}
示例#29
0
void CCPathFinderNetwork::view()
{
    if( nodes.length > 0 && connectingNodes == false )
    {
		gEngine->textureManager->setTextureIndex( 1 );

        const CCColour nodeColour = CCColour( 1.0f, 0.0f, 0.0f, 1.0f );
        const CCColour pathColour = CCColour( 1.0f, 1.0f, 1.0f, 1.0f );

        CCSetColour( nodeColour );

        for( int i=0; i<nodes.length; ++i )
        {
            const PathNode *node = nodes.list[i];
            GLPushMatrix();
            GLTranslatef( node->point.x, node->point.y, node->point.z );
            CCRenderCube( true );
            GLPopMatrix();
        }

        static CCVector3 start, end;
		{
            GLVertexPointer( 3, GL_FLOAT, sizeof( PathNode ), &nodes.list[0]->point, nodes.length );
#ifndef DXRENDERER
            gRenderer->GLDrawArrays( GL_POINTS, 0, nodes.length );
#endif

            for( int i=0; i<nodes.length; ++i )
            {
                const PathNode *node = nodes.list[i];
                const CCList<PathNode::PathConnection> &connections = node->connections;
                for( int j=0; j<connections.length; ++j )
                {
                    const PathNode::PathConnection *connection = connections.list[j];
                    start.set( node->point.x, 2.0f, node->point.z );
                    end.set( connection->node->point.x, 2.0f, connection->node->point.z );
                    CCRenderLine( start, end );
                }
            }
        }

        if( pathingFrom != NULL )
        {
            CCRenderer::CCSetDepthRead( false );

            CCSetColour( pathColour );

            const PathNode *currentNode = pathingFrom;
            for( int i=0; i<path.endDirection; ++i )
            {
                const int connectionIndex = path.directions[i];
                const CCList<PathNode::PathConnection> &connections = currentNode->connections;
                if( connectionIndex < connections.length )
                {
                    const PathNode::PathConnection *connection = connections.list[connectionIndex];
                    const PathNode *toNode = connection->node;
                    CCASSERT( toNode != NULL );
                    start.set( currentNode->point.x, 5.0f, currentNode->point.z );
                    end.set( toNode->point.x, 5.0f, toNode->point.z );
                    CCRenderLine( start, end );
                    currentNode = toNode;
                }
            }

            CCRenderer::CCSetDepthRead( true );
        }
    }
}
示例#30
0
/// scale getter
float Node::getScale(void) const
{
    CCASSERT( _scaleX == _scaleY, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return");
    return _scaleX;
}