OpenGL GLSL着色器未链接

bbmckpt7  于 2022-10-18  发布在  其他
关注(0)|答案(1)|浏览(244)

我有一个相当基本的着色器程序,但由于某种原因,着色器程序不会链接。代码如下。着色器加载程序成功地加载了着色器,但当我尝试将它们与程序链接时,仍然出错。
着色器加载器:


# include "Shaders.h"

# include <fstream>

# include <sstream>

# include <iostream>

namespace myEngine
{
    bool Shaders::LoadShader(std::string _path, std::string _type)
    {
    std::fstream file(_path);
    char* shadersSrc = nullptr;

    if (file.is_open())
    {
        file.seekg(0, file.end);
        int length = (int)file.tellg();
        file.seekg(0, file.beg);

        shadersSrc = new char[length];

        file.read(shadersSrc, length);

        if (!file.eof())
        {
            file.close();
            std::cerr << "WARNING: COULD NOT READ SHADER" << std::endl;
            return false;
        }

        length = (int)file.gcount();

        shadersSrc[length] = 0;

        file.close();
    }
    else
    {
        std::cerr << "WARNING: COULD NOT OPEN SHADER" << std::endl;
        return false;
    }

    if (_type == "vertex")
    {
        m_vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(m_vertexShaderId, 1, &shadersSrc, NULL);
        glCompileShader(m_vertexShaderId);
        if (!CheckShader(m_vertexShaderId)) return false;
    }
    else if (_type == "fragment")
    {
        m_fragmentShaderId = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(m_fragmentShaderId, 1, &shadersSrc, NULL);
        glCompileShader(m_fragmentShaderId);
        if (!CheckShader(m_fragmentShaderId)) return false;
    }

    return true;

}

bool Shaders::LinkShaders()
{
    m_programId = glCreateProgram();
    glAttachShader(m_programId, m_vertexShaderId);
    glAttachShader(m_programId, m_fragmentShaderId);

    glBindAttribLocation(m_programId, 0, "in_position");

    glLinkProgram(m_programId);

    glGetProgramiv(m_programId, GL_LINK_STATUS, &m_success);

    if (!m_success)
    {
        std::cerr << "WARNING: COULD NOT LINK PROGRAM" << std::endl;
        //throw std::exception();
        return false;
    }

    glDetachShader(m_programId, m_vertexShaderId);
    glDeleteShader(m_vertexShaderId);
    glDetachShader(m_programId, m_fragmentShaderId);
    glDeleteShader(m_fragmentShaderId);

    return true;
}

bool Shaders::CheckShader(GLuint _id)
{
    glGetShaderiv(_id, GL_COMPILE_STATUS, &m_success);
    if (!m_success)
    {
        std::cerr << "WARNING: COULD NOT COMPILE SHADER" << std::endl;
        throw std::exception();
        return false;
    }
    return true;
}

}
片段着色器为:


# version 330 core

out vec4 FragColor;

void main()
{
    FragColor = vec4(0.0, 0.0, 1.0, 1.0);
}

顶点着色器为:


# version 330 core

layout(location = 0) in vec3 in_position;

void main()
{
    gl_Position = vec4(in_position, 1.0);
}

任何帮助都是非常感谢的,就像对大学模块一样。
编辑:程序不会抛出任何错误。它只是说它不能链接第76行的程序。

sgtfey8w

sgtfey8w1#

我在第52行打错了字。应该是GL_FRAGMENT_SHADER而不是GL_VERTEX_SHADER

相关问题