OpenGL绘制绿色网状圆柱 c++
时间: 2023-07-19 11:41:04 浏览: 84
opengl实现任意两点间画圆柱体
下面是使用OpenGL绘制绿色网状圆柱的C++代码:
```c++
#include <GL/glut.h>
#include <cmath>
const int N = 50; // 网格数量
const float PI = 3.1415926f; // 圆周率
void drawCylinder() {
glColor3f(0.0f, 1.0f, 0.0f); // 绿色
glBegin(GL_QUAD_STRIP);
for (int i = 0; i <= N; ++i) {
float angle = 2 * PI / N * i;
float x = cos(angle);
float y = sin(angle);
glVertex3f(x, y, -1.0f);
glVertex3f(x, y, 1.0f);
}
glEnd();
glColor3f(0.0f, 0.0f, 0.0f); // 黑色
glBegin(GL_LINES);
for (int i = 0; i <= N; ++i) {
float angle = 2 * PI / N * i;
float x = cos(angle);
float y = sin(angle);
glVertex3f(x, y, -1.0f);
glVertex3f(x, y, 1.0f);
}
glEnd();
glBegin(GL_POLYGON);
for (int i = 0; i <= N; ++i) {
float angle = 2 * PI / N * i;
float x = cos(angle);
float y = sin(angle);
glVertex3f(x, y, -1.0f);
}
glEnd();
glBegin(GL_POLYGON);
for (int i = 0; i <= N; ++i) {
float angle = 2 * PI / N * i;
float x = cos(angle);
float y = sin(angle);
glVertex3f(x, y, 1.0f);
}
glEnd();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(2.0f, 2.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
drawCylinder();
glutSwapBuffers();
}
void reshape(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, (float)width / height, 0.1f, 100.0f);
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Cylinder");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
```
该程序使用OpenGL库绘制一个绿色的网状圆柱,并使用GLUT库管理窗口和事件。具体实现采用了三个步骤:首先绘制圆柱侧面的网格,然后绘制网格线,最后绘制圆柱两端的多边形。其中,使用GL_QUAD_STRIP绘制圆柱侧面的网格,使用GL_LINES绘制网格线,使用GL_POLYGON绘制圆柱两端的多边形。
阅读全文