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 modeling, exports, and hosted deployment
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Check, CloudUpload, Download, Eye, FolderOpen, X } from "lucide-react";
|
||||
import { Check, Circle as CircleIcon, CloudUpload, Download, Eye, FolderOpen, Hexagon as HexagonIcon, Square as SquareIcon, Triangle as TriangleIcon, X } from "lucide-react";
|
||||
import type manifoldModule from "manifold-3d";
|
||||
import type { ManifoldToplevel } from "manifold-3d";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -48,7 +48,7 @@ import {
|
||||
ToolbarVectorExportIcon,
|
||||
} from "./icons";
|
||||
import { WorkplaneViewport } from "./WorkplaneViewport";
|
||||
import { SketchWorkspace, type SketchMeasurement, type SketchSelection, type SketchTool } from "./SketchWorkspace";
|
||||
import { SketchWorkspace, type SketchMeasurement, type SketchPrimitive, type SketchSelection, type SketchTool } from "./SketchWorkspace";
|
||||
import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel";
|
||||
import {
|
||||
canonicalizeShape,
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
resizedImportedMeshPositions,
|
||||
serializeShapesForSync,
|
||||
shapeDepth,
|
||||
shapeHasTaper,
|
||||
shapeTaperScaleAt,
|
||||
shapeWidth,
|
||||
withHoleMode,
|
||||
workplaneShapesEqual,
|
||||
@@ -89,6 +91,7 @@ import { exportMeshesToObj } from "@/lib/objExport";
|
||||
import { importedShapeFromObj } from "@/lib/objImport";
|
||||
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
||||
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
|
||||
import { addLineIntersectionPoints, splitSketchSegment } from "@/lib/sketchPointRefinement";
|
||||
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
|
||||
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
|
||||
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
|
||||
@@ -1387,6 +1390,15 @@ function shapeFromCadMesh(
|
||||
mirrorY: undefined,
|
||||
mirrorZ: undefined,
|
||||
radius: undefined,
|
||||
// The CAD result is already generated from the final tapered surface. Do
|
||||
// not carry the parametric taper fields onto this baked mesh or the viewport
|
||||
// and subsequent mesh exports will apply the deformation a second time.
|
||||
taperTopWidth: undefined,
|
||||
taperTopDepth: undefined,
|
||||
taperBottomWidth: undefined,
|
||||
taperBottomDepth: undefined,
|
||||
taperTopScale: undefined,
|
||||
taperBottomScale: undefined,
|
||||
importedMesh: {
|
||||
positions: flattenedPositions,
|
||||
normals: flattenedNormals.length === flattenedPositions.length ? flattenedNormals : undefined,
|
||||
@@ -1618,6 +1630,11 @@ function groupedShapeWithComponentEdgeTreatment(
|
||||
) {
|
||||
if (
|
||||
!base.groupedShapes?.length ||
|
||||
// A tapered group is sent to CAD as one baked final mesh because the parent
|
||||
// deformation cannot be represented by its untapered child primitives.
|
||||
// Keep the treated result flattened instead of rebuilding a nested group
|
||||
// that would reintroduce the old pre-taper children.
|
||||
shapeHasTaper(base) ||
|
||||
!hasOneToOneCadComponentMapping(sourceParts.length, session.componentPreviews.map((component) => component.owner))
|
||||
) {
|
||||
return null;
|
||||
@@ -1758,6 +1775,18 @@ async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[]
|
||||
|
||||
function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData {
|
||||
const centerY = shape.height / 2;
|
||||
const tapered = shapeHasTaper(shape);
|
||||
let minLocalY = 0;
|
||||
let maxLocalY = 1;
|
||||
if (tapered && mesh.vertices.length) {
|
||||
minLocalY = Number.POSITIVE_INFINITY;
|
||||
maxLocalY = Number.NEGATIVE_INFINITY;
|
||||
mesh.vertices.forEach((vertex) => {
|
||||
minLocalY = Math.min(minLocalY, vertex[1]);
|
||||
maxLocalY = Math.max(maxLocalY, vertex[1]);
|
||||
});
|
||||
}
|
||||
const taperHeight = Math.max(1e-6, maxLocalY - minLocalY);
|
||||
const matrix = new THREE.Matrix4().makeRotationFromEuler(
|
||||
new THREE.Euler(
|
||||
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
|
||||
@@ -1773,7 +1802,10 @@ function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData {
|
||||
return {
|
||||
...mesh,
|
||||
vertices: mesh.vertices.map(([x, y, z]) => {
|
||||
const vertex = new THREE.Vector3(x * mirrorX, (y - centerY) * mirrorY, z * mirrorZ).applyMatrix4(matrix);
|
||||
const normalizedHeight = (y - minLocalY) / taperHeight;
|
||||
const widthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "width") : 1;
|
||||
const depthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "depth") : 1;
|
||||
const vertex = new THREE.Vector3(x * widthScale * mirrorX, (y - centerY) * mirrorY, z * depthScale * mirrorZ).applyMatrix4(matrix);
|
||||
return [vertex.x + shape.x, vertex.y + (shape.elevation ?? 0) + centerY, vertex.z + shape.z] as Vec3;
|
||||
}),
|
||||
faces: reversedWinding ? mesh.faces.map(([a, b, c]) => [a, c, b] as [number, number, number]) : mesh.faces,
|
||||
@@ -2334,6 +2366,10 @@ function shapeHasTransformToBake(shape: WorkplaneShape) {
|
||||
}
|
||||
|
||||
function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimitivePart | null {
|
||||
// Taper is a non-affine deformation, so an analytic primitive or stored BREP
|
||||
// cannot represent the final visible surface. Send the baked mesh to the CAD
|
||||
// worker instead so edge selection/treatment matches the viewport exactly.
|
||||
if (shapeHasTaper(shape)) return null;
|
||||
return cadModifierPrimitiveForBakedShape(shape)
|
||||
?? (shapeHasTransformToBake(shape) ? cadModifierPrimitiveForAnalyticBox(shape) : null);
|
||||
}
|
||||
@@ -2404,6 +2440,12 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
|
||||
mirrorX: undefined,
|
||||
mirrorY: undefined,
|
||||
mirrorZ: undefined,
|
||||
taperTopWidth: undefined,
|
||||
taperTopDepth: undefined,
|
||||
taperBottomWidth: undefined,
|
||||
taperBottomDepth: undefined,
|
||||
taperTopScale: undefined,
|
||||
taperBottomScale: undefined,
|
||||
importedMesh: {
|
||||
positions,
|
||||
baseWidth: rawWidth,
|
||||
@@ -6204,7 +6246,7 @@ export function SketchForgeEditor({
|
||||
|
||||
const commitSketchProfile = useCallback(
|
||||
(next: SketchProfile, message?: string) => {
|
||||
const snapshot = cloneSketchProfile(next);
|
||||
const snapshot = cloneSketchProfile(addLineIntersectionPoints(next, createLocalId));
|
||||
const current = sketchHistoryRef.current;
|
||||
const currentIndex = Math.min(sketchHistoryIndexRef.current, Math.max(0, current.length - 1));
|
||||
const trimmed = current.slice(0, currentIndex + 1);
|
||||
@@ -6341,6 +6383,10 @@ export function SketchForgeEditor({
|
||||
line: "Line: click points to draw straight segments",
|
||||
bezier: "Bézier: click and drag points to pull curve handles",
|
||||
smooth: "Smooth curve: click points to build a flowing path",
|
||||
rectangle: "Rectangle: drag across the sketch to create a closed rectangle",
|
||||
circle: "Circle: drag a bounding box to create a closed circle",
|
||||
triangle: "Triangle: drag a bounding box to create a closed triangle",
|
||||
hexagon: "Hexagon: drag a bounding box to create a closed hexagon",
|
||||
select: "Select: edit sketch geometry or place and scale reference images",
|
||||
refine: "Refine: click a segment to add a point, or a point to remove it",
|
||||
erase: "Erase: click a point or segment to remove it",
|
||||
@@ -6434,6 +6480,90 @@ export function SketchForgeEditor({
|
||||
[commitSketchProfile, connectSketchPoint, measureSketchPoint, sketchActivePointId, sketchProfile, sketchTool],
|
||||
);
|
||||
|
||||
const addSketchPrimitive = useCallback(
|
||||
(primitive: SketchPrimitive, center: { x: number; z: number } = { x: 0, z: 0 }) => {
|
||||
const cx = center.x;
|
||||
const cz = center.z;
|
||||
const width = 20;
|
||||
const depth = 20;
|
||||
const radius = width / 2;
|
||||
const minX = cx - width / 2;
|
||||
const maxX = cx + width / 2;
|
||||
const minZ = cz - depth / 2;
|
||||
const maxZ = cz + depth / 2;
|
||||
let points: SketchPoint[] = [];
|
||||
let segments: SketchSegment[] = [];
|
||||
|
||||
if (primitive === "circle") {
|
||||
const kappa = 0.5522847498307936;
|
||||
const right: SketchPoint = {
|
||||
id: createLocalId("sketch-point"), x: cx + radius, z: cz, mode: "smooth",
|
||||
handleIn: { x: cx + radius, z: cz - kappa * radius },
|
||||
handleOut: { x: cx + radius, z: cz + kappa * radius },
|
||||
};
|
||||
const bottom: SketchPoint = {
|
||||
id: createLocalId("sketch-point"), x: cx, z: cz + radius, mode: "smooth",
|
||||
handleIn: { x: cx + kappa * radius, z: cz + radius },
|
||||
handleOut: { x: cx - kappa * radius, z: cz + radius },
|
||||
};
|
||||
const left: SketchPoint = {
|
||||
id: createLocalId("sketch-point"), x: cx - radius, z: cz, mode: "smooth",
|
||||
handleIn: { x: cx - radius, z: cz + kappa * radius },
|
||||
handleOut: { x: cx - radius, z: cz - kappa * radius },
|
||||
};
|
||||
const top: SketchPoint = {
|
||||
id: createLocalId("sketch-point"), x: cx, z: cz - radius, mode: "smooth",
|
||||
handleIn: { x: cx - kappa * radius, z: cz - radius },
|
||||
handleOut: { x: cx + kappa * radius, z: cz - radius },
|
||||
};
|
||||
points = [right, bottom, left, top];
|
||||
segments = points.map((point, index) => ({
|
||||
id: createLocalId("sketch-segment"),
|
||||
startId: point.id,
|
||||
endId: points[(index + 1) % points.length]!.id,
|
||||
kind: "bezier",
|
||||
}));
|
||||
} else {
|
||||
const vertices: Array<{ x: number; z: number }> = primitive === "rectangle"
|
||||
? [
|
||||
{ x: minX, z: minZ },
|
||||
{ x: maxX, z: minZ },
|
||||
{ x: maxX, z: maxZ },
|
||||
{ x: minX, z: maxZ },
|
||||
]
|
||||
: primitive === "triangle"
|
||||
? [
|
||||
{ x: cx, z: minZ },
|
||||
{ x: maxX, z: maxZ },
|
||||
{ x: minX, z: maxZ },
|
||||
]
|
||||
: Array.from({ length: 6 }, (_, index) => {
|
||||
const angle = -Math.PI / 2 + index * Math.PI / 3;
|
||||
return { x: cx + Math.cos(angle) * width / 2, z: cz + Math.sin(angle) * depth / 2 };
|
||||
});
|
||||
points = vertices.map((vertex) => ({ id: createLocalId("sketch-point"), ...vertex, mode: "corner" }));
|
||||
segments = points.map((point, index) => ({
|
||||
id: createLocalId("sketch-segment"),
|
||||
startId: point.id,
|
||||
endId: points[(index + 1) % points.length]!.id,
|
||||
kind: "line",
|
||||
}));
|
||||
}
|
||||
|
||||
const next: SketchProfile = {
|
||||
...sketchProfile,
|
||||
points: [...sketchProfile.points, ...points],
|
||||
segments: [...sketchProfile.segments, ...segments],
|
||||
};
|
||||
const label = primitive[0]!.toUpperCase() + primitive.slice(1);
|
||||
commitSketchProfile(next, `${label} added to sketch`);
|
||||
setSketchActivePointId(null);
|
||||
setSketchSelection({ kind: "multiple", pointIds: points.map((point) => point.id), segmentIds: segments.map((segment) => segment.id), imageIds: [] });
|
||||
setSketchTool("select");
|
||||
},
|
||||
[commitSketchProfile, sketchProfile],
|
||||
);
|
||||
|
||||
const pressSketchPoint = useCallback(
|
||||
(id: string) => {
|
||||
const point = sketchProfile.points.find((entry) => entry.id === id);
|
||||
@@ -6584,6 +6714,15 @@ export function SketchForgeEditor({
|
||||
commitSketchProfile(next, "Sketch point moved");
|
||||
}, [commitSketchProfile, sketchProfile]);
|
||||
|
||||
const transformSketchPoints = useCallback((points: SketchPoint[], message = "Sketch geometry transformed") => {
|
||||
if (!points.length) return;
|
||||
const byId = new Map(points.map((point) => [point.id, point]));
|
||||
commitSketchProfile({
|
||||
...sketchProfile,
|
||||
points: sketchProfile.points.map((point) => byId.get(point.id) ?? point),
|
||||
}, message);
|
||||
}, [commitSketchProfile, sketchProfile]);
|
||||
|
||||
const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => {
|
||||
const next = cloneSketchProfile(sketchProfile);
|
||||
const point = next.points.find((entry) => entry.id === id);
|
||||
@@ -6616,21 +6755,11 @@ export function SketchForgeEditor({
|
||||
commitSketchProfile(next, mode === "corner" ? "Made corner" : mode === "smooth" ? "Made smooth" : "Curve handles split");
|
||||
}, [commitSketchProfile, sketchProfile]);
|
||||
|
||||
const insertSketchPoint = useCallback((segmentId: string, position: { x: number; z: number }) => {
|
||||
const segment = sketchProfile.segments.find((entry) => entry.id === segmentId);
|
||||
if (!segment) return;
|
||||
const point: SketchPoint = { id: createLocalId("sketch-point"), ...position, mode: segment.kind === "line" ? "corner" : "smooth" };
|
||||
let next: SketchProfile = {
|
||||
...sketchProfile,
|
||||
points: [...sketchProfile.points, point],
|
||||
segments: sketchProfile.segments.flatMap((entry) => entry.id === segmentId ? [
|
||||
{ ...entry, id: createLocalId("sketch-segment"), endId: point.id },
|
||||
{ ...entry, id: createLocalId("sketch-segment"), startId: point.id },
|
||||
] : [entry]),
|
||||
};
|
||||
if (segment.kind === "smooth") next = withSmoothSketchHandles(next);
|
||||
commitSketchProfile(next, "Point added to path");
|
||||
setSketchSelection({ kind: "point", id: point.id });
|
||||
const insertSketchPoint = useCallback((segmentId: string, _position: { x: number; z: number }, amount: number) => {
|
||||
const result = splitSketchSegment(sketchProfile, segmentId, amount, createLocalId);
|
||||
if (!result.pointId) return;
|
||||
if (result.inserted) commitSketchProfile(result.profile, "Point added to path");
|
||||
setSketchSelection({ kind: "point", id: result.pointId });
|
||||
setSketchTool("select");
|
||||
}, [commitSketchProfile, sketchProfile]);
|
||||
|
||||
@@ -7149,7 +7278,7 @@ export function SketchForgeEditor({
|
||||
invalidateCadModifierSession();
|
||||
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape);
|
||||
const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length);
|
||||
const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment
|
||||
const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment && !shapeHasTaper(selectedShape)
|
||||
? restoreGroupedChildren(selectedShape)
|
||||
: [selectedShape]).flatMap(cadModifierSourceParts);
|
||||
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => {
|
||||
@@ -7159,6 +7288,7 @@ export function SketchForgeEditor({
|
||||
Math.abs(shapeDepth(shape) - (frame?.depth ?? shapeDepth(shape))) > 1e-6 ||
|
||||
Math.abs(shape.height - (frame?.height ?? shape.height)) > 1e-6
|
||||
);
|
||||
if (shapeHasTaper(shape)) return { shape, mesh: meshForShape(shape) };
|
||||
const primitive = cadModifierPrimitiveForShape(shape);
|
||||
if (primitive) return { shape, primitive };
|
||||
return shape.cadBrep && frame && !preserveNeedsRetessellation
|
||||
@@ -7224,7 +7354,7 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape);
|
||||
const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length);
|
||||
const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment
|
||||
const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment && !shapeHasTaper(shape)
|
||||
? restoreGroupedChildren(shape)
|
||||
: [shape]).flatMap(cadModifierSourceParts);
|
||||
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => {
|
||||
@@ -7234,6 +7364,7 @@ export function SketchForgeEditor({
|
||||
Math.abs(shapeDepth(partShape) - (frame?.depth ?? shapeDepth(partShape))) > 1e-6 ||
|
||||
Math.abs(partShape.height - (frame?.height ?? partShape.height)) > 1e-6
|
||||
);
|
||||
if (shapeHasTaper(partShape)) return { shape: partShape, mesh: meshForShape(partShape) };
|
||||
const primitive = cadModifierPrimitiveForShape(partShape);
|
||||
if (primitive) return { shape: partShape, primitive };
|
||||
return partShape.cadBrep && frame && !preserveNeedsRetessellation
|
||||
@@ -8359,7 +8490,8 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const meshes = exportable.map(meshForShape);
|
||||
if (format === "stl") {
|
||||
void downloadTextFile(projectExportFileName(exportName, "stl"), exportMeshesToStl(meshes), "model/stl")
|
||||
const blob = new Blob([exportMeshesToStl(meshes)], { type: "model/stl" });
|
||||
void downloadBlobFile(projectExportFileName(exportName, "stl"), blob)
|
||||
.then((result) => finishNotice("STL", result))
|
||||
.catch((error: unknown) => failNotice("STL", error));
|
||||
return;
|
||||
@@ -8821,7 +8953,7 @@ export function SketchForgeEditor({
|
||||
return;
|
||||
}
|
||||
|
||||
if (!shortcut && !event.altKey && key === "r" && hasSelection) {
|
||||
if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r") && hasSelection) {
|
||||
event.preventDefault();
|
||||
rotateSelected45();
|
||||
return;
|
||||
@@ -8931,6 +9063,7 @@ export function SketchForgeEditor({
|
||||
onStartSketch={(operation) => beginSketch(operation)}
|
||||
onEditSketch={beginSketchEdit}
|
||||
onSketchTool={setActiveSketchTool}
|
||||
onSketchPrimitive={(primitive) => addSketchPrimitive(primitive, { x: 0, z: 0 })}
|
||||
onSketchImage={() => {
|
||||
if (sketchTool !== "select") {
|
||||
setNotice("Choose Select before adding a sketch image");
|
||||
@@ -8985,6 +9118,7 @@ export function SketchForgeEditor({
|
||||
initialSnap={snapGrid}
|
||||
initialWorkspace={workspaceSettings}
|
||||
onPlanePoint={addSketchPlanePoint}
|
||||
onAddPrimitive={addSketchPrimitive}
|
||||
onPointPress={pressSketchPoint}
|
||||
onSelectSegment={(id) => {
|
||||
setSketchSelection({ kind: "segment", id });
|
||||
@@ -9006,6 +9140,7 @@ export function SketchForgeEditor({
|
||||
onDeletePoint={deleteSketchPoint}
|
||||
onDeleteSegment={deleteSketchSegment}
|
||||
onMovePoint={moveSketchPoint}
|
||||
onTransformPoints={transformSketchPoints}
|
||||
onMoveHandle={moveSketchHandle}
|
||||
onInsertPoint={insertSketchPoint}
|
||||
onSetPointMode={setSketchPointMode}
|
||||
@@ -9227,6 +9362,7 @@ function SecondaryToolbar({
|
||||
onStartSketch,
|
||||
onEditSketch,
|
||||
onSketchTool,
|
||||
onSketchPrimitive,
|
||||
onSketchImage,
|
||||
onSketchUndo,
|
||||
onSketchRedo,
|
||||
@@ -9278,6 +9414,7 @@ function SecondaryToolbar({
|
||||
onStartSketch: (operation: SketchOperation) => void;
|
||||
onEditSketch: () => void;
|
||||
onSketchTool: (tool: SketchTool) => void;
|
||||
onSketchPrimitive: (primitive: SketchPrimitive) => void;
|
||||
onSketchImage: () => void;
|
||||
onSketchUndo: () => void;
|
||||
onSketchRedo: () => void;
|
||||
@@ -9647,6 +9784,23 @@ function SecondaryToolbar({
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="toolbar-section sketch-shapes-section">
|
||||
<div className="toolbar-section-label">Shapes</div>
|
||||
<div className="toolbar-section-tools">
|
||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Rectangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("rectangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "rectangle"); }}>
|
||||
<SquareIcon size={25} strokeWidth={1.8} />
|
||||
</button>
|
||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Circle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("circle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "circle"); }}>
|
||||
<CircleIcon size={25} strokeWidth={1.8} />
|
||||
</button>
|
||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Triangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("triangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "triangle"); }}>
|
||||
<TriangleIcon size={25} strokeWidth={1.8} />
|
||||
</button>
|
||||
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Hexagon" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("hexagon")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "hexagon"); }}>
|
||||
<HexagonIcon size={25} strokeWidth={1.8} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="toolbar-section sketch-edit-section">
|
||||
<div className="toolbar-section-label">Select</div>
|
||||
<div className="toolbar-section-tools">
|
||||
|
||||
@@ -6,11 +6,13 @@ import { SnapGridControl } from "@/components/workplane/ShapeInspector";
|
||||
import { SketchRevolvePreview } from "@/components/SketchRevolvePreview";
|
||||
import { parseMeasurementInput } from "@/lib/measurementUnits";
|
||||
import { WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
|
||||
import { closestPointOnSketchSegment, type SketchSegmentPlacement } from "@/lib/sketchPointRefinement";
|
||||
import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes";
|
||||
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
|
||||
import type { GridSize, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
export type SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure";
|
||||
export type SketchPrimitive = "rectangle" | "circle" | "triangle" | "hexagon";
|
||||
export type SketchTool = "line" | "bezier" | "smooth" | SketchPrimitive | "select" | "refine" | "erase" | "measure";
|
||||
export type SketchSelection =
|
||||
| { kind: "point"; id: string }
|
||||
| { kind: "segment"; id: string }
|
||||
@@ -32,6 +34,7 @@ type SketchWorkspaceProps = {
|
||||
initialSnap?: GridSize;
|
||||
initialWorkspace?: WorkplaneWorkspaceSettings;
|
||||
onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void;
|
||||
onAddPrimitive: (primitive: SketchPrimitive, center: { x: number; z: number }) => void;
|
||||
onPointPress: (id: string) => void;
|
||||
onSelectSegment: (id: string) => void;
|
||||
onSelectMany: (pointIds: string[], segmentIds: string[], imageIds: string[]) => void;
|
||||
@@ -41,8 +44,9 @@ type SketchWorkspaceProps = {
|
||||
onDeletePoint: (id: string) => void;
|
||||
onDeleteSegment: (id: string) => void;
|
||||
onMovePoint: (id: string, point: { x: number; z: number }) => void;
|
||||
onTransformPoints: (points: SketchPoint[], message?: string) => void;
|
||||
onMoveHandle: (id: string, handle: "in" | "out", point: { x: number; z: number }) => void;
|
||||
onInsertPoint: (segmentId: string, point: { x: number; z: number }) => void;
|
||||
onInsertPoint: (segmentId: string, point: { x: number; z: number }, amount: number) => void;
|
||||
onSetPointMode: (id: string, mode: "corner" | "smooth" | "split") => void;
|
||||
onClearMeasurement: () => void;
|
||||
};
|
||||
@@ -53,6 +57,8 @@ type SketchReferenceFootprint = { fillD: string | null; outlineD: string | null
|
||||
type PointerAction =
|
||||
| { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
|
||||
| { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } }
|
||||
| { kind: "move-selection"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number }; startPoints: SketchPoint[] }
|
||||
| { kind: "resize-selection"; pointerId: number; handle: ResizeHandle; current: { x: number; z: number }; startPoints: SketchPoint[]; bounds: SelectionBounds }
|
||||
| { kind: "move-handle"; pointerId: number; pointId: string; handle: "in" | "out"; current: { x: number; z: number } }
|
||||
| { kind: "pan"; pointerId: number; clientX: number; clientY: number }
|
||||
| { kind: "marquee"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
|
||||
@@ -60,6 +66,7 @@ type PointerAction =
|
||||
| { kind: "resize-image"; pointerId: number; imageId: string; handle: ResizeHandle; current: { x: number; z: number }; start: SketchImage };
|
||||
|
||||
type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
|
||||
type SelectionBounds = { minX: number; maxX: number; minZ: number; maxZ: number; width: number; depth: number; cx: number; cz: number };
|
||||
|
||||
function snapStep(size: GridSize) {
|
||||
if (size === "Off") return 0;
|
||||
@@ -126,6 +133,62 @@ function resizeSketchImage(start: SketchImage, handle: ResizeHandle, point: { x:
|
||||
};
|
||||
}
|
||||
|
||||
function boundsForSketchPoints(points: SketchPoint[]): SelectionBounds | null {
|
||||
if (points.length < 2) return null;
|
||||
const xs = points.map((point) => point.x);
|
||||
const zs = points.map((point) => point.z);
|
||||
const minX = Math.min(...xs);
|
||||
const maxX = Math.max(...xs);
|
||||
const minZ = Math.min(...zs);
|
||||
const maxZ = Math.max(...zs);
|
||||
return {
|
||||
minX,
|
||||
maxX,
|
||||
minZ,
|
||||
maxZ,
|
||||
width: maxX - minX,
|
||||
depth: maxZ - minZ,
|
||||
cx: (minX + maxX) / 2,
|
||||
cz: (minZ + maxZ) / 2,
|
||||
};
|
||||
}
|
||||
|
||||
function translateSketchPoints(points: SketchPoint[], dx: number, dz: number) {
|
||||
return points.map((point) => ({
|
||||
...point,
|
||||
x: point.x + dx,
|
||||
z: point.z + dz,
|
||||
handleIn: point.handleIn ? { x: point.handleIn.x + dx, z: point.handleIn.z + dz } : undefined,
|
||||
handleOut: point.handleOut ? { x: point.handleOut.x + dx, z: point.handleOut.z + dz } : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
function resizeSketchPoints(points: SketchPoint[], bounds: SelectionBounds, handle: ResizeHandle, current: { x: number; z: number }) {
|
||||
const minimum = 0.5;
|
||||
let minX = bounds.minX;
|
||||
let maxX = bounds.maxX;
|
||||
let minZ = bounds.minZ;
|
||||
let maxZ = bounds.maxZ;
|
||||
if (handle.includes("w")) minX = Math.min(current.x, bounds.maxX - minimum);
|
||||
if (handle.includes("e")) maxX = Math.max(current.x, bounds.minX + minimum);
|
||||
if (handle.includes("n")) minZ = Math.min(current.z, bounds.maxZ - minimum);
|
||||
if (handle.includes("s")) maxZ = Math.max(current.z, bounds.minZ + minimum);
|
||||
const width = Math.max(minimum, bounds.width);
|
||||
const depth = Math.max(minimum, bounds.depth);
|
||||
const scaleX = (maxX - minX) / width;
|
||||
const scaleZ = (maxZ - minZ) / depth;
|
||||
const map = (value: { x: number; z: number }) => ({
|
||||
x: minX + (value.x - bounds.minX) * scaleX,
|
||||
z: minZ + (value.z - bounds.minZ) * scaleZ,
|
||||
});
|
||||
return points.map((point) => ({
|
||||
...point,
|
||||
...map(point),
|
||||
handleIn: point.handleIn ? map(point.handleIn) : undefined,
|
||||
handleOut: point.handleOut ? map(point.handleOut) : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
function formatDimension(value: number, accuracy: 1 | 2 | 3) {
|
||||
const threshold = 0.5 * 10 ** -accuracy;
|
||||
return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy);
|
||||
@@ -414,6 +477,7 @@ export function SketchWorkspace({
|
||||
initialSnap,
|
||||
initialWorkspace,
|
||||
onPlanePoint,
|
||||
onAddPrimitive,
|
||||
onPointPress,
|
||||
onSelectSegment,
|
||||
onSelectMany,
|
||||
@@ -423,6 +487,7 @@ export function SketchWorkspace({
|
||||
onDeletePoint,
|
||||
onDeleteSegment,
|
||||
onMovePoint,
|
||||
onTransformPoints,
|
||||
onMoveHandle,
|
||||
onInsertPoint,
|
||||
onSetPointMode,
|
||||
@@ -434,6 +499,7 @@ export function SketchWorkspace({
|
||||
const [zoom, setZoom] = useState(1);
|
||||
const [pan, setPan] = useState({ x: 0, z: 0 });
|
||||
const [hover, setHover] = useState<{ x: number; z: number } | null>(null);
|
||||
const [refinePreview, setRefinePreview] = useState<{ segmentId: string; placement: SketchSegmentPlacement } | null>(null);
|
||||
const [pointerAction, setPointerAction] = useState<PointerAction | null>(null);
|
||||
const [svgSize, setSvgSize] = useState({ width: 0, height: 0 });
|
||||
const svgRef = useRef<SVGSVGElement | null>(null);
|
||||
@@ -447,6 +513,20 @@ export function SketchWorkspace({
|
||||
return fittedScale > 0 ? 1 / fittedScale : Math.max(width, depth) / 720;
|
||||
}, [depth, svgSize.height, svgSize.width, width]);
|
||||
const displayProfile = useMemo(() => {
|
||||
if (pointerAction?.kind === "move-selection") {
|
||||
const moved = translateSketchPoints(
|
||||
pointerAction.startPoints,
|
||||
pointerAction.current.x - pointerAction.origin.x,
|
||||
pointerAction.current.z - pointerAction.origin.z,
|
||||
);
|
||||
const movedById = new Map(moved.map((point) => [point.id, point]));
|
||||
return { ...profile, points: profile.points.map((point) => movedById.get(point.id) ?? point) };
|
||||
}
|
||||
if (pointerAction?.kind === "resize-selection") {
|
||||
const resized = resizeSketchPoints(pointerAction.startPoints, pointerAction.bounds, pointerAction.handle, pointerAction.current);
|
||||
const resizedById = new Map(resized.map((point) => [point.id, point]));
|
||||
return { ...profile, points: profile.points.map((point) => resizedById.get(point.id) ?? point) };
|
||||
}
|
||||
if (pointerAction?.kind === "move-point") {
|
||||
const source = profile.points.find((point) => point.id === pointerAction.pointId);
|
||||
if (!source) return profile;
|
||||
@@ -498,6 +578,10 @@ export function SketchWorkspace({
|
||||
const activePoint = activePointId ? pointById.get(activePointId) ?? null : null;
|
||||
const selectedPoint = selected?.kind === "point" ? pointById.get(selected.id) ?? null : null;
|
||||
const selectedImage = selected?.kind === "image" ? displayImages.find((image) => image.id === selected.id) ?? null : null;
|
||||
const selectedGeometryPoints = selected?.kind === "multiple"
|
||||
? selected.pointIds.map((id) => pointById.get(id)).filter((point): point is SketchPoint => Boolean(point))
|
||||
: [];
|
||||
const selectedGeometryBounds = boundsForSketchPoints(selectedGeometryPoints);
|
||||
const isPointSelected = (id: string) => selected?.kind === "point" ? selected.id === id : selected?.kind === "multiple" ? selected.pointIds.includes(id) : false;
|
||||
const isSegmentSelected = (id: string) => selected?.kind === "segment" ? selected.id === id : selected?.kind === "multiple" ? selected.segmentIds.includes(id) : false;
|
||||
const gridStep = clamp(workspace.gridBlockSize, 1, 200);
|
||||
@@ -529,6 +613,10 @@ export function SketchWorkspace({
|
||||
};
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (tool !== "refine") setRefinePreview(null);
|
||||
}, [tool]);
|
||||
|
||||
useEffect(() => {
|
||||
const svg = svgRef.current;
|
||||
if (!svg) return;
|
||||
@@ -619,6 +707,13 @@ export function SketchWorkspace({
|
||||
handleIn: { x: action.origin.x - dx, z: action.origin.z - dz },
|
||||
handleOut: { x: action.origin.x + dx, z: action.origin.z + dz },
|
||||
});
|
||||
} else if (action.kind === "move-selection") {
|
||||
onTransformPoints(
|
||||
translateSketchPoints(action.startPoints, action.current.x - action.origin.x, action.current.z - action.origin.z),
|
||||
"Sketch shape moved",
|
||||
);
|
||||
} else if (action.kind === "resize-selection") {
|
||||
onTransformPoints(resizeSketchPoints(action.startPoints, action.bounds, action.handle, action.current), "Sketch shape resized");
|
||||
} else if (action.kind === "move-point") {
|
||||
onMovePoint(action.pointId, action.current);
|
||||
} else if (action.kind === "move-handle") {
|
||||
@@ -673,6 +768,16 @@ export function SketchWorkspace({
|
||||
{ id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ },
|
||||
{ id: "w", x: selectedImageBounds.minX, z: selectedImage.z },
|
||||
] : [];
|
||||
const selectionResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedGeometryBounds ? [
|
||||
{ id: "nw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.minZ },
|
||||
{ id: "n", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.minZ },
|
||||
{ id: "ne", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.minZ },
|
||||
{ id: "e", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.cz },
|
||||
{ id: "se", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.maxZ },
|
||||
{ id: "s", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.maxZ },
|
||||
{ id: "sw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.maxZ },
|
||||
{ id: "w", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.cz },
|
||||
] : [];
|
||||
const referenceFootprints = useMemo(
|
||||
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
|
||||
[referenceShapes],
|
||||
@@ -697,8 +802,23 @@ export function SketchWorkspace({
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={finishPointerAction}
|
||||
onPointerCancel={() => setPointerAction(null)}
|
||||
onPointerLeave={() => !pointerAction && setHover(null)}
|
||||
onPointerLeave={() => {
|
||||
if (!pointerAction) setHover(null);
|
||||
setRefinePreview(null);
|
||||
}}
|
||||
onWheel={handleWheel}
|
||||
onDragOver={(event) => {
|
||||
if (!event.dataTransfer.types.includes("application/x-sketchforge-sketch-primitive")) return;
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
const primitive = event.dataTransfer.getData("application/x-sketchforge-sketch-primitive") as SketchPrimitive;
|
||||
if (!["rectangle", "circle", "triangle", "hexagon"].includes(primitive)) return;
|
||||
event.preventDefault();
|
||||
const point = pointFromEvent(event);
|
||||
if (point) onAddPrimitive(primitive, point);
|
||||
}}
|
||||
>
|
||||
<rect className="sketch-plate-background" x={-workspace.width / 2} y={-workspace.depth / 2} width={workspace.width} height={workspace.depth} />
|
||||
{workspace.showGrid ? (
|
||||
@@ -783,6 +903,29 @@ export function SketchWorkspace({
|
||||
<g className="sketch-profile-fills" pointerEvents="none">
|
||||
{paths.some((path) => path.closed) ? <path d={paths.filter((path) => path.closed).map(pathData).join(" ")} /> : null}
|
||||
</g>
|
||||
<g className="sketch-profile-hit-targets" pointerEvents={tool === "select" ? "auto" : "none"}>
|
||||
{paths.filter((path) => path.closed).map((path) => (
|
||||
<path
|
||||
key={`hit-${path.id}`}
|
||||
data-sketch-entity="closed-profile"
|
||||
d={pathData(path)}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button === 1) {
|
||||
beginPan(event);
|
||||
return;
|
||||
}
|
||||
if (event.button !== 0 || tool !== "select") return;
|
||||
const point = pointFromEvent(event);
|
||||
if (!point) return;
|
||||
const pointIds = path.points.map((entry) => entry.id);
|
||||
const segmentIds = path.steps.map((step) => step.segment.id);
|
||||
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
||||
onSelectMany(pointIds, segmentIds, []);
|
||||
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
<g className="sketch-segments">
|
||||
{displayProfile.segments.map((segment) => (
|
||||
<path
|
||||
@@ -790,20 +933,59 @@ export function SketchWorkspace({
|
||||
className={isSegmentSelected(segment.id) ? "selected" : ""}
|
||||
key={segment.id}
|
||||
d={segmentData(segment, pointById)}
|
||||
onPointerMove={(event) => {
|
||||
if (tool !== "refine") return;
|
||||
const target = pointFromEvent(event);
|
||||
const start = pointById.get(segment.startId);
|
||||
const end = pointById.get(segment.endId);
|
||||
if (!target || !start || !end) return;
|
||||
setRefinePreview({ segmentId: segment.id, placement: closestPointOnSketchSegment(segment, start, end, target) });
|
||||
}}
|
||||
onPointerLeave={() => {
|
||||
if (tool === "refine") setRefinePreview((current) => current?.segmentId === segment.id ? null : current);
|
||||
}}
|
||||
onPointerDown={(event) => {
|
||||
const point = pointFromEvent(event);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.button === 1) beginPan(event);
|
||||
else if (tool === "erase") onDeleteSegment(segment.id);
|
||||
else if (event.button === 0 && tool === "refine" && point) onInsertPoint(segment.id, point);
|
||||
else if (event.button === 0) onSelectSegment(segment.id);
|
||||
else if (event.button === 0 && tool === "refine" && point) {
|
||||
const start = pointById.get(segment.startId);
|
||||
const end = pointById.get(segment.endId);
|
||||
if (start && end) {
|
||||
const placement = closestPointOnSketchSegment(segment, start, end, point);
|
||||
onInsertPoint(segment.id, placement.point, placement.amount);
|
||||
}
|
||||
}
|
||||
else if (event.button === 0 && tool === "select" && point) {
|
||||
const closedPath = paths.find((path) => path.closed && path.steps.some((step) => step.segment.id === segment.id));
|
||||
if (!closedPath) {
|
||||
onSelectSegment(segment.id);
|
||||
return;
|
||||
}
|
||||
const pointIds = closedPath.points.map((entry) => entry.id);
|
||||
const segmentIds = closedPath.steps.map((step) => step.segment.id);
|
||||
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
||||
onSelectMany(pointIds, segmentIds, []);
|
||||
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
|
||||
} else if (event.button === 0) onSelectSegment(segment.id);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
{tool === "refine" && refinePreview ? (
|
||||
<circle
|
||||
className="sketch-cursor-point"
|
||||
cx={refinePreview.placement.point.x}
|
||||
cy={refinePreview.placement.point.z}
|
||||
r={hoverPointRadius}
|
||||
opacity={0.72}
|
||||
pointerEvents="none"
|
||||
/>
|
||||
) : null}
|
||||
<g className="sketch-segment-dimensions" pointerEvents="none">
|
||||
{displayProfile.segments.map((segment) => {
|
||||
{selected?.kind === "multiple" ? null : displayProfile.segments.map((segment) => {
|
||||
const dimension = segmentDimension(segment, pointById);
|
||||
if (!dimension) return null;
|
||||
const label = formatDimension(dimension.length, workspace.accuracy);
|
||||
@@ -816,6 +998,66 @@ export function SketchWorkspace({
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
{selectedGeometryBounds && tool === "select" ? (() => {
|
||||
const widthLabel = formatDimension(selectedGeometryBounds.width, workspace.accuracy);
|
||||
const depthLabel = formatDimension(selectedGeometryBounds.depth, workspace.accuracy);
|
||||
const widthPill = dimensionPillSize(widthLabel, screenUnit, 18);
|
||||
const depthPill = dimensionPillSize(depthLabel, screenUnit, 18);
|
||||
return (
|
||||
<g className="sketch-geometry-selection">
|
||||
<rect
|
||||
data-sketch-entity="selection-box"
|
||||
className="sketch-geometry-selection-box"
|
||||
x={selectedGeometryBounds.minX}
|
||||
y={selectedGeometryBounds.minZ}
|
||||
width={selectedGeometryBounds.width}
|
||||
height={selectedGeometryBounds.depth}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button === 1) {
|
||||
beginPan(event);
|
||||
return;
|
||||
}
|
||||
if (event.button !== 0 || selected?.kind !== "multiple") return;
|
||||
const point = pointFromEvent(event);
|
||||
if (!point) return;
|
||||
const startPoints = selected.pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
||||
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
|
||||
}}
|
||||
/>
|
||||
<g className="sketch-geometry-dimension" pointerEvents="none" transform={`translate(${selectedGeometryBounds.cx} ${selectedGeometryBounds.minZ - labelOffset})`}>
|
||||
<rect x={-widthPill.width / 2} y={-widthPill.height / 2} width={widthPill.width} height={widthPill.height} rx={widthPill.radius} />
|
||||
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{widthLabel}</text>
|
||||
</g>
|
||||
<g className="sketch-geometry-dimension" pointerEvents="none" transform={`translate(${selectedGeometryBounds.maxX + 34 * screenUnit} ${selectedGeometryBounds.cz})`}>
|
||||
<rect x={-depthPill.width / 2} y={-depthPill.height / 2} width={depthPill.width} height={depthPill.height} rx={depthPill.radius} />
|
||||
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{depthLabel}</text>
|
||||
</g>
|
||||
{selectionResizeHandles.map((handle) => (
|
||||
<rect
|
||||
key={`selection-handle-${handle.id}`}
|
||||
data-sketch-entity="selection-handle"
|
||||
className={`sketch-geometry-resize-handle handle-${handle.id}`}
|
||||
x={handle.x - handleSize / 2}
|
||||
y={handle.z - handleSize / 2}
|
||||
width={handleSize}
|
||||
height={handleSize}
|
||||
rx={handleRadius}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button === 1) {
|
||||
beginPan(event);
|
||||
return;
|
||||
}
|
||||
if (event.button !== 0 || selected?.kind !== "multiple") return;
|
||||
const startPoints = selected.pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
||||
const bounds = boundsForSketchPoints(startPoints);
|
||||
if (!bounds) return;
|
||||
beginEntityDrag(event, { kind: "resize-selection", pointerId: event.pointerId, handle: handle.id, current: { x: handle.x, z: handle.z }, startPoints, bounds });
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
})() : null}
|
||||
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? <line className="sketch-preview-line" x1={activePoint.x} y1={activePoint.z} x2={hover.x} y2={hover.z} pointerEvents="none" /> : null}
|
||||
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? (
|
||||
<g className="sketch-segment-dimensions preview" pointerEvents="none" transform={`translate(${(activePoint.x + hover.x) / 2} ${(activePoint.z + hover.z) / 2 - labelOffset})`}>
|
||||
@@ -888,8 +1130,17 @@ export function SketchWorkspace({
|
||||
} else if (tool === "erase" || tool === "refine") {
|
||||
onDeletePoint(point.id);
|
||||
} else if (event.button === 0 && tool === "select") {
|
||||
onPointPress(point.id);
|
||||
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
|
||||
const closedPath = paths.find((path) => path.closed && path.points.some((entry) => entry.id === point.id));
|
||||
if (closedPath) {
|
||||
const pointIds = closedPath.points.map((entry) => entry.id);
|
||||
const segmentIds = closedPath.steps.map((step) => step.segment.id);
|
||||
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
|
||||
onSelectMany(pointIds, segmentIds, []);
|
||||
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: { x: point.x, z: point.z }, current: { x: point.x, z: point.z }, startPoints });
|
||||
} else {
|
||||
onPointPress(point.id);
|
||||
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
|
||||
}
|
||||
} else if (event.button === 0) {
|
||||
onPointPress(point.id);
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint";
|
||||
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
|
||||
import { interiorWorkplaneGridCoordinates, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
|
||||
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
|
||||
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeTaperScaleAt, shapeWidth } from "@/lib/workplaneShapes";
|
||||
import { sphereTessellation } from "@/lib/sphereTessellation";
|
||||
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
|
||||
import {
|
||||
@@ -214,6 +214,15 @@ type WorkplaneViewportProps = {
|
||||
type WorkspaceSettings = WorkplaneWorkspaceSettings;
|
||||
type ViewCubeFace = "top" | "bottom" | "front" | "back" | "right" | "left";
|
||||
|
||||
const VIEW_FACE_SHORTCUTS: Readonly<Record<string, ViewCubeFace>> = {
|
||||
"1": "front",
|
||||
"2": "back",
|
||||
"3": "left",
|
||||
"4": "right",
|
||||
"5": "top",
|
||||
"6": "bottom",
|
||||
};
|
||||
|
||||
function readSavedWorkspaceDefault(key: string | null) {
|
||||
if (!key || typeof window === "undefined") {
|
||||
return null;
|
||||
@@ -816,6 +825,12 @@ function rulerShapeTopologyKey(shape: WorkplaneShape): string {
|
||||
segments: shape.segments,
|
||||
topRadius: shape.topRadius,
|
||||
baseRadius: shape.baseRadius,
|
||||
taperTopWidth: shape.taperTopWidth,
|
||||
taperTopDepth: shape.taperTopDepth,
|
||||
taperBottomWidth: shape.taperBottomWidth,
|
||||
taperBottomDepth: shape.taperBottomDepth,
|
||||
taperTopScale: shape.taperTopScale,
|
||||
taperBottomScale: shape.taperBottomScale,
|
||||
teeth: shape.teeth,
|
||||
toothSize: shape.toothSize,
|
||||
toothWidth: shape.toothWidth,
|
||||
@@ -872,12 +887,16 @@ function shapeMaterialSignature(shape: WorkplaneShape): string {
|
||||
}
|
||||
|
||||
function shapeGeometrySignature(shape: WorkplaneShape): string {
|
||||
const taper = shape.kind === "gear" || !shapeHasTaper(shape)
|
||||
? null
|
||||
: { ...shapeTaperDimensions(shape), baseWidth: shapeWidth(shape), baseDepth: shapeDepth(shape) };
|
||||
if (shape.groupedShapes?.length && !shape.importedMesh) {
|
||||
return JSON.stringify({
|
||||
kind: "group",
|
||||
width: shapeWidth(shape),
|
||||
depth: shapeDepth(shape),
|
||||
height: shape.height,
|
||||
taper,
|
||||
children: shape.groupedShapes.map((child) => [
|
||||
child.id,
|
||||
child.hidden,
|
||||
@@ -894,6 +913,7 @@ function shapeGeometrySignature(shape: WorkplaneShape): string {
|
||||
return JSON.stringify({
|
||||
kind: "mesh",
|
||||
mesh: shapeResourceId(shape.importedMesh),
|
||||
taper,
|
||||
preserve: preservesEdgeTreatmentSize(shape)
|
||||
? [shapeWidth(shape), shapeDepth(shape), shape.height, shape.edgeTreatments]
|
||||
: false,
|
||||
@@ -901,16 +921,16 @@ function shapeGeometrySignature(shape: WorkplaneShape): string {
|
||||
}
|
||||
|
||||
if (shape.kind === "box" && !(shape.radius && shape.radius > 0)) {
|
||||
return JSON.stringify({ kind: "box" });
|
||||
return JSON.stringify({ kind: "box", taper });
|
||||
}
|
||||
if (shape.kind === "cylinder") {
|
||||
return JSON.stringify({ kind: "cylinder", sides: shape.sides, segments: shape.segments });
|
||||
return JSON.stringify({ kind: "cylinder", sides: shape.sides, segments: shape.segments, taper });
|
||||
}
|
||||
if (shape.kind === "sphere") {
|
||||
return JSON.stringify({ kind: "sphere", steps: shape.steps });
|
||||
return JSON.stringify({ kind: "sphere", steps: shape.steps, taper });
|
||||
}
|
||||
if (shape.kind === "polygon") {
|
||||
return JSON.stringify({ kind: "polygon" });
|
||||
return JSON.stringify({ kind: "polygon", taper });
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
@@ -926,6 +946,12 @@ function shapeGeometrySignature(shape: WorkplaneShape): string {
|
||||
segments: shape.segments,
|
||||
topRadius: shape.topRadius,
|
||||
baseRadius: shape.baseRadius,
|
||||
taperTopWidth: shape.taperTopWidth,
|
||||
taperTopDepth: shape.taperTopDepth,
|
||||
taperBottomWidth: shape.taperBottomWidth,
|
||||
taperBottomDepth: shape.taperBottomDepth,
|
||||
taperTopScale: shape.taperTopScale,
|
||||
taperBottomScale: shape.taperBottomScale,
|
||||
teeth: shape.teeth,
|
||||
toothSize: shape.toothSize,
|
||||
toothWidth: shape.toothWidth,
|
||||
@@ -1442,10 +1468,11 @@ function shapeCenter(shape: WorkplaneShape) {
|
||||
}
|
||||
|
||||
function shapeLocalExtents(shape: WorkplaneShape) {
|
||||
const footprint = shapeOverallFootprintDimensions(shape);
|
||||
return {
|
||||
x: shapeWidth(shape) / 2,
|
||||
x: footprint.width / 2,
|
||||
y: shape.height / 2,
|
||||
z: shapeDepth(shape) / 2,
|
||||
z: footprint.depth / 2,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1490,13 +1517,28 @@ function importedShapeProjectionBounds(
|
||||
const min = new THREE.Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
|
||||
const max = new THREE.Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
|
||||
const point = new THREE.Vector3();
|
||||
const tapered = shapeHasTaper(shape);
|
||||
let taperMinY = Number.POSITIVE_INFINITY;
|
||||
let taperMaxY = Number.NEGATIVE_INFINITY;
|
||||
if (tapered) {
|
||||
for (let index = 1; index < positions.length; index += 3) {
|
||||
const localY = positions[index] * scaleY;
|
||||
taperMinY = Math.min(taperMinY, localY);
|
||||
taperMaxY = Math.max(taperMaxY, localY);
|
||||
}
|
||||
}
|
||||
const taperHeight = Math.max(1e-6, taperMaxY - taperMinY);
|
||||
|
||||
for (let index = 0; index + 2 < positions.length; index += 3) {
|
||||
const localY = positions[index + 1] * scaleY;
|
||||
const normalizedHeight = tapered ? (localY - taperMinY) / taperHeight : 0;
|
||||
const widthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "width") : 1;
|
||||
const depthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "depth") : 1;
|
||||
point
|
||||
.set(
|
||||
positions[index] * scaleX,
|
||||
positions[index + 1] * scaleY - shape.height / 2,
|
||||
positions[index + 2] * scaleZ,
|
||||
positions[index] * scaleX * widthScale,
|
||||
localY - shape.height / 2,
|
||||
positions[index + 2] * scaleZ * depthScale,
|
||||
)
|
||||
.applyQuaternion(quaternion)
|
||||
.add(center);
|
||||
@@ -1713,6 +1755,27 @@ function resizedShapePatchFromFrame(shape: WorkplaneShape, center: THREE.Vector3
|
||||
return patch;
|
||||
}
|
||||
|
||||
function scaledHorizontalShapePatch(shape: WorkplaneShape, scaleX: number, scaleZ: number): Partial<WorkplaneShape> {
|
||||
const width = Math.max(MIN_SHAPE_SIZE, shapeWidth(shape) * scaleX);
|
||||
const depth = Math.max(MIN_SHAPE_SIZE, shapeDepth(shape) * scaleZ);
|
||||
const patch: Partial<WorkplaneShape> = {
|
||||
width,
|
||||
depth,
|
||||
size: resizedShapeSize(width, depth),
|
||||
};
|
||||
if (shape.kind === "cone") {
|
||||
patch.baseRadius = width / 2;
|
||||
}
|
||||
if (shapeHasTaper(shape)) {
|
||||
const taper = shapeTaperDimensions(shape);
|
||||
patch.taperTopWidth = Math.max(MIN_SHAPE_SIZE, taper.topWidth * scaleX);
|
||||
patch.taperBottomWidth = Math.max(MIN_SHAPE_SIZE, taper.bottomWidth * scaleX);
|
||||
patch.taperTopDepth = Math.max(MIN_SHAPE_SIZE, taper.topDepth * scaleZ);
|
||||
patch.taperBottomDepth = Math.max(MIN_SHAPE_SIZE, taper.bottomDepth * scaleZ);
|
||||
}
|
||||
return patch;
|
||||
}
|
||||
|
||||
function shapeScreenBounds(state: ThreeState, shape: WorkplaneShape) {
|
||||
const frame = selectionFrameForShapes([shape], [shape.id]);
|
||||
if (!frame) {
|
||||
@@ -1895,12 +1958,16 @@ function patchWithResizeAnchor(
|
||||
return patchWithPreservedWorldBottom(shape, patch);
|
||||
}
|
||||
|
||||
const width = Math.max(MIN_SHAPE_SIZE, patch.width ?? shapeWidth(shape));
|
||||
const depth = Math.max(MIN_SHAPE_SIZE, patch.depth ?? shapeDepth(shape));
|
||||
const draftShape = { ...shape, ...patch };
|
||||
const draftFrame = selectionFrameForShapes([draftShape], [shape.id]);
|
||||
const width = Math.max(MIN_SHAPE_SIZE, draftFrame?.width ?? patch.width ?? shapeWidth(shape));
|
||||
const depth = Math.max(MIN_SHAPE_SIZE, draftFrame?.depth ?? patch.depth ?? shapeDepth(shape));
|
||||
const center = resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, width, depth);
|
||||
return patchWithPreservedWorldBottom(shape, {
|
||||
...patch,
|
||||
...resizedShapePatchFromFrame(shape, center, width, depth),
|
||||
x: cleanNearZero(center.x, 0.0005),
|
||||
z: cleanNearZero(center.z, 0.0005),
|
||||
elevation: cleanNearZero(center.y - shape.height / 2, 0.0005),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1945,6 +2012,17 @@ function resizeShapeFromFrameHandle(
|
||||
const nextCenter = altKey
|
||||
? frame.center.clone()
|
||||
: resizeCenterFromAnchor(frame, transform.scaleAnchorPoint ?? resizeAnchorPointForFrame(frame, signs), signs, nextWidth, nextDepth);
|
||||
if (shapeHasTaper(shape)) {
|
||||
const scaleX = nextWidth / Math.max(MIN_SHAPE_SIZE, width);
|
||||
const scaleZ = nextDepth / Math.max(MIN_SHAPE_SIZE, depth);
|
||||
const scaled = scaledHorizontalShapePatch(shape, scaleX, scaleZ);
|
||||
return {
|
||||
...scaled,
|
||||
x: cleanNearZero(nextCenter.x, 0.0005),
|
||||
z: cleanNearZero(nextCenter.z, 0.0005),
|
||||
elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005),
|
||||
};
|
||||
}
|
||||
return resizedShapePatchFromFrame(shape, nextCenter, nextWidth, nextDepth);
|
||||
}
|
||||
|
||||
@@ -2176,13 +2254,13 @@ function resizeSelectionFromHandle(
|
||||
.add(frame.zAxis.clone().multiplyScalar(localCenter.z * nextZ.scale));
|
||||
const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, 260);
|
||||
const depth = snapDimension(shapeDepth(item.startShape) * nextZ.scale, step, MIN_SHAPE_SIZE, 260);
|
||||
const actualScaleX = width / Math.max(MIN_SHAPE_SIZE, shapeWidth(item.startShape));
|
||||
const actualScaleZ = depth / Math.max(MIN_SHAPE_SIZE, shapeDepth(item.startShape));
|
||||
const patch = {
|
||||
...scaledHorizontalShapePatch(item.startShape, actualScaleX, actualScaleZ),
|
||||
x: nextItemCenter.x,
|
||||
z: nextItemCenter.z,
|
||||
elevation: cleanNearZero(nextItemCenter.y - item.startShape.height / 2, 0.0005),
|
||||
width,
|
||||
depth,
|
||||
size: resizedShapeSize(width, depth),
|
||||
} satisfies Partial<WorkplaneShape>;
|
||||
return {
|
||||
id: item.id,
|
||||
@@ -3722,13 +3800,45 @@ export function WorkplaneViewport({
|
||||
if (Number.isFinite(value) && value > 0) {
|
||||
const nextValue = Math.max(MIN_SHAPE_SIZE, value);
|
||||
if (edit.axis === "width") {
|
||||
const patch: Partial<WorkplaneShape> = { width: nextValue, size: resizedShapeSize(nextValue, shapeDepth(shape)) };
|
||||
if (shape.kind === "cone") {
|
||||
patch.baseRadius = nextValue / 2;
|
||||
const frame = selectionFrameForShapes([shape], [shape.id]);
|
||||
if (shapeHasTaper(shape) && frame) {
|
||||
const scaleX = nextValue / Math.max(MIN_SHAPE_SIZE, frame.width);
|
||||
const anchor = lastResizeAnchorRef.current;
|
||||
const signs = anchor?.shapeId === shape.id ? resizeSignsForDimension(anchor.signs, "width") : { x: 0, z: 0 };
|
||||
const nextCenter = signs.x
|
||||
? resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, nextValue, frame.depth)
|
||||
: frame.center.clone();
|
||||
onUpdateShape(id, {
|
||||
...scaledHorizontalShapePatch(shape, scaleX, 1),
|
||||
x: cleanNearZero(nextCenter.x, 0.0005),
|
||||
z: cleanNearZero(nextCenter.z, 0.0005),
|
||||
elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005),
|
||||
});
|
||||
} else {
|
||||
const patch: Partial<WorkplaneShape> = { width: nextValue, size: resizedShapeSize(nextValue, shapeDepth(shape)) };
|
||||
if (shape.kind === "cone") {
|
||||
patch.baseRadius = nextValue / 2;
|
||||
}
|
||||
onUpdateShape(id, patchWithResizeAnchor(shape, patch, edit.axis, lastResizeAnchorRef.current));
|
||||
}
|
||||
onUpdateShape(id, patchWithResizeAnchor(shape, patch, edit.axis, lastResizeAnchorRef.current));
|
||||
} else if (edit.axis === "depth") {
|
||||
onUpdateShape(id, patchWithResizeAnchor(shape, { depth: nextValue, size: resizedShapeSize(shapeWidth(shape), nextValue) }, edit.axis, lastResizeAnchorRef.current));
|
||||
const frame = selectionFrameForShapes([shape], [shape.id]);
|
||||
if (shapeHasTaper(shape) && frame) {
|
||||
const scaleZ = nextValue / Math.max(MIN_SHAPE_SIZE, frame.depth);
|
||||
const anchor = lastResizeAnchorRef.current;
|
||||
const signs = anchor?.shapeId === shape.id ? resizeSignsForDimension(anchor.signs, "depth") : { x: 0, z: 0 };
|
||||
const nextCenter = signs.z
|
||||
? resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, frame.width, nextValue)
|
||||
: frame.center.clone();
|
||||
onUpdateShape(id, {
|
||||
...scaledHorizontalShapePatch(shape, 1, scaleZ),
|
||||
x: cleanNearZero(nextCenter.x, 0.0005),
|
||||
z: cleanNearZero(nextCenter.z, 0.0005),
|
||||
elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005),
|
||||
});
|
||||
} else {
|
||||
onUpdateShape(id, patchWithResizeAnchor(shape, { depth: nextValue, size: resizedShapeSize(shapeWidth(shape), nextValue) }, edit.axis, lastResizeAnchorRef.current));
|
||||
}
|
||||
} else {
|
||||
onUpdateShape(id, patchWithResizeAnchor(shape, { height: nextValue }, edit.axis, lastResizeAnchorRef.current));
|
||||
}
|
||||
@@ -4740,6 +4850,9 @@ export function WorkplaneViewport({
|
||||
}
|
||||
|
||||
const key = event.key.toLowerCase();
|
||||
const shortcutView = !event.ctrlKey && !event.metaKey && !event.altKey
|
||||
? VIEW_FACE_SHORTCUTS[event.key]
|
||||
: undefined;
|
||||
if (event.key === "Escape" && workplaneModeRef.current) {
|
||||
event.preventDefault();
|
||||
onWorkplaneModeChange(false);
|
||||
@@ -4752,6 +4865,9 @@ export function WorkplaneViewport({
|
||||
setRulerMoveMode(false);
|
||||
rulerPointDragRef.current = null;
|
||||
setRulerToolsOpen(false);
|
||||
} else if (shortcutView) {
|
||||
event.preventDefault();
|
||||
setViewCubeFace(shortcutView);
|
||||
} else if (key === "w") {
|
||||
event.preventDefault();
|
||||
if (!event.shiftKey || !setPlacementWorkplaneAtSelection()) {
|
||||
@@ -4774,18 +4890,18 @@ export function WorkplaneViewport({
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, togglePlacementWorkplane, toggleProjection, zoomCamera]);
|
||||
}, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, setViewCubeFace, togglePlacementWorkplane, toggleProjection, zoomCamera]);
|
||||
|
||||
return (
|
||||
<main className={`workplane-stage ${challengeTutorial ? `key-tag-tutorial-active ${challengeTutorialCollapsed ? "key-tag-tutorial-collapsed" : ""}` : ""}`}>
|
||||
<div className="view-cube" aria-label="View orientation cube" onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="view-cube-inner" ref={viewCubeRef}>
|
||||
<button type="button" className="cube-face cube-top" aria-label="Bottom view" onClick={() => setViewCubeFace("bottom")}>BOTTOM</button>
|
||||
<button type="button" className="cube-face cube-bottom" aria-label="Top view" onClick={() => setViewCubeFace("top")}>TOP</button>
|
||||
<button type="button" className="cube-face cube-front" aria-label="Front view" onClick={() => setViewCubeFace("front")}>FRONT</button>
|
||||
<button type="button" className="cube-face cube-back" aria-label="Back view" onClick={() => setViewCubeFace("back")}>BACK</button>
|
||||
<button type="button" className="cube-face cube-right" aria-label="Right view" onClick={() => setViewCubeFace("right")}>RIGHT</button>
|
||||
<button type="button" className="cube-face cube-left" aria-label="Left view" onClick={() => setViewCubeFace("left")}>LEFT</button>
|
||||
<button type="button" className="cube-face cube-top" aria-label="Bottom view" aria-keyshortcuts="6" title="Bottom view (6)" onClick={() => setViewCubeFace("bottom")}>BOTTOM</button>
|
||||
<button type="button" className="cube-face cube-bottom" aria-label="Top view" aria-keyshortcuts="5" title="Top view (5)" onClick={() => setViewCubeFace("top")}>TOP</button>
|
||||
<button type="button" className="cube-face cube-front" aria-label="Front view" aria-keyshortcuts="1" title="Front view (1)" onClick={() => setViewCubeFace("front")}>FRONT</button>
|
||||
<button type="button" className="cube-face cube-back" aria-label="Back view" aria-keyshortcuts="2" title="Back view (2)" onClick={() => setViewCubeFace("back")}>BACK</button>
|
||||
<button type="button" className="cube-face cube-right" aria-label="Right view" aria-keyshortcuts="4" title="Right view (4)" onClick={() => setViewCubeFace("right")}>RIGHT</button>
|
||||
<button type="button" className="cube-face cube-left" aria-label="Left view" aria-keyshortcuts="3" title="Left view (3)" onClick={() => setViewCubeFace("left")}>LEFT</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7088,6 +7204,7 @@ function createShapeObject(
|
||||
);
|
||||
content.position.y = -shape.height / 2;
|
||||
group.add(content);
|
||||
applyGroupedContentTaper(content, shape, contentBox);
|
||||
group.traverse((child) => {
|
||||
child.userData.shapeId = shape.id;
|
||||
});
|
||||
@@ -7259,6 +7376,83 @@ function createImagePlateMaterials(shape: WorkplaneShape, sideMaterial: THREE.Me
|
||||
];
|
||||
}
|
||||
|
||||
function taperGeometryForShape(geometry: THREE.BufferGeometry, shape: WorkplaneShape) {
|
||||
if (!shapeHasTaper(shape)) return geometry;
|
||||
const tapered = geometry.userData.cached ? geometry.clone() : geometry;
|
||||
if (tapered !== geometry) {
|
||||
tapered.userData = {};
|
||||
}
|
||||
tapered.computeBoundingBox();
|
||||
const box = tapered.boundingBox;
|
||||
const position = tapered.getAttribute("position");
|
||||
if (!box || !position) return tapered;
|
||||
const height = Math.max(1e-6, box.max.y - box.min.y);
|
||||
const centerX = (box.min.x + box.max.x) / 2;
|
||||
const centerZ = (box.min.z + box.max.z) / 2;
|
||||
for (let index = 0; index < position.count; index += 1) {
|
||||
const y = position.getY(index);
|
||||
const normalizedHeight = (y - box.min.y) / height;
|
||||
const widthScale = shapeTaperScaleAt(shape, normalizedHeight, "width");
|
||||
const depthScale = shapeTaperScaleAt(shape, normalizedHeight, "depth");
|
||||
position.setXYZ(
|
||||
index,
|
||||
centerX + (position.getX(index) - centerX) * widthScale,
|
||||
y,
|
||||
centerZ + (position.getZ(index) - centerZ) * depthScale,
|
||||
);
|
||||
}
|
||||
position.needsUpdate = true;
|
||||
tapered.computeVertexNormals();
|
||||
tapered.computeBoundingBox();
|
||||
tapered.computeBoundingSphere();
|
||||
return tapered;
|
||||
}
|
||||
|
||||
function applyGroupedContentTaper(content: THREE.Group, shape: WorkplaneShape, baseBounds: THREE.Box3) {
|
||||
if (!shapeHasTaper(shape)) return;
|
||||
const height = Math.max(1e-6, baseBounds.max.y - baseBounds.min.y);
|
||||
const centerX = (baseBounds.min.x + baseBounds.max.x) / 2;
|
||||
const centerZ = (baseBounds.min.z + baseBounds.max.z) / 2;
|
||||
content.updateMatrixWorld(true);
|
||||
const contentWorldInverse = content.matrixWorld.clone().invert();
|
||||
content.traverse((object) => {
|
||||
if (!(object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.LineSegments)) return;
|
||||
if (!(object.geometry instanceof THREE.BufferGeometry)) return;
|
||||
const sourcePosition = object.geometry.getAttribute("position");
|
||||
if (!sourcePosition) return;
|
||||
object.updateMatrixWorld(true);
|
||||
const localToContent = new THREE.Matrix4().multiplyMatrices(contentWorldInverse, object.matrixWorld);
|
||||
const contentToLocal = localToContent.clone().invert();
|
||||
if (object instanceof THREE.Mesh) {
|
||||
releaseSharedShapeGeometry(object);
|
||||
}
|
||||
const nextGeometry = object.geometry.clone();
|
||||
nextGeometry.userData = {};
|
||||
const position = nextGeometry.getAttribute("position");
|
||||
const point = new THREE.Vector3();
|
||||
for (let index = 0; index < position.count; index += 1) {
|
||||
point.fromBufferAttribute(position, index).applyMatrix4(localToContent);
|
||||
const normalizedHeight = (point.y - baseBounds.min.y) / height;
|
||||
const widthScale = shapeTaperScaleAt(shape, normalizedHeight, "width");
|
||||
const depthScale = shapeTaperScaleAt(shape, normalizedHeight, "depth");
|
||||
point.x = centerX + (point.x - centerX) * widthScale;
|
||||
point.z = centerZ + (point.z - centerZ) * depthScale;
|
||||
point.applyMatrix4(contentToLocal);
|
||||
position.setXYZ(index, point.x, point.y, point.z);
|
||||
}
|
||||
position.needsUpdate = true;
|
||||
if (object instanceof THREE.Mesh) {
|
||||
nextGeometry.computeVertexNormals();
|
||||
}
|
||||
nextGeometry.computeBoundingBox();
|
||||
nextGeometry.computeBoundingSphere();
|
||||
object.geometry = nextGeometry;
|
||||
if (object instanceof THREE.Mesh && content.userData.acceleratedPicking !== false) {
|
||||
enableAcceleratedMeshPicking(object, nextGeometry, Boolean(shape.importedMesh));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function addMesh(
|
||||
group: THREE.Group,
|
||||
geometry: THREE.BufferGeometry,
|
||||
@@ -7268,7 +7462,8 @@ function addMesh(
|
||||
rotation?: THREE.Euler,
|
||||
scale?: THREE.Vector3,
|
||||
) {
|
||||
const prepared = geometry.userData.cached ? geometry : putGeometryOnBase(geometry);
|
||||
const based = geometry.userData.cached ? geometry : putGeometryOnBase(geometry);
|
||||
const prepared = taperGeometryForShape(based, shape);
|
||||
const mesh = new THREE.Mesh(prepared, material);
|
||||
mesh.userData.shapeSurface = true;
|
||||
retainSharedShapeGeometry(mesh, prepared);
|
||||
@@ -7375,7 +7570,7 @@ function getPreservedImportedMeshGeometry(shape: WorkplaneShape) {
|
||||
}
|
||||
|
||||
function getEdgesGeometry(shape: WorkplaneShape, geometry: THREE.BufferGeometry, threshold: number) {
|
||||
const importedCache = shape.importedMesh && !preservesEdgeTreatmentSize(shape)
|
||||
const importedCache = shape.importedMesh && !preservesEdgeTreatmentSize(shape) && !shapeHasTaper(shape)
|
||||
? getImportedMeshCache(shape.importedMesh).edges
|
||||
: null;
|
||||
let cache = importedCache ?? sharedEdgesGeometryCache.get(geometry);
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
gearToothPitch,
|
||||
} from "@/lib/gearGeometry";
|
||||
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
|
||||
import { resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
|
||||
import { resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeWidth } from "@/lib/workplaneShapes";
|
||||
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
|
||||
import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
@@ -104,18 +104,52 @@ function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step
|
||||
}
|
||||
|
||||
function propertyUsesLengthUnit(label: string) {
|
||||
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole"].includes(label);
|
||||
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole", "Top Length", "Top Width", "Bottom Length", "Bottom Width"].includes(label);
|
||||
}
|
||||
|
||||
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
|
||||
const width = shapeWidth(shape);
|
||||
const depth = shapeDepth(shape);
|
||||
const setWidth = (value: number) => onUpdate({ width: value, size: resizedShapeSize(value, depth) }, { resizeAxis: "width" });
|
||||
const setDepth = (value: number) => onUpdate({ depth: value, size: resizedShapeSize(width, value) }, { resizeAxis: "depth" });
|
||||
const setConeWidth = (value: number) => onUpdate({ width: value, baseRadius: value / 2, size: resizedShapeSize(value, depth) }, { resizeAxis: "width" });
|
||||
const baseWidth = shapeWidth(shape);
|
||||
const baseDepth = shapeDepth(shape);
|
||||
const footprint = shapeOverallFootprintDimensions(shape);
|
||||
const width = footprint.width;
|
||||
const depth = footprint.depth;
|
||||
const taper = shapeTaperDimensions(shape);
|
||||
const widthPatch = (value: number): Partial<WorkplaneShape> => {
|
||||
if (!shapeHasTaper(shape)) {
|
||||
return { width: value, size: resizedShapeSize(value, baseDepth) };
|
||||
}
|
||||
const scale = value / Math.max(MIN_SHAPE_SIZE, width);
|
||||
const nextBaseWidth = Math.max(MIN_SHAPE_SIZE, baseWidth * scale);
|
||||
return {
|
||||
width: nextBaseWidth,
|
||||
size: resizedShapeSize(nextBaseWidth, baseDepth),
|
||||
taperTopWidth: Math.max(MIN_SHAPE_SIZE, taper.topWidth * scale),
|
||||
taperBottomWidth: Math.max(MIN_SHAPE_SIZE, taper.bottomWidth * scale),
|
||||
};
|
||||
};
|
||||
const depthPatch = (value: number): Partial<WorkplaneShape> => {
|
||||
if (!shapeHasTaper(shape)) {
|
||||
return { depth: value, size: resizedShapeSize(baseWidth, value) };
|
||||
}
|
||||
const scale = value / Math.max(MIN_SHAPE_SIZE, depth);
|
||||
const nextBaseDepth = Math.max(MIN_SHAPE_SIZE, baseDepth * scale);
|
||||
return {
|
||||
depth: nextBaseDepth,
|
||||
size: resizedShapeSize(baseWidth, nextBaseDepth),
|
||||
taperTopDepth: Math.max(MIN_SHAPE_SIZE, taper.topDepth * scale),
|
||||
taperBottomDepth: Math.max(MIN_SHAPE_SIZE, taper.bottomDepth * scale),
|
||||
};
|
||||
};
|
||||
const setWidth = (value: number) => onUpdate(widthPatch(value), { resizeAxis: "width" });
|
||||
const setDepth = (value: number) => onUpdate(depthPatch(value), { resizeAxis: "depth" });
|
||||
const setConeWidth = (value: number) => {
|
||||
const patch = widthPatch(value);
|
||||
patch.baseRadius = Math.max(MIN_SHAPE_SIZE, (patch.width ?? baseWidth) / 2);
|
||||
onUpdate(patch, { resizeAxis: "width" });
|
||||
};
|
||||
const setBaseRadius = (value: number) => {
|
||||
const diameter = value * 2;
|
||||
onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, depth) }, { resizeAxis: "width" });
|
||||
onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, baseDepth) }, { resizeAxis: "width" });
|
||||
};
|
||||
const setHeight = (height: number) => onUpdate({ height }, { resizeAxis: "height" });
|
||||
|
||||
@@ -171,7 +205,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
|
||||
if (shape.kind === "cone") {
|
||||
return [
|
||||
{ label: "Top Radius", value: shape.topRadius ?? 0, min: 0, max: 40, onChange: (topRadius) => onUpdate({ topRadius }) },
|
||||
{ label: "Base Radius", value: shape.baseRadius ?? width / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius },
|
||||
{ label: "Base Radius", value: shape.baseRadius ?? baseWidth / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setConeWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
|
||||
@@ -356,9 +390,41 @@ export function ShapeInspector({
|
||||
const gearHelixProperties = shape.kind === "gear"
|
||||
? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label))
|
||||
: [];
|
||||
const taper = shapeTaperDimensions(shape);
|
||||
const taperProperties: ShapePropertyConfig[] = shape.kind === "gear" ? [] : [
|
||||
{
|
||||
label: "Top Length",
|
||||
value: taper.topDepth,
|
||||
min: MIN_SHAPE_SIZE,
|
||||
max: 480,
|
||||
onChange: (taperTopDepth) => onUpdate({ taperTopDepth, taperTopWidth: taper.topWidth, taperTopScale: undefined }),
|
||||
},
|
||||
{
|
||||
label: "Top Width",
|
||||
value: taper.topWidth,
|
||||
min: MIN_SHAPE_SIZE,
|
||||
max: 480,
|
||||
onChange: (taperTopWidth) => onUpdate({ taperTopWidth, taperTopDepth: taper.topDepth, taperTopScale: undefined }),
|
||||
},
|
||||
{
|
||||
label: "Bottom Length",
|
||||
value: taper.bottomDepth,
|
||||
min: MIN_SHAPE_SIZE,
|
||||
max: 480,
|
||||
onChange: (taperBottomDepth) => onUpdate({ taperBottomDepth, taperBottomWidth: taper.bottomWidth, taperBottomScale: undefined }),
|
||||
},
|
||||
{
|
||||
label: "Bottom Width",
|
||||
value: taper.bottomWidth,
|
||||
min: MIN_SHAPE_SIZE,
|
||||
max: 480,
|
||||
onChange: (taperBottomWidth) => onUpdate({ taperBottomWidth, taperBottomDepth: taper.bottomDepth, taperBottomScale: undefined }),
|
||||
},
|
||||
];
|
||||
const isSketchRevolve = shape.sketchOperation === "revolve" || Boolean(shape.sketchRevolve);
|
||||
const inspectorRef = useRef<HTMLElement>(null);
|
||||
const [propertiesOpen, setPropertiesOpen] = useState(true);
|
||||
const [taperOpen, setTaperOpen] = useState(false);
|
||||
const [gearTeethOpen, setGearTeethOpen] = useState(true);
|
||||
const [gearHelixOpen, setGearHelixOpen] = useState(true);
|
||||
const [colorOpen, setColorOpen] = useState(false);
|
||||
@@ -513,6 +579,25 @@ export function ShapeInspector({
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{shape.kind !== "gear" ? (
|
||||
<div className={`property-card ${taperOpen ? "" : "collapsed"}`}>
|
||||
<button
|
||||
className="property-card-header"
|
||||
type="button"
|
||||
aria-expanded={taperOpen}
|
||||
aria-controls={`taper-${shape.id}`}
|
||||
onClick={() => setTaperOpen((open) => !open)}
|
||||
>
|
||||
<span>Taper</span>
|
||||
<ChevronUp className={taperOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
|
||||
</button>
|
||||
{taperOpen ? (
|
||||
<div className="property-list" id={`taper-${shape.id}`}>
|
||||
<ShapePropertyRows properties={taperProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{shape.kind === "gear" ? (
|
||||
<div className={`property-card ${gearTeethOpen ? "" : "collapsed"}`}>
|
||||
<button
|
||||
@@ -631,7 +716,7 @@ function RangeProperty({
|
||||
onChange,
|
||||
onInteractionActiveChange,
|
||||
}: RangePropertyConfig & { workspace: WorkplaneWorkspaceSettings; disabled?: boolean; onInteractionActiveChange?: (active: boolean) => void }) {
|
||||
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height";
|
||||
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height" || label.endsWith(" Length") || label.endsWith(" Width");
|
||||
const isLength = propertyUsesLengthUnit(label);
|
||||
const accuracy = workspace.accuracy;
|
||||
const actualValue = Math.max(min, Number.isFinite(value) ? value : min);
|
||||
@@ -644,11 +729,6 @@ function RangeProperty({
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(formatPropertyNumber(controlValue, accuracy, controlStep));
|
||||
const unit = isLength ? lengthDisplayUnit(workspace).label : null;
|
||||
useEffect(() => {
|
||||
if (!editing) {
|
||||
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
|
||||
}
|
||||
}, [accuracy, controlStep, controlValue, editing]);
|
||||
const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue;
|
||||
const commitDraft = () => {
|
||||
const next = parseMeasurementInput(draft);
|
||||
|
||||
Reference in New Issue
Block a user