// TODO: Get rid of this function
static int getBitsPerComponent(const QImage::Format fmt)
{
    switch(fmt)
    {
    case QImage::Format_Mono: return 1;
    case QImage::Format_MonoLSB: return 1;
    case QImage::Format_Indexed8: return 8;
    case QImage::Format_RGB32: return 8;
    case QImage::Format_ARGB32: return 8;
    case QImage::Format_ARGB32_Premultiplied: return 8;
    case QImage::Format_RGB16: return 5;
    case QImage::Format_ARGB8565_Premultiplied: return 8;
    case QImage::Format_RGB666: return 6;
    case QImage::Format_ARGB6666_Premultiplied: return 6;
    case QImage::Format_RGB555: return 5;
    case QImage::Format_ARGB8555_Premultiplied: return 5;
    case QImage::Format_RGB888: return 8;
    case QImage::Format_RGB444: return 4;
    case QImage::Format_ARGB4444_Premultiplied: return 4;
    default:
        CCLOGERROR("Unknown QImage::Format %d", fmt);
        return 0;
    }
}
void FrameAniTest::testFrameAni()
{
    setInfo("testFrameAni");
    
    auto sprite = Sprite::create("frameAni/frameAni.png",Rect(0,0,32,32));
    if (sprite == nullptr) {
        CCLOGERROR("File not found!");
        return;
    }
    
    sprite->setScale(8);
    sprite->setPosition(Point(350,400));
    this->addChild(sprite,1);
    
    
    int width = 32;
    int height = 32;
    
    Vector<cocos2d::SpriteFrame *> frameArray;
    Animate *animate = nullptr;
    
    for (int i = 0; i < 6; i ++) {
        for (int j = 0; j < 8; j ++) {
            auto spriteFrame = SpriteFrame::create("frameAni/frameAni.png", Rect(j*width, i*height, width, height));
            frameArray.pushBack(spriteFrame);
        }
    }
    
    auto animation = Animation::createWithSpriteFrames(frameArray, 0.2f);
    animate = Animate::create(animation);

    auto spawn = Spawn::create(animate, NULL);
    sprite->runAction(RepeatForever::create(spawn));
    
    
}
void TurretDestroyState::create() {
    this->complete = true;
    BaseRenderAsset* asset = (BaseRenderAsset*)this->owner->getAsset("anime");
    asset->hide();
    Transform transform = asset->getTransform();
    Position pos = transform.getPosition();
    DestroyEffectBehaviour effect(this->owner->property);
    effect.onCreate(this->owner->getLayer(), pos);
    GeographicNode* node = this->owner->getGeographicNode();
    GeographicGateway* gateway = GeographicGateway::getInstance();
    std::vector<GeographicNode*> nodeVector = gateway->find2x2ByAddress(node->address);
    for (std::vector<GeographicNode*>::iterator it = nodeVector.begin(); it != nodeVector.end(); it++) {
        GeographicNode* node = (*it);
        node->type = BarrierBehaviourType::None;
    }
    int id = this->owner->getProperty()->getId();
    std::string barrierName = this->owner->getProperty()->getName();
    Parameter parameter;
    parameter.set<int>("id", id);
    parameter.set<std::string>("barrierName", barrierName);
    Response res = this->destoryStrategy->update(&parameter);
    if (ServiceStatus::SUCCESS != res.getStatus()) {
        CCLOGERROR("service faild %s, %s, %d", __FILE__, __FUNCTION__, __LINE__);
        res.clear();
        return;
    }
    Notifier::getInstance()->notify(NotifyMessage::Battle_Scene_Score_Update_State);
    bool showOverAllStar = res.get<bool>("showOverAllStar");
    if (false != showOverAllStar) {
        TOverAllTable record = res.get<TOverAllTable>("overAll");
        this->notifyOverAll(record);
    }
    res.clear();
    this->owner->getProperty()->setStatus(BehaviourStatus::COMPLETE);
    return;
}
Exemple #4
0
bool Socket::createSocket(int* sockfd) {
	
	if(*sockfd <= 0) {
		*sockfd = socket(AF_INET, SOCK_STREAM, 0);
		if (*sockfd < 0) {
			CCLOGERROR("ERROR opening socket");
			return false;
		}

		struct timeval tv0;
		tv0.tv_sec = 0;
		tv0.tv_usec = 0;
		struct timeval tv2;
		tv2.tv_sec = 2;
		tv2.tv_usec = 0;
		int yes = 1;

		if (setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
			CCLOGERROR("ERROR failed to enable socket address reuse");
			return false;
		}
		if (setsockopt(*sockfd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)) == -1) {
			CCLOGERROR("ERROR failed to enable socket port reuse");
			return false;
		}
		if (setsockopt(*sockfd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(tv0)) == -1) {
			CCLOGERROR("ERROR failed to enable keepalive");
			return false;
		}
		if (setsockopt(*sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv0, sizeof(tv0)) == -1) {
			CCLOGERROR("ERROR failed to disable read socket timeout");
			return false;
		}
		if (setsockopt(*sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv2, sizeof(tv2)) == -1) {
			CCLOGERROR("ERROR failed to enable send socket timeout");
			return false;
		}
	}
	
	return true;
}
Exemple #5
0
/**
 * cc_utf16_to_utf8:
 * @str: a UTF-16 encoded string
 * @len: the maximum length of @str to use. If @len < 0, then
 *       the string is terminated with a 0 character.
 * @items_read: location to store number of words read, or %nullptr.
 *              If %nullptr, then %G_CONVERT_ERROR_PARTIAL_INPUT will be
 *              returned in case @str contains a trailing partial
 *              character. If an error occurs then the index of the
 *              invalid input is stored here.
 * @items_written: location to store number of bytes written, or %nullptr.
 *                 The value stored here does not include the trailing
 *                 0 byte.
 * @error: location to store the error occuring, or %nullptr to ignore
 *         errors. Any of the errors in #GConvertError other than
 *         %G_CONVERT_ERROR_NO_CONVERSION may occur.
 *
 * Convert a string from UTF-16 to UTF-8. The result will be
 * terminated with a 0 byte.
 *
 * Return value: a pointer to a newly allocated UTF-8 string.
 *               This value must be freed with free(). If an
 *               error occurs, %nullptr will be returned and
 *               @error set.
 **/
