How to pass texture to GLSL in cocos

Hey I want to know how to pass another texture to GLSL?

right know i’m using the following code to use a shader on a sprite where it seems, cocos automatically passes the sprite’s texture to glsl which can be called with CC_Texture0?
But how do i pass another texture?

 GLProgram* glp = new GLProgram();

glp->initWithVertexShaderFilename("../../testv.vsh", "../../test.fsh");
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD);
glp->link();
glp->updateUniforms();

sprite_->setShaderProgram(glp);

vertex shader:

attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;
					

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
								
void main()	
{							
    gl_Position = CC_MVPMatrix * a_position;
	v_fragmentColor = a_color;
	v_texCoord = a_texCoord;
}

fragment shader:

varying vec4 v_fragmentColor;	
varying vec2 v_texCoord;

void main()			
{
    vec3 pixel = texture2D(CC_Texture0, v_texCoord).rgb;

	gl_FragColor = vec4(pixel,0.1);
}	

can anyone help me?

You can use GL::bindTexture2DN(1, my_Texture2D) and reference/use it in your shader with CC_Texture1. If you need a second a_texCoord1 that is different for each vertex you’ll have to create an additional VertexBuffer stream and pass it through a varying like v_texCoord. If not you can use some other method for generating a texture coord.

See CCFastTMXTileLayer.cpp if you’re unsure how that works.

Texture2D* tex = Director::getInstance()->getTextureCache()->addImage("filename");

GL::bindTexture2DN(1, tex->getName());
    
GLuint t1Location = glGetUniformLocation(glp->getProgram(), "tex1");

glp->setUniformLocationWith1i(t1Location, 1);

this seems to work

1 Like

Glad you got it working. I’ll remember to use your more common use case in answering similar questions.

Defining your own uniform name is probably more common and better for when you are using a texture and sampling it using a uv coord not based on an additional vertex attribute, for example when using a Normal or Noise map texture.

:smiley: it doesn’t work.
It only takes the alpha texture from the first texture, for all my sprites
but i think i found the solution