From c67755015e51ee64fdd756ac3c9d3aa2b3d911a6 Mon Sep 17 00:00:00 2001 From: chenjw28 <792430652@qq.com> Date: Thu, 30 Apr 2026 17:01:43 +0800 Subject: [PATCH] x --- src/api/v1/advanced_router.py | 63 +++++++-- src/utils/html_generator.py | 241 ++++++++++++++++++++-------------- 2 files changed, 198 insertions(+), 106 deletions(-) diff --git a/src/api/v1/advanced_router.py b/src/api/v1/advanced_router.py index 1743073..d4e94fc 100644 --- a/src/api/v1/advanced_router.py +++ b/src/api/v1/advanced_router.py @@ -4,6 +4,7 @@ import os from fastapi import APIRouter, Depends, HTTPException, Request from services.auth_service import get_current_active_user +from services.redis_task_manager import redis_task_manager from models.database import User from utils.logger import get_logger from api.routes import ( @@ -24,6 +25,16 @@ logger = get_logger(__name__) router = APIRouter() +async def _get_task_data(task_id: str) -> dict: + """从 Redis 优先查找任务,回退到旧版内存字典""" + task = await redis_task_manager.get_task(task_id) + if task: + return task + if task_id in tasks: + return tasks[task_id] + return None + + @router.post("/optimize-layout") async def optimize_cavity_layout( request: Request, @@ -140,10 +151,13 @@ async def ai_parting_surface_detect( body = await request.json() task_id = body.get("task_id") - if not task_id or task_id not in tasks: + if not task_id: + raise HTTPException(404, "缺少 task_id") + + task_data = await _get_task_data(task_id) + if not task_data: raise HTTPException(404, "任务不存在") - task_data = tasks[task_id] geometry_data = task_data.get("geometry_data") if not geometry_data: raise HTTPException(400, "该任务尚未完成几何分析") @@ -166,10 +180,13 @@ async def detect_undercuts( parting_direction = body.get("parting_direction", [0, 0, 1]) mold_size = body.get("mold_size", {"length": 300, "width": 300, "height": 200}) - if not task_id or task_id not in tasks: + if not task_id: + raise HTTPException(404, "缺少 task_id") + + task_data = await _get_task_data(task_id) + if not task_data: raise HTTPException(404, "任务不存在") - task_data = tasks[task_id] geometry_data = task_data.get("geometry_data") if not geometry_data: raise HTTPException(400, "该任务尚未完成几何分析") @@ -288,15 +305,25 @@ async def export_mold_results( formats = body.get("formats", ["step", "stl"]) components = body.get("components", ["cavity", "core"]) - if not task_id or task_id not in tasks: + if not task_id: + raise HTTPException(404, "缺少 task_id") + + task_data = await _get_task_data(task_id) + if not task_data: raise HTTPException(404, "任务不存在") - task_data = tasks[task_id] cavity_shapes = task_data.get("cavity_shapes") - if not cavity_shapes: - raise HTTPException(400, "该任务尚未完成模具生成或形状数据不可用") + filename = task_data.get("filename", f"mold_{task_id}") - base_filename = Path(task_data.get("filename", f"mold_{task_id}")).stem + if not cavity_shapes: + file_path = task_data.get("file_path") + if file_path and os.path.exists(str(file_path)): + cavity_shapes = await _reparse_stp_for_export(str(file_path), task_data.get("material", "ABS")) + + if not cavity_shapes: + raise HTTPException(400, "该任务尚未完成模具生成或形状数据不可用,请等待处理完成后再导出") + + base_filename = Path(filename).stem result = cad_exporter.export_mold_results( cavity_data=cavity_shapes, base_filename=base_filename, @@ -350,3 +377,21 @@ async def get_export_recommendations( """获取导出格式建议(UG/FreeCAD/SolidWorks)""" result = cad_exporter.get_export_recommendations(target) return {"status": "success", "data": result} + + +async def _reparse_stp_for_export(file_path: str, material: str = "ABS") -> dict: + """从 STP 文件重新生成模具型腔数据用于导出""" + try: + from core.stp_parser import STPParser + from core.mold_generator import MoldCavityGenerator + + stp_parser = STPParser() + shape = stp_parser.load_step_file(Path(file_path)) + mold_gen = MoldCavityGenerator(shrinkage_rate=0.005) + mold_gen.set_material(material) + cavity_result = mold_gen.generate_mold_cavities(shape) + logger.info(f"重新解析 STP 用于导出: {file_path}") + return cavity_result + except Exception as e: + logger.warning(f"重新解析 STP 导出失败: {e}") + return None diff --git a/src/utils/html_generator.py b/src/utils/html_generator.py index 501ec93..df0245d 100644 --- a/src/utils/html_generator.py +++ b/src/utils/html_generator.py @@ -241,10 +241,42 @@ class HTMLGenerator: y - Number(center[1] || 0), z - Number(center[2] || 0) ); + }} else {{ + normalized.push(0, 0, 0); }} }} return normalized; }} + + function filterDegenerateFaces(vertices, faces) {{ + const count = vertices.length / 3; + const faceCount = faces.length / 3; + const goodFaces = []; + for (let f = 0; f < faceCount; f++) {{ + const a = faces[f * 3]; + const b = faces[f * 3 + 1]; + const c = faces[f * 3 + 2]; + if (a >= 0 && a < count && b >= 0 && b < count && c >= 0 && c < count && + a !== b && b !== c && a !== c) {{ + goodFaces.push(a, b, c); + }} + }} + return goodFaces; + }} + + function getPartingDirectionFromData() {{ + if (cavityData?.metadata?.scheme_axis) {{ + const ax = cavityData.metadata.scheme_axis; + if (ax === 'X') return {{ axis: 'x', normal: [1, 0, 0], planeRot: [0, 0, Math.PI / 2] }}; + if (ax === 'Y') return {{ axis: 'y', normal: [0, 1, 0], planeRot: [Math.PI / 2, 0, 0] }}; + }} + if (cavityData?.parting?.axis) {{ + const ax = cavityData.parting.axis; + if (ax === 'X') return {{ axis: 'x', normal: [1, 0, 0], planeRot: [0, 0, Math.PI / 2] }}; + if (ax === 'Y') return {{ axis: 'y', normal: [0, 1, 0], planeRot: [Math.PI / 2, 0, 0] }}; + }} + return {{ axis: 'z', normal: [0, 0, 1], planeRot: [0, 0, 0] }}; + }} function fitCameraToScene() {{ const sceneBox = new THREE.Box3().setFromObject(scene); @@ -318,50 +350,56 @@ class HTMLGenerator: scene.add(productMesh); }} + // 获取分模方向 + const partingInfo = getPartingDirectionFromData(); + // 创建A板/定模(蓝色,分型面以上) - // 尝试从后端数据获取实际几何,否则使用简化Box if (cavityData && cavityData.mold_cavities && cavityData.mold_cavities.cavity && cavityData.mold_cavities.cavity.vertices) {{ const cavityVerts = cavityData.mold_cavities.cavity.vertices; const cavityFaces = cavityData.mold_cavities.cavity.faces; if (cavityVerts.length > 0 && cavityFaces.length > 0) {{ - const cavityGeometry = new THREE.BufferGeometry(); const positions = new Float32Array(normalizePositions(cavityVerts, centerOffset)); - const indices = new Uint32Array(toFlatArray(cavityFaces)); - cavityGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); - cavityGeometry.setIndex(new THREE.BufferAttribute(indices, 1)); - cavityGeometry.computeVertexNormals(); + const rawIndices = toFlatArray(cavityFaces); + const goodFaces = filterDegenerateFaces(positions, rawIndices); - const cavityMaterial = new THREE.MeshPhongMaterial({{ - color: 0x2196F3, - transparent: true, - opacity: 0.5, - wireframe: false, - side: THREE.DoubleSide - }}); - - cavityMesh = new THREE.Mesh(cavityGeometry, cavityMaterial); - scene.add(cavityMesh); - - // 添加线框 - const cavityWireframe = new THREE.WireframeGeometry(cavityGeometry); - const cavityLine = new THREE.LineSegments(cavityWireframe); - cavityLine.material.depthTest = false; - cavityLine.material.opacity = 0.6; - cavityLine.material.transparent = true; - cavityLine.material.color = new THREE.Color(0x1565C0); - cavityMesh.add(cavityLine); - - // 设置相机目标为型腔中心 - cavityGeometry.computeBoundingBox(); - const cavityCenter = new THREE.Vector3(); - cavityGeometry.boundingBox.getCenter(cavityCenter); - controls.target.set(cavityCenter.x, cavityCenter.y, cavityCenter.z); + if (goodFaces.length >= 3) {{ + const cavityGeometry = new THREE.BufferGeometry(); + cavityGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); + cavityGeometry.setIndex(goodFaces); + cavityGeometry.computeVertexNormals(); + + const cavityMaterial = new THREE.MeshPhongMaterial({{ + color: 0x2196F3, + transparent: true, + opacity: 0.5, + wireframe: false, + side: THREE.DoubleSide + }}); + + cavityMesh = new THREE.Mesh(cavityGeometry, cavityMaterial); + scene.add(cavityMesh); + + const cavityWireframe = new THREE.WireframeGeometry(cavityGeometry); + const cavityLine = new THREE.LineSegments(cavityWireframe); + cavityLine.material.depthTest = false; + cavityLine.material.opacity = 0.6; + cavityLine.material.transparent = true; + cavityLine.material.color = new THREE.Color(0x1565C0); + cavityMesh.add(cavityLine); + + cavityGeometry.computeBoundingBox(); + const cavityCenter = new THREE.Vector3(); + cavityGeometry.boundingBox.getCenter(cavityCenter); + controls.target.set(cavityCenter.x, cavityCenter.y, cavityCenter.z); + }} else {{ + createSimpleCavity(width, height, depth, partingInfo); + }} }} else {{ - createSimpleCavity(width, height, depth); + createSimpleCavity(width, height, depth, partingInfo); }} }} else {{ - createSimpleCavity(width, height, depth); + createSimpleCavity(width, height, depth, partingInfo); }} // 创建B板/动模(橙色,分型面以下) @@ -370,41 +408,50 @@ class HTMLGenerator: const coreFaces = cavityData.mold_cavities.core.faces; if (coreVerts.length > 0 && coreFaces.length > 0) {{ - const coreGeometry = new THREE.BufferGeometry(); const positions = new Float32Array(normalizePositions(coreVerts, centerOffset)); - const indices = new Uint32Array(toFlatArray(coreFaces)); - coreGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); - coreGeometry.setIndex(new THREE.BufferAttribute(indices, 1)); - coreGeometry.computeVertexNormals(); + const rawIndices = toFlatArray(coreFaces); + const goodFaces = filterDegenerateFaces(positions, rawIndices); - const coreMaterial = new THREE.MeshPhongMaterial({{ - color: 0xFF9800, - transparent: true, - opacity: 0.5, - wireframe: false, - side: THREE.DoubleSide - }}); - - coreMesh = new THREE.Mesh(coreGeometry, coreMaterial); - scene.add(coreMesh); - - // 添加线框 - const coreWireframe = new THREE.WireframeGeometry(coreGeometry); - const coreLine = new THREE.LineSegments(coreWireframe); - coreLine.material.depthTest = false; - coreLine.material.opacity = 0.6; - coreLine.material.transparent = true; - coreLine.material.color = new THREE.Color(0xE65100); - coreMesh.add(coreLine); + if (goodFaces.length >= 3) {{ + const coreGeometry = new THREE.BufferGeometry(); + coreGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); + coreGeometry.setIndex(goodFaces); + coreGeometry.computeVertexNormals(); + + const coreMaterial = new THREE.MeshPhongMaterial({{ + color: 0xFF9800, + transparent: true, + opacity: 0.5, + wireframe: false, + side: THREE.DoubleSide + }}); + + coreMesh = new THREE.Mesh(coreGeometry, coreMaterial); + scene.add(coreMesh); + + const coreWireframe = new THREE.WireframeGeometry(coreGeometry); + const coreLine = new THREE.LineSegments(coreWireframe); + coreLine.material.depthTest = false; + coreLine.material.opacity = 0.6; + coreLine.material.transparent = true; + coreLine.material.color = new THREE.Color(0xE65100); + coreMesh.add(coreLine); + }} else {{ + createSimpleCore(width, height, depth, partingInfo); + }} }} else {{ - createSimpleCore(width, height, depth); + createSimpleCore(width, height, depth, partingInfo); }} }} else {{ - createSimpleCore(width, height, depth); + createSimpleCore(width, height, depth, partingInfo); }} - // 创建分型面(红色平面) - const partingGeometry = new THREE.PlaneGeometry(width * 1.2, height * 1.2); + // 创建分型面(红色平面)- 按分模方向旋转 + const partingInfo2 = getPartingDirectionFromData(); + let planeW = width * 1.2, planeH = height * 1.2; + if (partingInfo2.axis === 'x') {{ planeW = depth * 1.2; planeH = height * 1.2; }} + else if (partingInfo2.axis === 'y') {{ planeW = width * 1.2; planeH = depth * 1.2; }} + const partingGeometry = new THREE.PlaneGeometry(planeW, planeH); const partingMaterial = new THREE.MeshBasicMaterial({{ color: 0xF44336, transparent: true, @@ -413,6 +460,7 @@ class HTMLGenerator: }}); partingMesh = new THREE.Mesh(partingGeometry, partingMaterial); + partingMesh.rotation.set(partingInfo2.planeRot[0], partingInfo2.planeRot[1], partingInfo2.planeRot[2]); partingMesh.position.set(0, 0, 0); scene.add(partingMesh); @@ -425,26 +473,33 @@ class HTMLGenerator: productLine.material.transparent = true; productLine.material.color = new THREE.Color(0x2E7D32); productMesh.add(productLine); + }} else if (cavityMesh || coreMesh) {{ + // 有型腔/型芯但没有产品模型时,补一个参考产品框 + const prodBox = new THREE.BoxGeometry(width * 0.85, height * 0.85, depth * 0.85); + const prodMat = new THREE.MeshPhongMaterial({{ + color: 0x4CAF50, transparent: true, opacity: 0.35, wireframe: false + }}); + productMesh = new THREE.Mesh(prodBox, prodMat); + scene.add(productMesh); }} }} // 创建简化型腔/A板(定模,分型面以上)— 备用 - function createSimpleCavity(width, height, depth) {{ - // A板:分型面(Z中心)以上的上半模 - const halfDepth = depth / 2; - const cavityGeometry = new THREE.BoxGeometry(width * 1.2, height * 1.2, halfDepth + 10); + function createSimpleCavity(width, height, depth, partingInfo) {{ + const pi = partingInfo || {{ axis: 'z', normal: [0, 0, 1] }}; + let boxW = width * 1.2, boxH = height * 1.2, boxD = depth / 2 + 10; + let pos = [0, 0, boxD / 2]; + let rot = [0, 0, 0]; + if (pi.axis === 'x') {{ boxW = depth / 2 + 10; boxH = height * 1.2; boxD = width * 1.2; pos = [boxW / 2, 0, 0]; rot = [0, 0, Math.PI / 2]; }} + else if (pi.axis === 'y') {{ boxW = width * 1.2; boxH = depth / 2 + 10; boxD = height * 1.2; pos = [0, boxH / 2, 0]; rot = [Math.PI / 2, 0, 0]; }} + const cavityGeometry = new THREE.BoxGeometry(boxW, boxH, boxD); const cavityMaterial = new THREE.MeshPhongMaterial({{ - color: 0x2196F3, - transparent: true, - opacity: 0.4, - wireframe: false + color: 0x2196F3, transparent: true, opacity: 0.4, wireframe: false }}); - cavityMesh = new THREE.Mesh(cavityGeometry, cavityMaterial); - // Z轴开模:A板放在分型面以上 - cavityMesh.position.set(0, 0, halfDepth / 2 + 5); + cavityMesh.position.set(pos[0], pos[1], pos[2]); + cavityMesh.rotation.set(rot[0], rot[1], rot[2]); scene.add(cavityMesh); - const cavityWireframe = new THREE.WireframeGeometry(cavityGeometry); const cavityLine = new THREE.LineSegments(cavityWireframe); cavityLine.material.depthTest = false; @@ -455,22 +510,21 @@ class HTMLGenerator: }} // 创建简化型芯/B板(动模,分型面以下)— 备用 - function createSimpleCore(width, height, depth) {{ - // B板:分型面(Z中心)以下的下半模 - const halfDepth = depth / 2; - const coreGeometry = new THREE.BoxGeometry(width * 1.2, height * 1.2, halfDepth + 10); + function createSimpleCore(width, height, depth, partingInfo) {{ + const pi = partingInfo || {{ axis: 'z', normal: [0, 0, 1] }}; + let boxW = width * 1.2, boxH = height * 1.2, boxD = depth / 2 + 10; + let pos = [0, 0, -boxD / 2]; + let rot = [0, 0, 0]; + if (pi.axis === 'x') {{ boxW = depth / 2 + 10; boxH = height * 1.2; boxD = width * 1.2; pos = [-boxW / 2, 0, 0]; rot = [0, 0, Math.PI / 2]; }} + else if (pi.axis === 'y') {{ boxW = width * 1.2; boxH = depth / 2 + 10; boxD = height * 1.2; pos = [0, -boxH / 2, 0]; rot = [Math.PI / 2, 0, 0]; }} + const coreGeometry = new THREE.BoxGeometry(boxW, boxH, boxD); const coreMaterial = new THREE.MeshPhongMaterial({{ - color: 0xFF9800, - transparent: true, - opacity: 0.4, - wireframe: false + color: 0xFF9800, transparent: true, opacity: 0.4, wireframe: false }}); - coreMesh = new THREE.Mesh(coreGeometry, coreMaterial); - // Z轴开模:B板放在分型面以下 - coreMesh.position.set(0, 0, -halfDepth / 2 - 5); + coreMesh.position.set(pos[0], pos[1], pos[2]); + coreMesh.rotation.set(rot[0], rot[1], rot[2]); scene.add(coreMesh); - const coreWireframe = new THREE.WireframeGeometry(coreGeometry); const coreLine = new THREE.LineSegments(coreWireframe); coreLine.material.depthTest = false; @@ -547,18 +601,11 @@ class HTMLGenerator: // 根据材料类型确定分模方向 function getPartingDirection() {{ - // 优先使用后端传递的 parting_direction - if (cavityData?.metadata?.parting_direction) {{ - return cavityData.metadata.parting_direction; - }} - if (cavityData?.manufacturing_info?.parting_direction) {{ - return cavityData.manufacturing_info.parting_direction; - }} - // 泡沫材料默认 Z 轴 - if (cavityData?.metadata?.is_foam) {{ - return 'Z'; - }} - // 默认 Z 轴 + if (cavityData?.metadata?.scheme_axis) return cavityData.metadata.scheme_axis; + if (cavityData?.parting?.axis) return cavityData.parting.axis; + if (cavityData?.metadata?.parting_direction) return cavityData.metadata.parting_direction; + if (cavityData?.manufacturing_info?.parting_direction) return cavityData.manufacturing_info.parting_direction; + if (cavityData?.metadata?.is_foam) return 'Z'; return 'Z'; }}