Back to Nappakura
SOURCE / PINNED RELEASE

Made of little things.

Nappakura

Release
a75ca0f8b596…
Author-recorded commit
4463126213fa…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-8db03001b62

Archive hash verified: b448d77b767ae754…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/unfold.ts
import { seamEdges, internalEdge, cross2, distance, dot, cross, sub, overlaps } from './mesh.js';
import type { Mesh, V2, Edge } from './mesh.js';

export interface FlatFace {
  face: number;
  points: V2[];
}
export interface Piece {
  id: number;
  faces: FlatFace[];
  x: number;
  y: number;
  rotation: number;
  page: number;
}
export interface PrintSettings {
  size: number;
  paper: 'a4' | 'letter';
  landscape: boolean;
  margin: number;
  tabDepth: number;
  tabTaper: number;
  lineWidth: number;
  labels: boolean;
  labelSize: number;
  tabs: boolean;
}
export interface Pattern {
  pieces: Piece[];
  joined: number[];
  flipped: number[];
  hiddenTabs: number[];
  settings: PrintSettings;
}
export interface Line {
  a: V2;
  b: V2;
  kind: 'cut' | 'mountain' | 'valley' | 'flat';
  edge: number;
  face: number;
}
export interface Label {
  point: V2;
  text: string;
  size: number;
  angle: number;
  box: V2[];
}
export interface PieceDrawing {
  polygons: { face: number; points: V2[] }[];
  tabs: V2[][];
  lines: Line[];
  labels: Label[];
  omitted: number;
}
export const DEFAULT_SETTINGS: PrintSettings = {
  size: 100,
  paper: 'a4',
  landscape: false,
  margin: 10,
  tabDepth: 5,
  tabTaper: 0.25,
  lineWidth: 0.18,
  labels: true,
  labelSize: 2.4,
  tabs: true,
};
export const paperSize = (s: PrintSettings): V2 => {
  const p: V2 = s.paper === 'letter' ? [215.9, 279.4] : [210, 297];
  return s.landscape ? [p[1], p[0]] : p;
};
export function bounds(points: V2[]) {
  return {
    minX: Math.min(...points.map((p) => p[0])),
    minY: Math.min(...points.map((p) => p[1])),
    maxX: Math.max(...points.map((p) => p[0])),
    maxY: Math.max(...points.map((p) => p[1])),
  };
}

function rootFace(mesh: Mesh, face: number): FlatFace {
  const [a, b, c] = mesh.faces[face].map((i) => mesh.vertices[i]),
    ab = distance(a, b),
    ac = distance(a, c),
    bc = distance(b, c);
  const x = (ab * ab + ac * ac - bc * bc) / (2 * ab),
    y = Math.sqrt(Math.max(0, ac * ac - x * x));
  return {
    face,
    points: [
      [0, 0],
      [ab, 0],
      [x, y],
    ],
  };
}

function adjacent(mesh: Mesh, flat: FlatFace, next: number, edge: Edge): FlatFace {
  const ids = mesh.faces[flat.face],
    a = flat.points[ids.indexOf(edge.a)],
    b = flat.points[ids.indexOf(edge.b)];
  const c = flat.points[ids.findIndex((id) => id !== edge.a && id !== edge.b)];
  const nextIds = mesh.faces[next],
    apex = nextIds.find((id) => id !== edge.a && id !== edge.b)!;
  const len = Math.hypot(b[0] - a[0], b[1] - a[1]),
    ac = distance(mesh.vertices[edge.a], mesh.vertices[apex]),
    bc = distance(mesh.vertices[edge.b], mesh.vertices[apex]);
  const x = (len * len + ac * ac - bc * bc) / (2 * len),
    y = Math.sqrt(Math.max(0, ac * ac - x * x)) * (cross2(a, b, c) > 0 ? -1 : 1);
  const dx = (b[0] - a[0]) / len,
    dy = (b[1] - a[1]) / len;
  const point: V2 = [a[0] + dx * x - dy * y, a[1] + dy * x + dx * y];
  return {
    face: next,
    points: nextIds.map((id) => (id === edge.a ? [...a] : id === edge.b ? [...b] : point)) as V2[],
  };
}

