1. vertShader.glsl(顶点着色器代码):
#version 460
void
main (void)
{
if (gl_VertexID == 0)
gl_Position = vec4 (0.25, -0.25, 0.0, 1.0);
else if (gl_VertexID == 1)
gl_Position = vec4 (-0.25, -0.25, 0.0, 1.0);
else
gl_Position = vec4 (0.25, 0.25, 0.0, 1.0);
}
2. Utils.h(读取着色器代码)
Utils.h
#pragma once
#include <fstream>
#include <iostream>
#include <string>
class Utils {
public:
using string = std::string;
using ifstream = std::ifstream;
static string readShaderSource (const char *filePath)
{
string content;
ifstream fileStream (filePath, std::ios::in);
string line = "";
while (!fileStream.eof()) {
std::getline (fileStream, line);
content.append (line += "\n");
}
fileStream.close();
return content;
}
};
3. main函数
需要注意的是,glDrawArrays (GL_TRIANGLES, 0, 3);
中指定的类型是三角形GL_TRIANGLES
。
#include "Utils.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;
constexpr int numVAOs = 1;
GLuint renderingProgram;
GLuint vao[numVAOs];
GLuint
createShaderProgram ()
{
Utils::string vShaderString = Utils::readShaderSource ("vertShader.glsl");
const char *vshaderSource = vShaderString.c_str();
const char *fshaderSource = "#version 460 \n"
"out vec4 color; \n"
"void main(void) \n"
"{ color = vec4(0.0, 0.0, 1.0, 1.0); }";
GLuint vShader = glCreateShader (GL_VERTEX_SHADER);
GLuint fShader = glCreateShader (GL_FRAGMENT_SHADER);
glShaderSource (vShader, 1, &vshaderSource, NULL);
glShaderSource (fShader, 1, &fshaderSource, NULL);
glCompileShader (vShader);
glCompileShader (fShader);
GLuint vfProgram = glCreateProgram();
glAttachShader (vfProgram, vShader);
glAttachShader (vfProgram, fShader);
glLinkProgram (vfProgram);
return vfProgram;
}
void
display (GLFWwindow *window, double currTime)
{
glUseProgram (renderingProgram);
glPointSize (5.0);
glDrawArrays (GL_TRIANGLES, 0, 3);
}
void
init (GLFWwindow *window)
{
renderingProgram = createShaderProgram();
glGenVertexArrays (numVAOs, vao);
glBindVertexArray (vao[0]);
}
int
main (int argc, char *argv[])
{
if (!glfwInit()) {
return -1;
}
glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 6);
GLFWwindow *window = glfwCreateWindow (600, 600, "Chapter2 - program1", nullptr, nullptr);
glfwMakeContextCurrent (window);
int errorCode = glewInit();
if (errorCode != GLEW_OK) {
cerr << "Error: " << glewGetErrorString (errorCode) << endl;
return -1;
}
glfwSwapInterval (1);
init (window);
while (!glfwWindowShouldClose (window)) {
display (window, glfwGetTime());
glfwSwapBuffers (window);
glfwPollEvents();
}
glfwDestroyWindow (window);
glfwTerminate();
return 0;
}