Algorithm Search⌘K

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)
Properties
deterministicofflineiterative
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 Θ(n)\Theta(n) arithmetic operations, where nn 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 p0,…,pk−1p_0, \ldots, p_{k-1} in R3\mathbb{R}^3. 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 VV with constant density ρ\rho. The output is

  • the volume T0=∫V1 dVT_0 = \int_V 1 \, dV and the mass m=ρT0m = \rho T_0;
  • the first moments Tx=∫Vx dVT_x = \int_V x \, dV, TyT_y, TzT_z, and the center of mass r=(Tx,Ty,Tz)/T0r = (T_x, T_y, T_z)/T_0;
  • the second moments Tx2=∫Vx2 dVT_{x^2} = \int_V x^2 \, dV, Ty2T_{y^2}, Tz2T_{z^2} and the products Txy=∫Vxy dVT_{xy} = \int_V xy \, dV, TyzT_{yz}, TzxT_{zx};
  • the inertia tensor about rr. Its diagonal entry is Jxx=ρ(Ty2+Tz2)−m(ry2+rz2)J_{xx} = \rho (T_{y^2} + T_{z^2}) - m (r_y^2 + r_z^2), and its off-diagonal entry is Jxy=−(ρTxy−mrxry)J_{xy} = -(\rho T_{xy} - m r_x r_y). The other entries follow by a cyclic shift of x,y,zx, y, z.

The last line is the parallel axis theorem: the tensor about the origin, minus the tensor of a point mass mm at rr.

The algorithm

Write n^\hat n for the unit outward normal of a face ff and ww for the constant with n^⋅p+w=0\hat n \cdot p + w = 0 on the plane of ff. Three identities do the work.

  1. Divergence theorem. For a vector field FF, ∫V∇⋅F dV=∑f∫fF⋅n^ dA\int_V \nabla \cdot F \, dV = \sum_f \int_f F \cdot \hat n \, dA. The fields (x,0,0)(x, 0, 0), (x2/2,0,0)(x^2/2, 0, 0), (x3/3,0,0)(x^3/3, 0, 0) and (x2y/2,0,0)(x^2 y/2, 0, 0) give T0=∑fn^x∫fx dAT_0 = \sum_f \hat n_x \int_f x \, dA, Tx=12∑fn^x∫fx2 dAT_x = \frac{1}{2} \sum_f \hat n_x \int_f x^2 \, dA, Tx2=13∑fn^x∫fx3 dAT_{x^2} = \frac{1}{3} \sum_f \hat n_x \int_f x^3 \, dA and Txy=12∑fn^x∫fx2y dAT_{xy} = \frac{1}{2} \sum_f \hat n_x \int_f x^2 y \, dA. The same holds with x,y,zx, y, z shifted cyclically.
  2. Projection. Pick the coordinate γ\gamma with the largest ∣n^γ∣|\hat n_\gamma| and let α,β\alpha, \beta be the next two in the cyclic order x,y,zx, y, z. On the face, γ=−(n^αα+n^ββ+w)/n^γ\gamma = -(\hat n_\alpha \alpha + \hat n_\beta \beta + w)/\hat n_\gamma, and dA=dα dβ/∣n^γ∣dA = d\alpha \, d\beta / |\hat n_\gamma|. So a face integral of a polynomial becomes a combination of the projection integrals Ppq=∫Παpβq dα dβP_{pq} = \int_\Pi \alpha^p \beta^q \, d\alpha \, d\beta over the projected polygon Π\Pi, with p+q≤3p + q \le 3.
  3. Green's theorem. Ppq=1p+1∮∂Παp+1βq dβP_{pq} = \frac{1}{p+1} \oint_{\partial \Pi} \alpha^{p+1} \beta^q \, d\beta. On a straight edge the line integral of a polynomial has a closed form in the two end points. For P00P_{00} it is the shoelace formula.
  1. MIRTICH(faces) ▷ closed surface, faces counterclockwise from outside
  2. 1T0 ← 0, T1 ← (0, 0, 0), T2 ← (0, 0, 0), TP ← (0, 0, 0)
  3. 2for each face f = (p0, ..., pk−1) do
  4. 3n ← the Newell normal of f, w ← −n · p0 ▷ n is outward, |n| = 2 · area(f)
  5. 4γ ← the axis with the largest |nγ|, (α, β) ← the next two axes in cyclic order
  6. 5P ← the ten projection integrals P00, ..., P03 of f on the (α, β) plane, by sums over the edges
  7. 6F ← the twelve face integrals of f, from P, n and w, with γ = −(nα α + nβ β + w)/nγ
  8. 7add the terms of f to T0, T1, T2 and TP, by the divergence theorem
  9. 8return T0, T1/2, T2/3, TP/2
  10. MASS(faces, ρ)
  11. 9m ← ρ 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 nγn_\gamma in the same degree, so the length of nn 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 nγ>0n_\gamma > 0, because (α,β,γ)(\alpha, \beta, \gamma) is a cyclic order. Dividing by the signed nγn_\gamma in line L6 then gives the factor 1/∣n^γ∣1/|\hat n_\gamma| of step 2.

