3D Computer Grapihcs Using OpenGL - 08 Text File Shaders
2024-09-05 19:58:31
使用之前的方法写Shader是一件很痛苦的事情,把Shader代码直接卸载C++文件中,需要使用很多引号来包裹,既不美观也不方便。
我们这节的目的是使用纯文本文件保存Shader。
首先在工程中创建两个文件,分别命名为VertexShaderCode.glsl 和 FragmentShaderCode.glsl,后缀名可以自己随意指定,不一定非要是glsl。
然后把上节的Shader代码拷贝到两个文件中去。
VertexShaderCode.glsl
#version in layout(location=) vec2 position;
in layout(location=) vec3 vertexColor; out vec3 passingColor; void main()
{
gl_Position= vec4(position,0.0,1.0);
passingColor= vertexColor;
}
FragmentShaderCode.glsl
#version in vec3 passingColor;
out vec4 finalColor; void main()
{
finalColor = vec4(passingColor,1.0);
}
另外在MyGlWindow中添加一个函数用来读取文件
MyGlWindow.h中添加include:
#include <string>
添加成员函数声明:
std::string ReadShaderCode(const char* fileName);
MyGlWindow.cpp中添加include:
#include <iostream>
#include <fstream>
添加成员函数定义:
std::string MyGlWindow::ReadShaderCode(const char* fileName)
{
std::ifstream myInput(fileName);
if (!myInput.good())
{
std::cout << "File failed to load..." << fileName;
exit();
}
return std::string(
std::istreambuf_iterator<char>(myInput),
std::istreambuf_iterator<char>());
}
删除掉开头的两个extern声明:
//extern const char* vertexShaderCode;
//extern const char* fragmentShaderCode;
修改installShaders()函数:
void MyGlWindow::installShaders()
{
GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); std::string tmp = ReadShaderCode("VertexShaderCode.glsl");
const char* vertexShaderCode = tmp.c_str();
glShaderSource(vertexShaderID, , &vertexShaderCode, ); tmp = ReadShaderCode("FragmentShaderCode.glsl");
const char* fragmentShaderCode = tmp.c_str();
glShaderSource(fragmentShaderID, , &fragmentShaderCode, ); glCompileShader(vertexShaderID);
glCompileShader(fragmentShaderID); GLuint programID = glCreateProgram();
glAttachShader(programID, vertexShaderID);
glAttachShader(programID, fragmentShaderID); glLinkProgram(programID); glUseProgram(programID);
}
注意第6-7行,先用一个string对象存储读取到的字符串,然后使用.c_str()返回C语言风格字符串 const char*。
最新文章
- 【原】tomcat 7 启动报错:java.lang.NoSuchMethodError: javax.servlet.ServletContext.getSessionCookieConfig()Ljavax/servlet/SessionCookieConfig的解决
- UVA 1401 Remember the Word
- Android5.0资源 colorAccent,colorPrimary,colorPrimaryDark
- SQLite数据库
- jqueyr获取动态创建的元素
- [NOIP2013] 提高组 洛谷P1969 积木大赛
- HDU - 人见人爱A^B
- [JS10] 获取时间
- 简单的C#线程开发实例(隔一秒改变一下Label的Text)
- PHP生成各种验证码和Ajax验证
- BZOJ 2588: Spoj 10628. Count on a tree 主席树+lca
- Google搜索解析
- Linux系统开发之路 - 下
- 浅谈cookie与session的区别
- MIME Type和Content-Type
- iOS - OC - 字典快速遍历
- 如何用Mockplus快速做一个手风琴菜单?
- MPU6050学习笔记(电源管理器1、2)
- ES6躬行记(22)——Promise
- 卸载oracle 10g
热门文章
- mybatis使用map传递多参数报错:A query was run and no Result Maps were found for the Mapped Statement
- Linux yum 命令篇
- 前端导出excel文件
- Python 入门之Python基础知识
- jquery中的插件EChars的使用
- Scrapy 教程(一)-安装与入门
- 工作日记之查看Linux系统里面的启动频率2017_02_07
- Find The Multiple (水题)
- JavaScript生成简单数字验证码
- CPM、CPC、CPA、PFP、CPS、CPL、CPR等广告术语是什么意思