示例#1
0
void MeshCommand::buildVAO()
{
    // FIXME: Assumes that all the passes in the Material share the same Vertex Attribs
    GLProgramState* programState = (_material != nullptr)
                                   ? _material->_currentTechnique->_passes.at(0)->getGLProgramState()
                                   : _glProgramState;

    releaseVAO();
    glGenVertexArrays(1, &_vao);
    GL::bindVAO(_vao);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
    auto flags = programState->getVertexAttribsFlags();
    for (int i = 0; flags > 0; i++) {
        int flag = 1 << i;
        if (flag & flags)
            glEnableVertexAttribArray(i);
        flags &= ~flag;
    }
    programState->applyAttributes(false);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);

    GL::bindVAO(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
示例#2
0
void ShaderBrush::loadShaderVertex(const std::string &vert, const std::string &frag)
{
	auto fileUtiles = FileUtils::getInstance();

	// frag
	auto fragmentFilePath = fileUtiles->fullPathForFilename(frag);
	auto fragSource = fileUtiles->getStringFromFile(fragmentFilePath);

	// vert
	std::string vertSource;
	if (vert.empty()) {
		//vertSource = ccPositionTextureColor_vert;
		vertSource = ccPositionTextureColor_noMVP_vert;
	}
	else {
		std::string vertexFilePath = fileUtiles->fullPathForFilename(vert);
		vertSource = fileUtiles->getStringFromFile(vertexFilePath);
	}

	auto glprogram = GLProgram::createWithByteArrays(vertSource.c_str(), fragSource.c_str());
	auto glprogramstate = GLProgramState::getOrCreateWithGLProgram(glprogram);
	
	// brush
	_brush = Sprite::create(NAME_BRUSH);
	_brush->retain();
	_blend = { GL_ONE, GL_ZERO };
	//_blend = BlendFunc{ GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA };
	_brush->setBlendFunc(_blend); 
	_brush->setGLProgramState(glprogramstate);

	auto s = Director::getInstance()->getVisibleSize();
	GLProgramState* pGLPS = _brush->getGLProgramState();
	pGLPS->setUniformVec2("resolution", Vec2(s)); 
}
void ExampleBase::refreshShader()
{
    if(_currentIndex < 0 || _currentIndex >= _examples.size()) {
        return;
    }

    _exampleSprite->setTexture("res/Logo-hd.png");

    auto shaderInfo = _examples.at(_currentIndex);

    auto vertFilename = std::string("res/shaders/").append(shaderInfo.name).append(".vsh");
    auto fragFilename = std::string("res/shaders/").append(shaderInfo.name).append(".fsh");

    CCLOG("refresh shader with files: %s, %s", vertFilename.c_str(), fragFilename.c_str());

    // Load the fragment shader in the file name E01_SimplestShader.fsh.
    // Also loads E01_SimplestShader.vsh as the vertex shader if it exists.
    auto glprogram = GLProgram::createWithFilenames(vertFilename, fragFilename);
    GLProgramState* glprogramstate = GLProgramState::getOrCreateWithGLProgram(glprogram);

    auto winsize = Director::getInstance()->getWinSizeInPixels();
    glprogramstate->setUniformVec2("cc_ViewSizeInPixels", winsize);

    if(! shaderInfo.texture2.empty()) {
        // add extra texture
        auto textureCache = Director::getInstance()->getTextureCache();
        auto tex1 = textureCache->getTextureForKey(shaderInfo.texture1);
        if(! tex1) {
            tex1 = textureCache->addImage(shaderInfo.texture1);
        }
        if(tex1) {
            // TODO: should store in shaderinfo
            _exampleSprite->setTexture("res/Rocks-hd.png");
            glprogramstate->setUniformTexture("u_CausticTexture", tex1);
        }

        // 2nd Extra Texture
        auto tex2 = textureCache->getTextureForKey(shaderInfo.texture2);
        if(! tex2) {
            tex2 = textureCache->addImage(shaderInfo.texture2);
        }
        if(tex2) {
            Texture2D::TexParams texParams = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT};
            tex2->setTexParameters(texParams);

            auto locid = glprogram->getUniformLocationForName("uNoiseTextureSize");
            glprogram->setUniformLocationWith2f(locid, 30, 30);
            glprogramstate->setUniformVec2("u_NoiseTextureSize", tex2->getContentSizeInPixels());
            glprogramstate->setUniformTexture("u_NoiseTexture", tex2);
        }

    }

    // attach the ProgramState to a Node
    _exampleSprite->setGLProgram(glprogram);
}
示例#4
0
GLProgramState* GLProgramState::create(GLProgram *glprogram)
{
    GLProgramState* ret = new (std::nothrow) GLProgramState();
    if(ret && ret->init(glprogram))
    {
        ret->autorelease();
        return ret;
    }
    CC_SAFE_DELETE(ret);
    return nullptr;
}
GLProgram* TextureBlur::getBlurShader(Vec2 pixelSize, Vec2 direction, const int radius, float* weights)
{
	std::string blurShaderPath = FileUtils::getInstance()->fullPathForFilename("Shaders/TextureBlur.fsh");
	const GLchar* blur_frag = String::createWithContentsOfFile(blurShaderPath.c_str())->getCString();

	GLProgram* blur = GLProgram::createWithByteArrays(ccPositionTextureColor_vert, blur_frag);
	
	GLProgramState* state = GLProgramState::getOrCreateWithGLProgram(blur);
	state->setUniformVec2("pixelSize", pixelSize);
	state->setUniformVec2("direction", direction);
	state->setUniformInt("radius", radius);
	state->setUniformFloatv("weights", radius, weights);

    return blur;
}
示例#6
0
// 全屏实时模糊,上真机效率很差,iPad mini1只能15帧左右。本例仅为演示用法
void P001::testShader()
{
    // --- Blur
    m_render = RenderTexture::create(m_visibleSize.width, m_visibleSize.height);
    m_render->setPosition(SCREEN_CENTER);
    m_render->clear(0, 0, 0, 0);
    
    m_render->getSprite()->setGLProgram(WJSpriteShaderBlurQuick::getShader());
    GLProgramState* glState = m_render->getSprite()->getGLProgramState();
    
    Size size = m_render->getSprite()->getTexture()->getContentSizeInPixels();
    size.width = 1.0f / size.width;
    size.height = 1.0f / size.height;
    glState->setUniformVec2("resolution", size);
    
    m_render->getSprite()->getTexture()->setAntiAliasTexParameters();
    
    this->addChild(m_render, m_sceneJson->getLocalZOrder());
    
    BlendFunc bf = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA};
    m_render->getSprite()->setBlendFunc(bf);
    m_render->getSprite()->runAction(RepeatForever::create(
                                        Sequence::create(
                                            DelayTime::create(2.0f),
                                            FadeOut::create(1.0f),
                                            DelayTime::create(1.0f),
                                            FadeIn::create(1.0f),
                                            NULL)));
    
    //m_sceneJson->setVisible(false);
    
    // --- Gray
    WJButton* btnStart = m_sceneJson->getSubButtonByKey("start");
    //btnStart->setGLProgram(WJSpriteShaderGray::getShader());  // 因为现在WJButton支持九宫格功能,对它设置Shader会无效
    btnStart->runAction(RepeatForever::create(
                                              Sequence::create(
                                                   DelayTime::create(2.0f),
                                                   CallFunc::create([=]()
                                                   {
													   btnStart->setGrayEnabled(true);
                                                   }),
                                                   DelayTime::create(2.0f),
                                                   CallFunc::create([=]()
                                                   {
													   btnStart->setGrayEnabled(false);
                                                   }),
                                                   NULL)));
}
示例#7
0
// on "init" you need to initialize your instance
bool Lession25::init()
{
    if ( !Layer::init() )
    {
        return false;
    }

	auto winSize = Director::getInstance()->getWinSize();
	FileUtils::getInstance()->addSearchPath(FileUtils::getInstance()->getSearchPaths().at(0) + "Lession25/");

	////µÃµ½ÆÁÄ»³ß´ç
	auto s = Director::getInstance()->getWinSize();
	//´´½¨3DÉãÏñ»ú
	auto _camera = cocos2d::Camera::createPerspective(60, (GLfloat)s.width / s.height, 1, 1000);
	//ÉèÖÃÉãÏñ»úÑÛ¾¦Î»ÖÃ
	_camera->setPosition3D(Vec3(0, 200, 200));
	//ÉèÖÃÉãÏñ»ú¹Û²ìµãλÖÃ
	_camera->lookAt(Vec3(0, 0, 0));
	_camera->setCameraFlag(CameraFlag::USER1);
	addChild(_camera);

	//´´½¨¾²Ì¬Ä£ÐÍ
	auto spriteStatic3D = Sprite3D::create("water.c3t");
	_sprite3D = spriteStatic3D;
	spriteStatic3D->setCameraMask(2);
	spriteStatic3D->setScale(2);
	spriteStatic3D->setPosition3D(Vec3(0, 0, 0));
	spriteStatic3D->setRotation3D(Vec3(-90, 0, 0));
	addChild(spriteStatic3D);

	GLProgramState* state = GLProgramState::create(GLProgram::createWithFilenames("Lession25.vert", "Lession25.frag"));
	state->applyUniforms();
	spriteStatic3D->setGLProgramState(state);

    return true;

}
示例#8
0
void FSprite::InitShader(const std::string& alpha_file)
{
#ifdef ETC1
    //Shader
    GLProgram* glp = new GLProgram();
    glp->autorelease();
    
    glp->initWithFilenames("testv.vsh", "test.fsh");
    glp->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
    glp->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);
    glp->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD);
    glp->link();
    glp->updateUniforms();
    
    opacity_location_ = glGetUniformLocation(glp->getProgram(), "u_opacity");
    
    current_alpha_file_ = alpha_file;
    
