Algorithm Search⌘K

Algorithmadvanced

O'Brien-Hodgins brittle fracture

Also called graphical modeling of brittle fracture.

Split the stress of each finite element into tensile and compressive parts, form a separation tensor at each node, and cut the mesh there when its largest eigenvalue exceeds the toughness.

Time
Θ(n + m) forces_and_tensors · step
Space
Θ(n + m) extra
Where
m = the number of elements; n = the number of nodes
Properties
deterministicnot exactiterative
Origin
James F. O'Brien, Jessica K. Hodgins, 1999

O'Brien-Hodgins brittle fracture lets a finite element mesh crack where it is pulled apart. At every step it splits the stress of each element into a tensile part and a compressive part, and it computes the nodal forces of each part. At each node it combines these forces into a symmetric separation tensor ς\varsigma. If the largest eigenvalue of ς\varsigma is above the toughness τ\tau, the mesh is cut through the node along the line (in 3D, the plane) normal to the eigenvector, and the node is duplicated. O'Brien and Hodgins (1999) gave the method for tetrahedra; this page and its code use triangles in 2D.

In plain words

Think of a slab of glass made of many small triangles. Each triangle pulls and pushes on its corners. At each corner the method asks a simple question: do the triangles around this corner pull it apart in two opposite directions? A corner that the whole slab drags in one direction is not being torn, and a corner that is only squeezed is not being torn either. Only a pull from two sides counts. When the tearing pull is stronger than a chosen strength, the method cuts the mesh through that corner. It gives the corner a twin, so the triangles on one side of the cut use the old corner and the triangles on the other side use the new one. Then the two sides can move apart. A crack grows one corner at a time, step by step.

The problem

The input is a triangle mesh with rest positions XX, current positions xx, velocities vv, the Lamé parameters μ\mu and λ\lambda, a density, the toughness τ\tau and a time step Δt\Delta t. Each element has the rest edge matrix DmD_m with det⁡Dm>0\det D_m > 0, the current edge matrix DsD_s, F=DsDm−1F = D_s D_m^{-1}, the Green strain E=(FTF−I)/2E = (F^T F - I)/2 and the rest area V0=det⁡Dm/2V_0 = \det D_m/2. The material is the St. Venant-Kirchhoff model with the stress S=2μE+λtr⁡(E)IS = 2\mu E + \lambda\operatorname{tr}(E)I, as in the paper, which uses an isotropic linear stress of the Green strain.

The output of one step is the new state, and possibly a new mesh in which one node has been split. The method must decide where the material breaks and in which direction, from the local state only. It must not break a body that is only compressed or only translated as a whole, and the result must not depend on the orientation of the body in the world.

The algorithm

  1. FRACTURE-STEP(mesh, Δt, τ) ▷ m(a) = a a^T / |a| and m(0) = 0
  2. 1for each element: F ← D_s D_m^(-1), E ← (F^T F - I)/2, S ← 2μE + λ tr(E) I
  3. 2S+ ← Σ_i max(0, v_i) n_i n_i^T over the eigenpairs (v_i, n_i) of S, and S- ← S - S+
  4. 3f ← the nodal forces of S, f+ ← the nodal forces of S+, f- ← f - f+
  5. 4for each node a: ς_a ← ½(-m(Σ f+) + Σ m(f+) + m(Σ f-) - Σ m(f-)), the sums over the elements at a
  6. 5(a*, v+, n̂) ← the node with the largest eigenvalue v+ of ς_a, and its unit eigenvector
  7. 6if v+ > τ then SPLIT-NODE(a*, n̂)
  8. 7recompute f; v ← v + Δt f / mass; x ← x + Δt v
  9. SPLIT-NODE(a, n̂)
  10. 8for each of the two rays from x_a normal to n̂: unless the ray snaps to an existing edge, cut the element it crosses and the neighbor across the crossed edge
  11. 9sort the elements at a by the side of the line on which their centroid lies
  12. 10if both sides have elements: add a copy a' of a with the same rest position, position and velocity, and give a' the elements on the negative side
  13. 11recompute D_m^(-1), V_0 and the lumped masses

Lines L1 to L3 are Eq. 28 to 31 of the paper. The nodal forces of a stress Σ\Sigma on the nodes 1 and 2 of an element are the columns of −V0FΣDm−T-V_0 F\Sigma D_m^{-T}, and node 0 gets minus their sum. These are linear in Σ\Sigma, so f++f−=ff^+ + f^- = f. Line L4 is Eq. 32. At each node f+f^+ and f−f^- come as sets with one force per element at the node. Line L5 is the fracture test of Section 4.2, and line L6 does at most one split per step in the code of this page. The paper also handles several eigenvalues above τ\tau by splitting for the largest one, remeshing and computing again.

Lines L8 to L10 are the local remeshing of Section 4.3. A cut through an element (a,b,c)(a, b, c) from its vertex aa meets the opposite edge bcbc at a new node pp with xp=(1−s)xb+sxcx_p = (1 - s)x_b + s x_c; the rest position and the velocity of pp use the same ss. The element becomes two elements, and the neighbor across bcbc is also cut at pp, so the mesh stays conforming. The ray snaps to an existing edge when an edge from aa is within 0.1 radians of it, and the new node snaps to bb or cc when s<0.05s < 0.05 or s>0.95s > 0.95; the paper uses 5 mm and 0.1 radians. These thresholds are tuning choices. They stop tiny and thin elements, which would need a tiny time step. The new crack tips pp are not duplicated, so the crack grows one node per split.

Line L7 is symplectic Euler with a velocity damping factor in the code; the paper uses explicit integrators and a damping stress.

Example

Take a square of 2 m by 2 m made of 2 by 2 cells of 1 m, each cut into two triangles, so 8 triangles meet at the center node. Use E=1E = 1 Pa and ν=0.3\nu = 0.3, so μ=0.384615\mu = 0.384615 N/m and λ=0.576923\lambda = 0.576923 N/m, and τ=0.1\tau = 0.1 N. Each row maps the rest square by a uniform deformation; so the stress is the same in every element and the net force on the center node is zero.

Deformation x=φ(X)x = \varphi(X) eigenvalues of SS eigenvalues of ς\varsigma at the center n^\hat n split?
(1.1X1,X2)(1.1X_1, X_2) 0.1413460.141346, 0.0605770.060577 0.1554810.155481, 0.0605770.060577 (1,0)(1, 0) yes
(1.1X1,1.1X2)(1.1X_1, 1.1X_2) 0.2019230.201923, 0.2019230.201923 0.2221150.222115, 0.2221150.222115 (1,0)(1, 0), any direction yes
(0.9X1,X2)(0.9X_1, X_2) −0.054808-0.054808, −0.127885-0.127885 −0.054808-0.054808, −0.115096-0.115096 (0,1)(0, 1) no
(X1+0.2X2,X2)(X_1 + 0.2X_2, X_2) 0.0965370.096537, −0.058076-0.058076 0.1506710.150671, −0.074236-0.074236 (0.741453,0.671005)(0.741453, 0.671005) yes
R(1.1X1,X2)R(1.1X_1, X_2) with RR the rotation with cos⁡=0.8\cos = 0.8 0.1413460.141346, 0.0605770.060577 0.1554810.155481, 0.0605770.060577 (0.8,0.6)(0.8, 0.6) yes

