Skip to content

ordito.validation

Mesh diagnostics: topological/geometric validity predicates and their per-element masks.

Functions:

Name Description
is_edge_manifold

Whether every undirected mesh edge is shared by a manifold number of faces.

edge_manifold_mask

Per-face flag: whether all three of each face's undirected edges are edge-manifold.

is_vertex_manifold

Whether every vertex up to max(faces) is used and has a single edge-connected fan of faces.

vertex_manifold_mask

Per-vertex flag: whether each vertex has a single edge-connected fan of faces.

is_self_intersecting

Whether any two non-adjacent triangles of the mesh intersect.

face_self_intersecting_mask

Per-face flag: whether each triangle intersects some non-adjacent triangle.

is_winding_consistent

Whether every shared edge is traversed in opposite directions by its two faces.

edge_winding_consistent_mask

Per shared-edge flag: whether an undirected edge's two faces traverse it in opposite directions.

face_orientation_bits

Per-face Z2 orientation bits (relative to each component seed) plus signed face-adjacency edges.

is_orientable

Whether the faces admit a consistent orientation (allowing per-face flips).

face_flip_mask

Per-face flag: whether a face must be flipped to make winding consistent within its patch.

is_watertight

Whether the mesh bounds a closed volume with no self-intersections.

face_watertight_mask

Per-face flag: whether all three of a face's undirected edges are shared by exactly two faces.

is_volume

Whether the mesh is a valid closed volume with outward-facing normals.

face_defective_mask

Flag faces that are thin, misoriented relative to their neighbourhood, or folded over it.

is_edge_manifold

is_edge_manifold(
    faces: array[int32],
    allow_boundary_edges: bool = True,
    *,
    n_vertices: int | None = None,
    validate: bool = True,
    mates: array[int32] | None = None,
) -> bool

Whether every undirected mesh edge is shared by a manifold number of faces.

Counts how many faces share each undirected edge. With allow_boundary_edges=True an edge is manifold when it belongs to one or two faces; with allow_boundary_edges=False it must belong to exactly two faces (no boundary or non-manifold edges), matching Open3D's IsEdgeManifold.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
allow_boundary_edges bool

When True (default) boundary edges (used by a single face) are allowed. When False every edge must be shared by exactly two faces.

True
n_vertices int | None

Optional vertex count (the upper bound checked). When None, only the negative half is checked.

None
validate bool

Whether to range-check the face indices. The check rides on the pass that packs the keys and shares the verdict's readback. Pass False only where both bounds are structurally guaranteed -- a face buffer this package produced itself, or one an entry point has already validated.

True
mates array[int32] | None

(3 * n_faces,) halfedge_mates of faces when the caller holds them (Trimesh.halfedge_mates). Each halfedge's mate code is its edge's share count, so the verdict is then one pass over them and no edge is counted. Trusted, not checked; faces is not read, so neither n_vertices nor validate has an effect.

None

Returns:

Type Description
bool

True when all edges satisfy the manifold condition. Vacuously True for an empty mesh.

Raises:

Type Description
ValueError

If validate is True, mates is None and a face index is negative or reaches the vertex count.

RuntimeError

If faces and mates are not all on one device.

See Also

is_vertex_manifold is_watertight

Notes

Equivalent to open3d.geometry.TriangleMesh.is_edge_manifold; libigl is_edge_manifold corresponds to the allow_boundary_edges=True case.

Deliberately not all(edge_manifold_mask(faces)), unlike the other is_* / *_mask pairs here: this counts each edge's faces in one pass over a hash set and needs no per-edge answer, where the mask needs each halfedge's own count and so pairs every halfedge. Delegating would add the pairing to the cheap path.

Examples:

An open grid is edge-manifold only while boundary edges are allowed; a fin makes an edge with three faces, which is never manifold:

import warp as wp

import ordito as od

vertices, grid_faces = od.creation.grid(count=(3, 3))
print(od.validation.is_edge_manifold(grid_faces))  # True
print(od.validation.is_edge_manifold(grid_faces, allow_boundary_edges=False))  # False
# A strip of three triangles with a fourth "fin" on the edge (1, 2): three faces share it.
faces = wp.array([0, 1, 2, 2, 1, 3, 2, 3, 4, 1, 2, 5], dtype=wp.int32)
print(od.validation.is_edge_manifold(faces))  # False
Source code in ordito/validation.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
def is_edge_manifold(
    faces: wp.array[wp.int32],
    allow_boundary_edges: bool = True,
    *,
    n_vertices: int | None = None,
    validate: bool = True,
    mates: wp.array[wp.int32] | None = None,
) -> bool:
    """
    Whether every undirected mesh edge is shared by a manifold number of faces.

    Counts how many faces share each undirected edge. With ``allow_boundary_edges=True`` an edge is
    manifold when it belongs to one or two faces; with ``allow_boundary_edges=False`` it must belong
    to exactly two faces (no boundary or non-manifold edges), matching Open3D's ``IsEdgeManifold``.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    allow_boundary_edges
        When ``True`` (default) boundary edges (used by a single face) are allowed. When ``False``
        every edge must be shared by exactly two faces.
    n_vertices
        Optional vertex count (the upper bound checked). When ``None``, only the negative half is
        checked.
    validate
        Whether to range-check the face indices. The check rides on the pass that packs the keys
        and shares the verdict's readback. Pass ``False`` only where both bounds are structurally
        guaranteed -- a face buffer this package produced itself, or one an entry point has
        already validated.
    mates
        ``(3 * n_faces,)`` [`halfedge_mates`][ordito.halfedge.halfedge_mates] of ``faces`` when the
        caller holds them ([`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates]). Each
        halfedge's mate code is its edge's share count, so the verdict is then one pass over them
        and no edge is counted. Trusted, not checked; ``faces`` is not read, so neither
        ``n_vertices`` nor ``validate`` has an effect.

    Returns
    -------
    bool
        ``True`` when all edges satisfy the manifold condition. Vacuously ``True`` for an empty
        mesh.

    Raises
    ------
    ValueError
        If ``validate`` is ``True``, ``mates`` is ``None`` and a face index is negative or reaches
        the vertex count.
    RuntimeError
        If ``faces`` and ``mates`` are not all on one device.

    See Also
    --------
    [`is_vertex_manifold`][ordito.validation.is_vertex_manifold]
    [`is_watertight`][ordito.validation.is_watertight]

    Notes
    -----
    Equivalent to ``open3d.geometry.TriangleMesh.is_edge_manifold``; libigl ``is_edge_manifold``
    corresponds to the ``allow_boundary_edges=True`` case.

    Deliberately **not** ``all(edge_manifold_mask(faces))``, unlike the other ``is_*`` / ``*_mask``
    pairs here: this counts each edge's faces in one pass over a hash set and needs no per-edge
    answer, where the mask needs each halfedge's own count and so pairs every halfedge.
    Delegating would add the pairing to the cheap path.

    Examples
    --------
    An open grid is edge-manifold only while boundary edges are allowed; a fin makes an edge with
    three faces, which is never manifold:

    ```python
    import warp as wp

    import ordito as od

    vertices, grid_faces = od.creation.grid(count=(3, 3))
    print(od.validation.is_edge_manifold(grid_faces))  # True
    print(od.validation.is_edge_manifold(grid_faces, allow_boundary_edges=False))  # False
    # A strip of three triangles with a fourth "fin" on the edge (1, 2): three faces share it.
    faces = wp.array([0, 1, 2, 2, 1, 3, 2, 3, 4, 1, 2, 5], dtype=wp.int32)
    print(od.validation.is_edge_manifold(faces))  # False
    ```
    """
    require_same_device(faces=faces, mates=mates)
    n_faces = faces.size // 3
    if n_faces == 0:
        return True

    device = faces.device
    if mates is not None:
        violation = _launch.zeros(1, dtype=wp.int32, device=device)
        _launch.launch(
            kernel_validation.mate_manifold_violation,
            dim=mates.size,
            inputs=[mates, allow_boundary_edges, violation],
            device=device,
        )
        return int(read_scalar(violation)) == 0
    # One pass counting every corner's edge into an open-addressing edge-key set
    # (``kernels/validation.edge_share_violations``): a vertex count homes each edge among its lower
    # vertex's slots (a given one is also the range checked; with none, a large mesh reads one
    # back, ``_common.edge_key_vertex_bound``), else the keys start at hashed homes and only a
    # negative index is checked. The three flags sit after the table in its zeroed allocation and
    # come back in one read: third arrivals, faces out of range, unique edges.
    table_vertices = edge_key_vertex_bound(faces, n_faces, n_vertices)
    per, capacity, global_mask = kernel_grouping.edge_key_table_shape(n_faces, table_vertices)
    base = kernel_grouping.EDGE_KEY_RADIX_UNBOUNDED if table_vertices is None else table_vertices
    bound = odt.dtype_max(wp.int32) if n_vertices is None else n_vertices
    buffer = _launch.zeros(capacity + 2, dtype=wp.uint64, device=device)
    table = _launch.view(buffer, 0, capacity)
    flags = _launch.view_as(_launch.view(buffer, capacity, capacity + 2), wp.int32)
    width, blocks = kernel_reduce.spanned_blocks_1d(n_faces, device)
    _launch.launch_tiled(
        kernel_validation.edge_share_violations,
        dim=[blocks],
        inputs=[faces, wp.uint64(base), per, global_mask, width, bound, table, flags],
        block_dim=TILE_1D,
        device=device,
    )
    # One readback for the three counts.
    third_arrivals, out_of_range, n_edges = read_values(flags, 0, 3)
    if validate and out_of_range:
        bound_text = "" if n_vertices is None else f" below {n_vertices}"
        raise ValueError(f"is_edge_manifold: faces must be non-negative indices{bound_text}")
    if third_arrivals:
        return False
    # Every edge on at most two faces: all on exactly two when the shares fill the corners.
    return allow_boundary_edges or 2 * n_edges == 3 * n_faces

edge_manifold_mask

edge_manifold_mask(
    faces: array[int32],
    allow_boundary_edges: bool = True,
    *,
    n_vertices: int | None = None,
    validate: bool = True,
    mates: array[int32] | None = None,
) -> wp.array[wp.bool]

Per-face flag: whether all three of each face's undirected edges are edge-manifold.

An edge is manifold when shared by one or two faces (allow_boundary_edges=True) or by exactly two faces (allow_boundary_edges=False); a face is flagged True only when all three of its edges qualify. This is a per-face collapse of libigl's BF (its per-corner is_edge_manifold matrix), and is_edge_manifold is True iff every entry of this mask is True.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
allow_boundary_edges bool

When True (default) boundary edges (used by a single face) count as manifold. When False every edge of a face must be shared by exactly two faces.

True
n_vertices int | None

Optional vertex count (the edge-hash base). When None and validate is True, inferred from faces by the same reduction that checks them; unvalidated, no bound is needed and none is inferred.

None
validate bool

Whether to range-check the edge indices before packing them. The check is a ordito.reduce.minmax whose host readback serialises the device pipeline. Pass False only where both bounds are structurally guaranteed -- a face buffer this package produced itself, or one an entry point has already validated.

True
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
array[bool]

(n_faces,) mask on faces.device. Empty for an empty mesh.

Raises:

Type Description
ValueError

If validate is True and a face index is negative or reaches the vertex count.

RuntimeError

If faces and mates are not all on one device.

See Also

is_edge_manifold vertex_manifold_mask

Examples:

The three faces on the over-shared edge are flagged False:

import warp as wp

import ordito as od

