本文参考LearnOpenGL CN
在前面的章节中,我们使用的实际上都是点光源,除了点光源之外,还有平行光,聚光灯。
平行光
平行光的特点是光的方向几乎都平行,只有一个方向,这是为了模拟光源在无限远处的情景,例如太阳光。平行光一般不考虑光的衰减,它与光源位置无关,我们只需为它指定方向即可。一般情况下,我们指定光源时,习惯从光源指向物体,而在计算光照时,又需要从物体指向光源的方向,因此需要做一个反转。
我们在这里创建一个LightDirection类,对平行光进行封装。
LightDirection.h
#pragma once
#include
#include
class LightDirection
{
public:
LightDirection(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color);
~LightDirection();
glm::vec3 position;
glm::vec3 angles;
glm::vec3 direction=glm::vec3(0,0,1.0f);
glm::vec3 color=glm::vec3(1.0f,1.0f,1.0f);
void UpdataDirection();
};
LightDirection.cpp
#include "LightDirection.h"
LightDirection::LightDirection(glm::vec3 _position,glm::vec3 _angles,glm::vec3 _color):
position(_position),
angles(_angles),
color(_color)
{
UpdataDirection();
}
LightDirection::~LightDirection()
{
}
void LightDirection::UpdataDirection()
{
direction = glm::vec3(0, 0, 1.0f);
direction = glm::rotateZ(direction, angles.z);
direction = glm::rotateY(direction, angles.y);
direction = glm::rotateX(direction, angles.x);
direction = -1.0f * direction;
}
fragmentSource.txt
#version 330 core
struct Material{
vec3 ambient;
sampler2D diffuse;
sampler2D specular;
float shininess;
};
in vec3 FragPos;
in vec3 Normal;
in vec2 TexCoord;
uniform vec3 objColor;
uniform vec3 ambientColor;
uniform vec3 lightPos;
uniform vec3 lightDir;
uniform vec3 lightColor;
uniform vec3 CameraPos;
uniform Material material;
out vec4 FragColor;
void main()
{
//vec3 lightDir = normalize(lightPos-FragPos);
vec3 reflectVec = reflect(-lightDir,Normal);
vec3 CameraVec = normalize(CameraPos-FragPos);
//specular
float specularAmount = pow(max(dot(reflectVec,CameraVec),0),material.shininess);
vec3 specular = texture(material.specular,TexCoord).rgb * specularAmount * lightColor;
//diffuse
vec3 diffuse =texture(material.diffuse,TexCoord).rgb * max( dot(lightDir,Normal),0) * lightColor;
//ambient
vec3 ambient = texture(material.diffuse,TexCoord).rgb*ambientColor;
FragColor = vec4((diffuse + ambient + specular) * objColor,1.0);
}
main.cpp
#include
#include
#include
#include"Shader.h"
#include"Camera.h"
#include
#include
#include
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include"Material.h"
#include"LightDirection.h"
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT =600;
#pragma region Camera Declare
Camera camera(glm::vec3(0, 0, 3.0f), glm::radians(-15.0f), glm::radians(180.0f), glm::vec3(0, 1.0f, 0));
#pragma endregion
#pragma region Light Declare
LightDirection light = LightDirection(glm::vec3(10.0f, 10.0f, -5.0f), glm::vec3(glm::radians(45.0f), 0, 0),glm::vec3(1.0f,0,0));
#pragma endregion
#pragma region Input Declare
float lastX;
float lastY;
bool firstMouse = true;
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
camera.speedZ = 0.1f;
}
else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
camera.speedZ = -0.1f;
}
else
{
camera.speedZ = 0;
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
camera.speedX = 0.1f;
}
else if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
camera.speedX = -0.1f;
}
else
{
camera.speedX = 0;
}
}
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
{
camera.speedY = -0.1f;
}
else if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
{
camera.speedY = 0.1f;
}
else
{
camera.speedY = 0;
}
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouse == true)
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float deltaX, deltaY;
deltaX = xpos - lastX;
deltaY = ypos - lastY;
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(deltaX, deltaY);
}
// utility function for loading a 2D texture from file
// ---------------------------------------------------
unsigned int loadTexture(char const * path)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
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_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
#pragma endregion
unsigned int LoadImageToGPU(const char*filename, GLint internalformat, GLenum format, int textureSlot)
{
unsigned int texBuffer;
glGenTextures(1, &texBuffer);
glActiveTexture(GL_TEXTURE0 + textureSlot);
glBindTexture(GL_TEXTURE_2D, texBuffer);
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
unsigned char *data = stbi_load(filename, &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, internalformat, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
return texBuffer;
}
int main()
{
#pragma region Open a window
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
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);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// configure global opengl state
// -----------------------------
glEnable(GL_DEPTH_TEST);
#pragma endregion
#pragma region Model Data
GLfloat vertices[] = {
// positions // normals // texture coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
#pragma endregion
#pragma region Init Shader Pragram
Shader *ourShader = new Shader("VertexSource.vert", "fragmentSource.frag");
#pragma region Init Material
Material* myMaterial = new Material(ourShader,
LoadImageToGPU("container2.png",GL_RGBA,GL_RGBA,Shader::DIFFUSE),
LoadImageToGPU("container2_specular.png", GL_RGBA, GL_RGBA, Shader::SPECULAR),
glm::vec3(0, 1.0f, 0),
32.0f);
#pragma endregion
#pragma endregion
#pragma region Init and Load Models to VAO,VBO
unsigned int VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
unsigned int VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
#pragma endregion
#pragma region Init and Load Texture
/*unsigned int texBufferA;
texBufferA = LoadImageToGPU("container.jpg",GL_RGB,GL_RGB,0);
unsigned int texBufferB;
texBufferB = LoadImageToGPU("awesomeface.png",GL_RGBA, GL_RGBA, 1);*/
#pragma endregion
// tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
// -------------------------------------------------------------------------------------------
#pragma region Prepare MVP matrices
glm::mat4 modelMat;
glm::mat4 viewMat;
glm::mat4 projMat;
projMat = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
#pragma endregion
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
processInput(window);
// clear srceen
glClearColor(0, 0, 0, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now!
viewMat = camera.GetViewMatrix();
for (unsigned int i = 0; i < 10; i++)
{
//set Model Matrix
modelMat = glm::translate(glm::mat4(1.0f), cubePositions[i]);
//set View and Project Matrices here
//set Material->shader program
ourShader->use();
//set Material->textures
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, myMaterial->diffuse);
glActiveTexture(GL_TEXTURE0+1);
glBindTexture(GL_TEXTURE_2D, myMaterial->specular);
//set material->uniforms
/* glUniform1i(glGetUniformLocation(ourShader.ID, "ourTexture"), 0);
glUniform1i(glGetUniformLocation(ourShader.ID, "ourFace"), 1);*/
unsigned int modelLoc = glGetUniformLocation(ourShader->ID, "modelMat");
unsigned int viewLoc = glGetUniformLocation(ourShader->ID, "viewMat");
unsigned int projectLoc = glGetUniformLocation(ourShader->ID, "projMat");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(modelMat));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(viewMat));
glUniformMatrix4fv(projectLoc, 1, GL_FALSE, glm::value_ptr(projMat));
glUniform3f(glGetUniformLocation(ourShader->ID, "objColor"), 1.0f, 1.0f, 1.0f);
glUniform3f(glGetUniformLocation(ourShader->ID, "ambientColor"), 0.5f,0.5f,0.5f);
//glUniform3f(glGetUniformLocation(ourShader->ID, "lightPos"), light.position.x,light.position.y,light.position.z); //light position
glUniform3f(glGetUniformLocation(ourShader->ID, "lightColor"), light.color.x,light.color.y,light.color.z); //light color
glUniform3f(glGetUniformLocation(ourShader->ID, "lightDir"), light.direction.x, light.direction.y, light.direction.z);
glUniform3f(glGetUniformLocation(ourShader->ID, "CameraPos"), camera.Position.x, camera.Position.y, camera.Position.z);
myMaterial->shader->SetUniform3f("material.ambient", myMaterial->ambient);
//myMaterial->shader->SetUniform3f("material.diffuse", myMaterial->diffuse);
myMaterial->shader->SetUniform1f("material.shininess", myMaterial->shininess);
//myMaterial->shader->SetUniform3f("material.specular", myMaterial->specular);
myMaterial->shader->SetUniform1i("material.diffuse", Shader::DIFFUSE);
myMaterial->shader->SetUniform1i("material.specular",Shader::SPECULAR);
// set Model
glBindVertexArray(VAO);
//Drawcall
glDrawArrays(GL_TRIANGLES, 0, 36);
}
//Clean up,prepare for next render loop
glfwSwapBuffers(window);
glfwPollEvents();
camera.UpdataCameraPos();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
点光源
在前面的部分,我们使用的都是一个简单的点光源,场景中的物体不管离光源的远近得到的光照强度都相同,这一点与实际不相符合。实际中的点光源向各个方向发射光,但是光照强度随着物体与光源的距离d的增大而减弱(这一现象称为衰减)。随距离减少强度的方式是使用一个线性方程。这样的方程能够随着距离的增长线性地减少光的强度,从而让远处的物体更暗。然而,这样的线性方程通常会看起来比较假。距离稍微远点的物体光照强度减少得太过明显,不符合实际情况,因此一般考虑使用二次函数。光照强度的衰减系数Fatt与距离d之间的关系可以定义为:
其中Kc表示常系数,当d=0时,Fatt=1表示没有衰减,这时光照强度最大;
Kl表示线性衰减系数,Kq表示二次衰减系数
由于二次项的存在,光线会在大部分时候以线性的方式衰退,直到距离变得足够大,让二次项超过一次项,光的强度会以更快的速度下降。这样的结果就是,光在近距离时亮度很高,但随着距离变远亮度迅速降低,最后会以更慢的速度减少亮度。下面这张图显示了在100的距离内衰减的效果:
可以看出距离较近时光照强度较大,当距离超过一定范围后光照强度就很弱了,光照强度的以曲线方式减小,更加符合实际情形。
类似与平行光,我们同样创建一个LightPoint类(点光源类)
LightPoint.h
#pragma once
#include
#include
class LightPoint
{
public:
LightPoint(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color = glm::vec3(1.0f, 1.0f, 1.0f));
~LightPoint();
glm::vec3 position;
glm::vec3 angles;
glm::vec3 direction = glm::vec3(0, 0, 1.0f);
glm::vec3 color;
};
LightPoint.cpp
#include "LightPoint.h"
LightPoint::LightPoint(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color):
position(_position),
angles(_angles),
color(_color)
{
constant = 1.0f;
linear = 0.0f;
quadratic = 0.032f;
}
LightPoint::~LightPoint()
{
}
将前面对平行光源的使用改为对点光源类的使用
LightPoint light = LightPoint(glm::vec3(1.0f, 1.0f, -1.0f), glm::vec3(glm::radians(45.0f),glm::radians(45.0f), 0), glm::vec3(1.0f, 1.0f, 1.0f));
这时发现离得远的箱子依然很亮,我们就要用法到衰减。
我们在fragmentSource.txt中创建LightPoint结构体
struct LightPoint{
float constant;
float linear;
float quadratic;
};
uniform LightPoint lightP;
在我们的LightPoint类中添加这几项
#pragma once
#include
#include
class LightPoint
{
public:
LightPoint(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color = glm::vec3(1.0f, 1.0f, 1.0f));
~LightPoint();
glm::vec3 position;
glm::vec3 angles;
glm::vec3 direction = glm::vec3(0, 0, 1.0f);
glm::vec3 color;
float constant;
float linear;
float quadratic;
};
#include "LightPoint.h"
LightPoint::LightPoint(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color):
position(_position),
angles(_angles),
color(_color)
{
constant = 1.0f;
linear = 0.0f;
quadratic = 0.032f;
}
LightPoint::~LightPoint()
{
}
接着我们在main.cpp中设置这些项
glUniform1f(glGetUniformLocation(ourShader->ID, "lightP.constant"), light.constant);
glUniform1f(glGetUniformLocation(ourShader->ID, "lightP.liner"), light.linear);
glUniform1f(glGetUniformLocation(ourShader->ID, "lightP.quadratic"), light.quadratic);
然后我们在片元着色器中实现衰减
#version 330 core
struct Material{
vec3 ambient;
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct LightPoint{
float constant;
float linear;
float quadratic;
};
in vec3 FragPos;
in vec3 Normal;
in vec2 TexCoord;
uniform vec3 objColor;
uniform vec3 ambientColor;
uniform vec3 lightPos;
uniform vec3 lightDirUniform;
uniform vec3 lightColor;
uniform vec3 CameraPos;
uniform Material material;
uniform LightPoint lightP;
out vec4 FragColor;
void main()
{
float dist=length(lightPos-FragPos);
float attenuation = 1.0 / (lightP.constant + lightP.linear * dist +
lightP.quadratic * (dist * dist));
vec3 lightDir = normalize(lightPos-FragPos);
vec3 reflectVec = reflect(-lightDir,Normal);
vec3 CameraVec = normalize(CameraPos-FragPos);
//specular
float specularAmount = pow(max(dot(reflectVec,CameraVec),0),material.shininess);
vec3 specular = texture(material.specular,TexCoord).rgb * specularAmount * lightColor;
//diffuse
vec3 diffuse =texture(material.diffuse,TexCoord).rgb * max( dot(lightDir,Normal),0) * lightColor;
//ambient
vec3 ambient = texture(material.diffuse,TexCoord).rgb*ambientColor;
FragColor = vec4((diffuse + (ambient + specular)*attenuation) * objColor,1.0);
}
聚光
聚光是位于环境中某个位置的光源,它只朝向一个特定方向而不是所有方向照射光线。这样的结果就是只有在聚光方向的特定半径内的物体才会被照亮,其他物体都保持黑暗。路灯和手电筒就是很好的例子。下图(来自learnOpenGL CN)
其中,LightDir:从片段指向光源的向量
SpotDir:聚光灯所指向的方向
Phi( ϕ):指定了聚光灯半径的切光角。落在这个角度之外的物体都不会被这个聚光灯所照亮。
Theta(θ):LightDir和SpotDir向量之间的夹角。在聚光灯内部的话θ值应该比ϕ值小。
类似与上面两种光,我们先创建一个LightSpot类。
LightSpot.h
#pragma once
#include
#include
class LightSpot
{
public:
LightSpot(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color = glm::vec3(1.0f, 1.0f, 1.0f));
~LightSpot();
void UpdataDirection();
glm::vec3 position;
glm::vec3 angles;
glm::vec3 direction = glm::vec3(0, 0, 1.0f);
glm::vec3 color;
float cosPhyInner = 0.9f;
float cosPhyOutter = 0.85f;
};
LightSpot.cpp
#include "LightSpot.h"
LightSpot::LightSpot(glm::vec3 _position, glm::vec3 _angles, glm::vec3 _color ):
position(_position),
angles(_angles),
color(_color)
{
UpdataDirection();
}
LightSpot::~LightSpot()
{
}
void LightSpot::UpdataDirection()
{
direction = glm::vec3(0, 0, 1.0f);
direction = glm::rotateZ(direction, angles.z);
direction = glm::rotateY(direction, angles.y);
direction = glm::rotateX(direction, angles.x);
direction = -1.0f * direction;
}
在main.cpp中将light修改为LightSpot类型变量,同时将前面lightS相关的内容注释掉。
LightSpot light = LightSpot(glm::vec3(0.0f, 2.0f, 01.0f), glm::vec3(glm::radians(90.0f),0, 0), glm::vec3(1.0f, 1.0f, 1.0f));
在fragmentSource.txt中,创建LightSpot结构体
struct LightSpot
{
float cosPhyInner;
float cosPhyOutter;
};
在聚光灯传递张角的时候,我们传递夹角的余弦值而不是角度值。对于cos函数,在[0,π/2]时函数递减,如下图(来自OpenGL学习脚印)
那么当θ<= ϕ时,有cos(θ)>=cos(ϕ),我们在片元着色器中实现。
float spotRation;
if(cosTheta>lightS.cosPhyInner)
{
//inside
spotRation=1.0f;
}
else if(cosTheta>lightS.cosPhyOutter){
//middle
spotRation = 1.0-(cosTheta-lightS.cosPhyInner)/(lightS.cosPhyOutter-lightS.cosPhyInner);
}
else{
//outside
spotRation=0;
}
FragColor = vec4((diffuse + (ambient + specular)*spotRation) * objColor,1.0);
}
在main函数中设置参数
glUniform1f(glGetUniformLocation(ourShader->ID, "lightS.cosPhyInner"), light.cosPhyInner);
glUniform1f(glGetUniformLocation(ourShader->ID, "lightS.cosPhyOutter"), light.cosPhyOutter);
完整的fragmentSource.txt
#version 330 core
struct Material{
vec3 ambient;
sampler2D diffuse;
sampler2D specular;
float shininess;
};
struct LightPoint{
float constant;
float linear;
float quadratic;
};
struct LightSpot
{
float cosPhyInner;
float cosPhyOutter;
};
in vec3 FragPos;
in vec3 Normal;
in vec2 TexCoord;
uniform vec3 objColor;
uniform vec3 ambientColor;
uniform vec3 lightPos;
uniform vec3 lightDirUniform;
uniform vec3 lightColor;
uniform vec3 CameraPos;
uniform Material material;
uniform LightPoint lightP;
uniform LightSpot lightS;
out vec4 FragColor;
void main()
{
float dist=length(lightPos-FragPos);
float attenuation = 1.0 / (lightP.constant + lightP.linear * dist +
lightP.quadratic * (dist * dist));
vec3 lightDir = normalize(lightPos-FragPos);
vec3 reflectVec = reflect(-lightDir,Normal);
vec3 CameraVec = normalize(CameraPos-FragPos);
//specular
float specularAmount = pow(max(dot(reflectVec,CameraVec),0),material.shininess);
vec3 specular = texture(material.specular,TexCoord).rgb * specularAmount * lightColor;
//diffuse
vec3 diffuse =texture(material.diffuse,TexCoord).rgb * max( dot(lightDir,Normal),0) * lightColor;
//ambient
vec3 ambient = texture(material.diffuse,TexCoord).rgb*ambientColor;
float cosTheta=dot(normalize(FragPos-lightPos),-1*lightDirUniform);
float spotRation;
if(cosTheta>lightS.cosPhyInner)
{
//inside
spotRation=1.0f;
}
else if(cosTheta>lightS.cosPhyOutter){
//middle
spotRation = 1.0-(cosTheta-lightS.cosPhyInner)/(lightS.cosPhyOutter-lightS.cosPhyInner);
}
else{
//outside
spotRation=0;
}
FragColor = vec4((diffuse + (ambient + specular)*spotRation) * objColor,1.0);
}