openGL学习笔记十五: 绘制带颜色的立方体

代码如下:


struct Vertex {
	unsigned char r, g, b, a;
	float x, y, z;
};

// 绘制
static void render(GLFWwindow * window) {

	glClearColor(0, 0, 0, 1);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//立方体4个面的顶点数据
	Vertex cubeVertices[] =
	{
		{ 255, 0, 0, 255, -1.0f, -1.0f, 1.0f },
		{ 255, 0, 0, 255, 1.0f, -1.0f, 1.0f },
		{ 255, 0, 0, 255, 1.0f, 1.0f, 1.0f },
		{ 255, 0, 0, 255, -1.0f, 1.0f, 1.0f },

		{ 0, 255, 0, 255, -1.0f, -1.0f, -1.0f },
		{ 0, 255, 0, 255, -1.0f, 1.0f, -1.0f },
		{ 0, 255, 0, 255, 1.0f, 1.0f, -1.0f },
		{ 0, 255, 0, 255, 1.0f, -1.0f, -1.0f },

		{ 0, 0, 255, 255, -1.0f, 1.0f, -1.0f },
		{ 0, 0, 255, 255, -1.0f, 1.0f, 1.0f },
		{ 0, 0, 255, 255, 1.0f, 1.0f, 1.0f },
		{ 0, 0, 255, 255, 1.0f, 1.0f, -1.0f },

		{ 0, 255, 255, 255, -1.0f, -1.0f, -1.0f },
		{ 0, 255, 255, 255, 1.0f, -1.0f, -1.0f },
		{ 0, 255, 255, 255, 1.0f, -1.0f, 1.0f },
		{ 0, 255, 255, 255, -1.0f, -1.0f, 1.0f },

		{ 255, 0, 255, 255, 1.0f, -1.0f, -1.0f },
		{ 255, 0, 255, 255, 1.0f, 1.0f, -1.0f },
		{ 255, 0, 255, 255, 1.0f, 1.0f, 1.0f },
		{ 255, 0, 255, 255, 1.0f, -1.0f, 1.0f },

		{ 255, 255, 255, 255, -1.0f, -1.0f, -1.0f },
		{ 255, 255, 255, 255, -1.0f, -1.0f, 1.0f },
		{ 255, 255, 255, 255, -1.0f, 1.0f, 1.0f },
		{ 255, 255, 255, 255, -1.0f, 1.0f, -1.0f }
	};

	for(int i = 0; i < 24; ++i) {
		cubeVertices[i].z -= 5;
	}

#if 1
	glEnable(GL_DEPTH_TEST); //启用深度测试
	glInterleavedArrays(GL_C4UB_V3F, 0, cubeVertices);  //确保 cubeVertices 数据格式和GL_C4UB_V3F 一致 这种方式更高效
#else

	glEnable(GL_DEPTH_TEST); //启用深度测试

	glEnableClientState(GL_VERTEX_ARRAY); //启动顶点缓冲
	glEnableClientState(GL_COLOR_ARRAY);  //启动颜色缓冲
	glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &cubeVertices[0].x); //指定顶点缓冲数据
	glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), cubeVertices);//指定颜色缓冲数据
#endif

	glDrawArrays(GL_QUADS, 0, 24);//绘制矩形

	glfwSwapBuffers(window);
	glfwPollEvents();
}

运行结果:

openGL学习笔记十五: 绘制带颜色的立方体_第1张图片

你可能感兴趣的:(#,1.7,OpenGL)