In the first row the pull is along xx, so the crack runs vertically through the center, across the pull. In the third row all stresses are compressive, so f+=0f^+ = 0 and ς=−12∑m(f−)\varsigma = -\frac12\sum m(f^-) has no positive eigenvalue, and nothing breaks. In the fourth row, a shear, only one principal stress is tensile, and the crack normal is the principal direction of the stretch, about 42 degrees from the xx axis. In the last row the body of the first row is rotated by about 36.87 degrees: the eigenvalues of ς\varsigma are the same and n^\hat n turns with the body.

For a measurement, take a strip of 3 m by 1 m with 6 by 2 cells whose end nodes are pulled apart at 0.05 m/s each, with Δt=0.02\Delta t = 0.02 s and damping 0.5. In the test code the first split comes at step 47, 114, 212 and 364 for τ=0.02\tau = 0.02, 0.050.05, 0.10.1 and 0.20.2 N, and the strip is in two pieces at step 87, 196, 310 and 509. So a tougher material breaks later, at a larger stretch.

Correctness

The proof shows these facts, each a proved property.

  • Line L2 gives S++S−=SS^+ + S^- = S with S+S^+ positive semidefinite, S−S^- negative semidefinite and S+S−=0S^+S^- = 0, and line L3 gives f++f−=ff^+ + f^- = f.
  • The nodal forces of line L3 are the exact negative gradient of the St. Venant-Kirchhoff energy ∑eV0(μ∣E∣F2+λ2tr⁡(E)2)\sum_e V_0\bigl(\mu|E|_F^2 + \frac{\lambda}{2}\operatorname{tr}(E)^2\bigr).
  • ς\varsigma is symmetric. Under a rigid motion x↦Qx+tx \mapsto Qx + t it becomes QςQTQ\varsigma Q^T, so the eigenvalues do not change and the crack direction turns with the body.
  • At a node of only one element ς=0\varsigma = 0: a force that is not balanced by an opposite force does not open a crack.
  • If all elements at an interior node have a negative definite stress, then ς\varsigma is negative semidefinite, so a compressed body does not break. If they all have a positive definite stress, ς\varsigma is positive semidefinite.
  • Lines L8 to L11 keep the mesh conforming with every element positively oriented. They keep the positions, the total rest area, the total mass, the linear momentum and the elastic energy unchanged, so a split adds no energy.

The key step is that each term m(f)m(f) is positive semidefinite and m(Qf)=Qm(f)QTm(Qf) = Qm(f)Q^T: line L4 compares the forces one by one with their sum, so it measures pulls that cancel at the node and ignores the net force.

Proof: The stress split, the separation tensor and the local remesh of O'Brien-Hodgins fracture have the properties the method needsfull

We use the notation of the page, in 2D. An element has the nodes a0,a1,a2a_0, a_1, a_2, the rest edge matrix DmD_m with det⁡Dm>0\det D_m > 0, V0=det⁡Dm/2V_0 = \det D_m/2 and F=DsDm−1F = D_s D_m^{-1}. For a symmetric 2×22 \times 2 matrix Σ\Sigma, the nodal forces of Σ\Sigma are the columns g1,g2g_1, g_2 of G(Σ)=−V0FΣDm−TG(\Sigma) = -V_0 F\Sigma D_m^{-T} on a1a_1 and a2a_2, and g0=−g1−g2g_0 = -g_1 - g_2 on a0a_0. m(a)=aaT/∣a∣m(a) = aa^T/|a| for a≠0a \ne 0 and m(0)=0m(0) = 0.

Step 1: the stress split of lines L2 and L3

Let S=v1n1n1T+v2n2n2TS = v_1 n_1 n_1^T + v_2 n_2 n_2^T with orthonormal eigenvectors. Line L2 sets S+=∑imax⁡(0,vi)niniTS^+ = \sum_i \max(0, v_i)n_i n_i^T and S−=S−S+=∑imin⁡(0,vi)niniTS^- = S - S^+ = \sum_i \min(0, v_i)n_i n_i^T. So S+S^+ has the eigenvalues max⁡(0,vi)≥0\max(0, v_i) \ge 0 and S−S^- the eigenvalues min⁡(0,vi)≤0\min(0, v_i) \le 0, and S+S−=∑imax⁡(0,vi)min⁡(0,vi)niniT=0S^+S^- = \sum_i \max(0, v_i)\min(0, v_i)n_i n_i^T = 0, because niTnj=0n_i^T n_j = 0 for i≠ji \ne j and one of max⁡(0,vi)\max(0, v_i) and min⁡(0,vi)\min(0, v_i) is zero. If v1=v2v_1 = v_2, SS is a multiple of II and the split does not depend on the choice of the eigenvectors. G(Σ)G(\Sigma) is linear in Σ\Sigma, so G(S+)+G(S−)=G(S)G(S^+) + G(S^-) = G(S) and f++f−=ff^+ + f^- = f, the rule of line L3. □\square

Step 2: the forces are the negative gradient of the energy

The energy of an element is W=V0ψ(F)W = V_0\psi(F) with ψ=μ∣E∣F2+λ2tr⁡(E)2\psi = \mu|E|_F^2 + \frac{\lambda}{2}\operatorname{tr}(E)^2 and E=(FTF−I)/2E = (F^TF - I)/2. Then dψ=(2μE+λtr⁡(E)I):dE=S:dEd\psi = (2\mu E + \lambda\operatorname{tr}(E)I) : dE = S : dE, and dE=(dFTF+FTdF)/2dE = (dF^TF + F^TdF)/2 with SS symmetric, so dψ=(FS):dFd\psi = (FS) : dF. With Ds=[xa1−xa0, xa2−xa0]D_s = [x_{a_1} - x_{a_0},\ x_{a_2} - x_{a_0}], dF=dDsDm−1dF = dD_s D_m^{-1}, so dW=V0(FSDm−T):dDsdW = V_0 (FSD_m^{-T}) : dD_s. The column kk of dDsdD_s is dxak−dxa0dx_{a_k} - dx_{a_0}, so ∂W/∂xak=V0(FSDm−T)⋅k=−gk\partial W/\partial x_{a_k} = V_0(FSD_m^{-T})_{\cdot k} = -g_k for k=1,2k = 1, 2 and ∂W/∂xa0=g1+g2=−g0\partial W/\partial x_{a_0} = g_1 + g_2 = -g_0. Summing over the elements, the forces of line L3 are −∇∑eWe-\nabla\sum_e W_e. □\square

Step 3: the separation tensor is symmetric and rotation covariant

Each m(a)m(a) is symmetric, so ς\varsigma of line L4 is symmetric. It is positive semidefinite: for any yy, yTm(a)y=(a⋅y)2/∣a∣≥0y^Tm(a)y = (a \cdot y)^2/|a| \ge 0.

