Code & Fun

How do math and computers work together? Here is a real example: the Python program that turns my shark drawing into a 3D-printed puzzle. No experience needed. Read it on your lunch break, drag the sliders, and see how a few simple ideas (lists, loops, one small formula) become something you can hold. If you like numbers, patterns or puzzles, this page is for you.

The page has two parts. First, five short steps with live sliders. Then a deeper look at each idea: the math behind it, a plain-English recipe (called pseudocode), the real Python, and a few questions to test yourself.

Step 1. A shape is a table of numbers

A computer has no idea what a shark looks like. It stores the outline as a list of points, and each point is an (x, y) pair. If you work with spreadsheets or databases, picture a two-column table with one row per corner:

shark = [(0, 0), (4, 0), (4, 3), (0, 3)]   # a rectangle: 4 corners
shark_moved = [(x + 10, y) for x, y in shark]   # slide it 10 to the right

The real shark outline has points. Moving a shape means adding to its numbers, nothing more.

Try it: drag the slider and read the first point in the box. Only its x value changed.

Step 2. Repeating a pattern: i·v1 + j·v2

Think of floor tiles. From any tile, the next tile along one direction sits one fixed step away (v1), and the next tile along the other direction sits another fixed step away (v2). Every tile position is then two whole numbers and two arrows:

for i in range(3):          # 3 steps along v1
    for j in range(3):      # 3 steps along v2
        x = i * v1[0] + j * v2[0]
        y = i * v1[1] + j * v2[1]
        place_shark_at(x, y)
Key idea: two arrows and two whole numbers generate every tile position. That is what a tessellation is. Each cell holds one shark plus its upside-down partner (Step 3). The nested loop is the same pattern you use to walk through every row and column of a grid of data.
Try it: with the real values the sharks fit together with no gaps. Press "off by 1 mm" and thin gaps or overlaps appear. That is why the program needs v1 and v2 to be exact (Step 4). Then change v2 x and v2 y and watch the lines of tiles along v2 lean. Note that i always counts steps along v1 and j along v2. Whether that looks like a row or a column depends on which way the arrows point.

Step 3. Turning a point 180°: p' = 2c − p

To spin a point p half a turn around a centre c, the new point lands on the opposite side of c, at the same distance. That makes c the exact midpoint of the old and new point:

c = (p + p_new) / 2        which gives        p_new = 2*c - p

c = (1, 1);  p = (3, 2)
p_new = (2*c[0] - p[0], 2*c[1] - p[1])     # (-1, 0)

In the project, c is the middle of the shark's straight edge. Applying this to every point of the shark produces its partner.

Try it: drag to 180° and compare the last two lines. The simple formula 2c − p matches the general rotation formula, without any sines or cosines.

Step 4. Comparing every pair to find an exact value

The problem: the program only knows the step approximately, for example (84, -183.5), but the geometry needs it exactly. The idea: when two corners sit at matching places on neighbouring sharks, the difference between them is the exact step. So compute the difference for every pair of points and look for the value that keeps repeating. If you have ever hunted for the most common value in a noisy column, it is the same instinct.

The long way, with loops that are easy to read:

differences = []
for a in points:
    for b in points:
        differences.append((b[0] - a[0], b[1] - a[1]))

The real code does the same job in one NumPy line:

diffs = (verts[None, :, :] - verts[:, None, :]).reshape(-1, 2)

NumPy lays the table out once as a row and once as a column, then subtracts. That fills an N × N grid where entry [a, b] is point b − point a, which is the double loop run inside the library. The program then keeps only the differences close to the rough guess (distance √(dx²+dy²)), takes the median, and averages the values near it. The median shrugs off the odd bad value, the same reason analysts report medians for skewed data.

Try it: the true step is exactly (10, 4). Raise the noise and the refined answer stays close to it, because the median ignores the wrong pairs and the average smooths the small errors.

Step 5. Shrinking and growing shapes: buffer

A geometry library can grow or shrink a shape evenly in every direction:

body  = shark.buffer(-0.2)               # shrink 0.2 mm all around
ring  = body.difference(body.buffer(-1.2))   # outline band, 1.2 mm wide
Exercise on paper: draw a square, draw a smaller square inside it, and shade the space between them. That shaded band is the "ring".

Going deeper: the math, the recipe and the code

Each part below follows the same pattern. First the idea in plain words, then where math meets code, then pseudocode (a recipe in everyday English that any programmer can turn into code), then the real Python. At the end, a few questions to test yourself. Click a question to reveal its answer.

PartIdeaMath meets code
1. Lists and loopsStore a shape as numbers and repeat itLattices and vectors
2. A formula as codeTurn a point half a turnMidpoints and symmetry
3. Finding the exact answerCompare every pair, then pick the middleStatistics: median versus average
4. Building geometryShrink, subtract and extrude with a libraryOffsetting and set operations
5. From drawing to 3D printThe whole program in one recipeChecking your work with areas

Part 1. Lists and loops

The idea in plain words. A shape is a list of points, and a point is two numbers. To move a shape you add the same amount to every point. To make a whole floor of tiles you do not draw each tile by hand: you tell the computer a step to the right and a step up, and let two loops, one inside the other, visit every tile.

Math meets code. The position i·v1 + j·v2 is a lattice: every point you can reach by taking whole-number steps along two arrows (vectors). Crystals, wallpaper and the Baby Shark tessellation all work this way. The two arrows are the whole pattern.

Pseudocode

shape  = list of (x, y) points

MOVE a shape by (dx, dy):
    new shape = empty list
    for each point in the shape:
        add (x + dx, y + dy) to the new shape
    return the new shape

GRID of tiles with step arrows v1 and v2:
    for each i from 0 up to n1 - 1:        (steps along v1)
        for each j from 0 up to n2 - 1:        (steps along v2)
            x = i * v1.x + j * v2.x
            y = i * v1.y + j * v2.y
            place a copy of the shape at (x, y)

Python

def move(shape, dx, dy):
    return [(x + dx, y + dy) for x, y in shape]

def grid_positions(v1, v2, n1, n2):
    positions = []
    for i in range(n1):
        for j in range(n2):
            x = i * v1[0] + j * v2[0]
            y = i * v1[1] + j * v2[1]
            positions.append((x, y))
    return positions

A few things to notice. range(n1) counts 0, 1, 2 and stops before n1. v1[0] is the x part of the arrow and v1[1] is the y part. The one-line loop in move is called a list comprehension.

Test yourself

How many tiles do 3 steps along v1 and 2 along v2 make?

6, because the loop body runs 3 × 2 times.

Where is the tile at i=2, j=1 if v1=(10,0) and v2=(3,8)?

(2·10 + 3, 2·0 + 8) = (23, 8).

What changes if v2 = (0, 8)?

The lines of tiles along v2 stand straight up. A slanted v2 makes those lines lean, which is how the shark parallelogram gets its slant.

Watch out for

Part 2. A formula as code

The idea in plain words. The upside-down partner of each shark is the same shape turned half a turn. To spin one point around a centre, the new point lands on the opposite side, at the same distance. That means the centre sits exactly halfway between the old and the new point.

Math meets code. Halfway is an average: c = (p + p_new) / 2. A little algebra (multiply by 2, subtract p) gives p_new = 2c − p. This is a point reflection, a kind of symmetry. One line of algebra replaced sines and cosines, and the code is just that line.

Pseudocode

TURN a point p half a turn around a centre c:
    new x = 2 * c.x - p.x
    new y = 2 * c.y - p.y
    return (new x, new y)

TURN a whole shape:
    for each point in the shape:
        turn that point around c
    return the list of new points

Python

def turn_180(point, centre):
    return (2 * centre[0] - point[0], 2 * centre[1] - point[1])

def turn_180_shape(shape, centre):
    return [turn_180(p, centre) for p in shape]

new = turn_180((3, 2), (1, 1))      # (-1, 0)
midpoint = ((3 + new[0]) / 2, (2 + new[1]) / 2)   # (1.0, 1.0) = c, so it is correct

The last line is a habit worth copying: check the answer a second way. Here the midpoint of the old and new point should be the centre, and it is.

Test yourself

Turn (5, 5) around (2, 3).

(2·2 − 5, 2·3 − 5) = (−1, 1). Check: the midpoint of (5,5) and (−1,1) is (2,3).

What happens if you turn a point twice?

It returns to where it started: 2c − (2c − p) = p.

What if the centre is (0, 0)?

The formula becomes (−x, −y), so both signs flip.

Watch out for

Part 3. Finding the exact answer in noisy data

The idea in plain words. The program starts with a rough guess of the step, say (11, 3.2), but the pieces only fit if the step is exact. The trick: whenever two corners sit at matching places on neighbouring sharks, the difference between them is the exact step. So compute the difference for every pair of corners and look for the value that keeps appearing. The right answer repeats. The wrong ones appear once.

Math meets code. This is a small piece of statistics. Take the median first, because a few wild values barely move it, then average the values close to it to smooth out tiny errors. Try the numbers 9.9, 10.0, 10.1 and 55.0: the average is 21.25, which describes nothing, while the median is 10.05, which describes the data well. That is why a few extreme values can wreck an average and not a median.

Pseudocode

REFINE a rough step guess using a list of points:
    differences = empty list
    for each point a in the points:
        for each point b in the points:
            add (b - a) to differences

    near = only the differences within 3 of the guess      (distance = sqrt(dx*dx + dy*dy))
    if there are fewer than 5 near differences:
        return the guess                                    (not enough evidence)

    middle = (median of the near x values, median of the near y values)
    good   = only the near differences within 0.3 of middle
    if there are fewer than 3 good differences:
        return middle
    return the average of the good differences

Python: loops first, then NumPy

# loops that are easy to read
def all_differences(points):
    differences = []
    for a in points:
        for b in points:
            differences.append((b[0] - a[0], b[1] - a[1]))
    return differences

# the same thing in the real program (make_stl.py, refine_vector)
diffs = (verts[None, :, :] - verts[:, None, :]).reshape(-1, 2)

How the NumPy line works: verts is a table with N rows. verts[None, :, :] lays it out as one row of N points, and verts[:, None, :] lays it out as one column of N points. Subtracting a row from a column fills an N × N grid, where entry [a, b] is point b − point a. Then .reshape(-1, 2) flattens the grid into a plain list of (dx, dy) pairs. It is the same double loop, run faster inside the library.

def distance(p, q):
    return math.hypot(p[0] - q[0], p[1] - q[1])     # sqrt(dx*dx + dy*dy)

def median(numbers):
    s = sorted(numbers)
    n = len(s)
    mid = n // 2
    return s[mid] if n % 2 else (s[mid - 1] + s[mid]) / 2

def refine_step(points, guess, tolerance=3.0, close=0.3):
    near = [d for d in all_differences(points) if distance(d, guess) < tolerance]
    if len(near) < 5:
        return guess
    mid = (median([d[0] for d in near]), median([d[1] for d in near]))
    good = [d for d in near if distance(d, mid) < close]
    if len(good) < 3:
        return mid
    return (sum(d[0] for d in good) / len(good), sum(d[1] for d in good) / len(good))

Test yourself

How many differences do 10 points give?

10 × 10 = 100. Ten of them are (0, 0), a point compared with itself.

Why keep only the differences near the guess?

Most pairs are unrelated corners. Only the right pairs repeat near the true step.

Why use the median first, then the average?

The median ignores a few wild values (like 55). The average of the good ones then smooths tiny measurement errors.

Why does the code say if len(near) < 5: return guess?

With too little evidence, a wrong "refined" answer is worse than an honest guess.

Watch out for

Part 4. Building geometry with a library

The idea in plain words. Most real programming is choosing the right tools, not writing everything from scratch. A geometry library (shapely) can grow a shape, shrink it, subtract one shape from another and join shapes together. With those four moves you can build the gap between sharks, the coloured outline, and the whole board.

Math meets code. Shrinking or growing a shape evenly is called offsetting. Subtracting and joining are set operations, the same idea as "in A but not in B" in a Venn diagram. An outline ring is just "the shape, minus a smaller copy of itself".

Pseudocode

BUILD one printable shark tile:
    body   = shark outline shrunk by gap / 2            (0.2 mm each side, so 0.4 mm between neighbours)
    ridge  = body minus (body shrunk by ridge width)    (a thin band around the edge)
    face   = face artwork, kept only inside (body shrunk by ridge / 2)
    raised = ridge joined with face
    base solid   = extrude body   from z = 0 to z = 3 mm
    raised solid = extrude raised from z = 3 to z = 4.5 mm

BUILD the board:
    plate  = bounding box of all 18 sharks, grown by the margin
    recess = outer outline of all 18 sharks joined together
    floor  = extrude plate               from z = 0 to z = 2 mm
    wall   = extrude (plate minus recess) from z = 2 to z = 5 mm
    board  = floor joined with wall

Python

def make_tile_parts(nominal, art, args):
    body = nominal.buffer(-args.gap / 2, join_style=2)
    ridge = body.difference(body.buffer(-args.ridge))
    face = art.intersection(body.buffer(-args.ridge / 2))
    raised = unary_union([ridge, face])
    return combine(extrude(body, args.base)), combine(extrude(raised, args.raised, z0=args.base))

def make_board(g, args):
    pad = args.margin
    minx, miny, maxx, maxy = g["mosaic"].bounds
    plate = box(minx - pad, miny - pad, maxx + pad, maxy + pad)
    recess = unary_union([Polygon(p.exterior) for p in parts])   # parts = pieces of the sharks' union
    wall = plate.difference(recess)
    return try_union(extrude(plate, args.floor) + extrude(wall, args.base, z0=args.floor))

The vocabulary: buffer(-d) shrinks by d, buffer(+d) grows by d, difference subtracts, intersection keeps the overlap, unary_union joins shapes, and extrude turns a flat shape into a solid of a given height.

Test yourself

Each shark shrinks by 0.2 mm. How far apart are two neighbours?

0.2 + 0.2 = 0.4 mm.

How thick is the board where the sharks sit?

2 mm, which is just the floor. Around the edge it is 5 mm (floor plus a 3 mm wall).

Why subtract the shrunk copy to make the outline?

A shape minus a smaller copy of itself leaves only the band around its edge.

Watch out for

Part 5. From drawing to 3D print

The idea in plain words. Put the first four parts together and you have the whole program. It reads my drawing, works out how the sharks interlock, builds the board and the pieces, and saves files a 3D printer understands.

Math meets code. Good programs check their own work. Here the check is about area: add up the areas of all 18 sharks, then subtract the area of the shapes joined together. If the answer is about 0, no sharks overlap and there are no gaps. If a step is off by a millimetre, that number stops being 0 and the program tells you.

The whole program in pseudocode

read the SVG drawing: the shark outline, the face lines, the eyes
convert pixels to millimetres (multiply by the scale, flip y because SVG y points down)
find the two step arrows v1 and v2 exactly         (Part 3)
make the partner shark by turning the outline 180 degrees   (Part 2)
place 18 sharks, 9 + 9, on the lattice              (Part 1)
check: total area of the sharks minus area of their union should be about 0 (no overlap, no gaps)
build each tile and the board                       (Part 4)
arrange copies on plates, row by row, 4 mm apart
save everything as STL files and a preview picture

Try it yourself

