機能と特長
Aspose.3D FOSS for Python は、複数の業界標準フォーマットで 3D コンテンツを読み取り、構築、書き出すための完全なシーングラフ API を提供します。このページでは、実際のライブラリ API を使用した動作する Python コード例とともに、すべての主要機能領域を文書化しています。.
インストールとセットアップ
以下の単一コマンドで PyPI からライブラリをインストールします:
pip install aspose-3d-foss追加のシステムパッケージ、ネイティブ拡張、コンパイラツールチェーンは不要です。このライブラリは純粋な Python で、Windows、macOS、Linux 上で Python 3.7 から 3.12 をサポートします。.
インストールを確認するには:
from aspose.threed import Scene
scene = Scene()
print("Aspose.3D FOSS installed successfully")
print(f"Root node name: {scene.root_node.name}")機能と特長
フォーマットのサポート
Aspose.3D FOSS for Python は以下のフォーマットの読み書きが可能です:
| フォーマット | 拡張子 | 読み取り | 書き込み | 備考 |
|---|---|---|---|---|
| Wavefront OBJ | .obj | はい | はい | .mtl マテリアル読み込みをサポート |
| STL(バイナリ) | .stl | はい | はい | 往復検証済み(39 テスト) |
| STL (ASCII) | .stl | はい | はい | 往復検証済み |
| glTF 2.0 | .gltf | はい | はい | 完全なシーングラフが保持されています |
| GLB(バイナリ glTF) | .glb | はい | はい | 単一ファイルのバイナリコンテナ |
| COLLADA | .dae | はい | はい | シーン階層とマテリアル |
| 3MF | .3mf | はい | はい | 積層造形フォーマット |
| FBX | .fbx | 部分的 | いいえ | トークナイザは動作中; パーサには既知のバグがあります |
オプション付き OBJ のロード
ObjLoadOptions OBJ ファイルの解析方法を制御します:
from aspose.threed import Scene
from aspose.threed.formats import ObjLoadOptions
options = ObjLoadOptions()
options.enable_materials = True # Load accompanying .mtl file
options.flip_coordinate_system = False # Preserve original handedness
options.normalize_normal = True # Normalize vertex normals to unit length
options.scale = 1.0 # Apply a uniform scale factor at load time
scene = Scene()
scene.open("model.obj", options)
print(f"Loaded {len(scene.root_node.child_nodes)} top-level nodes")STL への保存
StlSaveOptions バイナリと ASCII の出力、およびその他の STL 固有設定を制御します:
from aspose.threed import Scene
from aspose.threed.formats import StlSaveOptions
scene = Scene.from_file("model.obj")
options = StlSaveOptions()
scene.save("output.stl", options)シーングラフ
すべての 3D コンテンツはツリー構造として編成されます Node オブジェクトです。ツリーのルートは scene.root_node.。各ノードは子ノードを含むことができ、そして Entity (メッシュ、カメラ、またはライト) と Transform.
シーン階層の走査
from aspose.threed import Scene
scene = Scene.from_file("model.glb")
def traverse(node, depth=0):
indent = " " * depth
entity_type = type(node.entity).__name__ if node.entity else "none"
print(f"{indent}{node.name} [{entity_type}]")
for child in node.child_nodes:
traverse(child, depth + 1)
traverse(scene.root_node)プログラムでシーンを構築する
from aspose.threed import Scene, Node, Entity
from aspose.threed.entities import Mesh
from aspose.threed.utilities import Vector3
scene = Scene()
root = scene.root_node
##Create a child node and position it
child = root.create_child_node("my_object")
child.transform.translation = Vector3(1.0, 0.0, 0.0)
child.transform.scaling = Vector3(2.0, 2.0, 2.0)
scene.save("constructed.glb")GlobalTransform の検査
GlobalTransform すべての先祖の変換を累積した後のノードのワールド空間変換を示します:
from aspose.threed import Scene
scene = Scene.from_file("model.dae")
for node in scene.root_node.child_nodes:
gt = node.global_transform
print(f"Node: {node.name}")
print(f" World translation: {gt.translation}")
print(f" World scale: {gt.scale}")Mesh API
その Mesh エンティティは、制御点(頂点)、ポリゴン、法線、UV、カラー用の頂点要素を含むジオメトリデータへのアクセスを提供します。.
Mesh ジオメトリの読み取り
from aspose.threed import Scene
from aspose.threed.formats import ObjLoadOptions
options = ObjLoadOptions()
options.enable_materials = True
options.flip_coordinate_system = False
scene = Scene()
scene.open("model.obj", options)
for node in scene.root_node.child_nodes:
if node.entity is None:
continue
mesh = node.entity
print(f"Mesh: {node.name}")
print(f" Vertices: {len(mesh.control_points)}")
print(f" Polygons: {len(mesh.polygons)}")頂点要素へのアクセス
頂点要素は、頂点ごとまたはポリゴンごとのデータを保持します。最も一般的な要素は法線、UV 座標、頂点カラー、スムージンググループです:
from aspose.threed import Scene
from aspose.threed.entities import VertexElementNormal, VertexElementUV
scene = Scene.from_file("model.obj")
for node in scene.root_node.child_nodes:
if node.entity is None:
continue
mesh = node.entity
# Iterate vertex elements to find normals and UVs
for element in mesh.vertex_elements:
if isinstance(element, VertexElementNormal):
print(f" Normals count: {len(element.data)}")
elif isinstance(element, VertexElementUV):
print(f" UV count: {len(element.data)}")マテリアルシステム
Aspose.3D FOSS は 2 つのマテリアルタイプをサポートしています: LambertMaterial (拡散シェーディング)と PhongMaterial (specular shading)。使用時に .mtl ファイルから自動的に両方がロードされます ObjLoadOptions と enable_materials = True.
OBJ からマテリアルを読み取る
from aspose.threed import Scene
from aspose.threed.shading import LambertMaterial, PhongMaterial
from aspose.threed.formats import ObjLoadOptions
options = ObjLoadOptions()
options.enable_materials = True
scene = Scene()
scene.open("model.obj", options)
for node in scene.root_node.child_nodes:
mat = node.material
if mat is None:
continue
print(f"Node: {node.name}")
if isinstance(mat, PhongMaterial):
print(f" Type: Phong")
print(f" Diffuse: {mat.diffuse_color}")
print(f" Specular: {mat.specular_color}")
elif isinstance(mat, LambertMaterial):
print(f" Type: Lambert")
print(f" Diffuse: {mat.diffuse_color}")プログラムでマテリアルを割り当てる
from aspose.threed import Scene, Node
from aspose.threed.shading import PhongMaterial
from aspose.threed.utilities import Vector3
scene = Scene.from_file("model.glb")
material = PhongMaterial()
material.diffuse_color = Vector3(0.8, 0.2, 0.2) # Red diffuse
material.specular_color = Vector3(1.0, 1.0, 1.0) # White specular
##Apply to the first mesh node
for node in scene.root_node.child_nodes:
if node.entity is not None:
node.material = material
break
scene.save("recolored.glb")数学ユーティリティ
この aspose.threed.utilities モジュールは、シーン構築と検査に必要なすべての幾何学的数学型を提供します。.
| クラス | 目的 |
|---|---|
Vector2 | 2D floating-point vector (UV coordinates) |
Vector3 | 3D double-precision vector (positions, normals) |
Vector4 | 4D double-precision vector (homogeneous coordinates) |
FVector3 | 3D single-precision vector (compact storage) |
Quaternion | ジンバルロックなしの回転表現 |
Matrix4 | 4×4 transformation matrix |
BoundingBox | 最小/最大コーナーを持つ軸整列バウンディングボックス |
変換の操作
from aspose.threed.utilities import Vector3, Quaternion, Matrix4
import math
##Build a rotation quaternion from axis-angle
axis = Vector3(0.0, 1.0, 0.0) # Y-axis
angle_rad = math.radians(45.0)
q = Quaternion.from_angle_axis(angle_rad, axis)
print(f"Quaternion: x={q.x:.4f} y={q.y:.4f} z={q.z:.4f} w={q.w:.4f}")
##Convert to rotation matrix
mat = q.to_matrix()
print(f"Rotation matrix row 0: {mat[0, 0]:.4f} {mat[0, 1]:.4f} {mat[0, 2]:.4f}")バウンディングボックスの計算
from aspose.threed import Scene
scene = Scene.from_file("model.stl")
# NOTE: mesh.get_bounding_box() is a stub — it always returns an empty BoundingBox()
# regardless of geometry. Compute bounds manually from control_points:
for node in scene.root_node.child_nodes:
if node.entity is None:
continue
mesh = node.entity
pts = mesh.control_points # returns a copy of the vertex list
if not pts:
continue
xs = [p.x for p in pts]
ys = [p.y for p in pts]
zs = [p.z for p in pts]
print(f"Mesh: {node.name}")
print(f" Min: ({min(xs):.3f}, {min(ys):.3f}, {min(zs):.3f})")
print(f" Max: ({max(xs):.3f}, {max(ys):.3f}, {max(zs):.3f})")アニメーション
Aspose.3D FOSS は、… に基づくアニメーションモデルを提供します AnimationClip, AnimationNode, KeyFrame,、そして KeyframeSequence.。ロードされたファイル(glTF、COLLADA)に格納されたアニメーションデータは、これらのオブジェクトを通じてアクセス可能です。.
アニメーションクリップの読み込み
from aspose.threed import Scene
scene = Scene.from_file("animated.glb")
for clip in scene.animation_clips:
print(f"Clip: {clip.name} ({clip.start:.2f}s – {clip.stop:.2f}s)")
for anim_node in clip.animations:
print(f" Animation node: {anim_node.name}")
for sub in anim_node.sub_animations:
print(f" Sub-animation: {sub.name}")
for bp in anim_node.bind_points:
print(f" Bind point: {bp.name}")ロードと保存のオプション
サポートされているすべてのフォーマットには、解析とシリアライズの動作を制御する対応するオプションクラスがあります。.
| クラス | フォーマット | 主要なプロパティ |
|---|---|---|
ObjLoadOptions | OBJ | enable_materials, flip_coordinate_system, normalize_normal, scale |
StlSaveOptions | STL | バイナリ vs. ASCII 出力モード |
| (glTF はデフォルトを使用します) | glTF / GLB | シーン グラフとマテリアルが自動的に保持されます |
使用例
例 1: OBJ から STL 形式への変換
OBJ ファイル(マテリアル付き)をバイナリ STL に変換し、その過程でメッシュ統計を出力します::
from aspose.threed import Scene
from aspose.threed.formats import ObjLoadOptions
from aspose.threed.formats import StlSaveOptions
##Load OBJ with material support
load_opts = ObjLoadOptions()
load_opts.enable_materials = True
load_opts.flip_coordinate_system = False
load_opts.normalize_normal = True
scene = Scene()
scene.open("input.obj", load_opts)
##Report what was loaded
total_vertices = 0
total_polygons = 0
for node in scene.root_node.child_nodes:
if node.entity is not None:
mesh = node.entity
total_vertices += len(mesh.control_points)
total_polygons += len(mesh.polygons)
print(f" {node.name}: {len(mesh.control_points)} vertices, {len(mesh.polygons)} polygons")
print(f"Total: {total_vertices} vertices, {total_polygons} polygons")
##Save as STL
save_opts = StlSaveOptions()
scene.save("output.stl", save_opts)
print("Saved output.stl")例 2: バッチ glTF から GLB へのパッキング
個別の glTF とテクスチャファイルからなるディレクトリを、自己完結型の GLB バイナリとして再保存します::
import os
from aspose.threed import Scene
input_dir = "gltf_files"
output_dir = "glb_files"
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(input_dir):
if not filename.endswith(".gltf"):
continue
src = os.path.join(input_dir, filename)
dst = os.path.join(output_dir, filename.replace(".gltf", ".glb"))
scene = Scene.from_file(src)
scene.save(dst)
print(f"Packed {filename} -> {os.path.basename(dst)}")例 3: シーングラフの検査とエクスポートレポート
COLLADA ファイルのシーングラフを走査し、メッシュごとの統計を収集して、構造化されたレポートを出力します::
from aspose.threed import Scene
scene = Scene.from_file("assembly.dae")
report = []
def collect(node, path=""):
full_path = f"{path}/{node.name}" if node.name else path
if node.entity is not None:
mesh = node.entity
gt = node.global_transform
report.append({
"path": full_path,
"vertices": len(mesh.control_points),
"polygons": len(mesh.polygons),
"world_x": gt.translation.x,
"world_y": gt.translation.y,
"world_z": gt.translation.z,
})
for child in node.child_nodes:
collect(child, full_path)
collect(scene.root_node)
print(f"{'Path':<40} {'Verts':>6} {'Polys':>6} {'X':>8} {'Y':>8} {'Z':>8}")
print("-" * 78)
for entry in report:
print(
f"{entry['path']:<40} "
f"{entry['vertices']:>6} "
f"{entry['polygons']:>6} "
f"{entry['world_x']:>8.3f} "
f"{entry['world_y']:>8.3f} "
f"{entry['world_z']:>8.3f}"
)ヒントとベストプラクティス
フォーマット選択
- glTF 2.0 / GLB は、マテリアル、アニメーション、複雑な階層を含むシーンの推奨インターチェンジフォーマットです。ポータビリティのために、glTF(テキスト + 外部ファイル)よりも GLB(バイナリ)を優先してください。.
- STL は、下流のコンシューマがスライサー、CAD ツール、またはジオメトリだけが必要なツールである場合に適した選択です。STL にはマテリアルやアニメーションデータが含まれません。.
- OBJ は、広くサポートされており、古いツールとマテリアルデータをやり取りする必要がある場合に適した選択です。.mtl ファイルは .obj ファイルと一緒に必ず保持してください。.
座標系
- 異なるアプリケーションは異なる右左手系の規約を使用します。設定
ObjLoadOptions.flip_coordinate_system = True右手系座標系を使用するツールから OBJ ファイルをインポートする際に、パイプラインが左手系座標を期待している場合、またはその逆の場合に. - フリップを適用する前に、ソースアセットの軸規約を確認してください。二回フリップすると、ジオメトリが正しくなくなります。.
正規化
- 常に設定
ObjLoadOptions.normalize_normal = True下流のパイプラインが単位法線を期待している場合(例:シェーダーに法線を渡すときや、ドット積によるライティング計算を行うとき)。不適切に作成された OBJ ファイルからの正規化されていない法線は、ライティングのアーティファクトを引き起こします。.
パフォーマンス
- ファイルは一度だけ読み込み、メモリ上のシーングラフを変換し、各出力フォーマットごとにディスクから再読み込みしないようにします。単一の
Scene.from_file()呼び出しに続く複数のscene.save()呼び出しは、繰り返しのロードよりも効率的です。. - 大量のバッチを処理する際は、単一の
ObjLoadOptionsまたはStlSaveOptionsインスタンスを作成し、ファイルごとに新しいオプションオブジェクトを構築する代わりに、すべてのファイルで再利用します。.
エラーハンドリング
- ラップ
scene.open()およびscene.save()呼び出しtry/except信頼できない、またはユーザー提供のファイルを処理する際にブロックします。例外メッセージにファイル名を報告することで、バッチパイプラインのデバッグを簡素化します。.
一般的な問題
| 問題 | 原因 | 解決策 |
|---|---|---|
| ロード後にメッシュが鏡像のように表示されます | 座標系の右左手系の不一致 | 切り替え ObjLoadOptions.flip_coordinate_system |
| 法線がゼロ長です | ソースファイルに正規化されていない法線があります | 設定 ObjLoadOptions.normalize_normal = True |
| OBJからマテリアルが読み込まれません | enable_materials です False (デフォルト) | 設定 ObjLoadOptions.enable_materials = True |
| シーンは読み込まれますが、すべてのノードが空です | ファイルはFBX形式です | FBXパーサは開発中です。代わりにOBJ、STL、またはglTFをご使用ください |
| モデルが極端に小さいまたは大きいです | ソースファイルはメートル法以外の単位を使用しています | 適用 ObjLoadOptions.scale 対象の単位に変換するには |
AttributeError オン mesh.polygons | ノードエンティティはメッシュではありません | でガード if node.entity is not None エンティティプロパティにアクセスする前に |
| GLB ファイルはビューアに拒否されました | 保存時に .gltf 拡張子 | 使用する .glb 呼び出す際の拡張子 scene.save() バイナリコンテナをトリガーするために |
よくある質問
サポートされている Python のバージョンは何ですか?? Python 3.7、3.8、3.9、3.10、3.11、3.12 はすべてサポートされています。このライブラリはネイティブ拡張を持たない純粋な Python であるため、CPython が動作するあらゆるプラットフォームで動作します。.
このライブラリには外部依存関係がありますか?? いいえ。Aspose.3D FOSS for Python は Python 標準ライブラリのみを使用します。単一の pip install aspose-3d-foss コマンドで、追加の手順は不要です。.
FBX はサポートされていますか?? FBX トークナイザーは実装されており、バイナリ FBX トークンストリームを解析できますが、トークナイザー上に構築されたシーングラフビルダーには既知のバグがあり、製品レベルでは使用できません。信頼できる本番環境での使用には OBJ、STL、glTF、COLLADA、または 3MF を使用してください。.
商用製品で Aspose.3D FOSS を使用できますか?? はい。このライブラリは MIT ライセンスでリリースされており、ライセンス通知を含める限り、ロイヤリティなしでプロプライエタリおよび商用ソフトウェアでの使用が許可されています。.
バグを報告したりフォーマットをリクエストしたりするにはどうすればよいですか?? リポジトリで issue を開いてください。最小限の再現ファイルと Python バージョン、オペレーティングシステム、ライブラリバージョンを含めてください。 pip show aspose-3d-foss.
API リファレンス概要
コアクラス
Scene: 3Dシーンのトップレベルコンテナ。エントリーポイントはopen(),from_file(),: 、およびsave().Node: シーングラフ内のツリーノード。保持するentity,transform,global_transform,material,child_nodes,: 、およびname.Entity: ノードにアタッチされたオブジェクト(Mesh、Camera、Light)の基底クラス。.Transform: ノードのローカル空間における位置、回転(Quaternion)、およびスケール。.GlobalTransform: すべての祖先変換を累積して計算された、読み取り専用のワールド空間変換。.
Geometry
Mesh: 以下を持つポリゴンメッシュcontrol_points: (頂点リスト) とpolygons.VertexElementNormal: 頂点ごとまたはポリゴンごとの法線ベクトル。.VertexElementUV: 頂点ごとのUVテクスチャ座標。.VertexElementVertexColor: 頂点ごとのカラー データ。.VertexElementSmoothingGroup: ポリゴンのスムージング グループ割り当て。.
マテリアル
LambertMaterial: 拡散シェーディングモデル(diffuse_color: およびemissive_color.PhongMaterial: 鏡面シェーディングモデルに追加specular_color: およびshininess.
: 数学ユーティリティ(aspose.threed.utilities)
Vector2: 2D ベクトル。.Vector3: 3D ダブル精度ベクトル。.Vector4: 4D ダブル精度ベクトル。.FVector3: 3D シングル精度ベクトル。.Quaternion: 回転クォータニオン withfrom_angle_axis(): およびto_matrix().Matrix4: 4×4変換行列。.BoundingBox: 軸平行バウンディングボックス withminimum: およびmaximum: コーナー。.
アニメーション
AnimationClip: アニメーションチャンネルとそのキーフレームのセット用の名前付きコンテナ。.AnimationNode: クリップ内のノードごとのアニメーションデータ。.KeyFrame: 時間と値を持つ単一キーフレーム。.KeyframeSequence: 単一アニメーションプロパティ用のキーフレームの順序付けられたシーケンス。.
ロード / セーブ オプション
ObjLoadOptions: OBJ固有のロード設定::enable_materials,flip_coordinate_system,normalize_normal,scale.StlSaveOptions: STL固有の保存設定(バイナリモードとASCIIモード)。.
カメラとライト
Camera: 投影設定を持つカメラエンティティ、取り付け可能。Node.Light: 光源エンティティ、取り付け可能。Node.