Example

Take the tetrahedron with vertices O=(0,0,0)O = (0, 0, 0), A=(2,0,0)A = (2, 0, 0), B=(0,3,0)B = (0, 3, 0) and C=(0,0,4)C = (0, 0, 4). Its four faces, each counterclockwise from outside, give these values.

face Newell normal nn ww γ\gamma P00P_{00} term of T0T_0 terms of T1T_1
OBAO B A (0,0,−6)(0, 0, -6) 00 zz −3-3 00 (0,0,0)(0, 0, 0)
OACO A C (0,−8,0)(0, -8, 0) 00 yy −4-4 00 (0,0,0)(0, 0, 0)
OCBO C B (−12,0,0)(-12, 0, 0) 00 xx −6-6 00 (0,0,0)(0, 0, 0)
ABCA B C (12,8,6)(12, 8, 6) −24-24 xx 66 44 (4,6,8)(4, 6, 8)

On each of the first three faces one coordinate is 00 and the normal points along that axis, so every term vanishes. The face ABCABC projects onto the (y,z)(y, z) plane as the triangle (3,0),(0,4),(0,0)(3, 0), (0, 4), (0, 0), counterclockwise, with area P00=6P_{00} = 6, ∫y=6\int y = 6 and ∫z=8\int z = 8. On the face, x=(24−8y−6z)/12x = (24 - 8y - 6z)/12, so ∫Πx dy dz=(24⋅6−8⋅6−6⋅8)/12=4\int_\Pi x \, dy \, dz = (24 \cdot 6 - 8 \cdot 6 - 6 \cdot 8)/12 = 4. That is the volume T0=4T_0 = 4, which agrees with det⁡(A,B,C)/6=24/6\det(A, B, C)/6 = 24/6.

Line L8 halves T1T_1 to (2,3,4)(2, 3, 4), so the center of mass is r=(1/2,3/4,1)r = (1/2, 3/4, 1), the mean of the four vertices. The second moments are T2=(8/5,18/5,32/5)T_2 = (8/5, 18/5, 32/5) and TP=(Txy,Tyz,Tzx)=(6/5,12/5,8/5)TP = (T_{xy}, T_{yz}, T_{zx}) = (6/5, 12/5, 8/5). With ρ=1\rho = 1, line L9 gives the inertia tensor about rr:

J=(15/43/102/53/1033/52/53/539/20).J = \begin{pmatrix} 15/4 & 3/10 & 2/5 \\ 3/10 & 3 & 3/5 \\ 2/5 & 3/5 & 39/20 \end{pmatrix}.

For instance Jxx=18/5+32/5−4(9/16+1)=10−25/4=15/4J_{xx} = 18/5 + 32/5 - 4 (9/16 + 1) = 10 - 25/4 = 15/4.

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 n^γ≠0\hat n_\gamma \ne 0. 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 VV be a bounded solid whose boundary is a closed surface made of planar faces ff, each a simple polygon with its vertices in counterclockwise order seen from outside. For a face, let nn be its Newell normal, n^=n/∣n∣\hat n = n/|n| the unit outward normal, and w=−n⋅p0w = -n \cdot p_0, so that n⋅p+w=0n \cdot p + w = 0 on the plane of ff. We show that lines L1 to L8 return T0=∫V1T_0 = \int_V 1, T1=(∫Vx,∫Vy,∫Vz)T_1 = (\int_V x, \int_V y, \int_V z), T2=(∫Vx2,∫Vy2,∫Vz2)T_2 = (\int_V x^2, \int_V y^2, \int_V z^2) and TP=(∫Vxy,∫Vyz,∫Vzx)TP = (\int_V xy, \int_V yz, \int_V zx).

