PyOpenGL을 통한 3D 모델 로딩 및 렌더링

PyOpenGL은 Python에서 OpenGL을 사용하여 3D 그래픽을 생성하고 조작할 수 있는 강력한 라이브러리입니다. 이를 통해 3D 모델을 로딩하고 렌더링할 수 있습니다. 이번 포스트에서는 PyOpenGL을 사용하여 3D 모델을 로딩하고 화면에 렌더링하는 방법을 알아보겠습니다.

1. PyOpenGL 설치하기

PyOpenGL을 사용하기 위해서는 먼저 설치해야 합니다. 아래의 명령을 사용하여 PyOpenGL을 설치할 수 있습니다.

pip install PyOpenGL

2. 3D 모델 로딩하기

3D 모델을 로딩하려면 모델 파일을 읽고 처리해야 합니다. PyOpenGL은 다양한 파일 형식을 지원하며, 대표적으로 Wavefront obj 파일 형식을 사용할 수 있습니다.

아래는 예제로 model.obj 파일을 로딩하는 코드입니다.

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import shaders
import glm
import numpy as np

def load_model(filename):
    vertices = []
    normals = []
    texcoords = []
    faces = []

    with open(filename, "r") as file:
        for line in file:
            if line.startswith("#"):
                continue
            data = line.strip().split(" ")
            if data[0] == "v":
                vertices.append(list(map(float, data[1:4])))
            elif data[0] == "vn":
                normals.append(list(map(float, data[1:4])))
            elif data[0] == "vt":
                texcoords.append(list(map(float, data[1:3])))
            elif data[0] == "f":
                face = []
                for i in range(1, len(data)):
                    indices = data[i].split("/")
                    indices = [int(index) if index != "" else -1 for index in indices]
                    face.append(indices)
                faces.append(face)

    return vertices, normals, texcoords, faces

위의 코드는 Wavefront obj 파일을 읽어와서 정점, 법선, 텍스처 좌표, 면 정보를 추출하는 load_model 함수입니다.

3. 3D 모델 렌더링하기

3D 모델을 렌더링하기 위해서는 OpenGL을 사용해야 합니다. PyOpenGL을 사용하여 OpenGL을 조작할 수 있습니다.

아래는 예제로 3D 모델을 렌더링하는 코드입니다.

def render_model(vertices, normals, texcoords, faces):
    glBegin(GL_TRIANGLES)

    for face in faces:
        for vertex_indices in face:
            vertex_index = vertex_indices[0]
            normal_index = vertex_indices[2]
            texcoord_index = vertex_indices[1]

            vertex = vertices[vertex_index - 1]
            normal = normals[normal_index - 1]
            texcoord = texcoords[texcoord_index - 1]

            glNormal3f(*normal)
            glTexCoord2f(*texcoord)
            glVertex3f(*vertex)

    glEnd()

위의 코드는 render_model 함수로, 정점, 법선, 텍스처 좌표, 면 정보를 입력으로 받아서 3D 모델을 렌더링합니다.

4. OpenGL 윈도우 생성하기

먼저 OpenGL 윈도우를 생성하여 3D 모델을 렌더링할 수 있는 공간을 만들어야 합니다.

아래는 예제로 OpenGL 윈도우를 생성하는 코드입니다.

def init_window(width, height):
    glutInit()
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
    glutInitWindowSize(width, height)
    glutCreateWindow(b"PyOpenGL 3D Model Rendering")

def set_viewport(width, height):
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, width / height, 0.1, 100.0)
    glMatrixMode(GL_MODELVIEW)

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    
    # 카메라 위치 및 방향 설정
    gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0)
    
    # 3D 모델 렌더링
    render_model(vertices, normals, texcoords, faces)
    
    glutSwapBuffers()

def main():
    vertices, normals, texcoords, faces = load_model("model.obj")

    init_window(800, 600)
    set_viewport(800, 600)

    glEnable(GL_DEPTH_TEST)

    glutDisplayFunc(display)
    glutMainLoop()

if __name__ == "__main__":
    main()

위의 코드는 OpenGL 윈도우를 생성하고 렌더링을 위한 초기화 작업과 화면 갱신을 처리하는 코드입니다.

마무리

이제 PyOpenGL을 사용하여 3D 모델을 로딩하고 렌더링하는 방법에 대해 알아보았습니다. PyOpenGL은 다양한 기능과 함께 강력하고 유연한 라이브러리입니다. 다양한 프로젝트나 시각화 작업에 적용해 보세요.

#pyopengl #3D모델 #렌더링