我试图使用OpenGL在屏幕上显示一个三角形,但是当我运行代码时,出现黑屏
我目前正在使用我在互联网上找到的指南(此处是链接:http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/)。
这是代码:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int larghezza = 1024;
int altezza = 768;
int main (){
glewExperimental = true;
if (!glfwInit() )
{
fprintf (stderr, "non è stato possibile inizzializzare glfw\n");
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);// 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);// utilizza OpenGL 4.1
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//NON VOGLIO VECCHIE VERSIONI DI OPENGL
GLFWwindow* window; // crea una finestra
window = glfwCreateWindow(larghezza, altezza, "FINESTRA 1", NULL, NULL);
if (!window){
fprintf (stderr, "Non è stato possibile aprire la finestra!\n");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window); //inizzializza GLEW
glewExperimental = true;
if (glewInit() != GLEW_OK){
fprintf (stderr, "non è stato possibile inizzializzare GLEW");
return -1;
}
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
do {
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0 );
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
GLuint vertexbuffer;
// Generate 1 buffer, put the resulting identifier in vertexbuffer
glGenBuffers(1, &vertexbuffer);
// The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glDisableVertexAttribArray(0);
}
我该如何解决?
答案 0 :(得分:1)
glDrawArrays()调用应位于主渲染事件循环中。具体在do {}块内。
询问:如果在do {}循环内未调用绘图调用,为什么会呈现此代码?
当您按Escape键时,它将进行绘制,但是在隐藏的缓冲区中,一旦绘制完成,基本上该缓冲区将被交换到屏幕上。由于您在glDrawArrays()调用之后不进行交换,因此您将永远看不到它。
我不知道您正在使用哪个教程网站
但是,我建议像本网站一样的适当教程-Learnopengl.com。甚至通过入门一节也足以构成一个很好的介绍。