# A strip of three triangles with a fourth "fin" on the edge (1, 2): three faces share it.
faces = wp.array([0, 1, 2, 2, 1, 3, 2, 3, 4, 1, 2, 5], dtype=wp.int32)
print(od.validation.edge_manifold_mask(faces).numpy().tolist())  # [False, False, True, False]
Source code in ordito/validation.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def edge_manifold_mask(
    faces: wp.array[wp.int32],
    allow_boundary_edges: bool = True,
    *,
    n_vertices: int | None = None,
    validate: bool = True,
    mates: wp.array[wp.int32] | None = None,
) -> wp.array[wp.bool]:
    """
    Per-face flag: whether all three of each face's undirected edges are edge-manifold.

    An edge is manifold when shared by one or two faces (``allow_boundary_edges=True``) or by
    exactly two faces (``allow_boundary_edges=False``); a face is flagged ``True`` only when all
    three of its edges qualify. This is a per-face collapse of libigl's ``BF`` (its per-corner
    ``is_edge_manifold`` matrix), and
    [`is_edge_manifold`][ordito.validation.is_edge_manifold] is ``True`` iff every entry of
    this mask is ``True``.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    allow_boundary_edges
        When ``True`` (default) boundary edges (used by a single face) count as manifold. When
        ``False`` every edge of a face must be shared by exactly two faces.
    n_vertices
        Optional vertex count (the edge-hash base). When ``None`` and ``validate`` is ``True``,
        inferred from ``faces`` by the same reduction that checks them; unvalidated, no bound is
        needed and none is inferred.
    validate
        Whether to range-check the edge indices before packing them. The check is a
        ``ordito.reduce.minmax`` whose host readback serialises the device pipeline. Pass
        ``False`` only where both bounds are structurally guaranteed -- a face buffer this package
        produced itself, or one an entry point has already validated.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    wp.array[wp.bool]
        ``(n_faces,)`` mask on ``faces.device``. Empty for an empty mesh.

    Raises
    ------
    ValueError
        If ``validate`` is ``True`` and a face index is negative or reaches the vertex count.
    RuntimeError
        If ``faces`` and ``mates`` are not all on one device.

    See Also
    --------
    [`is_edge_manifold`][ordito.validation.is_edge_manifold]
    [`vertex_manifold_mask`][ordito.validation.vertex_manifold_mask]

    Examples
    --------
    The three faces on the over-shared edge are flagged ``False``:

    ```python
    import warp as wp

    import ordito as od

    # A strip of three triangles with a fourth "fin" on the edge (1, 2): three faces share it.
    faces = wp.array([0, 1, 2, 2, 1, 3, 2, 3, 4, 1, 2, 5], dtype=wp.int32)
    print(od.validation.edge_manifold_mask(faces).numpy().tolist())  # [False, False, True, False]
    ```
    """
    require_same_device(faces=faces, mates=mates)
    n_faces = faces.size // 3
    device = faces.device
    if n_faces == 0:
        return _launch.empty(0, dtype=wp.bool, device=device)

    # The share count of each edge is its halfedges' mate code, read in place: no unique-edge
    # table, inverse or count array, and no host read of the unique count.
    mates = (
        mates
        if mates is not None
        else od.halfedge.halfedge_mates(
            faces, _validated_vertex_bound(faces, n_vertices, validate, "edge_manifold_mask")
        )
    )
    # ``wp.empty``: the pass writes every face's entry.
    out_mask = _launch.empty(n_faces, dtype=wp.bool, device=device)
    _launch.launch(
        kernel_validation.mate_manifold_mask,
        dim=n_faces,
        inputs=[mates, wp.bool(allow_boundary_edges), out_mask],
        device=device,
    )
    return out_mask

is_vertex_manifold

is_vertex_manifold(
    faces: array[int32],
    *,
    face_adjacency: Array2dInt32 | None = None,
    face_adjacency_edges: Array2dInt32 | None = None,
    n_vertices: int | None = None,
    mates: array[int32] | None = None,
) -> bool

Whether every vertex up to max(faces) is used and has a single edge-connected fan of faces.

A vertex is manifold when the faces incident to it form one connected group under "shares an edge through this vertex" adjacency; two fans meeting only at the vertex (a bow-tie) are non-manifold. Unreferenced vertices in [0, max(faces)] are treated as non-manifold, matching libigl's is_vertex_manifold; Open3D's is_vertex_manifold skips them, and so does is_watertight.

The check builds the corner graph (node 3 * f + k per face corner), links the corresponding corners of edge-adjacent faces, and requires all corners of each vertex to fall in one connected component.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
face_adjacency Array2dInt32 | None

(m, 2) precomputed face-adjacency pairs from face_adjacency. Must be given together with face_adjacency_edges.

None
face_adjacency_edges Array2dInt32 | None

(m, 2) shared-edge vertex pairs aligned with face_adjacency (return_edges=True). Must be given together with face_adjacency.

None
n_vertices int | None

Optional length of the vertex buffer faces indexes, which must be at least max(faces) + 1 and is not checked. It sizes the working tables only and does not change the answer: vertices past max(faces) are still not considered. When None, max(faces) + 1 is inferred with a device-host sync.

None
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
bool

True when every vertex in [0, max(faces)] is referenced and manifold. Vacuously True for an empty mesh.

Raises:

Type Description
ValueError

If exactly one of face_adjacency / face_adjacency_edges is provided.

RuntimeError

If faces, face_adjacency, face_adjacency_edges and mates are not all on one device.

See Also

vertex_manifold_mask is_edge_manifold is_watertight

Notes

Corner adjacency is derived from face_adjacency, which pairs faces across edges shared by exactly two faces; on edge-non-manifold meshes (an edge shared by three or more faces) read the result together with is_edge_manifold. Equivalent to libigl is_vertex_manifold. The output is sized to max(faces) + 1 so unreferenced vertices in that range count as non-manifold; use vertex_manifold_mask for a per-vertex flag sized to a caller-provided vertex buffer.

Examples:

Two triangles meeting only at vertex 0 form a bow-tie, whose vertex 0 has two separate fans:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
print(od.validation.is_vertex_manifold(faces))  # True
bow_tie = wp.array([0, 1, 2, 0, 3, 4], dtype=wp.int32)
print(od.validation.is_vertex_manifold(bow_tie))  # False
Source code in ordito/validation.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def is_vertex_manifold(
    faces: wp.array[wp.int32],
    *,
    face_adjacency: odt.Array2dInt32 | None = None,
    face_adjacency_edges: odt.Array2dInt32 | None = None,
    n_vertices: int | None = None,
    mates: wp.array[wp.int32] | None = None,
) -> bool:
    """
    Whether every vertex up to ``max(faces)`` is used and has a single edge-connected fan of faces.

    A vertex is manifold when the faces incident to it form one connected group under
    "shares an edge through this vertex" adjacency; two fans meeting only at the vertex (a bow-tie)
    are non-manifold. Unreferenced vertices in ``[0, max(faces)]`` are treated as non-manifold,
    matching libigl's ``is_vertex_manifold``; Open3D's ``is_vertex_manifold`` skips them, and so
    does [`is_watertight`][ordito.validation.is_watertight].

    The check builds the corner graph (node ``3 * f + k`` per face corner), links the corresponding
    corners of edge-adjacent faces, and requires all corners of each vertex to fall in one connected
    component.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    face_adjacency
        ``(m, 2)`` precomputed face-adjacency pairs from
        [`face_adjacency`][ordito.adjacency.face_adjacency]. Must be given together with
        ``face_adjacency_edges``.
    face_adjacency_edges
        ``(m, 2)`` shared-edge vertex pairs aligned with ``face_adjacency``
        (``return_edges=True``). Must be given together with ``face_adjacency``.
    n_vertices
        Optional length of the vertex buffer ``faces`` indexes, which must be at least
        ``max(faces) + 1`` and is not checked. It sizes the working tables only and does not change
        the answer: vertices past ``max(faces)`` are still not considered. When ``None``,
        ``max(faces) + 1`` is inferred with a device-host sync.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    bool
        ``True`` when every vertex in ``[0, max(faces)]`` is referenced and manifold. Vacuously
        ``True`` for an empty mesh.

    Raises
    ------
    ValueError
        If exactly one of ``face_adjacency`` / ``face_adjacency_edges`` is provided.
    RuntimeError
        If ``faces``, ``face_adjacency``, ``face_adjacency_edges`` and ``mates`` are not all on
        one device.

    See Also
    --------
    [`vertex_manifold_mask`][ordito.validation.vertex_manifold_mask]
    [`is_edge_manifold`][ordito.validation.is_edge_manifold]
    [`is_watertight`][ordito.validation.is_watertight]

    Notes
    -----
    Corner adjacency is derived from
    [`face_adjacency`][ordito.adjacency.face_adjacency], which pairs faces across edges shared by
    exactly two faces; on edge-non-manifold meshes (an edge shared by three or more faces) read the
    result together with [`is_edge_manifold`][ordito.validation.is_edge_manifold]. Equivalent
    to libigl ``is_vertex_manifold``. The output is sized to ``max(faces) + 1`` so unreferenced
    vertices in that range count as non-manifold; use
    [`vertex_manifold_mask`][ordito.validation.vertex_manifold_mask] for a per-vertex flag
    sized to a caller-provided vertex buffer.

    Examples
    --------
    Two triangles meeting only at vertex 0 form a bow-tie, whose vertex 0 has two separate fans:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    print(od.validation.is_vertex_manifold(faces))  # True
    bow_tie = wp.array([0, 1, 2, 0, 3, 4], dtype=wp.int32)
    print(od.validation.is_vertex_manifold(bow_tie))  # False
    ```
    """
    require_same_device(
        faces=faces,
        face_adjacency=face_adjacency,
        face_adjacency_edges=face_adjacency_edges,
        mates=mates,
    )
    # Checked before the empty-mesh guard so a caller passing only one half of the pair is told
    # about it whatever the mesh is; resolved after it, because on an empty buffer the resolve is
    # two empty tables nothing reads. Every wrapper taking this pair does it in this order.
    od.adjacency.require_paired_adjacency(face_adjacency, face_adjacency_edges)
    if faces.size // 3 == 0:
        return True
    if n_vertices is None:
        # The corner graph derived below trusts this bound, so it carries the range check the
        # edge-key packing would otherwise have made itself.
        n_vertices = od.array.index_bound(faces, require_non_negative=face_adjacency is None)
    violation = _launch.zeros(1, dtype=wp.int32, device=faces.device)
    if face_adjacency is None:
        parents = _corner_parents_from_mates(
            faces,
            (mates if mates is not None else od.halfedge.halfedge_mates(faces, n_vertices)),
            False,
            None,
        )
    else:
        assert face_adjacency_edges is not None
        parents = _corner_parents_from_adjacency(faces, face_adjacency, face_adjacency_edges)
    _vertex_manifold_check(faces, n_vertices, parents, None, violation)
    return int(read_scalar(violation)) == 0

vertex_manifold_mask

vertex_manifold_mask(
    vertices: array[vec3],
    faces: array[int32],
    *,
    mates: array[int32] | None = None,
) -> wp.array[wp.bool]

Per-vertex flag: whether each vertex has a single edge-connected fan of faces.

A vertex is manifold when the faces incident to it form one connected group under "shares an edge through this vertex" adjacency; two fans meeting only at the vertex (a bow-tie) are non-manifold. Unreferenced vertices are flagged False, matching libigl's is_vertex_manifold per-vertex output B and Open3D's GetNonManifoldVertices.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) vertex positions. Only the length is used; it sets the output size so that trailing unreferenced vertices are reported (False).

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
array[bool]

