Skip to content

ordito.io

Mesh file loading via the optional meshio dependency.

Classes:

Name Description
MeshData

The attributes load_mesh_data read from a file, by name.

Functions:

Name Description
load_mesh_data

Load every mesh attribute meshio can read from a file into Warp arrays.

load_mesh

Load a triangle mesh file into a warp.Mesh.

mesh_from_numpy

Build a Trimesh from NumPy vertex and face arrays.

MeshData

Bases: TypedDict

The attributes load_mesh_data read from a file, by name.

A plain dict at runtime. vertices is always present; every other key only when the file carries that attribute.

Examples:

Only the attributes the file carries appear as keys:

import pathlib
import tempfile

import meshio
import numpy as np

import ordito as od

points = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
with tempfile.TemporaryDirectory() as folder:
    path = pathlib.Path(folder) / "triangle.ply"
    meshio.write(path, meshio.Mesh(points, [("triangle", np.array([[0, 1, 2]]))]))
    data = od.io.load_mesh_data(path)
print(sorted(data))  # ['faces', 'vertices']

vertices instance-attribute

vertices: Required[array[vec3]]

faces instance-attribute

faces: array[int32]

vertex_normals instance-attribute

vertex_normals: array[vec3]

uv instance-attribute

uv: array[vec2]

corner_uv instance-attribute

corner_uv: array[vec2]

colors instance-attribute

colors: array[vec3] | array[vec4]

face_normals instance-attribute

face_normals: array[vec3]

load_mesh_data

load_mesh_data(
    path: str | Path, *, device: DeviceLike = None
) -> MeshData

Load every mesh attribute meshio can read from a file into Warp arrays.

Reads path once with meshio and returns a dictionary whose keys are present only when the corresponding data exists in the file. vertices is always present; everything else is optional.

Parameters:

Name Type Description Default
path str | Path

Path to a mesh file in any format supported by meshio (PLY, STL, OBJ, OFF, VTK, glTF, ...).

required
device DeviceLike

Warp device for the returned arrays. Defaults to the current Warp device.

None

Returns:

Type Description
MeshData

Mapping with these possible keys:

  • vertices : wp.array[wp.vec3] of float32 vertex positions (always present).
  • faces : (3 * n_faces,) flat wp.array[wp.int32] (triangle cells only).
  • vertex_normals : wp.array[wp.vec3] from nx, ny, nz per-vertex data.
  • uv : wp.array[wp.vec2] from u, v (or s, t / texture_u, texture_v).
  • corner_uv : (3 * n_faces,) wp.array[wp.vec2], one texcoord per face corner, from an OBJ file's vt indices or a PLY file's texcoord face list -- the form of a UV atlas, whose seams give one vertex several texcoords. split_vertices_by_corner_values turns it into per-vertex uv.
  • colors : wp.array[wp.vec3] or wp.array[wp.vec4] from red, green, blue (and optional alpha); integer channels are normalized to [0, 1].
  • face_normals : wp.array[wp.vec3] — only when the file stored per-face normals.

Raises:

Type Description
ValueError

If an OBJ file's face names a vertex or a texcoord it does not define, or a PLY file with per-corner texcoords is malformed or names a vertex it does not define.

See Also

load_mesh

Notes

Only triangle cells are consumed; non-triangle cell blocks are ignored. meshio reads attributes verbatim and never computes them, so face_normals appears only when the file itself contained per-face normals.

An OBJ file is read here rather than by meshio, which refuses one whose vt count differs from its v count -- every UV-mapped OBJ with a seam. Its positions, triangles and corner_uv are returned; polygons with more than three corners are ignored as above. A PLY file whose faces carry a texcoord (or texcoords) list, which meshio cannot decode, is read here too, ASCII or binary, with every attribute above.

Examples:

A box written to PLY with per-vertex normals reads back with them:

import pathlib
import tempfile

import meshio

import ordito as od

vertices, faces = od.creation.box()
normals = od.normals.vertex_normals(vertices, faces).numpy()
mesh = meshio.Mesh(
    vertices.numpy(),
    [("triangle", faces.numpy().reshape(-1, 3))],
    point_data={"nx": normals[:, 0], "ny": normals[:, 1], "nz": normals[:, 2]},
)
with tempfile.TemporaryDirectory() as folder:
    path = pathlib.Path(folder) / "box.ply"
    meshio.write(path, mesh)
    data = od.io.load_mesh_data(path)
