13
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import React, { useRef, useState, useMemo, useEffect } from 'react';
|
||||
import React, { useRef, useState, useMemo } from 'react';
|
||||
import { AppConfig, LayoutSplits, Partition } from '../types';
|
||||
import { Grid, MousePointer2, Trash2, RotateCcw, X, Move, Settings2 } from 'lucide-react';
|
||||
|
||||
@@ -10,8 +10,6 @@ interface Props {
|
||||
|
||||
type EditMode = 'lines' | 'cells';
|
||||
type Axis = 'x' | 'y';
|
||||
type Limits = { min: number; max: number };
|
||||
type LimitMap = Record<string, Limits>;
|
||||
|
||||
type DragTarget =
|
||||
| { type: 'main'; axis: Axis; index: number }
|
||||
@@ -61,58 +59,29 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
};
|
||||
const selectedData = getSelectedPartition();
|
||||
|
||||
// --- SOLVER (Robust) ---
|
||||
const solveWallLimits = (parts: Partition[]): LimitMap => {
|
||||
const limits: LimitMap = {};
|
||||
parts.forEach(p => { limits[p.id] = { min: 0, max: 1 }; });
|
||||
|
||||
// 4 прохода для надежности
|
||||
for (let pass = 0; pass < 4; pass++) {
|
||||
parts.forEach(target => {
|
||||
let newMin = 0;
|
||||
let newMax = 1;
|
||||
const center = target.offset;
|
||||
|
||||
parts.forEach(obstacle => {
|
||||
if (target.id === obstacle.id || target.axis === obstacle.axis) return;
|
||||
|
||||
const obsMin = limits[obstacle.id].min;
|
||||
const obsMax = limits[obstacle.id].max;
|
||||
|
||||
// Epsilon для надежного пересечения
|
||||
const EPS = 0.001;
|
||||
if (target.offset >= obsMin - EPS && target.offset <= obsMax + EPS) {
|
||||
if (obstacle.offset < center) newMin = Math.max(newMin, obstacle.offset);
|
||||
else if (obstacle.offset > center) newMax = Math.min(newMax, obstacle.offset);
|
||||
}
|
||||
});
|
||||
limits[target.id] = { min: newMin, max: newMax };
|
||||
});
|
||||
}
|
||||
return limits;
|
||||
};
|
||||
|
||||
// --- RAYCASTING (Find empty box) ---
|
||||
const getCursorBox = (lx: number, ly: number, parts: Partition[], limitMap: LimitMap) => {
|
||||
// --- RAYCASTING (Надежный поиск коробки) ---
|
||||
// Находит ближайшие стенки во всех 4 направлениях
|
||||
const getCursorBox = (lx: number, ly: number, parts: Partition[]) => {
|
||||
let minX = 0, maxX = 1;
|
||||
let minY = 0, maxY = 1;
|
||||
|
||||
parts.forEach(p => {
|
||||
const { min: pMin, max: pMax } = limitMap[p.id];
|
||||
// Игнорируем схлопнутые стенки
|
||||
if (pMax - pMin < 0.001) return;
|
||||
|
||||
const EPS = 0.005; // Чуть больше допуск для мыши
|
||||
// Используем сохраненные границы (они теперь достоверны)
|
||||
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);
|
||||
}
|
||||
@@ -121,15 +90,16 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
return { minX, maxX, minY, maxY };
|
||||
};
|
||||
|
||||
// --- NEIGHBORS (For dimensions) ---
|
||||
const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[], limitMap: LimitMap) => {
|
||||
// Поиск соседей для размеров (Та же логика, что Raycasting)
|
||||
const getNeighborOffsets = (offset: number, crossPos: number, axis: Axis, parts: Partition[]) => {
|
||||
let min = 0;
|
||||
let max = 1;
|
||||
const EPS = 0.001;
|
||||
const EPS = 0.005;
|
||||
|
||||
parts.forEach(p => {
|
||||
if (p.axis === axis) {
|
||||
const { min: pMin, max: pMax } = limitMap[p.id];
|
||||
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);
|
||||
@@ -220,7 +190,7 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
setPhantomPartition(null);
|
||||
setHoveredCell(null);
|
||||
|
||||
// 1. Find Global Cell
|
||||
// Find Cell
|
||||
let cellIdx = null;
|
||||
for (let i = 0; i < sortedX.length - 1; i++) {
|
||||
if (nx >= sortedX[i] && nx <= sortedX[i+1]) {
|
||||
@@ -236,7 +206,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
setHoveredCell(cellIdx);
|
||||
const key = `${cellIdx.i}-${cellIdx.j}`;
|
||||
const parts = safePartitions[key] || [];
|
||||
const limitMap = solveWallLimits(parts);
|
||||
|
||||
const cx1 = sortedX[cellIdx.i]; const cx2 = sortedX[cellIdx.i+1];
|
||||
const cy1 = sortedY[cellIdx.j]; const cy2 = sortedY[cellIdx.j+1];
|
||||
@@ -244,54 +213,43 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
const lx = (nx - cx1) / cw;
|
||||
const ly = (ny - cy1) / ch;
|
||||
|
||||
// Check hover over existing walls
|
||||
// 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 { min, max } = limitMap[p.id];
|
||||
const pMin = p.min ?? 0;
|
||||
const pMax = p.max ?? 1;
|
||||
if (p.axis === 'x') {
|
||||
if (ly >= min && ly <= max && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
|
||||
if (ly >= pMin && ly <= pMax && Math.abs(lx - p.offset) < SNAP * (aspectRatio > 1 ? 1 : aspectRatio)) found = p;
|
||||
} else {
|
||||
if (lx >= min && lx <= max && Math.abs(ly - p.offset) < SNAP * (aspectRatio < 1 ? 1 : 1/aspectRatio)) found = p;
|
||||
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 {
|
||||
// --- PHANTOM LOGIC ---
|
||||
const box = getCursorBox(lx, ly, parts, limitMap);
|
||||
// --- FIND BOX ---
|
||||
const box = getCursorBox(lx, ly, parts);
|
||||
|
||||
// Локальные координаты относительно "коробки" (0..1)
|
||||
const localBoxW = box.maxX - box.minX;
|
||||
const localBoxH = box.maxY - box.minY;
|
||||
|
||||
const relX = (lx - box.minX) / localBoxW;
|
||||
const relY = (ly - box.minY) / localBoxH;
|
||||
const boxW = (box.maxX - box.minX) * realCellW;
|
||||
const boxH = (box.maxY - box.minY) * realCellH;
|
||||
|
||||
// Определяем ось на основе позиции мыши в "коробке"
|
||||
// Если мы близко к краям - хотим отрезать кусок (перпендикуляр)
|
||||
// Если в центре - делим длинную сторону
|
||||
|
||||
const edgeThreshold = 0.2; // 20% от края
|
||||
let newAxis: Axis;
|
||||
// Default axis based on longest side
|
||||
let newAxis: Axis = boxW > boxH ? 'x' : 'y';
|
||||
|
||||
const nearLeftRight = relX < edgeThreshold || relX > (1 - edgeThreshold);
|
||||
const nearTopBottom = relY < edgeThreshold || relY > (1 - edgeThreshold);
|
||||
// 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 (nearLeftRight && !nearTopBottom) {
|
||||
newAxis = 'x'; // Рядом с боковой стенкой -> Вертикальная
|
||||
} else if (nearTopBottom && !nearLeftRight) {
|
||||
newAxis = 'y'; // Рядом с верхней/нижней -> Горизонтальная
|
||||
} else {
|
||||
// В центре или в углу -> делим длинную сторону (учитывая реальные мм)
|
||||
const realBoxW = localBoxW * (cw * drawerW);
|
||||
const realBoxH = localBoxH * (ch * drawerD);
|
||||
newAxis = realBoxW > realBoxH ? 'x' : 'y';
|
||||
}
|
||||
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' && localBoxW > 0.05) || (newAxis === 'y' && localBoxH > 0.05);
|
||||
const valid = (newAxis === 'x' && (box.maxX - box.minX) > 0.05) || (newAxis === 'y' && (box.maxY - box.minY) > 0.05);
|
||||
|
||||
if (valid) {
|
||||
const offset = newAxis === 'x' ? lx : ly;
|
||||
@@ -359,8 +317,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
const realW = (x2 - x1) * drawerW;
|
||||
const realD = (y2 - y1) * drawerD;
|
||||
|
||||
const limitMap = solveWallLimits(parts);
|
||||
|
||||
if (parts.length === 0) {
|
||||
const labelX = cellX + cellW / 2;
|
||||
const labelY = cellY + cellH / 2;
|
||||
@@ -381,8 +337,9 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
{isAnySelected && mode === 'cells' && <rect x={cellX} y={cellY} width={cellW} height={cellH} fill="transparent" stroke="#a855f7" strokeWidth="2" className="pointer-events-none opacity-50"/>}
|
||||
|
||||
{parts.map(p => {
|
||||
const { min, max } = limitMap[p.id];
|
||||
if (max - min < 0.001) return null;
|
||||
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;
|
||||
@@ -392,22 +349,20 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
if (isVertical) {
|
||||
const px = cellX + (cellW * p.offset);
|
||||
lx1 = px; lx2 = px;
|
||||
ly1 = cellY + (cellH * min); ly2 = cellY + (cellH * max);
|
||||
ly1 = cellY + (cellH * pMin); ly2 = cellY + (cellH * pMax);
|
||||
|
||||
const cy = (min + max) / 2;
|
||||
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;
|
||||
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 * min); lx2 = cellX + (cellW * max);
|
||||
lx1 = cellX + (cellW * pMin); lx2 = cellX + (cellW * pMax);
|
||||
|
||||
const cx = (min + max) / 2;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -463,14 +418,12 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
|
||||
return (
|
||||
<div className="flex w-full h-full bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl">
|
||||
|
||||
{/* LEFT: WORKSPACE */}
|
||||
<div className="flex-1 flex flex-col relative min-w-0">
|
||||
<div className="flex justify-between items-center p-3 border-b border-slate-800 bg-slate-900 z-10 shrink-0">
|
||||
<h2 className="text-sm font-bold flex items-center gap-2 text-primary"><Grid size={18} /> Редактор</h2>
|
||||
<div className="flex bg-slate-800 p-1 rounded-lg border border-slate-700">
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
@@ -501,7 +454,6 @@ export const LayoutStep: React.FC<Props> = ({ config, splits, onChange }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* RIGHT: SIDEBAR */}
|
||||
{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>
|
||||
|
||||
@@ -2,48 +2,6 @@ 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<string, Limits>;
|
||||
|
||||
// --- SOLVER: Итеративный расчет границ (Улучшенный) ---
|
||||
const solveWallLimits = (partitions: Partition[]): LimitMap => {
|
||||
const limits: LimitMap = {};
|
||||
// 1. Инициализация
|
||||
partitions.forEach(p => { limits[p.id] = { min: 0, max: 1 }; });
|
||||
|
||||
// 2. Итерации (4 прохода для стабилизации сложных вложений)
|
||||
for (let pass = 0; pass < 4; pass++) {
|
||||
partitions.forEach(target => {
|
||||
let newMin = 0;
|
||||
let newMax = 1;
|
||||
const center = target.offset;
|
||||
|
||||
partitions.forEach(obstacle => {
|
||||
if (target.id === obstacle.id) return;
|
||||
if (target.axis === obstacle.axis) return; // Параллельные не влияют
|
||||
|
||||
// Берем границы препятствия с предыдущего шага
|
||||
const obsMin = limits[obstacle.id].min;
|
||||
const obsMax = limits[obstacle.id].max;
|
||||
|
||||
// Важно: используем >= и <= с небольшим запасом для надежности
|
||||
// Пересекает ли препятствие линию нашей стенки?
|
||||
if (target.offset >= obsMin - 0.001 && target.offset <= obsMax + 0.001) {
|
||||
// Препятствие на пути. Где оно относительно центра нашей стенки?
|
||||
if (obstacle.offset < center) {
|
||||
newMin = Math.max(newMin, obstacle.offset);
|
||||
} else if (obstacle.offset > center) {
|
||||
newMax = Math.min(newMax, obstacle.offset);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
limits[target.id] = { min: newMin, max: newMax };
|
||||
});
|
||||
}
|
||||
return limits;
|
||||
};
|
||||
|
||||
export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => {
|
||||
const parts: GeneratedPart[] = [];
|
||||
const safeX = Array.isArray(splits?.x) ? splits.x : [];
|
||||
@@ -130,6 +88,7 @@ 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 });
|
||||
floorGeo.rotateX(-Math.PI / 2);
|
||||
@@ -151,11 +110,12 @@ export const createBinGeometry = (
|
||||
wallGeo.translate(0, thickness, 0);
|
||||
geometries.push(wallGeo);
|
||||
|
||||
// Используем солвер для расчета реальных границ
|
||||
const limitMap = solveWallLimits(partitions);
|
||||
|
||||
// ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
||||
// Мы просто верим сохраненным данным (p.min/p.max). Они должны быть корректны при создании.
|
||||
partitions.forEach(p => {
|
||||
const { min: pMin, max: pMax } = limitMap[p.id];
|
||||
const pMin = p.min ?? 0;
|
||||
const pMax = p.max ?? 1;
|
||||
|
||||
if (pMax - pMin < 0.01) return;
|
||||
|
||||
const lengthRatio = pMax - pMin;
|
||||
@@ -181,6 +141,7 @@ export const createBinGeometry = (
|
||||
partGeo.translate(pX, thickness, pY);
|
||||
geometries.push(partGeo);
|
||||
|
||||
// СКРУГЛЕНИЯ
|
||||
if (p.rounded && radius > 1) {
|
||||
const filletR = Math.min(radius, 5);
|
||||
const filletShape = createConcaveFilletShape(filletR);
|
||||
|
||||
Reference in New Issue
Block a user