とりあえず,ファイル周りの扱いを便利にする関数があるようなので使ってみる.
今回は,OBJファイルとそれに付随するテクスチャを読み込んで表示させたい.Windowに関しては,とりあえずで動くModernGL-Windowお手製のものを使う.
使えるリソース
フォルダ構造
model_loading.py
resources
models/bunny/bunny.obj
などのファイル
コード
# model_loading.py import moderngl as mgl import moderngl_window as mglw from moderngl_window import resources from moderngl_window.resources import programs, scenes from moderngl_window.meta import SceneDescription from moderngl_window.scene import Camera from pathlib import Path import numpy as np class App(mglw.WindowConfig): # Default settings (can be manipulated via kwargs) gl_version = (4, 5) title = "ModernGL Example" window_size = (640, 480) aspect_ratio = window_size[0] / window_size[1] resizable = True resource_dir = Path(__file__).parent.resolve() / "resources" camera = Camera(aspect_ratio=aspect_ratio, near=0.01, far=100.0) def __init__(self, **kwargs): super().__init__(**kwargs) # Resources resources.register_scene_dir((self.resource_dir / "models").resolve()) self.scene = scenes.load(SceneDescription(path="bunny/bunny.obj")) for mesh in self.scene.meshes: print(">> mesh.attributes:", mesh.attributes) print(">> len(self.scene.meshes):", len(self.scene.meshes)) self.camera.set_position(0, 0.05, 0.5) self.camera.look_at(pos=(0, 0, 0)) @classmethod def run(cls): mglw.run_window_config(cls) def render(self, time: float, frametime: float): self.ctx.enable_only(mgl.DEPTH_TEST) self.ctx.clear(1, 0, 0, 0) self.scene.draw( projection_matrix=self.camera.projection.matrix, camera_matrix=self.camera.matrix, time=time) if __name__ == "__main__": App.run()
解説
- line 13:
mglw.WindowConfig
を継承したクラスでWindowを作り始める - lines 14 - 19: Windowの設定あれこれ
- line 20: ここでデータ入力のための大元のフォルダを指定
- lines 27-32: 指定のフォルダから
bunny.obj
を読み込み
- lines 27-32: 指定のフォルダから
- line 22: カメラの情報を保存しておける
Camera
クラス- lines 34 & 35: カメラの位置姿勢を指定
- lines 38 & 39: 既定の関数を用いたメインループ
- lines 41 - 48: 既定の
render
関数を用いてレンダリングするコンテンツを指定