OpenGL 因当前代码而崩溃(从书中跟随)

Posted

技术标签:

【中文标题】OpenGL 因当前代码而崩溃(从书中跟随)【英文标题】:OpenGL crashing with current code (followed from book) 【发布时间】:2020-12-31 00:21:07 【问题描述】:

Picture of program running with current code我正在尝试创建一个简单的着色器程序(4.4)。但无论我做什么,我的窗口只是显示为白色并永远加载......所以我的问题是,当我尝试从我的两个文件(与我的 main.cpp 位于同一目录中)加载任何内容时,我的程序似乎崩溃了/p>

代码运行良好,没有明显问题:

#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

#define numVAOs 1

GLuint renderingProgram;
GLuint vao[numVAOs];

void printShaderLog(GLuint shader) 
    int len = 0;
    int chWrittn = 0;
    char* log;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);

    if (len > 0) 
        log = (char*)malloc(len);
        glGetShaderInfoLog(shader, len, &chWrittn, log);
        cout << "Shader Info Log: " << log << endl;
        free(log);
    


void printProgramLog(int prog) 
    int len = 0;
    int chrWrittn = 0;
    char* log;
    glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len);

    if (len > 0) 
        log = (char*)malloc(len);
        glGetProgramInfoLog(prog, len, &chrWrittn, log);
        cout << "Program Info Log: " << log << endl;
        free(log);
    


bool checkOpenGLError() 
    bool foundError = false;
    int glErr = glGetError();
    while (glErr != GL_NO_ERROR) 
        cout << "glError: " << glErr << endl;
        foundError = true;
        glErr = glGetError();
    
    return foundError;


string readShaderSource(const char* filePath) 
    string content;
    ifstream fileStream(filePath, ios::in);
    string line = "";

    while (!fileStream.eof()) 
        getline(fileStream, line);
        content.append(line + "\n");
    
    fileStream.close();
    return content;


GLuint createShaderProgram() 
    GLint vertCompiled;
    GLint fragCompiled;
    GLint linked;
    //const char* vshaderSource =
    //  "#version 430    \n"
    //  "void main(void) \n"
    //  "gl_Position = vec4(0.0, 0.0, 0.0, 1.0);";
    //
    //const char* fshaderSource =
    //  "#version 430    \n"
    //  "out vec4 color; \n"
    //  "void main(void) \n"
    //  " if (gl_FragCoord.x > 300) color = vec4(1.0, 0.0, 0.0, 1.0); else color = vec4(0.0, 0.0, 
    1.0, 1.0);";

    string vertShader = readShaderSource("vshader.glsl");
    string fragShader = readShaderSource("fshader.glsl");
    cout << vertShader << endl;
    cout << fragShader << endl;

    const char* vertShaderSrc = vertShader.c_str();
    const char* fragShaderSrc = fragShader.c_str();


    GLuint vShader = glCreateShader(GL_VERTEX_SHADER);
    GLuint fShader = glCreateShader(GL_FRAGMENT_SHADER);

    glShaderSource(vShader, 1, &vertShaderSrc, NULL);

    glShaderSource(fShader, 1, &fragShaderSrc, NULL);
    glCompileShader(vShader);
    checkOpenGLError();
    glGetShaderiv(vShader, GL_COMPILE_STATUS, &vertCompiled);

    if (vertCompiled != 1) 
        cout << "vertex compilation failed" << endl;
        printShaderLog(vShader);
    

    glCompileShader(fShader);
    checkOpenGLError();
    glGetShaderiv(fShader, GL_COMPILE_STATUS, &fragCompiled);

    if (fragCompiled != 1) 
        cout << "fragment compilation failed" << endl;
        printShaderLog(fShader);
    
    GLuint vfProgram = glCreateProgram();
    glAttachShader(vfProgram, vShader);
    glAttachShader(vfProgram, fShader);
    glLinkProgram(vfProgram);
    checkOpenGLError();
    glGetProgramiv(vfProgram, GL_LINK_STATUS, &linked);

    if (linked != 1) 
        cout << "linking failed" << endl;
        printProgramLog(vfProgram);
    

    return vfProgram;


void init(GLFWwindow* window) 
    renderingProgram = createShaderProgram();
    glGenVertexArrays(numVAOs, vao);
    glBindVertexArray(vao[0]);

void display(GLFWwindow* window, double currentTime) 
    glUseProgram(renderingProgram);
    glPointSize(230.0f);
    glDrawArrays(GL_POINTS, 0, 1);

int main(void) 
    if (!glfwInit())  exit(EXIT_FAILURE); 
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    GLFWwindow* window = glfwCreateWindow(600, 600, "Chapter2 - program1", NULL, NULL);
    glfwMakeContextCurrent(window);
    if (glewInit() != GLEW_OK)  exit(EXIT_FAILURE); 
    glfwSwapInterval(1);
    init(window);
    while (!glfwWindowShouldClose(window)) 
        display(window, glfwGetTime());
        glfwSwapBuffers(window);
        glfwPollEvents();
    
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);

【问题讨论】:

