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
feat: improve shape tools and project previews
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
export const PROJECT_THUMBNAIL_IDLE_MS = 2_500;
|
||||
export const PROJECT_THUMBNAIL_MAX_WIDTH = 512;
|
||||
export const PROJECT_THUMBNAIL_MAX_HEIGHT = 320;
|
||||
|
||||
export type ProjectThumbnailSceneKey = {
|
||||
projectId: string;
|
||||
fingerprint: string;
|
||||
};
|
||||
|
||||
export function projectThumbnailDimensions(
|
||||
sourceWidth: number,
|
||||
sourceHeight: number,
|
||||
maxWidth = PROJECT_THUMBNAIL_MAX_WIDTH,
|
||||
maxHeight = PROJECT_THUMBNAIL_MAX_HEIGHT,
|
||||
) {
|
||||
const width = Math.max(1, Math.round(Number.isFinite(sourceWidth) ? sourceWidth : 1));
|
||||
const height = Math.max(1, Math.round(Number.isFinite(sourceHeight) ? sourceHeight : 1));
|
||||
const scale = Math.min(1, maxWidth / width, maxHeight / height);
|
||||
return {
|
||||
width: Math.max(1, Math.round(width * scale)),
|
||||
height: Math.max(1, Math.round(height * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
export function projectThumbnailSceneChanged(
|
||||
previous: ProjectThumbnailSceneKey | null,
|
||||
current: ProjectThumbnailSceneKey,
|
||||
) {
|
||||
return previous?.projectId === current.projectId && previous.fingerprint !== current.fingerprint;
|
||||
}
|
||||
@@ -1,7 +1,21 @@
|
||||
import { canonicalizeShape } from "@/lib/workplaneShapes";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import { DEFAULT_GEAR_CENTER_HOLE_SIZE, DEFAULT_GEAR_HELIX_ANGLE, DEFAULT_GEAR_HELIX_QUALITY, DEFAULT_GEAR_TEETH, DEFAULT_GEAR_TOOTH_SIZE, DEFAULT_GEAR_TYPE } from "@/lib/gearGeometry";
|
||||
import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
|
||||
import {
|
||||
DEFAULT_GEAR_CENTER_HOLE_SIZE,
|
||||
DEFAULT_GEAR_HELIX_ANGLE,
|
||||
DEFAULT_GEAR_HELIX_QUALITY,
|
||||
DEFAULT_GEAR_TEETH,
|
||||
DEFAULT_GEAR_TOOTH_SIZE,
|
||||
DEFAULT_GEAR_TYPE,
|
||||
normalizeGearCenterHoleSize,
|
||||
normalizeGearHelixAngle,
|
||||
normalizeGearHelixQuality,
|
||||
normalizeGearTeeth,
|
||||
normalizeGearToothSize,
|
||||
normalizeGearToothWidth,
|
||||
normalizeGearType,
|
||||
} from "@/lib/gearGeometry";
|
||||
import type { ShapeAsset, ShapeCustomization, ShapeKind, WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
|
||||
|
||||
@@ -20,6 +34,42 @@ export const toolbarShapeAssets: ToolbarShapeAsset[] = [
|
||||
{ id: "gear", name: "Gear", src: "assets/sketchforge/gear-types/spur.png", menuIcon: "assets/sketchforge/gear-types/spur.png", kind: "gear", color: "#6f7f8d" },
|
||||
];
|
||||
|
||||
export function shapeAssetDefaultDimensions(kind: ShapeKind) {
|
||||
const roundProfile = kind === "sphere" || kind === "torus" || kind === "ring" || kind === "halfSphere";
|
||||
const flatProfile = kind === "torus" || kind === "ring" || kind === "text" || kind === "gear";
|
||||
const size = kind === "gear" ? 30 : roundProfile ? 22 : 20;
|
||||
return {
|
||||
width: kind === "text" ? 86 : size,
|
||||
depth: kind === "text" ? 28 : size,
|
||||
height: kind === "gear" ? 6 : kind === "text" ? 10 : kind === "roundRoof" ? 10 : kind === "halfSphere" ? 11 : flatProfile ? 5 : 20,
|
||||
};
|
||||
}
|
||||
|
||||
export function shapeAssetSpecialDefaults(kind: ShapeKind, dimensions = shapeAssetDefaultDimensions(kind)): ShapeCustomization {
|
||||
if (kind === "cylinder") return { sides: 96 };
|
||||
if (kind === "sphere") return { steps: 24 };
|
||||
if (kind === "halfSphere") return { steps: 32 };
|
||||
if (kind === "cone") return { topRadius: 0, baseRadius: dimensions.width / 2, sides: 96 };
|
||||
if (kind === "pyramid") return { sides: 4 };
|
||||
if (kind === "roundRoof") return { sides: 64 };
|
||||
if (kind === "tube" || kind === "ring") return { bevel: 4 };
|
||||
if (kind === "text") return { text: "TEXT", font: "Multilanguage", bevel: 0, segments: 0 };
|
||||
if (kind === "gear") {
|
||||
const teeth = DEFAULT_GEAR_TEETH;
|
||||
const toothSize = normalizeGearToothSize(DEFAULT_GEAR_TOOTH_SIZE, dimensions.width, dimensions.depth);
|
||||
return {
|
||||
teeth,
|
||||
toothSize,
|
||||
toothWidth: normalizeGearToothWidth(undefined, dimensions.width, dimensions.depth, teeth),
|
||||
centerHoleSize: normalizeGearCenterHoleSize(DEFAULT_GEAR_CENTER_HOLE_SIZE, dimensions.width, dimensions.depth, toothSize),
|
||||
gearType: DEFAULT_GEAR_TYPE,
|
||||
helixAngle: DEFAULT_GEAR_HELIX_ANGLE,
|
||||
helixQuality: DEFAULT_GEAR_HELIX_QUALITY,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
|
||||
const width = shape.width ?? shape.size ?? 20;
|
||||
const depth = shape.depth ?? shape.size ?? 20;
|
||||
@@ -77,13 +127,18 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
|
||||
});
|
||||
}
|
||||
|
||||
export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape {
|
||||
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
|
||||
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text" || asset.kind === "gear";
|
||||
const size = asset.kind === "gear" ? 30 : roundProfile ? 22 : 20;
|
||||
const height = asset.kind === "gear" ? 6 : asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
|
||||
const width = asset.kind === "text" ? 86 : size;
|
||||
const depth = asset.kind === "text" ? 28 : size;
|
||||
export function makeShapeFromAsset(
|
||||
asset: ShapeAsset,
|
||||
point?: { x: number; z: number; elevation?: number },
|
||||
customization: ShapeCustomization = {},
|
||||
): WorkplaneShape {
|
||||
const defaults = shapeAssetDefaultDimensions(asset.kind);
|
||||
const width = customization.width ?? defaults.width;
|
||||
const depth = customization.depth ?? defaults.depth;
|
||||
const height = customization.height ?? defaults.height;
|
||||
const size = Math.max(width, depth);
|
||||
const gearTeeth = asset.kind === "gear" ? normalizeGearTeeth(customization.teeth ?? DEFAULT_GEAR_TEETH) : undefined;
|
||||
const gearToothSize = asset.kind === "gear" ? normalizeGearToothSize(customization.toothSize ?? DEFAULT_GEAR_TOOTH_SIZE, width, depth) : undefined;
|
||||
|
||||
return {
|
||||
id: createLocalId(asset.id),
|
||||
@@ -102,20 +157,23 @@ export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: nu
|
||||
rotationX: 0,
|
||||
rotationZ: 0,
|
||||
radius: asset.kind === "box" ? 0 : undefined,
|
||||
text: asset.kind === "text" ? "TEXT" : undefined,
|
||||
font: asset.kind === "text" ? "Multilanguage" : undefined,
|
||||
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? 24 : asset.kind === "halfSphere" ? 32 : undefined,
|
||||
sides: asset.kind === "cylinder" || asset.kind === "cone" ? 96 : asset.kind === "roundRoof" ? 64 : asset.kind === "pyramid" ? 4 : undefined,
|
||||
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? 4 : undefined,
|
||||
segments: asset.kind === "cylinder" ? 1 : undefined,
|
||||
topRadius: asset.kind === "cone" ? 0 : undefined,
|
||||
baseRadius: asset.kind === "cone" ? size / 2 : undefined,
|
||||
teeth: asset.kind === "gear" ? DEFAULT_GEAR_TEETH : undefined,
|
||||
toothSize: asset.kind === "gear" ? DEFAULT_GEAR_TOOTH_SIZE : undefined,
|
||||
centerHoleSize: asset.kind === "gear" ? DEFAULT_GEAR_CENTER_HOLE_SIZE : undefined,
|
||||
gearType: asset.kind === "gear" ? DEFAULT_GEAR_TYPE : undefined,
|
||||
helixAngle: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_ANGLE : undefined,
|
||||
helixQuality: asset.kind === "gear" ? DEFAULT_GEAR_HELIX_QUALITY : undefined,
|
||||
text: asset.kind === "text" ? customization.text ?? "TEXT" : undefined,
|
||||
font: asset.kind === "text" ? customization.font ?? "Multilanguage" : undefined,
|
||||
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? customization.steps ?? 24 : asset.kind === "halfSphere" ? customization.steps ?? 32 : undefined,
|
||||
sides: asset.kind === "cylinder" || asset.kind === "cone" ? customization.sides ?? 96 : asset.kind === "roundRoof" ? customization.sides ?? 64 : asset.kind === "pyramid" ? customization.sides ?? 4 : undefined,
|
||||
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? customization.bevel ?? 4 : asset.kind === "text" ? customization.bevel : undefined,
|
||||
segments: asset.kind === "cylinder" ? 1 : asset.kind === "text" ? customization.segments : undefined,
|
||||
topRadius: asset.kind === "cone" ? customization.topRadius ?? 0 : undefined,
|
||||
baseRadius: asset.kind === "cone" ? customization.baseRadius ?? width / 2 : undefined,
|
||||
teeth: gearTeeth,
|
||||
toothSize: gearToothSize,
|
||||
toothWidth: asset.kind === "gear" && customization.toothWidth !== undefined
|
||||
? normalizeGearToothWidth(customization.toothWidth, width, depth, gearTeeth)
|
||||
: undefined,
|
||||
centerHoleSize: asset.kind === "gear" ? normalizeGearCenterHoleSize(customization.centerHoleSize ?? DEFAULT_GEAR_CENTER_HOLE_SIZE, width, depth, gearToothSize) : undefined,
|
||||
gearType: asset.kind === "gear" ? normalizeGearType(customization.gearType ?? DEFAULT_GEAR_TYPE) : undefined,
|
||||
helixAngle: asset.kind === "gear" ? normalizeGearHelixAngle(customization.helixAngle ?? DEFAULT_GEAR_HELIX_ANGLE) : undefined,
|
||||
helixQuality: asset.kind === "gear" ? normalizeGearHelixQuality(customization.helixQuality ?? DEFAULT_GEAR_HELIX_QUALITY) : undefined,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
};
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { ManifoldToplevel } from "manifold-3d";
|
||||
import type { SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment } from "@/types/sketchforge";
|
||||
import { MAX_HIGH_RESOLUTION_SIDES } from "@/lib/workplaneSettings";
|
||||
|
||||
export const DEFAULT_SKETCH_REVOLVE_SETTINGS: SketchRevolveSettings = {
|
||||
startAngle: 0,
|
||||
sweepAngle: 360,
|
||||
sides: 64,
|
||||
quality: 6,
|
||||
thickness: 1,
|
||||
};
|
||||
|
||||
type OrderedStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
|
||||
@@ -36,9 +36,8 @@ export function normalizeSketchRevolveSettings(settings?: Partial<SketchRevolveS
|
||||
return {
|
||||
startAngle: ((finiteOr(settings?.startAngle, DEFAULT_SKETCH_REVOLVE_SETTINGS.startAngle) % 360) + 360) % 360,
|
||||
sweepAngle,
|
||||
sides: Math.round(clamp(finiteOr(settings?.sides, DEFAULT_SKETCH_REVOLVE_SETTINGS.sides), 3, 128)),
|
||||
sides: Math.round(clamp(finiteOr(settings?.sides, DEFAULT_SKETCH_REVOLVE_SETTINGS.sides), 3, MAX_HIGH_RESOLUTION_SIDES)),
|
||||
quality: Math.round(clamp(finiteOr(settings?.quality, DEFAULT_SKETCH_REVOLVE_SETTINGS.quality), 1, 10)),
|
||||
thickness: clamp(finiteOr(settings?.thickness, DEFAULT_SKETCH_REVOLVE_SETTINGS.thickness), 0.1, 20),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -152,34 +151,6 @@ function clipClosedPathToRevolveSide(points: SampledPoint[]) {
|
||||
return compactSampledPath(clipped);
|
||||
}
|
||||
|
||||
function clipOpenPathToRevolveSide(points: SampledPoint[]) {
|
||||
const paths: SampledPoint[][] = [];
|
||||
let current: SampledPoint[] = [];
|
||||
const finishCurrent = () => {
|
||||
const compact = compactSampledPath(current);
|
||||
if (compact.length >= 2) paths.push(compact);
|
||||
current = [];
|
||||
};
|
||||
for (let index = 0; index < points.length - 1; index += 1) {
|
||||
const from = points[index];
|
||||
const to = points[index + 1];
|
||||
const fromInside = from.x <= 0;
|
||||
const toInside = to.x <= 0;
|
||||
if (fromInside && toInside) {
|
||||
if (current.length === 0) current.push(from);
|
||||
current.push(to);
|
||||
} else if (fromInside) {
|
||||
if (current.length === 0) current.push(from);
|
||||
current.push(axisIntersection(from, to));
|
||||
finishCurrent();
|
||||
} else if (toInside) {
|
||||
current = [axisIntersection(from, to), to];
|
||||
}
|
||||
}
|
||||
finishCurrent();
|
||||
return paths;
|
||||
}
|
||||
|
||||
function distance(a: Point2, b: Point2) {
|
||||
return Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
}
|
||||
@@ -193,55 +164,19 @@ function compactPolygon(points: Point2[]) {
|
||||
return compact;
|
||||
}
|
||||
|
||||
function strokeOpenPath(points: Point2[], thickness: number) {
|
||||
if (points.length < 2) return [];
|
||||
const half = thickness / 2;
|
||||
const normals: Point2[] = [];
|
||||
for (let index = 0; index < points.length - 1; index += 1) {
|
||||
const dx = points[index + 1][0] - points[index][0];
|
||||
const dy = points[index + 1][1] - points[index][1];
|
||||
const length = Math.hypot(dx, dy);
|
||||
normals.push(length > 1e-8 ? [-dy / length, dx / length] : [0, 0]);
|
||||
}
|
||||
const offsetAt = (index: number): Point2 => {
|
||||
const previous = normals[Math.max(0, index - 1)];
|
||||
const next = normals[Math.min(normals.length - 1, index)];
|
||||
const sumX = previous[0] + next[0];
|
||||
const sumY = previous[1] + next[1];
|
||||
const sumLength = Math.hypot(sumX, sumY);
|
||||
if (sumLength <= 1e-8) return [next[0] * half, next[1] * half];
|
||||
const unit: Point2 = [sumX / sumLength, sumY / sumLength];
|
||||
const projection = Math.abs(unit[0] * next[0] + unit[1] * next[1]);
|
||||
const miter = Math.min(half * 4, half / Math.max(0.25, projection));
|
||||
return [unit[0] * miter, unit[1] * miter];
|
||||
};
|
||||
const left: Point2[] = [];
|
||||
const right: Point2[] = [];
|
||||
points.forEach((point, index) => {
|
||||
const offset = offsetAt(index);
|
||||
left.push([point[0] + offset[0], point[1] + offset[1]]);
|
||||
right.push([point[0] - offset[0], point[1] - offset[1]]);
|
||||
});
|
||||
return compactPolygon([...left, ...right.reverse()]);
|
||||
}
|
||||
|
||||
export function sketchProfileToRevolvePolygons(profile: SketchProfile, settings?: Partial<SketchRevolveSettings>) {
|
||||
const normalized = normalizeSketchRevolveSettings(settings);
|
||||
const paths = orderedPaths(profile).flatMap((path) => {
|
||||
const paths = orderedPaths(profile).filter((path) => path.closed).flatMap((path) => {
|
||||
const sampled = samplePath(path, normalized.quality);
|
||||
if (path.closed) {
|
||||
const clipped = clipClosedPathToRevolveSide(sampled);
|
||||
return clipped.length >= 3 ? [{ closed: true, points: clipped }] : [];
|
||||
}
|
||||
return clipOpenPathToRevolveSide(sampled).map((points) => ({ closed: false, points }));
|
||||
const clipped = clipClosedPathToRevolveSide(sampled);
|
||||
return clipped.length >= 3 ? [clipped] : [];
|
||||
});
|
||||
if (paths.length === 0) return [];
|
||||
const maxZ = Math.max(...paths.flatMap((entry) => entry.points.map((point) => point.z)));
|
||||
const maxZ = Math.max(...paths.flatMap((points) => points.map((point) => point.z)));
|
||||
const toSectionPoint = (point: SampledPoint): Point2 => [-point.x, maxZ - point.z];
|
||||
return paths.flatMap(({ closed, points }) => {
|
||||
return paths.flatMap((points) => {
|
||||
const sectionPoints = compactPolygon(points.map(toSectionPoint));
|
||||
const polygon = closed ? sectionPoints : strokeOpenPath(sectionPoints, normalized.thickness).map((point) => [Math.max(0, point[0]), point[1]] as Point2);
|
||||
return polygon.length >= 3 ? [compactPolygon(polygon)] : [];
|
||||
return sectionPoints.length >= 3 ? [sectionPoints] : [];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -261,7 +196,7 @@ function dispose(value: unknown) {
|
||||
export function buildSketchRevolveMesh(runtime: ManifoldToplevel, profile: SketchProfile, requestedSettings?: Partial<SketchRevolveSettings>): SketchRevolveMesh {
|
||||
const settings = normalizeSketchRevolveSettings(requestedSettings);
|
||||
const polygons = sketchProfileToRevolvePolygons(profile, settings);
|
||||
if (polygons.length === 0) throw new Error("Draw at least one connected profile on the left side of the revolve axis");
|
||||
if (polygons.length === 0) throw new Error("Draw at least one closed profile on the left side of the revolve axis");
|
||||
const disposable: unknown[] = [];
|
||||
try {
|
||||
const section = new runtime.CrossSection(polygons, "EvenOdd");
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { SketchPoint, SketchProfile } from "@/types/sketchforge";
|
||||
|
||||
export type SketchGeometrySelection = {
|
||||
pointIds: readonly string[];
|
||||
segmentIds: readonly string[];
|
||||
imageIds?: readonly string[];
|
||||
};
|
||||
|
||||
export function selectedClosedSketchPoints(
|
||||
profile: SketchProfile,
|
||||
selection: SketchGeometrySelection,
|
||||
): SketchPoint[] | null {
|
||||
if (selection.imageIds?.length) return null;
|
||||
|
||||
const pointIds = new Set(selection.pointIds);
|
||||
const segmentIds = new Set(selection.segmentIds);
|
||||
if (pointIds.size < 3 || segmentIds.size !== pointIds.size) return null;
|
||||
|
||||
const selectedPoints = profile.points.filter((point) => pointIds.has(point.id));
|
||||
if (selectedPoints.length !== pointIds.size) return null;
|
||||
|
||||
const segmentById = new Map(profile.segments.map((segment) => [segment.id, segment]));
|
||||
const adjacency = new Map([...pointIds].map((pointId) => [pointId, new Set<string>()]));
|
||||
|
||||
for (const segmentId of segmentIds) {
|
||||
const segment = segmentById.get(segmentId);
|
||||
if (
|
||||
!segment
|
||||
|| segment.startId === segment.endId
|
||||
|| !pointIds.has(segment.startId)
|
||||
|| !pointIds.has(segment.endId)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
adjacency.get(segment.startId)?.add(segment.endId);
|
||||
adjacency.get(segment.endId)?.add(segment.startId);
|
||||
}
|
||||
|
||||
if ([...adjacency.values()].some((neighbors) => neighbors.size !== 2)) return null;
|
||||
|
||||
const unvisited = new Set(pointIds);
|
||||
while (unvisited.size > 0) {
|
||||
const start = unvisited.values().next().value as string | undefined;
|
||||
if (!start) return null;
|
||||
const stack = [start];
|
||||
let componentSize = 0;
|
||||
while (stack.length > 0) {
|
||||
const pointId = stack.pop();
|
||||
if (!pointId || !unvisited.delete(pointId)) continue;
|
||||
componentSize += 1;
|
||||
adjacency.get(pointId)?.forEach((neighborId) => {
|
||||
if (unvisited.has(neighborId)) stack.push(neighborId);
|
||||
});
|
||||
}
|
||||
if (componentSize < 3) return null;
|
||||
}
|
||||
|
||||
return selectedPoints;
|
||||
}
|
||||
|
||||
export function rotateSketchPoints(points: readonly SketchPoint[], degrees = 45): SketchPoint[] {
|
||||
if (points.length === 0) return [];
|
||||
|
||||
const minX = Math.min(...points.map((point) => point.x));
|
||||
const maxX = Math.max(...points.map((point) => point.x));
|
||||
const minZ = Math.min(...points.map((point) => point.z));
|
||||
const maxZ = Math.max(...points.map((point) => point.z));
|
||||
const pivot = { x: (minX + maxX) / 2, z: (minZ + maxZ) / 2 };
|
||||
const radians = degrees * Math.PI / 180;
|
||||
const cosine = Math.cos(radians);
|
||||
const sine = Math.sin(radians);
|
||||
const rotatePosition = (position: { x: number; z: number }) => {
|
||||
const deltaX = position.x - pivot.x;
|
||||
const deltaZ = position.z - pivot.z;
|
||||
return {
|
||||
x: pivot.x + deltaX * cosine - deltaZ * sine,
|
||||
z: pivot.z + deltaX * sine + deltaZ * cosine,
|
||||
};
|
||||
};
|
||||
|
||||
return points.map((point) => ({
|
||||
...point,
|
||||
...rotatePosition(point),
|
||||
handleIn: point.handleIn ? rotatePosition(point.handleIn) : undefined,
|
||||
handleOut: point.handleOut ? rotatePosition(point.handleOut) : undefined,
|
||||
}));
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
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 const SKETCHFORGE_MCP_STALE_MS = 15_000;
|
||||
export const SKETCHFORGE_MCP_HEARTBEAT_MS = 5_000;
|
||||
export const SKETCHFORGE_MCP_LONG_POLL_TIMEOUT_MS = 25_000;
|
||||
export const SKETCHFORGE_MCP_POLL_RETRY_MS = 1_000;
|
||||
|
||||
export type SketchForgeMcpViewFace = "current" | "home" | "top" | "bottom" | "front" | "back" | "right" | "left";
|
||||
|
||||
|
||||
@@ -12,10 +12,18 @@ type PendingCommand = {
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
type PollWaiter = {
|
||||
resolve: (command: SketchForgeMcpCommand | null) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
signal?: AbortSignal;
|
||||
onAbort?: () => void;
|
||||
};
|
||||
|
||||
type SketchForgeMcpStore = {
|
||||
editors: Map<string, SketchForgeMcpEditorSummary>;
|
||||
queues: Map<string, SketchForgeMcpCommand[]>;
|
||||
pending: Map<string, PendingCommand>;
|
||||
pollWaiters: Map<string, PollWaiter>;
|
||||
};
|
||||
|
||||
declare global {
|
||||
@@ -24,22 +32,42 @@ declare global {
|
||||
}
|
||||
|
||||
function store() {
|
||||
globalThis.__sketchforgeMcpStore ??= {
|
||||
const state = globalThis.__sketchforgeMcpStore ??= {
|
||||
editors: new Map<string, SketchForgeMcpEditorSummary>(),
|
||||
queues: new Map<string, SketchForgeMcpCommand[]>(),
|
||||
pending: new Map<string, PendingCommand>(),
|
||||
pollWaiters: new Map<string, PollWaiter>(),
|
||||
};
|
||||
return globalThis.__sketchforgeMcpStore;
|
||||
// Development hot reload can preserve a store created before pollWaiters
|
||||
// existed. Initialize it lazily so an already-open editor keeps working.
|
||||
state.pollWaiters ??= new Map<string, PollWaiter>();
|
||||
return state;
|
||||
}
|
||||
|
||||
function createCommandId() {
|
||||
return globalThis.crypto?.randomUUID?.() ?? `sketchforge-mcp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
function settlePollWaiter(
|
||||
state: SketchForgeMcpStore,
|
||||
editorId: string,
|
||||
waiter: PollWaiter,
|
||||
command: SketchForgeMcpCommand | null,
|
||||
) {
|
||||
if (state.pollWaiters.get(editorId) !== waiter) return false;
|
||||
state.pollWaiters.delete(editorId);
|
||||
clearTimeout(waiter.timer);
|
||||
if (waiter.signal && waiter.onAbort) {
|
||||
waiter.signal.removeEventListener("abort", waiter.onAbort);
|
||||
}
|
||||
waiter.resolve(command);
|
||||
return true;
|
||||
}
|
||||
|
||||
function prune(current = Date.now()) {
|
||||
const state = store();
|
||||
for (const [editorId, editor] of state.editors) {
|
||||
if (current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
|
||||
if (state.pollWaiters.has(editorId) || current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
|
||||
continue;
|
||||
}
|
||||
state.editors.delete(editorId);
|
||||
@@ -79,6 +107,32 @@ export function pollSketchForgeMcpCommand(editorId: string) {
|
||||
return queue?.shift() ?? null;
|
||||
}
|
||||
|
||||
export function waitForSketchForgeMcpCommand(
|
||||
editorId: string,
|
||||
{ timeoutMs, signal }: { timeoutMs: number; signal?: AbortSignal },
|
||||
) {
|
||||
const state = store();
|
||||
const current = Date.now();
|
||||
const editor = state.editors.get(editorId);
|
||||
if (editor) state.editors.set(editorId, { ...editor, lastSeen: current });
|
||||
prune(current);
|
||||
const queued = state.queues.get(editorId)?.shift();
|
||||
if (queued) return Promise.resolve(queued);
|
||||
if (signal?.aborted) return Promise.resolve(null);
|
||||
|
||||
const existing = state.pollWaiters.get(editorId);
|
||||
if (existing) settlePollWaiter(state, editorId, existing, null);
|
||||
|
||||
return new Promise<SketchForgeMcpCommand | null>((resolve) => {
|
||||
let waiter: PollWaiter;
|
||||
const timer = setTimeout(() => settlePollWaiter(state, editorId, waiter, null), Math.max(1_000, Math.min(timeoutMs, 30_000)));
|
||||
const onAbort = () => settlePollWaiter(state, editorId, waiter, null);
|
||||
waiter = { resolve, timer, signal, onAbort };
|
||||
state.pollWaiters.set(editorId, waiter);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
export function completeSketchForgeMcpCommand(editorId: string, result: SketchForgeMcpCommandResult) {
|
||||
const state = store();
|
||||
const pending = state.pending.get(result.commandId);
|
||||
@@ -124,9 +178,12 @@ export function dispatchSketchForgeMcpCommand({
|
||||
params,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const queue = state.queues.get(editor.editorId) ?? [];
|
||||
queue.push(command);
|
||||
state.queues.set(editor.editorId, queue);
|
||||
const waiter = state.pollWaiters.get(editor.editorId);
|
||||
if (!waiter || !settlePollWaiter(state, editor.editorId, waiter, command)) {
|
||||
const queue = state.queues.get(editor.editorId) ?? [];
|
||||
queue.push(command);
|
||||
state.queues.set(editor.editorId, queue);
|
||||
}
|
||||
|
||||
return new Promise<SketchForgeMcpCommandResult>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
|
||||
@@ -872,7 +872,7 @@ function validateShapeDefinition(definition: Record<string, unknown>, label: str
|
||||
}
|
||||
if (definition.sketchRevolve !== undefined) {
|
||||
const settings = objectRecord(definition.sketchRevolve, `${label}.sketchRevolve`);
|
||||
["startAngle", "sweepAngle", "sides", "quality", "thickness"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
|
||||
["startAngle", "sweepAngle", "sides", "quality"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
|
||||
}
|
||||
if (kind === "gear") {
|
||||
const teeth = finiteNumber(definition.teeth, `${label}.teeth`);
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, ShapeCustomization, ShapeCustomizationMap, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
|
||||
import { DEFAULT_WORKPLANE_GRID_COLOR } from "@/lib/workplaneGrid";
|
||||
|
||||
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
|
||||
export const MIN_CUSTOM_SHAPE_DIMENSION = 0.01;
|
||||
export const MAX_CUSTOM_SHAPE_DIMENSION = 2000;
|
||||
export const MAX_HIGH_RESOLUTION_SIDES = 512;
|
||||
|
||||
export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
|
||||
width: 200,
|
||||
@@ -21,9 +24,14 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
|
||||
scale: "1:1 (millimeters)",
|
||||
accuracy: 2,
|
||||
historyLimit: 100,
|
||||
shapeCustomizations: {},
|
||||
};
|
||||
|
||||
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
||||
const customizableShapeKinds: ShapeKind[] = [
|
||||
"box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
|
||||
"halfSphere", "torus", "tube", "gear", "ring", "wedge", "polygon", "icosahedron", "mesh",
|
||||
];
|
||||
|
||||
function numberOrDefault(value: unknown, fallback: number) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
||||
@@ -51,6 +59,88 @@ function historyLimitOrDefault(value: unknown, fallback: HistoryRetentionLimit):
|
||||
return Math.min(5000, Math.max(1, Math.round(value)));
|
||||
}
|
||||
|
||||
function optionalShapeDimension(value: unknown, fallback: number | undefined) {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
||||
return Math.min(MAX_CUSTOM_SHAPE_DIMENSION, Math.max(MIN_CUSTOM_SHAPE_DIMENSION, value));
|
||||
}
|
||||
|
||||
function optionalShapeNumber(value: unknown, fallback: number | undefined, min: number, max: number, integer = false) {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
||||
const normalized = Math.min(max, Math.max(min, value));
|
||||
return integer ? Math.round(normalized) : normalized;
|
||||
}
|
||||
|
||||
function optionalShapeText(value: unknown, fallback: string | undefined, maxLength: number) {
|
||||
if (value === undefined) return fallback;
|
||||
if (typeof value !== "string") return fallback;
|
||||
return value.slice(0, maxLength) || " ";
|
||||
}
|
||||
|
||||
export function normalizeShapeCustomizations(value: unknown, fallback: ShapeCustomizationMap = {}): ShapeCustomizationMap {
|
||||
const candidate = value && typeof value === "object" ? value as Partial<Record<ShapeKind, unknown>> : {};
|
||||
const normalized: ShapeCustomizationMap = {};
|
||||
customizableShapeKinds.forEach((kind) => {
|
||||
const raw = candidate[kind];
|
||||
const source = raw && typeof raw === "object" ? raw as Partial<ShapeCustomization> : {};
|
||||
const fallbackEntry = fallback[kind];
|
||||
const entry: ShapeCustomization = {
|
||||
width: optionalShapeDimension(source.width, fallbackEntry?.width),
|
||||
depth: optionalShapeDimension(source.depth, fallbackEntry?.depth),
|
||||
height: optionalShapeDimension(source.height, fallbackEntry?.height),
|
||||
maxDimension: optionalShapeDimension(source.maxDimension, fallbackEntry?.maxDimension),
|
||||
};
|
||||
if (kind === "sphere" || kind === "halfSphere") {
|
||||
entry.steps = optionalShapeNumber(source.steps, fallbackEntry?.steps, 6, 64, true);
|
||||
}
|
||||
if (kind === "cylinder" || kind === "cone") {
|
||||
entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 3, MAX_HIGH_RESOLUTION_SIDES, true);
|
||||
} else if (kind === "pyramid") {
|
||||
entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 3, 24, true);
|
||||
} else if (kind === "roundRoof") {
|
||||
entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 4, MAX_HIGH_RESOLUTION_SIDES, true);
|
||||
}
|
||||
if (kind === "cone") {
|
||||
entry.topRadius = optionalShapeNumber(source.topRadius, fallbackEntry?.topRadius, 0, MAX_CUSTOM_SHAPE_DIMENSION / 2);
|
||||
entry.baseRadius = optionalShapeNumber(source.baseRadius, fallbackEntry?.baseRadius, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION / 2);
|
||||
}
|
||||
if (kind === "tube" || kind === "ring") {
|
||||
entry.bevel = optionalShapeNumber(source.bevel, fallbackEntry?.bevel, 0.5, 20);
|
||||
}
|
||||
if (kind === "text") {
|
||||
entry.text = optionalShapeText(source.text, fallbackEntry?.text, 24);
|
||||
entry.font = source.font === undefined
|
||||
? fallbackEntry?.font
|
||||
: ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"].includes(source.font)
|
||||
? source.font
|
||||
: fallbackEntry?.font;
|
||||
entry.bevel = optionalShapeNumber(source.bevel, fallbackEntry?.bevel, 0, 8);
|
||||
entry.segments = optionalShapeNumber(source.segments, fallbackEntry?.segments, 0, 24, true);
|
||||
}
|
||||
if (kind === "gear") {
|
||||
entry.teeth = optionalShapeNumber(source.teeth, fallbackEntry?.teeth, 6, 64, true);
|
||||
entry.toothSize = optionalShapeNumber(source.toothSize, fallbackEntry?.toothSize, 0.2, MAX_CUSTOM_SHAPE_DIMENSION / 2);
|
||||
entry.toothWidth = optionalShapeNumber(source.toothWidth, fallbackEntry?.toothWidth, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION);
|
||||
entry.centerHoleSize = optionalShapeNumber(source.centerHoleSize, fallbackEntry?.centerHoleSize, 0, MAX_CUSTOM_SHAPE_DIMENSION);
|
||||
entry.gearType = source.gearType === undefined
|
||||
? fallbackEntry?.gearType
|
||||
: source.gearType === "spur" || source.gearType === "helical" || source.gearType === "bevel"
|
||||
? source.gearType
|
||||
: fallbackEntry?.gearType;
|
||||
entry.helixAngle = optionalShapeNumber(source.helixAngle, fallbackEntry?.helixAngle, -45, 45);
|
||||
entry.helixQuality = optionalShapeNumber(source.helixQuality, fallbackEntry?.helixQuality, 4, 32, true);
|
||||
}
|
||||
const compact = Object.fromEntries(Object.entries(entry).filter(([, entryValue]) => entryValue !== undefined)) as ShapeCustomization;
|
||||
if (Object.keys(compact).length > 0) normalized[kind] = compact;
|
||||
});
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function shapeDimensionLimit(workspace: WorkplaneWorkspaceSettings, kind: ShapeKind, appDefault: number) {
|
||||
return workspace.shapeCustomizations[kind]?.maxDimension ?? appDefault;
|
||||
}
|
||||
|
||||
export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_SNAP_GRID): GridSize {
|
||||
return snapGridOptions.includes(value as GridSize) ? (value as GridSize) : fallback;
|
||||
}
|
||||
@@ -75,6 +165,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
|
||||
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
|
||||
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
|
||||
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
|
||||
shapeCustomizations: normalizeShapeCustomizations(candidate.shapeCustomizations, fallback.shapeCustomizations),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@ export function cleanNearZero(value: number, epsilon = 0.005) {
|
||||
return Math.abs(value) < epsilon ? 0 : value;
|
||||
}
|
||||
|
||||
export function shapeTransformShouldRemainEditable(shape: WorkplaneShape) {
|
||||
return shape.kind === "text" || Boolean(shape.groupedShapes?.length);
|
||||
}
|
||||
|
||||
export function cloneWorkplaneShapeTreeWithFreshIds(shape: WorkplaneShape, suffix: string): WorkplaneShape {
|
||||
return {
|
||||
...shape,
|
||||
@@ -213,6 +217,14 @@ export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
|
||||
if (shape.groupedShapes) {
|
||||
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
|
||||
}
|
||||
if (shape.sketchRevolve) {
|
||||
next.sketchRevolve = {
|
||||
startAngle: shape.sketchRevolve.startAngle,
|
||||
sweepAngle: shape.sketchRevolve.sweepAngle,
|
||||
sides: shape.sketchRevolve.sides,
|
||||
quality: shape.sketchRevolve.quality,
|
||||
};
|
||||
}
|
||||
if (shape.edgeTreatmentHistory) {
|
||||
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
|
||||
...entry,
|
||||
|
||||
Reference in New Issue
Block a user