OpenGL Cubemap : Writing to mipmap - c++

[Objectives] I need to write to a CubeMap's specific mipmap level in OpenGL 4+. Each mipmap levels is blurrier the deeper the level is.
[Problem] The problem is that I have the same image over all mipmap levels if I write only on level 0, and nothing at all if I try to write only on other mipmap level.
[Update] I'm pretty sure the problem is textureLod always clamp to the base LOD 0. Whatever mipmap level I try to get through it, it returns the base LOD.
Here is my cubemap generation (I'm trying to have 6 mipmap levels, counting the base):
GLuint PreFilteredEnvTex;
glGenTextures(1, &PreFilteredEnvTex);
glBindTexture(GL_TEXTURE_CUBE_MAP, PreFilteredEnvTex);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, 5);
for (int i = 0; i < 6; ++i)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 512, 512, 0, GL_RGB, GL_FLOAT, 0);
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
Utils::checkGlError("Generate PreFilteredEnvMap");
And here an example of my attempt to write to each mipmap levels :
//Compute pre filtered environnement maps
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, fboManager["fx"]);
glViewport(0, 0, screenWidth, screenHeight);
glClear(GL_COLOR_BUFFER_BIT);
const int MIPMAPLEVELS = 6;
const int MIPMAPBASELEVELSIZE = 512;
int MipMapTextureSize;
glBindVertexArray(vaoManager["cube"]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, skybox->texture_id);
Shader* PreEnvFilter = shaderManager["PreEnvFilter"];
PreEnvFilter->use();
glm::vec3 EyePosition = glm::vec3(0.f);
// Light space matrices
glm::mat4 CubeMapProjection = glm::perspective(glm::radians(90.f), 1.f, 1.f, 100.f);
std::vector<glm::mat4> worldToLight;
worldToLight.push_back(CubeMapProjection * glm::lookAt(EyePosition, EyePosition + glm::vec3(1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
worldToLight.push_back(CubeMapProjection * glm::lookAt(EyePosition, EyePosition + glm::vec3(-1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
worldToLight.push_back(CubeMapProjection * glm::lookAt(EyePosition, EyePosition + glm::vec3(0.0, 1.0, 0.0), glm::vec3(0.0, 0.0, 1.0)));
worldToLight.push_back(CubeMapProjection * glm::lookAt(EyePosition, EyePosition + glm::vec3(0.0, -1.0, 0.0), glm::vec3(0.0, 0.0, -1.0)));
worldToLight.push_back(CubeMapProjection * glm::lookAt(EyePosition, EyePosition + glm::vec3(0.0, 0.0, 1.0), glm::vec3(0.0, -1.0, 0.0)));
worldToLight.push_back(CubeMapProjection * glm::lookAt(EyePosition, EyePosition + glm::vec3(0.0, 0.0, -1.0), glm::vec3(0.0, -1.0, 0.0)));
for (GLuint i = 0; i < 6; ++i)
PreEnvFilter->SetMatrix4(("ViewMatrix[" + to_string(i) + "]").c_str(), worldToLight[i]);
PreEnvFilter->SetInt("EnvMapSampler", 0);
PreEnvFilter->SetMatrix4("Model", glm::mat4());
//For each faces compute all mipmaps levels
for (unsigned int j = 0; j < MIPMAPLEVELS; ++j)
{
//For each mipmap level, render the filtered environnement in it
MipMapTextureSize = std::max(1, MIPMAPBASELEVELSIZE / (1 << j));
glViewport(0, 0, MipMapTextureSize, MipMapTextureSize);
//glViewport(0, 0, MIPMAPBASELEVELSIZE, MIPMAPBASELEVELSIZE);
float roughness = (j + 0.5f) / MIPMAPLEVELS;
PreEnvFilter->SetFloat("Roughness", roughness);
//Bind to the current buffer
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, PreFilteredEnvTex, j);
glDrawElements(GL_TRIANGLES, 12 * 3, GL_UNSIGNED_INT, (void*)0);
}
PreEnvFilter->unuse();
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
Utils::checkGlError("Initialize PreFilteredEnvMap");
I'm sure my shader is working, because if I'm looping over all mipmap levels and drawing only to the base level I have a good looking result :
The result if I'm only writing to level 0 for all mipmap levels
The cubemap is printed with the following fragment shader (TexCoords is modified according to the face I want to draw) :
#version 430
uniform int MipMapLevel;
uniform samplerCube CubeMap;
in vec3 TexCoords;
out vec4 Color;
void main()
{
Color = textureLod(CubeMap, TexCoords, MipMapLevel);
}
And if I'm writing to all mipmap levels, I have the same image on all mipmap levels (actually if I write only to level 0 I have the same result on all mipmap levels as well )
Same result, different mipmap levels
My conclusion is as followed :
My mipmap generation is not good, but I've read the specs and glGenerateMipmap should have done the job
I have a problem when trying to bind the mipmap level throught glFramebufferTexture, but once again it doesn't seems wrong to me
My shader to draw the cubemap is not working as I think it should ? I've never used textureLod before, but as far as I know, I am using it right here, right ?
If someone as already done something similar, I would really appreciate some help ! After all the time I spent on it, I'm still not able to do this simple thing in OpenGL when I did it whithout problems in DX11 :(
P.S : OpenGL does not report any errors

After trying almost everything, I've finally make it works by generating my cubemap as follow :
GLuint PreFilteredEnvTex;
glGenTextures(1, &PreFilteredEnvTex);
glBindTexture(GL_TEXTURE_CUBE_MAP, PreFilteredEnvTex);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, 5);
for (int i = 0; i < 6; ++i)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 512, 512, 0, GL_RGB, GL_FLOAT, 0);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
I've change the min filter to GL_LINEAR_MIPMAP_LINEAR and call glGenerateMipmap at the end, instead of doing like in this link.
Thanks for your interest :)

Related

Compute Shader only writes to one pixel

I'm trying to build a compute shader to create a noise texture to use as a height map. gl_GlobalInvocationID is always (0, 0) from my debugging, and I'm not sure why. The good news is that something is being written inside of the compute shader, since I am able to retrieve an all-red texture, but I cannot write more than a solid color. I tried moving around the image binding as well as the dispatching command of the compute shader, but I haven't had any luck so far.
Not pictured is my shader program initializations, but no errors are being generated from compilation or linking, so I don't think the issue lies there. I believe that the image and texture formats are consistent and correct as well.
Thank you for any insight you could provide to this issue!
Compute Shader:
#version 430
layout(local_size_x = 1, local_size_y = 1) in;
layout(rgba32f, binding = 0) uniform image2D noiseImage;
void main() {
vec4 color = vec4(0.0, 0.0, 0.0, 1.0);
ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
// Debugging
if (pixel.x == 0 && pixel.y == 0) {
color = vec4(1.0, 0.0, 0.0, 1.0);
} else {
color = vec4(0.0, 1.0, 0.0, 1.0);
}
imageStore(noiseImage, pixel, color);
}
OpenGL Code:
width = 512;
height = 512;
noiseTexture = 0;
// Snipped (runs once)
glGenTextures(1, &noiseTexture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, noiseTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
glBindImageTexture(0, noiseTexture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
// Snipped (runs every frame)
glUseProgram(computeShader);
glDispatchCompute(width, height, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, noiseTexture);
glUseProgram(vertex/fragment);
render();
Hmm, so you're rendering the resulting image afterwards? Do you perhaps need the GL_TEXTURE_FETCH_BARRIER_BIT barrier too, so that the results of the compute shader rendering are visible to the texture fetch?

OpenGL - Texture not displayed on whole defined area

I am trying the texture mapping feature of OpenGL and the texture is displayed on the screen but not on the area that I set.
The area is a quad with 100.0 length and the texture is displayed only on the bottom.
When using GL_RGB in glTexImage2D, only one third of the quad is filled and when I change it to GL_RGBA, it becomes one quarter of the quad.
Main parameters declaration:
BYTE* m_pBMPBuffer;
int m_iWidth;
int m_iHeight;
GLuint m_uiTexture;
Code for setting up the texture mapping:
void CTextureMappingView::InitializeTexture()
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &m_uiTexture);
glBindTexture(GL_TEXTURE_2D, m_uiTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_iWidth, m_iHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, m_pBMPBuffer);
}
Buffer Initialization:
m_iWidth = 64;
m_iHeight = 64;
m_pBMPBuffer = new BYTE[m_iWidth * m_iHeight * 3];
for (int i = 0 ; i < m_iWidth * m_iHeight ; i += 3)
{
m_pBMPBuffer[i] = 255;
m_pBMPBuffer[i + 1] = 0;
m_pBMPBuffer[i + 2] = 0;
}
Rendering:
void CTextureMappingView::RenderScene()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(XAngle, 1.0f, 0.0f, 0.0f);
glRotatef(YAngle, 0.0f, 1.0f, 0.0f);
glPushMatrix();
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBindTexture(GL_TEXTURE_2D, m_uiTexture);
glBegin(GL_POLYGON);
glTexCoord2d(0.0, 0.0);
glVertex3d(0.0, 0.0, 0.0);
glTexCoord2d(0.0, 1.0);
glVertex3d(0.0, 100.0, 0.0);
glTexCoord2d(1.0, 1.0);
glVertex3d(100.0, 100.0, 0.0);
glTexCoord2d(1.0, 0.0);
glVertex3d(100.0, 0.0, 0.0);
glEnd();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
Current result:
You only initialize a third of your texture:
for (int i = 0 ; i < m_iWidth * m_iHeight ; i += 3)
You should go up to m_iWidth * m_iHeight * 3 since that's what you allocated.

opengl - Only one texture displaying

I have been trying draw a hut (as a cylinder with a cone on top) and add a brick txture to the wall and a roof-tile texture to the roof. However, I am only getting the first texture that I load (the bricks).
Here is my code (Please note that I have tried to switch between textures using glActiveTexture):
void drawCylinder()
{
int width, height;
unsigned char * data_for_wall = SOIL_load_image("./bricks.jpg", &width, &height, NULL, 0);
glDisable(GL_LIGHTING);
glGenTextures( 2, textures );
glActiveTexture(GL_TEXTURE0);
glEnable( GL_TEXTURE_2D );
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Generate mipmaps, by the way.
glGenerateMipmap(GL_TEXTURE_2D);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, width, height, GL_RGB, GL_UNSIGNED_BYTE, data_for_wall);
for(float theta = 0.0; theta <= 360.0; theta += 10.0 )
{
//colors[k] = color4(0.69, 0.35, 0.0, 1.0); //This color is brown.
tex_coords[global_index]=vec2(theta*DegreesToRadians, 0.0);
float x = 0.15*sin(theta*DegreesToRadians);
float y = 0.15*cos(theta*DegreesToRadians);
points[global_index] = Translate(0.6, 0.0, 0.35)*point4(x, 0.0, y, 1.0);
// This is the
// bottom of the cylinder. The points are plotted in a full circle. The first three numbers are the x,y and z values
// respectively. The last number (ie. 1.0) is not important - it just converts to homogeneous coordinates.
++global_index;
tex_coords[global_index] = vec2(theta*DegreesToRadians, 0.25);
points[global_index] = Translate(0.6, 0.0, 0.35)*point4(x, 0.25, y, 1.0);
// This is the
// top of the cylinder
++global_index;
}
}
//The roof of the hut
void drawCone()
{
int width, height;
unsigned char * data_for_roof = SOIL_load_image("./roof_tiles.jpg", &width, &height, NULL, 0);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE1);
glBindTexture( GL_TEXTURE_2D, textures[1] );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Generate mipmaps, by the way.
glGenerateMipmap(GL_TEXTURE_2D);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, width, height, GL_RGB, GL_UNSIGNED_BYTE, data_for_roof);
int index = 0;
int l = 0;
for(float theta = 0.0; theta <= 360.0; theta += 10.0)
{
tex_coords[global_index]=vec2(theta*DegreesToRadians, 0.25);
points[global_index] = Translate(0.6, 0.0, 0.35)*point4(0.0, 0.5, 0.0, 1.0); // This is the top of the cone.
++global_index;
tex_coords[global_index] = vec2(theta*DegreesToRadians, 0.5);
points[global_index] = Translate(0.6, 0.0, 0.35)*point4(0.25*sin(theta*DegreesToRadians), 0.25, 0.25*cos(theta*DegreesToRadians), 1.0);
// This is the
// bottom of the cone.
++global_index;
}
}
And here is the display function:
void
display( void )
{
mat4 mv = Translate(0.0, -0.065, -rad)*RotateX(Theta[0])*RotateY(Theta[1])*RotateZ(Theta[2]);
mat4 p = Perspective(10.0, aspectRatio, zNear, zFar);
glUniformMatrix4fv( matrix_loc, 1, GL_TRUE, mv );
glUniformMatrix4fv( projection_loc, 1, GL_TRUE, p );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glUniform3fv( theta, 1, Theta );
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glDrawArrays( GL_TRIANGLE_STRIP, 0, 74 );
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures[1]);
glDrawArrays( GL_TRIANGLE_STRIP, 74, 74);
glutSwapBuffers();
}
I am not sure if it is important to include the fragment shader but I will do it anyways:
#version 150
in vec2 texCoord;
out vec4 fColor;
uniform sampler2D texture;
void main()
{
fColor = texture2D( texture, texCoord );
}
I have been struggling for hours to get this right. Does anyone know what I have done wrong?
glActiveTexture() is used to set the texture slot that you are binding a texture to when multi-texturing (rendering more than one texture in a single pass). For example, you might have one texture for a texture map, another for normal map and so on.
However, you are not multi-texturing, because you render the walls and the cone in separate passes (i.e. two separate calls to glDrawArrays()), and your shader only uses a single texture per pass. So within each pass you are only rendering a single texture, which will be in slot 0.
If you set the active texture to GL_TEXTURE1 and then call glBindTexture() then the texture will be bound to slot 1, and slot 0 will remain unchanged.
So, set the active texture slot to 0 both times. Remove this line from your display() function:
glActiveTexture(GL_TEXTURE1);

