1. 程式人生 > >七、畫一個 3D 的彩色的立方體

七、畫一個 3D 的彩色的立方體

畫完會動的 3D 矩形,現在玩點高階的,畫一個會動的 3D 彩色的立方體。

一、程式碼

  • main.cpp
#include <iostream>

//GLEW
#define GLEW_STATIC
#include <GL/glew.h>

//GLFW
#include <GLFW/glfw3.h>

//Shader
#include "Shader.h"

// SOIL2
//Linux 用的是 \, 但是 / 都可以用
#include "SOIL2/SOIL2.h"  
#include "SOIL2/stb_image.h"
//glm #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> //需要什麼變換,就匯入什麼檔案,具體可以去官網看 #include <glm/gtc/type_ptr.hpp> const GLint WIDTH = 800, HEIGHT = 600; //新建視窗 int main() { glfwInit(); //OpenGL 版本 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,
3); //視窗設定 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //用的是新版的 OpenGL 3.3 glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // must for Mac glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); //改為 GL_TRUE,改變視窗,縱橫比會變 GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "Learn OpenGL B16112011"
, nullptr, nullptr); //視窗名字改成自己的學號 if (nullptr == window) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } // next two lines are for mac retina display int screenWidth, screenHeight; glfwGetFramebufferSize(window, &screenWidth, &screenHeight); //獲取視窗大小 glfwMakeContextCurrent(window); //可以新建很多 window glewExperimental = GL_TRUE; if (GLEW_OK != glewInit()) { std::cout << "Failed to initialise GLEW" << std::endl; return -1; } glViewport(0, 0, screenWidth, screenHeight); //從(0,0)開始畫點,直到 WIDTH 和 HEIGHT //glEnable(GL_CULL_FACE); //只顯示一半 //glEnable(GL_DEPTH_TEST); //深度測試 //glDepthFunc(GL_LESS); //深度資訊小於當期資訊,就把進行測試 /* //啟動透明度混合,固定不能改,alpha 線性混合:設定當前為 α ,其他就為 1- α glEnable(GL_BLEND); //表示把渲染的影象融合到目標區域。也就是說源的每一個畫素的alpha都等於自己的alpha, //目標的每一個畫素的alpha等於1減去該位置源畫素的alpha。因此不論疊加多少次,亮度是不變的。 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); */ //vs 是頂點調色器,frag 是邊緣調色器 Shader ourShader = Shader("core1.vs", "core1.frag"); //檔案相對路徑 //now the verte information comes below float vertices[] = { -0.5f, -0.5f, -0.5f, 0.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, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.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, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.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, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.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, 1.0f, 0.5f, -0.5f, 0.5f, 1.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, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; //the date should be transfered to the memory on the Graphics Card,傳到視訊記憶體 GLuint VAO, VBO; //VAO:Vertex Array Object VBO:Vertex Buffer Object傳資料 glGenVertexArrays(1, &VAO); //建立 VAO glGenBuffers(1, &VBO); glBindVertexArray(VAO); //設當前直線 glBindBuffer(GL_ARRAY_BUFFER, VBO); //VAO 和 VBO 成對出現 // transfer the data:傳資料 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //靜態訪問,幾乎不修改 //set the attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid *)0); //0:對應調色器裡 location 的值;3:對應 vec3 三個量;GL_FLOAT:浮點型;GL_FALSE:;5*sizeof(GLfloat):對應 Buffer 裡傳的資料;(GLvoid*)0:從第 0 個位置開始 glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid *)(3 * sizeof(GLfloat))); //0:對應調色器裡 location 的值;3:對應 vec3 三個量;GL_FLOAT:浮點型;GL_FALSE:;5*sizeof(GLfloat):對應 Buffer 裡傳的資料;(GLvoid*)0:從第 0 個位置開始 glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); //畫圖 while (!glfwWindowShouldClose(window)) { glfwPollEvents(); //把所有事件系統都取過來:鍵盤/滑鼠等操作 glClearColor(0.2f, 0.3f, 0.3f, 1.0f); //視窗背景顏色,RGB,最後一個是透明度 glClear(GL_COLOR_BUFFER_BIT); //Bind the shader //glUseProgram(shaderProgram); //使用調色器,不註釋 ourShader.Use(); //glm 從 0.9.9 版本起,預設會將矩陣型別初始化為一個零矩陣(所有元素均為 0) glm::mat4 transform = glm::mat4(1.0f); //初始化 4 * 4 單位矩陣 //旋轉 //GLM 希望它的角度是弧度制,radians 將角度轉化為弧度制 //glfwGetTime():讓圖形一直變換,做一個型別轉換,用 static_cast<GLfloat>,設為 GLfloat 型 //glm::vec3(1.0f, 1.0f, 1.0f),分別繞 x 軸、y 軸、z 軸進行旋轉,如果都為 1.0f,就是繞和向量 (1,1,1) 轉 transform = glm::rotate(transform, glm::radians(20.0f) * static_cast<GLfloat>(glfwGetTime()), glm::vec3(1.0f, 1.0f, 1.0f)); //縮放,x、y、z 都縮放到原來的 0.5 倍 transform = glm::scale(transform, glm::vec3(0.5f, 0.5f, 0.5f)); //平移 //transform = GLuint transLoc = glGetUniformLocation(ourShader.Program, "transform"); //到 vs 找到那個 transform 變數 //Matrix4fv:4維矩陣,fv:浮點型別 //transLoc:變數 uniform 的位置 //1:代表只傳入一個矩陣 //GL_FALSE:不對矩陣進行置換,即不交換矩陣的行和列。GLM 的預設佈局就是列主序,所以並不需要置換矩陣 //最後:直接給出 transform 矩陣陣列,這裡我們要把矩陣轉換成陣列的格式傳遞。 glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(transform)); //glUniformMatrix4fv:四個座標 glUniform4fv:三個座標 //Draw the triangle glBindVertexArray(VAO); //使用 VAO,直接繫結 //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glDrawArrays(GL_TRIANGLES, 0, 36); //畫三角形,從第 0 個數據開始畫,到最後一個數據(第 3 個)結束 //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //解繫結 glBindVertexArray(0); glfwSwapBuffers(window); //呼叫雙面進行畫,顯示一個,另一個在畫,畫面更流暢 } glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); //lDeleteBuffers(1, &EBO); glfwTerminate(); return 0; }
  • Shader.h
