This commit is contained in:
Халимов Рустам
2026-01-11 14:12:17 +03:00
parent 490adb8ac6
commit eb8c5c48c7
2 changed files with 118 additions and 105 deletions

View File

@@ -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<string, Limits>;
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 => {