glsl,opengl-3 , Modern GLSL ( opengl 3+ ) : Implementing phong effect correctly;

Modern GLSL ( opengl 3+ ) : Implementing phong effect correctly;


Tag: glsl,opengl-3

I am implementing a basic phong lighting GLSL shader; I have looked up some things on the internet, and found that the phong effect was created by adding an ambient, diffuse, and specular layer on the object (see image below, from tom dalling's site); problem is I have seen a lot of examples, and none of them really suits my GLSL set-up. Can any of you give me a code example of the correct way to implement the phong effect which would fit my GLSL set-up ? :

PS : This question could be put on hold because of the fact that it may be based on user opinion : In my mind, it is not, because I would like to know the most effective, and better way of implementing it.

Here is my vertex shader :

#version 120

uniform mat4 modelView;
uniform mat4 MVP;
uniform float time;

attribute vec3 position;
attribute vec2 texCoord;
attribute vec3 normal;

varying vec3 position0;
varying vec2 texCoord0;
varying vec3 normal0;
varying mat4 modelView0;

void main()
    //Updating varyings...
    position0 = position;
    texCoord0 = texCoord;
    normal0 = (MVP * vec4(normal, 0.0)).xyz;
    modelView0 = modelView;

    //set position
    gl_Position = MVP *  vec4(position, 1.0);

and my fragment shader :

#version 120

varying vec3 position0;
varying vec2 texCoord0;
varying vec3 normal0;
varying mat4 modelView0;

uniform sampler2D diffuse;

void main()

    vec4 surfaceColor = texture2D(diffuse, texCoord0);
    gl_FragColor = (texture2D(diffuse, texCoord0))
        * clamp(dot(-vec3(0.0, 0.5, 0.5), normal0), 0, 1.0);


enter image description here


try this:

void main() 
    vec4 texread = texture2D(diffuse, texCoord0);
    vec3 normal = normalize(normal0);

    vec3 material_kd = vec3(1.0,1.0,1.0);
    vec3 material_ks = vec3(1.0,1.0,1.0);
    vec3 material_ka = vec3(0.2,0.2,0.2);
    vec3 material_ke = vec3(0.0,0.0,0.0);
    float material_shininess = 60;

    vec3 lightpos = vec3(0.0,10.0,5.0);
    vec3 lightcolor = vec3(1.0,1.0,1.0);

    vec3 lightdir = normalize(lightpos - worldPosition);

    float shade = clamp(dot(lightdir, normal), 0.0, 1.0); 
    vec3 toWorldpos = normalize((worldPosition) - u_eyePos); 
    vec3 reflectDir = reflect( toWorldpos, normal ); 

    vec4 specular = vec4(pow(clamp(dot(lightdir, reflectDir),0.0,1.0), material_shininess) * lightcolor * material_ks, 1.0); 
    vec4 shaded = texread * vec4(material_kd, 1.0) * vec4(lightcolor , 1.0) * shade;

    vec4 ambient = texread * vec4(material_ka, 1.0);
    vec4 emission = vec4(material_ke, 1.0);

    gl_FragColor = shaded + specular + emission + ambient;


it may have some compilation errors though as i didnt run it... you may need to upload your eye position as a uniform (u_eyePos), and calculate the worldposition (worldPosition) for it to work


Scaling part of mesh in a given direction

I have a lot of cubes (ex 100) that are all part of the same mesh, and in a vertex shader I would like to scale each cube along a given axis, so it's top is moved and the cube stretched like this: Each cube has an ID, and each...

Applying glow effect to a square using glsl without texture

I've taken some same code from Android OpenGL tutorials, and I'm wondering is it possible to achieve the glowing effect seen here: using the Square implementation below? i.e without using textures? I'd like to apply this glowing effect to the entire Square i.e fill The link above uses a...

OpenGL GLSL: How to implement the concept of gradient map in photoshop using fragment shader?

This may be not the perfect question for stackoverflow but I have asked this in graphicdesign network of stackexchange but did not get any answer so posting it here. I am trying to implement gradient map of Photoshop programmatically using glsl fragment shader. Consider below shown gradient map where all...

GLSL - program link error: Slot 0 unavailable from layout location request

I'm trying to draw a textured quad copying some code from a tutorial but I'm afraid there is a problem with the shaders. Both the vertex shader and the fragment shader compilation works, but when linking the program I get the error: ERROR: Active attribute aliasing. Slot 0 unavailable for...

GLSL Error #132 Syntax error: “gl_position” parse error

I've tried my best to find the answer to this problem or any error i had made in the code, but i just couldn't find anything.. If this helps, i have a sapphire Radeon HD 6950 graphics card and it uses an AMD Radeon HD 6900 series driver. The Error...

Mesa + Linux : gl.h does not contain modern OpenGL

This is the environment I currently use: Eclipse-Luna, C++11 on Linux Mint -Rebecca. When I try to use modern OpenGL like with VAOs or VBOs I get Compiler Errors such that methods could not be resolved. For Example: GLuint VaoID; //GLuint is working glGenVertexArrays(1, &VaoID); or: GLuint VboID; glGenBuffers(1, &VboID);...

Simple GLSL Shader (Light) causes flickering

I'm trying to implement some basic lighting and shading following the tutorial over here and here. Everything is more or less working but I get some kind of strange flickering on object surfaces due to the shading. I have two images attached to show you guys how this problem looks....

Overlaying a transparent color over a Texture with GLSL

I have an image that I am loading using the Slick library, and the image renders fine without my shader active. When I use my shader to overlay a transparent color over the image the entire image is replaced by the transparent color. without the shader With the shader Vertex...

What can I use as an array index in GLSL in WebGL ?

Are there ONLY constants allowed or can I use for loop indices or any other dynamic values ?

HDR Bloom effect rendering pipeline using OpenGL/GLSL

I have integrated bloom HDR rendering using OpenGL and GLSL... At least I think! I'm not really sure about the result. I followed a tutorial from intel website: And about Gaussian blur effect I follow scrupulously all the advices concerning the performance on the following website: According to...

is early exit of loops on GPU worth doing?

We've written GLSL shader code to do ray tracing visualisation using the GPU. It seems to be pretty standard to put an early exit break in the ray marching loop, so if the light is extinguished, the loop breaks. But from what I know about GPU code, each render will...

GLSL - compressing/packing multiple 0-1 colours (var4) into a single var4 variable

I am trying to do the following in GLSL 2 es: Given a number (say 4 for example) of normalized var4 variables(RGBA) reduce their bit depth and pack the results in a single 0-1 clamped var4. This will be stored as an 8 bit (per channel) texture and later unpacked....

Shader - Simple SSS lighting issue

I am trying to create a simple subsurface scattering effect using a shader but I am facing a small issue. Look at those screenshots. The three images represents three lighting states (above surface, really close to surface, subsurface) with various lighting colors (red and blue) and always the same subsurface...

Opengl not drawing correctly using shader - issue with matrix setup/initialization?

When I render my app, I'm expecting to see a number of rectangles surrounding the edges of the window. Instead I'm seeing this .. All objects will be at z == 0.0f. If I dont render my scene using shaders, all objects show fine. So thinking it must be matrix...

Shaders in WebGL vs openGL? [closed]

I want to use shaders to use in WebGL and specifically three.js. Is there a specific version of GLSL that WebGL and three.js uses?

What is texture downsampling (downscaling) using OpenGL?

I did not found any tutorial that explains how to downscale a texture using OpenGL. For example if I have a 1024x720 texture and I want to generate downscale by the factor 1/4 how to do it? Here's a tutorial talking about downsampling. UPDATE I tried the following filtering code...

Opengl error 1281 when trying to glUseProgram

Any ideas how I could debug this opengl error further? 1281 I'm loading source from files, compiling, linking and then trying to check for errors after glUseProgram In my object's draw method ..; // true gl2.glUseProgram(shaderProgram); int error; while ((error = gl2.glGetError()) != GL2.GL_NO_ERROR) { throw new RuntimeException("glUseProgram" +...

Deferred Shading - Multiple Lights (OpenGL/GLSL)

I'm working on a deferred shading program and now I have to set up 50 different lights in the scene. To do so, I'm randomly generating its attributes (position, diffuse color, specular color) with this piece of code: void FBORender::BuildLights() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dis(0.0, 0.1); for (int...

OpenGL: Strange bahaviour of VBO deletion?

I am getting a strange issue in Vertex Buffer Object (VBO). I created a class that includes VBO creation and deletion. I delete all the VBOs (with glDeleteBuffers()) in the destructor of the class. Now I created 2 OpenGL context windows each running with VBO class. Now when I close...

Bloom effect using downscaling (downsampling) technique using OpenGL/GLSL

Hello I'm trying to implement Bloom effect in my program. In fact, I've already implemented the effect using a highlight pass and a separate gaussian blur pass. Here's an example: Bright pass texture: Gaussian blur render pass (2 internal passes for this effect): And finally the final pass (brightPass +...

GLSL: sampler upload only works when unused sampler is removed

Im currently trying to implement deferred shading with framebuffers in OpenGL. The framebuffer itself works perfectly, but when I dont use all uniform samplers in the shader, one of the textures stop working. This is my fragment shader, a test demonstration of the framebuffer: #version 330 core uniform sampler2D texCoordTex;...

How to get shader version from QOpenGLShader?

I am using QT to load, compile and link OpenGL shaders. I need to perform specific operations depending on the GLSLversion used in the shader code Is it possible to recover the version from the QOpenGLShader interface without actually getting the shader source code and parsing it to detect the...

Pass data from std::vector to uniform array in glsl

I have a uniform in a shader like this: uniform vec3 origins[10]; and a std::vector in my code like this: std::vector<glm::vec3> origins; that is filled with ten glm::vec3 elements. Does anyone know how do I pass that to the shader? I thought: GLint originsLoc = glGetUniformLocation(programID, "origins"); glUniform3fv(originsLoc, 10,;...

How to blur a transparent texture in a glsl shader?

My setup: Ping-ponging RGBA FBO's, and two shaders for blurring: a horizontal and a vertical one. Imagine I want to blur a red rectangle. The blend function is as follows: _gl.blendEquationSeparate(_gl.FUNC_ADD, _gl.FUNC_ADD); _gl.blendFuncSeparate(_gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA); In my blur shaders I add several fragments like this: vec4 color = texture2D(u_image,...

GL_ARB_sparse_texture not supported

I have this code which check if GL_ARB_sparse_texture is supported: GLint ExtensionCount = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &ExtensionCount); for (GLint i = 0; i < ExtensionCount; ++i) if (std::string((char const*)glGetStringi(GL_EXTENSIONS, i)) == std::string("GL_ARB_sparse_texture")){ std::cout << "supported" << std::endl; } It prints out that it is supported. Problem is that my shader says...

Sampler3D in iOS

I have just include OpenGL ES 3.0 in my iOS app and it is working fine. I have a working shader below: #version 300 es precision mediump float; uniform sampler2D texSampler; uniform float fExposure; in vec2 fTexCoord; in vec3 fColor; out vec4 fragmentColor; void main() { fragmentColor = texture(texSampler, fTexCoord)...

Atmosphere Scattering for Earth from space and on the ground

Please provide prompt how to make the atmosphere of the Earth so that it is visible from space and from the ground (as shown in the image) a model of the earth: Earth = new THREE.Mesh(new THREE.SphereGeometry(6700,32,32),ShaderMaterialEarth); model of the cosmos: cosmos= new THREE.Mesh(new THREE.SphereGeometry(50000,32,32),ShaderMaterialCosmos); and a light source: sun...

Writing fragment shaders: cannot make sense of how the uniforms are defined

I'm trying to make custom filters with Phaser, but I don't get how the uniforms, and vTextureCoord in particular are specified. Here's a JSFiddle (EDIT: Ignore the image, the minimal case lays in the square gradient): Why isn't the top-right corner white? I've set both the filter resolution and the...

How to create latitudinal (horizontal) contour lines in GLSL?

I'm aiming for this effect: (horizontal-only contour lines): I did find this example, however it creates horizontal and vertical contour lines. I can't quite wrap my head around how the call to fwidth() is generating the lines. uniform float gsize;//size of the grid uniform float gwidth;//grid lines'width in pixels varying...

WebGL Normal calculations from position texture

Iam trying to create a procedural water puddle in webGL with "water ripples" by vertex displacement. The problem I'm having is that I get a noise I can't explain. Below is the first pass vertex shader where I calculate the vertex positions that i later render to a texture that...

How to access all vertexes within the same patch in Tessellation Control Shader

I want to do LOD in Tessenllation Control Shader. And my method is to calculate the area each patch occupyed on screen coordinate, and set different tessellation level for them. So I need to access all vertices within a patch and I do so like: for(int i = 0; i...

Issues refactoring GLES30 shader?

I'm currently rewriting a shader written in GLES30 for the GLES20 shader language. I've hit a snag where the shader I need to convert makes a call to the function textureLod, which samples the currently bound texture using a specific level-of-detail. This call is made within the fragment shader, which...

can I send an array of data as a vertex attribute?

I have a PointCloud in which I am using to visualize some time-related data points. For each vertex in the PointCloud.Geometry, I'd like to assign an attribute which is an array of epoch times. These epoch times are ints, an example would be: epochTimes = [1432314839, 1432314840, 1432314841]; the custom...

Water rendering in opengl [duplicate]

This question already has an answer here: How to render ocean wave using opengl in 3D? [closed] 2 answers I have absolutely no idea how to render water sources (ocean, lake, etc). It's like every tutorial I come across assumes I have the basic knowledge in this subject, and...

Declaring array in GLSL based on uniform int

In the program that I'm coding, I have to generate multiple lights sources and pass is to the shader. As this number is defined outside the shader, I though to pass it through an uniform int and use this to declare the arrays size. uniform int numLights; uniform vec4 ambientColor;...

How can I render an infinite 2D grid in GLSL?

Ideally, what I'd like to do is draw a single quad and have GLSL handle the creation of the actual gridlines. In my attempt so far the vertex shader: #version 400 layout (location = 0) in vec4 in_position; layout (location = 2) in vec3 in_UV; uniform mat4 model; uniform mat4...

OpenGL: Defining variables in shaders

My OpenGL program, using GLSL for shaders, has a simple vertex and fragment shader (given by a tutorial). The vertex shader is: #version 330 layout (location = 0) in vec3 Position; void main() { gl_Position = vec4(0.5 * Position.x, 0.5 * Position.y, Position.z, 1.0); } And the fragment shader is:...

GLSL 400 samplerCube binding

My partner and I are working on an OpenGL project that includes a skybox. The skybox works fine on his computer (which has GLSL version 4.5) and everything BUT the skybox works on mine (GLSL 4.0). The compiler complains about a syntax error in this line: layout(binding=0) uniform samplerCube currTexture;...

Should Meshes with and without Skeleton use different Shaders?

Should Meshes with and without Skeleton use different Shaders? Background: Right now my shader is constructed to handle meshes with skeletons. Each vertex takes 3 bone IDs, with respective bone weight. This works well for models with skeletons that I wish to animate, but I feel that it is a...

How to use VBOs without VAOs with OpenGL core profile?

I'm having trouble using vertex buffer objects without using a vertex array object. My understanding was that VAOs are just encapsulating the state around VBOs. But shouldn't the VBOs be usable without a VAO? Here's a mini-example. With use_vao=true this works correctly (renders orange rect). With use_vao=false this renders nothing...

Video Memory from ETC2 Texture Compression on OpenGL 4.3

Currently I'm writing a renderer which uses many textures and will fill up my graphics card's video memory (3 Gb for my nVidia GTX 780 Ti). So I pre-compressed all necessary images by using Mali's texture compression tool and integrated my renderer with libktx for loading compressed textures(*.ktx). The compression...

Modern GLSL ( opengl 3+ ) : Implementing phong effect correctly;

I am implementing a basic phong lighting GLSL shader; I have looked up some things on the internet, and found that the phong effect was created by adding an ambient, diffuse, and specular layer on the object (see image below, from tom dalling's site); problem is I have seen a...

Ambient and Specular lighting not working correctly in GLSL

In my lighting scene, for some reason the ambient lighting isn't working at all. The whole model is the same brightness, no matter which way it is facing. I tried getting rid of the attenuation but it still has the same results. Along with that, the specular lighting is always...

Attribute Variable not found in OpenGL, possible optimization

I'm currently working in a deferred shading and I created a class which manages the FBOs and draw the buffers on the screen. This is how it looks so far: FBORender::FBORender(float screenWidth, float screenHeight) : _screenWidth(screenWidth), _screenHeight(screenHeight), ProgramManager("defVertexShader.txt", "defFragShader.txt") { CreateProgram(); _vbo[0] = 0; _vbo[1] = 0; _vao = 0;...

Passing grayscale OpenCV image to an OpenGL texture

I want to use a grayscale image generated in OpenCV in a GLSL shader. Based on the question on OpenCV image loading for OpenGL Texture, I've managed to come up with the code that passes RGB image to the shader: cv::Mat image; // ...acquire and process image somehow... //create and...

alpha not changing transparency of object using glsl shader

How come when i manually change the alpha value in array, being passed to shader, the result is the same for both 0.0f and 1.0f? I was expecting the object to be drawn with some level of transparency, depending on alpha value. I'm not using any textures. I always see...

Write positions to texture OpenGL/GLSL

I want to write the model-space vertex positions of a 3D mesh to a texture in OGL. Currently in order to write to a texture I set it to a fullscreen quad and write to it using a separate pass (based on tutorial seen here.) The problem is that, from...

OpenGL OGLDev SSAO Tutorial Implementation Fragment Shader yields Noise

TASK BACKGROUND I am trying to implement SSAO after OGLDev Tutorial 45, which is based on a Tutorial by John Chapman. The OGLDev Tutorial uses a highly simplified method which samples random points in a radius around the fragment position and steps up the AO factor depending on how many...

Problems passing OpenGL 3.0 uniforms through multiple classes

I'm loosely following the tutorial on, I'm currently passing multiple lights into my fragmentshader. For that I've got multiple lightclasses and one class that acts as a container to be able to pass my lights uniforms into the shader. The shader is set up correctly. However when I call...