首頁 > 軟體

C++ OpenGL實現三角形的繪製

2022-06-24 18:00:17

一、繪製三角形

1、初始化

(1)初始化GLFW

//初始化GLFW
    glfwInit();//初始化GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);//設定主版本號
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);//設定次版本號
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//設定核心模式
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);//MAC OS
    glfwWindowHint(GLFW_RESIZABLE, false);//關閉可調節視窗大小

(2)建立一個視窗

//建立視窗(寬、高、視窗名)
    auto window = glfwCreateWindow(screen_width, screen_hight, "Triangle", nullptr, nullptr);
    if (window == nullptr) {
        std::cout << "Failed to Create OpenGL Context" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

(3)初始化GLAD

//初始化GLAD
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

(4)建立一個視口

//建立視口
    glViewport(0, 0, screen_width, screen_hight);

初始化程式碼(全):

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

#include <iostream>

const int screen_width = 800;
const int screen_hight = 600;

int main() {

	//初始化GLFW
	glfwInit();//初始化GLFW
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);//設定主版本號
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);//設定次版本號
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//設定核心模式
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);//MAC OS
	glfwWindowHint(GLFW_RESIZABLE, false);//關閉可調節視窗大小
	
	//建立視窗(寬、高、視窗名)
	auto window = glfwCreateWindow(screen_width, screen_hight, "Triangle", nullptr, nullptr);
	if (window == nullptr) {
		std::cout << "Failed to Create OpenGL Context" << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);

	//初始化GLAD
	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
	{
		std::cout << "Failed to initialize GLAD" << std::endl;
		return -1;
	}

	//建立視口
	glViewport(0, 0, screen_width, screen_hight);

	return 0;
}

2、頂點輸入

座標系規定

頂點座標程式碼

//三角形的頂點資料
const float triangle[] = {
    //--位置--//
    -0.5f,-0.5f,0.0f,//左下
    0.5f,-0.5f,0.0f,//右下
    0.0f,0.5f,0.0f,//正上
};

3、資料處理

(1)VBO、VAO

//生成並繫結VBO
    GLuint vertex_buffer_object;
    glGenBuffers(1, &vertex_buffer_object);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_object);
    //將頂點資料繫結至預設的緩衝中
    glBufferData(GL_ARRAY_BUFFER, sizeof(triangle), triangle, GL_STATIC_DRAW);

//生成並繫結VAO
    GLuint vertex_array_object;
    glGenVertexArrays(1, &vertex_array_object);
    glBindVertexArray(vertex_array_object);

(2)頂點屬性

//設定頂點屬性指標
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float),(void*)0);
    glEnableVertexAttribArray(0);

(3)解綁程式碼

//設定完成之後就可以解綁VBO、VAO了
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

4、頂點著色器和片段著色器

//頂點著色器原始碼
    const char* vertex_shader_source =
        "#version 330 coren"
        "layout (location = 0) in vec3 aPos;n"
        "void main()n"
        "{n"
        "    gl_Position = vec4(aPos,1.0);n"
        "}n";

//片段著色器原始碼
    const char* fragment_shader_source =
        "#version 330 coren"
        "out vec4 FragColor;n"
        "void main()n"
        "{n"
        "    FragColor = vec4(1.0f,0.5f,0.2f,1.0f);n"
        "}n";

//生成並編譯著色器
    //頂點著色器
    int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    int success;
    char info_log[512];
    // 檢查著色器是否成功編譯,如果編譯失敗,列印錯誤資訊
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertex_shader, 512, NULL, info_log);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILEDn" << info_log << std::endl;
    }
    // 片段著色器
    int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    // 檢查著色器是否成功編譯,如果編譯失敗,列印錯誤資訊
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragment_shader, 512, NULL, info_log);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILEDn" << info_log << std::endl;
    }

// 連結頂點和片段著色器至一個著色器程式
    int shader_program = glCreateProgram();
    glAttachShader(shader_program, vertex_shader);
    glAttachShader(shader_program, fragment_shader);
    glLinkProgram(shader_program);
    // 檢查著色器是否成功連結,如果連結失敗,列印錯誤資訊
    glGetProgramiv(shader_program, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shader_program, 512, NULL, info_log);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILEDn" << info_log << std::endl;
    }
    // 刪除著色器
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
// 線框模式
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

5、渲染