char *
cc_utf16_to_utf8 (const unsigned short  *str,
                  int             len,
                  long            *items_read,
                  long            *items_written)
{
    /* This function and g_utf16_to_ucs4 are almost exactly identical - The lines that differ
     * are marked.
     */
    const unsigned short *in;
    char *out;
    char *result = nullptr;
    int n_bytes;
    unsigned int high_surrogate;

    if (str == 0) return nullptr;

    n_bytes = 0;
    in = str;
    high_surrogate = 0;
    while ((len < 0 || in - str < len) && *in)
    {
        unsigned short c = *in;
        unsigned int wc;

        if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
        {
            if (high_surrogate)
            {
                wc = SURROGATE_VALUE (high_surrogate, c);
                high_surrogate = 0;
            }
            else
            {
                CCLOGERROR("Invalid sequence in conversion input");
                goto err_out;
            }
        }
        else
        {
            if (high_surrogate)
            {
                CCLOGERROR("Invalid sequence in conversion input");
                goto err_out;
            }

            if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
            {
                high_surrogate = c;
                goto next1;
            }
            else
                wc = c;
        }

        /********** DIFFERENT for UTF8/UCS4 **********/
        n_bytes += UTF8_LENGTH (wc);

next1:
        in++;
    }

    if (high_surrogate && !items_read)
    {
        CCLOGERROR("Partial character sequence at end of input");
        goto err_out;
    }

    /* At this point, everything is valid, and we just need to convert
     */
    /********** DIFFERENT for UTF8/UCS4 **********/
    result = new char[n_bytes + 1];

    high_surrogate = 0;
    out = result;
    in = str;
    while (out < result + n_bytes)
    {
        unsigned short c = *in;
        unsigned int wc;

        if (c >= 0xdc00 && c < 0xe000) /* low surrogate */
        {
            wc = SURROGATE_VALUE (high_surrogate, c);
            high_surrogate = 0;
        }
        else if (c >= 0xd800 && c < 0xdc00) /* high surrogate */
        {
            high_surrogate = c;
            goto next2;
        }
        else
            wc = c;

        /********** DIFFERENT for UTF8/UCS4 **********/
        out += cc_unichar_to_utf8 (wc, out);

next2:
        in++;
    }

    /********** DIFFERENT for UTF8/UCS4 **********/
    *out = '\0';

    if (items_written)
        /********** DIFFERENT for UTF8/UCS4 **********/
        *items_written = out - result;

err_out:
    if (items_read)
        *items_read = in - str;

    return result;
}
Exemple #6
0
void GLViewImpl::onGLFWError(int errorID, const char* errorDesc)
{
    CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc);
}
void Renderer::processRenderCommand(RenderCommand* command)
{
    auto commandType = command->getType();
    if( RenderCommand::Type::TRIANGLES_COMMAND == commandType)
    {
        //Draw if we have batched other commands which are not triangle command
        flush3D();
        flushQuads();
        
        //Process triangle command
        auto cmd = static_cast<TrianglesCommand*>(command);
        
        //Draw batched Triangles if necessary
        if(cmd->isSkipBatching() || _filledVertex + cmd->getVertexCount() > VBO_SIZE || _filledIndex + cmd->getIndexCount() > INDEX_VBO_SIZE)
        {
            CCASSERT(cmd->getVertexCount()>= 0 && cmd->getVertexCount() < VBO_SIZE, "VBO for vertex is not big enough, please break the data down or use customized render command");
            CCASSERT(cmd->getIndexCount()>= 0 && cmd->getIndexCount() < INDEX_VBO_SIZE, "VBO for index is not big enough, please break the data down or use customized render command");
            //Draw batched Triangles if VBO is full
            drawBatchedTriangles();
        }
        
        //Batch Triangles
        _batchedCommands.push_back(cmd);
        
        fillVerticesAndIndices(cmd);
        
        if(cmd->isSkipBatching())
        {
            drawBatchedTriangles();
        }
        
    }
    else if ( RenderCommand::Type::QUAD_COMMAND == commandType )
    {
        //Draw if we have batched other commands which are not quad command
        flush3D();
        flushTriangles();
        
        //Process quad command
        auto cmd = static_cast<QuadCommand*>(command);
        
        //Draw batched quads if necessary
        if(cmd->isSkipBatching()|| (_numberQuads + cmd->getQuadCount()) * 4 > VBO_SIZE )
        {
            CCASSERT(cmd->getQuadCount()>= 0 && cmd->getQuadCount() * 4 < VBO_SIZE, "VBO for vertex is not big enough, please break the data down or use customized render command");
            //Draw batched quads if VBO is full
            drawBatchedQuads();
        }
        
        //Batch Quads
        _batchQuadCommands.push_back(cmd);
        
        fillQuads(cmd);
        
        if(cmd->isSkipBatching())
        {
            drawBatchedQuads();
        }
    }
    else if (RenderCommand::Type::MESH_COMMAND == commandType)
    {
        flush2D();
        auto cmd = static_cast<MeshCommand*>(command);
        
        if (cmd->isSkipBatching() || _lastBatchedMeshCommand == nullptr || _lastBatchedMeshCommand->getMaterialID() != cmd->getMaterialID())
        {
            flush3D();
            
            if(cmd->isSkipBatching())
            {
                // XXX: execute() will call bind() and unbind()
                // but unbind() shouldn't be call if the next command is a MESH_COMMAND with Material.
                // Once most of cocos2d-x moves to Pass/StateBlock, only bind() should be used.
                cmd->execute();
            }
            else
            {
                cmd->preBatchDraw();
                cmd->batchDraw();
                _lastBatchedMeshCommand = cmd;
            }
        }
        else
        {
            cmd->batchDraw();
        }
    }
    else if(RenderCommand::Type::GROUP_COMMAND == commandType)
    {
        flush();
        int renderQueueID = ((GroupCommand*) command)->getRenderQueueID();
        visitRenderQueue(_renderGroups[renderQueueID]);
    }
    else if(RenderCommand::Type::CUSTOM_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<CustomCommand*>(command);
        cmd->execute();
    }
    else if(RenderCommand::Type::BATCH_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<BatchCommand*>(command);
        cmd->execute();
    }
    else if(RenderCommand::Type::PRIMITIVE_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<PrimitiveCommand*>(command);
        cmd->execute();
    }
    else
    {
        CCLOGERROR("Unknown commands in renderQueue");
    }
}
Exemple #8
0
void Renderer::processRenderCommand(RenderCommand* command)
{
    auto commandType = command->getType();
    if( RenderCommand::Type::TRIANGLES_COMMAND == commandType)
    {
        // flush other queues
        flush3D();

        auto cmd = static_cast<TrianglesCommand*>(command);
        
        // flush own queue when buffer is full
        if(_filledVertex + cmd->getVertexCount() > VBO_SIZE || _filledIndex + cmd->getIndexCount() > INDEX_VBO_SIZE)
        {
            CCASSERT(cmd->getVertexCount()>= 0 && cmd->getVertexCount() < VBO_SIZE, "VBO for vertex is not big enough, please break the data down or use customized render command");
            CCASSERT(cmd->getIndexCount()>= 0 && cmd->getIndexCount() < INDEX_VBO_SIZE, "VBO for index is not big enough, please break the data down or use customized render command");
            drawBatchedTriangles();
        }
        
        // queue it
        _queuedTriangleCommands.push_back(cmd);
        _filledIndex += cmd->getIndexCount();
        _filledVertex += cmd->getVertexCount();
    }
    else if (RenderCommand::Type::MESH_COMMAND == commandType)
    {
        flush2D();
        auto cmd = static_cast<MeshCommand*>(command);
        
        if (cmd->isSkipBatching() || _lastBatchedMeshCommand == nullptr || _lastBatchedMeshCommand->getMaterialID() != cmd->getMaterialID())
        {
            flush3D();

            CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_MESH_COMMAND");

            if(cmd->isSkipBatching())
            {
                // XXX: execute() will call bind() and unbind()
                // but unbind() shouldn't be call if the next command is a MESH_COMMAND with Material.
                // Once most of cocos2d-x moves to Pass/StateBlock, only bind() should be used.
                cmd->execute();
            }
            else
            {
                cmd->preBatchDraw();
                cmd->batchDraw();
                _lastBatchedMeshCommand = cmd;
            }
        }
        else
        {
            CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_MESH_COMMAND");
            cmd->batchDraw();
        }
    }
    else if(RenderCommand::Type::GROUP_COMMAND == commandType)
    {
        flush();
        int renderQueueID = ((GroupCommand*) command)->getRenderQueueID();
        CCGL_DEBUG_PUSH_GROUP_MARKER("RENDERER_GROUP_COMMAND");
        visitRenderQueue(_renderGroups[renderQueueID]);
        CCGL_DEBUG_POP_GROUP_MARKER();
    }
    else if(RenderCommand::Type::CUSTOM_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<CustomCommand*>(command);
        CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_CUSTOM_COMMAND");
        cmd->execute();
    }
    else if(RenderCommand::Type::BATCH_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<BatchCommand*>(command);
        CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_BATCH_COMMAND");
        cmd->execute();
    }
    else if(RenderCommand::Type::PRIMITIVE_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<PrimitiveCommand*>(command);
        CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_PRIMITIVE_COMMAND");
        cmd->execute();
    }
    else
    {
        CCLOGERROR("Unknown commands in renderQueue");
    }
}
Exemple #9
0
void Label::updateContent()
{
    std::u16string utf16String;
    if (StringUtils::UTF8ToUTF16(_originalUTF8String, utf16String))
    {
        _currentUTF16String  = utf16String;
    }

    computeStringNumLines();
    if (_fontAtlas)
    {
        computeHorizontalKernings(_currentUTF16String);
    }

    if (_textSprite)
    {
        Node::removeChild(_textSprite,true);
        _textSprite = nullptr;
        if (_shadowNode)
        {
            Node::removeChild(_shadowNode,true);
            _shadowNode = nullptr;
        }
    }

    if (_fontAtlas)
    {
        alignText();
    }
    else
    {
        if (!_compatibleMode)
        {
            _fontDefinition._fontName = _systemFont;
            _fontDefinition._fontSize = _systemFontSize;

            _fontDefinition._alignment = _hAlignment;
            _fontDefinition._vertAlignment = _vAlignment;

            _fontDefinition._dimensions.width = _labelWidth;
            _fontDefinition._dimensions.height = _labelHeight;

            _fontDefinition._fontFillColor.r = _textColor.r;
            _fontDefinition._fontFillColor.g = _textColor.g;
            _fontDefinition._fontFillColor.b = _textColor.b;

            _fontDefinition._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;
#endif
        }

        createSpriteWithFontDefinition();
    }
    _contentDirty = false;
}
void Renderer::visitRenderQueue(const RenderQueue& queue)
{
    ssize_t size = queue.size();
    
    for (ssize_t index = 0; index < size; ++index)
    {
        auto command = queue[index];
        auto commandType = command->getType();
        if( RenderCommand::Type::TRIANGLES_COMMAND == commandType)
        {
            flush3D();
            if(_numberQuads > 0)
            {
                drawBatchedQuads();
                _lastMaterialID = 0;
            }
            
            auto cmd = static_cast<TrianglesCommand*>(command);
            //Batch Triangles
            if( _filledVertex + cmd->getVertexCount() > VBO_SIZE || _filledIndex + cmd->getIndexCount() > INDEX_VBO_SIZE)
            {
                CCASSERT(cmd->getVertexCount()>= 0 && cmd->getVertexCount() < VBO_SIZE, "VBO for vertex is not big enough, please break the data down or use customized render command");
                CCASSERT(cmd->getIndexCount()>= 0 && cmd->getIndexCount() < INDEX_VBO_SIZE, "VBO for index is not big enough, please break the data down or use customized render command");
                //Draw batched Triangles if VBO is full
                drawBatchedTriangles();
            }
            
            _batchedCommands.push_back(cmd);
            
            fillVerticesAndIndices(cmd);

        }
        else if ( RenderCommand::Type::QUAD_COMMAND == commandType )
        {
            flush3D();
            if(_filledIndex > 0)
            {
                drawBatchedTriangles();
                _lastMaterialID = 0;
            }
            auto cmd = static_cast<QuadCommand*>(command);
            //Batch quads
            if( (_numberQuads + cmd->getQuadCount()) * 4 > VBO_SIZE )
            {
                CCASSERT(cmd->getQuadCount()>= 0 && cmd->getQuadCount() * 4 < VBO_SIZE, "VBO for vertex is not big enough, please break the data down or use customized render command");
                //Draw batched quads if VBO is full
                drawBatchedQuads();
            }
            
            _batchQuadCommands.push_back(cmd);
            
            fillQuads(cmd);

        }
        else if(RenderCommand::Type::GROUP_COMMAND == commandType)
        {
            flush();
            int renderQueueID = ((GroupCommand*) command)->getRenderQueueID();
            visitRenderQueue(_renderGroups[renderQueueID]);
        }
        else if(RenderCommand::Type::CUSTOM_COMMAND == commandType)
        {
            flush();
            auto cmd = static_cast<CustomCommand*>(command);
            cmd->execute();
        }
        else if(RenderCommand::Type::BATCH_COMMAND == commandType)
        {
            flush();
            auto cmd = static_cast<BatchCommand*>(command);
            cmd->execute();
        }
        else if(RenderCommand::Type::PRIMITIVE_COMMAND == commandType)
        {
            flush();
            auto cmd = static_cast<PrimitiveCommand*>(command);
            cmd->execute();
        }
        else if (RenderCommand::Type::MESH_COMMAND == commandType)
        {
            flush2D();
            auto cmd = static_cast<MeshCommand*>(command);
            if (_lastBatchedMeshCommand == nullptr || _lastBatchedMeshCommand->getMaterialID() != cmd->getMaterialID())
            {
                flush3D();
                cmd->preBatchDraw();
                cmd->batchDraw();
                _lastBatchedMeshCommand = cmd;
            }
            else
            {
                cmd->batchDraw();
            }
        }
        else
        {
            CCLOGERROR("Unknown commands in renderQueue");
        }
    }
}
Exemple #11
0
void Properties::readProperties()
{
    CCASSERT(_data->getSize() >0, "Invalid data");

    char line[2048];
    char variable[256];
    int c;
    char* name;
    char* value;
    char* parentID;
    char* rc;
    char* rcc;
    char* rccc;
    bool comment = false;

    while (true)
    {
        // Skip whitespace at the start of lines
        skipWhiteSpace();

        // Stop when we have reached the end of the file.
        if (eof())
            break;

        // Read the next line.
        rc = readLine(line, 2048);
        if (rc == NULL)
        {
            CCLOGERROR("Error reading line from file.");
            return;
        }

        // Ignore comments
        if (comment)
        {
            // Check for end of multi-line comment at either start or end of line
            if (strncmp(line, "*/", 2) == 0)
                comment = false;
            else
            {
                trimWhiteSpace(line);
                const auto len = strlen(line);
                if (len >= 2 && strncmp(line + (len - 2), "*/", 2) == 0)
                    comment = false;
            }
        }
        else if (strncmp(line, "/*", 2) == 0)
        {
            // Start of multi-line comment (must be at start of line)
            comment = true;
        }
        else if (strncmp(line, "//", 2) != 0)
        {
            // If an '=' appears on this line, parse it as a name/value pair.
            // Note: strchr() has to be called before strtok(), or a backup of line has to be kept.
            rc = strchr(line, '=');
            if (rc != NULL)
            {
                // First token should be the property name.
                name = strtok(line, "=");
                if (name == NULL)
                {
                    CCLOGERROR("Error parsing properties file: attribute without name.");
                    return;
                }

                // Remove white-space from name.
                name = trimWhiteSpace(name);

                // Scan for next token, the property's value.
                value = strtok(NULL, "");
                if (value == NULL)
                {
                    CCLOGERROR("Error parsing properties file: attribute with name ('%s') but no value.", name);
                    return;
                }

                // Remove white-space from value.
                value = trimWhiteSpace(value);

                // Is this a variable assignment?
                if (isVariable(name, variable, 256))
                {
                    setVariable(variable, value);
                }
                else
                {
                    // Normal name/value pair
                    _properties.push_back(Property(name, value));
                }
            }
            else
            {
                parentID = NULL;

                // Get the last character on the line (ignoring whitespace).
                const char* lineEnd = trimWhiteSpace(line) + (strlen(trimWhiteSpace(line)) - 1);

                // This line might begin or end a namespace,
                // or it might be a key/value pair without '='.

                // Check for '{' on same line.
                rc = strchr(line, '{');

                // Check for inheritance: ':'
                rcc = strchr(line, ':');

                // Check for '}' on same line.
                rccc = strchr(line, '}');
            
                // Get the name of the namespace.
                name = strtok(line, " \t\n{");
                name = trimWhiteSpace(name);
                if (name == NULL)
                {
                    CCLOGERROR("Error parsing properties file: failed to determine a valid token for line '%s'.", line);
                    return;
                }
                else if (name[0] == '}')
                {
                    // End of namespace.
                    return;
                }

                // Get its ID if it has one.
                value = strtok(NULL, ":{");
                value = trimWhiteSpace(value);

                // Get its parent ID if it has one.
                if (rcc != NULL)
                {
                    parentID = strtok(NULL, "{");
                    parentID = trimWhiteSpace(parentID);
                }

                if (value != NULL && value[0] == '{')
                {
                    // If the namespace ends on this line, seek back to right before the '}' character.
                    if (rccc && rccc == lineEnd)
                    {
                        if (seekFromCurrent(-1) == false)
                        {
                            CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                            return;
                        }
                        while (readChar() != '}')
                        {
                            if (seekFromCurrent(-2) == false)
                            {
                                CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                return;
                            }
                        }
                        if (seekFromCurrent(-1) == false)
                        {
                            CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                            return;
                        }
                    }

                    // New namespace without an ID.
                    Properties* space = new (std::nothrow) Properties(_data, _dataIdx, name, NULL, parentID, this);
                    _namespaces.push_back(space);

                    // If the namespace ends on this line, seek to right after the '}' character.
                    if (rccc && rccc == lineEnd)
                    {
                        if (seekFromCurrent(1) == false)
                        {
                            CCLOGERROR("Failed to seek to immediately after a '}' character in properties file.");
                            return;
                        }
                    }
                }
                else
                {
                    // If '{' appears on the same line.
                    if (rc != NULL)
                    {
                        // If the namespace ends on this line, seek back to right before the '}' character.
                        if (rccc && rccc == lineEnd)
                        {
                            if (seekFromCurrent(-1) == false)
                            {
                                CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                return;
                            }
                            while (readChar() != '}')
                            {
                                if (seekFromCurrent(-2) == false)
                                {
                                    CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                    return;
                                }
                            }
                            if (seekFromCurrent(-1) == false)
                            {
                                CCLOGERROR("Failed to seek back to before a '}' character in properties file.");
                                return;
                            }
                        }

                        // Create new namespace.
                        Properties* space = new (std::nothrow) Properties(_data, _dataIdx, name, value, parentID, this);
                        _namespaces.push_back(space);

                        // If the namespace ends on this line, seek to right after the '}' character.
                        if (rccc && rccc == lineEnd)
                        {
                            if (seekFromCurrent(1) == false)
                            {
                                CCLOGERROR("Failed to seek to immediately after a '}' character in properties file.");
                                return;
                            }
                        }
                    }
                    else
                    {
                        // Find out if the next line starts with "{"
                        skipWhiteSpace();
                        c = readChar();
                        if (c == '{')
                        {
                            // Create new namespace.
                            Properties* space = new (std::nothrow) Properties(_data, _dataIdx, name, value, parentID, this);
                            _namespaces.push_back(space);
                        }
                        else
                        {
                            // Back up from fgetc()
                            if (seekFromCurrent(-1) == false)
                                CCLOGERROR("Failed to seek backwards a single character after testing if the next line starts with '{'.");

                            // Store "name value" as a name/value pair, or even just "name".
                            if (value != NULL)
                            {
                                _properties.push_back(Property(name, value));
                            }
                            else
                            {
                                _properties.push_back(Property(name, ""));
                            }
                        }
                    }
                }
            }
        }
    }
}
Exemple #12
0
void* connectionAccepter(void* threadData) {
	MessageReceiverData* messageReceiverData = (MessageReceiverData*)threadData;

	socklen_t clilen;
	struct sockaddr_in cli_addr;
	clilen = sizeof(cli_addr);
		
	while(messageReceiverData->socket != NULL && *messageReceiverData->sockfd > 0 && messageReceiverData->socket->isBound()) {
		int sockfd = *messageReceiverData->sockfd;

		fcntl(sockfd, F_SETFL, *messageReceiverData->sockFdFlags | O_NONBLOCK);
		
		fd_set rfd;
		FD_ZERO(&rfd);
		FD_SET(sockfd, &rfd);
		struct timeval tv;
		tv.tv_sec = 0;
		tv.tv_usec = 20000;	//20ms read timeout
		int retVal = select(sockfd+1, &rfd, NULL, NULL, &tv);
		//CCLOG("read accept select retVal: %d", retVal);

		if (retVal > 0) {		
		
			if(FD_ISSET(sockfd, &rfd)) {
				int newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
				if(*messageReceiverData->sockfd <= 0) {
					break;
				}
				
				if (newsockfd < 0) {
					CCLOGERROR("ERROR on accept - newsockfd=%d", newsockfd);
					return false;
				}
				CCLOG("Accepted new socket connection on socket %d", newsockfd);

				fcntl(newsockfd, F_SETFL, *messageReceiverData->sockFdFlags | O_NONBLOCK);
							
				//start our message receiver;
				MessageReceiverData* messageReceiverDataCopy = new MessageReceiverData();
				messageReceiverDataCopy->socket = messageReceiverData->socket;
				messageReceiverDataCopy->sockfd = new int(newsockfd);
				messageReceiverDataCopy->sockFdFlags = messageReceiverData->sockFdFlags;
				messageReceiverDataCopy->buffer = "";
				messageReceiverDataCopy->isSocketReady = false;
				pthread_create(&messageReceiverDataCopy->thread, NULL, &messageReceiver, messageReceiverDataCopy);

				int waitCounter = 0;
				while(waitCounter++ < 500 && !messageReceiverDataCopy->isSocketReady) {
					usleep(1000);
				}
				
				if(waitCounter >= 500) {
					CCLOGERROR("Accepted successfully but failed to setup reading from socket from socket id %d in time", messageReceiverData->socket->getId());
					close(*messageReceiverDataCopy->sockfd);
					*messageReceiverDataCopy->sockfd = 0;
					return false;
				}else {
					messageReceiverData->socket->setConnected(true);
					messageReceiverData->children.push_back(messageReceiverDataCopy);
				}
			}else {
				CCLOGERROR("Select socket doesn't match accepted rfd?");
			}
			
		}else if (retVal == 0) {
			//CCLOGERROR("Timeout on accept");
			
		}else {
			CCLOGERROR("ERROR on select for accept");
			
		}
	}

	CCLOG("Left connection accepting thread with sockfd=%d", *messageReceiverData->sockfd);

	close(*messageReceiverData->sockfd);
	*messageReceiverData->sockfd = 0;
	delete messageReceiverData;
	
	pthread_exit(0);
}
Exemple #13
0
bool Socket::connectTo(const string &hostname, const int &port, int timeout) {

	CCLOG("Connecting with socket id %d...", _id);

	if(_messageReceiverData != NULL) {
		if(*_messageReceiverData->sockfd > 0) {
			//pthread_kill(_messageReceiverData->thread, 0);
			close(*_messageReceiverData->sockfd);
			*_messageReceiverData->sockfd = 0;
			CCLOG("Set sockfd=0 in connectTo");
		}
		_messageReceiverData = NULL;
	}
	
	if(!Socket::createSocket(&_sockfd)) {
		return false;
	}
	
	//set socket to nonblocking
	if(_sockfdFlags == -1) {
		_sockfdFlags = fcntl(_sockfd, F_GETFL, 0);
	}
    fcntl(_sockfd, F_SETFL, _sockfdFlags | O_NONBLOCK);
	
	struct hostent *server;
	server = gethostbyname(hostname.c_str());
	if (server == NULL) {
		CCLOGERROR("ERROR, no such host \"%s\"", hostname.c_str());
		return false;
	}
	
	struct sockaddr_in serv_addr;
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
	serv_addr.sin_port = htons(port);
	
	//perform a select to do a timeout
	connect(_sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr));

	fd_set rfd;
	FD_ZERO(&rfd);
	FD_SET(_sockfd, &rfd);
	struct timeval tv;
	tv.tv_sec = timeout;	//X second timeout
	tv.tv_usec = 0;
	int retVal = select(_sockfd+1, NULL, &rfd, NULL, &tv);
    CCLOG("select retVal: %d", retVal);

	bool success = false;
	if (retVal == 1) {
		int so_error;
        socklen_t slen = sizeof so_error;
        getsockopt(_sockfd, SOL_SOCKET, SO_ERROR, &so_error, &slen);
        if (so_error == 0) {
            CCLOG("Successfully connected");
            success = true;
        } else {
            CCLOGERROR("Failed to connect - error: %d", so_error);
            success = false;
        }
    } else {     
        CCLOGERROR("No socket??"); 
    }
	
	
	if(!success) {
		return false;
	}
	
	//re-enable blocking
    //fcntl(_sockfd, F_SETFL, _sockfdFlags);
		
	_isConnected = true;

	//start our message receiver;
	_messageReceiverData = new MessageReceiverData();
	_messageReceiverData->socket = this;
	_messageReceiverData->sockfd = &_sockfd;
	_messageReceiverData->sockFdFlags = &_sockfdFlags;
	_messageReceiverData->buffer = "";
	_messageReceiverData->isSocketReady = false;
	pthread_create(&_messageReceiverData->thread, NULL, &messageReceiver, _messageReceiverData);
	
	int waitCounter = 0;
	while(waitCounter++ < 500 && _messageReceiverData != NULL && !_messageReceiverData->isSocketReady) {
		usleep(1000);
	}
	
	if(waitCounter >= 500) {
		CCLOGERROR("Connected successfully but failed to setup reading from socket in time");
		disconnect(false);
		return false;
	}
	
	if(_delegate != NULL) {
		_delegate->onConnect();
	}
	
	return true;
}
Exemple #14
0
void GameLevel::load(const std::string &levelFile) {
  unload();

  std::string buffer = levelFile.empty() ? sTemplateMap : JsonParser::getBuffer(levelFile);
  if (buffer.empty()) {
    load("");
    return;
  }
  JsonParser parser(buffer);
  if (!parser) {
    CCLOG("%s", buffer.c_str());
    CCLOGERROR("Cannot load the level file: %s", levelFile.c_str());
  }

  CCLOG("Loading level file: %s", levelFile.empty() ? "Template" : levelFile.c_str());

  auto& doc = parser.getCurrentDocument();

  std::string paletteFile = doc[LEVEL_PALETTE_FILE].GetString();
  CC_SAFE_DELETE(mPalette);
  mPalette = new ColorPalette(paletteFile);

  // Shadows.
  if (doc.HasMember(SHADOW_GROUP)) {
    mNumShadowGroup = doc[SHADOW_GROUP].Size();
    parser.parseArray(doc, SHADOW_GROUP, [&](JsonSizeT i, JsonValueT &val) {
      addShadowGroup();
      mShadows[i]->load(val);
      initShadowGroup(i);
    });
  }

  // Sprites.
  CC_ASSERT(mSpriteList.empty());
  if (doc.HasMember(GAME_SPRITES)) {
    parser.parseArray(doc, GAME_SPRITES, [&](JsonSizeT i, JsonValueT &val) {
      mSpriteList.push_back(new GameSprite());
      mSpriteList.back()->load(val);
      mGameLayer->getBlockRoot()->addChild(mSpriteList.back()->getSprite(),
                                           mSpriteList.back()->ZOrder);
    });
  }

  // Effects.
  CC_ASSERT(mEffects.empty());
  if (doc.HasMember(GAME_FX)) {
    parser.parseArray(doc, GAME_FX, [&](JsonSizeT i, JsonValueT &val) {
      mEffects.push_back(val.GetString());
    });
  }
  loadFx();

  // Objects.
  mHeroSpawnPos = doc[LEVEL_SPAWN_POS].GetVec2();
  createHero(mHeroSpawnPos);
  parser.parseArray(doc, LEVEL_BLOCK_ARRAY, [&](JsonSizeT i, JsonValueT& val) {
    mObjectManager->createObject(val);
  });

  // Update shadow right after loading objects.
  for (auto sm : mShadows) {
    sm->update(0);
  }
  
  // Time events.
  CC_ASSERT(mTimeEvents.empty());
  if (doc.HasMember(TIME_EVENTS)) {
    parser.parseArray(doc, TIME_EVENTS, [&](JsonSizeT i, JsonValueT &val) {
      auto timeEvent = new TimeEvent();
      timeEvent->load(val);
      mTimeEvents.push_back(timeEvent);
    });
  }

  updateBounds();
  mBackground->clear();
  mBackground->drawSolidRect({mBounds.getMinX(), mBounds.getMinY()},
                             {mBounds.getMaxX(), mBounds.getMaxY()},
                             Color4F(mPalette->getBackgroundColor()));

  setCurrentFile(levelFile);

  mGameLayer->afterLoad();
}
void Renderer::processRenderCommand(RenderCommand* command)
{
    auto commandType = command->getType();
    if( RenderCommand::Type::TRIANGLES_COMMAND == commandType)
    {
        //Draw if we have batched other commands which are not triangle command
        flush3D();
        flushQuads();

        //Process triangle command
        auto cmd = static_cast<TrianglesCommand*>(command);

        //Draw batched Triangles if necessary
        if(cmd->isSkipBatching() || _filledVertex + cmd->getVertexCount() > VBO_SIZE || _filledIndex + cmd->getIndexCount() > INDEX_VBO_SIZE)
        {
            CCASSERT(cmd->getVertexCount()>= 0 && cmd->getVertexCount() < VBO_SIZE, "VBO for vertex is not big enough, please break the data down or use customized render command");
            CCASSERT(cmd->getIndexCount()>= 0 && cmd->getIndexCount() < INDEX_VBO_SIZE, "VBO for index is not big enough, please break the data down or use customized render command");
            //Draw batched Triangles if VBO is full
            drawBatchedTriangles();
        }

        //Batch Triangles
        _batchedCommands.push_back(cmd);

        fillVerticesAndIndices(cmd);

        if(cmd->isSkipBatching())
        {
            drawBatchedTriangles();
        }

    }
    else if ( RenderCommand::Type::QUAD_COMMAND == commandType )
    {
        //Draw if we have batched other commands which are not quad command
        flush3D();
        flushTriangles();

        //Process quad command
        auto cmd = static_cast<QuadCommand*>(command);

        //Draw batched quads if necessary
        if(cmd->isSkipBatching()|| (_numberQuads + cmd->getQuadCount()) * 4 > VBO_SIZE )
        {
            CCASSERT(cmd->getQuadCount()>= 0 && cmd->getQuadCount() * 4 < VBO_SIZE, "VBO for vertex is not big enough, please break the data down or use customized render command");
            //Draw batched quads if VBO is full
            drawBatchedQuads();
        }

        //Batch Quads
        _batchQuadCommands.push_back(cmd);

        fillQuads(cmd);

        if(cmd->isSkipBatching())
        {
            drawBatchedQuads();
        }
    }
    else if (RenderCommand::Type::MESH_COMMAND == commandType)
    {
        flush2D();
        auto cmd = static_cast<MeshCommand*>(command);

        if (cmd->isSkipBatching() || _lastBatchedMeshCommand == nullptr || _lastBatchedMeshCommand->getMaterialID() != cmd->getMaterialID())
        {
            flush3D();

            if(cmd->isSkipBatching())
            {
                cmd->execute();
            }
            else
            {
                cmd->preBatchDraw();
                cmd->batchDraw();
                _lastBatchedMeshCommand = cmd;
            }
        }
        else
        {
            cmd->batchDraw();
        }
    }
    else if(RenderCommand::Type::GROUP_COMMAND == commandType)
    {
        flush();
        int renderQueueID = ((GroupCommand*) command)->getRenderQueueID();
        visitRenderQueue(_renderGroups[renderQueueID]);
    }
    else if(RenderCommand::Type::CUSTOM_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<CustomCommand*>(command);
        cmd->execute();
    }
    else if(RenderCommand::Type::BATCH_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<BatchCommand*>(command);
        cmd->execute();
    }
    else if(RenderCommand::Type::BEGIN_SCISSOR_COMMAND == commandType)
    {
        flush();
        command->execute<BeginScissorCommand>();
    }
    else if(RenderCommand::Type::END_SCISSOR_COMMAND == commandType)
    {
        flush();
        command->execute<EndScissorCommand>();
    }
    else if(RenderCommand::Type::BEGIN_STENCIL_COMMAND == commandType)
    {
        flush();
        command->execute<BeginStencilCommand>();
    }
    else if(RenderCommand::Type::AFTER_STENCIL_COMMAND == commandType)
    {
        flush();
        command->execute<AfterStencilCommand>();
    }
    else if(RenderCommand::Type::END_STENCIL_COMMAND == commandType)
    {
        flush();
        command->execute<EndStencilCommand>();
    }
    else
    {
        CCLOGERROR("Unknown commands in renderQueue");
    }
}
void EziFacebookFriend::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
    
    CCHttpResponse* response = (CCHttpResponse*)data;
    
    if (!response)
    {
        CCLOG("[EziSocial Error]: No Response");
    }
    
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        //CCLog("%s completed", response->getHttpRequest()->getTag());
    }
    
    int statusCode = response->getResponseCode();
    
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    
    if (!response->isSucceed())
    {
        CCLog("[EziSocial Error]: response failed");
        CCLog("[EziSocial Error]: error buffer: %s", response->getErrorBuffer());
        return;
    }
    
    // Dump the data
    std::vector<char> *buffer = response->getResponseData();
    
    // Create the CCSprite from data dump...
    
    CCImage * img=new CCImage();
    img->initWithImageData(&(buffer->front()), buffer->size());
    
    // Save file for resue.
    std::string writablePath = CCFileUtils::sharedFileUtils()->getWritablePath();
    //writablePath.append(response->getHttpRequest()->getTag());
    
    std::string fileName = "";
    fileName = fileName.append(_fbID);
    fileName = fileName.append(".jpg");
    writablePath.append(fileName);
    
    //CCLOG("File Name = %s", fileName.c_str());
    
    //CCLOG("File Path = %s", writablePath.c_str());
    
    cocos2d::CCTexture2D* texture = new cocos2d::CCTexture2D();
    texture->initWithImage(img);
    
    if(texture)
    {
        _profilePic = cocos2d::CCSprite::createWithTexture(texture);
    }
    else
    {
        CCLOGERROR("[EziSocial Error]: Cannot create user profile pic from texture.");
    }
    
    img->saveToFile(writablePath.c_str());
    delete img;
    
    if (_target && _selector)
    {
        (_target->*_selector)(_profilePic, _fbID.c_str());
    }
}
// loads info about all tiles,sets self.contentSize & screenLoadRectExtension
// creates & adds tiles for dynamic usage if batchNode
void CCBigImage::prepareTilesWithFileExtensionZ(string plistFile, string extension, int tilesZ)
{
	// load plist with image & tiles info
    CCDictionary *dict = CCDictionary::createWithContentsOfFile(plistFile.c_str());
    if ( !dict )
    {
        CCLOGERROR("CCBigImage#prepareTilesWithFile:extension:z: can not load dictionary from file: %s", plistFile.c_str());
        return;
    }
	
	// load image size
    CCDictionary *sourceDict = (CCDictionary*)dict->objectForKey(std::string("Source"));
    CCSize size = CCSizeFromString(valueForKey("Size", sourceDict));
    
    this->setContentSize(size);
	
	// load tiles
    CCArray* array = (CCArray*)dict->objectForKey(std::string("Tiles"));
	
	_dynamicChildren = CCArray::createWithCapacity(array->count());
    _dynamicChildren->retain();
    
	// set screenLoadRectExtension = size of first tile
	if (array->count())
	{
        CCDictionary *dict_ = (CCDictionary*)array->objectAtIndex(0);
        _screenLoadRectExtension = CCRectFromString(valueForKey("Rect", dict_)).size;
	}
	
	//read data and create nodes and add them
    for (int i=0; i<array->count(); i++)
    {
        CCDictionary* tileDict = (CCDictionary*)array->objectAtIndex(i);

        // All properties of Dictionary
        const char *spriteName = valueForKey("Name", tileDict);
		
		CCRect tileRect = CCRectFromString(valueForKey("Rect", tileDict));
        
		// convert rect origin from top-left to bottom-left
		tileRect.origin.y = this->getContentSize().height - tileRect.origin.y - tileRect.size.height;
		
		// Use forced tile extension or original if tilesExtension isn't set
		if (!extension.empty())
		{
			// Change extension
            string filename = string(spriteName);
            int index = filename.find('.');
            string name = filename.substr(0, index);
			spriteName = (name+"."+extension).c_str();
		}

		// Create & Add Tile (Dynamic Sprite Mode)
		UnloadableSpriteNode* tile = UnloadableSpriteNode::nodeWithImageForRect(spriteName, tileRect);
		this->addChild(tile, tilesZ);
		_dynamicChildren->addObject(tile);
		
    } //< for dict in arr
    
    dict->release();
	
}
void EziFBIncomingRequest::setData(std::string key, std::string data)
{
    
    if (key.compare("REQUEST_TYPE")==0)
    {
        int requestType = atoi(data.c_str());
        switch (requestType)
        {
            case EziSocialWrapperNS::FB_REQUEST::REQUEST_CHALLENGE:
                _requestType = EziSocialWrapperNS::FB_REQUEST::REQUEST_CHALLENGE;
                break;
        
            case EziSocialWrapperNS::FB_REQUEST::REQUEST_GIFT:
                _requestType = EziSocialWrapperNS::FB_REQUEST::REQUEST_GIFT;
                break;
        
            case EziSocialWrapperNS::FB_REQUEST::REQUEST_INVITE:
                _requestType = EziSocialWrapperNS::FB_REQUEST::REQUEST_INVITE;
                break;
                
            default:
                break;
        }
        
    }
    else if (key.compare("REQUEST_ID")==0)
    {
        this->setRequestID(data);
    }
    else if (key.compare("MESSAGE")==0)
    {
        this->setMessage(data);
    }
    else if (key.compare("SENDER_ID")==0)
    {
        if (this->_sender == NULL)
        {
            _sender = EziFacebookFriend::create();
            _sender->retain();
            
        }
        _sender->setID(data.c_str());
    }
    else if (key.compare("SENDER_NAME")==0)
    {
        if (this->_sender == NULL)
        {
            _sender = EziFacebookFriend::create();
            _sender->retain();
        }
        _sender->setName(data.c_str());
    }
    else if (key.compare("TO")==0)
    {
        this->setReceiverID(data);
    }
    else
    {
        CCLOGERROR("Unrecognized Key in EziFBIncomingRequest = %s", key.c_str());
    }
}
Exemple #19
0
			void DLCchecking::update(entityx::ptr<entityx::EntityManager> es, entityx::ptr<entityx::EventManager> events, double dt)
			{
				for (auto entity : es->entities_with_components<Comp::DataVerCheck>())
				{
					entityx::ptr<Comp::DataVerCheck> dllist = entity.component<Comp::DataVerCheck>();
					std::string url = dllist->m_url;

					if (!dllist->m_verlist.empty())
					{
						//we need to check if the version url is valid ( contains a manifest.json )
						url += "/" + dllist->m_verlist.back() + "/manifest.json";
						m_manifest = "";
						CCLOG("DLCchecking reading from %s", url.c_str());

						//list all files at given url
						CURLcode res;
						curl_easy_setopt(_curl, CURLOPT_URL, url.c_str());
#ifdef _DEBUG
						curl_easy_setopt(_curl, CURLOPT_VERBOSE, 1L);
#endif
						curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, write_data);
						curl_easy_setopt(_curl, CURLOPT_WRITEDATA, &m_manifest);
						if (_connectionTimeout) curl_easy_setopt(_curl, CURLOPT_CONNECTTIMEOUT, _connectionTimeout);
						curl_easy_setopt(_curl, CURLOPT_NOSIGNAL, 1L);
						curl_easy_setopt(_curl, CURLOPT_LOW_SPEED_LIMIT, LOW_SPEED_LIMIT);
						curl_easy_setopt(_curl, CURLOPT_LOW_SPEED_TIME, LOW_SPEED_TIME);
						res = curl_easy_perform(_curl);

						CCLOG("DLCchecking read from %s", url.c_str());

						if (res != 0)
						{

							CCLOG("DLCchecking can not read from %s, error code is %d", url.c_str(), res);

							dllist->m_retries--;
							if (0 == dllist->m_retries)
							{
								CCLOGERROR("DLCchecking can not read from %s, error code is %d", url.c_str(), res);
								//signal error
								events->emit<Events::Error>(entity, "DLCchecking system");
								//we give up on this entity
								entity.destroy();
							}
						}
						else
						{
							//read the downloaded manifest to compare md5
							rapidjson::Document json;
							json.Parse<0>(m_manifest.c_str());
							if (json.HasParseError()) {
								CCLOG("GetParseError %s\n", json.GetParseError());
								//version will be removed from the list later.
							}
							else
							{
								//is it possible to update ?
								bool dlc_update_allowed = false;

								//do we need to update ?
								bool dlc_update_required = false;

								std::string version = cocostudio::DictionaryHelper::getInstance()->getStringValue_json(json, "version", "");
								if (version == dllist->m_current_version) //if we have the exact same string : developer update or current version hotfix.
								{
									dlc_update_required = true;
								}
								else if (version.length() > 0 )  //we need to compare string to find if the online version is more recent
								{
									unsigned long lver = 0;
									try {
										lver = ToolBox::stoul(version);
										CCLOG("DLC at %s has Manifest version %lu", url.c_str(), lver);
									}
									catch (std::out_of_range oor)
									{
										lver = 0; //disabling update if online version is too high ( developer version )
									}

									unsigned long lcver = 0;
									try {
										lcver = ToolBox::stoul(dllist->m_current_version);
										CCLOG("Local DLC has Manifest version %lu", url.c_str(), lcver);
									}
									catch (std::out_of_range oor)
									{
										lcver = LONG_MAX; // if local version is too high, update should have been done before
									}

									if (lver > lcver) //not == to prevent LONG_MAX == LONG_MAX
									{
										dlc_update_required = true;
									}
								}

								std::string minAppVersion = cocostudio::DictionaryHelper::getInstance()->getStringValue_json(json, "minAppVersion", "error");
								if (minAppVersion != "error" && dllist->m_current_minAppVersion != "" )
								{
									//CAREFUL HERE with version comparison
									std::vector<unsigned long> mav = splitVersion(minAppVersion);
									std::vector<unsigned long> cmav = splitVersion(dllist->m_current_minAppVersion);

									dlc_update_allowed = true;
									while ( mav.size() < cmav.size() )
									{
										mav.push_back(0);
									}
									for (unsigned int i = 0; i < cmav.size(); ++i)
									{
										if (mav.at(i) > cmav.at(i))
										{
											dlc_update_allowed = false; break;
										}
									}
								}//if we cannot read the minimum app version. we dont download. better safe than sorry.

								if (dlc_update_allowed && dlc_update_required)
								{

									//prepare the list of downloads
									const rapidjson::Value & assets = cocostudio::DictionaryHelper::getInstance()->getSubDictionary_json(json, "assets");

									for (rapidjson::Value::ConstMemberIterator m = assets.MemberonBegin(); m != assets.MemberonEnd(); ++m)
									{
										std::string filename = m->name.GetString();
										std::string filehash = cocostudio::DictionaryHelper::getInstance()->getStringValue_json(m->value, "md5", "error");

										//lowering filehash to be sure
										std::transform(filehash.begin(), filehash.end(), filehash.begin(), ::tolower);

										//std::cout << filename << " : " << filehash << std::endl;

										entityx::Entity newentity = es->create();
										newentity.assign<Comp::LocalFile>(filename);
										newentity.assign<Comp::RemoteMD5>(filehash);
										newentity.assign<Comp::RemoteFile>(dllist->m_url + "/" + dllist->m_verlist.back(), filename);
										
										newentity.assign<Comp::ProgressValue>(1);
									}


									//downloading only the last verison should always be enough ( avoiding too many downloads - keeping all data for one version in same place )
									//if (dllist->m_verlist.empty()) //if we checked all versions
									//{
									entity.remove<Comp::DataVerCheck>();
									//}

									//we dont need to do anything more with this entity
									entity.destroy();
								}

							}

							//remove the version checked from the list
							dllist->m_verlist.pop_back();
							//In case of error, we should check the next version in stack on next update.
							//If success this will not be done ( entity destroyed )
							//TODO : check behavior

						}

						//exit this loop. one per update is enough
						break;
			
					}
					else //no version left to check
					{
						//we dont need to do anything more with this entity
						entity.destroy();
					}
				}
			};
