diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 1095817..bde04f1 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -1,7 +1,6 @@ import React, { useRef, useState, useMemo } from 'react'; import { AppConfig, LayoutSplits, Partition } from '../types'; -// Добавил Settings, Move и прочее в импорты -import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings, Plus } from 'lucide-react'; +import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react'; interface Props { config: AppConfig; @@ -25,23 +24,22 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const [dragging, setDragging] = useState(null); const [isButtonHovered, setIsButtonHovered] = useState(false); - // Main Grid Hover const [phantomMainAxis, setPhantomMainAxis] = useState(null); const [hoveredMainSplit, setHoveredMainSplit] = useState<{ axis: Axis; index: number } | null>(null); - // Partition Hover 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(null); - // -- SAFE DATA -- + // -- 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; @@ -61,27 +59,29 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // -- LOGIC: T-Junction Limits -- - // Находит ближайшие стенки, чтобы ограничить новую перегородку - const getHoveredBoundaries = (lx: number, ly: number, parts: Partition[]) => { + // --- RAYCASTING (Надежный поиск коробки) --- + // Находит ближайшие стенки во всех 4 направлениях + 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') { - // Вертикальная стенка (x=offset, y=min..max) - // Проверяем, находится ли мышь в её диапазоне по Y - if (ly >= pMin && ly <= pMax) { + // Вертикальная стенка. Перекрывает ли она наш 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 { - // Горизонтальная стенка (y=offset, x=min..max) - // Проверяем, находится ли мышь в её диапазоне по X - if (lx >= pMin && lx <= pMax) { + // Горизонтальная стенка. Перекрывает ли она наш 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); } @@ -90,20 +90,34 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { return { minX, maxX, minY, maxY }; }; + // Поиск соседей для размеров (Та же логика, что Raycasting) + 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 + axis, offset, min, max, + height: config.drawer.height || 80, rounded: false }; - // Обновляем стейт, но НЕ сбрасываем mode, так как ErrorBoundary теперь снаружи onChange({ ...splits, partitions: { ...safePartitions, [key]: [...current, newPart] } }); setSelectedPartitionId(newPart.id); }; @@ -129,12 +143,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setDragging(null); }; - // -- MOUSE HANDLER -- + // -- MOUSE HANDLERS -- const handleMouseMove = (e: React.MouseEvent) => { if (!svgRef.current) return; 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 ny = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height)); setMousePos({ x: nx, y: ny }); @@ -152,19 +165,11 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { 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); - } + if (dragging.axis === 'x') newOffset = (nx - cellX1) / (cellX2 - cellX1); + else newOffset = (ny - cellY1) / (cellY2 - cellY1); - // Ограничиваем в пределах "родительской" зоны (0-1) внутри ячейки - // В идеале тут тоже надо проверять коллизии, но пока просто границы ячейки newOffset = Math.max(0.02, Math.min(0.98, newOffset)); - - if (!isNaN(newOffset)) { - updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); - } + if (!isNaN(newOffset)) updatePartition(dragging.cellKey, dragging.id, { offset: newOffset }); } return; } @@ -177,25 +182,21 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (nx > SNAP && nx < 1 - SNAP && ny > SNAP && ny < 1 - SNAP) { const closeToX = safeX.some(val => Math.abs(nx - val) < SNAP); const closeToY = safeY.some(val => Math.abs(ny - val) < SNAP); - if (!closeToX && !closeToY) { - const distRight = 1 - nx; const distBottom = 1 - ny; - setPhantomMainAxis(Math.min(nx, distRight) < Math.min(ny, distBottom) ? 'y' : 'x'); - } else { setPhantomMainAxis(null); } + if (!closeToX && !closeToY) setPhantomMainAxis(Math.min(nx, 1-nx) < Math.min(ny, 1-ny) ? 'y' : 'x'); + else setPhantomMainAxis(null); } } else { - // Cells Mode setHoveredPartition(null); setPhantomPartition(null); setHoveredCell(null); - // 1. Находим ячейку + // 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; + cellIdx = { i, j }; break; } } } @@ -212,11 +213,15 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const lx = (nx - cx1) / cw; const ly = (ny - cy1) / ch; - // 2. Проверяем наведение на существующие (для удаления/выделения) + // 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; + 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 { @@ -227,29 +232,30 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // 3. Вычисляем T-образные границы - const bounds = getHoveredBoundaries(lx, ly, parts); + // --- FIND BOX --- + const box = getCursorBox(lx, ly, parts); - const distL = lx - bounds.minX; - const distR = bounds.maxX - lx; - const distT = ly - bounds.minY; - const distB = bounds.maxY - ly; + 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; + + if (relL < THRESHOLD || relL > 1 - THRESHOLD) newAxis = 'x'; // Near vertical edge -> vertical wall + else if (relT < THRESHOLD || relT > 1 - THRESHOLD) newAxis = 'y'; // Near horiz edge -> horizontal wall + + const valid = (newAxis === 'x' && (box.maxX - box.minX) > 0.05) || (newAxis === 'y' && (box.maxY - box.minY) > 0.05); - const minX = Math.min(distL, distR); - const minY = Math.min(distT, distB); - - // Определяем ось перпендикулярно ближайшей стороне - const axis = minX < minY ? 'y' : 'x'; - - // Проверяем, есть ли место - const width = bounds.maxX - bounds.minX; - const height = bounds.maxY - bounds.minY; - - if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) { - const offset = axis === 'x' ? lx : ly; - const min = axis === 'x' ? bounds.minY : bounds.minX; - const max = axis === 'x' ? bounds.maxY : bounds.maxX; - setPhantomPartition({ axis, offset, min, max }); + if (valid) { + const offset = newAxis === 'x' ? lx : ly; + const min = newAxis === 'x' ? box.minY : box.minX; + const max = newAxis === 'x' ? box.maxY : box.maxX; + setPhantomPartition({ axis: newAxis, offset, min, max }); } } } @@ -258,7 +264,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const handleMouseDown = (e: React.MouseEvent) => { if (isButtonHovered) return; - if (mode === 'lines') { if (hoveredMainSplit) { if (e.button === 0) setDragging({ type: 'main', ...hoveredMainSplit }); @@ -285,14 +290,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { } } else if (hoveredCell && phantomPartition) { if (e.button === 0) { - createPartition( - hoveredCell.i, - hoveredCell.j, - phantomPartition.axis, - phantomPartition.offset, - phantomPartition.min, - phantomPartition.max - ); + createPartition(hoveredCell.i, hoveredCell.j, phantomPartition.axis, phantomPartition.offset, phantomPartition.min, phantomPartition.max); } } else { setSelectedPartitionId(null); @@ -307,7 +305,6 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { for (let j = 0; j < sortedY.length - 1; j++) { const x1 = sortedX[i]; const x2 = sortedX[i + 1]; const y1 = sortedY[j]; const y2 = sortedY[j + 1]; - if (y2 === undefined || x2 === undefined) continue; const cellX = x1 * viewBoxW; const cellY = y1 * viewBoxH; @@ -317,6 +314,22 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const isHovered = hoveredCell?.i === i && hoveredCell?.j === j && mode === 'cells'; const parts = safePartitions[key] || []; const isAnySelected = parts.some(p => p.id === selectedPartitionId); + const realW = (x2 - x1) * drawerW; + const realD = (y2 - y1) * drawerD; + + if (parts.length === 0) { + const labelX = cellX + cellW / 2; + const labelY = cellY + cellH / 2; + const textW = Math.max(0, realW - wallThick).toFixed(0); + const textD = Math.max(0, realD - wallThick).toFixed(0); + if (cellH > 40 && cellW > 60) { + elements.push( + + {textW} × {textD} + + ); + } + } elements.push( @@ -324,25 +337,58 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {isAnySelected && mode === 'cells' && } {parts.map(p => { - const pMin = p.min ?? 0; const pMax = p.max ?? 1; + 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 (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 ( - { e.stopPropagation(); removePartition(key, p.id); }}> - - + + { e.stopPropagation(); removePartition(key, p.id); }}> + + + + + {isVertical ? ( + <> + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} + + ) : ( + <> + {Math.max(0, dist1).toFixed(0)} + {Math.max(0, dist2).toFixed(0)} + + )} + ); })} @@ -350,16 +396,14 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {isHovered && phantomPartition && !hoveredPartition && !dragging && ( {(() => { - const pMin = phantomPartition.min; const pMax = phantomPartition.max; + const { min, max } = phantomPartition; let fx1, fy1, fx2, fy2; if (phantomPartition.axis === 'x') { const px = cellX + (cellW * phantomPartition.offset); - fx1 = px; fx2 = px; - fy1 = cellY + (cellH * pMin); fy2 = cellY + (cellH * pMax); + fx1 = px; fx2 = px; fy1 = cellY + (cellH * min); fy2 = cellY + (cellH * max); } else { const py = cellY + (cellH * phantomPartition.offset); - fy1 = py; fy2 = py; - fx1 = cellX + (cellW * pMin); fx2 = cellX + (cellW * pMax); + fy1 = py; fy2 = py; fx1 = cellX + (cellW * min); fx2 = cellX + (cellW * max); } return ; })()} @@ -373,143 +417,60 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; return ( -
- - {/* TOOLBAR */} -
-

