textfile.h内容:
char *textFileRead(char *fn);
textfile.cpp内容:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *textFileRead(char *fn)
{
FILE *fp;
char *content = NULL;
int count = 0;
if (fn != NULL)
{
fp = fopen(fn, "rt");
if (fp != NULL)
{
fseek(fp, 0, SEEK_END);
count =ftell(fp);
rewind(fp);
if (count > 0)
{
content = (char *)malloc(sizeof(char)*(count + 1));
count = fread(content, sizeof(char), count, fp);
content[count] = '\0';
}
fclose(fp);
}
}
return content;
}
main.cpp内容:
#include<stdio.h>
#include<stdlib.h>
#include<GL/glew.h>
#include<GL/glut.h>
#include "textfile.h"
#pragma comment(lib,"opengl32.lib")
#pragma comment(lib,"glut32.lib")
#pragma comment(lib,"glew32.lib")
GLuint f, p;//片源着色器,着色器程序
void RenderScene()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0.0, 0.0, 5.0,
0.0, 0.0, -1.0,
0.0, 1.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glutSolidTeapot(1);
//glFlush();//刷新缓存
glutSwapBuffers();
}
void changeSize(int w,int h)
{
if (h == 0)
h = 1;
float ratio = 1.0*w / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(45, ratio, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void keys(unsigned char key, int x, int y)
{
if (key == 27)//Esc
exit (0);
}
void setShaders()
{
//创建着色器
f = glCreateShader(GL_FRAGMENT_SHADER);
char *fs;
fs = textFileRead("minimal.frag");
const char *ff = fs;
glShaderSource(f, 1, &ff, NULL);
free(fs);
glCompileShader(f);
p = glCreateProgram();
glAttachShader(p, f);
glLinkProgram(p);
glUseProgram(p);
}
int main(int argc,char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA| GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowPosition(100, 100);
glutInitWindowSize(400, 400);
glutCreateWindow("片源着色器");
glutDisplayFunc(RenderScene);
glutIdleFunc(RenderScene);
glutReshapeFunc(changeSize);
glutKeyboardFunc(keys);
glEnable(GL_DEPTH_TEST);
glClearColor(1.0, 1.0, 1.0, 1.0);
GLenum err=glewInit();
if (GLEW_OK != err)
{
printf("Error:%s\n", glewGetErrorString(err));
exit(1);
}
setShaders();
glutMainLoop();
return 0;
}
minimal.frag内容:
void main()
{
gl_FragColor=vec4(0.5,0.5,0.8,1.0);
}