最近学OpenGL ES,想在手机上画个球体。用的是极坐标生成顶点,运行会出错。我已经用native order了,还是报错
02-21 23:12:28.710: E/OpenGLES(3314): Application com.gl.demo (SDK target 8) called a GL11 Pointer method with an indirect Buffer.
02-21 23:12:28.726: W/dalvikvm(3314): threadid=9: thread exiting with uncaught exception (group=0x40018560)
02-21 23:12:28.734: E/AndroidRuntime(3314): FATAL EXCEPTION: GLThread 10
02-21 23:12:28.734: E/AndroidRuntime(3314): java.lang.IllegalArgumentException: Must use a native order direct Buffer
02-21 23:12:28.734: E/AndroidRuntime(3314): at com.google.android.gles_jni.GLImpl.glVertexPointerBounds(Native Method)
02-21 23:12:28.734: E/AndroidRuntime(3314): at com.google.android.gles_jni.GLImpl.glVertexPointer(GLImpl.java:1121)
02-21 23:12:28.734: E/AndroidRuntime(3314): at com.gl.demo.Ball.draw(Ball.java:87)
02-21 23:12:28.734: E/AndroidRuntime(3314): at com.gl.demo.HelloRender.onDrawFrame(HelloRender.java:53)
02-21 23:12:28.734: E/AndroidRuntime(3314): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1364)
02-21 23:12:28.734: E/AndroidRuntime(3314): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1119)
下面是Ball类的代码:
- Java code
public class Ball { private FloatBuffer vBuffer;//定点缓存 private ShortBuffer indexBuffer;//定点索引缓存 private int vCount;//顶点数量 private int iCount;//索引数量 public Ball(int scale){ ArrayList<Float> verties=new ArrayList<Float>(); ArrayList<Integer> alIndex=new ArrayList<Integer>(); int span=18; for(int v=0;v<=180;v+=span){ for(int h=0;h<=360;h+=span){ float r=(float)(scale*Math.sin(Math.toRadians(v))); float x=(float)(r*Math.cos(Math.toRadians(h))); float y=(float)(scale*Math.cos(Math.toRadians(v))); float z=(float)(r*Math.sin(Math.toRadians(h))); verties.add(x); verties.add(y); verties.add(z); } } vCount=verties.size()/3; float[] v=new float[vCount*3]; for(int i=0;i<v.length;i++){ v[i]=verties.get(i); } ByteBuffer bb0=ByteBuffer.allocate(verties.size()*4); bb0.order(ByteOrder.nativeOrder()); vBuffer=bb0.asFloatBuffer(); vBuffer.put(v); vBuffer.position(0); int row=180/span+1; int col=360/span+1; for(int i=0;i<row;i++){ if(i!=(row-1)){ for(int j=0;j<(col-1);j++){ int c=i*col+j; alIndex.add(c); alIndex.add(c+1); alIndex.add(c+col); } for(int j=1;j<col;j++){ int c=i*col+j; alIndex.add(c); alIndex.add(c+col); alIndex.add(c+col-1); } } } iCount=alIndex.size(); short[] ind=new short[iCount]; for(int i=0;i<ind.length;i++){ ind[i]=alIndex.get(i).shortValue(); } ByteBuffer bb1=ByteBuffer.allocate(ind.length*2); bb1.order(ByteOrder.nativeOrder()); indexBuffer=bb1.asShortBuffer(); indexBuffer.put(ind); indexBuffer.position(0); } public void draw(GL10 gl){ gl.glEnable(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vBuffer);//LogCat提示这里有问题,vBuffer不是native,order gl.glDrawElements(GL10.GL_TRIANGLES, iCount, GL10.GL_UNSIGNED_SHORT, indexBuffer); }}
------解决方案--------------------
别用ByteBuffer.allocate
用allocateDirect