export function unfold(
  mesh: Mesh,
  onlyJoined?: Set<number>,
  maxSize?: V2,
): { pieces: Piece[]; joined: number[] } {
  const visited = new Set<number>(),
    pieces: Piece[] = [],
    joined: number[] = [];
  // Grow a whole planar polygon atomically; never cut its triangulation to fit paper.
  const polygon = (seed: FlatFace) => {
    const faces = [seed],
      ids = new Set([seed.face]),
      joins: number[] = [];
    for (let i = 0; i < faces.length; i++)
      for (const id of mesh.faceEdges[faces[i].face]) {
        const e = mesh.edges[id];
        if (!internalEdge(mesh, e)) continue;
        const next = e.faces.find((f) => f !== faces[i].face)!;
        if (ids.has(next)) continue;
        ids.add(next);
        joins.push(id);
        faces.push(adjacent(mesh, faces[i], next, e));
      }
    return { faces, joins };
  };
  for (let root = 0; root < mesh.faces.length; root++) {
    if (visited.has(root)) continue;
    const initial = polygon(rootFace(mesh, root)),
      faces = initial.faces;
    faces.forEach((f) => visited.add(f.face));
    joined.push(...initial.joins);
    for (let k = 0; k < faces.length; k++) {
      const current = faces[k];
      const candidates = mesh.faceEdges[current.face]
        .map((i) => mesh.edges[i])
        .filter(
          (e) =>
            !internalEdge(mesh, e) && e.faces.length === 2 && (!onlyJoined || onlyJoined.has(e.id)),
        );
      candidates.sort(
        (a, b) =>
          dot(mesh.normals[current.face], mesh.normals[b.faces.find((f) => f !== current.face)!]) -
          dot(mesh.normals[current.face], mesh.normals[a.faces.find((f) => f !== current.face)!]),
      );
      for (const edge of candidates) {
        const next = edge.faces.find((f) => f !== current.face)!;
        if (visited.has(next)) continue;
        const proposed = polygon(adjacent(mesh, current, next, edge));
        const box = bounds([...faces, ...proposed.faces].flatMap((f) => f.points));
        const width = box.maxX - box.minX,
          height = box.maxY - box.minY;
        if (
          maxSize &&
          !(
            (width <= maxSize[0] && height <= maxSize[1]) ||
            (width <= maxSize[1] && height <= maxSize[0])
          )
        )
          continue;
        if (proposed.faces.some((p) => faces.some((f) => overlaps(f.points, p.points)))) {
          if (onlyJoined)
            throw new Error('That join would overlap faces. Cut a different seam first.');
          continue;
        }
        faces.push(...proposed.faces);
        proposed.faces.forEach((f) => visited.add(f.face));
        joined.push(...seamEdges(mesh, edge), ...proposed.joins);
      }
    }
    const box = bounds(faces.flatMap((f) => f.points));
    faces.forEach((f) =>
      f.points.forEach((p) => {
        p[0] -= box.minX;
        p[1] -= box.minY;
      }),
    );
    pieces.push({ id: pieces.length, faces, x: 0, y: 0, rotation: 0, page: 0 });
  }
  if (
    onlyJoined &&
    [...onlyJoined].some((id) => !internalEdge(mesh, mesh.edges[id]) && !joined.includes(id))
  )
    throw new Error('That join would close a cycle. Cut another edge in this piece first.');
  return { pieces, joined };
}

export function newPattern(mesh: Mesh, settings = { ...DEFAULT_SETTINGS }): Pattern {
  const paper = paperSize(settings),
    reserve = 2 * settings.margin + (settings.tabs ? 2 * settings.tabDepth : 0);
  const { pieces, joined } = unfold(mesh, undefined, [
    (paper[0] - reserve) / settings.size,
    (paper[1] - reserve) / settings.size,
  ]);
  const pattern = { pieces, joined, flipped: [], hiddenTabs: [], settings };
  repairTabSeams(mesh, pattern);
  pack(mesh, pattern);
  return pattern;
}

