- 1 year ago
How to draw grid with 3D-camera in OpenGl?
Comment
1 / 1
To draw a grid with a 3D-camera in OpenGL, you can follow these steps:
- Setup the OpenGL context:
c++// Initialize OpenGL context
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Grid with 3D-Camera");
// Enable depth test
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
- Define the grid vertices and indices:
c++const int gridSize = 10;
const int numVertices = (gridSize + 1) * (gridSize + 1);
const int numIndices = gridSize * gridSize * 6;
GLfloat vertices[numVertices * 3];
GLuint indices[numIndices];
int vertexIndex = 0;
for (int i = 0; i <= gridSize; ++i) {
for (int j = 0; j <= gridSize; ++j) {
vertices[vertexIndex++] = static_cast<float>(i - gridSize / 2);
vertices[vertexIndex++] = 0.0f;
vertices[vertexIndex++] = static_cast<float>(j - gridSize / 2);
}
}
int index = 0;
for (int i = 0; i < gridSize; ++i) {
for (int j = 0; j < gridSize; ++j) {
int vertex0 = i * (gridSize + 1) + j;
int vertex1 = vertex0 + 1;
int vertex2 = vertex0 + gridSize + 1;
int vertex3 = vertex2 + 1;
indices[index++] = vertex0;
indices[index++] = vertex1;
indices[index++] = vertex2;
indices[index++] = vertex2;
indices[index++] = vertex1;
indices[index++] = vertex3;
}
}
- Define the camera and projection matrices:
c++glm::mat4 view = glm::lookAt(glm::vec3(3.0f, 3.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
glm::mat4 viewProjection = projection * view;
- Define the vertex and index buffer objects:
c++GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
- Define the shader program:
c++GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"uniform mat4 viewProjection;\n"
"void main() {\n"
" gl_Position = viewProjection * vec4(position, 1.0);\n"
"}";
glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr);
glCompileShader(vertexShader);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
const char* fragmentShaderSource =