Here is code using VAO/VBO, and the minimum number of points. Unlike the other answers posted so far, it only needs one cos()
and one sin()
call.
Setup:
// Number of points used for half circle.
const unsigned HALF_PREC = 10;
const float angInc = M_PI / static_cast<float>(HALF_PREC);
const float cosInc = cos(angInc);
const float sinInc = sin(angInc);
GLfloat* coordA = new GLfloat[2 * HALF_PREC * 2];
unsigned coordIdx = 0;
coordA[coordIdx++] = 1.0f;
coordA[coordIdx++] = 0.0f;
float xc = 1.0f;
float yc = 0.0f;
for (unsigned iAng = 1; iAng < HALF_PREC; ++iAng) {
float xcNew = cosInc * xc - sinInc * yc;
yc = sinInc * xc + cosInc * yc;
xc = xcNew;
coordA[coordIdx++] = xc;
coordA[coordIdx++] = yc;
coordA[coordIdx++] = xc;
coordA[coordIdx++] = -yc;
}
coordA[coordIdx++] = -1.0f;
coordA[coordIdx++] = 0.0f;
GLuint vaoId = 0;
glGenVertexArrays(1, &vaoId);
glBindVertexArray(vaoId);
GLuint vboId = 0;
glGenBuffers(1, &vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, 2 * HALF_PREC * 2 * sizeof(GLfloat),
coordA, GL_STATIC_DRAW);
delete[] coordA;
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
Draw:
glBindVertexArray(vaoId);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 2 * HALF_PREC);
glBindVertexArray(0);