Algorithmadvanced
Mirtich's polyhedral mass properties
Also called Mirtich algorithm.
Computes the exact volume, centroid and inertia of a polyhedron by reducing volume integrals to face integrals and then to line integrals by Green's theorem.
- Time
- Θ(n) worst
- Space
- Θ(1) extra
- Where
- n = the total number of vertices over all faces (twice the number of edges)
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brian Mirtich, 1996
Mirtich's algorithm computes the volume, the center of mass and the inertia tensor of a uniform solid polyhedron from its boundary representation. It reduces each volume integral to a sum of integrals over the faces with the divergence theorem, then reduces each face integral to an integral over the projection of the face onto a coordinate plane, and then reduces that to a sum over the edges with Green's theorem. It solves the mass properties problem for polyhedra in arithmetic operations, where is the number of face vertices. The results are exact when the arithmetic is exact.
In plain words
To find the weight and the balance point of a solid, you must add up tiny pieces of the inside. A polyhedron is given only by its faces, so the method never looks at the inside. A theorem from calculus says that some sums over the inside are equal to sums over the outer skin. So the method visits each face one time.
A face is a flat polygon at an angle. The method lays it flat onto the floor or onto a wall, whichever gives the biggest shadow, and corrects for the tilt. A second theorem then turns the sum over the flat shadow into a sum along its edges. Each edge adds a short formula of the two corner coordinates. So the method is a loop over the faces and a loop over the edges of each face, with no division into small pieces.
The problem
The input is a closed polyhedral surface: a list of planar faces, each a list of vertices in . The vertices of each face are in counterclockwise order seen from outside, so the outward normal follows the right-hand rule. The surface bounds a solid with constant density . The output is
- the volume and the mass ;
- the first moments , , , and the center of mass ;
- the second moments , , and the products , , ;
- the inertia tensor about . Its diagonal entry is , and its off-diagonal entry is . The other entries follow by a cyclic shift of .
The last line is the parallel axis theorem: the tensor about the origin, minus the tensor of a point mass at .
The algorithm
Write for the unit outward normal of a face and for the constant with on the plane of . Three identities do the work.
- Divergence theorem. For a vector field , . The fields , , and give , , and . The same holds with shifted cyclically.
- Projection. Pick the coordinate with the largest and let be the next two in the cyclic order . On the face, , and . So a face integral of a polynomial becomes a combination of the projection integrals over the projected polygon , with .
- Green's theorem. . On a straight edge the line integral of a polynomial has a closed form in the two end points. For it is the shoelace formula.
MIRTICH(faces) ▷ closed surface, faces counterclockwise from outside- 1
T0 ← 0, T1 ← (0, 0, 0), T2 ← (0, 0, 0), TP ← (0, 0, 0) - 2
for each face f = (p0, ..., pk−1) do - 3
n ← the Newell normal of f, w ← −n · p0 ▷ n is outward, |n| = 2 · area(f) - 4
γ ← the axis with the largest |nγ|, (α, β) ← the next two axes in cyclic order - 5
P ← the ten projection integrals P00, ..., P03 of f on the (α, β) plane, by sums over the edges - 6
F ← the twelve face integrals of f, from P, n and w, with γ = −(nα α + nβ β + w)/nγ - 7
add the terms of f to T0, T1, T2 and TP, by the divergence theorem - 8
return T0, T1/2, T2/3, TP/2 MASS(faces, ρ)- 9
m ← ρ T0, r ← T1/T0, J ← the tensor about r by the parallel axis theorem
Line L3 does not normalize the normal. Every face integral in line L7 is multiplied by a normal component and divided by a power of in the same degree, so the length of cancels. This keeps the whole computation in the field of the input coordinates: with rational input there is no square root. Line L5 uses the signed projection integrals: the projected polygon is counterclockwise exactly when , because is a cyclic order. Dividing by the signed in line L6 then gives the factor of step 2.
Example
Take the tetrahedron with vertices , , and . Its four faces, each counterclockwise from outside, give these values.
| face | Newell normal | term of | terms of | |||
|---|---|---|---|---|---|---|
On each of the first three faces one coordinate is and the normal points along that axis, so every term vanishes. The face projects onto the plane as the triangle , counterclockwise, with area , and . On the face, , so . That is the volume , which agrees with .
Line L8 halves to , so the center of mass is , the mean of the four vertices. The second moments are and . With , line L9 gives the inertia tensor about :
For instance .
Correctness
The three identities are exact, so the algorithm returns the exact integrals when the arithmetic is exact. Step 1 is the divergence theorem applied to a polynomial field on a polyhedron. Step 2 is the change of variables from a planar face to its projection, which is one to one because . Step 3 is Green's theorem on a polygon, and the edge formulas are the exact integrals of a polynomial along a segment. The full proof derives the edge formulas and the signs.
Proof: Mirtich's reduction gives the exact volume integralsfull
Let be a bounded solid whose boundary is a closed surface made of planar faces , each a simple polygon with its vertices in counterclockwise order seen from outside. For a face, let be its Newell normal, the unit outward normal, and , so that on the plane of . We show that lines L1 to L8 return , , and .
Lemma 1 (Newell normal). is a positive multiple of , and for each coordinate with cyclic successors , is twice the signed area of the projection of onto the plane.
Proof. Take ; the other cases follow by a cyclic shift. Line L3 computes , indices mod . Expanding, . The second sum telescopes to , and the first is twice the signed area of the projected polygon by the shoelace formula. The signed area of the projection of a planar region onto the plane is the area of the region times , so .
Lemma 2 (divergence step). , , and , and the same with shifted cyclically.
Proof. A polyhedron is a bounded domain with a piecewise smooth boundary, so the divergence theorem holds for each polynomial field . The boundary is the union of the faces, which meet only along edges of zero area. Apply it to , , and , whose divergences are , , and .
The code applies Lemma 2 with the axis that fits each face. For the face with projection axes it adds , , to , and the same pattern of degree 3 to and . It uses in place of and the projection integrals in place of face integrals. Lemma 3 shows that the two changes cancel.
Lemma 3 (projection step). Let be the axis of line L4, so . For a polynomial , define at the point of the plane above , where . Let be the projected polygon and the signed integral over it (positive when is counterclockwise). Then for each axis ,
Proof. The map (the point of the plane above it) is one to one from onto , since , and its area factor is . So . By Lemma 1, is counterclockwise exactly when , so . Hence , because and differ by a positive factor.
Line L6 forms for , , , , and (and the pure powers of and ) by expanding the powers of with the binomial theorem. Each is then a polynomial in and of degree at most 3, and is a linear combination of the ten integrals , . The variable names in the code are these values divided by . The factor of Lemma 3 is the factor , or in line L7.
Lemma 4 (edge step). For a polygon with vertices in order, and , ,
Proof. Green's theorem on the polygon gives , with the boundary taken in vertex order. Take , for the first form, and , for the second. On edge write and for , so . Expand both powers by the binomial theorem. Each term is a constant times , and . This gives .
Line L5 evaluates these sums. , , , , and use the first form, and , , and the second, which is why some divisors in the code are negative. For example gives , and gives , which are the expressions and of the code.
Theorem. Lines L1 to L8 return the exact , , and of , and line L9 returns its mass, its center of mass and its inertia tensor about the center of mass.
Proof. By Lemma 4, line L5 computes the signed projection integrals exactly. By Lemma 3 and the expansion after it, line L6 and the factors of line L7 give for each face and each term that Lemma 2 needs. Line L7 adds them over all faces, and line L8 applies the factors , and of Lemma 2. So , , and are the volume integrals. For line L9, the inertia tensor about a point is and . With and , expanding gives and , which are the formulas of line L9.
Termination and cost. The loops of lines L2 and L5 run once per face and once per edge of each face, so the algorithm stops after arithmetic operations, where is the sum of the face sizes.
Complexity
For a face of vertices, lines L3 and L5 cost arithmetic operations, and lines L4, L6 and L7 cost . The total is , where is the sum of the face sizes, which is twice the number of edges. The extra space is : the algorithm keeps only the running sums. This holds in the real RAM. In exact rational arithmetic each operation costs more, but the count of operations is the same.
No algorithm can do better than in general. On a triangle mesh the volume depends on every vertex: if an algorithm does not read one coordinate, moving that vertex a little along the coordinate axis changes the volume but not the answer.
Properties
- Exact. With integer or rational coordinates every step is a ring operation or a division by . So the results are exact rationals. With integer coordinates, , , and are integers, because each equals a sum of signed tetrahedra (see Variants) with those denominators.
- Signed. If every face is reversed, every result changes sign. The volume is positive exactly when the faces are oriented outward.
- Works on non-convex solids and solids with holes. Nothing in the method uses convexity. A face may be any simple planar polygon, and a solid may have through holes and cavities, as long as the surface is closed and consistently oriented.
- Winding number. For a closed surface that intersects itself, the sums give , where is the winding number of the surface around . They are the integrals over the solid only when is or everywhere.
- Independent of the origin, in exact arithmetic. In floating point, moving the solid far from the origin causes cancellation in the third-degree terms. Translate the vertices so that one vertex is at the origin first.
Variants and improvements
- Signed tetrahedra. Fan each face into triangles and add, for each triangle , the signed tetrahedron with the origin: volume , first moment , and , where the sum is over and . This is the method of Lien and Kajiya (1984). It gives the same results and is the brute force of the tests. It needs a triangulation of each face.
- Higher moments and polynomial densities. The same three steps work for any polynomial integrand. A density of degree needs projection integrals of degree up to .
- Planar regions. In the plane, Green's theorem alone gives the area and moments of a polygon. The area is the shoelace formula of the polygon area page.
- Curved solids. For a B-rep with curved faces there is no closed form. Apply Gaussian quadrature to the face integrals of step 1, or use Monte Carlo integration with CSG ray casting or point classification.
When to use it
Use it to get the mass properties of a mesh or a polyhedral B-rep: for a rigid body simulation, for the center of gravity of a part, or to check the volume of a Boolean result. It needs a closed, consistently oriented surface with planar faces. For a triangle mesh the signed tetrahedra are shorter to code and as fast. For a mesh with holes in the surface or bad orientation, repair it first (mesh repair), or use the generalized winding number.
Pitfalls
- A fixed projection axis. If line L4 always takes , a face parallel to the axis has , and line L6 divides by zero. In floating point a face that is nearly vertical loses all accuracy. Line L4 must take the axis with the largest , so that .
- Inconsistent orientation. Line L3 takes the normal from the vertex order. One face in the wrong order adds its terms with the wrong sign, and the result is wrong with no warning. Orient all faces outward before line L2, and test that .
- Inertia about the wrong point. Lines L1 to L8 give moments about the origin. Line L9 must subtract the point mass term to get the tensor about the center of mass. The off-diagonal entries are , not .
- Non-planar faces. Line L6 assumes that the whole face lies in the plane of line L3. A face of a scanned mesh with four slightly non-coplanar vertices breaks this. Triangulate such faces first.
- Normalizing the normal. Making a unit vector in line L3 needs a square root. It adds rounding error in floating point and leaves the rationals in exact arithmetic. It is not needed, because the length cancels.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mirtich-polyhedral-mass-properties/. The authors are listed in prov/JVZRYG.jsonl.
"""Mirtich's exact volume, centroid and inertia tensor of a polyhedron.
A polyhedron is a list of faces. Each face is a list of at least three
vertices (x, y, z) that lie in one plane, in counterclockwise order when the
face is seen from outside the solid (the outward normal follows the
right-hand rule). The faces must form a closed surface. With int or Fraction
coordinates every result is an exact Fraction.
"""
from fractions import Fraction
from typing import NamedTuple, Sequence
Num = int | Fraction
Point = tuple[Num, Num, Num]
class VolumeIntegrals(NamedTuple):
t0: Fraction # integral of 1 (the volume)
t1: tuple[Fraction, Fraction, Fraction] # integrals of x, y, z
t2: tuple[Fraction, Fraction, Fraction] # integrals of x^2, y^2, z^2
tp: tuple[Fraction, Fraction, Fraction] # integrals of xy, yz, zx
def _sub(p: Point, q: Point) -> tuple[Num, Num, Num]:
return (p[0] - q[0], p[1] - q[1], p[2] - q[2])
def _cross(u: Sequence[Num], v: Sequence[Num]) -> tuple[Num, Num, Num]:
return (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0])
def face_normal(face: Sequence[Point]) -> tuple[Num, Num, Num]:
"""Newell's normal: exact, outward, of length twice the face area for a planar face."""
nx = ny = nz = 0
k = len(face)
for i in range(k):
p, q = face[i], face[(i + 1) % k]
nx += (p[1] - q[1]) * (p[2] + q[2])
ny += (p[2] - q[2]) * (p[0] + q[0])
nz += (p[0] - q[0]) * (p[1] + q[1])
return (nx, ny, nz)
def projection_integrals(face: Sequence[Point], a: int, b: int) -> dict[str, Fraction]:
"""Integrals over the projection of the face to the (a, b) plane, by Green's theorem.
Returns P1, Pa, Pb, Paa, Pab, Pbb, Paaa, Paab, Pabb, Pbbb: the integrals of
1, alpha, beta, alpha^2, ... over the projected region, signed by the
orientation of the projected boundary.
"""
p1 = pa = pb = paa = pab = pbb = paaa = paab = pabb = pbbb = Fraction(0)
k = len(face)
for i in range(k):
a0, b0 = face[i][a], face[i][b]
a1, b1 = face[(i + 1) % k][a], face[(i + 1) % k][b]
da, db = a1 - a0, b1 - b0
a0_2, a1_2, b0_2, b1_2 = a0 * a0, a1 * a1, b0 * b0, b1 * b1
a0_3, a1_3, b0_3, b1_3 = a0_2 * a0, a1_2 * a1, b0_2 * b0, b1_2 * b1
c1 = a1 + a0
ca = a1 * c1 + a0_2
caa = a1 * ca + a0_3
caaa = a1 * caa + a0_3 * a0
cb = b1 * (b1 + b0) + b0_2
cbb = b1 * cb + b0_3
cbbb = b1 * cbb + b0_3 * b0
cab = 3 * a1_2 + 2 * a1 * a0 + a0_2
kab = a1_2 + 2 * a1 * a0 + 3 * a0_2
caab = a0 * cab + 4 * a1_3
kaab = a1 * kab + 4 * a0_3
cabb = 4 * b1_3 + 3 * b1_2 * b0 + 2 * b1 * b0_2 + b0_3
kabb = b1_3 + 2 * b1_2 * b0 + 3 * b1 * b0_2 + 4 * b0_3
p1 += db * c1
pa += db * ca
paa += db * caa
paaa += db * caaa
pb += da * cb
pbb += da * cbb
pbbb += da * cbbb
pab += db * (b1 * cab + b0 * kab)
paab += db * (b1 * caab + b0 * kaab)
pabb += da * (a1 * cabb + a0 * kabb)
return {
"P1": p1 / 2, "Pa": pa / 6, "Paa": paa / 12, "Paaa": paaa / 20,
"Pb": pb / -6, "Pbb": pbb / -12, "Pbbb": pbbb / -20,
"Pab": pab / 24, "Paab": paab / 60, "Pabb": pabb / -60,
}
def volume_integrals(faces: Sequence[Sequence[Point]]) -> VolumeIntegrals:
"""Exact T0, T1, T2 and TP of a closed, outward oriented polyhedral surface.
Cost: Theta(total number of face vertices) arithmetic operations.
"""
t0 = Fraction(0) # @line L1
t1 = [Fraction(0)] * 3
t2 = [Fraction(0)] * 3
tp = [Fraction(0)] * 3
for face in faces: # @line L2
n = face_normal(face) # @line L3
w = -(n[0] * face[0][0] + n[1] * face[0][1] + n[2] * face[0][2])
c = max(range(3), key=lambda i: abs(n[i])) # @line L4
a, b = (c + 1) % 3, (c + 2) % 3
if n[c] == 0:
raise ValueError("a face has a zero normal")
P = projection_integrals(face, a, b) # @line L5
na, nb, nc = n[a], n[b], n[c]
k1 = Fraction(1) / nc # @line L6
k2, k3, k4 = k1 * k1, k1 * k1 * k1, k1 * k1 * k1 * k1
fa = k1 * P["Pa"]
fb = k1 * P["Pb"]
fc = -k2 * (na * P["Pa"] + nb * P["Pb"] + w * P["P1"])
faa = k1 * P["Paa"]
fbb = k1 * P["Pbb"]
fcc = k3 * (na * na * P["Paa"] + 2 * na * nb * P["Pab"] + nb * nb * P["Pbb"]
+ w * (2 * (na * P["Pa"] + nb * P["Pb"]) + w * P["P1"]))
faaa = k1 * P["Paaa"]
fbbb = k1 * P["Pbbb"]
fccc = -k4 * (na ** 3 * P["Paaa"] + 3 * na * na * nb * P["Paab"]
+ 3 * na * nb * nb * P["Pabb"] + nb ** 3 * P["Pbbb"]
+ 3 * w * (na * na * P["Paa"] + 2 * na * nb * P["Pab"] + nb * nb * P["Pbb"])
+ w * w * (3 * (na * P["Pa"] + nb * P["Pb"]) + w * P["P1"]))
faab = k1 * P["Paab"]
fbbc = -k2 * (na * P["Pabb"] + nb * P["Pbbb"] + w * P["Pbb"])
fcca = k3 * (na * na * P["Paaa"] + 2 * na * nb * P["Paab"] + nb * nb * P["Pabb"]
+ w * (2 * (na * P["Paa"] + nb * P["Pab"]) + w * P["Pa"]))
t0 += n[0] * (fa if a == 0 else fb if b == 0 else fc) # @line L7
t1[a] += na * faa
t1[b] += nb * fbb
t1[c] += nc * fcc
t2[a] += na * faaa
t2[b] += nb * fbbb
t2[c] += nc * fccc
tp[a] += na * faab
tp[b] += nb * fbbc
tp[c] += nc * fcca
return VolumeIntegrals( # @line L8
t0,
(t1[0] / 2, t1[1] / 2, t1[2] / 2),
(t2[0] / 3, t2[1] / 3, t2[2] / 3),
(tp[0] / 2, tp[1] / 2, tp[2] / 2),
)
class MassProperties(NamedTuple):
mass: Fraction
center: tuple[Fraction, Fraction, Fraction]
inertia: tuple[tuple[Fraction, Fraction, Fraction], ...] # about the center of mass
def mass_properties(faces: Sequence[Sequence[Point]], density: Num = 1) -> MassProperties:
"""Mass, center of mass and inertia tensor about the center of mass, for a uniform density."""
T = volume_integrals(faces)
if T.t0 == 0:
raise ValueError("the volume is zero")
m = density * T.t0 # @line L9
r = tuple(x / T.t0 for x in T.t1)
ixx = density * (T.t2[1] + T.t2[2]) - m * (r[1] ** 2 + r[2] ** 2)
iyy = density * (T.t2[2] + T.t2[0]) - m * (r[2] ** 2 + r[0] ** 2)
izz = density * (T.t2[0] + T.t2[1]) - m * (r[0] ** 2 + r[1] ** 2)
ixy = -(density * T.tp[0] - m * r[0] * r[1])
iyz = -(density * T.tp[1] - m * r[1] * r[2])
izx = -(density * T.tp[2] - m * r[2] * r[0])
inertia = ((ixx, ixy, izx), (ixy, iyy, iyz), (izx, iyz, izz))
return MassProperties(Fraction(m), (r[0], r[1], r[2]), inertia)
test_mirtich_polyhedral_mass_properties.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mirtich-polyhedral-mass-properties/. The authors are listed in prov/JVZRYG.jsonl.
import random
import unittest
from fractions import Fraction
from mirtich_polyhedral_mass_properties import mass_properties, volume_integrals
def tetra_sums(faces):
"""Brute force: fan each face into triangles and sum signed tetrahedra with the origin."""
t0 = Fraction(0)
t1 = [Fraction(0)] * 3
t2 = [Fraction(0)] * 3
tp = [Fraction(0)] * 3
for face in faces:
for k in range(1, len(face) - 1):
a, b, c = face[0], face[k], face[k + 1]
det = (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0])
+ a[2] * (b[0] * c[1] - b[1] * c[0]))
v = Fraction(det, 6)
t0 += v
s = [a[i] + b[i] + c[i] for i in range(3)]
for i in range(3):
t1[i] += v * s[i] / 4
t2[i] += v / 20 * (a[i] * a[i] + b[i] * b[i] + c[i] * c[i] + s[i] * s[i])
for i in range(3):
j = (i + 1) % 3
tp[i] += v / 20 * (a[i] * a[j] + b[i] * b[j] + c[i] * c[j] + s[i] * s[j])
return t0, tuple(t1), tuple(t2), tuple(tp)
def box(x0, y0, z0, x1, y1, z1):
v = lambda i, j, k: ((x0, x1)[i], (y0, y1)[j], (z0, z1)[k])
return [
[v(0, 0, 0), v(0, 1, 0), v(1, 1, 0), v(1, 0, 0)],
[v(0, 0, 1), v(1, 0, 1), v(1, 1, 1), v(0, 1, 1)],
[v(0, 0, 0), v(1, 0, 0), v(1, 0, 1), v(0, 0, 1)],
[v(0, 1, 0), v(0, 1, 1), v(1, 1, 1), v(1, 1, 0)],
[v(0, 0, 0), v(0, 0, 1), v(0, 1, 1), v(0, 1, 0)],
[v(1, 0, 0), v(1, 1, 0), v(1, 1, 1), v(1, 0, 1)],
]
def tetra(o, a, b, c):
return [[o, b, a], [o, a, c], [o, c, b], [a, b, c]]
DIRS = sorted({(x, y) for x in range(-3, 4) for y in range(-3, 4) if (x, y) != (0, 0)},
key=lambda d: __import__("math").atan2(d[1], d[0]))
def star_prism(rng):
"""A prism over a random star-shaped polygon (often not convex)."""
while True:
dirs = sorted(rng.sample(DIRS, rng.randint(3, 8)), key=DIRS.index)
poly = [(r * dx, r * dy) for (dx, dy), r in zip(dirs, [rng.randint(1, 4) for _ in dirs])]
area2 = sum(poly[i][0] * poly[(i + 1) % len(poly)][1] - poly[(i + 1) % len(poly)][0] * poly[i][1]
for i in range(len(poly)))
ok = all(dirs[(i + 1) % len(dirs)][0] * dirs[i][1] - dirs[(i + 1) % len(dirs)][1] * dirs[i][0] < 0
for i in range(len(dirs)))
if area2 > 0 and ok:
break
h = rng.randint(1, 5)
bottom = [(x, y, 0) for x, y in reversed(poly)]
top = [(x, y, h) for x, y in poly]
sides = []
k = len(poly)
for i in range(k):
(x0, y0), (x1, y1) = poly[i], poly[(i + 1) % k]
sides.append([(x0, y0, 0), (x1, y1, 0), (x1, y1, h), (x0, y0, h)])
return [bottom, top] + sides
def transform(faces, m, t):
f = lambda p: tuple(sum(m[i][j] * p[j] for j in range(3)) + t[i] for i in range(3))
return [[f(p) for p in face] for face in faces]
def det3(m):
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
class TestMirtich(unittest.TestCase):
def test_worked_example(self):
faces = tetra((0, 0, 0), (2, 0, 0), (0, 3, 0), (0, 0, 4))
T = volume_integrals(faces)
self.assertEqual(T.t0, 4)
self.assertEqual(T.t1, (2, 3, 4))
mp = mass_properties(faces)
self.assertEqual(mp.center, (Fraction(1, 2), Fraction(3, 4), Fraction(1)))
self.assertEqual(tuple(T), tuple(tetra_sums(faces)))
def test_unit_cube(self):
mp = mass_properties(box(0, 0, 0, 1, 1, 1))
self.assertEqual(mp.mass, 1)
self.assertEqual(mp.center, (Fraction(1, 2),) * 3)
z, s = Fraction(0), Fraction(1, 6)
self.assertEqual(mp.inertia, ((s, z, z), (z, s, z), (z, z, s)))
def test_box_density(self):
mp = mass_properties(box(1, 2, 3, 4, 4, 4), density=3)
self.assertEqual(mp.mass, 18)
self.assertEqual(mp.center, (Fraction(5, 2), Fraction(3), Fraction(7, 2)))
# I_xx = m (b^2 + c^2) / 12 with a = 3, b = 2, c = 1.
self.assertEqual(mp.inertia[0][0], Fraction(18 * 5, 12))
self.assertEqual(mp.inertia[0][1], 0)
def test_reversed_orientation_negates(self):
faces = box(0, 0, 0, 2, 3, 5)
rev = [list(reversed(f)) for f in faces]
self.assertEqual(volume_integrals(rev).t0, -30)
def test_zero_volume_raises(self):
flat = [[(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 0, 0), (0, 1, 0), (1, 0, 0)]]
with self.assertRaises(ValueError):
mass_properties(flat)
def test_random_against_tetrahedra(self):
rng = random.Random(20261114)
for trial in range(600):
kind = trial % 3
if kind == 0:
faces = star_prism(rng)
elif kind == 1:
x0, y0, z0 = (rng.randint(-5, 5) for _ in range(3))
faces = box(x0, y0, z0, x0 + rng.randint(1, 4), y0 + rng.randint(1, 4), z0 + rng.randint(1, 4))
else:
pts = [tuple(rng.randint(-6, 6) for _ in range(3)) for _ in range(4)]
o, a, b, c = pts
d = det3([[a[i] - o[i] for i in range(3)], [b[i] - o[i] for i in range(3)],
[c[i] - o[i] for i in range(3)]])
if d == 0:
continue
faces = tetra(o, a, b, c) if d > 0 else tetra(o, b, a, c)
while True:
m = [[rng.randint(-2, 2) for _ in range(3)] for _ in range(3)]
if det3(m) > 0:
break
t = [Fraction(rng.randint(-9, 9), rng.randint(1, 3)) for _ in range(3)]
faces = transform(faces, m, t)
T = volume_integrals(faces)
self.assertEqual(tuple(T), tuple(tetra_sums(faces)))
self.assertGreater(T.t0, 0)
if __name__ == "__main__":
unittest.main()
History
Lee and Requicha surveyed the methods for the volume and the moments of solids in 1982, and Lien and Kajiya gave the sum of signed tetrahedra for non-convex polyhedra in 1984. Brian Mirtich published the reduction by projection and Green's theorem in the Journal of Graphics Tools in 1996, with a C program. It was written for the dynamics of rigid bodies in simulation, where the inertia tensor of each body is needed.
References
- Brian Mirtich, Fast and accurate computation of polyhedral mass properties, Journal of Graphics Tools 1(2), 31 to 50, 1996, the whole paper (the reduction to face integrals, the projection to a coordinate plane, the Green's theorem step and the code)
- S. Lien and J. T. Kajiya, A symbolic method for calculating the integral properties of arbitrary nonconvex polyhedra, IEEE Computer Graphics and Applications 4(10), 35 to 42, 1984, the whole paper (the sum of signed tetrahedra)
- Yong Tsui Lee and Aristides A. G. Requicha, Algorithms for computing the volume and other integral properties of solids, I, Known methods and open issues, Communications of the ACM 25(9), 635 to 641, 1982, the whole paper (the survey of integration methods, including the reduction to boundary integrals)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JVZRYG Edit this page History Report an error Markdown