颜色就是光照与材质的颜色混合
而漫反射,镜面反射,就是根据法向量与视线,光线来源,最后获取到一个打了折的颜色,把它加到物体的最终颜色上即可
opengl_color_light.cpp
#include <iostream>
#include <cmath>
#include "glad/glad.h"
#include "GLFW/glfw3.h"
#include "utils/Shader.h"
//图片工具库
#include "utils/stb_image.h"
//矩阵工具库
#include "utils/glm/glm.hpp"
#include "utils/glm/gtc/matrix_transform.hpp"
#include "utils/glm/gtc/type_ptr.hpp"
#include "utils/Camera.h"
void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void processInput(GLFWwindow *window);
void loadTexture(unsigned int *texture, const char *path);
void mouse_callback(GLFWwindow *window, double xpos, double ypos);
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);//相机位置
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);//面对的方向,以这个为尺度更改观看的,其实就是单位速度
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);//头顶的方向
float deltaTime = 0.0f; //当前帧与上一帧的时间差
float lastFrameTime = 0.0f;//上一帧的时间
float lastX = 300;
float lastY = 300;
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
/**
* 顶点数组对象:Vertex Array Object,VAO
* 顶点缓冲对象:Vertex Buffer Object,VBO
* 索引缓冲对象:Element Buffer Object,EBO或Index Buffer Object,IBO
* @return
*/
int main() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_OPENGL_CORE_PROFILE);
//第三个参数是标题
GLFWwindow *window = glfwCreateWindow(600, 600, "LearnOpengl", NULL, NULL);
if (window == NULL) {
std::cout << "Fail to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
//奇特的写法,本应是个函数,写出来却像个变量,连参数都不需要传了
if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
std::cout << "File to initialize GLAD" << std::endl;
return -1;
}
//使窗口隐藏光标并且捕捉它
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
//使用回调
glfwSetCursorPosCallback(window, mouse_callback);
glViewport(0, 0, 600, 600);//指定视口大小,跟java一样
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetScrollCallback(window, scroll_callback);
//箱子
Shader lightingShader("D:\\cl_workspace\\TestOpengl\\shader\\vertex_shader_5.glsl",
"D:\\cl_workspace\\TestOpengl\\shader\\fragment_shader_5.glsl");
//光源
Shader lampShader("D:\\cl_workspace\\TestOpengl\\shader\\vertex_shader_4.glsl",
"D:\\cl_workspace\\TestOpengl\\shader\\fragment_shader_4.glsl");
//立方体
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
//创建VBO,绑定数据,绑定VAO
//明白了,VBO顶点缓冲区,是用来存放数据的,而VAO是调用数据的索引
unsigned int cubeVAO;
glGenVertexArrays(1, &cubeVAO);
glBindVertexArray(cubeVAO);
unsigned int VBO;
glGenBuffers(1, &VBO);//&符号应该是传引用对象的意思,不然会传值进去
glBindBuffer(GL_ARRAY_BUFFER, VBO);//这一步就是给GL_ARRAY_BUFFER绑定数据了
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//做的时间长,反而忘了。。。这是给着色器里面的某个location设置值的
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void *) (0));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void *) (3 * sizeof(float)));
glEnableVertexAttribArray(1);
//当调用glBindVertexArray(lightVAO)后,再调用glBindBuffer(GL_ARRAY_BUFFER, VBO)
//相当于把缓冲区中的数据设置给了lightVAO,上面的顺序一定不能变
unsigned int lightVAO;
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void *) 0);
glEnableVertexAttribArray(0);
//循环绘制
while (!glfwWindowShouldClose(window)) {//判断界面是否关闭,没关闭就循环绘制
processInput(window);
//记录deltaTime
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrameTime;
lastFrameTime = currentFrame;
//同java
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//如果开启了深度测试,这里就要把GL_DEPTH_BUFFER_BIT也清空
//让光源随着时间的变化而改变位置
// lightPos = glm::vec3(1.2f * sin(glfwGetTime()), 1.0f * sin(glfwGetTime()), 2.0f);
glm::vec3 lightColor;
lightColor.x = sin(glfwGetTime() * 2.0f);
lightColor.y = sin(glfwGetTime() * 0.7f);
lightColor.z = sin(glfwGetTime() * 1.3f);
glm::vec3 diffuseColor = lightColor * glm::vec3(0.5f);//降低影响
glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f);//环境光,更低
//开启深度测试
glEnable(GL_DEPTH_TEST);
//lighting其实是物体。。。
lightingShader.use();
lightingShader.setVec3("lightPos", lightPos);//光源位置
lightingShader.setVec3("viewPos", camera.Position);//观察位置
//设置各个光照的强度
// lightingShader.setVec3("light.ambient", ambientColor);
// lightingShader.setVec3("light.diffuse", diffuseColor);
lightingShader.setVec3("light.ambient", 1.0f, 1.0f, 1.0f);
lightingShader.setVec3("light.diffuse", 1.0f, 1.0f, 1.0f);
lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);//镜面反射
//设置材质的各种反光强度
// lightingShader.setVec3("material.ambient", 1.0f, 0.5f, 0.31f);
// lightingShader.setVec3("material.diffuse", 1.0f, 0.5f, 0.31f);
// lightingShader.setVec3("material.specular", 0.5f, 0.5f, 0.5f);
//青色的塑料箱,怎么看起来一点都不像 材质网址 http://devernay.free.fr/cours/opengl/materials.html
// lightingShader.setVec3("material.ambient", 0.0f, 0.1f, 0.06f);
// lightingShader.setVec3("material.diffuse", 0.0f, 0.50980392f, 0.50980392f);
// lightingShader.setVec3("material.specular", 0.50196078f, 0.50196078f, 0.50196078f);
//黄铜,有点像了
lightingShader.setVec3("material.ambient", 0.329412f, 0.223529f, 0.027451f);
lightingShader.setVec3("material.diffuse", 0.780392f, 0.568627f, 0.113725f);
lightingShader.setVec3("material.specular", 0.992157f, 0.941176f, 0.807843f);
lightingShader.setFloat("material.shininess", 32.0f);
glm::mat4 model = glm::mat4();
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), 1.0f, 0.1f, 100.0f);
glm::mat4 view = camera.GetViewMatrix();
lightingShader.setMat4("model", model);
lightingShader.setMat4("view", view);
lightingShader.setMat4("projection", projection);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
lampShader.use();
lampShader.setMat4("view", view);
lampShader.setMat4("projection", projection);
model = glm::mat4();
model = glm::translate(model, lightPos);
model = glm::scale(model, glm::vec3(0.2f));
lampShader.setMat4("model", model);
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
//双缓冲机制,前缓冲保存着最终输出的图像,后缓冲则进行绘制,绘制完成以后与前缓冲交换,就会立即显示
//单缓冲会存在闪烁问题
glfwSwapBuffers(window);//交换颜色缓冲
glfwPollEvents();//检查有没有什么触发事件,鼠标键盘等,并调用相关的回调
}
//回收数据
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &lightVAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();//结束绘制
return 0;
}
//窗口尺寸改变的回调
void framebuffer_size_callback(GLFWwindow *window, int width, int height) {
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow *window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
}
//*代表引用传递,传参数时要用&符号,而取*里的值则需要*p
void loadTexture(unsigned int *texture, const char *path) {
glGenTextures(1, texture);
// 对*p赋值,从而改变p所指的地址上说保存的值
//*textrue就能表示这个内存地址上表示的值
glBindTexture(GL_TEXTURE_2D, *texture);//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);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//加载纹理,第三个参数是颜色通道的个数
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true);
//图片
unsigned char *data = stbi_load(path, &width,
&height, &nrChannels, 0);
//第二个参数为多级渐远纹理的级别,0为基本级别,第三个参数为指定纹理存储为何种格式
//第六个总是设置为0,第七第八定义源图的格式和数据类型
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
//释放图像内存
stbi_image_free(data);
}
bool firstMouse = true;
void mouse_callback(GLFWwindow *window, double xpos, double ypos) {
if (firstMouse) {
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
//滚轮的回调
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) {
camera.ProcessMouseScroll(yoffset);
}
fragment_shader_5.glsl
#version 330 core
out vec4 FragColor;
uniform vec3 lightPos;
uniform vec3 viewPos;
in vec3 Normal;
in vec3 FragPos;
struct Material {
vec3 ambient;//环境光,一般是物体颜色
vec3 diffuse;//漫反射光照下物体的颜色
vec3 specular;//镜面光照对物体的颜色影响
float shininess;//反光度
};
//一个光源对它的ambient、diffuse和specular光照有着不同的强度
struct Light {
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
//之前都是用灯光来设定环境光,漫反射光和镜面反射光,现在我们要分开设置这些材质
uniform Material material;
uniform Light light;
void main() {
//环境光
vec3 ambient = light.ambient * material.ambient;
//漫反射,先对向量进行标准化
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);//光的方向向量是光源位置与片段位置之间的向量差
//依据法向量计算光源对当前片段的漫反射影响
float diff = max(dot(norm, lightDir),0.0);//点积,算出来的是投影长度,夹角越小,越接近1,越亮
vec3 diffuse = light.diffuse * (diff * material.diffuse);
//镜面反射
vec3 viewDir = normalize(viewPos - FragPos);//片段位置到摄像机位置的向量,也就是视线方向
//反射向量,reflect函数要求第一个向量是从光源指向片段位置的向量
vec3 reflectDir = reflect(-lightDir,norm);
//点乘,避免负值,取32次幂,32是高光的反光度,这个点乘肯定小于1,32次方,那就更小了
//一个物体的反光度越高,反射光的能力越强,散射得越少,高光点就会越小,可以理解
//反光度material.shininess,必须是float类型,否则报错
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * (spec * material.specular);
//为每一个光照分量指定一个强度向量
//将环境光,漫反射光,镜面反射光作用于物体
vec3 result = ambient + diffuse + specular;
//混合两个光照颜色
FragColor = vec4(result, 1.0);
}
vertex_shader_5.glsl
#version 330 core
layout (location = 0) in vec3 aPos;//位置变量的属性位置值为0
layout (location = 1) in vec3 aNormal;//法向量
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
out vec3 Normal;
out vec3 FragPos;
void main() {
gl_Position = projection*view*model*vec4(aPos,1.0);
FragPos = vec3(model * vec4(aPos,1.0));
//把法向量也转换为世界空间坐标,所以需要一个法线矩阵
//由于我们只在世界空间中进行操作(不是在观察空间),我们只使用模型矩阵
//使用inverse和transpose函数修改model生成这个法线矩阵,必须是3x3的
mat3 normalMatrix = mat3(transpose(inverse(model)));
Normal = normalMatrix * aNormal;
}
网友评论