export function toggleSeam(mesh: Mesh, pattern: Pattern, edgeId: number) {
  const edge = mesh.edges[edgeId];
  if (!edge || edge.faces.length !== 2)
    throw new Error('Only an edge shared by exactly two faces can be joined.');
  if (internalEdge(mesh, edge))
    throw new Error('This is an internal polygon diagonal, not a paper seam.');
  const joined = new Set(pattern.joined);
  if (joined.has(edgeId)) seamEdges(mesh, edge).forEach((id) => joined.delete(id));
  else seamEdges(mesh, edge).forEach((id) => joined.add(id));
  const result = unfold(mesh, joined);
  pattern.pieces = result.pieces;
  pattern.joined = result.joined;
  pack(mesh, pattern);
}

export function transform(p: V2, piece: Piece, size: number): V2 {
  const a = (piece.rotation * Math.PI) / 180,
    c = Math.cos(a),
    s = Math.sin(a);
  return [piece.x + size * (p[0] * c - p[1] * s), piece.y + size * (p[0] * s + p[1] * c)];
}

function foldKind(mesh: Mesh, e: Edge): Line['kind'] {
  if (e.faces.length !== 2) return 'cut';
  const [f1, f2] = e.faces,
    n1 = mesh.normals[f1],
    n2 = mesh.normals[f2];
  if (dot(n1, n2) > 0.99999) return 'flat';
  const face = mesh.faces[f1],
    a = face.indexOf(e.a),
    forward = face[(a + 1) % 3] === e.b;
  const direction = sub(mesh.vertices[forward ? e.b : e.a], mesh.vertices[forward ? e.a : e.b]);
  return dot(cross(n1, n2), direction) * (mesh.inverted ? -1 : 1) > 0 ? 'mountain' : 'valley';
}

// Convex clipping lets the folded tab be checked against a whole (possibly
// concave) recipient polygon represented by non-overlapping rendering triangles.
const area2 = (p: V2[]) =>
  Math.abs(
    p.reduce((sum, a, i) => {
      const b = p[(i + 1) % p.length];
      return sum + a[0] * b[1] - b[0] * a[1];
    }, 0),
  ) / 2;
function intersection(subject: V2[], triangle: V2[]) {
  let out = subject;
  const sign = Math.sign(cross2(triangle[0], triangle[1], triangle[2]));
  for (let j = 0; j < 3; j++) {
    const a = triangle[j],
      b = triangle[(j + 1) % 3],
      input = out;
    out = [];
    for (let i = 0; i < input.length; i++) {
      const p = input[i],
        q = input[(i + 1) % input.length],
        dp = sign * cross2(a, b, p),
        dq = sign * cross2(a, b, q);
      if (dp >= -1e-8) out.push(p);
      if (dp >= 0 !== dq >= 0) {
        const t = dp / (dp - dq);
        out.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
      }
    }
  }
  return out;
}
function recipientTriangles(mesh: Mesh, edge: Edge, owner: number, size: number): V2[][] {
  const receiver = edge.faces.find((f) => f !== owner)!,
    a = mesh.vertices[edge.a],
    b = mesh.vertices[edge.b];
  const u = sub(b, a),
    len = distance(a, b),
    n = mesh.normals[receiver];
  const x = u.map((v) => v / len) as [number, number, number];
  let y = cross(n, x);
  const third = mesh.faces[receiver].find((i) => i !== edge.a && i !== edge.b)!;
  if (dot(sub(mesh.vertices[third], a), y) < 0) y = y.map((v) => -v) as typeof y;
  return mesh.faces.flatMap((f, i) =>
    mesh.facePolygons[i] === mesh.facePolygons[receiver]
      ? [
          f.map((v) => {
            const p = sub(mesh.vertices[v], a);
            return [dot(p, x) * size, dot(p, y) * size] as V2;
          }),
        ]
      : [],
  );
}
export function tabFitsRecipient(
  mesh: Mesh,
  edge: Edge,
  owner: number,
  footprint: V2[],
  size: number,
) {
  const covered = recipientTriangles(mesh, edge, owner, size).reduce(
    (n, t) => n + area2(intersection(footprint, t)),
    0,
  );
  return Math.abs(covered - area2(footprint)) < 1e-5;
}
function tabTopInterval(triangles: V2[][], depth: number): V2 | undefined {
  const intervals: V2[] = [];
  for (const t of triangles) {
    const xs: number[] = [];
    for (let i = 0; i < 3; i++) {
      const a = t[i],
        b = t[(i + 1) % 3];
      if (Math.abs(a[1] - depth) < 1e-8) xs.push(a[0]);
      if (a[1] < depth !== b[1] < depth)
        xs.push(a[0] + ((depth - a[1]) / (b[1] - a[1])) * (b[0] - a[0]));
    }
    if (xs.length >= 2) intervals.push([Math.min(...xs), Math.max(...xs)]);
  }
  intervals.sort((a, b) => a[0] - b[0]);
  const merged: V2[] = [];
  for (const i of intervals) {
    const last = merged.at(-1);
    if (last && i[0] <= last[1] + 1e-7) last[1] = Math.max(last[1], i[1]);
    else merged.push([...i]);
  }
  return merged.sort((a, b) => b[1] - b[0] - (a[1] - a[0]))[0];
}

