Can someone please explain how the indices are generated for triangular mesh?
The programme generated array of vertices for sphere object, and indices are generated to be drawn using glDrawElements method.
I don't understand how those indices relate with stacks and slices.
I am new to openGL and I have been spending a lot of time trying to understand how this code works.
Thanks in advance. :)
int stacks = 40, slices = 40; // stacks = no. of Latitude lines,
// slices = no. of Longitude lines
double deltaLong = PI * 2 / slices;
double deltaLat = PI / stacks;
// Generate vertices coordinates, normal values, and texture coordinates
numVertices = (slices + 1) * (stacks - 1) + 2;
vertices = new float[numVertices * 3];
normals = new float[numVertices * 3];
textures = new float[numVertices * 2];
// North pole point
normals[0] = 0; normals[1] = 0; normals[2] = 1;
vertices[0] = 0; vertices[1] = 0; vertices[2] = radius;
textures[0] = 0.5f; textures[1] = 1.0f;
k = 1;
// vertices on the main body
for (i = 1; i < stacks; i++) {
for (j = 0; j <= slices; j++) {
normals[3 * k] = sin(deltaLat * i) * cos(deltaLong * j);
normals[3 * k + 1] = sin(deltaLat * i) * sin(deltaLong * j);
normals[3 * k + 2] = cos(deltaLat * i);
vertices[3 * k] = radius * normals[3 * k];
vertices[3 * k + 1] = radius * normals[3 * k + 1];
vertices[3 * k + 2] = radius * normals[3 * k + 2];
textures[2 * k] = (float) j / slices;
textures[2 * k + 1] = 1 - (float) i / stacks;
k++;
}
}
// South pole point
normals[3 * k] = 0;normals[3 * k + 1] = 0;normals[3 * k + 2] = -1;
vertices[3 * k] = 0;vertices[3 * k + 1] = 0;vertices[3 * k + 2] = -radius;
textures[2 * k] = 0.5f; textures[2 * k + 1] = 0.0f; k++;
//The above code is to generate vertices array and I think I understand how it works.
//**********************************
// Below is what I don't understand
int numIndices = (stacks - 1) * slices * 6; //why multiply by 6?
int[] indices = new int[numIndices];
int k = 0;
//add indices in North Pole region (no. of elements is slices * 3)
// WHY 3 times thenumber of slices?
for (int j = 1; j<= slices; j++){
indices[k++] = 0;
indices[k++] = j;
indices[k++] = j+1;
}
//add indices in South Pole Region (no. of element is slices * 3)
int temp = numVertices - 1;
for (int j = temp-1; j > temp - slices - 1; j--){
indices [k++] = temp;
indices [k++] = j;
indices [k++] = j - 1;
}
// add body (no. of element is (stacks - 2) * slices * 6
for (i = 1; i < stacks - 1; i++) {
for (j = 1; j <= slices; j++) {
// each quad gives two triangles
// triangle one
indices[k++] = (i - 1) * slices + j;
indices[k++] = i * slices + j;
indices[k++] = i * slices + j + 1;
// triangle two
indices[k++] = (i - 1) * slices + j;
indices[k++] = i * slices + j + 1;
indices[k++] = (i - 1) * slices + j + 1;
}
}
I finally understand how the indexing in sphere code I shown work and figured out how to make a cylinder shown in above pic.