天天看點

OpenGL學習之投光物

本文參考LearnOpenGL CN

在前面的章節中,我們使用的實際上都是點光源,除了點光源之外,還有平行光,聚光燈。

平行光

平行光的特點是光的方向幾乎都平行,隻有一個方向,這是為了模拟光源在無限遠處的情景,例如太陽光。平行光一般不考慮光的衰減,它與光源位置無關,我們隻需為它指定方向即可。一般情況下,我們指定光源時,習慣從光源指向物體,而在計算光照時,又需要從物體指向光源的方向,是以需要做一個反轉。

我們在這裡建立一個LightDirection類,對平行光進行封裝。

LightDirection.h

#pragma once
#include <glm/glm.hpp>
#include<glm/gtx/rotate_vector.hpp>

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 <glad/glad.h>
#include <GLFW/glfw3.h>

#include <iostream>
#include"Shader.h"
#include"Camera.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#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之間的關系可以定義為:

OpenGL學習之投光物

其中Kc表示常系數,當d=0時,Fatt=1表示沒有衰減,這時光照強度最大;

 Kl表示線性衰減系數,Kq表示二次衰減系數

由于二次項的存在,光線會在大部分時候以線性的方式衰退,直到距離變得足夠大,讓二次項超過一次項,光的強度會以更快的速度下降。這樣的結果就是,光在近距離時亮度很高,但随着距離變遠亮度迅速降低,最後會以更慢的速度減少亮度。下面這張圖顯示了在100的距離内衰減的效果:

OpenGL學習之投光物

可以看出距離較近時光照強度較大,當距離超過一定範圍後光照強度就很弱了,光照強度的以曲線方式減小,更加符合實際情形。 

類似與平行光,我們同樣建立一個LightPoint類(點光源類)

LightPoint.h

#pragma once
#include <glm/glm.hpp>
#include<glm/gtx/rotate_vector.hpp>

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 <glm/glm.hpp>
#include<glm/gtx/rotate_vector.hpp>

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)

OpenGL學習之投光物

其中,LightDir:從片段指向光源的向量

SpotDir:聚光燈所指向的方向

Phi( ϕ):指定了聚光燈半徑的切光角。落在這個角度之外的物體都不會被這個聚光燈所照亮。

Theta(θ):LightDir和SpotDir向量之間的夾角。在聚光燈内部的話θ值應該比ϕ值小。

類似與上面兩種光,我們先建立一個LightSpot類。

LightSpot.h

#pragma once
#include <glm/glm.hpp>
#include<glm/gtx/rotate_vector.hpp>
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學習腳印)

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);

}
           

繼續閱讀