Using the previous method to write shader is a very painful thing, the shader code directly uninstall C + + files, need to use a lot of quotation marks to wrap, neither beautiful nor convenient.
Our purpose in this section is to save shader using plain text files.
First in the project to create two files, respectively named VERTEXSHADERCODE.GLSL and FRAGMENTSHADERCODE.GLSL, suffix can be assigned to their own discretion, not necessarily GLSL.
Then copy the shader code from the previous section to two files.
Vertexshadercode.glsl
1#version430 2 3 inchLayout (location=0) VEC2 position; 4 inchLayout (location=1) vec3 Vertexcolor;5 6 outVEC3 Passingcolor; 7 8 voidMain ()9 { TenGl_position= Vec4 (Position,0.0,1.0); OnePassingcolor=Vertexcolor; A}
Fragmentshadercode.glsl
1#version430 2 3 inchVEC3 Passingcolor; 4 outVEC4 Finalcolor; 5 6 7 voidMain ()8 { 9Finalcolor = VEC4 (Passingcolor,1.0);Ten}
In addition, a function is added to the Myglwindow to read the file
Add include in MyGlWindow.h:
#include <string>
To add a member function declaration:
1 std::string readshadercode (constChar* fileName);
Add include in MyGlWindow.cpp:
#include <iostream><fstream>
To add a member function definition:
1STD::stringMyglwindow::readshadercode (Const Char*fileName)2 {3 std::ifstream myinput (fileName);4 if(!Myinput.good ())5 {6Std::cout <<"File failed to load ..."<<FileName;7Exit1);8 }9 returnSTD::string(Tenstd::istreambuf_iterator<Char>(myinput), Onestd::istreambuf_iterator<Char>()); A}
Delete the first two extern declarations:
// extern const char* Vertexshadercode; // extern const char* Fragmentshadercode;
Modify the Installshaders () function:
1 voidmyglwindow::installshaders ()2 {3Gluint Vertexshaderid =Glcreateshader (gl_vertex_shader);4Gluint Fragmentshaderid =Glcreateshader (gl_fragment_shader);5 6STD::stringTMP = Readshadercode ("VERTEXSHADERCODE.GLSL");7 Const Char* Vertexshadercode =tmp.c_str ();8Glshadersource (Vertexshaderid,1, &vertexshadercode,0);9 TenTMP = Readshadercode ("FRAGMENTSHADERCODE.GLSL"); One Const Char* Fragmentshadercode =Tmp.c_str (); AGlshadersource (Fragmentshaderid,1, &fragmentshadercode,0); - - Glcompileshader (Vertexshaderid); the Glcompileshader (Fragmentshaderid); - -Gluint ProgramID =Glcreateprogram (); - Glattachshader (ProgramID, Vertexshaderid); + Glattachshader (ProgramID, Fragmentshaderid); - + Gllinkprogram (programid); A at Gluseprogram (programid); -}
Note that the 第6-7 line first uses a string object to store the read string, and then uses. C_STR () to return the C-style string const char*.
3D computer Grapihcs Using OpenGL-08 Text File Shaders