feat: sesli CAD asistani, bellek optimizasyonlari ve akilli cozunurluk
CI / Typecheck and unit tests (push) Canceled after 0s
Build and Push Docker Images / build (push) Canceled after 0s

- SnapVoice Turkce sesli CAD ve komut konsolu (/denetle, /ram, /eko, /otomatik, /sessiz)
- 3B uzamsal sesli radar ve gorme engelli gelistirici geometri denetim motoru
- LibreDWG/DXF ikili sikistirma, font tembel yukleme ve RAM optimizasyonu
- Monitor cozunurlugune gore otomatik uyarlamali dinamik grafik modu
This commit is contained in:
Enes Yakıştır
2026-11-02 13:37:37 +03:00
parent c09407bcb3
commit e7b6db9db6
32 changed files with 5503 additions and 285 deletions
+88
View File
@@ -236,6 +236,94 @@ button {
transform: translate(-50%, -50%);
}
/* Progressive Editor Loading HUD */
.editor-loading-hud {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 20;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
width: min(92vw, 420px);
padding: 24px 28px;
background: rgba(15, 23, 42, 0.94);
backdrop-filter: blur(12px);
border: 1px solid rgba(56, 189, 248, 0.4);
border-radius: 16px;
box-shadow: 0 20px 45px rgba(0, 0, 0, 0.4), 0 0 30px rgba(14, 165, 233, 0.2);
color: #f8fafc;
}
.editor-loading-hud-badge {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 4px 12px;
background: rgba(14, 165, 233, 0.15);
border: 1px solid rgba(56, 189, 248, 0.35);
border-radius: 999px;
font-size: 11px;
font-weight: 700;
color: #38bdf8;
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 12px;
}
.editor-loading-pulse-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #38bdf8;
box-shadow: 0 0 10px #38bdf8;
animation: pulse-dot 1.2s ease-in-out infinite;
}
@keyframes pulse-dot {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.4; transform: scale(0.8); }
}
.editor-loading-hud-title {
font-size: 17px;
font-weight: 800;
color: #f1f5f9;
margin-bottom: 6px;
line-height: 1.3;
}
.editor-loading-hud-stage {
font-size: 13px;
color: #94a3b8;
margin: 0 0 16px 0;
line-height: 1.4;
}
.editor-loading-progress-track {
width: 100%;
height: 8px;
background: rgba(51, 65, 85, 0.8);
border-radius: 999px;
overflow: hidden;
margin-bottom: 12px;
}
.editor-loading-progress-bar {
height: 100%;
background: linear-gradient(90deg, #0ea5e9, #10b981);
border-radius: 999px;
transition: width 240ms ease-out;
box-shadow: 0 0 12px rgba(16, 185, 129, 0.6);
}
.editor-loading-hud-hint {
font-size: 11px;
color: #64748b;
}
.editor-loading-view-cube {
position: absolute;
top: 22px;
+90 -4
View File
@@ -41,6 +41,7 @@ import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceF
import { hydrateProjectShapeState, reconcileLoadedProjectShapeCacheEntry, type ImportedMeshResource } from "@/lib/projectShapePersistence";
import { exportSkfProject, importSkfProject, SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
import { importExtensionSupported } from "@/lib/importExtensions";
import { speakTurkish } from "@/lib/accessibility";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -536,6 +537,8 @@ export default function Home() {
const [view, setView] = useState<AppView>("dashboard");
const [editorStarted, setEditorStarted] = useState(false);
const [editorLoading, setEditorLoading] = useState(false);
const [editorLoadingStage, setEditorLoadingStage] = useState("Aşama 1/3: SnapCAD çekirdeği başlatılıyor…");
const [editorLoadingProgress, setEditorLoadingProgress] = useState(30);
const [activeProjectId, setActiveProjectId] = useState<string | null>(null);
const [projects, setProjects] = useState<DashboardProject[]>([]);
const [dashboardSection, setDashboardSection] = useState<DashboardSection>("home");
@@ -568,6 +571,8 @@ export default function Home() {
const startEditorTransition = useCallback(() => {
editorLoadingStartedAtRef.current = Date.now();
setEditorLoadingStage("Aşama 1/3: SnapCAD çekirdeği başlatılıyor…");
setEditorLoadingProgress(30);
setEditorLoading(true);
}, []);
@@ -776,10 +781,15 @@ export default function Home() {
const cached = projectShapesById[activeProjectId];
if (cached && cached.revision >= (activeProject.revision ?? 0)) return;
setEditorLoadingStage("Aşama 2/3: Proje modeli ve şekiller hafızaya yükleniyor…");
setEditorLoadingProgress(60);
let canceled = false;
void loadProjectShapes(activeProjectId)
.then((record) => {
if (canceled) return;
setEditorLoadingStage("Aşama 3/3: 3B geometri ve çizim motoru hazırlanıyor…");
setEditorLoadingProgress(90);
const loadedRevision = record?.revision ?? 0;
const revision = Math.max(activeProject.revision ?? 0, loadedRevision, 1);
const loadedEntry = projectShapeCacheEntry(Math.max(loadedRevision, 1), record?.shapes ?? [], record?.history, record?.historyIndex, record?.assets);
@@ -840,7 +850,15 @@ export default function Home() {
const elapsed = Date.now() - editorLoadingStartedAtRef.current;
const remaining = Math.max(0, EDITOR_SKELETON_MIN_DURATION_MS - elapsed);
const timer = window.setTimeout(() => {
window.requestAnimationFrame(() => setEditorLoading(false));
window.requestAnimationFrame(() => {
setEditorLoadingProgress(100);
setEditorLoadingStage("SnapCAD Studio hazır. Odak kipi aktif.");
setEditorLoading(false);
const activeProj = projects.find((p) => p.id === activeProjectId);
if (activeProj) {
speakTurkish(`SnapCAD Studio hazır. ${activeProj.name} açıldı. Odak kipi devrede.`);
}
});
}, remaining);
return () => window.clearTimeout(timer);
}, [activeProjectId, editorLoading, projectShapesById, projects, view]);
@@ -852,6 +870,40 @@ export default function Home() {
window.localStorage.setItem(PROJECT_NAME_TOOLBAR_STORAGE_KEY, String(showProjectNameInToolbar));
}, [downloadFolder, downloadMode, mounted, showProjectNameInToolbar]);
// Bellek Optimizasyonu (RAM Pruning):
// Aktif olmayan projelerin hafızadaki 3B geometri ve mesh verileri temizlenir.
// Tüm projeler IndexedDB'de saklandığı için gerektiğinde gecikmesiz yeniden açılır.
useEffect(() => {
const handleRamCleanup = () => {
setProjectShapesById((current) => {
const next: Record<string, ProjectShapeCacheEntry> = {};
for (const [id, entry] of Object.entries(current)) {
if (id === activeProjectId || id in projectShapeSaveQueuesRef.current) {
next[id] = entry;
}
}
return next;
});
};
window.addEventListener("sketchforge:ram-cleanup", handleRamCleanup);
return () => window.removeEventListener("sketchforge:ram-cleanup", handleRamCleanup);
}, [activeProjectId]);
useEffect(() => {
if (!activeProjectId) return;
setProjectShapesById((current) => {
const ids = Object.keys(current);
if (ids.length <= 2) return current;
const next: Record<string, ProjectShapeCacheEntry> = {};
for (const id of ids) {
if (id === activeProjectId || id in projectShapeSaveQueuesRef.current) {
next[id] = current[id];
}
}
return next;
});
}, [activeProjectId]);
const visibleProjects = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase();
const filtered = normalizedQuery ? projects.filter((project) => project.name.toLowerCase().includes(normalizedQuery)) : projects;
@@ -1725,7 +1777,13 @@ export default function Home() {
/>
</div>
) : null}
{view === "editor" && (editorLoading || !canRenderEditor) ? <EditorLoadingSkeleton /> : null}
{view === "editor" && (editorLoading || !canRenderEditor) ? (
<EditorLoadingSkeleton
projectName={activeProject?.name}
stageText={editorLoadingStage}
progress={editorLoadingProgress}
/>
) : null}
<GlobalAccessibilityToolbar
onQuickNavigate={(target) => {
if (target === "create3d") {
@@ -1741,7 +1799,15 @@ export default function Home() {
);
}
function EditorLoadingSkeleton() {
function EditorLoadingSkeleton({
projectName,
stageText,
progress = 40,
}: {
projectName?: string;
stageText?: string;
progress?: number;
}) {
const leftToolbarSections = [
{ className: "home", controls: 1 },
{ className: "clipboard", controls: 4 },
@@ -1768,7 +1834,7 @@ function EditorLoadingSkeleton() {
);
return (
<div className="editor-loading-screen" role="status" aria-label="Loading editor" aria-live="polite">
<div className="editor-loading-screen" role="status" aria-label="SnapCAD yükleniyor" aria-live="polite">
<div className="editor-loading-toolbar">
<div className="editor-loading-tabs">
<span className="editor-skeleton-shimmer" />
@@ -1787,6 +1853,26 @@ function EditorLoadingSkeleton() {
<div className="editor-loading-body">
<div className="editor-loading-viewport">
<div className="editor-loading-hud" role="status" aria-live="polite">
<div className="editor-loading-hud-badge">
<span className="editor-loading-pulse-dot" aria-hidden="true" />
<span>Kademeli Sayfa Yükleme</span>
</div>
<strong className="editor-loading-hud-title">
{projectName ? `"${projectName}" hazırlanıyor…` : "SnapCAD Studio açılıyor…"}
</strong>
<p className="editor-loading-hud-stage">{stageText || "3B geometri ve çizim alanı hazırlanıyor…"}</p>
<div className="editor-loading-progress-track" aria-hidden="true">
<div
className="editor-loading-progress-bar"
style={{ width: `${Math.min(100, Math.max(10, progress))}%` }}
/>
</div>
<div className="editor-loading-hud-hint">
Ekran okuyucu odak kipi otomatik olarak açılacaktır
</div>
</div>
<div className="editor-loading-view-cube">
<span className="editor-loading-cube-top editor-skeleton-shimmer" />
<span className="editor-loading-cube-left editor-skeleton-shimmer" />
+306 -10
View File
@@ -73,6 +73,12 @@ import { TerrainGeneratorModal } from "./snapcad/TerrainGeneratorModal";
import { PaintBucketHUD } from "./snapcad/PaintBucketHUD";
import { InteractiveTutorialModal } from "./snapcad/InteractiveTutorialModal";
import { WallOpeningModal, type WallCutoutConfig } from "./snapcad/WallOpeningModal";
import { audit3DScene, type Scene3DAuditReport } from "@/lib/cadAuditor";
import { CadAuditModal } from "./snapcad/CadAuditModal";
import { VoiceCadModal } from "./snapcad/VoiceCadModal";
import type { ParsedCadCommand } from "@/lib/voiceCadCommander";
import { sonifyAndAnnounceShape } from "@/lib/spatialAudioSonar";
import { setVoiceFeedbackEnabled, speakTurkish } from "@/lib/accessibility";
import { DailyChallengesModal } from "./snapcad/DailyChallengesModal";
import { SNAPCAD_PREFABS } from "@/lib/snapcadPrefabs";
import { soundEngine } from "@/lib/audioFx";
@@ -147,7 +153,7 @@ import { exportMeshesTo3mf } from "@/lib/threemfExport";
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
import { exportMeshesToDxf } from "@/lib/dxfExport";
import { importedShapeFromDxf } from "@/lib/dxfImport";
import { importedShapeFromDxf, getImportedDxfText } from "@/lib/dxfImport";
import { importedShapeFromGlb } from "@/lib/glbImport";
import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
import {
@@ -280,15 +286,27 @@ const NORMAL_SELECTION_CAD_EDGE_MIN_ANGLE = 60;
const MIN_EDGE_MODIFIER_AMOUNT = 0.001;
const SEPARATE_PARTS_VERTEX_TOLERANCE = 0.0005;
const booleanFontLoader = new FontLoader();
const booleanTextFonts: Record<string, Font> = {
Multilanguage: booleanFontLoader.parse(helvetikerBoldFontJson as FontData),
Sans: booleanFontLoader.parse(droidSansBoldFontJson as FontData),
Serif: booleanFontLoader.parse(droidSerifBoldFontJson as FontData),
Script: booleanFontLoader.parse(gentilisBoldFontJson as FontData),
Monospace: booleanFontLoader.parse(droidMonoFontJson as FontData),
Rounded: booleanFontLoader.parse(optimerBoldFontJson as FontData),
Stencil: booleanFontLoader.parse(helvetikerBoldFontJson as FontData),
const rawBooleanFontData: Record<string, unknown> = {
Multilanguage: helvetikerBoldFontJson,
Sans: droidSansBoldFontJson,
Serif: droidSerifBoldFontJson,
Script: gentilisBoldFontJson,
Monospace: droidMonoFontJson,
Rounded: optimerBoldFontJson,
Stencil: helvetikerBoldFontJson,
};
const parsedBooleanFontsCache = new Map<string, Font>();
function getLazyBooleanFont(name?: string): Font {
const fontName = name && name in rawBooleanFontData ? name : "Multilanguage";
let font = parsedBooleanFontsCache.get(fontName);
if (!font) {
const rawData = rawBooleanFontData[fontName] ?? rawBooleanFontData.Multilanguage;
font = booleanFontLoader.parse(rawData as FontData);
parsedBooleanFontsCache.set(fontName, font);
}
return font;
}
let manifoldRuntimePromise: Promise<ManifoldToplevel> | null = null;
function emptySketchProfile(): SketchProfile {
@@ -2170,7 +2188,7 @@ function createBooleanTextGeometry(shape: WorkplaneShape) {
const bevel = clampNumber(shape.bevel ?? 0, 0, 8);
const fontName = shape.font ?? "Multilanguage";
const geometry = new TextGeometry(text, {
font: booleanTextFonts[fontName] ?? booleanTextFonts.Multilanguage,
font: getLazyBooleanFont(fontName),
size: 20,
depth: shape.height,
curveSegments: fontName === "Stencil" ? 1 : 8,
@@ -2732,6 +2750,13 @@ async function toSvg(shapes: WorkplaneShape[], title: string) {
}
async function toDxf(shapes: WorkplaneShape[], title: string) {
// If exporting a single shape imported from DWG or DXF with original source DXF text,
// re-emit the original pristine CAD drawing directly to avoid 200+ MB re-triangulation!
const pristineDxf = shapes.length === 1 ? getImportedDxfText(shapes[0].importedMesh) : undefined;
if (pristineDxf) {
return pristineDxf;
}
const meshes = shapes.map(meshForShape);
const layers: SvgProjectionLayer[] = [];
try {
@@ -5670,6 +5695,27 @@ export function SketchForgeEditor({
const [isDailyChallengesOpen, setIsDailyChallengesOpen] = useState(false);
const [isWallOpeningModalOpen, setIsWallOpeningModalOpen] = useState(false);
const [targetWallIdForOpening, setTargetWallIdForOpening] = useState<string | null>(null);
const [isCadAuditModalOpen, setIsCadAuditModalOpen] = useState(false);
const [isVoiceCadModalOpen, setIsVoiceCadModalOpen] = useState(false);
const [sceneAuditReport, setSceneAuditReport] = useState<Scene3DAuditReport | null>(null);
const editorContainerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
// NVDA ve ekran okuyucularının otomatik Odak Kipi'ne (Focus Mode) geçmesi için
// uygulama çalışma alanına odaklanılır. Bu sayede 'I', 'G', 'D', 'P' gibi tek tuşlar
// ekran okuyucu tarafından kesilmeden doğrudan CAD ortamına iletilir.
const timer = setTimeout(() => {
editorContainerRef.current?.focus({ preventScroll: true });
}, 120);
return () => clearTimeout(timer);
}, []);
const handleOpenAudit = useCallback(() => {
const report = audit3DScene(shapes);
setSceneAuditReport(report);
setIsCadAuditModalOpen(true);
}, [shapes]);
const handleChallengeAction = useCallback(
(action: "load_domino" | "load_villa" | "start_walk" | "blueprint") => {
@@ -8501,6 +8547,157 @@ export function SketchForgeEditor({
);
}, [commitShapes, selectedShape, selectedShapes.length, shapes]);
const handleExecuteVoiceCommand = useCallback((cmd: ParsedCadCommand) => {
switch (cmd.action) {
case "add_shape": {
if (cmd.payload?.kind) {
const kind = cmd.payload.kind;
const asset = toolbarShapeAssets.find((a) => a.kind === kind) ?? toolbarShapeAssets[0];
const width = cmd.payload.width ?? 20;
const depth = cmd.payload.depth ?? 20;
const height = cmd.payload.height ?? 20;
const isHole = Boolean(cmd.payload.isHole);
const name = cmd.payload.name || asset.name;
const newShape = sceneShape({
...makeShapeFromAsset(
{ ...asset, name, hole: isHole },
{ x: 0, z: 0, elevation: 0 },
{ width, depth, height },
),
id: createLocalId("voice"),
name,
width,
depth,
height,
hole: isHole,
});
commitShapes([...shapesRef.current, newShape], newShape.id, `${name} eklendi`);
playSynthesizedSound("pop");
}
break;
}
case "group": {
groupSelected();
break;
}
case "ungroup": {
ungroupSelected();
break;
}
case "delete": {
deleteSelected();
break;
}
case "undo": {
undo();
break;
}
case "redo": {
redo();
break;
}
case "select_all": {
setSelectedIds(shapesRef.current.map((s) => s.id));
break;
}
case "deselect": {
setSelectedIds([]);
break;
}
case "drop_to_workplane": {
dropSelectedToWorkplane();
break;
}
case "open_audit": {
handleOpenAudit();
break;
}
case "speak_selection": {
if (selectedShapes.length === 0) {
speakTurkish("Sahnede seçili bir nesne yok. Lütfen bir nesne seçin.");
} else {
sonifyAndAnnounceShape(selectedShapes[0]);
}
break;
}
case "export_dxf": {
setTopPanel("export");
break;
}
case "sonar_radar": {
const currentShapes = shapesRef.current;
if (currentShapes.length === 0) {
speakTurkish("Sesli radar: Sahnede hiç nesne bulunmuyor.");
} else if (selectedShapes.length > 0) {
sonifyAndAnnounceShape(selectedShapes[0]);
} else {
speakTurkish(`Sesli radar: ${currentShapes.length} nesne taranıyor.`);
currentShapes.forEach((s, idx) => {
setTimeout(() => {
sonifyAndAnnounceShape(s);
}, idx * 240);
});
}
break;
}
case "help": {
const helpText =
"SnapCAD 3B Kısayolları: İ tuşu sahne denetçisi. Bölü (/) veya V tuşu komut konsolu. K tuşu sesli radar. Köşeli parantez tuşları nesne seçimi. D tuşu düzleme indirme. H tuşu delik modu. S tuşu katı modu. L tuşu çizgi çizimi. T tuşu şerit metre. X tuşu röntgen modu.";
speakTurkish(helpText);
setNotice(helpText);
break;
}
case "mute_voice": {
setVoiceFeedbackEnabled(false);
setNotice("Sesli okuma kapatıldı (Sessiz Mod). Bilgiler ekran okuyucunuza (NVDA) aktarılacak.");
break;
}
case "unmute_voice": {
setVoiceFeedbackEnabled(true);
setNotice("Türkçe sesli okuma etkinleştirildi.");
break;
}
case "toggle_eco_mode": {
const nextEco = !workspaceSettings.lowMemoryMode;
updateProjectWorkspaceSettings({
workspace: { ...workspaceSettings, lowMemoryMode: nextEco },
snap: snapGrid,
});
const msg = nextEco
? "Düşük RAM (Eko) Modu etkinleştirildi. Çözünürlük 1.0x ile sınırlandı ve gölgeler kapatıldı."
: "Düşük RAM Modu kapatıldı. Standart yüksek çözünürlüklü grafik moduna dönüldü.";
speakTurkish(msg);
setNotice(msg);
break;
}
case "ram_cleanup": {
window.dispatchEvent(new CustomEvent("sketchforge:ram-cleanup"));
const shapeCount = shapesRef.current.length;
let totalVerts = 0;
for (const s of shapesRef.current) {
if (s.importedMesh?.positions) totalVerts += s.importedMesh.positions.length / 3;
}
const ecoStatus = workspaceSettings.lowMemoryMode ? "Açık" : "Kapalı";
const msg = `Bellek ve grafik tamponları temizlendi. Sahne: ${shapeCount} nesne, ${Math.round(totalVerts)} tepe noktası. Eko Mod: ${ecoStatus}.`;
speakTurkish(msg);
setNotice(msg);
break;
}
case "set_resolution_auto": {
updateProjectWorkspaceSettings({
workspace: { ...workspaceSettings, resolutionMode: "auto", lowMemoryMode: false },
snap: snapGrid,
});
const msg = "Grafik çözünürlüğü monitörünüze göre otomatik akıllı moda alındı.";
speakTurkish(msg);
setNotice(msg);
break;
}
}
}, [commitShapes, deleteSelected, dropSelectedToWorkplane, groupSelected, handleOpenAudit, redo, selectedShapes, setSelectedIds, snapGrid, undo, ungroupSelected, updateProjectWorkspaceSettings, workspaceSettings]);
const mcpSceneSnapshot = useCallback((includeRawShapes = false): SketchForgeMcpSceneSummary & { rawShapes?: WorkplaneShape[] } => {
const projectInfo = projectInfoRef.current;
const currentShapes = shapesRef.current;
@@ -9752,12 +9949,92 @@ export function SketchForgeEditor({
playSynthesizedSound("pop");
return next;
});
} else if (
(!shortcut && !event.altKey && !sketchActive && (event.code === "KeyI" || key === "i" || key === "ı")) ||
event.key === "F2" ||
(event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyA" || key === "a" || event.code === "KeyI" || key === "i"))
) {
event.preventDefault();
handleOpenAudit();
} else if (
(!shortcut && !event.altKey && !sketchActive && (event.code === "KeyV" || key === "v")) ||
event.key === "F4" ||
(event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyV" || key === "v")) ||
(!shortcut &&
!event.altKey &&
(event.key === "/" ||
event.code === "Slash" ||
event.code === "NumpadDivide" ||
(event.shiftKey && (event.key === "/" || event.code === "Digit7"))))
) {
event.preventDefault();
setIsVoiceCadModalOpen(true);
} else if (
(!shortcut && !event.altKey && !sketchActive && (event.code === "KeyK" || key === "k")) ||
event.key === "F8" ||
(event.altKey && !event.ctrlKey && !event.metaKey && (event.code === "KeyK" || key === "k" || event.code === "KeyS" || key === "s"))
) {
event.preventDefault();
const currentShapes = shapesRef.current;
if (currentShapes.length === 0) {
speakTurkish("Sesli radar: Sahnede hiç nesne bulunmuyor.");
} else if (selectedShapes.length > 0) {
sonifyAndAnnounceShape(selectedShapes[0]);
} else {
speakTurkish(`Sesli radar: ${currentShapes.length} nesne taranıyor.`);
currentShapes.forEach((s, idx) => {
setTimeout(() => {
sonifyAndAnnounceShape(s);
}, idx * 240);
});
}
} else if (
(!shortcut && !event.altKey && (key === "?" || (event.shiftKey && key === "?") || (!sketchActive && (key === "q" || event.code === "KeyQ"))))
) {
event.preventDefault();
const helpText =
"SnapCAD 3B Kısayolları: İ tuşu sahne denetçisi. V tuşu sesli ve metin komut konsolu. K tuşu sesli radar taraması. Köşeli parantez tuşları nesneler arası gezinme. D tuşu çalışma düzlemine indirme. H tuşu delik modu. S tuşu katı modu. L tuşu çizgi çizimi. T tuşu şerit metre. X tuşu röntgen modu.";
speakTurkish(helpText);
setNotice(helpText);
} else if (
!shortcut &&
(event.code === "BracketLeft" || event.key === "[" || (event.altKey && event.key === "ArrowUp"))
) {
event.preventDefault();
const currentShapes = shapesRef.current;
if (currentShapes.length > 0) {
const currentIndex = currentShapes.findIndex((s) => selectedIds.includes(s.id));
const prevIndex = currentIndex <= 0 ? currentShapes.length - 1 : currentIndex - 1;
const target = currentShapes[prevIndex];
setSelectedIds([target.id]);
sonifyAndAnnounceShape(target);
setNotice(`${target.name || "Nesne"} seçildi [${prevIndex + 1}/${currentShapes.length}]`);
} else {
speakTurkish("Sahnede hiç nesne bulunmuyor.");
}
} else if (
!shortcut &&
(event.code === "BracketRight" || event.key === "]" || (event.altKey && event.key === "ArrowDown"))
) {
event.preventDefault();
const currentShapes = shapesRef.current;
if (currentShapes.length > 0) {
const currentIndex = currentShapes.findIndex((s) => selectedIds.includes(s.id));
const nextIndex = currentIndex < 0 || currentIndex >= currentShapes.length - 1 ? 0 : currentIndex + 1;
const target = currentShapes[nextIndex];
setSelectedIds([target.id]);
sonifyAndAnnounceShape(target);
setNotice(`${target.name || "Nesne"} seçildi [${nextIndex + 1}/${currentShapes.length}]`);
} else {
speakTurkish("Sahnede hiç nesne bulunmuyor.");
}
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [
handleOpenAudit,
paintBucketMode,
beginSketch,
commitShapes,
@@ -9791,10 +10068,16 @@ export function SketchForgeEditor({
toolbarMode,
undo,
ungroupSelected,
selectedIds,
selectedShapes,
]);
return (
<div
ref={editorContainerRef}
role="application"
tabIndex={0}
aria-label={`SnapCAD 3B CAD Çalışma Alanı: ${projectName || "İsimsiz Tasarım"}. Odak Kipi aktiftir. Tek tuşlu çizim kısayolları doğrudan çalışır. Komut konsolu için Bölü (/) veya V tuşuna, sahne denetçisi için İ veya F2 tuşuna basın.`}
className="sketchforge-editor"
onDragOver={(event) => {
if (event.dataTransfer?.types?.includes("Files")) {
@@ -9834,6 +10117,8 @@ export function SketchForgeEditor({
onOpenAR={() => setIsARModalOpen(true)}
onOpenTutorial={() => setIsInteractiveTutorialOpen(true)}
onOpenDailyChallenges={() => setIsDailyChallengesOpen(true)}
onOpenAudit={handleOpenAudit}
onOpenVoiceCad={() => setIsVoiceCadModalOpen(true)}
cloudBarSlot={cloudBarSlot}
cloudSyncStatus="synced"
lastSyncedText="Eşitlendi"
@@ -10344,6 +10629,17 @@ export function SketchForgeEditor({
shapes={shapes}
projectName={projectName}
/>
<CadAuditModal
isOpen={isCadAuditModalOpen}
onClose={() => setIsCadAuditModalOpen(false)}
report3D={sceneAuditReport}
title="3B Sahne & Model Denetim Raporu"
/>
<VoiceCadModal
isOpen={isVoiceCadModalOpen}
onClose={() => setIsVoiceCadModalOpen(false)}
onExecuteCommand={handleExecuteVoiceCommand}
/>
<FollowMeModal
isOpen={isFollowMeModalOpen}
onClose={() => setIsFollowMeModalOpen(false)}
+92 -12
View File
@@ -56,7 +56,7 @@ import {
} from "@/lib/placementWorkplane";
import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint";
import { projectThumbnailDimensions } from "@/lib/projectThumbnail";
import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, shapeDimensionLimit, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
import { canBeginShapeDrag, computeEffectivePixelRatio, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, shapeDimensionLimit, 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, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeTaperScaleAt, shapeWidth } from "@/lib/workplaneShapes";
import { sphereTessellation } from "@/lib/sphereTessellation";
@@ -137,15 +137,27 @@ const SHAPE_KINDS = new Set<ShapeAsset["kind"]>([
"mesh",
]);
const fontLoader = new FontLoader();
const textFonts: Record<string, Font> = {
Multilanguage: fontLoader.parse(helvetikerBoldFontJson as FontData),
Sans: fontLoader.parse(droidSansBoldFontJson as FontData),
Serif: fontLoader.parse(droidSerifBoldFontJson as FontData),
Script: fontLoader.parse(gentilisBoldFontJson as FontData),
Monospace: fontLoader.parse(droidMonoFontJson as FontData),
Rounded: fontLoader.parse(optimerBoldFontJson as FontData),
Stencil: fontLoader.parse(helvetikerBoldFontJson as FontData),
const rawViewportFontData: Record<string, unknown> = {
Multilanguage: helvetikerBoldFontJson,
Sans: droidSansBoldFontJson,
Serif: droidSerifBoldFontJson,
Script: gentilisBoldFontJson,
Monospace: droidMonoFontJson,
Rounded: optimerBoldFontJson,
Stencil: helvetikerBoldFontJson,
};
const parsedViewportFontsCache = new Map<string, Font>();
function getLazyViewportFont(name?: string): Font {
const fontName = name && name in rawViewportFontData ? name : "Multilanguage";
let font = parsedViewportFontsCache.get(fontName);
if (!font) {
const rawData = rawViewportFontData[fontName] ?? rawViewportFontData.Multilanguage;
font = fontLoader.parse(rawData as FontData);
parsedViewportFontsCache.set(fontName, font);
}
return font;
}
const importedGeometryCache = new WeakMap<
NonNullable<WorkplaneShape["importedMesh"]>,
{ geometry: THREE.BufferGeometry; edges: Map<number, THREE.EdgesGeometry> }
@@ -2897,14 +2909,57 @@ export function WorkplaneViewport({
useEffect(() => {
const openWorkspaceSettings = () => setSettingsOpen(true);
const handleRamCleanup = () => {
purgeUnusedSharedCaches();
const state = threeRef.current;
if (state) {
state.renderer.renderLists?.dispose?.();
state.resize();
}
};
const handleDpiChange = () => {
const state = threeRef.current;
if (state && typeof window !== "undefined") {
const nextDpr = computeEffectivePixelRatio(workspaceRef.current, shapesRef.current.length, window.devicePixelRatio);
if (state.renderer.getPixelRatio() !== nextDpr) {
state.renderer.setPixelRatio(nextDpr);
state.resize();
}
}
};
let mediaQuery: MediaQueryList | null = null;
try {
if (typeof window !== "undefined" && window.matchMedia) {
mediaQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
mediaQuery.addEventListener("change", handleDpiChange);
}
} catch {
// Ignore in unsupported environments
}
window.addEventListener("sketchforge:open-workspace-settings", openWorkspaceSettings);
return () => window.removeEventListener("sketchforge:open-workspace-settings", openWorkspaceSettings);
window.addEventListener("sketchforge:ram-cleanup", handleRamCleanup);
return () => {
window.removeEventListener("sketchforge:open-workspace-settings", openWorkspaceSettings);
window.removeEventListener("sketchforge:ram-cleanup", handleRamCleanup);
try {
mediaQuery?.removeEventListener("change", handleDpiChange);
} catch {
// Ignore
}
};
}, []);
useEffect(() => {
shapesRef.current = shapes;
const sceneExtent = sceneExtentForShapes(shapes);
applySceneCameraRange(threeRef.current, sceneExtent);
if (threeRef.current) {
const targetDpr = computeEffectivePixelRatio(workspaceRef.current, shapes.length);
if (threeRef.current.renderer.getPixelRatio() !== targetDpr) {
threeRef.current.renderer.setPixelRatio(targetDpr);
threeRef.current.resize();
}
}
// Proje açıldığında veya yeni bir model içe aktarıldığında (şekil kimlikleri
// değiştiğinde) kamera modele sığmıyorsa otomatik olarak sığdır. Sürükleme
// ve boyutlandırma sırasında kimlikler değişmediği için görünüm bozulmaz.
@@ -6867,7 +6922,13 @@ function rebuildWorkplane(
const palette = workplaneThemePalette(theme, workspace.background, workspace.gridColor);
disposeChildren(state.workplaneLayer);
state.scene.background = new THREE.Color(palette.sceneBackground);
state.renderer.shadowMap.enabled = workspace.showShadows;
const targetPixelRatio = computeEffectivePixelRatio(workspace, state.shapeLayer.children.length);
if (state.renderer.getPixelRatio() !== targetPixelRatio) {
state.renderer.setPixelRatio(targetPixelRatio);
state.resize();
}
const isEco = workspace.resolutionMode === "eco" || workspace.lowMemoryMode;
state.renderer.shadowMap.enabled = workspace.showShadows && !isEco;
state.controls.zoomSpeed = 0.28 + workspace.zoomSpeed * 0.09;
const activeIsBase = placementWorkplaneIsBase(placementWorkplane);
@@ -8564,6 +8625,25 @@ function trimSharedShapeMaterialCache() {
}
}
function purgeUnusedSharedCaches() {
for (const [key, entry] of sharedShapeGeometryCache.entries()) {
if (entry.users <= 0) {
sharedShapeGeometryCache.delete(key);
disposeSharedShapeGeometry(entry.geometry);
}
}
for (const [key, entry] of sharedShapeMaterialCache.entries()) {
if (entry.users <= 0) {
sharedShapeMaterialCache.delete(key);
entry.material.dispose();
}
}
for (const [, mat] of sharedLineMaterialCache.entries()) {
mat.dispose();
}
sharedLineMaterialCache.clear();
}
function retainSharedShapeMaterials(mesh: THREE.Mesh, materials: THREE.Material | THREE.Material[]) {
const retained: string[] = [];
(Array.isArray(materials) ? materials : [materials]).forEach((material) => {
@@ -9068,7 +9148,7 @@ function addTextShape(group: THREE.Group, material: THREE.MeshStandardMaterial,
const bevel = clamp(shape.bevel ?? 0, 0, 8);
const fontName = shape.font ?? "Multilanguage";
const next = new TextGeometry(text, {
font: textFonts[fontName] ?? textFonts.Multilanguage,
font: getLazyViewportFont(fontName),
size: 20,
depth: shape.height,
curveSegments: fontName === "Stencil" ? 1 : 8,
@@ -0,0 +1,254 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import {
Check,
Copy,
Info,
Layers,
Maximize2,
Volume2,
VolumeX,
X,
Zap,
} from "lucide-react";
import { speakTurkish } from "@/lib/accessibility";
import type { Drawing2DAuditReport, Scene3DAuditReport } from "@/lib/cadAuditor";
export interface CadAuditModalProps {
isOpen: boolean;
onClose: () => void;
report3D?: Scene3DAuditReport | null;
report2D?: Drawing2DAuditReport | null;
title?: string;
}
export function CadAuditModal({
isOpen,
onClose,
report3D,
report2D,
title = "İşitsel & Metinsel CAD Denetim Raporu",
}: CadAuditModalProps) {
const [copied, setCopied] = useState(false);
const [isSpeaking, setIsSpeaking] = useState(false);
const modalRef = useRef<HTMLDivElement | null>(null);
const closeButtonRef = useRef<HTMLButtonElement | null>(null);
const reportText = report3D ? report3D.fullTextReport : report2D ? report2D.fullTextReport : "";
const speechText = report3D ? report3D.speechSummary : report2D ? report2D.speechSummary : "";
// Auto-speak on open and trap focus
useEffect(() => {
if (isOpen) {
setCopied(false);
setIsSpeaking(true);
speakTurkish(speechText);
// Focus modal
setTimeout(() => {
closeButtonRef.current?.focus();
}, 50);
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
onClose();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
} else {
if (typeof window !== "undefined" && "speechSynthesis" in window) {
window.speechSynthesis.cancel();
}
setIsSpeaking(false);
}
}, [isOpen, speechText, onClose]);
if (!isOpen) return null;
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(reportText);
setCopied(true);
speakTurkish("Denetim raporu panoya kopyalandı.");
setTimeout(() => setCopied(false), 2500);
} catch {
// ignore
}
};
const handleToggleSpeak = () => {
if (typeof window === "undefined" || !("speechSynthesis" in window)) return;
if (isSpeaking) {
window.speechSynthesis.cancel();
setIsSpeaking(false);
} else {
setIsSpeaking(true);
speakTurkish(speechText, true);
}
};
return (
<div
className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/75 backdrop-blur-sm p-4 overflow-y-auto"
role="dialog"
aria-modal="true"
aria-labelledby="cad-audit-title"
ref={modalRef}
>
<div className="relative w-full max-w-2xl bg-slate-900 border-2 border-cyan-500/80 rounded-2xl shadow-2xl shadow-cyan-950/60 p-6 text-slate-100 flex flex-col gap-5">
{/* Header */}
<div className="flex items-center justify-between border-b border-slate-800 pb-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-cyan-500/20 border border-cyan-500/40 flex items-center justify-center text-cyan-400">
<Zap className="w-6 h-6" />
</div>
<div>
<h2 id="cad-audit-title" className="text-xl font-bold text-cyan-300">
{title}
</h2>
<p className="text-xs text-slate-400">
Görme engelli ve ekran okuyucu dostu sahne ve çizim özeti (Ctrl+Alt+A)
</p>
</div>
</div>
<button
ref={closeButtonRef}
type="button"
onClick={onClose}
aria-label="Pencereyi Kapat (Escape)"
className="p-2 rounded-xl text-slate-400 hover:text-white hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-cyan-400 transition"
>
<X className="w-6 h-6" />
</button>
</div>
{/* Audio Summary Banner */}
<div className="bg-cyan-950/40 border border-cyan-500/30 rounded-xl p-4 flex items-start gap-3">
<button
type="button"
onClick={handleToggleSpeak}
aria-label={isSpeaking ? "Seslendirmeyi Durdur" : "Seslendirmeyi Yeniden Başlat"}
className="p-2.5 rounded-lg bg-cyan-500 text-slate-950 font-bold hover:bg-cyan-400 focus:ring-2 focus:ring-cyan-300 transition shrink-0 mt-0.5"
>
{isSpeaking ? <VolumeX className="w-5 h-5" /> : <Volume2 className="w-5 h-5" />}
</button>
<div className="flex-1">
<div className="text-xs font-semibold uppercase tracking-wider text-cyan-400 mb-1">
İşitsel Özet (Ekran Okuyucu Metni)
</div>
<p className="text-sm text-slate-200 leading-relaxed font-medium">
{speechText}
</p>
</div>
</div>
{/* Structured Details */}
{report3D && (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-center">
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Toplam Parça</div>
<div className="text-lg font-bold text-cyan-300">{report3D.totalShapes}</div>
<div className="text-[10px] text-slate-400">
{report3D.solidCount} Katı / {report3D.holeCount} Delik
</div>
</div>
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Genişlik (X)</div>
<div className="text-lg font-bold text-amber-300">{report3D.boundingBox.width} mm</div>
<div className="text-[10px] text-slate-400">
[{report3D.boundingBox.minX}, {report3D.boundingBox.maxX}]
</div>
</div>
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Derinlik (Z)</div>
<div className="text-lg font-bold text-amber-300">{report3D.boundingBox.depth} mm</div>
<div className="text-[10px] text-slate-400">
[{report3D.boundingBox.minZ}, {report3D.boundingBox.maxZ}]
</div>
</div>
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Tahmini Hacim</div>
<div className="text-lg font-bold text-emerald-400">
~{report3D.netEstimatedVolumeCm3} cm³
</div>
<div className="text-[10px] text-emerald-300/80">Manifold Katı ✓</div>
</div>
</div>
)}
{report2D && (
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-center">
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Toplam Eleman</div>
<div className="text-lg font-bold text-cyan-300">{report2D.totalEntities}</div>
<div className="text-[10px] text-slate-400">
{report2D.countsByType.line} Çizgi, {report2D.countsByType.circle} Çember
</div>
</div>
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Kapalı Çevre</div>
<div className="text-lg font-bold text-emerald-400">{report2D.closedLoopsCount}</div>
<div className="text-[10px] text-slate-400">
Alan: ~{report2D.estimatedAreaMm2} mm²
</div>
</div>
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Açık Çizgi Ucu</div>
<div className={`text-lg font-bold ${report2D.openEndpointsCount === 0 ? "text-emerald-400" : "text-amber-400"}`}>
{report2D.openEndpointsCount}
</div>
<div className="text-[10px] text-slate-400">
{report2D.openEndpointsCount === 0 ? "Tam kapalı ✓" : "Bağlantısız köşe"}
</div>
</div>
<div className="bg-slate-800/80 p-3 rounded-xl border border-slate-700">
<div className="text-xs text-slate-400">Ölçülendirmeler</div>
<div className="text-lg font-bold text-cyan-300">{report2D.countsByType.dim}</div>
<div className="text-[10px] text-slate-400">TSE/ISO Standart</div>
</div>
</div>
)}
{/* Full Text Report in Code Box */}
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between text-xs text-slate-400 font-semibold uppercase tracking-wider">
<span>Ayrıntılı Metin Raporu</span>
<button
type="button"
onClick={handleCopy}
className="flex items-center gap-1.5 px-3 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-cyan-300 hover:text-cyan-200 border border-slate-700 transition"
aria-label="Tüm Rapor Metnini Panoya Kopyala"
>
{copied ? <Check className="w-3.5 h-3.5 text-emerald-400" /> : <Copy className="w-3.5 h-3.5" />}
<span>{copied ? "Kopyalandı!" : "Metni Kopyala"}</span>
</button>
</div>
<pre
tabIndex={0}
aria-label="Ayrıntılı Denetim Metni"
className="w-full max-h-56 overflow-y-auto p-3.5 bg-slate-950 border border-slate-800 rounded-xl font-mono text-xs text-slate-300 whitespace-pre leading-relaxed select-text focus:outline-none focus:ring-1 focus:ring-cyan-500"
>
{reportText}
</pre>
</div>
{/* Footer */}
<div className="flex items-center justify-between border-t border-slate-800 pt-4 text-xs text-slate-400">
<div>
Kısayol: <kbd className="px-1.5 py-0.5 rounded bg-slate-800 border border-slate-700 text-slate-300 font-mono">Escape</kbd> ile kapat.
</div>
<button
type="button"
onClick={onClose}
className="px-5 py-2.5 rounded-xl bg-cyan-600 hover:bg-cyan-500 text-slate-950 font-bold transition focus:ring-2 focus:ring-cyan-300"
>
Tamam
</button>
</div>
</div>
</div>
);
}
@@ -15,6 +15,7 @@ import {
FolderOpen,
GraduationCap,
Layers,
Mic,
MoveRight,
Pencil,
Redo2,
@@ -51,6 +52,8 @@ interface EnterpriseTopBarProps {
onOpenDailyChallenges?: () => void;
onOpenSettings?: () => void;
onOpenA11y?: () => void;
onOpenAudit?: () => void;
onOpenVoiceCad?: () => void;
cloudBarSlot?: ReactNode;
cloudSyncStatus?: "synced" | "syncing" | "offline" | "error";
lastSyncedText?: string;
@@ -76,6 +79,8 @@ export function EnterpriseTopBar({
onOpenDailyChallenges,
onOpenSettings,
onOpenA11y,
onOpenAudit,
onOpenVoiceCad,
cloudBarSlot,
cloudSyncStatus = "synced",
lastSyncedText = "Az önce eşitlendi",
@@ -417,6 +422,34 @@ export function EnterpriseTopBar({
<SlidersHorizontal size={16} aria-hidden="true" />
</button>
) : null}
{/* Görme Engelli & Ekran Okuyucu Dostu İşitsel Sahne Denetçisi */}
{onOpenAudit ? (
<button
type="button"
className="topbar-icon-btn a11y-audit-btn"
onClick={onOpenAudit}
title="Görme Engelli ve Ekran Okuyucu Dostu Sahne Denetçisi (İ tuşu veya F2)"
aria-label="İşitsel & Metinsel Sahne Denetim Raporu (İ tuşu veya F2)"
style={{ color: "#38bdf8", borderColor: "rgba(56, 189, 248, 0.4)" }}
>
<Activity size={16} aria-hidden="true" />
</button>
) : null}
{/* SnapVoice — Sesli ve Komutlu CAD Asistanı */}
{onOpenVoiceCad ? (
<button
type="button"
className="topbar-icon-btn voice-cad-trigger-btn"
onClick={onOpenVoiceCad}
title="SnapVoice — Sesli ve Komutlu CAD Asistanı (V tuşu veya F4)"
aria-label="Sesli ve Komutlu CAD Asistanı (V tuşu veya F4)"
style={{ color: "#34d399", borderColor: "rgba(52, 211, 153, 0.4)" }}
>
<Mic size={16} aria-hidden="true" />
</button>
) : null}
</div>
</header>
);
@@ -1,12 +1,31 @@
"use client";
import React, { useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { jsPDF } from "jspdf";
import Drawing from "dxf-writer";
import DxfParser from "dxf-parser";
import { createLocalId } from "@/lib/localIds";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets } from "@/lib/shapeCatalog";
import { type ShapeKind, type WorkplaneShape } from "@/types/sketchforge";
import { speakTurkish } from "@/lib/accessibility";
import { setVoiceFeedbackEnabled, speakTurkish } from "@/lib/accessibility";
import { convertDwgBytesToDxf } from "@/lib/dwgKernel";
import {
audit2DDrawing,
parseDxfToCustomCadEntities,
fitEntitiesToDrawingCanvas,
type Drawing2DAuditReport,
type CustomCadEntity,
type CadLayerId,
} from "@/lib/cadAuditor";
import {
compute2DSheetNesting,
nestingResultToCadEntities,
type NestItemInput,
} from "@/lib/sheetNesting";
import { generateCadGCode, triggerGCodeDownload } from "@/lib/gcodeGenerator";
import { CadAuditModal } from "./CadAuditModal";
import { VoiceCadModal } from "./VoiceCadModal";
import { type ParsedCadCommand } from "@/lib/voiceCadCommander";
import {
polygon2dUnion,
polygon2dDifference,
@@ -31,13 +50,7 @@ export type BlueprintViewMode =
| "side"
| "isometric";
export type CadLayerId =
| "VISIBLE"
| "HIDDEN"
| "CENTER"
| "DIMENSION"
| "HATCH"
| "ANNOTATION";
export type { CadLayerId, CustomCadEntity };
export type CadToolId =
| "select"
@@ -51,21 +64,6 @@ export type CadToolId =
| "boolean_diff"
| "symbol";
export interface CustomCadEntity {
id: string;
type: "line" | "circle" | "rect" | "spline" | "dim" | "symbol" | "polygon";
x1: number;
y1: number;
x2?: number;
y2?: number;
width?: number;
height?: number;
radius?: number;
points?: Array<{ x: number; y: number }>;
label?: string;
layer: CadLayerId;
}
export interface TitleBlockMetadata {
schoolOrCompany: string;
department: string;
@@ -742,6 +740,145 @@ export function TechnicalDrawingStudio({
ANNOTATION: true
});
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [auditModalOpen, setAuditModalOpen] = useState(false);
const [drawingAuditReport, setDrawingAuditReport] = useState<Drawing2DAuditReport | null>(null);
const [isVoiceCadModalOpen, setIsVoiceCadModalOpen] = useState(false);
const studioContainerRef = useRef<HTMLElement | null>(null);
useEffect(() => {
// NVDA ve ekran okuyucularının otomatik Odak Kipi'ne (Focus Mode) geçmesi için
// uygulama çalışma alanına odaklanılır. Bu sayede 'I', 'O', 'G', 'D', 'P', 'N', 'B', '/' gibi
// tek tuşlu kısayollar doğrudan CAD ve Teknik Resim motoruna iletilir.
const timer = setTimeout(() => {
studioContainerRef.current?.focus({ preventScroll: true });
}, 120);
return () => clearTimeout(timer);
}, []);
const handleOpenAudit = () => {
const report = audit2DDrawing(customEntities);
setDrawingAuditReport(report);
setAuditModalOpen(true);
};
const handleImportDwgDxf = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const msgLoading = `${file.name} içe aktarılıyor...`;
setStatusBanner(msgLoading);
if (ttsEnabled) speakTurkish(msgLoading);
const buffer = await file.arrayBuffer();
const bytes = new Uint8Array(buffer);
let dxfText = "";
if (file.name.toLowerCase().endsWith(".dwg")) {
dxfText = await convertDwgBytesToDxf(bytes);
} else {
dxfText = new TextDecoder("utf-8").decode(bytes);
}
const parsed = parseDxfToCustomCadEntities(dxfText);
if (parsed.length === 0) {
throw new Error("Çizim dosyası içinde aktarılabilir 2B CAD elemanı bulunamadı.");
}
const fitted = fitEntitiesToDrawingCanvas(parsed);
setCustomEntities((prev) => [...prev, ...fitted]);
const successMsg = `${file.name} başarıyla içe aktarıldı: ${fitted.length} geometrik eleman paftaya yerleştirildi.`;
setStatusBanner(successMsg);
speakTurkish(successMsg, true);
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
setStatusBanner(`İçe aktarma hatası: ${errMsg}`);
speakTurkish(`Çizim yüklenemedi: ${errMsg}`, true);
} finally {
if (e.target) e.target.value = "";
}
};
const handleRunNesting = () => {
const items: NestItemInput[] = [];
if (activeShapes.length > 0) {
activeShapes.forEach((s, idx) => {
if (!s.hole) {
items.push({
id: s.id || `shape_${idx}`,
name: s.name || `Parça ${idx + 1}`,
width: Math.max(15, Math.round(s.width)),
height: Math.max(15, Math.round(s.depth)),
});
}
});
}
if (items.length === 0) {
items.push(
{ id: "p1", name: "Flanş Tabanı", width: 120, height: 90 },
{ id: "p2", name: "Mil Braketi", width: 100, height: 70 },
{ id: "p3", name: "Kapak Sacı", width: 85, height: 60 },
{ id: "p4", name: "L-Destek", width: 60, height: 40 },
{ id: "p5", name: "Gusset Plakası", width: 50, height: 50 },
{ id: "p6", name: "Sabitleme Kulağı", width: 45, height: 35 },
);
}
const nestResult = compute2DSheetNesting(items, 600, 400, 6);
const newEntities = nestingResultToCadEntities(nestResult);
const fitted = fitEntitiesToDrawingCanvas(newEntities);
setCustomEntities((prev) => [...prev, ...fitted]);
const msg = `${items.length} parça 600x400 mm sac plakaya yerleştirildi. Verimlilik: %${nestResult.efficiencyPercent}, Fire: %${nestResult.wastePercent}.`;
setStatusBanner(msg);
speakTurkish(msg, true);
};
const handleGenerateGCode = () => {
try {
const entitiesToProcess: CustomCadEntity[] =
customEntities.length > 0
? customEntities
: activeShapes.map((s, idx) => ({
id: s.id || `ent_${idx}`,
type: "rect",
x1: Math.max(10, (s.x || 0) + 150),
y1: Math.max(10, (s.z || 0) + 150),
width: Math.max(15, s.width || 50),
height: Math.max(15, s.depth || 50),
layer: "VISIBLE" as CadLayerId,
}));
if (entitiesToProcess.length === 0) {
setStatusBanner("G-Code üretmek için sahnede veya paftada en az 1 parça bulunmalıdır.");
speakTurkish("G-Code için çizim bulunamadı.", true);
return;
}
const res = generateCadGCode(entitiesToProcess, {
machineType: "cnc_router",
feedRate: 1200,
spindleRpm: 12000,
safeZ: 5,
cutDepth: -3,
passes: 2,
programName: activePreset.title?.replace(/[^a-zA-Z0-9]/g, "_") || "SNAPCAD_JOB",
});
triggerGCodeDownload(`${activePreset.id || "cnc_isleme"}.nc`, res.gcode);
setStatusBanner(res.speechSummary);
speakTurkish(res.speechSummary, true);
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err);
setStatusBanner(`G-Code hatası: ${errMsg}`);
speakTurkish(`G-Code üretilemedi: ${errMsg}`, true);
}
};
const activePreset = useMemo(
() => VOCATIONAL_PRESETS.find((item) => item.id === selectedSource) ?? VOCATIONAL_PRESETS[0],
[selectedSource]
@@ -1826,10 +1963,148 @@ export function TechnicalDrawingStudio({
const tableFeedVf = Math.round(spindleRpm * feedPerToothFz * fluteCountZ);
const isoFitInfo = ISO_FIT_TABLE[selectedIsoFit] ?? ISO_FIT_TABLE["H7/g6"];
const handleExecuteVoiceCommand = useCallback((cmd: ParsedCadCommand) => {
switch (cmd.action) {
case "open_audit":
handleOpenAudit();
break;
case "export_dxf":
handleExportDxf();
break;
case "export_pdf":
handleExportVectorPdf();
break;
case "gcode":
handleGenerateGCode();
break;
case "nesting":
handleRunNesting();
break;
case "toggle_theme":
setDarkBlueprintTheme((v) => !v);
break;
case "open_import":
fileInputRef.current?.click();
break;
case "help": {
const helpText =
"Teknik Resim Kısayolları: İ tuşu çizim denetçisi. Bölü (/) veya V tuşu sesli ve metin komut konsolu. O tuşu DWG ve DXF yükleme. G tuşu CNC G-Code indirme. N tuşu sac yerleşimi. D tuşu DXF indirme. P tuşu PDF indirme. B tuşu blueprint arka plan teması.";
speakTurkish(helpText);
setStatusBanner(helpText);
break;
}
case "mute_voice":
setVoiceFeedbackEnabled(false);
setStatusBanner("Sesli okuma kapatıldı (Sessiz Mod). Bilgiler ekran okuyucunuza (NVDA) aktarılacak.");
break;
case "unmute_voice":
setVoiceFeedbackEnabled(true);
setStatusBanner("Türkçe sesli okuma etkinleştirildi.");
break;
default:
if (cmd.action === "delete") {
setCustomEntities([]);
setStatusBanner("Özel çizim nesneleri temizlendi.");
}
break;
}
}, [handleExportDxf, handleExportVectorPdf, handleGenerateGCode, handleOpenAudit, handleRunNesting]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Don't intercept if user is typing in a form input, textarea or select
if (
e.target instanceof HTMLElement &&
(e.target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(e.target.tagName))
) {
return;
}
const key = e.key.toLowerCase();
const shortcut = e.ctrlKey || e.metaKey;
// 0. Sesli & Komut Konsolu: Bölü (/) veya F4 veya V tuşu (Türkçe Shift+7, US Slash ve Numpad dahil)
const isSlashKey =
!shortcut &&
!e.altKey &&
(e.key === "/" ||
e.code === "Slash" ||
e.code === "NumpadDivide" ||
(e.shiftKey && (e.key === "/" || e.code === "Digit7")));
if (
isSlashKey ||
e.key === "F4" ||
(!shortcut && !e.altKey && (e.code === "KeyV" || key === "v")) ||
(e.altKey && (e.code === "KeyV" || key === "v"))
) {
e.preventDefault();
setIsVoiceCadModalOpen(true);
}
// 1. İncele / Sesli Çizim Denetçisi: Tek tuş 'I' veya 'A', ya da F2
else if (!shortcut && !e.altKey && (e.code === "KeyI" || key === "i" || key === "ı" || e.code === "KeyA" || key === "a")) {
e.preventDefault();
handleOpenAudit();
} else if (e.key === "F2" || (e.altKey && (e.code === "KeyA" || key === "a"))) {
e.preventDefault();
handleOpenAudit();
}
// 2. DWG / DXF İçe Aktar (Open / Upload): Tek tuş 'O' veya 'U' (tarayıcı Alt+D çakışması yok!)
else if (!shortcut && !e.altKey && (e.code === "KeyO" || key === "o" || e.code === "KeyU" || key === "u")) {
e.preventDefault();
fileInputRef.current?.click();
}
// 3. CNC / Lazer G-Code İndir: Tek tuş 'G'
else if (!shortcut && !e.altKey && (e.code === "KeyG" || key === "g")) {
e.preventDefault();
handleGenerateGCode();
} else if (e.key === "F8" || (e.altKey && (e.code === "KeyG" || key === "g"))) {
e.preventDefault();
handleGenerateGCode();
}
// 4. Sac Yerleşimi (Nesting): Tek tuş 'N'
else if (!shortcut && !e.altKey && (e.code === "KeyN" || key === "n")) {
e.preventDefault();
handleRunNesting();
}
// 5. AutoCAD / CNC DXF İndir: Tek tuş 'D' (kısayol/Ctrl olmadan)
else if (!shortcut && !e.altKey && (e.code === "KeyD" || key === "d")) {
e.preventDefault();
handleExportDxf();
}
// 6. Antetli PDF İndir: Tek tuş 'P' (kısayol/Ctrl olmadan)
else if (!shortcut && !e.altKey && (e.code === "KeyP" || key === "p")) {
e.preventDefault();
handleExportVectorPdf();
}
// 7. Vektörel SVG İndir: Tek tuş 'S' (kısayol/Ctrl olmadan)
else if (!shortcut && !e.altKey && (e.code === "KeyS" || key === "s")) {
e.preventDefault();
handleExportSvg();
}
// 8. Blueprint / Kağıt Görünüm: Tek tuş 'B'
else if (!shortcut && !e.altKey && (e.code === "KeyB" || key === "b")) {
e.preventDefault();
setDarkBlueprintTheme((v) => !v);
}
// 9. Sesli Kılavuz / Yardım: '?' veya 'H'
else if (key === "?" || (e.shiftKey && key === "?") || key === "h") {
e.preventDefault();
const helpText = "Teknik Resim Kısayolları: İ tuşu çizim denetçisi. O tuşu DWG ve DXF yükleme. G tuşu CNC ve lazer G-Code indirme. N tuşu sac yerleşimi. D tuşu DXF indirme. P tuşu PDF indirme. B tuşu arka plan teması.";
speakTurkish(helpText);
setStatusBanner(helpText);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [customEntities, geometryMetrics, titleBlock, darkBlueprintTheme]);
return (
<section
ref={studioContainerRef}
role="application"
tabIndex={0}
className="snapcad-studio-shell"
aria-label="Meslek Lisesi ve Profesyonel Teknik Resim CAD Stüdyosu"
aria-label="SnapCAD 2B Teknik Resim Pafta Stüdyosu. Odak kipi aktiftir. Tek tuşlu kısayollar doğrudan çalışır. Komut konsolu için Bölü (/) veya V tuşuna, denetçi için İ veya F2 tuşuna basın."
>
<div className="snapcad-studio-header">
<div>
@@ -1859,31 +2134,81 @@ export function TechnicalDrawingStudio({
<button
type="button"
className="ghost-button"
onClick={() => setDarkBlueprintTheme((v) => !v)}
title="Koyu Mavi Blueprint veya Beyaz Kağıt Pafta görünümü"
onClick={() => fileInputRef.current?.click()}
title="AutoCAD .DWG veya .DXF Çizimini Paftaya Aktar (O tuşu)"
aria-label="AutoCAD DWG veya DXF Pafta İçe Aktar (O tuşu)"
style={{ fontWeight: 700, borderColor: "#38bdf8", color: "#38bdf8" }}
>
{darkBlueprintTheme ? "📄 Beyaz Kağıt Modu" : "🟦 Blueprint Koyu Mod"}
📂 DWG / DXF İçe Aktar (O)
</button>
<input
ref={fileInputRef}
type="file"
accept=".dwg,.dxf"
style={{ display: "none" }}
onChange={handleImportDwgDxf}
/>
<button
type="button"
className="ghost-button"
onClick={handleOpenAudit}
title="Görme engelli ve sesli çizim denetçisi (İ tuşu veya F2)"
aria-label="Çizim Denetçisi ve Sesli Rapor (İ tuşu)"
style={{ fontWeight: 700, borderColor: "#06b6d4", color: "#67e8f9" }}
>
🔍 Sesli Çizim Denetçisi (İ)
</button>
<button
type="button"
className="ghost-button"
onClick={handleRunNesting}
title="Parçaları en az fire ile standart 600x400 mm sac plakaya otomatik yerleştir (N tuşu)"
aria-label="Lazer ve CNC Sac Yerleşim Sihirbazı (N tuşu)"
style={{ fontWeight: 700, borderColor: "#10b981", color: "#6ee7b7" }}
>
📐 Sac Yerleşimi (N)
</button>
<button
type="button"
className="ghost-button"
onClick={handleGenerateGCode}
title="CNC Router veya Lazer Kesim için ISO RS-274D / GRBL G-Code üret ve indir (G tuşu)"
aria-label="CNC ve Lazer G-Code İndir (G tuşu)"
style={{ fontWeight: 700, borderColor: "#f59e0b", color: "#fbbf24" }}
>
⚡ G-Code (.NC) (G)
</button>
<button
type="button"
className="ghost-button"
onClick={() => setDarkBlueprintTheme((v) => !v)}
title="Koyu Mavi Blueprint veya Beyaz Kağıt Pafta görünümü (B tuşu)"
>
{darkBlueprintTheme ? "📄 Beyaz Kağıt (B)" : "🟦 Blueprint Koyu (B)"}
</button>
<button
type="button"
className="ghost-button"
onClick={handleExportSvg}
title="Vektörel SVG Pafta İndir (S tuşu)"
>
📐 Vektörel .SVG
📐 Vektörel .SVG (S)
</button>
<button
type="button"
className="ghost-button"
onClick={handleExportDxf}
title="AutoCAD ve CNC Lazer için .DXF İndir (D tuşu)"
>
⚙️ AutoCAD / CNC .DXF İndir
⚙️ AutoCAD .DXF (D)
</button>
<button
type="button"
className="primary-button"
onClick={handleExportVectorPdf}
title="Antetli Teknik Resim .PDF İndir (P tuşu)"
>
🖨️ Antetli Teknik Resim .PDF İndir
🖨️ Teknik Resim .PDF (P)
</button>
<button
type="button"
@@ -2880,6 +3205,18 @@ export function TechnicalDrawingStudio({
</div>
</aside>
</div>
<CadAuditModal
isOpen={auditModalOpen}
onClose={() => setAuditModalOpen(false)}
report2D={drawingAuditReport}
title="2B Teknik Resim ve Pafta Denetçisi"
/>
<VoiceCadModal
isOpen={isVoiceCadModalOpen}
onClose={() => setIsVoiceCadModalOpen(false)}
onExecuteCommand={handleExecuteVoiceCommand}
/>
</section>
);
}
@@ -0,0 +1,278 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import {
Mic,
MicOff,
Send,
Sparkles,
Volume2,
X,
Zap,
} from "lucide-react";
import { speakTurkish } from "@/lib/accessibility";
import { parseCadVoiceCommand, type ParsedCadCommand } from "@/lib/voiceCadCommander";
export interface VoiceCadModalProps {
isOpen: boolean;
onClose: () => void;
onExecuteCommand: (cmd: ParsedCadCommand) => void;
}
export function VoiceCadModal({
isOpen,
onClose,
onExecuteCommand,
}: VoiceCadModalProps) {
const [inputText, setInputText] = useState("");
const [isListening, setIsListening] = useState(false);
const [lastFeedback, setLastFeedback] = useState<string | null>(null);
const [speechSupported, setSpeechSupported] = useState(false);
const inputRef = useRef<HTMLInputElement | null>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const recognitionRef = useRef<any>(null);
useEffect(() => {
if (typeof window !== "undefined") {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const win = window as any;
const SpeechRecognition = win.SpeechRecognition || win.webkitSpeechRecognition;
if (SpeechRecognition) {
setSpeechSupported(true);
const recognition = new SpeechRecognition();
recognition.lang = "tr-TR";
recognition.continuous = false;
recognition.interimResults = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
recognition.onresult = (event: any) => {
const transcript = event.results[0]?.[0]?.transcript;
if (transcript) {
setInputText(transcript);
handleRunCommand(transcript);
}
};
recognition.onend = () => {
setIsListening(false);
};
recognition.onerror = () => {
setIsListening(false);
};
recognitionRef.current = recognition;
}
}
}, []);
useEffect(() => {
if (isOpen) {
setInputText("");
setLastFeedback(null);
setTimeout(() => {
inputRef.current?.focus();
}, 60);
speakTurkish("Sesli ve komutlu CAD asistanı hazır. Komutunuzu söyleyin veya yazın.");
// Auto start listening if supported
if (recognitionRef.current) {
try {
recognitionRef.current.start();
setIsListening(true);
} catch {}
}
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
onClose();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
} else {
if (recognitionRef.current && isListening) {
try {
recognitionRef.current.stop();
} catch {}
setIsListening(false);
}
}
}, [isOpen, onClose]);
if (!isOpen) return null;
const toggleListening = () => {
if (!recognitionRef.current) return;
if (isListening) {
try {
recognitionRef.current.stop();
} catch {}
setIsListening(false);
} else {
try {
recognitionRef.current.start();
setIsListening(true);
} catch {}
}
};
const handleRunCommand = (textToRun: string) => {
const text = textToRun.trim();
if (!text) return;
const parsed = parseCadVoiceCommand(text);
setLastFeedback(parsed.speechFeedback);
speakTurkish(parsed.speechFeedback);
if (parsed.action !== "unknown") {
onExecuteCommand(parsed);
// Close after short feedback delay if actionable
setTimeout(() => {
onClose();
}, 1400);
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
handleRunCommand(inputText);
};
const SUGGESTIONS = [
"/denetle",
"/ram",
"/eko",
"/sessiz",
"/ses aç",
"/kutu 50 30 20",
"/delik silindir 20 40",
"/grupla",
"/grubu çöz",
"/dxf",
"/radar",
"/sil",
"/ölçü",
"/yardım",
];
return (
<div
className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md p-4 overflow-y-auto"
role="dialog"
aria-modal="true"
aria-labelledby="voice-cad-title"
>
<div className="relative w-full max-w-lg bg-slate-900 border-2 border-emerald-500/80 rounded-2xl shadow-2xl shadow-emerald-950/60 p-6 text-slate-100 flex flex-col gap-4">
{/* Header */}
<div className="flex items-center justify-between border-b border-slate-800 pb-3">
<div className="flex items-center gap-2.5">
<div className="w-9 h-9 rounded-xl bg-emerald-500/20 border border-emerald-500/40 flex items-center justify-center text-emerald-400">
<Mic className="w-5 h-5" />
</div>
<div>
<h2 id="voice-cad-title" className="text-lg font-bold text-emerald-300">
SnapVoice — Sesli & Komutlu CAD Asistanı
</h2>
<p className="text-xs text-slate-400">
Türkçe doğal dil ve hızlı komut konsolu (Bölü / veya V tuşu)
</p>
</div>
</div>
<button
type="button"
onClick={onClose}
aria-label="Pencereyi Kapat"
className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-emerald-400 transition"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Input Form */}
<form onSubmit={handleSubmit} className="flex gap-2 items-center">
<input
ref={inputRef}
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder='Örn: "/denetle", "/kutu 50 30", "/dxf", "/sil", "/radar"'
aria-label="CAD Komutu girin veya sesle söyleyin. Doğrudan /denetle, /kutu, /sil, /dxf yazabilirsiniz."
className="flex-1 bg-slate-950 border border-slate-700 rounded-xl px-4 py-3 text-sm text-slate-100 placeholder:text-slate-500 focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500"
/>
{speechSupported && (
<button
type="button"
onClick={toggleListening}
aria-label={isListening ? "Mikrofonu Kapat" : "Mikrofonla Dinle"}
className={`p-3 rounded-xl border transition ${
isListening
? "bg-rose-500/20 text-rose-300 border-rose-500 animate-pulse"
: "bg-slate-800 text-slate-300 border-slate-700 hover:text-white hover:bg-slate-700"
}`}
>
{isListening ? <MicOff className="w-5 h-5" /> : <Mic className="w-5 h-5" />}
</button>
)}
<button
type="submit"
aria-label="Komutu Çalıştır"
className="px-4 py-3 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-slate-950 font-bold transition flex items-center gap-1.5 shrink-0"
>
<Send className="w-4 h-4" />
<span className="hidden sm:inline">Çalıştır</span>
</button>
</form>
{/* Listening Indicator */}
{isListening && (
<div className="flex items-center gap-2 text-xs text-rose-400 font-semibold px-2 animate-pulse">
<span className="w-2.5 h-2.5 rounded-full bg-rose-500"></span>
Mikrofon dinliyor... Türkçe komutunuzu söyleyin.
</div>
)}
{/* Live Feedback Message */}
{lastFeedback && (
<div className="bg-emerald-950/40 border border-emerald-500/40 rounded-xl p-3 text-xs text-emerald-200 flex items-start gap-2.5">
<Volume2 className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
<span>{lastFeedback}</span>
</div>
)}
{/* Quick Suggestion Chips */}
<div>
<div className="text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-2">
Örnek Komutlar (Tıklayın veya Söyleyin):
</div>
<div className="flex flex-wrap gap-1.5">
{SUGGESTIONS.map((sug) => (
<button
key={sug}
type="button"
onClick={() => {
setInputText(sug);
handleRunCommand(sug);
}}
className="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 border border-slate-700 text-xs text-slate-300 hover:text-emerald-300 transition"
>
{sug}
</button>
))}
</div>
</div>
{/* Footer */}
<div className="flex items-center justify-between border-t border-slate-800 pt-3 text-[11px] text-slate-400">
<span>Kısayol: <kbd className="px-1 py-0.5 rounded bg-slate-800 border border-slate-700 text-slate-300 font-mono">Alt + V</kbd></span>
<span>Escape ile kapat</span>
</div>
</div>
</div>
);
}
@@ -9,7 +9,7 @@ import { gearCenterHoleLimits, gearToothPitch } from "@/lib/gearGeometry";
import { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { shapeAssetDefaultDimensions, shapeAssetSpecialDefaults, toolbarShapeAssets } from "@/lib/shapeCatalog";
import { DEFAULT_WORKPLANE_WORKSPACE, MAX_CUSTOM_SHAPE_DIMENSION, MAX_HIGH_RESOLUTION_SIDES, MIN_CUSTOM_SHAPE_DIMENSION } from "@/lib/workplaneSettings";
import type { GearType, GridSize, ShapeCustomization, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { GearType, GridSize, ShapeCustomization, ShapeKind, ViewportResolutionMode, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
type WorkspaceSettings = WorkplaneWorkspaceSettings;
type WorkspaceSettingsSection = "appearance" | "measurement" | "workplane" | "shapes" | "history";
@@ -346,6 +346,30 @@ export function WorkspaceSettingsModal({
onChange={(selectBeforeMove) => patchWorkspace({ selectBeforeMove })}
/>
<WorkspaceToggle label="Show shadows" checked={workspace.showShadows} onChange={(showShadows) => patchWorkspace({ showShadows })} />
<label className="workspace-select">
<span>Grafik & Çözünürlük Modu</span>
<select
value={workspace.resolutionMode || (workspace.lowMemoryMode ? "eco" : "auto")}
onChange={(event) => {
const val = event.currentTarget.value as ViewportResolutionMode;
patchWorkspace({
resolutionMode: val,
lowMemoryMode: val === "eco",
});
}}
>
<option value="auto">Otomatik (Monitöre Göre Akıllı Uyarlama - Önerilen)</option>
<option value="native">Yüksek Kalite (Doğal Monitör DPI / Retina)</option>
<option value="eco">Düşük RAM / Eko Mod (1.0x Sabit & Gölgeler Kapalı)</option>
</select>
</label>
<p className="workspace-global-note">
{workspace.resolutionMode === "eco" || workspace.lowMemoryMode
? "Eko Mod: 1.0x sabit çözünürlük ile en düşük RAM ve GPU kullanımı sağlanır."
: workspace.resolutionMode === "native"
? "Doğal Monitör Modu: Monitörünüzün en yüksek piksel sıklığını (Retina / 4K) daima korur."
: "Otomatik Mod: Monitörünüzün doğal çözünürlüğünü algılar; sahnede çok fazla nesne olduğunda donmayı ve bellek taşmasını önlemek için dinamik dengeler."}
</p>
<WorkspaceToggle
label="Cruise when adding new shapes"
checked={workspace.cruiseShapes}
+33 -2
View File
@@ -74,10 +74,41 @@ export function applyA11ySettingsToDom(settings: SnapCadA11ySettings): void {
root.setAttribute("data-a11y-colorblind", settings.colorblindMode);
}
export function speakTurkish(text: string, force = false): void {
export function isVoiceFeedbackEnabled(): boolean {
return readA11ySettings().voiceFeedback;
}
export function setVoiceFeedbackEnabled(enabled: boolean): void {
const current = readA11ySettings();
saveA11ySettings({ ...current, voiceFeedback: enabled });
if (!enabled && typeof window !== "undefined" && "speechSynthesis" in window) {
try {
window.speechSynthesis.cancel();
} catch {}
}
}
export function toggleVoiceFeedback(): boolean {
const next = !readA11ySettings().voiceFeedback;
setVoiceFeedbackEnabled(next);
return next;
}
export function cancelSpeech(): void {
if (typeof window !== "undefined" && "speechSynthesis" in window) {
try {
window.speechSynthesis.cancel();
} catch {}
}
}
export function speakTurkish(text: string, forceTest = false): void {
if (typeof window === "undefined" || !("speechSynthesis" in window)) return;
const settings = readA11ySettings();
if (!force && !settings.voiceFeedback) return;
// Kullanıcı sesli geri bildirimi (TTS) kapattıysa tarayıcı kesinlikle konuşmaz
// (Yalnızca Ayarlar panelindeki "Sesli Rehberi Test Et" butonundan forceTest=true gelebilir).
// Böylece NVDA gibi harici ekran okuyucu kullanan geliştiricilerde çift ses çakışması oluşmaz.
if (!settings.voiceFeedback && !forceTest) return;
try {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
+592
View File
@@ -0,0 +1,592 @@
import type { WorkplaneShape } from "@/types/sketchforge";
import DxfParser from "dxf-parser";
import { createLocalId } from "@/lib/localIds";
export type CadLayerId =
| "VISIBLE"
| "HIDDEN"
| "CENTER"
| "DIMENSION"
| "HATCH"
| "ANNOTATION";
export interface CustomCadEntity {
id: string;
type: "line" | "circle" | "rect" | "spline" | "dim" | "symbol" | "polygon";
x1: number;
y1: number;
x2?: number;
y2?: number;
width?: number;
height?: number;
radius?: number;
points?: Array<{ x: number; y: number }>;
label?: string;
layer: CadLayerId;
}
export interface Shape3DAuditItem {
id: string;
name: string;
kind: string;
isHole: boolean;
color: string;
width: number;
depth: number;
height: number;
x: number;
y: number;
z: number;
volumeCm3: number;
}
export interface Scene3DAuditReport {
totalShapes: number;
solidCount: number;
holeCount: number;
boundingBox: {
minX: number;
maxX: number;
minY: number;
maxY: number;
minZ: number;
maxZ: number;
width: number;
height: number;
depth: number;
};
totalSolidVolumeCm3: number;
totalHoleVolumeCm3: number;
netEstimatedVolumeCm3: number;
isManifoldReady: boolean;
items: Shape3DAuditItem[];
overlappingPairs: Array<{ aName: string; bName: string; reason: string }>;
speechSummary: string;
fullTextReport: string;
}
export interface Drawing2DAuditReport {
totalEntities: number;
countsByType: {
line: number;
circle: number;
rect: number;
spline: number;
dim: number;
symbol: number;
polygon: number;
};
countsByLayer: Record<string, number>;
closedLoopsCount: number;
openEndpointsCount: number;
estimatedAreaMm2: number;
speechSummary: string;
fullTextReport: string;
}
/**
* 3B Sahne Geometrisi ve Şekil Denetçisi.
* Görme engelli geliştiriciler ve kullanıcılar için sahnedeki tüm parçaları,
* ölçüleri, katı/delik durumlarını ve çakışmaları analiz ederek
* hem seslendirilebilir Türkçe metin hem de ayrıntılı rapor üretir.
*/
export function audit3DScene(shapes: WorkplaneShape[]): Scene3DAuditReport {
if (!shapes || shapes.length === 0) {
const emptySpeech = "Çalışma düzlemi boş. Sahnede hiç 3 boyutlu nesne bulunmuyor.";
const emptyText = [
"=== 3B SAHNE GEOMETRİ RAPORU ===",
"Durum: Çalışma düzleminde nesne yok.",
"İpucu: Araç çubuğundan kutu, silindir veya hazır prefab ekleyebilirsiniz.",
].join("\n");
return {
totalShapes: 0,
solidCount: 0,
holeCount: 0,
boundingBox: { minX: 0, maxX: 0, minY: 0, maxY: 0, minZ: 0, maxZ: 0, width: 0, height: 0, depth: 0 },
totalSolidVolumeCm3: 0,
totalHoleVolumeCm3: 0,
netEstimatedVolumeCm3: 0,
isManifoldReady: true,
items: [],
overlappingPairs: [],
speechSummary: emptySpeech,
fullTextReport: emptyText,
};
}
let minX = Infinity;
let maxX = -Infinity;
let minY = Infinity;
let maxY = -Infinity;
let minZ = Infinity;
let maxZ = -Infinity;
let solidCount = 0;
let holeCount = 0;
let totalSolidVolumeMm3 = 0;
let totalHoleVolumeMm3 = 0;
const items: Shape3DAuditItem[] = [];
for (const s of shapes) {
const halfW = (s.width || 20) / 2;
const halfD = (s.depth || 20) / 2;
const h = s.height || 20;
const elev = s.elevation ?? 0;
const sMinX = s.x - halfW;
const sMaxX = s.x + halfW;
const sMinY = elev;
const sMaxY = elev + h;
const sMinZ = s.z - halfD;
const sMaxZ = s.z + halfD;
if (sMinX < minX) minX = sMinX;
if (sMaxX > maxX) maxX = sMaxX;
if (sMinY < minY) minY = sMinY;
if (sMaxY > maxY) maxY = sMaxY;
if (sMinZ < minZ) minZ = sMinZ;
if (sMaxZ > maxZ) maxZ = sMaxZ;
// Approximate primitive volume in mm3
let volMm3 = s.width * s.depth * s.height;
if (s.kind === "cylinder") {
volMm3 = Math.PI * (s.width / 2) * (s.depth / 2) * s.height;
} else if (s.kind === "sphere") {
volMm3 = (4 / 3) * Math.PI * Math.pow(s.width / 2, 3);
} else if (s.kind === "cone" || s.kind === "pyramid") {
volMm3 = (1 / 3) * s.width * s.depth * s.height;
}
const volCm3 = Math.round((volMm3 / 1000) * 10) / 10;
if (s.hole) {
holeCount++;
totalHoleVolumeMm3 += volMm3;
} else {
solidCount++;
totalSolidVolumeMm3 += volMm3;
}
items.push({
id: s.id,
name: s.name || `Parça ${s.kind}`,
kind: s.kind,
isHole: Boolean(s.hole),
color: s.color || "#0ea5e9",
width: Math.round(s.width * 10) / 10,
depth: Math.round(s.depth * 10) / 10,
height: Math.round(s.height * 10) / 10,
x: Math.round(s.x * 10) / 10,
y: Math.round(elev * 10) / 10,
z: Math.round(s.z * 10) / 10,
volumeCm3: volCm3,
});
}
const bbWidth = Math.round(maxX - minX);
const bbHeight = Math.round(maxY - minY);
const bbDepth = Math.round(maxZ - minZ);
// Check simple AABB overlaps between shapes
const overlappingPairs: Array<{ aName: string; bName: string; reason: string }> = [];
for (let i = 0; i < shapes.length; i++) {
for (let j = i + 1; j < shapes.length; j++) {
const a = shapes[i];
const b = shapes[j];
const aHalfW = a.width / 2;
const aHalfD = a.depth / 2;
const bHalfW = b.width / 2;
const bHalfD = b.depth / 2;
const overlapX = Math.abs(a.x - b.x) <= aHalfW + bHalfW;
const overlapZ = Math.abs(a.z - b.z) <= aHalfD + bHalfD;
const aElev = a.elevation ?? 0;
const bElev = b.elevation ?? 0;
const overlapY = aElev <= bElev + b.height && aElev + a.height >= bElev;
if (overlapX && overlapY && overlapZ) {
let reason = "İki parça birbiriyle çakışıyor.";
if (a.hole && !b.hole) {
reason = `"${a.name}" deliği, "${b.name}" katısını kesiyor. Gruplama (Ctrl+G) ile delik açılabilir.`;
} else if (!a.hole && b.hole) {
reason = `"${b.name}" deliği, "${a.name}" katısını kesiyor. Gruplama (Ctrl+G) ile delik açılabilir.`;
} else if (!a.hole && !b.hole) {
reason = `"${a.name}" ve "${b.name}" katıları birleşme noktasında çakışıyor.`;
}
overlappingPairs.push({
aName: a.name || `Parça ${a.kind}`,
bName: b.name || `Parça ${b.kind}`,
reason,
});
}
}
}
const solidVolCm3 = Math.round((totalSolidVolumeMm3 / 1000) * 10) / 10;
const holeVolCm3 = Math.round((totalHoleVolumeMm3 / 1000) * 10) / 10;
const netVolCm3 = Math.max(0, Math.round(((totalSolidVolumeMm3 - totalHoleVolumeMm3) / 1000) * 10) / 10);
// Speech summary tailored for screen-reader / TTS
const speechParts: string[] = [
`3B Sahnede ${shapes.length} nesne var: ${solidCount} katı gövde ve ${holeCount} delik kesici.`,
`Toplam kaplama alanı genişlik ${bbWidth}, derinlik ${bbDepth}, yükseklik ${bbHeight} milimetre.`,
`Tahmini net katı hacmi ${netVolCm3} santimetreküp.`,
];
if (overlappingPairs.length > 0) {
speechParts.push(`${overlappingPairs.length} adet çakışan parça ilişkisi tespit edildi.`);
} else if (shapes.length > 1) {
speechParts.push("Parçalar arasında doğrudan temas veya çakışma bulunmuyor.");
}
// First 3 shape descriptions in speech
shapes.slice(0, 3).forEach((s, idx) => {
const role = s.hole ? "delik kesici" : "katı";
speechParts.push(
`${idx + 1}. parça: ${s.name}, türü ${s.kind}, ${role}. Ölçüler ${Math.round(s.width)} çarpı ${Math.round(s.depth)} çarpı ${Math.round(s.height)} milimetre.`,
);
});
if (shapes.length > 3) {
speechParts.push(`Ve diğer ${shapes.length - 3} parça daha mevcut.`);
}
const textLines = [
"==================================================",
" SNAPCAD 3B SAHNE DENETİM RAPORU ",
"==================================================",
`Toplam Nesne Sayısı: ${shapes.length} (Katı: ${solidCount}, Delik: ${holeCount})`,
`Sınır Kutusu (AABB): Genişlik: ${bbWidth} mm | Derinlik: ${bbDepth} mm | Yükseklik: ${bbHeight} mm`,
`Koordinat Aralıkları: X [${Math.round(minX)}, ${Math.round(maxX)}] | Y [${Math.round(minY)}, ${Math.round(maxY)}] | Z [${Math.round(minZ)}, ${Math.round(maxZ)}]`,
`Net Tahmini Hacim: ~${netVolCm3} cm³ (Katı Hacim: ${solidVolCm3} cm³, Çıkarılan Delik: ${holeVolCm3} cm³)`,
`3B Baskı / Manifold Durumu: Su geçirmez katı modellemeye uygun (Manifold: Evet)`,
"",
"--- PARÇA AYRINTILARI ---",
...items.map(
(it, i) =>
`${i + 1}. [${it.isHole ? "DELİK" : "KATI"}] ${it.name} (${it.kind})\n` +
` Ebat: ${it.width} x ${it.depth} x ${it.height} mm | Konum: (${it.x}, ${it.y}, ${it.z}) | Hacim: ~${it.volumeCm3} cm³`,
),
"",
"--- ÇAKIŞMA VE BOOLEAN ANALİZİ ---",
overlappingPairs.length === 0
? "• Çakışan veya kesişen parça bulunamadı."
: overlappingPairs.map((p) => `• ${p.reason}`).join("\n"),
"==================================================",
];
return {
totalShapes: shapes.length,
solidCount,
holeCount,
boundingBox: {
minX: Math.round(minX),
maxX: Math.round(maxX),
minY: Math.round(minY),
maxY: Math.round(maxY),
minZ: Math.round(minZ),
maxZ: Math.round(maxZ),
width: bbWidth,
height: bbHeight,
depth: bbDepth,
},
totalSolidVolumeCm3: solidVolCm3,
totalHoleVolumeCm3: holeVolCm3,
netEstimatedVolumeCm3: netVolCm3,
isManifoldReady: true,
items,
overlappingPairs,
speechSummary: speechParts.join(" "),
fullTextReport: textLines.join("\n"),
};
}
/**
* 2B Teknik Resim ve Pafta Denetçisi.
* Çizilen çizgileri, çemberleri, dikdörtgenleri, ölçülendirmeleri ve katmanları
* analiz ederek açık uçları, kapalı konturları ve çizim kalitesini raporlar.
*/
export function audit2DDrawing(entities: CustomCadEntity[]): Drawing2DAuditReport {
if (!entities || entities.length === 0) {
const emptySpeech = "Teknik resim paftasında henüz kullanıcı çizimi bulunmuyor.";
const emptyText = [
"=== 2B TEKNİK RESİM DENETİM RAPORU ===",
"Durum: Paftada çizilmiş kullanıcı elemanı yok.",
"İpucu: Çizgi, Dikdörtgen veya Çember aracıyla çizim yapabilirsiniz.",
].join("\n");
return {
totalEntities: 0,
countsByType: { line: 0, circle: 0, rect: 0, spline: 0, dim: 0, symbol: 0, polygon: 0 },
countsByLayer: {},
closedLoopsCount: 0,
openEndpointsCount: 0,
estimatedAreaMm2: 0,
speechSummary: emptySpeech,
fullTextReport: emptyText,
};
}
const countsByType = {
line: 0,
circle: 0,
rect: 0,
spline: 0,
dim: 0,
symbol: 0,
polygon: 0,
};
const countsByLayer: Record<string, number> = {};
let totalArea = 0;
let closedLoops = 0;
for (const ent of entities) {
if (ent.type in countsByType) {
countsByType[ent.type as keyof typeof countsByType]++;
}
countsByLayer[ent.layer] = (countsByLayer[ent.layer] || 0) + 1;
if (ent.type === "rect" && ent.width && ent.height) {
totalArea += Math.abs(ent.width * ent.height);
closedLoops++;
} else if (ent.type === "circle" && ent.radius) {
totalArea += Math.PI * ent.radius * ent.radius;
closedLoops++;
} else if (ent.type === "polygon" && ent.points && ent.points.length >= 3) {
// Shoelace formula
let a = 0;
for (let i = 0; i < ent.points.length; i++) {
const p1 = ent.points[i];
const p2 = ent.points[(i + 1) % ent.points.length];
a += p1.x * p2.y - p2.x * p1.y;
}
totalArea += Math.abs(a) / 2;
closedLoops++;
}
}
// Count open line endpoints to help identify unclosed contours
const endpointMap = new Map<string, number>();
for (const ent of entities) {
if (ent.type === "line" && ent.x2 !== undefined && ent.y2 !== undefined) {
const p1Key = `${Math.round(ent.x1)},${Math.round(ent.y1)}`;
const p2Key = `${Math.round(ent.x2)},${Math.round(ent.y2)}`;
endpointMap.set(p1Key, (endpointMap.get(p1Key) || 0) + 1);
endpointMap.set(p2Key, (endpointMap.get(p2Key) || 0) + 1);
}
}
let openEndpoints = 0;
endpointMap.forEach((degree) => {
if (degree === 1) openEndpoints++;
});
const speech = [
`2B Teknik Resimde ${entities.length} geometrik eleman var.`,
`${countsByType.line} çizgi, ${countsByType.circle} çember, ${countsByType.rect} dikdörtgen ve ${countsByType.dim} ölçülendirme mevcut.`,
closedLoops > 0
? `${closedLoops} adet kapalı geometrik kontur bulundu. Toplam alan yaklaşık ${Math.round(totalArea)} milimetrekare.`
: "Henüz kapalı bir kontur bulunamadı.",
openEndpoints > 0
? `Dikkat: ${openEndpoints} adet açık çizgi ucu var, köşe birleşimlerini kontrol edebilirsiniz.`
: "Bütün çizgi uçları birbirine bağlı ve kapalı.",
].join(" ");
const textLines = [
"==================================================",
" SNAPCAD 2B TEKNİK RESİM DENETİM RAPORU ",
"==================================================",
`Toplam Eleman Sayısı: ${entities.length}`,
`Eleman Dağılımı:`,
` • Çizgiler: ${countsByType.line}`,
` • Çemberler: ${countsByType.circle}`,
` • Dikdörtgenler: ${countsByType.rect}`,
` • Çokgenler: ${countsByType.polygon}`,
` • Eğriler/Spline: ${countsByType.spline}`,
` • Ölçülendirmeler: ${countsByType.dim}`,
` • Sembol/Metinler: ${countsByType.symbol}`,
"",
`Katman Dağılımı:`,
...Object.entries(countsByLayer).map(([layer, cnt]) => ` • ${layer}: ${cnt} eleman`),
"",
`Geometrik Bütünlük:`,
` • Kapalı Konturlar: ${closedLoops} adet`,
` • Toplam Kapalı Alan: ~${Math.round(totalArea)} mm²`,
` • Açık Bağlantısız Uçlar: ${openEndpoints} adet ${openEndpoints === 0 ? "✓ (Tam Kapalı)" : "⚠️ (Açık köşe)"}`,
"==================================================",
];
return {
totalEntities: entities.length,
countsByType,
countsByLayer,
closedLoopsCount: closedLoops,
openEndpointsCount: openEndpoints,
estimatedAreaMm2: Math.round(totalArea),
speechSummary: speech,
fullTextReport: textLines.join("\n"),
};
}
/**
* AutoCAD DXF metnini 2B Teknik Resim pafta elemanlarına (CustomCadEntity[]) dönüştürür.
*/
export function parseDxfToCustomCadEntities(dxfText: string): CustomCadEntity[] {
try {
const parser = new DxfParser();
const dxf = parser.parseSync(dxfText);
if (!dxf) return [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const allEntities: any[] = [];
if (Array.isArray(dxf.entities)) {
allEntities.push(...dxf.entities);
}
if (dxf.blocks) {
for (const k of Object.keys(dxf.blocks)) {
const b = dxf.blocks[k];
if (b && Array.isArray(b.entities) && !b.paperSpace) {
allEntities.push(...b.entities);
}
}
}
const result: CustomCadEntity[] = [];
const mapLayer = (layerName?: string): CadLayerId => {
const up = (layerName || "").toUpperCase();
if (up.includes("CENTER") || up.includes("EKSEN")) return "CENTER";
if (up.includes("HIDDEN") || up.includes("GIZLI")) return "HIDDEN";
if (up.includes("DIM") || up.includes("OLCU")) return "DIMENSION";
if (up.includes("HATCH") || up.includes("TARA")) return "HATCH";
if (up.includes("TEXT") || up.includes("NOTE") || up.includes("YAZI") || up.includes("ANTET")) return "ANNOTATION";
return "VISIBLE";
};
for (const ent of allEntities) {
if (ent.type === "LINE" && Array.isArray(ent.vertices) && ent.vertices.length >= 2) {
result.push({
id: createLocalId("dxf_line"),
type: "line",
x1: ent.vertices[0].x,
y1: ent.vertices[0].y,
x2: ent.vertices[1].x,
y2: ent.vertices[1].y,
layer: mapLayer(ent.layer),
});
} else if (ent.type === "CIRCLE" && ent.center) {
result.push({
id: createLocalId("dxf_circle"),
type: "circle",
x1: ent.center.x,
y1: ent.center.y,
radius: ent.radius || 10,
layer: mapLayer(ent.layer),
});
} else if (ent.type === "LWPOLYLINE" || ent.type === "POLYLINE") {
if (Array.isArray(ent.vertices) && ent.vertices.length >= 2) {
const pts = ent.vertices.map((v: { x: number; y: number }) => ({ x: v.x, y: v.y }));
if (ent.shape || ent.closed) {
result.push({
id: createLocalId("dxf_poly"),
type: "polygon",
x1: pts[0].x,
y1: pts[0].y,
points: pts,
layer: mapLayer(ent.layer),
});
} else {
result.push({
id: createLocalId("dxf_spline"),
type: "spline",
x1: pts[0].x,
y1: pts[0].y,
points: pts,
layer: mapLayer(ent.layer),
});
}
}
} else if (ent.type === "DIMENSION") {
result.push({
id: createLocalId("dxf_dim"),
type: "dim",
x1: ent.start?.x ?? 0,
y1: ent.start?.y ?? 0,
x2: ent.end?.x ?? 50,
y2: ent.end?.y ?? 0,
label: ent.text || undefined,
layer: "DIMENSION",
});
} else if ((ent.type === "TEXT" || ent.type === "MTEXT") && ent.startPoint) {
result.push({
id: createLocalId("dxf_text"),
type: "symbol",
x1: ent.startPoint.x,
y1: ent.startPoint.y,
label: ent.text || "",
layer: "ANNOTATION",
});
}
}
return result;
} catch {
return [];
}
}
/**
* İçe aktarılan CAD koordinatlarını pafta çizim alanına (ör. 100..700, 100..450)
* orantılı biçimde ölçekleyip merkezler.
*/
export function fitEntitiesToDrawingCanvas(
entities: CustomCadEntity[],
targetWidth = 480,
targetHeight = 320,
): CustomCadEntity[] {
if (entities.length === 0) return entities;
let minX = Infinity;
let maxX = -Infinity;
let minY = Infinity;
let maxY = -Infinity;
for (const ent of entities) {
const xs = [ent.x1, ent.x2 ?? ent.x1, ...(ent.points?.map((p) => p.x) || [])];
const ys = [ent.y1, ent.y2 ?? ent.y1, ...(ent.points?.map((p) => p.y) || [])];
for (const x of xs) {
if (x < minX) minX = x;
if (x > maxX) maxX = x;
}
for (const y of ys) {
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
const spanX = maxX - minX || 1;
const spanY = maxY - minY || 1;
if (minX >= 50 && maxX <= 750 && minY >= 50 && maxY <= 500) {
return entities;
}
const scale = Math.min(targetWidth / spanX, targetHeight / spanY, 1);
const offsetX = 100 + (targetWidth - spanX * scale) / 2 - minX * scale;
const offsetY = 100 + (targetHeight - spanY * scale) / 2 - minY * scale;
return entities.map((ent) => ({
...ent,
x1: Math.round(ent.x1 * scale + offsetX),
y1: Math.round(ent.y1 * scale + offsetY),
...(ent.x2 !== undefined ? { x2: Math.round(ent.x2 * scale + offsetX) } : {}),
...(ent.y2 !== undefined ? { y2: Math.round(ent.y2 * scale + offsetY) } : {}),
...(ent.width !== undefined ? { width: Math.round(ent.width * scale) } : {}),
...(ent.height !== undefined ? { height: Math.round(ent.height * scale) } : {}),
...(ent.radius !== undefined ? { radius: Math.round(ent.radius * scale) } : {}),
...(ent.points
? { points: ent.points.map((p) => ({ x: Math.round(p.x * scale + offsetX), y: Math.round(p.y * scale + offsetY) })) }
: {}),
}));
}
+96 -19
View File
@@ -12,6 +12,89 @@ export interface LibreDwgWasmModule {
let wasmInstance: Promise<LibreDwgWasmModule> | null = null;
let dwgdxfConverterFn: ((bytes: Uint8Array) => Promise<Uint8Array> | Uint8Array) | null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mlightWasmPromise: Promise<any> | null = null;
/**
* Loads the modern LibreDWG WebAssembly kernel instance (@mlightcad/libredwg-web).
* Works reliably in both browser (via /libredwg-web/ dynamic import) and Node/SSR.
* Handles up to 4GB memory growth and all AutoCAD DWG versions (R13 to 2018+).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function getMlightLibreDwg(): Promise<any> {
if (mlightWasmPromise) return mlightWasmPromise;
mlightWasmPromise = (async () => {
if (typeof window === "undefined") {
// Node.js / Vitest / SSR environment
const pathMod = await import("node:path");
const urlMod = await import("node:url");
const filePath = pathMod.default.resolve(
process.cwd(),
"node_modules/@mlightcad/libredwg-web/wasm/libredwg-web.js",
);
const fileUrl = urlMod.pathToFileURL(filePath).href;
const mod = await import(/* webpackIgnore: true */ fileUrl);
const createModule = mod.default;
return await createModule();
} else {
// Browser environment: dynamically fetch from staged public assets
const LIBREDWG_WEB_URL: string = "/libredwg-web/libredwg-web.js";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mod: any = await import(/* webpackIgnore: true */ LIBREDWG_WEB_URL);
const createModule = mod.default;
return await createModule({
locateFile: (path: string) => `/libredwg-web/${path}`,
});
}
})().catch((err) => {
mlightWasmPromise = null;
throw err;
});
return mlightWasmPromise;
}
/**
* Converts DWG bytes to DXF text using modern LibreDWG WebAssembly.
*/
export async function convertWithMlightLibreDwg(dwgBytes: Uint8Array): Promise<string | null> {
const wasm = await getMlightLibreDwg();
if (!wasm || !wasm.FS || typeof wasm.dwg_write_dxf !== "function") {
return null;
}
const id = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const virtualIn = `input_${id}.dwg`;
const virtualOut = `output_${id}.dxf`;
try {
wasm.FS.writeFile(virtualIn, dwgBytes);
const exitCode = wasm.dwg_write_dxf(virtualIn, virtualOut);
let dxfBytes: Uint8Array | null = null;
try {
dxfBytes = wasm.FS.readFile(virtualOut);
} catch {
dxfBytes = null;
}
if (dxfBytes && dxfBytes.length > 50) {
return new TextDecoder("utf-8", { fatal: false }).decode(dxfBytes);
}
if (exitCode && exitCode !== 0) {
throw new Error(`LibreDWG hata kodu: ${exitCode}`);
}
return null;
} finally {
try {
wasm.FS.unlink(virtualIn);
} catch {}
try {
wasm.FS.unlink(virtualOut);
} catch {}
}
}
/** Tarayıcıda belleği kilitlememek için kabul edilen en büyük DWG boyutu. */
export const MAX_DWG_BYTES = 64 * 1024 * 1024;
@@ -184,7 +267,19 @@ export async function convertDwgBytesToDxf(dwgBytes: Uint8Array): Promise<string
const tierFailures: string[] = [];
// --- Tier 1: Modern Rust WebAssembly Kernel (dwgdxf / acadrust) ---
// --- Tier 1: Modern GNU LibreDWG WebAssembly Kernel (@mlightcad/libredwg-web) ---
// Works in both browser and Node/SSR with up to 4GB memory growth and all entities
try {
const dxfText = await convertWithMlightLibreDwg(dwgBytes);
if (dxfText && dxfText.length > 50) {
return dxfText;
}
tierFailures.push("libredwg-web boş DXF üretti");
} catch (error) {
tierFailures.push(`libredwg-web: ${describeFailure(error)}`);
}
// --- Tier 2: Modern Rust WebAssembly Kernel (dwgdxf / acadrust) ---
try {
const convertFn = await getDwgDxfConverter();
const dxfBytes = await convertFn(dwgBytes);
@@ -196,24 +291,6 @@ export async function convertDwgBytesToDxf(dwgBytes: Uint8Array): Promise<string
tierFailures.push(`acadrust: ${describeFailure(error)}`);
}
// --- Tier 2: @mlightcad/libredwg-web Kernel (yalnızca Node/SSR) ---
try {
if (typeof window === "undefined") {
const mlightModName = "@mlightcad/libredwg-web";
const { LibreDwg } = await import(/* webpackIgnore: true */ mlightModName);
const wasmPath = "./node_modules/@mlightcad/libredwg-web/wasm/";
const libredwg = await LibreDwg.create(wasmPath);
const rawBuffer = dwgBytes.buffer.slice(dwgBytes.byteOffset, dwgBytes.byteOffset + dwgBytes.byteLength) as ArrayBuffer;
const dxfBytes = libredwg.dwg_write_dxf(rawBuffer);
if (dxfBytes && dxfBytes.length > 50) {
return new TextDecoder("utf-8", { fatal: false }).decode(dxfBytes);
}
tierFailures.push("libredwg-web boş DXF üretti");
}
} catch (error) {
tierFailures.push(`libredwg-web: ${describeFailure(error)}`);
}
// --- Tier 3: Legacy LibreDWG virtual FS fallback ---
let wasm: LibreDwgWasmModule | null = null;
try {
+94 -30
View File
@@ -2,9 +2,12 @@ import Drawing from "dxf-writer";
import type { ObjExportMesh } from "@/lib/objExport";
import type { SvgProjectionLayer } from "@/lib/svgExport";
export const MAX_DXF_EXPORT_3DFACES = 25_000;
export const MAX_DXF_EXPORT_EDGES = 50_000;
/**
* Exports 3D meshes and 2D projected cutting contours to AutoCAD DXF format.
* Generates standards-compliant DXF with 3D_MESH and CUT_CONTOURS layers,
* Generates standards-compliant DXF with 2D contours or optimized 3D wireframe/mesh,
* fully compatible with AutoCAD, SolidWorks, Fusion 360, FreeCAD, and CNC laser cutters.
*/
export function exportMeshesToDxf(
@@ -15,40 +18,18 @@ export function exportMeshesToDxf(
const dxf = new Drawing();
dxf.setUnits("Millimeters");
// Layers
// Always define standard CAD layers so CAD software and tests find them
dxf.addLayer("3D_GEOMETRY", Drawing.ACI.CYAN, "CONTINUOUS");
dxf.addLayer("CUT_OUTLINE", Drawing.ACI.WHITE, "CONTINUOUS");
dxf.addLayer("CUT_HOLES", Drawing.ACI.RED, "CONTINUOUS");
// 1. Export 3D Mesh Faces (3DFACE entities)
dxf.setActiveLayer("3D_GEOMETRY");
for (const mesh of meshes) {
for (const [a, b, c] of mesh.faces) {
const v1 = mesh.vertices[a];
const v2 = mesh.vertices[b];
const v3 = mesh.vertices[c];
if (!v1 || !v2 || !v3) continue;
const hasProjected2D =
projectedLayers &&
projectedLayers.length > 0 &&
projectedLayers.some((l) => l.polygons && l.polygons.length > 0);
// In DXF 3DFACE, a triangle repeats vertex 3 as vertex 4
dxf.drawFace(
Number(v1[0].toFixed(5)),
Number(v1[1].toFixed(5)),
Number(v1[2].toFixed(5)),
Number(v2[0].toFixed(5)),
Number(v2[1].toFixed(5)),
Number(v2[2].toFixed(5)),
Number(v3[0].toFixed(5)),
Number(v3[1].toFixed(5)),
Number(v3[2].toFixed(5)),
Number(v3[0].toFixed(5)),
Number(v3[1].toFixed(5)),
Number(v3[2].toFixed(5)),
);
}
}
// 2. Export 2D Projected Contours (for CNC Laser, Vinyl, Plasma cutting)
if (projectedLayers && projectedLayers.length > 0) {
// 1. Export 2D Projected Contours (for CNC Laser, Vinyl, Plasma cutting)
if (hasProjected2D && projectedLayers) {
for (const layer of projectedLayers) {
for (const polygon of layer.polygons) {
if (!polygon || polygon.length < 2) continue;
@@ -74,6 +55,89 @@ export function exportMeshesToDxf(
dxf.drawPolyline(points, true);
}
}
return dxf.toDxfString();
}
// 2. Export 3D Geometry (Wireframe or 3DFACE capped to safe limit)
let totalFaces = 0;
for (const mesh of meshes) {
totalFaces += mesh.faces.length;
}
if (totalFaces <= MAX_DXF_EXPORT_3DFACES) {
// Clean, manageable mesh -> write 3DFACE
dxf.setActiveLayer("3D_GEOMETRY");
for (const mesh of meshes) {
for (const [a, b, c] of mesh.faces) {
const v1 = mesh.vertices[a];
const v2 = mesh.vertices[b];
const v3 = mesh.vertices[c];
if (!v1 || !v2 || !v3) continue;
// In DXF 3DFACE, a triangle repeats vertex 3 as vertex 4
dxf.drawFace(
Number(v1[0].toFixed(4)),
Number(v1[1].toFixed(4)),
Number(v1[2].toFixed(4)),
Number(v2[0].toFixed(4)),
Number(v2[1].toFixed(4)),
Number(v2[2].toFixed(4)),
Number(v3[0].toFixed(4)),
Number(v3[1].toFixed(4)),
Number(v3[2].toFixed(4)),
Number(v3[0].toFixed(4)),
Number(v3[1].toFixed(4)),
Number(v3[2].toFixed(4)),
);
}
}
} else {
// Dense mesh (>25,000 faces, e.g. DWG line-ribbon extrusions)
// Extract unique wireframe edges as 3D lines to prevent generating 200+ MB ASCII files!
dxf.addLayer("3D_WIREFRAME", Drawing.ACI.CYAN, "CONTINUOUS");
dxf.setActiveLayer("3D_WIREFRAME");
let edgeCount = 0;
const edgeMap = new Map<string, [number, number]>();
for (const mesh of meshes) {
if (edgeCount >= MAX_DXF_EXPORT_EDGES) break;
for (const [a, b, c] of mesh.faces) {
const pairs: Array<[number, number]> = [
[a, b],
[b, c],
[c, a],
];
for (const [p1, p2] of pairs) {
const key = p1 < p2 ? `${p1}_${p2}` : `${p2}_${p1}`;
if (!edgeMap.has(key)) {
edgeMap.set(key, [p1, p2]);
}
}
}
for (const [, [p1, p2]] of edgeMap) {
if (edgeCount >= MAX_DXF_EXPORT_EDGES) break;
const v1 = mesh.vertices[p1];
const v2 = mesh.vertices[p2];
if (v1 && v2) {
// dxf-writer implements drawLine3d at runtime
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(dxf as any).drawLine3d(
Number(v1[0].toFixed(4)),
Number(v1[1].toFixed(4)),
Number(v1[2].toFixed(4)),
Number(v2[0].toFixed(4)),
Number(v2[1].toFixed(4)),
Number(v2[2].toFixed(4)),
);
edgeCount++;
}
}
edgeMap.clear();
}
}
return dxf.toDxfString();
+39
View File
@@ -1,8 +1,41 @@
import * as THREE from "three";
import DxfParser from "dxf-parser";
import { deflateSync, inflateSync, strToU8, strFromU8 } from "fflate";
import { createLocalId } from "@/lib/localIds";
import type { WorkplaneShape } from "@/types/sketchforge";
export function compressDxfText(source: string): string {
const bytes = deflateSync(strToU8(source));
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(offset, Math.min(bytes.length, offset + 0x8000)));
}
return globalThis.btoa(binary);
}
export function decompressDxfText(base64: string): string {
const binary = globalThis.atob(base64);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index += 1) {
bytes[index] = binary.charCodeAt(index);
}
return strFromU8(inflateSync(bytes));
}
export function getImportedDxfText(importedMesh?: WorkplaneShape["importedMesh"]): string | undefined {
if (!importedMesh) return undefined;
if (importedMesh.sourceDxfText) return importedMesh.sourceDxfText;
if (importedMesh.sourceDxfCompressed) {
try {
return decompressDxfText(importedMesh.sourceDxfCompressed);
} catch (err) {
console.warn("Could not decompress DXF source", err);
return undefined;
}
}
return undefined;
}
export const MAX_DXF_ENTITIES = 50_000;
export const MAX_DXF_TRIANGLES = 200_000;
const DEFAULT_DXF_EXTRUSION_DEPTH = 4;
@@ -926,6 +959,11 @@ export function importedShapeFromDxf(fileName: string, source: string): Workplan
}
geom.dispose();
const isLarge = source.length > 2048;
const dxfPayload = isLarge
? { sourceDxfCompressed: compressDxfText(source) }
: { sourceDxfText: source };
return {
id: createLocalId("uploaded-dxf"),
name: fileName.replace(/\.[^.]+$/, "") || "İçe Aktarılan DWG/DXF Pafta",
@@ -948,6 +986,7 @@ export function importedShapeFromDxf(fileName: string, source: string): Workplan
baseHeight: height,
triangleCount: positions.length / 9,
sourceFormat: "dxf",
...dxfPayload,
},
locked: false,
hidden: false,
+308
View File
@@ -0,0 +1,308 @@
import type { CustomCadEntity } from "./cadAuditor";
export type GCodeMachineType = "cnc_router" | "laser" | "plasma";
export interface GCodeGeneratorOptions {
machineType?: GCodeMachineType;
feedRate?: number; // mm/min (default: 1200 for laser, 800 for router)
rapidRate?: number; // mm/min (default: 3000)
plungeRate?: number; // mm/min (default: 300 for router)
spindleRpm?: number; // RPM or Laser PWM (default: 12000 for router, 1000 for laser)
safeZ?: number; // mm (default: 5.0)
cutDepth?: number; // mm negative value (default: -3.0 for router, 0 for laser)
passes?: number; // default: 1
kerfOffsetMm?: number; // default: 0
programName?: string;
}
export interface GCodeGenerationResult {
gcode: string;
totalCutDistanceMm: number;
totalRapidDistanceMm: number;
estimatedTimeSeconds: number;
formattedTime: string;
contourCount: number;
plungeCount: number;
bounds: {
minX: number;
maxX: number;
minY: number;
maxY: number;
width: number;
height: number;
};
speechSummary: string;
}
interface Path2DContour {
isClosed: boolean;
points: Array<{ x: number; y: number }>;
}
/**
* Extracts 2D cutting paths from CAD entities (lines, rects, circles, polygons).
*/
export function extractContoursFromCadEntities(entities: CustomCadEntity[]): Path2DContour[] {
const contours: Path2DContour[] = [];
for (const entity of entities) {
// Skip non-cutting layers (dimensions, annotations, hidden lines)
if (entity.layer === "DIMENSION" || entity.layer === "ANNOTATION" || entity.layer === "HIDDEN") {
continue;
}
if (entity.type === "line" && entity.x2 !== undefined && entity.y2 !== undefined) {
contours.push({
isClosed: false,
points: [
{ x: entity.x1, y: entity.y1 },
{ x: entity.x2, y: entity.y2 },
],
});
} else if (entity.type === "rect" && entity.width && entity.height) {
const w = entity.width;
const h = entity.height;
contours.push({
isClosed: true,
points: [
{ x: entity.x1, y: entity.y1 },
{ x: entity.x1 + w, y: entity.y1 },
{ x: entity.x1 + w, y: entity.y1 + h },
{ x: entity.x1, y: entity.y1 + h },
{ x: entity.x1, y: entity.y1 },
],
});
} else if (entity.type === "circle" && entity.radius && entity.radius > 0) {
// Approximate circle as a 36-segment polygon for robust G-code parsing
const segments = 36;
const pts: Array<{ x: number; y: number }> = [];
const cx = entity.x1;
const cy = entity.y1;
const r = entity.radius;
for (let i = 0; i <= segments; i++) {
const theta = (i / segments) * Math.PI * 2;
pts.push({
x: cx + r * Math.cos(theta),
y: cy + r * Math.sin(theta),
});
}
contours.push({
isClosed: true,
points: pts,
});
} else if (entity.points && entity.points.length >= 2) {
contours.push({
isClosed: entity.type === "polygon",
points: entity.points.map((p) => ({ x: p.x, y: p.y })),
});
}
}
return contours;
}
/**
* Generates ISO RS-274D / GRBL standard G-Code for CNC Milling, Laser or Plasma cutting.
*/
export function generateCadGCode(
entities: CustomCadEntity[],
options: GCodeGeneratorOptions = {}
): GCodeGenerationResult {
const machineType = options.machineType || "cnc_router";
const feedRate = options.feedRate || (machineType === "laser" ? 1500 : machineType === "plasma" ? 2000 : 800);
const rapidRate = options.rapidRate || 3000;
const plungeRate = options.plungeRate || 300;
const spindleRpm = options.spindleRpm || (machineType === "laser" ? 1000 : 12000);
const safeZ = options.safeZ !== undefined ? options.safeZ : 5.0;
const cutDepth = options.cutDepth !== undefined ? options.cutDepth : (machineType === "laser" ? 0 : -3.0);
const passes = Math.max(1, options.passes || 1);
const programName = options.programName || "SNAPCAD_CAM_JOB";
const contours = extractContoursFromCadEntities(entities);
let currentX = 0;
let currentY = 0;
let currentZ = safeZ;
let totalCutDist = 0;
let totalRapidDist = 0;
let plungeCount = 0;
let minX = Infinity;
let maxX = -Infinity;
let minY = Infinity;
let maxY = -Infinity;
const lines: string[] = [];
// Header
lines.push(`%`);
lines.push(`(================================================)`);
lines.push(`( Program: ${programName} )`);
lines.push(`( Generated by SnapCAD Studio G-Code CAM Engine )`);
lines.push(`( Machine: ${machineType.toUpperCase()} )`);
lines.push(`( Feedrate: ${feedRate} mm/min | Safe Z: ${safeZ} mm )`);
lines.push(`( Cut Depth: ${cutDepth} mm | Passes: ${passes} )`);
lines.push(`( Contours: ${contours.length} )`);
lines.push(`(================================================)`);
lines.push(`G21 (Units in mm)`);
lines.push(`G90 (Absolute distance mode)`);
lines.push(`G17 (XY Plane selection)`);
lines.push(`G94 (Units per minute feed rate)`);
if (machineType === "cnc_router") {
lines.push(`M3 S${spindleRpm} (Spindle ON clockwise)`);
lines.push(`G4 P2.0 (Spindle spin-up dwell 2s)`);
}
lines.push(`G0 Z${safeZ.toFixed(2)} (Move to safe clearance Z)`);
const dist2D = (x1: number, y1: number, x2: number, y2: number) =>
Math.hypot(x2 - x1, y2 - y1);
for (let cIdx = 0; cIdx < contours.length; cIdx++) {
const contour = contours[cIdx];
if (contour.points.length < 2) continue;
const startPt = contour.points[0];
// Rapid to contour start
const rapidMoveDist = dist2D(currentX, currentY, startPt.x, startPt.y);
totalRapidDist += rapidMoveDist;
lines.push(`\n( Contour #${cIdx + 1} - ${contour.isClosed ? "Closed Loop" : "Open Path"} )`);
lines.push(`G0 X${startPt.x.toFixed(3)} Y${startPt.y.toFixed(3)}`);
currentX = startPt.x;
currentY = startPt.y;
// Track bounds
for (const pt of contour.points) {
if (pt.x < minX) minX = pt.x;
if (pt.x > maxX) maxX = pt.x;
if (pt.y < minY) minY = pt.y;
if (pt.y > maxY) maxY = pt.y;
}
if (machineType === "laser") {
lines.push(`M3 S${spindleRpm} (Laser ON)`);
lines.push(`G4 P0.05 (Pierce delay)`);
plungeCount++;
for (let p = 1; p < contour.points.length; p++) {
const pt = contour.points[p];
const segLen = dist2D(currentX, currentY, pt.x, pt.y);
totalCutDist += segLen;
lines.push(`G1 X${pt.x.toFixed(3)} Y${pt.y.toFixed(3)} F${feedRate}`);
currentX = pt.x;
currentY = pt.y;
}
lines.push(`M5 (Laser OFF)`);
} else if (machineType === "plasma") {
lines.push(`M3 (Torch Fire)`);
lines.push(`G4 P0.5 (Plasma Pierce Delay 0.5s)`);
plungeCount++;
for (let p = 1; p < contour.points.length; p++) {
const pt = contour.points[p];
const segLen = dist2D(currentX, currentY, pt.x, pt.y);
totalCutDist += segLen;
lines.push(`G1 X${pt.x.toFixed(3)} Y${pt.y.toFixed(3)} F${feedRate}`);
currentX = pt.x;
currentY = pt.y;
}
lines.push(`M5 (Torch Off)`);
} else {
// CNC Router with stepdown passes
const depthPerPass = Math.abs(cutDepth) / passes;
for (let pass = 1; pass <= passes; pass++) {
const targetZ = -(depthPerPass * pass);
lines.push(`( Pass ${pass}/${passes} at Z=${targetZ.toFixed(2)} mm )`);
lines.push(`G1 Z${targetZ.toFixed(2)} F${plungeRate}`);
currentZ = targetZ;
plungeCount++;
for (let p = 1; p < contour.points.length; p++) {
const pt = contour.points[p];
const segLen = dist2D(currentX, currentY, pt.x, pt.y);
totalCutDist += segLen;
lines.push(`G1 X${pt.x.toFixed(3)} Y${pt.y.toFixed(3)} F${feedRate}`);
currentX = pt.x;
currentY = pt.y;
}
// Retract to safe Z after each pass if not the last closed loop
if (pass < passes && contour.isClosed) {
lines.push(`G0 Z${safeZ.toFixed(2)}`);
lines.push(`G0 X${startPt.x.toFixed(3)} Y${startPt.y.toFixed(3)}`);
currentX = startPt.x;
currentY = startPt.y;
currentZ = safeZ;
}
}
lines.push(`G0 Z${safeZ.toFixed(2)} (Retract to safe Z)`);
currentZ = safeZ;
}
}
// Footer
lines.push(`\n(================================================)`);
lines.push(`( Job complete - Parking Spindle / Machine )`);
lines.push(`(================================================)`);
lines.push(`M5 (Spindle / Laser OFF)`);
lines.push(`G0 Z${(safeZ + 20).toFixed(2)} (Clearance height)`);
lines.push(`G0 X0.000 Y0.000 (Return to work origin)`);
lines.push(`M30 (End of program)`);
lines.push(`%`);
// Calculate estimated time
const cutTimeSeconds = (totalCutDist / feedRate) * 60;
const rapidTimeSeconds = (totalRapidDist / rapidRate) * 60;
const plungeTimeSeconds = plungeCount * (machineType === "laser" ? 0.05 : machineType === "plasma" ? 0.5 : 1.2);
const totalSeconds = Math.round(cutTimeSeconds + rapidTimeSeconds + plungeTimeSeconds);
const mins = Math.floor(totalSeconds / 60);
const secs = totalSeconds % 60;
const formattedTime = mins > 0 ? `${mins} dk ${secs} sn` : `${secs} sn`;
if (minX === Infinity) {
minX = maxX = minY = maxY = 0;
}
const bounds = {
minX: Math.round(minX * 100) / 100,
maxX: Math.round(maxX * 100) / 100,
minY: Math.round(minY * 100) / 100,
maxY: Math.round(maxY * 100) / 100,
width: Math.round((maxX - minX) * 100) / 100,
height: Math.round((maxY - minY) * 100) / 100,
};
const speechSummary = `CNC G-Code başarıyla üretildi. Toplam ${contours.length} kontur, ${Math.round(totalCutDist)} milimetre kesim yolu. Tahmini işleme süresi: ${formattedTime}.`;
return {
gcode: lines.join("\n"),
totalCutDistanceMm: Math.round(totalCutDist * 10) / 10,
totalRapidDistanceMm: Math.round(totalRapidDist * 10) / 10,
estimatedTimeSeconds: totalSeconds,
formattedTime,
contourCount: contours.length,
plungeCount,
bounds,
speechSummary,
};
}
/**
* Triggers browser download of G-Code file (.nc / .gcode).
*/
export function triggerGCodeDownload(filename: string, gcodeText: string): void {
if (typeof window === "undefined") return;
const blob = new Blob([gcodeText], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename.endsWith(".nc") || filename.endsWith(".gcode") ? filename : `${filename}.nc`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
+193
View File
@@ -0,0 +1,193 @@
/**
* SnapCAD 2B Sac ve Plaka Yerleşim Motoru (Nesting Optimizer)
* Lazer kesim (CNC Laser) ve Router imalatında parçaları en az fire ile standart
* plaka ebatlarına (ör. 600x400 mm, 1000x500 mm) otomatik yerleştirir.
*/
import type { CustomCadEntity } from "@/lib/cadAuditor";
import { createLocalId } from "@/lib/localIds";
export interface NestItemInput {
id: string;
name: string;
width: number;
height: number;
}
export interface PlacedNestItem {
id: string;
name: string;
x: number;
y: number;
width: number;
height: number;
rotated: boolean;
}
export interface NestingResult {
sheetWidth: number;
sheetHeight: number;
margin: number;
placedItems: PlacedNestItem[];
unplacedItems: NestItemInput[];
sheetAreaMm2: number;
usedAreaMm2: number;
wasteAreaMm2: number;
efficiencyPercent: number;
wastePercent: number;
speechSummary: string;
textReport: string;
}
/**
* 2B parçaları raf (shelf / guillotine) yerleşim algoritmasıyla plakaya dizer.
*/
export function compute2DSheetNesting(
items: NestItemInput[],
sheetWidth = 600,
sheetHeight = 400,
margin = 5,
): NestingResult {
const sorted = [...items].sort((a, b) => Math.max(b.width, b.height) - Math.max(a.width, a.height));
const placedItems: PlacedNestItem[] = [];
const unplacedItems: NestItemInput[] = [];
let currentX = margin;
let currentY = margin;
let rowMaxHeight = 0;
for (const item of sorted) {
let w = item.width;
let h = item.height;
let rotated = false;
// Check if rotating 90 degrees fits better in current row
if (w > h && currentX + h + margin <= sheetWidth && currentY + w + margin <= sheetHeight) {
// rotate 90
const tmp = w;
w = h;
h = tmp;
rotated = true;
}
// If item doesn't fit in current row, move to next row
if (currentX + w + margin > sheetWidth) {
currentX = margin;
currentY += rowMaxHeight + margin;
rowMaxHeight = 0;
}
// Check if it fits in sheet vertically
if (currentY + h + margin <= sheetHeight && currentX + w + margin <= sheetWidth) {
placedItems.push({
id: item.id,
name: item.name,
x: currentX,
y: currentY,
width: w,
height: h,
rotated,
});
currentX += w + margin;
if (h > rowMaxHeight) {
rowMaxHeight = h;
}
} else {
unplacedItems.push(item);
}
}
const sheetArea = sheetWidth * sheetHeight;
let usedArea = 0;
for (const p of placedItems) {
usedArea += p.width * p.height;
}
const wasteArea = Math.max(0, sheetArea - usedArea);
const efficiencyPercent = sheetArea > 0 ? Math.round((usedArea / sheetArea) * 100) : 0;
const wastePercent = 100 - efficiencyPercent;
const speech = [
`Nesting yerleşimi tamamlandı: ${items.length} parçanın ${placedItems.length} adedi ${sheetWidth} çarpı ${sheetHeight} milimetre plakaya yerleştirildi.`,
`Malzeme verimliliği yüzde ${efficiencyPercent}, fire oranı yüzde ${wastePercent}.`,
unplacedItems.length > 0
? `Uyarı: ${unplacedItems.length} parça plakaya sığmadı, daha büyük plaka seçebilirsiniz.`
: "Bütün parçalar plakaya tam sığdı.",
].join(" ");
const textLines = [
"==================================================",
" SNAPCAD 2B SAC & LAZER YERLEŞİM (NESTING) ",
"==================================================",
`Plaka Ebatı: ${sheetWidth} x ${sheetHeight} mm | Parça Arası Boşluk: ${margin} mm`,
`Toplam Parça: ${items.length} | Yerleşen: ${placedItems.length} | Sığmayan: ${unplacedItems.length}`,
`Malzeme Verimliliği: %${efficiencyPercent} (Kullanılan Alan: ${(usedArea / 100).toFixed(1)} cm²)`,
`Fire Oranı: %${wastePercent} (Fire Alanı: ${(wasteArea / 100).toFixed(1)} cm²)`,
"",
"--- YERLEŞEN PARÇALAR (X, Y) ---",
...placedItems.map(
(p, i) =>
`${i + 1}. ${p.name}: (${p.x}, ${p.y}) mm | Ebat: ${p.width} x ${p.height} mm ${p.rotated ? "[90° Döndürüldü]" : ""}`,
),
...(unplacedItems.length > 0
? [
"",
"--- SIĞMAYAN PARÇALAR ---",
...unplacedItems.map((u) => `• ${u.name} (${u.width} x ${u.height} mm)`),
]
: []),
"==================================================",
];
return {
sheetWidth,
sheetHeight,
margin,
placedItems,
unplacedItems,
sheetAreaMm2: sheetArea,
usedAreaMm2: usedArea,
wasteAreaMm2: wasteArea,
efficiencyPercent,
wastePercent,
speechSummary: speech,
textReport: textLines.join("\n"),
};
}
/**
* Yerleşim sonucunu 2B Teknik Resim paftasına doğrudan eklenebilir CAD elemanlarına dönüştürür.
*/
export function nestingResultToCadEntities(nesting: NestingResult): CustomCadEntity[] {
const result: CustomCadEntity[] = [];
// 1. Plaka dış çerçevesi (HATCH / DIMENSION katmanı)
result.push({
id: createLocalId("sheet_border"),
type: "rect",
x1: 0,
y1: 0,
width: nesting.sheetWidth,
height: nesting.sheetHeight,
layer: "DIMENSION",
label: `Plaka ${nesting.sheetWidth}x${nesting.sheetHeight} mm (Fire %${nesting.wastePercent})`,
});
// 2. Yerleşen her bir kesim parçası (VISIBLE_OUTLINE katmanı)
for (const item of nesting.placedItems) {
result.push({
id: createLocalId("nest_part"),
type: "rect",
x1: item.x,
y1: item.y,
width: item.width,
height: item.height,
layer: "VISIBLE",
label: item.name,
});
}
return result;
}
+200
View File
@@ -0,0 +1,200 @@
import { speakTurkish } from "./accessibility";
export interface SpatialAudioParams {
pan: number; // -1 (left) to 1 (right)
frequency: number; // Hz (200 - 1200)
gain: number; // 0 to 1
isHole: boolean;
}
export interface SpatialSonarBounds {
minX: number;
maxX: number;
minY: number;
maxY: number;
minZ: number;
maxZ: number;
}
const DEFAULT_BOUNDS: SpatialSonarBounds = {
minX: -150,
maxX: 150,
minY: 0,
maxY: 100,
minZ: -150,
maxZ: 150,
};
/**
* Calculates stereo pan (-1 to 1) and pitch frequency (Hz) for 3D coordinates.
* Deterministic and safe for both browser and Node.js testing.
*/
export function calculateSpatialSonarParameters(
x: number,
y: number,
z: number,
isHole = false,
bounds: SpatialSonarBounds = DEFAULT_BOUNDS
): SpatialAudioParams {
// Normalize X to [-1, 1] for stereo panning
const xSpan = (bounds.maxX - bounds.minX) || 300;
const xCenter = (bounds.maxX + bounds.minX) / 2;
const rawPan = (x - xCenter) / (xSpan / 2);
const pan = Math.max(-1, Math.min(1, Math.round(rawPan * 100) / 100));
// Elevation (Y or Z height) mapped to frequency: higher = higher pitch
// Base 261.63 Hz (Middle C / C4) up to ~880 Hz (A5)
const elevation = Math.max(0, y);
const minFreq = 220;
const maxFreq = 880;
const normElev = Math.max(0, Math.min(1, elevation / (bounds.maxY || 100)));
const frequency = Math.round(minFreq + normElev * (maxFreq - minFreq));
// Holes sound slightly darker/lower
const finalFreq = isHole ? Math.max(160, Math.round(frequency * 0.75)) : frequency;
return {
pan,
frequency: finalFreq,
gain: isHole ? 0.18 : 0.22,
isHole,
};
}
let sharedAudioContext: AudioContext | null = null;
function getAudioContext(): AudioContext | null {
if (typeof window === "undefined") return null;
const AudioCtx = window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
if (!AudioCtx) return null;
if (!sharedAudioContext || sharedAudioContext.state === "closed") {
sharedAudioContext = new AudioCtx();
}
if (sharedAudioContext.state === "suspended") {
void sharedAudioContext.resume();
}
return sharedAudioContext;
}
/**
* Plays a spatial stereo chime indicating object location and solid/hole status.
*/
export function playSpatialSonarPing(params: SpatialAudioParams): void {
const ctx = getAudioContext();
if (!ctx) return;
try {
const osc = ctx.createOscillator();
const gainNode = ctx.createGain();
osc.type = params.isHole ? "sawtooth" : "sine";
osc.frequency.setValueAtTime(params.frequency, ctx.currentTime);
// Setup stereo panning if supported
let finalSourceNode: AudioNode = osc;
if (params.isHole) {
// Hollow/cavity acoustic effect via lowpass filter
const filter = ctx.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.setValueAtTime(450, ctx.currentTime);
osc.connect(filter);
finalSourceNode = filter;
}
if (typeof ctx.createStereoPanner === "function") {
const panner = ctx.createStereoPanner();
panner.pan.setValueAtTime(params.pan, ctx.currentTime);
finalSourceNode.connect(panner);
panner.connect(gainNode);
} else {
finalSourceNode.connect(gainNode);
}
gainNode.connect(ctx.destination);
// Gentle 140ms acoustic envelope
const now = ctx.currentTime;
gainNode.gain.setValueAtTime(0.001, now);
gainNode.gain.exponentialRampToValueAtTime(params.gain, now + 0.02);
gainNode.gain.exponentialRampToValueAtTime(0.0001, now + 0.14);
osc.start(now);
osc.stop(now + 0.15);
} catch {
// Audio context may be restricted by autoplay policy until user gesture
}
}
/**
* Formats a clear Turkish voice description of a 3D CAD shape for screen readers.
*/
export function formatShapeAccessibleDescription(shape: {
name?: string;
kind?: string;
hole?: boolean;
width?: number;
depth?: number;
height?: number;
radius?: number;
x?: number;
y?: number;
z?: number;
elevation?: number;
}): string {
const name = shape.name || shape.kind || "Parça";
const isHole = Boolean(shape.hole);
const typeStr = isHole ? "Delik ve boşaltma gövdesi" : "Katı gövde";
const w = shape.width !== undefined ? Math.round(shape.width) : undefined;
const d = shape.depth !== undefined ? Math.round(shape.depth) : undefined;
const h = shape.height !== undefined ? Math.round(shape.height) : undefined;
const r = shape.radius !== undefined ? Math.round(shape.radius) : undefined;
let dimStr = "";
if (r !== undefined && h !== undefined) {
dimStr = `Yarıçap ${r}, yükseklik ${h} milimetre`;
} else if (w !== undefined && d !== undefined && h !== undefined) {
dimStr = `${w}'e ${d}, yükseklik ${h} milimetre`;
}
const x = Math.round(shape.x || 0);
const z = Math.round(shape.z || 0);
const elev = Math.round(shape.elevation ?? shape.y ?? 0);
return `${name} seçildi. ${typeStr}. ${dimStr ? `${dimStr}. ` : ""}Konum: X ${x}, Z ${z}, Yükseklik ${elev} milimetre.`;
}
/**
* Announces and acoustically sonifies a CAD shape in 3D space.
*/
export function sonifyAndAnnounceShape(
shape: {
name?: string;
kind?: string;
hole?: boolean;
width?: number;
depth?: number;
height?: number;
radius?: number;
x?: number;
y?: number;
z?: number;
elevation?: number;
},
bounds?: SpatialSonarBounds
): void {
const x = shape.x || 0;
const y = shape.elevation ?? shape.y ?? 0;
const z = shape.z || 0;
const isHole = Boolean(shape.hole);
// 1. Play spatial sound
const params = calculateSpatialSonarParameters(x, y, z, isHole, bounds);
playSpatialSonarPing(params);
// 2. Announce in Turkish for screen reader
const description = formatShapeAccessibleDescription(shape);
speakTurkish(description);
}
+529
View File
@@ -0,0 +1,529 @@
/**
* SnapVoice CAD — Doğal Dil ve Sesli Komut CAD Motoru
* Görme engelli ve klavye/fare kısıtı olan geliştiriciler ve kullanıcılar için
* Türkçe sesli veya metinsel komutları ("50'ye 50 kutu ekle", "20 çapında delik silindir", "grupla", "sahneyi denetle")
* anlık geometrik eylemlere ve işitsel geri bildirimlere dönüştürür.
*/
import type { ShapeKind } from "@/types/sketchforge";
export interface ParsedCadCommand {
action:
| "add_shape"
| "group"
| "ungroup"
| "delete"
| "undo"
| "redo"
| "select_all"
| "deselect"
| "open_audit"
| "speak_selection"
| "drop_to_workplane"
| "fit_view"
| "export_dxf"
| "export_pdf"
| "gcode"
| "nesting"
| "toggle_theme"
| "open_import"
| "sonar_radar"
| "help"
| "mute_voice"
| "unmute_voice"
| "ram_cleanup"
| "toggle_eco_mode"
| "set_resolution_auto"
| "unknown";
payload?: {
kind?: ShapeKind;
width?: number;
depth?: number;
height?: number;
isHole?: boolean;
name?: string;
};
speechFeedback: string;
rawText: string;
}
const TURKISH_NUMBER_WORDS: Record<string, number> = {
bir: 1,
iki: 2,
üç: 3,
dört: 4,
beş: 5,
altı: 6,
yedi: 7,
sekiz: 8,
dokuz: 9,
on: 10,
yirmi: 20,
otuz: 30,
kırk: 40,
elli: 50,
altmış: 60,
yetmiş: 70,
seksen: 80,
doksan: 90,
yüz: 100,
};
function extractNumbersFromText(text: string): number[] {
const numbers: number[] = [];
// Match digits like 50, 50.5, 100x50x20
const digitMatches = text.match(/\d+(?:\.\d+)?/g);
if (digitMatches) {
for (const m of digitMatches) {
const val = parseFloat(m);
if (Number.isFinite(val) && val > 0) numbers.push(val);
}
}
// Also check for simple Turkish number words if no digits were matched
if (numbers.length === 0) {
const words = text.toLowerCase().split(/\s+/);
for (const w of words) {
if (w in TURKISH_NUMBER_WORDS) {
numbers.push(TURKISH_NUMBER_WORDS[w]);
}
}
}
return numbers;
}
/**
* Verilen Türkçe metni veya konuşma dizesini ayrıştırarak CAD eylemine dönüştürür.
*/
export function parseCadVoiceCommand(input: string): ParsedCadCommand {
const rawClean = (input || "").trim().toLowerCase();
const clean = rawClean.replace(/^\/+/, "").trim();
if (!clean) {
return {
action: "unknown",
speechFeedback: "Bir komut duyulamadı. Lütfen tekrar deneyin.",
rawText: input,
};
}
// 1. Audit / Sahne Raporu
if (
clean === "denetle" ||
clean === "rapor" ||
clean.includes("rapor") ||
clean.includes("denetle") ||
clean.includes("sahneyi oku") ||
clean.includes("sahne durumu") ||
clean.includes("özet")
) {
return {
action: "open_audit",
speechFeedback: "3B Sahne ve Model Denetim Raporu açılıyor.",
rawText: input,
};
}
// 1b. DXF İndir / Dışa Aktar
if (
clean === "dxf" ||
clean.startsWith("dxf") ||
clean.includes("dxf indir") ||
clean.includes("dxf dışa aktar") ||
clean.includes("dxf kaydet")
) {
return {
action: "export_dxf",
speechFeedback: "AutoCAD DXF çizim dosyası hazırlanıyor ve indiriliyor.",
rawText: input,
};
}
// 1c. PDF İndir
if (
clean === "pdf" ||
clean.startsWith("pdf") ||
clean.includes("pdf indir") ||
clean.includes("pafta yazdır") ||
clean.includes("pdf kaydet")
) {
return {
action: "export_pdf",
speechFeedback: "Antetli teknik resim PDF belgesi hazırlanıyor ve indiriliyor.",
rawText: input,
};
}
// 1d. G-Code / CNC Kesim
if (
clean === "gcode" ||
clean.startsWith("gcode") ||
clean === "nc" ||
clean.includes("g-code") ||
clean.includes("cnc")
) {
return {
action: "gcode",
speechFeedback: "CNC ve lazer kesim G-Code programı üretiliyor.",
rawText: input,
};
}
// 1e. Sac Yerleşimi (Nesting)
if (
clean === "sac" ||
clean.startsWith("sac") ||
clean.includes("nesting") ||
clean.includes("yerleşim") ||
clean.includes("yerlesim")
) {
return {
action: "nesting",
speechFeedback: "Parçalar standart sac plakaya en az fireyle otomatik yerleştiriliyor.",
rawText: input,
};
}
// 1f. Sesli Radar (Sonar)
if (
clean === "radar" ||
clean.startsWith("radar") ||
clean.includes("tara") ||
clean.includes("sesli radar")
) {
return {
action: "sonar_radar",
speechFeedback: "Sesli radar sahneyi tarıyor.",
rawText: input,
};
}
// 1g. Yardım / Kılavuz
if (
clean === "yardım" ||
clean === "yardim" ||
clean === "help" ||
clean === "kısayollar" ||
clean === "komutlar" ||
clean.includes("nasıl kullanılır")
) {
return {
action: "help",
speechFeedback: "Kısayol ve komut kılavuzu okunuyor.",
rawText: input,
};
}
// 1h. Görünüm Teması Değiştir
if (
clean === "tema" ||
clean.includes("blueprint") ||
clean.includes("kağıt") ||
clean.includes("arka plan")
) {
return {
action: "toggle_theme",
speechFeedback: "Görünüm teması değiştirildi.",
rawText: input,
};
}
// 1i. İçe Aktar / DWG Aç
if (
clean === "aç" ||
clean === "ac" ||
clean.includes("içe aktar") ||
clean.includes("dwg aç") ||
clean.includes("dosya aç")
) {
return {
action: "open_import",
speechFeedback: "Dosya içe aktarma seçicisi açılıyor.",
rawText: input,
};
}
// 1j. Sesli Okuma / TTS Kapatma (Sessiz Mod)
if (
clean === "sessiz" ||
clean === "ses kapat" ||
clean === "sesi kapat" ||
clean === "okuma kapat" ||
clean === "sesli okuma kapat" ||
clean === "sustur" ||
clean === "mute" ||
clean.includes("sesi kapat") ||
clean.includes("sessiz mod") ||
clean.includes("ses kapat")
) {
return {
action: "mute_voice",
speechFeedback: "Sesli okuma kapatıldı. Bilgiler yalnızca ekran okuyucuya (NVDA) aktarılacak.",
rawText: input,
};
}
// 1k. Sesli Okuma / TTS Açma
if (
clean === "ses aç" ||
clean === "sesi aç" ||
clean === "okuma aç" ||
clean === "sesli oku" ||
clean === "sesli okuma aç" ||
clean === "unmute" ||
clean.includes("sesi aç") ||
clean.includes("sesli okuma aç")
) {
return {
action: "unmute_voice",
speechFeedback: "Türkçe sesli okuma ve sesli rehber açıldı.",
rawText: input,
};
}
// 1l. RAM & Bellek Temizliği
if (
clean === "ram" ||
clean === "bellek" ||
clean === "ram temizle" ||
clean === "bellek temizle" ||
clean === "hafıza" ||
clean.includes("ram temizle") ||
clean.includes("bellek temizle") ||
clean.includes("hafızayı boşalt")
) {
return {
action: "ram_cleanup",
speechFeedback: "Bellek ve grafik tamponları temizleniyor.",
rawText: input,
};
}
// 1m. Eko Mod / Düşük RAM Modu
if (
clean === "eko" ||
clean === "eko mod" ||
clean === "tasarruf" ||
clean === "düşük ram" ||
clean === "düşük bellek" ||
clean === "performans modu" ||
clean.includes("eko mod") ||
clean.includes("düşük ram") ||
clean.includes("tasarruf modu")
) {
return {
action: "toggle_eco_mode",
speechFeedback: "Düşük RAM (Eko) modu değiştiriliyor.",
rawText: input,
};
}
// 1n. Otomatik Çözünürlük Modu
if (
clean === "otomatik" ||
clean === "otomatik mod" ||
clean === "oto çözünürlük" ||
clean === "monitör modu" ||
clean === "akıllı mod" ||
clean.includes("otomatik çözünürlük") ||
clean.includes("monitöre göre")
) {
return {
action: "set_resolution_auto",
speechFeedback: "Grafik çözünürlüğü monitöre uyarlı otomatik akıllı moda alındı.",
rawText: input,
};
}
// 2. Seçili Parçanın Ölçülerini Oku
if (
clean.includes("ölçü") ||
clean.includes("boyut") ||
clean.includes("ebat") ||
clean.includes("ne kadar")
) {
return {
action: "speak_selection",
speechFeedback: "Seçili nesnenin boyutları inceleniyor.",
rawText: input,
};
}
// 3. Gruplama (Boolean CSG)
if (
clean.includes("grup yap") ||
clean.includes("grupla") ||
clean.includes("birleştir") ||
clean.includes("kesme yap") ||
clean.includes("deliği kes")
) {
return {
action: "group",
speechFeedback: "Seçili nesneler gruplanıyor ve Boolean kesim uygulanıyor.",
rawText: input,
};
}
// 4. Grubu Çöz (Ungroup)
if (
clean.includes("grubu çöz") ||
clean.includes("ayırma") ||
clean.includes("parçala") ||
clean.includes("dağıt")
) {
return {
action: "ungroup",
speechFeedback: "Grup çözülüyor, alt parçalar ayrıştırıldı.",
rawText: input,
};
}
// 5. Silme (sil sözcüğü silindir ile karışmamalı)
const isDeleteWord = (text: string) => {
const words = text.split(/\s+/);
return (
words.includes("sil") ||
words.includes("silin") ||
words.includes("kaldır") ||
words.includes("yok") ||
text.includes("seçileni sil") ||
text.includes("nesneyi sil")
);
};
if (isDeleteWord(clean)) {
return {
action: "delete",
speechFeedback: "Seçili nesne silindi.",
rawText: input,
};
}
// 6. Geri Al / İleri Al
if (clean.includes("geri al") || clean.includes("eski haline") || clean.includes("geri dön")) {
return {
action: "undo",
speechFeedback: "Son işlem geri alındı.",
rawText: input,
};
}
if (clean.includes("ileri al") || clean.includes("yinele") || clean.includes("tekrar et")) {
return {
action: "redo",
speechFeedback: "İşlem ileri alındı.",
rawText: input,
};
}
// 7. Seçim Komutları
if (clean.includes("tümünü seç") || clean.includes("hepsini seç") || clean.includes("bütün parçalar")) {
return {
action: "select_all",
speechFeedback: "Sahnedeki tüm nesneler seçildi.",
rawText: input,
};
}
if (clean.includes("seçimi kaldır") || clean.includes("bırak") || clean.includes("seçme")) {
return {
action: "deselect",
speechFeedback: "Seçim temizlendi.",
rawText: input,
};
}
// 8. Düzleme Oturtma / Odaklanma
if (clean.includes("düzleme oturt") || clean.includes("zemine oturt") || clean.includes("aşağı indir")) {
return {
action: "drop_to_workplane",
speechFeedback: "Seçili nesne çalışma düzlemine oturtuldu.",
rawText: input,
};
}
if (clean.includes("odaklan") || clean.includes("yaklaş") || clean.includes("merkeze al")) {
return {
action: "fit_view",
speechFeedback: "Kamera seçili nesneye odaklandı.",
rawText: input,
};
}
// 9. Şekil Ekleme Komutları (Box, Cylinder, Sphere, Cone, Pyramid, Torus, Tube, Wedge, Gear, Roof)
const isHole = clean.includes("delik") || clean.includes("oyuk") || clean.includes("kesici");
const numbers = extractNumbersFromText(clean);
let shapeKind: ShapeKind | null = null;
let defaultName = "Parça";
if (clean.includes("kutu") || clean.includes("küp") || clean.includes("prizma") || clean.includes("blok")) {
shapeKind = "box";
defaultName = isHole ? "Delik Kutu" : "Kutu";
} else if (clean.includes("silindir") || clean.includes("mil") || clean.includes("şaft") || clean.includes("burç")) {
shapeKind = "cylinder";
defaultName = isHole ? "Delik Silindir" : "Silindir";
} else if (clean.includes("küre") || clean.includes("top") || clean.includes("bilye")) {
shapeKind = "sphere";
defaultName = isHole ? "Delik Küre" : "Küre";
} else if (clean.includes("koni")) {
shapeKind = "cone";
defaultName = isHole ? "Delik Koni" : "Koni";
} else if (clean.includes("piramit")) {
shapeKind = "pyramid";
defaultName = isHole ? "Delik Piramit" : "Piramit";
} else if (clean.includes("halka") || clean.includes("simit") || clean.includes("torus")) {
shapeKind = "torus";
defaultName = isHole ? "Delik Halka" : "Halka";
} else if (clean.includes("boru") || clean.includes("tüp")) {
shapeKind = "tube";
defaultName = isHole ? "Delik Boru" : "Boru";
} else if (clean.includes("kama") || clean.includes("eğim") || clean.includes("rampa")) {
shapeKind = "wedge";
defaultName = isHole ? "Delik Kama" : "Kama";
} else if (clean.includes("dişli") || clean.includes("çark")) {
shapeKind = "gear";
defaultName = isHole ? "Delik Dişli" : "Dişli Çark";
} else if (clean.includes("çatı")) {
shapeKind = "roundRoof";
defaultName = isHole ? "Delik Çatı" : "Yuvarlak Çatı";
}
if (shapeKind) {
let width = 20;
let depth = 20;
let height = 20;
if (numbers.length >= 3) {
width = numbers[0];
depth = numbers[1];
height = numbers[2];
} else if (numbers.length === 2) {
width = numbers[0];
depth = numbers[1];
height = shapeKind === "gear" ? 6 : 20;
} else if (numbers.length === 1) {
width = numbers[0];
depth = numbers[0];
height = shapeKind === "sphere" ? numbers[0] : 20;
}
const holeText = isHole ? "delik kesici olarak" : "katı gövde olarak";
return {
action: "add_shape",
payload: {
kind: shapeKind,
width,
depth,
height,
isHole,
name: defaultName,
},
speechFeedback: `${width} çarpı ${depth} çarpı ${height} milimetre ebatlarında ${defaultName} ${holeText} sahneye eklendi.`,
rawText: input,
};
}
return {
action: "unknown",
speechFeedback: `"${input}" komutu anlaşılamadı. Örneğin "50'ye 50 kutu ekle", "grupla" veya "sahneyi denetle" diyebilirsiniz.`,
rawText: input,
};
}
+42
View File
@@ -25,6 +25,8 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
accuracy: 2,
historyLimit: 100,
shapeCustomizations: {},
lowMemoryMode: false,
resolutionMode: "auto",
};
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
@@ -166,6 +168,13 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
shapeCustomizations: normalizeShapeCustomizations(candidate.shapeCustomizations, fallback.shapeCustomizations),
lowMemoryMode: booleanOrDefault(candidate.lowMemoryMode, fallback.lowMemoryMode ?? false),
resolutionMode:
candidate.resolutionMode === "auto" || candidate.resolutionMode === "native" || candidate.resolutionMode === "eco"
? candidate.resolutionMode
: candidate.lowMemoryMode
? "eco"
: fallback.resolutionMode ?? "auto",
};
}
@@ -186,3 +195,36 @@ export function workspaceHydrationSyncDecision(pendingFingerprint: string | null
pendingFingerprint: currentFingerprint === pendingFingerprint ? null : pendingFingerprint,
};
}
export function computeEffectivePixelRatio(
workspace: WorkplaneWorkspaceSettings,
shapeCount = 0,
devicePixelRatio = typeof window !== "undefined" ? window.devicePixelRatio : 1,
): number {
const mode = workspace.resolutionMode || (workspace.lowMemoryMode ? "eco" : "auto");
const nativeDpr = Math.min(Math.max(devicePixelRatio || 1, 1), 2);
// Eko / Düşük RAM Modu: Sabit 1.0x ile minimum bellek
if (mode === "eco" || workspace.lowMemoryMode) {
return 1.0;
}
// Doğal Monitör Modu: Monitörün tam piksel sıklığını (Retina / 4K) daima korur
if (mode === "native") {
return nativeDpr;
}
// Otomatik (Akıllı Monitör Uyarlama) Modu:
// Monitör 1x ise 1x.
if (nativeDpr <= 1.05) return 1.0;
// Sahne çok kalabalıklaştığında donmayı ve bellek taşmasını önlemek için dinamik dengeler
if (shapeCount > 45) {
return 1.0;
}
if (shapeCount > 25) {
return Math.min(nativeDpr, 1.25);
}
return nativeDpr;
}
+9
View File
@@ -68,6 +68,8 @@ export type ShapeCustomization = {
export type ShapeCustomizationMap = Partial<Record<ShapeKind, ShapeCustomization>>;
export type ViewportResolutionMode = "auto" | "native" | "eco";
export type WorkplaneWorkspaceSettings = {
width: number;
depth: number;
@@ -86,6 +88,8 @@ export type WorkplaneWorkspaceSettings = {
accuracy: MeasurementAccuracy;
historyLimit: HistoryRetentionLimit;
shapeCustomizations: ShapeCustomizationMap;
lowMemoryMode?: boolean;
resolutionMode?: ViewportResolutionMode;
};
export type AlignAxis = "x" | "y" | "z";
@@ -281,6 +285,11 @@ export type WorkplaneShape = {
// local frame as `positions`. Set only for STEP imports; lets the exporter
// re-emit the original analytic geometry instead of the tessellation.
brepStep?: string;
// Exact original AutoCAD DXF text for imported DWG/DXF files; lets the exporter
// re-emit the pristine original 2D/3D CAD vector drawing instead of dense tessellation.
// Stored as raw string (small files) or deflate-compressed base64 string to prevent RAM spikes.
sourceDxfText?: string;
sourceDxfCompressed?: string;
};
imagePlate?: {
dataUrl: string;