Let all positions move by x↦Qx+tx \mapsto Qx + t with a rotation QQ. Then Ds↦QDsD_s \mapsto QD_s and F↦QFF \mapsto QF. EE and SS depend on FTFF^TF only, so they do not change, and neither do S+S^+ and S−S^-. So G(Σ)↦QG(Σ)G(\Sigma) \mapsto QG(\Sigma) for Σ=S,S+\Sigma = S, S^+, and every force ff, f+f^+ and f−f^- is multiplied by QQ, as are their sums. Since ∣Qa∣=∣a∣|Qa| = |a|, m(Qa)=QaaTQT/∣a∣=Qm(a)QTm(Qa) = Qaa^TQ^T/|a| = Qm(a)Q^T. Every term of line L4 has this form, so ς↦QςQT\varsigma \mapsto Q\varsigma Q^T. This matrix has the same eigenvalues, and its eigenvectors are QniQn_i. □\square

Step 4: a node of one element

If only one element meets the node, each sum in line L4 has one term: ∑f+=f+\sum f^+ = f^+ and ∑m(f+)=m(f+)\sum m(f^+) = m(f^+), and the same for f−f^-. So ς=12(−m(f+)+m(f+)+m(f−)−m(f−))=0\varsigma = \frac12(-m(f^+) + m(f^+) + m(f^-) - m(f^-)) = 0, and line L6 never splits that node. □\square

Step 5: uniform states at an interior node

Let every element at an interior node aa have the same FF, for example because x=AX+tx = AX + t on the whole patch. We first show that the forces on aa sum to zero. By Step 2 the forces of an element are −∇W-\nabla W, and WW does not change under a cyclic relabeling of the nodes, which keeps det⁡Dm>0\det D_m > 0; so for each element ee at aa we may call aa its node a0a_0. Then the force on aa is g0=−g1−g2=V0FSDm−T1g_0 = -g_1 - g_2 = V_0FSD_m^{-T}\mathbf 1 with 1=(1,1)T\mathbf 1 = (1, 1)^T. The vector w=Dm−T1w = D_m^{-T}\mathbf 1 satisfies (Xa1−Xa)⋅w=(Xa2−Xa)⋅w=1(X_{a_1} - X_a) \cdot w = (X_{a_2} - X_a) \cdot w = 1, so it is normal to the edge opposite aa, points from aa toward that edge, and has the length 1/h1/h with the height hh of the element over that edge. Since V0=12hℓV_0 = \frac12 h\ell with the length ℓ\ell of the edge, V0w=12νeV_0w = \frac12\nu_e, where νe\nu_e is the normal of the opposite edge that points away from aa, with the length ℓ\ell. The edges opposite aa form the boundary of the patch of elements around the interior node aa, a closed polygon, and the νe\nu_e are its outward edge normals scaled by the edge lengths, so ∑eνe=0\sum_e\nu_e = 0. So ∑eg0=12FS∑eνe=0\sum_e g_0 = \frac12FS\sum_e\nu_e = 0. The same holds for S+S^+ and S−S^- in place of SS, so ∑f+=∑f−=0\sum f^+ = \sum f^- = 0 at aa.

If SS is negative definite, S+=0S^+ = 0, so all f+=0f^+ = 0 and line L4 gives ς=−12∑m(f−)\varsigma = -\frac12\sum m(f^-), which is negative semidefinite by Step 3. If SS is positive definite, S−=0S^- = 0 and ς=12∑m(f+)\varsigma = \frac12\sum m(f^+), which is positive semidefinite. So a uniformly compressed patch never splits at an interior node, for any τ≥0\tau \ge 0. □\square

Step 6: the local remesh keeps a valid mesh and the state

The cut of an edge (line L8). Let the element (v,a,b)(v, a, b) be positively oriented, and let the new node pp have Xp=(1−s)Xa+sXbX_p = (1 - s)X_a + sX_b and xp=(1−s)xa+sxbx_p = (1 - s)x_a + sx_b with 0<s<10 < s < 1. The two new elements (v,a,p)(v, a, p) and (v,p,b)(v, p, b) have the signed rest areas ss and 1−s1 - s times the area of (v,a,b)(v, a, b), so both are positive and their areas sum to the old one. The map from rest to current positions is affine on (v,a,b)(v, a, b), with the gradient FF. The new node lies on this map, because it uses the same ss in both coordinates, so the map is affine with the same FF on both new elements. So the energy density is the same, and the energy, being V0ψ(F)V_0\psi(F) summed, does not change. The neighbor (b,a,w)(b, a, w) across the edge is cut at the same pp into (b,p,w)(b, p, w) and (p,a,w)(p, a, w), with the same argument. After the two cuts, the edge abab is replaced by the edges apap and pbpb, each in two elements, and the new edges vpvp and pwpw are each in two elements, so the mesh stays conforming. If the edge abab is on the boundary, only the first cut takes place, and apap and pbpb are boundary edges.

The duplication (line L10). The copy a′a' has the same rest position, position and velocity as aa, and line L10 only renames aa to a′a' in some elements. So every element keeps its rest shape and its current shape, and the areas, the orientations and the energy do not change. An element at aa has no other copy of aa, so no element contains both aa and a′a', and no edge gets a third element.

Mass and momentum (line L11). The lumped mass of node ii is mi=∑e∋iρV0,e/3=∫ρϕi dXm_i = \sum_{e \ni i}\rho V_{0,e}/3 = \int\rho\phi_i\,dX, where ϕi\phi_i is the piecewise linear hat function of ii; this is the formula of line L11. The total mass is ρ\rho times the total area, which does not change. Let vh=∑iviϕiv_h = \sum_i v_i\phi_i be the piecewise linear velocity field. Since ∑iϕi=1\sum_i\phi_i = 1, ∑imivi=∫ρvh dX\sum_i m_iv_i = \int\rho v_h\,dX. The cut of an edge gives pp the velocity (1−s)va+svb=vh(Xp)(1 - s)v_a + sv_b = v_h(X_p), so on the new elements the linear interpolation is again vhv_h, and the duplication does not change the velocity of any element. So vhv_h is the same field after lines L8 to L10, and the linear momentum ∑imivi\sum_i m_iv_i is the same. ■\blacksquare

Complexity

Lines L1 to L3 cost a constant amount of work per element, and line L4 a constant amount per incident element of each node, so lines L1 to L5 cost Θ(n+m)\Theta(n + m) for nn nodes and mm elements. A split changes a constant number of elements near the node if the mesh stores the elements around each node; the code of this page scans the element list, which costs Θ(m)\Theta(m) per split. Line L11 is local too in a careful code; the code of this page recomputes all elements, which is also Θ(m)\Theta(m). So a step costs Θ(n+m)\Theta(n + m), and memory is Θ(n+m)\Theta(n + m). Each split adds one node and, for each of the up to two cut edges, one node and up to two elements.

Properties

  • Local and direction aware. The test at a node uses only the forces of its elements, and it gives the crack direction as well as the decision. This is proved.
  • Frame invariant. Rigid motions do not change the decision, and the direction turns with the body. This is proved.
  • No breaking in compression or in rigid motion. Proved for uniform states at interior nodes. Boundary nodes of a compressed body can have small positive eigenvalues, because their forces are not balanced; this is a measurement of the example code.
  • Conservation in the split. The split adds no energy, no area and no mass, and it keeps the linear momentum ∑mivi\sum m_i v_i, because the new velocities interpolate the old piecewise linear velocity field and a lumped mass is the integral of the density times the hat function of the node. This is proved.
  • Mesh dependent. The crack follows the mesh within the snapping thresholds and moves at most one node per step, so its speed depends on Δt\Delta t and on the element size. This is a heuristic of the method, not a law.
  • Toughness is a tuning value. τ\tau is a force, not a material constant from a test, and the right value depends on the mesh. This is a tuning choice.