print(sorted(data))  # ['faces', 'vertex_normals', 'vertices']
print(data["faces"].shape, data["vertex_normals"].shape)  # (36,) (8,)
Source code in ordito/io.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def load_mesh_data(path: str | Path, *, device: wp.DeviceLike = None) -> MeshData:
    """
    Load every mesh attribute ``meshio`` can read from a file into Warp arrays.

    Reads ``path`` once with ``meshio`` and returns a dictionary whose keys are present
    only when the corresponding data exists in the file. ``vertices`` is always present;
    everything else is optional.

    Parameters
    ----------
    path
        Path to a mesh file in any format supported by ``meshio`` (PLY, STL, OBJ, OFF,
        VTK, glTF, ...).
    device
        Warp device for the returned arrays. Defaults to the current Warp device.

    Returns
    -------
    MeshData
        Mapping with these possible keys:

        - ``vertices`` : ``wp.array[wp.vec3]`` of ``float32`` vertex positions (always present).
        - ``faces`` : ``(3 * n_faces,)`` flat ``wp.array[wp.int32]`` (triangle cells only).
        - ``vertex_normals`` : ``wp.array[wp.vec3]`` from ``nx, ny, nz`` per-vertex data.
        - ``uv`` : ``wp.array[wp.vec2]`` from ``u, v`` (or ``s, t`` / ``texture_u, texture_v``).
        - ``corner_uv`` : ``(3 * n_faces,)`` ``wp.array[wp.vec2]``, one texcoord per face corner,
          from an OBJ file's ``vt`` indices or a PLY file's ``texcoord`` face list -- the form of
          a UV atlas, whose seams give one vertex several texcoords.
          [`split_vertices_by_corner_values`][ordito.repair.split_vertices_by_corner_values]
          turns it into per-vertex ``uv``.
        - ``colors`` : ``wp.array[wp.vec3]`` or ``wp.array[wp.vec4]`` from ``red, green, blue``
          (and optional ``alpha``); integer channels are normalized to ``[0, 1]``.
        - ``face_normals`` : ``wp.array[wp.vec3]`` — only when the file stored per-face normals.

    Raises
    ------
    ValueError
        If an OBJ file's face names a vertex or a texcoord it does not define, or a PLY file with
        per-corner texcoords is malformed or names a vertex it does not define.

    See Also
    --------
    [`load_mesh`][ordito.io.load_mesh]

    Notes
    -----
    Only triangle cells are consumed; non-triangle cell blocks are ignored. ``meshio`` reads
    attributes verbatim and never computes them, so ``face_normals`` appears only when the
    file itself contained per-face normals.

    An OBJ file is read here rather than by ``meshio``, which refuses one whose ``vt`` count
    differs from its ``v`` count -- every UV-mapped OBJ with a seam. Its positions, triangles and
    ``corner_uv`` are returned; polygons with more than three corners are ignored as above. A PLY
    file whose faces carry a ``texcoord`` (or ``texcoords``) list, which ``meshio`` cannot decode,
    is read here too, ASCII or binary, with every attribute above.

    Examples
    --------
    A box written to PLY with per-vertex normals reads back with them:

    ```python
    import pathlib
    import tempfile

    import meshio

    import ordito as od

    vertices, faces = od.creation.box()
    normals = od.normals.vertex_normals(vertices, faces).numpy()
    mesh = meshio.Mesh(
        vertices.numpy(),
        [("triangle", faces.numpy().reshape(-1, 3))],
        point_data={"nx": normals[:, 0], "ny": normals[:, 1], "nz": normals[:, 2]},
    )
    with tempfile.TemporaryDirectory() as folder:
        path = pathlib.Path(folder) / "box.ply"
        meshio.write(path, mesh)
        data = od.io.load_mesh_data(path)
    print(sorted(data))  # ['faces', 'vertex_normals', 'vertices']
    print(data["faces"].shape, data["vertex_normals"].shape)  # (36,) (8,)
    ```
    """
    if Path(path).suffix.lower() == ".obj":
        return _load_obj_data(path, device)
    if _is_ply_with_corner_texcoords(path):
        ply = _read_ply(path)
        if ply.faces.size > 0:
            _require_valid_faces_host(ply.faces, len(ply.points), "load_mesh_data")
        return _mesh_data(
            ply.points, ply.faces, ply.point_data, ply.face_normals, ply.corner_uv, device
        )
    meshio = _import_meshio()
    mesh = meshio.read(path)
    return _mesh_data(
        mesh.points,
        mesh.cells_dict.get("triangle"),
        mesh.point_data,
        _face_normals_from_cell_data(mesh),
        None,
        device,
    )

