Python GLTF Library
pygltflib is a Python library for reading, writing, and managing 3D objects in the Khronos Group glTF (GL Transmission Format) and glTF2 formats. It supports the entire GLTF v2 specification, including materials, animations, and extensions, with all attributes being type-hinted. The library is actively maintained, with frequent updates addressing features and bug fixes.
Warnings
- breaking Several deprecated attributes and classes were removed in `pygltflib` version 1.15.x. These include `AlphaMode`, `SparseAccessor`, and `MaterialTexture`.
- breaking The `GLTF2.load()` method now raises a `FileNotFoundError` if the specified file does not exist, rather than failing silently.
- gotcha The default value for `Material.alphaCutoff` changed from `0.5` to `None` in version 1.16.0. This might affect how materials are rendered if you relied on the implicit default for 'MASK' `alphaMode` materials.
- gotcha Handling of image paths and buffer conversions, especially when working with GLB files, can be tricky. By default, images are loaded from/saved to the same directory as the GLTF file.
Install
-
pip install pygltflib
Imports
- GLTF2
from pygltflib import GLTF2
- Scene
from pygltflib import Scene
- Node
from pygltflib import Node
- BufferFormat
from pygltflib import BufferFormat
- glb2gltf
from pygltflib.utils import glb2gltf
Quickstart
import os
from pygltflib import GLTF2, Scene, Node
# Create a new GLTF2 object
gltf = GLTF2()
# Create a scene
scene = Scene(name="My_New_Scene")
gltf.scenes.append(scene)
gltf.scene = 0 # Set the default scene to the first one (index 0)
# Create a simple node (e.g., an empty node)
node = Node(name="My_Node")
gltf.nodes.append(node)
# Link the node to the scene
scene.nodes.append(0) # Referencing the first node (index 0)
# Define a filename
output_filename = "my_simple_scene.gltf"
# Save the GLTF file
try:
gltf.save(output_filename)
print(f"GLTF file saved to {output_filename}")
except Exception as e:
print(f"Error saving GLTF file: {e}")
# Clean up (optional)
if os.path.exists(output_filename):
os.remove(output_filename)
print(f"Cleaned up {output_filename}")