2014-06-11 94 views
0

我試圖用OpenGL創建一個三維立方體。獲得立體立方體。試圖添加多維數據集的另一面。在這裏,我看到這個錯誤:OpenGL NULL指針異常

logcat的告訴的我,

triangle1Buffer = NULL

FATAL EXCEPTION: GLThread 270 
    java.lang.NullPointerException 
      at com.google.android.gles_jni.GLImpl.glVertexPointer(GLImpl.java:1122) 
      at com.podlinov.elseapp.app.Renderer.onDrawFrame(Renderer.java:94) 

代碼:

public class Renderer implements GLSurfaceView.Renderer { 

    @Override 
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { 

    } 

    @Override 
    public void onSurfaceChanged(GL10 gl, int width, int height) { 

     gl.glViewport(0, 0, width, height); 
     float ratio = (float) width/height; 
     gl.glMatrixMode(GL10.GL_PROJECTION); 
     gl.glLoadIdentity(); 
     gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); 
    } 

    float [] triangle = { 
      0, 0, 0, // A 
      1, 0, 0, // B 
      0, 1, 0 , // C 

      1, 0, 0, // B 
      1, 1, 0 , // D 
      0, 1, 0 , // C 
    }; 

    float [] triangle2 = { 
      0, 0, 0, // A 
      1, 0, 0, // B 
      0, 1, 0, // C 
    }; 


    FloatBuffer triangleBuffer; 
    FloatBuffer triangle1Buffer; 

    public Renderer() { 

     ByteBuffer bb = ByteBuffer.allocateDirect(6*3*4); 
     bb.order(ByteOrder.nativeOrder()); 
     triangleBuffer = bb.asFloatBuffer(); 
     triangleBuffer.put(triangle); 
     triangleBuffer.position(0); 

     ByteBuffer bb2 = ByteBuffer.allocateDirect(3*3*4); 
     bb2.order(ByteOrder.nativeOrder()); 
     triangleBuffer = bb2.asFloatBuffer(); 
     triangleBuffer.put(triangle2); 
     triangleBuffer.position(0); 

    } 

    @Override 
    public void onDrawFrame(GL10 gl) { 

     gl.glClear(GL10.GL_COLOR_BUFFER_BIT); 

     gl.glMatrixMode(GL10.GL_MODELVIEW); 
     gl.glLoadIdentity(); 
     gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); 

     gl.glColor4f(1,0,1,1); 
     gl.glTranslatef(-1.5f, 0.5f, -3f); 
     gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleBuffer); 
     gl.glDrawArrays(GL10.GL_TRIANGLES, 0,6); 


     gl.glColor4f(0,0,1,1); 
     gl.glTranslatef(1.5f, 0, -3f); 
     gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangle1Buffer); // NULL POINTER EXCEPTION triangle1Buffer =NULL 
     gl.glDrawArrays(GL10.GL_TRIANGLES, 0,3); 
    } 

} 
+0

在構造函數中填充triangleBuffer兩次。我敢打賭,你打算在那裏填充triangleBuffer和triangle1Buffer。 – ThaMe90

+0

@ ThaMe90你的答案也是對的。部份! – Garf1eld

回答

0

我覺得你的問題是在這裏:

ByteBuffer bb2 = ByteBuffer.allocateDirect(3*3*4); 
    bb2.order(ByteOrder.nativeOrder()); 
    triangleBuffer = bb2.asFloatBuffer(); 
    triangleBuffer.put(triangle2); 
    triangleBuffer.position(0); 

你應該已經改變它triangle1Buffer我猜?

+0

非常感謝!!!!! – Garf1eld

+0

沒問題。實際上,你可以使用OpenGL的GL_QUADS來代替GL_TRIANGLES來繪製一個立方體,它需要較少的邊繪製(因爲一個立方體有6個正方形邊而不是12個三角形邊)。只要確保將頂點添加到浮點數組並更改緩衝區大小 - 順便說一句,3 * 3 * 4是36,但你的triangle2數組只有9個值。不是隻需要3 * 3,還是我是愚蠢的? – Monkey

+0

triangle2的值僅供參考。 – Garf1eld