currently, I am trying to read back the data I transfer to texture in OpenGL. However, I do not receive the correct result. Where do I wrong?
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
const int SCR_WIDTH = 600;
const int SCR_HEIGHT = 600;
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
int texSize = 2;
const int Size = texSize*texSize*4;
float *data = new float[Size];
float *result = new float[Size];
for(int i=0;i<Size;i++){
data[i] = i + 1.0;
}
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glEnable(GL_TEXTURE_2D);
GLuint fbo;
glGenFramebuffers(1,&fbo);
glBindFramebuffer(GL_FRAMEBUFFER,fbo);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
GLuint text;
glGenTextures(1,&text);
glBindTexture(GL_TEXTURE_2D,text);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexImage2D(GL_TEXTURE_2D,0, GL_RGBA, texSize, texSize, 0,GL_RGBA,GL_FLOAT,data);
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,text, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glReadPixels(0, 0, texSize, texSize,GL_RGBA,GL_FLOAT,result);
std::cout<<"Data before roundtrip:\n";
for (int i=0; i<texSize*texSize*4; i++)
std::cout<<"\n"<<data[i];
std::cout<<"\nData after roundtrip:\n";
for (int i=0; i<texSize*texSize*4; i++)
std::cout<<"\n"<<result[i];
// clean up
free(data);
free(result);
glDeleteFramebuffers (1,&fbo);
glDeleteTextures (1,&text);
glfwTerminate();
return 0;
}
Here is the result:
Data before roundtrip:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Data after roundtrip:
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
This is not the result I expected. I expected both data and result are the same
I have looked it up on the internet but still no result or explanation for this.