Skip to content

ordito.bounds

Bounding boxes: building them, and selecting or cropping with them.

Two halves. The constructors -- aabb, aabb_union, enclosing_diagonal and oriented_bounding_box -- reduce a cloud to a box. The queries -- points_in_aabb, points_in_obb and the crop_points / crop_mesh pair -- run the other way, testing points against a box someone already has. The two halves compose directly: every constructor's return is a query's argument, in that layout, which is why an oriented box is a (rotation, min_bound, max_bound) triple here rather than an object.

enclosing_diagonal is the one entry point here that exists for another module's sake rather than its own: it is the default search radius every mesh query in the package derives from its input's extent.

Functions:

Name Description
aabb

Axis-aligned bounding box of points (component-wise min / max).

aabb_union

Smallest axis-aligned bounding box enclosing two given boxes.

enclosing_diagonal

Diagonal of the axis-aligned box enclosing one or two point sets.

box_diagonal

Diagonal of an axis-aligned box given by its corners, as a host float.

points_in_aabb

Return the indices of the points inside an axis-aligned box, boundary included.

points_in_aabb_mask

Flag the points inside an axis-aligned box, boundary included.

points_in_obb

Return the indices of the points inside an oriented box, boundary included.

points_in_obb_mask

Flag the points inside an oriented box, boundary included.

crop_points

Keep the points inside a box, returning the survivors and where they came from.

crop_mesh

Keep the faces whose three vertices all lie inside a box, reindexed from zero.

oriented_bounding_box

Smallest bounding box over sampled orientations, sharpened by local refinement, and its frame.

ITEMS_PER_CANDIDATE_SLICE module-attribute

ITEMS_PER_CANDIDATE_SLICE = 256

EXTENT_MIN_SLICE module-attribute

EXTENT_MIN_SLICE = 64

CONVEX_PREFILTER_MIN_POINTS module-attribute

CONVEX_PREFILTER_MIN_POINTS = 100000

aabb

aabb(points: array[vec3]) -> tuple[wp.vec3, wp.vec3]

Axis-aligned bounding box of points (component-wise min / max).

The reduction is minmax's wp.vec3 path: one chunked kernel writes both corners into a single six-element buffer, read back once. This wrapper contributes only the empty-input (+inf, -inf) convention, where minmax raises.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions.

required

Returns:

Type Description
tuple[vec3, vec3]

(min_bound, max_bound) with min_bound[i] ≤ p[i] ≤ max_bound[i] for every point p and axis i. If n == 0, min_bound is (+inf, …) and max_bound is (-inf, …).

See Also

aabb_union enclosing_diagonal points_in_aabb The other direction: which points a box already in hand contains. ordito.reduce.minmax

Examples:

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
min_bound, max_bound = od.bounds.aabb(vertices)
print(min_bound, max_bound)  # [-1.0, -1.0, -1.0] [1.0, 1.0, 1.0]
Source code in ordito/bounds.py
 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
def aabb(points: wp.array[wp.vec3]) -> tuple[wp.vec3, wp.vec3]:
    """
    Axis-aligned bounding box of ``points`` (component-wise min / max).

    The reduction is [`minmax`][ordito.reduce.minmax]'s ``wp.vec3`` path: one chunked kernel
    writes both corners into a single six-element buffer, read back once. This wrapper contributes
    only the empty-input ``(+inf, -inf)`` convention, where ``minmax`` raises.

    Parameters
    ----------
    points
        ``(n,)`` positions.

    Returns
    -------
    tuple[wp.vec3, wp.vec3]
        ``(min_bound, max_bound)`` with ``min_bound[i] ≤ p[i] ≤ max_bound[i]`` for every
        point ``p`` and axis ``i``. If ``n == 0``, ``min_bound`` is ``(+inf, …)`` and
        ``max_bound`` is ``(-inf, …)``.

    See Also
    --------
    [`aabb_union`][ordito.bounds.aabb_union]
    [`enclosing_diagonal`][ordito.bounds.enclosing_diagonal]
    [`points_in_aabb`][ordito.bounds.points_in_aabb]
        The other direction: which points a box already in hand contains.
    [`ordito.reduce.minmax`][ordito.reduce.minmax]

    Examples
    --------
    ```python
    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    min_bound, max_bound = od.bounds.aabb(vertices)
    print(min_bound, max_bound)  # [-1.0, -1.0, -1.0] [1.0, 1.0, 1.0]
    ```
    """
    if points.size == 0:
        return (wp.vec3(math.inf, math.inf, math.inf), wp.vec3(-math.inf, -math.inf, -math.inf))
    return od.reduce.minmax(points)

aabb_union

aabb_union(
    a_min: vec3, a_max: vec3, b_min: vec3, b_max: vec3
) -> tuple[wp.vec3, wp.vec3]

Smallest axis-aligned bounding box enclosing two given boxes.

Parameters:

Name Type Description Default
a_min vec3

Min/max corners of the first box.

required
a_max vec3

Min/max corners of the first box.

required
b_min vec3

Min/max corners of the second box.

required
b_max vec3

Min/max corners of the second box.

required

Returns:

Type Description
tuple[vec3, vec3]

(min_bound, max_bound) of the box enclosing both inputs.

See Also

aabb enclosing_diagonal

Examples:

import warp as wp

import ordito as od

a_min, a_max = wp.vec3(0.0, 0.0, 0.0), wp.vec3(1.0, 1.0, 1.0)
b_min, b_max = wp.vec3(-1.0, 0.5, 0.5), wp.vec3(0.5, 2.0, 0.5)
min_bound, max_bound = od.bounds.aabb_union(a_min, a_max, b_min, b_max)
print(min_bound, max_bound)  # [-1.0, 0.0, 0.0] [1.0, 2.0, 1.0]
Source code in ordito/bounds.py
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
def aabb_union(
    a_min: wp.vec3, a_max: wp.vec3, b_min: wp.vec3, b_max: wp.vec3
) -> tuple[wp.vec3, wp.vec3]:
    """
    Smallest axis-aligned bounding box enclosing two given boxes.

    Parameters
    ----------
    a_min, a_max
        Min/max corners of the first box.
    b_min, b_max
        Min/max corners of the second box.

    Returns
    -------
    tuple[wp.vec3, wp.vec3]
        ``(min_bound, max_bound)`` of the box enclosing both inputs.

    See Also
    --------
    [`aabb`][ordito.bounds.aabb]
    [`enclosing_diagonal`][ordito.bounds.enclosing_diagonal]

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

    import ordito as od

    a_min, a_max = wp.vec3(0.0, 0.0, 0.0), wp.vec3(1.0, 1.0, 1.0)
    b_min, b_max = wp.vec3(-1.0, 0.5, 0.5), wp.vec3(0.5, 2.0, 0.5)
    min_bound, max_bound = od.bounds.aabb_union(a_min, a_max, b_min, b_max)
    print(min_bound, max_bound)  # [-1.0, 0.0, 0.0] [1.0, 2.0, 1.0]
    ```
    """
    # Componentwise ``min`` / ``max`` in plain Python rather than ``wp.min`` / ``wp.max``: this
    # function does no device work at all, so Warp's Python-scope builtin dispatch was its entire
    # cost, and the plain spelling is several times cheaper and byte-identical. A ``wp.vec3``
    # indexes to a native ``float``, which is what makes the plain builtins applicable.
    a_min_x, a_min_y, a_min_z = a_min
    b_min_x, b_min_y, b_min_z = b_min
    a_max_x, a_max_y, a_max_z = a_max
    b_max_x, b_max_y, b_max_z = b_max
    return (
        wp.vec3(min(a_min_x, b_min_x), min(a_min_y, b_min_y), min(a_min_z, b_min_z)),
        wp.vec3(max(a_max_x, b_max_x), max(a_max_y, b_max_y), max(a_max_z, b_max_z)),
    )

