7
This commit is contained in:
@@ -1,26 +1,20 @@
|
||||
import * as THREE from 'three';
|
||||
import { STLExporter } from 'three-stdlib';
|
||||
import { SUBTRACTION, Brush, Evaluator } from 'three-bvh-csg';
|
||||
import { mergeBufferGeometries } from 'three-stdlib';
|
||||
import { STLExporter, mergeBufferGeometries } from 'three-stdlib';
|
||||
import { AppConfig, LayoutSplits, GeneratedPart, Partition } from '../types';
|
||||
|
||||
// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
|
||||
// --- УТИЛИТЫ ---
|
||||
|
||||
// Очистка координат с округлением, чтобы убрать "фантомные" микро-ячейки
|
||||
const cleanPoints = (points: number[]) => {
|
||||
// Округляем до 2 знака (сантиметры/миллиметры), чтобы убрать дрожание float
|
||||
const rounded = points.map(p => parseFloat(p.toFixed(3))).sort((a, b) => a - b);
|
||||
// Убираем дубликаты
|
||||
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 : [];
|
||||
@@ -38,14 +32,13 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
|
||||
const y1 = uniqueY[j];
|
||||
const y2 = uniqueY[j+1];
|
||||
|
||||
// Фильтр: если ячейка меньше 2мм - это мусор
|
||||
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;
|
||||
|
||||
parts.push({
|
||||
@@ -65,7 +58,81 @@ export const calculateParts = (config: AppConfig, splits: LayoutSplits): Generat
|
||||
return parts;
|
||||
};
|
||||
|
||||
// --- ГЕНЕРАЦИЯ ГЕОМЕТРИИ (АТОМАРНЫЙ CSG) ---
|
||||
// --- ГЕНЕРАЦИЯ ГЕОМЕТРИИ (НАТИВНЫЙ THREE.JS) ---
|
||||
|
||||
// Создает 2D форму стены с отверстиями
|
||||
const createPerforatedShape = (length: number, height: number, config: AppConfig): THREE.Shape => {
|
||||
const shape = new THREE.Shape();
|
||||
|
||||
// 1. Внешний контур (CCW - Против часовой стрелки)
|
||||
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;
|
||||
|
||||
const { pattern, diameter, spacing } = config.perforation;
|
||||
const step = diameter + Math.max(2, spacing);
|
||||
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;
|
||||
|
||||
for (let j = 0; j < rows; j++) {
|
||||
const isOdd = j % 2 !== 0;
|
||||
const cy = startY + j * rowH;
|
||||
|
||||
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. Это критично для корректного вырезания.
|
||||
if (pattern === 'circle') {
|
||||
hole.absarc(cx, cy, r, 0, Math.PI * 2, true);
|
||||
}
|
||||
else if (pattern === 'hexagon') {
|
||||
for (let k = 0; k < 6; k++) {
|
||||
const angle = (-k * 60 + 90) * Math.PI / 180;
|
||||
const px = cx + r * Math.cos(angle);
|
||||
const py = cy + r * Math.sin(angle);
|
||||
if (k === 0) hole.moveTo(px, py); else hole.lineTo(px, py);
|
||||
}
|
||||
hole.closePath();
|
||||
}
|
||||
else if (pattern === 'triangle') {
|
||||
const rot = isOdd ? 180 : 0;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const angle = (-k * 120 + 90 + rot) * Math.PI / 180;
|
||||
const px = cx + r * Math.cos(angle);
|
||||
const py = cy + r * Math.sin(angle);
|
||||
if (k === 0) hole.moveTo(px, py); else hole.lineTo(px, py);
|
||||
}
|
||||
hole.closePath();
|
||||
}
|
||||
shape.holes.push(hole);
|
||||
}
|
||||
}
|
||||
return shape;
|
||||
};
|
||||
|
||||
export const createBinGeometry = (
|
||||
width: number, depth: number, height: number, thickness: number, radius: number = 0,
|
||||
@@ -73,117 +140,49 @@ export const createBinGeometry = (
|
||||
config?: AppConfig
|
||||
): THREE.BufferGeometry => {
|
||||
|
||||
const geometries: THREE.BufferGeometry[] = [];
|
||||
const safeConfig = config || { perforation: { enabled: false } } as AppConfig;
|
||||
const evaluator = new Evaluator();
|
||||
// Отключаем группы, чтобы результат был единым мешем с одним материалом
|
||||
evaluator.useGroups = false;
|
||||
|
||||
const finalGeometries: THREE.BufferGeometry[] = [];
|
||||
|
||||
// 1. ПОЛ (Всегда сплошной, без дырок)
|
||||
// 1. ПОЛ
|
||||
const floorGeo = new THREE.BoxGeometry(width, thickness, depth);
|
||||
floorGeo.translate(0, thickness / 2, 0); // Поднимаем, чтобы низ был на 0
|
||||
finalGeometries.push(floorGeo);
|
||||
|
||||
// --- ФУНКЦИЯ СОЗДАНИЯ "УМНОЙ" СТЕНКИ ---
|
||||
// Создает стену в локальных координатах, сверлит её, а потом ставит на место
|
||||
const createSmartWall = (wallLength: number, wallHeight: number, x: number, z: number, isVertical: boolean) => {
|
||||
|
||||
// 1. Создаем "заготовку" стены в центре координат (лежащую вдоль X)
|
||||
// Размеры: Длина=wallLength, Высота=wallHeight, Толщина=thickness
|
||||
const wallGeometry = new THREE.BoxGeometry(wallLength, wallHeight, thickness);
|
||||
|
||||
// Сразу создаем Brush для CSG
|
||||
let wallBrush = new Brush(wallGeometry);
|
||||
wallBrush.updateMatrixWorld();
|
||||
|
||||
// 2. Сверлим дырки (если включено)
|
||||
if (safeConfig.perforation?.enabled) {
|
||||
const { pattern, diameter, spacing } = safeConfig.perforation;
|
||||
const margin = 4; // Отступ от краев
|
||||
const step = diameter + Math.max(2, spacing);
|
||||
|
||||
// Рассчитываем сетку
|
||||
const cols = Math.floor((wallLength - margin * 2) / step);
|
||||
// Для сот (hexagon) шаг по вертикали меньше
|
||||
const rowH = pattern === 'circle' ? step : step * 0.866;
|
||||
const rows = Math.floor((wallHeight - margin * 2) / rowH);
|
||||
|
||||
if (cols > 0 && rows > 0) {
|
||||
const startX = -wallLength / 2 + (wallLength - cols * step) / 2 + diameter / 2;
|
||||
const startY = -wallHeight / 2 + (wallHeight - rows * rowH) / 2 + diameter / 2;
|
||||
|
||||
// Создаем один шаблон "сверла"
|
||||
const drillGeo = new THREE.CylinderGeometry(diameter / 2, diameter / 2, thickness * 2, 12);
|
||||
drillGeo.rotateX(Math.PI / 2); // Поворачиваем, чтобы сверлил сквозь стену (по оси Z локально)
|
||||
|
||||
// Собираем все сверла в одну геометрию (merge), чтобы вычесть 1 раз
|
||||
const drills: THREE.BufferGeometry[] = [];
|
||||
|
||||
for (let r = 0; r < rows; r++) {
|
||||
const isOdd = r % 2 !== 0;
|
||||
for (let c = 0; c < cols; c++) {
|
||||
let cx = startX + c * step;
|
||||
let cy = startY + r * rowH;
|
||||
|
||||
// Смещение для сот/треугольников
|
||||
if ((pattern === 'hexagon' || pattern === 'triangle') && isOdd) {
|
||||
cx += step / 2;
|
||||
}
|
||||
|
||||
// Проверка границ, чтобы не сверлить воздух или край
|
||||
if (cx > wallLength / 2 - margin || cx < -wallLength / 2 + margin) continue;
|
||||
|
||||
const drill = drillGeo.clone();
|
||||
drill.translate(cx, cy, 0);
|
||||
drills.push(drill);
|
||||
}
|
||||
}
|
||||
|
||||
if (drills.length > 0) {
|
||||
const mergedDrills = mergeBufferGeometries(drills);
|
||||
if (mergedDrills) {
|
||||
const drillBrush = new Brush(mergedDrills);
|
||||
drillBrush.updateMatrixWorld();
|
||||
// САМОЕ ГЛАВНОЕ: Вычитаем сверла из стены
|
||||
const result = evaluator.evaluate(wallBrush, drillBrush, SUBTRACTION);
|
||||
wallBrush = result; // Обновляем стену
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Позиционируем готовую (просверленную) стену в мире
|
||||
// Сейчас стена в центре (0,0,0) и смотрит вдоль X
|
||||
const resultGeo = wallBrush.geometry;
|
||||
|
||||
if (isVertical) {
|
||||
// Если стена вертикальная (вдоль Z), поворачиваем на 90 градусов вокруг Y
|
||||
resultGeo.rotateY(Math.PI / 2);
|
||||
}
|
||||
|
||||
// Перемещаем на финальную позицию
|
||||
// Y = thickness (пол) + wallHeight/2 (центр стены)
|
||||
resultGeo.translate(x, thickness + wallHeight / 2, z);
|
||||
|
||||
return resultGeo;
|
||||
};
|
||||
floorGeo.translate(0, thickness / 2, 0);
|
||||
geometries.push(floorGeo);
|
||||
|
||||
const wallH = height - thickness;
|
||||
const innerW = width - 2 * thickness;
|
||||
const innerD = depth - 2 * thickness;
|
||||
|
||||
// 2. СОЗДАЕМ ВНЕШНИЕ СТЕНЫ
|
||||
// Front (Спереди, вдоль X)
|
||||
finalGeometries.push(createSmartWall(innerW, wallH, 0, depth / 2 - thickness / 2, false));
|
||||
// Back (Сзади, вдоль X)
|
||||
finalGeometries.push(createSmartWall(innerW, wallH, 0, -depth / 2 + thickness / 2, false));
|
||||
// Left (Слева, вдоль Z) - полная глубина
|
||||
finalGeometries.push(createSmartWall(depth, wallH, -width / 2 + thickness / 2, 0, true));
|
||||
// Right (Справа, вдоль Z) - полная глубина
|
||||
finalGeometries.push(createSmartWall(depth, wallH, width / 2 - thickness / 2, 0, true));
|
||||
// Хелпер: создает стену, экструдит, вращает и ставит на место
|
||||
const addWall = (len: number, h: number, x: number, z: number, isVert: boolean) => {
|
||||
// 1. 2D форма
|
||||
const shape = createPerforatedShape(len, h, safeConfig);
|
||||
// 2. Экструзия (Толщина)
|
||||
const geo = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false });
|
||||
|
||||
// 3. Центрирование геометрии (чтобы вращать вокруг центра)
|
||||
geo.center();
|
||||
|
||||
// 3. СОЗДАЕМ ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
||||
// 4. Поворот и Позиционирование
|
||||
if (isVert) {
|
||||
geo.rotateY(Math.PI / 2);
|
||||
}
|
||||
// Поднимаем на пол (thickness + h/2)
|
||||
geo.translate(x, thickness + h/2, z);
|
||||
|
||||
geometries.push(geo);
|
||||
};
|
||||
|
||||
// 2. ВНЕШНИЕ СТЕНЫ
|
||||
// Front (вдоль X)
|
||||
addWall(innerW, wallH, 0, depth/2 - thickness/2, false);
|
||||
// Back (вдоль X)
|
||||
addWall(innerW, wallH, 0, -depth/2 + thickness/2, false);
|
||||
// Left (вдоль Z)
|
||||
addWall(depth, wallH, -width/2 + thickness/2, 0, true);
|
||||
// Right (вдоль Z)
|
||||
addWall(depth, wallH, width/2 - thickness/2, 0, true);
|
||||
|
||||
// 3. ВНУТРЕННИЕ ПЕРЕГОРОДКИ
|
||||
let partitions: Partition[] = [];
|
||||
if (Array.isArray(splits)) partitions = splits;
|
||||
else if (splits && splits.partitions) partitions = getAllPartitions(splits);
|
||||
@@ -191,8 +190,6 @@ 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;
|
||||
@@ -200,65 +197,53 @@ export const createBinGeometry = (
|
||||
let zPos = 0;
|
||||
let isVert = false;
|
||||
|
||||
if (p.axis === 'x') {
|
||||
// Вертикальная перегородка (Вдоль Z)
|
||||
if (p.axis === 'x') { // Vert (Z-axis)
|
||||
isVert = true;
|
||||
len = (pMax - pMin) * innerD;
|
||||
// X: смещение от центра
|
||||
xPos = (-innerW / 2) + (p.offset * innerW);
|
||||
// Z: центр отрезка
|
||||
const midZRatio = (pMin + pMax) / 2;
|
||||
zPos = (-innerD / 2) + (midZRatio * innerD);
|
||||
} else {
|
||||
// Горизонтальная перегородка (Вдоль X)
|
||||
xPos = (-innerW/2) + (p.offset * innerW);
|
||||
const midZ = (pMin + pMax) / 2;
|
||||
zPos = (-innerD/2) + (midZ * innerD);
|
||||
} else { // Horiz (X-axis)
|
||||
isVert = false;
|
||||
len = (pMax - pMin) * innerW;
|
||||
// X: центр отрезка
|
||||
const midXRatio = (pMin + pMax) / 2;
|
||||
xPos = (-innerW / 2) + (midXRatio * innerW);
|
||||
// Z: смещение от центра
|
||||
zPos = (-innerD / 2) + (p.offset * innerD);
|
||||
const midX = (pMin + pMax) / 2;
|
||||
xPos = (-innerW/2) + (midX * innerW);
|
||||
zPos = (-innerD/2) + (p.offset * innerD);
|
||||
}
|
||||
|
||||
// Генерируем, сверлим и ставим перегородку
|
||||
const partGeo = createSmartWall(len, p.height, xPos, zPos, isVert);
|
||||
finalGeometries.push(partGeo);
|
||||
addWall(len, p.height, xPos, zPos, isVert);
|
||||
|
||||
// --- СКРУГЛЕНИЯ (СТОЛБИКИ) ---
|
||||
// Добавляем цилиндры в торцы, если включено скругление
|
||||
if (p.rounded && radius > 0) {
|
||||
const r = Math.min(radius, 5);
|
||||
const filletGeo = new THREE.CylinderGeometry(r, r, p.height, 12);
|
||||
filletGeo.translate(0, p.height / 2 + thickness, 0); // Ставим на пол
|
||||
const cylGeo = new THREE.CylinderGeometry(r, r, p.height, 12);
|
||||
// Поднимаем пивот в центр (так как addWall центрирует)
|
||||
// Или просто позиционируем как есть
|
||||
|
||||
const addFillet = (fx: number, fz: number) => {
|
||||
const c = cylGeo.clone();
|
||||
c.translate(fx, thickness + p.height/2, fz);
|
||||
geometries.push(c);
|
||||
};
|
||||
|
||||
// Определяем координаты концов стенки
|
||||
if (isVert) {
|
||||
const zStart = (-innerD / 2) + (pMin * innerD);
|
||||
const zEnd = (-innerD / 2) + (pMax * innerD);
|
||||
|
||||
const f1 = filletGeo.clone(); f1.translate(xPos, 0, zStart); finalGeometries.push(f1);
|
||||
const f2 = filletGeo.clone(); f2.translate(xPos, 0, zEnd); finalGeometries.push(f2);
|
||||
const zStart = zPos - len/2;
|
||||
const zEnd = zPos + len/2;
|
||||
addFillet(xPos, zStart);
|
||||
addFillet(xPos, zEnd);
|
||||
} else {
|
||||
const xStart = (-innerW / 2) + (pMin * innerW);
|
||||
const xEnd = (-innerW / 2) + (pMax * innerW);
|
||||
|
||||
const f1 = filletGeo.clone(); f1.translate(xStart, 0, zPos); finalGeometries.push(f1);
|
||||
const f2 = filletGeo.clone(); f2.translate(xEnd, 0, zPos); finalGeometries.push(f2);
|
||||
const xStart = xPos - len/2;
|
||||
const xEnd = xPos + len/2;
|
||||
addFillet(xStart, zPos);
|
||||
addFillet(xEnd, zPos);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 4. СЛИЯНИЕ ВСЕГО В ОДИН MESH
|
||||
// Простое слияние геометрий (без CSG Union, так как детали просто соприкасаются)
|
||||
// Это намного быстрее и не вызывает артефактов
|
||||
const finalMerged = mergeBufferGeometries(finalGeometries);
|
||||
|
||||
if (finalMerged) {
|
||||
finalMerged.computeVertexNormals();
|
||||
return finalMerged;
|
||||
}
|
||||
|
||||
return new THREE.BoxGeometry(1, 1, 1);
|
||||
// 4. СЛИЯНИЕ
|
||||
const merged = mergeBufferGeometries(geometries);
|
||||
if (merged) merged.computeVertexNormals();
|
||||
return merged || new THREE.BoxGeometry(1, 1, 1);
|
||||
};
|
||||
|
||||
export const generateSTL = (mesh: THREE.Object3D): Uint8Array | string => {
|
||||
|
||||
Reference in New Issue
Block a user