(n_vertices,) mask on faces.device.

Raises:

Type Description
RuntimeError

If vertices, faces and mates are not all on one device.

See Also

is_vertex_manifold edge_manifold_mask

Examples:

In a bow-tie only the shared vertex is non-manifold; a vertex no face uses is flagged too:

import warp as wp

import ordito as od

vertices = wp.zeros(6, dtype=wp.vec3)
faces = wp.array([0, 1, 2, 0, 3, 4], dtype=wp.int32)
mask = od.validation.vertex_manifold_mask(vertices, faces)
print(mask.numpy().tolist())  # [False, True, True, True, True, False]
Source code in ordito/validation.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def vertex_manifold_mask(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    mates: wp.array[wp.int32] | None = None,
) -> wp.array[wp.bool]:
    """
    Per-vertex flag: whether each vertex has a single edge-connected fan of faces.

    A vertex is manifold when the faces incident to it form one connected group under
    "shares an edge through this vertex" adjacency; two fans meeting only at the vertex (a bow-tie)
    are non-manifold. Unreferenced vertices are flagged ``False``, matching libigl's
    ``is_vertex_manifold`` per-vertex output ``B`` and Open3D's ``GetNonManifoldVertices``.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` vertex positions. Only the length is used; it sets the output size so that
        trailing unreferenced vertices are reported (``False``).
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    wp.array[wp.bool]
        ``(n_vertices,)`` mask on ``faces.device``.

    Raises
    ------
    RuntimeError
        If ``vertices``, ``faces`` and ``mates`` are not all on one device.

    See Also
    --------
    [`is_vertex_manifold`][ordito.validation.is_vertex_manifold]
    [`edge_manifold_mask`][ordito.validation.edge_manifold_mask]

    Examples
    --------
    In a bow-tie only the shared vertex is non-manifold; a vertex no face uses is flagged too:

    ```python
    import warp as wp

    import ordito as od

    vertices = wp.zeros(6, dtype=wp.vec3)
    faces = wp.array([0, 1, 2, 0, 3, 4], dtype=wp.int32)
    mask = od.validation.vertex_manifold_mask(vertices, faces)
    print(mask.numpy().tolist())  # [False, True, True, True, True, False]
    ```
    """
    require_same_device(vertices=vertices, faces=faces, mates=mates)
    n_vertices = vertices.size
    if faces.size // 3 == 0:
        return _launch.zeros(n_vertices, dtype=wp.bool, device=faces.device)
    # The corner graph straight off the halfedge mates, with its pair check off: no thread indexes
    # the violation flag, so none is allocated.
    parents = _corner_parents_from_mates(
        faces,
        (mates if mates is not None else od.halfedge.halfedge_mates(faces, n_vertices)),
        False,
        None,
    )
    mask = _launch.zeros(n_vertices, dtype=wp.bool, device=faces.device)
    _vertex_manifold_check(faces, n_vertices, parents, mask, None)
    return mask

is_self_intersecting

is_self_intersecting(
    mesh: Mesh, *, max_triangle_collisions: int = 32
) -> bool

Whether any two non-adjacent triangles of the mesh intersect.

Broad phase queries each triangle's AABB against mesh's BVH for candidate overlaps; narrow phase runs Moller's interval test on each candidate pair, skipping pairs that share a vertex. Mirrors Open3D's IsSelfIntersecting (AABB pre-test followed by a triangle-triangle test on non-neighbouring faces). Coplanar and merely touching pairs are not intersections -- contact alone does not count.

Parameters:

Name Type Description Default
mesh Mesh

Mesh to test; mesh.points and mesh.indices are used directly, so its BVH is always in sync with the triangles being tested (a separately-passed vertex/face pair could otherwise be misaligned with a caller's mesh).

required
max_triangle_collisions int

Broad-phase slots reserved per triangle. Not a cap: a triangle with more candidates walks the rest again on the device, so the answer does not depend on it.

32

Returns:

Type Description
bool

True when at least one intersecting non-adjacent triangle pair exists. False for meshes with fewer than two faces.

See Also

face_self_intersecting_mask mesh_with_mesh is_watertight

Notes

Equivalent to open3d.geometry.TriangleMesh.is_self_intersecting.

Examples:

import warp as wp

import ordito as od

# Two triangles piercing each other, which share no vertex.
vertices = wp.array(
    [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0],
     [0.5, 0.5, -1.0], [0.5, 0.5, 1.0], [1.5, 0.5, 1.0]],
    dtype=wp.vec3,
)
faces = wp.array([0, 1, 2, 3, 4, 5], dtype=wp.int32)
print(od.validation.is_self_intersecting(wp.Mesh(points=vertices, indices=faces)))  # True
vertices, faces = od.creation.box()
print(od.validation.is_self_intersecting(wp.Mesh(points=vertices, indices=faces)))  # False
Source code in ordito/validation.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def is_self_intersecting(mesh: wp.Mesh, *, max_triangle_collisions: int = 32) -> bool:
    """
    Whether any two non-adjacent triangles of the mesh intersect.

    Broad phase queries each triangle's AABB against ``mesh``'s BVH for candidate overlaps;
    narrow phase runs Moller's interval test on each candidate pair, skipping pairs that share a
    vertex. Mirrors Open3D's ``IsSelfIntersecting`` (AABB pre-test followed by a triangle-triangle
    test on non-neighbouring faces). Coplanar and merely touching pairs are **not** intersections
    -- contact alone does not count.

    Parameters
    ----------
    mesh
        Mesh to test; ``mesh.points`` and ``mesh.indices`` are used directly, so its BVH is
        always in sync with the triangles being tested (a separately-passed vertex/face pair
        could otherwise be misaligned with a caller's ``mesh``).
    max_triangle_collisions
        Broad-phase slots reserved per triangle. Not a cap: a triangle with more candidates walks
        the rest again on the device, so the answer does not depend on it.

    Returns
    -------
    bool
        ``True`` when at least one intersecting non-adjacent triangle pair exists. ``False`` for
        meshes with fewer than two faces.

    See Also
    --------
    [`face_self_intersecting_mask`][ordito.validation.face_self_intersecting_mask]
    [`mesh_with_mesh`][ordito.intersection.mesh_with_mesh]
    [`is_watertight`][ordito.validation.is_watertight]

    Notes
    -----
    Equivalent to ``open3d.geometry.TriangleMesh.is_self_intersecting``.

    Examples
    --------
    ```python
    import warp as wp

    import ordito as od

    # Two triangles piercing each other, which share no vertex.
    vertices = wp.array(
        [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0],
         [0.5, 0.5, -1.0], [0.5, 0.5, 1.0], [1.5, 0.5, 1.0]],
        dtype=wp.vec3,
    )
    faces = wp.array([0, 1, 2, 3, 4, 5], dtype=wp.int32)
    print(od.validation.is_self_intersecting(wp.Mesh(points=vertices, indices=faces)))  # True
    vertices, faces = od.creation.box()
    print(od.validation.is_self_intersecting(wp.Mesh(points=vertices, indices=faces)))  # False
    ```
    """
    found = _launch.zeros(1, dtype=wp.bool, device=mesh.points.device)
    _mark_self_intersections(mesh, mesh.points, mesh.indices, max_triangle_collisions, False, found)
    return bool(read_scalar(found))

face_self_intersecting_mask

face_self_intersecting_mask(
    vertices: array[vec3],
    faces: array[int32],
    *,
    max_triangle_collisions: int = 32,
    mesh: Mesh | None = None,
) -> wp.array[wp.bool]

Per-face flag: whether each triangle intersects some non-adjacent triangle.

Broad phase builds a warp.Mesh and queries each triangle's AABB for candidate overlaps; narrow phase runs Moller's interval test on each candidate pair (skipping pairs that share a vertex), and both faces of every intersecting pair are flagged. is_self_intersecting is True iff any entry of this mask is True. A pair that is coplanar, or that touches without crossing, is not an intersection.

The narrow phase runs in float64 on the float32 vertices, and it is load-bearing rather than caution. Widening is lossless, so the geometry is unchanged; what the precision buys is the decisions -- the sign of a plane distance and the overlap of two intervals. Audited face for face against an independent float64 Moller implementation over seven self-intersecting surfaces, it is exact on five, and on the other two it matches a second library and differs from the reference by at most four faces, every one of them a vertex lying on the other triangle's plane -- a tolerance choice rather than a fact. In float32 the same audit read dozens of false positives and false negatives on one surface alone. It costs a few percent of the call.

Where a comparison against another library is wanted on that tangency class, compare counts, not sets: which faces sit exactly on a tangency is the part no two implementations agree on. And a library whose loader repairs connectivity first may cut the orientation-reversing seam of a non-orientable surface, leaving two coincident sheets where the surface had one -- after which every face along the cut genuinely does intersect. Establish that the load changed nothing before reading such a comparison.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
max_triangle_collisions int

Broad-phase slots reserved per triangle. Not a cap: a triangle with more candidates walks the rest again on the device, so the answer does not depend on it.

32
mesh Mesh | None

A wp.Mesh already built over vertices and faces, to spare the BVH build the broad phase otherwise pays on every call. Purely an optimization, and not checked against vertices / faces.

None

Returns:

Type Description
array[bool]

(n_faces,) mask on faces.device. All-False for meshes with fewer than two faces.

Raises:

Type Description
RuntimeError

If vertices, faces and mesh are not all on one device.

See Also

is_self_intersecting

Examples:

Both faces of an intersecting pair are flagged:

import warp as wp

import ordito as od

# Two triangles piercing each other, which share no vertex.
vertices = wp.array(
    [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0],
     [0.5, 0.5, -1.0], [0.5, 0.5, 1.0], [1.5, 0.5, 1.0]],
    dtype=wp.vec3,
)
faces = wp.array([0, 1, 2, 3, 4, 5], dtype=wp.int32)
mask = od.validation.face_self_intersecting_mask(vertices, faces)
print(mask.numpy().tolist())  # [True, True]
Source code in ordito/validation.py
572
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
def face_self_intersecting_mask(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    max_triangle_collisions: int = 32,
    mesh: wp.Mesh | None = None,
) -> wp.array[wp.bool]:
    """
    Per-face flag: whether each triangle intersects some non-adjacent triangle.

    Broad phase builds a ``warp.Mesh`` and queries each triangle's AABB for candidate overlaps;
    narrow phase runs Moller's interval test on each candidate pair (skipping pairs that share a
    vertex), and both faces of every intersecting pair are flagged.
    [`is_self_intersecting`][ordito.validation.is_self_intersecting] is ``True`` iff any entry of
    this mask is ``True``. A pair that is coplanar, or that touches without crossing, is not an
    intersection.

    **The narrow phase runs in ``float64`` on the ``float32`` vertices**, and it is load-bearing
    rather than caution. Widening is lossless, so the geometry is unchanged; what the precision buys
    is the decisions -- the sign of a plane distance and the overlap of two intervals. Audited face
    for face against an independent ``float64`` Moller implementation over seven self-intersecting
    surfaces, it is exact on five, and on the other two it matches a second library and differs from
    the reference by at most four faces, every one of them a vertex lying *on* the other triangle's
    plane -- a tolerance choice rather than a fact. In ``float32`` the same audit read dozens of
    false positives and false negatives on one surface alone. It costs a few percent of the call.

    Where a comparison against another library is wanted on that tangency class, compare **counts,
    not sets**: which faces sit exactly on a tangency is the part no two implementations agree on.
    And a library whose loader repairs connectivity first may cut the orientation-reversing seam of
    a non-orientable surface, leaving two coincident sheets where the surface had one -- after which
    every face along the cut genuinely does intersect. Establish that the load changed nothing
    before reading such a comparison.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    max_triangle_collisions
        Broad-phase slots reserved per triangle. Not a cap: a triangle with more candidates walks
        the rest again on the device, so the answer does not depend on it.
    mesh
        A ``wp.Mesh`` already built over ``vertices`` and ``faces``, to spare the BVH build the
        broad phase otherwise pays on every call. Purely an optimization, and not checked against
        ``vertices`` / ``faces``.

    Returns
    -------
    wp.array[wp.bool]
        ``(n_faces,)`` mask on ``faces.device``. All-``False`` for meshes with fewer than two faces.

    Raises
    ------
    RuntimeError
        If ``vertices``, ``faces`` and ``mesh`` are not all on one device.

    See Also
    --------
    [`is_self_intersecting`][ordito.validation.is_self_intersecting]

    Examples
    --------
    Both faces of an intersecting pair are flagged:

    ```python
    import warp as wp

    import ordito as od

    # Two triangles piercing each other, which share no vertex.
    vertices = wp.array(
        [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0],
         [0.5, 0.5, -1.0], [0.5, 0.5, 1.0], [1.5, 0.5, 1.0]],
        dtype=wp.vec3,
    )
    faces = wp.array([0, 1, 2, 3, 4, 5], dtype=wp.int32)
    mask = od.validation.face_self_intersecting_mask(vertices, faces)
    print(mask.numpy().tolist())  # [True, True]
    ```
    """
    require_same_device(vertices=vertices, faces=faces, mesh=mesh)
    return _face_self_intersecting_mask(vertices, faces, max_triangle_collisions, mesh)

