前言
众所周知,一个矩形沿其对角线可以分成两个三角形,所以我们也就可以通过绘制两个三角形,将其拼接成一个矩形。本节使用的是索引的方法,以减少设置顶点的数目。
1.代码
代码如下:
#include<glad/glad.h>
#include<GLFW/glfw3.h>
#include"Shader.h"
#include"stb_image.h"
#include<iostream>
using namespace std;
float mixValue = 0.2f;
void framebuff_size_callback(GLFWwindow*window, int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
{
mixValue += 0.01f;
if (mixValue >= 1.0f)
mixValue = 1.0f;
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
{
mixValue -= 0.01f;
if (mixValue <=0.0f)
mixValue = 0.0f;
}
}
const int SCR_WIDTH = 800;
const int SCR_HEIGHT = 600;
int main()
{
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, "OpenGLTexture", NULL, NULL);
if (window == NULL)
{
cout << "Failed to create GLFW window" << endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuff_size_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
cout << "Failed to initialize GLAD" << endl;
}
Shader ourshader("vshader.txt", "twofshader.txt");
float vertes[] =
{
//坐标 颜色 纹理坐标
0.5f, 0.5f,0.0f, 1.0f,0.0f,0.0f, 1.0f,1.0f,
0.5f, -0.5f,0.0f, 0.0f,1.0f,0.0f, 1.0f,0.0f,
-0.5f,-0.5f,0.0f, 0.0f,0.0f,1.0f, 0.0f,0.0f,
-0.5f, 0.5f,0.0f, 1.0f,1.0f,0.0f, 0.0f,1.0f
};
//索引
unsigned int indices[] = {
0,1,3,
1,2,3
};
//顶点数组对象
unsigned int VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertes), vertes, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
//位置
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);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window))
{
processInput(window);
//ourshader.setFloat("aMixValue", mixValue);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
//着色
ourshader.use();
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
glfwTerminate();
system("pause");
return 0;
}