#pragma once
//#ifndef shader_hpp
//#define shader_hpp
//#endif /* shader_hpp */
#include<string>
#include<fstream>  //可以開啟檔案
#include<sstream>
#include<iostream>
#include<GL/glew.h>

class Shader {
	GLuint vertex, fragment;
public:
	GLuint Program;
	Shader(const GLchar * vertexPath, const GLchar * fragmentPath)
	{
		std::string vertexCode;
		std::string fragmentCode;
		std::ifstream vShaderFile;
		std::ifstream fShaderFile;
		vShaderFile.exceptions(std::ifstream::badbit);
		fShaderFile.exceptions(std::ifstream::badbit);

		try {
			vShaderFile.open(vertexPath);
			fShaderFile.open(fragmentPath);

			std::stringstream vShaderStream, fShaderStream;

			vShaderStream << vShaderFile.rdbuf();
			fShaderStream << fShaderFile.rdbuf();

			//檔案關閉順序,先 v 再 f
			vShaderFile.close();
			fShaderFile.close();

			vertexCode = vShaderStream.str();
			fragmentCode = fShaderStream.str();
		}
		catch (std::ifstream::failure a) {
			std::cout <<
				"ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ"
				<< std::endl;
		}
		//型別轉換
		const GLchar *vShaderCode = vertexCode.c_str();
		const GLchar *fShaderCode = fragmentCode.c_str();

		//import and compile the shader
		vertex = glCreateShader(GL_VERTEX_SHADER);  //不用重新定義
		glShaderSource(vertex, 1, &vShaderCode, NULL);
		glCompileShader(vertex);  //編譯

		GLint success;
		GLchar infoLog[512];
		glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);  //編譯是否完成的位置
		if (!success) {
			glGetShaderInfoLog(vertex, 512, NULL, infoLog);
			std::cout <<
				"ERROR::SHADER::VERTEX::COMPILATION_FAILED\n"
				<< infoLog << std::endl;
		}

		//邊緣調色器
		fragment = glCreateShader(GL_FRAGMENT_SHADER);
		glShaderSource(fragment, 1, &fShaderCode, NULL);
		glCompileShader(fragment);  //編譯

		glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);  //編譯是否完成的位置
		if (!success) {
			glGetShaderInfoLog(fragment, 512, NULL, infoLog);
			std::cout <<
				"ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n"
				<< infoLog << std::endl;
		}

		//create the program and link the program
		this->Program = glCreateProgram();  //建立著色器程式
		glAttachShader(this->Program, vertex);
		glAttachShader(this->Program, fragment);
		glLinkProgram(this->Program);  //連結

		glValidateProgram(this->Program);  //可省略
		glGetProgramiv(this->Program, GL_LINK_STATUS, &success);
		if (!success) {
			glGetProgramInfoLog(this->Program, 512, NULL, infoLog);  //獲取連結情況
			std::cout <<
				"ERROR::SHADER::PROGRAM::LINKING_FAILED\n" <<
				infoLog << std::endl;
		}
	}

	~Shader() {
		glDetachShader(this->Program, vertex);
		glDetachShader(this->Program, fragment);
		glDeleteShader(vertex);
		glDeleteShader(fragment);
		glDeleteProgram(this->Program);
	}
	void Use() {
		glUseProgram(this->Program);
	}
};
  • core1.vs
#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 color;
out vec3 Color;
uniform mat4 transform;

void main(){
    gl_Position = transform * vec4(position, 1.0f);
	Color = color;
}
  • core1.frag
#version 330 core
in vec3 Color;
out vec4 color;

void main(){
    color = vec4(Color, 0.8f);
}

程式正常執行,應該能出現一個 3D 彩色動態的立方體在轉。

其實這個立方體是繞著(1,1,1)在轉動的。

二、講解

設定頂點屬性指標。

    //set the attribute
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
		6 * sizeof(GLfloat), (GLvoid *)0);  //0:對應調色器裡 location 的值;3:對應 vec3 三個量;GL_FLOAT:浮點型;GL_FALSE:;5*sizeof(GLfloat):對應 Buffer 裡傳的資料;(GLvoid*)0:從第 0 個位置開始
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
		6 * sizeof(GLfloat), (GLvoid *)(