I'm trying to create 3D scene. There is textured Earth with clouds. I think that clouds I will be able to create by transparent sphere and texture of clouds on it(if I'm wrong please correct me). So I have some code below:
ShaderProgram shader;
Mesh mesh, cloudMesh;
Texture texture, cloudTexture;
Matrix4 matrix = new Matrix4();
public void create() {
String vertexShader = "attribute vec4 a_position; \n"
+ "attribute vec4 a_color;\n"
+ "attribute vec2 a_texCoords;\n"
+ "uniform mat4 u_worldView;\n"
+ "varying vec4 v_color;"
+ "varying vec2 v_texCoords;"
+ "void main() \n"
+ "{ \n"
+ " v_color = vec4(1, 1, 1, 1); \n"
+ " v_texCoords = a_texCoords; \n"
+ " gl_Position = u_worldView * a_position; \n"
+ "} \n";
String fragmentShader = "#ifdef GL_ES\n"
+ "precision mediump float;\n"
+ "#endif\n"
+ "varying vec4 v_color;\n"
+ "varying vec2 v_texCoords;\n"
+ "uniform sampler2D u_texture;\n"
+ "void main() \n"
+ "{ \n"
+ " gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n"
+ "}";
shader = new ShaderProgram(vertexShader, fragmentShader);
if (shader.isCompiled() == false) {
System.exit(0);
}
mesh = ObjLoader.loadObj(Gdx.files.internal("objects/earth.obj").read());
cloudMesh = ObjLoader.loadObj(Gdx.files.internal("objects/cloud_sphere.obj").read());
texture = new Texture(Gdx.files.internal("images/earthmap.jpg"));
cloudTexture = new Texture(Gdx.files.internal("images/earth_clouds_map.jpg"));
}
public void render() {
angle += Gdx.graphics.getDeltaTime() * 30;
matrix.setToRotation(axis, angle);
Gdx.graphics.getGL20().glViewport(-10, 10, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
Gdx.graphics.getGL20().glClearColor(0.2f, 0.2f, 0.2f, 1);
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.graphics.getGL20().glEnable(GL20.GL_TEXTURE_2D);
Gdx.graphics.getGL20().glEnable(GL20.GL_BLEND);
Gdx.graphics.getGL20().glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
texture.bind();
shader.begin();
shader.setUniformMatrix("u_worldView", matrix);
shader.setUniformi("u_texture", 0);
mesh.render(shader, GL20.GL_TRIANGLE_STRIP);
shader.end();
//SHOULD I USE SHADER PROGRAM LIKE BELOW?
cloudTexture .bind();
shader.begin();
shader.setUniformMatrix("u_worldView", matrix);
shader.setUniformi("u_texture", 0);
cloudMesh.render(shader, GL20.GL_TRIANGLE_STRIP);
shader.end();
}
So I don't see any textures on spheres. Where is mistake? If someone have any ideas, links or examples it will be appreciated!
Before loading your textures you have to define a "slot" where your texture will be stored:
Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
texture = new Texture(Gdx.files.internal("images/earthmap.jpg"));
texture.bind();
Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE1);
cloudTexture = new Texture(Gdx.files.internal("images/earth_clouds_map.jpg"));
cloudTexture.bind();
in your render-method you then bind the texture and assign it to the shader using these "slots"
shader.setUniformi("u_texture", 0);
...
...
shader.setUniformi("u_texture", 1);
that should be all...
Related
This is my VertexShader:
public static final String vs_Face =
"uniform mat4 transMatrix;" +
"uniform mat4 scaleMatrix;" +
"uniform mat4 rotateZMatrix;" +
"attribute vec4 vPosition;" +
"attribute vec2 a_texCoord;" +
"varying vec2 v_texCoord;" +
"void main() {" +
" gl_Position = transMatrix * rotateZMatrix *scaleMatrix * vec4(vPosition.xyz,1.0) ;" +
" v_texCoord = a_texCoord.xy;" +
"}";
This my FragmentShader:
public static final String fs_Face =
"precision mediump float;" +
"varying vec2 v_texCoord;" +
"uniform sampler2D s_texture;" +
"void main() {" +
" gl_FragColor = texture2D( s_texture, v_texCoord );" +
"}";
This is my Draw function
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_ONE,GLES20.GL_ONE_MINUS_SRC_ALPHA);
//
GLES20.glUseProgram(mProgramMagic);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, mGLCubeId[0]);
GLES20.glEnableVertexAttribArray(mPositionHandleFace);
GLES20.glVertexAttribPointer(mPositionHandleFace, 2, GLES20.GL_FLOAT, false, 0, 0);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, mMagicTextureCoordinateId[0]);
GLES20.glEnableVertexAttribArray ( mTexCoordLocFace );
GLES20.glVertexAttribPointer(mTexCoordLocFace, 2, GLES20.GL_FLOAT, false, 4 * 2, 0);
//control matrix
GLES20.glUniformMatrix4fv(mTransHandle,1,false,transMatrix,0);
GLES20.glUniformMatrix4fv(mScaleHandle,1,false,scaleMatrix,0);
GLES20.glUniformMatrix4fv(mMvpMatrixHandle,1,false,mvpMatrix,0);
GLES20.glUniformMatrix4fv(mRotateZHandle,1,false,rotateZMatrix,0);
GLES20.glUniformMatrix4fv(mTransZeroMatrixHandle, 1, false, mTransZeroMatrix, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,mTextures[0]);
if(i>=mTotalCount)
{
i=i-mTotalCount;
}
// update texture
if(mPathList.size()-1>=i&&mTextureMap.containsKey(mPathList.get(i)))
{
GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D,0,0,0,mTextureMap.get(mPathList.get(i)));
}
GLES20.glUniform1i ( mSamplerLocFace, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandleFace);
GLES20.glDisableVertexAttribArray(mTexCoordLocFace);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0);
If I dont add the rotateZ matrix like this: gl_Position =vec4(vPosition.xyz,1.0) ,the texture can display properly. but after i add the rotateZMatrix,its shape will change.
This is the picture after i rotate 45 degrees,the rabbit ears and noise is the texture:
Picture
I don't know what i did wrong,I have tried multiple variations of this, but none of them seem to work.
I'm having mpvMatrix (mvpMatrix is calculated as model * view * projection using Matrix.multiply()) and passing it to shader and it's ok.
Now i'd like to move multiplication from CPU to GPU (from Matrix.multiply to shader).
If i'm trying to pass model, view and projection martrix separately and multiply them in shader i see nothing.
I'm sure matrix are not null and have real values (as if i multiply them on CPU instead of GPU it's ok), matrix uniform index are >= 0 (they are found in shader). What can be wrong?
Shaders:
private final String vertexShader =
"uniform mat4 u_mMatrix; \n" // Матрица модели
+ "uniform mat4 u_vMatrix; \n" // Матрица модели
+ "uniform mat4 u_pMatrix; \n" // Матрица модели
+ "attribute vec4 a_Position; \n" // Информация о положении вершин.
+ "attribute vec2 a_TexCoordinate; \n" // Per-vertex texture coordinate information we will pass in.
+ "varying vec2 v_TexCoordinate; \n" // This will be passed into the fragment shader.
+ "void main() \n" // Начало программы вершинного шейдера.
+ "{ \n"
+ " v_TexCoordinate = a_TexCoordinate; \n"
+ " mat4 mvMatrix = u_mMatrix * u_vMatrix;"
+ " mat4 mvpMatrix = mvMatrix * u_pMatrix;"
+ " gl_Position = mvpMatrix \n" // gl_Position специальные переменные используемые для хранения конечного положения.
+ " * a_Position; \n" // Умножаем вершины на матрицу для получения конечного положения
+ "} \n"; // в нормированных координатах экрана.
private final String fragmentShader =
"precision mediump float; \n" // Устанавливаем по умолчанию среднюю точность для переменных. Максимальная точность в фрагментном шейдере не нужна.
+ "uniform sampler2D u_Texture; \n" // The input texture.
+ "varying vec2 v_TexCoordinate; \n" // Interpolated texture coordinate per fragment.
+ "void main() \n" // Точка входа для фрагментного шейдера.
+ "{ \n"
+ " gl_FragColor = texture2D(u_Texture, v_TexCoordinate); \n" // Передаем значения цветов.
+ "}";
Binding:
mMatrixHandle = GLES20.glGetUniformLocation(programHandle, "u_mMatrix"); // = 0
vMatrixHandle = GLES20.glGetUniformLocation(programHandle, "u_vMatrix"); // = 2
pMatrixHandle = GLES20.glGetUniformLocation(programHandle, "u_pMatrix"); // = 3
Drawing:
GLES20.glUniformMatrix4fv(mMatrixHandle, 1, false, modelMatrix, 0);
GLES20.glUniformMatrix4fv(vMatrixHandle, 1, false, viewMatrix, 0);
GLES20.glUniformMatrix4fv(pMatrixHandle, 1, false, projectionMatrix, 0);
Actually my matrix multiplication order in shader was wrong, the correct order is:
gl_Position = u_pMatrix * u_mMatrix * u_vMatrix * a_Position;
so the correct shader source is:
private final String vertexShader =
"uniform mat4 u_mMatrix; \n" // Матрица модели
+ "uniform mat4 u_vMatrix; \n" // Матрица модели
+ "uniform mat4 u_pMatrix; \n" // Матрица модели
+ "attribute vec4 a_Position; \n" // Информация о положении вершин.
+ "attribute vec2 a_TexCoordinate; \n" // Per-vertex texture coordinate information we will pass in.
+ "varying vec2 v_TexCoordinate; \n" // This will be passed into the fragment shader.
+ "void main() \n" // Начало программы вершинного шейдера.
+ "{ \n"
+ " v_TexCoordinate = a_TexCoordinate; \n"
+ " gl_Position = u_pMatrix * u_mMatrix * u_vMatrix \n" // gl_Position специальные переменные используемые для хранения конечного положения.
+ " * a_Position; \n" // Умножаем вершины на матрицу для получения конечного положения
+ "} \n"; // в нормированных координатах экрана.
How can I pass a float value to fragment shader ?
This is my code on android:
int aUseTexture = GLES20.glGetAttribLocation(program, "uUseTexture");
GLES20.glUniform1f(aUseTexture, 1.0f);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
Here is my shader:
String verticesShader =
"uniform mat4 uScreen;\n" +
"attribute vec2 aPosition;\n" +
"attribute vec3 aColor;\n" +
"attribute vec2 aTexPos; \n" +
"varying vec2 vTexPos; \n" +
"varying vec3 vColor;\n" +
"void main() {\n" +
" vTexPos = aTexPos; \n" +
" gl_Position = uScreen * vec4(aPosition.xy, 0.0, 1.0);\n" +
" vColor = aColor;\n" +
"}";
// Our fragment shader. Just return vColor.
// If you look at this source and just said 'WTF?', remember
// that all the attributes are defined in the VERTEX shader and
// all the 'varying' vars are considered OUTPUT of vertex shader
// and INPUT of the fragment shader. Here we just use the color
// we received and add a alpha value of 1.
String fragmentShader =
"uniform float uUseTexture; \n" +
"uniform sampler2D uTexture;\n" +
"precision mediump float;\n"+
"varying vec2 vTexPos; \n" +
"varying vec3 vColor;\n" +
"void main(void)\n" +
"{\n" +
" if ( uUseTexture != 1.0 ) \n" +
" gl_FragColor = vec4(vColor.xyz, 1); \n" +
" else \n" +
" gl_FragColor = texture2D(uTexture, vTexPos); \n" +
//" gl_FragColor = vec4(vColor.xyz, 1);\n" +
"}";
You can see the if statement in the fragment shader , that is the one i tried to check if i pass in 1.0 it should do texture else use color.
You are probably using the wrong function call for "uniform variable". Try glGetUniformLocation() as follow:
int aUseTexture = GLES20.glGetUniformLocation(program, "uUseTexture");
Also, the floating point testing (uUseTexture != 1.0) may not be always reliable all the time. You may want to use an integer type.
As far as I know you have to pass the value through the vertex shader before it can get to the fragment shader. e.g. add "uniform float uUseTexture_in; \n" and "varying float uUseTexture; \n" at the top of the vertex shader, in the main function add "uUseTexture = uUseTexture_in;". And your shader should work
I've found andengine sample with blur effect and it works fine, i found that i can use ShaderProgram class and in PreDraw of the Sprite use some shaders (setShaders).
Can i use the same class ShaderProgramm and use shader without attach to sprite ?
For example in onDraw use Shader that only draw a grenn triangle on scene (like in android opengl example). Is there simple way to use ShaderProgram in this way (how can i attach shaders out of PreDraw of Sprite) ?
I've tried smth like this:
BrushShaderProgram bs = BrushShaderProgram.getInstance();
bs.link(pGLState);
GLES20.glUseProgram(bs.getId());
GLES20.glVertexAttribPointer(bs.maPositionHandle, 3, GLES20.GL_FLOAT, false, 12, triangleVB);
GLES20.glEnableVertexAttribArray(bs.maPositionHandle);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
shader is simple:
public static final String VERTEXSHADER =
"attribute vec4 vPosition; \n" +
"void main(){ \n" +
" gl_Position = vPosition; \n" +
"} \n";
public static final String FRAGMENTSHADER = "precision mediump float; \n" +
"void main(){ \n" +
" gl_FragColor = vec4 (0.63671875, 0.76953125, 0.22265625, 1.0); \n" +
"} \n";
Why not create a Triangle class, just like the Rectangle class?
How can I draw a pixel(2D view)for Android using OpenGlEs?
It is simple when we use for drawing
draw(Canvas canvas)
{
...
}
So using it we draw
canvas.drawPoint(i, j, paint);
But in OpenGlEs I still haven't got any function like it.
Please reply
Thank in Advance
GLES20Renderer.programLight = GLES20.glCreateProgram();
int vertexShaderLight = GLES20Renderer.loadShader(GLES20.GL_VERTEX_SHADER, GLES20Renderer.vertexShaderCodeLight);
int fragmentShaderLight = GLES20Renderer.loadShader(GLES20.GL_FRAGMENT_SHADER, GLES20Renderer.fragmentShaderCodeLight);
GLES20.glAttachShader(GLES20Renderer.programLight, vertexShaderLight);
GLES20.glAttachShader(GLES20Renderer.programLight, fragmentShaderLight);
GLES20.glLinkProgram(GLES20Renderer.programLight);
uPLocationLight = GLES20.glGetUniformLocation(GLES20Renderer.programLight, "uP");
uVPositionLocationLight = GLES20.glGetUniformLocation(GLES20Renderer.programLight, "uVPosition");
GLES20.glUseProgram(GLES20Renderer.programLight);
GLES20.glUniform4f(uVPositionLocationLight, LightPosInEyeSpace[0], LightPosInEyeSpace[1], LightPosInEyeSpace[2], LightPosInEyeSpace[3]);
GLES20.glUniformMatrix4fv(uPLocationLight, 1, false, ProjectionMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 1);
private static final String vertexShaderCodeLight =
"uniform vec4 uVPosition; \n"
+ "uniform mat4 uP; \n"
+ "void main(){ \n"
+ " gl_PointSize = 15.0; \n"
+ " gl_Position = uP * uVPosition; \n"
+ "} \n";
private static final String fragmentShaderCodeLight =
"#ifdef GL_FRAGMENT_PRECISION_HIGH \n"
+ "precision highp float; \n"
+ "#else \n"
+ "precision mediump float; \n"
+ "#endif \n"
+ "void main(){ \n"
+ " gl_FragColor = vec4(1.0,1.0,1.0,1.0); \n"
+ "} \n";
glDrawElements(GL_POINTS, 0, num_points, point_array);
You can also use glDrawArrays if you use glVertexPointer first.
Use glPointParameter, glPointSize, and glColor to modify the appearance of the points. Using glPointSizePointer lets you specify an array of point sizes, which is handy for particle effects.