Reputation: 32861
I am trying to draw a texture to both sides of a triangle in Android. I have the below code
float textureCoordinates[] = { 0.0f, 0.0f, //
0.0f, 1.0f, //
1.0f, 0.0f
};
short[] indices = new short[] { 0, 1, 2 };
float[] vertices = new float[] { -0.5f, 0.5f, 0.0f, // p0
-0.5f, -0.5f, 0.0f, // p1
0.5f, 0.5f, 0.0f, // p2
};
Now with this i am able to get the triangle with the texture. But when i rotate it along the y axis after a 180 degree rotation i see the same image on the other side of the triangle. I would like to change the texture of the triangle on the other side. Please let me know how to do it.
Upvotes: 3
Views: 2428
Reputation: 45948
This is not achievable with just a single function call. When using fragment shaders (ES 2) you may query the builtin fragment shader input variable gl_FrontFacing
to determine if the current fragment belongs to the front or the back of its triangle. So you would write something like this:
uniform sampler2D frontTexture;
uniform sampler2D backTexture;
varying vec2 texCoord;
void main()
{
if(gl_FrontFacing)
gl_FragColor = texture2D(frontTexture, texCoord);
else
gl_FragColor = texture2D(backTexture, texCoord);
}
When using the fixed function pipeline (ES 1) you won't get around rendering two versions of your object, one with the front texture and the other with the back texture. You can facilitate culling to prevent depth-fighting problems. So it would be something like this:
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK); //render only front faces
glBindTexture(GL_TEXTURE_2D, frontTexture);
<draw object>
glCullFace(GL_FRONT); //render only back faces
glBindTexture(GL_TEXTURE_2D, backTexture);
<draw object>
As I'm not sure how well modern ES devices handle branching in the shader (although in this case all fragments should take the same path), it may be, that the second approach together with a simple one-texture fragment shader might also be the preferred solution for ES 2, performance-wise.
Upvotes: 3