Variants and improvements

  • 3D. The paper works on tetrahedra, where a cut plane through a node crosses its tetrahedra, and a cut tetrahedron usually becomes three. The decomposition and the separation tensor are the same.
  • Ductile fracture. O'Brien, Bargteil and Hodgins (2002) added plastic flow before the fracture, so metals bend and tear.
  • Particles and nonlocal models. Peridynamics breaks bonds between particles instead of cutting elements, and the material point method lets material separate on a background grid with no remeshing.
  • Other materials. The decomposition works for any stress tensor, so the elastic model can be the corotational or an invertible model, if its stress is written in the same frame as the forces.
  • Spring models. A mass-spring system can break a spring when it stretches past a limit. It is simpler, but the crack direction then depends on the springs, not on the stress.

When to use it

Use it for animation of brittle objects such as glass, ceramics, stone or frozen material, where the crack pattern should come from the stress and not from a precomputed pattern. It suits explicit simulations with small time steps, because the crack grows one node per step. For real time breaking of rigid objects, a precomputed fracture pattern is much cheaper. For engineering predictions of crack growth, use a method from fracture mechanics with a calibrated toughness; this method is a model for animation.

Pitfalls

  • Separating the stress in the wrong frame. Line L2 must split the same stress that line L3 maps to forces. Splitting a world frame stress and mapping it with FSDm−TF S D_m^{-T} mixes two frames and gives a wrong f+f^+ for a rotated body.
  • Forgetting the term m(∑f)m(\sum f). Without the first and the third terms of line L4 every node of a pulled body looks torn, including a node that the body only drags along, such as a node with one element.
  • Using ffTff^T in place of m(f)m(f) in line L4. m(f)=ffT/∣f∣m(f) = ff^T/|f| is linear in the size of the force. With ffTff^T the test is quadratic in the force, and τ\tau then has the wrong units.
  • No snapping. If line L8 always cuts, a crack near an existing edge makes very thin elements, and the explicit step of line L7 then needs a tiny Δt\Delta t or becomes unstable.
  • Cutting a crossed element but not its neighbor. If line L8 cuts only the element, the new node lies inside an edge of the neighbor, the mesh is no longer conforming, and the neighbor does not move with it.
  • Duplicating the crack tips. If line L10 also duplicates the new nodes pp, the crack opens along the whole cut at once, not one node per step, and an element can lose its connection to the rest.
  • Not recomputing after a split. If line L7 uses the forces from before line L6, the new nodes have no force, and the old masses do not match the new mesh.

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.

anim.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.

Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
  left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
  with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
  rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""

import math

# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6


# ---------------------------------------------------------------- vectors


def add(a, b):
    """Return a + b."""
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    """Return a - b."""
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    """Return s a for a number s."""
    return tuple(s * x for x in a)


def dot(a, b):
    """Return the dot product of a and b."""
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    """Return the cross product of two 3D vectors."""
    return (
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    )


def cross2(a, b):
    """Return the scalar 2D cross product a_x b_y - a_y b_x."""
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    """Return the Euclidean length of a."""
    return math.sqrt(sum(x * x for x in a))


def normalize(a):
    """Return a / |a|. Raise ValueError for the zero vector."""
    n = norm(a)
    if n == 0.0:
        raise ValueError("cannot normalize the zero vector")
    return tuple(x / n for x in a)


def lerp(a, b, t):
    """Return (1 - t) a + t b."""
    return tuple((1 - t) * x + t * y for x, y in zip(a, b))


# ---------------------------------------------------------------- matrices


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None)."""
    if m is None:
        m = n
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the vector a x as a tuple."""
    return tuple(sum(p * q for p, q in zip(row, x)) for row in a)


def transpose(a):
    """Return the transpose of a."""
    return [list(col) for col in zip(*a)]


def _lu(a):
    """Gaussian elimination with partial pivoting on a copy of a square a.

    Return (lu, perm, sign), or None if a pivot is exactly zero.
    """
    n = len(a)
    lu = [list(map(float, row)) for row in a]
    perm = list(range(n))
    sign = 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if lu[p][k] == 0.0:
            return None
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        piv = lu[k][k]
        for i in range(k + 1, n):
            f = lu[i][k] / piv
            lu[i][k] = f
            if f != 0.0:
                rk = lu[k]
                ri = lu[i]
                for j in range(k + 1, n):
                    ri[j] -= f * rk[j]
    return lu, perm, sign


def det(a):
    """Return the determinant of a square matrix."""
    n = len(a)
    if n == 1:
        return a[0][0]
    if n == 2:
        return a[0][0] * a[1][1] - a[0][1] * a[1][0]
    if n == 3:
        return (
            a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
            - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
            + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
        )
    r = _lu(a)
    if r is None:
        return 0.0
    lu, _, sign = r
    d = sign
    for i in range(n):
        d *= lu[i][i]
    return d


def _lu_solve(lu, perm, b):
    n = len(lu)
    y = [float(b[perm[i]]) for i in range(n)]
    for i in range(n):
        s = y[i]
        row = lu[i]
        for j in range(i):
            s -= row[j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        row = lu[i]
        for j in range(i + 1, n):
            s -= row[j] * y[j]
        y[i] = s / row[i]
    return y


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (returns a list) or a matrix given as a list of rows
    (returns a list of rows, one column of x per column of b).
    Raise ValueError if a is singular.
    """
    r = _lu(a)
    if r is None:
        raise ValueError("singular matrix")
    lu, perm, _ = r
    if len(b) > 0 and isinstance(b[0], (list, tuple)):
        cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
        return [list(row) for row in zip(*cols)]
    return _lu_solve(lu, perm, b)


def inv(a):
    """Return the inverse of a square matrix. Raise ValueError if singular."""
    return solve(a, eye(len(a)))


# ---------------------------------------------------------------- polar decomposition


def rot2(theta):
    """Return the 2 by 2 rotation matrix by the angle theta."""
    c, s = math.cos(theta), math.sin(theta)
    return [[c, -s], [s, c]]


def _frob(a):
    return math.sqrt(sum(x * x for row in a for x in row))


def _sym_eig3(s):
    """Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).

    Return (values, vectors), where vectors[k] is the unit eigenvector of
    values[k].
    """
    a = [list(map(float, row)) for row in s]
    v = eye(3)
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            sn = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p] = c * akp - sn * akq
                a[k][q] = sn * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k] = c * apk - sn * aqk
                a[q][k] = sn * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p] = c * vkp - sn * vkq
                v[k][q] = sn * vkp + c * vkq
    values = [a[i][i] for i in range(3)]
    vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
    return values, vectors


def polar(f, tol=1e-14, max_iter=100):
    """Return (R, S) with F = R S, det R = +1 and S symmetric.

    2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
    the rotation that maximizes trace(R^T F), and S = R^T F.
    3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
    the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
    is above 1e-2. It stops when the relative change in the Frobenius norm is
    at most tol, or after max_iter steps. The iteration gives the orthogonal
    polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
    eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
    If det F > 0, S is symmetric positive definite. If det F < 0, S is
    symmetric with one negative eigenvalue. Raise ValueError for a singular
    3 by 3 F.
    """
    n = len(f)
    if n == 2:
        theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
        r = rot2(theta)
        s = mul(transpose(r), f)
        s01 = 0.5 * (s[0][1] + s[1][0])
        s[0][1] = s[1][0] = s01
        return r, s
    if n != 3:
        raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
    x = [list(map(float, row)) for row in f]
    change = float("inf")
    for _ in range(max_iter):
        xi = inv(x)
        if change > 1e-2:
            g = math.sqrt(_frob(xi) / _frob(x))
        else:
            g = 1.0
        xit = transpose(xi)
        y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
        change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
        x = y
        if change <= tol:
            break
    u = x
    s = mul(transpose(u), f)
    s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    if det(u) < 0.0:
        values, vectors = _sym_eig3(s)
        k = min(range(3), key=lambda i: values[i])
        v = vectors[k]
        h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
        u = mul(u, h)
        s = mul(h, s)
        s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    return u, s


# ---------------------------------------------------------------- quaternions


def q_mul(p, q):
    """Return the Hamilton product p q."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    return (
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    )


