Algorithm Search⌘K

Algorithmadvanced

Parting line generation

Also called parting curve computation.

Finds the curve on a part where the two mold halves meet, from the silhouette in the parting direction, chosen to be flat and to avoid undercuts.

Time
O(N) worst
Space
O(N) extra
Where
N = total number of vertex places in all faces (twice the number of edges)
Properties
deterministicexactiterative
Origin
M. W. Fu, A. Y. C. Nee, J. Y. H. Fuh, 2002

Parting line generation finds, for a part and a chosen parting direction dd, the closed curves on the part where the two halves of a mold meet. One half of the mold moves along +d+d and the other along −d-d. Each face of the part must be formed by the half that it faces, so the faces split into upper faces, with n⋅d>0n \cdot d > 0, and lower faces, with n⋅d<0n \cdot d < 0, and the parting line runs along the edges between the two sets. For a polyhedral part these are the silhouette edges for the direction dd. The algorithm on this page computes the face signs exactly, finds the edges between an upper and a lower face, and chains them into oriented loops in O(N)O(N) time. On a convex polyhedron in general position the result is one simple closed cycle, and the page proves this. On other parts there can be several loops, and the planner must choose among them or change the part. This page differs from mold parting direction, which chooses dd, and from undercut detection, which finds the faces that neither half can release.

In plain words

A plastic or cast part is made in a mold with two halves that come apart. Each surface of the part must be formed by the half on its side, so that the half can pull away. Surfaces that face up go to the upper half, and surfaces that face down go to the lower half. The line where the two kinds of surfaces meet is where the halves touch. That is the parting line.

The algorithm looks at each face once to see which way it faces. Then it walks around the region of upward faces and records its border, one loop at a time. On a simple convex part there is exactly one loop. On a part with holes or pockets there can be more, and the designer must choose.

The problem

Input. A closed, oriented polyhedral surface (a manifold mesh): vertices with integer coordinates and faces as lists of vertex indices, counterclockwise seen from outside, each edge in exactly two faces. A parting direction d≠0d \ne 0 with integer coordinates. A rule zero_side that puts each face with n⋅d=0n \cdot d = 0 on the lower side (the default) or the upper side.

Output. The boundary of the union UU of the upper faces, as a list of closed loops of vertices. Each loop is oriented with the upper faces on its left, seen from outside, and each edge between an upper and a lower face is in exactly one loop.

Faces with n⋅d=0n \cdot d = 0. A vertical face has zero draft and can go to either half. The rule zero_side makes the choice explicit. With the default, the loops run along the top edges of vertical walls. With the other choice, they run along the bottom edges. A real design gives such faces a draft first (see draft angle analysis).

The algorithm

The algorithm uses the half-edges of the mesh, as in a doubly connected edge list. The twin of the half-edge (u,v)(u, v) is (v,u)(v, u), which lies in the other face of the edge. For a half-edge hh of a face ff, succ(h)\mathrm{succ}(h) is the next half-edge of ff.

  1. PARTING-LOOPS(V, F, d, zero_side)
  2. 1for each face f: n_f ← Newell normal of f; s_f ← sign(n_f · d), or zero_side if n_f · d = 0
  3. 2for each half-edge h = (u, v) of each face f: face[h] ← f; succ[h] ← the half-edge after h in f
  4. 3B ← the half-edges h = (u, v) of upper faces whose twin (v, u) lies in a lower face
  5. 4for each h ∈ B: g ← succ[h]
  6. 5while the twin of g lies in an upper face: g ← succ[twin of g]
  7. 6next[h] ← g
  8. 7for each h ∈ B not yet used: follow next from h until it returns, mark the half-edges used, and record their start vertices as one loop
  9. 8return the loops

Line L1. The Newell normal of a face with vertices p0,…,pk−1p_0, \dots, p_{k-1} has the components ∑i(yi−yi+1)(zi+zi+1)\sum_i (y_i - y_{i+1})(z_i + z_{i+1}) and the two cyclic shifts of it. For a planar face it is the outward normal times twice the area. On integer input it is an integer vector, so the sign of nf⋅dn_f \cdot d is exact. A normal from the first three vertices fails on a face whose first three vertices are collinear, and a floating point normal can give the wrong sign on a face that is almost vertical.

Lines L4 to L6. Let h=(u,v)h = (u, v) be a boundary half-edge in the upper face ff. The next boundary half-edge starts at vv. Line L4 takes the half-edge of ff that leaves vv. If its twin is in an upper face f′f', the boundary does not go that way, and line L5 crosses into f′f' and takes the half-edge of f′f' that leaves vv. This turns around vv through the upper faces, until it reaches a half-edge whose other side is lower. At a vertex where the upper region touches itself, with two boundary arcs through one vertex, the turn takes the first exit in the order around vv, so the loops never cross.

Example