//渲染迴圈
	while (!glfwWindowShouldClose(window)) {

		// 清空顏色緩衝
		glClearColor(0.0f, 0.34f, 0.57f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		// 使用著色器程式
		glUseProgram(shader_program);

		// 繪製三角形
		glBindVertexArray(vertex_array_object);                                    // 繫結VAO
		glDrawArrays(GL_TRIANGLES, 0, 3);                                          // 繪製三角形
		glBindVertexArray(0);                                                      // 解除繫結

		// 交換緩衝並且檢查是否有觸發事件(比如鍵盤輸入、滑鼠移動等)
		glfwSwapBuffers(window);
		glfwPollEvents();
	}
    // 刪除VAO和VBO
    glDeleteVertexArrays(1, &vertex_array_object);
    glDeleteBuffers(1, &vertex_buffer_object);

二、完整程式碼

程式碼

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

#include <iostream>

const int screen_width = 800;
const int screen_hight = 600;

//三角形的頂點資料
const float triangle[] = {
	//--位置--//
	-0.5f,-0.5f,0.0f,//左下
	0.5f,-0.5f,0.0f,//右下
	0.0f,0.5f,0.0f,//正上
};

int main() {

	//初始化GLFW
	glfwInit();//初始化GLFW
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);//設定主版本號
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);//設定次版本號
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//設定核心模式
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);//MAC OS
	glfwWindowHint(GLFW_RESIZABLE, false);//關閉可調節視窗大小

	//建立視窗(寬、高、視窗名)
	auto window = glfwCreateWindow(screen_width, screen_hight, "Triangle", nullptr, nullptr);
	if (window == nullptr) {
		std::cout << "Failed to Create OpenGL Context" << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);

	//初始化GLAD
	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
	{
		std::cout << "Failed to initialize GLAD" << std::endl;
		return -1;
	}

	//建立視口
	glViewport(0, 0, screen_width, screen_hight);

	//生成並繫結VBO
	GLuint vertex_buffer_object;
	glGenBuffers(1, &vertex_buffer_object);
	glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_object);
	//將頂點資料繫結至預設的緩衝中
	glBufferData(GL_ARRAY_BUFFER, sizeof(triangle), triangle, GL_STATIC_DRAW);
	//生成並繫結VAO
	GLuint vertex_array_object;
	glGenVertexArrays(1, &vertex_array_object);
	glBindVertexArray(vertex_array_object);

	//設定頂點屬性指標
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);//引數:頂點著色器位置值,分量,頂點資料型別,是否標準化,步長、資料偏移量
	glEnableVertexAttribArray(0);//開啟0通道

	//設定完成之後就可以解綁VBO、VAO了
	glBindVertexArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	//頂點著色器原始碼
	const char* vertex_shader_source =
		"#version 330 coren"
		"layout (location = 0) in vec3 aPos;n"
		"void main()n"
		"{n"
		"	gl_Position = vec4(aPos,1.0);n"
		"}n";

	//片段著色器原始碼
	const char* fragment_shader_source =
		"#version 330 coren"
		"out vec4 FragColor;n"
		"void main()n"
		"{n"
		"	FragColor = vec4(1.0f,0.1f,0.1f,1.0f);n"
		"}n";

	//生成並編譯著色器
	//頂點著色器
	int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
	glCompileShader(vertex_shader);
	int success;
	char info_log[512];
	// 檢查著色器是否成功編譯,如果編譯失敗,列印錯誤資訊
	glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
	if (!success)
	{
		glGetShaderInfoLog(vertex_shader, 512, NULL, info_log);
		std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILEDn" << info_log << std::endl;
	}
	// 片段著色器
	int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
	glCompileShader(fragment_shader);
	// 檢查著色器是否成功編譯,如果編譯失敗,列印錯誤資訊
	glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
	if (!success)
	{
		glGetShaderInfoLog(fragment_shader, 512, NULL, info_log);
		std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILEDn" << info_log << std::endl;
	}
	// 連結頂點和片段著色器至一個著色器程式
	int shader_program = glCreateProgram();
	glAttachShader(shader_program, vertex_shader);
	glAttachShader(shader_program, fragment_shader);
	glLinkProgram(shader_program);
	// 檢查著色器是否成功連結,如果連結失敗,列印錯誤資訊
	glGetProgramiv(shader_program, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shader_program, 512, NULL, info_log);
		std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILEDn" << info_log << std::endl;
	}
	// 刪除著色器
	glDeleteShader(vertex_shader);
	glDeleteShader(fragment_shader);

	// 線框模式
	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	//渲染迴圈
	while (!glfwWindowShouldClose(window)) {

		// 清空顏色緩衝
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		// 使用著色器程式
		glUseProgram(shader_program);

		// 繪製三角形
		glBindVertexArray(vertex_array_object);                                    // 繫結VAO
		glDrawArrays(GL_TRIANGLES, 0, 3);                                          // 繪製三角形
		glBindVertexArray(0);                                                      // 解除繫結

		// 交換緩衝並且檢查是否有觸發事件(比如鍵盤輸入、滑鼠移動等)
		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	// 刪除VAO和VBO
	glDeleteVertexArrays(1, &vertex_array_object);
	glDeleteBuffers(1, &vertex_buffer_object);

	// 清理所有的資源並正確退出程式
	glfwTerminate();
	return 0;
}

輸出

修改尺寸

修改三角形顏色

修改背景顏色

線框模式

輸出

以上就是C++ OpenGL實現三角形的繪製的詳細內容,更多關於C++ OpenGL繪製三角形的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com