Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
Release SketchForge 0.5 edge tools
This commit is contained in:
@@ -0,0 +1,249 @@
|
||||
import * as THREE from "three";
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
import type { CadModifierPrimitivePart } from "@/lib/cadModifierTypes";
|
||||
import { mirrorSign, resizedImportedCoordinates, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
|
||||
|
||||
export type BakedCadMetadataFrame = {
|
||||
centerX: number;
|
||||
minY: number;
|
||||
centerZ: number;
|
||||
width: number;
|
||||
depth: number;
|
||||
height: number;
|
||||
yawDegrees: number;
|
||||
};
|
||||
|
||||
export function cadTransformToMatrix(transform: number[] | undefined) {
|
||||
if (!transform || transform.length !== 12 || !transform.every(Number.isFinite)) {
|
||||
return new THREE.Matrix4();
|
||||
}
|
||||
|
||||
return new THREE.Matrix4().set(
|
||||
transform[0], transform[1], transform[2], transform[3],
|
||||
transform[4], transform[5], transform[6], transform[7],
|
||||
transform[8], transform[9], transform[10], transform[11],
|
||||
0, 0, 0, 1,
|
||||
);
|
||||
}
|
||||
|
||||
export function cadTransformFromMatrix(matrix: THREE.Matrix4) {
|
||||
const elements = matrix.elements;
|
||||
return [
|
||||
elements[0], elements[4], elements[8], elements[12],
|
||||
elements[1], elements[5], elements[9], elements[13],
|
||||
elements[2], elements[6], elements[10], elements[14],
|
||||
];
|
||||
}
|
||||
|
||||
function isIdentityCadTransform(transform: number[]) {
|
||||
const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
||||
return transform.every((value, index) => Math.abs(value - identity[index]) < 1e-9);
|
||||
}
|
||||
|
||||
function allFinitePositive(values: number[]) {
|
||||
return values.every((value) => Number.isFinite(value) && value > 0);
|
||||
}
|
||||
|
||||
export function cadModifierPrimitiveForAnalyticBox(shape: WorkplaneShape): CadModifierPrimitivePart | null {
|
||||
if (shape.kind !== "box" || shape.importedMesh || shape.groupedShapes?.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const width = shapeWidth(shape);
|
||||
const depth = shapeDepth(shape);
|
||||
const height = shape.height;
|
||||
if (!allFinitePositive([width, depth, height])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const centerY = height / 2;
|
||||
const matrix = new THREE.Matrix4()
|
||||
.makeTranslation(shape.x, (shape.elevation ?? 0) + centerY, shape.z)
|
||||
.multiply(new THREE.Matrix4().makeRotationFromEuler(
|
||||
new THREE.Euler(
|
||||
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
|
||||
THREE.MathUtils.degToRad(shape.rotation ?? 0),
|
||||
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
|
||||
"XYZ",
|
||||
),
|
||||
))
|
||||
.multiply(new THREE.Matrix4().makeScale(mirrorSign(shape.mirrorX), mirrorSign(shape.mirrorY), mirrorSign(shape.mirrorZ)))
|
||||
.multiply(new THREE.Matrix4().makeTranslation(0, -centerY, 0));
|
||||
|
||||
const transform = cadTransformFromMatrix(matrix);
|
||||
return {
|
||||
kind: "box",
|
||||
width,
|
||||
depth,
|
||||
height,
|
||||
transform: isIdentityCadTransform(transform) ? undefined : transform,
|
||||
};
|
||||
}
|
||||
|
||||
export function cadModifierPrimitiveForBakedShape(shape: WorkplaneShape): CadModifierPrimitivePart | null {
|
||||
const primitive = shape.cadPrimitiveFrame;
|
||||
const frame = primitive?.frame;
|
||||
if (!primitive || primitive.kind !== "box" || !frame) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!allFinitePositive([
|
||||
primitive.width,
|
||||
primitive.depth,
|
||||
primitive.height,
|
||||
frame.width,
|
||||
frame.depth,
|
||||
frame.height,
|
||||
shapeWidth(shape),
|
||||
shapeDepth(shape),
|
||||
shape.height,
|
||||
])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const centerY = shape.height / 2;
|
||||
const scaleX = shapeWidth(shape) / frame.width;
|
||||
const scaleY = shape.height / frame.height;
|
||||
const scaleZ = shapeDepth(shape) / frame.depth;
|
||||
const mirrorX = mirrorSign(shape.mirrorX);
|
||||
const mirrorY = mirrorSign(shape.mirrorY);
|
||||
const mirrorZ = mirrorSign(shape.mirrorZ);
|
||||
const matrix = new THREE.Matrix4()
|
||||
.makeTranslation(shape.x, (shape.elevation ?? 0) + centerY, shape.z)
|
||||
.multiply(new THREE.Matrix4().makeRotationFromEuler(
|
||||
new THREE.Euler(
|
||||
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
|
||||
THREE.MathUtils.degToRad(shape.rotation ?? 0),
|
||||
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
|
||||
"XYZ",
|
||||
),
|
||||
))
|
||||
.multiply(new THREE.Matrix4().makeTranslation(0, -mirrorY * centerY, 0))
|
||||
.multiply(new THREE.Matrix4().makeScale(mirrorX * scaleX, mirrorY * scaleY, mirrorZ * scaleZ))
|
||||
.multiply(new THREE.Matrix4().makeTranslation(-frame.x, -frame.elevation, -frame.z))
|
||||
.multiply(cadTransformToMatrix(frame.sourceTransform));
|
||||
|
||||
const transform = cadTransformFromMatrix(matrix);
|
||||
return {
|
||||
kind: primitive.kind,
|
||||
width: primitive.width,
|
||||
depth: primitive.depth,
|
||||
height: primitive.height,
|
||||
transform: isIdentityCadTransform(transform) ? undefined : transform,
|
||||
};
|
||||
}
|
||||
|
||||
export function cadBrepTransformForShape(shape: WorkplaneShape) {
|
||||
const frame = shape.cadBrepFrame;
|
||||
if (!frame) return undefined;
|
||||
const oldCenter = new THREE.Vector3(frame.x, frame.elevation + frame.height / 2, frame.z);
|
||||
const currentCenter = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z);
|
||||
const rotation = new THREE.Quaternion().setFromEuler(new THREE.Euler(
|
||||
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
|
||||
THREE.MathUtils.degToRad(shape.rotation ?? 0),
|
||||
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
|
||||
"XYZ",
|
||||
));
|
||||
const scale = new THREE.Vector3(
|
||||
shapeWidth(shape) / Math.max(0.001, frame.width) * mirrorSign(shape.mirrorX),
|
||||
shape.height / Math.max(0.001, frame.height) * mirrorSign(shape.mirrorY),
|
||||
shapeDepth(shape) / Math.max(0.001, frame.depth) * mirrorSign(shape.mirrorZ),
|
||||
);
|
||||
const matrix = new THREE.Matrix4()
|
||||
.compose(currentCenter, rotation, scale)
|
||||
.multiply(new THREE.Matrix4().makeTranslation(-oldCenter.x, -oldCenter.y, -oldCenter.z))
|
||||
.multiply(cadTransformToMatrix(frame.sourceTransform));
|
||||
const result = cadTransformFromMatrix(matrix);
|
||||
return isIdentityCadTransform(result) ? undefined : result;
|
||||
}
|
||||
|
||||
function bakeCadDisplayEdgesForShape(shape: WorkplaneShape, frame: BakedCadMetadataFrame) {
|
||||
if (!shape.cadDisplayEdges?.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const centerY = shape.height / 2;
|
||||
const matrix = new THREE.Matrix4().makeRotationFromEuler(
|
||||
new THREE.Euler(
|
||||
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
|
||||
THREE.MathUtils.degToRad(frame.yawDegrees),
|
||||
THREE.MathUtils.degToRad(shape.rotationZ ?? 0),
|
||||
"XYZ",
|
||||
),
|
||||
);
|
||||
const xMirror = mirrorSign(shape.mirrorX);
|
||||
const yMirror = mirrorSign(shape.mirrorY);
|
||||
const zMirror = mirrorSign(shape.mirrorZ);
|
||||
const bakedEdges = shape.cadDisplayEdges.flatMap((edge) => {
|
||||
if (edge.points.length < 6) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const resizedPoints = resizedImportedCoordinates(shape, edge.points);
|
||||
const points: number[] = [];
|
||||
for (let index = 0; index + 2 < resizedPoints.length; index += 3) {
|
||||
const vertex = new THREE.Vector3(
|
||||
resizedPoints[index] * xMirror,
|
||||
(resizedPoints[index + 1] - centerY) * yMirror,
|
||||
resizedPoints[index + 2] * zMirror,
|
||||
).applyMatrix4(matrix);
|
||||
const x = vertex.x + shape.x - frame.centerX;
|
||||
const y = vertex.y + (shape.elevation ?? 0) + centerY - frame.minY;
|
||||
const z = vertex.z + shape.z - frame.centerZ;
|
||||
if ([x, y, z].every(Number.isFinite)) {
|
||||
points.push(x, y, z);
|
||||
}
|
||||
}
|
||||
|
||||
return points.length >= 6 ? [{ points }] : [];
|
||||
});
|
||||
|
||||
return bakedEdges.length > 0 ? bakedEdges : undefined;
|
||||
}
|
||||
|
||||
function bakeCadPrimitiveFrameForShapeTransform(shape: WorkplaneShape, frame: BakedCadMetadataFrame) {
|
||||
const primitive = cadModifierPrimitiveForBakedShape(shape) ?? cadModifierPrimitiveForAnalyticBox(shape);
|
||||
if (!primitive) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: primitive.kind,
|
||||
width: primitive.width,
|
||||
depth: primitive.depth,
|
||||
height: primitive.height,
|
||||
frame: {
|
||||
x: frame.centerX,
|
||||
z: frame.centerZ,
|
||||
elevation: frame.minY,
|
||||
width: frame.width,
|
||||
depth: frame.depth,
|
||||
height: frame.height,
|
||||
...(primitive.transform ? { sourceTransform: primitive.transform } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function bakeCadMetadataForShapeTransform(shape: WorkplaneShape, frame: BakedCadMetadataFrame) {
|
||||
const cadDisplayEdges = bakeCadDisplayEdgesForShape(shape, frame);
|
||||
const sourceTransform = cadBrepTransformForShape(shape);
|
||||
const cadPrimitiveFrame = bakeCadPrimitiveFrameForShapeTransform(shape, frame);
|
||||
const cadBrepFrame = shape.cadBrep && shape.cadBrepFrame
|
||||
? {
|
||||
x: frame.centerX,
|
||||
z: frame.centerZ,
|
||||
elevation: frame.minY,
|
||||
width: frame.width,
|
||||
depth: frame.depth,
|
||||
height: frame.height,
|
||||
...(sourceTransform ? { sourceTransform } : {}),
|
||||
}
|
||||
: undefined;
|
||||
return {
|
||||
cadDisplayEdges,
|
||||
cadDisplayEdgesVersion: cadDisplayEdges ? (2 as const) : undefined,
|
||||
cadBrep: cadBrepFrame ? shape.cadBrep : undefined,
|
||||
cadBrepFrame,
|
||||
cadPrimitiveFrame,
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,10 @@ export type CadModifierKind = "chamfer" | "fillet";
|
||||
|
||||
export type CadModifierEdge = {
|
||||
id: number;
|
||||
owner?: number;
|
||||
points: number[];
|
||||
display: boolean;
|
||||
selectable: boolean;
|
||||
angle: number;
|
||||
boundary: boolean;
|
||||
manifold: boolean;
|
||||
@@ -14,16 +17,35 @@ export type CadModifierDisplayEdge = {
|
||||
points: number[];
|
||||
};
|
||||
|
||||
export type CadModifierPrimitivePart = {
|
||||
kind: "box";
|
||||
width: number;
|
||||
depth: number;
|
||||
height: number;
|
||||
transform?: number[];
|
||||
};
|
||||
|
||||
export type CadModifierMeshPart = {
|
||||
positions?: Float32Array;
|
||||
indices?: Uint32Array;
|
||||
brep?: string;
|
||||
brepTransform?: number[];
|
||||
primitive?: CadModifierPrimitivePart;
|
||||
hole: boolean;
|
||||
};
|
||||
|
||||
export type CadModifierComponentMesh = {
|
||||
owner: number;
|
||||
positions: Float32Array;
|
||||
normals: Float32Array;
|
||||
indices: Uint32Array;
|
||||
triangleCount: number;
|
||||
brep: string;
|
||||
displayEdges: CadModifierDisplayEdge[];
|
||||
};
|
||||
|
||||
export type CadModifierWorkerRequest =
|
||||
| { type: "prepare"; requestId: number; parts: CadModifierMeshPart[]; sharpAngle: number }
|
||||
| { type: "prepare"; requestId: number; parts: CadModifierMeshPart[]; sharpAngle: number; suppressTreatmentDetailEdges?: boolean }
|
||||
| {
|
||||
type: "preview";
|
||||
requestId: number;
|
||||
@@ -46,6 +68,7 @@ export type CadModifierWorkerResponse =
|
||||
triangleCount: number;
|
||||
brep: string;
|
||||
displayEdges: CadModifierDisplayEdge[];
|
||||
components?: CadModifierComponentMesh[];
|
||||
}
|
||||
| { type: "disposed"; requestId: number }
|
||||
| { type: "error"; requestId: number; message: string };
|
||||
| { type: "error"; requestId: number; message: string; resetSession?: boolean };
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
const MILLIMETERS_PER_INCH = 25.4;
|
||||
const MILLIMETERS_PER_FOOT = 304.8;
|
||||
const MILLIMETERS_PER_STUD = 8;
|
||||
|
||||
type WorkspaceScaleOption = {
|
||||
label: string;
|
||||
displayLabel: string;
|
||||
millimetersPerDisplayUnit: number;
|
||||
};
|
||||
|
||||
const METRIC_SCALE_OPTIONS: WorkspaceScaleOption[] = [
|
||||
{ label: "1:1 (millimeters)", displayLabel: "mm", millimetersPerDisplayUnit: 1 },
|
||||
{ label: "1:10 (centimeters)", displayLabel: "cm", millimetersPerDisplayUnit: 10 },
|
||||
{ label: "1:1000 (meters)", displayLabel: "m", millimetersPerDisplayUnit: 1000 },
|
||||
];
|
||||
|
||||
const IMPERIAL_SCALE_OPTIONS: WorkspaceScaleOption[] = [
|
||||
{ label: "1:1 (inches)", displayLabel: "in", millimetersPerDisplayUnit: MILLIMETERS_PER_INCH },
|
||||
{ label: "1:1 (feet)", displayLabel: "ft", millimetersPerDisplayUnit: MILLIMETERS_PER_FOOT },
|
||||
];
|
||||
|
||||
const BRICK_SCALE_OPTIONS: WorkspaceScaleOption[] = [
|
||||
{ label: "1:1 (studs)", displayLabel: "stud", millimetersPerDisplayUnit: MILLIMETERS_PER_STUD },
|
||||
];
|
||||
|
||||
export const WORKSPACE_UNIT_OPTIONS = ["Metric (Default)", "Imperial", "Bricks"] as const;
|
||||
|
||||
export type LengthDisplayUnit = {
|
||||
label: string;
|
||||
millimetersPerUnit: number;
|
||||
};
|
||||
|
||||
function scaleEntriesForUnits(units: string) {
|
||||
if (units === "Imperial") return IMPERIAL_SCALE_OPTIONS;
|
||||
if (units === "Bricks") return BRICK_SCALE_OPTIONS;
|
||||
return METRIC_SCALE_OPTIONS;
|
||||
}
|
||||
|
||||
export function scaleOptionsForUnits(units: string) {
|
||||
return scaleEntriesForUnits(units).map((option) => option.label);
|
||||
}
|
||||
|
||||
export function defaultScaleForUnits(units: string) {
|
||||
return scaleEntriesForUnits(units)[0].label;
|
||||
}
|
||||
|
||||
export function normalizeScaleForUnits(units: string, scale: string) {
|
||||
const options = scaleEntriesForUnits(units);
|
||||
const normalizedScale = units !== "Imperial" && units !== "Bricks" && scale === "1:100 (meters)" ? "1:1000 (meters)" : scale;
|
||||
return options.some((option) => option.label === normalizedScale) ? normalizedScale : options[0].label;
|
||||
}
|
||||
|
||||
function scaleEntryForWorkspace(workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
|
||||
const options = scaleEntriesForUnits(workspace.units);
|
||||
const normalizedScale = normalizeScaleForUnits(workspace.units, workspace.scale);
|
||||
return options.find((option) => option.label === normalizedScale) ?? options[0];
|
||||
}
|
||||
|
||||
export function lengthDisplayUnit(workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">): LengthDisplayUnit {
|
||||
const scale = scaleEntryForWorkspace(workspace);
|
||||
return { label: scale.displayLabel, millimetersPerUnit: scale.millimetersPerDisplayUnit };
|
||||
}
|
||||
|
||||
export function millimetersToDisplay(value: number, workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
|
||||
return value / lengthDisplayUnit(workspace).millimetersPerUnit;
|
||||
}
|
||||
|
||||
export function displayToMillimeters(value: number, workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
|
||||
return value * lengthDisplayUnit(workspace).millimetersPerUnit;
|
||||
}
|
||||
|
||||
export function displayStepFromMillimeters(step: number, workspace: Pick<WorkplaneWorkspaceSettings, "units" | "scale">) {
|
||||
return step / lengthDisplayUnit(workspace).millimetersPerUnit;
|
||||
}
|
||||
|
||||
export function formatMeasurementNumber(value: number, accuracy: MeasurementAccuracy, _step?: number) {
|
||||
let decimals = accuracy;
|
||||
while (decimals < 6 && value !== 0 && Math.abs(value) < 0.5 * 10 ** -decimals) {
|
||||
decimals += 1;
|
||||
}
|
||||
const zeroThreshold = 0.5 * 10 ** -decimals;
|
||||
return (Math.abs(value) < zeroThreshold ? 0 : value).toFixed(decimals);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { GridSize, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
export const SKETCHFORGE_MCP_ROUTE = "/api/sketchforge-mcp";
|
||||
export const SKETCHFORGE_MCP_STALE_MS = 6500;
|
||||
export const SKETCHFORGE_MCP_POLL_MS = 220;
|
||||
|
||||
export type SketchForgeMcpViewFace = "current" | "home" | "top" | "bottom" | "front" | "back" | "right" | "left";
|
||||
|
||||
export type SketchForgeMcpShapeSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: ShapeKind;
|
||||
color: string;
|
||||
hole: boolean;
|
||||
locked: boolean;
|
||||
hidden: boolean;
|
||||
position: {
|
||||
x: number;
|
||||
z: number;
|
||||
elevation: number;
|
||||
};
|
||||
dimensions: {
|
||||
width: number;
|
||||
depth: number;
|
||||
height: number;
|
||||
size: number;
|
||||
};
|
||||
rotation: {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
};
|
||||
mirror: {
|
||||
x: boolean;
|
||||
y: boolean;
|
||||
z: boolean;
|
||||
};
|
||||
edgeTreatments: unknown[];
|
||||
groupedCount: number;
|
||||
importedTriangles: number;
|
||||
cadDisplayEdgeCount: number | null;
|
||||
sketchPointCount: number;
|
||||
sketchSegmentCount: number;
|
||||
children?: SketchForgeMcpShapeSummary[];
|
||||
};
|
||||
|
||||
export type SketchForgeMcpSceneSummary = {
|
||||
projectId: string | null;
|
||||
projectName: string;
|
||||
notice: string;
|
||||
selectedIds: string[];
|
||||
shapeCount: number;
|
||||
workspace: WorkplaneWorkspaceSettings;
|
||||
snap: GridSize | null;
|
||||
shapes: SketchForgeMcpShapeSummary[];
|
||||
};
|
||||
|
||||
export type SketchForgeMcpEditorSummary = {
|
||||
editorId: string;
|
||||
editorNumber: number;
|
||||
projectId: string | null;
|
||||
projectName: string;
|
||||
url: string;
|
||||
focused: boolean;
|
||||
shapeCount: number;
|
||||
selectedCount: number;
|
||||
notice: string;
|
||||
lastError: string | null;
|
||||
lastSeen: number;
|
||||
};
|
||||
|
||||
export type SketchForgeMcpCommandName =
|
||||
| "get_scene"
|
||||
| "list_objects"
|
||||
| "select_objects"
|
||||
| "delete_objects"
|
||||
| "create_shape"
|
||||
| "import_mesh"
|
||||
| "update_object"
|
||||
| "align_objects"
|
||||
| "group_objects"
|
||||
| "ungroup_objects"
|
||||
| "boolean_cut"
|
||||
| "separate_parts"
|
||||
| "list_edges"
|
||||
| "apply_edge_treatment"
|
||||
| "inspect_errors"
|
||||
| "capture_image";
|
||||
|
||||
export type SketchForgeMcpCommand = {
|
||||
id: string;
|
||||
action: SketchForgeMcpCommandName;
|
||||
params: Record<string, unknown>;
|
||||
createdAt: number;
|
||||
};
|
||||
|
||||
export type SketchForgeMcpCommandResult = {
|
||||
commandId: string;
|
||||
ok: boolean;
|
||||
data?: unknown;
|
||||
error?: string;
|
||||
completedAt?: number;
|
||||
};
|
||||
|
||||
export type SketchForgeMcpHeartbeatPayload = {
|
||||
type: "heartbeat";
|
||||
editor: Omit<SketchForgeMcpEditorSummary, "lastSeen">;
|
||||
};
|
||||
|
||||
export type SketchForgeMcpPollPayload = {
|
||||
type: "poll";
|
||||
editorId: string;
|
||||
};
|
||||
|
||||
export type SketchForgeMcpResultPayload = {
|
||||
type: "result";
|
||||
editorId: string;
|
||||
result: SketchForgeMcpCommandResult;
|
||||
};
|
||||
|
||||
export type SketchForgeMcpDispatchPayload = {
|
||||
type: "command";
|
||||
editorId?: string;
|
||||
editorNumber?: number;
|
||||
action: SketchForgeMcpCommandName;
|
||||
params?: Record<string, unknown>;
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
export type SketchForgeMcpApiPayload =
|
||||
| SketchForgeMcpHeartbeatPayload
|
||||
| SketchForgeMcpPollPayload
|
||||
| SketchForgeMcpResultPayload
|
||||
| SketchForgeMcpDispatchPayload;
|
||||
@@ -0,0 +1,143 @@
|
||||
import type {
|
||||
SketchForgeMcpCommand,
|
||||
SketchForgeMcpCommandName,
|
||||
SketchForgeMcpCommandResult,
|
||||
SketchForgeMcpEditorSummary,
|
||||
} from "@/lib/sketchforgeMcpProtocol";
|
||||
import { SKETCHFORGE_MCP_STALE_MS } from "@/lib/sketchforgeMcpProtocol";
|
||||
|
||||
type PendingCommand = {
|
||||
editorId: string;
|
||||
resolve: (value: SketchForgeMcpCommandResult) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
type SketchForgeMcpStore = {
|
||||
editors: Map<string, SketchForgeMcpEditorSummary>;
|
||||
queues: Map<string, SketchForgeMcpCommand[]>;
|
||||
pending: Map<string, PendingCommand>;
|
||||
};
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var __sketchforgeMcpStore: SketchForgeMcpStore | undefined;
|
||||
}
|
||||
|
||||
function store() {
|
||||
globalThis.__sketchforgeMcpStore ??= {
|
||||
editors: new Map<string, SketchForgeMcpEditorSummary>(),
|
||||
queues: new Map<string, SketchForgeMcpCommand[]>(),
|
||||
pending: new Map<string, PendingCommand>(),
|
||||
};
|
||||
return globalThis.__sketchforgeMcpStore;
|
||||
}
|
||||
|
||||
function createCommandId() {
|
||||
return globalThis.crypto?.randomUUID?.() ?? `sketchforge-mcp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
function prune(current = Date.now()) {
|
||||
const state = store();
|
||||
for (const [editorId, editor] of state.editors) {
|
||||
if (current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
|
||||
continue;
|
||||
}
|
||||
state.editors.delete(editorId);
|
||||
state.queues.delete(editorId);
|
||||
for (const [commandId, pending] of state.pending) {
|
||||
if (pending.editorId !== editorId) {
|
||||
continue;
|
||||
}
|
||||
clearTimeout(pending.timer);
|
||||
state.pending.delete(commandId);
|
||||
pending.resolve({
|
||||
commandId,
|
||||
ok: false,
|
||||
error: `SketchForge editor ${editor.editorNumber} is no longer open`,
|
||||
completedAt: current,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function registerSketchForgeMcpEditor(editor: Omit<SketchForgeMcpEditorSummary, "lastSeen">) {
|
||||
const current = Date.now();
|
||||
prune(current);
|
||||
const state = store();
|
||||
state.editors.set(editor.editorId, { ...editor, lastSeen: current });
|
||||
state.queues.set(editor.editorId, state.queues.get(editor.editorId) ?? []);
|
||||
}
|
||||
|
||||
export function listSketchForgeMcpEditors() {
|
||||
prune();
|
||||
return [...store().editors.values()].sort((a, b) => a.editorNumber - b.editorNumber);
|
||||
}
|
||||
|
||||
export function pollSketchForgeMcpCommand(editorId: string) {
|
||||
prune();
|
||||
const queue = store().queues.get(editorId);
|
||||
return queue?.shift() ?? null;
|
||||
}
|
||||
|
||||
export function completeSketchForgeMcpCommand(editorId: string, result: SketchForgeMcpCommandResult) {
|
||||
const state = store();
|
||||
const pending = state.pending.get(result.commandId);
|
||||
if (!pending || pending.editorId !== editorId) {
|
||||
return false;
|
||||
}
|
||||
clearTimeout(pending.timer);
|
||||
state.pending.delete(result.commandId);
|
||||
pending.resolve({ ...result, completedAt: result.completedAt ?? Date.now() });
|
||||
return true;
|
||||
}
|
||||
|
||||
export function dispatchSketchForgeMcpCommand({
|
||||
editorId,
|
||||
editorNumber,
|
||||
action,
|
||||
params = {},
|
||||
timeoutMs = 15000,
|
||||
}: {
|
||||
editorId?: string;
|
||||
editorNumber?: number;
|
||||
action: SketchForgeMcpCommandName;
|
||||
params?: Record<string, unknown>;
|
||||
timeoutMs?: number;
|
||||
}) {
|
||||
prune();
|
||||
const state = store();
|
||||
const editor =
|
||||
(editorId ? state.editors.get(editorId) : null) ??
|
||||
(typeof editorNumber === "number" ? [...state.editors.values()].find((candidate) => candidate.editorNumber === editorNumber) : null);
|
||||
if (!editor) {
|
||||
return Promise.resolve({
|
||||
commandId: "",
|
||||
ok: false,
|
||||
error: typeof editorNumber === "number" ? `No open SketchForge editor ${editorNumber}` : "No matching open SketchForge editor",
|
||||
completedAt: Date.now(),
|
||||
} satisfies SketchForgeMcpCommandResult);
|
||||
}
|
||||
|
||||
const command: SketchForgeMcpCommand = {
|
||||
id: createCommandId(),
|
||||
action,
|
||||
params,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const queue = state.queues.get(editor.editorId) ?? [];
|
||||
queue.push(command);
|
||||
state.queues.set(editor.editorId, queue);
|
||||
|
||||
return new Promise<SketchForgeMcpCommandResult>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
state.pending.delete(command.id);
|
||||
resolve({
|
||||
commandId: command.id,
|
||||
ok: false,
|
||||
error: `Timed out waiting for SketchForge editor ${editor.editorNumber}`,
|
||||
completedAt: Date.now(),
|
||||
});
|
||||
}, Math.max(1000, Math.min(timeoutMs, 60000)));
|
||||
state.pending.set(command.id, { editorId: editor.editorId, resolve, timer });
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { GridSize, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
|
||||
|
||||
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
|
||||
|
||||
@@ -42,6 +43,7 @@ export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_S
|
||||
|
||||
export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWorkspaceSettings = DEFAULT_WORKPLANE_WORKSPACE): WorkplaneWorkspaceSettings {
|
||||
const candidate = value && typeof value === "object" ? (value as Partial<WorkplaneWorkspaceSettings>) : {};
|
||||
const units = stringOrDefault(candidate.units, fallback.units);
|
||||
return {
|
||||
width: numberOrDefault(candidate.width, fallback.width),
|
||||
depth: numberOrDefault(candidate.depth, fallback.depth),
|
||||
@@ -53,8 +55,8 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
|
||||
showGrid: booleanOrDefault(candidate.showGrid, fallback.showGrid),
|
||||
cruiseShapes: booleanOrDefault(candidate.cruiseShapes, fallback.cruiseShapes),
|
||||
zoomSpeed: numberOrDefault(candidate.zoomSpeed, fallback.zoomSpeed),
|
||||
units: stringOrDefault(candidate.units, fallback.units),
|
||||
scale: stringOrDefault(candidate.scale, fallback.scale),
|
||||
units,
|
||||
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
|
||||
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -167,6 +167,7 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
|
||||
a.edgeResizeMode === b.edgeResizeMode &&
|
||||
a.cadBrep === b.cadBrep &&
|
||||
a.cadBrepFrame === b.cadBrepFrame &&
|
||||
a.cadPrimitiveFrame === b.cadPrimitiveFrame &&
|
||||
a.groupedShapes === b.groupedShapes &&
|
||||
a.groupedBaseWidth === b.groupedBaseWidth &&
|
||||
a.groupedBaseDepth === b.groupedBaseDepth &&
|
||||
|
||||
Reference in New Issue
Block a user