Open History to see the last commit
1import { z } from "zod";
2import { BY_KEY, CATALOGUE, COLORS } from "./catalogue";
3import { CATALOGUE_VERSION, MAX_AI_PARTS } from "./types";
4import type { Blueprint } from "./blueprint";
5
6type Template = {
7 name: string;
8 size: number[];
9 note: string;
10 parts: {
11 id: string;
12 part: string;
13 at: number[];
14 colour?: string;
15 turn?: number;
16 }[];
17};
18export const ASSEMBLIES: Record<string, Template> = {
19 "four-wheel-chassis": {
20 name: "four-wheel-chassis",
21 size: [6, 9, 8],
22 note: "Complete fitted four-wheel chassis, axles along x at turn=0. A 4x4 studded body platform has min [1,7,2] and TOP y=8. Add body at y=8 within x=1..5,z=2..6. Tyres occupy x=0..1 and5..6, up to y=9. Place on the board; do not add another floor through this unit.",
23 parts: [
24 ...[0, 5].flatMap((z, i) => [
25 {
26 id: `wheelL${i}`,
27 part: "wheel",
28 at: [0, 0, z],
29 turn: 1,
30 colour: "graphite",
31 },
32 {
33 id: `wheelR${i}`,
34 part: "wheel",
35 at: [5, 0, z],
36 turn: 1,
37 colour: "graphite",
38 },
39 {
40 id: `axle${i}`,
41 part: "axle-6",
42 at: [0, 3, z + 1],
43 turn: 1,
44 colour: "sand",
45 },
46 {
47 id: `mountL${i}`,
48 part: "bearing",
49 at: [1, 3, z + 1],
50 turn: 1,
51 colour: "graphite",
52 },
53 {
54 id: `mountR${i}`,
55 part: "bearing",
56 at: [4, 3, z + 1],
57 turn: 1,
58 colour: "graphite",
59 },
60 {
61 id: `deck${i}`,
62 part: "plate-2x4",
63 at: [1, 6, z + 1],
64 turn: 1,
65 colour: "graphite",
66 },
67 ]),
68 { id: "bodyPlatform", part: "plate-4x4", at: [1, 7, 2] },
69 ],
70 },
71 "upright-cross": {
72 name: "upright-cross",
73 size: [7, 29, 1],
74 note: "Static vertical brick cross for windmill blades or a sign. Faces z at turn=0. 7 studs wide,29 plates high. A brown grounded mast supports four pale arms; place in front of a tower without overlapping it. The pole starts at [3,0,0]; a base underneath must reach that point. Not a spinning propeller.",
75 parts: [
76 ...Array.from({ length: 2 }, (_, i) => ({
77 id: `mast${i}`,
78 part: "round",
79 at: [3, i * 3, 0],
80 colour: "tangerine",
81 })),
82 ...Array.from({ length: 3 }, (_, i) => ({
83 id: `lower${i}`,
84 part: "brick-1x1",
85 at: [3, 6 + i * 3, 0],
86 })),
87 { id: "left", part: "plate-1x4", at: [0, 15, 0], turn: 1 },
88 { id: "right", part: "plate-1x4", at: [3, 16, 0], turn: 1 },
89 ...Array.from({ length: 4 }, (_, i) => ({
90 id: `upper${i}`,
91 part: "brick-1x1",
92 at: [3, 17 + i * 3, 0],
93 })),
94 ],
95 },
96 "gable-roof": {
97 name: "gable-roof",
98 size: [4, 4, 4],
99 note: "A plate and four slopes forming a proper pitched roof, ridge along x at turn=0. Place on wall tops. Repeat step=[4,0,0] for a wider roof. Chimneys belong outside its footprint; use individual pieces for a roof with a chimney gap.",
100 parts: [
101 { id: "base", part: "plate-4x4", at: [0, 0, 0] },
102 { id: "back1", part: "slope-2x2", at: [0, 1, 0], turn: 2 },
103 { id: "back2", part: "slope-2x2", at: [2, 1, 0], turn: 2 },
104 { id: "front1", part: "slope-2x2", at: [0, 1, 2] },
105 { id: "front2", part: "slope-2x2", at: [2, 1, 2] },
106 ],
107 },
108 "pine-tree": {
109 name: "pine-tree",
110 size: [4, 14, 4],
111 note: "A tapered evergreen: brown trunk and green layered branches, 4x4 footprint and 14 plates tall. Place on the ground or a base. Foliage uses the requested colour; trunk is tangerine.",
112 parts: [
113 { id: "trunk", part: "round", at: [1, 0, 1], colour: "tangerine" },
114 { id: "trunk2", part: "round", at: [1, 3, 1], colour: "tangerine" },
115 { id: "boughs", part: "plate-4x4", at: [0, 6, 0] },
116 { id: "core", part: "brick-2x2", at: [1, 7, 1] },
117 { id: "left", part: "slope-1x2", at: [0, 7, 1] },
118 { id: "right", part: "slope-1x2", at: [3, 7, 1], turn: 2 },
119 { id: "back", part: "slope-1x2", at: [1, 7, 0], turn: 1 },
120 { id: "front", part: "slope-1x2", at: [1, 7, 3], turn: 3 },
121 { id: "crown", part: "plate-2x2", at: [1, 10, 1] },
122 { id: "tip", part: "slope-1x2", at: [1, 11, 1] },
123 ],
124 },
125 "wheel-axle": {
126 name: "wheel-axle",
127 size: [3, 9, 6],
128 note: "Two tyres on a 6-stud axle, with two bearings. turn=0 axle runs along z; turn=1 along x. At turn=0, bearings occupy x=1..2,z=1..2 and 4..5, top y=6. A deck can rest on them at y=6, within z=1..5. Wheels occupy z=0..1 and 5..6 and rise to y=9; keep the body out of those planes.",
129 parts: [
130 { id: "front", part: "wheel", at: [0, 0, 0], colour: "graphite" },
131 { id: "rear", part: "wheel", at: [0, 0, 5], colour: "graphite" },
132 { id: "shaft", part: "axle-6", at: [1, 3, 0], colour: "sand" },
133 { id: "mount1", part: "bearing", at: [1, 3, 1] },
134 { id: "mount2", part: "bearing", at: [1, 3, 4] },
135 ],
136 },
137 "gear-pair": {
138 name: "gear-pair",
139 size: [14 / 3, 9, 1],
140 note: "A fitted 12/20-tooth pair; axes along z at turn=0. Large gear rests on the board when placed at y=0. Keep this unit separate or provide a supported mounting assembly; it has no top studs.",
141 parts: [
142 { id: "small", part: "gear-12", at: [0, 1.5, 0] },
143 { id: "large", part: "gear-20", at: [5 / 3, 0, 0] },
144 ],
145 },
146 "hinge-pair": {
147 name: "hinge-pair",
148 size: [2, 1, 4],
149 note: "Two fitted coplanar hinge leaves; sockets below and studs above. Static, not folded.",
150 parts: [
151 { id: "base", part: "hinge-a", at: [0, 0, 0] },
152 { id: "leaf", part: "hinge-b", at: [0, 0, 2] },
153 ],
154 },
155};
156const vector = z.array(z.number()).length(3);
157export const designRowSchema = z.object({
158 id: z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,23}$/),
159 part: z.enum([...CATALOGUE.map((p) => p.key), ...Object.keys(ASSEMBLIES)] as [
160 string,
161 ...string[],
162 ]),
163 colour: z.enum(
164 COLORS.map((c) => c.name.toLowerCase()) as [string, ...string[]],
165 ),
166 turn: z.number().int().min(0).max(3),
167 at: vector,
168 repeat: z
169 .object({ count: z.number().int().min(2).max(32), step: vector })
170 .nullable(),
171});
172export const designSchema = z.object({
173 version: z.literal(2),
174 title: z.string().min(1).max(64),
175 summary: z.string().max(240),
176 front: z.enum(["+z", "-z", "+x", "-x"]).optional(),
177 pieces: z.array(designRowSchema).min(1).max(100),
178});
179// Required for new inference; optional above for previously saved v2 drafts.
180export const designGenerationSchema = designSchema.extend({
181 front: z.enum(["+z", "-z", "+x", "-x"]),
182});
183export const presentationTurn = (front?: Design["front"]) =>
184 ({ "+z": 0, "+x": 1, "-z": 2, "-x": 3 })[front || "+z"];
185export type Design = z.infer<typeof designSchema>;
186export class DesignError extends Error {}
187export const designPatchSchema = z.object({
188 title: z.string().min(1).max(64).nullable(),
189 summary: z.string().max(240).nullable(),
190 changes: z
191 .array(
192 z.object({ id: z.string().max(24), row: designRowSchema.nullable() }),
193 )
194 .min(1)
195 .max(40),
196});
197export function applyDesignPatch(previous: Design, input: unknown): Design {
198 const patch = designPatchSchema.parse(input);
199 const rows = new Map(previous.pieces.map((p) => [p.id, p]));
200 const changed = new Set<string>();
201 for (const change of patch.changes) {
202 if (changed.has(change.id))
203 throw new DesignError(`Row ${change.id} patched twice.`);
204 changed.add(change.id);
205 if (change.row) {
206 if (change.row.id !== change.id)
207 throw new DesignError("Patch row id must match change id.");
208 rows.set(change.id, change.row);
209 } else if (!rows.delete(change.id))
210 throw new DesignError(`Unknown row ${change.id}.`);
211 }
212 return designSchema.parse({
213 ...previous,
214 title: patch.title || previous.title,
215 summary: patch.summary ?? previous.summary,
216 pieces: [...rows.values()],
217 });
218}
219
220export function expandDesign(input: unknown): Blueprint {
221 const design = designSchema.parse(input);
222 const parts: Blueprint["parts"] = [];
223 const ids = new Set<string>();
224 for (const spec of design.pieces) {
225 if (ids.has(spec.id)) throw new DesignError(`Duplicate row id: ${spec.id}`);
226 ids.add(spec.id);
227 const assembly = ASSEMBLIES[spec.part];
228 const count = spec.repeat?.count || 1;
229 const templates = assembly?.parts || [
230 { id: "", part: spec.part, at: [0, 0, 0] },
231 ];
232 if (parts.length + count * templates.length > MAX_AI_PARTS)
233 throw new DesignError(
234 `Expanded design exceeds ${MAX_AI_PARTS} pieces. Reduce repeat counts.`,
235 );
236 for (let i = 0; i < count; i++) {
237 const origin = spec.at.map(
238 (v, axis) => v + i * (spec.repeat?.step[axis] || 0),
239 );
240 for (const template of templates) {
241 let [x, y, z] = template.at;
242 if (assembly) {
243 const d = BY_KEY[template.part];
244 const w = template.turn && template.turn % 2 ? d.d : d.w;
245 const depth = template.turn && template.turn % 2 ? d.w : d.d;
246 if (spec.turn === 1) [x, z] = [assembly.size[2] - z - depth, x];
247 else if (spec.turn === 2)
248 [x, z] = [assembly.size[0] - x - w, assembly.size[2] - z - depth];
249 else if (spec.turn === 3) [x, z] = [z, assembly.size[0] - x - w];
250 }
251 const id = `${spec.id}${spec.repeat ? `_${i}` : ""}${assembly ? `_${template.id}` : ""}`;
252 parts.push({
253 id,
254 part: template.part,
255 colour: template.colour || spec.colour,
256 turn: (spec.turn + (template.turn || 0)) % 4,
257 at: [origin[0] + x, origin[1] + y, origin[2] + z],
258 attach: null,
259 });
260 }
261 }
262 }
263 if (new Set(parts.map((p) => p.id)).size !== parts.length)
264 throw new DesignError(
265 "Expanded piece IDs collide. Give rows distinct names.",
266 );
267 // Present the declared front toward +z, matching the editor's default camera.
268 const turn = presentationTurn(design.front);
269 if (turn)
270 for (const p of parts) {
271 const d = BY_KEY[p.part];
272 const w = p.turn % 2 ? d.d : d.w;
273 const depth = p.turn % 2 ? d.w : d.d;
274 const [x, y, z] = p.at!;
275 p.at =
276 turn === 1
277 ? [-z - depth, y, x]
278 : turn === 2
279 ? [-x - w, y, -z - depth]
280 : [z, y, -x - w];
281 p.turn = (p.turn + turn) % 4;
282 }
283 return {
284 version: 1,
285 catalogue: CATALOGUE_VERSION,
286 title: design.title,
287 summary: design.summary,
288 parts,
289 };
290}
291
292export function designCatalogue() {
293 return CATALOGUE.map((d) => ({
294 part: d.key,
295 size: [d.w, d.h, d.d],
296 studs: d.studs,
297 sockets: [
298 "brick",
299 "plate",
300 "tile",
301 "round",
302 "slope",
303 "wedge",
304 "arch",
305 "window",
306 "hinge",
307 ].includes(d.shape),
308 }));
309}