The square pyramid with base [−1,1]2[-1, 1]^2 at z=0z = 0 and apex (0,0,2)(0, 0, 2), and d=(1,0,1)d = (1, 0, 1). The vertices are 0=(−1,−1,0)0 = (-1, -1, 0), 1=(1,−1,0)1 = (1, -1, 0), 2=(1,1,0)2 = (1, 1, 0), 3=(−1,1,0)3 = (-1, 1, 0) and 4=(0,0,2)4 = (0, 0, 2).

face vertices Newell normal n⋅dn \cdot d side
base 0, 3, 2, 1 (0,0,−8)(0, 0, -8) −8-8 lower
−y-y 0, 1, 4 (0,−4,2)(0, -4, 2) 22 upper
+x+x 1, 2, 4 (4,0,2)(4, 0, 2) 66 upper
+y+y 2, 3, 4 (0,4,2)(0, 4, 2) 22 upper
−x-x 3, 0, 4 (−4,0,2)(-4, 0, 2) −2-2 lower

Line L3 finds the half-edges (0,1)(0, 1), (4,0)(4, 0) in face −y-y, (1,2)(1, 2) in face +x+x, and (2,3)(2, 3), (3,4)(3, 4) in face +y+y. Lines L4 to L6:

hh first gg (L4) turns at L5 next[h]\mathrm{next}[h]
(0,1)(0, 1) (1,4)(1, 4), twin in +x+x (1,2)(1, 2), twin in base (1,2)(1, 2)
(1,2)(1, 2) (2,4)(2, 4), twin in +y+y (2,3)(2, 3), twin in base (2,3)(2, 3)
(2,3)(2, 3) (3,4)(3, 4), twin in −x-x none (3,4)(3, 4)
(3,4)(3, 4) (4,2)(4, 2), twin in +x+x (4,1)(4, 1), twin in −y-y; then (4,0)(4, 0), twin in −x-x (4,0)(4, 0)
(4,0)(4, 0) (0,1)(0, 1), twin in base none (0,1)(0, 1)

Line L7 gives one loop 0,1,2,3,40, 1, 2, 3, 4: three edges of the base and two slanted edges to the apex. The loop is not planar, so the mold needs a stepped parting surface. Its projection along dd is the boundary of the projection of the pyramid, as the theorem below says. The tests check this example, a box with vertical walls under both zero_side rules, and random cases.

Correctness

Theorem 1. PARTING-LOOPS returns loops in which every edge between an upper and a lower face occurs exactly once, oriented with the upper face on its left, and every loop is closed.

The sign at line L1 is exact. Line L3 keeps exactly one half-edge of each edge between an upper and a lower face: the half-edge in the upper face. The turn at lines L4 to L6 ends, because the edge {u,v}\{u, v\} of hh has a lower face on its other side, so the turn around vv meets a lower face before it can come back to ff. The map next\mathrm{next} is a bijection of BB: the turn the other way around uu undoes it. So next\mathrm{next} is a permutation of the finite set BB, its cycles are closed, and line L7 records each cycle once.

Theorem 2. Let PP be a convex polyhedron and dd a direction with nf⋅d≠0n_f \cdot d \ne 0 for every face. Then the silhouette edges form one simple closed cycle, and PARTING-LOOPS returns exactly one loop, with no repeated vertex.

The proof projects along dd. The projection maps the union UU of the upper faces one to one onto the projected polygon QQ, because each line parallel to dd leaves PP through an upper face and meets no other upper face. Each silhouette edge lies in a supporting plane of PP that is parallel to dd, so it projects into the boundary of QQ. A point of UU off the silhouette has only upper faces around it, so no supporting plane parallel to dd passes through it, and it projects into the interior of QQ. So the projection maps the silhouette onto the boundary of the convex polygon QQ, a simple closed curve, without folds. The silhouette edge page proves the weaker fact that the edges form closed loops on any closed mesh. The full proofs are below.

Proof: PARTING-LOOPS returns the boundary loops of the upper faces, and one simple cycle on a convex polyhedronfull

We use the definitions of the page. The mesh is closed and oriented: each half-edge (u,v)(u, v) lies in exactly one face, its twin (v,u)(v, u) lies in exactly one other face, and the faces around each vertex form one cycle (a manifold vertex). A face ff is upper if sf=+1s_f = +1 and lower if sf=−1s_f = -1, after line L1. BB is the set of half-edges of upper faces whose twins lie in lower faces.

Lemma 1 (exact signs). For a planar face with vertices p0,…,pk−1p_0, \dots, p_{k-1} in counterclockwise order seen from outside, the Newell vector n=∑i(yi−yi+1)(zi+zi+1,… )n = \sum_i (y_i - y_{i+1})(z_i + z_{i+1}, \dots) equals ∑ipi×pi+1\sum_i p_i \times p_{i+1}, which is twice the vector area of the face and points outward. On integer input it is an integer vector, so line L1 computes the sign of nf⋅dn_f \cdot d with no error.

