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
+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}