@protomaze/geometry 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GeometryDemo.js +1 -1
- package/README.md +129 -47
- package/common/Colors.d.ts +1 -2
- package/common/Colors.js +1 -1
- package/demo/DemoControls.d.ts +13 -3
- package/demo/DemoControls.js +1 -1
- package/edit/CreateController.js +1 -1
- package/edit/EditController.js +1 -1
- package/edit/GeometryController.d.ts +7 -1
- package/edit/MeasureController.js +1 -1
- package/edit/Sketch.d.ts +19 -2
- package/edit/Sketch.js +1 -1
- package/engine/GeometryEngine.d.ts +22 -3
- package/engine/GeometryEngine.js +1 -1
- package/engine/GeometryFrame.d.ts +3 -6
- package/engine/GeometryOptions.d.ts +48 -4
- package/engine/GeometryOptions.js +1 -1
- package/engine/GeometryView.d.ts +48 -6
- package/engine/GeometryView.js +1 -1
- package/engine/Labels.d.ts +9 -0
- package/engine/Labels.js +1 -1
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/layers/AreaLayer.js +1 -1
- package/layers/GeometryLayer.d.ts +33 -7
- package/layers/GeometryLayer.js +1 -1
- package/layers/LineLayer.d.ts +14 -0
- package/layers/LineLayer.js +1 -1
- package/layers/SphereLayer.js +1 -1
- package/layers/TubeLayer.js +1 -1
- package/package.json +1 -1
- package/theme/Theme.d.ts +125 -0
- package/theme/Theme.js +1 -0
- package/three/CanvasGeometryEngine.d.ts +1 -4
- package/three/CanvasGeometryEngine.js +1 -1
- package/three/DensityMap.d.ts +3 -3
- package/three/FeatureLook.d.ts +19 -2
- package/three/FeatureLook.js +1 -1
- package/three/Ground.d.ts +5 -0
- package/three/Ground.js +1 -1
- package/three/HostedGeometryEngine.d.ts +6 -5
- package/three/HostedGeometryEngine.js +1 -1
- package/three/Shading.d.ts +1 -1
- package/three/primitives/Body.d.ts +1 -1
- package/three/primitives/Body.js +1 -1
- package/three/primitives/GpuAreas.js +1 -1
- package/three/primitives/GpuIcons.d.ts +3 -3
- package/three/primitives/GpuIcons.js +1 -1
- package/three/primitives/GpuLines.d.ts +2 -2
- package/three/primitives/GpuLines.js +1 -1
- package/three/primitives/GpuSpheres.js +1 -1
- package/three/primitives/GpuTubes.d.ts +0 -2
- package/three/primitives/GpuTubes.js +1 -1
- package/three/RiaGeometryEngine.d.ts +0 -48
- package/three/RiaGeometryEngine.js +0 -1
package/GeometryDemo.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e,{useEffect as t,useMemo as r,useRef as o,useState as n}from"react";import{RAMPS as i,rampColor as a,toCss as l}from"./common/Colors.js";import{AreaLayer as s}from"./layers/AreaLayer.js";import{LineLayer as c}from"./layers/LineLayer.js";import{PointLayer as d}from"./layers/PointLayer.js";import{SphereLayer as p}from"./layers/SphereLayer.js";import{TubeLayer as m}from"./layers/TubeLayer.js";import{ReactGeometry as u}from"./react/ReactGeometry.js";import{boxProfile as h}from"./three/primitives/GpuTubes.js";import{ACCENT as f,Chip as g,DemoButton as y,DemoIconButton as w,DemoSelect as b,Divider as x,FullscreenButton as k,panelStyle as E,RangeSlider as v,Section as C,Slider as S}from"./demo/DemoControls.js";import{createTown as D,MATERIAL_COLORS as $,MATERIALS as L,ORIGIN_X as z,ORIGIN_Y as F,paintGround as R}from"./demo/Town.js";import{CreateController as j}from"./edit/CreateController.js";import{EditController as W}from"./edit/EditController.js";import{EditHistory as M}from"./edit/EditHistory.js";import{MeasureController as P}from"./edit/MeasureController.js";import{formatArea as A,formatLength as T,formatSlope as N}from"./engine/Labels.js";import{area as H,length as I}from"./math/Measure.js";const G=[{tool:"select",icon:"arrow_selector_tool",title:"Select (V): click to select, drag to pan",key:"v"},{tool:"point",icon:"add_location_alt",title:"Draw points (P)",key:"p"},{tool:"line",icon:"polyline",title:"Draw a line (L): click its points, double-click or Enter to finish",key:"l"},{tool:"polygon",icon:"pentagon",title:"Draw an area (A): click its corners, click the first to close it",key:"a"},{tool:"rectangle",icon:"rectangle",title:"Draw a rectangle (R): two corners",key:"r"},{tool:"circle",icon:"circle",title:"Draw a circle (C): its centre, then its edge",key:"c"},{tool:"edit",icon:"edit",title:"Edit (E): click a feature - drag vertices, Alt-drag heights, T to scale and turn, Del to delete",key:"e"},{tool:"distance",icon:"straighten",title:"Measure a distance (D): along points, on whatever is drawn there",key:"d"},{tool:"area",icon:"square_foot",title:"Measure an area (M)",key:"m"},{tool:"height",icon:"height",title:"Measure a height (H): between two points",key:"h"},{tool:"clearance",icon:"compare_arrows",title:"Clearance (K): click two features, the nearest they come in 3D",key:"k"}],U={point:"Click to place a point. Points snap to vertices and edges near the pointer.",line:"Click to place points; double-click or Enter to finish, Backspace to take one back. Shift: 15° steps.",polygon:"Click the corners; click the first again or double-click to close. Crossing edges are refused.",rectangle:"Click one corner, then the opposite one.",circle:"Click the centre, then a point on the edge.",edit:"Click a feature. Drag a vertex to move it, an edge's middle to add one; Alt-drag raises or lowers it (3D). Drag the shape to move it, T to scale or turn it. Double-click a vertex or Del to remove it; Del alone deletes the feature. Ctrl+Z / Ctrl+Y.",distance:"Click points along the way - on the ground, a pipe, a roof. Double-click to finish.",area:"Click the corners of the area. Double-click to finish.",height:"Click two points: their height difference, distance across and slope.",clearance:"Click two features - two pipes, a pipe and a cable - for the nearest they come, surface to surface."};let B=0;const _=[{value:1,text:"Town"},{value:2,text:"City"},{value:4,text:"Metro"},{value:6,text:"Region"}],V={age:{label:"Year laid",ramp:i.viridis.slice(1),domain:[1900,2024],value:e=>e.properties.year,format:e=>String(Math.round(e))},diameter:{label:"Diameter",ramp:i.magma.slice(1),domain:[150,1600],value:e=>e.properties.dn??NaN,format:e=>`DN ${Math.round(e)}`},condition:{label:"Condition class",ramp:i.condition,domain:[0,5],value:e=>e.properties.condition,format:e=>String(Math.round(e))},depth:{label:"Depth",ramp:i.ice,domain:[1,9],value:e=>"manhole"===e.properties.kind?e.properties.depth:(e.properties.depthFrom+e.properties.depthTo)/2,format:e=>`${e.toFixed(1)} m`}},O=[{key:"sewer",title:"Sewer & manholes",color:"#e07a3f"},{key:"laterals",title:"House laterals",color:"#4cc9f0"},{key:"connections",title:"Connections",color:"#ffd166"},{key:"water",title:"Water mains",color:"#3a86ff"},{key:"gas",title:"Gas mains",color:"#ffbe0b"},{key:"power",title:"Power ducts",color:"#ff006e"},{key:"buildings",title:"Buildings",color:"#7d8fa8"},{key:"zones",title:"Flood zones",color:"#ff4d6d"},{key:"trees",title:"Trees",color:"#52b788"},{key:"sensors",title:"Sensors",color:"#00f5d4"},{key:"trajectories",title:"Robot & drone",color:"#f72585"}],Y=e=>e.properties.year??NaN,q=e=>"manhole"===e.properties.kind?null:e.properties.material;export function GeometryDemo(){const[A,T]=n(1),[N,H]=n("3d"),[I,U]=n("dark"),[oe,ne]=n("glow"),[ie,ae]=n(!0),[le,se]=n(!0),[ce,de]=n(!1),[pe,me]=n(!1),[ue,he]=n("material"),[fe,ge]=n([1895,2024]),[ye,we]=n("fade"),[be,xe]=n(150),[ke,Ee]=n(new Set),[ve,Ce]=n(null),[Se,De]=n({}),[$e,Le]=n(null),[ze,Fe]=n(null),[Re,je]=n(null),[We,Me]=n("select"),[Pe,Ae]=n(!0),[Te,Ne]=n(null),[He,Ie]=n(null),[Ge,Ue]=n({canUndo:!1,canRedo:!1,undoLabel:null,redoLabel:null}),Be=o(null),_e=o(null),Ve=o({x:0,y:0}),Oe=o(null),Ye=o({flow:le,growth:0,xray:ce,dark:!0}),qe="dark"===I,Ke=r(()=>"undefined"!=typeof window&&window.innerWidth<J&&window.innerWidth<window.innerHeight?2.2:1,[]),Xe=r(()=>D(A),[A]),Ze=r(()=>function(e,t){const r={Residential:"#4c5a6d",Commercial:"#5f7189",Industrial:"#6e665a",Public:"#57716b"},o={Residential:"#d9dee5",Commercial:"#c9d3df",Industrial:"#ddd5c8",Public:"#cfe0da"},n=new m({id:"sewer",title:"Sewer",features:[...e.sewer,...e.manholes],profile:e=>e.properties.height?h(e.properties.dn/1e3,e.properties.height/1e3,.7):e.properties.dn/2e3,stand:e=>"manhole"===e.properties.kind?{bottom:-e.properties.depth,top:0,radius:e.properties.diameter/2}:null,arrows:!0,style:e=>{const r=e.properties;return"manhole"===r.kind?{color:"#aab4bf",material:"Beton",width:2}:{color:$[r.material],material:r.material,width:1.4+Math.min(4.5,r.dn/280),flow:t.flow,weight:.4+.5*r.condition}}}),a=new m({id:"laterals",title:"House laterals",features:e.laterals,profile:()=>.075,reach:()=>1400,style:e=>({color:$[e.properties.material],material:e.properties.material,width:1,weight:.3})}),l=new p({id:"connections",title:"Connections",features:e.connections,radius:()=>.16,reach:()=>900,style:{color:"#ffd166",material:"pvc",width:2.5}}),u={water:"#3a86ff",gas:"#ffbe0b",power:"#ff006e"},g=new m({id:"utilities",title:"Utilities",features:[...e.water,...e.gas,...e.power],profile:e=>e.properties.height?h(e.properties.dn/1e3,e.properties.height/1e3,.25):e.properties.dn/2e3,style:e=>({color:u[e.properties.kind],material:e.properties.material,width:"power"===e.properties.kind?1.5:1.2+e.properties.dn/300,flow:t.flow&&"power"!==e.properties.kind})});g.setCategories({of:e=>e.properties.kind,keys:["water","gas","power"]});const y=new s({id:"buildings",title:"Buildings",features:e.buildings,extrude:!0,style:e=>({color:(t.dark?r:o)[e.properties.use],height:e.properties.height*t.growth,material:"Commercial"===e.properties.use&&e.properties.floors>9?"glass":"concrete",opacity:t.xray?.16:1,outline:"#ffffff30",outlineWidth:1})}),w=new s({id:"zones",title:"Flood zones",features:e.zones,style:e=>{const t=e.properties.risk;return"High"===t?{color:"#ff4d6d40",pattern:"hatch",outline:"#ff4d6d",outlineWidth:2}:"Medium"===t?{color:"#ff9f1c1c",outline:"#ff9f1c",outlineWidth:1.5}:"Low"===t?{color:"#4cc9f014",outline:"#4cc9f0aa",outlineWidth:1.2,outlineDashed:!0}:{color:"#f9c74f30",pattern:"hatch",outline:"#f9c74f",outlineWidth:2.5,outlineDashed:!0}}}),b=["#2d6a4f","#40916c","#52b788","#3a7d44","#4f772d"],x=new p({id:"trees",title:"Trees",features:e.trees,radius:e=>e.properties.crown,reach:()=>3e3,ghost:!1,style:(e,t)=>({color:b[t%b.length],material:"default",width:2})}),k=new m({id:"trunks",title:"Trunks",features:e.trees,stand:e=>({bottom:0,top:e.properties.height-.5*e.properties.crown,radius:.18,open:!1}),reach:()=>1500,ghost:!1,covers:!1,pickable:!1,style:{color:"#6b4f3a",material:"default",width:1}}),E=new d({id:"sensors",title:"Sensors",features:e.sensors.map(e=>({...e,geometry:{type:"Point",coordinates:[...e.geometry.coordinates.slice(0,2),.3]}})),anchor:[0,-1],style:e=>({shape:"Quality"===e.properties.type?"hexagon":"pin",size:26,color:"#00f5d4"})});return E.colorBy({value:e=>e.properties.value,ramp:i.condition,domain:[0,100]}),{zones:w,sewer:n,laterals:a,connections:l,utilities:g,trunks:k,trees:x,buildings:y,sensors:E,trajectories:new c({id:"trajectories",title:"Robot & drone",features:e.trajectories,style:e=>"Robot"===e.properties.vehicle?{color:"#00f5d4",width:3.5,flow:!0}:{color:"#f72585",width:2.5,dashed:!0,flow:!0}}),defects:new d({id:"defects",title:"Defects",features:e.defects,visible:!1,pickable:!1,style:e=>({color:"#ff2d55",size:5,weight:.6*e.properties.severity})}),drawnAreas:new s({id:"drawn-areas",title:"Drawn areas",style:{color:"#ddff0026",outline:f,outlineWidth:2}}),drawnLines:new c({id:"drawn-lines",title:"Drawn lines",style:{color:f,width:3}}),drawnPoints:new d({id:"drawn-points",title:"Drawn points",depthTest:!1,border:1.5,style:{color:f,size:14,shape:"circle"}})}}(Xe,Ye.current),[Xe]),Qe=r(()=>Object.values(Ze),[Ze]),Je=r(()=>({bounds:Xe.bounds,image:R(Xe,qe),grid:{spacing:10,major:10,opacity:qe?.025:.05}}),[Xe,qe]),et=[Ze.sewer,Ze.laterals,Ze.utilities],tt=r(()=>new M,[Ze]);t(()=>tt.on("change",Ue),[tt]);const rt=r(()=>{const e=!!Pe&&{},t={stroke:f,fill:"#ddff0024",active:f},r=e=>t=>{const r=++B;return{id:`drawn-${r}`,geometry:t,properties:{name:`${e} ${r}`,kind:"drawn",shape:e}}};switch(We){case"point":return new j({shape:"point",layer:Ze.drawnPoints,feature:r("Point"),history:tt,snapping:e,theme:t});case"line":return new j({shape:"line",layer:Ze.drawnLines,feature:r("Line"),history:tt,snapping:e,theme:t});case"polygon":case"rectangle":case"circle":return new j({shape:We,layer:Ze.drawnAreas,feature:r(We[0].toUpperCase()+We.slice(1)),history:tt,snapping:e,theme:t});case"edit":return new W({layers:[Ze.drawnAreas,Ze.drawnLines,Ze.drawnPoints,Ze.zones,Ze.buildings,Ze.sewer,Ze.laterals,Ze.utilities,Ze.sensors,Ze.trajectories],history:tt,snapping:e,theme:t});case"distance":case"area":case"height":case"clearance":return new P({mode:We,snapping:e,theme:t,radius:(e,t)=>function(e){const t=e.properties??{};return"manhole"===t.kind?t.diameter/2:t.height?t.height/2e3:t.dn?t.dn/2e3:"lateral"===t.kind?.075:0}(t)});default:return null}},[We,Pe,Ze,tt]);t(()=>{if(Ne(null),Ie(null),rt instanceof P)return rt.on("change",Ne);if(rt instanceof W){const e=[rt.on("select",Ie),rt.on("commit",()=>Ie(rt.getTarget()))];return()=>e.forEach(e=>e())}},[rt]),t(()=>{const e=e=>{if(e.ctrlKey||e.metaKey||e.altKey||"INPUT"===e.target?.tagName)return;if(rt instanceof W&&rt.getTarget()&&"t"===e.key.toLowerCase())return;const t=G.find(t=>t.key===e.key.toLowerCase());t&&Me(t.tool)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[rt]),t(()=>{const e=performance.now();let t=0;const r=()=>{const o=Math.min(1,(performance.now()-e-250)/1600);Ye.current.growth=o<=0?0:1-Math.pow(1-o,3),Ze.buildings.restyle(),o<1&&(t=requestAnimationFrame(r))};return t=requestAnimationFrame(r),()=>cancelAnimationFrame(t)},[Ze]),t(()=>{const e=Be.current;e&&e.flyTo({target:[z,F,0],distance:1250*Ke*Math.sqrt(A)},1200)},[Xe]),t(()=>{Ye.current.flow=le,Ze.sewer.restyle(),Ze.utilities.restyle()},[Ze,le]),t(()=>{Ye.current.xray=ce,Ye.current.dark=qe,Ze.buildings.restyle()},[Ze,ce,qe]),t(()=>{const e="material"===ue?{by:"style"}:{value:V[ue].value,ramp:V[ue].ramp,domain:V[ue].domain};[Ze.sewer,Ze.laterals].forEach(t=>t.colorBy(e))},[Ze,ue]),t(()=>{[Ze.sewer,Ze.laterals].forEach(e=>e.setCategories({of:q,keys:L,colors:$}))},[Ze]),t(()=>{[Ze.sewer,Ze.laterals].forEach(e=>L.forEach(t=>e.setCategoryMode(t,ke.has(t)?"hidden":ve===t?"lit":"shown")))},[Ze,ke,ve]),t(()=>{[...et,Ze.buildings].forEach(e=>e.setRange({value:Y,low:fe[0],high:fe[1],outside:ye}))},[Ze,fe,ye]),t(()=>{Ze.sewer.setFilter(be<=150?null:e=>"manhole"===e.properties.kind||e.properties.dn>=be,"hide")},[Ze,be]),t(()=>{O.forEach(({key:e})=>{const t=Se[e]??!0;"water"===e||"gas"===e||"power"===e?Ze.utilities.setCategoryMode(e,t?"shown":"hidden"):Ze[e].setVisible(t)}),Ze.trunks.setVisible(Se.trees??!0)},[Ze,Se]),t(()=>{const e=Be.current;Ze.defects.setVisible(pe),e?.setDensity(pe?{layers:[Ze.defects,Ze.sewer],ramp:i.heat,top:4}:null)},[Ze,pe]),t(()=>{window.geometryDemo={view:()=>Be.current,layers:Ze,town:Xe,live:Ye.current,history:tt,setTool:Me,controller:()=>Be.current?.getController()??null,snapshot:async(e="snapshot")=>{const t=Be.current;if(!t)return null;t.engine.draw();const r=function(e){const t=e.engine.canvas,r=e.labels?.element;if(!r||0===r.childElementCount)return t.toDataURL("image/png");const o=document.createElement("canvas");o.width=t.width,o.height=t.height;const n=o.getContext("2d");n.drawImage(t,0,0);const i=t.width/Math.max(1,t.getBoundingClientRect().width),a=r.getBoundingClientRect();for(const e of Array.from(r.children)){if("none"===e.style.display)continue;const t=e.getBoundingClientRect(),r=getComputedStyle(e),o=(t.left-a.left)*i,l=(t.top-a.top)*i;n.fillStyle=r.backgroundColor,n.beginPath(),n.roundRect(o,l,t.width*i,t.height*i,4*i),n.fill(),n.fillStyle=r.color,n.font=`${r.fontWeight} ${parseFloat(r.fontSize)*i}px ${r.fontFamily}`,n.textBaseline="middle",n.fillText(e.textContent??"",o+parseFloat(r.paddingLeft)*i,l+t.height*i/2)}return o.toDataURL("image/png")}(t),o=await fetch(`/__snapshot?name=${encodeURIComponent(e)}`,{method:"POST",body:r});return(await o.json()).file}}},[Ze,Xe,tt]);const[ot,nt]=n(!1),[it,at]=n(!1);t(()=>{const e=_e.current;if(!e)return;const t=new ResizeObserver(()=>{const{clientWidth:t,clientHeight:r}=e;nt((t<J||r<ee)&&(t>r?"landscape":"portrait"))});return t.observe(e),()=>t.disconnect()},[]);const lt=r(()=>({look:oe,hoverFades:ie}),[oe,ie]),st={sewer:Xe.sewer.length,laterals:Xe.laterals.length,connections:Xe.connections.length,water:Xe.water.length,gas:Xe.gas.length,power:Xe.power.length,buildings:Xe.buildings.length,zones:Xe.zones.length,trees:Xe.trees.length,sensors:Xe.sensors.length,trajectories:Xe.trajectories.length},ct=Object.values(st).reduce((e,t)=>e+t,0)+Xe.manholes.length+Xe.defects.length,dt=qe?"#EBE8E0":"#1A1A1A",pt=E(qe),mt=$e?.layers[0],ut=mt?mt.layer.getFeature(mt.ids[0]):void 0,ht="material"!==ue?V[ue]:null,ft=_.map(t=>e.createElement(y,{key:t.value,text:t.text,active:A===t.value,onClick:()=>T(t.value),title:`A town ${t.value} times as wide`})),gt=e.createElement(e.Fragment,null,e.createElement(y,{text:"2D",active:"2d"===N,onClick:()=>H("2d"),title:"A flat map: lines and covers"}),e.createElement(y,{text:"3D",active:"3d"===N,onClick:()=>H("3d"),title:"In depth: pipes, shafts, buildings"})),yt=e.createElement(e.Fragment,null,e.createElement(y,{text:"Glow",active:"glow"===oe,onClick:()=>ne("glow"),title:"What is lit glows (bloom)"}),e.createElement(y,{text:"Outline",active:"outline"===oe,onClick:()=>ne("outline"),title:"What is lit is outlined"}),e.createElement(y,{text:"Dim others",active:ie,onClick:()=>ae(!ie),title:"Pointing at something dims the rest"})),wt=e.createElement(e.Fragment,null,e.createElement(y,{text:"Flow",active:le,onClick:()=>se(!le),title:"Light running along the networks, downstream (2D)"}),e.createElement(y,{text:"X-ray",active:ce,onClick:()=>de(!ce),title:"See through the buildings"}),e.createElement(y,{text:"Density",active:pe,onClick:()=>me(!pe),title:"A heatmap of the defects and the sewer in poor condition"})),bt=Re&&e.createElement("span",{style:{opacity:.7,fontSize:12,whiteSpace:ot?"normal":"nowrap",fontVariantNumeric:"tabular-nums"}},"webgpu"===Re.backend?"WebGPU":"WebGL 2"," · ",Re.fps," fps · ",Re.ms.toFixed(1)," ms · ",Re.drawCalls," draws · ",(Re.triangles/1e6).toFixed(1),"M triangles · ",ct.toLocaleString()," features"),xt=e.createElement(e.Fragment,null,e.createElement(w,{icon:"fit_screen",title:"Show everything",onClick:()=>Be.current?.fit()}),e.createElement(w,{icon:qe?"dark_mode":"light_mode",title:"Dark or light",onClick:()=>U(qe?"light":"dark")}),e.createElement(k,{target:()=>_e.current})),kt=e.createElement(e.Fragment,null,e.createElement(C,{title:"Layers"},e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},O.map(({key:t,title:r,color:o})=>{const n=Se[t]??!0;return e.createElement(X,{key:t,title:r,color:o,on:n,count:st[t],onClick:()=>De(e=>({...e,[t]:!n}))})}))),e.createElement(C,{title:"Colour the sewer by",right:e.createElement(b,{value:ue,onChange:he,options:[{value:"material",text:"Material"},{value:"age",text:"Age"},{value:"diameter",text:"Diameter"},{value:"condition",text:"Condition"},{value:"depth",text:"Depth"}]})},ht?e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:4}},e.createElement("div",{style:{height:10,borderRadius:5,background:`linear-gradient(90deg, ${ht.ramp.join(", ")})`}}),e.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,opacity:.75}},e.createElement("span",null,ht.format(ht.domain[0])),e.createElement("span",null,ht.label),e.createElement("span",null,ht.format(ht.domain[1])))):null,e.createElement("div",{style:{display:"flex",flexWrap:"wrap",gap:5}},L.map(t=>e.createElement(g,{key:t,text:t,color:$[t],on:!ke.has(t),onHover:e=>Ce(e?t:null),onClick:()=>Ee(e=>{const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r})}))),e.createElement("span",{style:{fontSize:11,opacity:.55}},"Point at a material to light it, click to hide it: one texel on the GPU.")),e.createElement(C,{title:"Year laid",right:e.createElement(e.Fragment,null,e.createElement(y,{text:"Fade",active:"fade"===ye,onClick:()=>we("fade"),title:"What falls outside is faded"}),e.createElement(y,{text:"Hide",active:"hide"===ye,onClick:()=>we("hide"),title:"What falls outside is hidden"}))},e.createElement(v,{min:1895,max:2024,value:fe,onChange:ge}),e.createElement("span",{style:{fontSize:11,opacity:.55}},"Every pipe and building, filtered on the GPU: two uniforms per step.")),e.createElement(C,{title:"Smallest sewer"},e.createElement(S,{min:150,max:1400,step:50,value:be,onChange:xe,format:e=>e<=150?"All":`DN ${e}`})),e.createElement(C,{title:"Navigate"},e.createElement("span",{style:{fontSize:12,opacity:.7,lineHeight:1.5}},"Drag to pan, right-drag to turn and tilt, wheel to zoom where you point, double-click to dive in. Click to select; Ctrl or Shift to add; Esc to clear."))),Et={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},vt=e.createElement(C,{title:"View"},e.createElement("div",{style:Et},ft),e.createElement("div",{style:Et},yt),e.createElement("div",{style:Et},wt),bt),Ct=ot?e.createElement("div",{style:{width:1,margin:"0 2px",flex:"none",background:qe?"#ffffff22":"#00000022"}}):e.createElement("div",{style:{height:1,margin:"2px 0",background:qe?"#ffffff22":"#00000022"}}),St=ot?8:12;return e.createElement("div",{ref:_e,style:{position:"relative",width:"100%",height:"100%",boxSizing:"border-box",padding:ot?4:8,gap:ot?4:8,display:"flex",flexDirection:"column",overflow:"hidden",backgroundColor:"#000",backgroundImage:`url('${te}')`,backgroundPosition:"center",backgroundSize:"cover",color:dt,font:`13px ${re}`}},ot?e.createElement("div",{style:{...pt,display:"flex",gap:8,alignItems:"center",padding:6,flex:"none",overflowX:"auto"}},e.createElement("b",{style:{letterSpacing:"0.5px",marginRight:2}},"Geometry"),gt,e.createElement("div",{style:{flexGrow:1}}),e.createElement(w,{icon:"tune",title:"Layers, colours, filters",active:it,onClick:()=>at(!it)}),xt):e.createElement("div",{style:{...pt,display:"flex",gap:8,alignItems:"center",padding:8,flexWrap:"wrap",flex:"none"}},e.createElement("b",{style:{letterSpacing:"0.5px",marginRight:4}},"Geometry"),ft,e.createElement(x,null),gt,e.createElement(x,null),yt,e.createElement(x,null),wt,e.createElement(x,null),bt,e.createElement("div",{style:{flexGrow:1}}),xt),e.createElement("div",{style:{display:"flex",flex:1,minHeight:0,gap:8}},!ot&&e.createElement("div",{className:"demo-scroll",style:{...pt,width:292,flex:"none",overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:18,boxSizing:"border-box"}},kt),e.createElement("div",{style:{...pt,flex:1,minWidth:0,position:"relative",overflow:"hidden"},onMouseMove:e=>{const t=e.currentTarget.getBoundingClientRect();Ve.current={x:e.clientX-t.left,y:e.clientY-t.top},Oe.current&&(Oe.current.style.left=`${Ve.current.x+14}px`,Oe.current.style.top=`${Ve.current.y+14}px`)}},e.createElement(u,{mode:N,theme:I,forceWebGL:Q,highlight:lt,camera:{target:[z,F,0],distance:1250*Ke,heading:18,tilt:58},layers:Qe,ground:Je,controller:rt,viewRef:Be,onHover:Fe,onSelect:Le,onFrame:je}),e.createElement("div",{style:{position:"absolute",left:St,top:St,...Z(qe),padding:5,display:"flex",gap:4,...ot?{flexDirection:"row",maxWidth:`calc(100% - ${2*St}px)`,overflowX:"auto",scrollbarWidth:"none",boxSizing:"border-box"}:{flexDirection:"column"}}},G.map((t,r)=>e.createElement(e.Fragment,{key:t.tool},(1===r||6===r||7===r)&&Ct,e.createElement(w,{icon:t.icon,title:t.title,active:We===t.tool,onClick:()=>Me(t.tool)}))),Ct,e.createElement(w,{icon:"undo",title:Ge.undoLabel?`Undo ${Ge.undoLabel.toLowerCase()} (Ctrl+Z)`:"Nothing to undo",onClick:()=>tt.undo(),active:!1}),e.createElement(w,{icon:"redo",title:Ge.redoLabel?`Redo ${Ge.redoLabel.toLowerCase()} (Ctrl+Y)`:"Nothing to redo",onClick:()=>tt.redo(),active:!1}),e.createElement(w,{icon:"join",title:Pe?"Snapping on: to vertices and edges of what is drawn":"Snapping off",active:Pe,onClick:()=>Ae(!Pe)})),"select"!==We&&e.createElement(K,{tool:We,dark:qe,measurement:Te,editing:He,compact:!!ot}),ze&&"select"===We&&e.createElement("div",{ref:Oe,style:{position:"absolute",left:Ve.current.x+14,top:Ve.current.y+14,pointerEvents:"none",...Z(qe),padding:"6px 9px",fontSize:12,maxWidth:280,whiteSpace:"nowrap"}},e.createElement("b",null,ze.feature.properties?.name??ze.id),e.createElement("div",{style:{opacity:.7}},function(e){const t=e.properties??{};switch(t.kind){case"sewer":case"lateral":case"water":case"gas":case"power":return`${t.material} · DN ${t.dn}${t.height?`/${t.height}`:""} · ${t.year} · ${t.length?.toFixed(0)} m`;case"manhole":return`${t.depth.toFixed(1)} m deep · ${t.material} · ${t.year}`;case"building":return`${t.use} · ${t.floors} floors · ${t.height.toFixed(0)} m`;case"sensor":return`${t.type} · ${t.value} %`;case"zone":return`Risk: ${t.risk}`;case"tree":return`${t.height.toFixed(0)} m high`;case"connection":return`On ${t.pipe}`;case"trajectory":return t.vehicle;default:return""}}(ze.feature))),ut&&"select"===We&&e.createElement("div",{style:{position:"absolute",...Z(qe),padding:12,display:"flex",flexDirection:"column",gap:8,boxSizing:"border-box",...ot?{left:St,right:St,bottom:St,maxHeight:"45%",overflowY:"auto"}:{right:12,top:12,width:270}}},e.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},e.createElement("span",{style:{width:10,height:10,borderRadius:5,background:f,boxShadow:`0 0 8px ${f}`}}),e.createElement("b",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},ut.properties?.name??ut.id)),$e.count>1&&e.createElement("span",{style:{fontSize:12,opacity:.7}},"and ",$e.count-1," more selected"),e.createElement("table",{style:{fontSize:12,borderCollapse:"collapse"}},e.createElement("tbody",null,function(e){const t=e.properties??{},r=[["Id",String(e.id)]],o=(e,t)=>{null!=t&&""!==t&&r.push([e,String(t)])};["sewer","lateral","water","gas","power"].includes(t.kind)?(o("Material",t.material),o("Profile",`DN ${t.dn}${t.height?` × ${t.height}`:""}`),o("Laid",t.year),o("Condition",`${t.condition} / 5`),o("Length",`${t.length.toFixed(1)} m`),o("Depth",`${t.depthFrom.toFixed(2)} → ${t.depthTo.toFixed(2)} m`),"sewer"===t.kind&&o("Slope",`${t.slope.toFixed(1)} ‰`),o("Upstream",t.upstream),o("Downstream",t.downstream)):Object.entries(t).forEach(([e,t])=>{"name"!==e&&"kind"!==e&&o(e[0].toUpperCase()+e.slice(1),"number"!=typeof t||Number.isInteger(t)?t:t.toFixed(1))});return r}(ut).map(([t,r])=>e.createElement("tr",{key:t},e.createElement("td",{style:{opacity:.6,padding:"2px 10px 2px 0",verticalAlign:"top"}},t),e.createElement("td",{style:{padding:"2px 0",fontVariantNumeric:"tabular-nums"}},r))))),e.createElement("div",{style:{display:"flex",gap:6}},e.createElement(y,{text:"Fly to",onClick:()=>{const e=function(e){const t=e.geometry;return t?"Point"===t.type?t.coordinates:"LineString"===t.type?t.coordinates[Math.floor(t.coordinates.length/2)]:"Polygon"===t.type?t.coordinates[0][0]:null:null}(ut);e&&Be.current?.flyTo({target:[e[0],e[1],0],distance:70,tilt:62},1100)}}),e.createElement(y,{text:"Clear",onClick:()=>Be.current?.clearSelection()}))),pe&&e.createElement("div",{style:{position:"absolute",...ot?{right:St,top:St+44}:{left:12,bottom:12},...Z(qe),padding:"8px 10px",width:ot?160:200,display:"flex",flexDirection:"column",gap:4}},e.createElement("span",{style:{fontSize:11,opacity:.7}},"Defects and poor condition"),e.createElement("div",{style:{height:8,borderRadius:4,background:`linear-gradient(90deg, ${i.heat.slice(1).map(e=>l(a([e],0))).join(", ")})`}})),ot&&it&&e.createElement("div",{className:"demo-scroll",style:{position:"absolute",zIndex:2,...pt,...Z(qe),overflowY:"auto",padding:12,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:18,..."portrait"===ot?{left:0,right:0,bottom:0,maxHeight:"58%",borderRadius:"10px 10px 0 0"}:{top:0,right:0,bottom:0,width:"min(300px, 55%)",borderRadius:"10px 0 0 10px"}}},e.createElement("div",{style:{display:"flex",alignItems:"center"}},e.createElement("b",{style:{flex:1}},"Layers and filters"),e.createElement(w,{icon:"close",title:"Close",onClick:()=>at(!1)})),vt,kt))))}function K({tool:t,dark:r,measurement:o,editing:n,compact:i}){const a=[],l=o;if(l&&"clearance"===l.mode?(l.a&&a.push(["From",String(l.a.feature.properties?.name??l.a.feature.id)]),l.b&&a.push(["To",String(l.b.feature.properties?.name??l.b.feature.id)]),void 0!==l.clearance&&a.push(["Clearance",T(l.clearance)])):l&&("area"===l.mode&&void 0!==l.area?(a.push(["Area",A(l.area)]),a.push(["Perimeter",T(l.perimeter??0)])):l.points.length>=2&&(a.push(["Length",T(l.length??0)]),a.push(["Across the map",T(l.horizontal??0)]),a.push(["Height difference",`${(l.rise??0)>=0?"+":""}${T(l.rise??0)}`]),a.push(["Slope",N(l.slope??0)]))),n){const e=n.geometry;a.push(["Editing",String(n.feature.properties?.name??n.feature.id)]),a.push(["Layer",n.layer.title??n.layer.id]),e.type.includes("Polygon")?a.push(["Area",A(H(e))]):e.type.includes("Line")&&a.push(["Length",T(I(e))])}const s=G.find(e=>e.tool===t)?.title.split(":")[0].replace(/ \(.\)$/,"")??"";return e.createElement("div",{style:{position:"absolute",...i?{left:8,right:8,bottom:8}:{left:52,bottom:12,maxWidth:360},...Z(r),padding:"9px 11px",display:"flex",flexDirection:"column",gap:6,pointerEvents:"none"}},e.createElement("b",{style:{fontSize:12}},s),a.length>0&&e.createElement("table",{style:{fontSize:12,borderCollapse:"collapse"}},e.createElement("tbody",null,a.map(([t,r])=>e.createElement("tr",{key:t},e.createElement("td",{style:{opacity:.6,padding:"1px 12px 1px 0"}},t),e.createElement("td",{style:{fontVariantNumeric:"tabular-nums",fontWeight:600}},r))))),e.createElement("span",{style:{fontSize:11,opacity:.65,lineHeight:1.45}},U[t]))}function X({title:t,color:r,on:o,count:i,onClick:a}){const[l,s]=n(!1);return e.createElement("button",{onClick:a,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"4px 6px",borderRadius:4,border:"none",cursor:"pointer",background:l?"#ffffff10":"transparent",color:"inherit",font:"inherit",textAlign:"left",opacity:o?1:.45}},e.createElement("span",{style:{width:14,height:14,borderRadius:3,border:`1.5px solid ${o?r:"#ffffff40"}`,background:o?`${r}55`:"transparent",flex:"none",boxShadow:o?`0 0 6px ${r}88`:"none"}}),e.createElement("span",{style:{flex:1}},t),void 0!==i&&e.createElement("span",{style:{fontSize:11,opacity:.55,fontVariantNumeric:"tabular-nums"}},i.toLocaleString()))}function Z(e){return{borderRadius:6,background:e?"rgba(20, 24, 30, 0.82)":"rgba(250, 250, 250, 0.88)",border:"1px solid "+(e?"#ffffff18":"#00000018"),boxShadow:"0 8px 24px rgba(0,0,0,0.35)",backdropFilter:"blur(8px)"}}const Q="undefined"!=typeof location&&new URLSearchParams(location.search).has("webgl"),J=720,ee=520,te="https://www.protomaze.com/resources/img/mosaic_equirectangular.png",re="Roboto, sans-serif";
|
|
1
|
+
import e,{useEffect as t,useMemo as r,useRef as o,useState as n}from"react";import{RAMPS as i,rampColor as a,toCss as l}from"./common/Colors.js";import{AreaLayer as s}from"./layers/AreaLayer.js";import{LineLayer as c}from"./layers/LineLayer.js";import{PointLayer as d}from"./layers/PointLayer.js";import{SphereLayer as p}from"./layers/SphereLayer.js";import{TubeLayer as m}from"./layers/TubeLayer.js";import{ReactGeometry as u}from"./react/ReactGeometry.js";import{boxProfile as h}from"./three/primitives/GpuTubes.js";import{ACCENT as f,Chip as g,DemoButton as y,DemoIconButton as w,DemoSelect as b,demoTheme as x,Divider as k,FullscreenButton as v,panelStyle as E,RangeSlider as C,Section as S,Slider as D,token as $}from"./demo/DemoControls.js";import{createTown as L,MATERIAL_COLORS as F,MATERIALS as z,ORIGIN_X as R,ORIGIN_Y as j,paintGround as W}from"./demo/Town.js";import{CreateController as M}from"./edit/CreateController.js";import{EditController as P}from"./edit/EditController.js";import{EditHistory as T}from"./edit/EditHistory.js";import{MeasureController as A}from"./edit/MeasureController.js";import{formatArea as N,formatLength as H,formatSlope as I}from"./engine/Labels.js";import{area as G,length as U}from"./math/Measure.js";const _=[{tool:"select",icon:"arrow_selector_tool",title:"Select (V): click to select, drag to pan",key:"v"},{tool:"point",icon:"add_location_alt",title:"Draw points (P)",key:"p"},{tool:"line",icon:"polyline",title:"Draw a line (L): click its points, double-click or Enter to finish",key:"l"},{tool:"polygon",icon:"pentagon",title:"Draw an area (A): click its corners, click the first to close it",key:"a"},{tool:"rectangle",icon:"rectangle",title:"Draw a rectangle (R): two corners",key:"r"},{tool:"circle",icon:"circle",title:"Draw a circle (C): its centre, then its edge",key:"c"},{tool:"edit",icon:"edit",title:"Edit (E): click a feature - drag vertices, Alt-drag heights, T to scale and turn, Del to delete",key:"e"},{tool:"distance",icon:"straighten",title:"Measure a distance (D): along points, on whatever is drawn there",key:"d"},{tool:"area",icon:"square_foot",title:"Measure an area (M)",key:"m"},{tool:"height",icon:"height",title:"Measure a height (H): between two points",key:"h"},{tool:"clearance",icon:"compare_arrows",title:"Clearance (K): click two features, the nearest they come in 3D",key:"k"}],B={point:"Click to place a point. Points snap to vertices and edges near the pointer.",line:"Click to place points; double-click or Enter to finish, Backspace to take one back. Shift: 15° steps.",polygon:"Click the corners; click the first again or double-click to close. Crossing edges are refused.",rectangle:"Click one corner, then the opposite one.",circle:"Click the centre, then a point on the edge.",edit:"Click a feature. Drag a vertex to move it, an edge's middle to add one; Alt-drag raises or lowers it (3D). Drag the shape to move it, T to scale or turn it. Double-click a vertex or Del to remove it; Del alone deletes the feature. Ctrl+Z / Ctrl+Y.",distance:"Click points along the way - on the ground, a pipe, a roof. Double-click to finish.",area:"Click the corners of the area. Double-click to finish.",height:"Click two points: their height difference, distance across and slope.",clearance:"Click two features - two pipes, a pipe and a cable - for the nearest they come, surface to surface."};let V=0;const O=[{value:1,text:"Town"},{value:2,text:"City"},{value:4,text:"Metro"},{value:6,text:"Region"}],Y={age:{label:"Year laid",ramp:i.viridis.slice(1),domain:[1900,2024],value:e=>e.properties.year,format:e=>String(Math.round(e))},diameter:{label:"Diameter",ramp:i.magma.slice(1),domain:[150,1600],value:e=>e.properties.dn??NaN,format:e=>`DN ${Math.round(e)}`},condition:{label:"Condition class",ramp:i.condition,domain:[0,5],value:e=>e.properties.condition,format:e=>String(Math.round(e))},depth:{label:"Depth",ramp:i.ice,domain:[1,9],value:e=>"manhole"===e.properties.kind?e.properties.depth:(e.properties.depthFrom+e.properties.depthTo)/2,format:e=>`${e.toFixed(1)} m`}},q=[{key:"sewer",title:"Sewer & manholes",color:"#e07a3f"},{key:"laterals",title:"House laterals",color:"#4cc9f0"},{key:"connections",title:"Connections",color:"#ffd166"},{key:"water",title:"Water mains",color:"#3a86ff"},{key:"gas",title:"Gas mains",color:"#ffbe0b"},{key:"power",title:"Power ducts",color:"#ff006e"},{key:"buildings",title:"Buildings",color:"#7d8fa8"},{key:"zones",title:"Flood zones",color:"#ff4d6d"},{key:"trees",title:"Trees",color:"#52b788"},{key:"sensors",title:"Sensors",color:"#00f5d4"},{key:"trajectories",title:"Robot & drone",color:"#f72585"}],K=e=>e.properties.year??NaN,X=e=>"manhole"===e.properties.kind?null:e.properties.material;export function GeometryDemo(){const[N,H]=n(1),[I,G]=n("3d"),[U,B]=n("dark"),[ne,ie]=n("glow"),[ae,le]=n(!0),[se,ce]=n(!0),[de,pe]=n(!1),[me,ue]=n(!1),[he,fe]=n("material"),[ge,ye]=n([1895,2024]),[we,be]=n("fade"),[xe,ke]=n(150),[ve,Ee]=n(new Set),[Ce,Se]=n(null),[De,$e]=n({}),[Le,Fe]=n(null),[ze,Re]=n(null),[je,We]=n(null),[Me,Pe]=n("select"),[Te,Ae]=n(!0),[Ne,He]=n(null),[Ie,Ge]=n(null),[Ue,_e]=n({canUndo:!1,canRedo:!1,undoLabel:null,redoLabel:null}),Be=o(null),Ve=o(null),Oe=o({x:0,y:0}),Ye=o(null),qe=o({flow:se,growth:0,xray:de,dark:!0}),Ke="dark"===U,Xe=r(()=>"undefined"!=typeof window&&window.innerWidth<te&&window.innerWidth<window.innerHeight?2.2:1,[]),Ze=r(()=>L(N),[N]),Qe=r(()=>function(e,t){const r={Residential:"#4c5a6d",Commercial:"#5f7189",Industrial:"#6e665a",Public:"#57716b"},o={Residential:"#d9dee5",Commercial:"#c9d3df",Industrial:"#ddd5c8",Public:"#cfe0da"},n=new m({id:"sewer",title:"Sewer",features:[...e.sewer,...e.manholes],profile:e=>e.properties.height?h(e.properties.dn/1e3,e.properties.height/1e3,.7):e.properties.dn/2e3,stand:e=>"manhole"===e.properties.kind?{bottom:-e.properties.depth,top:0,radius:e.properties.diameter/2}:null,arrows:!0,style:e=>{const r=e.properties;return"manhole"===r.kind?{color:"#aab4bf",material:"Beton",width:2}:{color:F[r.material],material:r.material,width:1.4+Math.min(4.5,r.dn/280),flow:t.flow,weight:.4+.5*r.condition}}}),a=new m({id:"laterals",title:"House laterals",features:e.laterals,profile:()=>.075,reach:()=>1400,style:e=>({color:F[e.properties.material],material:e.properties.material,width:1,weight:.3})}),l=new p({id:"connections",title:"Connections",features:e.connections,radius:()=>.16,reach:()=>900,style:{color:"#ffd166",material:"pvc",width:2.5}}),u={water:"#3a86ff",gas:"#ffbe0b",power:"#ff006e"},g=new m({id:"utilities",title:"Utilities",features:[...e.water,...e.gas,...e.power],profile:e=>e.properties.height?h(e.properties.dn/1e3,e.properties.height/1e3,.25):e.properties.dn/2e3,style:e=>({color:u[e.properties.kind],material:e.properties.material,width:"power"===e.properties.kind?1.5:1.2+e.properties.dn/300,flow:t.flow&&"power"!==e.properties.kind})});g.setCategories({of:e=>e.properties.kind,keys:["water","gas","power"]});const y=new s({id:"buildings",title:"Buildings",features:e.buildings,extrude:!0,style:e=>({color:(t.dark?r:o)[e.properties.use],height:e.properties.height*t.growth,material:"Commercial"===e.properties.use&&e.properties.floors>9?"glass":"concrete",opacity:t.xray?.16:1,outline:"#ffffff30",outlineWidth:1})}),w=new s({id:"zones",title:"Flood zones",features:e.zones,style:e=>{const t=e.properties.risk;return"High"===t?{color:"#ff4d6d40",pattern:"hatch",outline:"#ff4d6d",outlineWidth:2}:"Medium"===t?{color:"#ff9f1c1c",outline:"#ff9f1c",outlineWidth:1.5}:"Low"===t?{color:"#4cc9f014",outline:"#4cc9f0aa",outlineWidth:1.2,outlineDashed:!0}:{color:"#f9c74f30",pattern:"hatch",outline:"#f9c74f",outlineWidth:2.5,outlineDashed:!0}}}),b=["#2d6a4f","#40916c","#52b788","#3a7d44","#4f772d"],x=new p({id:"trees",title:"Trees",features:e.trees,radius:e=>e.properties.crown,reach:()=>3e3,ghost:!1,style:(e,t)=>({color:b[t%b.length],material:"default",width:2})}),k=new m({id:"trunks",title:"Trunks",features:e.trees,stand:e=>({bottom:0,top:e.properties.height-.5*e.properties.crown,radius:.18,open:!1}),reach:()=>1500,ghost:!1,covers:!1,pickable:!1,style:{color:"#6b4f3a",material:"default",width:1}}),v=new d({id:"sensors",title:"Sensors",features:e.sensors.map(e=>({...e,geometry:{type:"Point",coordinates:[...e.geometry.coordinates.slice(0,2),.3]}})),anchor:[0,-1],style:e=>({shape:"Quality"===e.properties.type?"hexagon":"pin",size:26,color:"#00f5d4"})});return v.colorBy({value:e=>e.properties.value,ramp:i.condition,domain:[0,100]}),{zones:w,sewer:n,laterals:a,connections:l,utilities:g,trunks:k,trees:x,buildings:y,sensors:v,trajectories:new c({id:"trajectories",title:"Robot & drone",features:e.trajectories,style:e=>"Robot"===e.properties.vehicle?{color:"#00f5d4",width:3.5,flow:!0}:{color:"#f72585",width:2.5,dashed:!0,flow:!0}}),defects:new d({id:"defects",title:"Defects",features:e.defects,visible:!1,pickable:!1,style:e=>({color:"#ff2d55",size:5,weight:.6*e.properties.severity})}),drawnAreas:new s({id:"drawn-areas",title:"Drawn areas",style:{color:"#ddff0026",outline:f,outlineWidth:2}}),drawnLines:new c({id:"drawn-lines",title:"Drawn lines",style:{color:f,width:3}}),drawnPoints:new d({id:"drawn-points",title:"Drawn points",depthTest:!1,border:1.5,style:{color:f,size:14,shape:"circle"}})}}(Ze,qe.current),[Ze]),Je=r(()=>Object.values(Qe),[Qe]),et=r(()=>({bounds:Ze.bounds,image:W(Ze,Ke),grid:{spacing:10,major:10,opacity:Ke?.025:.05}}),[Ze,Ke]),tt=[Qe.sewer,Qe.laterals,Qe.utilities],rt=r(()=>new T,[Qe]);t(()=>rt.on("change",_e),[rt]);const ot=r(()=>{const e=!!Te&&{},t=e=>t=>{const r=++V;return{id:`drawn-${r}`,geometry:t,properties:{name:`${e} ${r}`,kind:"drawn",shape:e}}};switch(Me){case"point":return new M({shape:"point",layer:Qe.drawnPoints,feature:t("Point"),history:rt,snapping:e});case"line":return new M({shape:"line",layer:Qe.drawnLines,feature:t("Line"),history:rt,snapping:e});case"polygon":case"rectangle":case"circle":return new M({shape:Me,layer:Qe.drawnAreas,feature:t(Me[0].toUpperCase()+Me.slice(1)),history:rt,snapping:e});case"edit":return new P({layers:[Qe.drawnAreas,Qe.drawnLines,Qe.drawnPoints,Qe.zones,Qe.buildings,Qe.sewer,Qe.laterals,Qe.utilities,Qe.sensors,Qe.trajectories],history:rt,snapping:e});case"distance":case"area":case"height":case"clearance":return new A({mode:Me,snapping:e,radius:(e,t)=>function(e){const t=e.properties??{};return"manhole"===t.kind?t.diameter/2:t.height?t.height/2e3:t.dn?t.dn/2e3:"lateral"===t.kind?.075:0}(t)});default:return null}},[Me,Te,Qe,rt]);t(()=>{if(He(null),Ge(null),ot instanceof A)return ot.on("change",He);if(ot instanceof P){const e=[ot.on("select",Ge),ot.on("commit",()=>Ge(ot.getTarget()))];return()=>e.forEach(e=>e())}},[ot]),t(()=>{const e=e=>{if(e.ctrlKey||e.metaKey||e.altKey||"INPUT"===e.target?.tagName)return;if(ot instanceof P&&ot.getTarget()&&"t"===e.key.toLowerCase())return;const t=_.find(t=>t.key===e.key.toLowerCase());t&&Pe(t.tool)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ot]),t(()=>{const e=performance.now();let t=0;const r=()=>{const o=Math.min(1,(performance.now()-e-250)/1600);qe.current.growth=o<=0?0:1-Math.pow(1-o,3),Qe.buildings.restyle(),o<1&&(t=requestAnimationFrame(r))};return t=requestAnimationFrame(r),()=>cancelAnimationFrame(t)},[Qe]),t(()=>{const e=Be.current;e&&e.flyTo({target:[R,j,0],distance:1250*Xe*Math.sqrt(N)},1200)},[Ze]),t(()=>{qe.current.flow=se,Qe.sewer.restyle(),Qe.utilities.restyle()},[Qe,se]),t(()=>{qe.current.xray=de,qe.current.dark=Ke,Qe.buildings.restyle()},[Qe,de,Ke]),t(()=>{const e="material"===he?{by:"style"}:{value:Y[he].value,ramp:Y[he].ramp,domain:Y[he].domain};[Qe.sewer,Qe.laterals].forEach(t=>t.colorBy(e))},[Qe,he]),t(()=>{[Qe.sewer,Qe.laterals].forEach(e=>e.setCategories({of:X,keys:z,colors:F}))},[Qe]),t(()=>{[Qe.sewer,Qe.laterals].forEach(e=>z.forEach(t=>e.setCategoryMode(t,ve.has(t)?"hidden":Ce===t?"lit":"shown")))},[Qe,ve,Ce]),t(()=>{[...tt,Qe.buildings].forEach(e=>e.setRange({value:K,low:ge[0],high:ge[1],outside:we}))},[Qe,ge,we]),t(()=>{Qe.sewer.setFilter(xe<=150?null:e=>"manhole"===e.properties.kind||e.properties.dn>=xe,"hide")},[Qe,xe]),t(()=>{q.forEach(({key:e})=>{const t=De[e]??!0;"water"===e||"gas"===e||"power"===e?Qe.utilities.setCategoryMode(e,t?"shown":"hidden"):Qe[e].setVisible(t)}),Qe.trunks.setVisible(De.trees??!0)},[Qe,De]),t(()=>{const e=Be.current;Qe.defects.setVisible(me),e?.setDensity(me?{layers:[Qe.defects,Qe.sewer],ramp:i.heat,top:4}:null)},[Qe,me]),t(()=>{window.geometryDemo={view:()=>Be.current,layers:Qe,town:Ze,live:qe.current,history:rt,setTool:Pe,controller:()=>Be.current?.getController()??null,snapshot:async(e="snapshot")=>{const t=Be.current;if(!t)return null;t.engine.draw();const r=function(e){const t=e.engine.canvas,r=e.labels?.element;if(!r||0===r.childElementCount)return t.toDataURL("image/png");const o=document.createElement("canvas");o.width=t.width,o.height=t.height;const n=o.getContext("2d");n.drawImage(t,0,0);const i=t.width/Math.max(1,t.getBoundingClientRect().width),a=r.getBoundingClientRect();for(const e of Array.from(r.children)){if("none"===e.style.display)continue;const t=e.getBoundingClientRect(),r=getComputedStyle(e),o=(t.left-a.left)*i,l=(t.top-a.top)*i;n.fillStyle=r.backgroundColor,n.beginPath(),n.roundRect(o,l,t.width*i,t.height*i,(parseFloat(r.borderTopLeftRadius)||0)*i),n.fill(),n.fillStyle=r.color,n.font=`${r.fontWeight} ${parseFloat(r.fontSize)*i}px ${r.fontFamily}`,n.textBaseline="middle",n.fillText(e.textContent??"",o+parseFloat(r.paddingLeft)*i,l+t.height*i/2)}return o.toDataURL("image/png")}(t),o=await fetch(`/__snapshot?name=${encodeURIComponent(e)}`,{method:"POST",body:r});return(await o.json()).file}}},[Qe,Ze,rt]);const[nt,it]=n(!1),[at,lt]=n(!1);t(()=>{const e=Ve.current;if(!e)return;const t=new ResizeObserver(()=>{const{clientWidth:t,clientHeight:r}=e;it((t<te||r<re)&&(t>r?"landscape":"portrait"))});return t.observe(e),()=>t.disconnect()},[]);const st=r(()=>({look:ne,hoverFades:ae}),[ne,ae]),ct={sewer:Ze.sewer.length,laterals:Ze.laterals.length,connections:Ze.connections.length,water:Ze.water.length,gas:Ze.gas.length,power:Ze.power.length,buildings:Ze.buildings.length,zones:Ze.zones.length,trees:Ze.trees.length,sensors:Ze.sensors.length,trajectories:Ze.trajectories.length},dt=Object.values(ct).reduce((e,t)=>e+t,0)+Ze.manholes.length+Ze.defects.length,pt=E(),mt=Le?.layers[0],ut=mt?mt.layer.getFeature(mt.ids[0]):void 0,ht="material"!==he?Y[he]:null,ft=O.map(t=>e.createElement(y,{key:t.value,text:t.text,active:N===t.value,onClick:()=>H(t.value),title:`A town ${t.value} times as wide`})),gt=e.createElement(e.Fragment,null,e.createElement(y,{text:"2D",active:"2d"===I,onClick:()=>G("2d"),title:"A flat map: lines and covers"}),e.createElement(y,{text:"3D",active:"3d"===I,onClick:()=>G("3d"),title:"In depth: pipes, shafts, buildings"})),yt=e.createElement(e.Fragment,null,e.createElement(y,{text:"Glow",active:"glow"===ne,onClick:()=>ie("glow"),title:"What is lit glows (bloom)"}),e.createElement(y,{text:"Outline",active:"outline"===ne,onClick:()=>ie("outline"),title:"What is lit is outlined"}),e.createElement(y,{text:"Dim others",active:ae,onClick:()=>le(!ae),title:"Pointing at something dims the rest"})),wt=e.createElement(e.Fragment,null,e.createElement(y,{text:"Flow",active:se,onClick:()=>ce(!se),title:"Light running along the networks, downstream (2D)"}),e.createElement(y,{text:"X-ray",active:de,onClick:()=>pe(!de),title:"See through the buildings"}),e.createElement(y,{text:"Density",active:me,onClick:()=>ue(!me),title:"A heatmap of the defects and the sewer in poor condition"})),bt=je&&e.createElement("span",{style:{opacity:.7,fontSize:12,whiteSpace:nt?"normal":"nowrap",fontVariantNumeric:"tabular-nums"}},"webgpu"===je.backend?"WebGPU":"WebGL 2"," · ",je.fps," fps · ",je.ms.toFixed(1)," ms · ",je.drawCalls," draws · ",(je.triangles/1e6).toFixed(1),"M triangles · ",dt.toLocaleString()," features"),xt=e.createElement(e.Fragment,null,e.createElement(w,{icon:"fit_screen",title:"Show everything",onClick:()=>Be.current?.fit()}),e.createElement(w,{icon:Ke?"dark_mode":"light_mode",title:"Dark or light",onClick:()=>B(Ke?"light":"dark")}),e.createElement(v,{target:()=>Ve.current})),kt=e.createElement(e.Fragment,null,e.createElement(S,{title:"Layers"},e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},q.map(({key:t,title:r,color:o})=>{const n=De[t]??!0;return e.createElement(Q,{key:t,title:r,color:o,on:n,count:ct[t],onClick:()=>$e(e=>({...e,[t]:!n}))})}))),e.createElement(S,{title:"Colour the sewer by",right:e.createElement(b,{value:he,onChange:fe,options:[{value:"material",text:"Material"},{value:"age",text:"Age"},{value:"diameter",text:"Diameter"},{value:"condition",text:"Condition"},{value:"depth",text:"Depth"}]})},ht?e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:4}},e.createElement("div",{style:{height:10,borderRadius:5,background:`linear-gradient(90deg, ${ht.ramp.join(", ")})`}}),e.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,opacity:.75}},e.createElement("span",null,ht.format(ht.domain[0])),e.createElement("span",null,ht.label),e.createElement("span",null,ht.format(ht.domain[1])))):null,e.createElement("div",{style:{display:"flex",flexWrap:"wrap",gap:5}},z.map(t=>e.createElement(g,{key:t,text:t,color:F[t],on:!ve.has(t),onHover:e=>Se(e?t:null),onClick:()=>Ee(e=>{const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r})}))),e.createElement("span",{style:{fontSize:11,opacity:.55}},"Point at a material to light it, click to hide it: one texel on the GPU.")),e.createElement(S,{title:"Year laid",right:e.createElement(e.Fragment,null,e.createElement(y,{text:"Fade",active:"fade"===we,onClick:()=>be("fade"),title:"What falls outside is faded"}),e.createElement(y,{text:"Hide",active:"hide"===we,onClick:()=>be("hide"),title:"What falls outside is hidden"}))},e.createElement(C,{min:1895,max:2024,value:ge,onChange:ye}),e.createElement("span",{style:{fontSize:11,opacity:.55}},"Every pipe and building, filtered on the GPU: two uniforms per step.")),e.createElement(S,{title:"Smallest sewer"},e.createElement(D,{min:150,max:1400,step:50,value:xe,onChange:ke,format:e=>e<=150?"All":`DN ${e}`})),e.createElement(S,{title:"Navigate"},e.createElement("span",{style:{fontSize:12,opacity:.7,lineHeight:1.5}},"Drag to pan, right-drag to turn and tilt, wheel to zoom where you point, double-click to dive in. Click to select; Ctrl or Shift to add; Esc to clear."))),vt={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},Et=e.createElement(S,{title:"View"},e.createElement("div",{style:vt},ft),e.createElement("div",{style:vt},yt),e.createElement("div",{style:vt},wt),bt),Ct=nt?e.createElement("div",{style:{width:1,margin:"0 2px",flex:"none",background:$("border")}}):e.createElement("div",{style:{height:1,margin:"2px 0",background:$("border")}}),St=nt?8:12;return e.createElement("div",{ref:Ve,style:{...x(U),position:"relative",width:"100%",height:"100%",boxSizing:"border-box",padding:nt?4:8,gap:nt?4:8,display:"flex",flexDirection:"column",overflow:"hidden",backgroundColor:$("background"),backgroundImage:`url('${oe}')`,backgroundPosition:"center",backgroundSize:"cover",color:$("text"),fontFamily:$("fontFamily"),fontSize:$("fontSize")}},nt?e.createElement("div",{style:{...pt,display:"flex",gap:8,alignItems:"center",padding:6,flex:"none",overflowX:"auto"}},e.createElement("b",{style:{letterSpacing:"0.5px",marginRight:2}},"Geometry"),gt,e.createElement("div",{style:{flexGrow:1}}),e.createElement(w,{icon:"tune",title:"Layers, colours, filters",active:at,onClick:()=>lt(!at)}),xt):e.createElement("div",{style:{...pt,display:"flex",gap:8,alignItems:"center",padding:8,flexWrap:"wrap",flex:"none"}},e.createElement("b",{style:{letterSpacing:"0.5px",marginRight:4}},"Geometry"),ft,e.createElement(k,null),gt,e.createElement(k,null),yt,e.createElement(k,null),wt,e.createElement(k,null),bt,e.createElement("div",{style:{flexGrow:1}}),xt),e.createElement("div",{style:{display:"flex",flex:1,minHeight:0,gap:8}},!nt&&e.createElement("div",{className:"demo-scroll",style:{...pt,width:292,flex:"none",overflowY:"auto",padding:12,display:"flex",flexDirection:"column",gap:18,boxSizing:"border-box"}},kt),e.createElement("div",{style:{...pt,flex:1,minWidth:0,position:"relative",overflow:"hidden"},onMouseMove:e=>{const t=e.currentTarget.getBoundingClientRect();Oe.current={x:e.clientX-t.left,y:e.clientY-t.top},Ye.current&&(Ye.current.style.left=`${Oe.current.x+14}px`,Ye.current.style.top=`${Oe.current.y+14}px`)}},e.createElement(u,{mode:I,theme:U,forceWebGL:ee,highlight:st,camera:{target:[R,j,0],distance:1250*Xe,heading:18,tilt:58},layers:Je,ground:et,controller:ot,viewRef:Be,onHover:Re,onSelect:Fe,onFrame:We}),e.createElement("div",{style:{position:"absolute",left:St,top:St,...J(),padding:5,display:"flex",gap:4,...nt?{flexDirection:"row",maxWidth:`calc(100% - ${2*St}px)`,overflowX:"auto",scrollbarWidth:"none",boxSizing:"border-box"}:{flexDirection:"column"}}},_.map((t,r)=>e.createElement(e.Fragment,{key:t.tool},(1===r||6===r||7===r)&&Ct,e.createElement(w,{icon:t.icon,title:t.title,active:Me===t.tool,onClick:()=>Pe(t.tool)}))),Ct,e.createElement(w,{icon:"undo",title:Ue.undoLabel?`Undo ${Ue.undoLabel.toLowerCase()} (Ctrl+Z)`:"Nothing to undo",onClick:()=>rt.undo(),active:!1}),e.createElement(w,{icon:"redo",title:Ue.redoLabel?`Redo ${Ue.redoLabel.toLowerCase()} (Ctrl+Y)`:"Nothing to redo",onClick:()=>rt.redo(),active:!1}),e.createElement(w,{icon:"join",title:Te?"Snapping on: to vertices and edges of what is drawn":"Snapping off",active:Te,onClick:()=>Ae(!Te)})),"select"!==Me&&e.createElement(Z,{tool:Me,measurement:Ne,editing:Ie,compact:!!nt}),ze&&"select"===Me&&e.createElement("div",{ref:Ye,style:{position:"absolute",left:Oe.current.x+14,top:Oe.current.y+14,pointerEvents:"none",...J(),padding:"6px 9px",fontSize:12,maxWidth:280,whiteSpace:"nowrap"}},e.createElement("b",null,ze.feature.properties?.name??ze.id),e.createElement("div",{style:{opacity:.7}},function(e){const t=e.properties??{};switch(t.kind){case"sewer":case"lateral":case"water":case"gas":case"power":return`${t.material} · DN ${t.dn}${t.height?`/${t.height}`:""} · ${t.year} · ${t.length?.toFixed(0)} m`;case"manhole":return`${t.depth.toFixed(1)} m deep · ${t.material} · ${t.year}`;case"building":return`${t.use} · ${t.floors} floors · ${t.height.toFixed(0)} m`;case"sensor":return`${t.type} · ${t.value} %`;case"zone":return`Risk: ${t.risk}`;case"tree":return`${t.height.toFixed(0)} m high`;case"connection":return`On ${t.pipe}`;case"trajectory":return t.vehicle;default:return""}}(ze.feature))),ut&&"select"===Me&&e.createElement("div",{style:{position:"absolute",...J(),padding:12,display:"flex",flexDirection:"column",gap:8,boxSizing:"border-box",...nt?{left:St,right:St,bottom:St,maxHeight:"45%",overflowY:"auto"}:{right:12,top:12,width:270}}},e.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},e.createElement("span",{style:{width:10,height:10,borderRadius:5,background:$("accent"),boxShadow:`0 0 8px ${$("accent")}`}}),e.createElement("b",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},ut.properties?.name??ut.id)),Le.count>1&&e.createElement("span",{style:{fontSize:12,opacity:.7}},"and ",Le.count-1," more selected"),e.createElement("table",{style:{fontSize:12,borderCollapse:"collapse"}},e.createElement("tbody",null,function(e){const t=e.properties??{},r=[["Id",String(e.id)]],o=(e,t)=>{null!=t&&""!==t&&r.push([e,String(t)])};["sewer","lateral","water","gas","power"].includes(t.kind)?(o("Material",t.material),o("Profile",`DN ${t.dn}${t.height?` × ${t.height}`:""}`),o("Laid",t.year),o("Condition",`${t.condition} / 5`),o("Length",`${t.length.toFixed(1)} m`),o("Depth",`${t.depthFrom.toFixed(2)} → ${t.depthTo.toFixed(2)} m`),"sewer"===t.kind&&o("Slope",`${t.slope.toFixed(1)} ‰`),o("Upstream",t.upstream),o("Downstream",t.downstream)):Object.entries(t).forEach(([e,t])=>{"name"!==e&&"kind"!==e&&o(e[0].toUpperCase()+e.slice(1),"number"!=typeof t||Number.isInteger(t)?t:t.toFixed(1))});return r}(ut).map(([t,r])=>e.createElement("tr",{key:t},e.createElement("td",{style:{opacity:.6,padding:"2px 10px 2px 0",verticalAlign:"top"}},t),e.createElement("td",{style:{padding:"2px 0",fontVariantNumeric:"tabular-nums"}},r))))),e.createElement("div",{style:{display:"flex",gap:6}},e.createElement(y,{text:"Fly to",onClick:()=>{const e=function(e){const t=e.geometry;return t?"Point"===t.type?t.coordinates:"LineString"===t.type?t.coordinates[Math.floor(t.coordinates.length/2)]:"Polygon"===t.type?t.coordinates[0][0]:null:null}(ut);e&&Be.current?.flyTo({target:[e[0],e[1],0],distance:70,tilt:62},1100)}}),e.createElement(y,{text:"Clear",onClick:()=>Be.current?.clearSelection()}))),me&&e.createElement("div",{style:{position:"absolute",...nt?{right:St,top:St+44}:{left:12,bottom:12},...J(),padding:"8px 10px",width:nt?160:200,display:"flex",flexDirection:"column",gap:4}},e.createElement("span",{style:{fontSize:11,opacity:.7}},"Defects and poor condition"),e.createElement("div",{style:{height:8,borderRadius:4,background:`linear-gradient(90deg, ${i.heat.slice(1).map(e=>l(a([e],0))).join(", ")})`}})),nt&&at&&e.createElement("div",{className:"demo-scroll",style:{position:"absolute",zIndex:2,...pt,...J(),overflowY:"auto",padding:12,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:18,..."portrait"===nt?{left:0,right:0,bottom:0,maxHeight:"58%",borderRadius:`${$("radius")} ${$("radius")} 0 0`}:{top:0,right:0,bottom:0,width:"min(300px, 55%)",borderRadius:`${$("radius")} 0 0 ${$("radius")}`}}},e.createElement("div",{style:{display:"flex",alignItems:"center"}},e.createElement("b",{style:{flex:1}},"Layers and filters"),e.createElement(w,{icon:"close",title:"Close",onClick:()=>lt(!1)})),Et,kt))))}function Z({tool:t,measurement:r,editing:o,compact:n}){const i=[],a=r;if(a&&"clearance"===a.mode?(a.a&&i.push(["From",String(a.a.feature.properties?.name??a.a.feature.id)]),a.b&&i.push(["To",String(a.b.feature.properties?.name??a.b.feature.id)]),void 0!==a.clearance&&i.push(["Clearance",H(a.clearance)])):a&&("area"===a.mode&&void 0!==a.area?(i.push(["Area",N(a.area)]),i.push(["Perimeter",H(a.perimeter??0)])):a.points.length>=2&&(i.push(["Length",H(a.length??0)]),i.push(["Across the map",H(a.horizontal??0)]),i.push(["Height difference",`${(a.rise??0)>=0?"+":""}${H(a.rise??0)}`]),i.push(["Slope",I(a.slope??0)]))),o){const e=o.geometry;i.push(["Editing",String(o.feature.properties?.name??o.feature.id)]),i.push(["Layer",o.layer.title??o.layer.id]),e.type.includes("Polygon")?i.push(["Area",N(G(e))]):e.type.includes("Line")&&i.push(["Length",H(U(e))])}const l=_.find(e=>e.tool===t)?.title.split(":")[0].replace(/ \(.\)$/,"")??"";return e.createElement("div",{style:{position:"absolute",...n?{left:8,right:8,bottom:8}:{left:52,bottom:12,maxWidth:360},...J(),padding:"9px 11px",display:"flex",flexDirection:"column",gap:6,pointerEvents:"none"}},e.createElement("b",{style:{fontSize:12}},l),i.length>0&&e.createElement("table",{style:{fontSize:12,borderCollapse:"collapse"}},e.createElement("tbody",null,i.map(([t,r])=>e.createElement("tr",{key:t},e.createElement("td",{style:{opacity:.6,padding:"1px 12px 1px 0"}},t),e.createElement("td",{style:{fontVariantNumeric:"tabular-nums",fontWeight:600}},r))))),e.createElement("span",{style:{fontSize:11,opacity:.65,lineHeight:1.45}},B[t]))}function Q({title:t,color:r,on:o,count:i,onClick:a}){const[l,s]=n(!1);return e.createElement("button",{onClick:a,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"4px 6px",borderRadius:$("radius"),border:"none",cursor:"pointer",background:l?$("surfaceRaised"):"transparent",color:"inherit",font:"inherit",textAlign:"left",opacity:o?1:.45}},e.createElement("span",{style:{width:14,height:14,borderRadius:3,border:`1.5px solid ${o?r:$("textDisabled")}`,background:o?`${r}55`:"transparent",flex:"none",boxShadow:o?`0 0 6px ${r}88`:"none"}}),e.createElement("span",{style:{flex:1}},t),void 0!==i&&e.createElement("span",{style:{fontSize:11,opacity:.55,fontVariantNumeric:"tabular-nums"}},i.toLocaleString()))}function J(){return{borderRadius:$("radius"),background:`color-mix(in srgb, ${$("surface")} 86%, transparent)`,border:`1px solid ${$("border")}`,boxShadow:$("shadow"),backdropFilter:"blur(8px)"}}const ee="undefined"!=typeof location&&new URLSearchParams(location.search).has("webgl"),te=720,re=520,oe="https://www.protomaze.com/resources/img/mosaic_equirectangular.png";
|
package/README.md
CHANGED
|
@@ -3,23 +3,25 @@
|
|
|
3
3
|
GPU geometry for maps and scenes: points, lines, tubes, spheres and areas, in 2D and 3D, each layer
|
|
4
4
|
one instanced draw. Every feature's look - colour, width, state, material, category, value - lives
|
|
5
5
|
in float textures the shaders read, so a restyle, a filter, a hover or a selection costs a texture
|
|
6
|
-
upload or a uniform, never a rebuild.
|
|
7
|
-
|
|
6
|
+
upload or a uniform, never a rebuild. Networks drawn as they are on a map - pipes, manholes,
|
|
7
|
+
laterals, flow arrows, a heatmap, picking on the GPU - with the geometry calculations, and the
|
|
8
8
|
controllers to draw, edit and measure, that go with it.
|
|
9
9
|
|
|
10
10
|
```bash
|
|
11
11
|
npm run dev # the demo, on http://localhost:8091
|
|
12
12
|
npm test # the DOM-free parts: calculations, editing's shapes and history, the camera
|
|
13
|
-
npm run check # type-check everything, demo
|
|
13
|
+
npm run check # type-check everything, demo included
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
Built on three.js's WebGPU renderer and TSL, so the same shaders run on WebGPU -
|
|
17
|
-
|
|
16
|
+
Built on three.js's WebGPU renderer and TSL, so the same shaders run on WebGPU - on a canvas of
|
|
17
|
+
their own, or inside a host's WebGPU frame (a map's, a globe's) - and on WebGL 2 where a browser
|
|
18
|
+
has no WebGPU.
|
|
18
19
|
|
|
19
20
|
## The model
|
|
20
21
|
|
|
21
22
|
```
|
|
22
|
-
GeometryView / <ReactGeometry> ──
|
|
23
|
+
GeometryView / <ReactGeometry> ── layers, highlight, hover, selection, picking; on a canvas with a
|
|
24
|
+
│ camera that pans, zooms and orbits - or in a host's frame, the host's camera and input
|
|
23
25
|
│
|
|
24
26
|
├─ layers: LineLayer, PointLayer, TubeLayer, SphereLayer, AreaLayer
|
|
25
27
|
│ features + style + filters + selection; each builds its primitives and owns their looks
|
|
@@ -28,7 +30,7 @@ GeometryView / <ReactGeometry> ── a canvas, a camera that pans, zooms and or
|
|
|
28
30
|
│ a Sketch of overlay layers over everything, a Snapper, labels, an EditHistory
|
|
29
31
|
│
|
|
30
32
|
└─ CanvasGeometryEngine ── the engine: scenes per pass, origin, scene depth, bloom, halo, heatmap, pick
|
|
31
|
-
HostedGeometryEngine
|
|
33
|
+
HostedGeometryEngine ── the same engine inside a host's WebGPU frame: a map's, a globe's
|
|
32
34
|
|
|
33
35
|
primitives: GpuLines, GpuIcons, GpuTubes, GpuSpheres, GpuAreas ── one instanced draw per pass,
|
|
34
36
|
reading a FeatureLook: the per-feature textures plus the uniforms that filter, light and colour
|
|
@@ -36,7 +38,7 @@ primitives: GpuLines, GpuIcons, GpuTubes, GpuSpheres, GpuAreas ── one instan
|
|
|
36
38
|
|
|
37
39
|
Three levels, each usable on its own: the **view** for an application that wants a map; the
|
|
38
40
|
**layers** for one that has features and styles; the **primitives and an engine** for a host that
|
|
39
|
-
draws its own frame
|
|
41
|
+
draws its own frame.
|
|
40
42
|
|
|
41
43
|
## A view
|
|
42
44
|
|
|
@@ -71,7 +73,7 @@ The view emits `hover`, `click`, `select`, `camera`, `mode` and `frame` (fps, dr
|
|
|
71
73
|
| `AreaLayer` | polygons | flat fills, solid or hatched, with outlines; or extruded volumes, heights on the GPU, lit windows at night |
|
|
72
74
|
|
|
73
75
|
Every 3D body is ghosted where the scene's surface (the ground) is in front of it and outlined by a
|
|
74
|
-
dark halo
|
|
76
|
+
dark halo; never thinner on screen than its look's width in
|
|
75
77
|
pixels, so far off a pipe is a line, still at its depth.
|
|
76
78
|
|
|
77
79
|
## Styling, filtering, lighting up
|
|
@@ -80,7 +82,7 @@ pixels, so far off a pipe is a line, still at its depth.
|
|
|
80
82
|
|---|---|---|
|
|
81
83
|
| A style | `layer.setStyle(f => ...)`, `layer.restyle(ids?)` | one write per feature into the look's textures, one upload at the next frame |
|
|
82
84
|
| A filter | `layer.setFilter(f => ..., 'hide' \| 'fade')` | as a style: decided on the CPU |
|
|
83
|
-
| A range | `layer.setRange({ value, low, high, outside })`, then `setRangeBounds(low, high)` | every value written once
|
|
85
|
+
| A range | `layer.setRange({ value, low, high, outside, fixed, fail })`, then `setRangeBounds(low, high)`; `setRange(null)` ends it | every value written once - `fixed` says where the other filters settle it whatever the range, `fail` gives a look out of it instead of hiding or fading - and a drag step is two uniforms |
|
|
84
86
|
| Categories | `layer.setCategories({ of, keys, colors })`, `setCategoryMode(key, 'hidden' \| 'faded' \| 'shown' \| 'lit')` | one texel per switch; 'lit' lights a whole category, a legend entry pointed at |
|
|
85
87
|
| Colour by | `layer.colorBy({ by: 'category' })`, `colorBy({ value, ramp, domain })` | a uniform and a 256-texel ramp |
|
|
86
88
|
| Hover | the view's pointer, or `layer.setHovered(id)` | one uniform |
|
|
@@ -88,9 +90,14 @@ pixels, so far off a pipe is a line, still at its depth.
|
|
|
88
90
|
| Emphasis | `layer.emphasize(ids)`: lit as the selection is, without selecting | a few texels |
|
|
89
91
|
| Density | `view.setDensity({ layers, ramp, top })` | the same geometry adding its weight into the heatmap instead |
|
|
90
92
|
|
|
91
|
-
What is lit glows - the bloom pass over the selected geometry alone
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
What is lit glows - the bloom pass over the selected geometry alone, the line shader's own glow, or
|
|
94
|
+
none (`highlight.glow`) - or is outlined (`highlight.look`), and while the pointer rests on something,
|
|
95
|
+
or something is emphasised, the rest is shaded (`hoverFades`, `othersShade`, `othersToward`). Faded
|
|
96
|
+
features go grey and see-through, the same whether the CPU's filter or the GPU's faded them.
|
|
97
|
+
|
|
98
|
+
What is lit stays lit where its own style - or a filter, a range - fades or hides it: drawn as lit,
|
|
99
|
+
its glow or its outline behind it, only faded (`highlight.outsideOpacity`, 0.6), to show it is
|
|
100
|
+
selected but not in view now. Where its style hides it, it is never picked.
|
|
94
101
|
|
|
95
102
|
Several primitives can share one look (`FeatureLook`): an area's fill and its outline, a pipe drawn as
|
|
96
103
|
a tube in 3D and as a line in 2D. They light, filter and colour as one, from one texture upload.
|
|
@@ -108,6 +115,66 @@ meanwhile: switching the demo to its City size keeps every frame under 150 ms, w
|
|
|
108
115
|
shaders inside the frames took up to 530 ms. What was compiled once draws at once when it comes
|
|
109
116
|
back, as a 2D map toggled back to 3D does. `engine.compilingShaders` says whether any are being made.
|
|
110
117
|
|
|
118
|
+
## Theming
|
|
119
|
+
|
|
120
|
+
The view's own chrome - the clear colour, the outline round what is lit, the ground grid, labels,
|
|
121
|
+
what a controller draws - is styled by the Protomaze theme, the design tokens every @protomaze
|
|
122
|
+
package shares (`src/theme/Theme.ts`): CSS custom properties, `--pm-*`, read where the view sits.
|
|
123
|
+
Set them once round the application and the view follows, as time, charts and the rest do. What is
|
|
124
|
+
left unset keeps Protomaze's own look, dark or light. The data's colours - styles, `CATEGORY_COLORS`,
|
|
125
|
+
`RAMPS`, the heatmap's ramp - are the application's and stay as they are.
|
|
126
|
+
|
|
127
|
+
| Token | Property | In the view |
|
|
128
|
+
|---|---|---|
|
|
129
|
+
| `background` | `--pm-color-background` | the canvas's clear colour: what a 2D map shows past its ground |
|
|
130
|
+
| `highlight` | `--pm-color-highlight` | the outline round what is lit (`highlight: { look: 'outline' }`): lines, icons, bodies |
|
|
131
|
+
| `text` | `--pm-color-text` | the ground grid's lines (drawn faint); labels' text; a sketch's vertex handles |
|
|
132
|
+
| `textMuted` | `--pm-color-text-muted` | `info` labels |
|
|
133
|
+
| `surface` | `--pm-color-surface` | labels' background, a little see-through over the map |
|
|
134
|
+
| `danger`, `onAccent` | `--pm-color-danger`, `--pm-color-on-accent` | `warning` labels (`onAccent` where it reads on danger, else white); a sketch's shape that cannot be |
|
|
135
|
+
| `accent` | `--pm-color-accent` | what a controller draws: the shape, the rubber band, the handle in hand |
|
|
136
|
+
| `fontFamily`, `fontSize`, `fontWeight`, `fontWeightStrong` | `--pm-font-*` | labels |
|
|
137
|
+
| `radius`, `shadow` | `--pm-radius`, `--pm-shadow` | labels' corners and shadow |
|
|
138
|
+
|
|
139
|
+
What wins: what the application passes the view - a `theme` object's colours, `highlight.outlineColor`,
|
|
140
|
+
a controller's `theme`, the styles - over the `--pm-*` tokens round the view, over Protomaze's
|
|
141
|
+
defaults for the look.
|
|
142
|
+
|
|
143
|
+
```css
|
|
144
|
+
:root {
|
|
145
|
+
--pm-color-background: #1A1A1A;
|
|
146
|
+
--pm-color-surface: #1A1A1A;
|
|
147
|
+
--pm-color-text: #EBE8E0;
|
|
148
|
+
--pm-color-accent: #9AC0A6;
|
|
149
|
+
--pm-color-highlight: #9AC0A6;
|
|
150
|
+
--pm-font-family: 'Source Sans 3', sans-serif;
|
|
151
|
+
--pm-radius: 0px;
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { applyTheme } from '@protomaze/geometry';
|
|
157
|
+
|
|
158
|
+
const undo = applyTheme({ accent: '#9AC0A6', highlight: '#9AC0A6', text: '#EBE8E0', radius: 0 }); // on <html>, or pass an element
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The tokens are read at the view's own element, so they can be set on any element round it, for one
|
|
162
|
+
view and not another. The view resolves them when it starts and whenever they change - a stylesheet
|
|
163
|
+
or class switching the application's theme, `applyTheme`, `color-scheme`, the system's dark mode -
|
|
164
|
+
and rewrites its uniforms, labels and sketches then, without a reload; never per frame. `view.tokens`
|
|
165
|
+
is what it resolved. The GPU draws its colours opaque: a token's alpha is dropped there.
|
|
166
|
+
|
|
167
|
+
`theme` picks the look whose defaults fill in what the tokens leave: `'dark'` (the default), `'light'`,
|
|
168
|
+
or `'auto'`, which follows the page's `color-scheme` where it names one, else the system's
|
|
169
|
+
preference. The look also decides what the rest is shaded towards while something is lit (black on
|
|
170
|
+
dark, white on light). The scene's own colours are not tokens - the ground, the sky in perspective,
|
|
171
|
+
whether the buildings' windows are lit - and stay in the `theme` object, one set per look
|
|
172
|
+
(`DARK_THEME`, `LIGHT_THEME`), where an application overrides them:
|
|
173
|
+
|
|
174
|
+
```tsx
|
|
175
|
+
<ReactGeometry theme={{ scheme: 'auto', ground: '#202020', sky: { zenith: '#000', horizon: '#222', glow: '#333' } }} />
|
|
176
|
+
```
|
|
177
|
+
|
|
111
178
|
## Calculations
|
|
112
179
|
|
|
113
180
|
Plain functions on GeoJSON-shaped geometry, in world units - metres in a projected or local
|
|
@@ -128,8 +195,8 @@ reference - DOM-free and tested (`npm test`). Lengths and distances count height
|
|
|
128
195
|
|
|
129
196
|
## Drawing, editing, measuring
|
|
130
197
|
|
|
131
|
-
A controller takes over the view's pointer and keys for a while, as
|
|
132
|
-
its map: `view.setController(controller)`, or `<ReactGeometry controller={controller}>`; null gives
|
|
198
|
+
A controller takes over the view's pointer and keys for a while, as a map toolkit's controllers do
|
|
199
|
+
on its map: `view.setController(controller)`, or `<ReactGeometry controller={controller}>`; null gives
|
|
133
200
|
the view its own ways back. It sees every event first and leaves what it does not handle - a drag
|
|
134
201
|
on empty ground still pans, the wheel still zooms.
|
|
135
202
|
|
|
@@ -188,42 +255,57 @@ bodies read to tell what lies behind the ground.
|
|
|
188
255
|
Frames on demand, continuously only while something moves (flow, a flight).
|
|
189
256
|
- **`HostedGeometryEngine`**: inside a frame someone else draws with WebGPU. The host gives a device,
|
|
190
257
|
and every frame its colour texture, its depth texture and its camera; three draws into that colour
|
|
191
|
-
texture with the host's device.
|
|
192
|
-
- **`RiaGeometryEngine`**: the hosted engine on a LuciadRIA map, typed by shape (no RIA import):
|
|
193
|
-
`RiaGeometryEngine.of(map)` hooks `PostRender` and `WebGPUDeviceChanged`.
|
|
258
|
+
texture with the host's device (see "In a host's frame").
|
|
194
259
|
|
|
195
|
-
A primitive is attached with `engine.attach(primitive)`, or its meshes put into the scenes by hand
|
|
196
|
-
|
|
260
|
+
A primitive is attached with `engine.attach(primitive)`, or its meshes put into the scenes by hand;
|
|
261
|
+
every frame it gets `setFrame(frame)`.
|
|
197
262
|
|
|
198
|
-
## In
|
|
263
|
+
## In a host's frame
|
|
199
264
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
on every `npm run check`).
|
|
265
|
+
A map toolkit or a globe that renders with WebGPU can have the layers drawn in its own frame, over
|
|
266
|
+
what it draws and against its depth, under its camera. The package knows no host by name: an
|
|
267
|
+
application wires its host up in a few lines of its own.
|
|
204
268
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
269
|
+
```ts
|
|
270
|
+
const engine = new HostedGeometryEngine({
|
|
271
|
+
device: host.device, // the host's WebGPU device (`setDevice` when it makes another)
|
|
272
|
+
requestFrame: () => host.repaint(), // a frame for a change only the geometry knows of
|
|
273
|
+
originKey: () => host.referenceName, // an origin per reference, for a host that switches
|
|
274
|
+
});
|
|
275
|
+
host.afterDrawing((color, depth) => engine.render(color, depth, {
|
|
276
|
+
viewProjection: host.camera.viewProjection, // world to clip, row-major, in the host's world units
|
|
277
|
+
glDepth: true, // clip z -1..1, as OpenGL's cameras have it
|
|
278
|
+
near: host.camera.near,
|
|
279
|
+
pixelRatio: color.width / host.width,
|
|
280
|
+
geocentric: host.isGlobe, // ECEF: up is the ellipsoid's
|
|
281
|
+
eye: host.camera.eye,
|
|
282
|
+
}));
|
|
283
|
+
|
|
284
|
+
const view = new GeometryView({ engine, mode: '3d', element: host.element });
|
|
285
|
+
view.addLayer(new LineLayer({ features, style }));
|
|
286
|
+
host.onClick(async (x, y) => select(await view.pickAt(x, y))); // { layer, id, feature, point }
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The view on a host's engine has layers, their looks, the highlight, selection, emphasis, the heatmap
|
|
290
|
+
and picking; the host keeps the camera, the ground and the input, so there is no `init`, no
|
|
291
|
+
controllers and no camera calls. `view.toScreen(p)` is where the host's camera put a position on
|
|
292
|
+
the last frame. On a globe (`geocentric`) the ground's up is the ellipsoid's normal at the origin,
|
|
293
|
+
which tubes stand along and volumes rise along. `view.setMode('2d' | '3d')` when the host switches:
|
|
294
|
+
the layers draw the other way, the host turns its camera. The `--pm-*` tokens are read round
|
|
295
|
+
`element`.
|
|
296
|
+
|
|
297
|
+
- **Depth.** The host's depth texture is copied in every frame and the bodies are ghosted behind it.
|
|
298
|
+
The camera's clip depth may be OpenGL's (`glDepth: true`, -1..1) or the backend's own; the engine
|
|
299
|
+
folds it into the camera, so the primitives use clip space as it is.
|
|
300
|
+
- **What stands in front.** A host's mask of buildings and trees is a `GeometryOccluder` by shape:
|
|
301
|
+
`occluder` on `LineLayer`, `TubeLayer`, `SphereLayer` (`layer.setOccluder` to change it).
|
|
302
|
+
- **Worlds not in metres.** On Web Mercator, `worldPerMetre: mercatorWorldPerMetre(y)` keeps a line's
|
|
303
|
+
width in metres true.
|
|
304
|
+
- **A host's own colour map.** `view.setDensity({ ramp })` takes a list of colours or anything with
|
|
305
|
+
`retrieveColor(level)`, as it is.
|
|
306
|
+
|
|
307
|
+
`npm run dev`, then `?hosted`: a stand-in host - its own WebGPU device, canvas, camera, colour and
|
|
308
|
+
depth - with the engine and a view in its frame (`src/hosted.tsx`, never in the package).
|
|
227
309
|
|
|
228
310
|
## How it draws
|
|
229
311
|
|
package/common/Colors.d.ts
CHANGED
|
@@ -15,8 +15,7 @@ export declare function desaturate([r, g, b, a]: Rgba, amount: number): Rgba;
|
|
|
15
15
|
export declare function withAlpha(color: ColorLike, alpha: number): Rgba;
|
|
16
16
|
/**
|
|
17
17
|
* Something that gives a colour for a level: a list of colours spread evenly from 0 to 1, or an
|
|
18
|
-
* object with `retrieveColor
|
|
19
|
-
* can be handed over as it is.
|
|
18
|
+
* object with `retrieveColor`, so a host's own colour map can be handed over as it is.
|
|
20
19
|
*/
|
|
21
20
|
export type ColorRamp = readonly ColorLike[] | {
|
|
22
21
|
retrieveColor(level: number): string;
|
package/common/Colors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const t=new Map;let e;export function parseColor(n,f=[.5,.5,.5,1]){if(!n)return f;if("string"!=typeof n)return[n[0]??0,n[1]??0,n[2]??0,n[3]??1];const o=t.get(n);if(o)return o;const a=r(n.trim())??function(t){
|
|
1
|
+
const t=new Map;let e;export function parseColor(n,f=[.5,.5,.5,1]){if(!n)return f;if("string"!=typeof n)return[n[0]??0,n[1]??0,n[2]??0,n[3]??1];const o=t.get(n);if(o)return o;const a=r(n.trim())??function(t){if("undefined"==typeof document)return;if(e??(e=document.createElement("canvas").getContext("2d",{willReadFrequently:!0})),!e)return;e.fillStyle="#000",e.fillStyle=t;const n=r(String(e.fillStyle));if(n)return n;e.clearRect(0,0,1,1),e.fillRect(0,0,1,1);const[f,o,a,c]=e.getImageData(0,0,1,1).data;return[f/255,o/255,a/255,c/255]}(n)??f;return t.size>4096&&t.clear(),t.set(n,a),a}function r(t){if(t.startsWith("#")){const e=t.slice(1),r=(t,r)=>parseInt(e.slice(t*r,t*r+r).repeat(3-r),16)/255;if(!/^[0-9a-fA-F]+$/.test(e))return;return 3===e.length||4===e.length?[r(0,1),r(1,1),r(2,1),4===e.length?r(3,1):1]:6===e.length||8===e.length?[r(0,2),r(1,2),r(2,2),8===e.length?r(3,2):1]:void 0}const e=/^rgba?\(([^)]+)\)$/i.exec(t);if(e){const t=e[1].split(/[\s,/]+/).filter(Boolean);if(t.length<3)return;const r=t=>t.endsWith("%")?parseFloat(t)/100:parseFloat(t)/255,n=void 0===t[3]?1:t[3].endsWith("%")?parseFloat(t[3])/100:parseFloat(t[3]);return[r(t[0]),r(t[1]),r(t[2]),n]}}export function toCss([t,e,r,n]){const f=t=>Math.round(255*Math.min(1,Math.max(0,t)));return`rgba(${f(t)}, ${f(e)}, ${f(r)}, ${Math.round(1e3*n)/1e3})`}export function desaturate([t,e,r,n],f){const o=(t+e+r)/3;return[t+(o-t)*f,e+(o-e)*f,r+(o-r)*f,n]}export function withAlpha(t,e){const[r,n,f]=parseColor(t);return[r,n,f,e]}export function sampleRamp(t,e,r=0,n=1){const f=new Float32Array(4*e);for(let o=0;o<e;o++){const a=1===e?0:o/(e-1);f.set(rampColor(t,r+(n-r)*a,r,n),4*o)}return f}export function rampColor(t,e,r=0,n=1){if(!Array.isArray(t))return parseColor(t.retrieveColor(e));const f=t;if(0===f.length)return[0,0,0,0];if(1===f.length)return parseColor(f[0]);const o=Math.min(1,Math.max(0,(e-r)/(n-r||1)))*(f.length-1),a=Math.min(f.length-2,Math.floor(o)),c=parseColor(f[a]),i=parseColor(f[a+1]),l=o-a;return[c[0]+(i[0]-c[0])*l,c[1]+(i[1]-c[1])*l,c[2]+(i[2]-c[2])*l,c[3]+(i[3]-c[3])*l]}export const RAMPS={viridis:["#440154","#3b528b","#21918c","#5ec962","#fde725"],magma:["#000004","#3b0f70","#8c2981","#de4968","#fe9f6d","#fcfdbf"],turbo:["#30123b","#4686fb","#1be5b5","#a4fc3c","#fbb938","#e4460a","#7a0403"],condition:["#1a9850","#91cf60","#fee08b","#fc8d59","#d73027"],heat:["#00000000","#1b2a8c","#2a7fff","#2ee6c8","#f4f86a","#ff8c3a","#ff2d55","#ffffff"],ice:["#04232b","#0b5563","#1fa3b5","#7fe3f0","#f2feff"]};export const CATEGORY_COLORS=["#4cc9f0","#f72585","#b5e48c","#ffb703","#9b5de5","#00f5d4","#fb8500","#e9ff70","#ff70a6","#70d6ff","#ff9770","#c0fdff"];
|
package/demo/DemoControls.d.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
import { CSSProperties, ReactNode } from 'react';
|
|
2
|
-
|
|
2
|
+
import { ColorScheme, ThemeTokens } from '../theme/Theme';
|
|
3
|
+
/** The Protomaze lime the demo's drawn features are in: their colour is data, drawn on the GPU. */
|
|
3
4
|
export declare const ACCENT = "#df0";
|
|
4
|
-
/**
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The demo's UI reads the theme through `--demo-*` properties set on its root (`demoTheme`): each
|
|
7
|
+
* the page's `--pm-*` token, else Protomaze's own for the look the demo is in.
|
|
8
|
+
*/
|
|
9
|
+
export declare function demoTheme(scheme: ColorScheme): Record<string, string>;
|
|
10
|
+
/** A token as the demo's UI uses it in CSS: `var(--demo-color-accent)`. */
|
|
11
|
+
export declare function token(key: keyof ThemeTokens): string;
|
|
12
|
+
/** A pill's round ends where the theme has round corners at all, square where it has none. */
|
|
13
|
+
export declare const PILL: string;
|
|
14
|
+
/** Panels in the theme's surface and corners. */
|
|
15
|
+
export declare function panelStyle(_dark?: boolean): CSSProperties;
|
|
6
16
|
/** A text button, lit while `active`: a choice of a group, or a switch that is on. */
|
|
7
17
|
export declare function DemoButton({ text, active, onClick, disabled, title }: {
|
|
8
18
|
text: ReactNode;
|
package/demo/DemoControls.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e,{useEffect as t,useState as n}from"react";export const ACCENT="#df0";export function panelStyle(e){return{borderRadius:
|
|
1
|
+
import e,{useEffect as t,useState as n}from"react";import{protomazeTheme as o,THEME_PROPERTIES as r,themeProperties as i}from"../theme/Theme.js";export const ACCENT="#df0";export function demoTheme(e){const t={};for(const[n,r]of Object.entries(i(o(e))))t[a(n)]=`var(${n}, ${r})`;return t}export function token(e){return`var(${a(r[e])})`}function a(e){return e.replace("--pm-","--demo-")}export const PILL=`min(calc(${token("radius")} * 100), 11px)`;export function panelStyle(e){return{borderRadius:token("radius"),backgroundColor:token("surface")}}function l(e,t,n){return{height:22,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,backgroundColor:t?token("accent"):e?`color-mix(in srgb, ${token("accent")} 24%, ${token("surfaceRaised")})`:token("surfaceRaised"),color:token(t?"onAccent":"text"),fontFamily:token("fontFamily"),fontWeight:token("fontWeightStrong"),fontSize:token("fontSize"),letterSpacing:"0.5px",padding:"2px 6px",border:"none",borderRadius:token("radius"),cursor:"pointer",boxShadow:e&&!t?`inset 0 0 0 1px ${token("accent")}`:"none",transition:"background-color 0.2s, box-shadow 0.2s",whiteSpace:"nowrap",...n}}function c(){const[e,t]=n(!1);return{hovered:e,bind:{onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1)}}}export function DemoButton({text:t,active:n=!1,onClick:o,disabled:r,title:i}){const{hovered:a,bind:s}=c();return e.createElement("button",{...s,onClick:o,disabled:r,title:i,style:l(n,a&&!r,r?{opacity:.4,cursor:"default"}:void 0)},t)}export function DemoIconButton({icon:o,active:r=!1,onClick:i,title:a}){const{hovered:p,bind:m}=c(),f=function(){const[e,o]=n(u);return t(()=>{if(u)return;let e=!0;return(d??(d=new Promise(e=>{const t="protomaze-material-symbols";if(!document.getElementById(t)){const e=document.createElement("link");e.id=t,e.rel="stylesheet",e.href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=block",document.head.appendChild(e)}const n=()=>{u=!0,e()},o=performance.now(),r=()=>{const e=document.fonts;if(!e?.load||performance.now()-o>1e4)return n();e.load(`18px "${s}"`,"fit_screen").then(e=>e.length>0?n():setTimeout(r,100),()=>setTimeout(r,100))};r()})),d).then(()=>{e&&o(!0)}),()=>{e=!1}},[]),e}();return e.createElement("button",{...m,onClick:i,title:a,"aria-label":a,style:l(r,p,{width:22,padding:2,overflow:"hidden"})},e.createElement("span",{className:"material-symbols-outlined","aria-hidden":"true",style:{fontSize:18,lineHeight:1,fontVariationSettings:"'FILL' 1",visibility:f?"visible":"hidden"}},o))}export function DemoSelect({value:t,options:n,onChange:o,label:r}){const{hovered:i,bind:a}=c();return e.createElement("select",{...a,value:t,"aria-label":r,onChange:e=>o(n.find(t=>String(t.value)===e.target.value).value),style:l(!1,i,{appearance:"auto",padding:"0 4px",outline:"none"})},n.map(t=>e.createElement("option",{key:String(t.value),value:t.value,style:{background:token("surface"),color:token("text")}},t.text)))}export function FullscreenButton({target:o}){const[r,i]=n(!1);return t(()=>{const e=()=>i(null!==document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[]),e.createElement(DemoIconButton,{icon:r?"fullscreen_exit":"fullscreen",title:"Full screen",onClick:()=>{document.fullscreenElement?document.exitFullscreen():o()?.requestFullscreen?.()}})}const s="Material Symbols Outlined";let u=!1,d=null;export function Divider(){return e.createElement("div",{style:{width:1,height:16,background:token("border"),flex:"none"}})}export function Section({title:t,right:n,children:o}){return e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:6}},e.createElement("div",{style:{display:"flex",alignItems:"center",gap:6}},e.createElement("span",{style:{fontSize:11,letterSpacing:"0.8px",textTransform:"uppercase",color:token("textMuted"),flex:1}},t),n),o)}export function RangeSlider({min:t,max:n,value:o,onChange:r,format:i=String}){const[a,l]=o,c=e=>(e-t)/(n-t)*100,s={position:"absolute",inset:0,width:"100%",margin:0,background:"none",pointerEvents:"none",appearance:"none",WebkitAppearance:"none",accentColor:token("accent"),height:18};return e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},e.createElement("div",{style:{position:"relative",height:18}},e.createElement("div",{style:{position:"absolute",left:0,right:0,top:8,height:2,background:token("border"),borderRadius:1}}),e.createElement("div",{style:{position:"absolute",left:`${c(a)}%`,right:100-c(l)+"%",top:7,height:4,background:token("accent"),borderRadius:2}}),e.createElement("input",{type:"range",className:"demo-thumb",min:t,max:n,value:a,style:s,onChange:e=>r([Math.min(Number(e.target.value),l),l])}),e.createElement("input",{type:"range",className:"demo-thumb",min:t,max:n,value:l,style:s,onChange:e=>r([a,Math.max(Number(e.target.value),a)])})),e.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,opacity:.75}},e.createElement("span",null,i(a)),e.createElement("span",null,i(l))))}export function Slider({min:t,max:n,step:o=1,value:r,onChange:i,format:a=String}){return e.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},e.createElement("input",{type:"range",min:t,max:n,step:o,value:r,onChange:e=>i(Number(e.target.value)),style:{flex:1,accentColor:token("accent"),margin:0}}),e.createElement("span",{style:{fontSize:11,opacity:.75,minWidth:54,textAlign:"right"}},a(r)))}export function Chip({color:t,text:n,on:o,onClick:r,onHover:i,count:a}){const{hovered:l,bind:s}=c();return e.createElement("button",{onClick:r,onMouseEnter:()=>{s.onMouseEnter(),i?.(!0)},onMouseLeave:()=>{s.onMouseLeave(),i?.(!1)},style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 8px 3px 6px",borderRadius:PILL,border:`1px solid ${token(l?"accent":"border")}`,background:o?token("surfaceRaised"):"transparent",color:"inherit",font:"inherit",fontSize:12,cursor:"pointer",opacity:o?1:.45,transition:"opacity 0.2s, border-color 0.2s"}},e.createElement("span",{style:{width:10,height:10,borderRadius:5,background:t,boxShadow:o?`0 0 6px ${t}`:"none"}}),n,void 0!==a&&e.createElement("span",{style:{opacity:.55,fontSize:11}},a.toLocaleString()))}
|
package/edit/CreateController.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatArea as t,formatLength as s}from"../engine/Labels.js";import{distance as e,pathLength as i,pointOnSurface as n,area as o}from"../math/Measure.js";import{selfIntersections as h}from"../math/Lines.js";import{circle as r,orientPolygon as p,rectangle as l}from"../math/Polygons.js";import{GeometryController as a}from"./GeometryController.js";import{Sketch as c,SKETCH_THEME as u}from"./Sketch.js";import{Snapper as g}from"./Snapper.js";let d=0;export class CreateController extends a{constructor(t){super(),this.options=t,this.snapper=null,this.points=[],this.hover=null,this.problem=null,this.sketch=new c({...u,...t.theme}),this.cursor="crosshair"}get shape(){return this.options.shape}setShape(t){this.options={...this.options,shape:t},this.reset()}setOptions(t){this.options={...this.options,...t},this.snapper&&(this.snapper.options=!1===t.snapping?{}:t.snapping??this.snapper.options),this.render()}getPoints(){return this.points}onAttach(t){this.sketch.attach(t),!1!==this.options.snapping&&(this.snapper=new g(t,this.options.snapping??{}),this.snapper.warm()),this.render()}onDetach(t){this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,t.labels?.clear("create"),this.points=[],this.hover=null}onPointerMove(t){return this.hover=this.locate(t),this.render(),!0}onPointerLeave(){this.hover=null,this.render()}onClick(t){if(0!==t.button)return!1;const s=this.locate(t);if(!s)return!0;this.hover=s;const e=this.options.shape;if("point"===e)return this.points=[s.point],this.finish(),!0;if("rectangle"===e||"circle"===e)return this.points.push(s.point),this.points.length>=2?this.finish():this.render(),!0;if("self"===s.kind){if(("polygon"===e?this.points.length>=3:this.points.length>=2)&&("polygon"===e&&0===s.own||s.own===this.points.length-1))return this.finish(),!0}const i=this.points[this.points.length-1],n=i?this.host?.toScreen(i):null,o=this.host?.toScreen(s.point);return n&&o&&Math.hypot(n[0]-o[0],n[1]-o[1])<3||(this.points.push(s.point),this.render()),!0}onDoubleClick(t){const s=this.options.shape;if("line"!==s&&"polygon"!==s)return this.points.length>0;const e=this.points.length;if(e>=2){const t=this.host?.toScreen(this.points[e-1]),s=this.host?.toScreen(this.points[e-2]);t&&s&&Math.hypot(t[0]-s[0],t[1]-s[1])<6&&this.points.pop()}return this.finish(),!0}onKeyDown(t){return"Escape"===t.key?0!==this.points.length&&(this.cancel(),!0):"Enter"===t.key?(this.finish(),!0):!("Backspace"!==t.key&&"Delete"!==t.key&&(!t.ctrlKey&&!t.metaKey||"z"!==t.key.toLowerCase()))&&(0!==this.points.length&&(this.points.pop(),this.render(),!0))}cancel(){const t=this.points.length>0;this.reset(),t&&this.emit("cancel")}finish(){const t=this.geometryOf(this.points);if(!t)return!1;const s=this.check(t);if(s)return this.problem=s,this.render(),!1;let e=null;const i=this.options.layer;return i&&(e=this.options.feature?.(t)??{id:`drawn-${Date.now().toString(36)}-${++d}`,geometry:t,properties:{}},i.addFeatures([e]),this.options.history?.push(`Draw ${this.options.shape}`,[{layer:i,before:null,after:e}])),this.emit("finish",{geometry:t,feature:e}),this.reset(),!0}reset(){this.points=[],this.problem=null,this.render()}locate(t){const s=this.host;if(!s)return null;const e=this.options.z??s.camera.state.target[2],i=this.options.shape,n="polygon"===i?this.points.length>=3?[this.points[0],this.points[this.points.length-1]]:[]:"line"===i&&this.points.length>=2?[this.points[this.points.length-1]]:[],o=this.points[this.points.length-1]??null;if(this.snapper){const s=this.snapper.snap(t.x,t.y,t.shift,{z:e,own:n,from:o});return"self"===s?.kind&&void 0!==s.own&&(s.own=n[s.own]===this.points[0]?0:this.points.length-1),s||null}const h=s.toGround(t.x,t.y,e);return h?{point:h,kind:"none"}:null}geometryOf(t){const s=this.options.shape,e=t.length;if("point"===s)return e>=1?{type:"Point",coordinates:t[0]}:null;if("line"===s)return e>=2?{type:"LineString",coordinates:t.map(t=>[...t])}:null;if("polygon"===s)return e>=3?{type:"Polygon",coordinates:p([t.map(t=>[...t])])}:null;if("rectangle"===s)return e<2||t[0][0]===t[1][0]||t[0][1]===t[1][1]?null:l(t[0],t[1]);if(e<2)return null;const i=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]);return i>0?r(t[0],i,this.options.segments??64):null}check(t){return"Polygon"!==t.type||o(t)>0?"LineString"!==t.type||i(t.coordinates)>0?this.options.validate?this.options.validate(t):"Polygon"===t.type&&h(t.coordinates[0],!0).length>0?"Edges cross":null:"A line needs length":"An area needs room inside"}render(){const r=this.host;if(!r)return;const p=this.options.shape,l=this.hover,a=l?[...this.points,l.point]:[...this.points],c={fills:[],lines:[],points:[]},u=[],g=!1!==this.options.measure;let d,m;const y=this.geometryOf(a),k="polygon"===p&&a.length>=4?h([...a,a[0]],!0):[],v=this.problem??(k.length>0?"Edges cross":null);if("line"===p||"polygon"===p){if("polygon"===p&&a.length>=3&&c.fills.push({rings:[[...a,a[0]]],role:v?"invalid":"fill"}),this.points.length>=2&&c.lines.push({coordinates:this.points,role:v?"invalid":"edge"}),l&&this.points.length>=1&&(c.lines.push({coordinates:[this.points[this.points.length-1],l.point],role:"rubber"}),"polygon"===p&&this.points.length>=2&&c.lines.push({coordinates:[l.point,this.points[0]],role:"guide"})),this.points.forEach(t=>c.points.push({position:t,role:"vertex"})),g){for(let t=1;t<a.length;t++){const i=a[t-1],n=a[t],o=e(i,n);o>0&&u.push({id:`s${t}`,position:f(i,n),text:s(o),kind:"segment"})}if(d=i(a),"polygon"===p&&y){m=o(y);const s=n(y);s&&u.push({id:"area",position:s,text:t(m),kind:"measure"})}else l&&this.points.length>=2&&u.push({id:"total",position:l.point,text:s(d),kind:"measure",offset:[0,-22]})}}else if("rectangle"===p&&a.length>=1){const[e,i]=[a[0],a[1]??a[0]],n=[[e[0],e[1],e[2]],[i[0],e[1],e[2]],[i[0],i[1],e[2]],[e[0],i[1],e[2]]];if(a.length>=2&&(c.fills.push({rings:[[...n,n[0]]],role:"fill"}),c.lines.push({coordinates:[...n,n[0]],role:"edge"}),g)){const o=Math.abs(i[0]-e[0]),h=Math.abs(i[1]-e[1]);m=o*h,u.push({id:"w",position:f(n[0],n[1]),text:s(o),kind:"segment"}),u.push({id:"h",position:f(n[1],n[2]),text:s(h),kind:"segment"}),u.push({id:"area",position:f(e,i),text:t(m),kind:"measure"})}c.points.push({position:e,role:"vertex"})}else if("circle"===p&&a.length>=1){const e=a[0];if(c.points.push({position:e,role:"center"}),a.length>=2&&y){const i=y.coordinates[0];if(c.fills.push({rings:[i],role:"fill"}),c.lines.push({coordinates:i,role:"edge"}),c.lines.push({coordinates:[e,a[1]],role:"guide"}),g){const i=Math.hypot(a[1][0]-e[0],a[1][1]-e[1]);m=Math.PI*i*i,u.push({id:"r",position:f(e,a[1]),text:`r ${s(i)}`,kind:"segment"}),u.push({id:"area",position:e,text:t(m),kind:"measure",offset:[0,20]})}}}if(l&&c.points.push({position:l.point,role:snapRole(l)}),v){const t=k[0]?.point??a[a.length-1];t&&u.push({id:"problem",position:t,text:v,kind:"warning",offset:[0,22]})}this.sketch.set(c),r.labels?.set("create",u),r.requestRepaint(),this.emit("change",{shape:p,geometry:y,points:[...this.points],length:d,area:m,problem:v})}}function f(t,s){return[(t[0]+s[0])/2,(t[1]+s[1])/2,((t[2]??0)+(s[2]??0))/2]}export function snapRole(t){switch(t.kind){case"vertex":case"self":return"snap-vertex";case"edge":return"snap-edge";case"grid":case"angle":return"snap-other";default:return"active"}}
|
|
1
|
+
import{formatArea as t,formatLength as s}from"../engine/Labels.js";import{distance as e,pathLength as i,pointOnSurface as n,area as o}from"../math/Measure.js";import{selfIntersections as h}from"../math/Lines.js";import{circle as r,orientPolygon as p,rectangle as l}from"../math/Polygons.js";import{GeometryController as a}from"./GeometryController.js";import{Sketch as c,SKETCH_THEME as u}from"./Sketch.js";import{Snapper as g}from"./Snapper.js";let d=0;export class CreateController extends a{constructor(t){super(),this.options=t,this.snapper=null,this.points=[],this.hover=null,this.problem=null,this.sketch=new c({...u,...t.theme},t.theme??{}),this.cursor="crosshair"}get shape(){return this.options.shape}setShape(t){this.options={...this.options,shape:t},this.reset()}setOptions(t){this.options={...this.options,...t},this.snapper&&(this.snapper.options=!1===t.snapping?{}:t.snapping??this.snapper.options),this.render()}getPoints(){return this.points}onAttach(t){this.sketch.attach(t),!1!==this.options.snapping&&(this.snapper=new g(t,this.options.snapping??{}),this.snapper.warm()),this.render()}onDetach(t){this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,t.labels?.clear("create"),this.points=[],this.hover=null}onPointerMove(t){return this.hover=this.locate(t),this.render(),!0}onPointerLeave(){this.hover=null,this.render()}onClick(t){if(0!==t.button)return!1;const s=this.locate(t);if(!s)return!0;this.hover=s;const e=this.options.shape;if("point"===e)return this.points=[s.point],this.finish(),!0;if("rectangle"===e||"circle"===e)return this.points.push(s.point),this.points.length>=2?this.finish():this.render(),!0;if("self"===s.kind){if(("polygon"===e?this.points.length>=3:this.points.length>=2)&&("polygon"===e&&0===s.own||s.own===this.points.length-1))return this.finish(),!0}const i=this.points[this.points.length-1],n=i?this.host?.toScreen(i):null,o=this.host?.toScreen(s.point);return n&&o&&Math.hypot(n[0]-o[0],n[1]-o[1])<3||(this.points.push(s.point),this.render()),!0}onDoubleClick(t){const s=this.options.shape;if("line"!==s&&"polygon"!==s)return this.points.length>0;const e=this.points.length;if(e>=2){const t=this.host?.toScreen(this.points[e-1]),s=this.host?.toScreen(this.points[e-2]);t&&s&&Math.hypot(t[0]-s[0],t[1]-s[1])<6&&this.points.pop()}return this.finish(),!0}onKeyDown(t){return"Escape"===t.key?0!==this.points.length&&(this.cancel(),!0):"Enter"===t.key?(this.finish(),!0):!("Backspace"!==t.key&&"Delete"!==t.key&&(!t.ctrlKey&&!t.metaKey||"z"!==t.key.toLowerCase()))&&(0!==this.points.length&&(this.points.pop(),this.render(),!0))}cancel(){const t=this.points.length>0;this.reset(),t&&this.emit("cancel")}finish(){const t=this.geometryOf(this.points);if(!t)return!1;const s=this.check(t);if(s)return this.problem=s,this.render(),!1;let e=null;const i=this.options.layer;return i&&(e=this.options.feature?.(t)??{id:`drawn-${Date.now().toString(36)}-${++d}`,geometry:t,properties:{}},i.addFeatures([e]),this.options.history?.push(`Draw ${this.options.shape}`,[{layer:i,before:null,after:e}])),this.emit("finish",{geometry:t,feature:e}),this.reset(),!0}reset(){this.points=[],this.problem=null,this.render()}locate(t){const s=this.host;if(!s)return null;const e=this.options.z??s.camera.state.target[2],i=this.options.shape,n="polygon"===i?this.points.length>=3?[this.points[0],this.points[this.points.length-1]]:[]:"line"===i&&this.points.length>=2?[this.points[this.points.length-1]]:[],o=this.points[this.points.length-1]??null;if(this.snapper){const s=this.snapper.snap(t.x,t.y,t.shift,{z:e,own:n,from:o});return"self"===s?.kind&&void 0!==s.own&&(s.own=n[s.own]===this.points[0]?0:this.points.length-1),s||null}const h=s.toGround(t.x,t.y,e);return h?{point:h,kind:"none"}:null}geometryOf(t){const s=this.options.shape,e=t.length;if("point"===s)return e>=1?{type:"Point",coordinates:t[0]}:null;if("line"===s)return e>=2?{type:"LineString",coordinates:t.map(t=>[...t])}:null;if("polygon"===s)return e>=3?{type:"Polygon",coordinates:p([t.map(t=>[...t])])}:null;if("rectangle"===s)return e<2||t[0][0]===t[1][0]||t[0][1]===t[1][1]?null:l(t[0],t[1]);if(e<2)return null;const i=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]);return i>0?r(t[0],i,this.options.segments??64):null}check(t){return"Polygon"!==t.type||o(t)>0?"LineString"!==t.type||i(t.coordinates)>0?this.options.validate?this.options.validate(t):"Polygon"===t.type&&h(t.coordinates[0],!0).length>0?"Edges cross":null:"A line needs length":"An area needs room inside"}render(){const r=this.host;if(!r)return;const p=this.options.shape,l=this.hover,a=l?[...this.points,l.point]:[...this.points],c={fills:[],lines:[],points:[]},u=[],g=!1!==this.options.measure;let d,m;const y=this.geometryOf(a),k="polygon"===p&&a.length>=4?h([...a,a[0]],!0):[],v=this.problem??(k.length>0?"Edges cross":null);if("line"===p||"polygon"===p){if("polygon"===p&&a.length>=3&&c.fills.push({rings:[[...a,a[0]]],role:v?"invalid":"fill"}),this.points.length>=2&&c.lines.push({coordinates:this.points,role:v?"invalid":"edge"}),l&&this.points.length>=1&&(c.lines.push({coordinates:[this.points[this.points.length-1],l.point],role:"rubber"}),"polygon"===p&&this.points.length>=2&&c.lines.push({coordinates:[l.point,this.points[0]],role:"guide"})),this.points.forEach(t=>c.points.push({position:t,role:"vertex"})),g){for(let t=1;t<a.length;t++){const i=a[t-1],n=a[t],o=e(i,n);o>0&&u.push({id:`s${t}`,position:f(i,n),text:s(o),kind:"segment"})}if(d=i(a),"polygon"===p&&y){m=o(y);const s=n(y);s&&u.push({id:"area",position:s,text:t(m),kind:"measure"})}else l&&this.points.length>=2&&u.push({id:"total",position:l.point,text:s(d),kind:"measure",offset:[0,-22]})}}else if("rectangle"===p&&a.length>=1){const[e,i]=[a[0],a[1]??a[0]],n=[[e[0],e[1],e[2]],[i[0],e[1],e[2]],[i[0],i[1],e[2]],[e[0],i[1],e[2]]];if(a.length>=2&&(c.fills.push({rings:[[...n,n[0]]],role:"fill"}),c.lines.push({coordinates:[...n,n[0]],role:"edge"}),g)){const o=Math.abs(i[0]-e[0]),h=Math.abs(i[1]-e[1]);m=o*h,u.push({id:"w",position:f(n[0],n[1]),text:s(o),kind:"segment"}),u.push({id:"h",position:f(n[1],n[2]),text:s(h),kind:"segment"}),u.push({id:"area",position:f(e,i),text:t(m),kind:"measure"})}c.points.push({position:e,role:"vertex"})}else if("circle"===p&&a.length>=1){const e=a[0];if(c.points.push({position:e,role:"center"}),a.length>=2&&y){const i=y.coordinates[0];if(c.fills.push({rings:[i],role:"fill"}),c.lines.push({coordinates:i,role:"edge"}),c.lines.push({coordinates:[e,a[1]],role:"guide"}),g){const i=Math.hypot(a[1][0]-e[0],a[1][1]-e[1]);m=Math.PI*i*i,u.push({id:"r",position:f(e,a[1]),text:`r ${s(i)}`,kind:"segment"}),u.push({id:"area",position:e,text:t(m),kind:"measure",offset:[0,20]})}}}if(l&&c.points.push({position:l.point,role:snapRole(l)}),v){const t=k[0]?.point??a[a.length-1];t&&u.push({id:"problem",position:t,text:v,kind:"warning",offset:[0,22]})}this.sketch.set(c),r.labels?.set("create",u),r.requestRepaint(),this.emit("change",{shape:p,geometry:y,points:[...this.points],length:d,area:m,problem:v})}}function f(t,s){return[(t[0]+s[0])/2,(t[1]+s[1])/2,((t[2]??0)+(s[2]??0))/2]}export function snapRole(t){switch(t.kind){case"vertex":case"self":return"snap-vertex";case"edge":return"snap-edge";case"grid":case"angle":return"snap-other";default:return"active"}}
|