From eb8c5c48c787db3ba783097531c5e6e6c5605d87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A5=D0=B0=D0=BB=D0=B8=D0=BC=D0=BE=D0=B2=20=D0=A0=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BC?= Date: Sun, 11 Jan 2026 14:12:17 +0300 Subject: [PATCH] 5 --- src/components/LayoutStep.tsx | 104 ++++++++++++-------------- src/services/geometryGenerator.ts | 119 ++++++++++++++++++------------ 2 files changed, 118 insertions(+), 105 deletions(-) diff --git a/src/components/LayoutStep.tsx b/src/components/LayoutStep.tsx index 35ecd49..a7eeeb0 100644 --- a/src/components/LayoutStep.tsx +++ b/src/components/LayoutStep.tsx @@ -10,6 +10,8 @@ interface Props { type EditMode = 'lines' | 'cells'; type Axis = 'x' | 'y'; +type Limits = { min: number; max: number }; +type LimitMap = Record; type DragTarget = | { type: 'main'; axis: Axis; index: number } @@ -24,11 +26,9 @@ 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); @@ -61,71 +61,62 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { }; const selectedData = getSelectedPartition(); - // 1. Рассчитываем реальные (динамические) границы стенки, основываясь на её соседях. - // Это нужно, чтобы отрисовать стенку "обрезанной" по соседним стенкам. - const calculateWallLimits = (target: Partition, allParts: Partition[]) => { + // --- CORE LOGIC: Two-Pass Limit Calculation (Sync with 3D) --- + const calculateLimits = (target: { axis: Axis, offset: number }, allParts: Partition[], limitMap: LimitMap | null) => { let min = 0; let max = 1; - - // Середина стенки (используем сохраненные данные как подсказку центра) - const center = ((target.min ?? 0) + (target.max ?? 1)) / 2; + const mid = target.offset; allParts.forEach(p => { - // Ищем только перпендикулярные стенки if (p.axis === target.axis) return; - // Проверяем, пересекает ли соседка нашу линию движения. - // Соседка P (перпендикулярная) имеет offset по своей оси (которая совпадает с нашей осью движения) - // И занимает диапазон [p.min, p.max] по нашей перпендикулярной оси. - - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; + let pMin = p.min ?? 0; + let pMax = p.max ?? 1; + if (limitMap && limitMap[p.id]) { + pMin = limitMap[p.id].min; + pMax = limitMap[p.id].max; + } - // target.offset - это наша позиция. Попадает ли она в диапазон длины соседки? if (target.offset > pMin && target.offset < pMax) { - // Да, соседка стоит на нашем пути. - // Где она? Сзади (уменьшает min) или спереди (уменьшает max)? - if (p.offset < center) { - min = Math.max(min, p.offset); - } else if (p.offset > center) { - max = Math.min(max, p.offset); - } + if (p.offset < mid) min = Math.max(min, p.offset); + else if (p.offset > mid) max = Math.min(max, p.offset); } }); return { min, max }; }; - // 2. Рассчитываем "коробку" под курсором мыши для создания НОВОЙ стенки. - // Используем Raycasting: ищем ближайшие стенки во всех 4 направлениях. - const getCursorBox = (lx: number, ly: number, parts: Partition[]) => { + // Helper to get final limits for a list of parts + const getFinalLimitsMap = (parts: Partition[]): LimitMap => { + const map: LimitMap = {}; + // Pass 1 + parts.forEach(p => { map[p.id] = calculateLimits(p, parts, null); }); + // Pass 2 + parts.forEach(p => { map[p.id] = calculateLimits(p, parts, map); }); + return map; + }; + + // Calculate phantom box under cursor using Raycasting + const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => { let minX = 0, maxX = 1; let minY = 0, maxY = 1; - // Сначала рассчитываем актуальные границы для всех существующих стенок, - // чтобы знать их реальную длину. - const processedParts = parts.map(p => ({ - ...p, - ...calculateWallLimits(p, parts) // Добавляем min/max calculated - })); + parts.forEach(p => { + const { min: pMin, max: pMax } = limitMap[p.id]; + // Ignore collapsed walls + if (pMax - pMin < 0.001) return; - processedParts.forEach(p => { if (p.axis === 'x') { - // Вертикальная стенка (препятствие по X) - // Проверяем, перекрывает ли она наш Y (курсор) - if (ly > p.min && ly < p.max) { + if (ly > pMin && ly < pMax) { if (p.offset < lx) minX = Math.max(minX, p.offset); if (p.offset > lx) maxX = Math.min(maxX, p.offset); } } else { - // Горизонтальная стенка (препятствие по Y) - // Проверяем, перекрывает ли она наш X (курсор) - if (lx > p.min && lx < p.max) { + if (lx > pMin && lx < pMax) { 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 }; }; @@ -226,6 +217,7 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { setHoveredCell(cellIdx); const key = `${cellIdx.i}-${cellIdx.j}`; const parts = safePartitions[key] || []; + const limitMap = getFinalLimitsMap(parts); // Calculate limits once per move const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1]; const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1]; @@ -235,9 +227,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { let found = null; const SNAP = 0.05; - // Check hover over existing (using dynamic limits for precision) for (const p of parts) { - const { min, max } = calculateWallLimits(p, parts); + const { min, max } = limitMap[p.id]; + if (max - min < 0.001) continue; // Skip collapsed if (p.axis === 'x') { if (ly >= min && ly <= max && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p; } else { @@ -248,19 +240,18 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { if (found) { setHoveredPartition({ id: found.id, cellKey: key }); } else { - // Calculate Phantom Box - const box = getCursorBox(lx, ly, parts); + const box = getCursorBox(lx, ly, parts, limitMap); const distL = lx - box.minX; const distR = box.maxX - lx; const distT = ly - box.minY; const distB = box.maxY - ly; const minX = Math.min(distL, distR); const minY = Math.min(distT, distB); - const axis = minX < minY ? 'y' : 'x'; // Split shortest distance + const axis = minX < minY ? 'y' : 'x'; const width = box.maxX - box.minX; const height = box.maxY - box.minY; - if ((axis === 'y' && height > 0.1) || (axis === 'x' && width > 0.1)) { + if ((axis === 'y' && height > 0.05) || (axis === 'x' && width > 0.05)) { const offset = axis === 'x' ? lx : ly; const min = axis === 'x' ? box.minY : box.minX; const max = axis === 'x' ? box.maxY : box.maxX; @@ -326,6 +317,9 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { const realW = (x2 - x1) * drawerW; const realD = (y2 - y1) * drawerD; + // Calculate limits for rendering + const limitMap = getFinalLimitsMap(parts); + if (parts.length === 0) { const labelX = cellX + cellW / 2; const labelY = cellY + cellH / 2; @@ -346,30 +340,25 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { {isAnySelected && mode === 'cells' && } {parts.map(p => { - // Используем ту же логику Limits, что и для мыши, чтобы отрисовка совпадала с поведением - const { min, max } = calculateWallLimits(p, parts); - + const { min, max } = limitMap[p.id]; + if (max - min < 0.001) return null; // Don't render collapsed + let lx1, ly1, lx2, ly2; let dist1 = 0, dist2 = 0; let midX, midY; const isVertical = p.axis === 'x'; - - // Для расчета размеров нам нужны границы "коробки", в которой находится эта стенка - // Это по сути то же самое, что и getCursorBox, но для точки на стенке. - // Чтобы не дублировать код, используем пределы самой стенки и пределы перпендикулярного пространства if (isVertical) { const px = cellX + (cellW * p.offset); lx1 = px; lx2 = px; ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max); - // Чтобы найти расстояние до левой/правой стенки, берем центр этой стенки const cy = (min + max) / 2; - const box = getCursorBox(p.offset, cy, parts); // Используем Box-логику для поиска соседей + // Use already calculated limits for neighbors + const box = getCursorBox(p.offset, cy, parts, limitMap); dist1 = Math.abs((p.offset - box.minX) * realW) - wallThick; dist2 = Math.abs((box.maxX - p.offset) * realW) - wallThick; - midX = px; midY = (ly1 + ly2) / 2; } else { const py = cellY + (cellH * p.offset); @@ -377,11 +366,10 @@ export const LayoutStep: React.FC = ({ config, splits, onChange }) => { lx1 = cellX + (cellW * min); lx2 = cellX + (cellW * max); const cx = (min + max) / 2; - const box = getCursorBox(cx, p.offset, parts); + const box = getCursorBox(cx, p.offset, parts, limitMap); dist1 = Math.abs((p.offset - box.minY) * realD) - wallThick; dist2 = Math.abs((box.maxY - p.offset) * realD) - wallThick; - midX = (lx1 + lx2) / 2; midY = py; } diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index 96daedc..8d7b71f 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -2,6 +2,10 @@ import * as THREE from 'three'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; +// --- ТИПЫ ДЛЯ РАСЧЕТА --- +type Limits = { min: number; max: number }; +type LimitMap = Record; + export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => { const parts: GeneratedPart[] = []; const safeX = Array.isArray(splits?.x) ? splits.x : []; @@ -15,11 +19,15 @@ 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 < 10 || rawD < 10) 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; @@ -52,7 +60,8 @@ const createRoundedRectShape = (width: number, height: number, radius: number): 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); @@ -74,47 +83,40 @@ const createRoundedRectShape = (width: number, height: number, radius: number): return shape; }; +// Форма галтели (вогнутый угол) const createFilletShape = (radius: number): THREE.Shape => { const shape = new THREE.Shape(); shape.moveTo(0, 0); shape.lineTo(radius, 0); + // Рисуем вогнутую дугу в квадранте (+X, +Y) shape.absarc(radius, radius, radius, 1.5 * Math.PI, Math.PI, true); shape.lineTo(0, 0); return shape; }; -// --- УМНЫЙ РАСЧЕТ ГРАНИЦ (Fix overlapping walls) --- -const calculateDynamicLimits = (target: Partition, allParts: Partition[]) => { +// --- УМНЫЙ РАСЧЕТ ГРАНИЦ (ДВУХПРОХОДНЫЙ) --- +const calculateLimits = (target: Partition, allParts: Partition[], limitMap: LimitMap | null) => { let min = 0; let max = 1; - - // Центр текущей стенки (чтобы понять, в каком мы сегменте) - const mid = ((target.min ?? 0) + (target.max ?? 1)) / 2; + const mid = target.offset; // Используем offset как центр для определения стороны allParts.forEach(p => { - // Нас интересуют только ПЕРПЕНДИКУЛЯРНЫЕ стенки - if (p.axis === target.axis) return; + if (p.axis === target.axis) return; // Игнорируем параллельные - // Определяем, пересекает ли соседка путь нашей стенки - // Для этого соседка должна "покрывать" нашу координату offset - const pMin = p.min ?? 0; - const pMax = p.max ?? 1; - - // p.offset - это позиция соседки по нашей оси движения - // target.offset - это наша позиция по оси соседки - + // Получаем границы соседки. Если это второй проход, берем уже рассчитанные. + let pMin = p.min ?? 0; + let pMax = p.max ?? 1; + if (limitMap && limitMap[p.id]) { + pMin = limitMap[p.id].min; + pMax = limitMap[p.id].max; + } + + // Проверяем пересечение if (target.offset > pMin && target.offset < pMax) { - // Соседка стоит на пути. Где она? Сверху или снизу (слева или справа)? - if (p.offset < mid) { - // Соседка "перед" нами, это новая нижняя граница - min = Math.max(min, p.offset); - } else if (p.offset > mid) { - // Соседка "после" нас, это новая верхняя граница - max = Math.min(max, p.offset); - } + if (p.offset < mid) min = Math.max(min, p.offset); + else if (p.offset > mid) max = Math.min(max, p.offset); } }); - return { min, max }; }; @@ -123,30 +125,42 @@ 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, curveSegments: 16 }); 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, curveSegments: 16 }); wallGeo.rotateX(-Math.PI / 2); wallGeo.translate(0, thickness, 0); geometries.push(wallGeo); + // --- РАСЧЕТ ГРАНИЦ ПЕРЕГОРОДОК (2 ПРОХОДА) --- + const limitMap: LimitMap = {}; + // Проход 1: Считаем черновые границы + partitions.forEach(p => { limitMap[p.id] = calculateLimits(p, partitions, null); }); + // Проход 2: Уточняем границы, используя результаты первого прохода + partitions.forEach(p => { limitMap[p.id] = calculateLimits(p, partitions, limitMap); }); + + // --- ГЕНЕРАЦИЯ ПЕРЕГОРОДОК --- partitions.forEach(p => { - // ИСПОЛЬЗУЕМ ДИНАМИЧЕСКИЙ РАСЧЕТ ВМЕСТО p.min/p.max - const { min: pMin, max: pMax } = calculateDynamicLimits(p, partitions); + const { min: pMin, max: pMax } = limitMap[p.id]; + + // Если стенка схлопнулась в ноль или стала отрицательной - пропускаем + if (pMax - pMin < 0.01) return; const lengthRatio = pMax - pMin; const midRatio = pMin + (lengthRatio / 2); @@ -165,16 +179,20 @@ 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.2); + const partGeo = new THREE.ExtrudeGeometry(partShape, { depth: p.height, bevelEnabled: false, curveSegments: 4 }); partGeo.rotateX(-Math.PI / 2); partGeo.translate(pX, thickness, pY); geometries.push(partGeo); - if (p.rounded && radius > 0.5) { - const filletR = Math.min(radius, 6); + // --- ГАЛТЕЛИ (СКРУГЛЕНИЯ) --- + if (p.rounded && radius > 1) { + const filletR = Math.min(radius, 6, thickness * 2); + if (filletR < 0.5) return; + const filletShape = createFilletShape(filletR); - const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 8 }; + const filletExtrudeSettings = { depth: p.height, bevelEnabled: false, curveSegments: 12 }; const addFillet = (x: number, y: number, rotation: number) => { const geo = new THREE.ExtrudeGeometry(filletShape, filletExtrudeSettings); @@ -187,26 +205,33 @@ export const createBinGeometry = ( const halfThick = thickness / 2; if (p.axis === 'x') { + // ВЕРТИКАЛЬНАЯ СТЕНКА - Углы были правильные const startY = (-innerDepth / 2) + (innerDepth * pMin); const endY = (-innerDepth / 2) + (innerDepth * pMax); - addFillet(pX - halfThick, startY, 0); - addFillet(pX + halfThick, startY, -Math.PI/2); - addFillet(pX - halfThick, endY, Math.PI/2); - addFillet(pX + halfThick, endY, Math.PI); + addFillet(pX - halfThick, startY, 0); // Top-Left + addFillet(pX + halfThick, startY, -Math.PI/2); // Top-Right + addFillet(pX - halfThick, endY, Math.PI/2); // Bottom-Left + addFillet(pX + halfThick, endY, Math.PI); // Bottom-Right } else { + // ГОРИЗОНТАЛЬНАЯ СТЕНКА - ИСПРАВЛЕНЫ УГЛЫ const startX = (-innerWidth / 2) + (innerWidth * pMin); const endX = (-innerWidth / 2) + (innerWidth * pMax); - addFillet(startX, pY + halfThick, -Math.PI/2); - addFillet(startX, pY - halfThick, 0); - addFillet(endX, pY + halfThick, Math.PI); - addFillet(endX, pY - halfThick, Math.PI/2); + + // Left End + addFillet(startX, pY + halfThick, 0); // Top-Left + addFillet(startX, pY - halfThick, Math.PI/2); // Bottom-Left + + // Right End + addFillet(endX, pY + halfThick, -Math.PI/2); // Top-Right + addFillet(endX, pY - halfThick, Math.PI); // Bottom-Right } } }); const merged = mergeBufferGeometries(geometries); if (merged) merged.computeVertexNormals(); - return merged || new THREE.BoxGeometry(1, 1, 1); + // Возвращаем пустой бокс если ничего не сгенерировалось, чтобы не крашить + return merged || new THREE.BoxGeometry(0.1, 0.1, 0.1); }; export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {