saltiresoftware commited on
Commit
c6218c1
·
verified ·
1 Parent(s): 16f1abb

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.js +207 -50
  2. index.html +17 -17
  3. system_prompt.txt +69 -85
app.js CHANGED
@@ -1,38 +1,70 @@
1
- const BUILD_ID = "20260922-triangles-2";
2
- const COREGX_PROXY_URL = window.TRIANGLE_STUDIO_CONFIG.coregxProxyUrl;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  const EXAMPLE_BANKS = {
4
- "sides": [
5
- "Draw a 3, 4, 5 triangle.",
6
- "Triangle ABC with AB=5, BC=6, AC=7.",
7
- "Draw triangle PQR with PQ=8, QR=10 and PR=12.",
8
- "A scalene triangle with sides 7, 9 and 11.",
9
- "Draw triangle ABC with AB=13, BC=14 and AC=15."
10
  ],
11
- "angles": [
12
- "Triangle ABC with AB=8, AC=6 and angle BAC=60 degrees.",
13
- "Draw triangle ABC with AB=10, angle BAC=40 degrees and angle ABC=65 degrees.",
14
- "Triangle PQR: PQ=7, PR=5, angle QPR=75 degrees.",
15
- "Triangle ABC with AB=6, angle BAC=30 degrees and angle ABC=90 degrees.",
16
- "Draw triangle ABC with AB=12, AC=9 and the included angle at A equal to 110 degrees."
17
  ],
18
- "special": [
19
- "An equilateral triangle with side length 6.",
20
- "An isosceles triangle with equal sides AB=7 and AC=7, and base BC=8.",
21
- "A right triangle ABC with right angle at B, AB=3 and BC=4.",
22
- "Draw an equilateral triangle PQR, side length 10.",
23
- "An isosceles right triangle ABC with the right angle at A and legs AB=5 and AC=5."
 
 
 
 
 
 
 
24
  ],
25
- "constructions": [
26
- "A 3, 4, 5 triangle with a median from A to BC.",
27
- "Triangle ABC with AB=5, BC=6 and AC=7. Draw all three medians.",
28
- "Triangle ABC with AB=6, AC=6 and BC=8. Draw the altitude from A to BC.",
29
- "Draw a triangle with sides AB=7, BC=8, AC=9 and the angle bisector at B.",
30
- "Triangle ABC has sides AB=5, BC=6, AC=7. Mark the midpoints of all sides and join them to form the medial triangle."
31
- ]
32
  };
33
- const exampleIndices = Object.fromEntries(Object.keys(EXAMPLE_BANKS).map(name => [name, 0]));
 
34
 