is_winding_consistent

is_winding_consistent(
    faces: array[int32],
    *,
    n_vertices: int | None = None,
    mates: array[int32] | None = None,
) -> bool

Whether every shared edge is traversed in opposite directions by its two faces.

A mesh has consistent winding when, for each edge shared by two faces, the two faces list the edge's endpoints in opposite order (so their normals agree locally). This is a property of the current winding, unlike is_orientable, which allows faces to be flipped. Matches trimesh.Trimesh.is_winding_consistent.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
n_vertices int | None

Optional exclusive bound on the vertex indices, forwarded to halfedge_mates, which pairs faster with it. It does not change the answer, and it is trusted, not checked: it must exceed every index.

None
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
bool

True when winding is consistent across all shared edges. Vacuously True for an empty mesh or a mesh with no shared edges.

Raises:

Type Description
RuntimeError

If faces and mates are not all on one device.

See Also

edge_winding_consistent_mask is_orientable is_volume trimesh.Trimesh.is_winding_consistent

Examples:

The cube is consistently wound; two triangles running their shared edge the same way are not, although flipping one would fix them (see is_orientable):

import warp as wp

import ordito as od

vertices, box_faces = od.creation.box()
print(od.validation.is_winding_consistent(box_faces))  # True
# Two triangles sharing the edge (1, 2), the second wound against the first.
faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
print(od.validation.is_winding_consistent(faces))  # False
print(od.validation.is_orientable(faces))  # True
Source code in ordito/validation.py
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
def is_winding_consistent(
    faces: wp.array[wp.int32],
    *,
    n_vertices: int | None = None,
    mates: wp.array[wp.int32] | None = None,
) -> bool:
    """
    Whether every shared edge is traversed in opposite directions by its two faces.

    A mesh has consistent winding when, for each edge shared by two faces, the two faces list the
    edge's endpoints in opposite order (so their normals agree locally). This is a property of the
    current winding, unlike [`is_orientable`][ordito.validation.is_orientable], which allows
    faces to be flipped. Matches [`trimesh.Trimesh.is_winding_consistent`][].

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    n_vertices
        Optional exclusive bound on the vertex indices, forwarded to
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], which pairs faster with it. It does
        not change the answer, and it is trusted, not checked: it must exceed every index.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    bool
        ``True`` when winding is consistent across all shared edges. Vacuously ``True`` for an empty
        mesh or a mesh with no shared edges.

    Raises
    ------
    RuntimeError
        If ``faces`` and ``mates`` are not all on one device.

    See Also
    --------
    [`edge_winding_consistent_mask`][ordito.validation.edge_winding_consistent_mask]
    [`is_orientable`][ordito.validation.is_orientable]
    [`is_volume`][ordito.validation.is_volume]
    [`trimesh.Trimesh.is_winding_consistent`][]

    Examples
    --------
    The cube is consistently wound; two triangles running their shared edge the same way are not,
    although flipping one would fix them (see [`is_orientable`][ordito.validation.is_orientable]):

    ```python
    import warp as wp

    import ordito as od

    vertices, box_faces = od.creation.box()
    print(od.validation.is_winding_consistent(box_faces))  # True
    # Two triangles sharing the edge (1, 2), the second wound against the first.
    faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
    print(od.validation.is_winding_consistent(faces))  # False
    print(od.validation.is_orientable(faces))  # True
    ```
    """
    require_same_device(faces=faces, mates=mates)
    n_faces = faces.size // 3
    if n_faces == 0:
        return True

    # ``edge_winding_consistent_mask``'s per-pair test read straight off the halfedge mates, so
    # the verdict needs no group table, no host read of its length and no reduction over a mask.
    mates = mates if mates is not None else od.halfedge.halfedge_mates(faces, n_vertices)
    violation = _launch.zeros(1, dtype=wp.int32, device=faces.device)
    _launch.launch(
        kernel_validation.mate_pair_winding_violation,
        dim=mates.size,
        inputs=[faces, None, mates, False, violation],
        device=faces.device,
    )
    return int(read_scalar(violation)) == 0

edge_winding_consistent_mask

edge_winding_consistent_mask(
    faces: array[int32], edges: Array2dInt32 | None = None
) -> wp.array[wp.bool]

Per shared-edge flag: whether an undirected edge's two faces traverse it in opposite directions.

Built over the undirected edges shared by exactly two faces (edge groups of length two). An entry is True when the two directed half-edges are reversed (locally consistent normals); boundary and non-manifold edges have no entry. is_winding_consistent is True iff every entry is True.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
edges Array2dInt32 | None

(3 * n_faces, 2) precomputed directed edges in faces_to_edges row order. Built from faces when None.

None

Returns:

Type Description
array[bool]

(n_shared_edges,) mask on faces.device. Empty when the mesh has no shared edges.

Raises:

Type Description
RuntimeError

If faces and edges are not all on one device.

See Also

is_winding_consistent face_flip_mask

Examples:

One entry per edge shared by two faces; the cube's 18 are all consistent:

import warp as wp

import ordito as od

vertices, box_faces = od.creation.box()
print(od.validation.edge_winding_consistent_mask(box_faces).shape)  # (18,)
# Two triangles sharing the edge (1, 2), the second wound against the first.
faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
print(od.validation.edge_winding_consistent_mask(faces).numpy().tolist())  # [False]
Source code in ordito/validation.py
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
def edge_winding_consistent_mask(
    faces: wp.array[wp.int32], edges: odt.Array2dInt32 | None = None
) -> wp.array[wp.bool]:
    """
    Per shared-edge flag: whether an undirected edge's two faces traverse it in opposite directions.

    Built over the undirected edges shared by exactly two faces (edge groups of length two). An
    entry is ``True`` when the two directed half-edges are reversed (locally consistent normals);
    boundary and non-manifold edges have no entry.
    [`is_winding_consistent`][ordito.validation.is_winding_consistent] is ``True`` iff every
    entry is ``True``.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    edges
        ``(3 * n_faces, 2)`` precomputed directed edges in
        [`faces_to_edges`][ordito.edges.faces_to_edges] row order. Built from ``faces`` when
        ``None``.

    Returns
    -------
    wp.array[wp.bool]
        ``(n_shared_edges,)`` mask on ``faces.device``. Empty when the mesh has no shared edges.

    Raises
    ------
    RuntimeError
        If ``faces`` and ``edges`` are not all on one device.

    See Also
    --------
    [`is_winding_consistent`][ordito.validation.is_winding_consistent]
    [`face_flip_mask`][ordito.validation.face_flip_mask]

    Examples
    --------
    One entry per edge shared by two faces; the cube's 18 are all consistent:

    ```python
    import warp as wp

    import ordito as od

    vertices, box_faces = od.creation.box()
    print(od.validation.edge_winding_consistent_mask(box_faces).shape)  # (18,)
    # Two triangles sharing the edge (1, 2), the second wound against the first.
    faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
    print(od.validation.edge_winding_consistent_mask(faces).numpy().tolist())  # [False]
    ```
    """
    require_same_device(faces=faces, edges=edges)
    n_faces = faces.size // 3
    device = faces.device
    if n_faces == 0:
        return _launch.empty(0, dtype=wp.bool, device=device)

    # The pairs are ``face_adjacency``'s: the keys come straight off ``faces`` into the sort, and
    # each pair's flag is written by the run emit, so neither an edge table nor a group table is
    # built; the kernel reads each directed edge from its face corner when ``edges`` is not given.
    order, inclusive, n_pairs = _sorted_pair_scan(faces, None)
    consistent = _launch.empty(n_pairs, dtype=wp.bool, device=device)
    if n_pairs > 0:
        _launch.launch(
            kernel_validation.emit_sorted_pair_winding,
            dim=inclusive.size,
            inputs=[faces, edges, inclusive, order, consistent],
            device=device,
        )
    return consistent

face_orientation_bits

face_orientation_bits(
    faces: array[int32],
    *,
    n_vertices: int | None = None,
    face_adjacency: Array2dInt32 | None = None,
    face_adjacency_edges: Array2dInt32 | None = None,
) -> tuple[
    wp.array[wp.int32],
    odt.Array2dInt32,
    wp.array[wp.int32],
    int,
]

Per-face Z2 orientation bits (relative to each component seed) plus signed face-adjacency edges.

orient[f] is 0 for a face that agrees with its connected component's seed and 1 for a face that must be flipped to agree — the flip mask consumed by face_flip_mask and make_winding_consistent. m is the number of face-adjacency rows; when m == 0 the returned signed_edges / signs are empty. Assumes n_faces > 0 (callers guard).

This is a lower-level primitive (the underlying orientation engine behind is_orientable and face_flip_mask) exposed for callers that need the raw flip bits together with the propagation edges, such as ordito.repair.make_winding_consistent.

The bits are solved, not propagated: orient is the Z2 potential of the signed face-adjacency graph, computed by a parity-carrying union-find (connected_component_parity_from_edges) in a fixed three launches. Cost therefore depends on the mesh's size, not on the diameter of its face-adjacency graph.

On a non-orientable component no potential exists, and some adjacency edges are left unsatisfied. Which ones depends on the setting of is_deterministic: on, the bits are the parity over the minimum spanning forest of the adjacency rows keyed by row index, each tree's lowest-indexed face at 0, the same on every run and on either device, for one more pass and a host read on every input, and a few passes more on a non-orientable one; off, they follow whichever spanning forest the parallel union-find builds, which on CUDA can differ between runs. On an orientable mesh the bits are the same either way.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer. n_faces must be positive.

required
n_vertices int | None

Optional vertex count, forwarded to face_adjacency: it narrows the sort that pairs the faces. Trusted, not checked: it must exceed every index in faces.

None
face_adjacency Array2dInt32 | None