// Plan ownership across the complete net, in local millimetres. Sheet movement
// and rotation must not change which matching edge receives the tab.
export function planTabs(mesh: Mesh, pattern: Pattern) {
  const s = pattern.settings;
  const faces = pattern.pieces.flatMap((piece) =>
    piece.faces.map((f) => ({
      piece: piece.id,
      face: f.face,
      points: f.points.map((p) => [p[0] * s.size, p[1] * s.size] as V2),
    })),
  );
  const byFace = new Map(faces.map((f) => [f.face, f]));
  const tabs = new Map<number, { face: number; piece: number; points: V2[] }>();
  if (!s.tabs) return tabs;
  const joined = new Set(pattern.joined),
    hidden = new Set(pattern.hiddenTabs);
  for (const e of mesh.edges) {
    if (e.faces.length !== 2 || internalEdge(mesh, e) || joined.has(e.id) || hidden.has(e.id))
      continue;
    const owners = pattern.flipped.includes(e.id) ? [...e.faces].reverse() : e.faces;
    for (const face of owners) {
      const poly = byFace.get(face)!;
      const ids = mesh.faces[face],
        a = poly.points[ids.indexOf(e.a)],
        b = poly.points[ids.indexOf(e.b)],
        c = poly.points[ids.findIndex((id) => id !== e.a && id !== e.b)],
        dx = b[0] - a[0],
        dy = b[1] - a[1],
        len = Math.hypot(dx, dy),
        sign = cross2(a, b, c) > 0 ? -1 : 1;
      const normal: V2 = [(-dy / len) * sign, (dx / len) * sign];
      for (const factor of [1, 0.7, 0.4, 0.2]) {
        const depth = Math.min(s.tabDepth, len * 0.45) * factor,
          inset = Math.min(len * s.tabTaper, depth * 0.9),
          corner = Math.min(0.4, len * 0.08);
        const interval = tabTopInterval(recipientTriangles(mesh, e, face, s.size), depth);
        if (!interval) continue;
        const left = Math.max(inset, interval[0] + corner),
          right = Math.min(len - inset, interval[1] - corner);
        const footprint: V2[] = [
          [corner, 0],
          [left, depth],
          [right, depth],
          [len - corner, 0],
        ];
        if (right - left < 1 || !tabFitsRecipient(mesh, e, face, footprint, s.size)) continue;
        const points: V2[] = [
          [a[0] + (dx / len) * corner, a[1] + (dy / len) * corner],
          [
            a[0] + (dx / len) * left + normal[0] * depth,
            a[1] + (dy / len) * left + normal[1] * depth,
          ],
          [
            a[0] + (dx / len) * right + normal[0] * depth,
            a[1] + (dy / len) * right + normal[1] * depth,
          ],
          [b[0] - (dx / len) * corner, b[1] - (dy / len) * corner],
        ];
        if (
          depth >= 1 &&
          !faces.some((f) => f.piece === poly.piece && overlaps(f.points, points)) &&
          ![...tabs.values()].some((t) => t.piece === poly.piece && overlaps(t.points, points))
        ) {
          tabs.set(e.id, { face, piece: poly.piece, points });
          break;
        }
      }
      if (tabs.has(e.id)) break;
    }
  }
  return tabs;
}

