OpenGL编程逐步深入(三)在窗口中显示一个三角形

这一节教程的内容会比较少,我们仅仅是对上一节教程中的代码进行扩展,在窗口中渲染一个三角形出来。
本节我们以下图所示正方形来讲解OpenGl中的坐标系统。当沿着Z轴负方向看时,可见顶点的坐标必须在这个正方形内,这样视口变换才可以將它们映射到窗口中的可见区域。
这里写图片描述

点(-1.0,-1.0)对应窗口的左下角,(-1.0,1.0)对应窗口的左上角,依此类推。如果指定一个顶点在这个正方形之外,构成的三角形在这个正方形之外的部分会被裁剪掉,将会看不到这部分。

显示三角形代码

/*

    Copyright 2010 Etay Meiri

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Tutorial 03 - Hello triangle!
*/
#include "stdafx.h"
#include <stdio.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
GLuint VBO;
//创建顶点结构体,用于表示OpenGL中的顶点
struct Vector3f
{
    float x;
    float y;
    float z;
    Vector3f(){}
    Vector3f(float _x, float _y, float _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }
};
static void RenderSceneCB()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);
    glutSwapBuffers();
}


static void InitializeGlutCallbacks()
{
    glutDisplayFunc(RenderSceneCB);
}
static void CreateVertexBuffer()
{
    Vector3f Vertices[3];
    Vertices[0] = Vector3f(-1.0f, -1.0f, 0.0f);
    Vertices[1] = Vector3f(1.0f, -1.0f, 0.0f);
    Vertices[2] = Vector3f(0.0f, 1.0f, 0.0f);

    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices,GL_STATIC_DRAW);
}

int _tmain(int argc, _TCHAR* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowSize(800, 600);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Tutorial 02");

    InitializeGlutCallbacks();
    // Must be done after glut is initialized!
    GLenum res = glewInit();
    if (res != GLEW_OK) {
        fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
        return 1;
    }
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    CreateVertexBuffer();

    glutMainLoop();
    return 0;
}

代码解读

本节代码在上节代码中稍作修改。

Vector3f Vertices[3];
Vertices[0] = Vector3f(-1.0f, -1.0f, 0.0f);
Vertices[1] = Vector3f(1.0f, -1.0f, 0.0f);
Vertices[2] = Vector3f(0.0f, 1.0f, 0.0f);

扩展数组容量,存放三角形的三个顶点。

glDrawArrays(GL_TRIANGLES, 0, 3);

调用绘图函数时將绘制模式改为GL_TRIANGLES(表示绘制三角形),第三个参数改为3,表示使用3个顶点绘制。

编译运行

这里写图片描述

可以看到窗口中显示一个白色的三角形。

posted on 2015-04-13 19:13  岚之山  阅读(291)  评论(0编辑  收藏  举报

导航