Proof. Expand the first component of pi×pi+1p_i \times p_{i+1}: it is yizi+1−ziyi+1y_i z_{i+1} - z_i y_{i+1}. The term of the Newell sum is (yi−yi+1)(zi+zi+1)=yizi−yi+1zi+1+yizi+1−yi+1zi(y_i - y_{i+1})(z_i + z_{i+1}) = y_i z_i - y_{i+1} z_{i+1} + y_i z_{i+1} - y_{i+1} z_i. The first two terms cancel in the cyclic sum. The other components are the same with the coordinates shifted. The vector 12∑ipi×pi+1\frac12 \sum_i p_i \times p_{i+1} is the vector area of a closed polygon, which for a planar polygon is its area times its unit normal, with the orientation of the vertex order. □\square

Lemma 2 (the turn ends). For h=(u,v)∈Bh = (u, v) \in B in the upper face ff, the loop of lines L4 and L5 ends after at most deg⁡(v)\deg(v) steps, at a half-edge g=(v,w)g = (v, w) of an upper face whose twin lies in a lower face.

Proof. Let f0=f,f1,f2,…f_0 = f, f_1, f_2, \dots be the faces around vv in the order in which the loop visits them. Line L4 takes the half-edge g0=(v,w0)g_0 = (v, w_0) of f0f_0 that leaves vv. If the twin (w0,v)(w_0, v) lies in an upper face f1f_1, line L5 sets g1=succ(w0,v)=(v,w1)g_1 = \mathrm{succ}(w_0, v) = (v, w_1), the half-edge of f1f_1 that leaves vv, and so on. Each step crosses one edge at vv and moves to the next face in the cyclic order around vv. The faces around vv form one cycle, and the edge {u,v}\{u, v\} is in it, with ff on one side and the lower face of (v,u)(v, u) on the other. Going around vv from ff, the loop reaches the edge {u,v}\{u, v\} from the side of the lower face only after it has passed that lower face, so it stops at the latest at the edge just before the lower face. Every face it visits is upper, since it only crosses into a face when that face is upper. □\square

Lemma 3 (next is a permutation of BB). The map h↦next[h]h \mapsto \mathrm{next}[h] is a bijection from BB to BB.

Proof. By Lemma 2, next[h]∈B\mathrm{next}[h] \in B. Define prev\mathrm{prev} by the same turn in the opposite direction: for g=(v,w)∈Bg = (v, w) \in B in the upper face f′f', take the half-edge of f′f' that enters vv; while its twin lies in an upper face, cross into that face and take its half-edge that enters vv. This visits, in reverse order, exactly the upper faces that the turn from hh to gg visited, because both turns move between the same consecutive faces around vv and both stop at the first lower face. So prev(next[h])=h\mathrm{prev}(\mathrm{next}[h]) = h, and next\mathrm{next} is injective. An injective map of a finite set to itself is a bijection. □\square

Theorem 1. PARTING-LOOPS returns loops that are closed, in which every edge between an upper face and a lower face occurs exactly once, with the upper face on its left.

Proof. Each edge between an upper and a lower face has exactly one half-edge in an upper face, and line L3 keeps exactly that one, with the upper face on its left by the orientation of the faces. By Lemma 3, next\mathrm{next} is a permutation of BB, so BB splits into disjoint cycles. Line L7 starts at each half-edge not yet used and follows next\mathrm{next}. In a permutation the orbit of hh returns to hh before it repeats any other element, so line L7 records exactly the cycle of hh and marks it used. Each half-edge of BB is in exactly one recorded cycle. Consecutive half-edges h=(u,v)h = (u, v) and next[h]=(v,w)\mathrm{next}[h] = (v, w) share the vertex vv, so the start vertices form a closed loop. □\square

Theorem 2. Let PP be a convex polyhedron (a bounded 3-dimensional convex polytope) whose faces are its facets, and let d≠0d \ne 0 with nf⋅d≠0n_f \cdot d \ne 0 for every facet ff. Let SS be the union of the silhouette edges. Then SS is homeomorphic to a circle. So the silhouette edges form one simple cycle, and PARTING-LOOPS returns one loop with no repeated vertex.

Proof. Write P={x:nf⋅x≤cf for all facets f}P = \{x : n_f \cdot x \le c_f \text{ for all facets } f\}. Let UU be the union of the closed upper facets and LL the union of the closed lower facets. Let π\pi be the orthogonal projection onto the plane HH through the origin normal to dd, and Q=π(P)Q = \pi(P). QQ is a convex polygon with nonempty interior in HH, since PP has nonempty interior.

Step 1: S=U∩LS = U \cap L. A point in the relative interior of an edge lies in exactly the two facets of that edge, and a point in the relative interior of a facet lies only in that facet. So a point of U∩LU \cap L that is not a vertex lies on an edge between an upper and a lower facet. If a vertex vv is in U∩LU \cap L, the facets around vv in cyclic order include both kinds, so the sign changes at least twice around vv, at edges between consecutive facets, and these are silhouette edges through vv. So U∩L⊆SU \cap L \subseteq S, and S⊆U∩LS \subseteq U \cap L is clear.

