r/OpenPythonSCAD • • 3d ago

Building watertight models from surfaces: patch() in PythonSCAD 1.2 (tutorial: a Y-adapter for dust extraction)

Everryone who has used OpenSCAD knows the CSG way of thinking: you start with solids (cube, cylinder, sphere, extrusions) and combine them with union(), difference() and intersection(). The volume is the building block, and the result is watertight because every input already was.

PythonSCAD 1.2 adds a fundamentally different way: you describe the skin of the object instead of its volume.

  1. You define a few closed outlines in 2.5D: ordinary 2D shapes like circle() or polygon(), moved into 3D space with translate(), rotate() and scale().
  2. patch() spans a surface between them.
  3. concat() stitches all the surfaces together along their shared edges into one watertight solid.

This tutorial walks through that workflow and ends with a real part: a Y-adapter that takes a round hose and splits it into two rectangular outlets of different size and angle.

Why is that a good example? Try building it with CSG:

  • rotate_extrude() doesn't work, because the part has no axis of symmetry.
  • hull() doesn't work, because it fills the gap between the two branches.
  • A classic loft doesn't work, because the shape branches.

With patch() it's about 15 outlines.

Note: patch() is new in PythonSCAD 1.2.

1. The smallest example: a closed cup

An outline is just a 2D shape placed somewhere in space. Here are two circles at different heights:

from pythonscad import *

bottom = circle(20, fn=48)
top = circle(14, fn=48).up(40)

wall = patch(bottom, holes=[top])   # skin between the two outlines
cup = concat(wall, patch(bottom), patch(top))
cup.show()

Three surfaces are involved:

  • patch(bottom, holes=[top]) is the wall: the first outline is the outer boundary, and the second one is a "hole" that the surface spans to.
  • patch(bottom) and patch(top) are the caps, single outlines without holes.
  • concat() joins them. The wall's lower edge and the bottom cap's edge are the same outline, so they fuse into one closed body.

That last point is the whole trick, so here it is as a rule:

Two surfaces that should meet must use the identical outline. Create every outline once, store it in a variable, and pass that same object to both patches.

2. Branching: one patch, two holes

This is where it gets interesting. An outline can have several holes:

top_view = lambda p: [p[0], p[1]]           # flatten by dropping z

base  = circle(1, fn=48).scale([40, 24])                        # bottom
left  = circle(1, fn=48).scale([13, 12]).translate([-22, 0, 35])
right = circle(1, fn=48).scale([13, 12]).translate([22, 0, 35])
left_end  = circle(1, fn=48).scale([9, 8]).translate([-24, 0, 80])
right_end = circle(1, fn=48).scale([9, 8]).translate([24, 0, 80])

crotch = patch(base, holes=[left, right], proj=top_view)
leg_l = patch(left, holes=[left_end], proj=top_view)
leg_r = patch(right, holes=[right_end], proj=top_view)

pants = concat(crotch, leg_l, leg_r,
               patch(base), patch(left_end), patch(right_end))
pants.show()

[image: tutorial_pants.png]

The crotch patch goes from one outline to two. This is the "pair of pants" surface that CSG has no primitive for.

What is proj?

Internally, patch() flattens all outlines into a 2D plane, triangulates there, and maps the result back onto the 3D surface. For that to work, the outlines must be nested in the flat view: the outer boundary contains the holes, and the holes don't overlap.

proj tells patch() how to flatten. Here, "look from above" ([x, y]) is enough, because both legs lie inside the base and next to each other when seen from the top. If you leave proj out, patch() picks a projection automatically. For anything beyond simple shapes, I recommend passing it explicitly.

3. The real part: a Y-adapter

The full script is linked at the end. Here are the important pieces, slightly simplified.

3.1 Outlines with character

circle() gives the round inlet. For the rectangular outlets, one small helper builds a superellipse as a polygon(), which is then scaled to size like any other shape:

def rrect(a, b, n):
    """Half sizes a, b: n=2 circle, n=8 rounded rectangle."""
    pts = []
    for i in range(N):
        t = 2 * math.pi * i / N
        c, s = math.cos(t), math.sin(t)
        pts.append([math.copysign(abs(c) ** (2 / n), c),
                    math.copysign(abs(s) ** (2 / n), s)])
    return polygon(pts).scale([a, b])