Download lesson_steps.py, a short program that needs nothing but Python, and run it:

python3 lesson_steps.py

It prints a moved rectangle, the grid positions, a half turn and a recovered step. Then change a number and run it again. The real program, make_stl.py, needs a few libraries (numpy, shapely, trimesh, segno, matplotlib) and your own shark drawing. Its output is the set of 3D-print files on the puzzle page.

One more experiment: go back to Step 2 and press Break it: v1 off by 1 mm. Notice how a tiny error ruins the whole pattern. That is why Part 3 exists: the step has to be exact.

Full code

Open a block to read it, or download the files: lesson_steps.py (runs with plain Python, no libraries) and make_stl.py (the real program).

Function guide for make_stl.py

FunctionWhat it doesThe idea
parse_points, read_svgReads the shark outline, face lines and eyes from the SVGText search with a regex, where -?\d+(\.\d+)? matches one number
refine_vectorFinds the exact lattice step from a rough oneAll-pairs differences, median, average (Part 3)
extrude, combine, try_union, saveTurns a flat shape into a solid, merges solids, writes an STLLibrary calls (Part 4)
buildReads the SVG, makes the partner, finds v1 and v2, places the sharks, checks overlapThe 2c − p turn and i·v1 + j·v2 (Parts 1 and 2)
place_gridLays out a 3 × 3 block of pairs (18 sharks)Nested loops, using v2 + v1 so the rows run level
fill_rectangleAlternative layout: the most whole sharks that fit in a boxTry many shifts and keep the best score
make_tile_mesh, make_tile_partsOne tile, as a single solid or as base plus raised partsbuffer, difference, intersection (Part 4)
make_boardThe board with the shark-shaped recessPlate minus recess (Part 4)
shelf_pack, make_plateArranges copies in rows on a print plateMove right by width plus 4 mm, and start a new row when the bed is full
make_qr, render_preview, mainQR plaque, preview picture, command-line optionsNot covered on this page
lesson_steps.py: the small demo program (no libraries, about 90 lines)
"""Shark puzzle, the maths in plain Python (no libraries needed).

Run it:   python3 lesson_steps.py

Each STEP matches a step in shark-lesson.html and a function in ../make_stl.py.
"""
import math
import random

# ---------------------------------------------------------------- STEP 1
# A shape is a list of points. Moving a shape = adding to its numbers.
def move(shape, dx, dy):
    return [(x + dx, y + dy) for x, y in shape]


# ---------------------------------------------------------------- STEP 2
# Tile positions: i*v1 + j*v2 for whole numbers i and j.
def grid_positions(v1, v2, n1, n2):
    positions = []
    for i in range(n1):
        for j in range(n2):
            x = i * v1[0] + j * v2[0]
            y = i * v1[1] + j * v2[1]
            positions.append((x, y))
    return positions


# ---------------------------------------------------------------- STEP 3
# Turn a point half a turn around a centre c:   p_new = 2*c - p
def turn_180(point, centre):
    return (2 * centre[0] - point[0], 2 * centre[1] - point[1])


def turn_180_shape(shape, centre):
    return [turn_180(p, centre) for p in shape]


# ---------------------------------------------------------------- STEP 4
# Find an exact step from a rough guess by comparing every pair of points.
def all_differences(points):
    differences = []
    for a in points:
        for b in points:
            differences.append((b[0] - a[0], b[1] - a[1]))
    return differences


def distance(p, q):
    return math.hypot(p[0] - q[0], p[1] - q[1])          # sqrt(dx*dx + dy*dy)


def median(numbers):
    s = sorted(numbers)
    n = len(s)
    mid = n // 2
    return s[mid] if n % 2 else (s[mid - 1] + s[mid]) / 2


def refine_step(points, guess, tolerance=3.0, close=0.3):
    near = [d for d in all_differences(points) if distance(d, guess) < tolerance]
    if len(near) < 5:
        return guess                                       # not enough evidence
    mid = (median([d[0] for d in near]), median([d[1] for d in near]))
    good = [d for d in near if distance(d, mid) < close]
    if len(good) < 3:
        return mid
    return (sum(d[0] for d in good) / len(good), sum(d[1] for d in good) / len(good))


# ---------------------------------------------------------------- demo
if __name__ == "__main__":
    print("STEP 1: move a rectangle 10 to the right")
    rectangle = [(0, 0), (4, 0), (4, 3), (0, 3)]
    print("  ", move(rectangle, 10, 0))

    print("\nSTEP 2: positions of a 3 x 2 grid of tiles")
    for pos in grid_positions((10, 0), (3, 8), 3, 2):
        print("  tile at", pos)

    print("\nSTEP 3: turn (3, 2) half a turn around (1, 1)")
    new = turn_180((3, 2), (1, 1))
    print("  result", new, "   check: midpoint is",
          ((3 + new[0]) / 2, (2 + new[1]) / 2), "(should be (1.0, 1.0))")

    print("\nSTEP 4: recover the step (10, 4) from noisy points")
    random.seed(1)
    first = [(0, 0), (3, 1), (7, 2), (2, 6), (8, 7)]
    second = [(x + 10 + random.uniform(-0.1, 0.1), y + 4 + random.uniform(-0.1, 0.1)) for x, y in first]
    guess = (11.0, 3.2)
    found = refine_step(first + second, guess)
    print("  rough guess  ", guess)
    print("  refined step ", (round(found[0], 2), round(found[1], 2)), " (true step is (10, 4))")