35
  const ui = {
 
36
  description: document.querySelector("#description"),
37
  build: document.querySelector("#build"),
38
  status: document.querySelector("#status"),
@@ -47,6 +79,7 @@ const ui = {
47
  let programUrl;
48
  let svgUrl;
49
  let cadUrl;
 
50
 
51
  function setStatus(message, isError = false) {
52
  ui.status.textContent = message;
@@ -66,6 +99,76 @@ function stripCodeFence(value) {
66
  return lines.join("\n").trim();
67
  }
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  function proxyEndpoint(path) {
70
  if (!/^https:\/\/.+/.test(COREGX_PROXY_URL)) {
71
  throw new Error("Add the Cloudflare Worker URL in config.js.");
@@ -84,22 +187,31 @@ async function proxyFetch(route, options) {
84
  }
85
  }
86
 
87
- async function generateProgram(description) {
88
- setStatus("Converting to CoreGX using " + window.TRIANGLE_STUDIO_CONFIG.modelName + "…");
89
- const promptResponse = await fetch("system_prompt.txt?v=" + BUILD_ID, { cache: "reload" });
90
- if (!promptResponse.ok) throw new Error("Could not load the triangle prompt.");
91
  const response = await proxyFetch("generate", {
92
  method: "POST",
93
  headers: { "Content-Type": "application/json" },
94
- body: JSON.stringify({ messages: [
95
- { role: "system", content: await promptResponse.text() },
96
- { role: "user", content: description },
97
- ] }),
 
 
 
 
 
98
  });
99
  const result = await response.json().catch(() => ({}));
100
- if (!response.ok || !result.ok) throw new Error(String(result.error || "Model request failed with HTTP " + response.status));
101
- if (typeof result.content !== "string" || !result.content.trim()) throw new Error("The model returned no program.");
102
- return "defaultproperties constraint visible=true\n\n" + stripCodeFence(result.content) + "\n";
 
 
 
 
 
103
  }
104
 
105
  async function renderCoreGX(program) {
@@ -121,9 +233,12 @@ async function requestCad(program) {
121
  headers: { "Content-Type": "application/json" },
122
  body: JSON.stringify({
123
  program,
 
124
  }),
125
  };
126
- const response = await proxyFetch("cad", options);
 
 
127
  const result = await response.json().catch(() => ({}));
128
  if (!response.ok || !result.ok) {
129
  throw new Error(String(result.error || `CAD export failed with HTTP ${response.status}.`));
@@ -144,7 +259,7 @@ async function exportCad() {
144
  cadUrl = URL.createObjectURL(new Blob([dxf], { type: "application/dxf;charset=utf-8" }));
145
  const link = document.createElement("a");
146
  link.href = cadUrl;
147
- link.download = "triangle.dxf";
148
  link.click();
149
  setStatus("✓ CAD exported");
150
  } catch (error) {
@@ -154,6 +269,22 @@ async function exportCad() {
154
  }
155
  }
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  function setDownloads(program, svg) {
158
  if (programUrl) URL.revokeObjectURL(programUrl);
159
  if (svgUrl) URL.revokeObjectURL(svgUrl);
@@ -168,24 +299,50 @@ function setDownloads(program, svg) {
168
  ui.downloadCad.disabled = false;
169
  }
170
 
171
- async function buildTriangle() {
 
 
 
 
 
 
 
 
 
 
172
  const description = ui.description.value.trim();
173
- if (!description) return setStatus("Describe a triangle first.", true);
 
 
 
174
  ui.build.disabled = true;
175
  ui.build.textContent = "Building…";
 
176
  try {
177
- const program = await generateProgram(description);
178
- setStatus("Drawing the triangle…");
 
 
 
 
 
 
 
 
 
 
 
 
179
  const svg = await renderCoreGX(program);
180
  showSvg(svg);
181
  ui.program.textContent = program;
182
  setDownloads(program, svg);
183
- setStatus("✓ Triangle built");
184
  } catch (error) {
185
- setStatus(error instanceof Error ? error.message : String(error), true);
186
  } finally {
187
  ui.build.disabled = false;
188
- ui.build.textContent = "Build triangle";
189
  }
190
  }
191
 
@@ -200,10 +357,10 @@ document.querySelectorAll("[data-example]").forEach((button) => {
200
  });
201
  });
202
 
203
- ui.build.addEventListener("click", buildTriangle);
204
  ui.downloadCad.addEventListener("click", exportCad);
205
  ui.description.addEventListener("keydown", (event) => {
206
- if ((event.ctrlKey || event.metaKey) && event.key === "Enter") buildTriangle();
207
  });
208
 
209
  window.addEventListener("beforeunload", () => {
 
1
+ const MOTION_LAW_NAMES = ["harmonic", "cycloid", "poly345", "poly4567"];
2
+
3
+ const LOCAL_MODE = window.CAM_STUDIO_LOCAL === true;
4
+ const COREGX_PROXY_URL = String(window.CAM_STUDIO_CONFIG?.coregxProxyUrl || "").trim();
5
+ const BUILD_ID = "20260922-14";
6
+
7
+ const TEMPLATES = {
8
+ recip_flat: {
9
+ file: "reciprocating_flat.coregx",
10
+ call: "@RFF(O,A,E,F,theta,...)"
11
+ },
12
+ recip_roller: {
13
+ file: "reciprocating_roller.coregx",
14
+ call: "@ReciprocatingRoller(O,A,B,theta,...)"
15
+ },
16
+ osc_flat: {
17
+ file: "oscillating_flat.coregx",
18
+ call: "@OFF(O,A,B,C,theta,...)"
19
+ },
20
+ osc_roller: {
21
+ file: "oscillating_roller.coregx",
22
+ call: "@OscillatingRoller(A,B,C,theta,...)"
23
+ },
24
+ };
25
+
26
+ const EXAMPLE_MOTION_LAWS = {
27
+ recip_flat: ["cycloid"],
28
+ recip_roller: ["harmonic", "cycloid", "poly345", "poly4567"],
29
+ osc_flat: ["cycloid"],
30
+ osc_roller: ["harmonic", "cycloid"],
31
+ };
32
+
33
  const EXAMPLE_BANKS = {
34
+ "recip-roller": [
35
+ "Reciprocating roller follower, base radius 20, roller radius 3, offset 2. Cycloidal rise from 0 to 5 over 20 degrees, dwell to 60 degrees, 3-4-5 polynomial rise from 5 to 12 over 30 degrees, dwell to 120 degrees, then 4-5-6-7 polynomial return from 12 to 0 over 40 degrees. Clockwise.",
36
+ "Reciprocating roller follower with a 5 mm harmonic rise over 90 degrees followed immediately by a 90 degree return.",
37
+ "Reciprocating roller follower with base radius 30, roller radius 4, offset 5, and outside contact. Harmonic rise from 0 to 8 mm over 90 degrees, dwell until 150 degrees, then harmonic return to zero over 90 degrees. Clockwise.",
38
+ "Reciprocating roller follower, base radius 24, roller radius 3, offset 4. Cycloidal rise to 7 mm over 60 degrees, dwell for 60 degrees, and cycloidal return over 80 degrees. Counterclockwise.",
39
+ "Reciprocating roller follower with a 28 mm base radius, 4 mm roller, 3 mm offset, and inside contact. Cycloidal rise from 0 to 6 mm over 45 degrees, dwell until 90 degrees, 3-4-5 rise from 6 to 10 mm over 60 degrees, dwell until 210 degrees, then harmonic return to zero over 90 degrees. Counterclockwise; 3 second animation.",
40
  ],
41
+ "recip-flat": [
42
+ "Reciprocating flat follower with a 40 mm base radius and 9 mm offset. Cycloidal 6 mm rise over 60 degrees followed immediately by cycloidal return over 60 degrees. Clockwise.",
43
+ "Reciprocating flat follower: 8 mm harmonic rise over 90 degrees, then return over 90 degrees.",
44
+ "Reciprocating flat follower with base radius 35 and offset 6. Cycloidal rise from 0 to 10 mm over 80 degrees, dwell until 140 degrees, then cycloidal return over 80 degrees. Counterclockwise.",
45
+ "Reciprocating flat follower, base radius 42, offset 7. Use a 3-4-5 polynomial rise to 9 mm over 70 degrees, dwell for 50 degrees, and a 3-4-5 return over 70 degrees. Clockwise.",
46
+ "Reciprocating flat follower with a 45 mm base radius and 8 mm offset. Use a 4-5-6-7 rise from 0 to 7 mm over 50 degrees, dwell until 100 degrees, cycloidal rise from 7 to 13 mm over 70 degrees, dwell until 220 degrees, then a 3-4-5 return to zero over 100 degrees. Clockwise; 4 second animation.",
47
  ],
48
+ "osc-roller": [
49
+ "Oscillating roller follower below the cam with outside contact. Start angle 50 degrees, roller radius 5, pivot distance 69, arm length 75. Cycloidal swing from 0 to 0.2 radians over 60 degrees followed immediately by cycloidal return over 60 degrees. Clockwise.",
50
+ "Oscillating roller follower below the cam: 0.2 radian harmonic swing over 60 degrees, then return over 60 degrees.",
51
+ "Oscillating roller follower above the cam with outside contact. Start angle 45 degrees, roller radius 4, pivot distance 65, arm length 72. Harmonic swing to 0.25 radians over 75 degrees, dwell until 150 degrees, then return over 75 degrees. Clockwise.",
52
+ "Oscillating roller follower below the cam with inside contact. Start angle 55 degrees, roller radius 5, pivot distance 72, arm length 80. Cycloidal swing to 0.18 radians over 80 degrees followed immediately by return over 80 degrees. Counterclockwise.",
53
+ "Oscillating roller follower above the cam with a 0.1 radian cycloidal swing over 90 degrees followed immediately by a 90 degree return.",
54
+ ],
55
+ "osc-flat": [
56
+ "Oscillating flat follower. Start angle 35 degrees, pivot distance 69, offset 5. Cycloidal swing of 0.15 radians over 90 degrees, then return over 90 degrees. Clockwise.",
57
+ "Oscillating flat follower with a 0.15 radian cycloidal swing over 90 degrees and immediate return over 90 degrees.",
58
+ "Oscillating flat follower with a 40 degree start angle, pivot distance 72, and offset 6. Cycloidal swing to 0.18 radians over 100 degrees followed immediately by return over 100 degrees. Counterclockwise.",
59
+ "Oscillating flat follower, start angle 30 degrees, pivot distance 64, offset 4. Harmonic swing to 0.2 radians over 60 degrees, dwell for 90 degrees, and harmonic return over 60 degrees. Clockwise.",
60
+ "Oscillating flat follower with a 38 degree start angle, pivot distance 75, and offset 6. Use a cycloidal swing from 0 to 0.1 radians over 45 degrees, dwell until 90 degrees, a 3-4-5 swing from 0.1 to 0.24 radians over 75 degrees, dwell until 220 degrees, then a 4-5-6-7 return to zero over 90 degrees. Counterclockwise; 3 second animation.",
61
  ],
 
 
 
 
 
 
 
62
  };
63
+
64
+ const exampleIndices = Object.fromEntries(Object.keys(EXAMPLE_BANKS).map((name) => [name, 0]));
65
 
66
  const ui = {
67
+ coregxKey: document.querySelector("#coregx-key"),
68
  description: document.querySelector("#description"),
69
  build: document.querySelector("#build"),
70
  status: document.querySelector("#status"),
 
79
  let programUrl;
80
  let svgUrl;
81
  let cadUrl;
82
+ if (LOCAL_MODE && ui.coregxKey) ui.coregxKey.value = "";
83
 
84
  function setStatus(message, isError = false) {
85
  ui.status.textContent = message;
 
99
  return lines.join("\n").trim();
100
  }
101
 
102
+ function canonicalizeOptionalDefaults(body, templateName, description) {
103
+ if (!templateName.endsWith("roller") || /\binside\b/i.test(description)) return body;
104
+ const lines = body.split(/\r?\n/);
105
+ lines[0] = lines[0].replace(/,\s*(?:side\s*=\s*)?(?:inside|outside)\s*\)\s*$/i, ")");
106
+ return lines.join("\n");
107
+ }
108
+
109
+ function escapeRegExp(value) {
110
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
111
+ }
112
+
113
+ function canonicalizeOscillatingPhaseOrigin(body, templateName, description) {
114
+ if (!templateName.startsWith("osc_")) return body;
115
+ if (/\bphase\s*(?:offset|shift)\b|\binitial\s+dwell\b|\b(?:motion|rise|swing|return)\s+(?:begins?|starts?)\s+(?:at|after)\b/i.test(description)) {
116
+ return body;
117
+ }
118
+
119
+ const lines = body.split(/\r?\n/);
120
+ const call = lines[0]?.match(/^@(OscillatingRoller|OFF)\((.*)\)\s*$/);
121
+ if (!call || !lines[1]) return body;
122
+ const args = call[2].split(",").map((value) => value.trim());
123
+ const startAngle = args[call[1] === "OscillatingRoller" ? 4 : 5];
124
+ if (!startAngle) return body;
125
+
126
+ const piecewiseStart = lines[1].indexOf("piecewise({");
127
+ const firstSegmentEnd = lines[1].indexOf("},", piecewiseStart);
128
+ if (piecewiseStart < 0 || firstSegmentEnd < 0) return body;
129
+ const firstSegment = lines[1].slice(piecewiseStart, firstSegmentEnd);
130
+ const shiftedByStartAngle = new RegExp(
131
+ `(phase\\(theta\\s*[+-]\\s*phi\\)\\s*-\\s*)${escapeRegExp(startAngle)}(?=\\s*[,\\)])`,
132
+ "i",
133
+ );
134
+ const correctedSegment = firstSegment.replace(shiftedByStartAngle, (_, prefix) => `${prefix}0`);
135
+ if (correctedSegment === firstSegment) return body;
136
+ lines[1] = `${lines[1].slice(0, piecewiseStart)}${correctedSegment}${lines[1].slice(firstSegmentEnd)}`;
137
+ return lines.join("\n");
138
+ }
139
+
140
+ function inferTemplate(description) {
141
+ const text = description.toLowerCase();
142
+ const oscillating = ["oscillating", "oscillate", "swing", "rocker"].some((word) => text.includes(word));
143
+ const roller = text.includes("roller");
144
+ if (oscillating) return roller ? "osc_roller" : "osc_flat";
145
+ return roller ? "recip_roller" : "recip_flat";
146
+ }
147
+
148
+ async function textFile(path) {
149
+ const url = new URL(path, window.location.href);
150
+ url.searchParams.set("v", BUILD_ID);
151
+ const response = await fetch(url, { cache: "reload" });
152
+ if (!response.ok) throw new Error(`Could not load ${path}.`);
153
+ return (await response.text()).trim();
154
+ }
155
+
156
+ async function assembleProgram(name, body) {
157
+ const [followerMacro, motionLawSource] = await Promise.all([
158
+ textFile(`macros/${TEMPLATES[name].file}`),
159
+ textFile("macros/motion_laws.coregx"),
160
+ ]);
161
+ const requiredNames = new Set(EXAMPLE_MOTION_LAWS[name]);
162
+ for (const law of MOTION_LAW_NAMES) {
163
+ if (body.includes(`${law}(`)) requiredNames.add(law);
164
+ }
165
+ const selectedMotionLaws = motionLawSource
166
+ .split(/\r?\n/)
167
+ .filter((line) => [...requiredNames].some((law) => line.startsWith(`@macro ${law}(`)))
168
+ .join("\n");
169
+ return `defaultproperties constraint visible=false\n\n${followerMacro}\n\n${selectedMotionLaws}\n\n${body}\n`;
170
+ }
171
+
172
  function proxyEndpoint(path) {
173
  if (!/^https:\/\/.+/.test(COREGX_PROXY_URL)) {
174
  throw new Error("Add the Cloudflare Worker URL in config.js.");
 
187
  }
188
  }
189
 
190
+ async function generateBody(description, templateName) {
191
+ const systemPrompt = await textFile("system_prompt.txt");
192
+ setStatus("Converting to CoreGX using Qwen2.5-Coder-7B-Instruct…");
 
193
  const response = await proxyFetch("generate", {
194
  method: "POST",
195
  headers: { "Content-Type": "application/json" },
196
+ body: JSON.stringify({
197
+ messages: [
198
+ { role: "system", content: systemPrompt },
199
+ {
200
+ role: "user",
201
+ content: `${description}\n\nUse the supplied ${TEMPLATES[templateName].call} macro call as the first line.`,
202
+ },
203
+ ],
204
+ }),
205
  });
206
  const result = await response.json().catch(() => ({}));
207
+ if (!response.ok || !result.ok) {
208
+ throw new Error(`Hugging Face: ${String(result.error || `request failed with HTTP ${response.status}.`)}`);
209
+ }
210
+ if (typeof result.content !== "string" || !result.content.trim()) {
211
+ throw new Error("The Hugging Face model returned an empty response.");
212
+ }
213
+ const body = canonicalizeOptionalDefaults(stripCodeFence(result.content), templateName, description);
214
+ return canonicalizeOscillatingPhaseOrigin(body, templateName, description);
215
  }
216
 
217
  async function renderCoreGX(program) {
 
233
  headers: { "Content-Type": "application/json" },
234
  body: JSON.stringify({
235
  program,
236
+ ...(LOCAL_MODE ? { coregxKey: ui.coregxKey?.value.trim() || "" } : {}),
237
  }),
238
  };
239
+ const response = LOCAL_MODE
240
+ ? await fetch("/api/cad", options)
241
+ : await proxyFetch("cad", options);
242
  const result = await response.json().catch(() => ({}));
243
  if (!response.ok || !result.ok) {
244
  throw new Error(String(result.error || `CAD export failed with HTTP ${response.status}.`));
 
259
  cadUrl = URL.createObjectURL(new Blob([dxf], { type: "application/dxf;charset=utf-8" }));
260
  const link = document.createElement("a");
261
  link.href = cadUrl;
262
+ link.download = "cam.dxf";
263
  link.click();
264
  setStatus("✓ CAD exported");
265
  } catch (error) {
 
269
  }
270
  }
271
 
272
+ async function buildWithLocalServer(description, coregxKey) {
273
+ const response = await fetch("/api/build", {
274
+ method: "POST",
275
+ headers: { "Content-Type": "application/json" },
276
+ body: JSON.stringify({ description, coregxKey }),
277
+ });
278
+ const result = await response.json().catch(() => ({}));
279
+ if (!response.ok || !result.ok) {
280
+ throw new Error(String(result.error || `Local demo request failed with HTTP ${response.status}.`));
281
+ }
282
+ if (typeof result.program !== "string" || typeof result.svg !== "string") {
283
+ throw new Error("The local demo returned an incomplete cam result.");
284
+ }
285
+ return result;
286
+ }
287
+
288
  function setDownloads(program, svg) {
289
  if (programUrl) URL.revokeObjectURL(programUrl);
290
  if (svgUrl) URL.revokeObjectURL(svgUrl);
 
299
  ui.downloadCad.disabled = false;
300
  }
301
 
302
+ function showError(message) {
303
+ ui.preview.replaceChildren();
304
+ const box = document.createElement("div");
305
+ box.className = "preview-error";
306
+ box.textContent = message;
307
+ ui.preview.append(box);
308
+ setStatus(`⚠ ${message}`, true);
309
+ }
310
+
311
+ async function buildCam() {
312
+ const coregxKey = LOCAL_MODE ? ui.coregxKey?.value.trim() || "" : "";
313
  const description = ui.description.value.trim();
314
+
315
+ if (LOCAL_MODE && !coregxKey) return showError("Add your CoreGX API key above.");
316
+ if (!description) return showError("Describe the cam first.");
317
+
318
  ui.build.disabled = true;
319
  ui.build.textContent = "Building…";
320
+
321
  try {
322
+ if (LOCAL_MODE) {
323
+ setStatus("Running the local model…");
324
+ const result = await buildWithLocalServer(description, coregxKey);
325
+ showSvg(result.svg);
326
+ ui.program.textContent = result.program;
327
+ setDownloads(result.program, result.svg);
328
+ setStatus("✓ Cam built");
329
+ return;
330
+ }
331
+
332
+ const templateName = inferTemplate(description);
333
+ const body = await generateBody(description, templateName);
334
+ const program = await assembleProgram(templateName, body);
335
+ setStatus("Rendering the mechanism…");
336
  const svg = await renderCoreGX(program);
337
  showSvg(svg);
338
  ui.program.textContent = program;
339
  setDownloads(program, svg);
340
+ setStatus("✓ Cam built");
341
  } catch (error) {
342
+ showError(error instanceof Error ? error.message : String(error));
343
  } finally {
344
  ui.build.disabled = false;
345
+ ui.build.textContent = "Build cam";
346
  }
347
  }
348
 
 
357
  });
358
  });
359
 
360
+ ui.build.addEventListener("click", buildCam);
361
  ui.downloadCad.addEventListener("click", exportCad);
362
  ui.description.addEventListener("keydown", (event) => {
363
+ if ((event.ctrlKey || event.metaKey) && event.key === "Enter") buildCam();
364
  });
365
 
366
  window.addEventListener("beforeunload", () => {
index.html CHANGED
@@ -3,14 +3,14 @@
3
  <head>
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <meta name="description" content="Draw triangles from descriptions using CoreGX.">
7
- <title>CoreGX Triangle Studio</title>
8
- <link rel="stylesheet" href="styles.css?v=20260922-triangles-2">
9
  </head>
10
  <body>
11
  <main class="page">
12
  <header class="hero">
13
- <h1>Triangle Studio</h1>
14
  <div class="celtic-border" aria-hidden="true">
15
  <svg viewBox="0 0 440 24" preserveAspectRatio="none">
16
  <path d="M0 12 H14 L24 2 H40 L50 12 H66 L76 22 H92 L102 12 H118 L128 2 H144 L154 12 H170 L180 22 H196 L206 12 H222 L232 2 H248 L258 12 H274 L284 22 H300 L310 12 H326 L336 2 H352 L362 12 H378 L388 22 H404 L414 12 H440"/>
@@ -21,24 +21,24 @@
21
 
22
  <section class="workspace">
23
  <div class="prompt-card">
24
- <label class="sr-only" for="description">Triangle description</label>
25
- <textarea id="description" maxlength="1800" placeholder="Draw a 3, 4, 5 triangle…"></textarea>
26
  <div class="chips" aria-label="Example descriptions">
27
- <button type="button" data-example="sides">Side lengths</button>
28
- <button type="button" data-example="angles">Angles</button>
29
- <button type="button" data-example="special">Special triangles</button>
30
- <button type="button" data-example="constructions">Constructions</button>
31
  </div>
32
- <button type="button" id="build">Build triangle</button>
33
  <p id="status" role="status" aria-live="polite"></p>
34
  </div>
35
 
36
  <div id="preview" class="preview-shell" aria-live="polite"></div>
37
  </section>
38
 
39
- <div id="downloads" class="downloads" aria-label="Triangle downloads">
40
- <a id="download-program" class="is-disabled" download="triangle.coregx" aria-disabled="true">Download CoreGX</a>
41
- <a id="download-svg" class="is-disabled" download="triangle.svg" aria-disabled="true">Download SVG</a>
42
  <button type="button" id="download-cad" disabled>Export CAD</button>
43
  </div>
44
 
@@ -49,12 +49,12 @@
49
 
50
  <footer class="site-footer">
51
  <p>CoreGX is a constraint-based geometry engine. Send a request in the CoreGX language and receive precise SVG output and symbolic measurements in return. This demo uses an LLM to convert natural language into CoreGX. Visit <a href="https://coregx.dev/dev/index.html" target="_blank" rel="noopener noreferrer">coregx.dev</a> to get your own CoreGX API key.</p>
52
- <p>Want to see CoreGX used for real mechanism modeling? Try the <a href="https://huggingface.co/spaces/saltiresoftware/CoreGX-Cams" target="_blank" rel="noopener noreferrer">CAM demo</a>.</p>
53
  <p>Want to see the full natural language to geometry functionality? Try <a href="https://gengx.geometryexpressions.com/" target="_blank" rel="noopener noreferrer">GenGX</a>.</p>
54
  </footer>
55
  </main>
56
 
57
- <script src="config.js?v=20260922-triangles-2"></script>
58
- <script type="module" src="app.js?v=20260922-triangles-2"></script>
59
  </body>
60
  </html>
 
3
  <head>
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="description" content="Generate animated CoreGX cam mechanisms in your browser.">
7
+ <title>CoreGX Cam Studio</title>
8
+ <link rel="stylesheet" href="styles.css?v=20260922-14">
9
  </head>
10
  <body>
11
  <main class="page">
12
  <header class="hero">
13
+ <h1>Cam Studio</h1>
14
  <div class="celtic-border" aria-hidden="true">
15
  <svg viewBox="0 0 440 24" preserveAspectRatio="none">
16
  <path d="M0 12 H14 L24 2 H40 L50 12 H66 L76 22 H92 L102 12 H118 L128 2 H144 L154 12 H170 L180 22 H196 L206 12 H222 L232 2 H248 L258 12 H274 L284 22 H300 L310 12 H326 L336 2 H352 L362 12 H378 L388 22 H404 L414 12 H440"/>
 
21
 
22
  <section class="workspace">
23
  <div class="prompt-card">
24
+ <label class="sr-only" for="description">Cam description</label>
25
+ <textarea id="description" maxlength="1800" placeholder="A roller follower with a smooth 10 mm rise…"></textarea>
26
  <div class="chips" aria-label="Example descriptions">
27
+ <button type="button" data-example="recip-roller">Reciprocating roller</button>
28
+ <button type="button" data-example="recip-flat">Reciprocating flat</button>
29
+ <button type="button" data-example="osc-roller">Oscillating roller</button>
30
+ <button type="button" data-example="osc-flat">Oscillating flat</button>
31
  </div>
32
+ <button type="button" id="build">Build cam</button>
33
  <p id="status" role="status" aria-live="polite"></p>
34
  </div>
35
 
36
  <div id="preview" class="preview-shell" aria-live="polite"></div>
37
  </section>
38
 
39
+ <div id="downloads" class="downloads" aria-label="Cam downloads">
40
+ <a id="download-program" class="is-disabled" download="cam.coregx" aria-disabled="true">Download CoreGX</a>
41
+ <a id="download-svg" class="is-disabled" download="cam.svg" aria-disabled="true">Download SVG</a>
42
  <button type="button" id="download-cad" disabled>Export CAD</button>
43
  </div>
44
 
 
49
 
50
  <footer class="site-footer">
51
  <p>CoreGX is a constraint-based geometry engine. Send a request in the CoreGX language and receive precise SVG output and symbolic measurements in return. This demo uses an LLM to convert natural language into CoreGX. Visit <a href="https://coregx.dev/dev/index.html" target="_blank" rel="noopener noreferrer">coregx.dev</a> to get your own CoreGX API key.</p>
52
+ <p>Want to see CoreGX used for natural language geometry? Try the <a href="https://huggingface.co/spaces/saltiresoftware/coregx-triangles" target="_blank" rel="noopener noreferrer">triangles demo</a>.</p>
53
  <p>Want to see the full natural language to geometry functionality? Try <a href="https://gengx.geometryexpressions.com/" target="_blank" rel="noopener noreferrer">GenGX</a>.</p>
54
  </footer>
55
  </main>
56
 
57
+ <script src="config.js?v=20260922-14"></script>
58
+ <script type="module" src="app.js?v=20260922-14"></script>
59
  </body>
60
  </html>
system_prompt.txt CHANGED
@@ -1,85 +1,69 @@
1
- You translate natural-language triangle descriptions into complete CoreGX programs.
2
- Output CoreGX commands only, one command per line. No Markdown, explanations, macros, or cam commands.
3
- Focus on triangles and their medians, altitudes, side midpoints, and angle bisectors. Follow the user's names, dimensions, units, angles, and requested constructions exactly. Examples demonstrate syntax, not fixed templates.
4
-
5
- CoreGX syntax:
6
- triangle A B C
7
- Creates the vertices and all three sides. Do not redeclare these vertices or sides.
8
- distance A B 5
9
- Constrains the distance between two points.
10
- anglemode degree
11
- angle B A C 60
12
- Sets angle BAC, with the middle point A as vertex. Put anglemode degree before any angles in degrees. For radians use anglemode radian. Use one angle mode throughout.
13
- midpoint M B C
14
- Creates a NEW point M at the midpoint of BC. Do not declare M beforehand.
15
- segment A M
16
- Draws a segment between points (and creates missing endpoints).
17
- point H
18
- incident H BC
19
- segment A H
20
- perpendicular AH BC
21
- Constructs the altitude foot H on the line through BC. For an obtuse triangle the foot can lie outside the side.
22
- anglebisector L1 A B C
23
- Creates the angle-bisector line at B. L1 is a new line name, not a point. To show only the segment to the opposite side: make L1 visible=false, declare D, incident D L1, incident D AC, and segment B D.
24
-
25
- Rules:
26
- - For a list such as '3,4,5 triangle', assign AB=3, BC=4, AC=5 unless named sides are supplied.
27
- - Preserve named vertices. Default to A, B, C when names are omitted.
28
- - Equilateral means three equal side lengths. Isosceles means two equal side lengths; use the named equal sides and base when provided.
29
- - A right angle at B is angle A B C 90 in degree mode. Do not additionally constrain a computed hypotenuse when two legs and the right angle are already provided.
30
- - Use the given minimal defining constraints: three sides, two sides and the included angle, or a side and two angles. Avoid redundant calculated constraints and arbitrary coordinates.
31
- - When dimensions are omitted, use a simple representative example matching the requested type: generic scalene sides 5,6,7; equilateral side 6; isosceles equal sides 6 with base 8; right triangle legs 3 and 4. Never override a supplied value with a default. If the shape is specified by angles alone, add a single side of length 6 for scale.
32
- - Don't add auxiliary geometry unless requested. Do not add animation unless requested and supported by the given syntax.
33
- - Keep expressions exact (e.g. sqrt(2)); do not round requested dimensions or convert lengths to pixels.
34
- - The application prepends defaultproperties constraint visible=true so CoreGX can draw length labels, angle measurements, and perpendicular markers. Do not add global visibility settings or hide requested distance, angle, or perpendicular constraints.
35
- - Represent requested lengths using distance constraints and requested angles using angle constraints so their annotations appear where CoreGX supports them. For requested altitudes/perpendicular constructions, use perpendicular so the right-angle marker can appear. Do not add redundant constraints merely to label a computed measurement. Hidden construction lines are allowed, but keep requested triangle sides and constructions visible.
36
-
37
- User: Draw a 3,4,5 triangle.
38
- Output:
39
- triangle A B C
40
- distance A B 3
41
- distance B C 4
42
- distance A C 5
43
-
44
- User: Triangle ABC with AB=8, AC=6 and angle BAC=60 degrees.
45
- Output:
46
- anglemode degree
47
- triangle A B C
48
- distance A B 8
49
- distance A C 6
50
- angle B A C 60
51
-
52
- User: Draw a right triangle ABC with right angle at B and legs AB=3 and BC=4.
53
- Output:
54
- anglemode degree
55
- triangle A B C
56
- distance A B 3
57
- distance B C 4
58
- angle A B C 90
59
-
60
- User: Triangle ABC with AB=5, BC=6, AC=7 and a median from A.
61
- Output:
62
- triangle A B C
63
- distance A B 5
64
- distance B C 6
65
- distance A C 7
66
- midpoint M B C
67
- segment A M
68
-
69
- User: Triangle ABC with AB=6, AC=6, BC=8 and an altitude from A.
70
- Output:
71
- triangle A B C
72
- distance A B 6
73
- distance A C 6
74
- distance B C 8
75
- point H
76
- incident H BC
77
- segment A H
78
- perpendicular AH BC
79
-
80
- User: An equilateral triangle PQR of side length 10.
81
- Output:
82
- triangle P Q R
83
- distance P Q 10
84
- distance Q R 10
85
- distance P R 10
 
1
+ You generate the three-line body for an animated cam mechanism. The application prepends the exact working follower macro and the required motion-law macros from the separate macro files. Return exactly: one follower macro call, one motion constraint, and one animate line. Do not output macro definitions, Markdown, comments, prose, or extra lines.
2
+
3
+ FOLLOW THE WORKING MACRO EXAMPLES
4
+ Keep the geometry call, motion expression, phase convention, and argument order isomorphic to the examples below. Do not invent geometry or rename points.
5
+
6
+ Allowed calls:
7
+ - Reciprocating roller: @ReciprocatingRoller(O,A,B,theta,<base_radius>,<roller_radius>,<offset>,inside|outside)
8
+ - Reciprocating flat: @RFF(O,A,E,F,theta,<base_radius>,<offset>)
9
+ - Oscillating flat: @OFF(O,A,B,C,theta,<start_angle>,<pivot_distance>,<offset>)
10
+ - Oscillating roller: @OscillatingRoller(A,B,C,theta,<start_angle>,<roller_radius>,<pivot_distance>,<arm_length>,above|below,inside|outside)
11
+
12
+ Use dimensions from the description. If omitted, use the matching example dimensions. Optional arguments may be omitted only when their macro defaults match the request.
13
+
14
+ DESCRIPTION IS AUTHORITATIVE
15
+ Examples demonstrate syntax only. Never replace an explicitly requested dimension, displacement, swing magnitude, duration, boundary, direction, follower location, or contact side with a value from an example. Include every requested rise, dwell, and return exactly once and in the stated order. Before answering, silently verify that each explicit number from the requested motion schedule appears in the appropriate macro call or motion expression and that the cumulative boundaries account for every described segment. Defaults apply only to genuinely omitted information.
16
+
17
+ OPTIONAL CONTACT SIDE
18
+ Outside contact is the macro default. When the description does not explicitly request inside contact, omit the final side argument entirely. Never invent inside contact. In particular, the default reciprocating-roller call must be @ReciprocatingRoller(O,A,B,theta,20,3,2), with no final inside or outside argument. For oscillating rollers, keep the requested above or below argument but omit the final side argument for outside contact.
19
+
20
+ CONTINUOUS MOTION
21
+ Use only harmonic, cycloid, poly345, or poly4567. Use cycloid when no motion law is requested.
22
+
23
+ Every segment must begin at exactly the previous segment's ending displacement. Never reset a moving segment or dwell to zero unless the preceding segment ended at zero. For a rise h0 to h1, the next rise, dwell, or return must start at h1. For a return, reverse the endpoints and end at the starting displacement. This continuity rule applies at every boundary.
24
+
25
+ Never invent a dwell. When the description says a rise over X degrees followed by a return over Y degrees, the return begins immediately at X degrees and ends at X+Y degrees. A positive rise to h must remain at +h during any requested dwell; never change it to -h. Never negate a displacement unless the description explicitly requests negative displacement.
26
+
27
+ For each moving segment:
28
+ - D equals that segment's duration.
29
+ - t equals phase(theta+phi)-<segment_start> for clockwise motion.
30
+ - t equals phase(theta-phi)-<segment_start> for counterclockwise motion.
31
+ - The segment condition uses the cumulative ending angle.
32
+
33
+ The oscillating follower start_angle is a geometric baseline only; it is not the motion segment's phase origin. Unless the description explicitly requests an initial dwell or phase shift, the first moving segment starts at phase zero, uses phase(theta+phi)-0 or phase(theta-phi)-0, and ends at its stated duration. Add start_angle outside piecewise as the baseline angle. Do not subtract start_angle from phase.
34
+
35
+ Use the same phase expression in every expression and condition. Use phase(...), never @phase(...). The final segment is { <current_displacement>, otherwise } and fills the rest of the revolution.
36
+
37
+ WORKING EXAMPLES
38
+
39
+ Reciprocating roller, matching the supplied macro example:
40
+ @ReciprocatingRoller(O,A,B,theta,20,3,2)
41
+ distance A B "20+3+piecewise({ cycloid(0,5,(20*pi/180),phase(theta+phi)-0), phase(theta+phi)<=20*pi/180 },{ 5, phase(theta+phi)<=60*pi/180 },{ poly345(5,12,(30*pi/180),phase(theta+phi)-60*pi/180), phase(theta+phi)<=90*pi/180 },{ 12, phase(theta+phi)<=120*pi/180 },{ poly4567(12,0,(40*pi/180),phase(theta+phi)-120*pi/180), phase(theta+phi)<=160*pi/180 },{ 0, otherwise })"
42
+ animate phi 0 6.283 duration=2
43
+
44
+ Reciprocating flat, matching the supplied macro example:
45
+ @RFF(O,A,E,F,theta,40,9)
46
+ distance A EF "40 + piecewise({ cycloid(0,6,(60*pi/180),phase(theta+phi)-0), phase(theta+phi)<=60*pi/180 },{ cycloid(6,0,(60*pi/180),phase(theta+phi)-60*pi/180), phase(theta+phi)<=120*pi/180 },{ 0, otherwise })"
47
+ animate phi 0 6.283 duration=2
48
+
49
+ Reciprocating roller with an immediate harmonic return and no requested dwell:
50
+ @ReciprocatingRoller(O,A,B,theta,20,3,2)
51
+ distance A B "20+3+piecewise({ harmonic(0,5,(90*pi/180),phase(theta+phi)-0), phase(theta+phi)<=90*pi/180 },{ harmonic(5,0,(90*pi/180),phase(theta+phi)-90*pi/180), phase(theta+phi)<=180*pi/180 },{ 0, otherwise })"
52
+ animate phi 0 6.283 duration=2
53
+
54
+ Oscillating flat, matching the supplied macro example:
55
+ @OFF(O,A,B,C,theta,35*pi/180,69,5)
56
+ angle A B C "35*pi/180 + piecewise({ cycloid(0,0.15,(90*pi/180),phase(theta+phi)-0), phase(theta+phi)<=90*pi/180 },{ cycloid(0.15,0,(90*pi/180),phase(theta+phi)-90*pi/180), phase(theta+phi)<=180*pi/180 },{ 0, otherwise })"
57
+ animate phi 0 6.283 duration=2
58
+
59
+ Oscillating roller, clockwise, matching the supplied macro example:
60
+ @OscillatingRoller(A,B,C,theta,50*pi/180,5,69,75,below)
61
+ angle A B C "50*pi/180 + piecewise({ cycloid(0,0.2,(60*pi/180),phase(theta+phi)-0), phase(theta+phi)<=60*pi/180 },{ cycloid(0.2,0,(60*pi/180),phase(theta+phi)-60*pi/180), phase(theta+phi)<=120*pi/180 },{ 0, otherwise })"
62
+ animate phi 0 6.283 duration=2
63
+
64
+ Oscillating roller, counterclockwise:
65
+ @OscillatingRoller(A,B,C,theta,0.7,5,69,75,below)
66
+ angle A B C "0.7 + piecewise({ cycloid(0,0.2,(60*pi/180),phase(theta-phi)-0), phase(theta-phi)<=60*pi/180 },{ cycloid(0.2,0,(60*pi/180),phase(theta-phi)-60*pi/180), phase(theta-phi)<=120*pi/180 },{ 0, otherwise })"
67
+ animate phi 0 6.283 duration=2
68
+
69
+ Always end with animate phi 0 6.283 duration=<seconds>. Use duration=2 when unspecified.