PART ONE
codes.cpp
#include <iostream>
#include <GL/freeglut.h>
using namespace std;
#define width 150
#define height 150
GLubyte green[height][width][4];
void initGreen()
{
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
green[y][x][0] = 0;
green[y][x][1] = 255;
green[y][x][2] = 0;
green[y][x][3] = 255;
}
}
}
void grab(GLint w, GLint h)
{
GLubyte* image;
GLint dataLength = w * 4 * h; //四通道
image = (GLubyte*)malloc(dataLength);// 分配CPU内存
if (image == 0) {
exit(0);
}
else {
//将GPU缓存数据四通道解包存到CPU内存
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glReadPixels(0, 0, w, h, GL_BGR_EXT, GL_UNSIGNED_BYTE, image);
}
//打开"rb"文件 获取文件头
GLubyte BMP_Head[54];
FILE* rbFile;
rbFile = fopen("test.bmp", "rb");
if (rbFile == 0) {
exit(0);
}
else {
fread(BMP_Head, sizeof(BMP_Head), 1, rbFile);
fclose(rbFile);
}
//打开"wb"文件
FILE* wbFile;
wbFile = fopen("grab.bmp", "wb");
if (wbFile == 0) {
exit(0);
}
else {
// 写入文件头
fwrite(BMP_Head, sizeof(BMP_Head), 1, rbFile);
//寻址到0x0012 写入文件大小
fseek(wbFile, 0x0012, SEEK_SET);
fwrite(&w, sizeof(w), 1, wbFile);
fwrite(&h, sizeof(h), 1, wbFile);
//寻址到0x0012 写入文件数据
fseek(wbFile, 0, SEEK_END);
fwrite(image, dataLength, 1, wbFile);
//文件生成结束
fclose(wbFile);
}
free(image);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutCreateWindow("glFlush");
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glDrawBuffer(GL_FRONT);
initGreen();
glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, green);
glReadBuffer(GL_BACK);
grab(600, 600);
glFlush();
glutMainLoop();
return 0;
}
PART TWO
代码分析
1、在上一讲的基础上,在mian()函数中调用glFlush()函数,GL_FRONT显示到窗口,GL_BACK被grab到”grab.bmp"。
2、调用glFlush()前,UNPACK-BUFFER被glReadBuffer()设置为GL_BACK,但glFlush()并没有将GL_BACK冲入GL_FRONT用于显示。
3、DOUBLE-BUFFER下, glFlush()实际作用于GL_FRONT。