make_stl.py: the real program (needs numpy, shapely, trimesh, segno, matplotlib)
#!/usr/bin/env python3
"""Build 3D-printable STL files for the baby-shark tessellation puzzle.

Reads the tile drawn in TesselManiac! (BabyShark8.svg), works out how the
sharks interlock (a shark plus its 180-degree-rotated partner repeats on a
lattice), and writes:

    stl/tile.stl              one shark tile (print-ready)
    stl/tiles_color_A.stl     a print plate of the "upright" sharks
    stl/tiles_color_B.stl     a print plate of the "upside-down" partner sharks
    stl/board.stl             recessed board the tiles drop into
    stl/qr_plaque.stl         plaque with a QR code linking to the website
    stl/preview.png           top-down picture of the assembled puzzle

Usage:
    .venv/bin/python make_stl.py --url https://your-domain.us.com
    .venv/bin/python make_stl.py --scale 0.18 --area 180x140 --gap 0.4

All lengths are millimetres. Change the defaults below or pass flags.
"""
import argparse
import re
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import segno
import trimesh
from shapely import affinity
from shapely.geometry import LineString, Point, Polygon, box
from shapely.ops import unary_union

HERE = Path(__file__).resolve().parent

# Approximate lattice vectors of the shark pair, in SVG pixels. They are found
# by image search and then refined from the tile's own vertices (refine_vector).
V1_APPROX = (84.0, -183.5)
V2_APPROX = (346.0, 209.5)
# Midpoint of the straight bottom edge (SVG pixels): the 180-degree turn centre.
HALF_TURN_PX = (296.01, 302.25)

# ----------------------------------------------------------------------------
# SVG reading
# ----------------------------------------------------------------------------
NUM = r"-?\d+(?:\.\d+)?"


def parse_points(text):
    return [(float(a), float(b)) for a, b in re.findall(rf"({NUM})\s*,\s*({NUM})", text)]


def read_svg(path):
    """Return (outline, polylines, ellipses) in SVG pixels for the FIRST tile.

    TesselManiac! writes the tile twice (a filled copy, then an outline-only
    copy lower down the page). Only the first copy is used.
    """
    src = Path(path).read_text()
    texts = [m.start() for m in re.finditer(r"<text", src)]
    first = src[: texts[1]] if len(texts) > 1 else src
    outline = parse_points(re.search(r'<polygon[^>]*points\s*=\s*"([^"]+)"', first).group(1))
    lines = [parse_points(m) for m in re.findall(r'<polyline[^>]*points\s*=\s*"([^"]+)"', first)]
    ellipses = []
    for m in re.finditer(r"<ellipse([^>]*)/>", first):
        a = dict(re.findall(r'(\w+)\s*=\s*"\s*([^"]+?)\s*"', m.group(1)))
        ellipses.append(tuple(float(a[k]) for k in ("cx", "cy", "rx", "ry")))
    return outline, lines, ellipses


# ----------------------------------------------------------------------------
# Lattice
# ----------------------------------------------------------------------------
def refine_vector(verts, approx, tol=3.0):
    """Snap an approximate lattice vector to the exact one using vertex pairs.

    TesselManiac! samples matching edges identically, so many vertex pairs differ
    by exactly the lattice vector. The most common difference near `approx` wins.
    """
    diffs = (verts[None, :, :] - verts[:, None, :]).reshape(-1, 2)
    near = diffs[np.hypot(*(diffs - approx).T) < tol]
    if len(near) < 5:
        return np.array(approx)
    # densest cluster: median of the points closest to the overall median
    med = np.median(near, axis=0)
    close = near[np.hypot(*(near - med).T) < 0.3]
    return close.mean(axis=0) if len(close) >= 3 else med


# ----------------------------------------------------------------------------
# Meshes
# ----------------------------------------------------------------------------
def extrude(geom, height, z0=0.0):
    """Extrude a (Multi)Polygon into watertight prisms from z0 to z0+height."""
    if geom.is_empty or height <= 0:
        return []
    polys = [geom] if geom.geom_type == "Polygon" else list(geom.geoms)
    meshes = []
    for p in polys:
        if p.is_empty or p.area < 1e-6:
            continue
        m = trimesh.creation.extrude_polygon(p, height, engine="earcut")
        m.apply_translation([0, 0, z0])
        meshes.append(m)
    return meshes


def combine(meshes):
    meshes = [m for m in meshes if m is not None]
    return trimesh.util.concatenate(meshes) if meshes else None


def try_union(meshes):
    """Boolean-union when manifold3d is installed, else plain concatenation.

    Slicers accept overlapping/touching shells, so concatenation is fine.
    """
    try:
        return trimesh.boolean.union(meshes, engine="manifold")
    except Exception:
        return combine(meshes)


def save(mesh, path):
    path.parent.mkdir(parents=True, exist_ok=True)
    mesh.export(path)
    b = mesh.bounds
    size = b[1] - b[0]
    print(f"  {path.name:22s} {size[0]:6.1f} x {size[1]:6.1f} x {size[2]:4.1f} mm  "
          f"{len(mesh.faces):7d} triangles  watertight={mesh.is_watertight}")


