diff --git a/src/services/geometryGenerator.ts b/src/services/geometryGenerator.ts index a8f228f..314a610 100644 --- a/src/services/geometryGenerator.ts +++ b/src/services/geometryGenerator.ts @@ -2,19 +2,21 @@ import * as THREE from 'three'; import { STLExporter, mergeBufferGeometries } from 'three-stdlib'; import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types'; -// --- УТИЛИТЫ --- +// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ --- +// Очистка координат (убирает фантомные ячейки и дрожание) const cleanPoints = (points: number[]) => { const rounded = points.map(p => Math.round(p * 1000) / 1000).sort((a, b) => a - b); return [...new Set(rounded)]; }; +// Сбор всех перегородок в плоский список const getAllPartitions = (splits: LayoutSplits): Partition[] => { if (!splits || !splits.partitions) return []; return Object.values(splits.partitions).flat(); }; -// Функция для визуализации (шаг 3) +// --- ВИЗУАЛИЗАЦИЯ (Цветные кубики для шага 3) --- export const calculateParts = (config: AppConfig, splits: LayoutSplits): GeneratedPart[] => { const parts: GeneratedPart[] = []; const safeX = Array.isArray(splits?.x) ? splits.x : []; @@ -35,18 +37,21 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat const rawW = (x2 - x1) * config.drawer.width; const rawD = (y2 - y1) * config.drawer.depth; + // Фильтр слишком мелких ячеек if (rawW < 2 || rawD < 2) continue; const rawX = x1 * config.drawer.width; const rawY = y1 * config.drawer.depth; - const gap = config.wallThickness / 2 + 0.1; + + // Зазор для визуализации (чтобы блоки не слипались) + const gap = config.wallThickness / 2 + 0.15; parts.push({ id: `part-${partCounter}`, name: `Ячейка ${partCounter}`, width: Math.max(1, rawW - gap * 2), depth: Math.max(1, rawD - gap * 2), - height: config.drawer.height, + height: config.drawer.height - config.wallThickness, // Высота без пола x: rawX + gap, y: rawY + gap, color: `hsl(${(partCounter * 137.5) % 360}, 70%, 50%)`, @@ -58,35 +63,39 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat return parts; }; -// --- ГЕНЕРАЦИЯ ГЕОМЕТРИИ (НАТИВНЫЙ THREE.JS) --- +// --- ГЕНЕРАЦИЯ ГЕОМЕТРИИ (NATIVE THREE.JS) --- -// Создает 2D форму стены с отверстиями +// Функция создания 2D формы с дырками const createPerforatedShape = (length: number, height: number, config: AppConfig): THREE.Shape => { const shape = new THREE.Shape(); - // 1. Внешний контур (CCW - Против часовой стрелки) + // 1. Внешний контур: ПРОТИВ ЧАСОВОЙ (CCW) + // (0,0) -> (L,0) -> (L,H) -> (0,H) -> (0,0) shape.moveTo(0, 0); shape.lineTo(length, 0); shape.lineTo(length, height); shape.lineTo(0, height); shape.lineTo(0, 0); - // Если перфорация выключена - if (!config.perforation?.enabled || length < 10 || height < 10) return shape; + // Если перфорация выключена или стенка слишком маленькая для дырок + if (!config.perforation?.enabled || length < 15 || height < 15) return shape; const { pattern, diameter, spacing } = config.perforation; const step = diameter + Math.max(2, spacing); - const margin = 4; + const margin = 4; // Отступ от краев стенки + // Эффективная зона для отверстий const effW = length - margin * 2; const effH = height - margin * 2; if (effW <= diameter || effH <= diameter) return shape; + // Расчет сетки const rowH = pattern === 'circle' ? step : step * 0.866; const cols = Math.floor(effW / step); const rows = Math.floor(effH / rowH); + // Центрирование сетки const startX = margin + (effW - (cols - 1) * step) / 2; const startY = margin + (effH - (rows - 1) * rowH) / 2; @@ -96,21 +105,25 @@ const createPerforatedShape = (length: number, height: number, config: AppConfig for (let i = 0; i < cols; i++) { let cx = startX + i * step; + // Смещение для сот/треугольников if ((pattern === 'hexagon' || pattern === 'triangle') && isOdd) cx += step / 2; + // Проверка, что отверстие не вылезает за пределы if (cx - diameter/2 < margin || cx + diameter/2 > length - margin || cy - diameter/2 < margin || cy + diameter/2 > height - margin) continue; const hole = new THREE.Path(); const r = diameter / 2; - // 2. Отверстия (CW - По часовой стрелке). - // aClockwise = true. Это критично для корректного вырезания. + // 2. ВНУТРЕННИЕ ОТВЕРСТИЯ: ПО ЧАСОВОЙ (CW) + // Параметр aClockwise = true в absarc. Это критично! + if (pattern === 'circle') { hole.absarc(cx, cy, r, 0, Math.PI * 2, true); } else if (pattern === 'hexagon') { for (let k = 0; k < 6; k++) { + // Угол идет в минус -> CW направление const angle = (-k * 60 + 90) * Math.PI / 180; const px = cx + r * Math.cos(angle); const py = cy + r * Math.sin(angle); @@ -121,6 +134,7 @@ const createPerforatedShape = (length: number, height: number, config: AppConfig else if (pattern === 'triangle') { const rot = isOdd ? 180 : 0; for (let k = 0; k < 3; k++) { + // Угол идет в минус -> CW направление const angle = (-k * 120 + 90 + rot) * Math.PI / 180; const px = cx + r * Math.cos(angle); const py = cy + r * Math.sin(angle); @@ -134,6 +148,46 @@ const createPerforatedShape = (length: number, height: number, config: AppConfig return shape; }; +// Форма пола (без дырок) +const createFloorShape = (width: number, depth: number, radius: number): THREE.Shape => { + const shape = new THREE.Shape(); + const x = -width / 2; + const y = -depth / 2; + const r = Math.min(radius, width / 2 - 0.1, depth / 2 - 0.1); + + if (r <= 0.1) { + shape.moveTo(x, y); + shape.lineTo(x + width, y); + shape.lineTo(x + width, y + depth); + shape.lineTo(x, y + depth); + shape.lineTo(x, y); + } else { + shape.moveTo(x, y + r); + shape.lineTo(x, y + depth - r); + shape.quadraticCurveTo(x, y + depth, x + r, y + depth); + shape.lineTo(x + width - r, y + depth); + shape.quadraticCurveTo(x + width, y + depth, x + width, y + depth - r); + shape.lineTo(x + width, y + r); + shape.quadraticCurveTo(x + width, y, x + width - r, y); + shape.lineTo(x + r, y); + shape.quadraticCurveTo(x, y, x, y + r); + } + return shape; +}; + +// Форма скругления (Cylinder sector) +const createFilletShape = (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; +}; + +// --- СБОРКА ВСЕЙ ГЕОМЕТРИИ --- + export const createBinGeometry = ( width: number, depth: number, height: number, thickness: number, radius: number = 0, splits: LayoutSplits | Partition[] = [], @@ -144,42 +198,47 @@ export const createBinGeometry = ( const safeConfig = config || { perforation: { enabled: false } } as AppConfig; // 1. ПОЛ - const floorGeo = new THREE.BoxGeometry(width, thickness, depth); - floorGeo.translate(0, thickness / 2, 0); + const floorShape = createFloorShape(width, depth, radius); + const floorGeo = new THREE.ExtrudeGeometry(floorShape, { depth: thickness, bevelEnabled: false }); + floorGeo.rotateX(-Math.PI / 2); // Кладем на землю geometries.push(floorGeo); const wallH = height - thickness; const innerW = width - 2 * thickness; const innerD = depth - 2 * thickness; - // Хелпер: создает стену, экструдит, вращает и ставит на место - const addWall = (len: number, h: number, x: number, z: number, isVert: boolean) => { - // 1. 2D форма - const shape = createPerforatedShape(len, h, safeConfig); - // 2. Экструзия (Толщина) + // Функция для создания, экструзии и установки стены + const addWall = (length: number, h: number, x: number, z: number, isVertical: boolean) => { + // 1. Создаем 2D чертеж с дырками + const shape = createPerforatedShape(length, h, safeConfig); + + // 2. Выдавливаем (получаем толщину) const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false }); - // 3. Центрирование геометрии (чтобы вращать вокруг центра) + // 3. Центрируем геометрию в локальных осях (чтобы вращать вокруг центра) geo.center(); + // Теперь координаты стены от -Len/2 до +Len/2 - // 4. Поворот и Позиционирование - if (isVert) { + // 4. Поворачиваем если нужно + if (isVertical) { geo.rotateY(Math.PI / 2); } - // Поднимаем на пол (thickness + h/2) + + // 5. Ставим на место + // Y: поднимаем на пол (thickness) + половина высоты (так как мы центрировали по Y) geo.translate(x, thickness + h/2, z); geometries.push(geo); }; // 2. ВНЕШНИЕ СТЕНЫ - // Front (вдоль X) + // Front (Вдоль X) addWall(innerW, wallH, 0, depth/2 - thickness/2, false); - // Back (вдоль X) + // Back (Вдоль X) addWall(innerW, wallH, 0, -depth/2 + thickness/2, false); - // Left (вдоль Z) + // Left (Вдоль Z, полная глубина) addWall(depth, wallH, -width/2 + thickness/2, 0, true); - // Right (вдоль Z) + // Right (Вдоль Z, полная глубина) addWall(depth, wallH, width/2 - thickness/2, 0, true); // 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ @@ -190,6 +249,8 @@ export const createBinGeometry = ( partitions.forEach(p => { const pMin = p.min ?? 0; const pMax = p.max ?? 1; + + // Защита от мусорных данных if (Math.abs(pMax - pMin) < 0.001) return; let len = 0; @@ -197,55 +258,64 @@ export const createBinGeometry = ( let zPos = 0; let isVert = false; - if (p.axis === 'x') { // Vert (Z-axis) + // Рассчитываем позицию центра перегородки + if (p.axis === 'x') { // Vert (Вдоль Z) isVert = true; len = (pMax - pMin) * innerD; + // X позиция: от левого края innerW xPos = (-innerW/2) + (p.offset * innerW); + // Z центр: середина отрезка const midZ = (pMin + pMax) / 2; zPos = (-innerD/2) + (midZ * innerD); - } else { // Horiz (X-axis) + } else { // Horiz (Вдоль X) isVert = false; len = (pMax - pMin) * innerW; + // X центр: середина отрезка const midX = (pMin + pMax) / 2; xPos = (-innerW/2) + (midX * innerW); + // Z позиция: от заднего края innerD zPos = (-innerD/2) + (p.offset * innerD); } + // Создаем стенку addWall(len, p.height, xPos, zPos, isVert); // --- СКРУГЛЕНИЯ (СТОЛБИКИ) --- + // Добавляем цилиндры в торцы перегородок, если включено if (p.rounded && radius > 0) { const r = Math.min(radius, 5); - const cylGeo = new THREE.CylinderGeometry(r, r, p.height, 12); - // Поднимаем пивот в центр (так как addWall центрирует) - // Или просто позиционируем как есть + const cylGeo = new THREE.CylinderGeometry(r, r, p.height, 16); + // Центрируем по высоте, чтобы translate работал так же как для стен + // (по умолчанию cylinder pivot в центре, так что всё ок) - const addFillet = (fx: number, fz: number) => { + const addCyl = (cx: number, cz: number) => { const c = cylGeo.clone(); - c.translate(fx, thickness + p.height/2, fz); + c.translate(cx, thickness + p.height/2, cz); geometries.push(c); }; if (isVert) { const zStart = zPos - len/2; const zEnd = zPos + len/2; - addFillet(xPos, zStart); - addFillet(xPos, zEnd); + addCyl(xPos, zStart); + addCyl(xPos, zEnd); } else { const xStart = xPos - len/2; const xEnd = xPos + len/2; - addFillet(xStart, zPos); - addFillet(xEnd, zPos); + addCyl(xStart, zPos); + addCyl(xEnd, zPos); } } }); // 4. СЛИЯНИЕ const merged = mergeBufferGeometries(geometries); - if (merged) merged.computeVertexNormals(); + if (merged) merged.computeVertexNormals(); // Исправляет тени и "прозрачность" return merged || new THREE.BoxGeometry(1, 1, 1); }; +// --- ЭКСПОРТ --- + export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => { const exporter = new STLExporter(); const result = exporter.parse(mesh, { binary: true });