/** Improve automatic seam choices without changing geometry or physical scale.
 * Every accepted change strictly reduces missing tabs; impossible nets stay errors.
 * Manual seam edits are never silently changed by Arrange or export.
 */
function repairTabSeams(mesh: Mesh, pattern: Pattern) {
  if (!pattern.settings.tabs) return;
  const missing = (p: Pattern) => {
    const planned = planTabs(mesh, p);
    return mesh.edges.filter(
      (e) =>
        e.faces.length === 2 &&
        !internalEdge(mesh, e) &&
        !p.joined.includes(e.id) &&
        !planned.has(e.id),
    );
  };
  for (;;) {
    const blocked = missing(pattern);
    if (!blocked.length) return;
    let best: Pattern | undefined,
      count = blocked.length;
    for (const edge of blocked) {
      // Swap a fold on the existing tree path for the blocked cut edge.
      const path = (
        face: number,
        target: number,
        seen = new Set<number>(),
      ): number[] | undefined => {
        if (face === target) return [];
        seen.add(face);
        for (const id of mesh.faceEdges[face]) {
          if (!pattern.joined.includes(id)) continue;
          const next = mesh.edges[id].faces.find((f) => f !== face)!;
          if (seen.has(next)) continue;
          const rest = path(next, target, seen);
          if (rest) return [id, ...rest];
        }
      };
      const route = path(edge.faces[0], edge.faces[1]);
      const alternatives = route
        ?.filter((cut) => !internalEdge(mesh, mesh.edges[cut]))
        .map((cut) =>
          pattern.joined
            .filter((e) => !seamEdges(mesh, mesh.edges[cut]).includes(e))
            .concat(seamEdges(mesh, edge)),
        ) ?? [pattern.joined.concat(edge.id)];
      // Splitting a neighbouring fold can also free space for a tab.
      for (const cut of edge.faces
        .flatMap((f) => mesh.faceEdges[f])
        .filter((id) => pattern.joined.includes(id) && !internalEdge(mesh, mesh.edges[id])))
        alternatives.push(
          pattern.joined.filter((id) => !seamEdges(mesh, mesh.edges[cut]).includes(id)),
        );
      for (const joins of alternatives) {
        try {
          const candidate: Pattern = {
            ...pattern,
            ...unfold(mesh, new Set(joins)),
          };
          const [w, h] = paperSize(pattern.settings),
            reserve = 2 * (pattern.settings.margin + pattern.settings.tabDepth);
          if (
            candidate.pieces.some((p) => {
              const b = bounds(p.faces.flatMap((f) => f.points)),
                x = (b.maxX - b.minX) * pattern.settings.size,
                y = (b.maxY - b.minY) * pattern.settings.size;
              return !(
                (x <= w - reserve && y <= h - reserve) ||
                (y <= w - reserve && x <= h - reserve)
              );
            })
          )
            continue;
          const n = missing(candidate).length;
          if (n < count) {
            best = candidate;
            count = n;
          }
        } catch {
          /* This alternative closes a cycle or overlaps faces. */
        }
      }
    }
    if (!best) return;
    pattern.pieces = best.pieces;
    pattern.joined = best.joined;
  }
}

