V1
This commit is contained in:
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
124
App.tsx
Normal file
124
App.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { AppConfig, LayoutSplits, GeneratedPart } from './types';
|
||||
// Убедись, что этот файл существует по этому пути
|
||||
import { calculateParts } from './services/geometryGenerator';
|
||||
import { ConfigStep } from './components/ConfigStep';
|
||||
import { LayoutStep } from './components/LayoutStep';
|
||||
import { PreviewStep } from './components/PreviewStep';
|
||||
import { ChevronRight, ChevronLeft, Box } from 'lucide-react';
|
||||
|
||||
const App = () => {
|
||||
const [step, setStep] = useState(1);
|
||||
|
||||
// State
|
||||
const [config, setConfig] = useState<AppConfig>({
|
||||
drawer: { width: 300, depth: 400, height: 80 },
|
||||
wallThickness: 1.2,
|
||||
printerTolerance: 0.5,
|
||||
});
|
||||
|
||||
const [splits, setSplits] = useState<LayoutSplits>({
|
||||
x: [],
|
||||
y: []
|
||||
});
|
||||
|
||||
// Derived State: Parts (Мгновенный пересчет без API)
|
||||
const parts: GeneratedPart[] = useMemo(() => {
|
||||
return calculateParts(config, splits);
|
||||
}, [config, splits]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col font-sans text-gray-100 bg-slate-950">
|
||||
{/* Header */}
|
||||
<header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md sticky top-0 z-50">
|
||||
<div className="max-w-7xl mx-auto flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-primary p-2 rounded-lg">
|
||||
<Box className="text-white" size={20} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-bold tracking-tight">PrintFit</h1>
|
||||
<p className="text-xs text-gray-400">Генератор без ИИ</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress Stepper */}
|
||||
<div className="flex items-center gap-4 text-sm font-medium">
|
||||
{[1, 2, 3].map((num) => (
|
||||
<React.Fragment key={num}>
|
||||
<div className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
|
||||
<span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}>
|
||||
{num}
|
||||
</span>
|
||||
<span className="hidden md:inline">
|
||||
{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}
|
||||
</span>
|
||||
</div>
|
||||
{num < 3 && <div className="w-8 h-[1px] bg-slate-700" />}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="flex-1 max-w-7xl mx-auto w-full p-4 md:p-8">
|
||||
{step === 1 && (
|
||||
<div className="max-w-4xl mx-auto animate-fade-in">
|
||||
<ConfigStep config={config} onChange={setConfig} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<div className="h-[calc(100vh-200px)] min-h-[500px] animate-fade-in">
|
||||
<LayoutStep config={config} splits={splits} onChange={setSplits} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in">
|
||||
<PreviewStep parts={parts} config={config} />
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
{/* Footer Navigation */}
|
||||
<footer className="bg-slate-900 border-t border-slate-800 p-4 sticky bottom-0 z-50">
|
||||
<div className="max-w-7xl mx-auto flex justify-between items-center">
|
||||
<button
|
||||
disabled={step === 1}
|
||||
onClick={() => setStep(s => Math.max(1, s - 1))}
|
||||
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-slate-800 text-white disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-700 transition-colors"
|
||||
>
|
||||
<ChevronLeft size={18} /> Назад
|
||||
</button>
|
||||
|
||||
<div className="text-sm text-gray-500">
|
||||
{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}
|
||||
</div>
|
||||
|
||||
{step < 3 ? (
|
||||
<button
|
||||
onClick={() => setStep(s => Math.min(3, s + 1))}
|
||||
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold bg-primary text-white hover:bg-blue-600 shadow-lg shadow-blue-900/20 transition-all active:scale-95"
|
||||
>
|
||||
Далее <ChevronRight size={18} />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => {
|
||||
setStep(1);
|
||||
setSplits({x: [], y: []});
|
||||
}}
|
||||
className="flex items-center gap-2 px-6 py-3 rounded-lg font-semibold text-gray-400 hover:text-white transition-colors border border-transparent hover:border-slate-700"
|
||||
>
|
||||
Новый проект
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
21
README.md
21
README.md
@@ -1 +1,20 @@
|
||||
# BoxGenerator
|
||||
<div align="center">
|
||||
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
|
||||
</div>
|
||||
|
||||
# Run and deploy your AI Studio app
|
||||
|
||||
This contains everything you need to run your app locally.
|
||||
|
||||
View your app in AI Studio: https://ai.studio/apps/drive/1gUfO_tgl_CPfAGf1eXuSFyC0K7nUZFgu
|
||||
|
||||
## Run Locally
|
||||
|
||||
**Prerequisites:** Node.js
|
||||
|
||||
|
||||
1. Install dependencies:
|
||||
`npm install`
|
||||
2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
|
||||
3. Run the app:
|
||||
`npm run dev`
|
||||
|
||||
133
components/ConfigStep.tsx
Normal file
133
components/ConfigStep.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import React from 'react';
|
||||
import { AppConfig } from '../types';
|
||||
import { Ruler, Box, Layers, Minimize2 } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
config: AppConfig;
|
||||
onChange: (newConfig: AppConfig) => void;
|
||||
}
|
||||
|
||||
const InputGroup: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
|
||||
<div className="flex flex-col gap-2 mb-4">
|
||||
<label className="text-sm font-medium text-gray-300">{label}</label>
|
||||
<div className="flex gap-4">{children}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const NumberInput = ({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
max
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
onChange: (val: number) => void;
|
||||
max?: number
|
||||
}) => (
|
||||
<div className="flex-1 relative">
|
||||
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-xs">{label}</span>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max={max}
|
||||
value={value}
|
||||
onChange={(e) => onChange(parseFloat(e.target.value) || 0)}
|
||||
className="w-full bg-slate-800 border border-slate-700 rounded p-2 pl-8 text-white focus:ring-2 focus:ring-primary outline-none"
|
||||
/>
|
||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 text-xs">мм</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
|
||||
const updateDrawer = (key: keyof AppConfig['drawer'], val: number) => {
|
||||
onChange({ ...config, drawer: { ...config.drawer, [key]: val } });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in">
|
||||
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
|
||||
<Box size={24} /> 1. Размеры
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
{/* Drawer Dimensions */}
|
||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700">
|
||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
||||
<Ruler className="text-accent" size={18} /> Внутренние размеры ящика
|
||||
</h3>
|
||||
<InputGroup label="Ширина (X)">
|
||||
<NumberInput label="Ш" value={config.drawer.width} onChange={(v) => updateDrawer('width', v)} />
|
||||
</InputGroup>
|
||||
<InputGroup label="Глубина (Y)">
|
||||
<NumberInput label="Г" value={config.drawer.depth} onChange={(v) => updateDrawer('depth', v)} />
|
||||
</InputGroup>
|
||||
<InputGroup label="Высота (Z)">
|
||||
<NumberInput label="В" value={config.drawer.height} onChange={(v) => updateDrawer('height', v)} />
|
||||
</InputGroup>
|
||||
</div>
|
||||
|
||||
{/* Settings */}
|
||||
<div className="bg-slate-800/50 p-4 rounded-lg border border-slate-700 flex flex-col justify-center">
|
||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-200">
|
||||
<Layers className="text-accent" size={18} /> Параметры печати
|
||||
</h3>
|
||||
|
||||
<div className="mb-6">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<label className="text-sm font-medium text-gray-300">Толщина стенок</label>
|
||||
<span className="text-primary font-bold bg-primary/10 px-2 py-1 rounded text-sm border border-primary/20">
|
||||
{config.wallThickness.toFixed(1)} мм
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-gray-500 font-mono">0.4</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.4"
|
||||
max="3.2"
|
||||
step="0.1"
|
||||
value={config.wallThickness}
|
||||
onChange={(e) => onChange({...config, wallThickness: parseFloat(e.target.value)})}
|
||||
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-primary hover:accent-blue-400 transition-all"
|
||||
/>
|
||||
<span className="text-xs text-gray-500 font-mono">3.2</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<label className="text-sm font-medium text-gray-300 flex items-center gap-1">
|
||||
<Minimize2 size={14} className="text-gray-400"/> Зазор (Tolerance)
|
||||
</label>
|
||||
<span className="text-accent font-bold bg-accent/10 px-2 py-1 rounded text-sm border border-accent/20">
|
||||
{config.printerTolerance.toFixed(1)} мм
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-gray-500 font-mono">0.0</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.0"
|
||||
max="2.0"
|
||||
step="0.1"
|
||||
value={config.printerTolerance}
|
||||
onChange={(e) => onChange({...config, printerTolerance: parseFloat(e.target.value)})}
|
||||
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-accent hover:accent-amber-400 transition-all"
|
||||
/>
|
||||
<span className="text-xs text-gray-500 font-mono">2.0</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-slate-900/50 p-3 rounded border border-slate-700/50">
|
||||
<p className="text-xs text-gray-400 leading-relaxed">
|
||||
<span className="text-accent font-semibold">Зазор</span> уменьшает размер каждой ячейки, чтобы они легко вставлялись в ящик и друг в друга. Рекомендуется 0.5 мм.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
372
components/LayoutStep.tsx
Normal file
372
components/LayoutStep.tsx
Normal file
@@ -0,0 +1,372 @@
|
||||
import React, { useRef, useState, useMemo } from 'react';
|
||||
import { AppConfig, LayoutSplits } from '../types';
|
||||
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
config: AppConfig;
|
||||
splits: LayoutSplits;
|
||||
onChange: (splits: LayoutSplits) => void;
|
||||
}
|
||||
|
||||
type Axis = 'x' | 'y';
|
||||
|
||||
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
|
||||
// State for interaction
|
||||
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null); // Proposed new line axis
|
||||
const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); // Normalized 0-1
|
||||
const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null);
|
||||
const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null);
|
||||
|
||||
// Constants
|
||||
const SNAP_THRESHOLD = 0.02; // Reduced threshold slightly for better precision on large grid
|
||||
const viewBoxW = 1000;
|
||||
const aspectRatio = config.drawer.depth / config.drawer.width;
|
||||
const viewBoxH = viewBoxW * aspectRatio;
|
||||
|
||||
// Helpers to calculate cell dimensions
|
||||
// IMPORTANT: Dependencies must be correct. dragging updates splits, which updates sortedX/Y
|
||||
const sortedX = useMemo(() => [0, ...splits.x, 1].sort((a, b) => a - b), [splits.x]);
|
||||
const sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]);
|
||||
|
||||
// Handlers
|
||||
const handleMouseMove = (e: React.MouseEvent) => {
|
||||
if (!svgRef.current) return;
|
||||
const rect = svgRef.current.getBoundingClientRect();
|
||||
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
|
||||
const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
|
||||
|
||||
setMousePos({ x: nx, y: ny });
|
||||
|
||||
if (dragging) {
|
||||
// Move logic
|
||||
// IMPORTANT: Create NEW array references so useMemo in this component and parent components detect changes
|
||||
const newSplits = {
|
||||
x: [...splits.x],
|
||||
y: [...splits.y]
|
||||
};
|
||||
|
||||
const val = dragging.axis === 'x' ? nx : ny;
|
||||
newSplits[dragging.axis][dragging.index] = val;
|
||||
|
||||
onChange(newSplits);
|
||||
return;
|
||||
}
|
||||
|
||||
// Hover logic: Check if near existing lines
|
||||
let foundSplit = null;
|
||||
|
||||
// Check X splits (Vertical lines)
|
||||
splits.x.forEach((val, idx) => {
|
||||
if (Math.abs(nx - val) < SNAP_THRESHOLD) foundSplit = { axis: 'x' as Axis, index: idx };
|
||||
});
|
||||
|
||||
// Check Y splits (Horizontal lines)
|
||||
if (!foundSplit) {
|
||||
splits.y.forEach((val, idx) => {
|
||||
if (Math.abs(ny - val) < SNAP_THRESHOLD) foundSplit = { axis: 'y' as Axis, index: idx };
|
||||
});
|
||||
}
|
||||
|
||||
setHoveredSplit(foundSplit);
|
||||
|
||||
// Auto-detect axis for NEW lines if not hovering existing
|
||||
// AND if not too close to other lines
|
||||
if (!foundSplit) {
|
||||
// Check proximity to ALL lines to prevent creating duplicates
|
||||
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD);
|
||||
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD);
|
||||
|
||||
// Also check edges (0 and 1)
|
||||
const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD);
|
||||
const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD);
|
||||
|
||||
if (closeToX || closeToEdgeX) {
|
||||
// Too close to X line or edge, don't allow vertical split here
|
||||
// But might allow horizontal?
|
||||
// Actually if we are close to an X line, we probably want to select it, which is handled by foundSplit.
|
||||
// If foundSplit is null but closeToX is true, it means we are just outside threshold?
|
||||
// Let's simplified: if too close to any parallel line, disable creation.
|
||||
}
|
||||
|
||||
const distLeft = nx;
|
||||
const distRight = 1 - nx;
|
||||
const distTop = ny;
|
||||
const distBottom = 1 - ny;
|
||||
|
||||
const minXDist = Math.min(distLeft, distRight);
|
||||
const minYDist = Math.min(distTop, distBottom);
|
||||
|
||||
// Determine potential axis
|
||||
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
|
||||
|
||||
// Validate proximity for that axis
|
||||
let valid = true;
|
||||
if (potentialAxis === 'x') {
|
||||
if (closeToX || closeToEdgeX) valid = false;
|
||||
} else {
|
||||
if (closeToY || closeToEdgeY) valid = false;
|
||||
}
|
||||
|
||||
if (valid) {
|
||||
setPhantomAxis(potentialAxis);
|
||||
} else {
|
||||
setPhantomAxis(null);
|
||||
}
|
||||
} else {
|
||||
setPhantomAxis(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseDown = (e: React.MouseEvent) => {
|
||||
if (hoveredSplit) {
|
||||
// Start Dragging
|
||||
if (e.button === 0) { // Left click
|
||||
setDragging(hoveredSplit);
|
||||
} else if (e.button === 2) { // Right click
|
||||
removeSplit(hoveredSplit.axis, hoveredSplit.index);
|
||||
}
|
||||
} else if (phantomAxis) {
|
||||
// Create New Split
|
||||
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y;
|
||||
const newSplits = { ...splits };
|
||||
newSplits[phantomAxis] = [...newSplits[phantomAxis], val];
|
||||
onChange(newSplits);
|
||||
// Immediately start dragging the new line for fine-tuning
|
||||
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 });
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
setDragging(null);
|
||||
};
|
||||
|
||||
const removeSplit = (axis: Axis, index: number) => {
|
||||
const newSplits = { ...splits };
|
||||
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
|
||||
onChange(newSplits);
|
||||
setHoveredSplit(null);
|
||||
setDragging(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
||||
<Grid size={24} /> 2. Редактор макета
|
||||
</h2>
|
||||
<button
|
||||
onClick={() => onChange({ x: [], y: [] })}
|
||||
className="px-3 py-1 text-xs bg-slate-800 text-red-400 hover:text-red-300 rounded hover:bg-slate-700 border border-slate-700 flex items-center gap-1 transition-colors"
|
||||
>
|
||||
<RotateCcw size={14} /> Сбросить сетку
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col h-full select-none">
|
||||
<div className="flex-1 bg-slate-800/30 rounded-lg p-6 flex flex-col items-center justify-center relative overflow-hidden border border-slate-700/50">
|
||||
|
||||
{/* Instruction Box */}
|
||||
<div className="absolute top-4 left-4 z-10 bg-slate-900/90 p-3 rounded-lg backdrop-blur border border-slate-700 shadow-xl max-w-[200px] pointer-events-none">
|
||||
<div className="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm">
|
||||
<MousePointer2 size={14} className="text-primary"/> Инструкция
|
||||
</div>
|
||||
<ul className="space-y-1.5 text-[10px] text-gray-400 leading-tight">
|
||||
<li><b className="text-blue-400">Клик у края:</b> Новая линия</li>
|
||||
<li><b className="text-orange-400">Перетаскивание:</b> Изменить размер</li>
|
||||
<li><b className="text-red-400">Двойной клик/ПКМ:</b> Удалить</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Rulers */}
|
||||
<div className="w-full flex justify-between px-8 mb-1 max-w-[900px]">
|
||||
<span className="text-xs text-slate-500 font-mono">0</span>
|
||||
<span className="text-xs text-slate-500 font-mono">{config.drawer.width} мм</span>
|
||||
</div>
|
||||
|
||||
<div className="relative flex items-center justify-center w-full h-full">
|
||||
<div className="h-full max-h-[90%] flex flex-col justify-between py-2 mr-2">
|
||||
<span className="text-xs text-slate-500 font-mono">0</span>
|
||||
<span className="text-xs text-slate-500 font-mono" style={{writingMode: 'vertical-rl'}}>{config.drawer.depth} мм</span>
|
||||
</div>
|
||||
|
||||
{/* Main Interactive SVG */}
|
||||
<div
|
||||
className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden"
|
||||
style={{
|
||||
width: '100%',
|
||||
maxWidth: '900px',
|
||||
aspectRatio: `${1/aspectRatio}`,
|
||||
cursor: dragging ? 'grabbing' : hoveredSplit ? 'grab' : 'crosshair',
|
||||
maxHeight: '75vh'
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`0 0 ${viewBoxW} ${viewBoxH}`}
|
||||
className="w-full h-full touch-none"
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseUp}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<defs>
|
||||
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
|
||||
<path d="M 50 0 L 0 0 0 50" fill="none" stroke="rgba(255,255,255,0.03)" strokeWidth="1"/>
|
||||
</pattern>
|
||||
<filter id="solid-bg" x="-0.1" y="-0.1" width="1.2" height="1.2">
|
||||
<feFlood floodColor="#1e293b" floodOpacity="0.8"/>
|
||||
<feComposite in="SourceGraphic" operator="over"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<rect width="100%" height="100%" fill="url(#grid)" />
|
||||
|
||||
{/* --- Cell Dimensions Labels --- */}
|
||||
{sortedX.slice(0, -1).map((x1, i) => {
|
||||
const x2 = sortedX[i + 1];
|
||||
return sortedY.slice(0, -1).map((y1, j) => {
|
||||
const y2 = sortedY[j + 1];
|
||||
const width = (x2 - x1) * config.drawer.width;
|
||||
const depth = (y2 - y1) * config.drawer.depth;
|
||||
const centerX = ((x1 + x2) / 2) * viewBoxW;
|
||||
const centerY = ((y1 + y2) / 2) * viewBoxH;
|
||||
|
||||
const cellWidthSVG = (x2 - x1) * viewBoxW;
|
||||
const cellHeightSVG = (y2 - y1) * viewBoxH;
|
||||
|
||||
// Dynamic Font Sizing Logic
|
||||
// Max font size: 36px
|
||||
// Must fit in height: 60% of height max
|
||||
// Must fit in width: approx 25% of width max (assuming ~5 chars)
|
||||
let fontSize = Math.min(36, cellHeightSVG * 0.6);
|
||||
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
|
||||
|
||||
// Don't show text if calculated font size is too small to be readable
|
||||
if (fontSize < 10) return null;
|
||||
|
||||
return (
|
||||
<text
|
||||
key={`label-${i}-${j}`}
|
||||
x={centerX}
|
||||
y={centerY}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="middle"
|
||||
className="pointer-events-none select-none fill-slate-100 font-bold font-mono drop-shadow-md transition-all duration-200"
|
||||
style={{
|
||||
fontSize: `${fontSize}px`,
|
||||
textShadow: '1px 1px 3px rgba(0,0,0,0.8)'
|
||||
}}
|
||||
>
|
||||
{width.toFixed(0)} × {depth.toFixed(0)}
|
||||
</text>
|
||||
);
|
||||
});
|
||||
})}
|
||||
|
||||
{/* --- Existing X Lines (Vertical) --- */}
|
||||
{splits.x.map((x, i) => {
|
||||
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i;
|
||||
const isDragging = dragging?.axis === 'x' && dragging.index === i;
|
||||
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
|
||||
const width = isHovered || isDragging ? 8 : 4;
|
||||
|
||||
return (
|
||||
<g key={`x-${i}`} onDoubleClick={() => removeSplit('x', i)}>
|
||||
{/* Invisible wide hit area */}
|
||||
<line
|
||||
x1={x * viewBoxW} y1={0}
|
||||
x2={x * viewBoxW} y2={viewBoxH}
|
||||
stroke="transparent" strokeWidth="60"
|
||||
className="cursor-col-resize hover:stroke-white/5"
|
||||
/>
|
||||
{/* Visible Line */}
|
||||
<line
|
||||
x1={x * viewBoxW} y1={0}
|
||||
x2={x * viewBoxW} y2={viewBoxH}
|
||||
stroke={color} strokeWidth={width}
|
||||
className="transition-all duration-150"
|
||||
/>
|
||||
{/* Delete Button if hovered */}
|
||||
{(isHovered || isDragging) && (
|
||||
<g transform={`translate(${x * viewBoxW}, 40)`} onClick={(e) => { e.stopPropagation(); removeSplit('x', i); }}>
|
||||
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
|
||||
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* --- Existing Y Lines (Horizontal) --- */}
|
||||
{splits.y.map((y, i) => {
|
||||
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i;
|
||||
const isDragging = dragging?.axis === 'y' && dragging.index === i;
|
||||
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
|
||||
const width = isHovered || isDragging ? 8 : 4;
|
||||
|
||||
return (
|
||||
<g key={`y-${i}`} onDoubleClick={() => removeSplit('y', i)}>
|
||||
{/* Invisible wide hit area */}
|
||||
<line
|
||||
x1={0} y1={y * viewBoxH}
|
||||
x2={viewBoxW} y2={y * viewBoxH}
|
||||
stroke="transparent" strokeWidth="60"
|
||||
className="cursor-row-resize hover:stroke-white/5"
|
||||
/>
|
||||
<line
|
||||
x1={0} y1={y * viewBoxH}
|
||||
x2={viewBoxW} y2={y * viewBoxH}
|
||||
stroke={color} strokeWidth={width}
|
||||
className="transition-all duration-150"
|
||||
/>
|
||||
{(isHovered || isDragging) && (
|
||||
<g transform={`translate(40, ${y * viewBoxH})`} onClick={(e) => { e.stopPropagation(); removeSplit('y', i); }}>
|
||||
<circle r="16" fill="#ef4444" className="cursor-pointer hover:scale-110 transition-transform shadow-lg"/>
|
||||
<Trash2 size={16} color="white" x={-8} y={-8} className="pointer-events-none"/>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* --- Phantom Line (Preview) --- */}
|
||||
{!hoveredSplit && !dragging && phantomAxis === 'x' && (
|
||||
<g>
|
||||
<line
|
||||
x1={mousePos.x * viewBoxW} y1="0"
|
||||
x2={mousePos.x * viewBoxW} y2="100%"
|
||||
stroke="#3b82f6"
|
||||
strokeWidth="4"
|
||||
strokeDasharray="12,8"
|
||||
className="pointer-events-none opacity-60"
|
||||
/>
|
||||
<g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}>
|
||||
<circle r="3" fill="#3b82f6" />
|
||||
</g>
|
||||
</g>
|
||||
)}
|
||||
{!hoveredSplit && !dragging && phantomAxis === 'y' && (
|
||||
<g>
|
||||
<line
|
||||
x1="0" y1={mousePos.y * viewBoxH}
|
||||
x2="100%" y2={mousePos.y * viewBoxH}
|
||||
stroke="#3b82f6"
|
||||
strokeWidth="4"
|
||||
strokeDasharray="12,8"
|
||||
className="pointer-events-none opacity-60"
|
||||
/>
|
||||
<g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}>
|
||||
<circle r="3" fill="#3b82f6" />
|
||||
</g>
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
259
components/PreviewStep.tsx
Normal file
259
components/PreviewStep.tsx
Normal file
@@ -0,0 +1,259 @@
|
||||
import React, { useMemo, Suspense, useEffect, useRef, useState } from 'react';
|
||||
import { Canvas } from '@react-three/fiber';
|
||||
import { OrbitControls, Center, Environment } from '@react-three/drei';
|
||||
import * as THREE from 'three';
|
||||
import JSZip from 'jszip';
|
||||
import { AppConfig, GeneratedPart } from '../types';
|
||||
import { createBinGeometry, exportSTL, generateSTL } from '../services/geometryGenerator';
|
||||
import { Download, Package, Info, Loader2 } from 'lucide-react';
|
||||
|
||||
// --- 3D Helper Components ---
|
||||
|
||||
// Каркас ящика (только ребра, без диагоналей)
|
||||
const DrawerFrame = ({ config }: { config: AppConfig }) => {
|
||||
const { width, depth, height } = config.drawer;
|
||||
const offset = 0.5; // Небольшой отступ наружу
|
||||
|
||||
return (
|
||||
<group position={[width / 2, height / 2, depth / 2]}>
|
||||
<lineSegments>
|
||||
<edgesGeometry args={[new THREE.BoxGeometry(width + offset, height + offset, depth + offset)]} />
|
||||
<lineBasicMaterial color="#475569" />
|
||||
</lineSegments>
|
||||
</group>
|
||||
)
|
||||
}
|
||||
|
||||
// --- Bin Component ---
|
||||
|
||||
interface BinMeshProps {
|
||||
part: GeneratedPart;
|
||||
thickness: number;
|
||||
isSelected: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, isSelected, onClick }) => {
|
||||
// REMOVED ARTIFICIAL GAP: The part dimensions now include the printer tolerance physically.
|
||||
// The gap will be visible naturally because part.width is smaller than grid size.
|
||||
|
||||
// Генерируем реальную геометрию, как для STL
|
||||
const geometry = useMemo(() => {
|
||||
return createBinGeometry(part.width, part.depth, part.height, thickness);
|
||||
}, [part, thickness]);
|
||||
|
||||
return (
|
||||
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}>
|
||||
{/* Основной меш ячейки */}
|
||||
<mesh
|
||||
geometry={geometry}
|
||||
onClick={(e) => { e.stopPropagation(); onClick(); }}
|
||||
>
|
||||
<meshStandardMaterial
|
||||
color={isSelected ? '#f59e0b' : part.color}
|
||||
roughness={0.5}
|
||||
metalness={0.1}
|
||||
/>
|
||||
</mesh>
|
||||
|
||||
{/* Подсветка выделения (Bounding Box) */}
|
||||
{isSelected && (
|
||||
<lineSegments position={[0, part.height/2, 0]}>
|
||||
<edgesGeometry args={[new THREE.BoxGeometry(part.width, part.height, part.depth)]} />
|
||||
<lineBasicMaterial color="white" linewidth={2} />
|
||||
</lineSegments>
|
||||
)}
|
||||
</group>
|
||||
);
|
||||
};
|
||||
|
||||
interface Props {
|
||||
parts: GeneratedPart[];
|
||||
config: AppConfig;
|
||||
}
|
||||
|
||||
export const PreviewStep: React.FC<Props> = ({ parts, config }) => {
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [isZipping, setIsZipping] = useState(false);
|
||||
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
|
||||
|
||||
// Автопрокрутка к выбранному элементу
|
||||
useEffect(() => {
|
||||
if (selectedId && itemRefs.current[selectedId]) {
|
||||
itemRefs.current[selectedId]?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'center'
|
||||
});
|
||||
}
|
||||
}, [selectedId]);
|
||||
|
||||
const handleDownload = (part: GeneratedPart) => {
|
||||
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness);
|
||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
|
||||
};
|
||||
|
||||
const handleDownloadAll = async () => {
|
||||
if (isZipping) return;
|
||||
setIsZipping(true);
|
||||
|
||||
try {
|
||||
console.log("Starting ZIP generation...");
|
||||
// Ensure JSZip is available
|
||||
if (typeof JSZip === 'undefined' && !JSZip) {
|
||||
throw new Error("Библиотека JSZip не загружена.");
|
||||
}
|
||||
|
||||
const zip = new JSZip();
|
||||
|
||||
// Генерация STL для каждой части и добавление в архив
|
||||
parts.forEach(part => {
|
||||
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness);
|
||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
|
||||
const stlData = generateSTL(mesh);
|
||||
// stlData is Uint8Array or string here, which is supported
|
||||
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
|
||||
});
|
||||
|
||||
console.log("Files added to ZIP. Generating blob...");
|
||||
|
||||
// Генерация самого ZIP файла
|
||||
const content = await zip.generateAsync({ type: "blob" });
|
||||
|
||||
console.log("ZIP blob generated. Size:", content.size);
|
||||
|
||||
// Скачивание
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(content);
|
||||
link.download = "PrintFit_Project.zip";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
} catch (e: any) {
|
||||
console.error("Failed to create zip archive", e);
|
||||
alert(`Ошибка при создании архива: ${e.message || 'Неизвестная ошибка'}`);
|
||||
} finally {
|
||||
setIsZipping(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col lg:flex-row h-full gap-6">
|
||||
{/* 3D Viewer */}
|
||||
<div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]">
|
||||
<div className="absolute top-4 right-4 z-10 bg-black/60 p-3 rounded-lg text-xs text-gray-300 backdrop-blur pointer-events-none border border-slate-700">
|
||||
<div className="flex items-center gap-2 mb-1 text-primary font-bold">
|
||||
<Info size={14} /> Управление
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
<li>• ЛКМ: Вращение</li>
|
||||
<li>• ПКМ: Перемещение</li>
|
||||
<li>• Скролл: Масштаб</li>
|
||||
<li className="text-accent mt-2 font-semibold">• Клик по детали для выбора</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<Canvas
|
||||
shadows
|
||||
dpr={[1, 2]}
|
||||
camera={{
|
||||
position: [config.drawer.width * 1.5, config.drawer.height * 3, config.drawer.depth * 1.5],
|
||||
fov: 45,
|
||||
near: 1,
|
||||
far: 20000
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={null}>
|
||||
<color attach="background" args={['#0f172a']} />
|
||||
|
||||
<ambientLight intensity={0.7} />
|
||||
<directionalLight position={[100, 200, 50]} intensity={1.2} />
|
||||
<directionalLight position={[-100, 100, -50]} intensity={0.5} />
|
||||
<Environment preset="city" />
|
||||
|
||||
<Center>
|
||||
<group>
|
||||
<DrawerFrame config={config} />
|
||||
{parts.map(part => (
|
||||
<BinMesh
|
||||
key={part.id}
|
||||
part={part}
|
||||
thickness={config.wallThickness}
|
||||
isSelected={selectedId === part.id}
|
||||
onClick={() => setSelectedId(part.id)}
|
||||
/>
|
||||
))}
|
||||
</group>
|
||||
</Center>
|
||||
|
||||
<OrbitControls makeDefault minDistance={10} maxDistance={10000} />
|
||||
</Suspense>
|
||||
</Canvas>
|
||||
</div>
|
||||
|
||||
{/* Sidebar List */}
|
||||
<div className="w-full lg:w-96 bg-slate-900 p-6 rounded-xl border border-slate-800 flex flex-col h-full shadow-xl">
|
||||
<div className="flex justify-between items-center mb-6 shrink-0">
|
||||
<h2 className="text-xl font-bold flex items-center gap-2 text-primary">
|
||||
<Package size={24} /> Детали ({parts.length})
|
||||
</h2>
|
||||
<button
|
||||
onClick={handleDownloadAll}
|
||||
disabled={isZipping || parts.length === 0}
|
||||
className={`bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-md text-sm font-medium flex items-center gap-1 transition-all active:scale-95 disabled:opacity-50 disabled:scale-100 disabled:cursor-not-allowed`}
|
||||
>
|
||||
{isZipping ? (
|
||||
<>
|
||||
<Loader2 size={16} className="animate-spin" /> ZIP...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download size={16} /> Скачать все
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto pr-2 space-y-3 custom-scrollbar">
|
||||
{parts.map(part => (
|
||||
<div
|
||||
key={part.id}
|
||||
ref={(el) => { itemRefs.current[part.id] = el }}
|
||||
className={`p-4 rounded-lg border transition-all cursor-pointer group ${selectedId === part.id ? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent' : 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'}`}
|
||||
onClick={() => setSelectedId(part.id)}
|
||||
>
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<span className="font-semibold text-gray-200 group-hover:text-white transition-colors">{part.name}</span>
|
||||
<div
|
||||
className="w-3 h-3 rounded-full border border-white/10"
|
||||
style={{ backgroundColor: part.color }}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-xs text-gray-400 mb-3">
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Ширина</span>
|
||||
{part.width.toFixed(1)}
|
||||
</div>
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Глубина</span>
|
||||
{part.depth.toFixed(1)}
|
||||
</div>
|
||||
<div className="bg-slate-900/50 p-1.5 rounded">
|
||||
<span className="block text-gray-500 uppercase text-[9px] mb-0.5">Высота</span>
|
||||
{part.height.toFixed(1)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
|
||||
className="w-full py-2 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-2 transition-colors font-medium"
|
||||
>
|
||||
<Download size={14} /> Скачать STL
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
33
index.html
Normal file
33
index.html
Normal file
@@ -0,0 +1,33 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>PrintFit - Генератор Органайзеров</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script>
|
||||
tailwind.config = {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
primary: '#3b82f6',
|
||||
secondary: '#1e293b',
|
||||
accent: '#f59e0b',
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<style>
|
||||
body { margin: 0; background-color: #0f172a; color: white; }
|
||||
/* Скроллбар в стиле приложения */
|
||||
::-webkit-scrollbar { width: 8px; }
|
||||
::-webkit-scrollbar-track { background: #1e293b; }
|
||||
::-webkit-scrollbar-thumb { background: #475569; border-radius: 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
15
index.tsx
Normal file
15
index.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
|
||||
const rootElement = document.getElementById('root');
|
||||
if (!rootElement) {
|
||||
throw new Error("Could not find root element to mount to");
|
||||
}
|
||||
|
||||
const root = ReactDOM.createRoot(rootElement);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
5
metadata.json
Normal file
5
metadata.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "PrintFit - Генератор органайзеров",
|
||||
"description": "Параметрический инструмент для создания и нарезки органайзеров для 3D-печати. Настройте размеры, создайте макет и скачайте STL файлы.",
|
||||
"requestFramePermissions": []
|
||||
}
|
||||
31
package.json
Normal file
31
package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "printfit-organizer",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"three": "^0.182.0",
|
||||
"three-stdlib": "^2.36.1",
|
||||
"lucide-react": "^0.562.0",
|
||||
"@react-three/drei": "^10.7.7",
|
||||
"@react-three/fiber": "^9.4.2",
|
||||
"jszip": "3.10.1",
|
||||
"uuid": "^9.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@types/node": "^22.14.0",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^6.2.0"
|
||||
}
|
||||
}
|
||||
137
services/geometryGenerator.ts
Normal file
137
services/geometryGenerator.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import * as THREE from 'three';
|
||||
import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
|
||||
import { AppConfig, LayoutSplits, GeneratedPart } from '../types';
|
||||
|
||||
/**
|
||||
* Calculates the final list of bins based on layout.
|
||||
* Removes printer bed constraints logic.
|
||||
*/
|
||||
export const calculateParts = (
|
||||
config: AppConfig,
|
||||
splits: LayoutSplits
|
||||
): GeneratedPart[] => {
|
||||
const parts: GeneratedPart[] = [];
|
||||
|
||||
// 1. Sort splits to create segments
|
||||
// CRITICAL FIX: Create a copy of the array before sorting to avoid mutating React state
|
||||
const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1];
|
||||
const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1];
|
||||
|
||||
let partCounter = 1;
|
||||
|
||||
// 2. Iterate through the grid defined by the user
|
||||
for (let i = 0; i < xPoints.length - 1; i++) {
|
||||
for (let j = 0; j < yPoints.length - 1; j++) {
|
||||
|
||||
const segmentX = xPoints[i] * config.drawer.width;
|
||||
const segmentY = yPoints[j] * config.drawer.depth;
|
||||
const segmentW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
|
||||
const segmentD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
|
||||
|
||||
// Apply Printer Tolerance (Gap)
|
||||
// We subtract the tolerance from the width/depth and shift the position
|
||||
// so the gap is evenly distributed around the part center.
|
||||
const realWidth = segmentW - config.printerTolerance;
|
||||
const realDepth = segmentD - config.printerTolerance;
|
||||
const realX = segmentX + (config.printerTolerance / 2);
|
||||
const realY = segmentY + (config.printerTolerance / 2);
|
||||
|
||||
// Filter out extremely small parts (likely errors/double lines or consumed by tolerance)
|
||||
if (realWidth < 1 || realDepth < 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
parts.push({
|
||||
id: `part-${partCounter}`,
|
||||
name: `Ячейка ${i+1}-${j+1}`,
|
||||
width: realWidth,
|
||||
depth: realDepth,
|
||||
height: config.drawer.height,
|
||||
x: realX,
|
||||
y: realY,
|
||||
color: `hsl(${Math.random() * 360}, 70%, 50%)`
|
||||
});
|
||||
partCounter++;
|
||||
}
|
||||
}
|
||||
|
||||
return parts;
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates a Three.js Geometry for a hollow bin.
|
||||
* The floor is at y=0..thickness.
|
||||
* The walls sit on top of the floor, y=thickness..height.
|
||||
*/
|
||||
export const createBinGeometry = (
|
||||
width: number,
|
||||
depth: number,
|
||||
height: number,
|
||||
thickness: number
|
||||
): THREE.BufferGeometry => {
|
||||
const geometries: THREE.BufferGeometry[] = [];
|
||||
|
||||
// 1. Floor (Base)
|
||||
// Positioned at the bottom (0 to thickness)
|
||||
const floorGeo = new THREE.BoxGeometry(width, thickness, depth);
|
||||
floorGeo.translate(0, thickness / 2, 0);
|
||||
geometries.push(floorGeo);
|
||||
|
||||
// Wall dimensions
|
||||
// Walls sit ON TOP of the floor to avoid overlap/z-fighting
|
||||
const wallHeight = height - thickness;
|
||||
const wallCenterY = thickness + (wallHeight / 2);
|
||||
|
||||
if (wallHeight > 0) {
|
||||
// 2. Left & Right Walls (Full depth)
|
||||
const wallLRGeo = new THREE.BoxGeometry(thickness, wallHeight, depth);
|
||||
|
||||
const leftWall = wallLRGeo.clone();
|
||||
leftWall.translate(-(width/2) + (thickness/2), wallCenterY, 0);
|
||||
geometries.push(leftWall);
|
||||
|
||||
const rightWall = wallLRGeo.clone();
|
||||
rightWall.translate((width/2) - (thickness/2), wallCenterY, 0);
|
||||
geometries.push(rightWall);
|
||||
|
||||
// 3. Front & Back Walls (Width minus LR thickness to fit between)
|
||||
// Width is reduced by 2*thickness
|
||||
const wallFBWidth = Math.max(0, width - (2 * thickness));
|
||||
const wallFBGeo = new THREE.BoxGeometry(wallFBWidth, wallHeight, thickness);
|
||||
|
||||
const frontWall = wallFBGeo.clone();
|
||||
frontWall.translate(0, wallCenterY, (depth/2) - (thickness/2));
|
||||
geometries.push(frontWall);
|
||||
|
||||
const backWall = wallFBGeo.clone();
|
||||
backWall.translate(0, wallCenterY, -(depth/2) + (thickness/2));
|
||||
geometries.push(backWall);
|
||||
}
|
||||
|
||||
// Merge geometries into a single mesh for clean STL export
|
||||
const merged = mergeBufferGeometries(geometries);
|
||||
return merged || new THREE.BoxGeometry(1, 1, 1);
|
||||
};
|
||||
|
||||
// Generates STL binary data without triggering download
|
||||
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
||||
const exporter = new STLExporter();
|
||||
const result = exporter.parse(mesh, { binary: true });
|
||||
|
||||
// JSZip requires Uint8Array or ArrayBuffer, not DataView
|
||||
if (result instanceof DataView) {
|
||||
return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
|
||||
}
|
||||
|
||||
return result as string;
|
||||
};
|
||||
|
||||
// Triggers download immediately
|
||||
export const exportSTL = (mesh: THREE.Object3D, filename: string) => {
|
||||
const result = generateSTL(mesh);
|
||||
const blob = new Blob([result], { type: 'application/octet-stream' });
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = filename;
|
||||
link.click();
|
||||
};
|
||||
29
tsconfig.json
Normal file
29
tsconfig.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"module": "ESNext",
|
||||
"lib": [
|
||||
"ES2022",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"skipLibCheck": true,
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"moduleResolution": "bundler",
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"allowJs": true,
|
||||
"jsx": "react-jsx",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
},
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true
|
||||
}
|
||||
}
|
||||
29
types.ts
Normal file
29
types.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export interface Dimensions {
|
||||
width: number;
|
||||
depth: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
drawer: Dimensions;
|
||||
wallThickness: number;
|
||||
printerTolerance: number; // Gap between parts for fit
|
||||
}
|
||||
|
||||
// Represents a vertical or horizontal divider position (0 to 1)
|
||||
export interface LayoutSplits {
|
||||
x: number[]; // Vertical dividers (along width)
|
||||
y: number[]; // Horizontal dividers (along depth)
|
||||
}
|
||||
|
||||
// A single generated bin part
|
||||
export interface GeneratedPart {
|
||||
id: string;
|
||||
name: string;
|
||||
width: number;
|
||||
depth: number;
|
||||
height: number;
|
||||
x: number; // Position in drawer
|
||||
y: number; // Position in drawer
|
||||
color: string;
|
||||
}
|
||||
16
vite.config.ts
Normal file
16
vite.config.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import path from 'path';
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: 3000,
|
||||
host: '0.0.0.0',
|
||||
},
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user