- 2. Редактор макета -

- -
- - -
+
+
+
+

Редактор

+
+ + +
+ +
- -
- - {/* INFO BAR */} -
- - {mode === 'lines' ? ( -
- ЛКМ: Линия - ПКМ: Удалить -
- ) : ( -
- ЛКМ в ячейке: Стенка (T-соединения) - Драг: Двигать - 2xЛКМ: Удалить -
- )} -
- - {/* WORKSPACE */} -
-
-
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'), - }} - > - setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()} - > - - - - - +
+
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') }}> + setDragging(null)} onMouseLeave={() => setDragging(null)} onContextMenu={(e) => e.preventDefault()}> + - {renderCellsAndPartitions()} - - {/* MAIN GRID X */} {safeX.map((x, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'x', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('x', i); }}> ))} - - {/* MAIN GRID Y */} {safeY.map((y, i) => ( { if(mode === 'lines' && !dragging) { e.stopPropagation(); setHoveredMainSplit({axis: 'y', index: i}); setPhantomMainAxis(null); }}} onDoubleClick={(e) => { e.stopPropagation(); removeMainSplit('y', i); }}> ))} - - {/* MAIN PHANTOMS */} - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'x' && } - {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis === 'y' && } + {mode === 'lines' && !hoveredMainSplit && !dragging && phantomMainAxis && ( + + )}
+
+
+ + {mode === 'cells' && selectedData ? ( +
+

Настройки

+
+
Высота {selectedData.part.height} мм
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"/>
+
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"/>
+
- - {/* --- SIDEBAR FOR EDITING --- */} - {mode === 'cells' && selectedData && ( -
-
-

- Настройки стенки -

- -
- -
- {/* Height */} -
-
- Высота {selectedData.part.height} мм -
- 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" - /> -
- - {/* Rounded */} -
- - 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" - /> -
- - {/* Delete */} - -
- -
- Выделите стенку для настройки.
Двойной клик удаляет её. -
-
- )} +
Выделите стенку для настройки.
Двойной клик удаляет её.
+ ) : ( +
+ +

Выберите стенку для настройки

+

Кликните по любой перегородке внутри ячейки

+
+ )}
); }; \ No newline at end of file diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index 354166f..58d7263 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -15,11 +15,13 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat for (let i = 0; i < xPoints.length - 1; i++) { for (let j = 0; j < yPoints.length - 1; j++) { - const rawX = xPoints[i] * config.drawer.width; - const rawY = yPoints[j] * config.drawer.depth; const rawW = (xPoints[i + 1] - xPoints[i]) * config.drawer.width; const rawD = (yPoints[j + 1] - yPoints[j]) * config.drawer.depth; + + if (rawW < 5 || rawD < 5) continue; + const rawX = xPoints[i] * config.drawer.width; + const rawY = yPoints[j] * config.drawer.depth; const internalPartitions = safeParts[`${i}-${j}`] || []; const realWidth = rawW - config.printerTolerance; @@ -27,8 +29,6 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat const realX = rawX + (config.printerTolerance / 2); const realY = rawY + (config.printerTolerance / 2); - if (realWidth < 5 || realDepth < 5) continue; - parts.push({ id: `part-${partCounter}`, name: `Ячейка ${i+1}-${j+1}`, @@ -48,12 +48,11 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat // --- ГЕОМЕТРИЯ --- -// 1. Форма скругленного прямоугольника (для дна и внешних стенок) const createRoundedRectShape = (width: number, height: number, radius: number): THREE.Shape => { const shape = new THREE.Shape(); const x = -width / 2; const y = -height / 2; - const r = Math.min(radius, width / 2, height / 2); + const r = Math.min(radius, width / 2 - 0.1, height / 2 - 0.1); if (r <= 0.1) { shape.moveTo(x, y); @@ -75,20 +74,12 @@ const createRoundedRectShape = (width: number, height: number, radius: number): return shape; }; -// 2. Форма галтели (вогнутого треугольника) для углов -const createFilletShape = (radius: number): THREE.Shape => { +const createConcaveFilletShape = (radius: number): THREE.Shape => { const shape = new THREE.Shape(); - // Начинаем из угла (0,0) shape.moveTo(0, 0); - // Линия вдоль одной стенки shape.lineTo(radius, 0); - // Вогнутая дуга к другой стенке - // Центр окружности (radius, radius), радиус radius. - // Рисуем дугу от 270 (-PI/2) до 180 (PI) градусов по часовой стрелке - shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true); - // Замыкаем в угол + shape.absarc(radius, radius, radius, -Math.PI / 2, -Math.PI, true); shape.lineTo(0, 0); - return shape; }; @@ -97,39 +88,41 @@ export const createBinGeometry = ( ): THREE.BufferGeometry => { const geometries: THREE.BufferGeometry[] = []; - // ДНО + // ДНО И ВНЕШНИЕ СТЕНКИ const floorShape = createRoundedRectShape(width, depth, radius); - const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false, curveSegments: 12 }); + const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); floorGeo.rotateX(-Math.PI / 2); geometries.push(floorGeo); - // ВНЕШНИЕ СТЕНКИ const outerShape = createRoundedRectShape(width, depth, radius); - const innerRadius = Math.max(0, radius - thickness); + const innerRadius = Math.max(0.1, radius - thickness); const innerWidth = width - (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); outerShape.holes.push(innerHole); } const wallHeight = height - thickness; - const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false, curveSegments: 12 }); + const wallGeo = new THREE.ExtrudeGeometry(outerShape, { depth: wallHeight, bevelEnabled: false }); wallGeo.rotateX(-Math.PI / 2); wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); - // ВНУТРЕННИЕ ПЕРЕГОРОДКИ И СКРУГЛЕНИЯ + // ВНУТРЕННИЕ ПЕРЕГОРОДКИ + // Мы просто верим сохраненным данным (p.min/p.max). Они должны быть корректны при создании. 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); let pWidth = 0, pDepth = 0, pX = 0, pY = 0; - // Размеры самой стенки if (p.axis === 'x') { pWidth = thickness; pDepth = lengthRatio * innerDepth; @@ -142,71 +135,44 @@ export const createBinGeometry = ( pY = (-innerDepth / 2) + (innerDepth * p.offset); } - // Создаем стенку - const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); // Чуть-чуть скругляем саму стенку, чтобы не была острой - const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 2 }); + const partShape = createRoundedRectShape(pWidth, pDepth, 0.1); + const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false }); partGeo.rotateX(-Math.PI / 2); partGeo.translate(pX, thickness, pY); geometries.push(partGeo); - // --- ДОБАВЛЕНИЕ ГАЛТЕЛЕЙ (FILLETS) --- - if (p.rounded && radius > 0.5) { - // Радиус скругления такой же, как у углов ящика, но не больше разумного предела - const filletR = Math.min(radius, 6); - const filletShape = createFilletShape(filletR); - const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 8 }; + // СКРУГЛЕНИЯ + if (p.rounded && radius > 1) { + const filletR = Math.min(radius, 5); + const filletShape = createConcaveFilletShape(filletR); + const filletExtrude = { depth: p.height, bevelEnabled: false }; - // Функция для создания и позиционирования одной галтели - const addFillet = (x: number, y: number, rotation: number) => { - const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrudeSettings); - geo.rotateX(-Math.PI / 2); // Положить на пол - geo.rotateY(rotation); // Повернуть в нужный угол - - // Корректировка позиции после вращения вокруг (0,0) - // Нам нужно сместить так, чтобы угол (0,0) галтели совпал с углом стыка + const addFillet = (x: number, y: number, rotY: number) => { + const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrude); + geo.rotateX(-Math.PI / 2); + geo.rotateY(rotY); geo.translate(x, thickness, y); geometries.push(geo); }; - const halfThick = thickness / 2; + const h = thickness / 2; if (p.axis === 'x') { - // Вертикальная стенка. Концы: Top (pMin) и Bottom (pMax) (в 2D координатах Y) - // Y координата начала: -innerDepth/2 + innerDepth * pMin - // Y координата конца: -innerDepth/2 + innerDepth * pMax - // X координата центра: pX - - const startY = (-innerDepth / 2) + (innerDepth * pMin); - const endY = (-innerDepth / 2) + (innerDepth * pMax); + const topY = (-innerDepth / 2) + (innerDepth * pMin); + addFillet(pX - h, topY, Math.PI); + addFillet(pX + h, topY, -Math.PI / 2); - // 4 Угла: - // 1. Start Left: X = pX - halfThick, Y = startY. Rotation: 0 (смотрит вправо-вверх? нет) - // Галтель рисуется в +X, +Y квадранте от 0,0. - // Нам нужно заполнить угол между стенкой (идет вниз) и перпендикуляром. - - // Start (Top in 2D view, actually Min Y in 3D logic here usually means "Back") - // Let's assume standard plan view: - // Min Y is "Top" edge visually in SVG usually 0. In 3D Z is Y. - - // Min End (Start of wall): - addFillet(pX - halfThick, startY, 0); // Left side, pointing towards +Z (down in visual) - addFillet(pX + halfThick, startY, -Math.PI/2); // Right side - - // Max End (End of wall): - addFillet(pX - halfThick, endY, Math.PI/2); // Left side - addFillet(pX + halfThick, endY, Math.PI); // Right side + const botY = (-innerDepth / 2) + (innerDepth * pMax); + addFillet(pX - h, botY, Math.PI / 2); + addFillet(pX + h, botY, 0); } else { - // Горизонтальная стенка - const startX = (-innerWidth / 2) + (innerWidth * pMin); - const endX = (-innerWidth / 2) + (innerWidth * pMax); + const leftX = (-innerWidth / 2) + (innerWidth * pMin); + addFillet(leftX, pY - h, 0); + addFillet(leftX, pY + h, -Math.PI / 2); - // Min End (Left side): - addFillet(startX, pY + halfThick, -Math.PI/2); - addFillet(startX, pY - halfThick, 0); - - // Max End (Right side): - addFillet(endX, pY + halfThick, Math.PI); - addFillet(endX, pY - halfThick, Math.PI/2); + const rightX = (-innerWidth / 2) + (innerWidth * pMax); + addFillet(rightX, pY - h, Math.PI / 2); + addFillet(rightX, pY + h, Math.PI); } } });