How to Build a 3D Mesh Programmatically in Python
Aspose.3D FOSS for Python lets you build 3D geometry entirely in code — no external modelling tool required. You create a Mesh, populate it with vertex positions (control_points) and face definitions (polygons), attach optional vertex attributes such as normals, then save the scene to any supported format.
Step-by-Step Guide
Common Issues
| Issue | Resolution |
|---|---|
IndexError in create_polygon | Verify that all indices are within range(len(mesh.control_points)). Indices are 0-based. |
| Normals count does not match vertex count | When using MappingMode.CONTROL_POINT + ReferenceMode.DIRECT, normals.data must have exactly len(control_points) entries. |
| Mesh missing from saved file | Confirm that node.add_entity(mesh) was called before scene.save(). A mesh not attached to any node is not exported. |
| Wrong winding order (face appears invisible) | Counter-clockwise vertex order produces an outward-facing normal. Reverse the index order in create_polygon to flip it. |
polygon_count returns 0 | polygon_count reads the same list as polygons. If create_polygon was not called, the list is empty. |
| Normals appear incorrect in viewer | Ensure all normal vectors are unit-length. Compute with n / abs(n) or pass pre-normalised values. |
Frequently Asked Questions
What is the difference between Vector3 and Vector4 for control points?
control_points stores Vector4 objects. The w component is the homogeneous coordinate: use w=1 for vertex positions and w=0 for direction vectors such as normals. Vector3 is used for transforms (translation, scale) but not for geometry storage.
Can I build a mesh with quads instead of triangles?
Yes. Call mesh.create_polygon(0, 1, 2, 3) with four indices to define a quad. Some save targets (STL, 3MF) require triangles and will triangulate quads automatically. glTF and COLLADA preserve quads.
How do I add UV coordinates?
Use mesh.create_element_uv(MappingMode.POLYGON_VERTEX) (or another mapping mode) to create a VertexElementUV, then populate its data list with Vector4 entries. UV coordinates use x and y; z and w are typically 0.
Does the mesh need normals to export correctly?
No. Normals are optional. If omitted, most viewers compute per-face normals from the polygon winding order. Adding explicit per-vertex normals produces smoother shading.
Can I add multiple meshes to one node?
Yes. Call node.add_entity(mesh) multiple times. Each call appends a new entity to node.entities. Some formats may flatten multiple entities into one on export.
How do I triangulate a mesh with mixed polygon types?
Call mesh.triangulate() to convert all quads and N-gons to triangles in place. This is useful before saving to formats that only support triangles.