def q_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return (q[0], -q[1], -q[2], -q[3])


def q_dot(p, q):
    """Return the dot product of p and q as vectors of R^4."""
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]


def q_normalize(q):
    """Return q / |q|."""
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("cannot normalize the zero quaternion")
    return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)


def q_from_axis_angle(axis, angle):
    """Return the unit quaternion of the rotation by angle about axis (any length)."""
    u = normalize(axis)
    s = math.sin(0.5 * angle)
    return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])


def q_to_mat3(q):
    """Return the 3 by 3 rotation matrix of a unit quaternion."""
    w, x, y, z = q
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
    ]


def q_rotate(q, v):
    """Return the vector part of q (0, v) q* for a unit quaternion q."""
    r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
    return (r[1], r[2], r[3])


def q_log(q):
    """Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).

    For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
    phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
    """
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("log of the zero quaternion")
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    lw = math.log(n)
    if vn == 0.0:
        return (lw, 0.0, 0.0, 0.0)
    phi = math.atan2(vn, q[0])
    f = phi / vn
    return (lw, f * q[1], f * q[2], f * q[3])


def q_exp(q):
    """Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    ew = math.exp(q[0])
    if vn == 0.0:
        return (ew, 0.0, 0.0, 0.0)
    f = ew * math.sin(vn) / vn
    return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])


def slerp(q0, q1, t):
    """Spherical linear interpolation of unit quaternions on the short arc.

    If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
    comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
    normalized linear interpolation is returned. See
    robotics/rigid-body-motion/spherical-linear-interpolation.
    """
    if q_dot(q0, q1) < 0.0:
        q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
    a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
    b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
    w = 2.0 * math.atan2(a, b)
    if w < SLERP_SMALL_ANGLE:
        return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
    s = math.sin(w)
    c0 = math.sin((1 - t) * w) / s
    c1 = math.sin(t * w) / s
    return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))


def q_from_mat3(r):
    """Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.

    Shepperd's method: take the largest of the trace, r00, r11 and r22, and
    divide by the component that it gives. See
    robotics/rigid-body-motion/shepperd-method.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
    if k == 0:
        w = math.sqrt(1.0 + t) / 2.0
        f = 4.0 * w
        q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
    elif k == 1:
        x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
        f = 4.0 * x
        q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
    elif k == 2:
        y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
        f = 4.0 * y
        q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
    else:
        z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
        f = 4.0 * z
        q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
    if q[0] < 0.0:
        q = (-q[0], -q[1], -q[2], -q[3])
    return q


# ---------------------------------------------------------------- transforms


def make_T(r, t):
    """Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
    d = len(t)
    m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
    m.append([0.0] * d + [1.0])
    return m


def T_mul(a, b):
    """Return the product a b of two homogeneous transforms."""
    return mul(a, b)


def T_inv(m):
    """Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].

    The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
    """
    d = len(m) - 1
    a = [row[:d] for row in m[:d]]
    t = [m[i][d] for i in range(d)]
    ai = inv(a)
    ti = matvec(ai, t)
    return make_T(ai, tuple(-x for x in ti))


def T_apply(m, p):
    """Apply a homogeneous transform to a point p and return a tuple."""
    d = len(m) - 1
    return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))


# ---------------------------------------------------------------- derivatives


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
brittle_fracture.py 305 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brittle-fracture/. The authors are listed in prov/PNJ37X.jsonl.
"""Brittle fracture after O'Brien and Hodgins (1999), on a 2D triangle mesh.

Each element has the St. Venant-Kirchhoff stress S = 2 mu E + lambda tr(E) I
with the Green strain E = (F^T F - I) / 2, and the nodal forces
G = -V0 F S D_m^(-T) on the nodes 1 and 2, node 0 getting minus the sum.
S is split by its eigenvalues into a tensile part S+ and a compressive part
S-, and the nodal forces of S+ are the tensile forces f+ (f- = f - f+).

At a node, with m(a) = a a^T / |a| (and m(0) = 0), the separation tensor is

    sep = 1/2 ( -m(sum f+) + sum m(f+) + m(sum f-) - sum m(f-) ),

where the sums run over the elements at the node. If its largest eigenvalue
exceeds the toughness tau, the mesh is split at the node along the line
with the eigenvector as normal: the node is duplicated, the elements that
the line crosses are cut, and their neighbours across the cut edge are cut
too, so the mesh stays conforming. The new crack tip points are not
duplicated, so a crack grows one node at a time.