Raising n morphs a circle into a rectangle, which is perfect for the transition from a round hose to rectangular outlets. All outlines use the same number of points N.

3.2 Placing outlines in space

The branches are tilted, so their outlines are simply rotated and moved into place. Each branch is 4 outlines along its axis: root, middle, outlet, and end of the collar:

def axis(angle):
    return [math.sin(math.radians(angle)), 0, math.cos(math.radians(angle))]

def at(c, angle, d):                     # point d mm along the branch
    return [ci + d * ai for ci, ai in zip(c, axis(angle))]

sizes = [(0.5, 6, 0), (0.46, 8, 30), (0.44, 8, 55), (0.44, 8, 80)]
branch_a = [rrect(w * k, h * k, n)
            .rotate([0, angle, 0])
            .translate(at(A, angle, d)) for k, n, d in sizes]

3.3 Skin between outlines along a path

Between consecutive outlines of a branch, sweep() creates the surface. Its proj flattens along the branch axis: the first outline becomes the big outer loop and the second one a smaller loop inside it. That keeps them nested no matter how the branch is tilted:

def sweep(a, b, c, angle):
    d = axis(angle)                          # path direction
    u = [d[2], 0, -d[0]]                     # perpendicular, in xz
    v = [0, 1, 0]

    def proj(p):
        q = [pi - ci for pi, ci in zip(p, c)]
        h = dot(q, d)                         # how far along the path
        ang = math.atan2(dot(q, v), dot(q, u))
        return [(300 - h) * math.cos(ang), (300 - h) * math.sin(ang)]
    return patch(a, holes=[b], proj=proj)

3.4 The crotch: the heart of the part

The round inlet ends in a wide rounded rectangle. From there, one patch goes to the roots of both branches:

crotch = patch(inlet[-1], holes=[branch_a[0], branch_b[0]],
               proj=lambda p: [p[0], p[1]])

This is the same idea as the pants in section 2, only with different shapes, sizes and angles.

3.5 Making it hollow: build the skin twice

A real adapter needs a wall. There is still no boolean involved:

outer, o_in, o_a, o_b = skin(0)        # outer skin
inner, i_in, i_a, i_b = skin(wall)     # same construction, shrunk by "wall"

parts = outer + inner + [
    rim(o_in, i_in, [0, 0, 0], 0),                    # flat rings that
    rim(o_a, i_a, at(A, -a_angle, 80), -a_angle),     # close the wall at
    rim(o_b, i_b, at(B, b_angle, 80), b_angle),       # the three openings
]
adapter = concat(*parts)

skin(off) builds every outline shrunk by off. At each opening, a flat ring (patch(outer, holes=[inner])) connects the outer and inner skins. The result is a single watertight shell with a constant wall, ready for the slicer.

3.6 Sliders

Everything is driven by add_parameter: inlet diameter, wall thickness, and width, height and angle of each branch. Drag a slider and the crotch adapts, because it's always spanned between whatever outlines currently exist.

4. Rules for watertight models

What I learned building this:

  1. Share outlines. Neighbouring patches must use the same outline object. Never rebuild an outline "the same way" twice, because tiny floating-point differences break the seam.
  2. Nested in the flat view. The outer boundary must contain all holes in the proj view, and the holes must not overlap. If a patch fails, this is the first thing to check.
  3. Give holes some room. A hole that comes within a millimetre or two of its outer boundary can break the triangulation. Leave a few millimetres.
  4. Same point count is easiest. It isn't required, but it keeps triangles even.
  5. Every edge needs exactly two neighbours. Each open outline must be used by exactly two patches, or closed by a cap. A cap is just patch(outline) with no holes.

5. CSG vs. patch: when to use which

CSG (union, difference, ...CSG (union, difference)patch() + concat()
Building blockVolumesSurfaces between outlines
Watertight becauseInputs are solidsShared edges are stitched
StrengthHoles, pockets, mechanical featuresTransitions between different shapes, branches, freeform
Typical partBracket, enclosureDuct, adapter, manifold, handle

Please find full code here:

https://bpa.st/VWMJM

Questions and your own patch() models are very welcome in the comments!

1 Upvotes

0 comments sorted by