load_mesh

load_mesh(
    path: str | Path, *, device: DeviceLike = None
) -> wp.Mesh

Load a triangle mesh file into a warp.Mesh.

Reads only the vertices and triangle faces (the subset load_mesh_data returns) and wraps them in a warp.Mesh that owns its buffers.

Parameters:

Name Type Description Default
path str | Path

Path to a mesh file in any format supported by meshio.

required
device DeviceLike

Warp device for the returned mesh. Defaults to the current Warp device.

None

Returns:

Type Description
Mesh

Mesh with vec3 points and flat int32 indices.

Raises:

Type Description
ValueError

If the file contains no triangle faces (e.g. a point cloud or a triangle-strip PLY that meshio cannot decode), if a face references a vertex index the file's own vertex count does not cover, or if a PLY file with per-corner texcoords is malformed.

See Also

load_mesh_data

Examples:

Round-trip an icosphere through an OBJ file:

import pathlib
import tempfile

import meshio

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=1)
mesh = meshio.Mesh(vertices.numpy(), [("triangle", faces.numpy().reshape(-1, 3))])
with tempfile.TemporaryDirectory() as folder:
    path = pathlib.Path(folder) / "sphere.obj"
    meshio.write(path, mesh)
    loaded = od.io.load_mesh(path)
print(loaded.points.shape, loaded.indices.shape)  # (42,) (240,)
Source code in ordito/io.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def load_mesh(path: str | Path, *, device: wp.DeviceLike = None) -> wp.Mesh:
    """
    Load a triangle mesh file into a ``warp.Mesh``.

    Reads only the vertices and triangle faces (the subset
    [`load_mesh_data`][ordito.io.load_mesh_data] returns) and wraps them in a ``warp.Mesh`` that
    owns its buffers.

    Parameters
    ----------
    path
        Path to a mesh file in any format supported by ``meshio``.
    device
        Warp device for the returned mesh. Defaults to the current Warp device.

    Returns
    -------
    warp.Mesh
        Mesh with ``vec3`` points and flat ``int32`` indices.

    Raises
    ------
    ValueError
        If the file contains no triangle faces (e.g. a point cloud or a triangle-strip
        PLY that ``meshio`` cannot decode), if a face references a vertex index the file's own
        vertex count does not cover, or if a PLY file with per-corner texcoords is malformed.

    See Also
    --------
    [`load_mesh_data`][ordito.io.load_mesh_data]

    Examples
    --------
    Round-trip an icosphere through an OBJ file:

    ```python
    import pathlib
    import tempfile

    import meshio

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=1)
    mesh = meshio.Mesh(vertices.numpy(), [("triangle", faces.numpy().reshape(-1, 3))])
    with tempfile.TemporaryDirectory() as folder:
        path = pathlib.Path(folder) / "sphere.obj"
        meshio.write(path, mesh)
        loaded = od.io.load_mesh(path)
    print(loaded.points.shape, loaded.indices.shape)  # (42,) (240,)
    ```
    """
    if Path(path).suffix.lower() == ".obj":
        points, faces_np, _ = _read_obj(path)
        if faces_np.size == 0:
            raise ValueError(f"Mesh file {path!r} has no triangle faces; cannot build a wp.Mesh.")
        _require_valid_faces_host(faces_np, len(points), "load_mesh")
        return wp.Mesh(
            points=_launch.array(points, dtype=wp.vec3, device=device),
            indices=_launch.array(faces_np.astype(np.int32), dtype=wp.int32, device=device),
        )
    if _is_ply_with_corner_texcoords(path):
        ply = _read_ply(path)
        points_np, faces_np = ply.points, ply.faces
    else:
        meshio = _import_meshio()
        mesh = meshio.read(path)
        points_np, faces_np = mesh.points, mesh.cells_dict.get("triangle")
    if faces_np is None or len(faces_np) == 0:
        raise ValueError(f"Mesh file {path!r} has no triangle faces; cannot build a wp.Mesh.")
    # A malformed file (or a meshio decoder bug) can hand back a face index the vertex buffer
    # doesn't cover; this is the trust boundary where that first enters ordito. The check reads
    # the decoder's own integers before the ``int32`` narrowing, which would wrap an index at or
    # above ``2**31`` into range.
    _require_valid_faces_host(faces_np, len(points_np), "load_mesh")
    vertices_wp = _launch.array(
        np.ascontiguousarray(points_np, dtype=np.float32), dtype=wp.vec3, device=device
    )
    faces_wp = _launch.array(
        np.ascontiguousarray(faces_np.reshape(-1), dtype=np.int32), dtype=wp.int32, device=device
    )
    # Both buffers were allocated on the lines above and nothing else holds them, so the mesh
    # can own them directly.
    return wp.Mesh(points=vertices_wp, indices=faces_wp)