The snapping thresholds, the velocity damping and the rule of at most one
split per step are tuning choices of this file.
"""

import math

from anim import det, inv, mul, transpose


def edge_matrix(p, t):
    a, b, c = p[t[0]], p[t[1]], p[t[2]]
    return [[b[0] - a[0], c[0] - a[0]], [b[1] - a[1], c[1] - a[1]]]


def sym_eig2(s):
    """Eigenvalues (larger first) and unit eigenvectors of a symmetric 2 by 2 matrix."""
    a, b, d = s[0][0], 0.5 * (s[0][1] + s[1][0]), s[1][1]
    m, r = 0.5 * (a + d), math.hypot(0.5 * (a - d), b)
    phi = 0.5 * math.atan2(2.0 * b, a - d)
    n1 = (math.cos(phi), math.sin(phi))
    return (m + r, m - r), (n1, (-n1[1], n1[0]))


def outer_m(f):
    """m(a) = a a^T / |a|, with m(0) = 0."""
    n = math.hypot(f[0], f[1])
    if n == 0.0:
        return [[0.0, 0.0], [0.0, 0.0]]
    return [[f[0] * f[0] / n, f[0] * f[1] / n], [f[1] * f[0] / n, f[1] * f[1] / n]]


def split_stress(s):
    """Return (S+, S-) with S+ + S- = S, S+ positive and S- negative semidefinite."""
    vals, vecs = sym_eig2(s)
    sp = [[0.0, 0.0], [0.0, 0.0]]
    for lam, n in zip(vals, vecs):
        if lam > 0.0:
            for i in range(2):
                for j in range(2):
                    sp[i][j] += lam * n[i] * n[j]
    sm = [[s[i][j] - sp[i][j] for j in range(2)] for i in range(2)]
    return sp, sm


class Mesh:
    """A 2D triangle mesh that can be cut. Positions are lists of [x, y]."""

    def __init__(self, rest, tris, mu, lam, density=1.0):
        self.rest = [list(map(float, p)) for p in rest]
        self.x = [list(map(float, p)) for p in rest]
        self.v = [[0.0, 0.0] for _ in rest]
        self.tris = [tuple(t) for t in tris]
        self.mu, self.lam, self.density = mu, lam, density
        self.update_rest()

    def update_rest(self):
        self.dm_inv, self.v0 = [], []
        self.mass = [0.0] * len(self.rest)
        for t in self.tris:
            dm = edge_matrix(self.rest, t)
            if det(dm) <= 0.0:
                raise ValueError("each triangle needs a positive rest orientation")
            self.dm_inv.append(inv(dm))
            self.v0.append(0.5 * det(dm))
            for a in t:
                self.mass[a] += self.density * 0.5 * det(dm) / 3.0  # @line L11


def stvk_stress(f, mu, lam):
    """S = 2 mu E + lambda tr(E) I with the Green strain E."""
    c = mul(transpose(f), f)
    e = [[0.5 * (c[i][j] - (1.0 if i == j else 0.0)) for j in range(2)] for i in range(2)]
    tr = e[0][0] + e[1][1]
    return [[2.0 * mu * e[i][j] + (lam * tr if i == j else 0.0) for j in range(2)] for i in range(2)]


def _nodal(mesh, e, f, s):
    """The three nodal forces of the stress S of element e."""
    g = mul(mul(f, s), transpose(mesh.dm_inv[e]))
    v0 = mesh.v0[e]
    g1 = (-v0 * g[0][0], -v0 * g[1][0])
    g2 = (-v0 * g[0][1], -v0 * g[1][1])
    return [(-g1[0] - g2[0], -g1[1] - g2[1]), g1, g2]


def element_forces(mesh, x=None):
    """Return (f, fplus) per element: lists of three nodal forces each."""
    x = mesh.x if x is None else x
    out = []
    for e, t in enumerate(mesh.tris):
        f = mul(edge_matrix(x, t), mesh.dm_inv[e])  # @line L1
        s = stvk_stress(f, mesh.mu, mesh.lam)
        sp, _ = split_stress(s)  # @line L2
        out.append((_nodal(mesh, e, f, s), _nodal(mesh, e, f, sp)))  # @line L3
    return out


def stvk_energy(mesh, x):
    tot = 0.0
    for e, t in enumerate(mesh.tris):
        f = mul(edge_matrix(x, t), mesh.dm_inv[e])
        c = mul(transpose(f), f)
        e00, e11, e01 = 0.5 * (c[0][0] - 1.0), 0.5 * (c[1][1] - 1.0), 0.5 * c[0][1]
        tr = e00 + e11
        tot += mesh.v0[e] * (mesh.mu * (e00 * e00 + e11 * e11 + 2 * e01 * e01) + 0.5 * mesh.lam * tr * tr)
    return tot


def separation_tensors(mesh, forces=None):
    """The separation tensor of every node. Cost Theta(n + m)."""
    forces = element_forces(mesh) if forces is None else forces
    n = len(mesh.x)
    fp = [[0.0, 0.0] for _ in range(n)]
    fm = [[0.0, 0.0] for _ in range(n)]
    sum_mp = [[[0.0, 0.0], [0.0, 0.0]] for _ in range(n)]
    sum_mm = [[[0.0, 0.0], [0.0, 0.0]] for _ in range(n)]
    for t, (f, fplus) in zip(mesh.tris, forces):
        for k, a in enumerate(t):
            p = fplus[k]
            q = (f[k][0] - p[0], f[k][1] - p[1])
            mp, mq = outer_m(p), outer_m(q)
            for i in range(2):
                fp[a][i] += p[i]
                fm[a][i] += q[i]
                for j in range(2):
                    sum_mp[a][i][j] += mp[i][j]
                    sum_mm[a][i][j] += mq[i][j]
    sep = []
    for a in range(n):  # @line L4
        mp, mq = outer_m(fp[a]), outer_m(fm[a])
        sep.append([[0.5 * (-mp[i][j] + sum_mp[a][i][j] + mq[i][j] - sum_mm[a][i][j]) for j in range(2)]
                    for i in range(2)])
    return sep


def _signed(n, origin, p):
    return n[0] * (p[0] - origin[0]) + n[1] * (p[1] - origin[1])


def _rotate_to(t, a):
    i = t.index(a)
    return t[i:] + t[:i]


def split_node(mesh, node, normal, snap_angle=0.1, snap_ratio=0.05):
    """Cut the mesh at node along the line through it with the given normal.

    Return the index of the new node, or None if all the elements at the node
    lie on one side of the line (no split is possible).
    """
    xv = mesh.x[node]
    nn = math.hypot(normal[0], normal[1])
    normal = (normal[0] / nn, normal[1] / nn)
    for ray in ((-normal[1], normal[0]), (normal[1], -normal[0])):  # @line L8
        incident = [k for k, t in enumerate(mesh.tris) if node in t]
        snapped = False
        for k in incident:
            for a in mesh.tris[k]:
                if a == node:
                    continue
                d = (mesh.x[a][0] - xv[0], mesh.x[a][1] - xv[1])
                ang = math.atan2(d[0] * ray[1] - d[1] * ray[0], d[0] * ray[0] + d[1] * ray[1])
                if abs(ang) < snap_angle:
                    snapped = True
        if snapped:
            continue
        for k in incident:
            v, a, b = _rotate_to(mesh.tris[k], node)
            da = (mesh.x[a][0] - xv[0], mesh.x[a][1] - xv[1])
            db = (mesh.x[b][0] - xv[0], mesh.x[b][1] - xv[1])
            ca = ray[0] * da[1] - ray[1] * da[0]
            cb = ray[0] * db[1] - ray[1] * db[0]
            if not (ca < 0.0 < cb):
                continue
            s = ca / (ca - cb)
            p_dir = (da[0] + s * (db[0] - da[0]), da[1] + s * (db[1] - da[1]))
            if p_dir[0] * ray[0] + p_dir[1] * ray[1] <= 0.0:
                continue
            if s < snap_ratio or s > 1.0 - snap_ratio:
                break
            _cut_edge(mesh, k, a, b, s)
            break
    side = {}
    for k, t in enumerate(mesh.tris):  # @line L9
        if node in t:
            cx = sum(mesh.x[i][0] for i in t) / 3.0
            cy = sum(mesh.x[i][1] for i in t) / 3.0
            side[k] = _signed(normal, xv, (cx, cy))
    if not any(d < 0.0 for d in side.values()) or not any(d > 0.0 for d in side.values()):
        mesh.update_rest()
        return None
    new = len(mesh.x)  # @line L10
    mesh.x.append(list(mesh.x[node]))
    mesh.rest.append(list(mesh.rest[node]))
    mesh.v.append(list(mesh.v[node]))
    for k, d in side.items():
        if d < 0.0:
            mesh.tris[k] = tuple(new if i == node else i for i in mesh.tris[k])
    mesh.update_rest()
    return new


def _cut_edge(mesh, k, a, b, s):
    """Add a node p on edge (a, b) at the parameter s and cut both triangles at the edge."""
    p = len(mesh.x)
    for arr in (mesh.x, mesh.rest, mesh.v):
        arr.append([(1.0 - s) * arr[a][i] + s * arr[b][i] for i in range(2)])
    v = _rotate_to(mesh.tris[k], a)[2]
    mesh.tris[k] = (v, a, p)
    mesh.tris.append((v, p, b))
    for j, t in enumerate(mesh.tris):
        if j != k and a in t and b in t and p not in t:
            r = _rotate_to(t, b)
            if r[1] == a:
                w = r[2]
                mesh.tris[j] = (b, p, w)
                mesh.tris.append((p, a, w))
            break


def fracture_step(mesh, dt, tau, fixed=(), prescribed=None, damping=0.0):
    """One step: forces, separation tensors, at most one split, symplectic Euler.

    prescribed maps a node to a fixed velocity. Return the new node or None.
    """
    forces = element_forces(mesh)
    sep = separation_tensors(mesh, forces)
    best, node, normal = tau, None, None
    for a, st in enumerate(sep):  # @line L5
        vals, vecs = sym_eig2(st)
        if vals[0] > best:
            best, node, normal = vals[0], a, vecs[0]
    new = None
    if node is not None:  # @line L6
        new = split_node(mesh, node, normal)
    n = len(mesh.x)
    ftot = [[0.0, 0.0] for _ in range(n)]
    for t, (f, _) in zip(mesh.tris, element_forces(mesh)):
        for k, a in enumerate(t):
            ftot[a][0] += f[k][0]
            ftot[a][1] += f[k][1]
    fixed = set(fixed)
    prescribed = prescribed or {}
    for i in range(n):  # @line L7
        if i in fixed:
            mesh.v[i] = [0.0, 0.0]
            continue
        if i in prescribed:
            mesh.v[i] = list(prescribed[i])
        else:
            mesh.v[i] = [(1.0 - damping * dt) * (mesh.v[i][k] + dt * ftot[i][k] / mesh.mass[i]) for k in range(2)]
        mesh.x[i] = [mesh.x[i][k] + dt * mesh.v[i][k] for k in range(2)]
    return new


def grid(nx, ny, w, h):
    """A rectangle of nx by ny cells, each cut into two triangles along alternating diagonals."""
    rest = [(w * i / nx, h * j / ny) for j in range(ny + 1) for i in range(nx + 1)]
    tris = []
    for j in range(ny):
        for i in range(nx):
            a = j * (nx + 1) + i
            b, c, d = a + 1, a + nx + 2, a + nx + 1
            if (i + j) % 2 == 0:
                tris += [(a, b, c), (a, c, d)]
            else:
                tris += [(a, b, d), (b, c, d)]
    return rest, tris


def components(mesh):
    """The number of connected pieces of the mesh (by shared nodes)."""
    parent = list(range(len(mesh.x)))

    def find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    for t in mesh.tris:
        for a in t[1:]:
            parent[find(a)] = find(t[0])
    return len({find(t[0]) for t in mesh.tris})
test_brittle_fracture.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brittle-fracture/. The authors are listed in prov/PNJ37X.jsonl.
"""Tests of the O'Brien-Hodgins fracture method on 2D triangle meshes.

