Pipe Assembly Lab v1.1: validated viscous damping, comparison and project delivery
Browse filesFiles changed (9)
- PROJECT_FORMAT.mdAdded+75
- README.md+4
- SHA256SUMS+8-6
- app.js+95-19
- index.html+4-1
- preview.png
- project.jsAdded+29
- solver.js+48-4
- style.css+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# Pipe project and dynamic response · v1.1
A saved project is JSON, not executable code. All stored numbers use SI units.`schema` is `agentfem.pipe-project/1`; `modelVersion` is `1.1.0`.
```json{ "schema": "agentfem.pipe-project/1", "modelVersion": "1.1.0", "units": "SI", "design": { "route": [ {"kind": "straight", "ratio": 5, "roll": 0}, {"kind": "elbow", "ratio": 2, "roll": 0}, {"kind": "straight", "ratio": 5, "roll": 0} ], "diameter": 0.2, "wall": 0.06, "supports": {"2": {"type": "spring", "k": 100000}}, "temperature": 100, "gravity": true, "damper": {"node": 3, "axis": 2, "c": 1000} }}```
`wall` is t/D; straight `ratio` is L/D, elbow `ratio` is R/D. Elbows also includetwo straight tangents, each 2D long. `roll` is degrees about the incoming localaxis. Component count is 1–10. Dimensions are selected from validated catalogentries; arbitrary dimensions and branching are not supported by this release.
Joint 0 is fixed in all six mechanical DOFs. Support nodes 1…N may be `none`,`spring` (global Z, k in N/m), `guide` (global Z displacement constrained), or`fixed` (all six DOFs). Grounded viscous damper axes 0/1/2 mean global X/Y/Z,with c in N·s/m. It can coexist with a support. A constrained damper directionhas zero relative velocity and therefore no dissipative effect.
Removal policy: deleting segment i removes its downstream joint i+1 and itsattachments. Downstream surviving joints are renumbered. Upstream attachmentsremain. A damper attached to the removed joint is disabled (c=0). Undo restoresthe entire prior design. Saving stores the design, not cached numerical answers;opening revalidates and recomputes it. Local drafts stay in browser storage.
## Dynamic experiment
The 12 lowest mass-normalized system modes are retained from the assembledCraig–Bampton matrices. A single grounded damper gives C=c b bᵀ, where b containsthe selected joint/direction entries of those modes. This full matrix is kept;cross-modal damping terms are not discarded. There is no background damping.
Initial displacement is the first undamped mode, normalized so its largestcentreline coordinate component is +0.001 m; initial velocity is zero. Motion isa perturbation about the linear equilibrium. The plotted geometry shows thisperturbation about the undeformed reference to isolate vibration. There is nothermal geometric stiffness or temperature-dependent material model.
Newmark average acceleration (β=1/4, γ=1/2) integrates for six first-mode periods.The integration step is at most 1/(80 f_max) and at least 2400 steps per record,rounded to a multiple of 600 for 601 output samples. Animation playback lasts8 seconds; chart time and exported time are physical seconds. Forces and forcepeaks are sampled at those 601 times. The no-damper reference is analytic cosine.
The independent Python reference uses a matrix exponential of the same modalequations. This verifies the time solver, not real-plant accuracy. Mode-retentionand energy-balance checks are provided separately. The release does not simulatehydraulic snubbers, gaps, preload, seismic excitation, pressure, fluid mass,plasticity, fatigue or piping-code compliance.
## Delivery
The comparison report shows unamplified static results and current supportforces/moments, along with material constants, model version and complete projectsettings. Print-to-PDF uses the browser. CSV includes port translations, supportforces/moments and, when a dynamic run exists, its time histories. The referenceand current designs are included in the printable report.30 unmodified lines3132333435362 unmodified lines39404130 unmodified lines- Apply uniform heating and self-weight.- Add fixed, vertical-restraint or linear spring supports.- Explore displacement, support force, and the first three natural modes.[Dataset](https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components) · [Downloadable model](https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM) · [AgentFEM](https://github.com/haoming-luo/agentfem)2 unmodified linesCode: Apache-2.0. `data/` numerical operators: CC BY 4.0. Vendor libraries retain their included MIT licenses.中文:拼接管道、设置支撑、改变温升,在网页中观察位移、支撑反力与振型。计算由浏览器完成;数据、模型与验证记录均可下载。30 unmodified lines31323334353637382 unmodified lines414243444530 unmodified lines- Apply uniform heating and self-weight.- Add fixed, vertical-restraint or linear spring supports.- Explore displacement, support force, and the first three natural modes.- Place a grounded viscous damper; compare physical free-decay histories with and without it.- Keep a baseline, undo edits, save/reopen projects, and export CSV or a printable report.[Dataset](https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components) · [Downloadable model](https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM) · [AgentFEM](https://github.com/haoming-luo/agentfem)2 unmodified linesCode: Apache-2.0. `data/` numerical operators: CC BY 4.0. Vendor libraries retain their included MIT licenses.中文:拼接管道、设置支撑、改变温升,在网页中观察位移、支撑反力与振型。计算由浏览器完成;数据、模型与验证记录均可下载。v1.1:增加真实黏性阻尼与振动衰减、末端拼接预览、撤销重做、方案保存、对照比较和结果导出。报告用于初步方案讨论,不替代管道规范校核。详见 [项目格式与动力学说明](PROJECT_FORMAT.md)。
123456743 unmodified lines515253545556575859604a8e89fe65965e0b5ab34a6a1b8faa412666e426ce92500dba6af0c8f3e0ca0b LICENSE-CODE9c3ceba7bc939a6d4a1ddd2c67e1485820ba38896770ca805239cb72d9b5e933 LICENSE-DATAf62bda15aa59d41541937a29ff345e3e3ea503939831bde3c8d6ddbbdda083ac README.md72b1833ac3613561a8c58687a4145234fe8e1ee4b7b8628b9117b0aa7fe3f86d app.jse246b1d3f40b6315fe5414fb8364f5c72f79264f6960b10b68bcfa197ac93421 data/catalog.json6e182b8c520a823f93cc8ea542868efd57620b4baa0e0ee857aae4f6f09e08c1 data/elbow-d120-t04-r1.5.jsonfb4c4dfa39b206a51ec0312a4d38c776b5b5d4dd204bd3900fd2fbe711ff5579 data/elbow-d120-t04-r2.json43 unmodified lines282dac78d4ddfeefd5f5a63b898c74941b3cd12c32855ce1b5bc25a6a8b67872 data/straight-d240-t06-r3.json7e34c8cd8b5777e076470bea605da69b7a8a8998ec254f78cb286caf9db27cce data/straight-d240-t06-r5.json588ef3d54997a9c56ad99dfc7e05b26a0d8e0050b91a7a8c5660ce33e109bf1e data/straight-d240-t06-r8.jsond6df8a4a8755682c06b97f3d4ff19d5bc2164828fd77b13fdc272fcb0b99fee8 index.html3ae714c78111d8b3aedd6a51b56fe2ff0468f2554a56d552463bdc7be97b810c preview.png2756bd769361ce35e2dc626d5f08995587e35a11d6a89f0c9db7a99d7002c9b7 solver.js8155a795b5ad4e6def48f0d0ddd3890015a614de30fad8f86eb350279141413b style.css80efaadea4f8a636a65fb0bd08bfef62f3d93a0bb94e2e7500f23176c5c07f4e vendor/OrbitControls.js346e97bfb765403f553352424558697837afc9625a02c5f6287e56c0bd3e2700 vendor/matrix.umd.jsac84c8235d52c5ed36243732bd33b96e37f2f8879a701682023194ad5dad8e67 vendor/ml-matrix-LICENSE.txt1234567843 unmodified lines52535455565758596061624a8e89fe65965e0b5ab34a6a1b8faa412666e426ce92500dba6af0c8f3e0ca0b LICENSE-CODE9c3ceba7bc939a6d4a1ddd2c67e1485820ba38896770ca805239cb72d9b5e933 LICENSE-DATA992de0b6f3559be62fa144c2d6127e151a2ca64551340fbe2e048797d052c17d PROJECT_FORMAT.md894a24e9e743da4dde22402971768825129d4fb0096b10c443bd3c028d4efa6e README.mdd869741e466584865f5cad5a91510cc9af3dacf925a63d61ca0fadbc9b6e2f59 app.jse246b1d3f40b6315fe5414fb8364f5c72f79264f6960b10b68bcfa197ac93421 data/catalog.json6e182b8c520a823f93cc8ea542868efd57620b4baa0e0ee857aae4f6f09e08c1 data/elbow-d120-t04-r1.5.jsonfb4c4dfa39b206a51ec0312a4d38c776b5b5d4dd204bd3900fd2fbe711ff5579 data/elbow-d120-t04-r2.json43 unmodified lines282dac78d4ddfeefd5f5a63b898c74941b3cd12c32855ce1b5bc25a6a8b67872 data/straight-d240-t06-r3.json7e34c8cd8b5777e076470bea605da69b7a8a8998ec254f78cb286caf9db27cce data/straight-d240-t06-r5.json588ef3d54997a9c56ad99dfc7e05b26a0d8e0050b91a7a8c5660ce33e109bf1e data/straight-d240-t06-r8.json91a87ae75aac8564704fd909c1579f7071a450f283e336ec96466ef01bc3767a index.html5dec817d04a07bdeb07da25d85352c6b834b38e6d61bd9594f83a160913466b2 preview.png7ea4f52701a689c288980eb1e8292ba05f9ae003cb6a4b05be85da98defa1491 project.js9d490da840d6e0ea83970e9ab3815579f270d3e76a61606d079dd74ecae10a96 solver.js161e791af55ca423d5a635d31463a8b7f065632ebf92bbc397aab524c9340004 style.css80efaadea4f8a636a65fb0bd08bfef62f3d93a0bb94e2e7500f23176c5c07f4e vendor/OrbitControls.js346e97bfb765403f553352424558697837afc9625a02c5f6287e56c0bd3e2700 vendor/matrix.umd.jsac84c8235d52c5ed36243732bd33b96e37f2f8879a701682023194ad5dad8e67 vendor/ml-matrix-LICENSE.txt
12345678910111213141516171819202122232425263 unmodified lines30313233343536373839404142432 unmodified lines4647484950515253545556575859606110 unmodified lines727374757677import * as THREE from 'three';import {OrbitControls} from './vendor/OrbitControls.js';const $=id=>document.getElementById(id);const words={en:{title:'Pipe Assembly Lab',subtitle:'Build a route. Watch the mechanics.',method:'How it works',route:'01 / ROUTE',reset:'Reset',spatial:'3D',diameter:'Outer diameter',wall:'Wall thickness',addStraight:'+ Straight',addElbow:'+ Elbow',remove:'Remove',bendPlane:'Bend direction',left:'Left',right:'Right',up:'Up',down:'Down',supports:'02 / SUPPORTS',station:'Connection',constraint:'Support',free:'Free',spring:'Vertical spring',guide:'Vertical restraint',fixed:'Fixed',stiffness:'Spring stiffness',rootFixed:'The inlet is fixed. Select a joint to add a support.',loading:'03 / LOADING',gravity:'Gravity',temperature:'Uniform temperature rise',material:'Steel · E 200 GPa · α 12 × 10⁻⁶/K',live:'COMPONENT ROM / LIVE SOLVE',reference:'Original shape',thermalView:'Expansion',scale:'Display',displacement:'Max. centreline displacement',reaction:'Largest support force',frequency:'First natural frequency',mass:'Pipe mass',gesture:'Drag to orbit · Scroll to zoom',footer:'Solid finite elements, assembled at your fingertips.',aboutTitle:'Small components. One connected system.',sceneTitle:'Room to expand.',sceneCaption:'A new support changes the whole route.',modeTitle:'Every route has a rhythm.',modeCaption:'Change a support. Shift a natural frequency.',deformed:'Deformed shape',modeShape:'Mode shape · normalized amplitude',loadingData:'Loading components…',solving:'Solving…',ready:'',component:'Component',length:'Length',radius:'Bend radius',joint:'Joint',inlet:'Inlet · fixed',limit:'Up to 10 components per route.',error:'Unable to solve. Check the route and supports.',overlap:'Parts of this route intersect. Contact is not modeled.',large:'Large displacement relative to pipe size; small-displacement model may not apply.',endpoint:'End',about:`<p>Each part starts as a three-dimensional hollow-pipe finite-element model, assembled with AgentFEM. Static constraint modes and 12 fixed-interface modes reduce it to a compact, reusable component.</p><p>Your browser connects those components, enforces support conditions, and solves equilibrium and the first three natural frequencies. This is a <b>physics-based reduced-order model</b>, not a neural network or a nearest-neighbour replay.</p><p><b>What you can explore</b><br>Uniform heating, gravity, fixed supports, vertical restraints and linear vertical springs. The animation scales a static solution; it is not a transient heat-transfer calculation. Mode amplitudes are normalized, not forced-vibration predictions.</p><p><b>Model</b><br>Linear elastic steel; small displacement; dry pipe. Bend components include straight tangents of 2 diameters at both ends. Ports enforce rigid mechanical cross-sections and allow prescribed radial thermal expansion. Centreline motion is displayed, not a local stress assessment. Pressure, fluid mass, contact, support preload and fatigue are outside this release.</p><p><a href="https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components" target="_blank" rel="noopener">Data & validation ↗</a> · <a href="https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM" target="_blank" rel="noopener">Operators & source ↗</a></p>`},zh:{title:'管道搭建实验室',subtitle:'拼一段管道,看力如何传递。',method:'数据与方法',route:'01 / 搭建管路',reset:'重置',spatial:'空间管路',diameter:'管道外径',wall:'管壁厚度',addStraight:'+ 直管',addElbow:'+ 弯管',remove:'删除',bendPlane:'弯曲方向',left:'向左',right:'向右',up:'向上',down:'向下',supports:'02 / 设置支撑',station:'连接位置',constraint:'支撑形式',free:'无支撑',spring:'竖向弹簧',guide:'限制竖向位移',fixed:'固定',stiffness:'弹簧刚度',rootFixed:'入口固定。选择连接点,可增设支撑。',loading:'03 / 施加载荷',gravity:'自重',temperature:'管壁均匀温升',material:'钢 · 弹性模量 200 GPa · 热膨胀系数 12 × 10⁻⁶/K',live:'实体有限元组件降阶 / 浏览器实时求解',reference:'原始轮廓',thermalView:'热膨胀',scale:'显示',displacement:'中心线最大位移',reaction:'最大支撑力',frequency:'一阶固有频率',mass:'管道质量',gesture:'拖动旋转 · 滚动缩放',footer:'从有限元组件,到可交互的管道系统。',aboutTitle:'拼接的是管道,也是力学模型。',sceneTitle:'让膨胀有去处。',sceneCaption:'增设一处支撑,整条管路都会改变。',modeTitle:'每条管路,都有自己的节奏。',modeCaption:'改变支撑,观察固有频率与振型。',deformed:'变形轮廓',modeShape:'振型 · 幅值归一化显示',loadingData:'正在载入组件…',solving:'正在计算…',ready:'',component:'组件',length:'直管长度',radius:'弯曲半径',joint:'连接点',inlet:'入口 · 固定',limit:'每条管路最多 10 个组件。',error:'暂时无法求解,请检查管路与支撑。',overlap:'当前管路��在相交部分,本模型不计算接触。',large:'位移相对管径较大,小变形假设可能不再适用。',endpoint:'末端',about:`<p>每个组件都来自 AgentFEM 装配的三维空心管实体有限元模型。保留静力约束模态与 12 阶内部模态,将大模型缩减为可重复拼接的小模型。</p><p>浏览器连接组件、施加支撑,实时计算静力平衡和前三阶固有频率。这里使用的是<b>基于力学的组件降阶模型</b>,不是神经网络,也不是查找相近结果。</p><p><b>可以观察什么</b><br>均匀受热、自重、固定支撑、竖向约束与线性弹簧下的管道响应。热膨胀动画仅缩放静力结果,不代表瞬态传热过程;振型幅值经过归一化,不代表实际受迫振动幅值。</p><p><b>模型条件</b><br>线弹性钢材、小变形、空管。弯管两端各含 2 倍管径的真实直管过渡段;接口采用刚性机械截面,并允许规定的径向热膨胀。显示中心线运动,不作局部应力评定。暂不包含内压、流体质量、接触、支撑预载和疲劳。</p><p><a href="https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components" target="_blank" rel="noopener">数据与验证 ↗</a> · <a href="https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM" target="_blank" rel="noopener">模型与源码 ↗</a></p>`}};let lang=new URLSearchParams(location.search).get('lang')==='zh'?'zh':'en';const t=k=>words[lang][k]||k;let route=[],selected=0,station=0,supports={},diameter=.2,wall=.06,result=null,view='static',playing=false,phase=Math.PI/1.4,requestId=0,needsFit=true,components=[];const cache=new Map(),worker=new Worker('./worker.js');let catalog=[];function translate(){document.documentElement.lang=lang;document.querySelectorAll('[data-t]').forEach(e=>e.textContent=t(e.dataset.t));$('language').textContent=lang==='en'?'中文':'EN';$('about-copy').innerHTML=t('about');updateSceneLabels();renderEditor();}function updateSceneLabels(){const m=view!=='static';$('scene-title').textContent=t(m?'modeTitle':'sceneTitle');$('scene-caption').textContent=t(m?'modeCaption':'sceneCaption');$('result-label').textContent=t(m?'modeShape':'deformed');$('scale').disabled=m;$('play').textContent=playing?'Ⅱ':'▶';updateMetrics();}function updateMetrics(){if(!result)return;const cards=[...document.querySelectorAll('.metrics article')];const staticValues=[(result.maxDisplacement*1000).toFixed(2),(Math.max(...result.supportForces.map(v=>Math.hypot(...v)))/1000).toFixed(2),result.frequency[0].toFixed(2)];for(let i=0;i<3;i++){const modal=view!=='static';cards[i].querySelector('span').textContent=modal?(lang==='zh'?['一阶固有频率','二阶固有频率','三阶固有频率'][i]:['First natural frequency','Second natural frequency','Third natural frequency'][i]):t(['displacement','reaction','frequency'][i]);cards[i].querySelector('strong').textContent=modal?result.frequency[i].toFixed(2):staticValues[i];cards[i].querySelector('strong').style.color=modal&&+view===i?'var(--accent)':'';cards[i].querySelector('small').textContent=modal?'Hz':['mm','kN','Hz'][i];}}function preset(name){const s=()=>({kind:'straight',ratio:5,roll:0}),e=(roll=0)=>({kind:'elbow',ratio:2,roll});route=name==='U'?[s(),e(),s(),e(),s()]:name==='spatial'?[s(),e(),s(),e(90),s()]:[s(),e(),s()];selected=0;station=0;supports={};needsFit=true;document.querySelectorAll('[data-preset]').forEach(b=>b.classList.toggle('active',b.dataset.preset===name));renderEditor();schedule();}function renderEditor(){if(!route.length)return;selected=Math.min(selected,route.length-1);station=Math.min(station,route.length);const c=route[selected];$('segments').replaceChildren(...route.map((r,i)=>{let b=document.createElement('button');b.textContent=`${i+1} ${r.kind==='straight'?'━':'╰'}`;b.className=i===selected?'active':'';b.title=`${t('component')} ${i+1}`;b.onclick=()=>{selected=i;renderEditor();highlight();};return b;}));$('selected-label').textContent=`${t('component')} ${selected+1}`;$('dimension-label').textContent=t(c.kind==='straight'?'length':'radius');$('dimension').replaceChildren(...(c.kind==='straight'?[3,5,8]:[1.5,2,3]).map(r=>new Option(`${Math.round(r*diameter*1000)} mm`,r)));$('dimension').value=c.ratio;$('roll-field').hidden=c.kind!=='elbow';$('roll').value=c.roll;$('remove').disabled=route.length===1;$('station').replaceChildren(...Array.from({length:route.length+1},(_,i)=>new Option(i===0?t('inlet'):`${t('joint')} ${i}${i===route.length?' · '+t('endpoint'):''}`,i)));$('station').value=station;$('support').disabled=station===0;$('support').value=station===0?'fixed':supports[station]?.type||'none';$('spring-field').hidden=$('support').value!=='spring';$('spring').value=Math.log10((supports[station]?.k||100000)/1000);$('spring-value').textContent=`${Math.round(10**+$('spring').value)} kN/m`;[...$('wall').options].forEach(o=>o.textContent=`${+(diameter*+o.value*1000).toFixed(1)} mm`);$('add-straight').disabled=$('add-elbow').disabled=route.length>=10;}let timer;function schedule(){clearTimeout(timer);timer=setTimeout(calculate,90);}async function calculate(){const id=++requestId;$('status').textContent=t('loadingData');try{const snapshot=route.map(r=>({...r}));components=await Promise.all(snapshot.map(async r=>{const entry=catalog.find(c=>c.kind===r.kind&&Math.abs(c.diameter-diameter)<1e-9&&Math.abs(c.thickness/diameter-wall)<1e-9&&Math.abs((r.kind==='straight'?c.length:c.radius)/diameter-r.ratio)<1e-9);if(!entry)throw Error('COMPONENT');if(!cache.has(entry.id))cache.set(entry.id,fetch('./data/'+entry.file).then(r=>{if(!r.ok)throw Error('FETCH');return r.json();}));return cache.get(entry.id);}));if(id!==requestId)return;$('status').textContent=t('solving');const ss=[{node:0,fixed:[0,1,2,3,4,5]}];Object.entries(supports).forEach(([node,s])=>{if(+node>route.length||+node===0)return;if(s.type==='fixed')ss.push({node:+node,fixed:[0,1,2,3,4,5]});if(s.type==='guide')ss.push({node:+node,fixed:[2]});if(s.type==='spring')ss.push({node:+node,spring:[0,0,s.k,0,0,0]});});worker.postMessage({id,request:{components,rolls:snapshot.map(r=>r.roll*Math.PI/180),deltaT:+$('temperature').value,gravity:$('gravity').checked?[0,0,-9.81]:[0,0,0],supports:ss}});}catch(e){if(id===requestId){$('status').textContent=t('error');console.error(e);}}}worker.onmessage=({data})=>{if(data.id!==requestId)return;if(data.error){$('status').textContent=t('error');console.error(data.error);return;}result=data.result;$('displacement').textContent=(result.maxDisplacement*1000).toFixed(2);$('reaction').textContent=(Math.max(...result.supportForces.map(v=>Math.hypot(...v)))/1000).toFixed(2);$('frequency').textContent=result.frequency[0].toFixed(2);$('mass').textContent=result.mass.toFixed(1);$('solve-time').textContent=`${Math.round(result.elapsedMs)} ms · ${route.length} ${lang==='zh'?'个组件':'components'}`;$('status').textContent=overlap(result.paths)?t('overlap'):result.maxDisplacement>diameter*.15?t('large'):'';rebuild();if(needsFit){fit();needsFit=false;}};function overlap(paths){for(let a=0;a<paths.length;a++)for(let b=a+2;b<paths.length;b++)for(let i=0;i<paths[a].length;i+=3)for(let j=0;j<paths[b].length;j+=3)if(Math.hypot(...paths[a][i].map((v,k)=>v-paths[b][j][k]))<diameter*.92)return true;return false;}$('language').onclick=()=>{lang=lang==='en'?'zh':'en';translate();if(result)$('solve-time').textContent=`${Math.round(result.elapsedMs)} ms · ${route.length} ${lang==='zh'?'个组件':'components'}`;};$('method').onclick=()=>$('about').showModal();$('close-about').onclick=()=>$('about').close();$('about').onclick=e=>{if(e.target===$('about')){const r=$('about').getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)$('about').close();}};document.querySelectorAll('[data-preset]').forEach(b=>b.onclick=()=>preset(b.dataset.preset));$('reset').onclick=()=>preset('L');$('diameter').onchange=()=>{diameter=+$('diameter').value;needsFit=true;renderEditor();schedule();};$('wall').onchange=()=>{wall=+$('wall').value;schedule();};$('dimension').onchange=()=>{route[selected].ratio=+$('dimension').value;needsFit=true;schedule();};$('roll').onchange=()=>{route[selected].roll=+$('roll').value;needsFit=true;schedule();};$('remove').onclick=()=>{if(route.length>1){route.splice(selected,1);supports={};selected=Math.max(0,selected-1);station=0;needsFit=true;renderEditor();schedule();}};for(const kind of ['straight','elbow'])$('add-'+kind).onclick=()=>{if(route.length>=10)return;route.push({kind,ratio:kind==='straight'?5:2,roll:0});selected=route.length-1;needsFit=true;renderEditor();schedule();};$('station').onchange=()=>{station=+$('station').value;renderEditor();highlight();};$('support').onchange=()=>{supports[station]={type:$('support').value,k:100000};renderEditor();schedule();};$('spring').oninput=()=>{supports[station]={type:'spring',k:1000*10**+$('spring').value};$('spring-value').textContent=`${Math.round(10**+$('spring').value)} kN/m`;schedule();};$('temperature').oninput=()=>{$('temperature-value').textContent=$('temperature').value+' K';schedule();};$('gravity').onchange=schedule;document.querySelectorAll('[data-view]').forEach(b=>b.onclick=()=>{view=b.dataset.view;playing=view!=='static';phase=view==='static'?Math.PI/1.4:Math.PI/5.2;document.querySelectorAll('[data-view]').forEach(x=>x.classList.toggle('active',x===b));updateSceneLabels();});$('play').onclick=()=>{playing=!playing;updateSceneLabels();};$('fit').onclick=()=>fit();$('toggle-tools').onclick=()=>document.body.classList.toggle('tools-open');// A small local studio provides neutral metallic reflections, without HDR downloads.const canvas=$('scene'),renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.25;const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(36,1,.01,1000);camera.up.set(0,0,1);const controls=new OrbitControls(camera,canvas);controls.enableDamping=true;controls.dampingFactor=.07;controls.minDistance=.3;controls.maxDistance=100;controls.target.set(1,1,0);camera.position.set(5,-6,5);const studio=new THREE.Scene();studio.background=new THREE.Color('#536461');for(const [pos,size,color,intensity] of [[[0,5,2],[8,4],0xffffff,4],[[3,-4,1],[3,7],0xbbe3e0,2],[[-4,0,4],[5,5],0xffe7c6,3]]){3 unmodified linesconst pmrem=new THREE.PMREMGenerator(renderer),env=pmrem.fromScene(studio,.03);scene.environment=env.texture;studio.traverse(o=>{o.geometry?.dispose();o.material?.dispose();});pmrem.dispose();scene.add(new THREE.HemisphereLight(0xe3fffa,0x18333d,2));const light=new THREE.DirectionalLight(0xffecd6,3);light.position.set(1,-2,5);scene.add(light);const pipeGroup=new THREE.Group(),supportGroup=new THREE.Group();scene.add(pipeGroup,supportGroup);let pipes=[],markers=[],ghosts=[];const material=new THREE.MeshStandardMaterial({color:0xb9c9c3,metalness:.82,roughness:.26});const ghostMat=new THREE.MeshBasicMaterial({color:0x688783,transparent:true,opacity:.17,depthWrite:false});const supportMat=new THREE.MeshStandardMaterial({color:0xd6b57d,metalness:.55,roughness:.35});const grid=new THREE.GridHelper(30,60,0x345a55,0x24433f);grid.rotation.x=Math.PI/2;grid.position.z=-.7;grid.material.transparent=true;grid.material.opacity=.3;scene.add(grid);function tube(points,radius){const n=points.length,around=16,pos=new Float32Array(n*around*3),idx=[];for(let i=0;i<n-1;i++)for(let j=0;j<around;j++){let a=i*around+j,b=i*around+(j+1)%around,c=a+around,d=b+around;idx.push(a,b,c,b,d,c);}const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(pos,3).setUsage(THREE.DynamicDrawUsage));g.setIndex(idx);g.userData={n,around};updateTube(g,points,radius);return g;}function updateTube(g,points,radius){const {n,around}=g.userData,arr=g.attributes.position.array;let prev=null;for(let i=0;i<n;i++){const p=new THREE.Vector3(...points[i]),a=new THREE.Vector3(...points[Math.max(0,i-1)]),b=new THREE.Vector3(...points[Math.min(n-1,i+1)]),dir=b.sub(a).normalize();let normal=prev?prev.clone().addScaledVector(dir,-prev.dot(dir)):new THREE.Vector3(0,0,1).addScaledVector(dir,-dir.z);if(normal.lengthSq()<.00001)normal.set(0,1,0).addScaledVector(dir,-dir.y);normal.normalize();prev=normal;const bin=new THREE.Vector3().crossVectors(dir,normal).normalize();for(let j=0;j<around;j++){let angle=j/around*Math.PI*2,point=p.clone().addScaledVector(normal,Math.cos(angle)*radius).addScaledVector(bin,Math.sin(angle)*radius);point.toArray(arr,(i*around+j)*3);}}g.attributes.position.needsUpdate=true;g.computeVertexNormals();g.computeBoundingSphere();}function clear(group){for(const o of [...group.children]){group.remove(o);o.traverse(v=>{v.geometry?.dispose();if(v.userData.ownMaterial)v.material?.dispose();});}}function rebuild(){clear(pipeGroup);clear(supportGroup);pipes=[];ghosts=[];markers=[];result.paths.forEach((p,i)=>{let m=material.clone();let mesh=new THREE.Mesh(tube(p,diameter/2),m);mesh.userData={segment:i,ownMaterial:true};pipeGroup.add(mesh);pipes.push(mesh);const ghost=new THREE.Mesh(tube(p,diameter/2),ghostMat);pipeGroup.add(ghost);ghosts.push(ghost);});result.nodes.forEach((p,i)=>{let marker=new THREE.Mesh(new THREE.SphereGeometry(diameter*.14,12,8),new THREE.MeshBasicMaterial({color:0x73ded1}));marker.position.set(...p);marker.userData={node:i,ownMaterial:true};supportGroup.add(marker);markers.push(marker);const type=i===0?'fixed':supports[i]?.type;if(type&&type!=='none'){const base=new THREE.Vector3(...p),height=diameter*2.6;const foot=new THREE.Mesh(new THREE.BoxGeometry(diameter*1.4,diameter*1.4,diameter*.15),supportMat);foot.position.copy(base).add(new THREE.Vector3(0,0,-height));supportGroup.add(foot);if(type==='spring'){let pts=[];for(let j=0;j<=100;j++){let a=j/100*Math.PI*12;pts.push([p[0]+Math.cos(a)*diameter*.26,p[1]+Math.sin(a)*diameter*.26,p[2]-diameter*.5-j/100*(height-diameter*.6)]);}supportGroup.add(new THREE.Mesh(tube(pts,diameter*.035),supportMat));}else{const leg=new THREE.Mesh(new THREE.CylinderGeometry(diameter*.08,diameter*.08,height,10),supportMat);leg.rotation.x=Math.PI/2;leg.position.copy(base).add(new THREE.Vector3(0,0,-height/2));supportGroup.add(leg);}const collar=new THREE.Mesh(new THREE.TorusGeometry(diameter*.54,diameter*.055,8,32),supportMat);const adjacent=result.paths[Math.min(i,result.paths.length-1)];const tangent=i===result.paths.length?new THREE.Vector3(...adjacent.at(-1)).sub(new THREE.Vector3(...adjacent.at(-2))):new THREE.Vector3(...adjacent[1]).sub(new THREE.Vector3(...adjacent[0]));collar.quaternion.setFromUnitVectors(new THREE.Vector3(0,0,1),tangent.normalize());collar.position.copy(base);supportGroup.add(collar);}});highlight();}function highlight(){geometryStamp='';updateMetrics();pipes.forEach((m,i)=>{m.material.color.setHex(i===selected?0xd1bd93:0xb9c9c3);});markers.forEach((m,i)=>{m.position.set(...result.nodes[i]);m.position.z+=diameter*.75;m.scale.setScalar(i===station?1.5:1);m.material.color.setHex(i===station?0xffd491:0x73ded1);});}function fit(){if(!result)return;geometryStamp='';const box=new THREE.Box3();result.paths.flat().forEach(p=>box.expandByPoint(new THREE.Vector3(...p)));const center=box.getCenter(new THREE.Vector3()),size=box.getSize(new THREE.Vector3()).length();controls.target.copy(center).add(new THREE.Vector3(0,0,-size*.035));camera.position.copy(center).add(new THREE.Vector3(1,-1.4,1.1).normalize().multiplyScalar(Math.max(2,size*2.25)*Math.max(1,1/camera.aspect)));camera.near=.01;camera.far=Math.max(100,size*20);camera.updateProjectionMatrix();grid.position.z=box.min.z-diameter*3;controls.update();}let pointerStart;canvas.addEventListener('pointerdown',e=>{pointerStart=[e.clientX,e.clientY];if(document.body.classList.contains('tools-open'))document.body.classList.remove('tools-open');});canvas.addEventListener('pointerup',e=>{if(!pointerStart||Math.hypot(e.clientX-pointerStart[0],e.clientY-pointerStart[1])>5)return;const rect=canvas.getBoundingClientRect(),ray=new THREE.Raycaster();ray.setFromCamera(new THREE.Vector2((e.clientX-rect.left)/rect.width*2-1,-(e.clientY-rect.top)/rect.height*2+1),camera);const hit=ray.intersectObjects([...markers,...pipes])[0];if(hit){if(hit.object.userData.node!==undefined)station=hit.object.userData.node;else selected=hit.object.userData.segment;renderEditor();highlight();}});let last=performance.now(),geometryStamp='';const reduced=matchMedia('(prefers-reduced-motion: reduce)').matches;2 unmodified linesconst rect=canvas.getBoundingClientRect();let draw=false;if(canvas.width!==Math.floor(rect.width*renderer.getPixelRatio())||canvas.height!==Math.floor(rect.height*renderer.getPixelRatio())){renderer.setSize(rect.width,rect.height,false);camera.aspect=rect.width/rect.height;camera.setViewOffset(rect.width,rect.height,0,rect.height*.13,rect.width,rect.height);camera.updateProjectionMatrix();fit();draw=true;}if(playing&&!reduced)phase+=dt;draw=controls.update()||draw;const stamp=[requestId,view,$('scale').value,phase].join('|');if(result&&stamp!==geometryStamp){geometryStamp=stamp;draw=true;let factor=view==='static'?(1-Math.cos(phase*1.4))/2:Math.sin(phase*2.6);const mode=+view;let amplitude=1;if(view!=='static'){const max=Math.max(...result.modeDisplacements.flat().map(m=>Math.hypot(m[0][mode],m[1][mode],m[2][mode])));amplitude=diameter*.8/Math.max(max,1e-30);if(reduced)factor=1;}for(let i=0;i<pipes.length;i++){const pts=result.paths[i].map((p,j)=>p.map((v,k)=>v+(view==='static'?result.displacements[i][j][k]*+$('scale').value:result.modeDisplacements[i][j][k][mode]*amplitude)*factor));updateTube(pipes[i].geometry,pts,diameter/2);// Show actual wall thickness at the two open external ports.for(const end of [0,1]){10 unmodified lines}}}if(draw)renderer.render(scene,camera);}requestAnimationFrame(frame);try{const response=await fetch('./data/catalog.json');if(!response.ok)throw Error('CATALOG');catalog=(await response.json()).components;translate();preset('L');}catch(e){$('status').textContent=t('error');console.error(e);}12345678910111213141516171819202122232425262728293031323334353637383 unmodified lines42434445464748495051525354552 unmodified lines5859606162636465666768697071727374757610 unmodified lines87888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import * as THREE from 'three';import {OrbitControls} from './vendor/OrbitControls.js';import {VERSION,validateProject,removeComponent} from './project.js';const $=id=>document.getElementById(id);const words={en:{title:'Pipe Assembly Lab',subtitle:'Build a route. Watch the mechanics.',method:'How it works',route:'01 / ROUTE',reset:'Reset',spatial:'3D',diameter:'Outer diameter',wall:'Wall thickness',addStraight:'+ Straight',addElbow:'+ Elbow',remove:'Remove',bendPlane:'Bend direction',left:'Left',right:'Right',up:'Up',down:'Down',supports:'02 / SUPPORTS',station:'Connection',constraint:'Support',free:'Free',spring:'Vertical spring',guide:'Vertical restraint',fixed:'Fixed',stiffness:'Spring stiffness',rootFixed:'The inlet is fixed. Select a joint to add a support.',loading:'03 / LOADING',gravity:'Gravity',temperature:'Uniform temperature rise',material:'Steel · E 200 GPa · α 12 × 10⁻⁶/K',live:'COMPONENT ROM / LIVE SOLVE',reference:'Original shape',thermalView:'Expansion',scale:'Display',displacement:'Max. centreline displacement',reaction:'Largest support force',frequency:'First natural frequency',mass:'Pipe mass',gesture:'Drag to orbit · Scroll to zoom',footer:'Solid finite elements, assembled at your fingertips.',aboutTitle:'Small components. One connected system.',sceneTitle:'Room to expand.',sceneCaption:'A new support changes the whole route.',modeTitle:'Every route has a rhythm.',modeCaption:'Change a support. Shift a natural frequency.',deformed:'Deformed shape',modeShape:'Mode shape · normalized amplitude',loadingData:'Loading components…',solving:'Solving…',ready:'',component:'Component',length:'Length',radius:'Bend radius',joint:'Joint',inlet:'Inlet · fixed',limit:'Up to 10 components per route.',error:'Unable to solve. Check the route and supports.',overlap:'Parts of this route intersect. Contact is not modeled.',large:'Large displacement relative to pipe size; small-displacement model may not apply.',endpoint:'End',about:`<p>Each part starts as a three-dimensional hollow-pipe finite-element model, assembled with AgentFEM. Static constraint modes and 12 fixed-interface modes reduce it to a compact, reusable component.</p><p>Your browser connects those components, enforces support conditions, and solves equilibrium and the first three natural frequencies. This is a <b>physics-based reduced-order model</b>, not a neural network or a nearest-neighbour replay.</p><p><b>What you can explore</b><br>Uniform heating, gravity, fixed supports, vertical restraints and linear vertical springs. The animation scales a static solution; it is not a transient heat-transfer calculation. Mode amplitudes are normalized, not forced-vibration predictions.</p><p><b>Model</b><br>Linear elastic steel; small displacement; dry pipe. Bend components include straight tangents of 2 diameters at both ends. Ports enforce rigid mechanical cross-sections and allow prescribed radial thermal expansion. Centreline motion is displayed, not a local stress assessment. Pressure, fluid mass, contact, support preload and fatigue are outside this release.</p><p><a href="https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components" target="_blank" rel="noopener">Data & validation ↗</a> · <a href="https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM" target="_blank" rel="noopener">Operators & source ↗</a></p>`},zh:{title:'管道搭建实验室',subtitle:'拼一段管道,看力如何传递。',method:'数据与方法',route:'01 / 搭建管路',reset:'重置',spatial:'空间管路',diameter:'管道外径',wall:'管壁厚度',addStraight:'+ 直管',addElbow:'+ 弯管',remove:'删除',bendPlane:'弯曲方向',left:'向左',right:'向右',up:'向上',down:'向下',supports:'02 / 设置支撑',station:'连接位置',constraint:'支撑形式',free:'无支撑',spring:'竖向弹簧',guide:'限制竖向位移',fixed:'固定',stiffness:'弹簧刚度',rootFixed:'入口固定。选择连接点,可增设支撑。',loading:'03 / 施加载荷',gravity:'自重',temperature:'管壁均匀温升',material:'钢 · 弹性模量 200 GPa · 热膨胀系数 12 × 10⁻⁶/K',live:'实体有限元组件降阶 / 浏览器实时求解',reference:'原始轮廓',thermalView:'热膨胀',scale:'显示',displacement:'中心线最大位移',reaction:'最大支撑力',frequency:'一阶固有频率',mass:'管道质量',gesture:'拖动旋转 · 滚动缩放',footer:'从有限元组件,到可交互的管道系统。',aboutTitle:'拼接的是管道,也是力学模型。',sceneTitle:'让膨胀有去处。',sceneCaption:'增设一处支撑,整条管路都会改变。',modeTitle:'每条管路,都有自己的节奏。',modeCaption:'改变支撑,观察固有频率与振型。',deformed:'变形轮廓',modeShape:'振型 · 幅值归一化显示',loadingData:'正在载入组件…',solving:'正在计算…',ready:'',component:'组件',length:'直管长度',radius:'弯曲半径',joint:'连接点',inlet:'入口 · 固定',limit:'每条管路最多 10 个组件。',error:'暂时无法求解,请检查管路与支撑。',overlap:'当前管路��在相交部分,本模型不计算接触。',large:'位移相对管径较大,小变形假设可能不再适用。',endpoint:'末端',about:`<p>每个组件都来自 AgentFEM 装配的三维空心管实体有限元模型。保留静力约束模态与 12 阶内部模态,将大模型缩减为可重复拼接的小模型。</p><p>浏览器连接组件、施加支撑,实时计算静力平衡和前三阶固有频率。这里使用的是<b>基于力学的组件降阶模型</b>,不是神经网络,也不是查找相近结果。</p><p><b>可以观察什么</b><br>均匀受热、自重、固定支撑、竖向约束与线性弹簧下的管道响应。热膨胀动画仅缩放静力结果,不代表瞬态传热过程;振型幅值经过归一化,不代表实际受迫振动幅值。</p><p><b>模型条件</b><br>线弹性钢材、小变形、空管。弯管两端各含 2 倍管径的真实直管过渡段;接口采用刚性机械截面,并允许规定的径向热膨胀。显示中心线运动,不作局部应力评定。暂不包含内压、流体质量、接触、支撑预载和疲劳。</p><p><a href="https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components" target="_blank" rel="noopener">数据与验证 ↗</a> · <a href="https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM" target="_blank" rel="noopener">模型与源码 ↗</a></p>`}};let lang=new URLSearchParams(location.search).get('lang')==='zh'?'zh':'en';const t=k=>words[lang][k]||k;let route=[],selected=0,station=0,supports={},diameter=.2,wall=.06,result=null,view='static',playing=false,phase=Math.PI/1.4,requestId=0,needsFit=true,components=[];let damper={node:3,axis:2,c:10000},baseline=null,pending=false,solvedDesign=null,dynamicTime=0,previewKind=null;const undoStack=[],redoStack=[];let lastDesign=null,historyMuted=false;Object.assign(words.en,{undo:'Undo',redo:'Redo',baseline:'Keep baseline',review:'Compare & export',save:'Save',open:'Open',damperTitle:'04 / VIBRATION & DAMPER',releaseHint:'First-mode release · initial peak 1 mm · zero initial velocity',axis:'Global direction',damping:'Damping coefficient',release:'Release & compare',extend:'Extend this end',confirm:'Connect',cancel:'Cancel',report:'Print / PDF',decayTitle:'Let the vibration settle.',decayCaption:'Same initial displacement. One grounded viscous damper.',without:'No damper',with:'With damper',custom:'Custom route',saved:'Project downloaded',invalid:'Invalid or incompatible project file.',baselineSaved:'Baseline retained',removed:'Segment removed; attachments on its downstream joint were removed.',noBaseline:'Keep a baseline, then change the route or supports.',current:'Current',comparison:'Baseline',modelScope:'Linear elastic dry pipe · small displacement · preliminary comparison, not a code compliance assessment.',blockedDamper:'The selected direction is restrained: the damper cannot move.',probe:'Measurement',peakForce:'Peak damper force',energyLeft:'Energy remaining',pending:'Updating…',reportHint:'Static values are unamplified. Reactions are forces acting on the pipe; moments are listed separately.',autoSaved:'Restored local draft',resetHint:'Choose a template',staticTitle:'Thermal displacement',jointSelect:'Select joint'});Object.assign(words.zh,{undo:'撤销',redo:'重做',baseline:'保留为对照',review:'对比与导出',save:'保存',open:'打开',damperTitle:'04 / 振动与阻尼器',releaseHint:'一阶振型释放 · 初始峰值 1 mm · 初速度为零',axis:'全局方向',damping:'阻尼系数',release:'释放并对比',extend:'从末端继续搭建',confirm:'接上',cancel:'取消',report:'打印 / PDF',decayTitle:'让振动慢慢停下来。',decayCaption:'相同初始变形,对比接地黏性阻尼器的作用。',without:'无阻尼器',with:'有阻尼器',custom:'自定义管路',saved:'方案已下载',invalid:'方案文件无效或模型版本不兼容。',baselineSaved:'已保留对照方案',removed:'已删除管段及其下游连接点上的附件,其余支撑保留。',noBaseline:'先保留对照,再调整管路或支撑。',current:'当前方案',comparison:'对照方案',modelScope:'线弹性空管 · 小变形 · 用于方案初步比选,不作规范合格判定。',blockedDamper:'该方向已被约束,阻尼器无法运动。',probe:'测点',peakForce:'阻尼器峰值作用力',energyLeft:'剩余振动能量',pending:'正在更新…',reportHint:'静力数值均为真实量,未乘显示倍数。反力为支撑对管道的作用力,力矩单独列出。',autoSaved:'已恢复本地草稿',resetHint:'选择初始管路',staticTitle:'受热位移',jointSelect:'选择连接点'});const cache=new Map(),worker=new Worker('./worker.js');let catalog=[];words.zh.energyLeft='结束时剩余能量';words.en.energyLeft='Energy at end of window';function translate(){document.documentElement.lang=lang;document.querySelectorAll('[data-t]').forEach(e=>e.textContent=t(e.dataset.t));$('language').textContent=lang==='en'?'中文':'EN';$('about-copy').innerHTML=t('about')+(lang==='zh'?'<p><b>振动衰减</b><br>相同的一阶振型初始变形(最大坐标分量 1 mm),初速度为零;围绕线性平衡位置释放。单个接地黏性阻尼器 F = −c v,保持完整的非比例模态阻尼矩阵。保留 12 阶系统模态,采用 Newmark 平均加速度法,不加背景阻尼。动画放慢至 8 秒,图中时间为物理时间;不模拟瞬态升温、地震或实际振源。</p>':'<p><b>Free decay</b><br>First-mode release: largest coordinate component 1 mm, zero initial velocity, about linear equilibrium. One grounded viscous damper F = −c v, full non-proportional modal damping, 12 system modes, Newmark average acceleration, no background damping. Playback is stretched to 8 seconds; the chart uses physical time. No transient heating, seismic input or operating excitation is modeled.</p>');updateSceneLabels();renderEditor();syncExtras();geometryStamp='';}function updateSceneLabels(){const d=view==='decay',m=view!=='static'&&!d;$('scene-title').textContent=t(d?'decayTitle':m?'modeTitle':'sceneTitle');$('scene-caption').textContent=t(d?'decayCaption':m?'modeCaption':'sceneCaption');$('reference-label').textContent=t(d?'without':'reference');$('result-label').textContent=t(d?'with':m?'modeShape':'deformed');$('scale').disabled=m;$('play').textContent=playing?'Ⅱ':'▶';$('trace-panel').hidden=!d;document.querySelectorAll('[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));updateMetrics();}function updateMetrics(){if(!result)return;const cards=[...document.querySelectorAll('.metrics article')];const staticValues=[(result.maxDisplacement*1000).toFixed(2),(Math.max(...result.supportForces.map(v=>Math.hypot(...v)))/1000).toFixed(2),result.frequency[0].toFixed(2)];for(let i=0;i<3;i++){const modal=view!=='static'&&view!=='decay';cards[i].querySelector('span').textContent=modal?(lang==='zh'?['一阶固有频率','二阶固有频率','三阶固有频率'][i]:['First natural frequency','Second natural frequency','Third natural frequency'][i]):t(['displacement','reaction','frequency'][i]);cards[i].querySelector('strong').textContent=modal?result.frequency[i].toFixed(2):staticValues[i];cards[i].querySelector('strong').style.color=modal&&+view===i?'var(--accent)':'';cards[i].querySelector('small').textContent=modal?'Hz':['mm','kN','Hz'][i];}if(view==='decay'&&result.dynamics){const d=result.dynamics;cards[0].querySelector('span').textContent=t('peakForce');cards[0].querySelector('strong').textContent=(d.peakForce/1000).toFixed(3);cards[0].querySelector('small').textContent='kN';cards[1].querySelector('span').textContent=t('energyLeft');cards[1].querySelector('strong').textContent=(100*d.energy.at(-1)/d.initialEnergy).toFixed(1);cards[1].querySelector('small').textContent='%';} }function preset(name){const s=()=>({kind:'straight',ratio:5,roll:0}),e=(roll=0)=>({kind:'elbow',ratio:2,roll});route=name==='U'?[s(),e(),s(),e(),s()]:name==='spatial'?[s(),e(),s(),e(90),s()]:[s(),e(),s()];selected=0;station=0;supports={};needsFit=true;document.querySelectorAll('[data-preset]').forEach(b=>b.classList.toggle('active',b.dataset.preset===name));renderEditor();schedule();}function renderEditor(){if(!route.length)return;selected=Math.min(selected,route.length-1);station=Math.min(station,route.length);const c=route[selected];$('segments').replaceChildren(...route.map((r,i)=>{let b=document.createElement('button');b.textContent=`${i+1} ${r.kind==='straight'?'━':'╰'}`;b.className=i===selected?'active':'';b.title=`${t('component')} ${i+1}`;b.onclick=()=>{selected=i;renderEditor();highlight();};return b;}));$('selected-label').textContent=`${t('component')} ${selected+1}`;$('dimension-label').textContent=t(c.kind==='straight'?'length':'radius');$('dimension').replaceChildren(...(c.kind==='straight'?[3,5,8]:[1.5,2,3]).map(r=>new Option(`${Math.round(r*diameter*1000)} mm`,r)));$('dimension').value=c.ratio;$('roll-field').hidden=c.kind!=='elbow';$('roll').value=c.roll;$('remove').disabled=route.length===1;$('station').replaceChildren(...Array.from({length:route.length+1},(_,i)=>new Option(i===0?t('inlet'):`${t('joint')} ${i}${i===route.length?' · '+t('endpoint'):''}`,i)));$('station').value=station;$('support').disabled=station===0;$('support').value=station===0?'fixed':supports[station]?.type||'none';$('spring-field').hidden=$('support').value!=='spring';$('spring').value=Math.log10((supports[station]?.k||100000)/1000);$('spring-value').textContent=`${Math.round(10**+$('spring').value)} kN/m`;[...$('wall').options].forEach(o=>o.textContent=`${+(diameter*+o.value*1000).toFixed(1)} mm`);$('add-straight').disabled=$('add-elbow').disabled=route.length>=10;}let timer;function schedule(){requestId++;pending=true;document.body.classList.add('solving');$('status').textContent=t('pending');['baseline','review','save-project'].forEach(id=>$(id).disabled=true);clearTimeout(timer);clearPreview();timer=setTimeout(calculate,90);}async function calculate(){const id=++requestId;$('status').textContent=t('loadingData');try{const design=getDesign(),snapshot=design.route;const loaded=await Promise.all(snapshot.map(r=>loadComponent(r,design.diameter,design.wall)));if(id!==requestId)return;components=loaded;$('status').textContent=t('solving');const ss=[{node:0,fixed:[0,1,2,3,4,5]}];Object.entries(design.supports).forEach(([node,s])=>{if(+node>snapshot.length||+node===0)return;if(s.type==='fixed')ss.push({node:+node,fixed:[0,1,2,3,4,5]});if(s.type==='guide')ss.push({node:+node,fixed:[2]});if(s.type==='spring')ss.push({node:+node,spring:[0,0,s.k,0,0,0]});});solvedDesign=design;worker.postMessage({id,request:{components,rolls:snapshot.map(r=>r.roll*Math.PI/180),deltaT:design.temperature,gravity:design.gravity?[0,0,-9.81]:[0,0,0],supports:ss,...(view==='decay'?{dynamic:design.damper}:{})}});}catch(e){if(id===requestId){$('status').textContent=t('error');console.error(e);}}}async function loadComponent(r,d=diameter,w=wall){const entry=catalog.find(c=>c.kind===r.kind&&Math.abs(c.diameter-d)<1e-9&&Math.abs(c.thickness/d-w)<1e-9&&Math.abs((r.kind==='straight'?c.length:c.radius)/d-r.ratio)<1e-9);if(!entry)throw Error('COMPONENT');if(!cache.has(entry.id))cache.set(entry.id,fetch('./data/'+entry.file).then(r=>{if(!r.ok)throw Error('FETCH');return r.json();}).catch(e=>{cache.delete(entry.id);throw e;}));return cache.get(entry.id);}worker.onmessage=({data})=>{if(data.id!==requestId)return;if(data.error){$('status').textContent=t('error');console.error(data.error);return;}result=data.result;pending=false;['baseline','review','save-project'].forEach(id=>$(id).disabled=false);dynamicTime=0;document.body.classList.remove('solving');$('mass').textContent=result.mass.toFixed(1);$('solve-time').textContent=`${Math.round(result.elapsedMs)} ms · ${route.length} ${lang==='zh'?'个组件':'components'}`;$('status').textContent=overlap(result.paths)?t('overlap'):result.maxDisplacement>diameter*.15?t('large'):result.dynamics?.blocked?t('blockedDamper'):'';rebuild();syncExtras();updateSceneLabels();try{localStorage.setItem('agentfem-pipe-draft',JSON.stringify(projectEnvelope(solvedDesign)));}catch{}if(needsFit){fit();needsFit=false;}};function overlap(paths){for(let a=0;a<paths.length;a++)for(let b=a+2;b<paths.length;b++)for(let i=0;i<paths[a].length;i+=3)for(let j=0;j<paths[b].length;j+=3)if(Math.hypot(...paths[a][i].map((v,k)=>v-paths[b][j][k]))<diameter*.92)return true;return false;}$('language').onclick=()=>{lang=lang==='en'?'zh':'en';translate();if(result)$('solve-time').textContent=`${Math.round(result.elapsedMs)} ms · ${route.length} ${lang==='zh'?'个组件':'components'}`;};$('method').onclick=()=>$('about').showModal();$('close-about').onclick=()=>$('about').close();$('about').onclick=e=>{if(e.target===$('about')){const r=$('about').getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)$('about').close();}};document.querySelectorAll('[data-preset]').forEach(b=>b.onclick=()=>{preset(b.dataset.preset);damper.node=route.length;syncExtras();});$('reset').onclick=()=>{preset('L');damper.node=route.length;syncExtras();};$('diameter').onchange=()=>{diameter=+$('diameter').value;needsFit=true;renderEditor();schedule();};$('wall').onchange=()=>{wall=+$('wall').value;schedule();};$('dimension').onchange=()=>{route[selected].ratio=+$('dimension').value;needsFit=true;schedule();};$('roll').onchange=()=>{route[selected].roll=+$('roll').value;needsFit=true;schedule();};$('remove').onclick=()=>{if(route.length>1){const next=removeComponent(getDesign(),selected);applyDesign(next);toast(t('removed'));}};for(const kind of ['straight','elbow'])$('add-'+kind).onclick=()=>{if(route.length>=10)return;route.push({kind,ratio:kind==='straight'?5:2,roll:0});selected=route.length-1;needsFit=true;renderEditor();schedule();};$('station').onchange=()=>{station=+$('station').value;renderEditor();highlight();};$('support').onchange=()=>{supports[station]={type:$('support').value,k:100000};renderEditor();schedule();};$('spring').oninput=()=>{supports[station]={type:'spring',k:1000*10**+$('spring').value};$('spring-value').textContent=`${Math.round(10**+$('spring').value)} kN/m`;schedule();};$('temperature').oninput=()=>{$('temperature-value').textContent=$('temperature').value+' K';schedule();};$('gravity').onchange=schedule;document.querySelectorAll('[data-view]').forEach(b=>b.onclick=()=>{view=b.dataset.view;playing=view!=='static';phase=view==='static'?Math.PI/1.4:Math.PI/5.2;updateSceneLabels();});$('play').onclick=()=>{if(view==='decay'&&result?.dynamics&&dynamicTime>=result.dynamics.time.at(-1))dynamicTime=0;playing=!playing;updateSceneLabels();};$('fit').onclick=()=>fit();$('toggle-tools').onclick=()=>document.body.classList.toggle('tools-open');// A small local studio provides neutral metallic reflections, without HDR downloads.const canvas=$('scene'),renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:true,preserveDrawingBuffer:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.25;const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(36,1,.01,1000);camera.up.set(0,0,1);const controls=new OrbitControls(camera,canvas);controls.enableDamping=true;controls.dampingFactor=.07;controls.minDistance=.3;controls.maxDistance=100;controls.target.set(1,1,0);camera.position.set(5,-6,5);const studio=new THREE.Scene();studio.background=new THREE.Color('#536461');for(const [pos,size,color,intensity] of [[[0,5,2],[8,4],0xffffff,4],[[3,-4,1],[3,7],0xbbe3e0,2],[[-4,0,4],[5,5],0xffe7c6,3]]){3 unmodified linesconst pmrem=new THREE.PMREMGenerator(renderer),env=pmrem.fromScene(studio,.03);scene.environment=env.texture;studio.traverse(o=>{o.geometry?.dispose();o.material?.dispose();});pmrem.dispose();scene.add(new THREE.HemisphereLight(0xe3fffa,0x18333d,2));const light=new THREE.DirectionalLight(0xffecd6,3);light.position.set(1,-2,5);scene.add(light);const pipeGroup=new THREE.Group(),supportGroup=new THREE.Group(),damperGroup=new THREE.Group();scene.add(pipeGroup,supportGroup,damperGroup);let pipes=[],markers=[],ghosts=[];const material=new THREE.MeshStandardMaterial({color:0xb9c9c3,metalness:.82,roughness:.26});const ghostMat=new THREE.MeshBasicMaterial({color:0x688783,transparent:true,opacity:.17,depthWrite:false});const supportMat=new THREE.MeshStandardMaterial({color:0xd6b57d,metalness:.55,roughness:.35});const grid=new THREE.GridHelper(30,60,0x345a55,0x24433f);grid.rotation.x=Math.PI/2;grid.position.z=-.7;grid.material.transparent=true;grid.material.opacity=.3;scene.add(grid);function tube(points,radius){const n=points.length,around=16,pos=new Float32Array(n*around*3),idx=[];for(let i=0;i<n-1;i++)for(let j=0;j<around;j++){let a=i*around+j,b=i*around+(j+1)%around,c=a+around,d=b+around;idx.push(a,b,c,b,d,c);}const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(pos,3).setUsage(THREE.DynamicDrawUsage));g.setIndex(idx);g.userData={n,around};updateTube(g,points,radius);return g;}function updateTube(g,points,radius){const {n,around}=g.userData,arr=g.attributes.position.array;let prev=null;for(let i=0;i<n;i++){const p=new THREE.Vector3(...points[i]),a=new THREE.Vector3(...points[Math.max(0,i-1)]),b=new THREE.Vector3(...points[Math.min(n-1,i+1)]),dir=b.sub(a).normalize();let normal=prev?prev.clone().addScaledVector(dir,-prev.dot(dir)):new THREE.Vector3(0,0,1).addScaledVector(dir,-dir.z);if(normal.lengthSq()<.00001)normal.set(0,1,0).addScaledVector(dir,-dir.y);normal.normalize();prev=normal;const bin=new THREE.Vector3().crossVectors(dir,normal).normalize();for(let j=0;j<around;j++){let angle=j/around*Math.PI*2,point=p.clone().addScaledVector(normal,Math.cos(angle)*radius).addScaledVector(bin,Math.sin(angle)*radius);point.toArray(arr,(i*around+j)*3);}}g.attributes.position.needsUpdate=true;g.computeVertexNormals();g.computeBoundingSphere();}function clear(group){for(const o of [...group.children]){group.remove(o);o.traverse(v=>{v.geometry?.dispose();if(v.userData.ownMaterial)v.material?.dispose();});}}function rebuild(){clear(pipeGroup);clear(supportGroup);pipes=[];ghosts=[];markers=[];result.paths.forEach((p,i)=>{let m=material.clone();let mesh=new THREE.Mesh(tube(p,diameter/2),m);mesh.userData={segment:i,ownMaterial:true};pipeGroup.add(mesh);pipes.push(mesh);const ghost=new THREE.Mesh(tube(p,diameter/2),ghostMat);pipeGroup.add(ghost);ghosts.push(ghost);});result.nodes.forEach((p,i)=>{let marker=new THREE.Mesh(new THREE.SphereGeometry(diameter*.14,12,8),new THREE.MeshBasicMaterial({color:0x73ded1}));marker.position.set(...p);marker.userData={node:i,ownMaterial:true};supportGroup.add(marker);markers.push(marker);const type=i===0?'fixed':supports[i]?.type;if(type&&type!=='none'){const base=new THREE.Vector3(...p),height=diameter*2.6;const foot=new THREE.Mesh(new THREE.BoxGeometry(diameter*1.4,diameter*1.4,diameter*.15),supportMat);foot.position.copy(base).add(new THREE.Vector3(0,0,-height));supportGroup.add(foot);if(type==='spring'){let pts=[];for(let j=0;j<=100;j++){let a=j/100*Math.PI*12;pts.push([p[0]+Math.cos(a)*diameter*.26,p[1]+Math.sin(a)*diameter*.26,p[2]-diameter*.5-j/100*(height-diameter*.6)]);}supportGroup.add(new THREE.Mesh(tube(pts,diameter*.035),supportMat));}else{const leg=new THREE.Mesh(new THREE.CylinderGeometry(diameter*.08,diameter*.08,height,10),supportMat);leg.rotation.x=Math.PI/2;leg.position.copy(base).add(new THREE.Vector3(0,0,-height/2));supportGroup.add(leg);}const collar=new THREE.Mesh(new THREE.TorusGeometry(diameter*.54,diameter*.055,8,32),supportMat);const adjacent=result.paths[Math.min(i,result.paths.length-1)];const tangent=i===result.paths.length?new THREE.Vector3(...adjacent.at(-1)).sub(new THREE.Vector3(...adjacent.at(-2))):new THREE.Vector3(...adjacent[1]).sub(new THREE.Vector3(...adjacent[0]));collar.quaternion.setFromUnitVectors(new THREE.Vector3(0,0,1),tangent.normalize());collar.position.copy(base);supportGroup.add(collar);}});highlight();}function highlight(){geometryStamp='';updateMetrics();syncExtras();drawDamper();pipes.forEach((m,i)=>{m.material.color.setHex(i===selected?0xd1bd93:0xb9c9c3);});markers.forEach((m,i)=>{m.position.set(...result.nodes[i]);m.position.z+=diameter*.75;m.scale.setScalar(i===station?1.5:1);m.material.color.setHex(i===station?0xffd491:0x73ded1);});}function fit(){if(!result)return;geometryStamp='';const box=new THREE.Box3();result.paths.flat().forEach(p=>box.expandByPoint(new THREE.Vector3(...p)));const center=box.getCenter(new THREE.Vector3()),size=box.getSize(new THREE.Vector3()).length();controls.target.copy(center).add(new THREE.Vector3(0,0,-size*.035));camera.position.copy(center).add(new THREE.Vector3(1,-1.4,1.1).normalize().multiplyScalar(Math.max(2,size*2.25)*Math.max(1,1/camera.aspect)));camera.near=.01;camera.far=Math.max(100,size*20);camera.updateProjectionMatrix();grid.position.z=box.min.z-diameter*3;controls.update();}let pointerStart;canvas.addEventListener('pointerdown',e=>{pointerStart=[e.clientX,e.clientY];if(document.body.classList.contains('tools-open'))document.body.classList.remove('tools-open');});canvas.addEventListener('pointerup',e=>{if(!pointerStart||Math.hypot(e.clientX-pointerStart[0],e.clientY-pointerStart[1])>5)return;const rect=canvas.getBoundingClientRect(),ray=new THREE.Raycaster();ray.setFromCamera(new THREE.Vector2((e.clientX-rect.left)/rect.width*2-1,-(e.clientY-rect.top)/rect.height*2+1),camera);const hit=ray.intersectObjects([...markers,...pipes])[0];if(hit){if(hit.object.userData.node!==undefined)station=hit.object.userData.node;else selected=hit.object.userData.segment;renderEditor();highlight();}});let last=performance.now(),geometryStamp='';const reduced=matchMedia('(prefers-reduced-motion: reduce)').matches;2 unmodified linesconst rect=canvas.getBoundingClientRect();let draw=false;if(canvas.width!==Math.floor(rect.width*renderer.getPixelRatio())||canvas.height!==Math.floor(rect.height*renderer.getPixelRatio())){renderer.setSize(rect.width,rect.height,false);camera.aspect=rect.width/rect.height;camera.setViewOffset(rect.width,rect.height,rect.width*.06,rect.height*.13,rect.width,rect.height);camera.updateProjectionMatrix();fit();draw=true;}if(playing&&!reduced&&!pending){phase+=dt;if(view==='decay'&&result?.dynamics){dynamicTime=Math.min(result.dynamics.time.at(-1),dynamicTime+dt*result.dynamics.time.at(-1)/8);if(dynamicTime>=result.dynamics.time.at(-1)){playing=false;updateSceneLabels();}}}draw=controls.update()||draw;const stamp=[requestId,view,$('scale').value,phase,dynamicTime].join('|');if(result&&!pending&&stamp!==geometryStamp){geometryStamp=stamp;draw=true;let factor=view==='static'?(1-Math.cos(phase*1.4))/2:Math.sin(phase*2.6);const mode=+view;let amplitude=1;if(view!=='static'&&view!=='decay'){const max=Math.max(...result.modeDisplacements.flat().map(m=>Math.hypot(m[0][mode],m[1][mode],m[2][mode])));amplitude=diameter*.8/Math.max(max,1e-30);if(reduced)factor=1;}const dyn=view==='decay'?result.dynamics:null,frameIndex=dyn?Math.min(600,Math.floor(dynamicTime/dyn.time.at(-1)*600)):0;for(let i=0;i<pipes.length;i++){const pts=result.paths[i].map((p,j)=>p.map((v,k)=>v+(view==='decay'?(dyn?result.modeDisplacements[i][j][k].reduce((s,x,m)=>s+x*dyn.coordinates[frameIndex][m],0)*+$('scale').value:0):view==='static'?result.displacements[i][j][k]*+$('scale').value*factor:result.modeDisplacements[i][j][k][mode]*amplitude*factor)));const reference=dyn?result.paths[i].map((p,j)=>p.map((v,k)=>v+result.modeDisplacements[i][j][k][0]*dyn.coordinates[0][0]*Math.cos(2*Math.PI*dyn.frequency[0]*dynamicTime)*+$('scale').value)):result.paths[i];updateTube(ghosts[i].geometry,reference,diameter/2);updateTube(pipes[i].geometry,pts,diameter/2);// Show actual wall thickness at the two open external ports.for(const end of [0,1]){10 unmodified lines}}}if(draw){renderer.render(scene,camera);positionLabels();if(view==='decay'&&result?.dynamics)drawTrace();}}requestAnimationFrame(frame);// Editing, persistence and reporting are independent of the operator assembler.function getDesign(){return structuredClone({route,diameter,wall,supports,temperature:+$('temperature').value,gravity:$('gravity').checked,damper});}function projectEnvelope(design){return {schema:'agentfem.pipe-project/1',modelVersion:VERSION,units:'SI',design};}function applyDesign(p){document.querySelectorAll('[data-preset]').forEach(b=>b.classList.remove('active'));route=structuredClone(p.route);diameter=p.diameter;wall=p.wall;supports=structuredClone(p.supports);damper={...p.damper};selected=Math.min(selected,route.length-1);station=Math.min(station,route.length);$('diameter').value=diameter;$('wall').value=wall;$('temperature').value=p.temperature;$('temperature-value').textContent=p.temperature+' K';$('gravity').checked=p.gravity;needsFit=true;renderEditor();syncExtras();schedule();}function toast(message){$('project-state').textContent=message;}function syncExtras(){if(!route.length)return;damper.node=Math.min(route.length,Math.max(1,damper.node));$('damper-node').replaceChildren(...route.map((_,i)=>new Option(`${t('joint')} ${i+1}`,i+1)));$('damper-node').value=damper.node;$('damper-axis').value=damper.axis;$('damper').value=damper.c/1000;$('damper-value').textContent=`${damper.c/1000} kN·s/m`;$('end-actions').hidden=station!==route.length||route.length>=10||pending||view==='decay';$('undo').disabled=!undoStack.length;$('redo').disabled=!redoStack.length;}function drawDamper(){clear(damperGroup);if(!result||!damper.c||!result.nodes[damper.node])return;const joint=new THREE.Vector3(...result.nodes[damper.node]),p=joint.clone(),axis=new THREE.Vector3(...[0,1,2].map(i=>i===damper.axis?-1:0)),length=diameter*3;// Offset the schematic attachment symbol so an axial damper is not hidden inside the pipe.p.setComponent(damper.axis===0?1:0,p.getComponent(damper.axis===0?1:0)+diameter*1.5);const link=new THREE.Line(new THREE.BufferGeometry().setFromPoints([joint,p]),new THREE.LineBasicMaterial({color:0x80ded0}));link.userData.ownMaterial=true;damperGroup.add(link);const cylinder=(radius,len,center,color)=>{const m=new THREE.Mesh(new THREE.CylinderGeometry(radius,radius,len,16),new THREE.MeshStandardMaterial({color,metalness:.7,roughness:.25}));m.userData.ownMaterial=true;m.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),axis);m.position.copy(center);damperGroup.add(m);};cylinder(diameter*.055,length,p.clone().addScaledVector(axis,length/2),0xd9e6e2);cylinder(diameter*.19,length*.48,p.clone().addScaledVector(axis,length*.65),0x67c2b3);const base=new THREE.Mesh(new THREE.BoxGeometry(diameter*.65,diameter*.65,diameter*.14),supportMat);base.quaternion.setFromUnitVectors(new THREE.Vector3(0,0,1),axis);base.position.copy(p).addScaledVector(axis,length);damperGroup.add(base);}const editIds=new Set(['diameter','wall','dimension','roll','support','spring','temperature','gravity','damper-node','damper-axis','damper','remove','reset','add-straight','add-elbow','confirm-part']);const historyEvents=new WeakMap();for(const event of ['click','change','input']){document.addEventListener(event,e=>{const edit=editIds.has(e.target.id)||e.target.dataset.preset;if(!edit||historyMuted||!lastDesign)return;if((event==='click'&&e.target.tagName!=='BUTTON')||(event!=='click'&&e.target.tagName==='BUTTON'))return;historyEvents.set(e,structuredClone(lastDesign));},true);document.addEventListener(event,e=>{const before=historyEvents.get(e);if(!before)return;const now=getDesign();if(JSON.stringify(before)!==JSON.stringify(now)){undoStack.push(before);if(undoStack.length>80)undoStack.shift();redoStack.length=0;lastDesign=now;document.querySelectorAll('[data-preset]').forEach(b=>b.classList.remove('active'));if(e.target.id!=='remove')toast(t('custom'));}syncExtras();});}function restore(stack,other){if(!stack.length)return;other.push(getDesign());historyMuted=true;applyDesign(stack.pop());lastDesign=getDesign();historyMuted=false;syncExtras();toast(t('custom'));}$('undo').onclick=()=>restore(undoStack,redoStack);$('redo').onclick=()=>restore(redoStack,undoStack);function download(name,text,type='application/json'){const url=URL.createObjectURL(new Blob([text],{type})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}$('save-project').onclick=()=>{if(!pending){download('AgentFEM-pipe-project.json',JSON.stringify({...projectEnvelope(getDesign()),baseline:baseline?projectEnvelope(baseline.design):null},null,2));toast(t('saved'));}};$('open-project').onclick=()=>$('project-file').click();$('project-file').onchange=async()=>{const file=$('project-file').files[0];if(!file)return;try{if(file.size>100000)throw Error('SIZE');const raw=JSON.parse(await file.text()),p=validateProject(raw),bp=raw.baseline?validateProject(raw.baseline):null;const revision=requestId;const br=bp?await computeSnapshot(bp):null;if(revision!==requestId)throw Error('CHANGED');undoStack.push(getDesign());redoStack.length=0;applyDesign(p);lastDesign=getDesign();baseline=bp?{design:bp,result:br}:null;toast(file.name);}catch{toast(t('invalid'));}$('project-file').value='';};async function computeSnapshot(p){const cs=await Promise.all(p.route.map(r=>loadComponent(r,p.diameter,p.wall))),ss=[{node:0,fixed:[0,1,2,3,4,5]}];for(const [node,s] of Object.entries(p.supports)){if(s.type==='fixed')ss.push({node:+node,fixed:[0,1,2,3,4,5]});if(s.type==='guide')ss.push({node:+node,fixed:[2]});if(s.type==='spring')ss.push({node:+node,spring:[0,0,s.k,0,0,0]});}return new Promise((resolve,reject)=>{const w=new Worker('./worker.js'),timeout=setTimeout(()=>{w.terminate();reject(Error('TIMEOUT'));},30000);w.onmessage=({data})=>{clearTimeout(timeout);w.terminate();data.error?reject(Error(data.error)):resolve(data.result);};w.onerror=()=>{clearTimeout(timeout);w.terminate();reject(Error('WORKER'));};w.postMessage({id:0,request:{components:cs,rolls:p.route.map(r=>r.roll*Math.PI/180),supports:ss,deltaT:p.temperature,gravity:p.gravity?[0,0,-9.81]:[0,0,0]}});});}$('baseline').onclick=()=>{if(result&&!pending){baseline={design:getDesign(),result:structuredClone(result)};toast(t('baselineSaved'));}};$('close-review').onclick=()=>$('review-dialog').close();$('damper-node').onchange=()=>{damper.node=+$('damper-node').value;schedule();};$('damper-axis').onchange=()=>{damper.axis=+$('damper-axis').value;schedule();};$('damper').oninput=()=>{damper.c=+$('damper').value*1000;syncExtras();schedule();};$('release').onclick=()=>{view='decay';dynamicTime=0;playing=!reduced;document.body.classList.remove('tools-open');updateSceneLabels();schedule();};let previewMesh=null,previewSerial=0;function clearPreview(){previewSerial++;previewKind=null;if(previewMesh){scene.remove(previewMesh);previewMesh.geometry.dispose();previewMesh.material.dispose();previewMesh=null;}$('confirm-part').hidden=$('cancel-part').hidden=true;}async function previewPart(kind){clearPreview();if(!result||pending||route.length>=10)return;const serial=previewSerial;previewKind=kind;const c=await loadComponent({kind,ratio:kind==='straight'?5:2});if(serial!==previewSerial)return;const path=result.paths.at(-1),end=new THREE.Vector3(...path.at(-1)),tangent=end.clone().sub(new THREE.Vector3(...path.at(-2))).normalize();// Carry the exact route frame, including accumulated bend rolls.const q=new THREE.Quaternion();for(const r of route){q.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0),r.roll*Math.PI/180));if(r.kind==='elbow')q.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1),Math.PI/2));}const points=c.path.map(p=>new THREE.Vector3(...p).applyQuaternion(q).add(end).toArray());previewMesh=new THREE.Mesh(tube(points,diameter/2),new THREE.MeshBasicMaterial({color:0x80ded0,transparent:true,opacity:.35,depthWrite:false}));scene.add(previewMesh);geometryStamp='';$('confirm-part').hidden=$('cancel-part').hidden=false;}$('preview-straight').onclick=()=>previewPart('straight');$('preview-elbow').onclick=()=>previewPart('elbow');$('cancel-part').onclick=()=>{clearPreview();geometryStamp='';};$('confirm-part').onclick=()=>{if(!previewKind)return;const kind=previewKind;route.push({kind,ratio:kind==='straight'?5:2,roll:0});selected=route.length-1;station=route.length;clearPreview();renderEditor();schedule();};function positionLabels(){if(!result)return;const box=canvas.getBoundingClientRect();if($('joint-labels').children.length!==result.nodes.length){$('joint-labels').replaceChildren(...result.nodes.map((_,i)=>{const b=document.createElement('button');b.textContent=i;b.title=`${t('jointSelect')} ${i}`;b.onclick=()=>{station=i;renderEditor();highlight();};return b;}));}result.nodes.forEach((p,i)=>{const v=new THREE.Vector3(...p).add(new THREE.Vector3(0,0,diameter*.8)).project(camera),b=$('joint-labels').children[i];b.style.left=(v.x*.5+.5)*box.width+'px';b.style.top=(-v.y*.5+.5)*box.height+'px';b.hidden=v.z>1;b.classList.toggle('selected',i===station);});}function drawTrace(){const d=result.dynamics,c=$('trace'),r=c.getBoundingClientRect(),ratio=Math.min(devicePixelRatio,2);c.width=r.width*ratio;c.height=r.height*ratio;const ctx=c.getContext('2d');ctx.scale(ratio,ratio);const w=r.width,h=r.height,pad=22,amp=Math.max(.001,...d.signal.map(Math.abs)),T=d.time.at(-1),x=t=>pad+t/T*(w-2*pad),y=v=>h/2-v/amp*(h*.34);ctx.strokeStyle='#39514f';ctx.beginPath();ctx.moveTo(pad,h/2);ctx.lineTo(w-pad,h/2);ctx.stroke();for(const [values,color,dashed] of [[d.reference,'#8da6a6',true],[d.signal,'#80ded0',false]]){ctx.strokeStyle=color;ctx.lineWidth=1.4;ctx.setLineDash(dashed?[3,3]:[]);ctx.beginPath();values.forEach((v,i)=>i?ctx.lineTo(x(d.time[i]),y(v)):ctx.moveTo(x(0),y(v)));ctx.stroke();}ctx.setLineDash([]);ctx.strokeStyle='#dbb67d';ctx.beginPath();ctx.moveTo(x(dynamicTime),8);ctx.lineTo(x(dynamicTime),h-12);ctx.stroke();ctx.fillStyle='#9fb8b1';ctx.font='10px sans-serif';ctx.fillText('mm',0,11);ctx.fillText(T.toFixed(2)+' s',w-48,h-1);ctx.fillText('0',pad,h-1);$('trace-clock').textContent=dynamicTime.toFixed(2)+' s';$('trace-caption').textContent=`${t('without')} / ${t('with')}`;$('trace-info').textContent=`${t('probe')}: ${d.probe.component+1} · ${'XYZ'[d.probe.axis]} · ${lang==='zh'?'初始峰值 1 mm,播放时长 8 秒':'Initial peak 1 mm; playback 8 s'}`;}function reportHTML(){const r=result,b=baseline?.result;const values=x=>[x.maxDisplacement*1000,Math.max(...x.supportForces.map(v=>Math.hypot(...v)))/1000,x.frequency[0],x.mass];const rows=[['displacement','mm'],['reaction','kN'],['frequency','Hz'],['mass','kg']].map(([key,unit],i)=>`<tr><td>${t(key)} / ${unit}</td><td>${b?values(b)[i].toFixed(3):'—'}</td><td>${values(r)[i].toFixed(3)}</td><td>${b?(values(r)[i]-values(b)[i]).toFixed(3):'—'}</td></tr>`).join('');const supportsRows=r.supportForces.map((f,i)=>{const node=r.supportNodes[i],mom=r.reaction.slice(node*6+3,node*6+6);return `<tr><td>${node}</td>${[...f,...mom].map(x=>`<td>${(x/1000).toFixed(3)}</td>`).join('')}</tr>`;}).join('');return `<p>${t('modelScope')}</p><table><thead><tr><th></th><th>${t('comparison')}</th><th>${t('current')}</th><th>Δ</th></tr></thead><tbody>${rows}</tbody></table>${b?'':`<p>${t('noBaseline')}</p>`}<h3>${t('supports').split('/').at(-1)}</h3><div class="table-scroll"><table><tr><th>#</th><th>Fx / kN</th><th>Fy / kN</th><th>Fz / kN</th><th>Mx / kN·m</th><th>My / kN·m</th><th>Mz / kN·m</th></tr>${supportsRows}</table></div><p>${t('reportHint')}</p><p>ROM ${VERSION} · ΔT ${solvedDesign.temperature} K · g ${solvedDesign.gravity?'9.81':'0'} m/s² · E 200 GPa · α 12×10⁻⁶/K · ρ 7850 kg/m³<br>D ${diameter*1000} mm · t ${(diameter*wall*1000).toFixed(1)} mm</p>${r.dynamics?`<p>${t('peakForce')}: ${(r.dynamics.peakForce/1000).toFixed(4)} kN · c ${r.dynamics.c/1000} kN·s/m · ${t('joint')} ${r.dynamics.node} / ${'XYZ'[r.dynamics.axis]}<br>Newmark β=¼, γ=½ · Δt ${r.dynamics.dt.toExponential(3)} s · ${r.dynamics.modeCount} modes · initial peak 1 mm · zero initial velocity · no background damping</p>`:''}`;}$('review').onclick=()=>{if(pending||!result)return;$('review-copy').innerHTML=reportHTML();$('review-dialog').showModal();};$('export-csv').onclick=()=>{const rows=[['scenario','quantity','location','time_s','value','unit']];for(const [name,r] of [['current',result],['baseline',baseline?.result]]){if(!r)continue;rows.push([name,'max_displacement','centreline','',r.maxDisplacement,'m']);r.frequency.forEach((f,i)=>rows.push([name,'frequency',i+1,'',f,'Hz']));r.supportForces.forEach((v,i)=>{const node=r.supportNodes[i];v.forEach((x,k)=>rows.push([name,'support_F'+'xyz'[k],node,'',x,'N']));r.reaction.slice(node*6+3,node*6+6).forEach((x,k)=>rows.push([name,'support_M'+'xyz'[k],node,'',x,'N m']));});r.nodes.forEach((_,i)=>r.q.slice(i*6,i*6+3).forEach((x,k)=>rows.push([name,'port_u'+'xyz'[k],i,'',x,'m'])));}if(result.dynamics){const d=result.dynamics;d.time.forEach((time,i)=>{for(const [key,values,unit] of [['undamped_displacement',d.reference,'m'],['damped_displacement',d.signal,'m'],['damper_force',d.force,'N'],['energy',d.energy,'J'],['dissipated_energy',d.dissipated,'J']])rows.push(['dynamic',key,key.includes('displacement')?'probe':d.node,time,values[i],unit]);});}download('AgentFEM-pipe-results.csv',rows.map(r=>r.join(',')).join('\n'),'text/csv');};$('export-report').onclick=()=>{const design=JSON.stringify(projectEnvelope(solvedDesign),null,2).replaceAll('<','<');const html=`<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>AgentFEM Pipe Comparison</title><style>body{font:14px Arial,"PingFang SC",sans-serif;max-width:960px;margin:30px auto;padding:20px;color:#172b2c}table{border-collapse:collapse;width:100%;font-size:12px}td,th{padding:9px;border-bottom:1px solid #b9c6c5;text-align:left}p{line-height:1.7}img{width:100%;max-height:340px;object-fit:contain;background:#102223}pre{white-space:pre-wrap;font-size:10px}button{padding:12px}@media print{button{display:none}h3{break-after:avoid}table{break-inside:avoid}}</style></head><body><h1>AgentFEM · ${t('review')}</h1><p>${new Date().toISOString()} · ROM ${VERSION}</p><button onclick="window.print()">${t('report')}</button><img src="${canvas.toDataURL('image/png')}" alt="Pipe geometry; deformation magnified ${$('scale').value} times"><p>${lang==='zh'?'画面显示放大':'Display scale'} ×${$('scale').value} · ${view}</p>${reportHTML()}<h3>${t('current')} / SI</h3><pre>${design}</pre>${baseline?`<h3>${t('comparison')} / SI</h3><pre>${JSON.stringify(projectEnvelope(baseline.design),null,2).replaceAll('<','<')}</pre>`:''}</body></html>`;download('AgentFEM-pipe-report.html',html,'text/html');toast(lang==='zh'?'报告已下载;打开后可打印为 PDF。':'Report downloaded; open it to print as PDF.');};try{const response=await fetch('./data/catalog.json');if(!response.ok)throw Error('CATALOG');catalog=(await response.json()).components;translate();let draft;try{draft=validateProject(JSON.parse(localStorage.getItem('agentfem-pipe-draft')));}catch{}if(draft){applyDesign(draft);toast(t('autoSaved'));}else preset('L');lastDesign=getDesign();syncExtras();}catch(e){$('status').textContent=t('error');console.error(e);}
1 unmodified line2345679 unmodified lines1718192021222324252627281 unmodified line<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#091315"><title>AgentFEM · Pipe Assembly Lab</title><meta name="description" content="Build a pipe. Add a support. See how it moves. A solid-FE component reduced-order model, running in your browser."><link rel="stylesheet" href="style.css"><script type="importmap">{"imports":{"three":"./vendor/three.module.js"}}</script></head><body><header><a class="brand" href="https://haoming-luo.github.io/agentfem/" target="_blank" rel="noopener">AgentFEM<span>RESEARCH LAB</span></a><div class="heading"><h1 data-t="title">Pipe Assembly Lab</h1><p data-t="subtitle">Build a route. Watch the mechanics.</p></div><nav><button id="method" data-t="method">How it works</button><button id="language" aria-label="Change language">中文</button></nav></header><main><aside id="tools"><div class="section-top"><span class="eyebrow" data-t="route">01 / ROUTE</span><button id="reset" class="quiet" data-t="reset">Reset</button></div><div class="presets"><button data-preset="L" class="active">L</button><button data-preset="U">U</button><button data-preset="spatial" data-t="spatial">3D</button></div>9 unmodified lines<div class="section-top"><span class="eyebrow" data-t="loading">03 / LOADING</span><label class="gravity"><input id="gravity" type="checkbox" checked><span data-t="gravity">Gravity</span></label></div><label class="slider"><span data-t="temperature">Uniform temperature rise</span><output id="temperature-value">100 K</output><input id="temperature" type="range" min="0" max="200" step="5" value="100"></label><p class="hint" data-t="material">Steel · E 200 GPa · α 12 × 10⁻⁶/K</p></aside><section id="viewport"><canvas id="scene" aria-label="Interactive three-dimensional pipe model"></canvas><div class="scene-heading"><div class="eyebrow" data-t="live">COMPONENT ROM / LIVE SOLVE</div><h2 id="scene-title">Room to expand.</h2><p id="scene-caption">A new support changes the whole route.</p></div><div class="view-controls"><button id="fit" title="Fit view" aria-label="Fit view">⌖</button><button id="toggle-tools" aria-label="Toggle controls">☷</button></div><div id="status" role="status">Loading component library…</div><div class="legend"><span class="swatch cold"></span><span data-t="reference">Original shape</span><span class="swatch hot"></span><span id="result-label">Deformed shape</span></div><div class="playbar"><div class="tabs" id="views"><button data-view="static" class="active" data-t="thermalView">Expansion</button><button data-view="0">f₁</button><button data-view="1">f₂</button><button data-view="2">f₃</button></div><button id="play" aria-label="Play or pause">Ⅱ</button><label class="scale"><span data-t="scale">Display</span><select id="scale"><option value="1">×1</option><option value="10">×10</option><option value="30" selected>×30</option><option value="100">×100</option></select></label></div><div class="metrics"><article><span data-t="displacement">Max. centreline displacement</span><strong id="displacement">—</strong><small>mm</small></article><article><span data-t="reaction">Largest support force</span><strong id="reaction">—</strong><small>kN</small></article><article><span data-t="frequency">First natural frequency</span><strong id="frequency">—</strong><small>Hz</small></article><article><span data-t="mass">Pipe mass</span><strong id="mass">—</strong><small>kg</small></article></div><div class="scene-footer"><span data-t="gesture">Drag to orbit · Scroll to zoom</span><span id="solve-time"></span></div></section></main><footer><span data-t="footer">Solid finite elements, assembled at your fingertips.</span><div><a href="https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components" target="_blank" rel="noopener">Dataset ↗</a><a href="https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM" target="_blank" rel="noopener">Model ↗</a><a href="https://lab.haoming-luo.com/" target="_blank" rel="noopener">Haoming Lab ↗</a></div></footer><dialog id="about"><button class="close" id="close-about" aria-label="Close">×</button><span class="eyebrow">AgentFEM / PIPE ASSEMBLY LAB</span><h2 data-t="aboutTitle">Small components. One connected system.</h2><div id="about-copy"></div></dialog><script type="module" src="app.js"></script></body></html>1 unmodified line23456789 unmodified lines18192021222324252627282930311 unmodified line<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#091315"><title>AgentFEM · Pipe Assembly Lab</title><meta name="description" content="Build a pipe. Add a support. See how it moves. A solid-FE component reduced-order model, running in your browser."><link rel="stylesheet" href="style.css"><script type="importmap">{"imports":{"three":"./vendor/three.module.js"}}</script></head><body><header><a class="brand" href="https://haoming-luo.github.io/agentfem/" target="_blank" rel="noopener">AgentFEM<span>RESEARCH LAB</span></a><div class="heading"><h1 data-t="title">Pipe Assembly Lab</h1><p data-t="subtitle">Build a route. Watch the mechanics.</p></div><nav><button id="method" data-t="method">How it works</button><button id="language" aria-label="Change language">中文</button></nav></header><div class="projectbar"><div><button id="undo" data-t="undo">Undo</button><button id="redo" data-t="redo">Redo</button><span id="project-state" role="status"></span></div><div><button id="baseline" data-t="baseline">Keep baseline</button><button id="review" data-t="review">Compare & export</button><button id="save-project" data-t="save">Save</button><button id="open-project" data-t="open">Open</button><input type="file" id="project-file" accept=".json,application/json" hidden></div></div><main><aside id="tools"><div class="section-top"><span class="eyebrow" data-t="route">01 / ROUTE</span><button id="reset" class="quiet" data-t="reset">Reset</button></div><div class="presets"><button data-preset="L" class="active">L</button><button data-preset="U">U</button><button data-preset="spatial" data-t="spatial">3D</button></div>9 unmodified lines<div class="section-top"><span class="eyebrow" data-t="loading">03 / LOADING</span><label class="gravity"><input id="gravity" type="checkbox" checked><span data-t="gravity">Gravity</span></label></div><label class="slider"><span data-t="temperature">Uniform temperature rise</span><output id="temperature-value">100 K</output><input id="temperature" type="range" min="0" max="200" step="5" value="100"></label><p class="hint" data-t="material">Steel · E 200 GPa · α 12 × 10⁻⁶/K</p><details id="dynamic-tools"><summary data-t="damperTitle">04 / VIBRATION & DAMPER</summary><p class="hint" data-t="releaseHint">Release the first mode from a 1 mm peak displacement.</p><label class="field"><span data-t="station">Connection</span><select id="damper-node"></select></label><label class="field"><span data-t="axis">Global direction</span><select id="damper-axis"><option value="0">X</option><option value="1">Y</option><option value="2" selected>Z ↑</option></select></label><label class="slider"><span data-t="damping">Damping coefficient</span><output id="damper-value">10 kN·s/m</output><input id="damper" type="range" min="0" max="100" step="1" value="10"></label><button id="release" data-t="release">Release & compare</button></details></aside><section id="viewport"><canvas id="scene" aria-label="Interactive three-dimensional pipe model"></canvas><div class="scene-heading"><div class="eyebrow" data-t="live">COMPONENT ROM / LIVE SOLVE</div><h2 id="scene-title">Room to expand.</h2><p id="scene-caption">A new support changes the whole route.</p></div><div class="view-controls"><button id="fit" title="Fit view" aria-label="Fit view">⌖</button><button id="toggle-tools" aria-label="Toggle controls">☷</button></div><div id="status" role="status">Loading component library…</div><div id="joint-labels"></div><div id="end-actions" hidden><span data-t="extend">Extend this end</span><button id="preview-straight" data-t="addStraight">+ Straight</button><button id="preview-elbow" data-t="addElbow">+ Elbow</button><button id="confirm-part" data-t="confirm" hidden>Connect</button><button id="cancel-part" data-t="cancel" hidden>Cancel</button></div><div id="trace-panel" hidden><div><span id="trace-caption"></span><strong id="trace-clock"></strong></div><canvas id="trace" aria-label="Displacement versus time, without and with damper"></canvas><p id="trace-info"></p></div><div class="legend"><span class="swatch cold"></span><span id="reference-label" data-t="reference">Original shape</span><span class="swatch hot"></span><span id="result-label">Deformed shape</span></div><div class="playbar"><div class="tabs" id="views"><button data-view="static" class="active" data-t="thermalView">Expansion</button><button data-view="0">f₁</button><button data-view="1">f₂</button><button data-view="2">f₃</button></div><button id="play" aria-label="Play or pause">Ⅱ</button><label class="scale"><span data-t="scale">Display</span><select id="scale"><option value="1">×1</option><option value="10">×10</option><option value="30" selected>×30</option><option value="100">×100</option></select></label></div><div class="metrics"><article><span data-t="displacement">Max. centreline displacement</span><strong id="displacement">—</strong><small>mm</small></article><article><span data-t="reaction">Largest support force</span><strong id="reaction">—</strong><small>kN</small></article><article><span data-t="frequency">First natural frequency</span><strong id="frequency">—</strong><small>Hz</small></article><article><span data-t="mass">Pipe mass</span><strong id="mass">—</strong><small>kg</small></article></div><div class="scene-footer"><span data-t="gesture">Drag to orbit · Scroll to zoom</span><span id="solve-time"></span></div></section></main><footer><span data-t="footer">Solid finite elements, assembled at your fingertips.</span><div><a href="https://huggingface.co/datasets/HaomingLuo/AgentFEM-Pipe-Components" target="_blank" rel="noopener">Dataset ↗</a><a href="https://huggingface.co/HaomingLuo/AgentFEM-Pipe-ROM" target="_blank" rel="noopener">Model ↗</a><a href="https://lab.haoming-luo.com/" target="_blank" rel="noopener">Haoming Lab ↗</a></div></footer><dialog id="about"><button class="close" id="close-about" aria-label="Close">×</button><span class="eyebrow">AgentFEM / PIPE ASSEMBLY LAB</span><h2 data-t="aboutTitle">Small components. One connected system.</h2><div id="about-copy"></div></dialog><dialog id="review-dialog"><button class="close" id="close-review" aria-label="Close">×</button><span class="eyebrow">AgentFEM / PIPE ASSEMBLY LAB</span><h2 data-t="review">Compare & export</h2><div id="review-copy"></div><div class="report-actions"><button id="export-csv">CSV</button><button id="export-report" data-t="report">Print / PDF</button></div></dialog><script type="module" src="app.js"></script></body></html>
1234567891011121314151617181920212223242526272829/* Versioned, portable project contract. No executable content in imports. */export const VERSION='1.1.0';export function validateProject(raw){ if(!raw||raw.schema!=='agentfem.pipe-project/1'||raw.modelVersion!==VERSION||raw.units!=='SI')throw Error('VERSION'); const p=raw.design; if(!p||![.12,.16,.2,.24].includes(p.diameter)||![.04,.06].includes(p.wall)||!Array.isArray(p.route)||!p.route.length||p.route.length>10)throw Error('GEOMETRY'); const route=p.route.map(r=>{ if(!r||!['straight','elbow'].includes(r.kind)||!(r.kind==='straight'?[3,5,8]:[1.5,2,3]).includes(r.ratio)||![0,90,180,270].includes(r.roll))throw Error('COMPONENT'); return {kind:r.kind,ratio:r.ratio,roll:r.roll}; }); if(!Number.isFinite(p.temperature)||p.temperature<0||p.temperature>200||typeof p.gravity!=='boolean')throw Error('LOAD'); const supports={}; for(const [key,s] of Object.entries(p.supports||{})){ const node=Number(key);if(!Number.isInteger(node)||node<1||node>route.length||!s||!['none','spring','guide','fixed'].includes(s.type)||!Number.isFinite(s.k)||s.k<10000||s.k>1000000)throw Error('SUPPORT'); supports[node]={type:s.type,k:s.k}; } const d=p.damper; if(!d||!Number.isInteger(d.node)||d.node<1||d.node>route.length||![0,1,2].includes(d.axis)||!Number.isFinite(d.c)||d.c<0||d.c>100000)throw Error('DAMPER'); return {route,diameter:p.diameter,wall:p.wall,supports,temperature:p.temperature,gravity:p.gravity,damper:{node:d.node,axis:d.axis,c:d.c}};}export function removeComponent(p,index){ const next=structuredClone(p);if(next.route.length<=1)return next; next.route.splice(index,1);next.supports={}; // Remove the deleted segment's downstream joint; keep upstream attachments. for(const [key,s] of Object.entries(p.supports)){const n=+key;if(n===index+1)continue;next.supports[n>index+1?n-1:n]=s;} if(next.damper.node===index+1)next.damper.c=0; next.damper.node=Math.max(1,Math.min(next.route.length,next.damper.node>index+1?next.damper.node-1:next.damper.node)); return next;}63 unmodified lines646566676869703 unmodified lines747576777879808182838463 unmodified lineslet reaction=mv(K,q).map((v,i)=>v-F[i]);let residual=norm(free.map(i=>reaction[i]))/Math.max(1,norm(F));const fC=Array.from({length:nc},(_,i)=>i).filter(i=>!fixed.has(i));const eig=modes(sub(KC,fC),sub(MC,fC),3),V=zeros(nc,3);fC.forEach((v,i)=>V[v]=eig.vectors[i]);let paths=[],displacements=[],modeDisplacements=[],nodes=[],mass=0;for(let a=0;a<n;a++){const c=components[a],p=places[a],local=mv(p.D,p.ix.map(j=>q[j])),gg=mv(tr(p.rotation),gravity),lm=mul(p.Dc,p.ic.map(j=>V[j]));3 unmodified linesmass+=c.metrics.mass_kg;}nodes.push(paths[n-1].at(-1));let maxDisplacement=Math.max(...displacements.flat().map(norm));let supportForces=supports.map(s=>Array.from({length:3},(_,j)=>fixed.has(6*s.node+j)?reaction[6*s.node+j]:-spring[6*s.node+j]*q[6*s.node+j]));if(!Number.isFinite(maxDisplacement)||residual>1e-6)throw Error('RESIDUAL');return {q,reaction,paths,nodes,displacements,modeDisplacements,frequency:eig.frequency,mass,maxDisplacement,supportForces,residual,elapsedMs:(typeof performance==='undefined'?Date.now():performance.now())-start};}if(typeof module!=='undefined')module.exports={solve};else root.PipeSolver={solve};})(typeof globalThis==='undefined'?self:globalThis);63 unmodified lines64656667686970713 unmodified lines7576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712863 unmodified lineslet reaction=mv(K,q).map((v,i)=>v-F[i]);let residual=norm(free.map(i=>reaction[i]))/Math.max(1,norm(F));const fC=Array.from({length:nc},(_,i)=>i).filter(i=>!fixed.has(i));const count=request.dynamic?Math.min(request.dynamic.modeCount||12,fC.length):3;const eig=modes(sub(KC,fC),sub(MC,fC),count),V=zeros(nc,count);fC.forEach((v,i)=>V[v]=eig.vectors[i]);let paths=[],displacements=[],modeDisplacements=[],nodes=[],mass=0;for(let a=0;a<n;a++){const c=components[a],p=places[a],local=mv(p.D,p.ix.map(j=>q[j])),gg=mv(tr(p.rotation),gravity),lm=mul(p.Dc,p.ic.map(j=>V[j]));3 unmodified linesmass+=c.metrics.mass_kg;}nodes.push(paths[n-1].at(-1));let maxDisplacement=0,maxLocation={component:0,sample:0,position:paths[0][0]};displacements.forEach((p,a)=>p.forEach((u,j)=>{if(norm(u)>maxDisplacement){maxDisplacement=norm(u);maxLocation={component:a,sample:j,position:paths[a][j]};}}));let supportForces=supports.map(s=>Array.from({length:3},(_,j)=>fixed.has(6*s.node+j)?reaction[6*s.node+j]:-spring[6*s.node+j]*q[6*s.node+j]));if(!Number.isFinite(maxDisplacement)||residual>1e-6)throw Error('RESIDUAL');let dynamics=null;if(request.dynamic){const d=request.dynamic,node=d.node??n,axis=d.axis??2,c=d.c??10000;if(!Number.isInteger(node)||node<0||node>n||![0,1,2].includes(axis)||!Number.isFinite(c)||c<0)throw Error('DAMPER');let peak=0,probe=null;modeDisplacements.forEach((path,a)=>path.forEach((m,j)=>m.forEach((r,k)=>{if(Math.abs(r[0])>peak){peak=Math.abs(r[0]);probe={component:a,sample:j,axis:k};}})));const amplitude=d.amplitude??.001;if(!(amplitude>0&&litude<=.01))throw Error('AMPLITUDE');const z0=Array(count).fill(0);z0[0]=amplitude/modeDisplacements[probe.component][probe.sample][probe.axis][0];const b=V[node*6+axis],C=b.map(x=>b.map(y=>c*x*y)),omega=eig.frequency.map(f=>2*Math.PI*f);dynamics=decay(omega,C,z0,d.duration??6/eig.frequency[0],d.stepFactor||1);const probeVector=modeDisplacements[probe.component][probe.sample][probe.axis];dynamics.signal=dynamics.coordinates.map(z=>z.reduce((s,v,i)=>s+v*probeVector[i],0));dynamics.reference=dynamics.time.map(t=>z0[0]*probeVector[0]*Math.cos(omega[0]*t));dynamics.force=dynamics.velocities.map(v=>-c*v.reduce((s,x,i)=>s+x*b[i],0));dynamics.peakForce=Math.max(...dynamics.force.map(Math.abs));Object.assign(dynamics,{node,axis,c,probe,amplitude,modeCount:count,frequency:eig.frequency,blocked:fixed.has(node*6+axis)});delete dynamics.velocities;}return {q,reaction,paths,nodes,displacements,modeDisplacements,frequency:eig.frequency.slice(0,3),mass,maxDisplacement,maxLocation,supportForces,supportNodes:supports.map(s=>s.node),residual,dynamics,elapsedMs:(typeof performance==='undefined'?Date.now():performance.now())-start};}// Average-acceleration Newmark, mass-normalized modal coordinates.// Physical non-proportional damping C=c*b*b^T is kept in full.function decay(omega,C,z0,duration,stepFactor=1){const n=omega.length,frames=600,stride=Math.ceil(Math.max(2400,80*Math.max(...omega)/(2*Math.PI)*duration)*stepFactor/frames),steps=stride*frames;if(steps>240000||!(duration>0)||!Number.isFinite(duration))throw Error('DYNAMIC_RANGE');const h=duration/steps,w2=omega.map(w=>w*w),H=C.map((r,i)=>r.map((v,j)=>h*.5*v+(i===j?1+h*h*.25*w2[i]:0)));const factor=new CholeskyDecomposition(new Matrix(sym(H))).lowerTriangularMatrix.to2DArray();const solveH=rhs=>{const y=Array(n),x=Array(n);for(let i=0;i<n;i++){let s=rhs[i];for(let j=0;j<i;j++)s-=factor[i][j]*y[j];y[i]=s/factor[i][i];}for(let i=n-1;i>=0;i--){let s=y[i];for(let j=i+1;j<n;j++)s-=factor[j][i]*x[j];x[i]=s/factor[i][i];}return x;};let z=[...z0],v=Array(n).fill(0),a=z.map((x,i)=>-w2[i]*x),diss=0,peakEnergyRise=0;const energy=()=>z.reduce((s,x,i)=>s+.5*(v[i]*v[i]+w2[i]*x*x),0),E0=energy();const time=[],coordinates=[],velocities=[],energies=[],dissipated=[];const record=t=>{time.push(t);coordinates.push([...z]);velocities.push([...v]);energies.push(energy());dissipated.push(diss);};record(0);for(let step=1;step<=steps;step++){const zp=z.map((x,i)=>x+h*v[i]+h*h*.25*a[i]),vp=v.map((x,i)=>x+h*.5*a[i]);const an=solveH(mv(C,vp).map((x,i)=>-x-w2[i]*zp[i]));const vn=vp.map((x,i)=>x+h*.5*an[i]),mid=v.map((x,i)=>(x+vn[i])*.5),prior=energy();const cmid=mv(C,mid);diss+=h*mid.reduce((s,x,i)=>s+x*cmid[i],0);z=zp.map((x,i)=>x+h*h*.25*an[i]);v=vn;a=an;peakEnergyRise=Math.max(peakEnergyRise,(energy()-prior)/Math.max(E0,1e-30));if(step%stride===0)record(step*h);}return {time,coordinates,velocities,energy:energies,dissipated,dt:h,initialEnergy:E0,energyBalanceRelative:Math.abs(energy()+diss-E0)/Math.max(E0,1e-30),peakEnergyRise};}if(typeof module!=='undefined')module.exports={solve,decay};else root.PipeSolver={solve,decay};})(typeof globalThis==='undefined'?self:globalThis);
4 unmodified lines5674 unmodified lines.presets button{font-size:12px;white-space:nowrap;padding-left:5px;padding-right:5px}@media(min-width:601px){main{min-height:540px}.scene-heading{top:23px}.scene-heading h2{font-size:clamp(24px,2.7vw,38px)}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}4 unmodified lines5678910114 unmodified lines.presets button{font-size:12px;white-space:nowrap;padding-left:5px;padding-right:5px}@media(min-width:601px){main{min-height:540px}.scene-heading{top:23px}.scene-heading h2{font-size:clamp(24px,2.7vw,38px)}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}.projectbar{min-height:48px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:7px 24px;border-bottom:1px solid var(--line);background:#0c191b}.projectbar>div{display:flex;align-items:center;gap:7px}.projectbar button{font-size:11px;padding:7px 10px}#project-state{font-size:10px;color:var(--muted);max-width:270px;line-height:1.4}main{height:calc(100svh - 192px)}details{border-top:1px solid var(--line);padding-top:15px;margin-top:17px}summary{font-size:10px;letter-spacing:1px;color:var(--accent);cursor:pointer}#release{width:100%;font-size:12px;color:var(--accent)}#joint-labels{position:absolute;inset:0;pointer-events:none}#joint-labels button{position:absolute;transform:translate(-50%,-50%);border-radius:50%;font-size:10px;width:25px;height:25px;padding:0;background:#102022df;pointer-events:auto;border-color:#49746d}#joint-labels button.selected{border-color:var(--gold);color:var(--gold)}#end-actions{position:absolute;right:22px;bottom:250px;display:flex;flex-wrap:wrap;gap:5px;max-width:270px;background:#102023ed;padding:10px;border:1px solid var(--line);border-radius:9px}#end-actions span{font-size:10px;color:var(--muted);width:100%}#end-actions button{font-size:11px;padding:7px}#trace-panel{position:absolute;right:24px;top:108px;width:280px;background:#09191bea;border:1px solid #36534e;border-radius:8px;padding:12px;pointer-events:none}#trace-panel>div{display:flex;justify-content:space-between;font-size:10px;color:var(--accent)}#trace-panel strong{font-weight:400;color:var(--gold)}#trace{width:100%;height:96px}#trace-info{font-size:9px;color:var(--muted);margin:4px 0;line-height:1.5}#review-dialog{width:min(850px,94vw)}#review-dialog table{border-collapse:collapse;width:100%;font-size:11px;white-space:nowrap}#review-dialog th,#review-dialog td{text-align:left;border-bottom:1px solid var(--line);padding:10px 8px}#review-dialog h3{font-size:15px;font-weight:500}.table-scroll{overflow:auto}.report-actions{display:flex;gap:8px;margin-top:20px}.scene-heading{max-width:calc(100% - 100px)}@media(max-width:1000px){#project-state{display:none}#trace-panel{width:230px;top:137px}.projectbar{padding:7px 16px}.projectbar button{padding:7px}.scene-heading h2{font-size:25px}}@media(max-width:600px){.projectbar{flex-wrap:wrap;padding:7px 12px;gap:7px}.projectbar>div:last-child{flex-wrap:wrap}.projectbar button{font-size:10px;padding:7px 8px}main{height:calc(100svh - 213px);min-height:730px}body.tools-open aside{position:fixed;top:0;bottom:0;width:min(310px,85vw);padding-top:48px;z-index:8;overscroll-behavior:contain}body.tools-open #toggle-tools{position:fixed;top:10px;left:260px;z-index:9;background:#172d2e}#trace-panel{top:138px;right:16px;width:calc(100% - 32px);max-width:300px;padding:9px}#trace{height:78px}.scene-heading h2{font-size:25px}.scene-heading p{font-size:11px;max-width:260px}#end-actions{bottom:285px;right:15px}.view-controls{top:17px}#joint-labels button{width:29px;height:29px}.projectbar>div:first-child{order:2}.metrics{z-index:1;pointer-events:none}}.solving .metrics{opacity:.4}
PROJECT_FORMAT.mdAdded+75
README.md+4
SHA256SUMS+8-6
app.js+95-19
index.html+4-1
preview.png


project.jsAdded+29
solver.js+48-4
style.css+4