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;
}
}
}
GLubyte blue[height][width][4];
void initBlue()
{
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
blue[y][x][0] = 0;
blue[y][x][1] = 0;
blue[y][x][2] = 255;
blue[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);
}
void DOUBLE_BUFFER()
{
glClearColor(1, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
//glDrawBuffer(GL_BACK);
initGreen();
glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, green);
glDrawBuffer(GL_FRONT);
initBlue();
glDrawPixels(width / 2, height / 2, GL_RGBA, GL_UNSIGNED_BYTE, blue);
glReadBuffer(GL_FRONT);
grab(1500, 900);
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutCreateWindow("glReadBuffer");
glutDisplayFunc(DOUBLE_BUFFER);
glutMainLoop();
return 0;
}
PART TWO
代码分析
1、通过glReadBuffer()将UNPACK_BUFFER更改为GL_FRONT,观察窗口和grab的结果发现:
(1)grab的是GL_FRONT。
(2)写入SCREEN的是GL_FRONT。
2、grab的是最近的UNPACK_BUFFER。