1. 程式人生 > >OpenGL程式設計指南2:環境搭配與第一個例項剖析

OpenGL程式設計指南2:環境搭配與第一個例項剖析

#include <iostream>  
using namespace std;  
#include "vgl.h"  
#include "LoadShaders.h"  
//announce Global variable and other struct
enum VAO_IDs { Triangles, NumVAOs };  
enum Buffer_IDs { ArrayBuffer, NumBuffers };  
enum Attrib_IDs { vPosition = 0 };  
  
GLuint  VAOs[NumVAOs];  
GLuint  Buffers[NumBuffers];   
const GLuint NumVertices = 6;  

// init()uesed to setdata  used later,eg. vertex, texture
void init(void) {  
    glGenVertexArrays(NumVAOs, VAOs);// important!
    glBindVertexArray(VAOs[Triangles]);  
    //firstly ensure the triangles we wanna to render position   
    GLfloat  vertices[NumVertices][2] = {  
        { -0.90, -0.90 },  // Triangle 1  
        {  0.85, -0.90 },  
        { -0.90,  0.85 },  
        {  0.90, -0.85 },  // Triangle 2  
        {  0.90,  0.90 },  
        { -0.85,  0.90 }  
    };  
    glGenBuffers(NumBuffers, Buffers);  
    glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);  
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices),  
                     vertices, GL_STATIC_DRAW);  
    // Secondly,refer vertex & fragment shaders  
    ShaderInfo  shaders[] = {  
            { GL_VERTEX_SHADER, "triangles.vert" },  
            { GL_FRAGMENT_SHADER, "triangles.frag" },  
            { GL_NONE, NULL }  
    };  
    // LoadShaders() is definited by users 
    // simplify the process for GPU preparing shaders 
    GLuint program = LoadShaders(shaders);  
    glUseProgram(program);  
    // lastly is shader plumbing (the pipeline of shader)  
    // connect the data and variables of shader
    glVertexAttribPointer(vPosition, 2, GL_FLOAT,  
                          GL_FALSE, 0, BUFFER_OFFSET(0));  
    glEnableVertexAttribArray(vPosition);  
}    
// we do render here, it's favored by OpenGL
// nearly all display() will executive following 3 steps
void display(void) {  
    // 1.glClear():clear window 
    glClear(GL_COLOR_BUFFER_BIT);  
    // 2.render our object
    glBindVertexArray(VAOs[Triangles]);  
    glDrawArrays(GL_TRIANGLES, 0, NumVertices);  
    // 3.Requests the image drawing to the window
    glFlush();  
}  
// main():used to create window,Call init(),last,goto event loop.
// here we also can see some function which header is 'gl'.
// all these functions are from Third-party libraries,
// So, we can use OpenGL on any OS.
// here,we use GLUT&GLEW.  
int main(int argc, char** argv) {  
    glutInit(&argc, argv);  
    glutInitDisplayMode(GLUT_RGBA);  
    glutInitWindowSize(512, 512);  
    glutInitContextVersion(4, 3);  
    glutInitContextProfile(GLUT_CORE_PROFILE);  
    glutCreateWindow(argv[0]);  
    glewExperimental= GL_TRUE;
    if (glewInit()) {  
        cerr << "Unable to initialize GLEW ... exiting" << endl; exit(EXIT_FAILURE);  
    }  
    init();  
    glutDisplayFunc(display);  
    glutMainLoop();  
}  
剖析1—如何傳遞頂點資料