Skip to content

Body–body distance ​

What it does ​

surface%distance_to(other, distance, ...) gives the distance between two bodies: the minimum over all pairs of their facets, with the two facets that realize it and the witness points on each, and whether the bodies touch or cross (issue #67). With several moving bodies the solver needs it for contact detection, lubrication corrections when two walls come within a few cells, and collision response.

the dragon and, beside its snout, a translucent cube; a gold segment joins the two witness points, and the dragon facet and the cube facet that realize the distance are drawn in ember

A cube beside the dragon's snout: distance_to returns the distance, 1.2285, the two witness points (gold) and the facets that realize it, 583 on the dragon and 45 on the cube (ember). The figure is drawn by docs/examples/src/fig_ref_body_distance_method.f90.

Method ​

  • Pair distance (fossil_body_distance%tri_tri_distance): 0 when the exact classification of fossil_tritri_exact says the two triangles meet (crossing, touching, or overlapping in a common plane, decided by exact orient2d); otherwise the minimum of the 6 vertex–triangle and 9 edge–edge distances (the closest pair of two disjoint triangles is one of these), each the norm of a residual. A degenerate facet (exactly collinear or coincident vertices, as raw exporter output can carry; sanitize removes them) has no plane, so the classification cannot apply to it (issue #96: a needle 0.5 from a face was reported in contact). Its contact is decided by exact segment and point predicates instead: the facet is the segment between its extreme vertices, or a point, tested by orient3d against the other triangle's plane and edges, and by orient2d in a common plane. The distance is the same minimum of 15.
  • Best-first descent of the two AABB trees: a heap of node pairs ordered by the distance between their boxes; a pair is dropped when its box distance exceeds the best found; leaf pairs are evaluated in a fixed order. Facet pairs at equal distance are tie-broken by the smaller (facet_self, facet_other), so the result, facets and points included, is bit-identical to the brute-force loop over all pairs (body_distance_brute).
  • Inside a leaf pair (roadmap #92 WP5): the facet pair of least box gap is evaluated first (the first in loop order on ties), so the pruning bound tightens sooner, then the others in loop order. The result does not depend on that order: the running best never drops below the final minimum, and an equal distance keeps the smaller pair. Once the best is 0 (contact), a pair after it in (facet_self, facet_other) order is not evaluated: its distance is ≥ 0 and it loses the tie rule. Before, every later pair with overlapping boxes was still classified exactly, though it could not win.
  • Cost. pairs= returns the number of facet pairs the call evaluated. Two 12-facet cubes (one tree leaf each, the distance_to.cubes line of fossil_val_perf): 27.3 evaluations per call apart (of 144; the box gaps allow no fewer than 26.7 in any order) and 3.4 in contact, 14.8 µs per call (35.9 µs before WP5); the dragon (fine) against a posed copy, 1.26 ms per call (3.3 ms). Part of the gain is the exact core: pair_cut orders the section points of two triangles with ip_compare, whose exact stage axis-aligned faces reached on every tie; a coordinate fixed by the construction is now compared directly (see booleans). What is left of a call is the arithmetic of the 15 sub-distances of each evaluated pair.
  • Poses (pose_self=, pose_other=): the bodies are taken where move would put them, without refitting either tree. Each facet is moved by to_world (the bits move writes), and each tree node is bounded by the box of its eight moved corners, a conservative bound. The result equals the one after move, bit for bit.
  • Many bodies: proximity_pairs(cutoff, pairs, distances) gives the pairs of bodies of one surface (its shells, facet_body) closer than cutoff, and proximity_pairs_of(surfaces, cutoff, ...) the pairs of a list of surfaces: pairs whose bounding boxes are farther than cutoff are skipped, the others get distance_to.
  • Curves (2-D twin): curve%distance_to(other, distance, point_self, point_other, segment_self, segment_other, intersecting, pose_self, pose_other). Two segments meet when the exact orient2d says they cross or touch (collinear overlaps included); otherwise their distance is the least of the four endpoint–segment distances. The segment pairs are evaluated in order behind a box test, with the same tie rule; poses (rigid_pose_2d_t) move the endpoints as move does, so the result equals the one after move, bit for bit.
  • CPU only: one query per pair of bodies, not a batch over points.

two disjoint triangles, one sepia and one teal, joined by the 15 candidate segments of the pair distance drawn faint, 6 from a vertex to the other triangle and 9 between edges; the least, 0.35, in gold, from a vertex of the teal triangle down onto the sepia one

The 15 candidates of one triangle pair, computed with the public kernels closest_on_triangle and closest_segment_segment of fossil_body_distance: the least, 0.35, from a vertex of one triangle to the face of the other, is the value tri_tri_distance returns.

Example ​

The cookbook's How close are my two bodies? measures one pair, with a pose. Here many bodies, the witness points and the 2-D twin. Three unit cubes, the second 0.25 beyond the first along x, the third 0.6 beyond it along y, given once as the three bodies of one surface and once as three surfaces:

f90
do k = 1, 3
   call cube(k)%load_from_file(file_name='cube-01.stl', guess_format=.true.)
enddo
call cube(2)%translate(delta=vector_R8P(1.25_R8P, 0._R8P, 0._R8P)) ; call cube(2)%analyze   ! 0.25 from cube 1
call cube(3)%translate(delta=vector_R8P(0._R8P, 1.6_R8P, 0._R8P))  ; call cube(3)%analyze   ! 0.6 from cube 1
all = cube(1)
call all%merge_solids(other=cube(2)) ; call all%merge_solids(other=cube(3))   ! one surface, three bodies
call all%proximity_pairs(cutoff=0.62_R8P, pairs=pairs, distances=distances, status=status)
if (status /= STATUS_OK) error stop 'proximity_pairs failed'
print '(A,I0,A)', 'one surface, ', all%get_bodies_number(), ' bodies, cutoff 0.62:'
do i = 1, size(distances)
   print '(A,I0,A,I0,A,F7.4)', '  bodies ', pairs(1, i), ' and ', pairs(2, i), ': ', distances(i)
enddo
call proximity_pairs_of(surfaces=cube, cutoff=0.62_R8P, pairs=pairs, distances=distances)
print '(A)', 'three surfaces, cutoff 0.62:'
do i = 1, size(distances)
   print '(A,I0,A,I0,A,F7.4)', '  surfaces ', pairs(1, i), ' and ', pairs(2, i), ': ', distances(i)
enddo

The closest pair of the first and third cubes, which face each other across a whole face:

f90
call cube(1)%distance_to(cube(3), distance=d, point_self=pa, point_other=pb, facet_self=fa, facet_other=fb)
print '(A,F7.4,A,I0,A,I0)', 'cubes 1 and 3: ', d, ', facets ', fa, ' and ', fb
print '(A,3F6.2,A,3F6.2)', '  from', pa, ' to', pb

In 2-D, a 64-gon of radius 0.5 against a unit square turned by 45° about its centre and placed at (1.5, 0) by a pose, so that a corner points at the polygon:

f90
do i = 1, 64
   cu(i) = 0.5_R8P * cos(2 * PI * (i - 1) / 64) ; cv(i) = 0.5_R8P * sin(2 * PI * (i - 1) / 64)
enddo
call circle%adopt_loops(u=cu, v=cv, loop_sizes=[64_I4P])                       ! a 64-gon of radius 0.5
call square%adopt_loops(u=[-0.5_R8P, 0.5_R8P, 0.5_R8P, -0.5_R8P], v=[-0.5_R8P, -0.5_R8P, 0.5_R8P, 0.5_R8P], &
                        loop_sizes=[4_I4P])                                    ! a unit square about the origin
call circle%distance_to(square, distance=d, point_self=qa, point_other=qb, &
                        pose_other=pose_2d(angle=PI / 4, translation=[1.5_R8P, 0._R8P]))   ! a corner towards the circle
print '(A,F8.5,A,F8.5,A,2F8.5,A,2F8.5)', '2-D: ', d, ' (exact ', 1._R8P - sqrt(0.5_R8P), ') from', qa, ' to', qb
$ ref_body_distance
one surface, 3 bodies, cutoff 0.62:
  bodies 1 and 2:  0.2500
  bodies 1 and 3:  0.6000
three surfaces, cutoff 0.62:
  surfaces 1 and 2:  0.2500
  surfaces 1 and 3:  0.6000
cubes 1 and 3:  0.6000, facets 1 and 5
  from  0.00  1.00  0.00 to  0.00  1.60  0.00
2-D:  0.29289 (exact  0.29289) from 0.50000 0.00000 to 0.79289 0.00000
  • Pairs. Both calls list the pairs closer than the cutoff 0.62: (1, 2) at 0.25 and (1, 3) at 0.6. The pair (2, 3), at 0.252+0.62=0.65, is beyond it and not listed; proximity_pairs_of skips it on its bounding boxes alone, 0.65 apart. proximity_pairs numbers the bodies by facet_body, proximity_pairs_of the surfaces by their index in the array.
  • Ties. Every point of the facing faces is at 0.6, so many facet pairs realize the distance. The tie rule takes the smallest (facet_self, facet_other): facets 1 and 5, with the witness points at the corner (0, 1, 0) and (0, 1.6, 0). The same rule makes the descent bit-identical to the brute-force loop.
  • 2-D. The square's corner lands at 1.5−2/2=0.79289 on the x axis, and the polygon has a vertex at (0.5, 0): the distance is 1−2/2=0.29289, between those two points. The square is queried where the pose puts it, without a move.

three unit cubes drawn translucent, the second 0.25 beyond the first along x, the third 0.6 beyond it along y; the closest pair of each body pair under the cutoff 0.62 drawn as a gold segment labelled 0.25 and 0.60

Moving bodies ​

a cube of side 0.25 approaching the dragon on a screw motion, half a turn about (1, 1, 1): each frame the closest pair joined by a segment and the gap, down to the first contact

Each frame calls distance_to(..., pose_other=) with the cube's tree as built (fig only moves a copy to draw it); the program is docs/examples/src/anim_body_distance.f90.

Command line ​

fossilizer --distance other.stl prints, for each input, the distance to the body of other.stl, whether they touch or cross, and the two closest facets and points:

bash
fossilizer -i a.stl --distance b.stl

src/tests/fossil_test_distance_cli.f90 reads the distance back for a cube against a copy 0.25 away and against itself.

Accuracy ​

The pair distance rests on two closest-point kernels, both checked against quadruple precision (src/tests/fossil_test_segment_distance_accuracy.f90, 4000 fixed-seed cases each):

  • Segment–segment (closest_segment_segment). The longer segment is the reference: the distance from a point of the other to it is a distance in the plane normal to its direction, while the foot stays inside it, so the least distance is a point-to-segment distance in that plane, or an endpoint distance. Each projection costs ~ε L, so near-parallel segments (angles down to 1e-15) stay within 0.62 ε L of the reference. The textbook solve (Ericson 5.1.9) used until issue #69 goes through a e − b² = |d₁ × d₂|² and lost ~ε L / angle: 139 of the 4000 cases were more than 16 ε L off, some by more than 1e5 ε L.
  • Point–triangle (closest_on_triangle). It calls the point kernel of the distance queries, triangle_closest_st (Eberly's solve, the residual form robust_st on needles, issue #39): within 33 ε L on needles of aspect up to 1e8. The Voronoi-region form (Ericson 5.1.5) used until issue #69 had 113 cases over 64 ε L.

Both paths of body_distance (the descent and body_distance_brute) call the same kernels, so they stay bit-identical.

the error of the segment-segment distance against a quadruple-precision reference, in units of eps L on a log scale, against the angle between the segments from 1e-2 to 1e-15: closest_segment_segment in teal, between 0.18 and 0.68 at every angle; the textbook solve in ember, above the 16 eps L bound from 1e-3 to 1e-8, up to 1.3e7 at 1e-8, and lower again at most of the smaller angles

The largest error over 40 fixed-seed pairs per decade of angle, drawn from the generator of the test: the kernel stays within 0.68 ε L at every angle; the textbook solve (written in the figure program) exceeds the 16 ε L bound from 1e-3 to 1e-8, peaks at 1.3e7 ε L at 1e-8, and falls back below it at most of the smaller angles (1.5e3 ε L at 1e-10).

Validation ​

src/tests/fossil_test_body_distance_small.f90: the bench's two cubes under 2000 poses (53 in contact), a grid of 128 facets on both tree kinds (200 poses), exact ties at contact (face, edge, vertex, overlap, plain and under an exact quarter turn) and degenerate facets, every output equal to body_distance_brute, the pair counts bounded (≤ 30 per call apart, ≤ 5 in contact; 37.06 and 35.51 before WP5). src/tests/fossil_test_body_distance.f90: cubes apart (exact distance), touching at a vertex, an edge, a face, and overlapping (0, intersecting), faces 1e-12 apart, and a sphere against a torus at six rigid motions, bit-identical to brute force. src/tests/fossil_test_body_distance_degenerate.f90: segment and point facets against a face (apart, crossing, touching at an end, in its plane) and against each other, both orders, through tri_tri_distance and distance_to, each against an exact contact reference and the minimum of the 15 sub-distances; and zero-length curve segments through curve%distance_to. src/tests/validation/fossil_val_body_distance.f90: the bunny (20 000 facets) against the dragon (5 000) under 20 motions, bit-identical to brute force. src/tests/fossil_test_curve_distance_to.f90: squares apart (exact distance), touching at a corner, along a side, and crossing, and a circle against a square at six poses, equal to the result after move.

API ​

See distance_to and the curve's queries.

ArgumentIntentNotes
otherinThe other body (surface_stl_object).
distanceoutThe least distance over the facet pairs; 0 when the bodies touch or cross.
point_self, point_otherout, opt.The witness points.
facet_self, facet_otherout, opt.The closest facets (ties: the smallest pair).
intersectingout, opt.The bodies touch or cross (exact).
statusout, opt.STATUS_OK, STATUS_INVALID_INPUT (empty surface).
pose_self, pose_otherin, opt.rigid_pose_t: the bodies where move would put them, trees not refitted; same bits.
pairsout, opt.The facet pairs evaluated by the triangle-triangle distance: the cost of the call (roadmap #92 WP5).

The free routines body_distance and body_distance_brute of fossil_body_distance take the same optional pairs.