Giới thiệu
3D content rarely stays in a single format for its entire lifetime. A model may originate as an OBJ file exported from a modelling application, travel through a 3D printing pipeline as STL, appear in a web application as glTF, and end up in an additive manufacturing tool as 3MF. Each format serves a different audience and a different downstream tool, and conversion between them is something most 3D pipelines need to handle reliably.
Python là lựa chọn tự nhiên cho công việc này: các script shell quá mong manh, và việc tích hợp đầy đủ công cụ DCC (digital content creation) quá nặng cho xử lý hàng loạt. Điều bạn cần là một thư viện có thể tải bất kỳ định dạng nào trong số này, cung cấp cho bạn một đồ thị cảnh nhất quán, và ghi lại ra bất kỳ định dạng đích nào mà không cần giao diện người dùng đồ họa hay driver đồ họa.
Aspose.3D FOSS cho Python (aspose-3d-foss, giấy phép MIT) lấp đầy khoảng trống đó. Hướng dẫn này trình bày các lộ trình chuyển đổi phổ biến nhất với các ví dụ mã đầy đủ, có thể chạy được.
Các định dạng nào Aspose.3D FOSS hỗ trợ?
| Định dạng | Extension(s) | Tải | Lưu | Trường hợp sử dụng phổ biến |
|---|---|---|---|---|
| Wavefront OBJ | .obj | Có | Có | Trao đổi từ các công cụ mô hình hoá; .mtl các tệp vật liệu được hỗ trợ |
| STL | .stl | Có | Có | 3D printing, CAD export; binary and ASCII variants |
| glTF 2.0 / GLB | .gltf, .glb | Có | Có | Trình xem web, engine trò chơi; GLB là phiên bản nhị phân tự chứa |
| COLLADA | .dae | Có | Có | Nhập từ các công cụ hoạt hình; ColladaSaveOptions hỗ trợ xuất |
| 3MF | .3mf | Có | Có | Sản xuất gia tăng, siêu dữ liệu in phong phú hơn so với STL |
Việc phát hiện định dạng được thực hiện tự động dựa trên phần mở rộng tệp. Các lớp tùy chọn riêng cho định dạng (ObjLoadOptions, StlSaveOptions, GltfSaveOptions) có sẵn khi bạn cần kiểm soát chi tiết.
Lưu ý về FBX: Thư viện bao gồm một bộ phân tích FBX một phần để nhập. FBX không được khuyến nghị cho quy trình chuyển đổi sản xuất trong phiên bản này; thay vào đó, hãy sử dụng OBJ hoặc glTF làm định dạng trung gian.
OBJ sang STL: Chuẩn bị mô hình cho in 3D
OBJ là định dạng xuất ra phổ biến nhất từ các công cụ mô hình hoá và điêu khắc. STL là ngôn ngữ chung của các slicer in 3D. Việc chuyển đổi giữa chúng chỉ cần một lệnh duy nhất.
from aspose.threed import Scene
from aspose.threed.formats import StlSaveOptions
scene = Scene.from_file("model.obj")
opts = StlSaveOptions()
scene.save("model.stl", opts)
STL chỉ mã hoá các mặt tam giác. Nếu tệp OBJ của bạn chứa các mặt tứ giác hoặc n-gon, bộ xuất sẽ tự động chia tam giác chúng trước khi ghi. Nếu bạn muốn kiểm soát việc chia tam giác một cách rõ ràng trước khi lưu, hãy gọi mesh.triangulate() trên mỗi lưới trong cảnh:
from aspose.threed import Scene
from aspose.threed.entities import Mesh
from aspose.threed.formats import StlSaveOptions
scene = Scene.from_file("model.obj")
def triangulate_all(node):
for entity in list(node.entities):
if isinstance(entity, Mesh):
tri_mesh = entity.triangulate()
# Attach the triangulated mesh via add_entity
node.add_entity(tri_mesh)
for child in node.child_nodes:
triangulate_all(child)
triangulate_all(scene.root_node)
scene.save("model_triangulated.stl", StlSaveOptions())
OBJ sang glTF: Xuất ra cho Web và các Engine Game
glTF 2.0 là định dạng trao đổi ưu tiên cho các bộ render thời gian thực, trình xem WebGL và các engine game như Babylon.js, Three.js và Unity. GLB (phiên bản nhị phân) gói geometry, texture và material vào một tệp duy nhất tự chứa, giúp việc phục vụ qua HTTP dễ dàng hơn.
from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions
scene = Scene.from_file("model.obj")
##Save as JSON-based glTF (external buffer)
opts_gltf = GltfSaveOptions()
scene.save("model.gltf", opts_gltf)
##Save as self-contained GLB binary: preferred for web delivery
scene.save("model.glb", GltfSaveOptions())
Định dạng được suy ra từ phần mở rộng tệp: .gltf tạo ra cặp JSON+binary-buffer; .glb tạo ra tệp nhị phân đơn. Dữ liệu vật liệu OBJ (LambertMaterial, PhongMaterial) được chuyển tiếp tới biểu diễn vật liệu glTF PBR khi có tương đương.
STL sang glTF: Từ đầu ra của máy quét hoặc CAD tới Web
Các tệp STL từ máy quét 3D và hệ thống CAD là các đầu vào phổ biến cần được làm cho có thể xem trên web. STL chỉ chứa hình học tam giác và không có dữ liệu vật liệu, vì vậy việc chuyển đổi là đơn giản.
from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions
scene = Scene.from_file("scan.stl")
scene.save("scan.glb", GltfSaveOptions())
Nếu tệp STL được tạo bởi công cụ CAD có hệ tọa độ bất thường (Z-up so với Y-up), bạn có thể kiểm tra và sửa đổi phép biến đổi của nút gốc trước khi lưu:
from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions
scene = Scene.from_file("cad_export.stl")
##Rotate 90 degrees around X to convert Z-up to Y-up
root = scene.root_node
root.transform.set_euler_angles(-90.0, 0.0, 0.0)
scene.save("cad_export_yup.glb", GltfSaveOptions())
glTF sang 3MF: Chuẩn bị cho Sản xuất Gia tăng
3MF is a modern 3D printing format backed by the 3MF Consortium. It supports richer metadata than STL (colour, material assignments, build instructions) and is accepted by slicer software such as PrusaSlicer and Bambu Studio. If you are delivering models from a web viewer into a printing workflow, converting GLB to 3MF is a useful step.
from aspose.threed import Scene
from aspose.threed import FileFormat
from aspose.threed.formats import SaveOptions
scene = Scene.from_file("model.glb")
scene.save("model.3mf")
Định dạng 3MF được phát hiện tự động từ .3mf phần mở rộng. Để kiểm soát rõ ràng, truyền một SaveOptions đối tượng được cấu hình cho 3MF.
Mẫu Chuyển Đổi Hàng Loạt
Trong thực tế, các nhiệm vụ chuyển đổi hoạt động trên các thư mục chứa nhiều tệp thay vì từng tệp riêng lẻ. Mẫu dưới đây xử lý một thư mục các tệp OBJ và chuyển đổi mỗi tệp sang GLB, với việc xử lý lỗi riêng cho từng tệp để một tệp lỗi không làm dừng toàn bộ quá trình.
import os
from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions
input_dir = "./obj_files"
output_dir = "./glb_files"
os.makedirs(output_dir, exist_ok=True)
opts = GltfSaveOptions()
results = {"ok": [], "failed": []}
for filename in os.listdir(input_dir):
if not filename.lower().endswith(".obj"):
continue
src = os.path.join(input_dir, filename)
stem = os.path.splitext(filename)[0]
dst = os.path.join(output_dir, stem + ".glb")
try:
scene = Scene.from_file(src)
scene.save(dst, opts)
results["ok"].append(filename)
print(f"OK {filename} -> {stem}.glb")
except Exception as exc:
results["failed"].append((filename, str(exc)))
print(f"ERR {filename}: {exc}")
print(f"\n{len(results['ok'])} converted, {len(results['failed'])} failed.")
if results["failed"]:
for name, reason in results["failed"]:
print(f" {name}: {reason}")
Mẫu này mở rộng một cách tự nhiên sang các cặp định dạng nguồn/đích khác: thay đổi bộ lọc phần mở rộng và the SaveOptions lớp cho bất kỳ sự kết hợp nào trong bảng hỗ trợ ở trên.
Kết luận
Aspose.3D FOSS cho Python giúp việc chuyển đổi định dạng trở nên đơn giản: load with Scene.from_file, tùy chọn kiểm tra hoặc sửa đổi scene graph, sau đó lưu với định dạng phù hợp SaveOptions.Thư viện xử lý triangulation, coordinate normalization và format-specific quirks một cách nội bộ.
Để xem danh sách đầy đủ các class và method, hãy xem API Reference. Để tìm hiểu sâu hơn về mô hình scene graph (nodes, meshes, transforms), xem:
- Class Scene: tải, lưu và metadata cấp scene
- Class Node: hierarchy, transforms, và entity attachment
- Class Mesh: vertex data, polygons, và vertex elements
- Cách tải mô hình 3D trong Python
- PyPI: aspose-3d-foss trên PyPI