在Opengl中绘制一条不显示C++的线

Drawing a line in Opengl not displaying C++

本文关键字:显示 C++ 的线 一条 Opengl 绘制      更新时间:2023-10-16

我正试图在我的窗口上画一条直线。屏幕颜色正常,但这条线似乎画不出来。我很确定这是因为我可能把位置设置错了,线被从窗户上剪掉了,但我不知道如何解决这个问题。

我的完整代码

#include <GLglew.h>
#include <GLFW/glfw3.h>
#include <GLglut.h>
#include <glm.hpp>
#include <GLfreeglut.h>
#include <GLGL.h>
#include <IL/il.h>
using namespace std;
int main() {
int windowWidth = 1024, windowHeight = 1024;
if (!glfwInit())
return -1;

GLFWwindow* window;
window = glfwCreateWindow(windowWidth, windowHeight, "electroCraft", NULL, NULL);
glfwMakeContextCurrent(window); // stes the specified window as active INACTIVE SCREEN IF WINDOW NOT CURRENT!!!!
if (!window) {
glfwTerminate();
printf("Screen failed to start. ABORTING...n");
return -1;
}
glViewport(0, 0, windowWidth, windowHeight);
glOrtho(0, windowWidth, 0, windowHeight, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window)) {
glClearColor(62.0f / 255.0f, 85.9f / 255.0f, 255.0 / 255.0, 0.0);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
//begin drawing
glBegin(GL_LINE);
glVertex2f(20, 100);
glVertex2f(600, 100);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}

如注释中所述,您必须使用GL_LINES而不是GL_LINE,因为GL_LINE不是有效的Primitive类型。

glBegin(GL_LINES); // <----
glVertex2f(20, 100);
glVertex2f(600, 100);
glEnd();

但还有另一个问题。默认矩阵模式为GL_MODELVIEW(请参见glMatrixMode(,因此正投影设置为模型视图矩阵,并被单位矩阵(glLoadIdentity(覆盖。您必须在glOrtho:之前设置矩阵模式GL_PROJECTION

glMatrixMode(GL_PROJECTION); // <----
glOrtho(0, windowWidth, 0, windowHeight, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();