void Renderer::visitRenderQueue(const RenderQueue& queue)
{
    ssize_t size = queue.size();
    
    for (ssize_t index = 0; index < size; ++index)
    {
        auto command = queue[index];
        auto commandType = command->getType();
        if(RenderCommand::Type::QUAD_COMMAND == commandType)
        {
            flush3D();
            auto cmd = static_cast<QuadCommand*>(command);
            //Batch quads
            if(_numQuads + cmd->getQuadCount() > VBO_SIZE)
            {
                CCASSERT(cmd->getQuadCount()>= 0 && cmd->getQuadCount() < VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command");
                
                //Draw batched quads if VBO is full
                drawBatchedQuads();
            }
            
            _batchedQuadCommands.push_back(cmd);
            
            memcpy(_quads + _numQuads, cmd->getQuads(), sizeof(V3F_C4B_T2F_Quad) * cmd->getQuadCount());
            convertToWorldCoordinates(_quads + _numQuads, cmd->getQuadCount(), cmd->getModelView());
            
            _numQuads += cmd->getQuadCount();

        }
        else if(RenderCommand::Type::GROUP_COMMAND == commandType)
        {
            flush();
            int renderQueueID = ((GroupCommand*) command)->getRenderQueueID();
            visitRenderQueue(_renderGroups[renderQueueID]);
        }
        else if(RenderCommand::Type::CUSTOM_COMMAND == commandType)
        {
            flush();
            auto cmd = static_cast<CustomCommand*>(command);
            cmd->execute();
        }
        else if(RenderCommand::Type::BATCH_COMMAND == commandType)
        {
            flush();
            auto cmd = static_cast<BatchCommand*>(command);
            cmd->execute();
        }
        else if (RenderCommand::Type::MESH_COMMAND == commandType)
        {
            flush2D();
            auto cmd = static_cast<MeshCommand*>(command);
            if (_lastBatchedMeshCommand == nullptr || _lastBatchedMeshCommand->getMaterialID() != cmd->getMaterialID())
            {
                flush3D();
                cmd->preBatchDraw();
                cmd->batchDraw();
                _lastBatchedMeshCommand = cmd;
            }
            else
            {
                cmd->batchDraw();
            }
        }
        else
        {
            CCLOGERROR("Unknown commands in renderQueue");
        }
    }
}
int WebSocket::onSocketCallback(struct libwebsocket_context *ctx,
                     struct libwebsocket *wsi,
                     enum libwebsocket_callback_reasons reason,
                     void *user, void *in, size_t len)
{
	//CCLOG("socket callback for %d reason", reason);
    CCAssert(_wsContext == NULL || ctx == _wsContext, "Invalid context.");
    CCAssert(_wsInstance == NULL || wsi == NULL || wsi == _wsInstance, "Invaild websocket instance.");

	switch (reason)
    {
        case LWS_CALLBACK_DEL_POLL_FD:
        case LWS_CALLBACK_PROTOCOL_DESTROY:
        case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
            {
                WsMessage* msg = NULL;
                if (reason == LWS_CALLBACK_CLIENT_CONNECTION_ERROR
                    || (reason == LWS_CALLBACK_PROTOCOL_DESTROY && _readyState == kStateConnecting)
                    || (reason == LWS_CALLBACK_DEL_POLL_FD && _readyState == kStateConnecting)
                    )
                {
                    msg = new WsMessage();
                    msg->what = WS_MSG_TO_UITHREAD_ERROR;
                    _readyState = kStateClosing;
                }
                else if (reason == LWS_CALLBACK_PROTOCOL_DESTROY && _readyState == kStateClosing)
                {
                    msg = new WsMessage();
                    msg->what = WS_MSG_TO_UITHREAD_CLOSE;
                }

                if (msg)
                {
                    _wsHelper->sendMessageToUIThread(msg);
                }
            }
            break;
        case LWS_CALLBACK_CLIENT_ESTABLISHED:
            {
                WsMessage* msg = new WsMessage();
                msg->what = WS_MSG_TO_UITHREAD_OPEN;
                _readyState = kStateOpen;
                /*
                 * start the ball rolling,
                 * LWS_CALLBACK_CLIENT_WRITEABLE will come next service
                 */
                libwebsocket_callback_on_writable(ctx, wsi);
                _wsHelper->sendMessageToUIThread(msg);
            }
            break;
            
        case LWS_CALLBACK_CLIENT_WRITEABLE:
            {
                pthread_mutex_lock(&_wsHelper->_subThreadWsMessageQueueMutex);
                std::list<WsMessage*>::iterator iter = _wsHelper->_subThreadWsMessageQueue->begin();
                
                int bytesWrite = 0;
                for (; iter != _wsHelper->_subThreadWsMessageQueue->end(); ++iter) {

                    WsMessage* subThreadMsg = *iter;
                    
                    if ( WS_MSG_TO_SUBTRHEAD_SENDING_STRING == subThreadMsg->what
                      || WS_MSG_TO_SUBTRHEAD_SENDING_BINARY == subThreadMsg->what)
                    {
                        Data* data = (Data*)subThreadMsg->obj;

                        unsigned char* buf = new unsigned char[LWS_SEND_BUFFER_PRE_PADDING
                                                               + data->len + LWS_SEND_BUFFER_POST_PADDING];
                        
                        memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, data->len);
                        memcpy((char*)&buf[LWS_SEND_BUFFER_PRE_PADDING], data->bytes, data->len);
                        
                        enum libwebsocket_write_protocol writeProtocol;
                        
                        if (WS_MSG_TO_SUBTRHEAD_SENDING_STRING == subThreadMsg->what)
                        {
                            writeProtocol = LWS_WRITE_TEXT;
                        }
                        else
                        {
                            writeProtocol = LWS_WRITE_BINARY;
                        }
                        
                        bytesWrite = libwebsocket_write(wsi,  &buf[LWS_SEND_BUFFER_PRE_PADDING], data->len, writeProtocol);
                        
                        if (bytesWrite < 0) {
                            CCLOGERROR("%s", "libwebsocket_write error...");
                        }
                        if (bytesWrite < data->len) {
                            CCLOGERROR("Partial write LWS_CALLBACK_CLIENT_WRITEABLE\n");
                        }
                        
                        CC_SAFE_DELETE_ARRAY(data->bytes);
                        CC_SAFE_DELETE(data);
                        CC_SAFE_DELETE_ARRAY(buf);
                    }
                    
                    CC_SAFE_DELETE(subThreadMsg);
                }

                _wsHelper->_subThreadWsMessageQueue->clear();
                
                pthread_mutex_unlock(&_wsHelper->_subThreadWsMessageQueueMutex);
                
                /* get notified as soon as we can write again */
                
                libwebsocket_callback_on_writable(ctx, wsi);
            }
            break;
            
        case LWS_CALLBACK_CLOSED:
            {
                
                CCLOG("%s", "connection closing..");

                _wsHelper->quitSubThread();
                
                if (_readyState != kStateClosed)
                {
                    WsMessage* msg = new WsMessage();
                    _readyState = kStateClosed;
                    msg->what = WS_MSG_TO_UITHREAD_CLOSE;
                    _wsHelper->sendMessageToUIThread(msg);
                }
            }
            break;
            
        case LWS_CALLBACK_CLIENT_RECEIVE:
            {
                if (in && len > 0)
                {
                    WsMessage* msg = new WsMessage();
                    msg->what = WS_MSG_TO_UITHREAD_MESSAGE;
                    
                    char* bytes = NULL;
                    Data* data = new Data();
                    
                    if (lws_frame_is_binary(wsi))
                    {
                        
                        bytes = new char[len];
                        data->isBinary = true;
                    }
                    else
                    {
                        bytes = new char[len+1];
                        bytes[len] = '\0';
                        data->isBinary = false;
                    }

                    memcpy(bytes, in, len);
                    
                    data->bytes = bytes;
                    data->len = len;
                    msg->obj = (void*)data;
                    
                    _wsHelper->sendMessageToUIThread(msg);
                }
            }
            break;
        default:
            break;
        
	}
    
	return 0;
}
Exemple #22
0
void EGLViewEventHandler::OnGLFWError(int errorID, const char* errorDesc)
{
    CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc);
}
Exemple #23
0
void* messageReceiver(void* threadData) {

	MessageReceiverData* messageReceiverData = (MessageReceiverData*)threadData;

	Json::Reader reader;
	Json::Value root;
			
	int numFailedReads = 0;
	int bytesRecv;
	char buffer[1024];
	bool isParent = true;
	
	CCLOG("Waiting for data from socket %d... %f", *messageReceiverData->sockfd, Utilities::getMillis());
	while(*messageReceiverData->sockfd > 0 && messageReceiverData->socket != NULL &&
		(!messageReceiverData->isSocketReady || messageReceiverData->socket->isConnected())) {

		bzero(buffer, 1024);
		messageReceiverData->isSocketReady = true;
		
		int sockfd = *messageReceiverData->sockfd;
		isParent = messageReceiverData->socket->getSockFd() == sockfd;

		//CCLOG("Waiting for data from from socket %d - %f", sockfd, Utilities::getMillis());
		
		fd_set rfd;
		FD_ZERO(&rfd);
		FD_SET(sockfd, &rfd);
		struct timeval tv;
		tv.tv_sec = 0;
		tv.tv_usec = 20000;	//20ms read timeout
		int retVal = select(sockfd+1, &rfd, NULL, NULL, &tv);
		//CCLOG("read select retVal: %d", retVal);

		if (retVal > 0) {
		

			bytesRecv = recv(sockfd, buffer, 1023, 0);
			//CCLOG("read BYTES: %d", bytesRecv);
			if(*messageReceiverData->sockfd <= 0 || messageReceiverData->socket == NULL) {
				messageReceiverData->isSocketReady = false;
				break;
			}
			
			if (bytesRecv < 0) {
				CCLOGERROR("ERROR reading from socket %d - %f", sockfd, Utilities::getMillis());
				messageReceiverData->isSocketReady = false;
				if(isParent) {
					messageReceiverData->socket->disconnect(true);
				}else {
					messageReceiverData->socket->disconnectChild(messageReceiverData);
				}
				break;
				
			}else if(bytesRecv == 0) {
				if(numFailedReads++ >= 100) {
					CCLOGERROR("ERROR reading from socket %d (numFailedReads=%d)", sockfd, numFailedReads);
					messageReceiverData->isSocketReady = false;
					if(isParent) {
						messageReceiverData->socket->disconnect(true);
					}else {
						messageReceiverData->socket->disconnectChild(messageReceiverData);
					}
					break;
				}
				
			}else {

				CCLOG("read: %s, retVal=%d, bytesRecv=%d", buffer, retVal, bytesRecv);
				messageReceiverData->buffer+= buffer;
				//CCLOG("messageReceiverData->buffer: %s", messageReceiverData->buffer.c_str());
							
				int endMessagePos = messageReceiverData->buffer.find(MESSAGE_TERMINATOR);
				while(endMessagePos != string::npos && messageReceiverData->buffer != "") {
							
					//pull out the parsed message
					string singleMessage = messageReceiverData->buffer.substr(0, endMessagePos);
					messageReceiverData->buffer = messageReceiverData->buffer.substr(endMessagePos+strlen(MESSAGE_TERMINATOR));
					endMessagePos = messageReceiverData->buffer.find(MESSAGE_TERMINATOR);
				
					//parse JSON
					if(reader.parse(singleMessage, root)) {
						//send off the message to the onMessage delegate
						messageReceiverData->socket->onMessage(root);
					}else {
						CCLOGERROR("Failed to parse message: %s", singleMessage.c_str());
					}
				}
				
				numFailedReads = 0;
			}
			
		} else if(retVal == 0) {
			//CCLOGERROR("Read timeout");
			
		} else {
			CCLOGERROR("Error while polling read socket");

		}
		
	}
	
	/*
	close(*messageReceiverData->sockfd);
	CCLOG("Set sockfd=0 in messageReceiver");
	*messageReceiverData->sockfd = 0;
	*/
	if(!isParent) {
		delete messageReceiverData->sockfd;
	}
	delete messageReceiverData;
		
	pthread_exit(0);
}
void Renderer::processRenderCommand(RenderCommand* command)
{
	auto commandType = command->getType();
	if (RenderCommand::Type::ARBITRARY_VERTEX_COMMAND == commandType) {
		// TODO use FastVector
		_batchedArbitaryCommands.push_back(command);
	}
	else if (RenderCommand::Type::MESH_COMMAND == commandType)
	{
		flush2D();
		auto cmd = static_cast<MeshCommand*>(command);

		if (cmd->isSkipBatching() || _lastBatchedMeshCommand == nullptr || _lastBatchedMeshCommand->getMaterialID() != cmd->getMaterialID())
		{
			flush3D();

			if (cmd->isSkipBatching())
			{
				// XXX: execute() will call bind() and unbind()
				// but unbind() shouldn't be call if the next command is a MESH_COMMAND with Material.
				// Once most of cocos2d-x moves to Pass/StateBlock, only bind() should be used.
				cmd->execute();
			}
			else
			{
				cmd->preBatchDraw();
				cmd->batchDraw();
				_lastBatchedMeshCommand = cmd;
			}
		}
		else
		{
			cmd->batchDraw();
		}
	}
	else if (RenderCommand::Type::CUSTOM_COMMAND == commandType)
	{
		flush();
		auto cmd = static_cast<CustomCommand*>(command);
		cmd->execute();
	}
	else if (RenderCommand::Type::BATCH_COMMAND == commandType)
	{
		flush();
		auto cmd = static_cast<BatchCommand*>(command);
		cmd->execute();
	}
	else if (RenderCommand::Type::PRIMITIVE_COMMAND == commandType)
	{
		flush();
		auto cmd = static_cast<PrimitiveCommand*>(command);
		cmd->execute();
	}
	else if ((RenderCommand::Type)QueueCommand::QUEUE_COMMAND == commandType)
	{
		flush();
		auto cmd = static_cast<QueueCommand*>(command);
		(this->*cmd->func)();
	}
	else
	{
		CCLOGERROR("Unknown commands in renderQueue");
	}
}
bool FileUtils::removeDirectory(const std::string& path)
{
    if (path.size() > 0 && path[path.size() - 1] != '/')
    {
        CCLOGERROR("Fail to remove directory, path must termniate with '/': %s", path.c_str());
        return false;
    }

    // Remove downloaded files

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
    std::wstring wpath = std::wstring(path.begin(), path.end());
    std::wstring files = wpath +  L"*.*";
    WIN32_FIND_DATA wfd;
    HANDLE  search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
    bool ret=true;
    if (search!=INVALID_HANDLE_VALUE)
    {
        BOOL find=true;
        while (find)
        {
            //. ..
            if(wfd.cFileName[0]!='.')
            {
                std::wstring temp = wpath + wfd.cFileName;
                if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                {
                    temp += '/';
                    ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end()));
                }
                else
                {
                    SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL);
                    ret = ret && DeleteFile(temp.c_str());
                }
            }
            find = FindNextFile(search, &wfd);
        }
        FindClose(search);
    }
    if (ret && RemoveDirectory(wpath.c_str()))
    {
        return true;
    }
    return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    std::string command = "cmd /c rd /s /q ";
    // Path may include space.
    command += "\"" + path + "\"";

    if (WinExec(command.c_str(), SW_HIDE) > 31)
        return true;
    else
        return false;
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
    if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
        return false;
    else
        return true;