# ----------------------------------------------------------------------------
# Puzzle geometry
# ----------------------------------------------------------------------------

def fill_rectangle(tile0, rot, v1, v2, area):
    """Choose the lattice offset that fits the most WHOLE tiles inside a w x h box.

    Returns [(kind, polygon)] for one connected group, kind "A" = upright shark,
    "B" = its 180-degree partner.
    """
    w, h = area
    rect = box(0, 0, w, h)
    base = {"A": tile0, "B": rot(tile0)}
    best = None
    steps = 14
    for fa in np.linspace(0, 1, steps, endpoint=False):
        for fb in np.linspace(0, 1, steps, endpoint=False):
            shift = fa * v1 + fb * v2 + np.array([-w / 2, -h / 2])
            found = []
            for i in range(-8, 9):
                for j in range(-8, 9):
                    off = i * v1 + j * v2 + shift + np.array([w / 2, h / 2])
                    for kind in "AB":
                        poly = affinity.translate(base[kind], *off)
                        if poly.within(rect):
                            found.append((kind, poly))
            if not found:
                continue
            # keep the largest edge-connected group so no tile floats alone
            glued = unary_union([p.buffer(0.05) for _, p in found])
            groups = [glued] if glued.geom_type == "Polygon" else list(glued.geoms)
            main = max(groups, key=lambda gg: sum(1 for _, p in found if gg.contains(p.representative_point())))
            keep = [(k, p) for k, p in found if main.contains(p.representative_point())]
            na = sum(1 for k, _ in keep if k == "A")
            score = (len(keep), -abs(na - (len(keep) - na)))
            if best is None or score > best[0]:
                best = (score, keep)
    return best[1] if best else []

def place_grid(tile0, rot, v1, v2, ni, nj):
    """Lay out ni x nj lattice cells (each = one shark + its 180-degree partner)."""
    base = {"A": tile0, "B": rot(tile0)}
    placed = []
    for i in range(ni):
        for j in range(nj):
            off = i * v1 + j * (v2 + v1)  # v2+v1 runs almost level, so pairs form straight rows
            for kind in "AB":
                placed.append((kind, affinity.translate(base[kind], *off)))
    return placed


def build(args):
    outline_px, lines_px, ellipses_px = read_svg(args.svg)
    s = args.scale

    def to_mm(pts):
        # SVG y grows downward; flip so the shark is the right way up in the slicer.
        return [(x * s, -y * s) for x, y in pts]

    tile0 = Polygon(to_mm(outline_px)).buffer(0)
    hx, hy = min(outline_px, key=lambda q: (q[0] - HALF_TURN_PX[0]) ** 2 + (q[1] - HALF_TURN_PX[1]) ** 2)
    center = np.array(to_mm([(hx, hy)])[0])  # midpoint of the straight edge
    rot = lambda g: affinity.rotate(g, 180, origin=tuple(center))

    # Face artwork: line strokes, eye rings, pupils.
    stroke = args.line_width
    art = [LineString(to_mm(p)).simplify(0.02).buffer(stroke / 2, cap_style=1) for p in lines_px if len(p) > 1]
    for cx, cy, rx, ry in ellipses_px:
        e = affinity.scale(Point(cx * s, -cy * s).buffer(1.0, 32), rx * s, ry * s)
        if min(rx, ry) * s < args.pupil_max:
            art.append(e)  # small ellipse: solid pupil
        else:
            art.append(e.boundary.buffer(stroke / 2))  # big ellipse: ring
    art = unary_union(art)

    # Lattice (in mm). The cell holds one tile plus its rotated partner.
    verts_px = np.array(outline_px + [(2 * hx - x, 2 * hy - y) for x, y in outline_px])
    v1 = refine_vector(verts_px, V1_APPROX) * [s, -s]
    v2 = refine_vector(verts_px, V2_APPROX) * [s, -s]
    print(f"lattice vectors (mm): v1=({v1[0]:.3f}, {v1[1]:.3f})  v2=({v2[0]:.3f}, {v2[1]:.3f})")

    if args.grid:
        ni, nj = (int(v) for v in args.grid.lower().split("x"))
        placed = place_grid(tile0, rot, v1, v2, ni, nj)
    else:
        placed = fill_rectangle(tile0, rot, v1, v2, args.area)
    if not placed:
        raise SystemExit("no whole tile fits in --area; make the area larger or the scale smaller")

    # Sanity check: neighbours must neither overlap nor leave gaps.
    total = sum(p.area for _, p in placed)
    mosaic = unary_union([p for _, p in placed])
    overlap = total - mosaic.area
    holes = sum(Polygon(r).area for g in ([mosaic] if mosaic.geom_type == "Polygon" else mosaic.geoms) for r in g.interiors)
    print(f"tiling check: tile area {tile0.area:.1f} mm2, overlap {overlap:.2f} mm2, interior gaps {holes:.2f} mm2")
    if overlap > 0.01 * total or holes > 0.01 * total:
        print("  WARNING: tiles overlap or leave gaps; lattice vectors may be wrong.")

    return dict(tile0=tile0, art=art, center=center, rot=rot, placed=placed, mosaic=mosaic, v1=v1, v2=v2)


