如何在 Python 中开始使用 3D
先决条件
- Python 3.8 或更高版本
- pip 包管理器
步骤 1 — 安装软件包
从 PyPI 安装 Aspose.3D FOSS for Python:
pip install aspose-3d-foss验证安装:
import aspose.threed as a3d
print(a3d.__version__)步骤 2 — 创建您的第一个 3D 场景
Scene 是所有 3D 对象的根容器。构造函数接受可选的实体、父场景和名称:
import aspose.threed as a3d
# Create an empty scene (CLM-3d-35d727)
scene = a3d.Scene()
# Access the root node of the scene (CLM-3d-859ac2)
root = scene.root_node()
print("Root node:", root)第3步 — 将网格添加到场景
Mesh 表示多边形几何。Node 将实体附加到场景图:
import aspose.threed as a3d
scene = a3d.Scene()
# Create a named mesh (CLM-3d-529c11)
mesh = a3d.Mesh("my_mesh")
# Create a node and attach the mesh (CLM-3d-0edae8)
node = a3d.Node("my_node", mesh)
# Add the node as a child of the root (CLM-3d-a403f5)
scene.root_node().add_child_node(node)第4步 — 加载现有的3D文件
Scene.open() 从磁盘或流加载 3D 文件。它接受路径和可选的加载选项:
import aspose.threed as a3d
# Load an OBJ file (CLM-3d-d84964)
scene = a3d.Scene()
scene.open("model.obj")
# Inspect the loaded scene
root = scene.root_node()
print("Child nodes:", len(root.child_nodes()))在加载之前检测文件格式:
import aspose.threed as a3d
# Detect the format from a file name (CLM-3d-d2de62)
fmt = a3d.FileFormat.detect(None, "model.fbx")
if fmt:
print("Detected format:", fmt.extension())步骤 5 — 将输出保存到文件
Scene.save() 将场景导出为任何受支持的格式。推荐的方法是基于扩展名的自动检测:Aspose.3D 根据文件扩展名推断格式(CLM-3d-8051bd、CLM-3d-b28d7a、CLM-3d-de8e1a):
import aspose.threed as a3d
scene = a3d.Scene()
# ... populate scene ...
# Save as Wavefront OBJ — extension auto-detects the format
scene.save("output.obj")
# Save as glTF 2.0 binary — .glb extension triggers binary GLB output
scene.save("output.glb")您也可以使用工厂方法 FileFormat.WAVEFRONT_OBJ() 或 FileFormat.GLTF2() 传递显式格式,但扩展名自动检测更简单且更具可移植性。
下一步
- 如何在 Python 中加载 3D 模型 — 格式、选项、场景图遍历
- 如何在 Python 中转换 3D 模型 — 批量转换工作流
- 如何在 Python 中构建网格几何体 — 控制点、多边形、法线
- 常见问题解答 — 常见问题与故障排除