要在OpenGL中以交互方式绘制基元,您需要遵循以下步骤:
以下是一个简单的示例代码,演示如何在OpenGL中绘制一个三角形:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
// Vertex shader source code
const char* vertexShaderSource = "#version 330 core\n"
"layout(location = 0) in vec4 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = aPos;\n"
"}\n";
// Fragment shader source code
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n";
int main()
{
// Initialize GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create GLFW window
GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL Triangle", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window"<< std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// Initialize GLEW
glewExperimental = true;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW"<< std::endl;
return -1;
}
// Compile and link shader program
unsigned int shaderProgram = glCreateProgram();
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// ...
// Create vertex buffer object
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), &triangleVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
// Main loop
while (!glfwWindowShouldClose(window))
{
// Input
processInput(window);
// Render
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
// Swap buffers and poll IO events
glfwSwapBuffers(window);
glfwPollEvents();
}
// Clean up
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shaderProgram);
glfwTerminate();
return 0;
}
这个示例代码演示了如何创建一个简单的OpenGL窗口,编译和链接着色器程序,创建顶点缓冲区对象,并绘制一个三角形。您可以根据自己的需求修改这个示例代码,以绘制其他基元
领取专属 10元无门槛券
手把手带您无忧上云