enclosing_diagonal

enclosing_diagonal(
    points: array[vec3], other: array[vec3] | None = None
) -> float

Diagonal of the axis-aligned box enclosing one or two point sets.

The default search radius for every mesh query in the package: no closest point, ray hit or tangent sphere can be further away than the diagonal of a box containing both the surface and the query points, so it is the smallest bound that is guaranteed not to cut an answer off. Pass other whenever the queries may lie outside the mesh's own box, which is the usual case -- with points alone a query far outside would get a radius too short to reach the surface.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions, typically a mesh's vertices.

required
other array[vec3] | None

(m,) second point set, typically the query points. None or empty measures points alone.

None

Returns:

Type Description
float

|max_bound - min_bound| of the union box. inf when points is empty, since an empty box has infinite negative extent -- callers guard on the point count first.

Raises:

Type Description
RuntimeError

If points and other are not all on one device.

See Also

aabb aabb_union

Examples:

A unit cube's diagonal is sqrt(3); a query point outside the cube stretches the box:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
print(f"{od.bounds.enclosing_diagonal(vertices):.4f}")  # 1.7321
queries = wp.array([[3.0, 0.0, 0.0]], dtype=wp.vec3)
print(f"{od.bounds.enclosing_diagonal(vertices, queries):.4f}")  # 3.7749
Source code in ordito/bounds.py
153
154
155
156
157
158
159
160
161
162
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
def enclosing_diagonal(points: wp.array[wp.vec3], other: wp.array[wp.vec3] | None = None) -> float:
    """
    Diagonal of the axis-aligned box enclosing one or two point sets.

    The default search radius for every mesh query in the package: no closest point, ray hit or
    tangent sphere can be further away than the diagonal of a box containing both the surface and
    the query points, so it is the smallest bound that is guaranteed not to cut an answer off. Pass
    ``other`` whenever the queries may lie outside the mesh's own box, which is the usual case --
    with ``points`` alone a query far outside would get a radius too short to reach the surface.

    Parameters
    ----------
    points
        ``(n,)`` positions, typically a mesh's vertices.
    other
        ``(m,)`` second point set, typically the query points. ``None`` or empty measures
        ``points`` alone.

    Returns
    -------
    float
        ``|max_bound - min_bound|`` of the union box. ``inf`` when ``points`` is empty, since an
        empty box has infinite negative extent -- callers guard on the point count first.

    Raises
    ------
    RuntimeError
        If ``points`` and ``other`` are not all on one device.

    See Also
    --------
    [`aabb`][ordito.bounds.aabb]
    [`aabb_union`][ordito.bounds.aabb_union]

    Examples
    --------
    A unit cube's diagonal is ``sqrt(3)``; a query point outside the cube stretches the box:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    print(f"{od.bounds.enclosing_diagonal(vertices):.4f}")  # 1.7321
    queries = wp.array([[3.0, 0.0, 0.0]], dtype=wp.vec3)
    print(f"{od.bounds.enclosing_diagonal(vertices, queries):.4f}")  # 3.7749
    ```
    """
    require_same_device(points=points, other=other)
    # Both clouds reduce into **one** corner buffer, so the union costs one readback rather than
    # two boxes and an ``aabb_union``, and in one launch: ``minmax_vec3_pair_chunked`` folds both
    # clouds' chunks into the same slots with ``wp.atomic_min``. Reducing a concatenation instead
    # is slower -- the union buffer is an allocation and a copy of both clouds.
    device = cast("wp.Device", points.device)
    corners = _launch.full(6, math.inf, dtype=wp.float32, device=device)
    n_other = 0 if other is None else other.size
    if points.size + n_other > 0:
        _launch.launch(
            kernel_reduce.minmax_vec3_pair_chunked,
            dim=kernel_reduce.chunks_1d(points.size) + kernel_reduce.chunks_1d(n_other),
            inputs=[points, points if other is None else other, wp.int32(0)],
            outputs=[corners],
            device=device,
        )
    # Slots 3..5 hold the *negated* upper corner; see the kernel. An all-empty input leaves the
    # seeded ``inf`` in place, so ``upper - lower`` is ``-inf`` componentwise and the length is
    # ``inf`` -- the documented empty-input answer, reached without a branch.
    #
    # Taken in NumPy ``float32``, as ``box_diagonal`` takes it, rather than through two
    # ``wp.vec3`` constructions and ``wp.length``: every Warp operator and builtin at *Python*
    # scope routes through Warp's builtin dispatch (``inspect.signature().bind()`` per operand),
    # an order of magnitude dearer than this. On CUDA one six-value ``read_values`` copy, which
    # builds no host array; on the CPU device that would only add a list round trip.
    if device.is_cpu:
        corners_np = read_array(corners)
    else:
        corners_np = np.array(read_values(corners, 0, 6), dtype=np.float32)
    return float(np.linalg.norm(-corners_np[3:] - corners_np[:3]))

box_diagonal

box_diagonal(min_bound: vec3, max_bound: vec3) -> float

Diagonal of an axis-aligned box given by its corners, as a host float.

The same number enclosing_diagonal returns for the points whose aabb the corners are, bit for bit: both take the norm of the float32 corner difference. So a caller that already holds a box -- a Trimesh.bounds -- gets the diagonal without the reduction and readback that measure it again.

Parameters:

Name Type Description Default
min_bound vec3

Lower corner.

required
max_bound vec3

Upper corner.

required

Returns:

Type Description
float

|max_bound - min_bound|.

See Also

enclosing_diagonal

Examples:

import ordito as od

vertices, _ = od.creation.box()
lower, upper = od.bounds.aabb(vertices)
print(od.bounds.box_diagonal(lower, upper) == od.bounds.enclosing_diagonal(vertices))  # True
Source code in ordito/bounds.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def box_diagonal(min_bound: wp.vec3, max_bound: wp.vec3) -> float:
    """
    Diagonal of an axis-aligned box given by its corners, as a host float.

    The same number [`enclosing_diagonal`][ordito.bounds.enclosing_diagonal] returns for the points
    whose [`aabb`][ordito.bounds.aabb] the corners are, bit for bit: both take the norm of the
    ``float32`` corner difference. So a caller that already holds a box -- a
    [`Trimesh.bounds`][ordito.mesh.Trimesh.bounds] -- gets the diagonal without the reduction and
    readback that measure it again.

    Parameters
    ----------
    min_bound
        Lower corner.
    max_bound
        Upper corner.

    Returns
    -------
    float
        ``|max_bound - min_bound|``.

    See Also
    --------
    [`enclosing_diagonal`][ordito.bounds.enclosing_diagonal]

    Examples
    --------
    ```python
    import ordito as od

    vertices, _ = od.creation.box()
    lower, upper = od.bounds.aabb(vertices)
    print(od.bounds.box_diagonal(lower, upper) == od.bounds.enclosing_diagonal(vertices))  # True
    ```
    """
    lower = np.array(min_bound, dtype=np.float32)
    upper = np.array(max_bound, dtype=np.float32)
    return float(np.linalg.norm(upper - lower))

