Open History to see the last commit
1import { compileBlueprint, type CompiledBlueprint } from "./blueprint";
2import { expandDesign, presentationTurn, type Design } from "./design";
3import { bounds, connectorList } from "./geometry";
4
5export type DesignAdjustment = { rows: string[]; shift: number[] };
6// Correct only small missed stud placements. Move an entire disconnected
7// component, preserving its shape, repeats and colours. Every candidate goes
8// through full validation; collisions and large design errors need inference.
9export function snapDesign(
10 initial: Design,
11 checked = compileBlueprint(initial),
12) {
13 let design = initial;
14 let compiled: CompiledBlueprint = checked;
15 const adjustments: DesignAdjustment[] = [];
16 let evaluations = 0;
17 while (compiled.issueCounts.unattached && evaluations < 36) {
18 const missing = new Set(
19 compiled.issues
20 .filter((i) => i.code === "unattached")
21 .flatMap((i) => i.parts),
22 );
23 const conflicts = compiled.issues.filter((i) => i.code !== "unattached");
24 const conflictedParts = new Set(conflicts.flatMap((i) => i.parts));
25 const existingConflicts = new Set(
26 conflicts.map((i) => `${i.code}:${[...i.parts].sort().join("/")}`),
27 );
28 const graph = new Map(compiled.parts.map((p) => [p.id, new Set<string>()]));
29 for (const edge of compiled.edges) {
30 graph.get(edge.a)!.add(edge.b);
31 graph.get(edge.b)!.add(edge.a);
32 }
33 const owner = new Map<string, string>();
34 const members = new Map<string, string[]>();
35 for (const row of design.pieces) {
36 const ids = expandDesign({ ...design, pieces: [row] }).parts.map(
37 (p) => p.id,
38 );
39 members.set(row.id, ids);
40 ids.forEach((id) => owner.set(id, row.id));
41 }
42 const roots = compiled.parts
43 .filter((p) => missing.has(p.id))
44 .sort((a, b) => bounds(a).miny - bounds(b).miny);
45 let improved = false;
46 const visited = new Set<string>();
47 for (const root of roots) {
48 if (visited.has(root.id)) continue;
49 const group = new Set([root.id]);
50 const queue = [root.id];
51 for (let i = 0; i < queue.length; i++)
52 for (const id of graph.get(queue[i])!)
53 if (!group.has(id)) {
54 group.add(id);
55 queue.push(id);
56 }
57 group.forEach((id) => visited.add(id));
58 if ([...group].some((id) => !missing.has(id) || conflictedParts.has(id)))
59 continue;
60 const rows = new Set([...group].map((id) => owner.get(id)!));
61 if ([...rows].some((id) => members.get(id)!.some((p) => !group.has(p))))
62 continue;
63 const sockets = connectorList(root).filter((c) => c.type === "socket");
64 const offsets = new Map<string, number[]>();
65 // Scenery one plate above bare ground has no nearby stud to catch.
66 // Drop only the whole unsupported component, within the same small bound.
67 const bottom = Math.min(
68 ...compiled.parts
69 .filter((p) => group.has(p.id))
70 .map((p) => bounds(p).miny),
71 );
72 if (bottom > 0 && bottom <= 2)
73 offsets.set(`0,${-bottom},0`, [0, -bottom, 0]);
74 for (const target of compiled.parts) {
75 if (group.has(target.id) || missing.has(target.id)) continue;
76 for (const stud of connectorList(target).filter(
77 (c) => c.type === "stud",
78 ))
79 for (const socket of sockets) {
80 const d = [
81 stud.at.x - socket.at.x,
82 stud.at.y - socket.at.y,
83 stud.at.z - socket.at.z,
84 ];
85 if (
86 Math.hypot(d[0], d[2]) > 6 ||
87 Math.abs(d[1]) > 2 ||
88 d.every((v) => v === 0)
89 )
90 continue;
91 offsets.set(d.join(","), d);
92 }
93 }
94 const candidates = [...offsets.values()]
95 .sort(
96 (a, b) =>
97 a.reduce((s, v) => s + v * v, 0) - b.reduce((s, v) => s + v * v, 0),
98 )
99 .slice(0, 12);
100 for (const delta of candidates) {
101 if (++evaluations > 36) break;
102 const turn = presentationTurn(design.front);
103 const [x, y, z] = delta;
104 const local =
105 turn === 1
106 ? [z, y, -x]
107 : turn === 2
108 ? [-x, y, -z]
109 : turn === 3
110 ? [-z, y, x]
111 : delta;
112 const shift = [local[0] / 6, local[1] / 2, local[2] / 6].map(
113 (v) => v || 0,
114 );
115 const next = {
116 ...design,
117 pieces: design.pieces.map((row) =>
118 rows.has(row.id)
119 ? { ...row, at: row.at.map((v, i) => v + shift[i]) }
120 : row,
121 ),
122 };
123 const result = compileBlueprint(next);
124 if (
125 (result.issueCounts.unattached || 0) >=
126 compiled.issueCounts.unattached ||
127 Object.entries(result.issueCounts).some(
128 ([code, count]) =>
129 code !== "unattached" &&
130 count > (compiled.issueCounts[code] || 0),
131 ) ||
132 result.issues.some(
133 (i) =>
134 i.code !== "unattached" &&
135 !existingConflicts.has(
136 `${i.code}:${[...i.parts].sort().join("/")}`,
137 ),
138 )
139 )
140 continue;
141 design = next;
142 compiled = result;
143 adjustments.push({ rows: [...rows], shift });
144 improved = true;
145 break;
146 }
147 if (improved) break;
148 }
149 if (!improved) break;
150 }
151 return { design, compiled, adjustments };
152}