你永远不会讨厌glfwSwapBuffers,所以无论你渲染什么都不会出现。你也永远不会打电话给glClear,所以你的颜色缓冲区内容无论如何都是未定义的。您还尝试在没有设置顶点属性数组的情况下绘制 1 个点。 @derhass glfwSwapBuffers 实际上正在被调用:) 哇,我怎么会错过呢?无论如何,这段代码仍然非常缺乏。 所以正如我所说,我对此很陌生,所以它是什么,在代码@derhass 中缺少这么多,因为我只是想知道如何才能做得更好,或者什么我需要注意 【参考方案1】:

正如@derhass 指出的那样,您缺少glClear()(已将着色器加载器丢弃):

// g++ main.cpp `pkg-config --cflags --libs glew glfw3`
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>

void CheckStatus( GLuint obj, bool isShader )

    GLint status = GL_FALSE, log[ 1 << 11 ] =  0 ;
    ( isShader ? glGetShaderiv : glGetProgramiv )( obj, isShader ? GL_COMPILE_STATUS : GL_LINK_STATUS, &status );
    if( status == GL_TRUE ) return;
    ( isShader ? glGetShaderInfoLog : glGetProgramInfoLog )( obj, sizeof( log ), NULL, (GLchar*)log );
    std::cerr << (GLchar*)log << "\n";
    std::exit( EXIT_FAILURE );


void AttachShader( GLuint program, GLenum type, const char* src )

    GLuint shader = glCreateShader( type );
    glShaderSource( shader, 1, &src, NULL );
    glCompileShader( shader );
    CheckStatus( shader, true );
    glAttachShader( program, shader );
    glDeleteShader( shader );


const char* const vert = R"GLSL(
#version 430
void main()

    gl_Position = vec4( 0.0, 0.0, 0.0, 1.0 );

)GLSL";

const char* const frag = R"GLSL(
#version 430
out vec4 color;
void main()

    if( gl_FragCoord.x > 300 )
        color = vec4( 1.0, 0.0, 0.0, 1.0 );
    else
        color = vec4( 0.0, 0.0, 1.0, 1.0 );

)GLSL";

int main( int argc, char** argv )

    if( !glfwInit() )
    
        exit( EXIT_FAILURE );
    
    glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
    glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
    GLFWwindow* window = glfwCreateWindow( 600, 600, "GLFW", NULL, NULL );
    glfwMakeContextCurrent(window);
    if( glewInit() != GLEW_OK )
    
        exit( EXIT_FAILURE );
    
    glfwSwapInterval(1);

    GLuint prog = glCreateProgram();
    AttachShader( prog, GL_VERTEX_SHADER, vert );
    AttachShader( prog, GL_FRAGMENT_SHADER, frag );
    glLinkProgram( prog );
    CheckStatus( prog, false );
    glUseProgram( prog );

    GLuint vao = 0;
    glGenVertexArrays( 1, &vao );
    glBindVertexArray( vao );

    while( !glfwWindowShouldClose( window ) )
    
        glClearColor(0, 0, 0, 1);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

        glUseProgram( prog );
        glPointSize( 230.0f );
        glDrawArrays( GL_POINTS, 0, 1 );
        glfwSwapBuffers( window );
        glfwPollEvents();
    

    glfwDestroyWindow( window );
    glfwTerminate();
    exit( EXIT_SUCCESS );

【讨论】:

【参考方案2】:

您在主循环中缺少这两行代码。第一个设置“环境”或“背景”的颜色。第二个在每帧之前清除屏幕和深度缓冲区。

glClearColor(0, 0, 0, 1);

glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

【讨论】:

嘿。感谢您对线条的作用的回答和解释。可悲的是,我的代码仍然不会显示任何内容,并且仍然只是加载白屏。 @ThobiasLarsen 代码本身看起来不错,是不是您的程序找不到着色器文件?这会导致像您这样的问题,如果您使用的是 Visual Studio,则应将工作目录设置为 $(ProjectDir)。 感谢您的推荐,但遗憾的是它设置为 projectDir。所以仍然可能是读取文件的问题,但我不知道如何。也许我把文件放在了错误的地方或什么地方? @ThobiasLarsen Projectdir 表示包含 .vcxproj 文件的文件夹,如果着色器文件不在该文件夹中,请尝试将它们移动到该文件夹​​。您可能需要稍微探索一下您的目录才能找到它。 (不是很明显) 该死的,你是对的。我把它放在一个文件夹里,所以它没有用,该死的它现在真的运行了。太感谢了。你拯救了我的 OpenGL 学习!

以上是关于OpenGL 因当前代码而崩溃(从书中跟随)的主要内容,如果未能解决你的问题,请参考以下文章

OpenGL黑屏?

从书中复制C#代码(假人为C#.0,无法获得预期的结果

如何在 Java 中成功地从书中删除标签?

既然喜欢就要认真对待

日本菲尔兹奖得主广中平祐:不要急于从书中寻找答案,要尝试独立思考

C 中的 Vigenere 代码因多字符键而崩溃