points_in_aabb

points_in_aabb(
    points: array[vec3], min_bound: vec3, max_bound: vec3
) -> wp.array[wp.int32]

Return the indices of the points inside an axis-aligned box, boundary included.

The bounded selection primitive, and the one that needs no spatial index at all: every point is tested independently against six planes, so the cost is one pass over the cloud whatever the box holds. A tree would only help if the box were the thing being searched for -- see ordito.neighbors.query_bvh_box for that direction.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions in space.

required
min_bound vec3

Opposite corners of the box, as aabb returns them. An empty box (any min_bound[i] > max_bound[i]) selects nothing.

required
max_bound vec3

Opposite corners of the box, as aabb returns them. An empty box (any min_bound[i] > max_bound[i]) selects nothing.

required

Returns:

Type Description
array[int32]

(m,) ascending indices into points on points.device, m the number inside. Empty when nothing is inside.

Notes

Containment is inclusive: a point exactly on a face, edge or corner of the box is selected. A point with a nan coordinate is not selected, and neither is one at an infinity. Both conventions differ from half_space_mask, whose test is strict.

See Also

points_in_aabb_mask The same selection as a boolean mask, for a caller that wants to combine it. points_in_obb The oriented counterpart. crop_points This plus the gather, when the points themselves are wanted. aabb

Examples:

The point on the box's corner is selected, the one past it is not:

import warp as wp

import ordito as od

points = wp.array(
    [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.5, -0.5, 0.0]], dtype=wp.vec3
)
inside = od.bounds.points_in_aabb(points, wp.vec3(-1.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0))
print(inside.numpy().tolist())  # [0, 2, 3]
Source code in ordito/bounds.py
275
276
277
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
def points_in_aabb(
    points: wp.array[wp.vec3], min_bound: wp.vec3, max_bound: wp.vec3
) -> wp.array[wp.int32]:
    """
    Return the indices of the points inside an axis-aligned box, boundary included.

    The bounded selection primitive, and the one that needs no spatial index at all: every point is
    tested independently against six planes, so the cost is one pass over the cloud whatever the
    box holds. A tree would only help if the *box* were the thing being searched for -- see
    [`ordito.neighbors.query_bvh_box`][ordito.neighbors.query_bvh_box] for that direction.

    Parameters
    ----------
    points
        ``(n,)`` positions in space.
    min_bound, max_bound
        Opposite corners of the box, as [`aabb`][ordito.bounds.aabb] returns them. An empty box
        (any ``min_bound[i] > max_bound[i]``) selects nothing.

    Returns
    -------
    wp.array[wp.int32]
        ``(m,)`` ascending indices into ``points`` on ``points.device``, ``m`` the number inside.
        Empty when nothing is inside.

    Notes
    -----
    Containment is **inclusive**: a point exactly on a face, edge or corner of the box is selected.
    A point with a ``nan`` coordinate is *not* selected, and neither is one at an infinity. Both
    conventions differ from [`half_space_mask`][ordito.points.half_space_mask], whose test is
    strict.

    See Also
    --------
    [`points_in_aabb_mask`][ordito.bounds.points_in_aabb_mask]
        The same selection as a boolean mask, for a caller that wants to combine it.
    [`points_in_obb`][ordito.bounds.points_in_obb]
        The oriented counterpart.
    [`crop_points`][ordito.bounds.crop_points]
        This plus the gather, when the points themselves are wanted.
    [`aabb`][ordito.bounds.aabb]

    Examples
    --------
    The point on the box's corner is selected, the one past it is not:

    ```python
    import warp as wp

    import ordito as od

    points = wp.array(
        [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.5, -0.5, 0.0]], dtype=wp.vec3
    )
    inside = od.bounds.points_in_aabb(points, wp.vec3(-1.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0))
    print(inside.numpy().tolist())  # [0, 2, 3]
    ```
    """
    return _box_indices(points, min_bound, max_bound, None)

points_in_aabb_mask

points_in_aabb_mask(
    points: array[vec3], min_bound: vec3, max_bound: vec3
) -> wp.array[wp.bool]

Flag the points inside an axis-aligned box, boundary included.

The mask form of points_in_aabb, for a caller that wants to intersect the selection with another predicate before compacting it -- combining masks costs one wp.map where combining index lists costs a set operation.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions in space.

required
min_bound vec3

Opposite corners of the box, as aabb returns them.

required
max_bound vec3

Opposite corners of the box, as aabb returns them.

required

Returns:

Type Description
array[bool]

(n,) mask on points.device. True marks a point to keep, the same sense as ordito.points.half_space_mask.

See Also

points_in_aabb The index form, and where the boundary and nan conventions are documented. points_in_obb_mask ordito.array.flatnonzero

Examples:

import warp as wp

import ordito as od

points = wp.array(
    [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.5, -0.5, 0.0]], dtype=wp.vec3
)
mask = od.bounds.points_in_aabb_mask(points, wp.vec3(-1.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0))
print(mask.numpy().tolist())  # [True, False, True, True]
Source code in ordito/bounds.py
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
def points_in_aabb_mask(
    points: wp.array[wp.vec3], min_bound: wp.vec3, max_bound: wp.vec3
) -> wp.array[wp.bool]:
    """
    Flag the points inside an axis-aligned box, boundary included.

    The mask form of [`points_in_aabb`][ordito.bounds.points_in_aabb], for a caller that wants to
    intersect the selection with another predicate before compacting it -- combining masks costs
    one ``wp.map`` where combining index lists costs a set operation.

    Parameters
    ----------
    points
        ``(n,)`` positions in space.
    min_bound, max_bound
        Opposite corners of the box, as [`aabb`][ordito.bounds.aabb] returns them.

    Returns
    -------
    wp.array[wp.bool]
        ``(n,)`` mask on ``points.device``. ``True`` marks a point to **keep**, the same sense
        as [`ordito.points.half_space_mask`][ordito.points.half_space_mask].

    See Also
    --------
    [`points_in_aabb`][ordito.bounds.points_in_aabb]
        The index form, and where the boundary and ``nan`` conventions are documented.
    [`points_in_obb_mask`][ordito.bounds.points_in_obb_mask]
    [`ordito.array.flatnonzero`][ordito.array.flatnonzero]

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

    import ordito as od

    points = wp.array(
        [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.5, -0.5, 0.0]], dtype=wp.vec3
    )
    mask = od.bounds.points_in_aabb_mask(points, wp.vec3(-1.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0))
    print(mask.numpy().tolist())  # [True, False, True, True]
    ```
    """
    out_mask = _launch.empty(points.size, dtype=wp.bool, device=points.device)
    if points.size == 0:
        return out_mask

    _launch.map(kernel_predicates.is_in_aabb, points, min_bound, max_bound, out=out_mask)
    return out_mask