(m, 2) precomputed face-adjacency pairs from face_adjacency (Trimesh.face_adjacency), which spares the sort that pairs the faces; signed_edges is then this array itself. Must be given together with face_adjacency_edges.

None
face_adjacency_edges Array2dInt32 | None

(m, 2) shared-edge vertex pairs aligned with face_adjacency (return_edges=True). Must be given together with face_adjacency.

None

Returns:

Name Type Description
orient array[int32]

(n_faces,) flip bits (0 or 1) on faces.device.

signed_edges Array2dInt32

(m, 2) face-adjacency pairs, one row per face-adjacency edge.

signs array[int32]

(m,) Z2 sign per adjacency edge.

m int

Number of face-adjacency rows.

Raises:

Type Description
ValueError

If only one of face_adjacency and face_adjacency_edges is given.

RuntimeError

If faces, face_adjacency and face_adjacency_edges are not all on one device.

See Also

is_orientable face_flip_mask

Examples:

The second face disagrees with the first, its component's seed:

import warp as wp

import ordito as od

# Two triangles sharing the edge (1, 2), the second wound against the first.
faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
orient, signed_edges, signs, m = od.validation.face_orientation_bits(faces)
print(orient.numpy().tolist())  # [0, 1]
print(signed_edges.numpy().tolist(), m)  # [[0, 1]] 1
Source code in ordito/validation.py
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
def face_orientation_bits(
    faces: wp.array[wp.int32],
    *,
    n_vertices: int | None = None,
    face_adjacency: odt.Array2dInt32 | None = None,
    face_adjacency_edges: odt.Array2dInt32 | None = None,
) -> tuple[wp.array[wp.int32], odt.Array2dInt32, wp.array[wp.int32], int]:
    """
    Per-face Z2 orientation bits (relative to each component seed) plus signed face-adjacency edges.

    ``orient[f]`` is ``0`` for a face that agrees with its connected component's seed and ``1`` for
    a face that must be flipped to agree — the flip mask consumed by
    [`face_flip_mask`][ordito.validation.face_flip_mask] and
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]. ``m`` is the number of
    face-adjacency rows; when ``m == 0`` the returned ``signed_edges`` / ``signs`` are empty.
    Assumes ``n_faces > 0`` (callers guard).

    This is a lower-level primitive (the underlying orientation engine behind
    [`is_orientable`][ordito.validation.is_orientable] and
    [`face_flip_mask`][ordito.validation.face_flip_mask]) exposed for callers that
    need the raw flip bits together with the propagation edges, such as
    [`ordito.repair.make_winding_consistent`][ordito.repair.make_winding_consistent].

    The bits are solved, not propagated: ``orient`` is the Z2 potential of the signed
    face-adjacency graph, computed by a parity-carrying union-find
    ([`connected_component_parity_from_edges`]
    [ordito.graph.connected_component_parity_from_edges]) in a fixed three launches. Cost
    therefore depends on the mesh's *size*, not on the diameter of its face-adjacency graph.

    On a non-orientable component no potential exists, and some adjacency edges are left
    unsatisfied. Which ones depends on the setting of
    [`is_deterministic`][ordito.config.is_deterministic]: on, the bits are the parity over the
    minimum spanning forest of the adjacency rows keyed by row index, each tree's lowest-indexed
    face at ``0``, the same on every run and on either device, for one more pass and a host read
    on every input, and a few passes more on a non-orientable one; off, they follow whichever
    spanning forest the parallel union-find builds, which on CUDA can differ between runs. On an
    orientable mesh the bits are the same either way.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer. ``n_faces`` must be positive.
    n_vertices
        Optional vertex count, forwarded to
        [`face_adjacency`][ordito.adjacency.face_adjacency]: it narrows the sort that pairs the
        faces. Trusted, not checked: it must exceed every index in ``faces``.
    face_adjacency
        ``(m, 2)`` precomputed face-adjacency pairs from
        [`face_adjacency`][ordito.adjacency.face_adjacency]
        ([`Trimesh.face_adjacency`][ordito.mesh.Trimesh.face_adjacency]), which spares the sort
        that pairs the faces; ``signed_edges`` is then this array itself. Must be given together
        with ``face_adjacency_edges``.
    face_adjacency_edges
        ``(m, 2)`` shared-edge vertex pairs aligned with ``face_adjacency``
        (``return_edges=True``). Must be given together with ``face_adjacency``.

    Returns
    -------
    orient : wp.array[wp.int32]
        ``(n_faces,)`` flip bits (``0`` or ``1``) on ``faces.device``.
    signed_edges : odt.Array2dInt32
        ``(m, 2)`` face-adjacency pairs, one row per face-adjacency edge.
    signs : wp.array[wp.int32]
        ``(m,)`` Z2 sign per adjacency edge.
    m : int
        Number of face-adjacency rows.

    Raises
    ------
    ValueError
        If only one of ``face_adjacency`` and ``face_adjacency_edges`` is given.
    RuntimeError
        If ``faces``, ``face_adjacency`` and ``face_adjacency_edges`` are not all on one device.

    See Also
    --------
    [`is_orientable`][ordito.validation.is_orientable]
    [`face_flip_mask`][ordito.validation.face_flip_mask]

    Examples
    --------
    The second face disagrees with the first, its component's seed:

    ```python
    import warp as wp

    import ordito as od

    # Two triangles sharing the edge (1, 2), the second wound against the first.
    faces = wp.array([0, 1, 2, 1, 2, 3], dtype=wp.int32)
    orient, signed_edges, signs, m = od.validation.face_orientation_bits(faces)
    print(orient.numpy().tolist())  # [0, 1]
    print(signed_edges.numpy().tolist(), m)  # [[0, 1]] 1
    ```
    """
    require_same_device(
        faces=faces, face_adjacency=face_adjacency, face_adjacency_edges=face_adjacency_edges
    )
    od.adjacency.require_paired_adjacency(face_adjacency, face_adjacency_edges)
    device = faces.device
    n_faces = faces.size // 3
    if face_adjacency is None or face_adjacency_edges is None:
        adjacency, adjacency_edges = od.adjacency.face_adjacency(
            faces, return_edges=True, n_vertices=n_vertices
        )
    else:
        adjacency, adjacency_edges = face_adjacency, face_adjacency_edges
    m = int(adjacency.shape[0])

    if m == 0:
        signed_edges = odt.empty_2d((0, 2), wp.int32, device=device)
        signs = _launch.empty(0, dtype=wp.int32, device=device)
        return _launch.zeros(n_faces, dtype=wp.int32, device=device), signed_edges, signs, m

    # The signed edges are the adjacency rows themselves, so only the signs are written, by the
    # launch that also lays down the parity forest's identity words.
    signed_edges = adjacency
    signs = _launch.empty(m, dtype=wp.int32, device=device)
    words = _launch.empty(n_faces, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_validation.face_pair_signs_and_roots,
        dim=max(m, n_faces),
        inputs=[faces, adjacency, adjacency_edges, n_faces],
        outputs=[signs, words],
        device=device,
    )

    # The flip bits *are* a Z2 potential over the signed face-adjacency graph, so a parity-carrying
    # union-find produces them directly, in a hook and a flatten after the signs, with no host sync
    # ([`connected_component_parity_from_edges`]
    # [ordito.graph.connected_component_parity_from_edges]). The bits are unchanged from the
    # edge-by-edge flood fill this replaces: that seeded ``0`` at each component's smallest face id
    # and XOR-ed signs outward, and the union-find's root is that same smallest id at that same
    # parity 0. What changes is the cost — the fill ran one launch per graph level, so a mesh whose
    # face adjacency is a long path (a ribbon) paid tens of thousands of launches and thousands of
    # readbacks for work bounded by a few milliseconds of bandwidth.
    # ``signed_edges`` holds face ids this function just built from ``adjacency`` (itself bounded
    # by ``n_faces`` by construction) and every sign is ``0`` or ``1``, so nothing is range-checked.
    if is_deterministic():
        # The flagged hook tells whether the racing forest already is the reproducible answer.
        conflict = _launch.zeros(1, dtype=wp.int32, device=device)
        _launch.launch(
            kernel_connected_components.ecl_hook_parity_flagged,
            dim=m,
            inputs=[signed_edges, signs, words],
            outputs=[conflict],
            device=device,
        )
        words = _reproducible_orientation_words(faces, None, signed_edges, signs, words, conflict)
    else:
        _launch.launch(
            kernel_connected_components.ecl_hook_parity,
            dim=m,
            inputs=[signed_edges, signs, words],
            device=device,
        )
    return _flatten_orientation(words), signed_edges, signs, m

is_orientable

is_orientable(
    faces: array[int32],
    *,
    n_vertices: int | None = None,
    mates: array[int32] | None = None,
) -> bool

Whether the faces admit a consistent orientation (allowing per-face flips).

A mesh is orientable when each face can be assigned a flip bit so that every pair of edge-adjacent faces traverses their shared edge in opposite directions. This is a topological property independent of the current winding. Only edges shared by exactly two faces constrain the bits; a boundary edge, an edge shared by three or more faces, and a degenerate face's edge run both ways by that face alone constrain nothing.

Each face-adjacency edge carries a Z2 constraint on its two faces' flip bits; a parity union-find joins the faces and reports a non-orientable mesh as soon as an edge contradicts the bits its faces already hold.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
n_vertices int | None

Optional exclusive bound on the vertex indices, forwarded to halfedge_mates, which pairs faster with it. It does not change the answer, and it is trusted, not checked: it must exceed every index.

None
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
bool

True when a consistent orientation exists. Vacuously True for an empty mesh.

Raises:

Type Description
RuntimeError

If faces and mates are not all on one device.

See Also

face_flip_mask is_watertight is_winding_consistent

Notes

Equal to open3d.geometry.TriangleMesh.is_orientable on edge-manifold meshes without degenerate faces. Elsewhere Open3D orients by a traversal whose answer can change with the order of the faces alone, so the two are not comparable there. Unlike is_winding_consistent, orientability allows individual faces to be flipped, so a consistently-orientable mesh with inconsistent winding still returns True.

Examples:

A Mobius strip, three quads joined with a half twist, cannot be wound consistently whichever faces are flipped:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
print(od.validation.is_orientable(faces))  # True
mobius = wp.array([0, 3, 4, 0, 4, 1, 1, 4, 5, 1, 5, 2, 2, 5, 0, 2, 0, 3], dtype=wp.int32)
print(od.validation.is_orientable(mobius))  # False
Source code in ordito/validation.py
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
def is_orientable(
    faces: wp.array[wp.int32],
    *,
    n_vertices: int | None = None,
    mates: wp.array[wp.int32] | None = None,
) -> bool:
    """
    Whether the faces admit a consistent orientation (allowing per-face flips).

    A mesh is orientable when each face can be assigned a flip bit so that every pair of
    edge-adjacent faces traverses their shared edge in opposite directions. This is a topological
    property independent of the current winding. Only edges shared by exactly two faces constrain
    the bits; a boundary edge, an edge shared by three or more faces, and a degenerate face's edge
    run both ways by that face alone constrain nothing.

    Each face-adjacency edge carries a Z2 constraint on its two faces' flip bits; a parity
    union-find joins the faces and reports a non-orientable mesh as soon as an edge contradicts the
    bits its faces already hold.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    n_vertices
        Optional exclusive bound on the vertex indices, forwarded to
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], which pairs faster with it. It does
        not change the answer, and it is trusted, not checked: it must exceed every index.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    bool
        ``True`` when a consistent orientation exists. Vacuously ``True`` for an empty mesh.

    Raises
    ------
    RuntimeError
        If ``faces`` and ``mates`` are not all on one device.

    See Also
    --------
    [`face_flip_mask`][ordito.validation.face_flip_mask]
    [`is_watertight`][ordito.validation.is_watertight]
    [`is_winding_consistent`][ordito.validation.is_winding_consistent]

    Notes
    -----
    Equal to ``open3d.geometry.TriangleMesh.is_orientable`` on edge-manifold meshes without
    degenerate faces. Elsewhere Open3D orients by a traversal whose answer can change with the order
    of the faces alone, so the two are not comparable there. Unlike
    [`is_winding_consistent`][ordito.validation.is_winding_consistent], orientability allows
    individual faces to be flipped, so a consistently-orientable mesh with inconsistent winding
    still returns ``True``.

    Examples
    --------
    A Mobius strip, three quads joined with a half twist, cannot be wound consistently whichever
    faces are flipped:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    print(od.validation.is_orientable(faces))  # True
    mobius = wp.array([0, 3, 4, 0, 4, 1, 1, 4, 5, 1, 5, 2, 2, 5, 0, 2, 0, 3], dtype=wp.int32)
    print(od.validation.is_orientable(mobius))  # False
    ```
    """
    require_same_device(faces=faces, mates=mates)
    n_faces = faces.size // 3
    if n_faces == 0:
        return True

    # The hook flags a pair its forest contradicts, which is a re-test of every pair against the
    # flattened bits: no flatten and no second pass.
    conflict = _launch.zeros(1, dtype=wp.int32, device=faces.device)
    _orientation_words_from_mates(faces, n_vertices, mates, conflict)
    return int(read_scalar(conflict, 0)) == 0

face_flip_mask

face_flip_mask(
    faces: array[int32],
    *,
    n_vertices: int | None = None,
    mates: array[int32] | None = None,
) -> wp.array[wp.bool]

Per-face flag: whether a face must be flipped to make winding consistent within its patch.

Runs the Z2 orientation propagation over the face-adjacency graph and returns True for every face whose winding disagrees with its connected component's seed, the component's lowest-indexed face (whose own entry is therefore always False). Applying these flips yields a consistently wound mesh, so this is the per-face flip mask consumed by make_winding_consistent. A mesh that is already consistently wound yields an all-False mask.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
n_vertices int | None

Optional exclusive bound on the vertex indices, forwarded to halfedge_mates, which pairs faster with it. It does not change the answer, and it is trusted, not checked: it must exceed every index.

None
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
array[bool]

(n_faces,) mask on faces.device. Empty for an empty mesh.

Raises:

Type Description
RuntimeError

If faces and mates are not all on one device.

See Also

is_orientable is_winding_consistent make_winding_consistent face_flipped_mask

Notes

On an orientable mesh the mask is a deterministic function of faces: each component keeps its lowest-indexed face's winding, on either device. On a non-orientable patch no consistent winding exists and the mask is a best-effort flood-fill (matching trimesh.repair.fix_winding) that leaves the contradiction on a seam. Which seam depends on the setting of is_deterministic:

  • on, the mask is the parity over the minimum spanning forest of the edge-adjacent face pairs, each pair keyed by the lower of its two halfedge indices (3 * face + corner): each tree's lowest-indexed face keeps its winding, every other face agrees with its tree path, and the seam is the pairs the forest leaves out. The same mask on every run and on either device, for one more pass and a host read on every input, and a few passes more on a non-orientable one;
  • off, it is whichever spanning forest the parallel union-find builds, which on CUDA can differ between runs.

This is a different flip from face_flipped_mask, which is about the UV domain: this mask flags a triangle whose index order must be reversed to agree with its patch, a property of the 3D connectivity that ignores geometry entirely, while that one flags a triangle whose UV image has negative signed area. Neither implies the other.

Examples:

Reversing one cube face makes it disagree with all the others. The mask keeps the winding of the lowest-indexed face, so here it flags the eleven faces that were not changed; flipping them gives a consistent, inward-facing cube:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
rows = faces.numpy().reshape(-1, 3)
rows[0] = rows[0][::-1]
faces = wp.array(rows.ravel(), dtype=wp.int32)
flips = od.validation.face_flip_mask(faces).numpy()
print(int(flips.sum()), bool(flips[0]))  # 11 False
Source code in ordito/validation.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
def face_flip_mask(
    faces: wp.array[wp.int32],
    *,
    n_vertices: int | None = None,
    mates: wp.array[wp.int32] | None = None,
) -> wp.array[wp.bool]:
    """
    Per-face flag: whether a face must be flipped to make winding consistent within its patch.

    Runs the Z2 orientation propagation over the face-adjacency graph and returns ``True`` for
    every face whose winding disagrees with its connected component's seed, the component's
    lowest-indexed face (whose own entry is therefore always ``False``). Applying these flips
    yields a consistently wound mesh, so this is the per-face flip mask consumed by
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]. A mesh that is already
    consistently wound yields an all-``False`` mask.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    n_vertices
        Optional exclusive bound on the vertex indices, forwarded to
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], which pairs faster with it. It does
        not change the answer, and it is trusted, not checked: it must exceed every index.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    wp.array[wp.bool]
        ``(n_faces,)`` mask on ``faces.device``. Empty for an empty mesh.

    Raises
    ------
    RuntimeError
        If ``faces`` and ``mates`` are not all on one device.

    See Also
    --------
    [`is_orientable`][ordito.validation.is_orientable]
    [`is_winding_consistent`][ordito.validation.is_winding_consistent]
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]
    [`face_flipped_mask`][ordito.parametrization.face_flipped_mask]

    Notes
    -----
    On an orientable mesh the mask is a deterministic function of ``faces``: each component keeps
    its lowest-indexed face's winding, on either device. On a non-orientable patch no consistent
    winding exists and the mask is a best-effort flood-fill (matching
    ``trimesh.repair.fix_winding``) that leaves the contradiction on a seam. Which seam depends
    on the setting of [`is_deterministic`][ordito.config.is_deterministic]:

    - on, the mask is the parity over the minimum spanning forest of the edge-adjacent face pairs,
      each pair keyed by the lower of its two halfedge indices (``3 * face + corner``): each tree's
      lowest-indexed face keeps its winding, every other face agrees with its tree path, and the
      seam is the pairs the forest leaves out. The same mask on every run and on either device,
      for one more pass and a host read on every input, and a few passes more on a non-orientable
      one;
    - off, it is whichever spanning forest the parallel union-find builds, which on CUDA can differ
      between runs.

    This is a different flip from
    [`face_flipped_mask`][ordito.parametrization.face_flipped_mask], which is about the *UV
    domain*: this mask flags a triangle whose index order must be reversed to agree with its patch,
    a property of the 3D connectivity that ignores geometry entirely, while that one flags a
    triangle whose UV image has negative signed area. Neither implies the other.

    Examples
    --------
    Reversing one cube face makes it disagree with all the others. The mask keeps the winding of
    the lowest-indexed face, so here it flags the eleven faces that were *not* changed; flipping
    them gives a consistent, inward-facing cube:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    rows = faces.numpy().reshape(-1, 3)
    rows[0] = rows[0][::-1]
    faces = wp.array(rows.ravel(), dtype=wp.int32)
    flips = od.validation.face_flip_mask(faces).numpy()
    print(int(flips.sum()), bool(flips[0]))  # 11 False
    ```
    """
    require_same_device(faces=faces, mates=mates)
    n_faces = faces.size // 3
    device = faces.device
    if n_faces == 0:
        return _launch.empty(0, dtype=wp.bool, device=device)

    # The flip mask is the parity itself, so the flatten writes it as a ``bool`` directly.
    words = _face_flip_words(faces, n_vertices, mates)
    mask = _launch.empty(n_faces, dtype=wp.bool, device=device)
    _launch.launch(
        kernel_validation.flatten_parity_flip_mask, dim=n_faces, inputs=[words, mask], device=device
    )
    return mask

is_watertight

is_watertight(
    vertices: array[vec3],
    faces: array[int32],
    *,
    mesh: Mesh | Callable[[], Mesh] | None = None,
    mates: array[int32] | None = None,
) -> bool

Whether the mesh bounds a closed volume with no self-intersections.

Follows Open3D's IsWatertight: the mesh must be edge-manifold with no boundary edges, vertex-manifold, and free of self-intersections. Vertices no face uses are ignored, as in Open3D: they are not part of the surface. (The stricter is_vertex_manifold counts one below max(faces) as non-manifold, as libigl does.)

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
mesh Mesh | Callable[[], Mesh] | None

A wp.Mesh already built over vertices and faces, forwarded to the self-intersection broad phase so its BVH is not rebuilt -- or a zero-argument callable returning one, called only once both manifold tests have passed, so a caller that caches the mesh builds it only when the answer needs it. Purely an optimization, and not checked against vertices / faces.

None
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
bool

True when the mesh is edge-manifold (no boundary), vertex-manifold, and not self-intersecting.

Raises:

Type Description
RuntimeError

If vertices, faces, a wp.Mesh mesh and mates are not all on one device.

See Also

face_watertight_mask is_edge_manifold is_vertex_manifold is_self_intersecting is_volume

Notes

Equivalent to open3d.geometry.TriangleMesh.is_watertight. For the cheaper "every edge shared by exactly two faces" test (trimesh semantics) use is_edge_manifold with allow_boundary_edges=False.

This is not the predicate form of face_watertight_mask, despite the names: that mask is trimesh's per-face edge test, while this is Open3D's three-part composition, so all(face_watertight_mask(faces)) is the first of the three conditions and not this function. Every other is_* / *_mask pair in this module does relate that way.