def make_tile_mesh(nominal, art, args, kind):
    """One printable tile: flat base plus raised outline and face."""
    body = nominal.buffer(-args.gap / 2, join_style=2)
    ridge = body.difference(body.buffer(-args.ridge))
    face = art.intersection(body.buffer(-args.ridge / 2))
    raised = unary_union([ridge, face])
    return try_union(extrude(body, args.base) + extrude(raised, args.raised, z0=args.base)), body


def make_tile_parts(nominal, art, args):
    """Same tile as make_tile_mesh, but as two separate solids for two-colour printing.

    base    : flat shark shape, z = 0 .. base
    outline : raised perimeter ridge + face lines, z = base .. base+raised
    Both share one coordinate frame, so load them together as one multi-part
    object (PrusaSlicer: select both > right-click > Add part / "Assign to extruder").
    """
    body = nominal.buffer(-args.gap / 2, join_style=2)
    ridge = body.difference(body.buffer(-args.ridge))
    face = art.intersection(body.buffer(-args.ridge / 2))
    raised = unary_union([ridge, face])
    return combine(extrude(body, args.base)), combine(extrude(raised, args.raised, z0=args.base))


def make_board(g, args):
    pad = args.margin
    minx, miny, maxx, maxy = g["mosaic"].bounds
    plate = box(minx - pad, miny - pad, maxx + pad, maxy + pad)
    holes = []
    if args.push_holes:
        for _, poly in g["placed"]:
            body = poly.buffer(-args.gap / 2)
            core = body.buffer(-4)
            pt = (core if not core.is_empty else body).representative_point()
            holes.append(pt.buffer(args.push_hole_d / 2, 24))
    floor = plate.difference(unary_union(holes)) if holes else plate
    # Recess = outer outline of the whole group of sharks. Tiny interior voids between
    # tiles are filled in so no thin slivers of wall stand up inside the recess.
    parts = [g["mosaic"]] if g["mosaic"].geom_type == "Polygon" else list(g["mosaic"].geoms)
    recess = unary_union([Polygon(p.exterior) for p in parts])
    wall = plate.difference(recess)
    return try_union(extrude(floor, args.floor) + extrude(wall, args.base, z0=args.floor)), plate


def shelf_pack(items, bed_w, spacing=4.0):
    """Place identical bounding boxes in rows; returns (x, y) offsets and total height."""
    x = y = row_h = 0.0
    out = []
    for w, h in items:
        if x + w > bed_w and x > 0:
            x, y, row_h = 0.0, y + row_h + spacing, 0.0
        out.append((x, y))
        x += w + spacing
        row_h = max(row_h, h)
    return out, y + row_h


def make_plate(tile_mesh, n, bed_w):
    b = tile_mesh.bounds
    w, h = b[1][0] - b[0][0], b[1][1] - b[0][1]
    spots, total_h = shelf_pack([(w, h)] * n, bed_w)
    meshes = []
    for sx, sy in spots:
        m = tile_mesh.copy()
        m.apply_translation([sx - b[0][0], sy - b[0][1], 0])
        meshes.append(m)
    return combine(meshes), (max(x for x, _ in spots) + w, total_h)


def make_qr(args):
    qr = segno.make(args.url, error=args.qr_error, micro=False)
    mat = np.array(qr.matrix, dtype=bool)  # True = dark module
    n = mat.shape[0]
    q = args.qr_quiet
    mod = args.qr_module
    size = (n + 2 * q) * mod
    dark = []
    for r in range(n):
        for c in range(n):
            if mat[r, c]:
                x0 = (c + q) * mod
                y0 = (n - 1 - r + q) * mod  # image rows run top-down; STL y runs up
                dark.append(box(x0, y0, x0 + mod, y0 + mod).buffer(0.03, join_style=2))
    modules = unary_union(dark)
    plate = box(0, 0, size, size)
    mesh = try_union(extrude(plate, args.qr_base) + extrude(modules, args.qr_raise, z0=args.qr_base))
    print(f"  QR: {n}x{n} modules (version {qr.version}), plaque {size:.1f} mm square, module {mod} mm")
    return mesh


def _patch(ax, geom, **kw):
    from matplotlib.patches import PathPatch
    from matplotlib.path import Path as MPath
    for p in ([geom] if geom.geom_type == "Polygon" else getattr(geom, "geoms", [])):
        if p.geom_type != "Polygon" or p.is_empty:
            continue
        rings = [p.exterior] + list(p.interiors)
        verts = np.concatenate([np.array(r.coords) for r in rings])
        codes = np.concatenate([[MPath.MOVETO] + [MPath.LINETO] * (len(r.coords) - 2) + [MPath.CLOSEPOLY] for r in rings])
        ax.add_patch(PathPatch(MPath(verts, codes), **kw))


OUTLINE_COLOR = "#d62728"


