OpenGL(三)三维图形绘制

#include "stdafx.h"
#include<GL/freeglut.h>
#include<GLFW/glfw3.h>

// 绘图棱锥
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // 三维图形由三维空间中的三角形拼接而成
    glBegin(GL_TRIANGLES);

    // 指定棱锥的四个顶点
    GLfloat vertex[4][3] = {
        {0, 0, 0.5},
        {0.2, 0.2, 0},
        {-0.3, 0, 0},
        {0, -0.3, 0}
    };

    // 绘制三角形
    glColor3f(0.5, 0.5, 0.9);
    for (int i = 0; i < 2; i++) {
        for (int j = i + 1; j < 3; j++) {
            for (int k = j + 1; k < 4; k++) {
                glVertex3fv(vertex[i]);
                glVertex3fv(vertex[j]);
                glVertex3fv(vertex[k]);
            }
        }
    }

    glEnd();

    // 绘制顶点连线
    glBegin(GL_LINES);

    glColor3f(1, 0, 0);
    for (int i = 0; i < 3; i++)
    {
        for (int j = i + 1; j < 4; j++) {
            glVertex3fv(vertex[i]);
            glVertex3fv(vertex[j]);
        }
    }

    glEnd();
    glFlush();
}

int main()
{
    glfwInit();
    GLFWwindow* window = glfwCreateWindow(400, 400, "hello, glfw", NULL, NULL);
    glfwMakeContextCurrent(window);
    glfwSwapInterval(10);
    while (glfwWindowShouldClose(window) == GL_FALSE)
    {
        // 绘制棱锥
        display();

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

3d

猜你喜欢

转载自blog.csdn.net/lolimostlovely/article/details/82682634