Examples:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
print(od.validation.is_watertight(vertices, faces))  # True
open_box = wp.array(faces.numpy()[3:], dtype=wp.int32)  # face 0 removed
print(od.validation.is_watertight(vertices, open_box))  # False
Source code in ordito/validation.py
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
def is_watertight(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    mesh: wp.Mesh | Callable[[], wp.Mesh] | None = None,
    mates: wp.array[wp.int32] | None = None,
) -> bool:
    """
    Whether the mesh bounds a closed volume with no self-intersections.

    Follows Open3D's ``IsWatertight``: the mesh must be edge-manifold with no boundary edges,
    vertex-manifold, and free of self-intersections. Vertices no face uses are ignored, as in
    Open3D: they are not part of the surface. (The stricter
    [`is_vertex_manifold`][ordito.validation.is_vertex_manifold] counts one below ``max(faces)``
    as non-manifold, as libigl does.)

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    mesh
        A ``wp.Mesh`` already built over ``vertices`` and ``faces``, forwarded to the
        self-intersection broad phase so its BVH is not rebuilt -- or a zero-argument callable
        returning one, called only once both manifold tests have passed, so a caller that caches
        the mesh builds it only when the answer needs it. Purely an optimization, and not checked
        against ``vertices`` / ``faces``.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    bool
        ``True`` when the mesh is edge-manifold (no boundary), vertex-manifold, and not
        self-intersecting.

    Raises
    ------
    RuntimeError
        If ``vertices``, ``faces``, a ``wp.Mesh`` ``mesh`` and ``mates`` are not all on one device.

    See Also
    --------
    [`face_watertight_mask`][ordito.validation.face_watertight_mask]
    [`is_edge_manifold`][ordito.validation.is_edge_manifold]
    [`is_vertex_manifold`][ordito.validation.is_vertex_manifold]
    [`is_self_intersecting`][ordito.validation.is_self_intersecting]
    [`is_volume`][ordito.validation.is_volume]

    Notes
    -----
    Equivalent to ``open3d.geometry.TriangleMesh.is_watertight``. For the cheaper "every edge shared
    by exactly two faces" test (trimesh semantics) use
    [`is_edge_manifold`][ordito.validation.is_edge_manifold] with
    ``allow_boundary_edges=False``.

    **This is not the predicate form of
    [`face_watertight_mask`][ordito.validation.face_watertight_mask]**, despite the names: that
    mask is trimesh's per-face edge test, while this is Open3D's three-part composition, so
    ``all(face_watertight_mask(faces))`` is the *first* of the three conditions and not this
    function. Every other ``is_*`` / ``*_mask`` pair in this module does relate that way.

    Examples
    --------
    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    print(od.validation.is_watertight(vertices, faces))  # True
    open_box = wp.array(faces.numpy()[3:], dtype=wp.int32)  # face 0 removed
    print(od.validation.is_watertight(vertices, open_box))  # False
    ```
    """
    require_same_device(
        vertices=vertices,
        faces=faces,
        mesh=mesh if isinstance(mesh, wp.Mesh) else None,
        mates=mates,
    )
    n_faces = faces.size // 3
    if n_faces == 0:
        return True

    # One sort of the halfedge keys serves the first two checks: the runs of equal keys are the
    # edge-share counts the edge test reads and the face pairs the vertex test's corner graph
    # links, so neither a face-adjacency table nor a second packing is built. Both tests raise one
    # flag and it is read once; only the self-intersection test, which needs a BVH, waits for it.
    # Reading the edge test's flag first, to skip the vertex test on an open mesh, costs a closed
    # mesh more than it saves an open one: the vertex test's launches then no longer overlap the
    # sort on the device. Declined the other way (2026-11-12, CUDA): issuing the BVH build and the
    # self-intersection pass before this read, so one sync serves both, took watertight and
    # self-intersecting icospheres to 0.97-1.02x from 5 k to 2.6 M faces and cost an open one
    # 3.1-17x (the BVH and the broad phase it skips today).
    n_vertices = vertices.size
    violation = _launch.zeros(1, dtype=wp.int32, device=faces.device)
    parents = _corner_parents_from_mates(
        faces,
        (mates if mates is not None else od.halfedge.halfedge_mates(faces, n_vertices)),
        True,
        violation,
    )
    _vertex_manifold_check(faces, n_vertices, parents, None, violation, require_referenced=False)
    if int(read_scalar(violation)) != 0:
        return False
    if mesh is None:
        require_nonempty_mesh(faces, "is_watertight")
        mesh = wp.Mesh(points=vertices, indices=faces)
    elif not isinstance(mesh, wp.Mesh):
        mesh = mesh()
    return not is_self_intersecting(mesh)

face_watertight_mask

face_watertight_mask(
    faces: array[int32], *, n_vertices: int | None = None
) -> wp.array[wp.bool]

Per-face flag: whether all three of a face's undirected edges are shared by exactly two faces.

This is edge_manifold_mask with allow_boundary_edges=False: a face is True only when none of its edges is a boundary edge (used once) or a non-manifold edge (used three or more times). The faces that break watertightness (trimesh's broken_faces) are flatnonzero(~face_watertight_mask(faces)).

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
n_vertices int | None

Optional vertex count forwarded as the edge-hash base. When None, inferred from faces with a device-host sync.

None

Returns:

Type Description
array[bool]

(n_faces,) mask on faces.device. Empty for an empty mesh.

Raises:

Type Description
ValueError

If a face index is negative or reaches the vertex count.

See Also

is_watertight edge_manifold_mask

Examples:

Removing one face of a cube opens a hole whose rim runs through the faces next to it:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
open_box = wp.array(faces.numpy()[3:], dtype=wp.int32)  # face 0 removed
mask = od.validation.face_watertight_mask(open_box)
print(mask.shape)  # (11,)
print(np.flatnonzero(~mask.numpy()).tolist())  # [0, 1, 3]
Source code in ordito/validation.py
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
def face_watertight_mask(
    faces: wp.array[wp.int32], *, n_vertices: int | None = None
) -> wp.array[wp.bool]:
    """
    Per-face flag: whether all three of a face's undirected edges are shared by exactly two faces.

    This is [`edge_manifold_mask`][ordito.validation.edge_manifold_mask] with
    ``allow_boundary_edges=False``: a face is ``True`` only when none of its edges is a boundary
    edge (used once) or a non-manifold edge (used three or more times). The faces that break
    watertightness (trimesh's ``broken_faces``) are ``flatnonzero(~face_watertight_mask(faces))``.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    n_vertices
        Optional vertex count forwarded as the edge-hash base. When ``None``, inferred from
        ``faces`` with a device-host sync.

    Returns
    -------
    wp.array[wp.bool]
        ``(n_faces,)`` mask on ``faces.device``. Empty for an empty mesh.

    Raises
    ------
    ValueError
        If a face index is negative or reaches the vertex count.

    See Also
    --------
    [`is_watertight`][ordito.validation.is_watertight]
    [`edge_manifold_mask`][ordito.validation.edge_manifold_mask]

    Examples
    --------
    Removing one face of a cube opens a hole whose rim runs through the faces next to it:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    open_box = wp.array(faces.numpy()[3:], dtype=wp.int32)  # face 0 removed
    mask = od.validation.face_watertight_mask(open_box)
    print(mask.shape)  # (11,)
    print(np.flatnonzero(~mask.numpy()).tolist())  # [0, 1, 3]
    ```
    """
    return edge_manifold_mask(faces, allow_boundary_edges=False, n_vertices=n_vertices)

is_volume

is_volume(
    vertices: array[vec3],
    faces: array[int32],
    *,
    edges: Array2dInt32 | None = None,
    mates: array[int32] | None = None,
) -> bool

Whether the mesh is a valid closed volume with outward-facing normals.

Follows trimesh.Trimesh.is_volume: the mesh must be watertight (every undirected edge shared by exactly two faces), winding-consistent, and enclose a positive signed volume (normals point outward). A mesh with inward-facing normals encloses a negative signed volume and is reported False.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
edges Array2dInt32 | None

(3 * n_faces, 2) precomputed directed edges in faces_to_edges row order. When None, built from faces.

None
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None

Returns:

Type Description
bool

True when the mesh is watertight, winding-consistent, and has outward normals (positive signed volume). False for an empty mesh.

Raises:

Type Description
RuntimeError

If vertices, faces, edges and mates are not all on one device.

See Also

make_volume Produce one: flip whatever fails this test. volume Measure one, once this returns True. is_winding_consistent is_watertight is_orientable trimesh.Trimesh.is_volume

Notes

Watertightness here is trimesh's "every undirected edge shared by exactly two faces" (each sorted edge forms a group of two), and winding consistency requires the two directed copies of every shared edge to be reversed. The signed volume is the sum of per-face signed tetrahedron volumes dot(v0, cross(v1, v2)) / 6 measured from the origin; for a closed surface this is independent of the reference point and its sign encodes the normal orientation.

Examples:

Reversing every face keeps the cube watertight and consistent but turns its normals inward:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
print(od.validation.is_volume(vertices, faces))  # True
inverted = wp.array(faces.numpy().reshape(-1, 3)[:, ::-1].ravel(), dtype=wp.int32)
print(od.validation.is_volume(vertices, inverted))  # False
Source code in ordito/validation.py
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
def is_volume(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    edges: odt.Array2dInt32 | None = None,
    mates: wp.array[wp.int32] | None = None,
) -> bool:
    """
    Whether the mesh is a valid closed volume with outward-facing normals.

    Follows [`trimesh.Trimesh.is_volume`][]: the mesh must be watertight (every undirected edge
    shared by exactly two faces), winding-consistent, and enclose a positive signed volume (normals
    point outward). A mesh with inward-facing normals encloses a negative signed volume and is
    reported ``False``.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    edges
        ``(3 * n_faces, 2)`` precomputed directed edges in
        [`faces_to_edges`][ordito.edges.faces_to_edges] row order. When ``None``, built from
        ``faces``.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.

    Returns
    -------
    bool
        ``True`` when the mesh is watertight, winding-consistent, and has outward normals (positive
        signed volume). ``False`` for an empty mesh.

    Raises
    ------
    RuntimeError
        If ``vertices``, ``faces``, ``edges`` and ``mates`` are not all on one device.

    See Also
    --------
    [`make_volume`][ordito.repair.make_volume]
        Produce one: flip whatever fails this test.
    [`volume`][ordito.measures.volume]
        Measure one, once this returns ``True``.
    [`is_winding_consistent`][ordito.validation.is_winding_consistent]
    [`is_watertight`][ordito.validation.is_watertight]
    [`is_orientable`][ordito.validation.is_orientable]
    [`trimesh.Trimesh.is_volume`][]

    Notes
    -----
    Watertightness here is trimesh's "every undirected edge shared by exactly two faces" (each
    sorted edge forms a group of two), and winding consistency requires the two directed copies of
    every shared edge to be reversed. The signed volume is the sum of per-face signed tetrahedron
    volumes ``dot(v0, cross(v1, v2)) / 6`` measured from the origin; for a closed surface this is
    independent of the reference point and its sign encodes the normal orientation.

    Examples
    --------
    Reversing every face keeps the cube watertight and consistent but turns its normals inward:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    print(od.validation.is_volume(vertices, faces))  # True
    inverted = wp.array(faces.numpy().reshape(-1, 3)[:, ::-1].ravel(), dtype=wp.int32)
    print(od.validation.is_volume(vertices, inverted))  # False
    ```
    """
    require_same_device(vertices=vertices, faces=faces, edges=edges, mates=mates)
    n_faces = faces.size // 3
    if n_faces == 0:
        return False

    # Watertightness and winding consistency are a count over the halfedge mates -- a halfedge
    # without a mate is on an edge not shared by exactly two faces, and each pair's two directed
    # copies must be reversed -- taken in the launch that folds the volume, read back with it.
    mates = mates if mates is not None else od.halfedge.halfedge_mates(faces, vertices.size)
    volume, closed = _closed_signed_volume(vertices, faces, mates, edges, True)
    return closed and volume > 0.0

face_defective_mask

face_defective_mask(
    vertices: array[vec3],
    faces: array[int32],
    *,
    min_quality: float | None = 0.02,
    max_normal_angle: float | None = None,
    max_fold_angle: float | None = None,
    face_normals: array[vec3] | None = None,
    mates: array[int32] | None = None,
    normal_criterion: Literal[
        "consensus", "meshlab"
    ] = "consensus",
) -> wp.array[wp.bool]

Flag faces that are thin, misoriented relative to their neighbourhood, or folded over it.

The three criteria are independent and a face is flagged if any enabled one fires; each is disabled by passing None. This is the detector behind repair.remove_folded_faces -- unlike the rest of this module it needs geometry rather than topology, which is why it takes vertices and has no is_* counterpart: "defective" is a threshold question, not a property of the mesh.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
min_quality float | None

Flag a face whose radius_ratio (face_quality) is below this. 0 is fully degenerate and 1 is equilateral, so this is a thinness gate; MeshLab's aratio, whose default of 0.02 is this one. None disables it.

0.02
max_normal_angle float | None

Flag a face whose normal is more than this many degrees from the direction of the sum of its edge-neighbours' normals — the local consensus. This catches a single face inserted the wrong way round in an otherwise consistent patch. Same default (60) as MeshLab's nfratio but not the same test unless normal_criterion="meshlab" (see Notes). None disables it.

None
max_fold_angle float | None

Flag a face that meets some neighbour at more than this many degrees — a fold, where the two triangles lie almost on top of each other with opposing normals. Of the two faces at such an edge only the one facing against its own wider neighbourhood is flagged, since only one of them is the mistake; a face whose neighbours give it no consensus (an isolated face, or a strip of exactly three) is therefore never flagged on this criterion alone. MeshLab's folded_faces_angle_threshold (default 160, off by default). Must be in (0, 180]. None disables it.

None
face_normals array[vec3] | None

(n_faces,) unit face normals from face_normals_and_areas; formed from the corners where they are read when None. Only the two angle criteria read them.

None
mates array[int32] | None

(3 * n_faces,) halfedge mate codes of faces, from halfedge_mates, to spare the sort that otherwise pairs the halfedges. Not checked against faces. Trimesh.halfedge_mates is the cached one to pass.

None
normal_criterion Literal['consensus', 'meshlab']

What max_normal_angle compares a face's normal with.

  • "consensus" (default) — the direction of the sum of its edge-neighbours' normals.
  • "meshlab" — each edge-neighbour's normal in turn, flagging the face when any one differs by more than the angle: MeshLab's nfratio.

"consensus" is the default because it flags far fewer correct faces: MeshLab's test flags both faces of every edge sharper than the angle, so it marks a reversed face's neighbours, and every face of a cube (see Notes).

'consensus'

Returns:

Type Description
array[bool]

(n_faces,) mask on faces.device; True marks a defective face. All-False when every criterion is disabled.

Raises:

Type Description
ValueError

If max_normal_angle or max_fold_angle is outside (0, 180], or normal_criterion is not "consensus" or "meshlab".

RuntimeError

If vertices, faces, face_normals and mates are not all on one device.

Notes

The thinness and fold criteria match MeshLab's compute_selection_bad_faces (its aratio and folded_faces_angle_threshold). The default normal criterion does not match its nfratio: MeshLab selects both faces of every edge whose normals differ by more than the angle (normal_criterion="meshlab"), so it flags a reversed face together with all its neighbours, and every face of a cube at 60. Comparing each face with its neighbours' consensus instead flags the reversed face alone on a smooth surface. The consensus needs neighbours that mostly agree: on a coarse mesh, where a face has three neighbours and they meet at sharp angles, a correct face next to a reversed one can fail it too (a cube with one triangle reversed flags that triangle and one neighbour).

See Also

repair.remove_folded_faces Deletes the folded ones. Trimesh.face_normals Caches what face_normals wants. repair.remove_degenerate_faces Deletes the fully degenerate ones, on an exact test rather than a threshold. ordito.triangles.face_quality The thinness measure min_quality gates on.

Examples:

The second triangle is a sliver, far below the default thinness gate:

import warp as wp

import ordito as od

vertices = wp.array(
    [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.001, 0.0]], dtype=wp.vec3
)
faces = wp.array([0, 1, 2, 1, 3, 2], dtype=wp.int32)
print(od.validation.face_defective_mask(vertices, faces).numpy().tolist())  # [False, True]

