release: publish v1.0.0

This commit is contained in:
Formsmith
2026-08-10 16:15:32 +03:00
parent decf33521a
commit a42922c4f3
56 changed files with 3914 additions and 125 deletions
+65
View File
@@ -0,0 +1,65 @@
export const OFFICIAL_UPDATE_GUIDE_URL = "https://github.com/Formsmith746/SketchForge-3D#update-sketchforge-later";
export type AppUpdateStatus = {
currentVersion: string;
latestVersion: string | null;
updateAvailable: boolean;
checkedAt: string;
updateUrl: string;
installationReady: boolean;
requiresUpdateKey: boolean;
checkError?: string;
};
type ParsedVersion = {
major: number;
minor: number;
patch: number;
prerelease: string[];
};
function parseVersion(value: string): ParsedVersion | null {
const match = value.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
if (!match) return null;
return {
major: Number(match[1]),
minor: Number(match[2]),
patch: Number(match[3]),
prerelease: match[4] ? match[4].split(".") : [],
};
}
function comparePrereleasePart(left: string, right: string) {
const leftNumber = /^\d+$/.test(left) ? Number(left) : null;
const rightNumber = /^\d+$/.test(right) ? Number(right) : null;
if (leftNumber !== null && rightNumber !== null) return Math.sign(leftNumber - rightNumber);
if (leftNumber !== null) return -1;
if (rightNumber !== null) return 1;
return left.localeCompare(right);
}
export function compareAppVersions(leftValue: string, rightValue: string) {
const left = parseVersion(leftValue);
const right = parseVersion(rightValue);
if (!left || !right) return leftValue.trim().localeCompare(rightValue.trim());
for (const key of ["major", "minor", "patch"] as const) {
if (left[key] !== right[key]) return Math.sign(left[key] - right[key]);
}
if (!left.prerelease.length && !right.prerelease.length) return 0;
if (!left.prerelease.length) return 1;
if (!right.prerelease.length) return -1;
const partCount = Math.max(left.prerelease.length, right.prerelease.length);
for (let index = 0; index < partCount; index += 1) {
if (left.prerelease[index] === undefined) return -1;
if (right.prerelease[index] === undefined) return 1;
const comparison = comparePrereleasePart(left.prerelease[index], right.prerelease[index]);
if (comparison !== 0) return comparison;
}
return 0;
}
export function appUpdateIsAvailable(currentVersion: string, latestVersion: string) {
return compareAppVersions(latestVersion, currentVersion) > 0;
}
+7
View File
@@ -0,0 +1,7 @@
export const CHALLENGE_TUTORIAL_IDS = ["key-tag", "nameplate"] as const;
export type ChallengeTutorialId = (typeof CHALLENGE_TUTORIAL_IDS)[number];
export function isChallengeTutorialId(value: unknown): value is ChallengeTutorialId {
return typeof value === "string" && CHALLENGE_TUTORIAL_IDS.includes(value as ChallengeTutorialId);
}
+11
View File
@@ -0,0 +1,11 @@
export type MeshPoint = readonly [number, number, number];
/** Maps the Z-up coordinate convention used by slicers/CAD files into SketchForge's Y-up scene. */
export function zUpToSketchForge([x, y, z]: MeshPoint): [number, number, number] {
return [x, z, -y];
}
/** Maps SketchForge's Y-up scene into the Z-up coordinate convention expected by slicers. */
export function sketchForgeToZUp([x, y, z]: MeshPoint): [number, number, number] {
return [x, -z, y];
}
+79
View File
@@ -0,0 +1,79 @@
import type { MeshPoint } from "@/lib/meshCoordinates";
export type ObjExportMesh = {
name: string;
vertices: readonly MeshPoint[];
faces: readonly (readonly [number, number, number])[];
};
const OBJ_WELD_TOLERANCE = 0.00001;
function bucketKey(x: number, y: number, z: number) {
return `${x}:${y}:${z}`;
}
function weldMeshVertices(mesh: ObjExportMesh) {
const vertices: Array<[number, number, number]> = [];
const buckets = new Map<string, number[]>();
const remappedIndices: number[] = [];
mesh.vertices.forEach((sourceVertex) => {
// OBJ tools conventionally treat Y as up. Keep SketchForge's Y-up
// coordinates here so slicers do not apply their OBJ axis conversion a
// second time. STL is exported separately using explicit Z-up coordinates.
const vertex: [number, number, number] = [...sourceVertex];
const bucketX = Math.floor(vertex[0] / OBJ_WELD_TOLERANCE);
const bucketY = Math.floor(vertex[1] / OBJ_WELD_TOLERANCE);
const bucketZ = Math.floor(vertex[2] / OBJ_WELD_TOLERANCE);
let weldedIndex: number | undefined;
for (let xOffset = -1; xOffset <= 1 && weldedIndex === undefined; xOffset += 1) {
for (let yOffset = -1; yOffset <= 1 && weldedIndex === undefined; yOffset += 1) {
for (let zOffset = -1; zOffset <= 1 && weldedIndex === undefined; zOffset += 1) {
const candidates = buckets.get(bucketKey(bucketX + xOffset, bucketY + yOffset, bucketZ + zOffset)) ?? [];
weldedIndex = candidates.find((candidateIndex) => {
const candidate = vertices[candidateIndex];
return (
Math.abs(candidate[0] - vertex[0]) <= OBJ_WELD_TOLERANCE &&
Math.abs(candidate[1] - vertex[1]) <= OBJ_WELD_TOLERANCE &&
Math.abs(candidate[2] - vertex[2]) <= OBJ_WELD_TOLERANCE
);
});
}
}
}
if (weldedIndex === undefined) {
weldedIndex = vertices.length;
vertices.push(vertex);
const key = bucketKey(bucketX, bucketY, bucketZ);
buckets.set(key, [...(buckets.get(key) ?? []), weldedIndex]);
}
remappedIndices.push(weldedIndex);
});
const faces = mesh.faces
.map(([a, b, c]) => [remappedIndices[a], remappedIndices[b], remappedIndices[c]] as [number, number, number])
.filter(([a, b, c]) => a !== b && b !== c && c !== a);
return { vertices, faces };
}
function objNumber(value: number) {
return Math.abs(value) < 1e-12 ? "0" : String(value);
}
export function exportMeshesToObj(meshes: readonly ObjExportMesh[]) {
const lines = ["# SketchForge OBJ export"];
let offset = 1;
meshes.forEach((mesh) => {
const welded = weldMeshVertices(mesh);
lines.push(`o ${mesh.name}`);
welded.vertices.forEach(([x, y, z]) => lines.push(`v ${objNumber(x)} ${objNumber(y)} ${objNumber(z)}`));
welded.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`));
offset += welded.vertices.length;
});
return lines.join("\n");
}
+151
View File
@@ -0,0 +1,151 @@
import type { SketchPoint, SketchProfile, SketchSegment } from "@/types/sketchforge";
export type OrderedCadSketchStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
export type OrderedCadSketchPath = { id: string; points: SketchPoint[]; steps: OrderedCadSketchStep[]; closed: boolean };
export type CadSketchRegion = { outer: OrderedCadSketchPath; holes: OrderedCadSketchPath[] };
export function orderedCadSketchPaths(profile: SketchProfile): OrderedCadSketchPath[] {
const pointById = new Map(profile.points.map((point) => [point.id, point]));
const adjacency = new Map<string, Array<{ pointId: string; segment: SketchSegment }>>();
profile.points.forEach((point) => adjacency.set(point.id, []));
const valid = profile.segments.filter((segment) => {
if (segment.startId === segment.endId || !pointById.has(segment.startId) || !pointById.has(segment.endId)) return false;
adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment });
adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment });
return true;
});
const unvisited = new Set(valid.map((segment) => segment.id));
const paths: OrderedCadSketchPath[] = [];
while (unvisited.size > 0) {
const seedId = unvisited.values().next().value as string;
const seed = valid.find((segment) => segment.id === seedId);
if (!seed) break;
const component = new Set<string>();
const queue = [seed.startId, seed.endId];
while (queue.length > 0) {
const id = queue.pop();
if (!id || component.has(id)) continue;
component.add(id);
adjacency.get(id)?.forEach((edge) => queue.push(edge.pointId));
}
const startId = [...component].find((id) => (adjacency.get(id)?.filter((edge) => unvisited.has(edge.segment.id)).length ?? 0) === 1) ?? seed.startId;
const first = pointById.get(startId);
if (!first) {
unvisited.delete(seed.id);
continue;
}
const points = [first];
const steps: OrderedCadSketchStep[] = [];
let currentId = startId;
for (let guard = 0; guard <= valid.length; guard += 1) {
const edge = adjacency.get(currentId)?.find((candidate) => unvisited.has(candidate.segment.id));
if (!edge) break;
const from = pointById.get(currentId);
const to = pointById.get(edge.pointId);
if (!from || !to) break;
unvisited.delete(edge.segment.id);
steps.push({ segment: edge.segment, from, to });
currentId = to.id;
if (currentId === startId) break;
points.push(to);
}
paths.push({ id: seed.id, points, steps, closed: currentId === startId && steps.length >= 3 });
}
return paths;
}
function sampledPath(path: OrderedCadSketchPath) {
const samples: Array<{ x: number; z: number }> = [];
path.steps.forEach(({ segment, from, to }, stepIndex) => {
if (stepIndex === 0) samples.push({ x: from.x, z: from.z });
const forward = segment.startId === from.id;
const first = forward ? from.handleOut : from.handleIn;
const second = forward ? to.handleIn : to.handleOut;
if (segment.kind === "line" || !first || !second) {
samples.push({ x: to.x, z: to.z });
return;
}
for (let index = 1; index <= 16; index += 1) {
const amount = index / 16;
const inverse = 1 - amount;
samples.push({
x: inverse ** 3 * from.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * to.x,
z: inverse ** 3 * from.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * to.z,
});
}
});
return samples;
}
function signedArea(points: Array<{ x: number; z: number }>) {
return points.reduce((area, point, index) => {
const next = points[(index + 1) % points.length];
return area + point.x * next.z - next.x * point.z;
}, 0) / 2;
}
function pointInPolygon(point: { x: number; z: number }, polygon: Array<{ x: number; z: number }>) {
let inside = false;
for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) {
const current = polygon[index];
const before = polygon[previous];
if ((current.z > point.z) !== (before.z > point.z)
&& point.x < ((before.x - current.x) * (point.z - current.z)) / (before.z - current.z) + current.x) inside = !inside;
}
return inside;
}
export function cadSketchRegions(profile: SketchProfile): CadSketchRegion[] {
const allPaths = orderedCadSketchPaths(profile);
const openCount = allPaths.filter((path) => !path.closed).length;
const records = allPaths
.filter((path) => path.closed)
.map((path) => {
const polygon = sampledPath(path);
return { path, polygon, area: Math.abs(signedArea(polygon)) };
})
.filter((record) => record.polygon.length >= 3 && record.area > 1e-8)
.sort((a, b) => b.area - a.area);
// Compute nesting depth: count how many larger closed paths contain each record.
// Even depth = solid (outer boundary), odd depth = hole.
const depths = records.map((record, index) => {
let depth = 0;
for (let i = 0; i < records.length; i++) {
if (i === index) continue;
if (records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) {
depth++;
}
}
return depth;
});
const regions: CadSketchRegion[] = [];
records.forEach((record, index) => {
const depth = depths[index];
if (depth % 2 === 0) {
regions.push({ outer: record.path, holes: [] });
} else {
// Odd depth: find the nearest even-depth ancestor (smallest containing solid)
let bestParent: (typeof records)[number] | null = null;
for (let i = 0; i < records.length; i++) {
if (i === index) continue;
if (depths[i] % 2 === 0 && depths[i] < depth && records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) {
if (!bestParent || records[i].area < bestParent.area) {
bestParent = records[i];
}
}
}
if (bestParent) {
const region = regions.find((r) => r.outer === bestParent!.path);
if (region) region.holes.push(record.path);
}
}
});
if (regions.length === 0 && openCount > 0 && allPaths.length > 0) {
throw new Error("All profile paths are open. Close at least one loop before finishing the sketch.");
}
return regions;
}
+20
View File
@@ -0,0 +1,20 @@
import type { SketchProfile } from "@/types/sketchforge";
export type SketchCadBuildRequest = {
type: "build";
requestId: number;
profile: SketchProfile;
height: number;
};
export type SketchCadBuildResponse =
| {
type: "built";
requestId: number;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
triangleCount: number;
brep: string;
}
| { type: "error"; requestId: number; message: string };
+1 -1
View File
@@ -11,7 +11,7 @@ import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation,
export const SKF_SCHEMA_ID = "com.sketchforge.project";
export const SKF_FORMAT_VERSION = 1;
export const SKF_MINIMUM_READER_VERSION = 1;
export const SKF_CREATED_WITH_VERSION = "0.9.0";
export const SKF_CREATED_WITH_VERSION = "1.0.0";
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
export const SKF_LIMITS = {
+41
View File
@@ -0,0 +1,41 @@
import { sketchForgeToZUp, type MeshPoint } from "@/lib/meshCoordinates";
export type StlExportMesh = {
vertices: readonly MeshPoint[];
faces: readonly (readonly [number, number, number])[];
};
function normalFor(a: MeshPoint, b: MeshPoint, c: MeshPoint): [number, number, number] {
const ux = b[0] - a[0];
const uy = b[1] - a[1];
const uz = b[2] - a[2];
const vx = c[0] - a[0];
const vy = c[1] - a[1];
const vz = c[2] - a[2];
const nx = uy * vz - uz * vy;
const ny = uz * vx - ux * vz;
const nz = ux * vy - uy * vx;
const length = Math.hypot(nx, ny, nz) || 1;
return [nx / length, ny / length, nz / length];
}
export function exportMeshesToStl(meshes: readonly StlExportMesh[]) {
const lines = ["solid sketchforge_design"];
meshes.forEach((mesh) => {
mesh.faces.forEach(([ai, bi, ci]) => {
const a = sketchForgeToZUp(mesh.vertices[ai]);
const b = sketchForgeToZUp(mesh.vertices[bi]);
const c = sketchForgeToZUp(mesh.vertices[ci]);
const n = normalFor(a, b, c);
lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`);
lines.push(" outer loop");
lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`);
lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`);
lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`);
lines.push(" endloop");
lines.push(" endfacet");
});
});
lines.push("endsolid sketchforge_design");
return lines.join("\n");
}
+34 -2
View File
@@ -1,6 +1,7 @@
import * as THREE from "three";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
import { createLocalId } from "@/lib/localIds";
import { zUpToSketchForge } from "@/lib/meshCoordinates";
import type { WorkplaneShape } from "@/types/sketchforge";
const stlLoader = new STLLoader();
@@ -10,6 +11,34 @@ function fileExtension(fileName: string) {
return fileName.split(".").pop()?.toLowerCase() ?? "";
}
function stlHeader(buffer: ArrayBuffer) {
return new TextDecoder("ascii").decode(new Uint8Array(buffer, 0, Math.min(80, buffer.byteLength))).toLowerCase();
}
function stlUsesSketchForgeYUp(buffer: ArrayBuffer, position: THREE.BufferAttribute | THREE.InterleavedBufferAttribute) {
// SketchForge's older ASCII STL exports were already Y-up. Preserve those,
// including tall models where geometry alone cannot reveal an up axis.
if (stlHeader(buffer).includes("sketchforge")) return true;
let minY = Number.POSITIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let i = 0; i < position.count; i += 1) {
minY = Math.min(minY, position.getY(i));
maxY = Math.max(maxY, position.getY(i));
minZ = Math.min(minZ, position.getZ(i));
maxZ = Math.max(maxZ, position.getZ(i));
}
const ySpan = maxY - minY;
const zSpan = maxZ - minZ;
// Some legacy/model-library STLs (including the Raspberry Pi fixture) are
// unmistakably flat on Y. Keep that established orientation; ambiguous STL
// files follow the slicer-standard Z-up convention.
return Number.isFinite(ySpan) && Number.isFinite(zSpan) && ySpan <= zSpan * 0.55;
}
export function importedShapeFromTriangleSoup(
fileName: string,
rawPositions: number[],
@@ -97,11 +126,14 @@ export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): Wor
const normal = geometry.getAttribute("normal");
const rawPositions: number[] = [];
const rawNormals: number[] = [];
const usesSketchForgeYUp = stlUsesSketchForgeYUp(buffer, position);
for (let i = 0; i < position.count; i += 1) {
rawPositions.push(position.getX(i), position.getY(i), position.getZ(i));
const sourcePosition: [number, number, number] = [position.getX(i), position.getY(i), position.getZ(i)];
rawPositions.push(...(usesSketchForgeYUp ? sourcePosition : zUpToSketchForge(sourcePosition)));
if (normal) {
rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
const sourceNormal: [number, number, number] = [normal.getX(i), normal.getY(i), normal.getZ(i)];
rawNormals.push(...(usesSketchForgeYUp ? sourceNormal : zUpToSketchForge(sourceNormal)));
}
}