@willcgage/module-schematic 0.97.1 → 0.101.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -227,7 +227,7 @@ function moduleCenterline(input) {
227
227
  if (drawn) return samplePath(drawn);
228
228
  const chained = sectionedCenterline(input);
229
229
  if (chained.length >= 2) return chained;
230
- if (!input.geometryType) return [];
230
+ if (!input.geometryType && !input.hasPlacedTrack) return [];
231
231
  const L = input.lengthInches > 0 ? input.lengthInches : 24;
232
232
  const gt = input.geometryType;
233
233
  if (gt === "dead_end") return [{ x: 0, y: 0 }];
@@ -1797,8 +1797,8 @@ function turnoutFacing(input) {
1797
1797
  function turnoutOccupiedSpan(input) {
1798
1798
  const e = input.extent;
1799
1799
  if (!e) return null;
1800
- const a = input.pos - input.facing * e.behindPoints;
1801
- const b = input.pos + input.facing * e.aheadOfPoints;
1800
+ const a = input.pos - input.facing * e.behindFrog;
1801
+ const b = input.pos + input.facing * e.pastFrog;
1802
1802
  return { fromPos: Math.min(a, b), toPos: Math.max(a, b) };
1803
1803
  }
1804
1804
  function resizeFlexPiece(pieces, index, nextLengthInches) {
@@ -1831,10 +1831,12 @@ function partExtent(part) {
1831
1831
  if (pts.source !== "measured" || overall.source !== "measured") return null;
1832
1832
  const frog = part?.frogOffset;
1833
1833
  const aheadOfPoints = overall.inches - pts.inches;
1834
+ const frogMeasured = frog && frog.source === "measured";
1834
1835
  return {
1835
1836
  behindPoints: pts.inches,
1836
1837
  aheadOfPoints,
1837
- pastFrog: frog && frog.source === "measured" ? overall.inches - frog.inches : aheadOfPoints
1838
+ pastFrog: frogMeasured ? overall.inches - frog.inches : aheadOfPoints,
1839
+ behindFrog: frogMeasured ? frog.inches : pts.inches
1838
1840
  };
1839
1841
  }
1840
1842
  function partExtentForSize(size, library = BUILT_IN_TRACK_PARTS) {
@@ -2551,6 +2553,83 @@ function fitFlexBetween(piece, others, library = BUILT_IN_TRACK_PARTS, withinInc
2551
2553
  lengthInches: Math.round(len * 1e3) / 1e3
2552
2554
  };
2553
2555
  }
2556
+ function insertIntoRun(pieces, fresh, at, library = BUILT_IN_TRACK_PARTS, withinInches = 1) {
2557
+ let host = null;
2558
+ let bestD = Infinity;
2559
+ for (const piece of pieces) {
2560
+ const part = library.find((x) => x.id === piece.partId);
2561
+ if (part?.kind !== "flex") continue;
2562
+ for (const { points } of pieceRoutePaths(piece, library))
2563
+ for (let i = 1; i < points.length; i++) {
2564
+ const d = distanceToSegment(at, points[i - 1], points[i]);
2565
+ if (d < bestD) {
2566
+ bestD = d;
2567
+ host = piece;
2568
+ }
2569
+ }
2570
+ }
2571
+ if (!host || bestD > withinInches) return null;
2572
+ const L = host.lengthInches ?? 0;
2573
+ const R = host.radiusInches;
2574
+ const steps = 200;
2575
+ let s = 0;
2576
+ let closest = Infinity;
2577
+ for (let i = 0; i <= steps; i++) {
2578
+ const t = L * i / steps;
2579
+ const local = flexRunEnd(t, R);
2580
+ const world = placeLocal(host, local.x, local.y);
2581
+ const d = Math.hypot(world.x - at.x, world.y - at.y);
2582
+ if (d < closest) {
2583
+ closest = d;
2584
+ s = t;
2585
+ }
2586
+ }
2587
+ const cutLocal = flexRunEnd(s, R);
2588
+ const cut = placeLocal(host, cutLocal.x, cutLocal.y);
2589
+ const heading = norm360(host.rotationDeg + (host.flipped ? -cutLocal.headingDeg : cutLocal.headingDeg));
2590
+ const placed = { ...fresh, x: cut.x, y: cut.y, rotationDeg: heading };
2591
+ const js = placedJoints([placed], library);
2592
+ const entry = js.find((j) => j.joint === "throat" || j.joint === "a");
2593
+ const exit = js.find((j) => j.joint === "through" || j.joint === "b");
2594
+ if (!entry || !exit) return null;
2595
+ const body = Math.hypot(exit.x - entry.x, exit.y - entry.y);
2596
+ const rest = L - s - body;
2597
+ if (s < 0 || rest < 0) return null;
2598
+ const ids = new Set(pieces.map((p) => p.id));
2599
+ let n = 1;
2600
+ while (ids.has(`${host.id}b${n}`)) n += 1;
2601
+ const tail = {
2602
+ ...host,
2603
+ id: `${host.id}b${n}`,
2604
+ x: exit.x,
2605
+ y: exit.y,
2606
+ rotationDeg: exit.headingDeg,
2607
+ lengthInches: rest
2608
+ };
2609
+ const out = pieces.map((p) => p.id === host.id ? { ...p, lengthInches: s } : p);
2610
+ const kept = out.filter((p) => p.id !== host.id || s > 0);
2611
+ return {
2612
+ pieces: [...kept, placed, ...rest > 0 ? [tail] : []],
2613
+ hostId: host.id,
2614
+ insertedId: placed.id
2615
+ };
2616
+ }
2617
+ function placeLocal(piece, x, y) {
2618
+ const rad = piece.rotationDeg * Math.PI / 180;
2619
+ const ly = piece.flipped ? -y : y;
2620
+ return {
2621
+ x: piece.x + x * Math.cos(rad) - ly * Math.sin(rad),
2622
+ y: piece.y + x * Math.sin(rad) + ly * Math.cos(rad)
2623
+ };
2624
+ }
2625
+ function distanceToSegment(p, a, b) {
2626
+ const vx = b.x - a.x;
2627
+ const vy = b.y - a.y;
2628
+ const len2 = vx * vx + vy * vy;
2629
+ if (len2 === 0) return Math.hypot(p.x - a.x, p.y - a.y);
2630
+ const t = Math.max(0, Math.min(1, ((p.x - a.x) * vx + (p.y - a.y) * vy) / len2));
2631
+ return Math.hypot(p.x - (a.x + t * vx), p.y - (a.y + t * vy));
2632
+ }
2554
2633
  var danglingDivergeWarning = (id) => `the route diverging at ${id} is not connected to anything`;
2555
2634
  var unreachedWarning = (id) => `${id} is not reachable from the endplate \u2014 nothing connects it`;
2556
2635
  function walkTrackGraph(graph, pieces, startAt, library = BUILT_IN_TRACK_PARTS) {
@@ -2621,12 +2700,13 @@ function walkTrackGraph(graph, pieces, startAt, library = BUILT_IN_TRACK_PARTS)
2621
2700
  const through = byKey.get(`${here.piece}.through`) ?? byKey.get(`${here.piece}.legA`);
2622
2701
  const body = gap(throat, through);
2623
2702
  const lead = part.lead?.inches ?? body / 2;
2703
+ const frogAxial = part.frogOffset?.inches ?? (part.pointsOffset?.inches ?? 0) + lead;
2624
2704
  const dvj = byKey.get(`${here.piece}.diverge`) ?? byKey.get(`${here.piece}.legB`);
2625
2705
  const frogPt = throat && body > 0 && dvj ? {
2626
- x: throat.x + (dvj.x - throat.x) * lead / body,
2627
- y: throat.y + (dvj.y - throat.y) * lead / body
2706
+ x: throat.x + (dvj.x - throat.x) * frogAxial / body,
2707
+ y: throat.y + (dvj.y - throat.y) * frogAxial / body
2628
2708
  } : null;
2629
- const toFrog = here.joint === "throat" ? lead : here.joint === "diverge" || here.joint === "legB" ? frogPt && dvj ? Math.hypot(dvj.x - frogPt.x, dvj.y - frogPt.y) : Math.max(0, body - lead) : Math.max(0, body - lead);
2709
+ const toFrog = here.joint === "throat" ? frogAxial : here.joint === "diverge" || here.joint === "legB" ? frogPt && dvj ? Math.hypot(dvj.x - frogPt.x, dvj.y - frogPt.y) : Math.max(0, body - frogAxial) : Math.max(0, body - frogAxial);
2630
2710
  const frogPos = pos + toFrog;
2631
2711
  if (here.joint === "diverge" || here.joint === "legB") {
2632
2712
  route.endsAt = here.piece;
@@ -2641,8 +2721,8 @@ function walkTrackGraph(graph, pieces, startAt, library = BUILT_IN_TRACK_PARTS)
2641
2721
  if (!d || queued.has(dk)) continue;
2642
2722
  queued.add(dk);
2643
2723
  const fp = throat && body > 0 ? {
2644
- x: throat.x + (d.x - throat.x) * lead / body,
2645
- y: throat.y + (d.y - throat.y) * lead / body
2724
+ x: throat.x + (d.x - throat.x) * frogAxial / body,
2725
+ y: throat.y + (d.y - throat.y) * frogAxial / body
2646
2726
  } : null;
2647
2727
  pending.push({
2648
2728
  from: here.piece,
@@ -2928,6 +3008,323 @@ function deriveGraphDoc(doc, library = BUILT_IN_TRACK_PARTS) {
2928
3008
  });
2929
3009
  return { doc: out.doc, warnings: out.warnings };
2930
3010
  }
3011
+ function placeableTurnoutParts(library, kind) {
3012
+ return library.filter((p) => kind.includes(p.kind) && partGeometryGap(p) == null);
3013
+ }
3014
+ function moduleConversionReport(doc, library = BUILT_IN_TRACK_PARTS) {
3015
+ if (doc.graph?.pieces?.length) {
3016
+ return {
3017
+ alreadyGraph: true,
3018
+ offerable: false,
3019
+ readyWithoutAsking: false,
3020
+ turnouts: [],
3021
+ unanswered: [],
3022
+ orphanTracks: [],
3023
+ blockers: []
3024
+ };
3025
+ }
3026
+ const straight = placeableTurnoutParts(library, ["turnout"]);
3027
+ const curved = placeableTurnoutParts(library, ["curved-turnout"]);
3028
+ const blockers = [];
3029
+ const turnouts = (doc.turnouts ?? []).map((t) => {
3030
+ const wantCurved = t.curved === true;
3031
+ const pool = wantCurved ? curved : straight;
3032
+ const base = {
3033
+ id: t.id,
3034
+ name: t.name,
3035
+ pos: t.pos,
3036
+ size: t.size,
3037
+ statedPartId: t.partId
3038
+ };
3039
+ const exact = t.size == null ? [] : pool.filter((p) => p.frogNumber === t.size);
3040
+ const candidates = [...exact, ...pool.filter((p) => !exact.includes(p))].map((p) => p.id);
3041
+ const resolve = (part, from) => ({
3042
+ ...base,
3043
+ partId: part.id,
3044
+ from,
3045
+ source: partGeometry(part, library)?.source ?? null,
3046
+ why: null,
3047
+ candidates
3048
+ });
3049
+ if (t.partId) {
3050
+ const named = library.find((p) => p.id === t.partId);
3051
+ if (named && partGeometryGap(named) == null) return resolve(named, "named");
3052
+ return {
3053
+ ...base,
3054
+ partId: null,
3055
+ from: "unresolved",
3056
+ source: null,
3057
+ why: named ? `this turnout names ${named.id}, which cannot be placed yet \u2014 ${partGeometryGap(named)}` : `this turnout names a part the library does not have (${t.partId})`,
3058
+ candidates
3059
+ };
3060
+ }
3061
+ if (t.size != null && exact.length) return resolve(exact[0], "frog-number");
3062
+ return {
3063
+ ...base,
3064
+ partId: null,
3065
+ from: "unresolved",
3066
+ source: null,
3067
+ why: t.size == null ? "the document never says what this turnout is \u2014 no part, no frog number" : wantCurved ? `no curved turnout is placeable yet, so a curved #${t.size} cannot be converted` : `no measured #${t.size} in the parts library yet`,
3068
+ candidates
3069
+ };
3070
+ });
3071
+ for (const c of doc.crossings ?? [])
3072
+ blockers.push({
3073
+ kind: "crossing",
3074
+ ref: c.id,
3075
+ why: "crossing geometry is not modelled yet, so a diamond has no piece to become"
3076
+ });
3077
+ if (doc.loop)
3078
+ blockers.push({
3079
+ kind: "loop",
3080
+ why: "a balloon's curve radii were never recorded, and laying the loop would mean inventing them \u2014 the one thing ADR 0001 forbids"
3081
+ });
3082
+ const reached = new Set((doc.turnouts ?? []).map((t) => t.divergeTrack));
3083
+ const orphanTracks = (doc.tracks ?? []).filter((t) => t.role !== "main" && !reached.has(t.id)).map((t) => ({
3084
+ id: t.id,
3085
+ ...t.trackName ? { trackName: t.trackName } : {},
3086
+ role: t.role,
3087
+ why: "no turnout in the document diverges onto this track, so there is nothing to join it to"
3088
+ }));
3089
+ const unanswered = turnouts.filter((t) => !t.partId).map((t) => t.id);
3090
+ return {
3091
+ alreadyGraph: false,
3092
+ offerable: blockers.length === 0,
3093
+ readyWithoutAsking: blockers.length === 0 && unanswered.length === 0 && orphanTracks.length === 0,
3094
+ turnouts,
3095
+ unanswered,
3096
+ orphanTracks,
3097
+ blockers
3098
+ };
3099
+ }
3100
+ var CONVERSION_TIGHT_RADIUS_INCHES = 12;
3101
+ function docToGraph(doc, answers = {}, library = BUILT_IN_TRACK_PARTS) {
3102
+ const refuse = (why) => ({
3103
+ graph: null,
3104
+ refused: why,
3105
+ notLaid: [],
3106
+ warnings: []
3107
+ });
3108
+ const report = moduleConversionReport(doc, library);
3109
+ if (report.alreadyGraph) return refuse("this module is already authored as pieces");
3110
+ if (!report.offerable) return refuse(report.blockers.map((b) => b.why).join("; "));
3111
+ if ((doc.mainPath?.length ?? 0) > 2)
3112
+ return refuse(
3113
+ "this module's mainline is drawn with bends, and laying it as pieces would need each bend's radius \u2014 convert it once curved runs are supported"
3114
+ );
3115
+ const partById = new Map(library.map((p) => [p.id, p]));
3116
+ const chosen = /* @__PURE__ */ new Map();
3117
+ const unknown = [];
3118
+ for (const t of report.turnouts) {
3119
+ const id = answers.overrides?.[t.id] ?? (t.partId ? t.partId : answers.turnoutPartId) ?? null;
3120
+ const part = id ? partById.get(id) : void 0;
3121
+ if (!part || partGeometryGap(part)) unknown.push(t.id);
3122
+ else chosen.set(t.id, part);
3123
+ }
3124
+ if (unknown.length)
3125
+ return refuse(
3126
+ `${unknown.length} turnout${unknown.length === 1 ? "" : "s"} still need identifying: ${unknown.join(", ")}`
3127
+ );
3128
+ const flexId = DEFAULT_FLEX_PART_ID;
3129
+ if (!partById.get(flexId)) return refuse("the parts library has no flex track to lay plain track with");
3130
+ const maxPiece = maxFlexPieceInches(flexId, library);
3131
+ const tracks = doc.tracks ?? [];
3132
+ const trackById = new Map(tracks.map((t) => [t.id, t]));
3133
+ const turnouts = doc.turnouts ?? [];
3134
+ const mainLen = doc.lengthInches ?? Math.max(0, ...tracks.map((t) => t.toPos ?? 0), ...turnouts.map((t) => t.pos));
3135
+ if (!(mainLen > 0)) return refuse("this module has no length to lay track along");
3136
+ const pieces = [];
3137
+ const notLaid = [];
3138
+ const warnings = [];
3139
+ const rad = (d) => d * Math.PI / 180;
3140
+ const norm180 = (d) => ((d + 180) % 360 + 360) % 360 - 180;
3141
+ const r3 = (n) => Math.round(n * 1e3) / 1e3;
3142
+ const jointsOf = (p) => placedJoints([p], library);
3143
+ const jointAt = (p, id) => jointsOf(p).find((j) => j.joint === id) ?? null;
3144
+ const transition = (id, from, toY, dirSign = 1) => {
3145
+ const theta = rad(norm180(from.headingDeg - (dirSign > 0 ? 0 : 180)));
3146
+ const dy = (toY - from.y) * dirSign;
3147
+ if (Math.abs(theta) < 1e-9 || Math.abs(dy) < 1e-9) return null;
3148
+ const R = dy / (1 - Math.cos(theta));
3149
+ if (!Number.isFinite(R) || R === 0) return null;
3150
+ const mag = Math.abs(R);
3151
+ if (mag < CONVERSION_TIGHT_RADIUS_INCHES)
3152
+ warnings.push(
3153
+ `the curve bringing ${id} back parallel works out at ${mag.toFixed(1)}\u2033 radius \u2014 tighter than anyone lays by hand, which usually means the document's lane and its turnout disagree`
3154
+ );
3155
+ return {
3156
+ id,
3157
+ partId: flexId,
3158
+ x: from.x,
3159
+ y: from.y,
3160
+ rotationDeg: from.headingDeg,
3161
+ // Curving BACK toward the host: opposite the way we are already heading.
3162
+ // `radiusInches` is signed and the sign IS the side.
3163
+ radiusInches: r3(-Math.sign(theta) * mag),
3164
+ lengthInches: r3(mag * Math.abs(theta))
3165
+ };
3166
+ };
3167
+ const layTurnout = (t, hostY) => {
3168
+ const part = chosen.get(t.id);
3169
+ const geom = partGeometry(part, library);
3170
+ const branch = trackById.get(t.divergeTrack);
3171
+ const ends = [branch?.fromPos, branch?.toPos].filter(
3172
+ (n) => typeof n === "number" && Number.isFinite(n)
3173
+ );
3174
+ const divergeFarPos = ends.length ? ends.reduce((a, b) => Math.abs(b - t.pos) > Math.abs(a - t.pos) ? b : a) : void 0;
3175
+ const facing = turnoutFacing({
3176
+ pos: t.pos,
3177
+ divergeFarPos,
3178
+ flipped: t.flipped ?? false
3179
+ });
3180
+ const body = part.overallLength.inches;
3181
+ const lead = part.lead?.inches ?? body / 2;
3182
+ const frogAxial = part.frogOffset?.inches ?? (part.pointsOffset?.inches ?? 0) + lead;
3183
+ const throatPos = facing > 0 ? t.pos - frogAxial : t.pos + frogAxial;
3184
+ const hostLane = trackById.get(t.onTrack)?.lane ?? 0;
3185
+ const want = Math.sign((branch?.lane ?? hostLane) - hostLane) || 1;
3186
+ const unflipped = facing > 0 ? 1 : -1;
3187
+ const piece = {
3188
+ id: `t-${t.id}`,
3189
+ partId: part.id,
3190
+ x: throatPos,
3191
+ y: hostY,
3192
+ rotationDeg: facing > 0 ? 0 : 180,
3193
+ ...unflipped !== want ? { flipped: true } : {},
3194
+ ...t.name ? { name: t.name } : {}
3195
+ };
3196
+ const bodyEnds = [throatPos, facing > 0 ? throatPos + body : throatPos - body];
3197
+ const span = { fromPos: Math.min(...bodyEnds), toPos: Math.max(...bodyEnds) };
3198
+ const divergeId = geom.joints.find((j) => j.role === "diverge")?.id ?? "diverge";
3199
+ return { t, piece, span, divergeId };
3200
+ };
3201
+ const layFlex = (label, hostY, fromPos, toPos, occupied, cuts) => {
3202
+ const out = flexPieces({ fromPos, toPos, maxPieceInches: maxPiece, occupied, cuts: cuts ?? null });
3203
+ out.forEach(
3204
+ (f, i) => pieces.push({
3205
+ id: `f-${label}-${i}`,
3206
+ partId: flexId,
3207
+ x: f.fromPos,
3208
+ y: hostY,
3209
+ rotationDeg: 0,
3210
+ lengthInches: r3(f.lengthInches)
3211
+ })
3212
+ );
3213
+ return out;
3214
+ };
3215
+ const turnoutsOn = (trackId, hostY) => turnouts.filter((t) => t.onTrack === trackId && chosen.has(t.id)).sort((a, b) => a.pos - b.pos).map((t) => layTurnout(t, hostY));
3216
+ const main = trackById.get(MAIN_TRACK_ID) ?? tracks.find((t) => t.role === "main");
3217
+ if (!main) return refuse("this module's document has no mainline to convert");
3218
+ const mains = [main, ...tracks.filter((t) => t.role === "main" && t.id !== main.id)];
3219
+ const laidTurnouts = /* @__PURE__ */ new Map();
3220
+ const done = /* @__PURE__ */ new Set();
3221
+ for (const m of mains) {
3222
+ const y = laneOffsetAt(m.lane ?? 0, 0);
3223
+ const on = turnoutsOn(m.id, y);
3224
+ for (const l of on) {
3225
+ pieces.push(l.piece);
3226
+ laidTurnouts.set(l.t.id, l);
3227
+ }
3228
+ layFlex(m.id, y, m.fromPos ?? 0, m.toPos ?? mainLen, on.map((l) => l.span), m.flexCuts);
3229
+ done.add(m.id);
3230
+ }
3231
+ let progressed = true;
3232
+ while (progressed) {
3233
+ progressed = false;
3234
+ for (const t of turnouts) {
3235
+ if (!done.has(t.onTrack)) continue;
3236
+ const branch = trackById.get(t.divergeTrack);
3237
+ if (!branch || done.has(branch.id)) continue;
3238
+ const near = laidTurnouts.get(t.id);
3239
+ if (!near) continue;
3240
+ done.add(branch.id);
3241
+ progressed = true;
3242
+ const dj = jointAt(near.piece, near.divergeId);
3243
+ if (!dj) {
3244
+ notLaid.push({ id: branch.id, why: `turnout ${t.id} has no diverging end to leave from` });
3245
+ continue;
3246
+ }
3247
+ const branchY = laneOffsetAt(branch.lane ?? 0, 0);
3248
+ const curve = transition(branch.id, { x: dj.x, y: dj.y, headingDeg: dj.headingDeg }, branchY);
3249
+ let start = { x: dj.x, y: dj.y, headingDeg: dj.headingDeg };
3250
+ if (curve) {
3251
+ pieces.push(curve);
3252
+ const e = jointAt(curve, "b");
3253
+ if (e) start = { x: e.x, y: e.y, headingDeg: e.headingDeg };
3254
+ }
3255
+ const farSw = turnouts.find(
3256
+ (o) => o.id !== t.id && o.divergeTrack === branch.id && laidTurnouts.has(o.id)
3257
+ );
3258
+ const farJoint = farSw ? (() => {
3259
+ const f = laidTurnouts.get(farSw.id);
3260
+ return jointAt(f.piece, f.divergeId);
3261
+ })() : null;
3262
+ let endX = farJoint != null ? farJoint.x : Math.max(branch.fromPos ?? t.pos, branch.toPos ?? t.pos);
3263
+ let farCurve = null;
3264
+ if (farJoint) {
3265
+ farCurve = transition(
3266
+ `${branch.id}-far`,
3267
+ { x: farJoint.x, y: farJoint.y, headingDeg: farJoint.headingDeg },
3268
+ branchY,
3269
+ -1
3270
+ );
3271
+ if (farCurve) {
3272
+ pieces.push(farCurve);
3273
+ const e = jointAt(farCurve, "b");
3274
+ if (e) endX = e.x;
3275
+ }
3276
+ }
3277
+ if (endX - start.x <= 1e-6) {
3278
+ notLaid.push({
3279
+ id: branch.id,
3280
+ why: `the turnout and the curve bringing this track parallel already reach ${start.x.toFixed(1)}\u2033, past where it has to end at ${endX.toFixed(1)}\u2033 \u2014 with the turnout chosen there is no room for this track where the document places it`
3281
+ });
3282
+ continue;
3283
+ }
3284
+ const on = turnoutsOn(branch.id, branchY).filter((l) => {
3285
+ if (l.span.fromPos >= start.x - 1e-6) return true;
3286
+ notLaid.push({
3287
+ id: l.t.divergeTrack,
3288
+ why: `turnout ${l.t.id} sits at ${l.t.pos}\u2033 but this track has only reached ${start.x.toFixed(1)}\u2033 by then \u2014 the ladder is pitched tighter than the chosen turnout allows`
3289
+ });
3290
+ return false;
3291
+ });
3292
+ for (const l of on) {
3293
+ pieces.push(l.piece);
3294
+ laidTurnouts.set(l.t.id, l);
3295
+ }
3296
+ layFlex(branch.id, branchY, start.x, endX, on.map((l) => l.span), branch.flexCuts);
3297
+ }
3298
+ }
3299
+ const orphanWhy = new Map(report.orphanTracks.map((o) => [o.id, o.why]));
3300
+ const alreadySaid = new Set(notLaid.map((n) => n.id));
3301
+ for (const t of tracks) {
3302
+ if (t.role === "main" || done.has(t.id) || alreadySaid.has(t.id)) continue;
3303
+ notLaid.push({
3304
+ id: t.id,
3305
+ why: orphanWhy.get(t.id) ?? "the track it branches from could not be laid, so there is nothing to join it to"
3306
+ });
3307
+ }
3308
+ const startOf = (t) => {
3309
+ const y = laneOffsetAt(t.lane ?? 0, 0);
3310
+ let best = null;
3311
+ for (const p of pieces)
3312
+ for (const j of jointsOf(p)) {
3313
+ if (Math.abs(j.y - y) > 0.05) continue;
3314
+ if (!best || j.x < best.x) best = { piece: p.id, joint: j.joint, x: j.x };
3315
+ }
3316
+ return best ? { piece: best.piece, joint: best.joint } : null;
3317
+ };
3318
+ const startAt = startOf(main);
3319
+ if (!startAt) return refuse("nothing was laid on the mainline, so the module has no starting point");
3320
+ const second = mains[1] ? startOf(mains[1]) : null;
3321
+ return {
3322
+ graph: { pieces, startAt, ...second ? { start2: second } : {} },
3323
+ refused: null,
3324
+ notLaid,
3325
+ warnings
3326
+ };
3327
+ }
2931
3328
  function frogCasting(cl, opts = {}) {
2932
3329
  const g = opts.gaugeInches ?? RAIL_GAUGE_INCHES;
2933
3330
  const w = opts.reachInches ?? g * 1.5;
@@ -3561,6 +3958,6 @@ function poseOverridesFromDoc(doc) {
3561
3958
  return out;
3562
3959
  }
3563
3960
 
3564
- export { ATLAS_CODE55_N, BUILT_IN_TRACK_PARTS, BUMPER_DRAWN_INCHES, CLEARANCE_SPACING_INCHES, CODE55_RAIL_HEIGHT_INCHES, DEFAULT_FLEX_PART_ID, ENDPLATE_FASCIA_CLEAR_INCHES, ENDPLATE_LEAD_INCHES, FAST_TRACKS_N_ME55, FAST_TRACKS_N_ME55_CROSSOVERS, FLEX_TRACK_PARTS, FREEMO_ENDPLATE_TRACK_FASCIA_CLEARANCE_INCHES, FREEMO_ENDPLATE_WIDTH_MIN_INCHES, FREEMO_ENDPLATE_WIDTH_RECOMMENDED_INCHES, FREEMO_MAIN_MIN_RADIUS_INCHES, FREEMO_REVERSE_CURVE_STRAIGHT_INCHES, FREEMO_TRACK_SPACING_INCHES, GENERIC_END_OF_TRACK, JOINT_SNAP_INCHES, MAIN2_TRACK_ID, MAIN_TRACK_ID, N_CAR_LENGTH_INCHES, N_SCALE_RATIO, PINCH_EASE_INCHES, RAIL_GAUGE_INCHES, TIE_HALF_LENGTH_INCHES, TRACK_PART_KINDS, TURNOUT_LEAD_INCHES_PER_FROG, WHOLE_MODULE_SECTION_ID, asModuleSchematic, assessSectionEnd, assessSectionJoint, benchworkBand, benchworkOutline, buildCrossover, buildPassingSiding, buildTrackGraph, buildTransition, carCapacity, checkEndplateWidth, clearancePointPastFrogInches, crossoverPinches, deriveEndplatePoses, deriveGraphDoc, divergeSideForHand, docToState, emptyEditorState, endplateCentreOffsetInches, endplateEdgePose, endplateFaceSegments, endplateLead, endplateTrackOffsetInches, endplateWidthInches, fitFlexBetween, flexPartFor, flexParts, flexPieces, flexRunEnd, flexUsage, frogCasting, frogNumberFromName, fromSectionRelative, geometryTurnDegrees, graphToDoc, hasNoFarEndplate, importedPartToTrackPart, inchesToScaleFeet, isLoopDoc, isTransitionTurnout, laneOffsetAt, leadInchesForSize, maxFlexPieceInches, mergeImportedParts, mergeStoredParts, moduleCenterline, moduleFeatures, moduleFootprint, moduleLengthFromSections, moduleSections, nextId, parseXtpLibrary, partExtent, partExtentForSize, partGeometry, partGeometryGap, partOutlineAtFrog, partsPlaceable, pastFrogInchesForSize, pathLengthInches, pieceHand, piecePartNumber, pieceRoutePaths, placedJoints, poseNeedsManual, poseOverridesFromDoc, remapPos, resizeFlexPiece, resolveGraphAnchor, returnLoop, sampleBenchworkOutline, samplePartSegments, samplePath, scaleFeetToInches, sectionAdjacency, sectionBand, sectionBreaksFromSections, sectionComponents, sectionFootprints, sectionNeighbours, sectionSpans, sectionSpansOrWhole, sectionalArcInches, sectionedCenterline, sectionedEndPose, sliceCenterline, snapPiece, spanOverhang, stateToDoc, storedPartToTrackPart, toSectionRelative, trackMeetsEndplateIssues, trackPart, trackPath, turnoutClosure, turnoutFacing, turnoutOccupiedSpan, turnoutPartForSize, usableCapacity, walkTrackGraph };
3961
+ export { ATLAS_CODE55_N, BUILT_IN_TRACK_PARTS, BUMPER_DRAWN_INCHES, CLEARANCE_SPACING_INCHES, CODE55_RAIL_HEIGHT_INCHES, DEFAULT_FLEX_PART_ID, ENDPLATE_FASCIA_CLEAR_INCHES, ENDPLATE_LEAD_INCHES, FAST_TRACKS_N_ME55, FAST_TRACKS_N_ME55_CROSSOVERS, FLEX_TRACK_PARTS, FREEMO_ENDPLATE_TRACK_FASCIA_CLEARANCE_INCHES, FREEMO_ENDPLATE_WIDTH_MIN_INCHES, FREEMO_ENDPLATE_WIDTH_RECOMMENDED_INCHES, FREEMO_MAIN_MIN_RADIUS_INCHES, FREEMO_REVERSE_CURVE_STRAIGHT_INCHES, FREEMO_TRACK_SPACING_INCHES, GENERIC_END_OF_TRACK, JOINT_SNAP_INCHES, MAIN2_TRACK_ID, MAIN_TRACK_ID, N_CAR_LENGTH_INCHES, N_SCALE_RATIO, PINCH_EASE_INCHES, RAIL_GAUGE_INCHES, TIE_HALF_LENGTH_INCHES, TRACK_PART_KINDS, TURNOUT_LEAD_INCHES_PER_FROG, WHOLE_MODULE_SECTION_ID, asModuleSchematic, assessSectionEnd, assessSectionJoint, benchworkBand, benchworkOutline, buildCrossover, buildPassingSiding, buildTrackGraph, buildTransition, carCapacity, checkEndplateWidth, clearancePointPastFrogInches, crossoverPinches, deriveEndplatePoses, deriveGraphDoc, divergeSideForHand, docToGraph, docToState, emptyEditorState, endplateCentreOffsetInches, endplateEdgePose, endplateFaceSegments, endplateLead, endplateTrackOffsetInches, endplateWidthInches, fitFlexBetween, flexPartFor, flexParts, flexPieces, flexRunEnd, flexUsage, frogCasting, frogNumberFromName, fromSectionRelative, geometryTurnDegrees, graphToDoc, hasNoFarEndplate, importedPartToTrackPart, inchesToScaleFeet, insertIntoRun, isLoopDoc, isTransitionTurnout, laneOffsetAt, leadInchesForSize, maxFlexPieceInches, mergeImportedParts, mergeStoredParts, moduleCenterline, moduleConversionReport, moduleFeatures, moduleFootprint, moduleLengthFromSections, moduleSections, nextId, parseXtpLibrary, partExtent, partExtentForSize, partGeometry, partGeometryGap, partOutlineAtFrog, partsPlaceable, pastFrogInchesForSize, pathLengthInches, pieceHand, piecePartNumber, pieceRoutePaths, placedJoints, poseNeedsManual, poseOverridesFromDoc, remapPos, resizeFlexPiece, resolveGraphAnchor, returnLoop, sampleBenchworkOutline, samplePartSegments, samplePath, scaleFeetToInches, sectionAdjacency, sectionBand, sectionBreaksFromSections, sectionComponents, sectionFootprints, sectionNeighbours, sectionSpans, sectionSpansOrWhole, sectionalArcInches, sectionedCenterline, sectionedEndPose, sliceCenterline, snapPiece, spanOverhang, stateToDoc, storedPartToTrackPart, toSectionRelative, trackMeetsEndplateIssues, trackPart, trackPath, turnoutClosure, turnoutFacing, turnoutOccupiedSpan, turnoutPartForSize, usableCapacity, walkTrackGraph };
3565
3962
  //# sourceMappingURL=index.js.map
3566
3963
  //# sourceMappingURL=index.js.map