#else
    std::string command = "rm -r ";
    // Path may include space.
    command += "\"" + path + "\"";
    if (system(command.c_str()) >= 0)
        return true;
    else
        return false;
#endif
}
Exemple #26
0
 void CCStoreUtils::logError(const char *tag, const char *message) {
     CCLOGERROR("%s %s", tag, message);
 }
Exemple #27
0
void Label::createSpriteForSystemFont()
{
    _currentLabelType = LabelType::STRING_TEXTURE;

    if (!_compatibleMode)
    {
        _fontDefinition._fontName = _systemFont;
        _fontDefinition._fontSize = _systemFontSize;

        _fontDefinition._alignment = _hAlignment;
        _fontDefinition._vertAlignment = _vAlignment;

        _fontDefinition._dimensions.width = _labelWidth;
        _fontDefinition._dimensions.height = _labelHeight;

        _fontDefinition._fontFillColor.r = _textColor.r;
        _fontDefinition._fontFillColor.g = _textColor.g;
        _fontDefinition._fontFillColor.b = _textColor.b;
        _fontDefinition._fontAlpha = _textColor.a;

        _fontDefinition._shadow._shadowEnabled = false;

        if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0)
        {
            _fontDefinition._stroke._strokeEnabled = true;
            _fontDefinition._stroke._strokeSize = _outlineSize;
            _fontDefinition._stroke._strokeColor.r = _effectColor.r;
            _fontDefinition._stroke._strokeColor.g = _effectColor.g;
            _fontDefinition._stroke._strokeColor.b = _effectColor.b;
            _fontDefinition._stroke._strokeAlpha = _effectColor.a;
        }
        else
        {
            _fontDefinition._stroke._strokeEnabled = false;
        }

#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
        if (_fontDefinition._stroke._strokeEnabled)
        {
            CCLOGERROR("Currently only supported on iOS and Android!");
        }
        _fontDefinition._stroke._strokeEnabled = false;
#endif
    }

    auto texture = new (std::nothrow) Texture2D;
    texture->initWithString(_originalUTF8String.c_str(), _fontDefinition);

    _textSprite = Sprite::createWithTexture(texture);
    //set camera mask using label's camera mask, because _textSprite may be null when setting camera mask to label
    _textSprite->setCameraMask(getCameraMask());
    _textSprite->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
    this->setContentSize(_textSprite->getContentSize());
    texture->release();
    if (_blendFuncDirty)
    {
        _textSprite->setBlendFunc(_blendFunc);
    }

    Node::addChild(_textSprite, 0, Node::INVALID_TAG);

    _textSprite->updateDisplayedColor(_displayedColor);
    _textSprite->updateDisplayedOpacity(_displayedOpacity);
}
bool VertexAttribBinding::init(MeshIndexData* meshIndexData, GLProgramState* glProgramState)
{
    CCASSERT(meshIndexData && glProgramState, "Invalid arguments");

    // One-time initialization.
    if (__maxVertexAttribs == 0)
    {
        GLint temp;
        glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &temp);

        __maxVertexAttribs = temp;
        if (__maxVertexAttribs <= 0)
        {
            CCLOGERROR("The maximum number of vertex attributes supported by OpenGL on the current device is 0 or less.");
            return false;
        }
    }

    _meshIndexData = meshIndexData;
    _meshIndexData->retain();
    _glProgramState = glProgramState;
    _glProgramState->retain();

    auto meshVertexData = meshIndexData->getMeshVertexData();
    auto attributeCount = meshVertexData->getMeshVertexAttribCount();


    // Parse and set attributes
    parseAttributes();
    long offset = 0;
    for (auto k = 0; k < attributeCount; k++)
    {
        auto meshattribute = meshVertexData->getMeshVertexAttrib(k);
        setVertexAttribPointer(
                               s_attributeNames[meshattribute.vertexAttrib],
                               meshattribute.size,
                               meshattribute.type,
                               GL_FALSE,
                               meshVertexData->getVertexBuffer()->getSizePerVertex(),
                               (GLvoid*)offset);
        offset += meshattribute.attribSizeBytes;
    }

    // VAO hardware
    if (Configuration::getInstance()->supportsShareableVAO())
    {
        glGenVertexArrays(1, &_handle);
        GL::bindVAO(_handle);
        glBindBuffer(GL_ARRAY_BUFFER, meshVertexData->getVertexBuffer()->getVBO());

        auto flags = _vertexAttribsFlags;
        for (int i = 0; flags > 0; i++) {
            int flag = 1 << i;
            if (flag & flags)
                glEnableVertexAttribArray(i);
            flags &= ~flag;
        }

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIndexData->getIndexBuffer()->getVBO());

        for(auto &attribute : _attributes)
        {
            attribute.second.apply();
        }

        GL::bindVAO(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }

    return true;
}
Exemple #29
0
//英雄显示位置
void BattleUI::CreateHeroEvent(int cfgId, int idx)
{

    auto layout_Bottom = m_RootWidget->getChildByName<Layout*>("Layout_Bottom");
    
    string btn_Name = StringUtils::format("Btn_Skill%d", idx);
    auto Btn_Hero = layout_Bottom->getChildByName<Button*>(btn_Name);
    Btn_Hero->setVisible(true);
    
    auto lbar_Name = StringUtils::format("LBar_State%d", idx);
    auto lbar_State = Btn_Hero->getChildByName<LoadingBar*>(lbar_Name);
    lbar_State->setPercent(100);
    
    CfgDataRow dataRow(cfgId);
    auto textName = StringUtils::format("Text_Name%d", idx);
    
    auto text_Name = Btn_Hero->getChildByName<Text*>(textName);
    
    auto skillId = dataRow.GetValue(CfgField::SkillID_V)->asValueVector().begin()->asInt();
    CfgDataRow skillDataRow(skillId);
    auto langId = skillDataRow.GetValue(CfgField::Name)->asInt();
    auto langText = MultiLanguage::getInstance()->GetText(langId);
    text_Name->setString(langText);
    
    auto attack_Speed = dataRow.GetValue(CfgField::Spd_F)->asFloat();
    attack_Speed = 10 / attack_Speed;
    
    Armature* armature = CreateHeroArmature(cfgId);
    
    string pbName = StringUtils::format("HeroSkillSchedule%d", idx);
    auto playName = skillDataRow.GetValue(CfgField::SkillAtksfxID_S)->asString();
    
    auto isGetKong = UserData::getInstance()->Check_VI_Fun(UserDataEnum::TalentList, Value((int)CfgIdEnum::TalentEliminateCD));
    auto progressBar = new ProgressBar();
    progressBar->SetScheduleName(pbName);
    progressBar->SetTotalTime(attack_Speed, isGetKong);
    progressBar->SetLoadingBar(lbar_State);
    
    m_VecProgressBar->push_back(progressBar);
    
    progressBar->SetCallBack([=]()
       {
           progressBar->Restart();
           if (armature->getAnimation()->getAnimationData()->getMovement(playName) == nullptr)
           {
               CCLOGERROR("Armature:%s, not %s", armature->getName().c_str(), playName.c_str());
           }else if(m_IsPlayAnim)
           {
               armature->setVisible(true);
               armature->getAnimation()->play(playName);
           }
           
           if (m_MonsterArmature != nullptr && m_IsPlayAnim)
           {
               m_MonsterArmature->getAnimation()->play(m_Beating);
           }
           
           auto attackResult = BattleData::getInstance()->HeroAttack(cfgId);
           if (attackResult == -1)
           {
               BattleFinish(true);

           }else if(attackResult > 0)
           {
               BufferEffect(attackResult);
           }

           if (!BattleData::getInstance()->m_HeroAutoAttack)
           {
               m_RootWidget->unschedule(pbName);
           }
       });
    
    Btn_Hero->addClickEventListener([this, progressBar, pbName](Ref* sender)
        {
            if(progressBar->GetRemainTime() == progressBar->GetTotalTime())
            {
                m_RootWidget->schedule([this, progressBar](float f)
                   {
                       progressBar->Update(f);
                       
                   }, pbName);
            }
        });
    
    m_RootWidget->schedule([this, progressBar](float f)
       {
           progressBar->Update(f);
           
       }, pbName);
    
    if (BattleData::getInstance()->m_HeroAutoAttack)
    {
        progressBar->Resume();
    }
    
    UIUtils::getInstance()->showProperImg(Btn_Hero, cfgId);
    
}
void GLViewImpl::onGLFWError(int errorID, const char* errorDesc)
{
    _glfwError = StringUtils::format("GLFWError #%d Happen, %s", errorID, errorDesc);
    CCLOGERROR("%s", _glfwError.c_str());
}