Step 2: π\pi restricted to UU is a homeomorphism onto QQ. Take y∈Qy \in Q. The line π−1(y)\pi^{-1}(y) meets PP in a segment with a highest point bb in the direction dd. For small ε>0\varepsilon > 0, b+εd∉Pb + \varepsilon d \notin P. The facets not through bb have slack at bb, so some facet ff through bb has nf⋅(b+εd)>cfn_f \cdot (b + \varepsilon d) > c_f, that is nf⋅d>0n_f \cdot d > 0: ff is upper and b∈Ub \in U. If another point p=b−tdp = b - t d with t>0t > 0 of the segment lay on an upper facet gg, then ng⋅p=cgn_g \cdot p = c_g and ng⋅b=cg+t ng⋅d>cgn_g \cdot b = c_g + t\, n_g \cdot d > c_g, which contradicts b∈Pb \in P. So each y∈Qy \in Q has exactly one preimage in UU. The map π∣U\pi|_U is a continuous bijection from a compact set to a Hausdorff space, so it is a homeomorphism.

Step 3: π(S)⊆∂Q\pi(S) \subseteq \partial Q. Let xx lie on an edge between the upper facet ff and the lower facet gg. Set m=(nf⋅d) ng−(ng⋅d) nfm = (n_f \cdot d)\, n_g - (n_g \cdot d)\, n_f. The two coefficients are positive, and nf,ngn_f, n_g are not parallel, so m≠0m \ne 0, and m⋅d=0m \cdot d = 0. For every p∈Pp \in P, m⋅p≤(nf⋅d)cg−(ng⋅d)cf=m⋅xm \cdot p \le (n_f \cdot d) c_g - (n_g \cdot d) c_f = m \cdot x. Since m⊥dm \perp d, m⋅π(p)=m⋅pm \cdot \pi(p) = m \cdot p, so the nonzero linear function mm on HH has its maximum over QQ at π(x)\pi(x), and π(x)∈∂Q\pi(x) \in \partial Q.

Step 4: π(U∖S)⊆int⁡Q\pi(U \setminus S) \subseteq \operatorname{int} Q. Let x∈U∖Sx \in U \setminus S. By Step 1, every facet through xx is upper. Suppose π(x)∈∂Q\pi(x) \in \partial Q. Then some m∈Hm \in H, m≠0m \ne 0, has m⋅π(x)≥m⋅ym \cdot \pi(x) \ge m \cdot y for all y∈Qy \in Q, so m⋅x≥m⋅pm \cdot x \ge m \cdot p for all p∈Pp \in P, since m⊥dm \perp d. So mm is in the normal cone of PP at xx, which is the cone generated by the normals of the facets through xx: m=∑fλfnfm = \sum_f \lambda_f n_f with λf≥0\lambda_f \ge 0, not all zero. Then m⋅d=∑fλf(nf⋅d)>0m \cdot d = \sum_f \lambda_f (n_f \cdot d) > 0, which contradicts m⋅d=0m \cdot d = 0.

Step 5. By Steps 2 to 4, π∣U\pi|_U is a homeomorphism that maps SS into ∂Q\partial Q and U∖SU \setminus S into int⁡Q\operatorname{int} Q. It is onto QQ, so every point of ∂Q\partial Q has its preimage in SS. So π∣S\pi|_S is a homeomorphism from SS onto ∂Q\partial Q, the boundary of a convex polygon with nonempty interior, which is a simple closed curve. A graph whose underlying space is homeomorphic to a circle is connected and has degree 2 at every vertex, so it is one simple cycle.

The algorithm. Each vertex of SS has exactly two silhouette edges, one half-edge in BB entering it and one leaving it, so next\mathrm{next} has no choice to make and follows the cycle. The cycle is connected, so by Theorem 1 line L7 records it as one loop, and each vertex of the cycle appears once. ■\blacksquare

Complexity

Let NN be the sum of the face sizes, which is 2E2E for EE edges. Line L1 costs O(N)O(N), line L2 builds two hash maps of NN entries, and line L3 is one pass. In lines L4 to L6, the turns around a vertex vv that start from different boundary half-edges cover disjoint runs of upper faces around vv, so the total number of steps at line L5 is at most the sum of the vertex degrees, O(N)O(N). Line L7 visits each half-edge of BB once. So the time is O(N)O(N) expected with hashing, or O(N)O(N) worst case with a mesh structure that stores the twins. The extra space is O(N)O(N). On integer input with coordinates of bb bits, the Newell normal has O(b)O(b) bits more, so each operation is constant time on the real RAM.

Properties

  • Exact. The face signs come from integer arithmetic, so a face that is almost vertical gets the right side.
  • Local. The side of a face depends only on its normal, not on the rest of the part. So the loops are candidates, not a check that the halves can come apart: a face can face up and still be blocked by another part of the part. That is an undercut.
  • Deterministic. The loops come out in the order of their first boundary half-edge in the face list.
  • One loop for convex parts. By Theorem 2. For a non-convex part the number of loops is not fixed: a part with a through hole along dd has at least two.