export function drawPiece(
  mesh: Mesh,
  pattern: Pattern,
  piece: Piece,
  planned = planTabs(mesh, pattern),
): PieceDrawing {
  const { settings: s } = pattern,
    joined = new Set(pattern.joined);
  const polygons = piece.faces.map((f) => ({
    face: f.face,
    points: f.points.map((p) => transform(p, piece, s.size)),
  }));
  const lines: Line[] = [],
    labels: Label[] = [],
    tabs: V2[][] = [];
  let omitted = 0;
  const drawn = new Set<number>();
  for (const poly of polygons) {
    const ids = mesh.faces[poly.face];
    for (const edgeId of mesh.faceEdges[poly.face]) {
      if (internalEdge(mesh, mesh.edges[edgeId])) continue;
      const e = mesh.edges[edgeId],
        a = poly.points[ids.indexOf(e.a)],
        b = poly.points[ids.indexOf(e.b)];
      if (joined.has(edgeId)) {
        if (!drawn.has(edgeId)) {
          lines.push({
            a,
            b,
            kind: foldKind(mesh, e),
            edge: edgeId,
            face: poly.face,
          });
          drawn.add(edgeId);
        }
        continue;
      }
      const dx = b[0] - a[0],
        dy = b[1] - a[1];
      const mid: V2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
      const placement = planned.get(edgeId);
      const tab =
        placement?.face === poly.face
          ? placement.points.map((p) => transform(p, piece, 1))
          : undefined;
      if (e.faces.length === 2 && e.faces[0] === poly.face && !placement) omitted++;
      if (tab) {
        tabs.push(tab);
        lines.push({ a, b, kind: 'valley', edge: edgeId, face: poly.face });
        lines.push({
          a,
          b: tab[0],
          kind: 'cut',
          edge: edgeId,
          face: poly.face,
        });
        lines.push({
          a: tab[3],
          b,
          kind: 'cut',
          edge: edgeId,
          face: poly.face,
        });
        for (let i = 0; i < 3; i++)
          lines.push({
            a: tab[i],
            b: tab[i + 1],
            kind: 'cut',
            edge: edgeId,
            face: poly.face,
          });
      } else lines.push({ a, b, kind: 'cut', edge: edgeId, face: poly.face });
      if (s.labels && e.faces.length === 2) {
        const text = String(e.id + 1);
        let angle = Math.atan2(dy, dx);
        if (angle > Math.PI / 2) angle -= Math.PI;
        if (angle < -Math.PI / 2) angle += Math.PI;
        if (Math.abs(Math.abs(angle) - Math.PI / 2) < 1e-8) angle = Math.PI / 2;
        const regions = tab ? [poly.points, tab] : [poly.points];
        let label: Label | undefined;
        const inside = (p: V2, region: V2[]) => {
          const signs = region.map((a, i) => cross2(a, region[(i + 1) % region.length], p));
          return signs.every((v) => v >= -1e-6) || signs.every((v) => v <= 1e-6);
        };
        for (const size of [s.labelSize, 2].filter((n) => n <= s.labelSize && n >= 2)) {
          for (const region of regions) {
            const center: V2 = [
              region.reduce((sum, p) => sum + p[0], 0) / region.length,
              region.reduce((sum, p) => sum + p[1], 0) / region.length,
            ];
            for (const t of [0.35, 0.6, 0.85, 1]) {
              const point: V2 = [
                mid[0] + (center[0] - mid[0]) * t,
                mid[1] + (center[1] - mid[1]) * t,
              ];
              const w = text.length * size * 0.6 + 0.25,
                h = size + 0.25;
              const box: V2[] = [
                [-w / 2, -h / 2],
                [w / 2, -h / 2],
                [w / 2, h / 2],
                [-w / 2, h / 2],
              ].map(([x, y]) => [
                point[0] + x * Math.cos(angle) - y * Math.sin(angle),
                point[1] + x * Math.sin(angle) + y * Math.cos(angle),
              ]);
              if (
                box.every((p) => inside(p, region)) &&
                !labels.some((l) => overlaps(l.box, box))
              ) {
                label = { point, text, size, angle, box };
                break;
              }
            }
            if (label) break;
          }
          if (label) break;
        }
        if (label) labels.push(label);
      }
    }
  }
  return { polygons, tabs, lines, labels, omitted };
}

export function pieceBounds(mesh: Mesh, pattern: Pattern, piece: Piece) {
  const drawing = drawPiece(mesh, pattern, piece);
  return bounds([...drawing.polygons.flatMap((p) => p.points), ...drawing.tabs.flat()]);
}