OpenGL Texture Mapping Not mapping

I am creating a flat surface and applying a texture for it. But for some reason the texture is not getting applied properly. I am getting something like this.
This is the code that I am using (I have a class for applying textures),
for(int i = 0; i < 512; i++) {
for(int j = 0; j < 512; j++) {
int c = ((((i&0x8)==0)^(((j&0x8))==0)))*255;
checkImage[i][j][0] = (GLubyte) c;
checkImage[i][j][1] = (GLubyte) c;
checkImage[i][j][2] = (GLubyte) c;
checkImage[i][j][3] = (GLubyte)255;
//cout<<"("<<(int)dataForPixel.rgbtRed<<","<<(int)dataForPixel.rgbtGreen<<","<<(int)dataForPixel.rgbtBlue<<")";
}
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
imageX,
imageY,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
checkImage
);
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, texName);
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0); glVertex3d(-100, -100, 0.0);
glTexCoord2d(0.0, 1.0); glVertex3d(-100, 100, 0.0);
glTexCoord2d(1.0, 1.0); glVertex3d( 100, 100, 0.0);
glTexCoord2d(1.0, 0.0); glVertex3d( 100, -100, 0.0);
glEnd();
The image is a 512 x 512 image.
Why is the texture not applying properly.
UPDATE:
The c value is just for producing a chess board pattern which consists of squares of 8 pixels width and height of alternating black and white.
Ok I found out the problem. Seems i was trying to allocate the checkImage memory dynamically but not in one go. So there were gaps in the memory which the OpenGL did not bother with.
Once I fixed it to allocate the memory as one big chunk it worked.