The stress split, the forces against central differences of the energy,
the separation tensor (zero at a node of one element, rotation covariant,
along the pull in a stretched strip), the cut of the mesh (valid, area and
energy conserved), and the pulled strip that breaks later for a larger
toughness.
"""

import math
import random

import anim
from brittle_fracture import (Mesh, components, element_forces, fracture_step, grid, separation_tensors,
                              split_node, split_stress, stvk_energy, stvk_stress, sym_eig2)

MU, LAM = 0.384615, 0.576923


def mat_close(a, b, tol):
    return all(abs(a[i][j] - b[i][j]) <= tol for i in range(2) for j in range(2))


def total_forces(mesh):
    f = [[0.0, 0.0] for _ in mesh.x]
    for t, (fe, _) in zip(mesh.tris, element_forces(mesh)):
        for k, a in enumerate(t):
            f[a][0] += fe[k][0]
            f[a][1] += fe[k][1]
    return f


def test_sym_eig2_against_definition():
    rng = random.Random(1)
    for _ in range(500):
        a, b, d = rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2)
        vals, vecs = sym_eig2([[a, b], [b, d]])
        assert vals[0] >= vals[1]
        for lam, n in zip(vals, vecs):
            r = (a * n[0] + b * n[1] - lam * n[0], b * n[0] + d * n[1] - lam * n[1])
            assert math.hypot(*r) < 1e-12
        assert abs(vecs[0][0] * vecs[1][0] + vecs[0][1] * vecs[1][1]) < 1e-15


def test_stress_split():
    rng = random.Random(2)
    for _ in range(500):
        a, b, d = rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2)
        s = [[a, b], [b, d]]
        sp, sm = split_stress(s)
        assert mat_close([[sp[i][j] + sm[i][j] for j in range(2)] for i in range(2)], s, 1e-14)
        assert min(sym_eig2(sp)[0]) >= -1e-12 and max(sym_eig2(sm)[0]) <= 1e-12
        assert mat_close(anim.mul(sp, sm), [[0, 0], [0, 0]], 1e-12)


def test_force_is_minus_gradient_of_stvk_energy():
    rng = random.Random(3)
    rest, tris = grid(2, 2, 1.0, 1.0)
    mesh = Mesh(rest, tris, MU, LAM)
    for _ in range(10):
        mesh.x = [[p[0] + rng.uniform(-0.15, 0.15), p[1] + rng.uniform(-0.15, 0.15)] for p in rest]
        f = total_forces(mesh)
        g = anim.num_grad(lambda z: stvk_energy(mesh, [z[2 * i:2 * i + 2] for i in range(len(z) // 2)]),
                          [c for p in mesh.x for c in p])
        s = max(map(abs, g))
        for a, b in zip([c for p in f for c in p], g):
            assert abs(a + b) <= 1e-6 * s


def test_tensile_force_equals_force_under_pure_tension():
    mesh = Mesh([(0, 0), (1, 0), (0, 1)], [(0, 1, 2)], MU, LAM)
    mesh.x = [[0, 0], [1.2, 0.1], [0.05, 1.1]]
    (f, fp), = element_forces(mesh)
    s = stvk_stress(anim.mul([[1.2, 0.05], [0.1, 1.1]], [[1, 0], [0, 1]]), MU, LAM)
    assert min(sym_eig2(s)[0]) > 0
    for a, b in zip(f, fp):
        assert math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-14


def test_separation_tensor_is_zero_at_a_node_of_one_element():
    rng = random.Random(4)
    mesh = Mesh([(0, 0), (1, 0), (0, 1)], [(0, 1, 2)], MU, LAM)
    for _ in range(50):
        mesh.x = [[p[0] + rng.uniform(-0.3, 0.3), p[1] + rng.uniform(-0.3, 0.3)] for p in mesh.rest]
        for st in separation_tensors(mesh):
            assert mat_close(st, [[0, 0], [0, 0]], 1e-14)


def test_separation_tensor_is_rotation_covariant():
    rng = random.Random(5)
    rest, tris = grid(3, 2, 1.5, 1.0)
    mesh = Mesh(rest, tris, MU, LAM)
    mesh.x = [[p[0] * 1.1 + rng.uniform(-0.05, 0.05), p[1] + rng.uniform(-0.05, 0.05)] for p in rest]
    before = separation_tensors(mesh)
    q = anim.rot2(0.7)
    mesh.x = [list(anim.add(anim.matvec(q, p), (2.0, -1.0))) for p in mesh.x]
    after = separation_tensors(mesh)
    for a, b in zip(before, after):
        assert mat_close(anim.mul(anim.mul(q, a), anim.transpose(q)), b, 1e-12)


def test_stretched_strip_cracks_across_the_pull():
    rest, tris = grid(6, 2, 3.0, 1.0)
    mesh = Mesh(rest, tris, MU, LAM)
    mesh.x = [[1.1 * p[0], p[1]] for p in rest]
    sep = separation_tensors(mesh)
    for a, p in enumerate(rest):
        if 0.0 < p[0] < 3.0:
            vals, vecs = sym_eig2(sep[a])
            assert vals[0] > 0.0 and abs(vecs[0][0]) > 1.0 - 1e-12


def test_uniform_compression_never_breaks_an_interior_node():
    rng = random.Random(7)
    rest, tris = grid(2, 2, 2.0, 2.0)
    mesh = Mesh(rest, tris, MU, LAM)
    for sign in (-1, 1):
        for _ in range(20):
            a, b = 1 + sign * rng.uniform(0.02, 0.2), 1 + sign * rng.uniform(0.02, 0.2)
            q = anim.mul(anim.rot2(rng.uniform(0, 6.3)), anim.mul([[a, 0], [0, b]], anim.rot2(rng.uniform(0, 6.3))))
            mesh.x = [list(anim.matvec(q, p)) for p in rest]
            vals = sym_eig2(stvk_stress(q, MU, LAM))[0]
            sv = sym_eig2(separation_tensors(mesh)[4])[0]
            if sign < 0:
                assert vals[0] < 0 and sv[0] <= 1e-12
            else:
                assert vals[1] > 0 and sv[1] >= -1e-12


def check_valid(mesh, area):
    assert all(v > 0.0 for v in mesh.v0)
    assert abs(sum(mesh.v0) - area) < 1e-12
    count = {}
    for t in mesh.tris:
        for k in range(3):
            e = frozenset((t[k], t[(k + 1) % 3]))
            count[e] = count.get(e, 0) + 1
    assert max(count.values()) <= 2


def test_cut_through_an_interior_node_keeps_the_mesh_valid():
    rng = random.Random(6)
    for trial in range(20):
        rest, tris = grid(2, 2, 1.0, 1.0)
        mesh = Mesh(rest, tris, MU, LAM)
        mesh.x = [[p[0] * 1.05 + rng.uniform(-0.02, 0.02), p[1] + rng.uniform(-0.02, 0.02)] for p in rest]
        mesh.v = [[rng.uniform(-1, 1), rng.uniform(-1, 1)] for _ in rest]
        e0 = stvk_energy(mesh, mesh.x)
        p0 = [sum(m * v[k] for m, v in zip(mesh.mass, mesh.v)) for k in range(2)]
        n0, m0 = len(mesh.x), len(mesh.tris)
        ang = rng.uniform(0.0, math.pi)
        new = split_node(mesh, 4, (math.cos(ang), math.sin(ang)))
        assert new is not None
        check_valid(mesh, 1.0)
        assert abs(stvk_energy(mesh, mesh.x) - e0) < 1e-12
        assert abs(sum(mesh.mass) - 1.0) < 1e-12
        p1 = [sum(m * v[k] for m, v in zip(mesh.mass, mesh.v)) for k in range(2)]
        assert math.hypot(p1[0] - p0[0], p1[1] - p0[1]) < 1e-12
        added = len(mesh.x) - n0
        assert added in (1, 2, 3)
        # each cut edge adds one triangle on each side that has a triangle
        assert added - 1 <= len(mesh.tris) - m0 <= 2 * (added - 1)
        assert any(new in t for t in mesh.tris) and any(4 in t for t in mesh.tris)
        assert not any(new in t and 4 in t for t in mesh.tris)


def test_no_split_when_all_elements_are_on_one_side():
    mesh = Mesh([(0, 0), (1, 0), (0, 1)], [(0, 1, 2)], MU, LAM)
    assert split_node(mesh, 0, (1.0, 1.0)) is None
    assert len(mesh.x) == 3 and len(mesh.tris) == 1


def pulled_strip(tau, steps, stop_at_first=False):
    rest, tris = grid(6, 2, 3.0, 1.0)
    mesh = Mesh(rest, tris, MU, LAM)
    pres = {i: ((-0.05 if p[0] == 0.0 else 0.05), 0.0) for i, p in enumerate(rest) if p[0] in (0.0, 3.0)}
    first = None
    for it in range(steps):
        new = fracture_step(mesh, 0.02, tau, prescribed=pres, damping=0.5)
        if new is not None and first is None:
            first = it
            if stop_at_first:
                return first, None, mesh
        if components(mesh) > 1:
            return first, it, mesh
    return first, None, mesh


def test_pulled_strip_breaks_in_two():
    first, done, mesh = pulled_strip(0.02, 150)
    assert done is not None and first <= done
    check_valid(mesh, 3.0)
    xs = [p[0] for p in mesh.x]
    assert min(xs) < 0.0 and max(xs) > 3.0


def test_larger_toughness_breaks_later():
    times = [pulled_strip(tau, 150, stop_at_first=True)[0] for tau in (0.02, 0.035, 0.05)]
    assert all(t is not None for t in times)
    assert times == sorted(times) and times[0] < times[-1]
    assert pulled_strip(1e6, 150, stop_at_first=True)[0] is None

History

Terzopoulos and Fleischer (1988) let a deformable model break where its deformation passed a limit. O'Brien and Hodgins (1999) introduced the separation tensor on a finite element mesh, with the split of the stress into tensile and compressive parts and a local remesh, and they showed examples such as an adobe wall that breaks. O'Brien, Bargteil and Hodgins (2002) extended it to ductile fracture with plasticity. Later work in graphics replaced the remesh by virtual nodes, by particles or by nonlocal models, and moved the expensive work to a precomputation for interactive use.

References

  1. James F. O'Brien and Jessica K. Hodgins, Graphical modeling and animation of brittle fracture, Proceedings of SIGGRAPH 99, 137-146, Section 4.1 (Eq. 28 to 31, the tensile and compressive parts of the stress and the forces), Section 4.2 (Eq. 32, the separation tensor and the toughness test), Section 4.3 (local remeshing and the snapping thresholds of 5 mm and 0.1 radians)
  2. Eftychios Sifakis and Jernej Barbič, FEM simulation of 3D deformable solids, a practitioner's guide to theory, discretization and model reduction, SIGGRAPH 2012 Courses, article 20, the St. Venant-Kirchhoff model and the nodal forces of a linear element (general locator)

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.forces_and_tensors
  • a full proof of time.step
  • 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
  • at least three sources
  • a scene preset for the example