1. 程式人生 > >OpenGL建立一個帶顏色的矩形

OpenGL建立一個帶顏色的矩形



 Shader.h

#pragma once

#define GLEW_STATIC
#include  <GL\glew.h>
#include <GLFW/glfw3.h>

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

class Shader
{
public:
	Shader(const char* vertexPath, const char* fragmentPath);
	~Shader();
	unsigned int ID;
	void Shader::use();
	void Shader::setBool(const std::string &name, bool value) const;
	void Shader::setInt(const std::string &name, int value) const;
	void Shader::setFloat(const std::string &name, float value) const;

private:
	void Shader::checkCompileErrors(unsigned int shader, std::string type);
};


Shader.cpp

#include "Shader.h"


void Shader::use()
{
	glUseProgram(ID);
}
// utility uniform functions
// ------------------------------------------------------------------------
void Shader::setBool(const std::string &name, bool value) const
{
	glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
// ------------------------------------------------------------------------
void Shader::setInt(const std::string &name, int value) const
{
	glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void Shader::setFloat(const std::string &name, float value) const
{
	glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}

void Shader::checkCompileErrors(unsigned int shader, std::string type)
{
	int success;
	char infoLog[1024];
	if (type != "PROGRAM")
	{
		glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
		if (!success)
		{
			glGetShaderInfoLog(shader, 1024, NULL, infoLog);
			std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
		}
	}
	else
	{
		glGetProgramiv(shader, GL_LINK_STATUS, &success);
		if (!success)
		{
			glGetProgramInfoLog(shader, 1024, NULL, infoLog);
			std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
		}
	}
}


Shader::Shader(const char* vertexPath, const char* fragmentPath)
{
	// 1. 從檔案路徑中獲取頂點/片段著色器
	std::string vertexCode;
	std::string fragmentCode;
	std::ifstream vShaderFile;
	std::ifstream fShaderFile;
	// 保證ifstream物件可以丟擲異常:
	vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
	fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
	try
	{
		// 開啟檔案
		vShaderFile.open(vertexPath);
		fShaderFile.open(fragmentPath);
		std::stringstream vShaderStream, fShaderStream;
		// 讀取檔案的緩衝內容到資料流中
		vShaderStream << vShaderFile.rdbuf();
		fShaderStream << fShaderFile.rdbuf();
		// 關閉檔案處理器
		vShaderFile.close();
		fShaderFile.close();
		// 轉換資料流到string
		vertexCode = vShaderStream.str();
		fragmentCode = fShaderStream.str();
	}
	catch (std::ifstream::failure e)
	{
		std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
	}
	const char* vShaderCode = vertexCode.c_str();
	const char* fShaderCode = fragmentCode.c_str();

	unsigned int vertex, fragment;
	
	// vertex shader
	vertex = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertex, 1, &vShaderCode, NULL);
	glCompileShader(vertex);
	checkCompileErrors(vertex, "VERTEX");
	// fragment Shader
	fragment = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragment, 1, &fShaderCode, NULL);
	glCompileShader(fragment);
	checkCompileErrors(fragment, "FRAGMENT");
	// shader Program
	ID = glCreateProgram();
	glAttachShader(ID, vertex);
	glAttachShader(ID, fragment);
	glLinkProgram(ID);
	checkCompileErrors(ID, "PROGRAM");
	// delete the shaders as they're linked into our program now and no longer necessary
	glDeleteShader(vertex);
	glDeleteShader(fragment);
}






Shader::~Shader()
{
}

 


 main.cpp

#define GLEW_STATIC
#include  <GL\glew.h>
#include <GLFW/glfw3.h>

#include <iostream>

#include "Shader.h"
using namespace std;
//QQ技術交流群:386476712

//terminate	[ˈtɜ:mɪneɪt]  結束 終結
//hint [hɪnt] 提示 注意事項


void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
	cout << "width :  " << width << endl;
	glViewport(0, 0, width, height);
}

int main(){

	

	//glfw初始化
	//告訴glfw當前所用的OpenGL的版本號是3.3
	//告訴glfw當前使用核心模式,意味著我們只能使用OpenGL功能的一個子集(沒有我們已不再需要的向後相容特性)
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	//使用glfw建立一個視窗
	GLFWwindow* window = glfwCreateWindow(800, 600, "Hunk Xu  OpenGL", NULL, NULL);
	if (window == NULL)
	{
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return -1;
	}
	//通知GLFW將window的上下文設定為當前執行緒的主上下文,設定主活動視窗
	glfwMakeContextCurrent(window);

    
	//glew初始化
	if (glewInit() != GLEW_OK){
		printf("glew init failed");
		glfwTerminate();
		return -1;
	}

	//告訴OpenGL視口(Viewport)大小
	//前兩個引數為視窗左下角位置
	//後兩個引數渲染視窗的寬和高(畫素)
	glViewport(0, 0, 800, 600);
	//每當視窗調整大小時候,就呼叫這個函式
	glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

	float vertices[] = {
		0.5f, 0.5f, 0.0f,  // top right
		0.5f, -0.5f, 0.0f,  // bottom right
		-0.5f, -0.5f, 0.0f,  // bottom left
		-0.5f, 0.5f, 0.0f   // top left 
	};
	unsigned int indices[] = {  // note that we start from 0!
		0, 1, 3,  // first Triangle
		1, 2, 3   // second Triangle
	};
	unsigned int VBO, VAO, EBO;
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);

	glBindVertexArray(VAO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);//第二個引數要設定成你想操作記憶體的標識,然後接下來的操作都是針對這一塊記憶體進行的
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
	glEnableVertexAttribArray(4);


	//將頂點資料buffer和之前的繫結關係進行解綁 用於打破之前的頂點資料buffer的繫結關係
	//使OpenGL的頂點資料buffer繫結狀態恢復到預設狀態。
	glBindBuffer(GL_ARRAY_BUFFER, 0); 



	//將VAO繫結到預設的VAO處,一般用於打破之前的VAO繫結關係
	//使OpenGL的VAO繫結狀態恢復到預設狀態
	glBindVertexArray(0);


	Shader* myShader = new Shader("vertexSource.txt", "fragementSource.txt");
	//渲染迴圈
	while (!glfwWindowShouldClose(window)){

		myShader->use();
		glBindVertexArray(VAO); 
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); //6表示6個頂點索引

		//雙緩衝(Double Buffer)
		//前緩衝儲存著最終輸出的影象,它會在螢幕上顯示;
		//而所有的的渲染指令都會在後緩衝上繪製。
		//當所有的渲染指令執行完畢後,我們交換(Swap)前緩衝和後緩衝,這樣影象就立即呈顯出來
		//不會出現影象閃爍的問題
		glfwSwapBuffers(window);  
		glfwPollEvents(); //輪詢使用者的輸入(鍵盤移動,滑鼠輸入)
	}

	//終止
	glfwTerminate();
	return 0;
}


fragementSource.txt

#version 330 core
out vec4 FragColor;

in vec4 vertexColor; // 從頂點著色器傳來的輸入變數(名稱相同、型別相同)

void main()
{
    FragColor = vertexColor;
}

vertexSource.txt

#version 330 core
layout (location = 4) in vec3 aPos; // 位置變數的屬性位置值為0

out vec4 vertexColor; // 為片段著色器指定一個顏色輸出

void main()
{
    gl_Position = vec4(aPos, 1.0); // 注意我們如何把一個vec3作為vec4的構造器的引數
    vertexColor = vec4(0, 0, 1.0, 1.0); // 把輸出變數設定為暗紅色
}

最後執行結果:



FR:海濤高軟(hunk Xu)
QQ技術交流群:386476712