points_in_obb

points_in_obb(
    points: array[vec3],
    rotation: mat33,
    min_bound: vec3,
    max_bound: vec3,
) -> wp.array[wp.int32]

Return the indices of the points inside an oriented box, boundary included.

Takes the box exactly as oriented_bounding_box returns it, so the two compose without a transpose or a corner rebuild.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions in world space.

required
rotation mat33

World-to-box frame as wp.mat33, i.e. its rows are the box axes in world coordinates. A point's box coordinates are rotation * p.

required
min_bound vec3

Extent of the box along its own axes, in box coordinates.

required
max_bound vec3

Extent of the box along its own axes, in box coordinates.

required

Returns:

Type Description
array[int32]

(m,) ascending indices into points on points.device, m the number inside. Empty when nothing is inside.

Notes

One rotated point per thread, then the identical six comparisons points_in_aabb makes -- the two share one predicate, so the inclusive boundary and the nan exclusion documented there hold here too, and the two functions cannot drift apart on either. Passing the identity as rotation reproduces the axis-aligned answer exactly.

Being a proper rotation, the frame's inverse is its transpose, so nothing here inverts a matrix; a general affine box would, and is not what this takes.

See Also

points_in_obb_mask points_in_aabb The axis-aligned counterpart, and the shared conventions. oriented_bounding_box Where the (rotation, min_bound, max_bound) triple comes from.

Examples:

A 1 x 2 x 4 box turned 30 degrees about z: the point at x = 0.9 lies inside the axis-aligned box but outside the oriented one:

import math

import warp as wp

import ordito as od