Variants and improvements

  • Smooth surfaces. On a NURBS or other smooth part, the parting line is the silhouette curve where n⋅d=0n \cdot d = 0, traced as a curve on each face. This page covers polyhedra and tessellated parts.
  • Choosing among loops. Fu, Nee and Fuh classify the faces by their visibility and moldability for the parting direction, and among the edge loops they choose the one with the largest projected area on the plane normal to dd as the main parting line. The other loops are inner parting lines, for example around a through hole, where a core closes the hole.
  • Flat parting lines. A planar parting line makes a cheap mold. When a loop runs along vertical faces, the zero-draft faces can move to the other side, which moves the loop down the wall, and the planner chooses the position that makes the loop flat or stepped least often.
  • Parting surface. The mold also needs a parting surface, which extends the parting line outward to the edge of the mold block. A flat loop gives a flat surface. A loop like the one in the example needs a ruled or stepped surface.
  • Choice of the direction. The direction dd comes first, from mold parting direction. Ahn and coauthors test one direction for a two-piece cast and find all valid directions of a polyhedron. The algorithm on this page then gives the line for the chosen direction.
  • Undercuts. If a face is blocked from both +d+d and −d-d, no choice of loop helps. Undercut detection finds such faces, and the mold needs side cores.

When to use it

Use it after the parting direction is fixed, on a tessellated part or a polyhedral model, to get the candidate parting lines in linear time. Use exact integer or rational coordinates, or snap the input to a grid, so that faces close to vertical get a reliable side. Do not use the loops as a proof that the mold works. Check undercuts and draft separately.

Pitfalls

  • Vertical faces. A face with n⋅d=0n \cdot d = 0 must go to one side by a fixed rule. A test with a tolerance puts some vertical faces up and some down at random, and the loops then zigzag over the walls.
  • Pinched loops. At a vertex where the upper region touches itself, two boundary arcs meet. A chaining rule that takes any boundary edge at vv can join the arcs into a loop that crosses itself. Lines L4 to L6 turn around vv in the order of the faces, which gives non-crossing loops. In the random terrain tests of the implementation, several loops repeat a vertex for this reason.
  • Open or bad meshes. An edge with one face, or two faces that use the same half-edge, breaks the twin map. The implementation raises an error instead of returning wrong loops.
  • Orientation. If the faces are clockwise from outside, all normals flip, and the upper and lower sides swap. A test of the signed volume finds this.

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.

parting_line_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parting-line-generation/. The authors are listed in prov/D4D190.jsonl.

"""Parting line candidates of a closed polyhedral mesh for a parting direction.

The mesh is a closed, oriented 2-manifold: `verts` is a list of integer
points (x, y, z) and `faces` is a list of vertex index lists, each in
counterclockwise order seen from outside. A face is *upper* when its outward
normal n has n . d > 0 and *lower* when n . d < 0. A face with n . d = 0 goes
to the side given by `zero_side` (-1, the lower side, by default).

The parting line candidates are the boundary loops of the union of the upper
faces. Each loop is a list of vertex indices; the loop closes from the last
vertex back to the first, and the upper faces are on its left when seen from
outside. All arithmetic is on integers, so the face signs are exact.
"""

from typing import Dict, List, Sequence, Set, Tuple

Point = Tuple[int, int, int]
HalfEdge = Tuple[int, int]


def newell_normal(verts: Sequence[Point], face: Sequence[int]) -> Point:
    """Return twice the area vector of a planar face (Newell's method).

    For a planar polygon in counterclockwise order seen from outside, this
    is an outward normal whose length is twice the area. Exact on integers.
    Cost: O(k) for a face with k vertices.
    """
    nx = ny = nz = 0
    k = len(face)
    for i in range(k):
        x0, y0, z0 = verts[face[i]]
        x1, y1, z1 = verts[face[(i + 1) % k]]
        nx += (y0 - y1) * (z0 + z1)
        ny += (z0 - z1) * (x0 + x1)
        nz += (x0 - x1) * (y0 + y1)
    return (nx, ny, nz)


def face_signs(verts: Sequence[Point], faces: Sequence[Sequence[int]], d: Point, zero_side: int = -1) -> List[int]:
    """Return +1 for each upper face and -1 for each lower face.

    A face with n . d = 0 gets `zero_side`. Cost: O(total face size).
    """
    if zero_side not in (1, -1):
        raise ValueError("zero_side must be +1 or -1")
    signs = []
    for f in faces:  # @line L1
        n = newell_normal(verts, f)
        dot = n[0] * d[0] + n[1] * d[1] + n[2] * d[2]
        signs.append(1 if dot > 0 else -1 if dot < 0 else zero_side)
    return signs


