2011-12-29 83 views
1

我一直在試圖做android dev-guide on OPENGLES20, ,但是當我運行代碼時,我只得到背景顏色,而不是三角形(我完成了直到拉伸的三角形照片)。Android HelloOpenGLES20示例不起作用

我怎樣才能讓三角形顯示出來? (運行在Android 2.2設備的應用程序)

下面的代碼:

public class HelloOpenGLES20Renderer implements Renderer { 
private FloatBuffer triangleVB; 

private final String vertexShaderCode = "attribute vec4 vPosition; \n" 
     + "void main(){    \n" + " gl_Position = vPosition; \n" 
     + "}       \n"; 

private final String fragmentShaderCode = "precision mediump float; \n" 
     + "void main(){    \n" 
     + " gl_FragColor = vec4 (0.63671875, 0.76953125, 0.22265625, 1.0); \n" 
     + "}       \n"; 

private int mProgram; 
private int maPositionHandle; 

private int loadShader(int type, String shaderCode) { 

    // create a vertex shader type (GLES20.GL_VERTEX_SHADER) 
    // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER) 
    int shader = GLES20.glCreateShader(type); 

    // add the source code to the shader and compile it 
    GLES20.glShaderSource(shader, shaderCode); 
    GLES20.glCompileShader(shader); 

    return shader; 
} 

@Override 
public void onDrawFrame(GL10 gl) { 
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); 

    GLES20.glUseProgram(mProgram); 

    GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, 
      false, 12, triangleVB); 
    GLES20.glEnableVertexAttribArray(maPositionHandle); 

    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); 
} 

public void onSurfaceChanged(GL10 gl, int width, int height) { 
    GLES20.glViewport(0, 0, width, height); 
} 

@Override 
public void onSurfaceCreated(GL10 gl, EGLConfig config) { 
    gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); 
    initShapes(); 
    int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode); 
    int fragmentShader = loadShader(GLES20.GL_VERTEX_SHADER, 
      fragmentShaderCode); 
    mProgram = GLES20.glCreateProgram(); 
    GLES20.glAttachShader(mProgram, vertexShader); 
    GLES20.glAttachShader(mProgram, fragmentShader); 
    GLES20.glLinkProgram(mProgram); 

    maPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition"); 
} 

private void initShapes() { 
    float[] triangleCoords = new float[] { 
      // X,Y,Z 
      -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; 
    ByteBuffer vbb = ByteBuffer.allocateDirect(triangleCoords.length * 4); 
    vbb.order(ByteOrder.nativeOrder()); 
    triangleVB = vbb.asFloatBuffer(); 
    triangleVB.put(triangleCoords); 
    triangleVB.position(0); 
} 

}

+4

我認爲你沒有正確地遵循教程100%。例如,在onSurfaceCreated(...)中,您可以調用loadShader(GLES20.GL_VERTEX_SHADER ..)兩次,而後者應該是loadShader(GLES20.GL_FRAGMENT_SHADER ..)。 – harism 2011-12-29 20:37:09

+1

哦對!謝謝,那就是問題所在...... – saarraz1 2011-12-29 20:53:01

回答

2

我想你沒有按照教程100%正確。例如,在onSurfaceCreated(...)中,您撥打loadShader(GLES20.GL_VERTEX_SHADER..)兩次,而後者應爲loadShader(GLES20.GL_FRAGMENT_SHADER..)