-1
我試圖在opengl es 2.0中創建一個球體,但我得到一個空指針異常。我一直堅持這幾個小時。在檢查logcat後,它似乎找到了幾個頂點,但是索引緩衝區總是直接擊中空指針。生成球體時的空指針
private void generateSphereCoords(float radius, int stacks, int slices) {
for (int stackNumber = 0; stackNumber <= stacks; stackNumber++) {
for (int sliceNumber = 0; sliceNumber <= slices; sliceNumber++) {
float theta = (float) (stackNumber * Math.PI/stacks);
float phi = (float) (sliceNumber * 2 * Math.PI/slices);
Log.i("theta", String.valueOf(theta));
Log.i("phi", String.valueOf(phi));
float sinTheta = FloatMath.sin(theta);
float sinPhi = FloatMath.sin(phi);
float cosTheta = FloatMath.cos(theta);
float cosPhi = FloatMath.cos(phi);
vertices = new float[]{radius * cosPhi * cosTheta, radius * sinPhi * cosTheta, radius * sinTheta};
Log.i("vertexX", String.valueOf(vertices[0]));
Log.i("vertexY", String.valueOf(vertices[1]));
Log.i("vertexZ", String.valueOf(vertices[2]));
// a float is 4 bytes, therefore I multiply the number of vertices by 4.
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);// (number of coordinate values * 4 bytes per float)
vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
vertexBuffer = vbb.asFloatBuffer();// create a floating point buffer from the ByteBuffer
vertexBuffer.put(vertices);
vertexBuffer.position(0);// set the buffer to read the first coordinate
}
}
for (int stackNumber = 0; stackNumber <= stacks; stackNumber++) {
for (int sliceNumber = 0; sliceNumber <= slices; sliceNumber++) {
ByteBuffer ibb = ByteBuffer.allocateDirect(vertexCount * 2);// (number of coordinate values * 4 bytes per float)
ibb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
indexBuffer = ibb.asShortBuffer();// create a floating point buffer from the ByteBuffer
indexBuffer.put((short) ((stackNumber * slices) + (sliceNumber % slices)));
indexBuffer.put((short) (((stackNumber + 1) * slices) + (sliceNumber % slices)));
indexBuffer.position(0);// set the buffer to read the first coordinate
}
}
}