Search code examples
cocos2d-xcocos2d-x-3.0

Setting a custom shader messes up the scale and position of a Sprite


I am using a custom shader on cocos2dx 3.1 trying to accomplish an special effect on a sprite used as a background (has to cover the whole screen)

However If i do not use the shader, the sprite is perfectly scaled and positioned, but when i do use it its show way smaller and on the bottom left.

Here is how i load the sprite

this->background_image = Sprite::create(image_name->GetText());

// Add background shader

if (this->background_image)
{
    const GLchar *shaderSource = (const GLchar*) CCString::createWithContentsOfFile("OverlayShader.fsh")->getCString();

    GLProgram * p = new GLProgram();
    p->initWithByteArrays(ccPositionTextureA8Color_vert, shaderSource);
    p->link();
    p->updateUniforms();
    this->background_image->setGLProgram(p);
}

// Classroom will be streched to cover all of the game screen
Size bgImgSize = this->background_image->getContentSize();
Size windowSize = Director::getInstance()->getWinSize();

float xScaleFactor = windowSize.width/bgImgSize.width;
float yScaleFactor = (windowSize.height-MARGIN_SPACE+10)/bgImgSize.height;

this->background_image->setScale(xScaleFactor, yScaleFactor);

this->background_image->setPosition(Vec2(windowSize.width/2.0f,windowSize.height/2.0f + ((MARGIN_SPACE-10)/2.0)));

this->background_image->retain();

And this is the shader im trying to use (a simple one, once this works ill change it to a photoshop-overlay style one)

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;

void main()
{
    vec4 v_orColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);
    float gray = dot(v_orColor.rgb, vec3(0.299, 0.587, 0.114));
    gl_FragColor = vec4(gray, gray, gray, v_orColor.a);
}   

My question is, what am i doing wrong? The first thing that comes to my mind is that the attribute pointers used on the vertex shader are not correct, but now i am using the default vertex shader.


Solution

  • I found the solution on another post, so i'll just quote it and link to that post:

    Found the solution. The vert shader should not use the MVP matrix so I loaded ccPositionTextureColor_noMVP_vert instead of ccPositionTextureA8Color_vert.

    Weird y-position offset using custom frag shader (Cocos2d-x)