const MOTION_LAW_NAMES = ["harmonic", "cycloid", "poly345", "poly4567"]; const LOCAL_MODE = window.CAM_STUDIO_LOCAL === true; const COREGX_PROXY_URL = String(window.CAM_STUDIO_CONFIG?.coregxProxyUrl || "").trim(); const BUILD_ID = "20261001-02"; const TEMPLATES = { recip_flat: { file: "reciprocating_flat.coregx", call: "@RFF(O,A,E,F,theta,...)" }, recip_roller: { file: "reciprocating_roller.coregx", call: "@ReciprocatingRoller(O,A,B,theta,...)" }, osc_flat: { file: "oscillating_flat.coregx", call: "@OFF(O,A,B,C,theta,...)" }, osc_roller: { file: "oscillating_roller.coregx", call: "@OscillatingRoller(A,B,C,theta,...)" }, }; const EXAMPLE_MOTION_LAWS = { recip_flat: ["cycloid"], recip_roller: ["harmonic", "cycloid", "poly345", "poly4567"], osc_flat: ["cycloid"], osc_roller: ["harmonic", "cycloid"], }; const EXAMPLE_BANKS = { "recip-roller": [ "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.", "Reciprocating roller follower with a 5 mm harmonic rise over 90 degrees followed immediately by a 90 degree return.", "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.", "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.", "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.", ], "recip-flat": [ "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.", "Reciprocating flat follower: 8 mm harmonic rise over 90 degrees, then return over 90 degrees.", "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.", "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.", "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.", ], "osc-roller": [ "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.", "Oscillating roller follower below the cam: 0.2 radian harmonic swing over 60 degrees, then return over 60 degrees.", "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.", "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.", "Oscillating roller follower above the cam with a 0.1 radian cycloidal swing over 90 degrees followed immediately by a 90 degree return.", ], "osc-flat": [ "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.", "Oscillating flat follower with a 0.15 radian cycloidal swing over 90 degrees and immediate return over 90 degrees.", "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.", "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.", "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.", ], }; const exampleIndices = Object.fromEntries(Object.keys(EXAMPLE_BANKS).map((name) => [name, 0])); const ui = { coregxKey: document.querySelector("#coregx-key"), description: document.querySelector("#description"), build: document.querySelector("#build"), status: document.querySelector("#status"), preview: document.querySelector("#preview"), program: document.querySelector("#program"), downloads: document.querySelector("#downloads"), downloadProgram: document.querySelector("#download-program"), downloadSvg: document.querySelector("#download-svg"), downloadCad: document.querySelector("#download-cad"), }; let programUrl; let svgUrl; let cadUrl; if (LOCAL_MODE && ui.coregxKey) ui.coregxKey.value = ""; function setStatus(message, isError = false) { ui.status.textContent = message; ui.status.classList.toggle("error", isError); } function showSvg(svg) { ui.preview.innerHTML = svg; } function stripCodeFence(value) { const text = value.trim(); if (!text.startsWith("```")) return text; const lines = text.split(/\r?\n/); lines.shift(); if (lines.at(-1)?.trim() === "```") lines.pop(); return lines.join("\n").trim(); } function canonicalizeOptionalDefaults(body, templateName, description) { if (!templateName.endsWith("roller") || /\binside\b/i.test(description)) return body; const lines = body.split(/\r?\n/); lines[0] = lines[0].replace(/,\s*(?:side\s*=\s*)?(?:inside|outside)\s*\)\s*$/i, ")"); return lines.join("\n"); } function escapeRegExp(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function canonicalizeOscillatingPhaseOrigin(body, templateName, description) { if (!templateName.startsWith("osc_")) return body; 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)) { return body; } const lines = body.split(/\r?\n/); const call = lines[0]?.match(/^@(OscillatingRoller|OFF)\((.*)\)\s*$/); if (!call || !lines[1]) return body; const args = call[2].split(",").map((value) => value.trim()); const startAngle = args[call[1] === "OscillatingRoller" ? 4 : 5]; if (!startAngle) return body; const piecewiseStart = lines[1].indexOf("piecewise({"); const firstSegmentEnd = lines[1].indexOf("},", piecewiseStart); if (piecewiseStart < 0 || firstSegmentEnd < 0) return body; const firstSegment = lines[1].slice(piecewiseStart, firstSegmentEnd); const shiftedByStartAngle = new RegExp( `(phase\\(theta\\s*[+-]\\s*phi\\)\\s*-\\s*)${escapeRegExp(startAngle)}(?=\\s*[,\\)])`, "i", ); const correctedSegment = firstSegment.replace(shiftedByStartAngle, (_, prefix) => `${prefix}0`); if (correctedSegment === firstSegment) return body; lines[1] = `${lines[1].slice(0, piecewiseStart)}${correctedSegment}${lines[1].slice(firstSegmentEnd)}`; return lines.join("\n"); } function inferTemplate(description) { const text = description.toLowerCase(); const oscillating = ["oscillating", "oscillate", "swing", "rocker"].some((word) => text.includes(word)); const roller = text.includes("roller"); if (oscillating) return roller ? "osc_roller" : "osc_flat"; return roller ? "recip_roller" : "recip_flat"; } async function textFile(path) { const url = new URL(path, window.location.href); url.searchParams.set("v", BUILD_ID); const response = await fetch(url, { cache: "reload" }); if (!response.ok) throw new Error(`Could not load ${path}.`); return (await response.text()).trim(); } async function assembleProgram(name, body) { const [followerMacro, motionLawSource] = await Promise.all([ textFile(`macros/${TEMPLATES[name].file}`), textFile("macros/motion_laws.coregx"), ]); const requiredNames = new Set(EXAMPLE_MOTION_LAWS[name]); for (const law of MOTION_LAW_NAMES) { if (body.includes(`${law}(`)) requiredNames.add(law); } const selectedMotionLaws = motionLawSource .split(/\r?\n/) .filter((line) => [...requiredNames].some((law) => line.startsWith(`@macro ${law}(`))) .join("\n"); return `defaultproperties constraint visible=false\n\n${followerMacro}\n\n${selectedMotionLaws}\n\n${body}\n`; } function proxyEndpoint(path) { if (!/^https:\/\/.+/.test(COREGX_PROXY_URL)) { throw new Error("Add the Cloudflare Worker URL in config.js."); } const base = COREGX_PROXY_URL.endsWith("/") ? COREGX_PROXY_URL : `${COREGX_PROXY_URL}/`; return new URL(path.replace(/^\//, ""), base).toString(); } async function proxyFetch(route, options) { const endpoint = proxyEndpoint(route); try { return await fetch(endpoint, options); } catch (error) { const detail = error instanceof Error ? error.message : String(error); throw new Error(`Could not reach the ${route} proxy from ${window.location.origin}: ${detail}`); } } async function generateBody(description, templateName) { const systemPrompt = await textFile("system_prompt.txt"); setStatus("Converting to CoreGX using Qwen2.5-Coder-7B-Instruct…"); const response = await proxyFetch("generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: [ { role: "system", content: systemPrompt }, { role: "user", content: `${description}\n\nUse the supplied ${TEMPLATES[templateName].call} macro call as the first line.`, }, ], }), }); const result = await response.json().catch(() => ({})); if (!response.ok || !result.ok) { throw new Error(`Hugging Face: ${String(result.error || `request failed with HTTP ${response.status}.`)}`); } if (typeof result.content !== "string" || !result.content.trim()) { throw new Error("The Hugging Face model returned an empty response."); } const body = canonicalizeOptionalDefaults(stripCodeFence(result.content), templateName, description); return canonicalizeOscillatingPhaseOrigin(body, templateName, description); } async function renderCoreGX(program) { const response = await proxyFetch("render", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ program }), }); const result = await response.json().catch(() => ({})); if (!response.ok) throw new Error(`CoreGX request failed with HTTP ${response.status}.`); if (!result.ok) throw new Error(String(result.error || "CoreGX rejected the program.")); if (typeof result?.value?.svg !== "string") throw new Error("CoreGX returned no SVG."); return result.value.svg; } async function requestCad(program) { const options = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ program, ...(LOCAL_MODE ? { coregxKey: ui.coregxKey?.value.trim() || "" } : {}), }), }; const response = LOCAL_MODE ? await fetch("/api/cad", options) : await proxyFetch("cad", options); const result = await response.json().catch(() => ({})); if (!response.ok || !result.ok) { throw new Error(String(result.error || `CAD export failed with HTTP ${response.status}.`)); } const dxf = result?.value?.dxf ?? result.dxf; if (typeof dxf !== "string" || !dxf.trim()) throw new Error("CoreGX returned no CAD file."); return dxf; } async function exportCad() { const program = ui.program.textContent.trim(); if (!program) return; ui.downloadCad.disabled = true; setStatus("Exporting CAD…"); try { const dxf = await requestCad(program); if (cadUrl) URL.revokeObjectURL(cadUrl); cadUrl = URL.createObjectURL(new Blob([dxf], { type: "application/dxf;charset=utf-8" })); const link = document.createElement("a"); link.href = cadUrl; link.download = "cam.dxf"; link.click(); setStatus("✓ CAD exported"); } catch (error) { setStatus(`⚠ ${error instanceof Error ? error.message : String(error)}`, true); } finally { ui.downloadCad.disabled = false; } } async function buildWithLocalServer(description, coregxKey) { const response = await fetch("/api/build", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ description, coregxKey }), }); const result = await response.json().catch(() => ({})); if (!response.ok || !result.ok) { throw new Error(String(result.error || `Local demo request failed with HTTP ${response.status}.`)); } if (typeof result.program !== "string" || typeof result.svg !== "string") { throw new Error("The local demo returned an incomplete cam result."); } return result; } function setDownloads(program, svg) { if (programUrl) URL.revokeObjectURL(programUrl); if (svgUrl) URL.revokeObjectURL(svgUrl); programUrl = URL.createObjectURL(new Blob([program], { type: "text/plain;charset=utf-8" })); svgUrl = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml;charset=utf-8" })); ui.downloadProgram.href = programUrl; ui.downloadSvg.href = svgUrl; ui.downloadProgram.classList.remove("is-disabled"); ui.downloadSvg.classList.remove("is-disabled"); ui.downloadProgram.removeAttribute("aria-disabled"); ui.downloadSvg.removeAttribute("aria-disabled"); ui.downloadCad.disabled = false; } function showError(message) { ui.preview.replaceChildren(); const box = document.createElement("div"); box.className = "preview-error"; box.textContent = message; ui.preview.append(box); setStatus(`⚠ ${message}`, true); } async function buildCam() { const coregxKey = LOCAL_MODE ? ui.coregxKey?.value.trim() || "" : ""; const description = ui.description.value.trim(); if (LOCAL_MODE && !coregxKey) return showError("Add your CoreGX API key above."); if (!description) return showError("Describe the cam first."); ui.build.disabled = true; ui.build.textContent = "Building…"; try { if (LOCAL_MODE) { setStatus("Running the local model…"); const result = await buildWithLocalServer(description, coregxKey); showSvg(result.svg); ui.program.textContent = result.program; setDownloads(result.program, result.svg); setStatus("✓ Cam built"); return; } const templateName = inferTemplate(description); const body = await generateBody(description, templateName); const program = await assembleProgram(templateName, body); setStatus("Rendering the mechanism…"); const svg = await renderCoreGX(program); showSvg(svg); ui.program.textContent = program; setDownloads(program, svg); setStatus("✓ Cam built"); } catch (error) { showError(error instanceof Error ? error.message : String(error)); } finally { ui.build.disabled = false; ui.build.textContent = "Build cam"; } } document.querySelectorAll("[data-example]").forEach((button) => { button.addEventListener("click", () => { const name = button.dataset.example; const bank = EXAMPLE_BANKS[name]; const index = exampleIndices[name]; ui.description.value = bank[index]; exampleIndices[name] = (index + 1) % bank.length; ui.description.focus(); }); }); ui.build.addEventListener("click", buildCam); ui.downloadCad.addEventListener("click", exportCad); ui.description.addEventListener("keydown", (event) => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") buildCam(); }); window.addEventListener("beforeunload", () => { if (programUrl) URL.revokeObjectURL(programUrl); if (svgUrl) URL.revokeObjectURL(svgUrl); if (cadUrl) URL.revokeObjectURL(cadUrl); }); const DEFAULT_PROGRAM = "defaultproperties constraint visible=false\n\n@macro ReciprocatingRoller(O,A,B,theta,base_radius,roller_radius,offset,side=outside) {\n point O\n coordinates O 0 0\n line ln visible=false\n incident O ln\n direction ln theta\n line perp visible=false\n perpendicular perp ln\n incident O perp\n point A visible=false\n distance A ln offset\n incident A perp\n point B\n segment A B visible=false\n direction AB theta\n circle base O\n radius base base_radius\n point C visible=false\n segment B C\n distance B C base_radius\n incident C AB\n circle roll B\n radius roll roller_radius\n@if side == outside\n envelope cam roll theta 0 6.2832 position=negative\n@else\n envelope cam roll theta 0 6.2832 position=positive\n@endif\n value theta 1.5708\n}\n\n@macro harmonic(h0,h1,D,t)=(h0+(h1-h0)*((1-cos(pi*t/D))/2))\n@macro cycloid(h0,h1,D,t)=(h0+(h1-h0)*((t/D)-(sin(2*pi*t/D)/(2*pi))))\n@macro poly345(h0,h1,D,t)=(h0+(h1-h0)*(10*(t/D)^3-15*(t/D)^4+6*(t/D)^5))\n@macro poly4567(h0,h1,D,t)=(h0+(h1-h0)*(35*(t/D)^4-84*(t/D)^5+70*(t/D)^6-20*(t/D)^7))\n\n@ReciprocatingRoller(O,A,B,theta,20,3,2)\ndistance 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 })\"\nanimate phi 0 6.283 duration=2\n"; const DEFAULT_SVG = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nO\nB\n\n\n \n\n\n"; showSvg(DEFAULT_SVG); ui.program.textContent = DEFAULT_PROGRAM; setDownloads(DEFAULT_PROGRAM, DEFAULT_SVG);