I’m working on a 3D FPS game in OpenGL that features “gun holding”. I’ve discovered that the simplest way to draw weapon in the corner of the screen is to ommit the view matrix while calculating position of the vertex, so my vertex shader looks like this:
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoord;
out vec3 FragPos;
out vec3 Normal;
out vec2 TexCoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform bool viewIndependant;
void main() {
FragPos = vec3(model * vec4(aPos, 1.0));
Normal = mat3(transpose(inverse(model))) * aNormal;
TexCoord = vec2(aTexCoord);
gl_Position = viewIndependant ? projection * vec4(FragPos, 1.0) : projection * view * vec4(FragPos, 1.0);
}
To calculate light I’m using Phong model:
#define MAX_LIGHTS 8
struct Light {
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
struct Material {
sampler2D diffuse;
sampler2D specular;
float shininess;
};
out vec4 FragColor;
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoord;
uniform vec3 viewPos;
uniform Material material;
uniform Light light[MAX_LIGHTS];
uniform bool isLightSource;
vec3 calcLight(Light light, vec3 norm, vec3 viewDir) {
vec3 lightDir = normalize(light.position - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoord));
vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoord));
vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoord));
return (ambient + diffuse + specular);
}
void main() {
vec3 norm = normalize(Normal);
vec3 viewDir = normalize(viewPos - FragPos);
vec3 result = vec3(0.0);
for(int i = 0; i < MAX_LIGHTS; i++) {
result += calcLight(light[i], norm, viewDir);
}
FragColor = isLightSource ? vec4(255.0, 255.0, 255.0, 1.0) : vec4(result, 1.0);
}
In this way the model “sticks” to the vieport, but the lighting on a gun always stays the same, no matter the camera position or looking direction. So, how can you correctly apply lighting on a model drawn like this if it’s not being transformed relative to a camera view?