// 流程图仿真工具脚本 document.addEventListener('DOMContentLoaded', function() { // 全局变量 const canvas = document.getElementById('flow-canvas'); const ctx = canvas.getContext('2d'); let shapes = []; let connections = []; let selectedShape = null; let draggedShape = null; let dragOffset = { x: 0, y: 0 }; let isDragging = false; let isPanning = false; let lastMousePos = { x: 0, y: 0 }; let zoomLevel = 1; let panOffset = { x: 0, y: 0 }; let isConnecting = false; let connectingFrom = null; let connectingToPoint = { x: 0, y: 0 }; let simulationRunning = false; let simulationInterval = null; let simulationTime = 0; // 仿真时间(分钟) let simulationSpeed = 1; // 仿真速度倍率 let particles = []; // 用于动画的粒子 let nextShapeId = 1; let nextConnectionId = 1; let hoveredConnectionPoint = null; let selectedConnection = null; // 常量 const SHAPE_TYPES = { START: 'start', PROCESS: 'process', TRANSPORT: 'transport', ENDPOINT: 'endpoint' }; const SHAPE_SIZES = { [SHAPE_TYPES.START]: { width: 160, height: 80 }, [SHAPE_TYPES.PROCESS]: { width: 160, height: 80 }, [SHAPE_TYPES.TRANSPORT]: { width: 140, height: 80 }, [SHAPE_TYPES.ENDPOINT]: { width: 160, height: 80 } }; const SHAPE_COLORS = { [SHAPE_TYPES.START]: '#ff0000', [SHAPE_TYPES.PROCESS]: '#4CAF50', [SHAPE_TYPES.TRANSPORT]: '#FF9800', [SHAPE_TYPES.ENDPOINT]: '#9C27B0' }; const SHAPE_STATUS = { IDLE: '等待上一步', WORKING: '工作中', WAITING: '等待下一步' }; const GRID_SIZE = 20; const SIMULATION_TICK = 0.1; // 仿真时间步长(分钟) // 初始化 initCanvas(); setupEventListeners(); updateCanvasSize(); updateStatus('就绪'); // 初始化画布 function initCanvas() { updateCanvasSize(); window.addEventListener('resize', updateCanvasSize); } // 更新画布大小 function updateCanvasSize() { const container = canvas.parentElement; canvas.width = container.clientWidth; canvas.height = container.clientHeight; drawCanvas(); } // 设置事件监听器 function setupEventListeners() { // 画布事件 canvas.addEventListener('mousedown', handleCanvasMouseDown); canvas.addEventListener('mousemove', handleCanvasMouseMove); canvas.addEventListener('mouseup', handleCanvasMouseUp); canvas.addEventListener('dblclick', handleCanvasDblClick); canvas.addEventListener('wheel', handleCanvasWheel); // 拖拽图形事件 setupDragAndDrop(); // 按钮事件 document.getElementById('start-simulation').addEventListener('click', startSimulation); document.getElementById('stop-simulation').addEventListener('click', stopSimulation); document.getElementById('reset-simulation').addEventListener('click', resetSimulation); document.getElementById('save-project').addEventListener('click', showSaveProjectDialog); document.getElementById('load-project').addEventListener('click', showLoadProjectDialog); document.getElementById('zoom-in').addEventListener('click', zoomIn); document.getElementById('zoom-out').addEventListener('click', zoomOut); // 添加步骤按钮事件 document.getElementById('add-step').addEventListener('click', function() { const stepsContainer = document.getElementById('steps-container'); const stepItems = stepsContainer.querySelectorAll('.step-item'); const newIndex = stepItems.length; // 创建新步骤 const newStep = { name: `步骤${newIndex + 1}`, startTime: 0, workTime: 1.0 }; // 添加到UI addStepToUI(newStep, newIndex); // 更新总耗时 updateTotalTime(); }); // 模态框关闭按钮 document.querySelectorAll('.close').forEach(btn => { btn.addEventListener('click', function() { this.closest('.modal').style.display = 'none'; }); }); // 模态框表单提交事件 document.getElementById('shape-form').addEventListener('submit', function(e) { e.preventDefault(); saveShapeData(); }); document.getElementById('connection-form').addEventListener('submit', function(e) { e.preventDefault(); saveConnectionData(); }); document.getElementById('file-form').addEventListener('submit', function(e) { e.preventDefault(); handleFileSubmit(); }); // 取消按钮事件 document.getElementById('cancel-edit').addEventListener('click', function() { document.getElementById('shape-modal').style.display = 'none'; }); document.getElementById('cancel-connection-edit').addEventListener('click', function() { document.getElementById('connection-modal').style.display = 'none'; }); document.getElementById('cancel-file-action').addEventListener('click', function() { document.getElementById('file-modal').style.display = 'none'; }); // 删除连接按钮 document.getElementById('delete-connection').addEventListener('click', deleteSelectedConnection); } // 设置拖拽功能 function setupDragAndDrop() { const shapeItems = document.querySelectorAll('.shape-item'); shapeItems.forEach(item => { item.addEventListener('dragstart', function(e) { e.dataTransfer.setData('shape-type', this.getAttribute('data-shape-type')); e.dataTransfer.effectAllowed = 'copy'; }); }); canvas.addEventListener('dragover', function(e) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }); canvas.addEventListener('drop', function(e) { e.preventDefault(); const shapeType = e.dataTransfer.getData('shape-type'); if (shapeType) { const rect = canvas.getBoundingClientRect(); const x = (e.clientX - rect.left - panOffset.x) / zoomLevel; const y = (e.clientY - rect.top - panOffset.y) / zoomLevel; createNewShape(shapeType, x, y); } }); } // 处理画布鼠标按下事件 function handleCanvasMouseDown(e) { const mousePos = getMousePos(e); // 检查是否点击在连接点上 hoveredConnectionPoint = getConnectionPointAt(mousePos.x, mousePos.y); if (hoveredConnectionPoint) { // 开始连接操作 isConnecting = true; connectingFrom = hoveredConnectionPoint.shape; connectingToPoint = mousePos; return; } // 检查是否点击在连接线上 const clickedConnection = getConnectionAt(mousePos.x, mousePos.y); if (clickedConnection) { selectedConnection = clickedConnection; selectedShape = null; drawCanvas(); return; } // 检查是否点击在形状上 const clickedShape = getShapeAt(mousePos.x, mousePos.y); if (clickedShape) { // 选择并准备拖动形状 selectedShape = clickedShape; selectedConnection = null; draggedShape = clickedShape; isDragging = true; dragOffset.x = mousePos.x - clickedShape.x; dragOffset.y = mousePos.y - clickedShape.y; } else { // 点击在空白区域,取消选择并准备平移 selectedShape = null; selectedConnection = null; isPanning = true; lastMousePos = mousePos; } drawCanvas(); } // 处理画布鼠标移动事件 function handleCanvasMouseMove(e) { const mousePos = getMousePos(e); if (isConnecting) { // 更新连接目标点 connectingToPoint = mousePos; drawCanvas(); return; } if (isDragging && draggedShape) { // 移动形状 draggedShape.x = snapToGrid(mousePos.x - dragOffset.x); draggedShape.y = snapToGrid(mousePos.y - dragOffset.y); drawCanvas(); return; } if (isPanning) { // 平移画布 panOffset.x += (mousePos.x - lastMousePos.x) * zoomLevel; panOffset.y += (mousePos.y - lastMousePos.y) * zoomLevel; lastMousePos = mousePos; drawCanvas(); return; } // 检查鼠标是否悬停在连接点上 const connectionPoint = getConnectionPointAt(mousePos.x, mousePos.y); if (connectionPoint) { canvas.style.cursor = 'crosshair'; hoveredConnectionPoint = connectionPoint; } else { // 检查是否悬停在形状上 const hoverShape = getShapeAt(mousePos.x, mousePos.y); canvas.style.cursor = hoverShape ? 'move' : 'default'; hoveredConnectionPoint = null; } drawCanvas(); } // 处理画布鼠标松开事件 function handleCanvasMouseUp(e) { if (isConnecting) { const mousePos = getMousePos(e); const targetShape = getShapeAt(mousePos.x, mousePos.y); if (targetShape && targetShape !== connectingFrom) { // 创建新连接 createConnection(connectingFrom, targetShape); } isConnecting = false; connectingFrom = null; } isDragging = false; draggedShape = null; isPanning = false; drawCanvas(); } // 处理画布双击事件 function handleCanvasDblClick(e) { if (simulationRunning) return; const mousePos = getMousePos(e); const clickedShape = getShapeAt(mousePos.x, mousePos.y); if (clickedShape) { // 打开编辑对话框 openShapeEditor(clickedShape); } } // 添加键盘事件监听删除功能 window.addEventListener('keydown', function(e) { if (e.key === 'Delete' && selectedShape && !simulationRunning) { deleteSelectedShape(); } }); // 删除选定的形状 function deleteSelectedShape() { if (!selectedShape) return; // 删除所有与该形状相关的连接 connections = connections.filter(conn => { const isConnected = conn.fromId === selectedShape.id || conn.toId === selectedShape.id; if (isConnected) { // 更新其他形状的输入输出 shapes.forEach(shape => { if (conn.fromId === selectedShape.id && conn.toId === shape.id) { // 从目标形状的输入中移除 shape.inputs = shape.inputs.filter(id => id !== selectedShape.id); } if (conn.toId === selectedShape.id && conn.fromId === shape.id) { // 从源形状的输出中移除 shape.outputs = shape.outputs.filter(id => id !== selectedShape.id); } }); } return !isConnected; }); // 删除形状 shapes = shapes.filter(shape => shape.id !== selectedShape.id); // 重新计算产能 calculateAllThroughputs(); // 更新状态 selectedShape = null; updateStatus('已删除形状'); drawCanvas(); } // 处理画布滚轮事件 function handleCanvasWheel(e) { e.preventDefault(); const mousePos = getMousePos(e); const zoomFactor = e.deltaY < 0 ? 1.1 : 0.9; // 以鼠标位置为中心进行缩放 zoomCanvas(zoomFactor, mousePos); } // 获取鼠标在画布中的位置 function getMousePos(e) { const rect = canvas.getBoundingClientRect(); return { x: (e.clientX - rect.left - panOffset.x) / zoomLevel, y: (e.clientY - rect.top - panOffset.y) / zoomLevel }; } // 缩放画布 function zoomCanvas(factor, center) { const oldZoom = zoomLevel; zoomLevel *= factor; // 限制缩放范围 zoomLevel = Math.max(0.2, Math.min(zoomLevel, 5)); if (center) { // 调整偏移量,使缩放以鼠标位置为中心 panOffset.x = center.x * zoomLevel - center.x * oldZoom + panOffset.x; panOffset.y = center.y * zoomLevel - center.y * oldZoom + panOffset.y; } // 更新缩放显示 document.getElementById('zoom-level').textContent = Math.round(zoomLevel * 100) + '%'; drawCanvas(); } // 放大 function zoomIn() { const center = { x: canvas.width / 2, y: canvas.height / 2 }; zoomCanvas(1.1, center); } // 缩小 function zoomOut() { const center = { x: canvas.width / 2, y: canvas.height / 2 }; zoomCanvas(0.9, center); } // 创建新形状 function createNewShape(shapeType, x, y) { const size = SHAPE_SIZES[shapeType]; // 创建新形状对象 const newShape = { id: nextShapeId++, type: shapeType, x: snapToGrid(x - size.width / 2), y: snapToGrid(y - size.height / 2), width: size.width, height: size.height, name: getDefaultShapeName(shapeType), params: getDefaultParams(shapeType), inputs: [], outputs: [], calculatedThroughput: 0, processedItems: 0, buffer: 0, status: SHAPE_STATUS.IDLE, realTimeThroughput: 0, // 实时产能 lastProcessTime: 0, // 上次处理时间 waitingForNext: false, // 是否等待下一步 waitingForPrevious: true // 是否等待上一步 }; shapes.push(newShape); selectedShape = newShape; // 打开形状编辑对话框 openShapeEditor(newShape); drawCanvas(); return newShape; } // 获取默认形状名称 function getDefaultShapeName(shapeType) { switch(shapeType) { case SHAPE_TYPES.START: return '开始 ' + nextShapeId; case SHAPE_TYPES.PROCESS: return '普通机构 ' + nextShapeId; case SHAPE_TYPES.TRANSPORT: return '运输机构 ' + nextShapeId; case SHAPE_TYPES.ENDPOINT: return '收料机构 ' + nextShapeId; default: return '未命名 ' + nextShapeId; } } // 获取默认参数 function getDefaultParams(shapeType) { switch(shapeType) { case SHAPE_TYPES.START: return { outputRate: 5.0 // 每分钟产出数量 }; case SHAPE_TYPES.PROCESS: return { batchSize: 1, steps: [ { name: "步骤1", startTime: 0, workTime: 1.0 } ] }; case SHAPE_TYPES.TRANSPORT: return { transportTime: 2.0, transportBatch: 1, transportCount: 1 }; case SHAPE_TYPES.ENDPOINT: return { collectionCapacity: 100 }; default: return {}; } } // 打开形状编辑对话框 function openShapeEditor(shape) { const modal = document.getElementById('shape-modal'); const titleElement = document.getElementById('modal-title'); const nameInput = document.getElementById('shape-name'); const processParams = document.getElementById('process-params'); const transportParams = document.getElementById('transport-params'); const endpointParams = document.getElementById('endpoint-params'); // 设置标题 titleElement.textContent = '编辑' + getShapeTypeLabel(shape.type); // 设置名称 nameInput.value = shape.name; // 隐藏所有参数区域 processParams.style.display = 'none'; transportParams.style.display = 'none'; endpointParams.style.display = 'none'; // 根据形状类型显示对应参数 switch(shape.type) { case SHAPE_TYPES.PROCESS: processParams.style.display = 'block'; document.getElementById('batch-size').value = shape.params.batchSize; // 清空步骤容器 const stepsContainer = document.getElementById('steps-container'); stepsContainer.innerHTML = ''; // 添加现有步骤 if (shape.params.steps && shape.params.steps.length > 0) { shape.params.steps.forEach((step, index) => { addStepToUI(step, index); }); } else { // 如果没有步骤,添加一个默认步骤 addStepToUI({name: "步骤1", startTime: 0, workTime: 1.0}, 0); } // 计算并显示总耗时 updateTotalTime(); break; case SHAPE_TYPES.TRANSPORT: transportParams.style.display = 'block'; document.getElementById('transport-time').value = shape.params.transportTime; document.getElementById('transport-batch').value = shape.params.transportBatch; document.getElementById('transport-count').value = shape.params.transportCount; break; case SHAPE_TYPES.ENDPOINT: endpointParams.style.display = 'block'; document.getElementById('collection-capacity').value = shape.params.collectionCapacity; break; } // 显示对话框 modal.style.display = 'block'; } // 获取形状类型标签 function getShapeTypeLabel(type) { switch(type) { case SHAPE_TYPES.START: return '开始'; case SHAPE_TYPES.PROCESS: return '普通机构'; case SHAPE_TYPES.TRANSPORT: return '运输机构'; case SHAPE_TYPES.ENDPOINT: return '收料机构'; default: return '未知类型'; } } // 添加步骤到UI function addStepToUI(step, index) { const stepsContainer = document.getElementById('steps-container'); const stepItem = document.createElement('div'); stepItem.className = 'step-item'; stepItem.dataset.index = index; // 创建步骤内容 stepItem.innerHTML = `
步骤 ${index + 1}
`; stepsContainer.appendChild(stepItem); // 添加删除步骤事件 const removeBtn = stepItem.querySelector('.step-remove'); removeBtn.addEventListener('click', function() { removeStep(parseInt(this.dataset.index)); }); // 添加输入变化事件以更新总耗时 const inputs = stepItem.querySelectorAll('input[type="number"]'); inputs.forEach(input => { input.addEventListener('input', updateTotalTime); }); } // 删除步骤 function removeStep(index) { const stepsContainer = document.getElementById('steps-container'); const stepItems = stepsContainer.querySelectorAll('.step-item'); // 至少保留一个步骤 if (stepItems.length <= 1) { alert('至少需要保留一个步骤'); return; } // 删除指定步骤 stepItems[index].remove(); // 重新编号步骤 const remainingSteps = stepsContainer.querySelectorAll('.step-item'); remainingSteps.forEach((item, i) => { item.dataset.index = i; item.querySelector('.step-title').textContent = `步骤 ${i + 1}`; item.querySelector('.step-remove').dataset.index = i; // 更新输入框ID const inputs = item.querySelectorAll('input'); inputs[0].id = `step-name-${i}`; inputs[1].id = `step-start-${i}`; inputs[2].id = `step-work-${i}`; }); // 更新总耗时 updateTotalTime(); } // 计算并更新总耗时 function updateTotalTime() { const stepsContainer = document.getElementById('steps-container'); const stepItems = stepsContainer.querySelectorAll('.step-item'); let maxEndTime = 0; stepItems.forEach((item, index) => { const startTime = parseFloat(document.getElementById(`step-start-${index}`).value) || 0; const workTime = parseFloat(document.getElementById(`step-work-${index}`).value) || 0; const endTime = startTime + workTime; if (endTime > maxEndTime) { maxEndTime = endTime; } }); document.getElementById('total-time').textContent = maxEndTime.toFixed(1); } // 保存形状数据 function saveShapeData() { if (!selectedShape) return; // 获取基本信息 selectedShape.name = document.getElementById('shape-name').value; // 根据形状类型获取特定参数 switch(selectedShape.type) { case SHAPE_TYPES.PROCESS: selectedShape.params.batchSize = parseInt(document.getElementById('batch-size').value) || 1; // 获取所有步骤数据 const stepsContainer = document.getElementById('steps-container'); const stepItems = stepsContainer.querySelectorAll('.step-item'); const steps = []; stepItems.forEach((item, index) => { steps.push({ name: document.getElementById(`step-name-${index}`).value, startTime: parseFloat(document.getElementById(`step-start-${index}`).value) || 0, workTime: parseFloat(document.getElementById(`step-work-${index}`).value) || 0.1 }); }); selectedShape.params.steps = steps; break; case SHAPE_TYPES.TRANSPORT: selectedShape.params.transportTime = parseFloat(document.getElementById('transport-time').value) || 2.0; selectedShape.params.transportBatch = parseInt(document.getElementById('transport-batch').value) || 1; selectedShape.params.transportCount = parseInt(document.getElementById('transport-count').value) || 1; break; case SHAPE_TYPES.ENDPOINT: selectedShape.params.collectionCapacity = parseInt(document.getElementById('collection-capacity').value) || 100; break; } // 计算产能 calculateThroughput(selectedShape); // 关闭对话框 document.getElementById('shape-modal').style.display = 'none'; // 重绘画布 drawCanvas(); } // 创建连接 function createConnection(fromShape, toShape) { // 检查是否已有相同的连接 const existingConnection = connections.find(conn => conn.fromId === fromShape.id && conn.toId === toShape.id); if (existingConnection) { alert('连接已存在'); return; } // 创建新连接 const connection = { id: nextConnectionId++, fromId: fromShape.id, toId: toShape.id, delay: 0, startPosition: hoveredConnectionPoint ? hoveredConnectionPoint.position : 'right', endPosition: 'left', // 默认连接到左侧 particles: [], // 动态粒子 controlPoints: [] // 用于贝塞尔曲线的控制点 }; // 自动计算合适的控制点,使曲线更自然 updateConnectionControlPoints(connection); // 更新形状的输入输出关系 fromShape.outputs.push(toShape.id); toShape.inputs.push(fromShape.id); connections.push(connection); // 重新计算所有产能 calculateAllThroughputs(); // 重绘画布 drawCanvas(); } // 更新连接的控制点 function updateConnectionControlPoints(connection) { const fromShape = shapes.find(s => s.id === connection.fromId); const toShape = shapes.find(s => s.id === connection.toId); if (!fromShape || !toShape) return; // 获取连接起点和终点 const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); // 计算两点间距离 const dx = endPoint.x - startPoint.x; const dy = endPoint.y - startPoint.y; const distance = Math.sqrt(dx * dx + dy * dy); // 设置控制点,使曲线更自然 const controlOffset = Math.min(distance * 0.4, 150); // 根据起点和终点位置设置控制点 let cp1x, cp1y, cp2x, cp2y; // 从起点位置确定第一控制点方向 const dir1 = getDirectionFromPosition(connection.startPosition); cp1x = startPoint.x + dir1.x * controlOffset; cp1y = startPoint.y + dir1.y * controlOffset; // 从终点位置确定第二控制点方向 const dir2 = getDirectionFromPosition(connection.endPosition); cp2x = endPoint.x + dir2.x * controlOffset; cp2y = endPoint.y + dir2.y * controlOffset; connection.controlPoints = [ { x: cp1x, y: cp1y }, { x: cp2x, y: cp2y } ]; } // 根据位置获取方向向量 function getDirectionFromPosition(position) { switch(position) { case 'left': return { x: -1, y: 0 }; case 'right': return { x: 1, y: 0 }; case 'top': return { x: 0, y: -1 }; case 'bottom': return { x: 0, y: 1 }; default: return { x: 1, y: 0 }; } } // 获取连接点坐标 function getConnectionPointCoordinates(shape, position) { switch(position) { case 'left': return { x: shape.x, y: shape.y + shape.height / 2 }; case 'right': return { x: shape.x + shape.width, y: shape.y + shape.height / 2 }; case 'top': return { x: shape.x + shape.width / 2, y: shape.y }; case 'bottom': return { x: shape.x + shape.width / 2, y: shape.y + shape.height }; default: return { x: shape.x + shape.width, y: shape.y + shape.height / 2 }; } } // 打开连接编辑对话框 function openConnectionEditor(connection) { const modal = document.getElementById('connection-modal'); document.getElementById('connection-delay').value = connection.delay || 0; // 存储当前连接用于保存 selectedConnection = connection; modal.style.display = 'block'; } // 保存连接数据 function saveConnectionData() { if (!selectedConnection) return; // 获取参数 selectedConnection.delay = parseFloat(document.getElementById('connection-delay').value) || 0; // 关闭对话框 document.getElementById('connection-modal').style.display = 'none'; // 重绘画布 drawCanvas(); } // 删除选定的连接 function deleteSelectedConnection() { if (!selectedConnection) return; // 删除形状中的引用 const fromShape = shapes.find(s => s.id === selectedConnection.fromId); const toShape = shapes.find(s => s.id === selectedConnection.toId); if (fromShape) { fromShape.outputs = fromShape.outputs.filter(id => id !== selectedConnection.toId); } if (toShape) { toShape.inputs = toShape.inputs.filter(id => id !== selectedConnection.fromId); } // 删除连接 connections = connections.filter(c => c.id !== selectedConnection.id); // 重新计算所有产能 calculateAllThroughputs(); // 关闭对话框 document.getElementById('connection-modal').style.display = 'none'; // 重绘画布 drawCanvas(); } // 计算单个节点的产能 function calculateThroughput(shape) { let throughput = 0; switch(shape.type) { case SHAPE_TYPES.PROCESS: // 计算周期时间(秒) let maxEndTime = 0; if (shape.params.steps && shape.params.steps.length > 0) { shape.params.steps.forEach(step => { const endTime = step.startTime + step.workTime; if (endTime > maxEndTime) { maxEndTime = endTime; } }); } else { // 兼容旧数据 maxEndTime = (shape.params.actionSteps || 1) * (shape.params.stepTime || 1); } // 转换为分钟产能 (PPM) throughput = shape.params.batchSize * 60 / maxEndTime; break; case SHAPE_TYPES.TRANSPORT: // 计算总运输时间(秒) const transportTime = shape.params.transportTime * shape.params.transportCount; // 转换为分钟产能 (PPM) throughput = shape.params.transportBatch * 60 / transportTime; break; case SHAPE_TYPES.ENDPOINT: // 终端节点产能由输入决定 throughput = 0; // 将在拓扑排序后计算 break; } shape.calculatedThroughput = throughput; return throughput; } // 计算整个流程的产能 function calculateAllThroughputs() { // 对节点进行拓扑排序 let visited = new Set(); let sortedShapes = []; // 深度优先搜索函数 function dfs(shape) { if (visited.has(shape.id)) return; visited.add(shape.id); // 先处理所有输入节点 shape.inputs.forEach(inputId => { const inputShape = shapes.find(s => s.id === inputId); if (inputShape) dfs(inputShape); }); sortedShapes.push(shape); } // 从终端节点开始反向搜索 shapes.filter(s => s.type === SHAPE_TYPES.ENDPOINT) .forEach(dfs); // 如果有未访问的节点(可能是孤立的) shapes.forEach(shape => { if (!visited.has(shape.id)) dfs(shape); }); // 按排序计算产能 sortedShapes.forEach(calculateThroughput); // 特殊处理终端节点 shapes.filter(s => s.type === SHAPE_TYPES.ENDPOINT).forEach(endpoint => { let inputThroughput = 0; endpoint.inputs.forEach(inputId => { const inputShape = shapes.find(s => s.id === inputId); if (inputShape) { inputThroughput += inputShape.calculatedThroughput; } }); endpoint.calculatedThroughput = inputThroughput; }); } // 获取形状在指定位置 function getShapeAt(x, y) { // 从上到下检查,这样最上面的形状会被先选中 for (let i = shapes.length - 1; i >= 0; i--) { const shape = shapes[i]; // 检查点是否在形状内 if (x >= shape.x && x <= shape.x + shape.width && y >= shape.y && y <= shape.y + shape.height) { return shape; } } return null; } // 获取连接点 function getConnectionPointAt(x, y) { // 连接点检测半径 - 增加检测半径提高敏感度 const hitRadius = 15; // 先检查是否已有开始组件 const hasStartShape = shapes.some(s => s.type === SHAPE_TYPES.START); for (const shape of shapes) { // 根据形状类型确定连接点位置 let connectionPoints = []; switch(shape.type) { case SHAPE_TYPES.START: // 开始组件:只有右侧连接点 connectionPoints = [ { x: shape.x + shape.width, y: shape.y + shape.height/2, position: 'right' } // 右 ]; break; case SHAPE_TYPES.PROCESS: // 如果已经有开始组件,且当前形状不是开始组件的输出目标,则只允许左侧连接点 if (hasStartShape && !isConnectedToStart(shape)) { connectionPoints = [ { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 只允许左侧连接 ]; } else { // 否则允许所有连接点 connectionPoints = [ { x: shape.x, y: shape.y + shape.height/2, position: 'left' }, // 左 { x: shape.x + shape.width, y: shape.y + shape.height/2, position: 'right' }, // 右 { x: shape.x + shape.width/2, y: shape.y, position: 'top' }, // 上 { x: shape.x + shape.width/2, y: shape.y + shape.height, position: 'bottom' } // 下 ]; } break; case SHAPE_TYPES.TRANSPORT: // 如果已经有开始组件,且当前形状不是开始组件的输出目标,则只允许左侧连接点 if (hasStartShape && !isConnectedToStart(shape)) { connectionPoints = [ { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 只允许左侧连接 ]; } else { connectionPoints = [ { x: shape.x + shape.width/2, y: shape.y, position: 'top' }, // 上 { x: shape.x + shape.width, y: shape.y + shape.height/2, position: 'right' }, // 右 { x: shape.x + shape.width/2, y: shape.y + shape.height, position: 'bottom' }, // 下 { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 左 ]; } break; case SHAPE_TYPES.ENDPOINT: // 椭圆:只在左侧有连接点 connectionPoints = [ { x: shape.x, y: shape.y + shape.height/2, position: 'left' } // 左 ]; break; } // 检测连接点显示灵敏度的额外加强 // 对于新拖入的组件,增加一个标记来促使连接点更容易显示 const isNewShape = !shape.outputs || shape.outputs.length === 0; const effectiveHitRadius = isNewShape ? hitRadius * 1.5 : hitRadius; // 检查每个连接点 for (const point of connectionPoints) { const dx = x - point.x; const dy = y - point.y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance <= effectiveHitRadius) { return { shape: shape, x: point.x, y: point.y, position: point.position }; } } } return null; } // 检查形状是否已连接到开始组件 function isConnectedToStart(shape) { const startShape = shapes.find(s => s.type === SHAPE_TYPES.START); if (!startShape) return false; // 检查是否有从开始组件到此形状的直接连接 const directConnection = connections.some(conn => conn.fromId === startShape.id && conn.toId === shape.id ); if (directConnection) return true; // 递归检查是否通过其他形状间接连接到开始组件 function checkConnection(currentShape, visited = new Set()) { if (visited.has(currentShape.id)) return false; visited.add(currentShape.id); // 检查当前形状的所有输入 for (const inputId of currentShape.inputs) { const inputShape = shapes.find(s => s.id === inputId); if (!inputShape) continue; if (inputShape.type === SHAPE_TYPES.START) return true; if (checkConnection(inputShape, visited)) return true; } return false; } return checkConnection(shape); } // 获取连接 function getConnectionAt(x, y) { // 连接线检测范围 const hitDistance = 5; for (const connection of connections) { const fromShape = shapes.find(s => s.id === connection.fromId); const toShape = shapes.find(s => s.id === connection.toId); if (!fromShape || !toShape) continue; const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); // 使用线段到点的距离检测 if (isPointNearLine(x, y, startPoint, endPoint, hitDistance)) { return connection; } } return null; } // 检查点是否靠近线段 function isPointNearLine(px, py, start, end, maxDistance) { const dx = end.x - start.x; const dy = end.y - start.y; const length = Math.sqrt(dx * dx + dy * dy); maxDistance = Math.max(maxDistance, 10); // 增加最小检测范围 // 避免除以零 if (length === 0) return false; // 计算点到线的距离 const t = ((px - start.x) * dx + (py - start.y) * dy) / (length * length); // 如果t < 0,最近点在线段外的起点一侧 if (t < 0) { return distanceSquared(px, py, start.x, start.y) <= maxDistance * maxDistance; } // 如果t > 1,最近点在线段外的终点一侧 if (t > 1) { return distanceSquared(px, py, end.x, end.y) <= maxDistance * maxDistance; } // 最近点在线段上 const nearestX = start.x + t * dx; const nearestY = start.y + t * dy; return distanceSquared(px, py, nearestX, nearestY) <= maxDistance * maxDistance; } // 计算两点间距离的平方 function distanceSquared(x1, y1, x2, y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } // 绘制画布 function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 应用缩放和平移 ctx.save(); ctx.translate(panOffset.x, panOffset.y); ctx.scale(zoomLevel, zoomLevel); // 绘制所有连接线 connections.forEach(drawConnection); // 绘制所有形状 shapes.forEach(drawShape); // 绘制正在创建的连接线 if (isConnecting && connectingFrom) { drawTemporaryConnection(); } // 绘制悬停的连接点 if (hoveredConnectionPoint) { drawHoveredConnectionPoint(); } ctx.restore(); } // 绘制形状 function drawShape(shape) { ctx.save(); // 设置基本样式 ctx.lineWidth = shape === selectedShape ? 3 : 2; ctx.strokeStyle = SHAPE_COLORS[shape.type]; ctx.fillStyle = 'white'; // 根据状态调整边框颜色 if (simulationRunning) { if (shape.status === SHAPE_STATUS.WORKING) { ctx.strokeStyle = '#FF5722'; // 工作中 - 橙色 } else if (shape.status === SHAPE_STATUS.WAITING) { ctx.strokeStyle = '#2196F3'; // 等待下一步 - 蓝色 } } // 根据形状类型绘制不同图形 switch(shape.type) { case SHAPE_TYPES.START: // 绘制圆形 drawCircle(shape); break; case SHAPE_TYPES.PROCESS: // 绘制圆角矩形 drawRoundedRect(shape); break; case SHAPE_TYPES.TRANSPORT: // 绘制菱形 drawDiamond(shape); break; case SHAPE_TYPES.ENDPOINT: // 绘制椭圆 drawEllipse(shape); break; } // 绘制文本和状态信息 drawShapeInfo(shape); ctx.restore(); } // 绘制开始组件(圆角矩形) function drawCircle(shape) { const radius = 10; const x = shape.x; const y = shape.y; const width = shape.width; const height = shape.height; ctx.beginPath(); ctx.moveTo(x + radius, y); ctx.lineTo(x + width - radius, y); ctx.arcTo(x + width, y, x + width, y + radius, radius); ctx.lineTo(x + width, y + height - radius); ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius); ctx.lineTo(x + radius, y + height); ctx.arcTo(x, y + height, x, y + height - radius, radius); ctx.lineTo(x, y + radius); ctx.arcTo(x, y, x + radius, y, radius); ctx.closePath(); ctx.fill(); ctx.stroke(); } // 绘制圆角矩形 function drawRoundedRect(shape) { const radius = 10; const x = shape.x; const y = shape.y; const width = shape.width; const height = shape.height; ctx.beginPath(); ctx.moveTo(x + radius, y); ctx.lineTo(x + width - radius, y); ctx.arcTo(x + width, y, x + width, y + radius, radius); ctx.lineTo(x + width, y + height - radius); ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius); ctx.lineTo(x + radius, y + height); ctx.arcTo(x, y + height, x, y + height - radius, radius); ctx.lineTo(x, y + radius); ctx.arcTo(x, y, x + radius, y, radius); ctx.closePath(); ctx.fill(); ctx.stroke(); } // 绘制菱形 function drawDiamond(shape) { const x = shape.x; const y = shape.y; const width = shape.width; const height = shape.height; const centerX = x + width / 2; const centerY = y + height / 2; ctx.beginPath(); ctx.moveTo(centerX, y); // 顶点 ctx.lineTo(x + width, centerY); // 右点 ctx.lineTo(centerX, y + height); // 底点 ctx.lineTo(x, centerY); // 左点 ctx.closePath(); ctx.fill(); ctx.stroke(); } // 绘制椭圆 function drawEllipse(shape) { const x = shape.x; const y = shape.y; const width = shape.width; const height = shape.height; const centerX = x + width / 2; const centerY = y + height / 2; ctx.beginPath(); ctx.ellipse(centerX, centerY, width / 2, height / 2, 0, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); ctx.stroke(); } // 绘制形状内的信息 function drawShapeInfo(shape) { const x = shape.x; const y = shape.y; const width = shape.width; const height = shape.height; const centerX = x + width / 2; // 绘制名称 ctx.fillStyle = '#000'; ctx.font = 'bold 12px Arial'; ctx.textAlign = 'center'; ctx.fillText(shape.name, centerX, y + 20, width - 10); // 根据形状类型绘制不同信息 switch(shape.type) { case SHAPE_TYPES.PROCESS: // 显示状态 ctx.font = '10px Arial'; ctx.fillText(shape.status, centerX, y + 35, width - 10); // 显示当前步骤 if (shape.status === SHAPE_STATUS.WORKING && shape.currentStepName) { ctx.font = '10px Arial'; ctx.fillStyle = '#FF5722'; ctx.fillText(`当前: ${shape.currentStepName}`, centerX, y + 50, width - 10); } // 显示理论产能 ctx.font = 'bold 10px Arial'; ctx.fillStyle = '#FF5722'; ctx.fillText(`理论: ${shape.calculatedThroughput.toFixed(1)} PPM`, centerX, y + 65, width - 10); // 显示实时产能 ctx.font = '10px Arial'; ctx.fillStyle = '#2196F3'; ctx.fillText(`实时: ${shape.realTimeThroughput.toFixed(1)} PPM`, centerX, y + 80, width - 10); break; case SHAPE_TYPES.TRANSPORT: // 显示状态 ctx.font = '10px Arial'; ctx.fillText(shape.status, centerX, y + 35, width - 10); // 显示理论产能 ctx.font = 'bold 10px Arial'; ctx.fillStyle = '#FF5722'; ctx.fillText(`理论: ${shape.calculatedThroughput.toFixed(1)} PPM`, centerX, y + 50, width - 10); // 显示实时产能 ctx.font = '10px Arial'; ctx.fillStyle = '#2196F3'; ctx.fillText(`实时: ${shape.realTimeThroughput.toFixed(1)} PPM`, centerX, y + 65, width - 10); break; case SHAPE_TYPES.ENDPOINT: // 显示收集数量 ctx.font = 'bold 11px Arial'; ctx.fillStyle = '#000'; ctx.fillText(`收集数量: ${shape.processedItems}`, centerX, y + 35, width - 10); // 移除系统产能显示 break; } } // 绘制连接线 function drawConnection(connection) { const fromShape = shapes.find(s => s.id === connection.fromId); const toShape = shapes.find(s => s.id === connection.toId); if (!fromShape || !toShape) return; const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); // 高亮选中的连接 ctx.strokeStyle = connection === selectedConnection ? '#f44336' : '#2196F3'; ctx.lineWidth = connection === selectedConnection ? 3 : 2; // 设置虚线样式,使用动画移动虚线 ctx.setLineDash([8, 4]); // 使用simulationTime创建移动效果,让虚线随时间流动 ctx.lineDashOffset = -simulationTime * 60 * 5; // 乘以60将分钟转为秒,乘以5增加移动速度 // 绘制直线或正交连接 drawOrthogonalConnection(connection, startPoint, endPoint); // 绘制箭头 drawArrow(endPoint, getDirectionVectorTowards(endPoint, connection.lastPoint || startPoint)); // 清除虚线设置 ctx.setLineDash([]); // 注意:我们不再需要粒子来表示动态效果,因为已经使用了虚线动画 } // 绘制正交连接(直角连接) function drawOrthogonalConnection(connection, start, end) { const fromShape = shapes.find(s => s.id === connection.fromId); const toShape = shapes.find(s => s.id === connection.toId); if (!fromShape || !toShape) return; // 计算连接点的路径 let path = calculateOrthogonalPath(start, end, fromShape, toShape, connection); // 保存路径点用于粒子动画 connection.pathPoints = path; connection.lastPoint = path.length > 0 ? path[path.length - 1] : start; // 绘制路径 ctx.beginPath(); ctx.moveTo(start.x, start.y); for (const point of path) { ctx.lineTo(point.x, point.y); } ctx.lineTo(end.x, end.y); ctx.stroke(); } // 计算正交路径 function calculateOrthogonalPath(start, end, fromShape, toShape, connection) { const path = []; // 获取方向向量 const startDir = getDirectionFromPosition(connection.startPosition); const endDir = getDirectionFromPosition(connection.endPosition); // 计算控制点的偏移量 const offset = 20; // 第一个控制点(从起点沿起点方向延伸) const firstPoint = { x: start.x + startDir.x * offset, y: start.y + startDir.y * offset }; path.push(firstPoint); // 判断是否需要中间点 if (Math.abs(startDir.x) === Math.abs(endDir.x) && Math.abs(startDir.y) === Math.abs(endDir.y)) { // 方向平行或相反,需要两个中间点 // 计算中点 const midX = (start.x + end.x) / 2; const midY = (start.y + end.y) / 2; if (startDir.x !== 0) { // 水平方向起点 path.push({ x: midX, y: firstPoint.y }); path.push({ x: midX, y: end.y - endDir.y * offset }); } else { // 垂直方向起点 path.push({ x: firstPoint.x, y: midY }); path.push({ x: end.x - endDir.x * offset, y: midY }); } } else { // 方向不同,只需要一个拐点 if (startDir.x !== 0) { // 水平方向起点 path.push({ x: end.x - endDir.x * offset, y: firstPoint.y }); } else { // 垂直方向起点 path.push({ x: firstPoint.x, y: end.y - endDir.y * offset }); } } return path; } // 获取朝向某点的方向向量 function getDirectionVectorTowards(point, fromPoint) { const dx = point.x - fromPoint.x; const dy = point.y - fromPoint.y; const length = Math.sqrt(dx * dx + dy * dy) || 1; // 避免除以零 return { x: dx / length, y: dy / length }; } // 绘制箭头 function drawArrow(point, direction) { const arrowSize = 8; const arrowAngle = Math.PI / 6; // 30度 // 计算箭头角度 const angle = Math.atan2(direction.y, direction.x); // 绘制箭头 ctx.beginPath(); ctx.moveTo(point.x, point.y); ctx.lineTo( point.x - arrowSize * Math.cos(angle - arrowAngle), point.y - arrowSize * Math.sin(angle - arrowAngle) ); ctx.lineTo( point.x - arrowSize * Math.cos(angle + arrowAngle), point.y - arrowSize * Math.sin(angle + arrowAngle) ); ctx.closePath(); ctx.fillStyle = ctx.strokeStyle; ctx.fill(); } // 绘制临时连接线 function drawTemporaryConnection() { if (!connectingFrom || !hoveredConnectionPoint) return; const startPoint = getConnectionPointCoordinates( connectingFrom, hoveredConnectionPoint.position ); ctx.strokeStyle = '#2196F3'; ctx.lineWidth = 2; ctx.setLineDash([5, 3]); // 绘制临时连接线 drawTemporaryOrthogonalLine(startPoint, connectingToPoint, hoveredConnectionPoint.position); ctx.setLineDash([]); } // 绘制临时正交线 function drawTemporaryOrthogonalLine(start, end, startPosition) { const startDir = getDirectionFromPosition(startPosition); const offset = 20; // 第一个控制点 const firstPoint = { x: start.x + startDir.x * offset, y: start.y + startDir.y * offset }; // 判断连接类型并绘制 ctx.beginPath(); ctx.moveTo(start.x, start.y); ctx.lineTo(firstPoint.x, firstPoint.y); if (startDir.x !== 0) { // 水平方向起点 ctx.lineTo(end.x, firstPoint.y); } else { // 垂直方向起点 ctx.lineTo(firstPoint.x, end.y); } ctx.lineTo(end.x, end.y); ctx.stroke(); } // 绘制悬停的连接点 function drawHoveredConnectionPoint() { if (!hoveredConnectionPoint) return; ctx.fillStyle = 'rgba(33, 150, 243, 0.6)'; ctx.strokeStyle = '#2196F3'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(hoveredConnectionPoint.x, hoveredConnectionPoint.y, 8, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); // 绘制加号 ctx.fillStyle = 'white'; ctx.font = 'bold 12px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('+', hoveredConnectionPoint.x, hoveredConnectionPoint.y); } // 绘制动态粒子 function drawParticles(connection) { if (!connection.particles || !connection.pathPoints) return; const fromShape = shapes.find(s => s.id === connection.fromId); const toShape = shapes.find(s => s.id === connection.toId); if (!fromShape || !toShape) return; const startPoint = getConnectionPointCoordinates(fromShape, connection.startPosition); const endPoint = getConnectionPointCoordinates(toShape, connection.endPosition); // 构建完整路径 const fullPath = [startPoint, ...connection.pathPoints, endPoint]; // 绘制每个粒子 for (const particle of connection.particles) { const pos = calculateParticlePosition(particle.progress, fullPath); ctx.fillStyle = '#FF9800'; ctx.beginPath(); ctx.arc(pos.x, pos.y, 4, 0, Math.PI * 2); ctx.fill(); } } // 计算粒子在路径上的位置 function calculateParticlePosition(progress, path) { if (path.length < 2) return path[0]; // 计算路径总长度和各段长度 let totalLength = 0; const segmentLengths = []; for (let i = 0; i < path.length - 1; i++) { const dx = path[i+1].x - path[i].x; const dy = path[i+1].y - path[i].y; const length = Math.sqrt(dx*dx + dy*dy); segmentLengths.push(length); totalLength += length; } // 根据进度找到对应段 const targetDistance = progress * totalLength; let distanceTraveled = 0; for (let i = 0; i < segmentLengths.length; i++) { if (distanceTraveled + segmentLengths[i] >= targetDistance) { // 找到了段,计算位置 const segmentProgress = (targetDistance - distanceTraveled) / segmentLengths[i]; return { x: path[i].x + (path[i+1].x - path[i].x) * segmentProgress, y: path[i].y + (path[i+1].y - path[i].y) * segmentProgress }; } distanceTraveled += segmentLengths[i]; } // 如果到达这里,返回路径终点 return path[path.length - 1]; } // 将坐标对齐到网格 function snapToGrid(value) { return Math.round(value / GRID_SIZE) * GRID_SIZE; } // 更新状态信息 function updateStatus(message) { document.getElementById('status-message').textContent = message; } // 重置仿真 function resetSimulation() { // 停止当前仿真 if (simulationRunning) { stopSimulation(); } // 重置所有形状的状态 shapes.forEach(shape => { shape.processedItems = 0; shape.buffer = 0; shape.status = SHAPE_STATUS.IDLE; shape.waitingForNext = false; shape.waitingForPrevious = true; shape.realTimeThroughput = 0; shape.lastProcessTime = 0; }); // 清空所有连接上的粒子 connections.forEach(connection => { connection.particles = []; }); // 重置仿真时间 simulationTime = 0; // 更新统计信息 updateSimulationStats(); // 重绘画布 drawCanvas(); updateStatus('仿真已重置'); } // 开始仿真 function startSimulation() { if (simulationRunning) return; // 设置固定的仿真速度,完全按照机构的实际速度进行 simulationSpeed = 1; // 使仿真时间与现实时间保持一致 // 重置仿真状态 resetSimulation(); // 不再需要初始化粒子动画,因为使用虚线实现动态效果 // initializeConnectionAnimations(); // 更新按钮文本 document.getElementById('start-simulation').textContent = '正在仿真'; document.getElementById('start-simulation').disabled = true; simulationRunning = true; // 记录仿真开始的真实时间 let simulationStartTime = Date.now(); let lastUpdateTime = simulationStartTime; // 启动仿真计时器 - 使用更小的时间间隔使动画更流畅 simulationInterval = setInterval(() => { // 获取当前真实时间 const currentTime = Date.now(); // 计算真实经过的时间差(毫秒转换为分钟) const realTimeDiff = (currentTime - lastUpdateTime) / (1000 * 60); // 更新仿真时间(按真实时间流逝) simulationTime += realTimeDiff; // 更新上次更新时间 lastUpdateTime = currentTime; // 更新仿真逻辑 updateSimulation(); // 更新统计信息 updateSimulationStats(); // 重绘画布 drawCanvas(); // 仿真持续进行,直到用户手动停止 // 不再根据设定时间自动停止 // 更新状态栏显示当前仿真时间(以秒为单位) updateStatus(`仿真进行中 - ${Math.floor(simulationTime * 60)}秒`) }, 10); // 使用10毫秒的间隔使动画更流畅 updateStatus('仿真进行中'); } // 初始化连接线动画效果 function initializeConnectionAnimations() { // 为每条连接线添加初始粒子 connections.forEach(connection => { // 清空现有粒子 connection.particles = []; // 添加2-3个随机分布的粒子 const particleCount = 2 + Math.floor(Math.random() * 2); for (let i = 0; i < particleCount; i++) { connection.particles.push({ // 随机初始位置 progress: Math.random(), speed: 0.05 // 使用固定速度,不再依赖速度倍率 }); } }); } // 停止仿真 function stopSimulation() { if (!simulationRunning) return; clearInterval(simulationInterval); simulationRunning = false; // 更新按钮文本 document.getElementById('start-simulation').textContent = '开始仿真'; document.getElementById('start-simulation').disabled = false; updateStatus('仿真已停止'); } // 更新仿真逻辑 function updateSimulation() { // 首先计算每个形状的输入流量 calculateInputFlows(); // 更新每个形状的状态和输出 updateShapeStates(); // 更新连接上的粒子移动 updateParticles(); } // 计算各个形状的输入流量 function calculateInputFlows() { shapes.forEach(shape => { // 开始组件不等待输入 if (shape.type === SHAPE_TYPES.START) { shape.waitingForPrevious = false; // 确保开始组件不会被阻塞 shape.waitingForNext = false; shape.status = SHAPE_STATUS.WORKING; return; } // 检查输入形状的状态 let hasActiveInput = false; let inputBuffer = 0; let hasStartShapeInput = false; // 如果没有输入连接,则不等待上游 if (shape.inputs.length === 0) { shape.waitingForPrevious = false; return; } shape.inputs.forEach(inputId => { const inputShape = shapes.find(s => s.id === inputId); if (inputShape) { // 检查是否有开始组件作为输入 if (inputShape.type === SHAPE_TYPES.START) { hasStartShapeInput = true; hasActiveInput = true; // 开始组件总是被视为活跃输入 } // 只要上游机构有产品,就认为有活跃输入 else if (inputShape.buffer > 0) { hasActiveInput = true; inputBuffer += inputShape.buffer; } } }); // 更新形状的等待状态 if (shape.type !== SHAPE_TYPES.ENDPOINT) { // 如果有开始组件作为输入,则不等待上游 if (hasStartShapeInput) { shape.waitingForPrevious = false; shape.status = SHAPE_STATUS.WORKING; } else { // 只有当上游没有产品时才等待 shape.waitingForPrevious = inputBuffer === 0; } } else { // 终端节点不等待输入 shape.waitingForPrevious = false; } }); // 第二次遍历,确保所有连接到开始组件的下游组件都能自动开始工作 shapes.forEach(shape => { if (shape.type === SHAPE_TYPES.START) { // 激活所有连接到开始组件的下游组件 shape.outputs.forEach(outputId => { const outputShape = shapes.find(s => s.id === outputId); if (outputShape) { outputShape.waitingForPrevious = false; outputShape.status = SHAPE_STATUS.WORKING; } }); } }); } // 更新形状状态和输出 function updateShapeStates() { // 首先更新所有机构的等待状态 updateWaitingStates(); // 然后按照拓扑顺序更新机构状态,确保上游机构先更新 // 这样可以正确传递产能限制信息 const processedShapes = new Set(); // 首先处理起始节点 shapes.filter(shape => shape.type === SHAPE_TYPES.START).forEach(shape => { processShape(shape, processedShapes); }); // 确保所有节点都被处理 shapes.forEach(shape => { if (!processedShapes.has(shape.id)) { processShape(shape, processedShapes); } }); } // 按照拓扑顺序处理节点 function processShape(shape, processedShapes) { // 如果已处理过,直接返回 if (processedShapes.has(shape.id)) return; // 先处理所有输入节点 shape.inputs.forEach(inputId => { const inputShape = shapes.find(s => s.id === inputId); if (inputShape && !processedShapes.has(inputShape.id)) { processShape(inputShape, processedShapes); } }); // 根据形状类型更新状态 switch(shape.type) { case SHAPE_TYPES.START: updateStartShape(shape); break; case SHAPE_TYPES.PROCESS: updateProcessShape(shape); break; case SHAPE_TYPES.TRANSPORT: updateTransportShape(shape); break; case SHAPE_TYPES.ENDPOINT: updateEndpointShape(shape); break; } // 标记为已处理 processedShapes.add(shape.id); } // 更新开始组件 function updateStartShape(shape) { // 开始组件始终处于工作状态 shape.status = SHAPE_STATUS.WORKING; // 开始组件不累积物料,只作为流程标记 shape.buffer = 0; // 确保开始组件不会被阻塞 shape.waitingForPrevious = false; shape.waitingForNext = false; // 直接激活所有下游组件 shape.outputs.forEach(outputId => { const outputShape = shapes.find(s => s.id === outputId); if (outputShape) { // 标记下游组件不需要等待上游 outputShape.waitingForPrevious = false; // 无论下游组件有多少输入,都直接设置为工作状态 // 这确保了开始组件能够正确触发所有下游组件 outputShape.status = SHAPE_STATUS.WORKING; // 特别处理运输组件 if (outputShape.type === SHAPE_TYPES.TRANSPORT) { // 确保运输组件不会等待上游 outputShape.waitingForPrevious = false; // 确保运输组件不会等待下游 outputShape.waitingForNext = false; // 初始化处理时间,确保能立即开始工作 outputShape.lastProcessTime = 0; } } }); // 调用transferProducts函数来创建粒子动画 transferProducts(shape); // 开始组件仅作为流程标记,不设置任何产能值 shape.realTimeThroughput = 0; } // 更新普通机构 function updateProcessShape(shape) { // 初始化当前步骤和总周期时间 if (!shape.currentStepIndex) { shape.currentStepIndex = 0; } // 获取步骤数据 const steps = shape.params.steps || [ // 兼容旧数据 { name: "步骤1", startTime: 0, workTime: (shape.params.actionSteps || 1) * (shape.params.stepTime || 1) } ]; // 计算总周期时间(分钟) let maxEndTime = 0; steps.forEach(step => { const endTime = step.startTime + step.workTime; if (endTime > maxEndTime) { maxEndTime = endTime; } }); const cycleTimeMinutes = maxEndTime / 60; // 如果上游机构未完成,等待上游机构传送产品 if (shape.waitingForPrevious) { shape.status = SHAPE_STATUS.IDLE; // 不重置处理时间,保持当前进度 return; } // 检查是否有产品在缓冲区等待传送 if (shape.buffer > 0) { // 检查下游机构是否可接收 const outputBlocked = checkOutputBlocked(shape); if (outputBlocked) { // 下游机构阻塞,无法传送产品,停止生产 shape.waitingForNext = true; shape.status = SHAPE_STATUS.WAITING; return; // 停止处理,不继续生产 } else { // 下游机构可接收,传送产品 transferProducts(shape); // transferProducts函数会重置waitingForNext状态 } } else { shape.waitingForNext = false; } // 检查下游机构是否可接收 - 即使当前没有缓冲产品也要检查 // 这是为了模拟现实中的情况:如果下游机构无法接收,则不应继续生产 const outputBlocked = checkOutputBlocked(shape); if (outputBlocked) { // 下游机构阻塞,无法接收产品,停止生产 shape.waitingForNext = true; shape.status = SHAPE_STATUS.WAITING; return; // 停止处理,不继续生产 } // 只有当下游机构可以接收产品时,才继续生产 shape.status = SHAPE_STATUS.WORKING; // 累积工作时间 shape.lastProcessTime += SIMULATION_TICK; // 更新当前执行的步骤 const currentTime = shape.lastProcessTime * 60; // 转换为秒 let activeStepFound = false; // 查找当前时间正在执行的步骤 for (let i = 0; i < steps.length; i++) { const step = steps[i]; const stepStartTime = step.startTime; const stepEndTime = step.startTime + step.workTime; if (currentTime >= stepStartTime && currentTime <= stepEndTime) { shape.currentStepIndex = i; shape.currentStepName = step.name; activeStepFound = true; break; } } // 如果没有找到活动步骤,可能是在步骤之间的间隙 if (!activeStepFound) { shape.currentStepName = "等待下一步骤"; } // 如果完成了一个处理周期 if (shape.lastProcessTime >= cycleTimeMinutes) { // 生产产品 shape.buffer += shape.params.batchSize; shape.totalProduced = (shape.totalProduced || 0) + shape.params.batchSize; // 计算实时产能 (PPM) - 使用理论周期时间计算 if (simulationTime > 0) { // 使用理论周期时间计算实时产能,而不是累计产量除以总时间 const theoreticalCyclesCompleted = Math.floor(simulationTime / cycleTimeMinutes); const theoreticalProduction = theoreticalCyclesCompleted * shape.params.batchSize; shape.realTimeThroughput = theoreticalProduction / simulationTime; } // 重置处理时间和步骤索引 shape.lastProcessTime = 0; shape.currentStepIndex = 0; shape.currentStepName = steps[0].name; // 检查下游机构是否可接收 const outputBlocked = checkOutputBlocked(shape); if (outputBlocked) { // 下游机构阻塞,无法传送产品 shape.waitingForNext = true; shape.status = SHAPE_STATUS.WAITING; } else { // 下游机构可接收,传送产品 transferProducts(shape); shape.waitingForNext = false; } } } // 更新运输机构 - 使其逻辑与普通组件一致 function updateTransportShape(shape) { // 计算运输周期时间(分钟) const transportTimeMinutes = shape.params.transportTime * shape.params.transportCount / 60; // 如果上游机构未完成,等待上游机构传送产品 if (shape.waitingForPrevious) { shape.status = SHAPE_STATUS.IDLE; // 不重置处理时间,保持当前进度 return; } // 检查是否有产品在缓冲区等待传送 if (shape.buffer > 0) { // 检查下游机构是否可接收 const outputBlocked = checkOutputBlocked(shape); if (outputBlocked) { // 下游机构阻塞,无法传送产品,停止生产 shape.waitingForNext = true; shape.status = SHAPE_STATUS.WAITING; return; // 停止处理,不继续生产 } else { // 下游机构可接收,传送产品 transferProducts(shape); // transferProducts函数会重置waitingForNext状态 } } else { shape.waitingForNext = false; } // 检查下游机构是否可接收 - 即使当前没有缓冲产品也要检查 // 这是为了模拟现实中的情况:如果下游机构无法接收,则不应继续生产 const outputBlocked = checkOutputBlocked(shape); if (outputBlocked) { // 下游机构阻塞,无法接收产品,停止生产 shape.waitingForNext = true; shape.status = SHAPE_STATUS.WAITING; return; // 停止处理,不继续生产 } // 只有当下游机构可以接收产品时,才继续生产 shape.status = SHAPE_STATUS.WORKING; // 累积工作时间 shape.lastProcessTime += SIMULATION_TICK; // 如果完成了一个运输周期 if (shape.lastProcessTime >= transportTimeMinutes) { // 生产产品 shape.buffer += shape.params.transportBatch; shape.totalTransported = (shape.totalTransported || 0) + shape.params.transportBatch; // 计算实时产能 (PPM) if (simulationTime > 0) { // 使用理论周期时间计算实时产能 const theoreticalCyclesCompleted = Math.floor(simulationTime / transportTimeMinutes); const theoreticalTransported = theoreticalCyclesCompleted * shape.params.transportBatch; shape.realTimeThroughput = theoreticalTransported / simulationTime; } // 重置处理时间 shape.lastProcessTime = 0; // 检查下游机构是否可接收 const outputBlocked = checkOutputBlocked(shape); if (outputBlocked) { // 下游机构阻塞,无法传送产品 shape.waitingForNext = true; shape.status = SHAPE_STATUS.WAITING; } else { // 下游机构可接收,传送产品 transferProducts(shape); // 如果传递后仍有物料,说明下游产能有限 shape.waitingForNext = shape.buffer > 0; // 更新状态 shape.status = shape.waitingForNext ? SHAPE_STATUS.WAITING : SHAPE_STATUS.WORKING; } } } // 更新终端收料机构 function updateEndpointShape(shape) { // 终端节点始终处于活跃状态 shape.status = SHAPE_STATUS.WORKING; // 从所有输入形状接收产品 let receivedItems = 0; shape.inputs.forEach(inputId => { const inputShape = shapes.find(s => s.id === inputId); if (inputShape && inputShape.buffer > 0) { // 创建从输入到此终端节点的粒子 const connection = connections.find(c => c.fromId === inputShape.id && c.toId === shape.id); if (connection) { for (let i = 0; i < inputShape.buffer; i++) { // 添加新粒子 connection.particles.push({ progress: 0, // 起点 speed: 0.02 * simulationSpeed / 100 // 速度根据仿真速度调整 }); } } // 清空输入形状的缓冲区 inputShape.buffer = 0; // 输入形状不再等待 inputShape.waitingForNext = false; } }); // 更新终端节点的处理产品数量 shape.processedItems = shape.processedItems || 0; // 更新实时产能 (PPM) if (simulationTime > 0) { // 计算系统实际产能 const systemThroughput = shape.processedItems / simulationTime; shape.realTimeThroughput = systemThroughput; // 更新系统产能显示 document.getElementById('system-throughput').textContent = systemThroughput.toFixed(1); // 更新总产出显示 document.getElementById('total-output').textContent = shape.processedItems; } } // 检查下游机构是否可接收产品 function checkOutputBlocked(shape) { // 如果没有输出连接,则不阻塞 if (shape.outputs.length === 0) return false; // 检查所有下游节点是否都已阻塞 let allBlocked = true; shape.outputs.forEach(outputId => { const outputShape = shapes.find(s => s.id === outputId); if (outputShape && !outputShape.waitingForNext) { allBlocked = false; } }); return allBlocked; } // 尝试向下游传递产品 function transferProducts(shape) { // 如果是开始组件,不传递实际物料,只激活下游组件 if (shape.type === SHAPE_TYPES.START) { // 获取所有下游节点 const outputs = shape.outputs .map(id => shapes.find(s => s.id === id)) .filter(s => s); // 激活所有下游组件 outputs.forEach(outputShape => { outputShape.waitingForPrevious = false; outputShape.status = SHAPE_STATUS.WORKING; // 特别处理运输组件 if (outputShape.type === SHAPE_TYPES.TRANSPORT) { // 确保运输组件不会等待上游 outputShape.waitingForPrevious = false; // 确保运输组件不会等待下游 outputShape.waitingForNext = false; // 初始化处理时间,确保能立即开始工作 outputShape.lastProcessTime = 0; // 运输组件的物料处理逻辑与普通组件一致 outputShape.buffer = (outputShape.buffer || 0) + itemsToTransfer; outputShape.status = SHAPE_STATUS.WORKING; } // 为每个连接创建粒子动画,增强可视化效果 const connection = connections.find(c => c.fromId === shape.id && c.toId === outputShape.id); if (connection) { if (!connection.particles) connection.particles = []; // 添加一个粒子表示信号传递 connection.particles.push({ progress: 0, speed: 0.05 * simulationSpeed / 100 }); } }); // 开始组件不等待下游 shape.waitingForNext = false; return; } if (shape.buffer <= 0 || shape.outputs.length === 0) return; // 获取可用的下游节点 - 包括终端节点和非终端节点 const availableOutputs = shape.outputs .map(id => shapes.find(s => s.id === id)) .filter(s => s && (s.type === SHAPE_TYPES.ENDPOINT || !s.waitingForNext)); if (availableOutputs.length === 0) { // 所有下游都被阻塞,但不应该停止整个系统 // 仅标记当前节点等待下游,但允许继续累积物料 shape.waitingForNext = true; return; } // 考虑下游机构的产能限制 let maxTransferAmount = shape.buffer; // 检查下游机构的产能限制 availableOutputs.forEach(outputShape => { // 如果不是终端节点,检查其产能 if (outputShape.type !== SHAPE_TYPES.ENDPOINT) { // 获取下游机构的理论产能 let downstreamCapacity = 0; if (outputShape.type === SHAPE_TYPES.PROCESS) { // 计算处理机构的理论产能 const steps = outputShape.params.steps || [ { name: "步骤1", startTime: 0, workTime: (outputShape.params.actionSteps || 1) * (outputShape.params.stepTime || 1) } ]; // 计算总周期时间(分钟) let maxEndTime = 0; steps.forEach(step => { const endTime = step.startTime + step.workTime; if (endTime > maxEndTime) { maxEndTime = endTime; } }); const cycleTimeMinutes = maxEndTime / 60; // 计算理论产能 if (cycleTimeMinutes > 0) { downstreamCapacity = outputShape.params.batchSize / cycleTimeMinutes; } } else if (outputShape.type === SHAPE_TYPES.TRANSPORT) { // 计算运输机构的理论产能 const transportTimeMinutes = outputShape.params.transportTime * outputShape.params.transportCount / 60; if (transportTimeMinutes > 0) { downstreamCapacity = outputShape.params.transportBatch / transportTimeMinutes; } } // 如果下游机构有产能限制,调整传输量,但确保至少传递一些物料 if (downstreamCapacity > 0 && shape.realTimeThroughput > downstreamCapacity) { // 根据下游产能比例调整传输量 const capacityRatio = downstreamCapacity / shape.realTimeThroughput; const adjustedAmount = Math.max(1, Math.ceil(shape.buffer * capacityRatio)); maxTransferAmount = Math.min(maxTransferAmount, adjustedAmount); } } }); // 计算每个下游节点应接收的产品数量,考虑产能限制 // 确保至少传递1个物料,避免完全停滞 const itemsPerOutput = Math.max(1, Math.floor(maxTransferAmount / availableOutputs.length)); let remainingItems = maxTransferAmount % availableOutputs.length; // 创建粒子并传递产品 availableOutputs.forEach(outputShape => { // 分配产品数量 let itemsToTransfer = itemsPerOutput; if (remainingItems > 0) { itemsToTransfer++; remainingItems--; } if (itemsToTransfer <= 0) return; // 创建从此形状到输出形状的粒子 const connection = connections.find(c => c.fromId === shape.id && c.toId === outputShape.id); if (connection) { // 所有机构瞬间传递物料到下游 if (outputShape.type === SHAPE_TYPES.ENDPOINT) { // 如果是终端节点,直接增加处理数量 outputShape.processedItems = (outputShape.processedItems || 0) + itemsToTransfer; // 更新系统产能 - 使用理论计算方式 if (simulationTime > 0) { // 使用系统理论周期时间计算 const systemThroughput = outputShape.processedItems / simulationTime; outputShape.realTimeThroughput = systemThroughput; } } else { // 非终端节点,直接增加缓冲区 outputShape.buffer = (outputShape.buffer || 0) + itemsToTransfer; // 更新下游机构状态 outputShape.waitingForPrevious = false; outputShape.status = SHAPE_STATUS.WORKING; // 确保下游组件知道它有新的物料需要处理 if (outputShape.type === SHAPE_TYPES.TRANSPORT) { // 如果下游是运输组件,确保它知道有物料可以传递 outputShape.waitingForNext = false; } } // 创建粒子动画(仅用于可视化) for (let i = 0; i < itemsToTransfer; i++) { connection.particles.push({ progress: 0, speed: 0.05 * simulationSpeed / 100 }); } } }); // 更新缓冲区,保留未传递的物料 const transferredAmount = Math.min(shape.buffer, maxTransferAmount); shape.buffer -= transferredAmount; // 如果成功传送了物料,则允许机构继续生产 // 但如果缓冲区仍有物料,说明下游产能有限,应限制上游生产 // 但不应完全阻止生产,只是标记状态 shape.waitingForNext = shape.buffer > 0; // 通知上游机构可以继续生产 // 即使当前机构缓冲区已满,也不应完全阻止上游生产 shape.inputs.forEach(inputId => { const inputShape = shapes.find(s => s.id === inputId); if (inputShape) { // 允许上游继续生产,但可能会限制产能 inputShape.waitingForNext = false; } }); } // 更新连接上的粒子 - 简化实现,主要依赖虚线动画 function updateParticles() { // 由于我们使用了虚线动画替代粒子,这个函数简化为主要处理开始组件特殊情况的逻辑 connections.forEach(connection => { // 获取源形状和目标形状 const fromShape = shapes.find(s => s.id === connection.fromId); const toShape = shapes.find(s => s.id === connection.toId); // 特殊处理开始组件的连接 if (fromShape && toShape && fromShape.type === SHAPE_TYPES.START) { // 开始组件连接的下游组件不等待上游 toShape.waitingForPrevious = false; toShape.status = SHAPE_STATUS.WORKING; // 特别处理运输组件 if (toShape.type === SHAPE_TYPES.TRANSPORT) { toShape.waitingForPrevious = false; toShape.status = SHAPE_STATUS.WORKING; toShape.waitingForNext = false; toShape.lastProcessTime = 0; } } // 粒子动画部分不再需要,因为使用虚线效果代替 }); } // 更新仿真统计信息 function updateSimulationStats() { // 更新仿真时间显示(转换为秒) const timeInSeconds = simulationTime * 60; // 将分钟转换为秒 document.getElementById('elapsed-time').textContent = timeInSeconds.toFixed(1); // 找到终端节点计算系统吞吐量 const endpoints = shapes.filter(s => s.type === SHAPE_TYPES.ENDPOINT); if (endpoints.length > 0) { // 计算所有终端节点的总产出 const totalOutput = endpoints.reduce((sum, endpoint) => sum + endpoint.processedItems, 0); // 显示总产出 document.getElementById('total-output').textContent = totalOutput; // 计算系统产能 (PPS - 每秒产能) let systemThroughput = 0; if (simulationTime > 0) { systemThroughput = totalOutput / (simulationTime * 60); // 转换为每秒产能 } // 显示系统产能 document.getElementById('system-throughput').textContent = systemThroughput.toFixed(2); } } // 显示保存项目对话框 function showSaveProjectDialog() { const modal = document.getElementById('file-modal'); document.getElementById('file-modal-title').textContent = '保存项目'; document.getElementById('file-action-btn').textContent = '保存'; document.getElementById('saved-projects-container').style.display = 'none'; document.getElementById('file-form').dataset.action = 'save'; // 显示对话框 modal.style.display = 'block'; } // 显示加载项目对话框 function showLoadProjectDialog() { const modal = document.getElementById('file-modal'); document.getElementById('file-modal-title').textContent = '加载项目'; document.getElementById('file-action-btn').textContent = '加载'; document.getElementById('saved-projects-container').style.display = 'block'; document.getElementById('file-form').dataset.action = 'load'; // 加载已保存的项目列表 loadProjectList(); // 显示对话框 modal.style.display = 'block'; } // 加载已保存项目列表 function loadProjectList() { const projectsList = document.getElementById('saved-projects-list'); projectsList.innerHTML = ''; // 从localStorage获取已保存的项目 let savedProjects = localStorage.getItem('flowSimProjects'); if (savedProjects) { try { savedProjects = JSON.parse(savedProjects); // 为每个项目创建列表项 Object.keys(savedProjects).forEach(projectName => { const li = document.createElement('li'); li.textContent = projectName; li.addEventListener('click', function() { document.getElementById('project-name').value = projectName; }); // 创建删除按钮 const deleteBtn = document.createElement('button'); deleteBtn.textContent = '删除'; deleteBtn.className = 'delete-btn'; deleteBtn.addEventListener('click', function(e) { e.stopPropagation(); if (confirm(`确定删除项目 "${projectName}"?`)) { delete savedProjects[projectName]; localStorage.setItem('flowSimProjects', JSON.stringify(savedProjects)); loadProjectList(); } }); li.appendChild(deleteBtn); projectsList.appendChild(li); }); } catch (e) { console.error('加载项目列表失败:', e); } } // 如果没有项目,显示提示信息 if (projectsList.children.length === 0) { const li = document.createElement('li'); li.textContent = '没有已保存的项目'; li.style.textAlign = 'center'; li.style.cursor = 'default'; projectsList.appendChild(li); } } // 处理文件表单提交 function handleFileSubmit() { const form = document.getElementById('file-form'); const action = form.dataset.action; const projectName = document.getElementById('project-name').value.trim(); if (!projectName) { alert('请输入项目名称'); return; } if (action === 'save') { saveProject(projectName); } else if (action === 'load') { loadProject(projectName); } // 关闭对话框 document.getElementById('file-modal').style.display = 'none'; } // 保存项目 function saveProject(projectName) { // 收集项目数据 const projectData = { shapes: shapes, connections: connections, nextShapeId: nextShapeId, nextConnectionId: nextConnectionId }; // 获取已保存的项目 let savedProjects = localStorage.getItem('flowSimProjects'); if (!savedProjects) { savedProjects = {}; } else { savedProjects = JSON.parse(savedProjects); } // 检查是否覆盖现有项目 if (savedProjects[projectName] && !confirm(`项目 "${projectName}" 已存在,是否覆盖?`)) { return; } // 保存项目 savedProjects[projectName] = projectData; localStorage.setItem('flowSimProjects', JSON.stringify(savedProjects)); alert(`项目 "${projectName}" 已保存`); } // 加载项目 function loadProject(projectName) { // 获取已保存的项目 let savedProjects = localStorage.getItem('flowSimProjects'); if (!savedProjects) { alert('没有找到已保存的项目'); return; } savedProjects = JSON.parse(savedProjects); // 检查项目是否存在 if (!savedProjects[projectName]) { alert(`项目 "${projectName}" 不存在`); return; } const projectData = savedProjects[projectName]; // 加载项目数据 shapes = projectData.shapes; connections = projectData.connections; nextShapeId = projectData.nextShapeId; nextConnectionId = projectData.nextConnectionId; // 重置选择状态 selectedShape = null; selectedConnection = null; // 重置仿真状态 resetSimulation(); alert(`项目 "${projectName}" 已加载`); } });