c, s = math.cos(math.pi / 6), math.sin(math.pi / 6)
spin = wp.mat44(c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
vertices, faces = od.creation.box(extents=(1.0, 2.0, 4.0), transform=spin)
rotation, lower, upper = od.bounds.oriented_bounding_box(vertices)
points = wp.array([[0.0, 0.0, 0.0], [0.9, 0.0, 0.0]], dtype=wp.vec3)
print(od.bounds.points_in_obb(points, rotation, lower, upper).numpy().tolist())  # [0]
min_bound, max_bound = od.bounds.aabb(vertices)
print(od.bounds.points_in_aabb(points, min_bound, max_bound).numpy().tolist())  # [0, 1]
Source code in ordito/bounds.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def points_in_obb(
    points: wp.array[wp.vec3], rotation: wp.mat33, min_bound: wp.vec3, max_bound: wp.vec3
) -> wp.array[wp.int32]:
    """
    Return the indices of the points inside an oriented box, boundary included.

    Takes the box exactly as [`oriented_bounding_box`][ordito.bounds.oriented_bounding_box]
    returns it, so the two compose without a transpose or a corner rebuild.

    Parameters
    ----------
    points
        ``(n,)`` positions in world space.
    rotation
        World-to-box frame as ``wp.mat33``, i.e. its **rows** are the box axes in world
        coordinates. A point's box coordinates are ``rotation * p``.
    min_bound, max_bound
        Extent of the box along its own axes, in box coordinates.

    Returns
    -------
    wp.array[wp.int32]
        ``(m,)`` ascending indices into ``points`` on ``points.device``, ``m`` the number inside.
        Empty when nothing is inside.

    Notes
    -----
    One rotated point per thread, then the identical six comparisons
    [`points_in_aabb`][ordito.bounds.points_in_aabb] makes -- the two share one predicate, so the
    inclusive boundary and the ``nan`` exclusion documented there hold here too, and the two
    functions cannot drift apart on either. Passing the identity as ``rotation`` reproduces the
    axis-aligned answer exactly.

    Being a proper rotation, the frame's inverse is its transpose, so nothing here inverts a
    matrix; a general affine box would, and is not what this takes.

    See Also
    --------
    [`points_in_obb_mask`][ordito.bounds.points_in_obb_mask]
    [`points_in_aabb`][ordito.bounds.points_in_aabb]
        The axis-aligned counterpart, and the shared conventions.
    [`oriented_bounding_box`][ordito.bounds.oriented_bounding_box]
        Where the ``(rotation, min_bound, max_bound)`` triple comes from.

    Examples
    --------
    A ``1 x 2 x 4`` box turned 30 degrees about ``z``: the point at ``x = 0.9`` lies inside the
    axis-aligned box but outside the oriented one:

    ```python
    import math

    import warp as wp

    import ordito as od

    c, s = math.cos(math.pi / 6), math.sin(math.pi / 6)
    spin = wp.mat44(c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
    vertices, faces = od.creation.box(extents=(1.0, 2.0, 4.0), transform=spin)
    rotation, lower, upper = od.bounds.oriented_bounding_box(vertices)
    points = wp.array([[0.0, 0.0, 0.0], [0.9, 0.0, 0.0]], dtype=wp.vec3)
    print(od.bounds.points_in_obb(points, rotation, lower, upper).numpy().tolist())  # [0]
    min_bound, max_bound = od.bounds.aabb(vertices)
    print(od.bounds.points_in_aabb(points, min_bound, max_bound).numpy().tolist())  # [0, 1]
    ```
    """
    return _box_indices(points, min_bound, max_bound, rotation)

points_in_obb_mask

points_in_obb_mask(
    points: array[vec3],
    rotation: mat33,
    min_bound: vec3,
    max_bound: vec3,
) -> wp.array[wp.bool]

Flag the points inside an oriented box, boundary included.

The mask form of points_in_obb; see points_in_aabb_mask for why the mask form exists.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions in world space.

required
rotation mat33

World-to-box frame as wp.mat33, rows being the box axes (points_in_obb documents the convention).

required
min_bound vec3

Extent of the box along its own axes, in box coordinates.

required
max_bound vec3

Extent of the box along its own axes, in box coordinates.

required

Returns:

Type Description
array[bool]

(n,) mask on points.device. True marks a point to keep.

See Also

points_in_obb The index form, and where the conventions are documented. points_in_aabb_mask

Examples:

import math

import warp as wp

import ordito as od

c, s = math.cos(math.pi / 6), math.sin(math.pi / 6)
spin = wp.mat44(c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
vertices, faces = od.creation.box(extents=(1.0, 2.0, 4.0), transform=spin)
rotation, lower, upper = od.bounds.oriented_bounding_box(vertices)
points = wp.array([[0.0, 0.0, 0.0], [0.9, 0.0, 0.0]], dtype=wp.vec3)
mask = od.bounds.points_in_obb_mask(points, rotation, lower, upper)
print(mask.numpy().tolist())  # [True, False]
Source code in ordito/bounds.py
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
510
def points_in_obb_mask(
    points: wp.array[wp.vec3], rotation: wp.mat33, min_bound: wp.vec3, max_bound: wp.vec3
) -> wp.array[wp.bool]:
    """
    Flag the points inside an oriented box, boundary included.

    The mask form of [`points_in_obb`][ordito.bounds.points_in_obb]; see
    [`points_in_aabb_mask`][ordito.bounds.points_in_aabb_mask] for why the mask form exists.

    Parameters
    ----------
    points
        ``(n,)`` positions in world space.
    rotation
        World-to-box frame as ``wp.mat33``, rows being the box axes
        ([`points_in_obb`][ordito.bounds.points_in_obb] documents the convention).
    min_bound, max_bound
        Extent of the box along its own axes, in box coordinates.

    Returns
    -------
    wp.array[wp.bool]
        ``(n,)`` mask on ``points.device``. ``True`` marks a point to **keep**.

    See Also
    --------
    [`points_in_obb`][ordito.bounds.points_in_obb]
        The index form, and where the conventions are documented.
    [`points_in_aabb_mask`][ordito.bounds.points_in_aabb_mask]

    Examples
    --------
    ```python
    import math

    import warp as wp

    import ordito as od

    c, s = math.cos(math.pi / 6), math.sin(math.pi / 6)
    spin = wp.mat44(c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
    vertices, faces = od.creation.box(extents=(1.0, 2.0, 4.0), transform=spin)
    rotation, lower, upper = od.bounds.oriented_bounding_box(vertices)
    points = wp.array([[0.0, 0.0, 0.0], [0.9, 0.0, 0.0]], dtype=wp.vec3)
    mask = od.bounds.points_in_obb_mask(points, rotation, lower, upper)
    print(mask.numpy().tolist())  # [True, False]
    ```
    """
    out_mask = _launch.empty(points.size, dtype=wp.bool, device=points.device)
    if points.size == 0:
        return out_mask

    _launch.map(kernel_predicates.is_in_obb, points, rotation, min_bound, max_bound, out=out_mask)
    return out_mask

crop_points

crop_points(
    points: array[vec3],
    min_bound: vec3,
    max_bound: vec3,
    *,
    rotation: mat33 | None = None,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]

Keep the points inside a box, returning the survivors and where they came from.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions in world space.

required
min_bound vec3

Opposite corners of the box: in world coordinates when rotation is None, in box coordinates otherwise.

required
max_bound vec3

Opposite corners of the box: in world coordinates when rotation is None, in box coordinates otherwise.

required
rotation mat33 | None

World-to-box frame as wp.mat33, rows being the box axes. None -- the default -- crops to the axis-aligned box, which is the same test with one transform fewer rather than a different rule; pass the frame oriented_bounding_box returns to crop to an oriented one.

None

Returns:

Name Type Description
kept array[vec3]

(m,) points inside the box, in ascending index order, on points.device.

indices array[int32]

(m,) their indices in points, so a caller can crop a parallel per-point attribute with ordito.array.gather instead of re-running the test. This is the second return rather than an option because the compaction has already computed it.

See Also

crop_mesh The mesh counterpart, which must also decide what to do with a straddling face. points_in_aabb The selection alone, when the points are not needed. ordito.array.gather

Examples:

Cropping a unit icosphere to its x >= 0 half keeps 89 of its 162 vertices:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
kept, indices = od.bounds.crop_points(
    vertices, wp.vec3(0.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0)
)
print(kept.shape, indices.shape)  # (89,) (89,)
print(f"{kept.numpy()[:, 0].min():.4f}")  # 0.0000
Source code in ordito/bounds.py
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
570
571
572
573
574
575
576
577
578
579
580
581
582
def crop_points(
    points: wp.array[wp.vec3],
    min_bound: wp.vec3,
    max_bound: wp.vec3,
    *,
    rotation: wp.mat33 | None = None,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]:
    """
    Keep the points inside a box, returning the survivors and where they came from.

    Parameters
    ----------
    points
        ``(n,)`` positions in world space.
    min_bound, max_bound
        Opposite corners of the box: in world coordinates when ``rotation`` is ``None``, in box
        coordinates otherwise.
    rotation
        World-to-box frame as ``wp.mat33``, rows being the box axes. ``None`` -- the default --
        crops to the **axis-aligned** box, which is the same test with one transform fewer rather
        than a different rule; pass the frame
        [`oriented_bounding_box`][ordito.bounds.oriented_bounding_box] returns to crop to an
        oriented one.

    Returns
    -------
    kept : wp.array[wp.vec3]
        ``(m,)`` points inside the box, in ascending index order, on ``points.device``.
    indices : wp.array[wp.int32]
        ``(m,)`` their indices in ``points``, so a caller can crop a parallel per-point attribute
        with [`ordito.array.gather`][ordito.array.gather] instead of re-running the test. This is
        the second return rather than an option because the compaction has already computed it.

    See Also
    --------
    [`crop_mesh`][ordito.bounds.crop_mesh]
        The mesh counterpart, which must also decide what to do with a straddling face.
    [`points_in_aabb`][ordito.bounds.points_in_aabb]
        The selection alone, when the points are not needed.
    [`ordito.array.gather`][ordito.array.gather]

    Examples
    --------
    Cropping a unit icosphere to its ``x >= 0`` half keeps 89 of its 162 vertices:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    kept, indices = od.bounds.crop_points(
        vertices, wp.vec3(0.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0)
    )
    print(kept.shape, indices.shape)  # (89,) (89,)
    print(f"{kept.numpy()[:, 0].min():.4f}")  # 0.0000
    ```
    """
    device = points.device
    inclusive, n_kept = _scanned_box_flags(points, min_bound, max_bound, rotation)
    kept = _launch.empty(n_kept, dtype=wp.vec3, device=device)
    indices = _launch.empty(n_kept, dtype=wp.int32, device=device)
    if n_kept > 0:
        _launch.launch(
            kernel_bounds.compact_scanned_points,
            dim=points.size,
            inputs=[inclusive, points, kept, indices],
            device=device,
        )
    return kept, indices

crop_mesh

crop_mesh(
    vertices: array[vec3],
    faces: array[int32],
    min_bound: vec3,
    max_bound: vec3,
    *,
    rotation: mat33 | None = None,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
crop_mesh(
    vertices: array[vec3],
    faces: array[int32],
    min_bound: vec3,
    max_bound: vec3,
    *,
    rotation: mat33 | None = None,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
crop_mesh(
    vertices: array[vec3],
    faces: array[int32],
    min_bound: vec3,
    max_bound: vec3,
    *,
    rotation: mat33 | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Keep the faces whose three vertices all lie inside a box, reindexed from zero.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions on the target device.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
min_bound vec3

Opposite corners of the box: in world coordinates when rotation is None, in box coordinates otherwise.

required
max_bound vec3

Opposite corners of the box: in world coordinates when rotation is None, in box coordinates otherwise.

required
rotation mat33 | None

World-to-box frame as wp.mat33, rows being the box axes; None crops to the axis-aligned box. Same argument as crop_points's.

None
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
tuple[array[vec3], array[int32]]

(n_sub_vertices,) and (3 * n_sub_faces,) compact (sub_vertices, sub_faces) on vertices.device, carrying only the vertices the kept faces reference.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of an input vertex, and each output face of the input face it is.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

Notes

A face straddling the box boundary is dropped, not clipped: the result is a subset of the input's triangles, so the crop never introduces a vertex the input did not have and the cut edge is ragged at the triangle scale. That is what makes the operation a selection rather than a boolean -- for a flush cut, intersect the mesh with the box as a solid instead.

To keep the straddling faces instead, take the mask and pass it on directly, which is the face_mode="any" rule; the second example below shows it.

See Also

crop_points ordito.selection.submesh_from_vertex_mask The same selection over a box mask (face_mode="all"), where face_mode is exposed.

Examples:

Cropping a unit icosphere to its x >= 0 half keeps only the faces wholly inside:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
lower, upper = wp.vec3(0.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0)
sub_vertices, sub_faces = od.bounds.crop_mesh(vertices, faces, lower, upper)
print(sub_vertices.shape, sub_faces.shape[0] // 3)  # (89,) 152

Keeping the faces that straddle the box as well, with the vertex mask:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
lower, upper = wp.vec3(0.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0)
mask = od.bounds.points_in_aabb_mask(vertices, lower, upper)
sub_vertices, sub_faces = od.selection.submesh_from_vertex_mask(
    vertices, faces, mask, face_mode="any"
)
print(sub_vertices.shape, sub_faces.shape[0] // 3)  # (111,) 198
Source code in ordito/bounds.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
def crop_mesh(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    min_bound: wp.vec3,
    max_bound: wp.vec3,
    *,
    rotation: wp.mat33 | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Keep the faces whose three vertices all lie inside a box, reindexed from zero.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions on the target device.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    min_bound, max_bound
        Opposite corners of the box: in world coordinates when ``rotation`` is ``None``, in box
        coordinates otherwise.
    rotation
        World-to-box frame as ``wp.mat33``, rows being the box axes; ``None`` crops to the
        axis-aligned box. Same argument as
        [`crop_points`][ordito.bounds.crop_points]'s.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
        ``(n_sub_vertices,)`` and ``(3 * n_sub_faces,)`` compact ``(sub_vertices, sub_faces)`` on
        ``vertices.device``, carrying only the vertices the kept faces reference.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of an input
        vertex, and each output face of the input face it is.

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

    Notes
    -----
    A face straddling the box boundary is **dropped**, not clipped: the result is a subset of the
    input's triangles, so the crop never introduces a vertex the input did not have and the cut
    edge is ragged at the triangle scale. That is what makes the operation a selection rather than
    a boolean -- for a flush cut, intersect the mesh with the box as a solid instead.

    To keep the straddling faces instead, take the mask and pass it on directly, which is the
    ``face_mode="any"`` rule; the second example below shows it.

    See Also
    --------
    [`crop_points`][ordito.bounds.crop_points]
    [`ordito.selection.submesh_from_vertex_mask`][ordito.selection.submesh_from_vertex_mask]
        The same selection over a box mask (``face_mode="all"``), where ``face_mode`` is
        exposed.

    Examples
    --------
    Cropping a unit icosphere to its ``x >= 0`` half keeps only the faces wholly inside:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    lower, upper = wp.vec3(0.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0)
    sub_vertices, sub_faces = od.bounds.crop_mesh(vertices, faces, lower, upper)
    print(sub_vertices.shape, sub_faces.shape[0] // 3)  # (89,) 152
    ```

    Keeping the faces that straddle the box as well, with the vertex mask:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    lower, upper = wp.vec3(0.0, -1.0, -1.0), wp.vec3(1.0, 1.0, 1.0)
    mask = od.bounds.points_in_aabb_mask(vertices, lower, upper)
    sub_vertices, sub_faces = od.selection.submesh_from_vertex_mask(
        vertices, faces, mask, face_mode="any"
    )
    print(sub_vertices.shape, sub_faces.shape[0] // 3)  # (111,) 198
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    device = vertices.device
    n_faces = faces.size // 3
    if n_faces == 0:
        empty_vertices = _launch.empty(0, dtype=wp.vec3, device=device)
        empty_index = _launch.empty(0, dtype=wp.int32, device=device)
        if return_provenance:
            provenance = od.interpolation.Provenance(
                empty_index, empty_index, None, vertices.size, 0
            )
            return empty_vertices, empty_index, provenance
        return empty_vertices, empty_index
    # ``submesh_from_vertex_mask(..., face_mode="all")`` over the box mask, with each corner's box
    # test taken in the marking pass itself, so the mask is neither launched nor stored.
    face_mask = _launch.empty(n_faces, dtype=wp.bool, device=device)
    ranks = _launch.zeros(n_faces + vertices.size, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_bounds.mark_submesh_in_box,
        dim=n_faces,
        inputs=[
            vertices,
            faces,
            _UNUSED_ROTATION if rotation is None else rotation,
            min_bound,
            max_bound,
            0 if rotation is None else 1,
            face_mask,
            ranks,
        ],
        device=device,
    )
    sub_vertices, sub_faces, vertex_index, _ = _compact_marked_submesh(
        vertices, faces, face_mask, ranks, keep_masked=True, with_index=return_provenance
    )
    if not return_provenance:
        return sub_vertices, sub_faces
    provenance = od.interpolation.Provenance(
        vertex_index, od.array.flatnonzero(face_mask), None, vertices.size, n_faces
    )
    return sub_vertices, sub_faces, provenance

oriented_bounding_box

oriented_bounding_box(
    points: array[vec3],
    rotations: int = 4096,
    objective: Literal[
        "volume", "surface_area", "diagonal"
    ] = "volume",
    refine_iterations: int = 8,
) -> tuple[wp.mat33, wp.vec3, wp.vec3]

Smallest bounding box over sampled orientations, sharpened by local refinement, and its frame.

The box is searched, not solved. The global phase scores rotations candidate orientations from the Super-Fibonacci spiral [Alexa 2022], a low-discrepancy sampling of SO(3), with the identity appended as the last candidate, scored in parallel. Alone (refine_iterations=0) it is igl::oriented_bounding_box with n = rotations: the same candidates and the same three objectives, so the same box. But the sampled optimum sits up to a covering radius from the true one, which costs little on a smooth cloud and a great deal on a box-like one (a turned 1 x 2 x 4 box comes back 23 % too large at 4096 rotations).

The default therefore adds a refinement phase, which takes the best-scoring candidates from up to four mutually distant basins and runs that many trust-region rounds around each: every round scores a low-discrepancy ball of perturbed frames whose angular radius starts at the global grid's covering radius and shrinks by a factor of 0.4 per round, keeping each chain's best. Eight rounds reach the minimum-volume box of trimesh's and Open3D's hull-face searches to a few parts in 1e5 of volume (the minimum is flat, so the frames can differ by a fraction of a degree). Refinement is monotone (each chain re-scores its own base), so the answer is never worse than the global phase's and never worse than aabb; with refine_iterations=0 and rotations=1 it reproduces the axis-aligned box exactly.

Cost is rotations * len(points) point transforms for the global phase plus refine_iterations * 512 * len(points) for refinement — but past CONVEX_PREFILTER_MIN_POINTS a convex_superset_mask prefilter first drops every point that provably cannot touch the box, so both phases run on the few hull-candidate survivors and the cost stops growing with the cloud (the box is identical: the mask keeps every hull vertex and the extents are order-independent reductions over them).

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions.

required
rotations int

Number of global candidates to score, >= 1. With refinement, raising this past a few thousand is pointless: the global phase only needs to land inside the optimum's basin, and refinement does the rest.

4096
objective Literal['volume', 'surface_area', 'diagonal']

Which box quantity to minimize: "volume", "surface_area", or "diagonal" (the squared diagonal length, which has the same minimizer as the length).

'volume'
refine_iterations int

Trust-region rounds after the global phase, >= 0. 8 (default) reaches the minimum-volume box to a few parts in 1e5; 0 returns the pure sampled answer, igl's.

8

Returns:

Name Type Description
rotation mat33

World-to-box frame, i.e. its rows are the box axes in world coordinates. A world point p has box coordinates rotation * p, and a box corner maps back with wp.transpose(rotation) * corner. rotation is a proper rotation (orthonormal, determinant +1).

(min_bound, max_bound)

Extent of points along the box axes, in box coordinates -- so the box is {transpose(rotation) * q : min_bound <= q <= max_bound} and its side lengths are max_bound - min_bound. For n == 0 these are (+inf, …) and (-inf, …) and rotation is the identity, matching aabb.

Raises:

Type Description
ValueError

If rotations < 1, refine_iterations < 0, or objective is not one of the three named above.

Notes

The whole search runs on the device: candidate frames, extents, the objective, the argmin that picks the chains, the perturbed frames each round composes, and the per-chain selection. One row of the winning chain comes back at the end, and that is the only host traffic.

The result is a converged local minimum, not a certified global one. Certifying the true minimum-volume box requires the exact-arithmetic search over the convex hull's face and edge events (O'Rourke's rotating-calipers family), and ordito deliberately has no exact convex hull. What the sampling-plus-refinement search gives up is the certificate, not the volume: the global phase lands in the optimum's basin whenever the grid's covering radius resolves it, refinement converges within the basin, and the refined search ties or beats hull-based reference methods on volume across a range of test shapes. A pathological cloud whose optimum basin is narrower than the covering radius of rotations samples can still hide its box from this search; raise rotations if the input is a near-symmetric polyhedron far from any sampled orientation.

Neither hull-based reference is an oracle for the minimum either: on a stretched icosahedron the refined search returns less volume than both, because the hull-face-flush restriction misses optima whose box touches only edges and vertices.

See Also

aabb points_in_obb Takes this triple as returned, to select the points a box contains. trimesh.bounds.oriented_bounds igl.oriented_bounding_box

Examples:

The oriented box recovers a turned 1 x 2 x 4 box exactly, at half the volume of its axis-aligned box:

import math

import numpy as np
import warp as wp

import ordito as od

c, s = math.cos(math.pi / 6), math.sin(math.pi / 6)
spin = wp.mat44(c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
vertices, faces = od.creation.box(extents=(1.0, 2.0, 4.0), transform=spin)
rotation, lower, upper = od.bounds.oriented_bounding_box(vertices)
print(sorted(round(float(side), 2) for side in upper - lower))  # [1.0, 2.0, 4.0]
print(f"{np.prod(upper - lower):.2f}")  # 8.00
min_bound, max_bound = od.bounds.aabb(vertices)
print(f"{np.prod(max_bound - min_bound):.2f}")  # 16.66
Source code in ordito/bounds.py
 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
 831
 832
 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
 904
 905
 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
def oriented_bounding_box(
    points: wp.array[wp.vec3],
    rotations: int = 4096,
    objective: Literal["volume", "surface_area", "diagonal"] = "volume",
    refine_iterations: int = 8,
) -> tuple[wp.mat33, wp.vec3, wp.vec3]:
    """
    Smallest bounding box over sampled orientations, sharpened by local refinement, and its frame.

    The box is searched, not solved. The **global phase** scores ``rotations`` candidate
    orientations from the **Super-Fibonacci spiral** [Alexa 2022], a low-discrepancy sampling of
    ``SO(3)``, with the identity appended as the last candidate, scored in parallel. Alone
    (``refine_iterations=0``) it is ``igl::oriented_bounding_box`` with ``n = rotations``: the same
    candidates and the same three objectives, so the same box. But the sampled optimum sits up to a
    covering radius from the true one, which costs little on a smooth cloud and a great deal on a
    box-like one (a turned ``1 x 2 x 4`` box comes back 23 % too large at 4096 rotations).

    The default therefore adds a **refinement phase**, which takes the best-scoring candidates
    from up to four mutually distant basins and runs that many trust-region rounds around each:
    every round scores a low-discrepancy ball of perturbed frames whose angular radius starts at the
    global grid's covering radius and shrinks by a factor of 0.4 per round, keeping each chain's
    best. Eight rounds reach the minimum-volume box of trimesh's and Open3D's hull-face searches to
    a few parts in 1e5 of volume (the minimum is flat, so the frames can differ by a fraction of a
    degree). Refinement is monotone (each chain re-scores its own base), so the answer is never
    worse than the global phase's and never worse than [`aabb`][ordito.bounds.aabb]; with
    ``refine_iterations=0`` and ``rotations=1`` it reproduces the axis-aligned box exactly.

    Cost is ``rotations * len(points)`` point transforms for the global phase plus
    ``refine_iterations * 512 * len(points)`` for refinement — but past
    ``CONVEX_PREFILTER_MIN_POINTS`` a
    [`convex_superset_mask`][ordito.points.convex_superset_mask] prefilter first drops every
    point that provably cannot touch the box, so both phases run on the few hull-candidate
    survivors and the cost stops growing with the cloud (the box is identical: the mask keeps
    every hull vertex and the extents are order-independent reductions over them).


    Parameters
    ----------
    points
        ``(n,)`` positions.
    rotations
        Number of global candidates to score, ``>= 1``. With refinement, raising this past a few
        thousand is pointless: the global phase only needs to land *inside* the optimum's basin,
        and refinement does the rest.
    objective
        Which box quantity to minimize: ``"volume"``, ``"surface_area"``, or ``"diagonal"`` (the
        squared diagonal length, which has the same minimizer as the length).
    refine_iterations
        Trust-region rounds after the global phase, ``>= 0``. ``8`` (default) reaches the
        minimum-volume box to a few parts in 1e5; ``0`` returns the pure sampled answer, igl's.

    Returns
    -------
    rotation : wp.mat33
        World-to-box frame, i.e. its **rows** are the box axes in world coordinates. A world point
        ``p`` has box coordinates ``rotation * p``, and a box corner maps back with
        ``wp.transpose(rotation) * corner``. ``rotation`` is a proper rotation (orthonormal,
        determinant ``+1``).
    min_bound, max_bound
        Extent of ``points`` along the box axes, in box coordinates -- so the box is
        ``{transpose(rotation) * q : min_bound <= q <= max_bound}`` and its side lengths are
        ``max_bound - min_bound``. For ``n == 0`` these are ``(+inf, …)`` and ``(-inf, …)`` and
        ``rotation`` is the identity, matching
        [`aabb`][ordito.bounds.aabb].

    Raises
    ------
    ValueError
        If ``rotations < 1``, ``refine_iterations < 0``, or ``objective`` is not one of the three
        named above.

    Notes
    -----
    The whole search runs on the device: candidate frames, extents, the objective, the argmin that
    picks the chains, the perturbed frames each round composes, and the per-chain selection. One row
    of the winning chain comes back at the end, and that is the only host traffic.

    **The result is a converged local minimum, not a certified global one.** Certifying the true
    minimum-volume box requires the exact-arithmetic search over the convex hull's face and edge
    events (O'Rourke's rotating-calipers family), and ordito deliberately has no exact convex hull.
    What the sampling-plus-refinement search gives up is the *certificate*, not the volume: the
    global phase lands in the optimum's basin whenever the grid's covering radius resolves it,
    refinement converges within the basin, and the refined search ties or beats hull-based
    reference methods on volume across a range of test shapes. A pathological cloud whose optimum
    basin is narrower than the covering radius of ``rotations`` samples can still hide its box from
    this search; raise ``rotations`` if the input is a near-symmetric polyhedron far from any
    sampled orientation.

    Neither hull-based reference is an oracle for the minimum either: on a stretched icosahedron the
    refined search returns **less** volume than both, because the hull-face-flush restriction misses
    optima whose box touches only edges and vertices.

    See Also
    --------
    [`aabb`][ordito.bounds.aabb]
    [`points_in_obb`][ordito.bounds.points_in_obb]
        Takes this triple as returned, to select the points a box contains.
    [`trimesh.bounds.oriented_bounds`][]
    ``igl.oriented_bounding_box``

    Examples
    --------
    The oriented box recovers a turned ``1 x 2 x 4`` box exactly, at half the volume of its
    axis-aligned box:

    ```python
    import math

    import numpy as np
    import warp as wp

    import ordito as od

    c, s = math.cos(math.pi / 6), math.sin(math.pi / 6)
    spin = wp.mat44(c, -s, 0.0, 0.0, s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
    vertices, faces = od.creation.box(extents=(1.0, 2.0, 4.0), transform=spin)
    rotation, lower, upper = od.bounds.oriented_bounding_box(vertices)
    print(sorted(round(float(side), 2) for side in upper - lower))  # [1.0, 2.0, 4.0]
    print(f"{np.prod(upper - lower):.2f}")  # 8.00
    min_bound, max_bound = od.bounds.aabb(vertices)
    print(f"{np.prod(max_bound - min_bound):.2f}")  # 16.66
    ```
    """
    if rotations < 1:
        raise ValueError(f"rotations must be >= 1, got {rotations}")
    if refine_iterations < 0:
        raise ValueError(f"refine_iterations must be >= 0, got {refine_iterations}")
    if objective not in ("volume", "surface_area", "diagonal"):
        raise ValueError(
            f'objective must be "volume", "surface_area" or "diagonal", got {objective!r}'
        )

    n = points.size
    if n == 0:
        return (
            wp.mat33(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0),
            wp.vec3(math.inf, math.inf, math.inf),
            wp.vec3(-math.inf, -math.inf, -math.inf),
        )

    if n >= CONVEX_PREFILTER_MIN_POINTS:
        # Identical box, decided at the threshold above: only hull vertices can touch an
        # enclosing box, the mask keeps all of them, and min/max extents do not care about the
        # discarded interior points.
        points = _compact_masked_points(points, od.points.convex_superset_mask(points))
        n = points.size

    device = cast("wp.Device", points.device)
    # One chain when there is nothing to refine: the seeding walk's first pick is the global
    # argmin, so it stops after a single round and the row it writes is already the answer.
    n_chains = 1 if refine_iterations == 0 else _REFINE_CHAINS
    # The refinement's state is ping-ponged: round ``r`` reads half ``r % 2`` of each buffer and
    # its selection writes the other, so the frames and rows a launch writes are never ones it
    # still reads. The seeding walk writes half 0, including the first round's frames.
    count = _REFINE_CANDIDATES if refine_iterations > 0 else 0
    total = n_chains * count
    # Every table of the search is carved from one allocation. The axes kernel also seeds each
    # candidate's six extent slots, so ``corners`` is uninitialised until then and every slot is
    # written before the extents kernel reads it; it also draws the refinement ball's ``deltas``,
    # once for every round.
    state_size = 2 * n_chains * kernel_bounds.BOX_STATE_COLUMNS
    axes, refine_axes, corners, loss, refine_corners, state_flat, deltas = _launch.carve_typed(
        [
            (wp.mat33, rotations),
            (wp.mat33, 2 * total),
            (wp.float32, 6 * rotations),
            (wp.float32, rotations),
            (wp.float32, 12 * total),
            (wp.float32, state_size),
            (wp.vec4d, count),
        ],
        device,
    )
    _launch.launch(
        kernel_bounds.oriented_box_candidate_axes,
        dim=max(rotations, count),
        inputs=[rotations, count, axes, corners, deltas],
        device=device,
    )

    # The extent of the cloud in every candidate frame, six packed slots each. The kernel only
    # ``atomic_min``s into ``corners``, so it must arrive holding ``+inf``: both axes kernels seed a
    # candidate's slots as they write its frame, which is what lets the refinement reuse one
    # buffer across its rounds.
    n_slices = _extent_slices(n, rotations, device)
    kernel, dim = kernel_bounds.OBB_EXTENTS.launch_shape(rotations, n_slices)
    _launch.launch(kernel, dim=dim, inputs=[points, axes, n_slices, corners], device=points.device)

    _launch.launch(
        kernel_bounds.oriented_box_losses,
        dim=rotations,
        inputs=[corners, _BOX_OBJECTIVES[objective], loss],
        device=device,
    )
    chain_state = odt.as_array2d(
        state_flat.reshape((2 * n_chains, kernel_bounds.BOX_STATE_COLUMNS)), wp.float32
    )
    # Start at the covering radius of the global grid: the sampled winner is at most about this
    # far from its basin's optimum, and each round shrinks the radius.
    sigma = 2.0 * (math.pi**2 / max(rotations, 2)) ** (1.0 / 3.0)
    _launch.launch_tiled(
        kernel_bounds.oriented_box_seed_chains,
        dim=(1,),
        inputs=[
            loss,
            axes,
            corners,
            wp.int32(min(_REFINE_WINDOW, rotations)),
            wp.int32(n_chains),
            wp.float64(sigma / math.pi),
            wp.int32(count),
            deltas,
            chain_state,
            refine_axes,
            refine_corners,
        ],
        block_dim=_SEED_BLOCK_DIM,
        device=device,
    )
    if refine_iterations == 0:
        return _best_chain(chain_state, n_chains, 0)
    _refine_box(
        points,
        deltas,
        objective,
        refine_iterations,
        sigma,
        n_chains,
        chain_state,
        refine_axes,
        refine_corners,
    )
    return _best_chain(chain_state, n_chains, refine_iterations % 2)