[Modern OpenGL系列(四)]在OpenGL中使用Shader

本文已同步发表在CSDN:http://blog.csdn.net/wenxin2011/article/details/51347440


上一篇文章中已经介绍了OpenGL窗口的创建。本文接着说如何用OpenGL绘制一个三角形。
1 . 添加头文件mesh.h,代码如下:

#pragma once

#include <glm\glm.hpp>
#include <GL\glew.h>

class Vertex
{
public:
	Vertex(const glm::vec3& pos)
	{
		this->pos = pos;
	}
protected:
private:
	glm::vec3 pos;
};

class Mesh
{
public:
	Mesh(Vertex* vertices, unsigned int numVertices);

	void Draw();
	
	virtual ~Mesh();

protected:
private:
	Mesh(const Mesh& other);
	void operator=(const Mesh& other);

	enum
	{
		POSITION_VB,
		NUM_BUFFERS
	};

	GLuint m_vertexArrayObject;
	GLuint m_vertexArrayBuffers[NUM_BUFFERS];
	unsigned int m_drawCount;
};

2 . 添加类mesh.cpp,代码如下:

#include "mesh.h"

Mesh::Mesh(Vertex* vertices, unsigned int numVertices)
{
	m_drawCount = numVertices;

	glGenVertexArrays(1, &m_vertexArrayObject);
	glBindVertexArray(m_vertexArrayObject);

	glGenBuffers(NUM_BUFFERS, m_vertexArrayBuffers);
	glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[POSITION_VB]);
	glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(vertices[0]),  vertices, GL_STATIC_DRAW);
	
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

	glBindVertexArray(0);
}

Mesh::~Mesh()
{
	glDeleteVertexArrays(1, &m_vertexArrayObject);
}

void Mesh::Draw()
{
	glBindVertexArray(m_vertexArrayObject);
	glDrawArrays(GL_TRIANGLES, 0, m_drawCount);

	glBindVertexArray(0);
}

3 . 修改主类main.cpp,代码如下:

#include <GL\glew.h>
#include "display.h"
#include "mesh.h"

int main(int argc, char** argv)
{
	// 设置窗体大小和标题
	Display display(400, 300, "hello world!");

	// 设置三角形顶点
	Vertex vertices[] = { Vertex(glm::vec3(-0.5, -0.5, 0)), Vertex(glm::vec3(0, 0.5, 0)), Vertex(glm::vec3(0.5, -0.5, 0)), };

	// 生成网格
	Mesh mesh(vertices, sizeof(vertices) / sizeof(vertices[0]));

	while (!display.IsClosed())
	{
		display.Clear(0.0f, 1.0f, 0.0f, 1.0f);

		// 绘制三角形
		mesh.Draw();	

		display.Update();// 刷新
	}

	return 0;
}

本文整理自YouTube视频教程#3.5 Intro to Modern OpenGL Tutorial: Meshes


声明:本文欢迎转载和分享,但是请尊重作者的劳动成果,转载分享时请注明出处:http://www.cnblogs.com/davidsheh/p/5471689.html 。同时,码字实在不易,如果你觉得笔者分享的笔记对你有点用处,请顺手点击下方的推荐,谢谢!

posted @ 2016-05-08 21:31  Sheh伟伟  阅读(486)  评论(0编辑  收藏  举报