def _half_edge_maps(faces: Sequence[Sequence[int]]) -> Tuple[Dict[HalfEdge, int], Dict[HalfEdge, HalfEdge]]:
    """Map each half-edge to its face, and to the next half-edge of that face.

    Cost: O(total face size) expected time with hashing.
    """
    owner: Dict[HalfEdge, int] = {}
    succ: Dict[HalfEdge, HalfEdge] = {}
    for fi, f in enumerate(faces):  # @line L2
        k = len(f)
        for i in range(k):
            h = (f[i], f[(i + 1) % k])
            if h in owner:
                raise ValueError("half-edge %r is used by two faces; the mesh is not oriented" % (h,))
            owner[h] = fi
            succ[h] = (f[(i + 1) % k], f[(i + 2) % k])
    for (u, v) in owner:
        if (v, u) not in owner:
            raise ValueError("edge %r has no twin; the mesh is not closed" % ((u, v),))
    return owner, succ


def silhouette_edges(verts: Sequence[Point], faces: Sequence[Sequence[int]], d: Point, zero_side: int = -1) -> Set[Tuple[int, int]]:
    """Return the edges (u, v), u < v, between an upper face and a lower face.

    Cost: O(total face size).
    """
    signs = face_signs(verts, faces, d, zero_side)
    owner, _ = _half_edge_maps(faces)
    out = set()
    for (u, v), f in owner.items():
        if signs[f] > 0 and signs[owner[(v, u)]] < 0:
            out.add((min(u, v), max(u, v)))
    return out


def parting_loops(verts: Sequence[Point], faces: Sequence[Sequence[int]], d: Point, zero_side: int = -1) -> List[List[int]]:
    """Return the boundary loops of the union of the upper faces.

    Each loop is a list of vertex indices with the upper faces on its left.
    The loops are in a fixed order (by their first half-edge in face order),
    so the result is deterministic. Cost: O(total face size).
    """
    signs = face_signs(verts, faces, d, zero_side)  # @line L1
    owner, succ = _half_edge_maps(faces)  # @line L2
    boundary: List[HalfEdge] = []
    for fi, f in enumerate(faces):  # @line L3
        if signs[fi] < 0:
            continue
        k = len(f)
        for i in range(k):
            h = (f[i], f[(i + 1) % k])
            if signs[owner[(h[1], h[0])]] < 0:
                boundary.append(h)
    nxt: Dict[HalfEdge, HalfEdge] = {}
    for h in boundary:
        g = succ[h]  # @line L4
        while signs[owner[(g[1], g[0])]] > 0:  # @line L5
            g = succ[(g[1], g[0])]
        nxt[h] = g  # @line L6
    loops: List[List[int]] = []
    used: Set[HalfEdge] = set()
    for h in boundary:  # @line L7
        if h in used:
            continue
        loop = []
        g = h
        while g not in used:
            used.add(g)
            loop.append(g[0])
            g = nxt[g]
        loops.append(loop)
    return loops  # @line L8
test_parting_line_generation.py 280 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parting-line-generation/. The authors are listed in prov/D4D190.jsonl.

import random
import unittest
from fractions import Fraction

from parting_line_generation import face_signs, newell_normal, parting_loops, silhouette_edges

# The square pyramid of the page: base [-1, 1]^2 at z = 0, apex (0, 0, 2).
PYR_V = [(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0), (0, 0, 2)]
PYR_F = [[0, 3, 2, 1], [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]]

BOX_V = [(0, 0, 0), (2, 0, 0), (2, 3, 0), (0, 3, 0), (0, 0, 1), (2, 0, 1), (2, 3, 1), (0, 3, 1)]
BOX_F = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]