Lemma 1 (Newell normal). nn is a positive multiple of n^\hat n, and for each coordinate γ\gamma with cyclic successors α,β\alpha, \beta, nγn_\gamma is twice the signed area of the projection of ff onto the (α,β)(\alpha, \beta) plane.

Proof. Take γ=z\gamma = z; the other cases follow by a cyclic shift. Line L3 computes nz=∑i(xi−xi+1)(yi+yi+1)n_z = \sum_i (x_i - x_{i+1})(y_i + y_{i+1}), indices mod kk. Expanding, nz=∑i(xiyi+1−xi+1yi)+∑i(xiyi−xi+1yi+1)n_z = \sum_i (x_i y_{i+1} - x_{i+1} y_i) + \sum_i (x_i y_i - x_{i+1} y_{i+1}). The second sum telescopes to 00, 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 (α,β)(\alpha, \beta) plane is the area of the region times n^γ\hat n_\gamma, so n=2area⁡(f)n^n = 2 \operatorname{area}(f) \hat n. □\square

Lemma 2 (divergence step). T0=∑fn^x∫fx dAT_0 = \sum_f \hat n_x \int_f x \, dA, ∫Vx=12∑fn^x∫fx2 dA\int_V x = \frac{1}{2} \sum_f \hat n_x \int_f x^2 \, dA, ∫Vx2=13∑fn^x∫fx3 dA\int_V x^2 = \frac{1}{3} \sum_f \hat n_x \int_f x^3 \, dA and ∫Vxy=12∑fn^x∫fx2y dA\int_V xy = \frac{1}{2} \sum_f \hat n_x \int_f x^2 y \, dA, and the same with x,y,zx, y, z shifted cyclically.

Proof. A polyhedron is a bounded domain with a piecewise smooth boundary, so the divergence theorem ∫V∇⋅F=∫∂VF⋅n^ dA\int_V \nabla \cdot F = \int_{\partial V} F \cdot \hat n \, dA holds for each polynomial field FF. The boundary is the union of the faces, which meet only along edges of zero area. Apply it to F=(x,0,0)F = (x, 0, 0), (x2/2,0,0)(x^2/2, 0, 0), (x3/3,0,0)(x^3/3, 0, 0) and (x2y/2,0,0)(x^2 y/2, 0, 0), whose divergences are 11, xx, x2x^2 and xyxy. □\square

The code applies Lemma 2 with the axis that fits each face. For the face with projection axes (a,b,c)(a, b, c) it adds na∫xa2n_a \int x_a^2, nb∫xb2n_b \int x_b^2, nc∫xc2n_c \int x_c^2 to T1T_1, and the same pattern of degree 3 to T2T_2 and TPTP. It uses nn in place of n^\hat n and the projection integrals in place of face integrals. Lemma 3 shows that the two changes cancel.

Lemma 3 (projection step). Let γ\gamma be the axis of line L4, so nγ≠0n_\gamma \ne 0. For a polynomial gg, define g~(α,β)=g\tilde g(\alpha, \beta) = g at the point of the plane above (α,β)(\alpha, \beta), where γ=−(nαα+nββ+w)/nγ\gamma = -(n_\alpha \alpha + n_\beta \beta + w)/n_\gamma. Let Π\Pi be the projected polygon and S(⋅)S(\cdot) the signed integral over it (positive when Π\Pi is counterclockwise). Then for each axis ee,

n^e∫fg dA=nenγS(g~).\hat n_e \int_f g \, dA = \frac{n_e}{n_\gamma} S(\tilde g).

Proof. The map (α,β)↦(\alpha, \beta) \mapsto (the point of the plane above it) is one to one from Π\Pi onto ff, since nγ≠0n_\gamma \ne 0, and its area factor is 1/∣n^γ∣1/|\hat n_\gamma|. So ∫fg dA=1∣n^γ∣∫Πg~\int_f g \, dA = \frac{1}{|\hat n_\gamma|} \int_\Pi \tilde g. By Lemma 1, Π\Pi is counterclockwise exactly when nγ>0n_\gamma > 0, so ∫Πg~=sign⁡(nγ)S(g~)\int_\Pi \tilde g = \operatorname{sign}(n_\gamma) S(\tilde g). Hence n^e∫fg=n^en^γS(g~)=nenγS(g~)\hat n_e \int_f g = \frac{\hat n_e}{\hat n_\gamma} S(\tilde g) = \frac{n_e}{n_\gamma} S(\tilde g), because nn and n^\hat n differ by a positive factor. □\square

