Cut-cell geometry
What it does
FOSSIL computes, on a rectilinear (possibly stretched) block of an AMR grid, where the grid meets the wall:
- Grid-line crossings. Every crossing of an axis-aligned line with the surface (curve), sorted, with its facet (segment) and whether the line enters or leaves the solid. From them, for each cell centre, the fraction of the spacing toward each neighbour at which the wall is met, and the inside flag. These serve finite-difference closures: shortened spacing, ILW boundary data, fluxes at grid-line intersections.
- Cut cells, 2-D:
- per cell: fluid area fraction, the four edge apertures, fluid centroid, and wetted length, centroid and normal;
- the separate fluid pieces of a cell, each with its own measures.
- Cut cells, 3-D:
- face fluid fractions and centroids from exact plane sections;
- per cell: fluid volume fraction and centroid, and wetted area, centroid and normal;
- the separate fluid pieces of a cell (
cut%pieces), each with its own volume and centroid, wetted area, centroid and normal, and the fluid fraction of each of the six cell faces (cut%piece_*).
The fluid is outside the solid. These outputs serve conservative cut-cell closures and sub-cell masks.
| Query | 3-D | 2-D |
|---|---|---|
| Crossings of one line | surface%line_crossings | curve%line_crossings |
| Crossings of many parallel lines, fixed buffers | surface%line_crossings_many(_device) | curve%line_crossings_many(_device) |
| Wall fractions along the grid lines of a block | surface%cell_wall_fractions | curve%cell_wall_fractions |
| Cut cells of a block | cut_cells_3d(surface, x, y, z, cut) | curve%cut_cells(x, y, cut) |
| Cut cells of a block on the device, copied back or resident | cut_cells_3d_device(surface, x, y, z, cut, resident=) | curve%cut_cells_device(x, y, cut, resident=) |
| Cut cells of several posed bodies, pieces and walls labelled by body | cut_cells_3d_bodies(surfaces, poses, x, y, z, cut, piece_bodies=) | cut_cells_2d_bodies(curves, poses, x, y, cut, piece_bodies=) |
The 2-D outputs on one picture: 16 of the 48 cells are cut and the grid lines cross the ellipse 16 times. The solid area of the cells is 0.22610, the polygon's area; the wetted lengths add up to 1.79520, and the aperture differences equal the wetted normal integral in every cell, residual 0.00e+00 (fig_ref_cut_cells_outputs.f90).
On the device
curve%cut_cells_device(x, y, cut, status, intervals, resident) (issue #100) returns the cut of curve%cut_cells bit for bit:
- fractions, apertures, centroids;
- wetted lengths, centroids and normals;
- pieces and their measures;
node_inand the fluid edge intervals.
Moments, boundaries and quadrature are host only, and the twin has no arguments for them.
How the work is split:
- Host: walks the segments through the grid and indexes the crossings.
- Device: computes the node flags (the exact tests of the host, one thread per node), classifies the cells, runs the integer prefix sums and the same per-cell kernels as
cut_cells(count, then fill).
The two agree by construction: same kernels, and integer sums are exact in any order. The curve needs no enter_device.
Resident outputs. With resident=.true. the outputs stay on the device:
- the host arrays of
cutare allocated but hold garbage untilcut%update_host; cut%on_devicesays so;cut%exit_devicereleases them, and must be called before the cut goes out of scope or is deallocated.
cut_cells, cut_cells_device and cut_coarsen_2d release a resident cut they are given before overwriting it. A routine that reads a cut on the host (cut_links_2d, cut_coarsen_2d) needs update_host first. A copy b = a of a resident cut is not resident. Device code reads the outputs through pointer aliases, the rule of the other device routines:
program resident_cut
use fossil, only : curve_object, cut_cells_2d_t
use penf, only : I4P, R8P
implicit none
type(curve_object) :: curve
type(cut_cells_2d_t), target :: cut
real(R8P), allocatable :: u(:), v(:), x(:), y(:)
real(R8P), pointer :: alpha(:,:)
real(R8P) :: fluid
integer(I4P) :: i, j, k, status
allocate(u(256), v(256), x(129), y(129))
do k = 1, 256
u(k) = 0.5_R8P + 0.3_R8P * cos(0.0245436926_R8P * (k - 1)) ; v(k) = 0.5_R8P + 0.3_R8P * sin(0.0245436926_R8P * (k - 1))
enddo
call curve%adopt_loops(u=u, v=v, loop_sizes=[256_I4P])
do k = 1, 129
x(k) = (k - 1) / 128._R8P ; y(k) = x(k)
enddo
call curve%cut_cells_device(x=x, y=y, cut=cut, status=status, resident=.true.)
alpha => cut%alpha ! a device consumer: the fluid area, summed on the device
fluid = 0._R8P
!$acc parallel loop collapse(2) reduction(+:fluid) present(alpha)
do j = 1, 128
do i = 1, 128
fluid = fluid + max(alpha(i, j), 0._R8P) / 128._R8P**2
enddo
enddo
call cut%update_host ! only if the host needs the outputs
call cut%exit_device ! before cut goes away
print '(A,F8.5)', 'fluid area: ', fluid
endprogram resident_cutMeasured on an RTX 4070 (nvfortran 26.9, -gpu=nofma), best of 5 calls with the fluid intervals:
| curve | cells | CPU [ms] | device, copied back [ms] | device, resident [ms] |
|---|---|---|---|---|
| ellipse, 1024 segments | 1024² | 41 | 27 | 6.4 |
| NACA 0012, 1022 segments | 1024² | 42 | 30 | 6.6 |
| 50 circles, 3200 segments | 1024² | 68 | 32 | 9.3 |
| any of the three | 256² | 2.8-5.8 | 3.4-4.4 | 1.2-2.0 |
What bounds each path at 1024²:
- Copied back: the copy of about 250 MB of outputs to pageable host memory (12-14 GB/s into pages already written, 3-4 GB/s into new ones: the twin reuses the host arrays of the cut it overwrites when the shape is unchanged).
- Resident: about 3 ms on the device (kernels 1.3 ms, 13 MB of indexes copied in) and about 3.6 ms on the host (walk, indexes, allocations).
Per time step. fossil_test_curve_bench 256 also times a moving body: each step moves the curve (move, 2 degrees about the block centre), tags the cells (box_classify_many, one box per cell) and computes the cut cells, 20 steps, per-step best of 5:
| curve | cells | CPU [ms] | device, copied back [ms] | device, resident [ms] |
|---|---|---|---|---|
| ellipse | 1024² | 138 | 60 | 32 |
| NACA 0012 | 1024² | 111 | 63 | 31 |
| ellipse | 256² | 9.7 | 6.7 | 4.5 |
| NACA 0012 | 256² | 7.6 | 7.0 | 4.5 |
The resident step is bound by the tags, about 25 of its 32 ms at 1024², because box_classify_many_device uploads the one million cell boxes and returns the codes at every step. The swept geometry and the piece links are not on the device yet (issue #100, steps 4 and 5), so a whole solver step still goes back to the host.
The 3-D plane sections. cut_cells_3d(..., device_sections=.true.) cuts its 3(N+1) plane sections on the device, with the same bits, when no links, moments_order > 0 or quadrature is asked; the default stays the host path. The sections of one axis are the blocks of one multi-block launch (cut_cells_device_many), and a device kernel writes the face arrays, which alone come back. Every plane is sliced through a plane sweep (the facets spanning each plane, in facet order: the same curves as slice_surface bit for bit). Measured by fossil_test_distance_bench (faces copied back, best of 5):
| body | 32³ host / device [ms] | 64³ | 128³ |
|---|---|---|---|
| bunny | 47 / 50 | 119 / 106 | 462 / 375 |
| dragon-fine | 36 / 38 | 102 / 82 | 464 / 302 |
| cube-01 | 6.3 / 4.2 | 43 / 12 | 308 / 106 |
The 3-D cut cells. cut_cells_3d_device(surface, x, y, z, cut, status, edges, resident) returns the cut of cut_cells_3d (without links) bit for bit:
- cell fractions, centroids, wetted areas, centroids and normals;
- face fractions, centroids, pieces and closed flags;
- pieces and their measures;
node_in, and withedges=.true.the edge fractions;- with
links=, the piece links (cut-solver reference); - with
walls=, the labelled wall terms ofcut_cells_3d(..., walls=)(cut_walls_3d_t: one term per cell and facet clipped to three vertices or more, with its piece, vector area, wet area and centroid, in cell then facet order), every field bit for bit. Their force and moment for a solver's pressure:cut_loads_3d(surface loads).
Moments and quadrature stay on the host.
The wall terms are a stage after the pieces, on the host's own kernels: one thread per cell counts its terms, a prefix sum places them, one thread per cell writes them. A multi-piece cell reads its polygons and their pieces from the workspace slice its fill pass left, as the host path does; every other cell clips its candidates as the cell totals do. With resident=.true. the terms stay mapped like the cut (walls%update_host, walls%exit_device; every writer releases resident terms first). With alpha_only=.true. none are computed. On an RTX 4070 (best of 5) the terms add 5-9 ms to a resident call at 128³ (sphere 0.150 -> 0.156 s, cone 0.208 -> 0.217 s), about 4 %, and a few ms or nothing measurable on the CPU path.
How the work is split:
- Host: the grid check, the candidate facets of each cell (bounding-box binning and the box-triangle filter), the open cells, the slicing.
- Device: the sections, the node states (one thread per grid line: the line's crossings in the host's order, each placed by the exact
orient3d), the cell totals, the classification and the prefix sums, the exact edge piercings, andcell_pieces(count, then fill), one thread per cell.
The surface needs its SAH BVH. resident=.true. follows the 2-D contract: the outputs stay mapped, the host arrays hold garbage until cut%update_host, cut%exit_device releases them, and every routine that writes a cut releases a resident one first.
Measured on an RTX 4070, best of 5 after a warm-up, the CPU path being cut_cells_3d without links:
| body | cells | CPU [s] | device, copied back [s] | device, resident [s] |
|---|---|---|---|---|
| sphere (marching cubes) | 64³ | 0.137 | 0.061 | 0.058 |
| sphere | 128³ | 0.680 | 0.248 | 0.207 |
| cone | 128³ | 0.648 | 0.305 | 0.243 |
| cube-02 | 128³ | 0.537 | 0.182 | 0.142 |
| cube-01 | 32³ | 0.014 | 0.011 | 0.009 |
That is 2.1-3.0x copied back and 2.7-3.8x resident at 128³. One resident sphere call at 128³ (0.21 s):
- kernels about 41 ms (the piercings and the count pass 16 ms);
- copies about 87 ms: the sections copy the faces back and the cells map them again;
- host work about 100 ms: the candidates, the open cells and the slicing.
The face round trip and the host candidates are what remain to move.
Several bodies
cut_cells_3d_bodies(surfaces, poses, x, y, z, cut, ...) cuts a block by several bodies at once, each with its own pose (2-D: cut_cells_2d_bodies(curves, poses, x, y, cut, ...); #109 WP3). It is the cut of one surface: the bodies placed as move places them and merged as merge_solids merges them (merge_posed_bodies), so the cut, its links and its wall terms are bit for bit those of a copy moved and merged by hand. What it adds:
- Labels.
piece_bodies=(apiece_bodies_t) gives the body of every wall term,wall_body(the index of the surface or curve) andwall_sub_body(itsfacet_bodyorloop_body), and for every piece the sorted list of the bodies its wall terms belong to (start,body,sub_body, CSR). A piece between two bodies lists both. The wall terms are those ofwalls=in 3-D (one per cell and facet) and ofcut_walls_2din 2-D (one per wall segment). - Overlap refused. The cut of overlapping bodies would need their boolean union, so an overlap returns
STATUS_INVALID_INPUTand an empty cut. The test is exact: an edge of one body piercing a facet of another transversally, two coplanar facets of the same orientation overlapping, or a vertex of one body (one per shell, off the other body) strictly inside the other by the exact parity of the cut's own line kernels. Bodies whose boxes do not meet are not tested further. Overlaps between the sub-bodies of one surface are that surface's own business, as for one body. - Touching allowed. Bodies in contact without a common volume are cut as they are: two cubes along a face, an edge or a corner, on grid planes or between them, leave every cell trusted and the solid volume equal to the sum of the bodies' to round-off (
fossil_test_cut_bodies).contacts=counts the facet pairs in contact. - Device.
device=.true.runs the cut on the device,resident=as for one body; the merge, the check and the labels run on the host. In 2-D the device cut has no oriented boundaries, so the labels come from a host cut with boundaries. Moments and quadrature are host-only, as for one body. - The merged surface.
merged=returns it, withfacet_body=andfacet_sub_body=(2-Dsegment_*): the surface the loads need (cut_loads_3d,cut_walls_gyration). The swept cells of several bodies have the Gauss path (moving bodies); their piece map is not built.
Two bodies in their own poses, cut together. The two cells in the gap hold a fluid piece bounded by both walls; the solid area of the cells is the sum of the two bodies' areas. A pose where the circle crosses the ellipse is refused; two squares touching along an edge that lies on a grid line are cut with every cell trusted.
!< Figure of the reference page "Cut-cell geometry", section "Several bodies": a turned ellipse (semi-axes 0.3 and
!< 0.16, a 96-gon) and a 64-gon circle of radius 0.18, each with its own pose, 0.04 apart, cut together on 12 x 7 cells
!< of 0.1 by `cut_cells_2d_bodies`. The cells are shaded by their fluid fraction (cream to sepia); the cells whose
!< fluid piece is bounded by both bodies (two entries in `piece_bodies`) are outlined in red; the wall segments are drawn
!< in the colour of their body (`wall_body`). The run checks the covering sum, then shows a crossing pose refused and
!< two squares touching along an edge accepted.
program fig_ref_cut_cells_bodies
use fossil, only : curve_object, cut_cells_2d_t, cut_walls_2d_t, piece_bodies_t, rigid_pose_2d_t, pose_2d, &
cut_cells_2d_bodies, STATUS_OK
use fossil_fig, only : fig_open, fig_segments, fig_quad, fig_close
use penf, only : I4P, R8P
use vecfor, only : vector_R8P
implicit none
integer(I4P), parameter :: NX = 12, NY = 7
real(R8P), parameter :: H = 0.1_R8P, PI = acos(-1._R8P), LIFT = 1.e-3_R8P
type(curve_object) :: body(2), sq
type(rigid_pose_2d_t) :: pose(2)
type(cut_cells_2d_t) :: cut
type(cut_walls_2d_t) :: walls
type(piece_bodies_t) :: pb
real(R8P) :: x(NX + 1), y(NY + 1), u(96), v(96), solid
type(vector_R8P), allocatable :: s(:), e(:)
integer(I4P) :: i, j, k, m, p, status, nboth, w
x = [(H * i, i = 0, NX)] ; y = [(H * j, j = 0, NY)]
do k = 1, 96
u(k) = 0.3_R8P * cos(2 * PI * (k - 1) / 96) ; v(k) = 0.16_R8P * sin(2 * PI * (k - 1) / 96)
enddo
call body(1)%adopt_loops(u=u, v=v, loop_sizes=[96_I4P])
do k = 1, 64
u(k) = 0.18_R8P * cos(2 * PI * (k - 1) / 64) ; v(k) = 0.18_R8P * sin(2 * PI * (k - 1) / 64)
enddo
call body(2)%adopt_loops(u=u(1:64), v=v(1:64), loop_sizes=[64_I4P])
pose(1) = pose_2d(angle=0.35_R8P, translation=[0.42_R8P, 0.36_R8P]) ! each body in its own pose
pose(2) = pose_2d(angle=0._R8P, translation=[0.93_R8P, 0.33_R8P])
call cut_cells_2d_bodies(body, pose, x, y, cut, status=status, piece_bodies=pb, walls=walls)
if (status /= STATUS_OK) error stop 'cut_cells_2d_bodies failed'
nboth = 0 ; solid = 0._R8P
do p = 1, pb%np
if (pb%start(p + 1) - pb%start(p) == 2) nboth = nboth + 1
enddo
do j = 1, NY
do i = 1, NX
solid = solid + (1._R8P - cut%alpha(i, j)) * H**2
enddo
enddo
print '(A,I0,A,I0,A,I0,A,I0)', 'cells ', NX * NY, ', pieces ', cut%np, ', wall segments ', walls%n, &
', pieces bounded by both bodies ', nboth
print '(A,F10.7,A,F10.7)', 'solid area ', solid, ', A1 + A2 ', body(1)%get_area() + body(2)%get_area()
pose(2) = pose_2d(angle=0._R8P, translation=[0.8_R8P, 0.33_R8P]) ! now the circle crosses the ellipse
call cut_cells_2d_bodies(body, pose, x, y, cut, status=status)
print '(A,I0,A)', 'crossing pose: status ', status, ' (refused)'
call sq%adopt_loops(u=[0._R8P, 0.25_R8P, 0.25_R8P, 0._R8P], v=[0._R8P, 0._R8P, 0.25_R8P, 0.25_R8P], loop_sizes=[4_I4P])
pose(1) = pose_2d(angle=0._R8P, translation=[0.25_R8P, 0.25_R8P])
pose(2) = pose_2d(angle=0._R8P, translation=[0.5_R8P, 0.375_R8P]) ! along the edge x = 0.5
call cut_cells_2d_bodies([sq, sq], pose, x, y, cut, status=status)
print '(A,I0,A,I0)', 'touching squares: status ', status, ', untrusted cells ', count(cut%pieces < 0)
! the figure, on the first cut
pose(1) = pose_2d(angle=0.35_R8P, translation=[0.42_R8P, 0.36_R8P])
pose(2) = pose_2d(angle=0._R8P, translation=[0.93_R8P, 0.33_R8P])
call cut_cells_2d_bodies(body, pose, x, y, cut, status=status, piece_bodies=pb, walls=walls)
call fig_open(w, 'ref-cut-cells-bodies', 'fluid fraction (shading), cells of a piece bounded by both bodies (red), '// &
'walls by body (gold, teal)', -90._R8P, 90._R8P, width=760_I4P, height=470_I4P)
do j = 1, NY
do i = 1, NX
call fig_quad(w, 'frac', q(x(i), y(j), 0._R8P), q(x(i + 1), y(j), 0._R8P), q(x(i + 1), y(j + 1), 0._R8P), &
q(x(i), y(j + 1), 0._R8P), value=max(0._R8P, cut%alpha(i, j)))
enddo
enddo
call fig_segments(w, 'box', [([(q(x(i), y(j), LIFT), i = 1, NX)], j = 1, NY + 1)], &
[([(q(x(i + 1), y(j), LIFT), i = 1, NX)], j = 1, NY + 1)])
call fig_segments(w, 'box', [([(q(x(i), y(j), LIFT), j = 1, NY)], i = 1, NX + 1)], &
[([(q(x(i), y(j + 1), LIFT), j = 1, NY)], i = 1, NX + 1)])
allocate(s(4 * pb%np), e(4 * pb%np)) ; m = 0
do p = 1, pb%np ! the cells of the pieces bounded by both bodies
if (pb%start(p + 1) - pb%start(p) < 2) cycle
i = cut%piece_cell(1, p) ; j = cut%piece_cell(2, p)
s(m + 1:m + 4) = [q(x(i), y(j), 2 * LIFT), q(x(i + 1), y(j), 2 * LIFT), q(x(i + 1), y(j + 1), 2 * LIFT), &
q(x(i), y(j + 1), 2 * LIFT)]
e(m + 1:m + 4) = [q(x(i + 1), y(j), 2 * LIFT), q(x(i + 1), y(j + 1), 2 * LIFT), q(x(i), y(j + 1), 2 * LIFT), &
q(x(i), y(j), 2 * LIFT)]
m = m + 4
enddo
call fig_segments(w, 'hole', s(1:m), e(1:m))
deallocate(s, e) ; allocate(s(walls%n), e(walls%n))
do k = 1, 2 ! the wall segments, by body
m = 0
do i = 1, walls%n
if (pb%wall_body(i) /= k) cycle
m = m + 1
s(m) = q(walls%ends(1, i), walls%ends(2, i), 3 * LIFT) ; e(m) = q(walls%ends(3, i), walls%ends(4, i), 3 * LIFT)
enddo
call fig_segments(w, trim(merge('foot ', 'probe', k == 1)), s(1:m), e(1:m))
enddo
call fig_close(w)
contains
function q(a_, b_, dz) result(r)
!< A point of the plane z = 0, lifted by dz towards the viewer.
real(R8P), intent(in) :: a_, b_, dz !< Coordinates, lift.
type(vector_R8P) :: r !< Point.
r = vector_R8P(a_, b_, dz)
endfunction q
endprogram fig_ref_cut_cells_bodies$ fig_ref_cut_cells_bodies
cells 84, pieces 73, wall segments 196, pieces bounded by both bodies 2
solid area 0.2523130, A1 + A2 0.2523130
fossil cut_cells_2d_bodies: refused -- two bodies overlap (their areas intersect)
crossing pose: status 5 (refused)
touching squares: status 0, untrusted cells 0Example
The basic calls, on the dragon section and the dragon, are in tutorial chapter 10, and the solver data built on them (links, SRD and merge neighbourhoods) in the cookbook. This program runs the checks of this page on small cases with known answers.
!< Reference page "Cut-cell geometry": the checks of the page on small exact cases. 2-D: a solid strip thinner than
!< the cell across a row of cells (two fluid pieces per cell). 3-D: the unit cube turned about (1, 1, 1) and shifted,
!< on a 6^3 block: covering sum, per-cell divergence residual, small cells, wall fractions along the centre lines.
program ref_cut_cells
use fossil, only : curve_object, cut_cells_2d_t, surface_stl_object, cut_cells_3d_t, cut_cells_3d, rigid_pose_t, &
pose_from_axis_angle
use penf, only : I4P, R8P
implicit none
type(curve_object) :: strip
type(cut_cells_2d_t) :: cut2
type(surface_stl_object) :: cube
type(cut_cells_3d_t) :: cut3
real(R8P) :: e(5), g(7), c(6), h, res, frac(6, 6, 6, 6)
logical :: inside(6, 6, 6)
integer(I4P) :: i, j, k, p
e = [(0.25_R8P * i, i = 0, 4)] ! 4 x 4 cells of side 1/4
call strip%adopt_loops(u=[-0.1_R8P, 1.1_R8P, 1.1_R8P, -0.1_R8P], & ! a solid strip 0.05 thick across row 2
v=[0.35_R8P, 0.35_R8P, 0.40_R8P, 0.40_R8P], loop_sizes=[4_I4P])
call strip%cut_cells(x=e, y=e, cut=cut2)
print '(A,4I2)', 'strip: pieces of row 2 ', cut2%pieces(:, 2)
p = cut2%first_piece(2, 2)
print '(A,2F8.4,A,F8.4)', ' cell (2, 2): piece areas / cell ', cut2%piece_area(p:p + 1) / 0.0625_R8P, &
', alpha ', cut2%alpha(2, 2)
print '(A,4F6.2,A,4F6.2)', ' apertures (-u, +u, -v, +v) ', cut2%piece_aperture(:, p), ' and ', cut2%piece_aperture(:, p + 1)
call cube%load_from_file(file_name='cube-01.stl', guess_format=.true.)
call cube%move(pose_from_axis_angle(axis=[1._R8P, 1._R8P, 1._R8P], angle=0.3_R8P, translation=[0.21_R8P, 0.13_R8P, 0.07_R8P]))
h = 0.25_R8P
g = [(-0.1_R8P + h * i, i = 0, 6)] ! 6^3 cells, the block covers the body
call cut_cells_3d(surface=cube, x=g, y=g, z=g, cut=cut3)
print '(A,I0,A,I0,A,I0)', 'cube: cut cells ', count(cut3%alpha > 0._R8P .and. cut3%alpha < 1._R8P), &
', multi-piece ', count(cut3%pieces > 1), ', flagged ', count(cut3%pieces < 0)
print '(A,ES9.2)', ' covering sum: solid volume - body volume ', sum(1._R8P - cut3%alpha) * h**3 - cube%get_volume()
res = 0._R8P
do k = 1, 6 ; do j = 1, 6 ; do i = 1, 6 ! divergence theorem, cell by cell
res = max(res, maxval(abs([cut3%face_x(i + 1, j, k) - cut3%face_x(i, j, k), &
cut3%face_y(i, j + 1, k) - cut3%face_y(i, j, k), &
cut3%face_z(i, j, k + 1) - cut3%face_z(i, j, k)] * h**2 - cut3%wet_normal(:, i, j, k))))
enddo ; enddo ; enddo
print '(A,ES9.2)', ' largest divergence residual ', res
print '(A,I0,A,ES10.3)', ' small cells (0 < alpha < 1e-2) ', count(cut3%alpha > 0._R8P .and. cut3%alpha < 1.e-2_R8P), &
', smallest alpha ', minval(cut3%alpha, cut3%alpha > 0._R8P)
c = 0.5_R8P * (g(1:6) + g(2:7)) ! the cell centres
call cube%cell_wall_fractions(x=c, y=c, z=c, frac=frac, inside=inside)
print '(A,I0,A,I0)', 'centres inside ', count(inside), ' of ', size(inside)
print '(A,L1,A,6F7.3)', ' centre (2, 3, 3): inside ', inside(2, 3, 3), ', fractions (-x .. +z)', frac(:, 2, 3, 3)
endprogram ref_cut_cells$ ref_cut_cells
strip: pieces of row 2 2 2 2 2
cell (2, 2): piece areas / cell 0.4000 0.4000, alpha 0.8000
apertures (-u, +u, -v, +v) 0.40 0.40 1.00 0.00 and 0.40 0.40 0.00 1.00
cube: cut cells 125, multi-piece 7, flagged 0
covering sum: solid volume - body volume 5.55E-16
largest divergence residual 3.22E-16
small cells (0 < alpha < 1e-2) 5, smallest alpha 1.576E-05
centres inside 64 of 216
centre (2, 3, 3): inside T, fractions (-x .. +z) 0.270 -1.000 -1.000 -1.000 -1.000 -1.000- Thin strip, 2-D. The solid strip, 0.05 thick, lies inside row 2 (v from 0.25 to 0.5), so each cell of the row holds two fluid pieces, of 0.4 of the cell each, and
alphais 0.8.piece_aperturesplits the edges between them: each piece owns 0.4 of the -u and +u edges, the lower piece all of the -v edge and none of the +v edge, the upper piece the reverse. - Turned cube, 3-D.
moveturns the unit cube 0.3 rad about (1, 1, 1) and shifts it, so no face is grid-aligned. On the 6³ block, 125 cells are cut and none is flagged. 7 cells hold two pieces or more: the body is convex, but where an edge of the cube runs through a cell, the solid wedge can split the cell's fluid in two. - Covering sum. The solid volume summed over the block differs from
get_volumeby 5.55·10⁻¹⁶. - Divergence theorem. The largest residual of the face-fraction differences against
wet_normal, over every cell, is 3.22·10⁻¹⁶. - Small cells. 5 cells have a fluid fraction below 10⁻², the smallest 1.576·10⁻⁵: the cells a solver's small-cell treatment has to handle.
- Wall fractions.
cell_wall_fractionsworks on the cell centres, not the edges. Centre (2, 3, 3) is inside, and its -x line meets the wall at 0.270 of the spacing to the neighbouring centre; -1 marks the directions with no wall before the next centre.
The batched line query, on the dragon: 24 × 24 lines along x through its bounding box, into buffers of 16 crossings per line, each line checked against the single-line call.
!< Reference page "Cut-cell geometry": batched grid-line crossings. 24 x 24 lines along x through the dragon's box,
!< into fixed buffers of 16 crossings per line (surface%line_crossings_many), checked line by line against
!< surface%line_crossings, and the entering and leaving crossings of every line counted.
program ref_cut_cells_lines
use fossil, only : surface_stl_object
use penf, only : I4P, R8P
use vecfor, only : vector_R8P
implicit none
integer(I4P), parameter :: N = 24, NMAX = 16
type(surface_stl_object) :: dragon
type(vector_R8P) :: lo, hi
real(R8P) :: a(N * N), b(N * N), t(NMAX, N * N)
integer(I4P) :: facets(NMAX, N * N), counts(N * N), i, j, m, nodd, ndiff
logical :: entering(NMAX, N * N), overflow(N * N)
real(R8P), allocatable :: t1(:)
integer(I4P), allocatable :: f1(:)
logical, allocatable :: e1(:)
call dragon%load_from_file(file_name='dragon.stl', guess_format=.true.)
lo = dragon%get_bmin() ; hi = dragon%get_bmax()
do j = 1, N
do i = 1, N ! line (i, j) at y = a, z = b, cell-centred in the box
a(i + (j - 1) * N) = lo%y + (hi%y - lo%y) * (i - 0.5_R8P) / N
b(i + (j - 1) * N) = lo%z + (hi%z - lo%z) * (j - 0.5_R8P) / N
enddo
enddo
call dragon%line_crossings_many(axis=1_I4P, a=a, b=b, t0=lo%x - 1._R8P, t1=hi%x + 1._R8P, t=t, facets=facets, &
entering=entering, counts=counts, overflow=overflow)
print '(A,I0,A,I0,A,I0,A,I0)', 'lines ', N * N, ', crossing the dragon ', count(counts > 0), ', crossings ', sum(counts), &
', overflowed ', count(overflow)
nodd = 0 ; ndiff = 0
do m = 1, N * N
if (count(entering(1:counts(m), m)) /= counts(m) - count(entering(1:counts(m), m))) nodd = nodd + 1
call dragon%line_crossings(axis=1_I4P, a=a(m), b=b(m), t0=lo%x - 1._R8P, t1=hi%x + 1._R8P, t=t1, facets=f1, &
entering=e1, n=i)
if (i /= counts(m)) then
ndiff = ndiff + 1
elseif (any(t1(1:i) /= t(1:i, m)) .or. any(f1(1:i) /= facets(1:i, m))) then
ndiff = ndiff + 1
endif
enddo
print '(A,L1)', 'dragon watertight ', dragon%is_watertight()
print '(A,I0,A,I0)', 'lines with unequal entering/leaving counts ', nodd, ', lines differing from line_crossings ', ndiff
m = maxloc(counts, 1)
print '(A,I0,A,F7.3,A,F7.3,A,I0,A)', 'most crossed line: ', counts(m), ' crossings, sorted from x = ', t(1, m), ' to ', &
t(counts(m), m), ', ', count(entering(1:counts(m), m)), ' entering'
endprogram ref_cut_cells_lines$ ref_cut_cells_lines
lines 576, crossing the dragon 337, crossings 1460, overflowed 0
dragon watertight F
lines with unequal entering/leaving counts 0, lines differing from line_crossings 0
most crossed line: 14 crossings, sorted from x = -7.845 to 8.207, 7 entering- Buffers. 337 of the 576 lines cross the dragon, 1460 crossings in all, the most crossed line 14 times: a buffer of 16 does not overflow (with 8, 10 lines overflowed).
overflow(i)flags a line whose buffer was too small; its kept crossings are then not the first ones, so re-run it with a larger buffer. - Agreement. Every line gives the same parameters and facets as
line_crossings, and enters as often as it leaves: the dragon is not watertight (is_watertightis false), but none of these lines passes through an opening.
The exactness model
- Decisions are exact, constructed coordinates are rounded.
- Every topological decision is a comparison or the exact
orient2d:- whether a line crosses a triangle or segment;
- on which side of a grid plane or line a vertex lies;
- in which cell a piece of a segment lies.
- Crossing points are constructed in floating point.
- So the topology is exact and the measures are exact to round-off.
- Every topological decision is a comparison or the exact
- One symbolic tie-break. A point exactly on a grid line or plane counts as being on its low side (the line or plane is taken at x + ε). An axis-aligned line through an edge or a vertex of the surface is resolved by a symbolic perturbation of its position (Woop et al. 2013, made exact).
- On a watertight surface every crossing is counted exactly once, also on grid-aligned bodies.
- Every point lies in exactly one half-open cell, (x_i, x_i+1].
Every crossing of the diamond lies on a grid node, the worst case for a rounded test. The line v = 1/8 touches the bottom vertex: taken at v + ε it passes just above it and crosses both sides there, so it has 2 crossings, both at u = 0.5. The line v = 7/8 touches the top vertex and, taken at v + ε, misses it: 0 crossings. The other lines have one entering and one leaving crossing each, and the 12 cut cells are halved exactly: the solid area is 0.28125, the area of the diamond.
- 2-D cut cells.
- Each segment is walked through the grid. Whether it leaves a cell through the vertical or the horizontal line first is decided by the exact side of the cell corner.
- The measures come from Green's theorem over the wall pieces and the solid parts of the cell edges.
- The pieces come from a union-find over the fluid boundary arcs, joined by the wall chains that connect them. A clockwise loop inside a cell (a hole) is a piece of its own; a counter-clockwise loop (an island) is subtracted from the piece that contains it.
- 3-D cut cells.
- Each grid plane is cut once (
slice_surfacewithon_plane_low), and the section is cut by the 2-D machinery, so the two cells sharing a face see the same fraction. - Every triangle is clipped to every cell it overlaps, with the same rule. The planes are cut x, then y, then z, except for a triangle nearly parallel to a y or z grid plane (its normal within 10⁻³ of that axis): it is cut along that axis first, on its own vertices, as the plane's section reads it (issue #107). Cut later, its crossings would come from points the earlier cuts had rounded, a few ulps above the plane would round onto it, and the region would be counted in both cells: up to a third of a cell, and 2.7·10⁻⁴ of a cell still for a slope of 1000 ulps.
- Volume and first moments come from the divergence theorem over the clipped triangles and the solid face parts, in coordinates local to each cell.
- Pieces come from a union-find over the parts of the boundary of the fluid:
- the parts are the wall polygons (each triangle clipped to the cell) and the fluid intervals of the 12 cell edges;
- the corner states are the exact inside flags of the perturbed nodes, and the piercings of an edge are its exact crossings under the global perturbation (between the perturbed corners), entering or leaving the solid by the sign of the normal along the edge, so the states alternate from corner to corner (issue #70; before, the piercings were the clipped polygon vertices on the edge, one per incident facet when a mesh edge or vertex lay on it);
- the parts are joined where polygons share a vertex (the clipped points of a shared mesh edge are bit-identical), at a piercing, at a fluid corner, and where a solid island traced on a face is surrounded by fluid (a ray from the island to the nearest trace or face edge);
- every joined set that touches the cell boundary is one piece; a closed wall set inside the cell adds a piece only if it encloses a void.
- So a passage narrower than the cell, whose fluid meets the cell boundary in two separate disks, is one piece, and a thin plate across the cell leaves two.
- Each grid plane is cut once (
The plate cuts 32 cells and splits 22 of them in two; none is flagged. The two centroids of each split cell lie on opposite sides of the plate.
- Piece measures. The pieces of cell (i, j, k) are
first_piece(i, j, k)tofirst_piece(i, j, k) + pieces(i, j, k) - 1;piece_cell(:, p)gives the cell back. For each piece:- the wall terms (area, centroid, normal, divergence-theorem volume and moments) of the wall polygons in its set;
- the fluid area of each of the six faces by Green's theorem over the fluid edge intervals and the traces of its wall polygons on the face, oriented by the polygon winding: no sign test, so a wall lying in a face plane needs no special case;
- volume and centroid from the high faces and the walls (coordinates local to the cell);
- an inclusion (a closed solid inside the cell) belongs to the piece around it, found by a ray in +x from its rightmost vertex to the nearest wall, or to the +x face. A cell with one piece takes the cell totals.
Checks you can make
- Divergence theorem per cell. The aperture-weighted face (edge) normals equal the wall normal integral. In 3-D:
[(face_x(i+1) - face_x(i)) dy dz, (face_y(j+1) - face_y(j)) dz dx, (face_z(k+1) - face_z(k)) dx dy] = wet_normal. The residual is at round-off. - Covering sums. Over a block covering the body, the solid volumes (areas) add up to the body volume (area).
- Small cells. Flag the cells whose fraction is below a threshold, for example
cut%alpha < 1.e-4, the instability threshold the literature records for coarse cut cells. The small-cell treatment itself belongs to the solver.
On the turned cube of the example (6³ cells of 0.25) the covering sum is 5.55·10⁻¹⁶ and the largest divergence residual 3.22·10⁻¹⁶. The 5 small cells are cells the cube almost fills: only a corner sticks out through a face, the smallest, cell (5, 4, 3), with a fluid fraction of 1.576·10⁻⁵ (fig_ref_cut_cells_checks.f90).
The checks on a moving body, frame by frame (anim_ref_cut_cells_plate.f90): the plate cuts 9 to 18 cells, splits 3 to 8 of them into two pieces and leaves up to 7 cells with a piece below 0.1 of the cell; the covering sum stays within 7.98·10⁻¹⁷ of the plate's area in every frame.
Results
| Case | Result |
|---|---|
| 3-D: 9 sign-benchmark bodies, 13³ centres | parity inside = solid angle off the surface, every line consistent |
| 3-D: unit cube with lines along faces, through edges and vertices | no odd lines, parity right, fractions exact |
| 2-D: offset, rotated squares, 128-gon, uniform and stretched | fraction, moment, apertures, wetted length ≤ 5·10⁻¹⁵ against clipping |
| 2-D: diamond with vertices and sides through grid nodes | exact |
| 2-D: thin solid strip across a row | 2 fluid pieces per cell, areas right |
| 2-D: island, hole, island in a hole inside one cell | 1 piece, right fraction |
| 3-D faces: rotated cube, pyramid, 32-face cone | face fractions and moments ≤ 3.4·10⁻¹⁵ against half-space clipping |
| 3-D cells: axis-aligned box | fractions and moments ≤ 5·10⁻¹⁶ |
| 3-D cells: half-space | fractions ≤ 1.7·10⁻¹³ against the closed-form volume |
| 3-D cells: rotated cube, pyramid, cone | covering sums exact, per-cell divergence residual ≤ 2·10⁻¹⁶ |
| 3-D pieces: prisms (thin wedge rotated about z, square tube, L-prism), 410 cells | equal to the 2-D pieces of the section on every cell; 32 cells with 2 pieces |
| 3-D pieces: tube hole narrower than the cell; passage cutting a cell corner | 1 piece (the cell-boundary fluid alone would give 2) |
| 3-D pieces: thin plate; rods along x, y, z; void in the solid; hollow body; inclusion | 2; 1; 1; 2; 1 |
| 3-D pieces: cube on a grid through its faces, edges and corners | equal to 2-D, no cell flagged |
| 3-D pieces: bunny (open, 69451 facets), 24³ | holed cells flagged; no other cell with fluid and 0 pieces |
| 3-D piece measures: sums over the pieces vs cell totals, 16922 cells (115 with 2+ pieces; tilted wedge, cone, tube, L-prism generic and grid-aligned, plate, hollow box) | volume 5.5·10⁻¹⁵, moments 5.5·10⁻¹⁴, wall terms 3.8·10⁻¹⁵, face fractions 1.6·10⁻¹⁴ |
| 3-D piece measures: prisms vs the 2-D pieces of the section, 410 pieces | volume, first moments, ±z face fractions ≤ 1.8·10⁻¹⁴ |
| 3-D piece measures: thin plate; hollow box; inclusion in the void, above a plate, beside a wall | exact volumes (0.5 and 0.499 of the cell; 98 and 1; 0.992; 0.782; 0.792) |
orient3d: near-coplanar grid (6144 points), coplanar dyadic points | exact signs and zeros (the naive determinant is wrong on 2022) |
| line crossings, device path vs CPU | 0 mismatches (device path run on the host) |
2-D cut cells, cut_cells_device vs cut_cells: the sections of 9 benchmark bodies and 4 curves up to 1024², with and without intervals (RTX 4070) | 0 mismatches, every output bitwise (fossil_test_curve_bench 256) |
2-D cut cells resident (resident=.true., then update_host) vs cut_cells, same cases; the classification and prefix sums of the device path vs the host's, integer for integer | 0 mismatches (fossil_test_curve_bench 256, fossil_test_cut_cells_device_twin) |
| a moving ellipse and NACA 0012, 3 steps of move + tag + cut, device tags and resident cut vs the CPU at every step | 0 mismatches (cut cells 2-D chain device vs serial mismatches) |
3-D faces with the plane sections on the device (device_sections=.true.) vs the host path: bunny, cube-01, dragon-fine at 32³; stress curves as blocks of one multi-block call | 0 mismatches (cut cells 3-D sections device vs serial mismatches, fossil_test_cut_cells_blocks_twin) |
exact orient3d and line_crossing_before on the device vs the host: 31,576 quadruples (near-coplanar grids at 2^0 and 2^40, shared coordinate planes, coincident points, random) and 9,036 placements | 0 mismatches (orient3d device vs serial mismatches, fossil_test_orient3d) |
3-D node states and edge fractions on the device vs cut_cells_3d(..., edges=.true.) | 0 mismatches (cut cells 3-D nodes device vs serial mismatches, fossil_test_cut_cells_3d_device_twin) |
cut_cells_3d_device vs cut_cells_3d, every output, with and without edges, copied back and resident: bunny, cube-01, dragon-fine at 32³; sphere, cone, cube-02 at 64³ and 128³ | 0 mismatches (cut cells 3-D device vs serial mismatches, fossil_test_cut_cells_3d_device_twin) |
cut_cells_3d_device(..., walls=) vs cut_cells_3d(..., walls=), every field of the terms and the cut, without and with links, copied back and resident: the bench body at 32³; sphere and cone at 64³; on the host twin a thin plate (multi-piece cells), the open dragon and a grid off the body | 0 mismatches (cut walls 3-D device vs serial mismatches, fossil_test_cut_walls_3d_device_twin) |
| 3-D pieces: cube-01, an octahedron and 40 lattice tetrahedra on grids of step 1/8, 1/4, 1/16 (1.57 million cells) | 19 cells untrusted (947 before issue #70), none outside [0, 1]; per-piece closure 3.5·10⁻¹⁴, piece sums 1.4·10⁻¹⁴, block volume 1.6·10⁻¹⁵ |
| node parities along x, y, z on a grid-aligned cube, an octahedron, 20 lattice tetrahedra (2-D: square, diamond, 20 triangles) | 0 of 108 086 and 0 of 6358 disagree (108 and 45 before issue #69) |
| centre inside flags within 3 ulp of a tilted face: tetrahedron (3-D), triangle (2-D), quadruple-precision reference | 0 of 3168 and 0 of 3200 wrong (249 and 295 before issue #69) |
Limitations
- Zero-volume pieces. A wall lying on the high plane of a cell belongs to that cell, so the open face (aperture 1) bounds a fluid piece of zero volume. It is counted, as in 2-D, with
piece_volume0 (centroid at the cell centre); a solver can drop pieces with no volume. - Flagged cells (
pieces = -1). Cells a boundary edge of the mesh overlaps, cells whose fraction is outside [0, 1] (an open surface corrupts the face parities beyond the cells it flags), cells whose edge states do not close, and (issue #70) multi-piece cells whose split does not close: the face fractions of the pieces must add up to the plane sections, their volumes to the cell's, and every piece must close per axis. - Points exactly on the surface.
- The inside flag of a cell centre is the parity of the crossings along its x line before it. Since issue #69 "before" is exact: with n = (B − A) × (C − A), orient3d(A, B, C, P) = −n_x (c − t), so one
orient3dand the crossing's entering flag decide it (2-D: oneorient2d). A centre on the wall counts as past the crossing (taken at x + ε). Before #69 the rounded crossing position decided it, and on a tilted tetrahedron 249 of 3168 centres within 3 ulp of a face landed on the wrong side (295 of 3200 in 2-D). - One global perturbation (issue #69). Every grid point is taken at P + (ε₁, ε₂, ε₃), ε₁ ≫ ε₂ ≫ ε₃: the line kernels break ties on a projected edge or vertex in that order (on y lines x before z; before #69 each axis ordered its own pair cyclically, with no global order), and a point on a facet's plane takes the sign of the perturbed
orient3d, minus the first nonzero component of the normal. The parities of a grid node along x, y and z are then the point-in-solid test of one perturbed point and agree everywhere: 0 disagreements over 108 086 nodes of a grid-aligned cube, an octahedron and 20 lattice tetrahedra (108 before), 0 over 6358 nodes in 2-D (45 before). The 2-D sections of the 3-D cut cells keep their own (u, v) order. - Pieces on bodies through grid nodes (issue #70). Before #70, on tetrahedra with vertices on the grid nodes, the piece classification flagged up to 38 cells per body (947 of 1.57 million cells over 42 bodies and three grids): a mesh edge or vertex on a cell edge gave one piercing per incident facet. The edges now take their exact crossings, and the face traces are read on the perturbed plane: a polygon lying in the face plane bounds the fluid only if its solid lies beyond the face, and then not along the cell edges; a facet ending on the plane counts there only if the facet across its edge crosses the plane. 19 cells remain flagged, where a facet touches the cell only along a segment of a cell edge (its clipped polygon is empty, so its trace on the face is missing); the closure test flags them, none is wrong. The "fractions outside [0, 1]" seen before were 1 + 4·10⁻¹⁶, round-off of the face sums, inside the 10⁻¹² tolerance.
- The inside flag of a cell centre is the parity of the crossings along its x line before it. Since issue #69 "before" is exact: with n = (B − A) × (C − A), orient3d(A, B, C, P) = −n_x (c − t), so one
- Constructed points. The 3-D sections and the clipping decide on the rounded crossing points, consistently across kernels. A body passing exactly through grid lines at non-representable points can then give a face that does not close; it is flagged. Before issue #107 a triangle a few ulps from a y or z plane was silently wrong (above); it is now cut along that plane first. What is left: a triangle with a slope just above 10⁻³ carries a relative cell error of about 10⁻¹³, and a steep triangle sharing a near-flat edge can leave its cell untrusted (
pieces = -1, the totals right). Exact predicates on every constructed point would remove both, at the cost of every output's bits. - Watertight input. Cells whose boundary does not close (open curves or surfaces) are flagged in
closedand get no measures. - On the device: the 2-D and 3-D cut cells, their links and the 3-D wall terms.
curve%cut_cells_device,cut_cells_3d_device(withlinks=,walls=),cut_links_2d_device,cut_cells_3d(..., device_sections=.true.)and the line crossings have device paths; moments and quadrature are CPU only.