def render_preview(g, plate, path, args=None):
    fig, ax = plt.subplots(figsize=(10, 7))
    colors = {"A": "#f6b73c", "B": "#4aa3df"}
    t0 = g["tile0"].bounds[:2]
    for kind, poly in g["placed"]:
        gap = args.gap if args else 0.4
        ridge_w = args.ridge if args else 1.2
        body = poly.buffer(-gap / 2, join_style=2)
        _patch(ax, poly, fc=colors[kind], ec="none", lw=0)
        _patch(ax, body.difference(body.buffer(-ridge_w)), fc=OUTLINE_COLOR, lw=0)
        ref = g["rot"](g["tile0"]) if kind == "B" else g["tile0"]
        off = np.array(poly.bounds[:2]) - np.array(ref.bounds[:2])
        art = g["rot"](g["art"]) if kind == "B" else g["art"]
        _patch(ax, affinity.translate(art, *off).intersection(body.buffer(-ridge_w / 2)), fc=OUTLINE_COLOR, lw=0)
    px, py = plate.exterior.xy
    ax.plot(px, py, "k-", lw=1)
    ax.autoscale_view()
    ax.set_aspect("equal")
    ax.set_title("Assembled puzzle: gold / blue = shark bases, red = raised outline + face (print in a 2nd colour)")
    fig.savefig(path, dpi=110, bbox_inches="tight")


# ----------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--svg", default=HERE / "BabyShark8.svg")
    ap.add_argument("--out", default=HERE / "stl")
    ap.add_argument("--scale", type=float, default=0.20, help="mm per SVG pixel (0.20 -> tile about 62 mm wide)")
    ap.add_argument("--grid", default="3x3",
                    help="lattice cells across x down; each cell is 2 sharks, so 3x3 = 18 sharks. "
                         "Use 'none' to fill --area instead")
    ap.add_argument("--area", default="200x150", help="WxH box (mm) the puzzle is cut to; only whole tiles inside it are used")
    ap.add_argument("--gap", type=float, default=0.4, help="clearance between neighbouring tiles (mm)")
    ap.add_argument("--base", type=float, default=3.0, help="tile thickness (mm)")
    ap.add_argument("--raised", type=float, default=1.5, help="raised outline/face height (mm)")
    ap.add_argument("--ridge", type=float, default=1.2, help="raised outline width (mm)")
    ap.add_argument("--line-width", type=float, default=0.9, help="face line width (mm)")
    ap.add_argument("--pupil-max", type=float, default=2.2, help="ellipses smaller than this radius (mm) are solid")
    ap.add_argument("--floor", type=float, default=2.0, help="board floor thickness (mm)")
    ap.add_argument("--margin", type=float, default=9.0, help="board border around the puzzle (mm)")
    ap.add_argument("--push-holes", action=argparse.BooleanOptionalAction, default=False,
                    help="hole under each tile so it can be pushed out from below")
    ap.add_argument("--push-hole-d", type=float, default=8.0)
    ap.add_argument("--bed", type=float, default=220.0, help="print bed width used to arrange tile plates (mm)")
    ap.add_argument("--url", default="https://something.us.com", help="address the QR code opens")
    ap.add_argument("--qr-error", default="m", choices=list("lmqh"))
    ap.add_argument("--qr-module", type=float, default=1.6, help="QR square size (mm); keep a multiple of the nozzle")
    ap.add_argument("--qr-quiet", type=int, default=4, help="blank border, in modules")
    ap.add_argument("--qr-base", type=float, default=2.0)
    ap.add_argument("--qr-raise", type=float, default=1.0)
    args = ap.parse_args()
    if args.grid.lower() == "none":
        args.grid = None
    args.area = tuple(float(v) for v in args.area.lower().split("x"))
    out = Path(args.out)

    g = build(args)
    print("writing STL files:")
    tile_a, _ = make_tile_mesh(g["placed"][0][1], g["art"], args, "A")
    save(tile_a, out / "tile.stl")
    na = sum(1 for k, _ in g["placed"] if k == "A")
    nb = len(g["placed"]) - na
    print(f"puzzle: {na + nb} sharks ({na} upright + {nb} upside-down)")
    base_m, outline_m = make_tile_parts(g["placed"][0][1], g["art"], args)
    save(base_m, out / "tile_base.stl")
    save(outline_m, out / "tile_outline.stl")
    plate_a, _ = make_plate(tile_a, na, args.bed)
    save(plate_a, out / "tiles_color_A.stl")
    if nb:
        plate_b, _ = make_plate(tile_a, nb, args.bed)  # partners are the same shape, turned 180 degrees
        save(plate_b, out / "tiles_color_B.stl")
    # Two-colour plates: identical layout, split into base + outline solids.
    for name, n in (("A", na), ("B", nb)):
        if n:
            pb, _ = make_plate(base_m, n, args.bed)
            po, _ = make_plate(outline_m, n, args.bed)
            save(pb, out / f"tiles_color_{name}_base.stl")
            save(po, out / f"tiles_color_{name}_outline.stl")
    board, plate = make_board(g, args)
    save(board, out / "board.stl")
    save(make_qr(args), out / "qr_plaque.stl")
    render_preview(g, plate, out / "preview.png", args)
    if "something.us.com" in args.url:
        print("NOTE: QR code uses the placeholder URL; rerun with --url once the website address is final.")


if __name__ == "__main__":
    main()