//  #pragma message WARN("getTextureForKey or someth else, texture should be added on loading scene, do not add (cocos should check that anyway but still dont do it)  all the time!!")
    Texture2D* tex = Director::getInstance()->getTextureCache()->addImage(alpha_file);
	setBlendFunc(BlendFunc({ GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }));
    //setBlendFunc((BlendFunc) { GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA });
    
    GLProgramState* glprogramstate = GLProgramState::getOrCreateWithGLProgram(glp);
    
    setGLProgramState(glprogramstate);
    
    glprogramstate->setUniformFloat(opacity_location_, (float)getOpacity()/255.0);
    
    glprogramstate->setUniformTexture("u_texture1", tex);
    

    
    setGLProgram(glp);
#endif
}
示例#9
0
void MeshCommand::preBatchDraw()
{
    // Do nothing if using material since each pass needs to bind its own VAO
    if (!_material)
    {
        if (Configuration::getInstance()->supportsShareableVAO() && _vao == 0)
            buildVAO();
        if (_vao)
        {
            GL::bindVAO(_vao);
        }
        else
        {
            glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);

            // FIXME: Assumes that all the passes in the Material share the same Vertex Attribs
            GLProgramState* programState = _material
                                           ? _material->_currentTechnique->_passes.at(0)->getGLProgramState()
                                           : _glProgramState;
            programState->applyAttributes();
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);
        }
    }
}
示例#10
0
void ShaderBrush::movePaint(Sprite *pTarget, RenderTexture *pCanvas, Point worldPos)
{
	Point localPos = pCanvas->getSprite()->convertToNodeSpace(worldPos);
	localPos.y = pCanvas->getContentSize().height - localPos.y;

	GLProgramState* pGLPS = _brush->getGLProgramState();
	_brush->setPosition(worldPos);
	CCLOG("movePaint worldPos%f %f", worldPos.x, worldPos.y);

	// set brush texture
	GL::bindTexture2DN(0, _brush->getTexture()->getName());
	pGLPS->setUniformTexture("u_brushTexture", _brush->getTexture()->getName());
	pGLPS->setUniformFloat("u_brushOpacity", ((float)_brush->getOpacity()) / 255);
	pGLPS->setUniformVec2("u_brushSize", Vec2(_brush->getContentSize()));

	// set target glstate && texture coord
	GL::bindTexture2DN(1, pTarget->getTexture()->getName());
	pGLPS->setUniformTexture("u_targetTexture", pTarget->getTexture()->getName());
	float lX = (localPos.x - _brush->getContentSize().width / 2.0) / pTarget->getContentSize().width;
	float lY = (localPos.y - _brush->getContentSize().height / 2.0) / pTarget->getContentSize().height;
	pGLPS->setUniformVec2("v_targetCoord", Vec2(lX, lY));
	pGLPS->setUniformVec2("u_targetSize", Vec2(pTarget->getContentSize()));

	// set canvas glstate
	//static CCTexture2D *pCanvasTex = NULL;
	//if (pCanvasTex) {
	//	delete pCanvasTex;
	//	pCanvasTex = new Texture2D();
	//}
	//Image *img = pCanvas->newImage();
	//pCanvasTex->initWithImage(img);
	//delete img;
	//GL::bindTexture2DN(2, pCanvasTex->getName());
	//_brush->getGLProgramState()->setUniformTexture("u_canvasTexture", pCanvasTex->getName());

	// draw
	pCanvas->begin();
	_brush->visit();
	//CCLOG("brush pos:%f %f", _brush->getPosition().x, _brush->getPosition().y);
	//CCLOG("canvase pos%f %f", pCanvas->getPosition().x, pCanvas->getPosition().y);
	pCanvas->end();
}
示例#11
0
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();



    auto center = Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y);

    auto bg = Sprite::create("bg.png");
    bg->setPosition(center);
    auto bgsize = bg->getContentSize();
    float scaleX = visibleSize.width / bgsize.width;
    float scaleY = visibleSize.height / bgsize.height;
    bg->setScaleX(scaleX);
    bg->setScaleY(scaleY);
    addChild(bg);

    auto grass = Sprite::create("grass.png");
    grass->setAnchorPoint(ccp(0.5, 0.5));
    grass->setPosition(center);
    addChild(grass);

    Texture2D::TexParams p;
    p.minFilter = GL_LINEAR;
    p.magFilter = GL_LINEAR;
    p.wrapS = GL_REPEAT;
    p.wrapT = GL_REPEAT;

    glActiveTexture(GL_TEXTURE0);

    auto textureCache = Director::getInstance()->getTextureCache();
    auto tex1 = textureCache->addImage("grass.png");
    //tex1->setTexParameters(p);

    GLProgram* prog = new GLProgram();
    prog->initWithFilenames("perlin_wind.vert", "perlin_wind.frag");
    prog->retain();
    prog->link();
    prog->use();
    prog->updateUniforms();


    float gtime = Director::getInstance()->getDeltaTime();
    float ctime = Director::getInstance()->getTotalFrames() * Director::getInstance()->getAnimationInterval();

    //CCLog("Wind is %f", pnoise);

    ShaderCache::getInstance()->addGLProgram(prog, "perlin_wind");

    grass->setGLProgram(prog);

    GLProgramState* state = GLProgramState::getOrCreateWithGLProgram(prog);

    //state->setUniformFloat("u_gtime", 1.0f);
    //state->setUniformFloat("u_ctime",0.5f);
    //state->setUniformFloat("u_color", m_cloudAmount);
    state->setUniformFloat("u_wind", 0);
    schedule(schedule_selector(HelloWorld::setWind));
    prog->release();

    schedule(schedule_selector(HelloWorld::setWind));
    return true;


}
示例#12
0
uint32_t GAFMovieClip::setUniforms()
{
#if GAF_ENABLE_NEW_UNIFORM_SETTER
#define getUniformId(x) GAFShaderManager::getUniformLocation(x)
#else
#define getUniformId(x) GAFShaderManager::getUniformName(x)
#endif

#if CHECK_CTX_IDENTITY
    const bool ctx = hasCtx();
#else
    const bool ctx = false;
#endif


    GLProgramState* state = getGLProgramState();

    GAFMovieClipHash hash;
    memset(&hash, 0, sizeof(GAFMovieClipHash));

    hash.program = getGLProgram()->getProgram();
    hash.texture = _texture->getName();
    hash.blend = _blendFunc;


    if (!ctx)
    {
        Color4F color(m_colorTransformMult.x, m_colorTransformMult.y, m_colorTransformMult.z, m_colorTransformMult.w);
        setColor(Color3B(color));
        setOpacity(static_cast<GLubyte>(color.a * 255.0f));
    }
    else
    {
        {
            hash.a = m_colorTransformMult;
            hash.b = m_colorTransformOffsets;
            state->setUniformVec4(
                getUniformId(GAFShaderManager::EUniforms::ColorTransformMult),
                m_colorTransformMult);
            state->setUniformVec4(
                getUniformId(GAFShaderManager::EUniforms::ColorTransformOffset),
                m_colorTransformOffsets);
        }

        if (!m_colorMatrixFilterData)
        {
            hash.d = cocos2d::Mat4::IDENTITY;
            hash.e = cocos2d::Vec4::ZERO;
            state->setUniformMat4(
                getUniformId(GAFShaderManager::EUniforms::ColorMatrixBody),
                cocos2d::Mat4::IDENTITY);
            state->setUniformVec4(
                getUniformId(GAFShaderManager::EUniforms::ColorMatrixAppendix),
                cocos2d::Vec4::ZERO);
        }
        else
        {
            hash.d = Mat4(m_colorMatrixFilterData->matrix);
            hash.e = Vec4(m_colorMatrixFilterData->matrix2);
            state->setUniformMat4(
                getUniformId(GAFShaderManager::EUniforms::ColorMatrixBody),
                Mat4(m_colorMatrixFilterData->matrix));
            state->setUniformVec4(
                getUniformId(GAFShaderManager::EUniforms::ColorMatrixAppendix),
                Vec4(m_colorMatrixFilterData->matrix2));
        }
    }
    return XXH32((void*)&hash, sizeof(GAFMovieClipHash), 0);
}