Line L6 forms g~\tilde g for g=γg = \gamma, γ2\gamma^2, γ3\gamma^3, α2β\alpha^2 \beta, β2γ\beta^2 \gamma and γ2α\gamma^2 \alpha (and the pure powers of α\alpha and β\beta) by expanding the powers of γ=−(nαα+nββ+w)/nγ\gamma = -(n_\alpha \alpha + n_\beta \beta + w)/n_\gamma with the binomial theorem. Each g~\tilde g is then a polynomial in α\alpha and β\beta of degree at most 3, and S(g~)S(\tilde g) is a linear combination of the ten integrals Ppq=S(αpβq)P_{pq} = S(\alpha^p \beta^q), p+q≤3p + q \le 3. The variable names Fa,Fbb,Fcca,…F_a, F_{bb}, F_{cca}, \ldots in the code are these values divided by nγn_\gamma. The factor nen_e of Lemma 3 is the factor nan_a, nbn_b or ncn_c in line L7.

Lemma 4 (edge step). For a polygon Π\Pi with vertices (αi,βi)(\alpha_i, \beta_i) in order, and Δαi=αi+1−αi\Delta \alpha_i = \alpha_{i+1} - \alpha_i, Δβi=βi+1−βi\Delta \beta_i = \beta_{i+1} - \beta_i,

S(αpβq)=1p+1∑iΔβi Ep+1,q(i)=−1q+1∑iΔαi Ep,q+1(i),S(\alpha^p \beta^q) = \frac{1}{p+1} \sum_i \Delta \beta_i \, E_{p+1, q}(i) = -\frac{1}{q+1} \sum_i \Delta \alpha_i \, E_{p, q+1}(i),
Es,t(i)=1s+t+1∑u=0s∑v=0t(su)(tv)(s+tu+v)αis−uαi+1uβit−vβi+1v.E_{s, t}(i) = \frac{1}{s + t + 1} \sum_{u=0}^{s} \sum_{v=0}^{t} \frac{\binom{s}{u}\binom{t}{v}}{\binom{s+t}{u+v}} \alpha_i^{s-u} \alpha_{i+1}^{u} \beta_i^{t-v} \beta_{i+1}^{v}.

Proof. Green's theorem on the polygon gives S(∂Q/∂α−∂P/∂β)=∮∂ΠP dα+Q dβS(\partial Q/\partial \alpha - \partial P/\partial \beta) = \oint_{\partial \Pi} P \, d\alpha + Q \, d\beta, with the boundary taken in vertex order. Take Q=αp+1βq/(p+1)Q = \alpha^{p+1}\beta^q/(p+1), P=0P = 0 for the first form, and P=−αpβq+1/(q+1)P = -\alpha^p \beta^{q+1}/(q+1), Q=0Q = 0 for the second. On edge ii write α=(1−τ)αi+ταi+1\alpha = (1 - \tau)\alpha_i + \tau \alpha_{i+1} and β=(1−τ)βi+τβi+1\beta = (1 - \tau)\beta_i + \tau \beta_{i+1} for τ∈[0,1]\tau \in [0, 1], so dβ=Δβi dτd\beta = \Delta \beta_i \, d\tau. Expand both powers by the binomial theorem. Each term is a constant times τu+v(1−τ)s+t−u−v\tau^{u+v}(1 - \tau)^{s+t-u-v}, and ∫01τj(1−τ)N−jdτ=j!(N−j)!(N+1)!=1(N+1)(Nj)\int_0^1 \tau^{j}(1 - \tau)^{N - j} d\tau = \frac{j! (N - j)!}{(N + 1)!} = \frac{1}{(N + 1)\binom{N}{j}}. This gives ∫01αsβtdτ=Es,t(i)\int_0^1 \alpha^s \beta^t d\tau = E_{s,t}(i). □\square

