I有一个int main();
函数和int Game();
函数,其中在主函数中,我有一个在两个函数中都使用的窗口。我已经在全局范围中定义了窗口,当我尝试在主函数中的GLFW循环之前运行Game();
函数时,窗口会打开一秒钟,然后关闭。然后我得到
错误:GLFW库未初始化
从error_callback();
打印
这是我的代码
#include <GLFW/glfw3.h>
#include <GL/freeglut.h>
#include <GL/GL.h>
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
void drawText(const char *text, int length, int x, int y);
void framebuffer_size_callback(GLFWwindow* wndow, int width, int height);
void DrawCube(GLfloat centerPosX, GLfloat centerPosY, GLfloat centerPosZ, GLfloat edgeLength);
void button(GLfloat red, GLfloat green, GLfloat blue, int x, int y, int width, int height);
void error_callback(int error, const char* description);
int Game();
int width = 860, height = 490;
GLFWwindow* window;
int main(int argc, char **argv) {
//GLTtext* text = gltCreateText();
//gltSetText(text, "ElectroCraft");
//GLFWwindow* window;
int width = 860, height = 490;
if (!glfwInit()) {
printf("failed to init glfw");
return -1;
}
glutInit(&argc, argv);
window = glfwCreateWindow(width, height, "ElectroCraft", NULL, NULL);
glfwMakeContextCurrent(window);
if (!window) {
printf("failed to start window");
glfwTerminate();
return -1;
}
Game();
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, 0, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
string text;
glfwSetErrorCallback(error_callback);
while (!glfwWindowShouldClose(window)) {
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glClearColor(53.0f / 255.0f, 81.0f / 255.0f, 92.0f / 255.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2f(0, height-80);
glVertex2f(width, height - 80);
glEnd();
button(192.0f / 255.0f, 192.0f / 255.0f, 192.0f / 255.0f, width / 2 - 70, height / 2, 260, 50);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 1;
}
void error_callback(int error, const char* description) {
fprintf(stderr, "Error: %sn", description);
}
int Game() {
//glfwMakeContextCurrent(window);
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, 0, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
while (!glfwWindowShouldClose) {
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glClearColor(62.0f / 255.0f, 85.9f / 255.0f, 255.0 / 255.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 1;
}
这可能是因为我没有在全局范围内启动GLFW库,但我似乎无法做到这一点,因为如果if语句在函数之外,我会出错
窗口打开一秒钟,然后关闭
当然,因为glfwWindowShouldClose
不是函数Game
中的函数调用。glfwWindowShouldClose
是一个函数指针,因此!glfwWindowShouldClose
的求值结果为false
,循环永远不会运行:
while (!glfwWindowShouldClose) {
while (!glfwWindowShouldClose(window)) {
然后我得到错误:GLFW库未初始化
这是因为GLFW由函数Game
中的glfwTerminate()
终止。从函数Game
中删除glfwTerminate()
。
但请注意,一旦关闭了一个窗口,就必须创建一个新窗口。一种选择是隐藏glfwHideWindow
并向glfwShowWindow
显示一个窗口。