Cách bắt đầu với 3D trong Python

Cách bắt đầu với 3D trong Python

Điều kiện tiên quyết

  • Python 3.8 hoặc mới hơn
  • trình quản lý gói pip

Bước 1 — Cài đặt Gói

Cài đặt Aspose.3D FOSS cho Python từ PyPI:

pip install aspose-3d-foss

Xác minh việc cài đặt:

import aspose.threed as a3d
print(a3d.__version__)

Bước 2 — Tạo Cảnh 3D Đầu Tiên Của Bạn

Một Scene là container gốc cho tất cả các đối tượng 3D. Hàm khởi tạo chấp nhận một thực thể tùy chọn, cảnh cha và tên:

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)

Bước 3 — Thêm một Mesh vào Cảnh

Mesh đại diện cho hình đa giác.
Node gắn các thực thể vào đồ thị cảnh:

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)

Bước 4 — Tải tệp 3D hiện có

Scene.open() tải một tệp 3D từ đĩa hoặc luồng. Nó chấp nhận một đường dẫn và các tùy chọn tải (tùy chọn):

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()))

Để phát hiện định dạng tệp trước khi tải:

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())

Bước 5 — Lưu Đầu ra vào Tệp

Scene.save() xuất cảnh sang bất kỳ định dạng nào được hỗ trợ. Cách tiếp cận được khuyến nghị là tự động phát hiện dựa trên phần mở rộng: Aspose.3D suy ra định dạng từ phần mở rộng của tệp (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")

Bạn cũng có thể truyền một định dạng rõ ràng bằng cách sử dụng các phương thức factory FileFormat.WAVEFRONT_OBJ() hoặc FileFormat.GLTF2(), nhưng việc tự động phát hiện phần mở rộng đơn giản hơn và di động hơn.

Các bước tiếp theo

 Tiếng Việt