结构体的uniform设置的名称 "xxx.xxx"
uniform是数组则使"xxx[n]"
光源
光源的设置 直射光、点光源、聚光源
代码中主要就是传必要的值给shader
#ifndef LIGHT_H
#define LIGHT_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
#include "Shader.h"
class DirectionLight {
public:
glm::vec3 direction;
glm::vec3 color;
float intensity;
DirectionLight(glm::vec3 direction,glm::vec3 color,float intensity) {
this->direction = direction;
this->color = color;
this->intensity = intensity;
}
void ApplyLightToShader(Shader shader) {
shader.SetVec3("directLight.lightDir", direction);
shader.SetVec3("directLight.lightColor", color);
shader.SetFloat("directLight.intensity", intensity);
}
};
class PointLight {
public:
glm::vec3 pos;
glm::vec3 color;
float intensity;
float constant;
float linear;
float quadratic;
PointLight(glm::vec3 pos, glm::vec3 color, float intensity,glm::vec3 clq) {
this->pos = pos;
this->color = color;
this->intensity = intensity;
this->constant = clq.x;
this->linear = clq.y;
this->quadratic = clq.z;
}
void ApplyLightToShader(Shader shader,char* name ) {
std::string lightName(name);
shader.SetVec3((lightName +".lightPos").c_str(), pos);
shader.SetVec3((lightName + ".lightColor").c_str(),color);
shader.SetFloat((lightName + ".intensity").c_str(), intensity);
shader.SetFloat((lightName + ".constant").c_str(),constant );
shader.SetFloat((lightName + ".linear").c_str(), linear);
shader.SetFloat((lightName + ".quadratic").c_str(), quadratic);
}
};
class SpotLight {
public:
glm::vec3 direction;
glm::vec3 pos;
glm::vec3 color;
float innerCutOff;
float outerCutOff;
float intensity;
SpotLight(glm::vec3 direction, glm::vec3 pos, glm::vec3 color, float innerCutOff, float outerCutOff, float intensity) {
this->direction = direction;
this->pos = pos;
this->color = color;
this->innerCutOff = innerCutOff;
this->outerCutOff = outerCutOff;
this->intensity = intensity;
}
void AlppyLightToShader(Shader shader)
{
shader.SetVec3("spotLight.lightDir", direction);
shader.SetVec3("spotLight.lightPos", pos);
shader.SetVec3("spotLight.lightCol", color);
shader.SetFloat("spotLight.innerCutOff", innerCutOff);
shader.SetFloat("spotLight.outerCutOff", outerCutOff);
shader.SetFloat("spotLight.intensity", intensity);
}
};
#endif
shader中计算 ps:不知道是不是个人问题,这里点光源的最大值必须和实际传入的数量相同,(比如这里是四个点光源,就一定要传入四个点光源的数据)不然整个物体都是黑色的,按理说用的是+=,如果默认0的话应该不会有影响啊- -||。
#version 330 core
struct Material{
vec3 ambient;
sampler2D albedoTex;
sampler2D specularTex;
float gloss;
};
struct DirectLight{
vec3 lightColor;
vec3 lightDir;
float intensity;
};
struct PointLight{
vec3 lightColor;
vec3 lightPos;
float intensity;
float constant;
float linear;
float quadratic;
};
struct SpotLight{
vec3 lightDir;
vec3 lightPos;
vec3 lightCol;
float innerCutOff;
float outerCutOff;
float intensity;
};
#define MAX_POINT_LIGHTS 4
in vec3 worldPos;
in vec3 worldNormal;
in vec2 texCoord;
out vec4 FragColor;
uniform Material mat;
uniform DirectLight directLight;
uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform SpotLight spotLight;
uniform vec3 cameraPos;
vec3 CalcDirectLight(DirectLight light,vec3 normal,vec3 viewDir){
vec3 lightDir=normalize(-light.lightDir);
vec3 reflectDir=reflect(-lightDir,normal);
vec3 albedo=texture(mat.albedoTex,texCoord).rgb;
vec3 specularCol=texture(mat.specularTex,texCoord).rgb;
vec3 ambient=albedo*mat.ambient;
vec3 diffuse=light.lightColor*albedo*max(0,dot(normal,lightDir));
vec3 specular=light.lightColor*specularCol*pow(max(0,dot(reflectDir,viewDir)),mat.gloss);
return (ambient+diffuse+specular)*light.intensity;
}
vec3 CalcPointLight(PointLight light,vec3 normal,vec3 viewDir,vec3 worldPos){
vec3 lightVector=light.lightPos-worldPos;
vec3 lightDir=normalize(lightVector);
vec3 reflectDir=reflect(-lightDir,normal);
vec3 albedo=texture(mat.albedoTex,texCoord).rgb;
vec3 specularCol=texture(mat.specularTex,texCoord).rgb;
vec3 diffuse=light.lightColor*albedo*max(0,dot(normal,lightDir));
vec3 specular=light.lightColor*specularCol*pow(max(0,dot(reflectDir,viewDir)),mat.gloss);
float distance=length(lightVector);
float attenuation=1.0f/(light.constant+light.linear*distance+light.quadratic*pow(distance,2));
return (diffuse+specular)*attenuation*light.intensity;
}
vec3 CalcSpotLight(SpotLight light,vec3 normal,vec3 viewDir,vec3 worldPos){
vec3 lightVector=light.lightPos-worldPos;
vec3 lightDir=normalize(lightVector);
float theta = dot(lightDir, normalize(-light.lightDir));
float epsilon = light.innerCutOff - light.outerCutOff;//outerCutOff和innerCutOff都是cos值
float attenuation = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);
vec3 reflectDir=reflect(-lightDir,normal);
vec3 albedo=texture(mat.albedoTex,texCoord).rgb;
vec3 specularCol=texture(mat.specularTex,texCoord).rgb;
vec3 diffuse=light.lightCol*albedo*max(0,dot(normal,lightDir));
vec3 specular=light.lightCol*specularCol*pow(max(0,dot(reflectDir,viewDir)),mat.gloss);
return (diffuse+specular)*attenuation*light.intensity;
}
void main()
{
vec3 normal=normalize(worldNormal);
vec3 viewDir=normalize(cameraPos-worldPos);
vec3 finalColor=CalcDirectLight(directLight,normal,viewDir);
for(int i=0;i<MAX_POINT_LIGHTS;i++){
finalColor+=CalcPointLight(pointLights[i],normal,viewDir,worldPos);
}
finalColor+=CalcSpotLight(spotLight,normal,viewDir,worldPos);
FragColor =vec4(finalColor,1);
}
模型载入
使用资源加载库Assimp加载模型->将资源转为我们自己的数据结构->顶点属性数据绑定VAO、VBO、EBO->其余资源(如贴图)载入并传至shader->渲染
自定义的mesh和model
#ifndef MESH_H
#define MESH_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Shader.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
struct Vertex {
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TexCoords;
glm::vec3 Tangent;
glm::vec3 Bitangent;
};
struct Texture {
unsigned int id;
string type;
string path;
};
class Mesh {
public:
vector<Vertex> vertexs;
vector<unsigned int> indices;
vector<Texture> textures;
Mesh(vector<Vertex> vertexs, vector<unsigned int> indices, vector<Texture> textures) {
this->vertexs = vertexs;
this->indices = indices;
this->textures = textures;
SetupMesh();
}
void DrawMesh(Shader shader) {
//设置纹理 约定名称为texture_diffuse/specular/normal/heightN
unsigned int diffuseNr = 1, specularNr = 1, normalNr = 1, heightNr = 1;
for (unsigned int i = 0; i < textures.size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i);
string number, name;
name = textures[i].type;
if (name == "texture_diffuse") number = to_string(diffuseNr++);
if (name == "texture_specular") number = to_string(specularNr++);
if (name == "texture_normal")number = to_string(normalNr++);
if (name == "texture_height")number = to_string(heightNr++);
glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
glBindTexture(GL_TEXTURE_2D, textures[i].id);
}
//绘制网格
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
//重置默认
glBindVertexArray(0);
glActiveTexture(GL_TEXTURE0);
}
private:
unsigned int VAO, VBO, EBO;
void SetupMesh() {
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertexs.size() * sizeof(Vertex), &vertexs[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex,Normal));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));
glBindVertexArray(0);
}
};
#endif
#ifndef MODEL_H
#define MODEL_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stb_image.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Mesh.h"
#include "Shader.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class Model {
public:
vector<Mesh> meshs;
string directory;
vector<Texture> textures_loaded;//每张纹理只存一次
Model(char* path) {
loadModel(path);
}
void Draw(Shader shader) {
for (unsigned int i = 0; i < meshs.size(); i++)
{
meshs[i].DrawMesh(shader);
}
}
private:
void loadModel(string path) {
Assimp::Importer importer;
//第二个参数为对导入模型的额外处理,分别是三角化和反转y轴
const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);
if(!scene||scene->mFlags==AI_SCENE_FLAGS_INCOMPLETE||!scene->mRootNode){
cout << "ERROR::ASSIMP::" << importer.GetErrorString() << endl;
return;
}
directory = path.substr(0, path.find_last_of('/'));
processNode(scene->mRootNode,scene);
}
void processNode(aiNode *node, const aiScene *scene) {
//节点中存储的是网格数组的序列,网格数组在scene中
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
Mesh a = processMesh(mesh, scene);
meshs.push_back(a);
}
//继续递归遍历
for (unsigned int i = 0; i < node->mNumChildren; i++) {
processNode(node->mChildren[i],scene);
}
}
Mesh processMesh(aiMesh *mesh, const aiScene *scene) {
//将aiMesh转为我们自己的mesh类型 normal tangent bitangent 不一定有,最好检查一下
vector<Vertex> vertexs;
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
Vertex vertex;
glm::vec3 vector;
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.Position = vector;
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;
//我们只用第一层的uv
if (mesh->mTextureCoords[0])
{
glm::vec2 uv;
uv.x = mesh->mTextureCoords[0][i].x;
uv.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = uv;
}
else
{
vertex.TexCoords = glm::vec2(0, 0);
}
if (mesh->HasTangentsAndBitangents()) {
vector.x = mesh->mTangents[i].x;
vector.y = mesh->mTangents[i].y;
vector.z = mesh->mTangents[i].z;
vertex.Tangent = vector;
vector.x = mesh->mBitangents[i].x;
vector.y = mesh->mBitangents[i].y;
vector.z = mesh->mBitangents[i].z;
vertex.Tangent = vector;
}
else
{
vertex.Tangent = glm::vec3(0);
vertex.Bitangent = glm::vec3(0);
}
vertexs.push_back(vertex);
}
vector<unsigned int >indices;
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j]);
}
}
vector<Texture> textures;
aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_NORMALS, "texture_normal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_height");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
return Mesh(vertexs, indices, textures);
}
vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type,
string typeName) {
vector<Texture> textures;
for (unsigned int i = 0; i < mat->GetTextureCount(type); i++)
{
aiString str;
mat->GetTexture(type, i, &str);
bool isLoaded=false;
for (unsigned int j = 0; j < textures_loaded.size(); j++)
{
if (std::strcmp(textures_loaded[j].path.c_str(), str.C_Str()) == 0) {
textures.push_back(textures_loaded[j]);
isLoaded = true;
break;
}
}
if (!isLoaded)
{
Texture texture;
texture.id = TextureFromFile(str.C_Str(), directory);
texture.type = typeName;
texture.path = str.C_Str();
textures.push_back(texture);
}
}
return textures;
}
unsigned int TextureFromFile(const char *path, const string &directory) {
string filename = string(path);
filename = directory + '/' + filename;
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(filename.c_str(), &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;
}
};
#endif