Compare commits

...
65 Commits
Author SHA1 Message Date
Халимов Рустам 64cdd902f8 F 2026-07-03 09:55:12 +03:00
Халимов Рустам f7fbae506e WIP on test 2026-07-03 09:46:35 +03:00
rust 0137872fb7 Merge pull request 'Добавление перфораций' (#10) from test into main
Reviewed-on: http://192.168.1.114:3000/rust/BoxGenerator/pulls/10
2026-01-13 01:13:41 +03:00
Халимов Рустам 21a41ccf05 Add sizes 2026-01-13 01:10:04 +03:00
Халимов Рустам 01dbf52fc7 Fix 2026-01-12 23:53:21 +03:00
Халимов Рустам 34543d07c5 Fix 2026-01-12 23:21:07 +03:00
Халимов Рустам aaff0d06df Fix height 2026-01-12 21:26:38 +03:00
Халимов Рустам 531b5dc0b1 Add perforation 2026-01-12 17:32:41 +03:00
rust 356873fb0e Merge pull request 'Скругления только для примыканий к стенкам' (#9) from test into main
Reviewed-on: http://192.168.1.114:3000/rust/BoxGenerator/pulls/9
2026-01-11 23:50:32 +03:00
Халимов Рустам 96bf976b64 2 2026-01-11 23:40:10 +03:00
Халимов Рустам 43a54c99a6 1 2026-01-11 23:11:09 +03:00
Халимов Рустам 0f071c9587 Height limit 2026-01-11 22:53:38 +03:00
Халимов Рустам ade10e0aaf 1 2026-01-11 22:38:12 +03:00
Халимов Рустам 918d9e0ea7 Restore 2026-01-11 22:12:56 +03:00
Халимов Рустам d9bc3bda17 Restote 2026-01-11 22:07:46 +03:00
Халимов Рустам fe1f5df710 Mouse leave 2026-01-11 22:03:15 +03:00
rust 6daa10746b Merge pull request 'Корректная расстановка стенок' (#7) from test into main
Reviewed-on: http://192.168.1.114:3000/rust/BoxGenerator/pulls/7
2026-01-11 15:58:40 +03:00
Халимов Рустам 33a5b8d44d 13 2026-01-11 15:54:50 +03:00
Халимов Рустам 803c7213d5 12 2026-01-11 15:48:49 +03:00
Халимов Рустам 56183b3ada 11 2026-01-11 15:40:07 +03:00
Халимов Рустам 272b2b6f77 10 2026-01-11 15:27:12 +03:00
Халимов Рустам 454e6cf822 9 2026-01-11 15:14:29 +03:00
Халимов Рустам 1e9a1d288a 8 2026-01-11 15:01:42 +03:00
Халимов Рустам 8c39e18de4 7 2026-01-11 14:36:56 +03:00
Халимов Рустам 94eb2f00b2 6 2026-01-11 14:26:00 +03:00
Халимов Рустам eb8c5c48c7 5 2026-01-11 14:12:17 +03:00
Халимов Рустам 490adb8ac6 4 2026-01-11 14:02:04 +03:00
Халимов Рустам 6cd7a5194d 3 2026-01-11 13:54:10 +03:00
Халимов Рустам 438c7b6615 2 2026-01-11 13:42:33 +03:00
Халимов Рустам d85cac8a16 1 2026-01-11 13:34:11 +03:00
Халимов Рустам 621958c0d4 Font size for sizes 2026-01-11 00:25:25 +03:00
Халимов Рустам 57a5695c2a Add size 2026-01-11 00:09:49 +03:00
rust 6990f18c78 Merge pull request 'Добавление перегородок в ячейки и их скругления' (#6) from test into main
Reviewed-on: http://192.168.1.114:3000/rust/BoxGenerator/pulls/6
2026-01-10 23:56:09 +03:00
Халимов Рустам 4b4ebb68d1 Radius 2026-01-10 23:42:23 +03:00
Халимов Рустам b422cdef6b 3 2026-01-10 23:22:45 +03:00
Халимов Рустам bd8b3ff985 2 2026-01-10 23:11:50 +03:00
Халимов Рустам 81d9e8e920 Try add wals and split 2026-01-10 22:51:47 +03:00
Халимов Рустам 9249b424fe Try add wals 2026-01-10 22:35:25 +03:00
Халимов Рустам b60d7e6117 9 2026-01-10 22:10:37 +03:00
Халимов Рустам 7757de44a2 8 2026-01-10 21:56:23 +03:00
Халимов Рустам cac9b70ea8 7 2026-01-10 21:49:09 +03:00
Халимов Рустам 18cc8f23db 6 2026-01-10 21:40:13 +03:00
Халимов Рустам 85b5fef5ab 5 2026-01-10 21:09:32 +03:00
Халимов Рустам cde48b0843 4 2026-01-10 20:50:09 +03:00
Халимов Рустам 9a9b35977c 3 2026-01-10 20:44:27 +03:00
Халимов Рустам 5cb362dccc 2 2026-01-10 20:06:56 +03:00
Халимов Рустам 8d3841ae1f 1 2026-01-10 19:54:16 +03:00
Халимов Рустам f3bc06e69f Try fix build 2026-01-10 18:54:11 +03:00
Халимов Рустам 4d033cbd97 Fix build 2026-01-10 18:44:23 +03:00
Халимов Рустам 8d4b26c001 Fixed 2026-01-10 18:35:39 +03:00
Халимов Рустам 568632c7fb Fix 2026-01-10 18:09:58 +03:00
Халимов Рустам 89734eedea Layout step 2026-01-10 17:57:22 +03:00
Халимов Рустам 5e11d7a194 Fix layout 2026-01-10 17:31:22 +03:00
Халимов Рустам cf09961807 Add logs 2026-01-10 17:23:27 +03:00
Халимов Рустам 3f527ab7e4 2 fix 2026-01-10 17:16:36 +03:00
Халимов Рустам a9b07a07d8 Fix 2026-01-10 17:09:53 +03:00
Халимов Рустам f7911e7147 Try fix layout step 2026-01-10 16:57:20 +03:00
Халимов Рустам 4af73b00eb Add split 2026-01-10 16:43:20 +03:00
Халимов Рустам 8789d82064 Fix 2025-12-27 23:53:52 +03:00
Халимов Рустам 929e071ea7 Try repeat 2025-12-27 23:46:13 +03:00
Халимов Рустам ac00068175 Rollback 2025-12-27 23:33:57 +03:00
Халимов Рустам 492585a2be Try fix 2 step 2025-12-27 23:20:04 +03:00
Халимов Рустам 19754baaae Fix 2025-12-27 23:10:24 +03:00
Халимов Рустам 6c6c859a3b Fixed layout step 2025-12-27 23:06:22 +03:00
Халимов Рустам 8999d1f06a Added split in to cell 2025-12-27 22:59:31 +03:00
8 changed files with 1886 additions and 856 deletions
+19
View File
@@ -0,0 +1,19 @@
# Build stage
FROM node:20-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+52
View File
@@ -18,3 +18,55 @@ View your app in AI Studio: https://ai.studio/apps/drive/1gUfO_tgl_CPfAGf1eXuSFy
2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key 2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
3. Run the app: 3. Run the app:
`npm run dev` `npm run dev`
### 💾 Экспорт и Шеринг
- **STL Экспорт**: Генерация готовых к печати STL файлов. Можно скачать отдельные детали или весь проект архивом (ZIP).
- **Сохранение проектов**: Возможность поделиться ссылкой на конфигурацию (все параметры кодируются в URL).
## 🚀 Запуск Локально
Для работы требуется установленный **Node.js**.
1. Клонируйте репозиторий:
```bash
git clone https://github.com/your-username/printfit-box-generator.git
cd printfit-box-generator
```
2. Установите зависимости:
```bash
npm install
```
3. Запустите локальный сервер разработки:
```bash
npm run dev
```
4. Откройте приложение в браузере (обычно http://localhost:5173).
## 🐳 Запуск в Docker
Приложение можно легко развернуть в контейнере Docker (используется Nginx для раздачи статики).
1. Соберите образ:
```bash
docker build -t printfit-app .
```
2. Запустите контейнер:
```bash
docker run -p 8080:80 printfit-app
```
3. Откройте http://localhost:8080
## 🛠 Технологический Стек
- **React**: UI и управление состоянием.
- **Three.js (@react-three/fiber)**: 3D рендеринг и геометрия.
- **Tailwind CSS**: Стилизация интерфейса.
- **Vite**: Сборщик проекта.
- **Lucide React**: Иконки.
## 📝 Лицензия
Этот проект распространяется под лицензией MIT. Вы можете свободно использовать, изменять и распространять его.
+62 -66
View File
@@ -5,130 +5,126 @@ import { ConfigStep } from './components/ConfigStep';
import { LayoutStep } from './components/LayoutStep'; import { LayoutStep } from './components/LayoutStep';
import { PreviewStep } from './components/PreviewStep'; import { PreviewStep } from './components/PreviewStep';
import { parseShareUrl } from './utils/share'; import { parseShareUrl } from './utils/share';
import { ChevronRight, ChevronLeft, Box } from 'lucide-react'; import { ChevronRight, ChevronLeft, Box, AlertTriangle } from 'lucide-react';
// ВАЖНО: ErrorBoundary должен быть ЗДЕСЬ, снаружи компонента App
class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { hasError: boolean }> {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() {
if (this.state.hasError) return (
<div className="h-full flex flex-col items-center justify-center text-red-400">
<AlertTriangle size={32} className="mb-2" />
<p>Ошибка отрисовки интерфейса.</p>
<button onClick={() => window.location.reload()} className="mt-4 px-4 py-2 bg-slate-800 rounded hover:bg-slate-700 transition-colors">
Перезагрузить
</button>
</div>
);
return this.props.children;
}
}
const App = () => { const App = () => {
const [step, setStep] = useState(1); const [step, setStep] = useState(1);
const [isLoadedFromUrl, setIsLoadedFromUrl] = useState(false);
// State
const [config, setConfig] = useState<AppConfig>({ const [config, setConfig] = useState<AppConfig>({
drawer: { width: 300, depth: 400, height: 80 }, drawer: { width: 100, depth: 100, height: 100 },
wallThickness: 1.2, wallThickness: 0.8,
printerTolerance: 0.5, printerTolerance: 0.5,
cornerRadius: 4, // <--- Дефолтное скругление (4мм) cornerRadius: 4,
perforation: {
enabled: true,
shape: 'honeycomb',
size: 8,
gap: 2
}
}); });
const [splits, setSplits] = useState<LayoutSplits>({ const [splits, setSplits] = useState<LayoutSplits>({
x: [], x: [],
y: [] y: [],
partitions: {}
}); });
// --- ЛОГИКА ВОССТАНОВЛЕНИЯ ИЗ ССЫЛКИ ---
useEffect(() => { useEffect(() => {
try {
const sharedData = parseShareUrl(); const sharedData = parseShareUrl();
if (sharedData) { if (sharedData) {
setConfig(sharedData.config); setConfig(sharedData.config);
setSplits(sharedData.splits); setSplits({
x: Array.isArray(sharedData.splits.x) ? sharedData.splits.x : [],
y: Array.isArray(sharedData.splits.y) ? sharedData.splits.y : [],
partitions: sharedData.splits.partitions || {}
});
setStep(3); setStep(3);
setIsLoadedFromUrl(true);
window.history.replaceState({}, '', window.location.pathname); window.history.replaceState({}, '', window.location.pathname);
} }
} catch (e) {
console.error("URL load error", e);
}
}, []); }, []);
// Derived State: Parts
const parts: GeneratedPart[] = useMemo(() => { const parts: GeneratedPart[] = useMemo(() => {
try {
return calculateParts(config, splits); return calculateParts(config, splits);
} catch (e) {
return [];
}
}, [config, splits]); }, [config, splits]);
return ( return (
<div className="min-h-screen flex flex-col font-sans text-gray-100 bg-slate-950"> <div className="h-screen flex flex-col font-sans text-gray-100 bg-slate-950 overflow-hidden">
{/* Header */} {/* Header */}
<header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md sticky top-0 z-50"> <header className="bg-slate-900 border-b border-slate-800 p-4 shadow-md shrink-0 z-50">
<div className="max-w-7xl mx-auto flex items-center justify-between"> <div className="max-w-7xl mx-auto flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="bg-primary p-2 rounded-lg"> <div className="bg-primary p-2 rounded-lg"><Box className="text-white" size={20} /></div>
<Box className="text-white" size={20} /> <div><h1 className="text-xl font-bold tracking-tight">PrintFit</h1><p className="text-xs text-gray-400">Генератор органайзеров</p></div>
</div> </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"> <div className="flex items-center gap-4 text-sm font-medium">
{[1, 2, 3].map((num) => ( {[1, 2, 3].map((num) => (
<React.Fragment key={num}> <div key={num} className={`flex items-center gap-2 ${step === num ? 'text-primary' : 'text-gray-500'}`}>
<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={`w-6 h-6 rounded-full flex items-center justify-center text-xs border ${step === num ? 'border-primary bg-primary/10' : 'border-gray-600'}`}> <span className="hidden md:inline">{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}</span>
{num}
</span>
<span className="hidden md:inline">
{num === 1 ? 'Настройки' : num === 2 ? 'Макет' : 'Экспорт'}
</span>
</div> </div>
{num < 3 && <div className="w-8 h-[1px] bg-slate-700" />}
</React.Fragment>
))} ))}
</div> </div>
</div> </div>
</header> </header>
{/* Main Content */} {/* Main Content */}
<main className="flex-1 max-w-7xl mx-auto w-full p-4 md:p-8"> <main className="flex-1 w-full max-w-7xl mx-auto p-4 overflow-hidden flex flex-col min-h-0">
{step === 1 && ( {step === 1 && (
<div className="max-w-4xl mx-auto animate-fade-in"> <div className="h-full overflow-y-auto animate-fade-in custom-scrollbar">
<ConfigStep config={config} onChange={setConfig} /> <ConfigStep config={config} onChange={setConfig} />
</div> </div>
)} )}
{step === 2 && ( {step === 2 && (
<div className="h-[calc(100vh-200px)] min-h-[500px] animate-fade-in"> <div className="h-full flex flex-col animate-fade-in min-h-0">
<ErrorBoundary>
<LayoutStep config={config} splits={splits} onChange={setSplits} /> <LayoutStep config={config} splits={splits} onChange={setSplits} />
</ErrorBoundary>
</div> </div>
)} )}
{step === 3 && ( {step === 3 && (
<div className="h-[calc(100vh-200px)] min-h-[600px] animate-fade-in"> <div className="h-full flex flex-col animate-fade-in min-h-0">
<PreviewStep parts={parts} config={config} splits={splits} /> <PreviewStep parts={parts} config={config} splits={splits} />
</div> </div>
)} )}
</main> </main>
{/* Footer Navigation */} {/* Footer */}
<footer className="bg-slate-900 border-t border-slate-800 p-4 sticky bottom-0 z-50"> <footer className="bg-slate-900 border-t border-slate-800 p-4 shrink-0 z-50">
<div className="max-w-7xl mx-auto flex justify-between items-center"> <div className="max-w-7xl mx-auto flex justify-between items-center">
<button <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>
disabled={step === 1} <div className="text-sm text-gray-500">{step === 2 && <span className="text-accent font-mono">Ячеек: {parts.length}</span>}</div>
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 ? ( {step < 3 ? (
<button <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>
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 <button onClick={() => { setStep(1); setSplits({ x: [], y: [], partitions: {} }); window.history.replaceState({}, '', window.location.pathname); }} 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>
onClick={() => {
setStep(1);
setSplits({x: [], y: []});
window.history.replaceState({}, '', window.location.pathname);
}}
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> </div>
</footer> </footer>
+176 -9
View File
@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { AppConfig } from '../types'; import { AppConfig, PerforationShape } from '../types';
import { Ruler, Box, Layers, Minimize2, CircleDashed } from 'lucide-react'; import { Ruler, Box, Layers, Minimize2, CircleDashed, Grid, Circle, Hexagon, Triangle } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; config: AppConfig;
@@ -39,13 +39,92 @@ const NumberInput = ({
</div> </div>
); );
const PerforationPreview = ({ config }: { config: AppConfig['perforation'] }) => {
if (!config.enabled) return (
<div className="w-full h-48 bg-slate-950 rounded-lg border border-slate-800 flex items-center justify-center text-gray-600">
<span className="text-sm">Перфорация отключена</span>
</div>
);
// Simple canvas-like SVG generation
const width = 200;
const height = 120;
const size = config.size * 2; // Scale up mostly for visibility
const gap = config.gap * 2;
const step = size + gap;
const elements = [];
if (config.shape === 'circle') {
for (let y = 0; y < height; y += step) {
for (let x = 0; x < width; x += step) {
elements.push(<circle key={`${x}-${y}`} cx={x + step / 2} cy={y + step / 2} r={size / 2} fill="#3b82f6" />);
}
}
} else if (config.shape === 'honeycomb') {
const hStep = size * 0.866; // height of equilateral triangle
for (let y = 0; y < height; y += (size + gap) * 0.85) {
const row = Math.floor(y / ((size + gap) * 0.85));
const xOffset = row % 2 === 0 ? 0 : (size + gap) / 2;
for (let x = xOffset - step; x < width; x += step) {
// Hexagon points
const r = size / 2;
const cx = x + step / 2;
const cy = y + step / 2;
// Points for flat-topped hexagon
const points = [];
for (let i = 0; i < 6; i++) {
const angle_deg = 60 * i + 30;
const angle_rad = Math.PI / 180 * angle_deg;
points.push(`${cx + r * Math.cos(angle_rad)},${cy + r * Math.sin(angle_rad)}`);
}
elements.push(<polygon key={`${x}-${y}`} points={points.join(" ")} fill="#3b82f6" />);
}
}
} else if (config.shape === 'triangle') {
for (let y = 0; y < height; y += step * 0.866) { // Staggered rows
const row = Math.floor(y / (step * 0.866));
const xOffset = row % 2 === 0 ? 0 : step / 2;
for (let x = -step + xOffset; x < width; x += step) {
const cx = x + step / 2;
const cy = y + step / 2;
const r = size / 2;
// Upright triangle
const points = [
`${cx},${cy - r}`,
`${cx + r * 0.866},${cy + r * 0.5}`,
`${cx - r * 0.866},${cy + r * 0.5}`
];
elements.push(<polygon key={`${x}-${y}`} points={points.join(" ")} fill="#3b82f6" />);
}
}
}
return (
<div className="w-full h-48 bg-slate-950 rounded-lg border border-slate-800 overflow-hidden relative">
<svg width="100%" height="100%" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="xMidYMid slice">
{elements}
</svg>
<div className="absolute top-2 right-2 text-xs text-gray-500">:: Масштаб условен</div>
</div>
);
}
export const ConfigStep: React.FC<Props> = ({ config, onChange }) => { export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
const updateDrawer = (key: keyof AppConfig['drawer'], val: number) => { const updateDrawer = (key: keyof AppConfig['drawer'], val: number) => {
onChange({ ...config, drawer: { ...config.drawer, [key]: val } }); onChange({ ...config, drawer: { ...config.drawer, [key]: val } });
}; };
const updatePerforation = (key: keyof AppConfig['perforation'], val: any) => {
onChange({ ...config, perforation: { ...config.perforation, [key]: val } })
}
return ( return (
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in"> <div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 animate-fade-in space-y-8">
{/* SECTION 1: Dimensions & Settings */}
<div>
<h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary"> <h2 className="text-xl font-bold mb-6 flex items-center gap-2 text-primary">
<Box size={24} /> 1. Размеры <Box size={24} /> 1. Размеры
</h2> </h2>
@@ -89,18 +168,18 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
max="3.2" max="3.2"
step="0.1" step="0.1"
value={config.wallThickness} value={config.wallThickness}
onChange={(e) => onChange({...config, wallThickness: parseFloat(e.target.value)})} 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" 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> <span className="text-xs text-gray-500 font-mono">3.2</span>
</div> </div>
</div> </div>
{/* Corner Radius (NEW) */} {/* Corner Radius */}
<div className="mb-6"> <div className="mb-6">
<div className="flex justify-between items-center mb-2"> <div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300 flex items-center gap-1"> <label className="text-sm font-medium text-gray-300 flex items-center gap-1">
<CircleDashed size={14} className="text-gray-400"/> Радиус скругления <CircleDashed size={14} className="text-gray-400" /> Радиус скругления
</label> </label>
<span className="text-purple-400 font-bold bg-purple-400/10 px-2 py-1 rounded text-sm border border-purple-400/20"> <span className="text-purple-400 font-bold bg-purple-400/10 px-2 py-1 rounded text-sm border border-purple-400/20">
{config.cornerRadius?.toFixed(0) || 0} мм {config.cornerRadius?.toFixed(0) || 0} мм
@@ -114,7 +193,7 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
max="20" max="20"
step="1" step="1"
value={config.cornerRadius || 0} value={config.cornerRadius || 0}
onChange={(e) => onChange({...config, cornerRadius: parseFloat(e.target.value)})} onChange={(e) => onChange({ ...config, cornerRadius: parseFloat(e.target.value) })}
className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-purple-500 hover:accent-purple-400 transition-all" className="w-full h-2 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-purple-500 hover:accent-purple-400 transition-all"
/> />
<span className="text-xs text-gray-500 font-mono">20</span> <span className="text-xs text-gray-500 font-mono">20</span>
@@ -125,7 +204,7 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
<div className="mb-4"> <div className="mb-4">
<div className="flex justify-between items-center mb-2"> <div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300 flex items-center gap-1"> <label className="text-sm font-medium text-gray-300 flex items-center gap-1">
<Minimize2 size={14} className="text-gray-400"/> Зазор (Tolerance) <Minimize2 size={14} className="text-gray-400" /> Зазор (Tolerance)
</label> </label>
<span className="text-accent font-bold bg-accent/10 px-2 py-1 rounded text-sm border border-accent/20"> <span className="text-accent font-bold bg-accent/10 px-2 py-1 rounded text-sm border border-accent/20">
{config.printerTolerance.toFixed(1)} мм {config.printerTolerance.toFixed(1)} мм
@@ -139,7 +218,7 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
max="2.0" max="2.0"
step="0.1" step="0.1"
value={config.printerTolerance} value={config.printerTolerance}
onChange={(e) => onChange({...config, printerTolerance: parseFloat(e.target.value)})} 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" 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> <span className="text-xs text-gray-500 font-mono">2.0</span>
@@ -149,5 +228,93 @@ export const ConfigStep: React.FC<Props> = ({ config, onChange }) => {
</div> </div>
</div> </div>
</div> </div>
{/* SECTION 2: Perforation */}
<div className="bg-slate-800/30 p-6 rounded-lg border border-slate-700/50">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-semibold flex items-center gap-2 text-blue-400">
<Grid size={20} /> 2. Перфорация (узоры)
</h3>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-gray-400 uppercase tracking-wider">Включено</span>
<button
onClick={() => updatePerforation('enabled', !config.perforation.enabled)}
className={`w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 ${config.perforation.enabled ? 'bg-blue-600' : 'bg-slate-600'}`}
>
<span className={`block w-4 h-4 rounded-full bg-white shadow transform transition-transform duration-200 ease-in-out absolute top-1 ${config.perforation.enabled ? 'translate-x-7' : 'translate-x-1'}`} />
</button>
</div>
</div>
<div className={`grid grid-cols-1 md:grid-cols-2 gap-8 transition-all duration-300 ${config.perforation.enabled ? 'opacity-100 pointer-events-auto' : 'opacity-40 pointer-events-none filter blur-[1px]'}`}>
<div>
<label className="text-xs font-bold text-gray-500 uppercase mb-3 block">Тип узора</label>
<div className="flex gap-4 mb-8">
{[
{ id: 'circle', icon: Circle, label: 'Круг' },
{ id: 'honeycomb', icon: Hexagon, label: 'Соты' },
{ id: 'triangle', icon: Triangle, label: 'Треуг.' }
].map((item) => (
<button
key={item.id}
onClick={() => updatePerforation('shape', item.id as PerforationShape)}
className={`flex-1 flex flex-col items-center justify-center gap-2 py-4 px-2 rounded-lg border transition-all ${config.perforation.shape === item.id
? 'bg-slate-700/80 border-blue-500 text-blue-400 shadow-lg shadow-blue-500/10'
: 'bg-slate-800 border-slate-700 text-gray-400 hover:bg-slate-750 hover:border-slate-600'
}`}
>
<item.icon size={24} />
<span className="text-sm font-medium">{item.label}</span>
</button>
))}
</div>
{/* Resize Controls */}
<div className="space-y-6">
<div>
<div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300">Диаметр отверстий</label>
<span className="text-sm font-bold text-blue-400">{config.perforation.size} мм</span>
</div>
<div className="flex items-center gap-4">
<span className="text-xs text-gray-500">2 мм</span>
<input
type="range" min="2" max="25" step="1"
value={config.perforation.size}
onChange={(e) => updatePerforation('size', parseFloat(e.target.value))}
className="flex-1 h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
/>
<span className="text-xs text-gray-500">25 мм</span>
</div>
</div>
<div>
<div className="flex justify-between items-center mb-2">
<label className="text-sm font-medium text-gray-300">Зазор (между отверстиями)</label>
<span className="text-sm font-bold text-blue-400">{config.perforation.gap} мм</span>
</div>
<div className="flex items-center gap-4">
<span className="text-xs text-gray-500">1 мм</span>
<input
type="range" min="1" max="10" step="0.5"
value={config.perforation.gap}
onChange={(e) => updatePerforation('gap', parseFloat(e.target.value))}
className="flex-1 h-1.5 bg-slate-700 rounded-lg appearance-none cursor-pointer accent-blue-500"
/>
<span className="text-xs text-gray-500">10 мм</span>
</div>
</div>
</div>
</div>
{/* Preview */}
<div>
<label className="text-xs font-bold text-gray-500 uppercase mb-3 block">Предпросмотр</label>
<PerforationPreview config={config.perforation} />
</div>
</div>
</div>
</div>
); );
}; };
+413 -263
View File
@@ -1,6 +1,6 @@
import React, { useRef, useState, useMemo } from 'react'; import React, { useRef, useState, useMemo } from 'react';
import { AppConfig, LayoutSplits } from '../types'; import { AppConfig, LayoutSplits, Partition } from '../types';
import { Grid, MousePointer2, Trash2, RotateCcw } from 'lucide-react'; import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react';
interface Props { interface Props {
config: AppConfig; config: AppConfig;
@@ -8,336 +8,486 @@ interface Props {
onChange: (splits: LayoutSplits) => void; onChange: (splits: LayoutSplits) => void;
} }
type EditMode = 'lines' | 'cells';
type Axis = 'x' | 'y'; type Axis = 'x' | 'y';
type DragTarget =
| { type: 'main'; axis: Axis; index: number }
| { type: 'partition'; cellKey: string; id: string; axis: Axis };
export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => { export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
const svgRef = useRef<SVGSVGElement>(null); const svgRef = useRef<SVGSVGElement>(null);
// State // -- STATE --
const [phantomAxis, setPhantomAxis] = useState<Axis | null>(null); const [mode, setMode] = useState<EditMode>('lines');
const [mousePos, setMousePos] = useState({ x: 0, y: 0 }); const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
const [hoveredSplit, setHoveredSplit] = useState<{ axis: Axis; index: number } | null>(null); const [dragging, setDragging] = useState<DragTarget | null>(null);
const [dragging, setDragging] = useState<{ axis: Axis; index: number } | null>(null); const [isButtonHovered, setIsButtonHovered] = useState(false);
const [phantomMainAxis, setPhantomMainAxis] = useState<Axis | null>(null);
const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null);
const [hoveredCell, setHoveredCell] = useState<{ i: number; j: number } | null>(null);
const [hoveredPartition, setHoveredPartition] = useState<{ id: string; cellKey: string } | null>(null);
const [phantomPartition, setPhantomPartition] = useState<{ axis: Axis; offset: number; min: number; max: number } | null>(null);
const [selectedPartitionId, setSelectedPartitionId] = useState<string | null>(null);
// -- DATA --
const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safePartitions = splits?.partitions || {};
const drawerW = Math.max(1, config.drawer.width || 300);
const drawerD = Math.max(1, config.drawer.depth || 400);
const wallThick = config.wallThickness || 1.2;
const aspectRatio = drawerD / drawerW;
const viewBoxW = 1000; const viewBoxW = 1000;
const aspectRatio = config.drawer.depth / config.drawer.width;
const viewBoxH = viewBoxW * aspectRatio; const viewBoxH = viewBoxW * aspectRatio;
const sortedX = useMemo(() => [0, ...splits.x, 1].sort((a, b) => a - b), [splits.x]); const sortedX = useMemo(() => [0, ...safeX, 1].sort((a, b) => a - b), [safeX]);
const sortedY = useMemo(() => [0, ...splits.y, 1].sort((a, b) => a - b), [splits.y]); const sortedY = useMemo(() => [0, ...safeY, 1].sort((a, b) => a - b), [safeY]);
// --- Глобальный обработчик (для пустого места и перетаскивания) --- // -- HELPER: Get Selected --
const handleGlobalMouseMove = (e: React.MouseEvent) => { const getSelectedPartition = () => {
if (!selectedPartitionId) return null;
for (const key in safePartitions) {
const part = safePartitions[key].find(p => p.id === selectedPartitionId);
if (part) return { key, part };
}
return null;
};
const selectedData = getSelectedPartition();
// --- RAYCASTING (Поиск коробки для НОВОЙ стенки) ---
// Мы ищем ближайшие препятствия, чтобы определить границы новой стенки
const getCursorBox = (lx: number, ly: number, parts: Partition[]) => {
let minX = 0, maxX = 1;
let minY = 0, maxY = 1;
parts.forEach(p => {
// Используем сохраненные границы (честные)
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
const EPS = 0.005; // Допуск
if (p.axis === 'x') {
// Вертикальная стенка. Перекрывает ли она наш Y?
if (ly >= pMin - EPS && ly <= pMax + EPS) {
// Стенка на нашем уровне. Слева или справа?
if (p.offset < lx) minX = Math.max(minX, p.offset);
if (p.offset > lx) maxX = Math.min(maxX, p.offset);
}
} else {
// Горизонтальная стенка. Перекрывает ли она наш X?
if (lx >= pMin - EPS && lx <= pMax + EPS) {
// Стенка на нашем уровне. Сверху или снизу?
if (p.offset < ly) minY = Math.max(minY, p.offset);
if (p.offset > ly) maxY = Math.min(maxY, p.offset);
}
}
});
return { minX, maxX, minY, maxY };
};
// Поиск соседей для размеров (Используем сохраненные данные)
const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[]) => {
let min = 0;
let max = 1;
const EPS = 0.005;
parts.forEach(p => {
if (p.axis === axis) {
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (crossPos >= pMin - EPS && crossPos <= pMax + EPS) {
if (p.offset < offset) min = Math.max(min, p.offset);
if (p.offset > offset) max = Math.min(max, p.offset);
}
}
});
return { min, max };
};
// -- ACTIONS --
const createPartition = (i: number, j: number, axis: Axis, offset: number, min: number, max: number) => {
const key = `${i}-${j}`;
const current = safePartitions[key] || [];
const newPart: Partition = {
id: Math.random().toString(36).substr(2, 9),
axis, offset, min, max,
height: config.drawer.height || 80, rounded: false
};
onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } });
setSelectedPartitionId(newPart.id);
};
const updatePartition = (key: string, id: string, updates: Partial<Partition>) => {
const current = safePartitions[key] || [];
const updated = current.map(p => p.id === id ? { ...p, ...updates } : p);
onChange({ ...splits, partitions: { ...safePartitions, [key]: updated } });
};
const removePartition = (key: string, id: string) => {
const current = safePartitions[key] || [];
onChange({ ...splits, partitions: { ...safePartitions, [key]: current.filter(p => p.id !== id) } });
if (selectedPartitionId === id) setSelectedPartitionId(null);
setHoveredPartition(null);
};
const removeMainSplit = (axis: Axis, index: number) => {
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index);
onChange(newSplits);
setHoveredMainSplit(null);
setDragging(null);
};
// -- MOUSE HANDLERS --
const handleMouseMove = (e: React.MouseEvent) => {
if (!svgRef.current) return; if (!svgRef.current) return;
const rect = svgRef.current.getBoundingClientRect(); const rect = svgRef.current.getBoundingClientRect();
if (rect.width === 0) return;
const nx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); 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)); const ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
setMousePos({ x: nx, y: ny }); setMousePos({ x: nx, y: ny });
// 1. Если тащим - обновляем позицию
if (dragging) { if (dragging) {
const newSplits = { if (dragging.type === 'main') {
x: [...splits.x], const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
y: [...splits.y]
};
const val = dragging.axis === 'x' ? nx : ny; const val = dragging.axis === 'x' ? nx : ny;
newSplits[dragging.axis][dragging.index] = val; newSplits[dragging.axis][dragging.index] = val;
onChange(newSplits); onChange(newSplits);
} else {
const [iStr, jStr] = dragging.cellKey.split('-');
const i = parseInt(iStr); const j = parseInt(jStr);
const cellX1 = sortedX[i]; const cellX2 = sortedX[i+1];
const cellY1 = sortedY[j]; const cellY2 = sortedY[j+1];
let newOffset = 0;
if (dragging.axis === 'x') newOffset = (nx - cellX1) / (cellX2 - cellX1);
else newOffset = (ny - cellY1) / (cellY2 - cellY1);
newOffset = Math.max(0.02, Math.min(0.98, newOffset));
if (!isNaN(newOffset)) updatePartition(dragging.cellKey, dragging.id, { offset: newOffset });
}
return; return;
} }
// 2. Если мы здесь, значит мышка НЕ на существующей линии if (isButtonHovered) return;
// (иначе событие было бы перехвачено в handleSplitHover)
setHoveredSplit(null);
// 3. Логика Фантомной линии (создание новой) if (mode === 'lines') {
const SNAP_THRESHOLD = 0.02; setHoveredMainSplit(null);
const SNAP = 0.015;
// Проверяем, не слишком ли мы близко к краям или другим линиям (чтобы не спамить) if (nx > SNAP && nx < 1 - SNAP && ny > SNAP && ny < 1 - SNAP) {
const closeToX = splits.x.some(val => Math.abs(nx - val) < SNAP_THRESHOLD); const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP);
const closeToY = splits.y.some(val => Math.abs(ny - val) < SNAP_THRESHOLD); const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP);
const closeToEdgeX = nx < SNAP_THRESHOLD || nx > (1 - SNAP_THRESHOLD); if (!closeToX && !closeToY) setPhantomMainAxis(Math.min(nx, 1-nx) < Math.min(ny, 1-ny) ? 'y' : 'x');
const closeToEdgeY = ny < SNAP_THRESHOLD || ny > (1 - SNAP_THRESHOLD); else setPhantomMainAxis(null);
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);
// Определяем ось по близости к краю
let potentialAxis: Axis = minXDist < minYDist ? 'y' : 'x';
let valid = true;
if (potentialAxis === 'x') {
if (closeToX || closeToEdgeX) valid = false;
} else {
if (closeToY || closeToEdgeY) valid = false;
} }
} else {
setHoveredPartition(null);
setPhantomPartition(null);
setHoveredCell(null);
// Find Cell
let cellIdx = null;
for (let i = 0; i < sortedX.length - 1; i++) {
if (nx >= sortedX[i] && nx <= sortedX[i+1]) {
for (let j = 0; j < sortedY.length - 1; j++) {
if (ny >= sortedY[j] && ny <= sortedY[j+1]) {
cellIdx = { i, j }; break;
}
}
}
}
if (cellIdx) {
setHoveredCell(cellIdx);
const key = `${cellIdx.i}-${cellIdx.j}`;
const parts = safePartitions[key] || [];
const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1];
const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1];
const cw = cx2 - cx1; const ch = cy2 - cy1;
const lx = (nx - cx1) / cw;
const ly = (ny - cy1) / ch;
// Use real mm for aspect ratio logic
const realCellW = cw * drawerW;
const realCellH = ch * drawerD;
let found = null;
const SNAP = 0.05;
for (const p of parts) {
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (p.axis === 'x') {
if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
} else {
if (lx >= pMin && lx <= pMax && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p;
}
}
if (found) {
setHoveredPartition({ id: found.id, cellKey: key });
} else {
// --- FIND BOX USING RAYCASTING ---
const box = getCursorBox(lx, ly, parts);
const boxW = (box.maxX - box.minX) * realCellW;
const boxH = (box.maxY - box.minY) * realCellH;
// Default axis based on longest side
let newAxis: Axis = boxW > boxH ? 'x' : 'y';
// Override if near edges
const relL = (lx - box.minX) / (box.maxX - box.minX);
const relT = (ly - box.minY) / (box.maxY - box.minY);
const THRESHOLD = 0.2; // 20% zone near edges
if (relL < THRESHOLD || relL > 1 - THRESHOLD) newAxis = 'x';
else if (relT < THRESHOLD || relT > 1 - THRESHOLD) newAxis = 'y';
// Validate space
const valid = (newAxis === 'x' && (box.maxX - box.minX) > 0.05) || (newAxis === 'y' && (box.maxY - box.minY) > 0.05);
if (valid) { if (valid) {
setPhantomAxis(potentialAxis); const offset = newAxis === 'x' ? lx : ly;
} else { const min = newAxis === 'x' ? box.minY : box.minX;
setPhantomAxis(null); const max = newAxis === 'x' ? box.maxY : box.maxX;
setPhantomPartition({ axis: newAxis, offset, min, max });
}
}
}
} }
};
// --- Обработчик наведения на КОНКРЕТНУЮ линию ---
const handleSplitHover = (e: React.MouseEvent, axis: Axis, index: number) => {
// Если мы тащим линию, позволяем событию всплыть до глобального обработчика,
// чтобы он посчитал координаты.
if (dragging) return;
// Если просто водим мышкой - блокируем всплытие,
// чтобы глобальный обработчик не думал, что мы в пустоте.
e.stopPropagation();
setHoveredSplit({ axis, index });
setPhantomAxis(null); // Убираем фантом, раз мы на линии
}; };
const handleMouseDown = (e: React.MouseEvent) => { const handleMouseDown = (e: React.MouseEvent) => {
// Клик по существующей линии (hoveredSplit уже установлен через onMouseMove линии) if (isButtonHovered) return;
if (hoveredSplit) { if (mode === 'lines') {
if (hoveredMainSplit) {
if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit });
else if (e.button === 2) removeMainSplit(hoveredMainSplit.axis, hoveredMainSplit.index);
} else if (phantomMainAxis) {
const val = phantomMainAxis === 'x' ? mousePos.x : mousePos.y;
const newSplits = { ...splits, x: [...safeX], y: [...safeY] };
newSplits[phantomMainAxis] = [...newSplits[phantomMainAxis], val];
onChange(newSplits);
setDragging({ type: 'main', axis: phantomMainAxis, index: newSplits[phantomMainAxis].length - 1 });
}
} else {
if (hoveredPartition) {
const key = hoveredPartition.cellKey;
const parts = safePartitions[key] || [];
const part = parts.find(p => p.id === hoveredPartition.id);
if (part) {
if (e.button === 0) { if (e.button === 0) {
setDragging(hoveredSplit); setDragging({ type: 'partition', cellKey: key, id: part.id, axis: part.axis });
setSelectedPartitionId(part.id);
} else if (e.button === 2) { } else if (e.button === 2) {
removeSplit(hoveredSplit.axis, hoveredSplit.index); removePartition(key, part.id);
} }
} }
// Клик по пустому месту (создание) } else if (hoveredCell && phantomPartition) {
else if (phantomAxis) { if (e.button === 0) {
const val = phantomAxis === 'x' ? mousePos.x : mousePos.y; createPartition(hoveredCell.i, hoveredCell.j, phantomPartition.axis, phantomPartition.offset, phantomPartition.min, phantomPartition.max);
const newSplits = { ...splits }; }
newSplits[phantomAxis] = [...newSplits[phantomAxis], val]; } else {
onChange(newSplits); setSelectedPartitionId(null);
setDragging({ axis: phantomAxis, index: newSplits[phantomAxis].length - 1 }); }
} }
}; };
const handleMouseUp = () => { // --- HANDLER: Clear Phantom on Leave ---
const handleMouseLeave = () => {
setDragging(null); setDragging(null);
setPhantomMainAxis(null);
setHoveredMainSplit(null);
setHoveredCell(null);
setHoveredPartition(null);
setPhantomPartition(null);
}; };
const removeSplit = (axis: Axis, index: number) => { // --- RENDER ---
const newSplits = { ...splits }; const renderCellsAndPartitions = () => {
newSplits[axis] = newSplits[axis].filter((_, i) => i !== index); const elements = [];
onChange(newSplits); for (let i = 0; i < sortedX.length - 1; i++) {
setHoveredSplit(null); for (let j = 0; j < sortedY.length - 1; j++) {
setDragging(null); const x1 = sortedX[i]; const x2 = sortedX[i + 1];
}; const y1 = sortedY[j]; const y2 = sortedY[j + 1];
if (y2 === undefined || x2 === undefined) continue;
return ( const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH;
<div className="bg-slate-900 p-6 rounded-xl shadow-lg border border-slate-800 h-full flex flex-col"> const cellW = (x2 - x1) * viewBoxW; const cellH = (y2 - y1) * viewBoxH;
<div className="flex justify-between items-center mb-4"> const key = `${i}-${j}`;
<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"> const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells';
<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"> const parts = safePartitions[key] || [];
const isAnySelected = parts.some(p => p.id === selectedPartitionId);
const realW = (x2 - x1) * drawerW;
const realD = (y2 - y1) * drawerD;
<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"> if (parts.length === 0) {
<div className="flex items-center gap-2 font-bold text-gray-100 mb-2 text-sm"> const labelX = cellX + cellW / 2;
<MousePointer2 size={14} className="text-primary"/> Инструкция const labelY = cellY + cellH / 2;
</div> const textW = Math.max(0, realW - wallThick).toFixed(0);
<ul className="space-y-1.5 text-[10px] text-gray-400 leading-tight"> const textD = Math.max(0, realD - wallThick).toFixed(0);
<li><b className="text-blue-400">Клик у края:</b> Новая линия</li> if (cellH > 40 && cellW > 60) {
<li><b className="text-orange-400">Перетаскивание:</b> Изменить размер</li> elements.push(
<li><b className="text-red-400">Двойной клик/ПКМ:</b> Удалить</li> <text key={`label-${key}`} x={labelX} y={labelY} textAnchor="middle" dominantBaseline="middle" className="fill-slate-300 font-mono text-[16px] font-bold pointer-events-none select-none opacity-80" style={{ textShadow: '1px 1px 2px rgba(0,0,0,0.8)' }}>
</ul> {textW} × {textD}
</div>
<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>
<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={handleGlobalMouseMove}
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>
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
{/* --- 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;
let fontSize = Math.min(36, cellHeightSVG * 0.6);
fontSize = Math.min(fontSize, cellWidthSVG * 0.25);
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> </text>
); );
}); }
})} }
{/* --- X Lines (Vertical) --- */} elements.push(
{splits.x.map((x, i) => { <g key={key}>
const isHovered = hoveredSplit?.axis === 'x' && hoveredSplit.index === i; {isHovered && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="rgba(16, 185, 129, 0.05)" stroke="#10b981" strokeWidth="2" strokeDasharray="4,4" className="pointer-events-none"/>}
const isDragging = dragging?.axis === 'x' && dragging.index === i; {isAnySelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>}
const color = isHovered || isDragging ? '#f59e0b' : '#64748b';
const width = isHovered || isDragging ? 8 : 4; {parts.map(p => {
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (pMax - pMin < 0.001) return null;
let lx1, ly1, lx2, ly2;
let dist1 = 0, dist2 = 0;
let midX, midY;
const isVertical = p.axis === 'x';
if (isVertical) {
const px = cellX + (cellW * p.offset);
lx1 = px; lx2 = px;
ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax);
const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts);
dist1 = Math.abs((p.offset - neighbors.min) * realW) - wallThick;
dist2 = Math.abs((neighbors.max - p.offset) * realW) - wallThick;
midX = px; midY = (ly1 + ly2) / 2;
} else {
const py = cellY + (cellH * p.offset);
ly1 = py; ly2 = py;
lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax);
const neighbors = getNeighborOffsets(p.offset, (pMin + pMax)/2, p.axis, parts);
dist1 = Math.abs((p.offset - neighbors.min) * realD) - wallThick;
dist2 = Math.abs((neighbors.max - p.offset) * realD) - wallThick;
midX = (lx1 + lx2) / 2; midY = py;
}
const isSel = selectedPartitionId === p.id;
const isHov = hoveredPartition?.id === p.id;
const textOffset = 12;
return ( return (
<g <g key={p.id}>
key={`x-${i}`} <g onDoubleClick={(e) => { e.stopPropagation(); removePartition(key, p.id); }}>
onDoubleClick={() => removeSplit('x', i)} <line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke="transparent" strokeWidth="40" />
// ВАЖНО: Событие вешаем на группу <line x1={lx1} y1={ly1} x2={lx2} y2={ly2} stroke={isSel ? "#a855f7" : (isHov ? "#d8b4fe" : "#7e22ce")} strokeWidth={isSel ? 6 : 4} strokeLinecap="round" />
onMouseMove={(e) => handleSplitHover(e, 'x', i)}
>
{/* Невидимая широкая зона захвата (80 единиц!) */}
<line
x1={x * viewBoxW} y1={0}
x2={x * viewBoxW} y2={viewBoxH}
stroke="transparent" strokeWidth="80"
className="cursor-col-resize"
/>
{/* Видимая линия */}
<line
x1={x * viewBoxW} y1={0}
x2={x * viewBoxW} y2={viewBoxH}
stroke={color} strokeWidth={width}
className="transition-all duration-150 pointer-events-none"
/>
{(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>
<g className="pointer-events-none select-none font-mono text-[14px] font-bold fill-white" style={{ textShadow: '0px 0px 3px #000' }}>
{isVertical ? (
<>
<text x={midX - textOffset} y={midY} textAnchor="end" dominantBaseline="middle">{Math.max(0, dist1).toFixed(0)}</text>
<text x={midX + textOffset} y={midY} textAnchor="start" dominantBaseline="middle">{Math.max(0, dist2).toFixed(0)}</text>
</>
) : (
<>
<text x={midX} y={midY - textOffset} textAnchor="middle" dominantBaseline="auto">{Math.max(0, dist1).toFixed(0)}</text>
<text x={midX} y={midY + textOffset * 2} textAnchor="middle" dominantBaseline="auto">{Math.max(0, dist2).toFixed(0)}</text>
</>
)} )}
</g> </g>
</g>
); );
})} })}
{/* --- Y Lines (Horizontal) --- */} {isHovered && phantomPartition && !hoveredPartition && !dragging && (
{splits.y.map((y, i) => { <g className="pointer-events-none opacity-60">
const isHovered = hoveredSplit?.axis === 'y' && hoveredSplit.index === i; {(() => {
const isDragging = dragging?.axis === 'y' && dragging.index === i; const { min, max } = phantomPartition;
const color = isHovered || isDragging ? '#f59e0b' : '#64748b'; let fx1, fy1, fx2, fy2;
const width = isHovered || isDragging ? 8 : 4; if (phantomPartition.axis === 'x') {
const px = cellX + (cellW * phantomPartition.offset);
return ( fx1 = px; fx2 = px; fy1 = cellY + (cellH * min); fy2 = cellY + (cellH * max);
<g } else {
key={`y-${i}`} const py = cellY + (cellH * phantomPartition.offset);
onDoubleClick={() => removeSplit('y', i)} fy1 = py; fy2 = py; fx1 = cellX + (cellW * min); fx2 = cellX + (cellW * max);
onMouseMove={(e) => handleSplitHover(e, 'y', i)} }
> return <line x1={fx1} y1={fy1} x2={fx2} y2={fy2} stroke="#34d399" strokeWidth="3" strokeDasharray="6,6"/>;
<line })()}
x1={0} y1={y * viewBoxH}
x2={viewBoxW} y2={y * viewBoxH}
stroke="transparent" strokeWidth="80"
className="cursor-row-resize"
/>
<line
x1={0} y1={y * viewBoxH}
x2={viewBoxW} y2={y * viewBoxH}
stroke={color} strokeWidth={width}
className="transition-all duration-150 pointer-events-none"
/>
{(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>
)} )}
</g> </g>
); );
})} }
}
return elements;
};
{/* --- Phantom Lines --- */} return (
{!hoveredSplit && !dragging && phantomAxis === 'x' && ( <div className="flex w-full h-full bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl">
<g className="pointer-events-none"> <div className="flex-1 flex flex-col relative min-w-0">
<line <div className="flex justify-between items-center p-3 border-b border-slate-800 bg-slate-900 z-10 shrink-0">
x1={mousePos.x * viewBoxW} y1="0" <h2 className="text-sm font-bold flex items-center gap-2 text-primary"><Grid size={18} /> Редактор</h2>
x2={mousePos.x * viewBoxW} y2="100%" <div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8" <button onClick={() => { setMode('lines'); setSelectedPartitionId(null); }} className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'lines' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}><Move size={14}/> Границы</button>
className="opacity-60" <button onClick={() => setMode('cells')} className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${mode === 'cells' ? 'bg-primary text-white shadow' : 'text-gray-400 hover:text-gray-200'}`}><Grid size={14}/> Внутри ячеек</button>
/> </div>
<g transform={`translate(${mousePos.x * viewBoxW}, ${viewBoxH/2})`}> <button onClick={() => onChange({ x: [], y: [], partitions: {} })} className="px-3 py-1.5 text-xs text-red-400 border border-slate-700 rounded hover:bg-slate-800 transition-colors flex items-center gap-1"><RotateCcw size={14} /> Сброс</button>
<circle r="3" fill="#3b82f6" /> </div>
</g>
</g> <div className="flex-1 bg-slate-800/30 flex items-center justify-center p-4 overflow-hidden relative">
)} <div className="relative shadow-2xl bg-[#1e293b] border border-slate-600 rounded-sm overflow-hidden" style={{ width: aspectRatio > 1 ? 'auto' : '100%', height: aspectRatio > 1 ? '100%' : 'auto', aspectRatio: `${1/aspectRatio}`, maxHeight: '100%', maxWidth: '100%', cursor: mode === 'lines' ? (dragging ? 'grabbing' : hoveredMainSplit ? 'col-resize' : 'crosshair') : (dragging ? 'grabbing' : hoveredPartition ? 'grab' : hoveredCell ? 'crosshair' : 'default') }}>
{!hoveredSplit && !dragging && phantomAxis === 'y' && ( <svg ref={svgRef} viewBox={`0 0 ${viewBoxW} ${viewBoxH}`} className="w-full h-full touch-none block"
<g className="pointer-events-none"> onMouseMove={handleMouseMove}
<line onMouseDown={handleMouseDown}
x1="0" y1={mousePos.y * viewBoxH} onMouseUp={() => setDragging(null)}
x2="100%" y2={mousePos.y * viewBoxH} onMouseLeave={handleMouseLeave} // ДОБАВЛЕНО СЮДА
stroke="#3b82f6" strokeWidth="4" strokeDasharray="12,8" onContextMenu={(e) => e.preventDefault()}
className="opacity-60" >
/> <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></defs>
<g transform={`translate(${viewBoxW/2}, ${mousePos.y * viewBoxH})`}> <rect width="100%" height="100%" fill="url(#grid)" />
<circle r="3" fill="#3b82f6" /> {renderCellsAndPartitions()}
{safeX.map((x, i) => (
<g key={`x-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}>
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-col-resize" : ""} />
<line x1={x * viewBoxW} y1="0" x2={x * viewBoxW} y2="100%" stroke={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'x' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
</g> </g>
))}
{safeY.map((y, i) => (
<g key={`y-${i}`} onMouseMove={(e) => { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}>
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke="transparent" strokeWidth="40" className={mode === 'lines' ? "cursor-row-resize" : ""} />
<line x1="0" y1={y * viewBoxH} x2="100%" y2={y * viewBoxH} stroke={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? "#f59e0b" : "#64748b"} strokeWidth={hoveredMainSplit?.axis === 'y' && hoveredMainSplit.index === i ? 6 : 4} className="pointer-events-none" />
</g> </g>
))}
{mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis && (
<line x1={phantomMainAxis === 'x' ? mousePos.x * viewBoxW : 0} y1={phantomMainAxis === 'y' ? mousePos.y * viewBoxH : 0} x2={phantomMainAxis === 'x' ? mousePos.x * viewBoxW : '100%'} y2={phantomMainAxis === 'y' ? mousePos.y * viewBoxH : '100%'} stroke="#3b82f6" strokeWidth="4" strokeDasharray="8,8" className="pointer-events-none opacity-50"/>
)} )}
</svg> </svg>
</div> </div>
</div> </div>
</div> </div>
{mode === 'cells' && selectedData ? (
<div className="w-72 bg-slate-900 border-l border-slate-800 p-4 flex flex-col shrink-0 z-20">
<div className="flex justify-between items-center mb-6"><h3 className="text-sm font-bold text-white flex items-center gap-2"><Settings2 size={16} className="text-purple-400"/>Настройки</h3><button onClick={() => setSelectedPartitionId(null)} className="text-gray-400 hover:text-white"><X size={20}/></button></div>
<div className="bg-slate-800 p-4 rounded border border-slate-700 space-y-6">
<div><div className="flex justify-between text-xs text-gray-300 mb-2"><span>Высота</span> <span className="font-mono bg-slate-900 px-1.5 py-0.5 rounded text-xs">{selectedData.part.height} мм</span></div><input type="range" min="5" max={config.drawer.height || 100} step="1" value={selectedData.part.height} onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { height: parseFloat(e.target.value) })} className="w-full h-1 bg-slate-600 rounded-lg appearance-none cursor-pointer accent-purple-500"/></div>
<div className="flex items-center justify-between"><label htmlFor="rounded-check" className="text-xs text-gray-300 cursor-pointer select-none">Скруглить края</label><input type="checkbox" id="rounded-check" checked={selectedData.part.rounded} onChange={(e) => updatePartition(selectedData.key, selectedData.part.id, { rounded: e.target.checked })} className="w-4 h-4 rounded bg-slate-700 border-slate-600 text-purple-500 focus:ring-0 cursor-pointer"/></div>
<button onClick={() => removePartition(selectedData.key, selectedData.part.id)} className="w-full py-2 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 rounded text-xs flex items-center justify-center gap-2 transition-colors mt-4"><Trash2 size={14}/> Удалить</button>
</div> </div>
<div className="mt-auto text-[10px] text-gray-500 text-center leading-relaxed">Выделите стенку для настройки.<br/>Двойной клик удаляет её.</div>
</div>
) : (
<div className="w-72 bg-slate-900/50 border-l border-slate-800 p-8 flex flex-col items-center justify-center text-center text-gray-500 shrink-0">
<MousePointer2 size={32} className="mb-4 opacity-50"/>
<p className="text-sm">Выберите стенку для настройки</p>
<p className="text-xs mt-2 opacity-50">Кликните по любой перегородке внутри ячейки</p>
</div>
)}
</div> </div>
); );
}; };
+172 -15
View File
@@ -1,14 +1,14 @@
import React, { Suspense, useEffect, useRef, useState, useMemo } from 'react'; import React, { Suspense, useEffect, useRef, useState, useMemo } from 'react';
import { Canvas } from '@react-three/fiber'; import { Canvas } from '@react-three/fiber';
import { OrbitControls, Center, Environment } from '@react-three/drei'; import { OrbitControls, Center, Environment, Text } from '@react-three/drei';
import * as THREE from 'three'; import * as THREE from 'three';
import JSZip from 'jszip'; import JSZip from 'jszip';
import { AppConfig, GeneratedPart, LayoutSplits } from '../types'; import { AppConfig, GeneratedPart, LayoutSplits, PerforationConfig } from '../types';
import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator'; import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator';
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react'; import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
import { generateShareUrl } from '../utils/share'; import { generateShareUrl } from '../utils/share';
// --- DrawerFrame (Каркас) --- // --- DrawerFrame (Каркас ящика) ---
const DrawerFrame = ({ config }: { config: AppConfig }) => { const DrawerFrame = ({ config }: { config: AppConfig }) => {
const { width, depth, height } = config.drawer; const { width, depth, height } = config.drawer;
const offset = 0.5; const offset = 0.5;
@@ -27,22 +27,139 @@ interface BinMeshProps {
part: GeneratedPart; part: GeneratedPart;
thickness: number; thickness: number;
cornerRadius: number; cornerRadius: number;
perforation: PerforationConfig;
isSelected: boolean; isSelected: boolean;
onClick: () => void; onClick: () => void;
} }
const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSelected, onClick }) => { const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, perforation, isSelected, onClick }) => {
// 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const geometry = useMemo(() => { const geometry = useMemo(() => {
return createBinGeometry(part.width, part.depth, part.height, thickness, cornerRadius); return createBinGeometry(
}, [part, thickness, cornerRadius]); part.width,
part.depth,
part.height,
thickness,
cornerRadius,
part.internalPartitions, // <--- ВАЖНО: передаем перегородки в генератор
perforation
);
}, [part, thickness, cornerRadius, perforation]);
// 2. Создаем контур выделения (EdgesGeometry)
// Threshold 20 градусов скрывает линии на плавных скруглениях
const edgesGeometry = useMemo(() => { const edgesGeometry = useMemo(() => {
return new THREE.EdgesGeometry(geometry, 20); return new THREE.EdgesGeometry(geometry, 20);
}, [geometry]); }, [geometry]);
// 3. Вычисляем размеры и позиции для каждой под-ячейки
// 3. Вычисляем размеры и позиции для реальных отсеков (с учетом мерджинга)
const dimLabels = useMemo(() => {
const xOffsets = new Set<number>([0, 1]);
const zOffsets = new Set<number>([0, 1]);
part.internalPartitions.forEach(p => {
if (p.axis === 'x') xOffsets.add(p.offset);
if (p.axis === 'y') zOffsets.add(p.offset);
});
const xSplits = Array.from(xOffsets).sort((a, b) => a - b);
const zSplits = Array.from(zOffsets).sort((a, b) => a - b);
const numCols = xSplits.length - 1;
const numRows = zSplits.length - 1;
if (numCols === 0 || numRows === 0) return [];
// Union-Find для объединения ячеек, не разделенных стеной
const parent = new Int32Array(numCols * numRows).map((_, i) => i);
const find = (i: number): number => {
if (parent[i] === i) return i;
parent[i] = find(parent[i]);
return parent[i];
}
const union = (i: number, j: number) => {
const rootI = find(i);
const rootJ = find(j);
if (rootI !== rootJ) parent[rootJ] = rootI;
}
const getIdx = (c: number, r: number) => r * numCols + c;
// Вертикальные границы (X)
for (let i = 0; i < numCols - 1; i++) {
const boundaryX = xSplits[i + 1];
for (let j = 0; j < numRows; j++) {
const zMid = (zSplits[j] + zSplits[j + 1]) / 2;
// Проверяем наличие перегородки axis='x'
const isBlocked = part.internalPartitions.some(p =>
p.axis === 'x' &&
Math.abs(p.offset - boundaryX) < 0.001 &&
(p.min ?? 0) <= zMid && (p.max ?? 1) >= zMid
);
if (!isBlocked) union(getIdx(i, j), getIdx(i + 1, j));
}
}
// Горизонтальные границы (Z/Y)
for (let j = 0; j < numRows - 1; j++) {
const boundaryZ = zSplits[j + 1];
for (let i = 0; i < numCols; i++) {
const xMid = (xSplits[i] + xSplits[i + 1]) / 2;
// Проверяем наличие перегородки axis='y'
const isBlocked = part.internalPartitions.some(p =>
p.axis === 'y' &&
Math.abs(p.offset - boundaryZ) < 0.001 &&
(p.min ?? 0) <= xMid && (p.max ?? 1) >= xMid
);
if (!isBlocked) union(getIdx(i, j), getIdx(i, j + 1));
}
}
// Агрегируем регионы
const regions: Record<number, { minC: number, maxC: number, minR: number, maxR: number }> = {};
for (let j = 0; j < numRows; j++) {
for (let i = 0; i < numCols; i++) {
const root = find(getIdx(i, j));
if (!regions[root]) regions[root] = { minC: i, maxC: i, minR: j, maxR: j };
else {
const r = regions[root];
r.minC = Math.min(r.minC, i);
r.maxC = Math.max(r.maxC, i);
r.minR = Math.min(r.minR, j);
r.maxR = Math.max(r.maxR, j);
}
}
}
return Object.values(regions).map((r, idx) => {
const fXStart = xSplits[r.minC];
const fXEnd = xSplits[r.maxC + 1];
const fZStart = zSplits[r.minR];
const fZEnd = zSplits[r.maxR + 1];
const fracW = fXEnd - fXStart;
const fracD = fZEnd - fZStart;
const dimX = Math.max(0, fracW * (part.width - thickness) - thickness);
const dimZ = Math.max(0, fracD * (part.depth - thickness) - thickness);
const cx = -part.width / 2 + (fXStart + fXEnd) / 2 * part.width;
const cz = -part.depth / 2 + (fZStart + fZEnd) / 2 * part.depth;
return {
key: `region-${idx}`,
pos: [cx, thickness + 0.2, cz] as [number, number, number],
text: `${dimX.toFixed(0)} x ${dimZ.toFixed(0)}`
};
});
}, [part, thickness]);
return ( return (
<group position={[part.x + part.width/2, 0, part.y + part.depth/2]}> <group
<mesh geometry={geometry} onClick={(e) => { e.stopPropagation(); onClick(); }}> position={[part.x + part.width / 2, 0, part.y + part.depth / 2]}
onClick={(e) => { e.stopPropagation(); onClick(); }}
>
{/* Сама модель */}
<mesh geometry={geometry}>
<meshStandardMaterial <meshStandardMaterial
color={isSelected ? '#f59e0b' : part.color} color={isSelected ? '#f59e0b' : part.color}
roughness={0.5} roughness={0.5}
@@ -51,6 +168,23 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
/> />
</mesh> </mesh>
{/* Текстовые метки размеров внутри каждой ячейки */}
{dimLabels.map(label => (
<Text
key={label.key}
position={label.pos}
rotation={[-Math.PI / 2, 0, 0]}
fontSize={Math.min(part.width, part.depth) * 0.035}
color="#1e293b"
anchorX="center"
anchorY="middle"
characters="0123456789x "
>
{label.text}
</Text>
))}
{/* Белая подсветка при выборе */}
{isSelected && ( {isSelected && (
<lineSegments geometry={edgesGeometry}> <lineSegments geometry={edgesGeometry}>
<lineBasicMaterial color="white" linewidth={2} /> <lineBasicMaterial color="white" linewidth={2} />
@@ -60,7 +194,7 @@ const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, isSele
); );
}; };
// --- PreviewStep (Основной) --- // --- PreviewStep (Основной компонент) ---
interface Props { interface Props {
parts: GeneratedPart[]; parts: GeneratedPart[];
config: AppConfig; config: AppConfig;
@@ -73,25 +207,44 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
const [shareUrlCopied, setShareUrlCopied] = useState(false); const [shareUrlCopied, setShareUrlCopied] = useState(false);
const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({}); const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
// Скролл к выбранной детали в списке
useEffect(() => { useEffect(() => {
if (selectedId && itemRefs.current[selectedId]) { if (selectedId && itemRefs.current[selectedId]) {
itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' }); itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
} }
}, [selectedId]); }, [selectedId]);
// Скачивание одной детали
const handleDownload = (part: GeneratedPart) => { const handleDownload = (part: GeneratedPart) => {
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.cornerRadius); const geometry = createBinGeometry(
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions, // <--- ВАЖНО для STL
config.perforation
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()); const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`); exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
}; };
// Скачивание всего архивом
const handleDownloadAll = async () => { const handleDownloadAll = async () => {
if (isZipping) return; if (isZipping) return;
setIsZipping(true); setIsZipping(true);
try { try {
const zip = new JSZip(); const zip = new JSZip();
parts.forEach(part => { parts.forEach(part => {
const geometry = createBinGeometry(part.width, part.depth, part.height, config.wallThickness, config.cornerRadius); const geometry = createBinGeometry(
part.width,
part.depth,
part.height,
config.wallThickness,
config.cornerRadius,
part.internalPartitions, // <--- ВАЖНО для STL
config.perforation
);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()); const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
const stlData = generateSTL(mesh); const stlData = generateSTL(mesh);
zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData); zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
@@ -110,6 +263,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
} }
}; };
// Поделиться ссылкой
const handleShare = async () => { const handleShare = async () => {
const url = generateShareUrl(config, splits); const url = generateShareUrl(config, splits);
let success = false; let success = false;
@@ -143,8 +297,9 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
{/* Верхняя панель */} {/* Верхняя панель: Размеры + Поделиться */}
<div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg"> <div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">
<div className="flex flex-wrap items-center gap-6 justify-center md:justify-start"> <div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
<div className="hidden md:flex items-center gap-2 text-gray-300 mr-2"> <div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
<Ruler className="text-primary" size={20} /> <Ruler className="text-primary" size={20} />
@@ -166,6 +321,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
<span className="text-sm text-slate-500 font-bold self-baseline">мм</span> <span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
</div> </div>
</div> </div>
<button <button
onClick={handleShare} onClick={handleShare}
className={` className={`
@@ -219,6 +375,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
part={part} part={part}
thickness={config.wallThickness} thickness={config.wallThickness}
cornerRadius={config.cornerRadius || 0} cornerRadius={config.cornerRadius || 0}
perforation={config.perforation}
isSelected={selectedId === part.id} isSelected={selectedId === part.id}
onClick={() => setSelectedId(part.id)} onClick={() => setSelectedId(part.id)}
/> />
@@ -261,7 +418,7 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
`} `}
onClick={() => setSelectedId(part.id)} onClick={() => setSelectedId(part.id)}
> >
{/* Фон-индикатор */} {/* Индикатор цвета */}
<div <div
className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none" className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none"
style={{ backgroundColor: part.color, opacity: 0.1 }} style={{ backgroundColor: part.color, opacity: 0.1 }}
@@ -278,12 +435,12 @@ export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
/> />
</div> </div>
{/* --- РАЗМЕРЫ (НОВОЕ) --- */} {/* Размеры */}
<div className="text-[10px] text-gray-400 font-mono z-10"> <div className="text-[10px] text-gray-400 font-mono z-10">
{part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)} {part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
</div> </div>
{/* Кнопка */} {/* Кнопка скачивания */}
<button <button
onClick={(e) => { e.stopPropagation(); handleDownload(part); }} onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1" className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"
+547 -80
View File
@@ -1,78 +1,66 @@
import * as THREE from 'three'; import * as THREE from 'three';
import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
import { AppConfig, LayoutSplits, GeneratedPart } from '../types'; import { AppConfig, LayoutSplits, GeneratedPart, Partition, PerforationConfig } from '../types';
/** export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
* Calculates the final list of bins based on layout.
*/
export const calculateParts = (
config: AppConfig,
splits: LayoutSplits
): GeneratedPart[] => {
const parts: GeneratedPart[] = []; const parts: GeneratedPart[] = [];
const safeX = Array.isArray(splits?.x) ? splits.x : [];
const safeY = Array.isArray(splits?.y) ? splits.y : [];
const safeParts = splits?.partitions || {};
// Сортируем линии разреза const xPoints = [0, ...[...safeX].sort((a, b) => a - b), 1];
const xPoints = [0, ...[...splits.x].sort((a, b) => a - b), 1]; const yPoints = [0, ...[...safeY].sort((a, b) => a - b), 1];
const yPoints = [0, ...[...splits.y].sort((a, b) => a - b), 1];
let partCounter = 1; let partCounter = 1;
for (let i = 0; i < xPoints.length - 1; i++) { for (let i = 0; i < xPoints.length - 1; i++) {
for (let j = 0; j < yPoints.length - 1; j++) { for (let j = 0; j < yPoints.length - 1; j++) {
const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width;
const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth;
const segmentX = xPoints[i] * config.drawer.width; if (rawW < 5 || rawD < 5) continue;
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;
// Применяем зазор (Tolerance) const rawX = xPoints[i] * config.drawer.width;
const realWidth = segmentW - config.printerTolerance; const rawY = yPoints[j] * config.drawer.depth;
const realDepth = segmentD - config.printerTolerance; const internalPartitions = safeParts[`${i}-${j}`] || [];
const realX = segmentX + (config.printerTolerance / 2);
const realY = segmentY + (config.printerTolerance / 2);
// Игнорируем слишком мелкие детали const realWidth = rawW - config.printerTolerance;
if (realWidth < 5 || realDepth < 5) { const realDepth = rawD - config.printerTolerance;
continue; const realX = rawX + (config.printerTolerance / 2);
} const realY = rawY + (config.printerTolerance / 2);
parts.push({ parts.push({
id: `part-${partCounter}`, id: `part-${partCounter}`,
name: `Ячейка ${i+1}-${j+1}`, name: `Ячейка ${i + 1}-${j + 1}`,
width: realWidth, width: realWidth,
depth: realDepth, depth: realDepth,
height: config.drawer.height, height: config.drawer.height,
x: realX, x: realX,
y: realY, y: realY,
color: `hsl(${Math.random() * 360}, 70%, 50%)` color: `hsl(${Math.random() * 360}, 70%, 50%)`,
internalPartitions: internalPartitions
}); });
partCounter++; partCounter++;
} }
} }
return parts; return parts;
}; };
/** // --- ГЕОМЕТРИЯ ---
* Создает 2D форму прямоугольника со скругленными краями
*/
const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => { const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => {
const shape = new THREE.Shape(); const shape = new THREE.Shape();
const x = -width / 2; const x = -width / 2;
const y = -height / 2; const y = -height / 2;
const r = Math.min(radius, width / 2 - 0.1, height / 2 - 0.1);
// Ограничиваем радиус, чтобы он не сломал геометрию (не больше половины стороны)
const r = Math.min(radius, width / 2, height / 2);
if (r <= 0.1) { if (r <= 0.1) {
// Обычный прямоугольник (если радиус 0)
shape.moveTo(x, y); shape.moveTo(x, y);
shape.lineTo(x + width, y); shape.lineTo(x + width, y);
shape.lineTo(x + width, y + height); shape.lineTo(x + width, y + height);
shape.lineTo(x, y + height); shape.lineTo(x, y + height);
shape.lineTo(x, y); shape.lineTo(x, y);
} else { } else {
// Прямоугольник со скруглениями
shape.moveTo(x, y + r); shape.moveTo(x, y + r);
shape.lineTo(x, y + height - r); shape.lineTo(x, y + height - r);
shape.quadraticCurveTo(x, y + height, x + r, y + height); shape.quadraticCurveTo(x, y + height, x + r, y + height);
@@ -83,90 +71,569 @@ const createRoundedRectShape = (width: number, height: number, radius: number):
shape.lineTo(x + r, y); shape.lineTo(x + r, y);
shape.quadraticCurveTo(x, y, x, y + r); shape.quadraticCurveTo(x, y, x, y + r);
} }
return shape; return shape;
} };
const createConcaveFilletShape = (radius: number): THREE.Shape => {
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(radius, 0);
shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true);
shape.lineTo(0, 0);
return shape;
};
// New Helper: Create Perforated Plate (Vertical Wall)
const createPerforatedPlate = (
width: number,
height: number,
thickness: number,
perf: PerforationConfig,
marginLeft: number = 0,
marginRight: number = 0,
exclusions: { start: number, end: number, yMax?: number }[] = []
): THREE.BufferGeometry => {
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(width, 0);
shape.lineTo(width, height);
shape.lineTo(0, height);
shape.lineTo(0, 0);
// Hole Generation
if (perf && perf.enabled && width > perf.size && height > perf.size) {
const { shape: shapeType, size, gap } = perf;
const step = size + gap;
// Margins: ensure holes don't cut into the solid edge zones
const startX = Math.max(gap, marginLeft + gap);
const startY = gap;
const endX = width - Math.max(gap, marginRight + gap);
const endY = height - gap;
// Rows
let row = 0;
for (let y = startY + size / 2; y < endY; y += (shapeType === 'triangle' || shapeType === 'honeycomb' ? step * 0.866 : step)) {
const isStaggered = (row % 2 !== 0);
const xOffset = (isStaggered && (shapeType === 'honeycomb' || shapeType === 'triangle')) ? step / 2 : 0;
for (let x = startX + size / 2 + xOffset; x < endX; x += step) {
const hole = new THREE.Path();
const r = size / 2;
// Boundary check
if (x - r < marginLeft || x + r > width - marginRight || y - r < 0 || y + r > height) continue;
// Exclusion Zone Check
// Zone active if hole X is within [start, end] AND hole Y is below yMax (if specified).
// If y > yMax, the exclusion doesn't apply (it's above the intersecting wall).
// Note: y is measured from bottom (0) to top (height).
// yMax is the height of the intersecting partition.
const inExclusion = exclusions.some(zone => {
if (x + r <= zone.start || x - r >= zone.end) return false; // X-axis check
if (zone.yMax !== undefined && y - r > zone.yMax) return false; // Y-axis check (hole above wall)
return true;
});
if (inExclusion) continue;
if (shapeType === 'circle') {
hole.absarc(x, y, r, 0, Math.PI * 2, true);
} else if (shapeType === 'honeycomb') {
// Hexagon
for (let i = 0; i < 6; i++) {
const ang = (i * 60 + 30) * Math.PI / 180;
const px = x + r * Math.cos(ang);
const py = y + r * Math.sin(ang);
if (i === 0) hole.moveTo(px, py);
else hole.lineTo(px, py);
}
hole.closePath();
} else if (shapeType === 'triangle') {
// Triangle
const ang1 = -90 * Math.PI / 180;
const ang2 = 30 * Math.PI / 180;
const ang3 = 150 * Math.PI / 180;
hole.moveTo(x + r * Math.cos(ang1), y + r * Math.sin(ang1));
hole.lineTo(x + r * Math.cos(ang2), y + r * Math.sin(ang2));
hole.lineTo(x + r * Math.cos(ang3), y + r * Math.sin(ang3));
hole.closePath();
}
shape.holes.push(hole);
}
row++;
}
}
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false });
// Extruded along Z. Wall is flat on XY.
// We want "thickness" to be Z depth.
return geo;
};
// New Helper: Create Corner Profile (Extruded Vertical)
const createCornerProfile = (radius: number, thickness: number, height: number): THREE.BufferGeometry => {
if (radius <= 0) return new THREE.BufferGeometry();
const shape = new THREE.Shape();
// Create a Ring Segment (Hollow Corner) as a single loop.
// Center at (0,0).
const innerRadius = Math.max(0.01, radius - thickness); // Ensure slightly > 0 to maintain shape integrity
// 1. Start at Outer Start
shape.moveTo(radius, 0);
// 2. Outer Arc (CCW) -> To (0, radius)
shape.absarc(0, 0, radius, 0, Math.PI / 2, false);
// 3. Line to Inner End (0, innerRadius)
shape.lineTo(0, innerRadius);
// 4. Inner Arc (CW) -> To (innerRadius, 0)
shape.absarc(0, 0, innerRadius, Math.PI / 2, 0, true);
// 5. Close loop
shape.lineTo(radius, 0);
// Extrude
// curveSegments 32 for smoothness
const geo = new THREE.ExtrudeGeometry(shape, { depth: height, bevelEnabled: false, curveSegments: 32 });
return geo;
};
/**
* Генерирует 3D геометрию ящика
*/
export const createBinGeometry = ( export const createBinGeometry = (
width: number, width: number,
depth: number, depth: number,
height: number, height: number,
thickness: number, thickness: number,
radius: number = 0 radius: number = 0,
partitions: Partition[] = [],
perforation?: PerforationConfig
): THREE.BufferGeometry => { ): THREE.BufferGeometry => {
const geometries: THREE.BufferGeometry[] = [];
// 1. ГЕОМЕТРИЯ ДНА (Сплошная) // ДНО (Floor) - Always same
const floorShape = createRoundedRectShape(width, depth, radius); const floorShape = createRoundedRectShape(width, depth, radius);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false });
floorGeo.rotateX(-Math.PI / 2); // Lay flat
geometries.push(floorGeo);
const floorGeo = new THREE.ExtrudeGeometry(floorShape, { // WALLS
depth: thickness, // Выдавливаем на толщину дна if (!perforation || !perforation.enabled) {
bevelEnabled: false, // --- ORIGINAL LOGIC (Optimized for Solid Walls) ---
curveSegments: 16 // Количество сегментов на скруглениях
});
// Extrude выдавливает по оси Z. Нам нужно повернуть, чтобы "глубина" стала "высотой" (Y).
// Поворот на -90 градусов вокруг X кладет Z на Y.
floorGeo.rotateX(-Math.PI / 2);
// Теперь дно занимает пространство от Y=0 до Y=thickness.
// 2. ГЕОМЕТРИЯ СТЕНОК (С дыркой)
const outerShape = createRoundedRectShape(width, depth, radius); const outerShape = createRoundedRectShape(width, depth, radius);
const innerRadius = Math.max(0.1, radius - thickness);
// Вырезаем внутреннюю часть
const innerRadius = Math.max(0, radius - thickness);
const innerWidth = width - (2 * thickness); const innerWidth = width - (2 * thickness);
const innerDepth = depth - (2 * thickness); const innerDepth = depth - (2 * thickness);
if (innerWidth > 0 && innerDepth > 0) { if (innerWidth > 0.1 && innerDepth > 0.1) {
const innerHole = createRoundedRectShape(innerWidth, innerDepth, innerRadius); const innerHole = createRoundedRectShape(innerWidth, innerDepth, innerRadius);
outerShape.holes.push(innerHole); outerShape.holes.push(innerHole);
} }
// Высота стенок = общая высота минус толщина дна
const wallHeight = height - thickness; const wallHeight = height - thickness;
const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false });
wallGeo.rotateX(-Math.PI / 2);
wallGeo.translate(0, thickness, 0);
geometries.push(wallGeo);
} else {
// --- PERFORATED LOGIC (Split Walls) ---
const wallHeight = height - thickness;
// Clamp radius to at least thickness for valid corners in this mode
const effRadius = Math.max(radius, thickness);
const wallGeo = new THREE.ExtrudeGeometry(outerShape, { const straightW = width - 2 * effRadius;
depth: wallHeight, const straightD = depth - 2 * effRadius;
bevelEnabled: false,
curveSegments: 16 // 1. Corners (4 pcs)
if (effRadius > 0) {
const cornerGeoBase = createCornerProfile(effRadius, thickness, wallHeight);
// 1. Stand Up: Extrusion Z -> Y. Shape moves to X(+)/Z(+).
cornerGeoBase.rotateX(-Math.PI / 2);
// Base Corner Shape (after rotateX) is Q4 (+X, -Z).
// Rotation Logic: -90 degrees per Quadrant (Standard Three.js Y-Rot).
// Q4 (0) -> Q1 (-90) -> Q2 (-180/180) -> Q3 (-270/+90).
const positions = [
// Back Right (+X, +Z). Q1.
// Rot -90 (-PI/2).
{ x: width / 2 - effRadius, z: depth / 2 - effRadius, rot: -Math.PI / 2 },
// Back Left (-X, +Z). Q2.
// Rot 180 (PI).
{ x: -(width / 2 - effRadius), z: depth / 2 - effRadius, rot: Math.PI },
// Front Left (-X, -Z). Q3.
// Rot 90 (PI/2). (Equivalent to -270).
{ x: -(width / 2 - effRadius), z: -(depth / 2 - effRadius), rot: Math.PI / 2 },
// Front Right (+X, -Z). Q4.
// Rot 0.
{ x: width / 2 - effRadius, z: -(depth / 2 - effRadius), rot: 0 }
];
positions.forEach(pos => {
const corner = cornerGeoBase.clone();
corner.rotateY(pos.rot);
corner.translate(pos.x, 0, pos.z); // Start at Y=0
corner.translate(0, thickness, 0); // Move on top of floor
geometries.push(corner);
});
}
// 2. Straight Walls (4 pcs) - Centered on edges
// REWRITE EXCLUSION COLLECTION LOGIC TO BE WALL-SPECIFIC
const exclusionsBack: { start: number, end: number, yMax: number }[] = [];
const exclusionsFront: { start: number, end: number, yMax: number }[] = [];
const exclusionsLeft: { start: number, end: number, yMax: number }[] = [];
const exclusionsRight: { start: number, end: number, yMax: number }[] = [];
// Inner Dimensions
const effectiveInnerW = width - 2 * thickness;
const effectiveInnerD = depth - 2 * thickness;
partitions.forEach(p => {
const hEff = Math.max(0.1, p.height - thickness); // Exclude only up to partition height
// Ensure solid strip around partition by adding padding to exclusion zone
const padding = (perforation?.gap ?? 2) + 1;
if (p.axis === 'x') {
// Runs Depth-wise (Y axis in Layout).
// Intersects Front and Back walls.
const partGlobalX = (-effectiveInnerW / 2) + (effectiveInnerW * p.offset);
const sW = width - 2 * effRadius;
const localXOnWall = partGlobalX + sW / 2;
// Check intersection with active straight wall area + padding
if (localXOnWall + thickness / 2 + padding > 0 && localXOnWall - thickness / 2 - padding < sW) {
const zone = {
start: localXOnWall - thickness / 2 - padding,
end: localXOnWall + thickness / 2 + padding,
yMax: hEff
};
if ((p.max ?? 1) > 0.99) exclusionsFront.push(zone); // Near
if ((p.min ?? 0) < 0.01) exclusionsBack.push(zone); // Far
}
} else { // p.axis === 'y'
// Runs Width-wise (X axis in Layout).
// Intersects Left and Right walls.
const partGlobalZ = (-effectiveInnerD / 2) + (effectiveInnerD * p.offset);
const sD = depth - 2 * effRadius;
const localXOnWall = partGlobalZ + sD / 2;
if (localXOnWall + thickness / 2 + padding > 0 && localXOnWall - thickness / 2 - padding < sD) {
const zone = {
start: localXOnWall - thickness / 2 - padding,
end: localXOnWall + thickness / 2 + padding,
yMax: hEff
};
if ((p.min ?? 0) < 0.01) {
exclusionsLeft.push(zone);
}
if ((p.max ?? 1) > 0.99) {
exclusionsRight.push(zone);
}
}
}
}); });
// Поворачиваем стенки так же, как дно // Front/Back
wallGeo.rotateX(-Math.PI / 2); if (straightW > 0.1) {
// Wall 1 (at +Z). This is "Front" (Near). Contacts p.max.
// Uses exclusionsFront.
const wGeoFront = createPerforatedPlate(straightW, wallHeight, thickness, perforation, 0, 0, exclusionsFront);
wGeoFront.translate(-straightW / 2, 0, 0);
const w1 = wGeoFront.clone();
w1.translate(0, thickness, depth / 2 - thickness);
geometries.push(w1);
// Сейчас стенки тоже начинаются с Y=0. // Wall 2 (at -Z). This is "Back" (Far). Contacts p.min.
// Нам нужно поднять их НАД дном. // Uses exclusionsBack.
wallGeo.translate(0, thickness, 0); // Needs checking mapping (Rot 180).
// p.offset increases X. Wall rotated 180 means X is inverted.
// So we map exclusionsBack.
const exclusionsBackMapped = exclusionsBack.map(e => ({
start: straightW - e.end,
end: straightW - e.start,
yMax: e.yMax
}));
// Теперь стенки занимают пространство от Y=thickness до Y=height. const wGeoBack = createPerforatedPlate(straightW, wallHeight, thickness, perforation, 0, 0, exclusionsBackMapped);
wGeoBack.translate(-straightW / 2, 0, 0);
const w2 = wGeoBack.clone();
w2.rotateY(Math.PI);
w2.translate(0, thickness, -(depth / 2 - thickness));
geometries.push(w2);
}
// 3. ОБЪЕДИНЕНИЕ // Left/Right
// Сливаем две геометрии в одну. Слайсеры поймут это как единый объект, if (straightD > 0.1) {
// так как поверхности идеально соприкасаются. // Wall 3 (Right? +X).
const merged = mergeBufferGeometries([floorGeo, wallGeo]); // Plate is 0..straightD in X, 0..wallHeight in Y. Thickness along Z.
// We want it to be at X = width/2.
// It needs to be rotated -PI/2 around Y to align its X-axis with World Z-axis.
// After rotateY(-PI/2): Plate X (0..straightD) becomes World Z (0..straightD).
// Plate Z (thickness) becomes World -X (towards Left).
// So if we place it at X=width/2, it extrudes to width/2 - thickness. Correct for Right Wall.
const wGeoRight = createPerforatedPlate(straightD, wallHeight, thickness, perforation, 0, 0, exclusionsRight);
wGeoRight.translate(-straightD / 2, 0, 0); // Center X of plate
const w3 = wGeoRight.clone();
w3.rotateY(-Math.PI / 2); // Rotate to align with Z-axis
w3.translate(width / 2, thickness, 0); // Position at X=width/2
geometries.push(w3);
// Центрирование не нужно, так как createRoundedRectShape строит форму вокруг (0,0) по X и Z. // Wall 4 (Left? -X).
// А по Y мы выстроили от 0 вверх. // This wall is also rotated PI/2.
// Pivot point (опорная точка) осталась внизу в центре (0,0,0), что идеально для позиционирования. // Plate Z (thickness) becomes World X (towards Right).
// We want it at X=-width/2.
// It will extrude to -width/2 + thickness. Correct for Left Wall.
const exclusionsLeftMapped = exclusionsLeft.map(e => ({
start: straightD - e.end,
end: straightD - e.start,
yMax: e.yMax
}));
const wGeoLeft = createPerforatedPlate(straightD, wallHeight, thickness, perforation, 0, 0, exclusionsLeftMapped);
wGeoLeft.translate(-straightD / 2, 0, 0); // Center X of plate
const w4 = wGeoLeft.clone();
w4.rotateY(Math.PI / 2);
w4.translate(-width / 2, thickness, 0); // Position at X=-width/2
geometries.push(w4);
}
}
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ
const innerWidth = width - (2 * thickness);
const innerDepth = depth - (2 * thickness); // Approximate usable space logic
partitions.forEach(p => {
const pMin = p.min ?? 0;
const pMax = p.max ?? 1;
if (pMax - pMin < 0.01) return;
const lengthRatio = pMax - pMin;
const midRatio = pMin + (lengthRatio / 2);
// FIX: Subtract thickness because partitions sit ON TOP of the floor
const effectiveHeight = Math.max(0.1, p.height - thickness);
// --- PERFORATED LOGIC FOR PARTITIONS ---
// If enabled, use Plate. Else use Extrude Solid.
const usePerf = perforation && perforation.enabled;
let pX = 0, pY = 0; // Declare here for visibility in Fillets
if (usePerf) {
// Calculate exact geometry
let pLen = 0;
if (p.axis === 'x') {
// Axis X -> Divider runs along Y (Depth)
pLen = lengthRatio * innerDepth;
pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = (-innerDepth / 2) + (innerDepth * midRatio); // Center of partition
// Calculate Exclusions for Internal Partition
const partExclusions: { start: number, end: number, yMax?: number }[] = [];
// This partition is 'p' (Axis X, runs along Depth).
// Intersected by partitions 'n' (Axis Y, runs along Width).
// p global Y range: pY - pLen/2 to pY + pLen/2.
// n global Y pos: (-innerDepth/2) + (innerDepth * n.offset).
partitions.forEach(n => {
if (n.axis !== 'y') return; // Only orthogonal partitions intersect
// Check if n intersects p
// Intersection Y location:
const nY = (-innerDepth / 2) + (innerDepth * n.offset);
// Does nY (which is global Y of the intersecting partition) match p's position?
// p is Axis X, runs along DEPTH (Global Y).
// p is centered at pX (Width) and covers pLen in Depth (Y).
// Wait. p (Axis X) runs along Y?
// p.axis='x' -> "Runs along Y (Depth)". Correct.
// So p covers Y range [pY - pLen/2, pY + pLen/2].
// n is Axis Y, runs along X (Width).
// n is centered at nY (Depth).
// So intersection happens if nY is within p's Y range.
const pStartGlobal = pY - pLen / 2;
const pEndGlobal = pY + pLen / 2;
// And check if n covers p's X location.
// n runs along X from nMin to nMax.
const nXStart = (-innerWidth / 2) + (innerWidth * (n.min ?? 0));
const nXEnd = (-innerWidth / 2) + (innerWidth * (n.max ?? 1));
const pXLoc = pX;
if (nY >= pStartGlobal && nY <= pEndGlobal && pXLoc >= nXStart && pXLoc <= nXEnd) {
// Intersection confirmed.
// Calculate local coord on p's plate.
// p runs along Y. Plate local X maps to Global Y.
// local = global - pY + pLen/2.
const nHeight = Math.max(0.1, n.height - thickness);
const localX = nY - pY + pLen / 2;
partExclusions.push({ start: localX - thickness / 2, end: localX + thickness / 2, yMax: nHeight });
}
});
// Add margins (solid ends)
const margin = thickness;
const plate = createPerforatedPlate(pLen, effectiveHeight, thickness, perforation!, margin, margin, partExclusions);
plate.translate(-pLen / 2, 0, 0); // Center X
// Rotate to align with Depth (along Z)
// Plate X -> Z
plate.rotateY(-Math.PI / 2);
// Position
// Plate is now vertical Z-aligned. Thickness along X.
plate.translate(pX + thickness / 2, thickness, pY);
geometries.push(plate);
} else {
// Axis Y -> Divider runs along X (Width)
pLen = lengthRatio * innerWidth;
pX = (-innerWidth / 2) + (innerWidth * midRatio);
pY = (-innerDepth / 2) + (innerDepth * p.offset);
// Calculate Exclusions
const partExclusions: { start: number, end: number, yMax?: number }[] = [];
// This partition is 'p' (Axis Y, runs along Width).
// Intersected by partitions 'n' (Axis X, runs along Depth).
partitions.forEach(n => {
if (n.axis !== 'x') return;
const nX = (-innerWidth / 2) + (innerWidth * n.offset);
const pStartGlobal = pX - pLen / 2; // X range of p
const pEndGlobal = pX + pLen / 2;
const nYStart = (-innerDepth / 2) + (innerDepth * (n.min ?? 0));
const nYEnd = (-innerDepth / 2) + (innerDepth * (n.max ?? 1));
const pYLoc = pY;
if (nX >= pStartGlobal && nX <= pEndGlobal && pYLoc >= nYStart && pYLoc <= nYEnd) {
// Intersection confirmed
// local = global - pX + pLen/2
const nHeight = Math.max(0.1, n.height - thickness); // INTERSECTING PARTITION HEIGHT
const localX = nX - pX + pLen / 2;
partExclusions.push({ start: localX - thickness / 2, end: localX + thickness / 2, yMax: nHeight });
}
});
const margin = thickness;
const plate = createPerforatedPlate(pLen, effectiveHeight, thickness, perforation!, margin, margin, partExclusions);
plate.translate(-pLen / 2, 0, 0); // Center X
// Already aligned with X. Thickness along Z.
// Z range [0, th]. We want [-th/2, th/2] relative to pY.
// Translate Z by -th/2.
plate.translate(0, 0, -thickness / 2);
// Move to position
plate.translate(pX, thickness, pY);
geometries.push(plate);
}
} else {
// --- SOLID LOGIC ---
let pWidth = 0, pDepth = 0;
if (p.axis === 'x') {
pWidth = thickness;
pDepth = lengthRatio * innerDepth;
pX = (-innerWidth / 2) + (innerWidth * p.offset);
pY = (-innerDepth / 2) + (innerDepth * midRatio);
} else {
pWidth = lengthRatio * innerWidth;
pDepth = thickness;
pX = (-innerWidth / 2) + (innerWidth * midRatio);
pY = (-innerDepth / 2) + (innerDepth * p.offset);
}
const partShape = createRoundedRectShape(pWidth, pDepth, 0.1);
const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: effectiveHeight, bevelEnabled: false });
partGeo.rotateX(-Math.PI / 2);
partGeo.translate(pX, thickness, pY);
geometries.push(partGeo);
}
// Fillets Logic for partitions (Keep solid for strength/aesthetics)
if (p.rounded && radius > 1) {
const filletR = Math.min(radius, 5);
const filletShape = createConcaveFilletShape(filletR);
// Helper to get neighbor height
const getNeighborHeight = (pos: number) => {
if (pos < 0.001 || pos > 0.999) return height;
const neighbor = partitions.find(n => {
if (n.axis === p.axis) return false;
const nMin = n.min ?? 0;
const nMax = n.max ?? 1;
if (Math.abs(n.offset - pos) > 0.002) return false;
return p.offset > nMin && p.offset < nMax;
});
return neighbor ? neighbor.height : 0;
};
const hStart = Math.min(p.height, getNeighborHeight(pMin));
const hEnd = Math.min(p.height, getNeighborHeight(pMax));
const addFillet = (x: number, y: number, rotY: number, h: number) => {
const hEff = Math.max(0.1, h - thickness);
if (hEff <= 1) return;
const geo = new THREE.ExtrudeGeometry(filletShape, { depth: hEff, bevelEnabled: false });
geo.rotateX(-Math.PI / 2);
geo.rotateY(rotY);
geo.translate(x, thickness, y);
geometries.push(geo);
};
const t = thickness / 2;
if (p.axis === 'x') {
const topY = (-innerDepth / 2) + (innerDepth * pMin);
const botY = (-innerDepth / 2) + (innerDepth * pMax);
addFillet(pX - t, topY, Math.PI, hStart);
addFillet(pX + t, topY, -Math.PI / 2, hStart);
addFillet(pX - t, botY, Math.PI / 2, hEnd);
addFillet(pX + t, botY, 0, hEnd);
} else {
const leftX = (-innerWidth / 2) + (innerWidth * pMin);
const rightX = (-innerWidth / 2) + (innerWidth * pMax);
addFillet(leftX, pY - t, 0, hStart);
addFillet(leftX, pY + t, -Math.PI / 2, hStart);
addFillet(rightX, pY - t, Math.PI / 2, hEnd);
addFillet(rightX, pY + t, Math.PI, hEnd);
}
}
});
const merged = mergeBufferGeometries(geometries);
if (merged) merged.computeVertexNormals();
return merged || new THREE.BoxGeometry(1, 1, 1); return merged || new THREE.BoxGeometry(1, 1, 1);
}; };
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => { export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
const exporter = new STLExporter(); const exporter = new STLExporter();
const result = exporter.parse(mesh, { binary: true }); const result = exporter.parse(mesh, { binary: true });
if (result instanceof DataView) { if (result instanceof DataView) return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
}
return result as string; return result as string;
}; };
export const exportSTL = (mesh: THREE.Object3D, filename: string) => { export const exportSTL = (mesh: THREE.Object3D, filename: string) => {
const result = generateSTL(mesh); const result = generateSTL(mesh);
const blob = new Blob([result], { type: 'application/octet-stream' }); const blob = new Blob([result as any], { type: 'application/octet-stream' });
const link = document.createElement('a'); const link = document.createElement('a');
link.href = URL.createObjectURL(blob); link.href = URL.createObjectURL(blob);
link.download = filename; link.download = filename;
+23 -1
View File
@@ -8,12 +8,33 @@ export interface AppConfig {
drawer: DrawerDimensions; drawer: DrawerDimensions;
wallThickness: number; wallThickness: number;
printerTolerance: number; printerTolerance: number;
cornerRadius: number; // <--- Новое свойство cornerRadius: number;
perforation: PerforationConfig;
}
export type PerforationShape = 'circle' | 'honeycomb' | 'triangle' | 'diamond';
export interface PerforationConfig {
enabled: boolean;
shape: PerforationShape;
size: number;
gap: number;
}
export interface Partition {
id: string;
axis: 'x' | 'y';
offset: number; // Позиция (0.0 - 1.0)
min: number; // Начало стенки (0.0 - 1.0)
max: number; // Конец стенки (0.0 - 1.0)
height: number;
rounded: boolean;
} }
export interface LayoutSplits { export interface LayoutSplits {
x: number[]; x: number[];
y: number[]; y: number[];
partitions: Record<string, Partition[]>;
} }
export interface GeneratedPart { export interface GeneratedPart {
@@ -25,4 +46,5 @@ export interface GeneratedPart {
x: number; x: number;
y: number; y: number;
color: string; color: string;
internalPartitions: Partition[];
} }