加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
shader.cc 3.26 KB
一键复制 编辑 原始数据 按行查看 历史
pengrui_2009 提交于 2021-03-03 20:15 . Feature:add Shader class.
#include "shader.h"
Shader::Shader(const GLchar* vertexPath, const GLchar* fragmentPath)
{
//读取着色器的代码
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
//确保文件流会输出异常
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
//打开文件
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
//读取文件
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
vShaderFile.close();
fShaderFile.close();
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch(const std::ifstream::failure e)
{
std::cerr << "错误:读取文件失败,请检查文件是否存在!" << std::endl;
}
//2 编译着色器
const char *vShaderCode = vertexCode.c_str();
const char *fShaderCode = fragmentCode.c_str();
unsigned int vertex, fragment;
int success;
char infoLog[512];
//顶点着色器
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertex, 512, NULL, infoLog);
std::cout << "编译顶点着色器失败,错误信息:" << infoLog << std::endl;
}
//片元着色器
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragment, 512, NULL, infoLog);
std::cout << "编译片元着色器失败,错误信息:" << infoLog << std::endl;
}
// //着色器程序
// ID = glad_glCreateProgram();
// glAttachShader(ID, vertex);
// glAttachShader(ID, fragment);
// glLinkProgram(ID);
// glGetProgramiv(ID, GL_LINK_STATUS, &success);
// if (!success)
// {
// glad_glGetProgramInfoLog(ID, 512, NULL, infoLog);
// std::cout << "编译片元着色器失败,错误信息:" << infoLog << std::endl;
// }
//链接着色器
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
glGetProgramiv(ID, GL_LINK_STATUS, &success);
if (!success)
{
glad_glGetProgramInfoLog(ID, 512, NULL, infoLog);
std::cout << "链接着色器失败,错误信息:" << infoLog << std::endl;
}
//删除着色器
glDeleteShader(vertex);
glDeleteShader(fragment);
}
//使用着色器
void Shader::use()
{
glUseProgram(ID);
}
//设置uniform变量
void Shader::setBool(const std::string& name, bool value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
void Shader::setInt(const std::string& name, int value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
void Shader::setFloat(const std::string& name, float value) const
{
glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化