LoadShader辅助函数

加载shader

superbible 中采用将 shader 的source 写在数组里面的方式加载,每次都要在末尾加 和前后的"" ,比较麻烦。

写一个辅助函数来从文件中读取

#ifndef _LOAD_H
#define _LOAD_H
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <sb6.h>
const int BUFFER_SIZE = 4096;
void LoadShader(const char *file, GLchar *& arg) {
	std::ifstream read_file;
	std::string result;
	read_file.open(file);
	if (!read_file){
		return;
	}
	std::string line;
	while (std::getline(read_file, line)) {
		for (std::string::iterator i = line.begin(); i != line.end(); i++) {
			result.push_back(*i);
		}
		result.push_back('
');
	}
	arg = new GLchar[BUFFER_SIZE];	
	memcpy(arg, result.c_str(), result.size());
	arg[result.size()] = '';
}
#endif //load.h 

注意事项

  • 需要给arg创建一个缓冲区

  • memcpy复制之后注意要给末尾加上'',这样才可以使之成为合法的字符串

  • 调用中注意加个取地址符

GLchar* vertex_shader_source;
LoadShader("vertex.vert",vertex_shader_source);
glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
原文地址:https://www.cnblogs.com/gaoduan/p/4532094.html