shader放到文件中比較容易讀取却音,這里實(shí)現(xiàn)一個(gè)簡(jiǎn)單的讀取類
//
// Shader.hpp
//
#ifndef Shader_hpp
#define Shader_hpp
#include <stdio.h>
#ifndef SHADER_H
#define SHADER_H
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <OpenGL/gl3.h>
//#include <OpenGL/glew.h> // 包含glew來(lái)獲取所有的必須OpenGL頭文件
class Shader
{
public:
// 程序ID
GLuint Program;
// 構(gòu)造器讀取并構(gòu)建著色器
Shader(const GLchar* vertexPath, const GLchar* fragmentPath);
// 使用程序
void Use();
};
#endif
#endif /* Shader_hpp */
//
// Shader.cpp
//
#include "Shader.hpp"
Shader::Shader(const GLchar* vertexPath, const GLchar* fragmentPath)
{
// 1. 從文件路徑中獲取頂點(diǎn)/片段著色器
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
// 保證ifstream對(duì)象可以拋出異常:
vShaderFile.exceptions(std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::badbit);
try
{
// 打開文件
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
// 讀取文件的緩沖內(nèi)容到流中
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// 關(guān)閉文件
vShaderFile.close();
fShaderFile.close();
// 轉(zhuǎn)換流至GLchar數(shù)組
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch(std::ifstream::failure e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
}
const GLchar* vShaderCode = vertexCode.c_str();
const GLchar* fShaderCode = fragmentCode.c_str();
// 2. 編譯著色器
GLuint vertex, fragment;
GLint success;
GLchar infoLog[512];
// 頂點(diǎn)著色器
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
// 打印編譯錯(cuò)誤(如果有的話)
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertex, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
};
// 片段著色器
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
// 打印編譯錯(cuò)誤(如果有的話)
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(fragment, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
};
// 著色器程序
this->Program = glCreateProgram();
glAttachShader(this->Program, vertex);
glAttachShader(this->Program, fragment);
glLinkProgram(this->Program);
// 打印連接錯(cuò)誤(如果有的話)
glGetProgramiv(this->Program, GL_LINK_STATUS, &success);
if(!success)
{
glGetProgramInfoLog(this->Program, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
// 刪除著色器缸浦,它們已經(jīng)鏈接到我們的程序中了桃纯,已經(jīng)不再需要了
glDeleteShader(vertex);
glDeleteShader(fragment);
}
void Shader::Use()
{
glUseProgram(this->Program);
}
shader編譯成功后乓序,Use()方法可以隨時(shí)調(diào)用批狱。