Line L5 evaluates these sums. P00P_{00}, P10P_{10}, P20P_{20}, P30P_{30}, P11P_{11} and P21P_{21} use the first form, and P01P_{01}, P02P_{02}, P03P_{03} and P12P_{12} the second, which is why some divisors in the code are negative. For example E1,0(i)=12(αi+αi+1)E_{1,0}(i) = \frac{1}{2}(\alpha_i + \alpha_{i+1}) gives P00=12∑iΔβi(αi+αi+1)P_{00} = \frac{1}{2} \sum_i \Delta \beta_i (\alpha_i + \alpha_{i+1}), and E2,0(i)=13(αi2+αiαi+1+αi+12)E_{2,0}(i) = \frac{1}{3}(\alpha_i^2 + \alpha_i \alpha_{i+1} + \alpha_{i+1}^2) gives P10=16∑iΔβi(αi2+αiαi+1+αi+12)P_{10} = \frac{1}{6} \sum_i \Delta \beta_i (\alpha_i^2 + \alpha_i \alpha_{i+1} + \alpha_{i+1}^2), which are the expressions C1C_1 and CαC_\alpha of the code.

Theorem. Lines L1 to L8 return the exact T0T_0, T1T_1, T2T_2 and TPTP of VV, 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 n^e∫fg dA\hat n_e \int_f g \, dA for each face and each term that Lemma 2 needs. Line L7 adds them over all faces, and line L8 applies the factors 12\frac{1}{2}, 13\frac{1}{3} and 12\frac{1}{2} of Lemma 2. So T0T_0, T1T_1, T2T_2 and TPTP are the volume integrals. For line L9, the inertia tensor about a point rr is Jxx=ρ∫V((y−ry)2+(z−rz)2)J_{xx} = \rho \int_V ((y - r_y)^2 + (z - r_z)^2) and Jxy=−ρ∫V(x−rx)(y−ry)J_{xy} = -\rho \int_V (x - r_x)(y - r_y). With r=T1/T0r = T_1/T_0 and m=ρT0m = \rho T_0, expanding gives ρ∫V(y−ry)2=ρTy2−2ρryTy+mry2=ρTy2−mry2\rho \int_V (y - r_y)^2 = \rho T_{y^2} - 2 \rho r_y T_y + m r_y^2 = \rho T_{y^2} - m r_y^2 and ρ∫V(x−rx)(y−ry)=ρTxy−mrxry\rho \int_V (x - r_x)(y - r_y) = \rho T_{xy} - m r_x r_y, which are the formulas of line L9. ■\blacksquare

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 Θ(n)\Theta(n) arithmetic operations, where nn is the sum of the face sizes.

Complexity

For a face of kk vertices, lines L3 and L5 cost Θ(k)\Theta(k) arithmetic operations, and lines L4, L6 and L7 cost O(1)O(1). The total is Θ(n)\Theta(n), where nn is the sum of the face sizes, which is twice the number of edges. The extra space is Θ(1)\Theta(1): 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 Ω(n)\Omega(n) 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 nγ≠0n_\gamma \ne 0. So the results are exact rationals. With integer coordinates, 6T06 T_0, 24Tx24 T_x, 120Tx2120 T_{x^2} and 120Txy120 T_{xy} 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 ∫ω(p)g(p) dp\int \omega(p) g(p) \, dp, where ω\omega is the winding number of the surface around pp. They are the integrals over the solid only when ω\omega is 00 or 11 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 (a,b,c)(a, b, c), the signed tetrahedron with the origin: volume det⁡(a,b,c)/6\det(a, b, c)/6, first moment V4(a+b+c)\frac{V}{4}(a + b + c), and ∫xixj dV=V20(∑vvivj+sisj)\int x_i x_j \, dV = \frac{V}{20}\left(\sum_v v_i v_j + s_i s_j\right), where the sum is over a,b,ca, b, c and s=a+b+cs = a + b + c. 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 ρ(x,y,z)\rho(x, y, z) of degree dd needs projection integrals of degree up to d+3d + 3.
  • 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 γ=z\gamma = z, a face parallel to the zz axis has nz=0n_z = 0, 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 ∣nγ∣|n_\gamma|, so that ∣n^γ∣≥1/3|\hat n_\gamma| \ge 1/\sqrt{3}.
  • 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 T0>0T_0 > 0.
  • Inertia about the wrong point. Lines L1 to L8 give moments about the origin. Line L9 must subtract the point mass term m(ry2+rz2)m(r_y^2 + r_z^2) to get the tensor about the center of mass. The off-diagonal entries are −∫xy-\int xy, not +∫xy+\int xy.
  • 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 nn 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.

mirtich_polyhedral_mass_properties.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example