mesh_from_numpy

mesh_from_numpy(
    vertices: ndarray,
    faces: ndarray,
    *,
    device: DeviceLike = None,
) -> Trimesh

Build a Trimesh from NumPy vertex and face arrays.

Parameters:

Name Type Description Default
vertices ndarray

(n_vertices, 3) vertex positions, any NumPy float dtype.

required
faces ndarray

(n_faces, 3) (or already-flat (3 * n_faces,)) triangle vertex indices, any NumPy integer dtype.

required
device DeviceLike

Warp device for the returned mesh. Defaults to the current Warp device.

None

Returns:

Type Description
Trimesh

New mesh with vec3 vertices and a flat int32 face buffer, owning freshly allocated Warp arrays (no aliasing with vertices / faces).

Raises:

Type Description
ValueError

If a face references a vertex index vertices does not cover.

See Also

load_mesh

Examples:

(n_faces, 3) faces are flattened into ordito's (3 * n_faces,) layout:

import numpy as np

import ordito as od

vertices = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]])
faces = np.array([[0, 1, 2], [0, 2, 3]])
mesh = od.io.mesh_from_numpy(vertices, faces)
print(mesh.n_vertices, mesh.n_faces, mesh.faces.shape)  # 4 2 (6,)
print(f"{mesh.area:.4f}")  # 1.0000
Source code in ordito/io.py
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
def mesh_from_numpy(
    vertices: np.ndarray, faces: np.ndarray, *, device: wp.DeviceLike = None
) -> Trimesh:
    """
    Build a [`Trimesh`][ordito.mesh.Trimesh] from NumPy vertex and face arrays.

    Parameters
    ----------
    vertices
        ``(n_vertices, 3)`` vertex positions, any NumPy float dtype.
    faces
        ``(n_faces, 3)`` (or already-flat ``(3 * n_faces,)``) triangle vertex indices,
        any NumPy integer dtype.
    device
        Warp device for the returned mesh. Defaults to the current Warp device.

    Returns
    -------
    Trimesh
        New mesh with ``vec3`` vertices and a flat ``int32`` face buffer, owning freshly
        allocated Warp arrays (no aliasing with ``vertices`` / ``faces``).

    Raises
    ------
    ValueError
        If a face references a vertex index ``vertices`` does not cover.

    See Also
    --------
    [`load_mesh`][ordito.io.load_mesh]

    Examples
    --------
    ``(n_faces, 3)`` faces are flattened into ordito's ``(3 * n_faces,)`` layout:

    ```python
    import numpy as np

    import ordito as od

    vertices = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]])
    faces = np.array([[0, 1, 2], [0, 2, 3]])
    mesh = od.io.mesh_from_numpy(vertices, faces)
    print(mesh.n_vertices, mesh.n_faces, mesh.faces.shape)  # 4 2 (6,)
    print(f"{mesh.area:.4f}")  # 1.0000
    ```
    """
    # This is the trust boundary where an external caller's raw NumPy connectivity first enters
    # ordito. The range is checked on the caller's own integers, before the ``int32`` narrowing
    # (which would wrap an index at or above ``2**31`` into range) and before any upload.
    _require_valid_faces_host(faces, len(vertices), "mesh_from_numpy")
    vertices_wp = _launch.array(
        np.ascontiguousarray(vertices, dtype=np.float32), dtype=wp.vec3, device=device
    )
    faces_wp = _launch.array(
        np.ascontiguousarray(faces.reshape(-1), dtype=np.int32), dtype=wp.int32, device=device
    )
    return Trimesh(vertices_wp, faces_wp)