texture(...) function always returns 0

I have been trying to get shadow mapping to work for quite some time now and I am still no closer than I was a month ago. I am beginning to think it may be an issue with my GL drivers because I haven't been able to see any side effects such as "light acne."
I was told to start using a sampler2DShadow instead of a sampler2D and this is what I did. However, whenever I sample the map using texture(...) the result is always 0. Why would this be happening?
I have tried entering manual depthCoord values and I still get 0. Could this be a result of the shadowMap itself (i.e the way it has been setup?) or is it a driver issue?
Framebuffer Setup
FramebufferName = 0;
glGenFramebuffers(1, &FramebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);
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_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT, 512, 512, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
Fragment Shader
uniform sampler2DShadow shadowMap;
in vec4 depthCoord;
void main(){
//The final color after lighting is stored as 'FinalColor'
float visibility = 1.0;
if (texture(shadowMap, depthCoord.xyz) == 0.0){
visibility = 0.1;
}
color = vec4(finalColor.rgb * visibility, 1.0);
}
Rendering Code
glm::vec3 lightInvDir = glm::vec3(0,-10,-10);
glm::mat4 depthProjectionMatrix = glm::ortho<float>(-10,10,-10,10,-10,20);
glm::mat4 depthViewMatrix = glm::lookAt(lightInvDir, glm::vec3(0,0,0), glm::vec3(0,1,0));
glm::mat4 depthModelMatrix = glm::mat4(1.0);
glm::mat4 depthMVP = depthProjectionMatrix * depthViewMatrix * depthModelMatrix;
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
glm::mat4 depthBiasMVP = biasMatrix*depthMVP;
/* Shadow */
subShader->useShader();
glViewport(0,0,512,512);
glUniformMatrix4fv(glGetUniformLocation(subShader->getShader(),"depthMVP"), 1, GL_FALSE, &depthMVP[0][0]);
glBindFramebuffer(GL_FRAMEBUFFER, Shadows::framebuffer());
renderBuffer(objBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
/* Clear */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Shader */
objShader->useShader();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, Shadows::shadowmap());
glUniform1f(glGetUniformLocation(objShader->getShader(),"shadowMap"),0);
/* Render Scene */
glUniformMatrix4fv(glGetUniformLocation(objShader->getShader(),"depthBiasMVP"), 1, GL_FALSE, &depthBiasMVP[0][0]);
glViewport(0,0,640,480);
glUniform1f(glGetUniformLocation(objShader->getShader(),"renderingPass"),1.0);
renderBuffer(objBuffer);
The majority of this code has been learned from sites such as (http://www.opengl-tutorial.org/) with modifications based on (http://www.fabiensanglard.net/shadowmapping/index.php) and the red book.