I need to render to a texture from an Android plugin written in Java, using OpenGL ES20.
I have set up an FBO and provided my Unity script with its textureID, then I can set up the corresponding Unity texture using
IntPtr texturePointer = (IntPtr)textureID;
Texture2D texture=Texture2D.CreateExternalTexture(width,height,TextureFormat.RGBA32,false,false,texturePointer);
I can now successfully clear the Unity texture to different colors in the plugin with
GLES20.glClearColor(0.0f, 1.0, 0.0f, 1.0f);
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
However, when I try to do pretty much anything else, like simply draw a textured quad, I get some strange and random results that looks different every time I restart the app. It seems like the OpenGL state at the time when the plugin is called is pretty much random, and I do not know what to do to reset it to a state where my code will produce the desired output.
This is the plugins render loop code:
public void render()
{
GLES20.glViewport(0, 0, fbo.width, fbo.height);
GLES20.glUseProgram(program);
GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
Matrix.setIdentityM(mtrxMVP, 0);
GLES20.glUniformMatrix4fv(u_MVPMatrix, 1, false, mtrxMVP, 0);
GLES20.glVertexAttribPointer(a_Position, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer);
GLES20.glEnableVertexAttribArray(a_Position);
GLES20.glVertexAttribPointer(a_texCoord, 2, GLES20.GL_FLOAT, false, 0, uvBuffer);
GLES20.glEnableVertexAttribArray(a_texCoord);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, testimageID);
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, indices.length/2, GLES20.GL_UNSIGNED_SHORT, indicesBuffer);
GLES20.glFinish();
}
My vertex/fragment shaders:
//VERTEX SHADER
uniform mat4 u_MVPMatrix;
attribute vec4 a_Position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main() {
gl_Position = u_MVPMatrix * a_Position;
v_texCoord = a_texCoord;
}
//FRAGMENT SHADER
precision mediump float;
uniform sampler2D u_texture;
varying vec2 v_texCoord;
void main() {
gl_FragColor = texture2D(u_texture, v_texCoord);
//gl_FragColor = texture2D(u_texture, vec2(-gl_FragCoord.x,gl_FragCoord.y)/256.0);
//gl_FragColor = vec4(gl_FragCoord.x/40.0,1.0,0.0,1.0);
}
It is all pretty much basic stuff for rendering a textured quad. I have been working for two days now to figure this out, and would be grateful if anyone could provide some insight. Or a working sample showing how to render a textured quad to an Unity texture from an Android plugin.