OpenGL ESでSphere


OpenGL ESのプリミティブを手軽に作る第三弾のSphereです。
Cubeの時よりは作りやすかったけど、面を作るところで結構悩んだ。


これでPlane、Cube、Sphereの三つができてマウスピッキングも(一応)できるようになったので、
何か作れるんじゃないだろうかと思ってます。何か作ろう。


あー、あとマウスとかキーボードの入力をひとまとめにして便利に扱えるようにしよう。


以下動作画面とソース。
ソースは基本的に前のと同じなので生成部のみ掲載します。
http://screencast.com/t/j6RHUuDnVh

ソース

protected void create(int segW, int segH) {
	int gridU = segW;
	int gridV = segH;
	int gridU1 = gridU + 1;
	int gridV1 = gridV + 1;
	int incU = 360 / gridU;
	int incV = 2 * mRadius / gridV;
	int cnt;

				
	//vertices
	int[] vertices = new int[(2 + (gridV1-2) * gridU) * 3];
	cnt = 0;
	vertices[cnt++] = 0;
	vertices[cnt++] = -mRadius;
	vertices[cnt++] = 0;
	double d = mRadius;
	double y, t, r;
	for( int iv = 1; iv < gridV1 - 1; ++ iv ) {
		y = iv * incV - d;			
		r = Math.sqrt(d * d - y * y);
		for( int iu = 0; iu < gridU; ++ iu ) {
			t = iu * incU * Math.PI / 180; 
			vertices[cnt++] = (int)(r * Math.cos(t));
			vertices[cnt++] = (int)y;
			vertices[cnt++] = (int)(r * Math.sin(t));
		}
	}
	vertices[cnt++] = 0;
	vertices[cnt++] = mRadius;
	vertices[cnt++] = 0;			

	//indices
	byte[] indices = new byte[((gridV-1) * gridU * 2) * 3];
	cnt = 0;
	for( int iu = 0; iu < gridU; ++ iu ) {
		indices[cnt++] = 0;				
		indices[cnt++] = (byte)((iu + 1) % gridU + 1);
		indices[cnt++] = (byte)(iu + 1);
	}
	for( int iv = 1; iv < gridV1 - 2; ++ iv ) {
		for( int iu = 0; iu < gridU; ++ iu ) {
			int m = (iv - 1) * gridU;
			//Triangle A
			indices[cnt++] = (byte)(iu + 1 + m);
			indices[cnt++] = (byte)((iu + 1) % gridU + 1 + m);
			indices[cnt++] = (byte)(iu + 1 + gridU + m);
			
			//Triangle B
			indices[cnt++] = (byte)((iu + 1) % gridU + 1 + gridU + m);
			indices[cnt++] = (byte)(iu + 1 + gridU + m);
			indices[cnt++] = (byte)((iu + 1) % gridU + 1 + m);
		}
	}

	int n = (2 + (gridV1-2) * gridU) - 1;
	for( int iu = n - gridU; iu < n; ++ iu ) {
		indices[cnt++] = (byte)iu;
		indices[cnt++] = (byte)(iu % gridU + n - gridU );				
		indices[cnt++] = (byte)n;
	}

	int[] colors = new int[(2 + (gridV1-2) * gridU) * 4];
	cnt = 0;
	Random rand = new Random();
	for( int i = 0; i < colors.length; i += 4 ) {
		colors[cnt++] = rand.nextInt();
		colors[cnt++] = rand.nextInt();
		colors[cnt++] = rand.nextInt();
		colors[cnt++] = 0x10000;
	}

	mVertexBuffer = createIntBuffer(vertices);
	mColorBuffer = createIntBuffer(colors);
	mIndexBuffer = createByteBuffer(indices);
}