{
  "name": "ship",
  "title": "Ship",
  "type": "registry:component",
  "description": "A big three-masted sailing ship you can board and walk through: a plank up from the dock, the waist, the quarterdeck with its wheel, the forecastle with its bell and bowsprit, a gun deck with a cannon at every port and hammocks slung forward, a cargo hold, and the captain's cabin under the stern windows. Lanterns light the decks below. Seeded planking, sails, gunport lids and cargo; moored and steady.",
  "dependencies": [
    "@react-three/rapier@^2.2.0",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [
    "barrel",
    "bed",
    "chair",
    "crate",
    "flag",
    "staircase",
    "table"
  ],
  "files": [
    {
      "path": "Ship.tsx",
      "content": "import {\n  ConvexHullCollider,\n  CuboidCollider,\n  CylinderCollider,\n  RigidBody,\n  TrimeshCollider,\n} from '@react-three/rapier'\nimport { useMaterials, useWorld, type WorldComponentProps } from '@runek/core'\nimport { useEffect, useMemo } from 'react'\nimport { BoxGeometry, Color, DoubleSide, Euler, Matrix4, Quaternion, Vector3 } from 'three'\nimport { Flag } from './Flag'\nimport { buildBulkhead, buildDeck, bulkheads, deckBeams, deckHulls, shipDecks } from './ship/decks'\nimport { Furnishing, Stairs } from './ship/Furnishing'\nimport {\n  cabinTable,\n  cargoLayout,\n  furnishLayout,\n  gunLayout,\n  hammockLayout,\n  lanternLayout,\n} from './ship/fittings'\nimport { buildHull, gangwayGap, hullCollider } from './ship/hull'\nimport { MeshBuilder, type V3 } from './ship/mesh'\nimport {\n  Anchors,\n  Bell,\n  CannonColliders,\n  Cannons,\n  Capstan,\n  Gangway,\n  GangwayColliders,\n  gangwayPlan,\n  Hammocks,\n  Instanced,\n  Lantern,\n  type Mats,\n  Ports,\n  Rudder,\n  Wheel,\n  WheelColliders,\n} from './ship/parts'\nimport { Rig } from './ship/Rig'\nimport { rigLayout, type SailPlan } from './ship/rigging'\nimport {\n  gangwayReach,\n  innerBreadth,\n  LEVEL,\n  type ShipLayout,\n  SKIN,\n  shipLayout,\n  shipShape,\n  shipSurface,\n  sternZ,\n} from './surfaces/ship'\n\nexport interface ShipProps extends WorldComponentProps {\n  /** Hull length from stern to stem, in units (30 to 60). Deck heights, stairs and doors keep\n   *  human scale; the length spreads the layout. */\n  length?: number\n  /** Hull breadth at its widest, in units (8 to 16). */\n  beam?: number\n  /** 3 for fore, main and mizzen; 2 drops the mizzen; 1 keeps only the main. */\n  masts?: number\n  /** Sails set and drawing, furled on their yards, or bare spars. */\n  sails?: SailPlan\n  /** Cannons a side on the gun deck (0 for none); the waist carries a few more. */\n  guns?: number\n  /** Which side the boarding plank runs out from, or none. */\n  gangway?: 'starboard' | 'port' | 'none'\n  /** How far below the main deck the plank's shore end sits, in units: a dock deck's height\n   *  under the main deck (which stands 4.8 above the waterline). */\n  gangwayDrop?: number\n  /** Fit out the cabin, crew quarters, mess and hold with furniture and cargo. */\n  furnish?: boolean\n  /** Hang lit lanterns below decks and on the stern. */\n  lanterns?: boolean\n  /** Fly a flag from the main truck. */\n  flag?: boolean\n  /** The hull, decks and fittings are solid (board it and walk the decks). Off, they are a bare\n   *  visual; the stairs and furniture it is fitted out with keep their own colliders. */\n  collider?: boolean\n  /** Topsides colour; defaults to the world palette's `woodDark`. */\n  hullColor?: string\n  /** The painted band along the gunports. */\n  bandColor?: string\n  /** Deck planking; defaults to the palette's `floor`. */\n  deckColor?: string\n  sailColor?: string\n  flagColor?: string\n}\n\nconst compose = (p: V3, r: V3 = [0, 0, 0], s: V3 = [1, 1, 1]) =>\n  new Matrix4().compose(\n    new Vector3(...p),\n    new Quaternion().setFromEuler(new Euler(...r)),\n    new Vector3(...s),\n  )\n\ninterface Rail {\n  key: string\n  y: number\n  x0: number\n  z0: number\n  x1: number\n  z1: number\n}\n\n/** Rails round each hatch (open at the stair's head) and along each castle's break. */\nfunction rails(lay: ShipLayout): Rail[] {\n  const { main, gun, quarter, fore } = LEVEL\n  const out: Rail[] = []\n  const hatch = (key: string, y: number, h: ShipLayout['hatchA'], end: number) => {\n    const w = h.w / 2 + 0.05\n    out.push({ key: `${key}p`, y, x0: w, z0: h.z0, x1: w, z1: h.z1 })\n    out.push({ key: `${key}s`, y, x0: -w, z0: h.z0, x1: -w, z1: h.z1 })\n    out.push({ key: `${key}e`, y, x0: -w, z0: end, x1: w, z1: end })\n  }\n  hatch('a', main, lay.hatchA, lay.hatchA.z1)\n  hatch('b', gun, lay.hatchB, lay.hatchB.z0)\n  const qx = Math.abs(lay.quarterStairs[0].x) - lay.quarterStairs[0].w / 2 - 0.05\n  out.push({ key: 'q', y: quarter, x0: -qx, z0: lay.zQ - 0.05, x1: qx, z1: lay.zQ - 0.05 })\n  const fx = Math.abs(lay.foreStairs[0].x) - lay.foreStairs[0].w / 2 - 0.05\n  out.push({ key: 'f', y: fore, x0: -fx, z0: lay.zF + 0.05, x1: fx, z1: lay.zF + 0.05 })\n  return out\n}\n\n/**\n * A big three-masted sailing ship you can board and walk through. A plank runs up from the dock\n * to the waist; hatches drop to the gun deck (a cannon at every port, hammocks slung forward, a\n * mess table) and on down to the cargo hold. Stairs climb to the quarterdeck (the wheel) and\n * the forecastle (the bell, the bowsprit), and doors at each break open into the captain's\n * cabin under the stern windows and the crew quarters in the bow. Lanterns light the decks\n * below. The hull is lofted from one shape that the decks, the colliders and the deck surface\n * all share; the seed varies the planking, the sails, the open gunport lids and the cargo.\n * Moored and steady: the origin is the waterline at midships, the bow at +Z.\n */\nexport function Ship({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  seed = 1,\n  length = 36,\n  beam = 10,\n  masts = 3,\n  sails = 'set',\n  guns = 8,\n  gangway = 'starboard',\n  gangwayDrop = 3.8,\n  furnish = true,\n  lanterns = true,\n  flag = true,\n  collider = true,\n  hullColor,\n  bandColor = '#a8742c',\n  deckColor,\n  sailColor = '#e9e0c8',\n  flagColor = '#1b1b1b',\n}: ShipProps) {\n  const { unit: U, palette } = useWorld()\n  const hullC = hullColor ?? palette.woodDark\n  const deckC = deckColor ?? palette.floor\n  const m = useMaterials({\n    painted: {\n      color: '#ffffff',\n      vertexColors: true,\n      flatShading: true,\n      roughness: 0.85,\n      side: DoubleSide,\n    },\n    wood: { slot: 'wood', color: palette.wood, roughness: 0.8 },\n    dark: { slot: 'wood', color: '#2b211a', roughness: 0.8 },\n    spar: { slot: 'wood', color: palette.woodDark, roughness: 0.75 },\n    iron: { slot: 'metal.painted', color: '#2a2a2d', metalness: 0.55, roughness: 0.45 },\n    port: { color: '#15110e', roughness: 1 },\n    lid: { color: hullC, roughness: 0.85 },\n    canvas: { slot: 'fabric', color: '#d6cbad', roughness: 1, side: DoubleSide },\n    sail: { slot: 'fabric', color: sailColor, roughness: 0.95, side: DoubleSide },\n    glass: { color: '#ffd28a', emissive: '#ffae45', emissiveIntensity: 1.4, roughness: 0.3 },\n    window: { color: '#26323a', emissive: '#d49a52', emissiveIntensity: 0.3, roughness: 0.15 },\n    brass: { slot: 'metal.bare', color: '#b08d3c', metalness: 0.7, roughness: 0.35 },\n    rope: { color: '#4a3b2a', roughness: 1 },\n  })\n  const mats: Mats = m\n\n  const shape = useMemo(() => shipShape(length, beam), [length, beam])\n  const side = gangway === 'port' ? 1 : -1\n  const lay = useMemo(() => shipLayout(shape, side), [shape, side])\n  const open = gangway !== 'none'\n  const gap = useMemo(() => gangwayGap(lay, open), [lay, open])\n  const rig = useMemo(() => rigLayout(lay, masts), [lay, masts])\n  const mastZ = useMemo(() => {\n    const z = (k: string) => rig.masts.find((mt) => mt.key === k)?.z ?? null\n    return { main: lay.masts.main, fore: z('fore'), mizzen: z('mizzen') }\n  }, [rig, lay])\n\n  const hull = useMemo(() => {\n    const colors = {\n      hull: new Color(hullC),\n      band: new Color(bandColor),\n      bottom: new Color('#3b2a21'),\n      trim: new Color(hullC).multiplyScalar(0.5),\n      inner: new Color(palette.wood),\n    }\n    const { outer, inner, trim } = buildHull(lay, colors, gap, seed)\n    const b = new MeshBuilder()\n    for (const part of [outer, inner, trim]) b.append(part)\n    const top = new Color(deckC)\n    const under = new Color(palette.wood).multiplyScalar(0.8)\n    const decks = shipDecks(lay)\n    decks.forEach((d, i) => {\n      buildDeck(b, shape, d, top, under, seed + 10 + i)\n    })\n    for (const h of bulkheads(lay)) buildBulkhead(b, h, colors.inner, seed + 20)\n    return { geometry: b.geometry(), decks }\n  }, [lay, shape, gap, seed, hullC, bandColor, deckC, palette.wood])\n  useEffect(() => () => hull.geometry.dispose(), [hull])\n\n  const solid = useMemo(() => {\n    if (!collider) return null\n    return {\n      walls: hullCollider(lay, gap),\n      decks: hull.decks.flatMap((d) => deckHulls(shape, d)),\n    }\n  }, [collider, lay, gap, hull, shape])\n\n  const beams = useMemo(\n    () =>\n      hull.decks.slice(1).flatMap((d) => {\n        const { y, beams: bs } = deckBeams(shape, d)\n        return bs.map((b) => compose([0, y, b.z], [0, 0, 0], [b.w, 1, 1]))\n      }),\n    [hull, shape],\n  )\n\n  const windows = useMemo(() => {\n    const y = LEVEL.main + 1.25\n    const z = sternZ(shape, y) + SKIN / 2\n    const tilt = Math.atan((sternZ(shape, y + 0.1) - sternZ(shape, y - 0.1)) / 0.2)\n    const span = innerBreadth(shape, z, y) * 1.6\n    const panes = Array.from({ length: 5 }, (_, i) =>\n      compose([((i - 2) * span) / 5, y, z], [tilt, 0, 0]),\n    )\n    return {\n      pane: new BoxGeometry(0.62, 0.78, SKIN + 0.08),\n      bar: new BoxGeometry(0.66, 0.05, SKIN + 0.12),\n      panes,\n    }\n  }, [shape])\n  const beamBox = useMemo(() => new BoxGeometry(1, 0.22, 0.2), [])\n\n  const guns_ = useMemo(() => gunLayout(lay, guns, gap, seed), [lay, guns, gap, seed])\n  const hammocks = useMemo(\n    () => (furnish ? hammockLayout(lay, mastZ.fore, seed) : []),\n    [furnish, lay, mastZ, seed],\n  )\n  const pieces = useMemo(() => (furnish ? furnishLayout(lay, mastZ) : []), [furnish, lay, mastZ])\n  const cargo = useMemo(() => (furnish ? cargoLayout(lay, seed) : []), [furnish, lay, seed])\n  const tableZ = cabinTable(lay, mastZ.mizzen)\n  const lamps = useMemo(() => lanternLayout(lay, tableZ), [lay, tableZ])\n  const plan = useMemo(\n    () => gangwayPlan(shape, lay.gangway.z, side, gangwayDrop, gangwayReach(gangwayDrop)),\n    [shape, lay, side, gangwayDrop],\n  )\n  const railList = useMemo(() => rails(lay), [lay])\n  const wheelZ = mastZ.mizzen !== null ? mastZ.mizzen + 1.7 : lay.zQ - 2.2\n  const capstanZ = mastZ.main - 3\n  const bellZ = lay.zF + 0.7\n  const main = rig.masts.find((mt) => mt.key === 'main') ?? rig.masts[0]\n\n  const visual = (\n    <>\n      <mesh geometry={hull.geometry} material={m.painted} castShadow receiveShadow />\n      <Instanced geometry={beamBox} material={m.dark} matrices={beams} />\n      <Instanced geometry={windows.pane} material={m.window} matrices={windows.panes} />\n      <Instanced geometry={windows.bar} material={m.dark} matrices={windows.panes} />\n      {railList.map((r) => (\n        <RailMesh key={r.key} rail={r} m={mats} />\n      ))}\n      <Rig\n        lay={lay}\n        rig={rig}\n        sails={sails}\n        seed={seed}\n        spar={m.spar}\n        sail={m.sail}\n        rope=\"#2a2118\"\n      />\n      <Cannons guns={guns_} m={mats} />\n      <Ports guns={guns_} shape={shape} m={mats} />\n      {hammocks.length > 0 && <Hammocks items={hammocks} m={mats} />}\n      <Wheel z={wheelZ} m={mats} />\n      <Capstan z={capstanZ} m={mats} />\n      <Bell z={bellZ} m={mats} />\n      <Anchors shape={shape} m={mats} />\n      <Rudder shape={shape} m={mats} />\n      {open && <Gangway plan={plan} m={mats} />}\n      {lanterns &&\n        lamps.map((l) => (\n          <Lantern key={l.position.join()} position={l.position} stern={l.stern} m={mats} />\n        ))}\n    </>\n  )\n\n  const at = (p: V3): V3 => [p[0] * U, p[1] * U, p[2] * U]\n\n  return (\n    <group position={position} rotation={rotation}>\n      <group scale={U}>\n        {solid ? (\n          <RigidBody type=\"fixed\" colliders={false}>\n            <TrimeshCollider args={solid.walls} />\n            {solid.decks.map((pts, i) => (\n              <ConvexHullCollider key={i} args={[pts]} />\n            ))}\n            {bulkheads(lay).flatMap((h) => {\n              const w = Math.min(h.w0, h.w1) + 0.1\n              const d = 0.6\n              const half = (w - d) / 2\n              return [-1, 1].map((s) => (\n                <CuboidCollider\n                  key={`${h.z}:${s}`}\n                  args={[half, (h.y1 - h.y0) / 2, 0.05]}\n                  position={[s * (d + half), (h.y0 + h.y1) / 2, h.z]}\n                />\n              ))\n            })}\n            {railList.map((r) => {\n              const len = Math.hypot(r.x1 - r.x0, r.z1 - r.z0)\n              return (\n                <CuboidCollider\n                  key={r.key}\n                  args={[r.x0 === r.x1 ? 0.04 : len / 2, 0.5, r.x0 === r.x1 ? len / 2 : 0.04]}\n                  position={[(r.x0 + r.x1) / 2, r.y + 0.5, (r.z0 + r.z1) / 2]}\n                />\n              )\n            })}\n            {rig.masts.map((mt) => {\n              const top = mt.key === 'main' ? LEVEL.main + 3 : LEVEL.quarter + 3\n              return (\n                <CylinderCollider\n                  key={mt.key}\n                  args={[(top - LEVEL.hold) / 2, mt.r]}\n                  position={[0, (top + LEVEL.hold) / 2, mt.z]}\n                />\n              )\n            })}\n            <CylinderCollider args={[0.55, 0.58]} position={[0, LEVEL.main + 0.55, capstanZ]} />\n            <CuboidCollider args={[0.45, 0.75, 0.1]} position={[0, LEVEL.fore + 0.75, bellZ]} />\n            <WheelColliders z={wheelZ} />\n            <CannonColliders guns={guns_} />\n            {open && <GangwayColliders plan={plan} />}\n            {visual}\n          </RigidBody>\n        ) : (\n          visual\n        )}\n      </group>\n      <Stairs lay={lay} unit={U} color={deckC} />\n      {furnish && <Furnishing pieces={pieces} cargo={cargo} unit={U} seed={seed} />}\n      {flag && (\n        <Flag\n          position={at([0, main.truck + 0.1, main.z])}\n          rotation={[0, Math.PI / 2, 0]}\n          poleHeight={2.2}\n          fly={3.2}\n          drop={2}\n          color={flagColor}\n          seed={seed}\n        />\n      )}\n    </group>\n  )\n}\n\nShip.surface = shipSurface\n\nfunction RailMesh({ rail, m }: { rail: Rail; m: Mats }) {\n  const len = Math.hypot(rail.x1 - rail.x0, rail.z1 - rail.z0)\n  const along = rail.x0 === rail.x1 ? Math.PI / 2 : 0\n  const cx = (rail.x0 + rail.x1) / 2\n  const cz = (rail.z0 + rail.z1) / 2\n  const posts = Math.max(2, Math.round(len / 0.9) + 1)\n  return (\n    <group position={[cx, rail.y, cz]} rotation={[0, along, 0]}>\n      <mesh material={m.dark} position={[0, 1, 0]} castShadow>\n        <boxGeometry args={[len + 0.08, 0.08, 0.1]} />\n      </mesh>\n      <mesh material={m.dark} position={[0, 0.5, 0]}>\n        <boxGeometry args={[len, 0.05, 0.05]} />\n      </mesh>\n      {Array.from({ length: posts }, (_, i) => (\n        <mesh key={i} material={m.dark} position={[-len / 2 + (len * i) / (posts - 1), 0.5, 0]}>\n          <boxGeometry args={[0.07, 1, 0.07]} />\n        </mesh>\n      ))}\n    </group>\n  )\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/Furnishing.tsx",
      "content": "import { sub, type Vec3 } from '@runek/core'\nimport { Barrel } from '../Barrel'\nimport { Bed } from '../Bed'\nimport { Chair } from '../Chair'\nimport { Crate } from '../Crate'\nimport { Staircase } from '../Staircase'\nimport { CASTLE_STAIR, LEVEL, type ShipLayout, STAIR, STEPS } from '../surfaces/ship'\nimport { Table } from '../Table'\nimport type { Cargo, Piece } from './fittings'\nimport type { V3 } from './mesh'\n\n/** The flights between levels, as the catalog's own `Staircase`, placed in world units. */\nexport function Stairs({ lay, unit, color }: { lay: ShipLayout; unit: number; color: string }) {\n  const at = (p: V3): Vec3 => [p[0] * unit, p[1] * unit, p[2] * unit]\n  const { gun, hold, main, quarter, fore } = LEVEL\n  const flights: {\n    key: string\n    at: V3\n    turn: boolean\n    rise: number\n    run: number\n    width: number\n    steps: number\n  }[] = [\n    {\n      key: 'a',\n      at: [0, gun, lay.hatchA.z0 + STAIR.run],\n      turn: true,\n      rise: main - gun,\n      run: STAIR.run,\n      width: STAIR.width,\n      steps: STEPS.main,\n    },\n    {\n      key: 'b',\n      at: [0, hold, lay.hatchB.z1 - STAIR.run],\n      turn: false,\n      rise: gun - hold,\n      run: STAIR.run,\n      width: STAIR.width,\n      steps: STEPS.main,\n    },\n    ...lay.quarterStairs.map((b, i) => ({\n      key: `q${i}`,\n      at: [b.x, main, b.z1] as V3,\n      turn: true,\n      rise: quarter - main,\n      run: CASTLE_STAIR.quarterRun,\n      width: b.w,\n      steps: STEPS.quarter,\n    })),\n    ...lay.foreStairs.map((b, i) => ({\n      key: `f${i}`,\n      at: [b.x, main, b.z0] as V3,\n      turn: false,\n      rise: fore - main,\n      run: CASTLE_STAIR.foreRun,\n      width: b.w,\n      steps: STEPS.fore,\n    })),\n  ]\n  return flights.map((f) => (\n    <Staircase\n      key={f.key}\n      position={at(f.at)}\n      rotation={[0, f.turn ? Math.PI : 0, 0]}\n      form=\"floating\"\n      steps={f.steps}\n      totalHeight={f.rise}\n      width={f.width}\n      depth={f.run}\n      color={color}\n    />\n  ))\n}\n\n/** The cabins, mess, crew quarters and cargo, furnished from the catalog. */\nexport function Furnishing({\n  pieces,\n  cargo,\n  unit,\n  seed,\n}: {\n  pieces: Piece[]\n  cargo: Cargo[]\n  unit: number\n  seed: number\n}) {\n  const at = (p: V3): Vec3 => [p[0] * unit, p[1] * unit, p[2] * unit]\n  return (\n    <>\n      {pieces.map((p, i) => {\n        const key = `${p.type}-${i}`\n        const s = sub(seed, i)\n        switch (p.type) {\n          case 'Table':\n            return (\n              <Table\n                key={key}\n                position={at(p.position)}\n                rotation={p.rotation}\n                width={p.width}\n                depth={p.depth}\n                height={p.height}\n                seed={s}\n              />\n            )\n          case 'Chair':\n            return <Chair key={key} position={at(p.position)} rotation={p.rotation} seed={s} />\n          case 'Bed':\n            return <Bed key={key} position={at(p.position)} rotation={p.rotation} seed={s} />\n          case 'Crate':\n            return (\n              <Crate\n                key={key}\n                position={at(p.position)}\n                rotation={p.rotation}\n                size={p.size}\n                seed={s}\n              />\n            )\n          case 'Barrel':\n            return <Barrel key={key} position={at(p.position)} seed={s} />\n        }\n        return null\n      })}\n      {cargo.map((c, i) => {\n        const key = `cargo-${c.seed}`\n        const s = sub(seed, 100 + i)\n        if (c.kind === 'barrel') return <Barrel key={key} position={at(c.position)} seed={s} />\n        const top: V3 = [c.position[0], c.position[1] + 0.8, c.position[2]]\n        return (\n          <group key={key}>\n            <Crate position={at(c.position)} seed={s} />\n            {c.stacked && (\n              <Crate position={at(top)} size={0.7} rotation={[0, 0.3, 0]} seed={s + 1} />\n            )}\n          </group>\n        )\n      })}\n    </>\n  )\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/Rig.tsx",
      "content": "import { useEffect, useMemo } from 'react'\nimport {\n  BufferAttribute,\n  BufferGeometry,\n  LineBasicMaterial,\n  type Material,\n  Quaternion,\n  Vector3,\n} from 'three'\nimport { LEVEL, type ShipLayout } from '../surfaces/ship'\nimport type { V3 } from './mesh'\nimport { buildRigging, buildSails, type Rig as RigPlan, type SailPlan } from './rigging'\n\nconst UP = new Vector3(0, 1, 0)\n\n/** A round spar between two points, tapering from `r0` to `r1`. */\nfunction Spar({\n  from,\n  to,\n  r0,\n  r1,\n  material,\n}: {\n  from: V3\n  to: V3\n  r0: number\n  r1: number\n  material: Material\n}) {\n  const { position, quaternion, length } = useMemo(() => {\n    const a = new Vector3(...from)\n    const b = new Vector3(...to)\n    const dir = b.clone().sub(a)\n    return {\n      position: a.add(b).multiplyScalar(0.5),\n      quaternion: new Quaternion().setFromUnitVectors(UP, dir.clone().normalize()),\n      length: dir.length(),\n    }\n  }, [from, to])\n  return (\n    <mesh material={material} position={position} quaternion={quaternion} castShadow>\n      <cylinderGeometry args={[r1, r0, length, 8]} />\n    </mesh>\n  )\n}\n\nexport function Rig({\n  lay,\n  rig,\n  sails,\n  seed,\n  spar,\n  sail,\n  rope,\n}: {\n  lay: ShipLayout\n  rig: RigPlan\n  sails: SailPlan\n  seed: number\n  spar: Material\n  sail: Material\n  rope: string\n}) {\n  const cloth = useMemo(() => (sails === 'set' ? buildSails(rig, seed) : null), [rig, sails, seed])\n  const lines = useMemo(() => {\n    const g = new BufferGeometry()\n    g.setAttribute('position', new BufferAttribute(buildRigging(lay, rig), 3))\n    return g\n  }, [lay, rig])\n  const lineMaterial = useMemo(() => new LineBasicMaterial({ color: rope }), [rope])\n  useEffect(() => () => cloth?.dispose(), [cloth])\n  useEffect(() => () => lines.dispose(), [lines])\n  useEffect(() => () => lineMaterial.dispose(), [lineMaterial])\n  const { base, tip } = rig.bowsprit\n  const sp = rig.spanker\n  return (\n    <>\n      {rig.masts.map((m) => {\n        const k = m.r / 0.45\n        return (\n          <group key={m.key}>\n            <Spar\n              from={[0, LEVEL.hold, m.z]}\n              to={[0, m.top + 0.8, m.z]}\n              r0={m.r}\n              r1={m.r * 0.78}\n              material={spar}\n            />\n            <Spar\n              from={[0, m.top - 0.6, m.z]}\n              to={[0, m.cross + 0.7, m.z]}\n              r0={m.r * 0.55}\n              r1={m.r * 0.42}\n              material={spar}\n            />\n            <Spar\n              from={[0, m.cross - 0.6, m.z]}\n              to={[0, m.truck, m.z]}\n              r0={m.r * 0.34}\n              r1={m.r * 0.2}\n              material={spar}\n            />\n            <mesh material={spar} position={[0, m.top, m.z - 0.1]} castShadow>\n              <boxGeometry args={[m.topHalf * 2, 0.14, 1.7 * k]} />\n            </mesh>\n            <mesh material={spar} position={[0, m.cross, m.z]}>\n              <boxGeometry args={[1.5 * k, 0.1, 0.9 * k]} />\n            </mesh>\n            <mesh material={spar} position={[0, m.truck + 0.08, m.z]}>\n              <cylinderGeometry args={[0.14 * k, 0.14 * k, 0.16, 10]} />\n            </mesh>\n            {m.yards.map((yd) => (\n              <group key={yd.y} position={[0, yd.y, m.z + m.r + 0.1]}>\n                <mesh material={spar} rotation={[0, 0, Math.PI / 2]} castShadow>\n                  <cylinderGeometry args={[0.1 * k, 0.17 * k, yd.half * 2, 8]} />\n                </mesh>\n                {sails === 'furled' && yd.sail && (\n                  <mesh\n                    material={sail}\n                    position={[0, 0.12, 0.22]}\n                    rotation={[0, 0, Math.PI / 2]}\n                    castShadow\n                  >\n                    <cylinderGeometry args={[0.22 * k, 0.22 * k, yd.half * 1.84, 8]} />\n                  </mesh>\n                )}\n              </group>\n            ))}\n          </group>\n        )\n      })}\n      <Spar from={base} to={tip} r0={0.24} r1={0.1} material={spar} />\n      {sp && (\n        <>\n          <Spar from={sp.jaw} to={sp.peak} r0={0.12} r1={0.08} material={spar} />\n          <Spar from={sp.tack} to={sp.clew} r0={0.14} r1={0.1} material={spar} />\n        </>\n      )}\n      {cloth && <mesh geometry={cloth} material={sail} castShadow receiveShadow />}\n      <lineSegments geometry={lines} material={lineMaterial} />\n    </>\n  )\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/decks.ts",
      "content": "import type { Color } from 'three'\nimport {\n  type Box,\n  DECK,\n  DOOR,\n  deckSpan,\n  innerBreadth,\n  LEVEL,\n  type ShipLayout,\n  type ShipShape,\n} from '../surfaces/ship'\nimport { hash01, type MeshBuilder } from './mesh'\n\nexport interface DeckSpec {\n  y: number\n  z0: number\n  z1: number\n  hole?: Box\n  /** Ends that stand open to the waist, so their edge shows. */\n  open?: { aft?: boolean; fore?: boolean }\n}\n\ninterface Piece {\n  z0: number\n  z1: number\n  /** 0 spans the hull; ±1 is the strip beside a hatch on that side. */\n  side: 0 | 1 | -1\n  hw: number\n}\n\nconst PLANK = 0.26\nconst BUTT = 3.6\n\n/** A deck as convex pieces: the whole width, or, around a hatch, aft, fore and two strips. */\nfunction pieces(d: DeckSpec): Piece[] {\n  const h = d.hole\n  if (!h) return [{ z0: d.z0, z1: d.z1, side: 0, hw: 0 }]\n  return [\n    { z0: d.z0, z1: h.z0, side: 0, hw: 0 },\n    { z0: h.z1, z1: d.z1, side: 0, hw: 0 },\n    { z0: h.z0, z1: h.z1, side: 1, hw: h.w / 2 },\n    { z0: h.z0, z1: h.z1, side: -1, hw: h.w / 2 },\n  ]\n}\n\nconst samples = (z0: number, z1: number, step: number) => {\n  const n = Math.max(1, Math.ceil((z1 - z0) / step))\n  return Array.from({ length: n + 1 }, (_, i) => z0 + ((z1 - z0) * i) / n)\n}\n\nfunction limits(s: ShipShape, y: number, p: Piece, z: number): [number, number] {\n  const w = innerBreadth(s, z, y)\n  if (p.side === 0) return [-w, w]\n  const edge = Math.max(w, p.hw)\n  return p.side > 0 ? [p.hw, edge] : [-edge, -p.hw]\n}\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\n\n/** Planked top (a seeded shade per plank length, butts staggered), plain underside, and the\n *  edges that show round a hatch or an open castle end. */\nexport function buildDeck(\n  b: MeshBuilder,\n  s: ShipShape,\n  d: DeckSpec,\n  top: Color,\n  under: Color,\n  seed: number,\n) {\n  const { y } = d\n  const yb = y - DECK\n  for (const p of pieces(d)) {\n    if (p.z1 - p.z0 < 0.01) continue\n    const zs = samples(p.z0, p.z1, 0.8)\n    const lims = zs.map((z) => limits(s, y, p, z))\n    const lo = Math.min(...lims.map((l) => l[0]))\n    const hi = Math.max(...lims.map((l) => l[1]))\n    for (let k = Math.floor(lo / PLANK); k < Math.ceil(hi / PLANK); k++) {\n      const xa = k * PLANK\n      const xb = xa + PLANK\n      const stagger = hash01(k, 7, seed) * BUTT\n      for (let i = 0; i < zs.length - 1; i++) {\n        const [la, ha] = lims[i]\n        const [lb, hb] = lims[i + 1]\n        const a0 = clamp(xa, la, ha)\n        const a1 = clamp(xb, la, ha)\n        const b0 = clamp(xa, lb, hb)\n        const b1 = clamp(xb, lb, hb)\n        if (a1 - a0 < 1e-4 && b1 - b0 < 1e-4) continue\n        const seg = Math.floor(((zs[i] + zs[i + 1]) / 2 + stagger) / BUTT)\n        const shade = top.clone().multiplyScalar(0.86 + 0.22 * hash01(k, seg, seed))\n        b.quad(\n          [a0, y, zs[i]],\n          [a1, y, zs[i]],\n          [b1, y, zs[i + 1]],\n          [b0, y, zs[i + 1]],\n          [0, 1, 0],\n          shade,\n        )\n      }\n    }\n    for (let i = 0; i < zs.length - 1; i++) {\n      const [la, ha] = lims[i]\n      const [lb, hb] = lims[i + 1]\n      b.quad(\n        [la, yb, zs[i]],\n        [ha, yb, zs[i]],\n        [hb, yb, zs[i + 1]],\n        [lb, yb, zs[i + 1]],\n        [0, -1, 0],\n        under,\n      )\n    }\n  }\n  const edge = (x0: number, z0: number, x1: number, z1: number, hint: [number, number, number]) =>\n    b.quad([x0, yb, z0], [x1, yb, z1], [x1, y, z1], [x0, y, z0], hint, under)\n  const h = d.hole\n  if (h) {\n    const w = h.w / 2\n    edge(-w, h.z0, w, h.z0, [0, 0, 1])\n    edge(-w, h.z1, w, h.z1, [0, 0, -1])\n    edge(w, h.z0, w, h.z1, [-1, 0, 0])\n    edge(-w, h.z0, -w, h.z1, [1, 0, 0])\n  }\n  const w0 = innerBreadth(s, d.z0, y)\n  const w1 = innerBreadth(s, d.z1, y)\n  if (d.open?.aft) edge(-w0, d.z0, w0, d.z0, [0, 0, -1])\n  if (d.open?.fore) edge(-w1, d.z1, w1, d.z1, [0, 0, 1])\n}\n\n/** Each deck piece's corner points, for a convex-hull collider. */\nexport function deckHulls(s: ShipShape, d: DeckSpec): Float32Array[] {\n  const out: Float32Array[] = []\n  for (const p of pieces(d)) {\n    if (p.z1 - p.z0 < 0.05) continue\n    const pts: number[] = []\n    for (const z of samples(p.z0, p.z1, 1.5)) {\n      const [l, h] = limits(s, d.y, p, z)\n      if (h - l < 0.05) continue\n      pts.push(l, d.y, z, h, d.y, z, l, d.y - DECK, z, h, d.y - DECK, z)\n    }\n    if (pts.length >= 24) out.push(new Float32Array(pts))\n  }\n  return out\n}\n\n/** Beams under a deck, across the hull, clear of the hatch the stair climbs through. */\nexport function deckBeams(s: ShipShape, d: DeckSpec, spacing = 1.25) {\n  const out: { z: number; w: number }[] = []\n  const y = d.y - DECK - 0.11\n  for (let z = d.z0 + 0.6; z < d.z1 - 0.3; z += spacing) {\n    if (d.hole && z > d.hole.z0 - 0.2 && z < d.hole.z1 + 0.2) continue\n    const w = 2 * innerBreadth(s, z, y)\n    if (w > 0.6) out.push({ z, w })\n  }\n  return { y, beams: out }\n}\n\n/** The ship's five floors: hold, gun deck, main deck (under the castles too), quarterdeck and\n *  forecastle. */\nexport function shipDecks(lay: ShipLayout): DeckSpec[] {\n  const s = lay.shape\n  const span = (y: number) => deckSpan(s, y)\n  const { hold, gun, main, quarter, fore } = LEVEL\n  return [\n    { y: hold, z0: span(hold)[0], z1: span(hold)[1] },\n    { y: gun, z0: span(gun)[0], z1: span(gun)[1], hole: lay.hatchB },\n    { y: main, z0: span(main)[0], z1: span(main)[1], hole: lay.hatchA },\n    { y: quarter, z0: span(quarter)[0], z1: lay.zQ, open: { fore: true } },\n    { y: fore, z0: lay.zF, z1: span(fore)[1], open: { aft: true } },\n  ]\n}\n\nexport interface Bulkhead {\n  z: number\n  y0: number\n  y1: number\n  /** Inner hull half-width at the bulkhead's foot and head. */\n  w0: number\n  w1: number\n}\n\n/** The two castle breaks: a wall from the main deck up to the castle deck, a door in its\n *  middle. */\nexport function bulkheads(lay: ShipLayout): Bulkhead[] {\n  const s = lay.shape\n  const { main } = LEVEL\n  return [\n    { z: lay.zQ, y1: LEVEL.quarter - DECK },\n    { z: lay.zF, y1: LEVEL.fore - DECK },\n  ].map(({ z, y1 }) => ({\n    z,\n    y0: main,\n    y1,\n    w0: innerBreadth(s, z, main),\n    w1: innerBreadth(s, z, y1),\n  }))\n}\n\nconst BOARD = 0.3\nconst WALL = 0.05\n\n/** Vertical boards both faces of a bulkhead, with the doorway left open and its jambs faced. */\nexport function buildBulkhead(b: MeshBuilder, h: Bulkhead, color: Color, seed: number) {\n  const door = DOOR.width / 2\n  const wMax = Math.max(h.w0, h.w1)\n  for (let k = Math.floor(-wMax / BOARD); k < Math.ceil(wMax / BOARD); k++) {\n    let x0 = k * BOARD\n    let x1 = x0 + BOARD\n    if (x1 > -door && x0 < door) {\n      if (x0 < -door) x1 = -door\n      else if (x1 > door) x0 = door\n      else continue\n    }\n    const shade = color.clone().multiplyScalar(0.88 + 0.2 * hash01(k, 31, seed))\n    const lo = (x: number) => clamp(x, -h.w0, h.w0)\n    const hi = (x: number) => clamp(x, -h.w1, h.w1)\n    if (lo(x1) - lo(x0) < 1e-4 && hi(x1) - hi(x0) < 1e-4) continue\n    for (const f of [-1, 1]) {\n      const z = h.z + f * WALL\n      b.quad(\n        [lo(x0), h.y0, z],\n        [lo(x1), h.y0, z],\n        [hi(x1), h.y1, z],\n        [hi(x0), h.y1, z],\n        [0, 0, f],\n        shade,\n      )\n    }\n  }\n  for (const x of [-door, door]) {\n    b.quad(\n      [x, h.y0, h.z - WALL],\n      [x, h.y0, h.z + WALL],\n      [x, h.y1, h.z + WALL],\n      [x, h.y1, h.z - WALL],\n      [-Math.sign(x), 0, 0],\n      color,\n    )\n  }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/fittings.ts",
      "content": "import {\n  DECK,\n  deckSpan,\n  halfBreadth,\n  innerBreadth,\n  LEVEL,\n  railY,\n  type ShipLayout,\n  sternZ,\n} from '../surfaces/ship'\nimport type { Gap } from './hull'\nimport { hash01, type V3 } from './mesh'\n\nexport interface Gun {\n  side: 1 | -1\n  x: number\n  y: number\n  z: number\n  /** Height of the port's centre on the hull. */\n  portY: number\n  open: boolean\n}\n\nconst GUN_PITCH = 1.7\n\nfunction row(z0: number, z1: number, n: number): number[] {\n  const fit = Math.min(n, Math.floor((z1 - z0) / GUN_PITCH) + 1)\n  if (fit <= 0) return []\n  if (fit === 1) return [(z0 + z1) / 2]\n  return Array.from({ length: fit }, (_, i) => z0 + ((z1 - z0) * i) / (fit - 1))\n}\n\n/** Cannons run out at a port each: `count` a side on the gun deck, fewer along the waist, none\n *  in the gangway's way. Which lids stand open is seeded. */\nexport function gunLayout(lay: ShipLayout, count: number, gap: Gap | null, seed: number): Gun[] {\n  if (count <= 0) return []\n  const s = lay.shape\n  const { gun, main } = LEVEL\n  const [za, zb] = deckSpan(s, gun)\n  const out: Gun[] = []\n  const place = (\n    zs: number[],\n    y: number,\n    portY: number,\n    skip?: (side: number, z: number) => boolean,\n  ) => {\n    for (const side of [1, -1] as const)\n      for (const z of zs) {\n        if (skip?.(side, z)) continue\n        const x = side * (innerBreadth(s, z, y + 0.6) - 0.95)\n        out.push({ side, x, y, z, portY, open: hash01(Math.round(z * 10), side, seed) < 0.75 })\n      }\n  }\n  place(row(za + 3.2, zb - 4.5, Math.round(count)), gun, gun + 0.75)\n  const waist = Math.max(2, Math.round(count * 0.4))\n  const zw = row(lay.quarterStairs[0].z1 + 0.9, lay.foreStairs[0].z0 - 0.9, waist)\n  place(\n    zw,\n    main,\n    main + 0.6,\n    (side, z) => !!gap && side === gap.side && Math.abs(z - lay.gangway.z) < 1.4,\n  )\n  return out\n}\n\nexport interface Hammock {\n  x: number\n  y: number\n  z: number\n  sag: number\n  tint: number\n}\n\n/** Hammocks slung fore and aft in rows: the gun deck's berth forward of the main hatch, and\n *  the crew quarters under the forecastle. Clear of the guns, the foremast, and head height. */\nexport function hammockLayout(lay: ShipLayout, foremast: number | null, seed: number): Hammock[] {\n  const s = lay.shape\n  const out: Hammock[] = []\n  const zones = [\n    { y: LEVEL.gun, z0: lay.hatchA.z1 + 1.1, z1: deckSpan(s, LEVEL.gun)[1] - 1.6, margin: 2.1 },\n    { y: LEVEL.main, z0: lay.zF + 1.2, z1: deckSpan(s, LEVEL.main)[1] - 1.2, margin: 0.9 },\n  ]\n  let n = 0\n  for (const zone of zones) {\n    for (let z = zone.z0; z <= zone.z1; z += 2.2) {\n      const reach = innerBreadth(s, z, zone.y + 1.95) - zone.margin\n      for (let x = -Math.floor(reach / 0.85) * 0.85; x <= reach; x += 0.85) {\n        if (foremast !== null && Math.abs(x) < 0.8 && Math.abs(z - foremast) < 1.4) continue\n        n++\n        out.push({\n          x,\n          y: zone.y + 1.95,\n          z,\n          sag: 0.85 + 0.3 * hash01(n, 1, seed),\n          tint: 0.85 + 0.2 * hash01(n, 2, seed),\n        })\n      }\n    }\n  }\n  return out\n}\n\nexport interface Cargo {\n  kind: 'crate' | 'barrel'\n  position: V3\n  stacked: boolean\n  seed: number\n}\n\nconst MAX_CARGO = 28\n\n/** Cargo stowed along both sides of the hold, leaving a centre aisle to the stair. */\nexport function cargoLayout(lay: ShipLayout, seed: number): Cargo[] {\n  const s = lay.shape\n  const y = LEVEL.hold\n  const [za, zb] = deckSpan(s, y)\n  const slots: (Cargo & { order: number })[] = []\n  let n = 0\n  for (const side of [1, -1] as const)\n    for (let z = za + 1.4; z < zb - 2.2; z += 1.6)\n      for (const col of [0, 1]) {\n        n++\n        const x = side * (innerBreadth(s, z, y + 0.6) - 0.65 - col * 1.0)\n        if (Math.abs(x) < 1.4) continue\n        const r = hash01(n, 11, seed)\n        if (r < 0.3) continue\n        const kind = r < 0.68 ? 'crate' : 'barrel'\n        slots.push({\n          kind,\n          position: [x, y, z],\n          stacked: kind === 'crate' && hash01(n, 12, seed) < 0.4,\n          seed: n,\n          order: hash01(n, 13, seed),\n        })\n      }\n  return slots\n    .sort((a, b) => a.order - b.order)\n    .slice(0, MAX_CARGO)\n    .map(({ order: _, ...c }) => c)\n}\n\nexport interface Lamp {\n  position: V3\n  /** A big stern lantern on the taffrail rather than one hung from a beam. */\n  stern?: boolean\n}\n\n/** Lanterns: two in the hold, two on the gun deck, one in each cabin, two at the stern. */\nexport function lanternLayout(lay: ShipLayout, tableZ: number): Lamp[] {\n  const s = lay.shape\n  const L = s.length\n  const { gun, main, quarter, fore } = LEVEL\n  const hang = (deck: number) => deck - DECK - 0.55\n  const [, gunBow] = deckSpan(s, gun)\n  const [, mainBow] = deckSpan(s, main)\n  const yr = railY(s, sternZ(s, quarter + 1))\n  const zs = sternZ(s, yr) + 0.35\n  const xs = halfBreadth(s, zs, yr) - 0.55\n  return [\n    { position: [0, hang(gun), -0.22 * L] },\n    { position: [0, hang(gun), 0.2 * L] },\n    { position: [0, hang(main), (lay.hatchA.z1 + gunBow) / 2] },\n    { position: [0, hang(main), lay.hatchB.z0 - 1] },\n    { position: [0, hang(quarter), tableZ] },\n    { position: [0, hang(fore), (lay.zF + mainBow) / 2] },\n    { position: [xs, yr, zs], stern: true },\n    { position: [-xs, yr, zs], stern: true },\n  ]\n}\n\nexport type Piece =\n  | { type: 'Table'; position: V3; rotation?: V3; width: number; depth: number; height: number }\n  | { type: 'Chair'; position: V3; rotation: V3 }\n  | { type: 'Bed'; position: V3; rotation?: V3 }\n  | { type: 'Crate'; position: V3; size: number; rotation?: V3 }\n  | { type: 'Barrel'; position: V3 }\n\n/** Where the captain's table goes: aft of the mizzen, clear of the transom. */\nexport function cabinTable(lay: ShipLayout, mizzen: number | null): number {\n  const aft = deckSpan(lay.shape, LEVEL.main)[0]\n  if (mizzen === null) return (aft + lay.zQ) / 2 - 0.5\n  const z = mizzen - 2.5\n  return z - 1.6 > aft + 0.4 ? z : (aft + mizzen) / 2\n}\n\n/** The furniture each room is fitted with: the captain's cabin, the gun deck's mess, the crew\n *  quarters, and a little deck cargo. The hold's cargo comes from `cargoLayout`. */\nexport function furnishLayout(\n  lay: ShipLayout,\n  masts: { main: number; fore: number | null; mizzen: number | null },\n): Piece[] {\n  const s = lay.shape\n  const { gun, main } = LEVEL\n  const out: Piece[] = []\n  const t = cabinTable(lay, masts.mizzen)\n  out.push({ type: 'Table', position: [0, main, t], width: 1.2, depth: 2.4, height: 0.76 })\n  for (const dz of [-0.55, 0.55]) {\n    out.push({ type: 'Chair', position: [0.95, main, t + dz], rotation: [0, -Math.PI / 2, 0] })\n    out.push({ type: 'Chair', position: [-0.95, main, t + dz], rotation: [0, Math.PI / 2, 0] })\n  }\n  out.push({ type: 'Chair', position: [0, main, t - 1.55], rotation: [0, 0, 0] })\n  const zb = lay.zQ - 1.5\n  const wb = innerBreadth(s, zb, main + 0.5)\n  out.push({ type: 'Bed', position: [wb - 0.8, main, zb] })\n  out.push({ type: 'Crate', position: [wb - 0.6, main, zb - 1.5], size: 0.55 })\n  out.push({\n    type: 'Table',\n    position: [-(wb - 0.55), main, zb],\n    rotation: [0, Math.PI / 2, 0],\n    width: 1.3,\n    depth: 0.7,\n    height: 0.8,\n  })\n  out.push({ type: 'Chair', position: [-(wb - 1.25), main, zb], rotation: [0, -Math.PI / 2, 0] })\n\n  const depth = 2.2\n  let mess = lay.hatchB.z0 - 1.4 - depth / 2\n  if (masts.mizzen !== null && Math.abs(mess - masts.mizzen) < depth / 2 + 0.7)\n    mess = masts.mizzen - 0.8 - depth / 2\n  out.push({ type: 'Table', position: [0, gun, mess], width: 0.9, depth, height: 0.72 })\n  for (const sx of [-1, 1])\n    for (const dz of [-0.55, 0.55])\n      out.push({ type: 'Crate', position: [sx * 0.8, gun, mess + dz], size: 0.42 })\n  for (const sx of [-1, 1]) {\n    const x = sx * (innerBreadth(s, masts.main, gun + 0.5) - 2.7)\n    out.push({ type: 'Barrel', position: [x, gun, masts.main] })\n  }\n\n  for (const sx of [-1, 1])\n    for (const k of [0, 1]) {\n      const z = lay.zF + 1 + k * 1.3\n      out.push({\n        type: 'Crate',\n        position: [sx * (innerBreadth(s, z, main + 0.3) - 0.45), main, z],\n        size: 0.5,\n      })\n    }\n  out.push({\n    type: 'Barrel',\n    position: [innerBreadth(s, lay.zF + 3.6, main + 0.5) - 0.6, main, lay.zF + 3.6],\n  })\n\n  if (masts.fore !== null)\n    for (const sx of [-1, 1])\n      out.push({ type: 'Barrel', position: [sx * 1, main, masts.fore - 1.1] })\n  out.push({ type: 'Crate', position: [1.3, main, masts.main - 1.3], size: 0.8 })\n  out.push({\n    type: 'Crate',\n    position: [1.3, main + 0.8, masts.main - 1.3],\n    size: 0.6,\n    rotation: [0, 0.4, 0],\n  })\n  return out\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/hull.ts",
      "content": "import type { Color } from 'three'\nimport {\n  bowZ,\n  DECK,\n  GANGWAY,\n  halfBreadth,\n  innerBreadth,\n  LEVEL,\n  railY,\n  type ShipLayout,\n  type ShipShape,\n  SKIN,\n  sternZ,\n  TOP,\n} from '../surfaces/ship'\nimport { hash01, MeshBuilder, type V3 } from './mesh'\n\nexport interface HullColors {\n  hull: Color\n  band: Color\n  bottom: Color\n  trim: Color\n  inner: Color\n}\n\ntype Height = number | ((z: number) => number)\n\ninterface Band {\n  y0: Height\n  y1: Height\n  rows: number\n  color?: Color\n  /** Above the main deck, where the gangway opening is cut. */\n  upper?: boolean\n}\n\ninterface Skin {\n  breadth: (z: number, y: number) => number\n  ends: (y: number) => [number, number]\n  /** Which way the face looks on the port (+x) side. */\n  outward: 1 | -1\n}\n\nconst at = (h: Height, z: number) => (typeof h === 'number' ? h : h(z))\n\n/** Stations along the hull, cosine-spaced so the ends get detail, plus exact marks. */\nexport function stations(s: ShipShape, n: number, marks: number[]): number[] {\n  const z0 = sternZ(s, TOP)\n  const z1 = bowZ(s, TOP)\n  const out: number[] = []\n  for (let i = 0; i < n; i++)\n    out.push(z0 + ((1 - Math.cos((Math.PI * i) / (n - 1))) / 2) * (z1 - z0))\n  for (const m of marks) if (m > z0 && m < z1) out.push(m)\n  out.sort((a, b) => a - b)\n  return out.filter((z, i) => i === 0 || z - out[i - 1] > 0.05)\n}\n\nexport interface Gap {\n  side: 1 | -1\n  z0: number\n  z1: number\n}\n\nexport function gangwayGap(lay: ShipLayout, open: boolean): Gap | null {\n  if (!open) return null\n  const half = GANGWAY.gap / 2\n  return { side: lay.gangway.side, z0: lay.gangway.z - half, z1: lay.gangway.z + half }\n}\n\nfunction inGap(gap: Gap | null, side: number, za: number, zb: number) {\n  return !!gap && side === gap.side && (za + zb) / 2 > gap.z0 && (za + zb) / 2 < gap.z1\n}\n\nfunction skin(\n  b: MeshBuilder,\n  zs: number[],\n  sk: Skin,\n  bands: Band[],\n  gap: Gap | null,\n  seed: number,\n  shade = true,\n) {\n  const point = (side: number, z: number, y: number): [V3, number] => {\n    const [lo, hi] = sk.ends(y)\n    const zc = Math.min(hi, Math.max(lo, z))\n    return [[side * sk.breadth(zc, y), y, zc], zc]\n  }\n  bands.forEach((band, bi) => {\n    for (let r = 0; r < band.rows; r++) {\n      for (const side of [1, -1]) {\n        const tint = shade ? 0.93 + 0.12 * hash01(bi * 16 + r, side, seed) : 1\n        const color = band.color?.clone().multiplyScalar(tint)\n        for (let i = 0; i < zs.length - 1; i++) {\n          const za = zs[i]\n          const zb = zs[i + 1]\n          if (band.upper && inGap(gap, side, za, zb)) continue\n          const y = (z: number, k: number) => {\n            const y0 = at(band.y0, z)\n            return y0 + ((at(band.y1, z) - y0) * k) / band.rows\n          }\n          const [A, cA] = point(side, za, y(za, r))\n          const [B, cB] = point(side, zb, y(zb, r))\n          const [C, cC] = point(side, zb, y(zb, r + 1))\n          const [D, cD] = point(side, za, y(za, r + 1))\n          if (cA === cB && cC === cD) continue\n          b.quad(A, B, C, D, [side * sk.outward, 0, 0], color)\n        }\n      }\n    }\n  })\n}\n\n/** A flat face across the stern (or the stem), port to starboard, through the band rows. */\nfunction across(\n  b: MeshBuilder,\n  bands: Band[],\n  zAt: (y: number) => number,\n  breadth: (z: number, y: number) => number,\n  hint: V3,\n  zRef: number,\n) {\n  for (const band of bands) {\n    const y0 = at(band.y0, zRef)\n    const y1 = at(band.y1, zRef)\n    for (let r = 0; r < band.rows; r++) {\n      const ya = y0 + ((y1 - y0) * r) / band.rows\n      const yb = y0 + ((y1 - y0) * (r + 1)) / band.rows\n      const za = zAt(ya)\n      const zb = zAt(yb)\n      const xa = breadth(za, ya)\n      const xb = breadth(zb, yb)\n      b.quad([-xa, ya, za], [xa, ya, za], [xb, yb, zb], [-xb, yb, zb], hint, band.color)\n    }\n  }\n}\n\nexport interface HullGeometry {\n  outer: MeshBuilder\n  inner: MeshBuilder\n  trim: MeshBuilder\n}\n\n/** The hull's painted outer skin, its planked inner skin, and the rail cap that joins them. */\nexport function buildHull(\n  lay: ShipLayout,\n  colors: HullColors,\n  gap: Gap | null,\n  seed: number,\n): HullGeometry {\n  const s = lay.shape\n  const rail = (z: number) => railY(s, z)\n  const cap = (z: number) => rail(z) - 0.12\n  const zs = stations(s, 72, [\n    ...(gap ? [gap.z0, gap.z1] : []),\n    lay.zQ,\n    lay.zQ + 1.5,\n    lay.zF - 1.5,\n    lay.zF,\n  ])\n  const { keel, gun, main, hold } = LEVEL\n  const outerBands: Band[] = [\n    { y0: keel, y1: 0.3, rows: 4, color: colors.bottom },\n    { y0: 0.3, y1: gun + 0.3, rows: 3, color: colors.hull },\n    { y0: gun + 0.3, y1: gun + 1.25, rows: 1, color: colors.band },\n    { y0: gun + 1.25, y1: main, rows: 2, color: colors.hull },\n    { y0: main, y1: cap, rows: 3, color: colors.hull, upper: true },\n    { y0: cap, y1: rail, rows: 1, color: colors.trim, upper: true },\n  ]\n  const innerBands: Band[] = [\n    { y0: hold - DECK, y1: gun, rows: 2, color: colors.inner },\n    { y0: gun, y1: main, rows: 2, color: colors.inner },\n    { y0: main, y1: rail, rows: 3, color: colors.inner, upper: true },\n  ]\n  const outerSkin: Skin = {\n    breadth: (z, y) => halfBreadth(s, z, y),\n    ends: (y) => [sternZ(s, y), bowZ(s, y)],\n    outward: 1,\n  }\n  const innerSkin: Skin = {\n    breadth: (z, y) => innerBreadth(s, z, y),\n    ends: (y) => [sternZ(s, y) + SKIN, bowZ(s, y)],\n    outward: -1,\n  }\n\n  const outer = new MeshBuilder()\n  skin(outer, zs, outerSkin, outerBands, gap, seed)\n  const zStern = sternZ(s, TOP)\n  const zBow = bowZ(s, TOP)\n  const hb = (z: number, y: number) => halfBreadth(s, z, y)\n  across(outer, outerBands, (y) => sternZ(s, y), hb, [0, 0, -1], zStern)\n  across(outer, outerBands, (y) => bowZ(s, y), hb, [0, 0, 1], zBow)\n  for (let i = 0; i < zs.length - 1; i++) {\n    const [lo, hi] = outerSkin.ends(keel)\n    const za = Math.min(hi, Math.max(lo, zs[i]))\n    const zb = Math.min(hi, Math.max(lo, zs[i + 1]))\n    if (za === zb) continue\n    const xa = hb(za, keel)\n    const xb = hb(zb, keel)\n    outer.quad(\n      [-xa, keel, za],\n      [xa, keel, za],\n      [xb, keel, zb],\n      [-xb, keel, zb],\n      [0, -1, 0],\n      colors.bottom,\n    )\n  }\n\n  const inner = new MeshBuilder()\n  skin(inner, zs, innerSkin, innerBands, gap, seed + 1)\n  const ib = (z: number, y: number) => innerBreadth(s, z, y)\n  across(inner, innerBands, (y) => sternZ(s, y) + SKIN, ib, [0, 0, 1], zStern)\n\n  const trim = new MeshBuilder()\n  for (const side of [1, -1]) {\n    for (let i = 0; i < zs.length - 1; i++) {\n      const za = zs[i]\n      const zb = zs[i + 1]\n      const open = inGap(gap, side, za, zb)\n      const ya = open ? main : rail(za)\n      const yb = open ? main : rail(zb)\n      const [lo, hi] = outerSkin.ends(ya)\n      if (zb <= lo || za >= hi) continue\n      const ca = Math.max(lo, za)\n      const cb = Math.min(hi, zb)\n      trim.quad(\n        [side * hb(ca, ya), ya, ca],\n        [side * hb(cb, yb), yb, cb],\n        [side * ib(cb, yb), yb, cb],\n        [side * ib(ca, ya), ya, ca],\n        [0, 1, 0],\n        colors.trim,\n      )\n    }\n  }\n  if (gap) {\n    for (const z of [gap.z0, gap.z1]) {\n      const y = rail(z)\n      const o = gap.side * hb(z, main)\n      const n = gap.side * ib(z, main)\n      trim.quad(\n        [o, main, z],\n        [n, main, z],\n        [n, y, z],\n        [o, y, z],\n        [0, 0, z === gap.z0 ? 1 : -1],\n        colors.trim,\n      )\n    }\n  }\n  const yr = rail(zStern)\n  const zo = sternZ(s, yr)\n  const zi = zo + SKIN\n  const xo = hb(zo, yr)\n  const xi = ib(zi, yr)\n  trim.quad([-xo, yr, zo], [xo, yr, zo], [xi, yr, zi], [-xi, yr, zi], [0, 1, 0], colors.trim)\n\n  return { outer, inner, trim }\n}\n\n/** The walls the avatar walks along: the skin's mid-surface from the hold floor to the rail,\n *  and the transom, as one trimesh. */\nexport function hullCollider(lay: ShipLayout, gap: Gap | null): [Float32Array, Uint32Array] {\n  const s = lay.shape\n  const rail = (z: number) => railY(s, z)\n  const zs = stations(s, 40, [...(gap ? [gap.z0, gap.z1] : []), lay.zQ, lay.zF])\n  const mid: Skin = {\n    breadth: (z, y) => halfBreadth(s, z, y) - SKIN / 2,\n    ends: (y) => [sternZ(s, y) + SKIN / 2, bowZ(s, y)],\n    outward: 1,\n  }\n  const { hold, gun, main } = LEVEL\n  const bands: Band[] = [\n    { y0: hold - DECK, y1: gun, rows: 1 },\n    { y0: gun, y1: main, rows: 1 },\n    { y0: main, y1: rail, rows: 1, upper: true },\n  ]\n  const b = new MeshBuilder()\n  skin(b, zs, mid, bands, gap, 0, false)\n  across(b, bands, (y) => sternZ(s, y) + SKIN / 2, mid.breadth, [0, 0, 1], sternZ(s, TOP))\n  return b.trimesh()\n}\n\n/** Where a fitting sits flush on the outer skin at (z, y): its position and the turn (Euler\n *  order `YZX`) that points its local +x out of the hull and +y up the topsides. */\nexport function onHull(s: ShipShape, side: 1 | -1, z: number, y: number, proud = 0) {\n  const d = 0.05\n  const dz = (halfBreadth(s, z + d, y) - halfBreadth(s, z - d, y)) / (2 * d)\n  const dy = (halfBreadth(s, z, y + d) - halfBreadth(s, z, y - d)) / (2 * d)\n  const position: V3 = [side * (halfBreadth(s, z, y) + proud), y, z]\n  const yaw = side > 0 ? Math.atan(dz) : Math.PI - Math.atan(dz)\n  const rotation: V3 = [0, yaw, -Math.atan(dy)]\n  return { position, rotation }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/mesh.ts",
      "content": "import { BufferAttribute, BufferGeometry, type Color } from 'three'\n\nexport type V3 = [number, number, number]\n\n/** Collects flat-shaded, vertex-coloured triangles. `quad` takes a hint the face should point\n *  along and winds it to match, so callers never reason about winding. */\nexport class MeshBuilder {\n  readonly pos: number[] = []\n  readonly col: number[] = []\n\n  tri(a: V3, b: V3, c: V3, color?: Color) {\n    const ux = b[0] - a[0]\n    const uy = b[1] - a[1]\n    const uz = b[2] - a[2]\n    const vx = c[0] - a[0]\n    const vy = c[1] - a[1]\n    const vz = c[2] - a[2]\n    const nx = uy * vz - uz * vy\n    const ny = uz * vx - ux * vz\n    const nz = ux * vy - uy * vx\n    // Clamped hull rows meet at the stem and stern; their slivers would only trouble the collider.\n    if (nx * nx + ny * ny + nz * nz < 1e-10) return\n    this.pos.push(...a, ...b, ...c)\n    if (color) for (let i = 0; i < 3; i++) this.col.push(color.r, color.g, color.b)\n  }\n\n  quad(a: V3, b: V3, c: V3, d: V3, hint: V3, color?: Color) {\n    // The diagonals' cross product stays true when the quad has collapsed to a triangle.\n    const ux = c[0] - a[0]\n    const uy = c[1] - a[1]\n    const uz = c[2] - a[2]\n    const vx = d[0] - b[0]\n    const vy = d[1] - b[1]\n    const vz = d[2] - b[2]\n    const n =\n      (uy * vz - uz * vy) * hint[0] + (uz * vx - ux * vz) * hint[1] + (ux * vy - uy * vx) * hint[2]\n    if (n >= 0) {\n      this.tri(a, b, c, color)\n      this.tri(a, c, d, color)\n    } else {\n      this.tri(a, c, b, color)\n      this.tri(a, d, c, color)\n    }\n  }\n\n  append(other: MeshBuilder) {\n    for (const v of other.pos) this.pos.push(v)\n    for (const v of other.col) this.col.push(v)\n  }\n\n  get empty() {\n    return this.pos.length === 0\n  }\n\n  geometry(): BufferGeometry {\n    const g = new BufferGeometry()\n    g.setAttribute('position', new BufferAttribute(new Float32Array(this.pos), 3))\n    if (this.col.length) g.setAttribute('color', new BufferAttribute(new Float32Array(this.col), 3))\n    g.computeVertexNormals()\n    return g\n  }\n\n  /** The same triangles as a trimesh collider's vertices and indices. */\n  trimesh(): [Float32Array, Uint32Array] {\n    const vertices = new Float32Array(this.pos)\n    const indices = new Uint32Array(vertices.length / 3)\n    for (let i = 0; i < indices.length; i++) indices[i] = i\n    return [vertices, indices]\n  }\n}\n\n/** A cheap stable hash of two integers and a seed, in [0, 1). */\nexport function hash01(a: number, b: number, seed: number): number {\n  let h =\n    Math.imul(a | 0, 0x27d4eb2d) ^ Math.imul(b | 0, 0x165667b1) ^ Math.imul(seed | 0, 0x9e3779b1)\n  h = Math.imul(h ^ (h >>> 15), 0x85ebca6b)\n  h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35)\n  return ((h ^ (h >>> 16)) >>> 0) / 4294967296\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/parts.tsx",
      "content": "import { CuboidCollider, CylinderCollider } from '@react-three/rapier'\nimport { useLight } from '@runek/core'\nimport { useEffect, useLayoutEffect, useMemo, useRef } from 'react'\nimport {\n  BoxGeometry,\n  type BufferGeometry,\n  Color,\n  CylinderGeometry,\n  Euler,\n  type InstancedMesh,\n  type Material,\n  Matrix4,\n  PlaneGeometry,\n  Quaternion,\n  Vector3,\n} from 'three'\nimport { bowZ, GANGWAY, halfBreadth, LEVEL, type ShipShape, sternZ } from '../surfaces/ship'\nimport type { Gun, Hammock } from './fittings'\nimport { onHull } from './hull'\nimport type { V3 } from './mesh'\n\nexport type Mats = Record<\n  'wood' | 'dark' | 'iron' | 'port' | 'lid' | 'canvas' | 'glass' | 'brass' | 'rope',\n  Material\n>\n\nconst matrix = (position: V3, rotation: V3 = [0, 0, 0], scale: V3 = [1, 1, 1], order = 'XYZ') =>\n  new Matrix4().compose(\n    new Vector3(...position),\n    new Quaternion().setFromEuler(new Euler(...rotation, order as 'XYZ')),\n    new Vector3(...scale),\n  )\n\n/** One instanced draw for many copies of a part. */\nexport function Instanced({\n  geometry,\n  material,\n  matrices,\n  colors,\n  castShadow = false,\n}: {\n  geometry: BufferGeometry\n  material: Material\n  matrices: Matrix4[]\n  colors?: Color[]\n  castShadow?: boolean\n}) {\n  const ref = useRef<InstancedMesh>(null)\n  useLayoutEffect(() => {\n    const mesh = ref.current\n    if (!mesh) return\n    matrices.forEach((m, i) => {\n      mesh.setMatrixAt(i, m)\n      if (colors) mesh.setColorAt(i, colors[i])\n    })\n    mesh.instanceMatrix.needsUpdate = true\n    if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true\n    mesh.computeBoundingSphere()\n  }, [matrices, colors])\n  useEffect(() => () => geometry.dispose(), [geometry])\n  if (!matrices.length) return null\n  return (\n    <instancedMesh\n      key={matrices.length}\n      ref={ref}\n      args={[geometry, material, matrices.length]}\n      castShadow={castShadow}\n      receiveShadow\n    />\n  )\n}\n\nconst BARREL = matrix([0.15, 0.62, 0], [0, 0, -Math.PI / 2])\nconst CARRIAGE = matrix([-0.15, 0.34, 0])\nconst WHEELS = [-1, 1].flatMap((a) =>\n  [-1, 1].map((b) => matrix([-0.15 + a * 0.42, 0.17, b * 0.42], [Math.PI / 2, 0, 0])),\n)\n\n/** Cannons on their carriages, run out to the ports. */\nexport function Cannons({ guns, m }: { guns: Gun[]; m: Mats }) {\n  const parts = useMemo(() => {\n    const bases = guns.map((g) => matrix([g.x, g.y, g.z], [0, g.side > 0 ? 0 : Math.PI, 0]))\n    return {\n      barrel: new CylinderGeometry(0.12, 0.2, 2, 12),\n      carriage: new BoxGeometry(1.3, 0.36, 0.78),\n      wheel: new CylinderGeometry(0.17, 0.17, 0.1, 10),\n      barrels: bases.map((b) => b.clone().multiply(BARREL)),\n      carriages: bases.map((b) => b.clone().multiply(CARRIAGE)),\n      wheels: bases.flatMap((b) => WHEELS.map((w) => b.clone().multiply(w))),\n    }\n  }, [guns])\n  return (\n    <>\n      <Instanced geometry={parts.barrel} material={m.iron} matrices={parts.barrels} castShadow />\n      <Instanced\n        geometry={parts.carriage}\n        material={m.wood}\n        matrices={parts.carriages}\n        castShadow\n      />\n      <Instanced geometry={parts.wheel} material={m.dark} matrices={parts.wheels} />\n    </>\n  )\n}\n\n/** One cuboid per gun: the gun line is something you walk round, not through. */\nexport function CannonColliders({ guns }: { guns: Gun[] }) {\n  return guns.map((g) => (\n    <CuboidCollider\n      key={`${g.side}:${g.y}:${g.z.toFixed(2)}`}\n      args={[0.95, 0.45, 0.42]}\n      position={[g.x, g.y + 0.45, g.z]}\n    />\n  ))\n}\n\nconst LID_SHUT = matrix([0.05, 0, 0])\nconst LID_OPEN = matrix([0.03, 0.33, 0])\n  .multiply(matrix([0, 0, 0], [0, 0, 1.15]))\n  .multiply(matrix([0.03, -0.33, 0]))\n\n/** A dark recess and a lid for each gun's port, flush on the hull. */\nexport function Ports({ guns, shape, m }: { guns: Gun[]; shape: ShipShape; m: Mats }) {\n  const parts = useMemo(() => {\n    const frames = guns.map((g) => {\n      const size = g.y === LEVEL.gun ? 1 : 0.8\n      const { position, rotation } = onHull(shape, g.side, g.z, g.portY, 0.01)\n      return { base: matrix(position, rotation, [1, size, size], 'YZX'), open: g.open }\n    })\n    return {\n      port: new BoxGeometry(0.08, 0.62, 0.62),\n      lid: new BoxGeometry(0.06, 0.66, 0.66),\n      ports: frames.map((f) => f.base),\n      lids: frames.map((f) => f.base.clone().multiply(f.open ? LID_OPEN : LID_SHUT)),\n    }\n  }, [guns, shape])\n  return (\n    <>\n      <Instanced geometry={parts.port} material={m.port} matrices={parts.ports} />\n      <Instanced geometry={parts.lid} material={m.lid} matrices={parts.lids} />\n    </>\n  )\n}\n\n/** Canvas hammocks slung under the beams, each sagging and weathered a little differently. */\nexport function Hammocks({ items, m }: { items: Hammock[]; m: Mats }) {\n  const parts = useMemo(() => {\n    const g = new PlaneGeometry(0.8, 1.9, 6, 8)\n    g.rotateX(-Math.PI / 2)\n    const p = g.attributes.position\n    for (let i = 0; i < p.count; i++) {\n      const u = p.getX(i) / 0.4\n      const v = p.getZ(i) / 0.95\n      p.setY(i, -0.2 * (1 - u * u) * (1 - v ** 6))\n    }\n    g.computeVertexNormals()\n    const base = new Color(1, 1, 1)\n    return {\n      geometry: g,\n      matrices: items.map((h) => matrix([h.x, h.y, h.z], [0, 0, 0], [1, h.sag, 1])),\n      colors: items.map((h) => base.clone().multiplyScalar(h.tint)),\n    }\n  }, [items])\n  return (\n    <Instanced\n      geometry={parts.geometry}\n      material={m.canvas}\n      matrices={parts.matrices}\n      colors={parts.colors}\n    />\n  )\n}\n\n/** A hanging lantern, or a big stern lantern on the taffrail. Lit through the light pool. */\nexport function Lantern({\n  position,\n  stern = false,\n  m,\n}: {\n  position: V3\n  stern?: boolean\n  m: Mats\n}) {\n  const glow = useLight({\n    color: '#ffb766',\n    intensity: stern ? 14 : 7,\n    distance: stern ? 14 : 9,\n    decay: 2,\n  })\n  const k = stern ? 2.2 : 1\n  return (\n    <group position={position} scale={k}>\n      {!stern && (\n        <mesh material={m.iron} position={[0, 0.36, 0]}>\n          <cylinderGeometry args={[0.012, 0.012, 0.32, 4]} />\n        </mesh>\n      )}\n      {stern && (\n        <mesh material={m.iron} position={[0, -0.32, 0]}>\n          <cylinderGeometry args={[0.03, 0.05, 0.28, 6]} />\n        </mesh>\n      )}\n      <mesh material={m.glass}>\n        <cylinderGeometry args={[0.11, 0.09, 0.3, 6]} />\n      </mesh>\n      <mesh material={m.iron} position={[0, 0.19, 0]}>\n        <coneGeometry args={[0.15, 0.12, 6]} />\n      </mesh>\n      <mesh material={m.iron} position={[0, -0.17, 0]}>\n        <cylinderGeometry args={[0.12, 0.1, 0.04, 6]} />\n      </mesh>\n      <object3D ref={glow.ref} />\n    </group>\n  )\n}\n\n/** The ship's wheel on its pedestal, with the binnacle forward of it. */\nexport function Wheel({ z, m }: { z: number; m: Mats }) {\n  const y = LEVEL.quarter\n  return (\n    <group position={[0, y, z]}>\n      {[-1, 1].map((s) => (\n        <mesh key={s} material={m.wood} position={[s * 0.32, 0.62, 0]} castShadow>\n          <boxGeometry args={[0.12, 1.25, 0.18]} />\n        </mesh>\n      ))}\n      <mesh material={m.wood} position={[0, 1.15, 0]} castShadow>\n        <boxGeometry args={[0.76, 0.26, 0.3]} />\n      </mesh>\n      <group position={[0, 1.15, 0.22]}>\n        <mesh material={m.dark} castShadow>\n          <torusGeometry args={[0.62, 0.035, 6, 28]} />\n        </mesh>\n        <mesh material={m.dark} rotation={[Math.PI / 2, 0, 0]}>\n          <cylinderGeometry args={[0.11, 0.11, 0.14, 10]} />\n        </mesh>\n        {[0, 1, 2, 3].map((k) => (\n          <mesh key={k} material={m.dark} rotation={[0, 0, (k * Math.PI) / 4]}>\n            <boxGeometry args={[0.04, 1.62, 0.04]} />\n          </mesh>\n        ))}\n      </group>\n      <group position={[0, 0, 1.1]}>\n        <mesh material={m.wood} position={[0, 0.5, 0]} castShadow>\n          <cylinderGeometry args={[0.22, 0.28, 1, 8]} />\n        </mesh>\n        <mesh material={m.brass} position={[0, 1, 0]}>\n          <sphereGeometry args={[0.2, 12, 6, 0, Math.PI * 2, 0, Math.PI / 2]} />\n        </mesh>\n      </group>\n    </group>\n  )\n}\n\nexport function WheelColliders({ z }: { z: number }) {\n  const y = LEVEL.quarter\n  return (\n    <>\n      <CuboidCollider args={[0.45, 0.9, 0.3]} position={[0, y + 0.9, z + 0.05]} />\n      <CylinderCollider args={[0.55, 0.28]} position={[0, y + 0.55, z + 1.1]} />\n    </>\n  )\n}\n\n/** The capstan: a waisted drum with whelps under a round drumhead. */\nexport function Capstan({ z, m }: { z: number; m: Mats }) {\n  return (\n    <group position={[0, LEVEL.main, z]}>\n      <mesh material={m.wood} position={[0, 0.45, 0]} castShadow>\n        <cylinderGeometry args={[0.4, 0.46, 0.9, 12]} />\n      </mesh>\n      {Array.from({ length: 8 }, (_, k) => {\n        const a = (k / 8) * Math.PI * 2\n        return (\n          <mesh\n            key={a}\n            material={m.dark}\n            position={[Math.sin(a) * 0.44, 0.45, Math.cos(a) * 0.44]}\n            rotation={[0, a, 0]}\n          >\n            <boxGeometry args={[0.08, 0.82, 0.1]} />\n          </mesh>\n        )\n      })}\n      <mesh material={m.wood} position={[0, 0.98, 0]} castShadow>\n        <cylinderGeometry args={[0.58, 0.58, 0.16, 16]} />\n      </mesh>\n    </group>\n  )\n}\n\n/** The ship's bell in a small belfry at the forecastle's break. */\nexport function Bell({ z, m }: { z: number; m: Mats }) {\n  return (\n    <group position={[0, LEVEL.fore, z]}>\n      {[-1, 1].map((s) => (\n        <mesh key={s} material={m.wood} position={[s * 0.36, 0.7, 0]} castShadow>\n          <boxGeometry args={[0.1, 1.4, 0.12]} />\n        </mesh>\n      ))}\n      <mesh material={m.wood} position={[0, 1.42, 0]} castShadow>\n        <boxGeometry args={[0.86, 0.12, 0.16]} />\n      </mesh>\n      <mesh material={m.brass} position={[0, 1.15, 0]} castShadow>\n        <cylinderGeometry args={[0.08, 0.17, 0.3, 14, 1, true]} />\n      </mesh>\n    </group>\n  )\n}\n\n/** The rudder, hung on the raked sternpost from below the keel line to the counter. */\nexport function Rudder({ shape, m }: { shape: ShipShape; m: Mats }) {\n  const y0 = LEVEL.keel + 0.3\n  const y1 = LEVEL.gun + 0.6\n  const z0 = sternZ(shape, y0)\n  const z1 = sternZ(shape, y1)\n  const rake = Math.atan2(z0 - z1, y1 - y0)\n  const chord = 1.3\n  return (\n    <mesh\n      material={m.dark}\n      position={[0, (y0 + y1) / 2, (z0 + z1) / 2 - chord / 2]}\n      rotation={[-rake, 0, 0]}\n      castShadow\n    >\n      <boxGeometry args={[0.28, Math.hypot(y1 - y0, z1 - z0), chord]} />\n    </mesh>\n  )\n}\n\n/** A stocked anchor hanging from its cathead on each bow. */\nexport function Anchors({ shape, m }: { shape: ShipShape; m: Mats }) {\n  const y = LEVEL.fore + 0.6\n  const z = bowZ(shape, y) - 4\n  return [1, -1].map((side) => {\n    const x = side * (halfBreadth(shape, z, y) + 0.45)\n    const hx = side * (halfBreadth(shape, z, y - 2) + 0.5)\n    return (\n      <group key={side}>\n        <mesh material={m.wood} position={[x + side * 0.1, y, z]} castShadow>\n          <boxGeometry args={[1.1, 0.26, 0.26]} />\n        </mesh>\n        <group position={[hx, y - 1.5, z]} rotation={[0, 0, side * 0.08]}>\n          <mesh material={m.iron} castShadow>\n            <cylinderGeometry args={[0.06, 0.07, 2.6, 6]} />\n          </mesh>\n          <mesh material={m.wood} position={[0, 1.15, 0]} castShadow>\n            <boxGeometry args={[0.14, 0.14, 1.9]} />\n          </mesh>\n          {[-1, 1].map((a) => (\n            <mesh\n              key={a}\n              material={m.iron}\n              position={[0, -1.05, a * 0.42]}\n              rotation={[a * -0.75, 0, 0]}\n              castShadow\n            >\n              <boxGeometry args={[0.1, 0.8, 0.12]} />\n            </mesh>\n          ))}\n        </group>\n      </group>\n    )\n  })\n}\n\nexport interface GangwayPlan {\n  side: 1 | -1\n  z: number\n  /** Outer hull at the main deck, where the plank meets the ship. */\n  x: number\n  reach: number\n  drop: number\n}\n\nexport function gangwayPlan(\n  shape: ShipShape,\n  z: number,\n  side: 1 | -1,\n  drop: number,\n  reach: number,\n) {\n  return { side, z, x: side * halfBreadth(shape, z, LEVEL.main), reach, drop }\n}\n\n/** A cleated plank from the gangway opening down to the shore, with rope rails on stanchions. */\nexport function Gangway({ plan, m }: { plan: GangwayPlan; m: Mats }) {\n  const { reach, drop } = plan\n  const len = Math.hypot(reach, drop)\n  const tilt = Math.atan2(drop, reach)\n  const w = GANGWAY.width\n  const parts = useMemo(() => {\n    const cleat = new BoxGeometry(0.05, 0.04, w * 0.9)\n    const cleats: Matrix4[] = []\n    for (let d = 0.3; d < len - 0.2; d += 0.4) cleats.push(matrix([d, 0.02, 0]))\n    const post = new CylinderGeometry(0.03, 0.03, 1, 5)\n    const posts: Matrix4[] = []\n    const n = Math.max(2, Math.round(len / 1.5) + 1)\n    for (let i = 0; i < n; i++)\n      for (const s of [-1, 1]) posts.push(matrix([(len * i) / (n - 1), 0.5, s * (w / 2 - 0.03)]))\n    return { cleat, cleats, post, posts }\n  }, [len, w])\n  return (\n    <group position={[plan.x, LEVEL.main, plan.z]} rotation={[0, plan.side > 0 ? 0 : Math.PI, 0]}>\n      <group rotation={[0, 0, -tilt]}>\n        <mesh material={m.wood} position={[len / 2, -0.05, 0]} castShadow receiveShadow>\n          <boxGeometry args={[len, 0.1, w]} />\n        </mesh>\n        <Instanced geometry={parts.cleat} material={m.dark} matrices={parts.cleats} />\n        <Instanced geometry={parts.post} material={m.wood} matrices={parts.posts} />\n        {[-1, 1].map((s) => (\n          <mesh\n            key={s}\n            material={m.rope}\n            position={[len / 2, 0.98, s * (w / 2 - 0.03)]}\n            rotation={[0, 0, Math.PI / 2]}\n          >\n            <cylinderGeometry args={[0.018, 0.018, len, 4]} />\n          </mesh>\n        ))}\n      </group>\n    </group>\n  )\n}\n\n/** The plank, its rails, and a sill bridging the hull's thickness to the deck. */\nexport function GangwayColliders({ plan }: { plan: GangwayPlan }) {\n  const { reach, drop } = plan\n  const len = Math.hypot(reach, drop)\n  const tilt = Math.atan2(drop, reach)\n  const w = GANGWAY.width\n  return (\n    <group position={[plan.x, LEVEL.main, plan.z]} rotation={[0, plan.side > 0 ? 0 : Math.PI, 0]}>\n      <CuboidCollider args={[0.3, 0.075, w / 2]} position={[-0.25, -0.075, 0]} />\n      <group rotation={[0, 0, -tilt]}>\n        <CuboidCollider args={[len / 2, 0.05, w / 2]} position={[len / 2, -0.05, 0]} />\n        {[-1, 1].map((s) => (\n          <CuboidCollider\n            key={s}\n            args={[len / 2, 0.5, 0.03]}\n            position={[len / 2, 0.5, s * (w / 2 + 0.03)]}\n          />\n        ))}\n      </group>\n    </group>\n  )\n}\n",
      "type": "registry:component"
    },
    {
      "path": "ship/rigging.ts",
      "content": "import { BufferAttribute, BufferGeometry } from 'three'\nimport { bowZ, halfBreadth, LEVEL, railY, type ShipLayout, sternZ } from '../surfaces/ship'\nimport { hash01, type V3 } from './mesh'\n\nexport type SailPlan = 'set' | 'furled' | 'none'\n\nexport interface Yard {\n  y: number\n  /** Half the yard's span. */\n  half: number\n  /** Carries a square sail hanging to the yard below (or the course's foot). */\n  sail: boolean\n}\n\nexport interface Mast {\n  key: 'fore' | 'main' | 'mizzen'\n  z: number\n  /** Radius at the deck. */\n  r: number\n  top: number\n  cross: number\n  truck: number\n  /** Half the top platform's width. */\n  topHalf: number\n  yards: Yard[]\n}\n\nexport interface Bowsprit {\n  base: V3\n  tip: V3\n  length: number\n  angle: number\n}\n\nexport interface Spanker {\n  jaw: V3\n  peak: V3\n  tack: V3\n  clew: V3\n}\n\nexport interface Rig {\n  masts: Mast[]\n  bowsprit: Bowsprit\n  spanker: Spanker | null\n}\n\nconst SCALE = { fore: 0.86, main: 1, mizzen: 0.66 }\n\n/** Which masts stand for a count: three-masted, then the mizzen goes, then the fore. */\nconst STEP: Record<number, Mast['key'][]> = {\n  1: ['main'],\n  2: ['fore', 'main'],\n  3: ['fore', 'main', 'mizzen'],\n}\n\nexport function rigLayout(lay: ShipLayout, count: number): Rig {\n  const s = lay.shape\n  const L = s.length\n  const H = 0.85 * L\n  const { main } = LEVEL\n  const masts = STEP[Math.min(3, Math.max(1, Math.round(count)))].map((key): Mast => {\n    const k = SCALE[key]\n    const h = H * k\n    const mizzen = key === 'mizzen'\n    return {\n      key,\n      z: lay.masts[key],\n      r: 0.45 * k,\n      top: main + 0.42 * h,\n      cross: main + 0.74 * h,\n      truck: main + h,\n      topHalf: 1.3 * k,\n      yards: [\n        // The mizzen's lowest yard (the crossjack) sets no sail: the spanker fills that space.\n        { y: main + 0.36 * h, half: 0.25 * L * k, sail: !mizzen },\n        { y: main + 0.62 * h, half: 0.19 * L * k, sail: true },\n        { y: main + 0.86 * h, half: 0.13 * L * k, sail: true },\n      ],\n    }\n  })\n  const zb = bowZ(s, LEVEL.fore)\n  const angle = 0.36\n  const length = 0.26 * L\n  const base: V3 = [0, LEVEL.fore + 0.5, zb - 2.2]\n  const tip: V3 = [0, base[1] + Math.sin(angle) * length, base[2] + Math.cos(angle) * length]\n  const miz = masts.find((m) => m.key === 'mizzen')\n  let spanker: Spanker | null = null\n  if (miz) {\n    const jaw: V3 = [0, miz.top - 0.6, miz.z - miz.r]\n    const gaff = 0.17 * L\n    const peak: V3 = [0, jaw[1] + gaff * 0.5, jaw[2] - gaff * 0.87]\n    const boomY = LEVEL.quarter + 2.3\n    const tack: V3 = [0, boomY, miz.z - miz.r]\n    const clew: V3 = [0, boomY, Math.max(miz.z - 0.24 * L, sternZ(s, boomY) - 1.6)]\n    spanker = { jaw, peak, tack, clew }\n  }\n  return { masts, bowsprit: { base, tip, length, angle }, spanker }\n}\n\n/** Indexed, smooth-shaded cloth. */\nclass Cloth {\n  readonly pos: number[] = []\n  readonly idx: number[] = []\n\n  grid(nu: number, nv: number, at: (u: number, v: number) => V3) {\n    const start = this.pos.length / 3\n    for (let j = 0; j <= nv; j++) for (let i = 0; i <= nu; i++) this.pos.push(...at(i / nu, j / nv))\n    const row = nu + 1\n    for (let j = 0; j < nv; j++)\n      for (let i = 0; i < nu; i++) {\n        const a = start + j * row + i\n        this.idx.push(a, a + 1, a + row, a + 1, a + row + 1, a + row)\n      }\n  }\n\n  /** A triangle subdivided n times, its belly deepest at the centroid. */\n  triangle(n: number, a: V3, b: V3, c: V3, belly: V3) {\n    const start = this.pos.length / 3\n    const index: number[][] = []\n    for (let i = 0; i <= n; i++) {\n      index.push([])\n      for (let j = 0; j <= n - i; j++) {\n        const la = 1 - (i + j) / n\n        const lb = i / n\n        const lc = j / n\n        const f = 27 * la * lb * lc\n        index[i].push(this.pos.length / 3 - start)\n        this.pos.push(\n          la * a[0] + lb * b[0] + lc * c[0] + belly[0] * f,\n          la * a[1] + lb * b[1] + lc * c[1] + belly[1] * f,\n          la * a[2] + lb * b[2] + lc * c[2] + belly[2] * f,\n        )\n      }\n    }\n    for (let i = 0; i < n; i++)\n      for (let j = 0; j < n - i; j++) {\n        const p = start + index[i][j]\n        const q = start + index[i + 1][j]\n        const r = start + index[i][j + 1]\n        this.idx.push(p, q, r)\n        if (j < n - i - 1) this.idx.push(q, start + index[i + 1][j + 1], r)\n      }\n  }\n\n  geometry() {\n    const g = new BufferGeometry()\n    g.setAttribute('position', new BufferAttribute(new Float32Array(this.pos), 3))\n    g.setIndex(this.idx)\n    g.computeVertexNormals()\n    return g\n  }\n}\n\n/** Where each square sail hangs: from its yard down to the yard below, the course to a foot\n *  clear of a castle deck's heads. */\nexport function squareSails(rig: Rig) {\n  const out: { z: number; yt: number; yb: number; top: number; bottom: number }[] = []\n  for (const m of rig.masts) {\n    m.yards.forEach((yd, i) => {\n      if (!yd.sail) return\n      const below = m.yards[i - 1]\n      out.push({\n        z: m.z + m.r + 0.25,\n        yt: yd.y,\n        yb: below ? below.y + 0.3 : LEVEL.main + 4.2,\n        top: yd.half * 0.96,\n        bottom: below ? below.half * 0.94 : yd.half * 1.02,\n      })\n    })\n  }\n  return out\n}\n\n/** Every set sail as one geometry: square sails bellied forward, the spanker and the jibs\n *  bellied to port. The seed varies each sail's belly. */\nexport function buildSails(rig: Rig, seed: number): BufferGeometry {\n  const cloth = new Cloth()\n  squareSails(rig).forEach((sq, i) => {\n    const belly = (0.55 + 0.4 * hash01(i, 3, seed)) * (sq.top / 9)\n    cloth.grid(10, 6, (u, v) => {\n      const x = -1 + 2 * u\n      const half = sq.bottom + (sq.top - sq.bottom) * v\n      const roach = (1 - v) * 0.35 * Math.sin(Math.PI * u)\n      const y = sq.yb + (sq.yt - sq.yb) * v + roach\n      const bag = Math.sin(Math.PI * u) ** 0.8 * Math.sin(Math.PI * (1 - v) * 0.85)\n      return [x * half, y, sq.z + belly * bag]\n    })\n  })\n  const sp = rig.spanker\n  if (sp) {\n    const belly = 0.6 + 0.3 * hash01(40, 3, seed)\n    cloth.grid(6, 6, (u, v) => {\n      const lerp = (a: V3, b: V3, t: number): V3 => [\n        a[0] + (b[0] - a[0]) * t,\n        a[1] + (b[1] - a[1]) * t,\n        a[2] + (b[2] - a[2]) * t,\n      ]\n      const foot = lerp(sp.tack, sp.clew, u)\n      const head = lerp(sp.jaw, sp.peak, u)\n      const p = lerp(foot, head, v)\n      p[0] += belly * Math.sin(Math.PI * u) * Math.sin(Math.PI * v)\n      return p\n    })\n  }\n  const fore = rig.masts.find((m) => m.key === 'fore') ?? rig.masts[0]\n  const { tip, base } = rig.bowsprit\n  const stay = (from: V3, to: V3, t: number): V3 => [\n    from[0] + (to[0] - from[0]) * t,\n    from[1] + (to[1] - from[1]) * t,\n    from[2] + (to[2] - from[2]) * t,\n  ]\n  const head: V3 = [0, fore.cross, fore.z]\n  const mid: V3 = stay(base, tip, 0.45)\n  const inner: V3 = [0, fore.top, fore.z]\n  const jibs: [V3, V3][] = [\n    [stay(tip, head, 0.06), stay(tip, head, 0.6)],\n    [stay(mid, inner, 0.06), stay(mid, inner, 0.62)],\n  ]\n  jibs.forEach(([tack, peak], i) => {\n    const clew: V3 = [0, tack[1] - 0.4 - i * 0.6, tack[2] - 0.62 * (tack[2] - peak[2])]\n    const belly = 0.45 + 0.3 * hash01(50 + i, 3, seed)\n    cloth.triangle(6, tack, peak, clew, [belly, 0, 0])\n  })\n  return cloth.geometry()\n}\n\n/** Shrouds with ratlines, stays, backstays, lifts and braces: one line-segment list. */\nexport function buildRigging(lay: ShipLayout, rig: Rig): Float32Array {\n  const s = lay.shape\n  const seg: number[] = []\n  const line = (a: V3, b: V3) => seg.push(...a, ...b)\n  const lerp = (a: V3, b: V3, t: number): V3 => [\n    a[0] + (b[0] - a[0]) * t,\n    a[1] + (b[1] - a[1]) * t,\n    a[2] + (b[2] - a[2]) * t,\n  ]\n  const channel = (side: number, z: number): V3 => {\n    const zc = Math.max(sternZ(s, LEVEL.quarter) + 1, z)\n    const y = railY(s, zc) - 0.15\n    return [side * (halfBreadth(s, zc, y) + 0.35), y, zc]\n  }\n  for (const m of rig.masts) {\n    const n = m.key === 'mizzen' ? 4 : 6\n    for (const side of [1, -1]) {\n      const head: V3 = [side * m.topHalf * 0.9, m.top, m.z]\n      const feet = Array.from({ length: n }, (_, k) => channel(side, m.z - 2.6 + k * 0.8))\n      for (const f of feet) line(head, f)\n      const low = Math.max(...feet.map((f) => f[1])) + 0.5\n      for (let y = low; y < m.top - 0.8; y += 0.42) {\n        const pts = feet.map((f) => lerp(f, head, (y - f[1]) / (head[1] - f[1])))\n        for (let k = 0; k < pts.length - 1; k++) line(pts[k], pts[k + 1])\n      }\n      for (let k = -1; k <= 1; k++)\n        line([side * 0.35, m.cross, m.z], [side * m.topHalf, m.top, m.z + k * 0.5])\n      for (const dz of [5.4, 6.6]) line([side * 0.3, m.cross, m.z], channel(side, m.z - dz))\n      for (const yd of m.yards) {\n        const end: V3 = [side * yd.half, yd.y, m.z + m.r]\n        line([0, yd.y + 2.2, m.z], end)\n        line(end, channel(side, m.z - 7.5))\n      }\n    }\n  }\n  const by = Object.fromEntries(rig.masts.map((m) => [m.key, m])) as Partial<\n    Record<Mast['key'], Mast>\n  >\n  const { tip, base } = rig.bowsprit\n  const first = by.fore ?? by.main\n  if (first) {\n    line([0, first.top, first.z], lerp(base, tip, 0.45))\n    line([0, first.cross, first.z], tip)\n    line([0, first.truck - 0.5, first.z], tip)\n  }\n  if (by.main && by.fore) {\n    line([0, by.main.top, by.main.z], [0, LEVEL.main + 1, by.fore.z - 0.6])\n    line([0, by.main.cross, by.main.z], [0, by.fore.top, by.fore.z])\n  }\n  if (by.mizzen && by.main) {\n    line([0, by.mizzen.top, by.mizzen.z], [0, LEVEL.main + 3.5, by.main.z])\n    line([0, by.mizzen.cross, by.mizzen.z], [0, by.main.top, by.main.z])\n  }\n  line(tip, [0, 1.2, bowZ(s, 1.2)])\n  return new Float32Array(seg)\n}\n",
      "type": "registry:component"
    },
    {
      "path": "surfaces/ship.ts",
      "content": "import type { SurfaceDef } from '@runek/core'\n\n// The ship's shape and layout, in metres with the origin on the waterline at midships and the\n// bow at +z. Pure, so the mesh, the colliders and `runek check-world` all read one hull.\n\n/** Floor heights of each level above the waterline. */\nexport const LEVEL = { keel: -3.6, hold: 0.4, gun: 2.6, main: 4.8, fore: 7, quarter: 7 }\nexport const DECK = 0.15\nexport const SKIN = 0.2\nexport const BULWARK = 1.05\n/** Each hatch's opening; its stair runs the length of it, 0.2 short at the foot. */\nexport const HATCH = { width: 1.5, length: 5 }\nexport const STAIR = { width: 1.2, run: 4.8 }\nexport const CASTLE_STAIR = { width: 1.1, quarterRun: 4.4, foreRun: 4.4 }\nexport const DOOR = { width: 1.2, height: 2 }\nexport const GANGWAY = { width: 1.2, gap: 1.6, slope: 0.38 }\n\nexport const TOP = LEVEL.quarter + BULWARK\nconst STEM = 0.15\n\nconst clamp01 = (v: number) => Math.min(1, Math.max(0, v))\nconst smooth = (v: number) => {\n  const t = clamp01(v)\n  return t * t * (3 - 2 * t)\n}\n\nexport interface ShipShape {\n  length: number\n  beam: number\n}\n\nexport function shipShape(length = 36, beam = 10): ShipShape {\n  return {\n    length: Math.min(60, Math.max(30, length)),\n    beam: Math.min(16, Math.max(8, beam)),\n  }\n}\n\nconst heightFrac = (y: number) => clamp01((y - LEVEL.keel) / (TOP - LEVEL.keel))\n\n/** Where the stem is at height y: raked forward toward the rail. */\nexport const bowZ = (s: ShipShape, y: number) => (s.length / 2) * (0.8 + 0.2 * heightFrac(y) ** 0.8)\n\n/** Where the stern is at height y: the transom overhangs above the waterline. */\nexport const sternZ = (s: ShipShape, y: number) =>\n  -(s.length / 2) * (0.86 + 0.14 * smooth(heightFrac(y)))\n\n/** Half the outer hull's breadth at (z, y): full midships, a fine entry at the bow, a wide\n *  transom aft above the waterline narrowing to the sternpost below it, a little tumblehome. */\nexport function halfBreadth(s: ShipShape, z: number, y: number): number {\n  const zb = bowZ(s, y)\n  const zs = sternZ(s, y)\n  if (z > zb || z < zs) return 0\n  let plan: number\n  let fine: number\n  if (z >= 0) {\n    const u = z / zb\n    plan = 1 - u ** 2.3\n    fine = u ** 1.5\n  } else {\n    const a = z / zs\n    const transom = 0.62 * smooth((y + 1.2) / 4.2)\n    plan = transom + (1 - transom) * (1 - a ** 2.6) ** 0.6\n    fine = a * a * 0.6\n  }\n  let section: number\n  if (y < 0) {\n    const q = clamp01((y - LEVEL.keel) / -LEVEL.keel)\n    const full = 1 - (1 - q) ** 2.6\n    section = full + (q ** 0.9 - full) * fine\n  } else {\n    section = 1 - 0.1 * clamp01(y / TOP) ** 1.6\n  }\n  return Math.max((s.beam / 2) * plan * section, STEM)\n}\n\nexport const innerBreadth = (s: ShipShape, z: number, y: number) =>\n  Math.max(0, halfBreadth(s, z, y) - SKIN)\n\n/** The z span a deck at height y covers: from inside the transom to where the bow gets too\n *  narrow to stand in. */\nexport function deckSpan(s: ShipShape, y: number): [number, number] {\n  const aft = sternZ(s, y) + SKIN\n  let lo = 0\n  let hi = bowZ(s, y)\n  for (let i = 0; i < 30; i++) {\n    const mid = (lo + hi) / 2\n    if (innerBreadth(s, mid, y) > 0.05) lo = mid\n    else hi = mid\n  }\n  return [aft, lo]\n}\n\nconst ease = (v: number) => smooth(v)\n\n/** Top of the bulwark at z: a castle's rail over the quarterdeck and forecastle, the waist's\n *  rail between, eased up over 1.5 m outside each castle. */\nexport function railY(s: ShipShape, z: number): number {\n  const { zQ, zF } = breaks(s)\n  const q = (LEVEL.quarter - LEVEL.main) * ease((zQ + 1.5 - z) / 1.5)\n  const f = (LEVEL.fore - LEVEL.main) * ease((z - (zF - 1.5)) / 1.5)\n  return LEVEL.main + BULWARK + q + f\n}\n\n/** The quarterdeck (aft of zQ) and forecastle (fore of zF) breaks. */\nexport function breaks(s: ShipShape) {\n  const h = s.length / 2\n  return { zQ: -h + 0.3 * s.length, zF: h - 0.2 * s.length }\n}\n\nexport interface Box {\n  z0: number\n  z1: number\n  x: number\n  w: number\n}\n\nexport interface ShipLayout {\n  shape: ShipShape\n  zQ: number\n  zF: number\n  masts: { fore: number; main: number; mizzen: number }\n  /** Main deck to gun deck: the stair rises aft, its head at `z0`. */\n  hatchA: Box\n  /** Gun deck to hold: the stair rises forward, its head at `z1`. */\n  hatchB: Box\n  /** Waist to quarterdeck, port and starboard: rising aft, head at zQ. */\n  quarterStairs: Box[]\n  /** Waist to forecastle: rising forward, head at zF. */\n  foreStairs: Box[]\n  gangway: { z: number; side: 1 | -1 }\n}\n\n/** Every place the ship's levels, masts, hatches and stairs go, from length and beam. */\nexport function shipLayout(s: ShipShape, gangwaySide: 1 | -1 = -1): ShipLayout {\n  const h = s.length / 2\n  const { zQ, zF } = breaks(s)\n  const masts = { fore: 0.52 * h, main: -0.05 * h, mizzen: -0.62 * h }\n  const a0 = masts.main + 2.1\n  const hatchA = { z0: a0, z1: a0 + HATCH.length, x: 0, w: HATCH.width }\n  const b1 = masts.main - 1.5\n  const hatchB = { z0: b1 - HATCH.length, z1: b1, x: 0, w: HATCH.width }\n  const w = CASTLE_STAIR.width\n  const qz1 = zQ + CASTLE_STAIR.quarterRun\n  const qx = Math.min(innerBreadth(s, zQ, LEVEL.quarter), innerBreadth(s, qz1, LEVEL.main)) - 0.7\n  const fz0 = zF - CASTLE_STAIR.foreRun\n  const fx = Math.min(innerBreadth(s, zF, LEVEL.fore), innerBreadth(s, zF, LEVEL.main)) - 0.7\n  return {\n    shape: s,\n    zQ,\n    zF,\n    masts,\n    hatchA,\n    hatchB,\n    quarterStairs: [-1, 1].map((side) => ({ z0: zQ, z1: qz1, x: side * qx, w })),\n    foreStairs: [-1, 1].map((side) => ({ z0: fz0, z1: zF, x: side * fx, w })),\n    gangway: { z: (qz1 + fz0) / 2, side: gangwaySide },\n  }\n}\n\n/** The gangplank's horizontal reach for a given drop to the shore end. */\nexport const gangwayReach = (drop: number) => Math.max(2, drop / GANGWAY.slope)\n\n/** Tread top of a `Staircase` flight (floating form) at distance `d` from its foot. */\nfunction treadAt(d: number, run: number, rise: number, steps: number): number | null {\n  if (d < 0 || d > run) return null\n  const i = Math.min(steps - 1, Math.floor((d / run) * steps))\n  return (rise / steps) * (i + 1)\n}\n\nexport const STEPS = { main: 12, quarter: 12, fore: 12 }\n\nconst inBox = (b: Box, x: number, z: number) =>\n  z >= b.z0 && z <= b.z1 && Math.abs(x - b.x) <= b.w / 2\n\ninterface ShipSurfaceProps {\n  length?: number\n  beam?: number\n  gangway?: 'port' | 'starboard' | 'none'\n  gangwayDrop?: number\n  collider?: boolean\n}\n\n/** The ship's weather decks: the waist, the quarterdeck and forecastle, their stairs, and the\n *  gangplank, the highest walkable top at a point. Below-deck floors are covered. */\nexport const shipSurface: SurfaceDef = {\n  kind: 'deck',\n  build(props, { unit }) {\n    const p = props as ShipSurfaceProps\n    if (p.collider === false) return () => null\n    const s = shipShape(p.length, p.beam)\n    const side = p.gangway === 'port' ? 1 : -1\n    const lay = shipLayout(s, side)\n    const drop = p.gangwayDrop ?? 3.8\n    const reach = gangwayReach(drop)\n    const [, bowMain] = deckSpan(s, LEVEL.main)\n    const [aftQ] = deckSpan(s, LEVEL.quarter)\n    const [, bowF] = deckSpan(s, LEVEL.fore)\n    return (ux, uz) => {\n      const x = ux / unit\n      const z = uz / unit\n      const at = (y: number) => y * unit\n      if (p.gangway !== 'none') {\n        const out = side * x - halfBreadth(s, lay.gangway.z, LEVEL.main)\n        if (Math.abs(z - lay.gangway.z) <= GANGWAY.width / 2 && out >= 0 && out <= reach)\n          return at(LEVEL.main - (out / reach) * drop)\n      }\n      for (const b of lay.quarterStairs) {\n        if (!inBox(b, x, z)) continue\n        const t = treadAt(\n          b.z1 - z,\n          CASTLE_STAIR.quarterRun,\n          LEVEL.quarter - LEVEL.main,\n          STEPS.quarter,\n        )\n        if (t !== null) return at(LEVEL.main + t)\n      }\n      for (const b of lay.foreStairs) {\n        if (!inBox(b, x, z)) continue\n        const t = treadAt(z - b.z0, CASTLE_STAIR.foreRun, LEVEL.fore - LEVEL.main, STEPS.fore)\n        if (t !== null) return at(LEVEL.main + t)\n      }\n      if (z <= lay.zQ) {\n        if (z < aftQ || Math.abs(x) > innerBreadth(s, z, LEVEL.quarter)) return null\n        return at(LEVEL.quarter)\n      }\n      if (z >= lay.zF) {\n        if (z > bowF || Math.abs(x) > innerBreadth(s, z, LEVEL.fore)) return null\n        return at(LEVEL.fore)\n      }\n      if (z > bowMain || Math.abs(x) > innerBreadth(s, z, LEVEL.main)) return null\n      if (inBox(lay.hatchA, x, z)) {\n        const t = treadAt(\n          lay.hatchA.z0 + STAIR.run - z,\n          STAIR.run,\n          LEVEL.main - LEVEL.gun,\n          STEPS.main,\n        )\n        return at(LEVEL.gun + (t ?? 0))\n      }\n      return at(LEVEL.main)\n    }\n  },\n}\n",
      "type": "registry:component"
    }
  ]
}
