OpenGL 渲染三角形示例[不要看注釋...]
#define GLEW_STATIC
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
void EscInput(GLFWwindow *win);
float vertices[]={
-0.5f,-0.5f,0.0f,
0.5f,-0.5f,0.0f,
0.0f, 0.5f,0.0f
};
const char *vertexShaderSource =
"#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\n";
const char *fragmentShaderSource=
"#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n";
int main(){
glfwInit(); //初始化
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);//提示1:用主版本
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);//提示2:用子版本
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);//提示3:使用啥
/*glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);*/ //提示4:使用mac兼容
//new一個(gè) GLFWwindow 對(duì)象 并設(shè)置w,h,"title_text",null,null
GLFWwindow *win = glfwCreateWindow(800,600,"Test window",NULL,NULL);
if(win == NULL){
std::cout<<"Open Window Failed\n";
glfwTerminate();
return -1;//失敗則結(jié)束
}
glfwMakeContextCurrent(win);
//=============================
glewExperimental = true;//bool
if(glewInit()!= GLEW_OK){
std::cout<<"glew init failed\n";
glfwTerminate();
return -1;
}
glViewport(0,0,800,600);//設(shè)置窗口維度(屏幕x,屏幕y,窗口x,窗口y)貌似沒(méi)鳥(niǎo)用
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);
unsigned int vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader,1,&vertexShaderSource,NULL);
glCompileShader(vertexShader);
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader,1,&fragmentShaderSource,NULL);
glCompileShader(fragmentShader);
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram,vertexShader);
glAttachShader(shaderProgram,fragmentShader);
glLinkProgram(shaderProgram);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,3*sizeof(float),(void*)0);
glEnableVertexAttribArray(0);
while(!glfwWindowShouldClose(win)){ //循環(huán)渲染 (每幀[30/60/120])
glClearColor(0.1137254901960784,0.85,1,1.0); //設(shè)置顏色
glClear(GL_COLOR_BUFFER_BIT);
//自定義函數(shù)
EscInput(win);
//繪制三角形
glBindVertexArray(VAO);
glUseProgram(shaderProgram);
glDrawArrays(GL_TRIANGLES,0,3);
glfwSwapBuffers(win); //顏色繪制與輸出2D屏幕
glfwPollEvents();
}
glfwTerminate(); //釋放/刪除之前的資源
return 0;
}
//當(dāng)按下ESC時(shí),退出
void EscInput(GLFWwindow *win){
if(glfwGetKey(win,GLFW_KEY_ESCAPE)==GLFW_PRESS){
std::cout<<"eixt!\n";
glfwSetWindowShouldClose(win,1);
}
}