def cross(a, b):
    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 sub(a, b):
    return tuple(x - y for x, y in zip(a, b))


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def hull_2d(points):
    """Andrew's monotone chain, strict corners only, counterclockwise."""
    pts = sorted(set(points))
    if len(pts) <= 2:
        return pts

    def turn(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    lower, upper = [], []
    for p in pts:
        while len(lower) >= 2 and turn(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    for p in reversed(pts):
        while len(upper) >= 2 and turn(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]


def strict_corners(poly):
    """Drop the points of a closed polygon that are collinear with their neighbours."""
    out = list(poly)
    changed = True
    while changed and len(out) > 2:
        changed = False
        for i in range(len(out)):
            a, b, c = out[i - 1], out[i], out[(i + 1) % len(out)]
            if (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) == 0:
                del out[i]
                changed = True
                break
    return out


def same_cycle(p, q):
    if len(p) != len(q):
        return False
    n = len(p)
    for r in (q, q[::-1]):
        for s in range(n):
            if all(p[i] == r[(i + s) % n] for i in range(n)):
                return True
    return False


def random_convex_polygon(rng, around_origin):
    while True:
        pts = [(rng.randint(-20, 20), rng.randint(-20, 20)) for _ in range(rng.randint(3, 14))]
        h = hull_2d(pts)
        if len(h) < 3:
            continue
        if around_origin:
            k = len(h)
            if not all((h[(i + 1) % k][0] - h[i][0]) * (0 - h[i][1]) - (h[(i + 1) % k][1] - h[i][1]) * (0 - h[i][0]) > 0 for i in range(k)):
                continue
        return h


def prism(poly, h):
    k = len(poly)
    verts = [(x, y, 0) for x, y in poly] + [(x, y, h) for x, y in poly]
    faces = [list(range(k - 1, -1, -1)), list(range(k, 2 * k))]
    for i in range(k):
        j = (i + 1) % k
        faces.append([i, j, k + j, k + i])
    return verts, faces


def bipyramid(poly, h):
    k = len(poly)
    verts = [(x, y, 0) for x, y in poly] + [(0, 0, h), (0, 0, -h)]
    faces = []
    for i in range(k):
        j = (i + 1) % k
        faces.append([i, j, k])
        faces.append([j, i, k + 1])
    return verts, faces


def terrain(rng, nx, ny, hmax):
    """A closed heightfield block: triangulated top, walls and bottom."""
    def top(i, j):
        return i * (ny + 1) + j

    def bot(i, j):
        return (nx + 1) * (ny + 1) + top(i, j)

    verts = [(i, j, rng.randint(1, hmax)) for i in range(nx + 1) for j in range(ny + 1)]
    verts += [(i, j, 0) for i in range(nx + 1) for j in range(ny + 1)]
    faces = []
    for i in range(nx):
        for j in range(ny):
            a, b, c, e = top(i, j), top(i + 1, j), top(i + 1, j + 1), top(i, j + 1)
            faces += [[a, b, c], [a, c, e]]
            a, b, c, e = bot(i, j), bot(i + 1, j), bot(i + 1, j + 1), bot(i, j + 1)
            faces += [[a, c, b], [a, e, c]]
    quads = []
    for i in range(nx):
        quads.append((bot(i, 0), bot(i + 1, 0), top(i + 1, 0), top(i, 0)))
        quads.append((bot(i + 1, ny), bot(i, ny), top(i, ny), top(i + 1, ny)))
    for j in range(ny):
        quads.append((bot(0, j + 1), bot(0, j), top(0, j), top(0, j + 1)))
        quads.append((bot(nx, j), bot(nx, j + 1), top(nx, j + 1), top(nx, j)))
    for a, b, c, e in quads:
        faces += [[a, b, c], [a, c, e]]
    return verts, faces


def linear_map(rng, verts, faces):
    while True:
        m = [[rng.randint(-3, 3) for _ in range(3)] for _ in range(3)]
        det = dot(m[0], cross(m[1], m[2]))
        if det != 0:
            break
    nv = [tuple(dot(row, v) for row in m) for v in verts]
    nf = [list(f) if det > 0 else list(reversed(f)) for f in faces]
    return nv, nf


def volume6(verts, faces):
    total = 0
    for f in faces:
        for i in range(1, len(f) - 1):
            total += dot(verts[f[0]], cross(verts[f[i]], verts[f[i + 1]]))
    return total


def brute_signs(verts, faces, d, zero_side):
    """Face signs from the cross product of the first three vertices, in Fraction."""
    out = []
    for f in faces:
        p0, p1, p2 = ([Fraction(c) for c in verts[i]] for i in f[:3])
        n = cross(sub(p1, p0), sub(p2, p0))
        s = dot(n, [Fraction(c) for c in d])
        out.append(1 if s > 0 else -1 if s < 0 else zero_side)
    return out


def brute_silhouette(verts, faces, d, zero_side=-1):
    """Compare every pair of faces: an edge is on the silhouette if its two faces differ in sign."""
    signs = brute_signs(verts, faces, d, zero_side)
    edges = [set(frozenset((f[i], f[(i + 1) % len(f)])) for i in range(len(f))) for f in faces]
    out = set()
    for i in range(len(faces)):
        for j in range(i + 1, len(faces)):
            if signs[i] != signs[j]:
                for e in edges[i] & edges[j]:
                    out.add(tuple(sorted(e)))
    return out


def projection_basis(d):
    axes = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    e = min(axes, key=lambda a: abs(dot(a, d)))
    a = cross(d, e)
    b = cross(d, a)
    return a, b


class TestPartingLines(unittest.TestCase):
    def check_loops(self, verts, faces, d, zero_side=-1):
        loops = parting_loops(verts, faces, d, zero_side)
        signs = face_signs(verts, faces, d, zero_side)
        upper_half_edges = set()
        for fi, f in enumerate(faces):
            if signs[fi] > 0:
                upper_half_edges |= {(f[i], f[(i + 1) % len(f)]) for i in range(len(f))}
        seen = []
        for loop in loops:
            for i in range(len(loop)):
                h = (loop[i], loop[(i + 1) % len(loop)])
                self.assertIn(h, upper_half_edges)
                seen.append(tuple(sorted(h)))
        expected = brute_silhouette(verts, faces, d, zero_side)
        self.assertEqual(len(seen), len(set(seen)))
        self.assertEqual(set(seen), expected)
        self.assertEqual(silhouette_edges(verts, faces, d, zero_side), expected)
        return loops

    def test_pyramid_trace(self):
        d = (1, 0, 1)
        self.assertEqual([newell_normal(PYR_V, f) for f in PYR_F], [(0, 0, -8), (0, -4, 2), (4, 0, 2), (0, 4, 2), (-4, 0, 2)])
        self.assertEqual(face_signs(PYR_V, PYR_F, d), [-1, 1, 1, 1, -1])
        self.assertEqual(parting_loops(PYR_V, PYR_F, d), [[0, 1, 2, 3, 4]])
        self.check_loops(PYR_V, PYR_F, d)

    def test_box_vertical_faces(self):
        # d = z: the four walls have n . d = 0, and zero_side decides where they go.
        d = (0, 0, 1)
        self.assertEqual(parting_loops(BOX_V, BOX_F, d, -1), [[4, 5, 6, 7]])
        self.assertEqual(parting_loops(BOX_V, BOX_F, d, 1), [[0, 1, 2, 3]])
        self.check_loops(BOX_V, BOX_F, d, -1)
        self.check_loops(BOX_V, BOX_F, d, 1)

    def test_box_tilted(self):
        loops = self.check_loops(BOX_V, BOX_F, (1, 1, 1))
        self.assertEqual(len(loops), 1)
        self.assertEqual(len(loops[0]), 6)

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            parting_loops(PYR_V, PYR_F[:-1], (0, 0, 1))
        with self.assertRaises(ValueError):
            face_signs(PYR_V, PYR_F, (0, 0, 1), 0)

    def test_random_convex(self):
        rng = random.Random(20261115)
        done = 0
        while done < 150:
            poly = random_convex_polygon(rng, around_origin=True)
            maker = prism if done % 2 == 0 else bipyramid
            verts, faces = maker(poly, rng.randint(1, 15))
            verts, faces = linear_map(rng, verts, faces)
            self.assertGreater(volume6(verts, faces), 0)
            d = (rng.randint(-5, 5), rng.randint(-5, 5), rng.randint(-5, 5))
            if d == (0, 0, 0):
                continue
            if any(dot(newell_normal(verts, f), d) == 0 for f in faces):
                continue  # not in general position; the theorem needs n . d != 0
            loops = self.check_loops(verts, faces, d)
            self.assertEqual(len(loops), 1)
            loop = loops[0]
            self.assertEqual(len(loop), len(set(loop)))
            a, b = projection_basis(d)
            proj = [(dot(a, verts[v]), dot(b, verts[v])) for v in loop]
            hull = hull_2d([(dot(a, v), dot(b, v)) for v in verts])
            self.assertTrue(same_cycle(strict_corners(proj), hull))
            done += 1

    def test_random_terrain(self):
        rng = random.Random(7)
        for trial in range(40):
            verts, faces = terrain(rng, rng.randint(1, 6), rng.randint(1, 6), rng.randint(1, 6))
            self.assertGreater(volume6(verts, faces), 0)
            d = (rng.randint(-3, 3), rng.randint(-3, 3), rng.randint(1, 4))
            for zero_side in (-1, 1):
                self.check_loops(verts, faces, d, zero_side)

    def test_flat_terrain_is_one_loop(self):
        # A terrain with a constant height and d = z: the top face set is the upper region.
        rng = random.Random(3)
        verts, faces = terrain(rng, 3, 2, 1)
        loops = self.check_loops(verts, faces, (0, 0, 1))
        self.assertEqual(len(loops), 1)
        self.assertEqual(len(loops[0]), 2 * (3 + 2))


if __name__ == "__main__":
    unittest.main()

History

The two-piece mold model, with the faces of a part split by their direction relative to the parting direction, is the base of the geometric work on casting by Bose, Bremner and van Kreveld (1997) and by Ahn and coauthors, first at SoCG 1997 and in Computer-Aided Design in 2002. In mold CAD, parting lines were derived from the silhouette in the parting direction. Weinstein and Manoochehri (1997) chose among parting lines by manufacturing criteria. Fu, Nee and Fuh (2002) classified the faces by visibility and moldability and chose the 3D parting line among the edge loops by their projected area.

References

  1. M. W. Fu, A. Y. C. Nee and J. Y. H. Fuh, The application of surface visibility and moldability to parting line generation, Computer-Aided Design 34(6), 2002, 469 to 480, the classification of the faces by their orientation to the parting direction, the edge loops between the classes, and the choice of a 3D parting line from the projected areas of the loops
  2. Optimum parting line design of molded and cast parts for manufacturability, Journal of Manufacturing Systems 16(1), 1997, the choice of a parting line among candidates by manufacturing criteria (authors and pages not confirmed here)
  3. Hee-Kap Ahn, Mark de Berg, Prosenjit Bose, Siu-Wing Cheng, Dan Halperin, Jiri Matousek and Otfried Schwarzkopf, Separating an object from its cast, Computer-Aided Design 34(8), 2002, 547 to 559, the two-piece cast model, in which the parting surface splits the part into the faces seen from +d and from -d, and the test of one direction

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