#include <stdio.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> #include <GL/glew.h> #include <GL/freeglut.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> using namespace std; using namespace cv; using namespace glm; //shader文件 const char* vsShaderName = "shader.vs";//頂點着色器 const char* fsShaderName = "shader.fs";//片元着色器 GLuint VBO;//頂點緩衝對象 GLuint IBO;//索引緩衝對象 GLuint UVBO;//uv緩衝對象 GLuint TexBO;//貼圖對象 GLuint NormalBO;//法線對象 //光照定義 struct { GLuint Color;//顏色 GLuint AmbientIntensity;//環境光強度 GLuint Direction;//方向 GLuint DiffuseIntensity;//漫反射強度 } m_dirLightLocation; static GLfloat *vertices; static unsigned int *indices; static GLfloat *uvs; static GLfloat *normals; GLuint ShaderProgram; GLuint MatrixID; GLuint MatrixID2; GLuint TextureID; int windowWidth = 1000; int windowHeight = 800; int imgWidth; int imgHeihgt; float verticeScale = 0.1f; float yScale = 5.0f; //相機參數 glm::mat4 ViewMatrix;//視圖矩陣 glm::mat4 ProjectionMatrix; //投影矩陣 glm::mat4 MVP;//模型視圖矩陣 glm::mat4 ModelMatrix;//模型矩陣 glm::vec3 position = glm::vec3(5, 5, 5); //相機位置 float horizontalAngle = 3.14f; float verticalAngle = 0.0f; float initialFoV = 45.0f; //相機視場角 float speed = 0.05f; //平移速度 float mouseSpeed = 0.005f; int mouseX, mouseY;//鼠標位置 窗口座標 bool mouseLeftDown = false;//鼠標左鍵按下 // 傳遞鍵盤事件 static void SpecialKeyboardCB(unsigned char Key, int x, int y) { glm::vec3 direction( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle) ); glm::vec3 right = glm::vec3( sin(horizontalAngle - 3.14f / 2.0f), 0, cos(horizontalAngle - 3.14f / 2.0f) ); glm::vec3 up = glm::cross(right, direction); switch (Key) { case 'w': position += direction * speed; //fprintf(stderr, "up \n"); break; case 'd': position += right * speed; //fprintf(stderr, "right \n"); break; case 's': position -= direction * speed; //fprintf(stderr, "down \n"); break; case 'a': position -= right * speed; //fprintf(stderr, "left \n"); break; case 27: exit(1); break; default: break; //fprintf(stderr, "Unimplemented GLUT key\n"); //exit(1); } float FoV = initialFoV; ProjectionMatrix = glm::perspective(glm::radians(FoV), (float)windowWidth / (float)windowHeight, 0.1f, 100.0f); ViewMatrix = glm::lookAt( position, position + direction, up ); ModelMatrix = glm::mat4(1.0); MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; glutPostRedisplay();//設置窗口重繪 } //傳遞鼠標事件 void mouseCB(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON) { if (state == GLUT_DOWN) { mouseLeftDown = true; mouseX = x; mouseY = y; } else if (state == GLUT_UP) { mouseLeftDown = false; } } } //傳遞鼠標位置 static void mouseMotionCB(int x, int y) { if (mouseLeftDown == true) { horizontalAngle += mouseSpeed * float(x - mouseX); verticalAngle += mouseSpeed * float(y - mouseY); mouseX = x; mouseY = y; SpecialKeyboardCB(0, 0, 0); } } //渲染回調函數 void RenderScenceCB() { // 清空顏色緩存 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);//線框模式 //傳遞矩陣數據 glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(MatrixID2,1, GL_FALSE,&ModelMatrix[0][0]); //傳遞光照 glUniform3f(m_dirLightLocation.Color, 1, 1, 0); glUniform1f(m_dirLightLocation.AmbientIntensity, 0.5); glUniform3f(m_dirLightLocation.Direction,1,1,0); glUniform1f(m_dirLightLocation.DiffuseIntensity,0.7); //傳遞頂點、索引、UV、法線 glEnableVertexAttribArray(0); //開啓頂點屬性 glBindBuffer(GL_ARRAY_BUFFER, VBO); //綁定GL_ARRAY_BUFFER緩衝器 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //告訴管線怎樣解析bufer中的數據 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, UVBO); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, NormalBO); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); //傳遞貼圖紋理 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, TexBO); glUniform1i(TextureID, 0); //繪製 glDrawElements(GL_TRIANGLES_ADJACENCY, (imgWidth - 1)*(imgHeihgt - 1) * 6 * 4, GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); //交換先後緩存 glutSwapBuffers(); } //建立頂點 static void CreateVertexBuffer() { //讀取圖片 Mat img = imread("T2.png"); int imgType = img.type(); Mat resImg = Mat(img.rows, img.cols, imgType); resize(img, resImg, resImg.size(), 0, 0, INTER_LINEAR); Mat gImg = Mat(img.rows, img.cols, CV_8UC1); //灰度圖 cv::cvtColor(resImg, gImg, CV_BGR2GRAY);//bgr轉灰度 imgWidth = resImg.rows; imgHeihgt = resImg.cols; vertices = new GLfloat[imgWidth*imgHeihgt * 3]; int k = 0; for (int i = 0; i < imgHeihgt; i++) { for (int j = 0; j < imgWidth; j++) { vertices[k++] = verticeScale* (float)i; int c = (int)gImg.at<uchar>(j, i); vertices[k++] = yScale*(float)c / 255.0f; vertices[k++] = verticeScale*(float)j; } } glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, imgWidth*imgHeihgt * 3 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); } //建立索引 static void CreateIndexBuffer() { indices = new unsigned int[(imgWidth - 1)*(imgHeihgt - 1) * 6]; int k = 0; for (int i = 0; i < imgHeihgt - 1; i++) { for (int j = 0; j < imgWidth - 1; j++) { indices[k++] = i*imgWidth + j; indices[k++] = i*imgWidth + j + 1; indices[k++] = i*imgWidth + j + imgWidth; indices[k++] = i*imgWidth + j + imgWidth; indices[k++] = i*imgWidth + j + 1; indices[k++] = i*imgWidth + j + imgWidth + 1; } } glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (imgWidth - 1)*(imgHeihgt - 1) * 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW); } //建立uv static void CreateUVBuffer() { uvs = new GLfloat[imgWidth*imgHeihgt * 2]; int k = 0; for (int i = 0; i < imgHeihgt; i++) { for (int j = 0; j < imgWidth; j++) { uvs[k++] = (float)i / (float)(imgHeihgt); uvs[k++] = (float)j / (float)(imgWidth); } } glGenBuffers(1, &UVBO); glBindBuffer(GL_ARRAY_BUFFER, UVBO); glBufferData(GL_ARRAY_BUFFER, imgWidth*imgHeihgt * 2 * sizeof(GLfloat), uvs, GL_STATIC_DRAW); } //建立貼圖 static void CreateTexture() { Mat img = imread("T2.png"); Mat resImg = Mat(256, 256, img.type()); resize(img, resImg, resImg.size(), 0, 0, INTER_LINEAR); cv::cvtColor(resImg, resImg, CV_BGR2RGB); glGenTextures(1, &TexBO); glBindTexture(GL_TEXTURE_2D, TexBO); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, resImg.data);//設定紋理 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);//重複紋理 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);//濾波 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); TextureID = glGetUniformLocation(ShaderProgram, "myTexture"); } //建立法線 static void CreateNormal() { normals= new GLfloat[imgWidth*imgHeihgt*3]; int k = 0; //遍歷索引三角 for (size_t i = 0; i < (imgWidth - 1)*(imgHeihgt - 1) * 6; i+=3) { static unsigned int pIndex1 = indices[i]; static unsigned int pIndex2 = indices[i + 1]; static unsigned int pIndex3 = indices[i + 2]; static float x1 = vertices[pIndex1]; static float y1 = vertices[pIndex1 + 1]; static float z1 = vertices[pIndex1 + 2]; static float x2 = vertices[pIndex2]; static float y2 = vertices[pIndex2 + 1]; static float z2 = vertices[pIndex2 + 2]; static float x3 = vertices[pIndex3]; static float y3 = vertices[pIndex3 + 1]; static float z3 = vertices[pIndex3 + 2]; //求邊 static float vx1 = x2 - x1; static float vy1 = y2 - y1; static float vz1 = z2 - z1; static float vx2 = x3 - x1; static float vy2 = y3 - y1; static float vz2 = z3 - z1; //叉乘求三角形法線 static float xN = vy1 * vz2 - vz1 *vy2; static float yN = vz1 * vx2 - vx1 * vz2; static float zN = vx1 * vy2 - vy1 * vx2; static float Length = sqrtf(xN * xN + yN * yN + zN * zN); xN /= Length; yN /= Length; zN /= Length; //頂點法線更新 normals[pIndex1] += xN; normals[pIndex1 + 1] += yN; normals[pIndex1 + 2] += zN; normals[pIndex2] += xN; normals[pIndex2 + 1] += yN; normals[pIndex2 + 2] += zN; normals[pIndex3] += xN; normals[pIndex3 + 1] += yN; normals[pIndex3 + 2] += zN; } glGenBuffers(1, &NormalBO); glBindBuffer(GL_ARRAY_BUFFER, NormalBO); glBufferData(GL_ARRAY_BUFFER, imgWidth*imgHeihgt * 3 * sizeof(GLfloat), normals, GL_STATIC_DRAW); } // 使用shader文本編譯shader對象,並綁定shader到着色器程序中 static void AddShader(GLuint ShaderProgram, const char* pShaderText, GLenum ShaderType) { // 根據shader類型參數定義兩個shader對象 GLuint ShaderObj = glCreateShader(ShaderType); // 檢查是否認義成功 if (ShaderObj == 0) { fprintf(stderr, "Error creating shader type %d\n", ShaderType); exit(0); } // 定義shader的代碼源 const GLchar* p[1]; p[0] = pShaderText; GLint Lengths[1]; Lengths[0] = strlen(pShaderText); glShaderSource(ShaderObj, 1, p, Lengths); glCompileShader(ShaderObj);// 編譯shader對象 // 檢查和shader相關的錯誤 GLint success; glGetShaderiv(ShaderObj, GL_COMPILE_STATUS, &success); if (!success) { GLchar InfoLog[1024]; glGetShaderInfoLog(ShaderObj, 1024, NULL, InfoLog); fprintf(stderr, "Error compiling shader type %d: '%s'\n", ShaderType, InfoLog); exit(1); } // 將編譯好的shader對象綁定到program object程序對象上 glAttachShader(ShaderProgram, ShaderObj); } // 編譯着色器函數 static void CompileShaders() { // 建立着色器程序 ShaderProgram = glCreateProgram(); // 檢查是否建立成功 if (ShaderProgram == 0) { fprintf(stderr, "Error creating shader program\n"); exit(1); } // 存儲着色器文本的字符串 string vs, fs; // 分別讀取着色器文件中的文本到字符串 std::ifstream VertexShaderStream(vsShaderName, std::ios::in); if (VertexShaderStream.is_open()) { std::stringstream sstr; sstr << VertexShaderStream.rdbuf(); vs = sstr.str(); VertexShaderStream.close(); } else { printf("Error to open %s\n", vsShaderName); getchar(); exit(0); } std::ifstream FragmentShaderStream(fsShaderName, std::ios::in); if (FragmentShaderStream.is_open()) { std::stringstream sstr; sstr << FragmentShaderStream.rdbuf(); fs = sstr.str(); FragmentShaderStream.close(); } // 添加頂點着色器和片斷着色器 AddShader(ShaderProgram, vs.c_str(), GL_VERTEX_SHADER); AddShader(ShaderProgram, fs.c_str(), GL_FRAGMENT_SHADER); // 連接shader着色器程序,並檢查程序相關錯誤 GLint Success = 0; GLchar ErrorLog[1024] = { 0 }; glLinkProgram(ShaderProgram); glGetProgramiv(ShaderProgram, GL_LINK_STATUS, &Success); if (Success == 0) { glGetProgramInfoLog(ShaderProgram, sizeof(ErrorLog), NULL, ErrorLog); fprintf(stderr, "Error linking shader program: '%s'\n", ErrorLog); exit(1); } // 檢查驗證在當前的管線狀態程序是否能夠被執行 glValidateProgram(ShaderProgram); glGetProgramiv(ShaderProgram, GL_VALIDATE_STATUS, &Success); if (!Success) { glGetProgramInfoLog(ShaderProgram, sizeof(ErrorLog), NULL, ErrorLog); fprintf(stderr, "Invalid shader program: '%s'\n", ErrorLog); exit(1); } glUseProgram(ShaderProgram); //統一變量位置 MatrixID = glGetUniformLocation(ShaderProgram, "gWVP"); MatrixID2= glGetUniformLocation(ShaderProgram, "gWorld"); m_dirLightLocation.Color = glGetUniformLocation(ShaderProgram,"gDirectionalLight.Color"); m_dirLightLocation.AmbientIntensity = glGetUniformLocation(ShaderProgram,"gDirectionalLight.AmbientIntensity"); m_dirLightLocation.Direction = glGetUniformLocation(ShaderProgram,"gDirectionalLight.Direction"); m_dirLightLocation.DiffuseIntensity = glGetUniformLocation(ShaderProgram,"gDirectionalLight.DiffuseIntensity"); } int main(int argc, char ** argv) { // 初始化GLUT glutInit(&argc, argv); // 顯示模式:雙緩衝、RGBA glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); // 窗口設置 glutInitWindowSize(windowWidth, windowHeight); // 窗口尺寸 glutInitWindowPosition(100, 100); // 窗口位置 glutCreateWindow("terrainTest2"); // 窗口標題 GLenum res = glewInit(); if (res != GLEW_OK) { fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res)); return 1; } // 開始渲染 glutDisplayFunc(RenderScenceCB); // 註冊鍵盤事件 glutKeyboardFunc(SpecialKeyboardCB); //註冊鼠標事件 glutMouseFunc(mouseCB); glutMotionFunc(mouseMotionCB); mouseX = windowWidth / 2; mouseY = windowHeight / 2; // 緩存清空後的顏色值 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //建立頂點 CreateVertexBuffer(); //建立索引 CreateIndexBuffer(); //建立uv CreateUVBuffer(); //建立貼圖 CreateTexture(); //建立法線 CreateNormal(); // 編譯着色器 CompileShaders(); //開啓深度測試 glEnable(GL_DEPTH_TEST); // 通知開始GLUT的內部循環 glutMainLoop(); delete vertices; return 0; }
#version 330 layout (location = 0) in vec3 Position; layout (location = 1) in vec2 vertexUV; layout (location = 2) in vec3 Normal; uniform mat4 gWVP; uniform mat4 gWorld; out vec2 UV; out vec3 Normal0; void main() { gl_Position = gWVP * vec4(Position, 1.0); UV = vertexUV; Normal0 = (gWorld * vec4(Normal, 0.0)).xyz; }
#version 330 in vec2 UV; in vec3 Normal0; out vec4 FragColor; //光照 struct DirectionalLight { vec3 Color; float AmbientIntensity; float DiffuseIntensity; vec3 Direction; }; uniform DirectionalLight gDirectionalLight; uniform sampler2D myTexture; void main() { //環境光 vec4 AmbientColor = vec4(gDirectionalLight.Color, 1.0f) * gDirectionalLight.AmbientIntensity; //漫反射 float DiffuseFactor = dot(normalize(Normal0), -gDirectionalLight.Direction); vec4 DiffuseColor; if (DiffuseFactor > 0) { DiffuseColor = vec4(gDirectionalLight.Color, 1.0f) * gDirectionalLight.DiffuseIntensity * DiffuseFactor; } else { DiffuseColor = vec4(0, 0, 0, 0); } FragColor = texture2D(myTexture, UV.xy) * (AmbientColor + DiffuseColor); }