03->OpenGL多邊形,glut實現三角形條帶和三角形扇
阿新 • • 發佈:2018-08-28
pub 技術分享 oat single 頂點 rip ++ {} void
圖形學中基本圖元是多邊形,一般要求是凸多邊形,三角形是最簡單的凸多邊形,在圖形渲染中比一般多邊形其繪制速度快。今天學習OpenGL繪制三角形條帶和三角形扇基礎。編程環境!
1. 三角形條帶
指定頂點序列,按順序每三個頂點畫一個三角形。主要是在畫的時候指定參數GL_TRIANGLE_STRIP。(如頂點序列為{0,1,2,3,4,5,6,7},則0,1,2形成一個三角形,1,2,3形成一個三角形,以此類推)
#include <glut.h>
class Point2d { public: GLfloat x = 0.0f; GLfloat y = 0.0f; Point2d(const GLfloat &a, const GLfloat &b) : x(a), y(b) {} Point2d() {} };// GL_TRANGLE_STRIP 三角形條帶 void triangles(void) { Point2d p[8]; p[0] = Point2d(-0.5f, -0.8f); p[1] = Point2d(-0.35f, 0.8f); p[2] = Point2d(-0.2f, -0.8f); p[3] = Point2d(0.0f, 0.8f); p[4] = Point2d(0.2f, -0.8f); p[5] = Point2d(0.35f, 0.8f); p[6] = Point2d(0.5f, -0.8f); p[7] = Point2d(0.75f, 0.8f); glColor3f(0.38f, 1.0f, 0.2f);
glPolygonMode(GL_FRONT, GL_LINE); glPolygonMode(GL_BACK, GL_LINE); glLineWidth(2.0f); glBegin(GL_TRIANGLE_STRIP); for (int i = 0; i < 8; ++i) { glVertex2f(p[i].x, p[i].y); } glEnd(); glFlush(); }int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(100, 100); glutInitWindowSize(600, 600); glutCreateWindow("三角形條帶"); glutDisplayFunc(&triangles); glutMainLoop(); }
2. 三角形扇
指定頂點序列,第一個為頂點,後續按順序每兩個頂點與第一個頂點形成三角形,主要是在畫的時候指定參數GL_TRIANGLE_FAN。(如頂點序列為{0,1,2,3,4,5,6,7},則0,1,2形成一個三角形,0,2,3形成一個三角形,0,3,4形成一個三角形,以此類推)
#include <glut.h> class Point2d { public: GLfloat x = 0.0f; GLfloat y = 0.0f; Point2d(const GLfloat &a, const GLfloat &b) : x(a), y(b) {} Point2d() {} }; // 扇形 void fan(void) { Point2d p[8]; p[0] = Point2d(-0.8f, 0.0f); p[1] = Point2d(0.0f, 0.8f); p[2] = Point2d(0.4f, 0.5f); p[3] = Point2d(0.7f, 0.2f); p[4] = Point2d(0.7f, -0.2f); p[5] = Point2d(0.4f, -0.5f); p[6] = Point2d(0.0f, -0.8f); glColor3f(0.38f, 1.0f, 0.2f); glPolygonMode(GL_FRONT, GL_LINE); glPolygonMode(GL_BACK, GL_LINE); glLineWidth(1.0f); glBegin(GL_TRIANGLE_FAN); for (int i = 0; i < 7; ++i) { glVertex2f(p[i].x, p[i].y); } glEnd(); glFlush(); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(100, 100); glutInitWindowSize(600, 600); glutCreateWindow("三角形扇"); glutDisplayFunc(&fan); glutMainLoop(); }
03->OpenGL多邊形,glut實現三角形條帶和三角形扇