One face of a sphere reversed against its neighbours is caught by the normal criterion:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
rows = faces.numpy().reshape(-1, 3)
rows[5] = rows[5][::-1]
faces = wp.array(rows.ravel(), dtype=wp.int32)
mask = od.validation.face_defective_mask(vertices, faces, max_normal_angle=60.0)
print(np.flatnonzero(mask.numpy()).tolist())  # [5]
Source code in ordito/validation.py
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
def face_defective_mask(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    min_quality: float | None = 0.02,
    max_normal_angle: float | None = None,
    max_fold_angle: float | None = None,
    face_normals: wp.array[wp.vec3] | None = None,
    mates: wp.array[wp.int32] | None = None,
    normal_criterion: Literal["consensus", "meshlab"] = "consensus",
) -> wp.array[wp.bool]:
    """
    Flag faces that are thin, misoriented relative to their neighbourhood, or folded over it.

    The three criteria are independent and a face is flagged if *any* enabled one fires; each is
    disabled by passing ``None``. This is the detector behind
    [`repair.remove_folded_faces`][ordito.repair.remove_folded_faces] -- unlike the rest of this
    module it needs geometry rather than topology, which is why it takes ``vertices`` and has no
    ``is_*`` counterpart: "defective" is a threshold question, not a property of the mesh.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    min_quality
        Flag a face whose ``radius_ratio``
        ([`face_quality`][ordito.triangles.face_quality]) is below this. ``0`` is fully degenerate
        and ``1`` is equilateral, so this is a *thinness* gate; MeshLab's ``aratio``, whose default
        of ``0.02`` is this one. ``None`` disables it.
    max_normal_angle
        Flag a face whose normal is more than this many **degrees** from the direction of the sum of
        its edge-neighbours' normals — the local consensus. This catches a single face inserted the
        wrong way round in an otherwise consistent patch. Same default (``60``) as MeshLab's
        ``nfratio`` but not the same test unless ``normal_criterion="meshlab"`` (see Notes).
        ``None`` disables it.
    max_fold_angle
        Flag a face that meets *some* neighbour at more than this many **degrees** — a fold, where
        the two triangles lie almost on top of each other with opposing normals. Of the two faces at
        such an edge only the one facing *against* its own wider neighbourhood is flagged, since
        only one of them is the mistake; a face whose neighbours give it no consensus (an isolated
        face, or a strip of exactly three) is therefore never flagged on this criterion alone.
        MeshLab's ``folded_faces_angle_threshold`` (default ``160``, off by default). Must be in
        ``(0, 180]``. ``None`` disables it.
    face_normals
        ``(n_faces,)`` unit face normals from
        [`face_normals_and_areas`][ordito.triangles.face_normals_and_areas]; formed from the
        corners where they are read when ``None``. Only the two angle criteria read them.
    mates
        ``(3 * n_faces,)`` halfedge mate codes of ``faces``, from
        [`halfedge_mates`][ordito.halfedge.halfedge_mates], to spare the sort that otherwise pairs
        the halfedges. Not checked against ``faces``.
        [`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates] is the cached one to pass.
    normal_criterion
        What ``max_normal_angle`` compares a face's normal with.

        - ``"consensus"`` (default) — the direction of the sum of its edge-neighbours' normals.
        - ``"meshlab"`` — each edge-neighbour's normal in turn, flagging the face when any one
          differs by more than the angle: MeshLab's ``nfratio``.

        ``"consensus"`` is the default because it flags far fewer correct faces: MeshLab's test
        flags both faces of every edge sharper than the angle, so it marks a reversed face's
        neighbours, and every face of a cube (see Notes).

    Returns
    -------
    wp.array[wp.bool]
        ``(n_faces,)`` mask on ``faces.device``; ``True`` marks a defective face. All-``False``
        when every criterion is disabled.

    Raises
    ------
    ValueError
        If ``max_normal_angle`` or ``max_fold_angle`` is outside ``(0, 180]``, or
        ``normal_criterion`` is not ``"consensus"`` or ``"meshlab"``.
    RuntimeError
        If ``vertices``, ``faces``, ``face_normals`` and ``mates`` are not all on one device.

    Notes
    -----
    The thinness and fold criteria match MeshLab's ``compute_selection_bad_faces`` (its ``aratio``
    and ``folded_faces_angle_threshold``). The default normal criterion does not match its
    ``nfratio``: MeshLab selects *both* faces of every edge whose normals differ by more than the
    angle (``normal_criterion="meshlab"``), so it flags a reversed face together with all its
    neighbours, and every face of a cube at ``60``. Comparing each face with its neighbours'
    consensus instead flags the reversed face alone on a smooth surface. The consensus needs
    neighbours that mostly agree: on a coarse mesh, where a face has three neighbours and they meet
    at sharp angles, a correct face next to a reversed one can fail it too (a cube with one
    triangle reversed flags that triangle and one neighbour).

    See Also
    --------
    [`repair.remove_folded_faces`][ordito.repair.remove_folded_faces]
        Deletes the folded ones.
    [`Trimesh.face_normals`][ordito.mesh.Trimesh.face_normals]
        Caches what ``face_normals`` wants.
    [`repair.remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]
        Deletes the fully degenerate ones, on an exact test rather than a threshold.
    [`ordito.triangles.face_quality`][ordito.triangles.face_quality]
        The thinness measure ``min_quality`` gates on.

    Examples
    --------
    The second triangle is a sliver, far below the default thinness gate:

    ```python
    import warp as wp

    import ordito as od

    vertices = wp.array(
        [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.001, 0.0]], dtype=wp.vec3
    )
    faces = wp.array([0, 1, 2, 1, 3, 2], dtype=wp.int32)
    print(od.validation.face_defective_mask(vertices, faces).numpy().tolist())  # [False, True]
    ```

    One face of a sphere reversed against its neighbours is caught by the normal criterion:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    rows = faces.numpy().reshape(-1, 3)
    rows[5] = rows[5][::-1]
    faces = wp.array(rows.ravel(), dtype=wp.int32)
    mask = od.validation.face_defective_mask(vertices, faces, max_normal_angle=60.0)
    print(np.flatnonzero(mask.numpy()).tolist())  # [5]
    ```
    """
    require_same_device(vertices=vertices, faces=faces, face_normals=face_normals, mates=mates)
    for name, angle in (("max_normal_angle", max_normal_angle), ("max_fold_angle", max_fold_angle)):
        if angle is not None and not 0.0 < angle <= 180.0:
            raise ValueError(f"{name} must be in (0, 180] degrees, got {angle}")
    if normal_criterion not in ("consensus", "meshlab"):
        raise ValueError(
            f"normal_criterion must be 'consensus' or 'meshlab', got {normal_criterion!r}"
        )

    device = faces.device
    n_faces = faces.size // 3
    # ``wp.empty``: the mask kernel writes every face on every path.
    out_bad = _launch.empty(n_faces, dtype=wp.bool, device=device)
    if n_faces == 0:
        return out_bad

    # Both angle criteria read the face normals and the halfedge mates; with both off the kernel
    # reads neither, see its comment. Normals not given are formed in the kernel, from the
    # corners, where each is read: no normal table and no launch to write one.
    if max_normal_angle is not None or max_fold_angle is not None:
        mates = mates if mates is not None else od.halfedge.halfedge_mates(faces, vertices.size)
    else:
        face_normals = None
        mates = None

    # -2 is unreachable for a cosine, -1 for the normalized quality and ``FOLD_ANGLE_OFF`` (past
    # pi) for a dihedral, so a disabled criterion simply never fires and the kernel needs no
    # per-criterion flag. The normal criterion is the consensus cosine or the pairwise angle.
    normal_cos = -2.0
    pair_angle = kernel_validation.FOLD_ANGLE_OFF
    if max_normal_angle is not None and normal_criterion == "meshlab":
        pair_angle = wp.float32(math.radians(max_normal_angle))
    elif max_normal_angle is not None:
        normal_cos = math.cos(math.radians(max_normal_angle))
    _launch.launch(
        kernel_validation.face_defective_mask,
        dim=n_faces,
        inputs=[
            vertices,
            faces,
            face_normals,
            mates,
            wp.float32(min_quality if min_quality is not None else -1.0),
            wp.float32(normal_cos),
            pair_angle,
            wp.float32(math.radians(max_fold_angle))
            if max_fold_angle is not None
            else kernel_validation.FOLD_ANGLE_OFF,
            out_bad,
        ],
        device=device,
    )
    return out_bad