export function pack(mesh: Mesh, pattern: Pattern) {
  const s = pattern.settings,
    [width, height] = paperSize(s),
    gap = 5;
  let x = s.margin,
    y = s.margin,
    rowHeight = 0,
    page = 0;
  for (const piece of pattern.pieces) {
    piece.x = piece.y = 0;
    piece.rotation = 0;
    let box = pieceBounds(mesh, pattern, piece),
      w = box.maxX - box.minX,
      h = box.maxY - box.minY;
    if (
      (w > width - 2 * s.margin && h <= width - 2 * s.margin) ||
      (h > w && h < width - 2 * s.margin)
    ) {
      piece.rotation = 90;
      box = pieceBounds(mesh, pattern, piece);
      w = box.maxX - box.minX;
      h = box.maxY - box.minY;
    }
    if (x + w > width - s.margin + 1e-6 && x > s.margin) {
      x = s.margin;
      y += rowHeight + gap;
      rowHeight = 0;
    }
    if (y + h > height - s.margin + 1e-6 && y > s.margin) {
      page++;
      x = s.margin;
      y = s.margin;
      rowHeight = 0;
    }
    piece.x = x - box.minX;
    piece.y = y - box.minY;
    piece.page = page;
    x += w + gap;
    rowHeight = Math.max(rowHeight, h);
  }
}

export function printIssues(mesh: Mesh, pattern: Pattern): string[] {
  const [width, height] = paperSize(pattern.settings),
    m = pattern.settings.margin;
  const issues: string[] = [],
    planned = planTabs(mesh, pattern),
    drawings = pattern.pieces.map((p) => drawPiece(mesh, pattern, p, planned));
  const missing = mesh.edges.filter(
    (e) =>
      e.faces.length === 2 &&
      !internalEdge(mesh, e) &&
      !pattern.joined.includes(e.id) &&
      !planned.has(e.id),
  );
  const labelCounts = new Map<number, number>();
  for (const d of drawings)
    for (const l of d.labels)
      labelCounts.set(Number(l.text), (labelCounts.get(Number(l.text)) ?? 0) + 1);
  const unlabelled = mesh.edges.filter(
    (e) =>
      e.faces.length === 2 &&
      !internalEdge(mesh, e) &&
      !pattern.joined.includes(e.id) &&
      labelCounts.get(e.id + 1) !== 2,
  );
  if (unlabelled.length)
    issues.push(
      `${unlabelled.length} assembly join${unlabelled.length === 1 ? ' needs' : 's need'} matching readable edge numbers (edges ${unlabelled.map((e) => e.id + 1).join(', ')}). Enable labels at least 2 mm high or enlarge the model before exporting.`,
    );
  if (missing.length)
    issues.push(
      `${missing.length} assembly join${missing.length === 1 ? ' is' : 's are'} missing a usable glue tab (edges ${missing.map((e) => e.id + 1).join(', ')}). Enable/show tabs, switch sides, cut another seam or enlarge the model before exporting.`,
    );
  let outside = 0,
    collisions = 0;
  pattern.pieces.forEach((piece, i) => {
    const d = drawings[i],
      box = bounds([...d.polygons.flatMap((p) => p.points), ...d.tabs.flat()]);
    if (
      box.minX < m - 0.01 ||
      box.minY < m - 0.01 ||
      box.maxX > width - m + 0.01 ||
      box.maxY > height - m + 0.01
    )
      outside++;
    for (let j = 0; j < i; j++) {
      if (piece.page !== pattern.pieces[j].page) continue;
      const other = drawings[j];
      if (
        [...d.polygons.map((p) => p.points), ...d.tabs].some((a) =>
          [...other.polygons.map((p) => p.points), ...other.tabs].some((b) => overlaps(a, b, 0.01)),
        )
      )
        collisions++;
    }
  });
  if (outside)
    issues.push(
      `${outside} piece${outside === 1 ? ' is' : 's are'} outside the printable margins. Move, rotate, cut or reduce model size.`,
    );
  if (collisions)
    issues.push(
      `${collisions} overlapping piece pair${collisions === 1 ? '' : 's'}. Move pieces or use Arrange.`,
    );
  if (pageCount(pattern) > 64)
    issues.push('More than 64 sheets. Reduce model size or join pieces before exporting.');
  return issues;
}
export const pageCount = (pattern: Pattern) =>
  Math.max(1, ...pattern.pieces.map((p) => p.page + 1));