@protomaze/geometry 0.1.1 → 0.2.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 +60 -0
- 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 +6 -0
- package/edit/MeasureController.js +1 -1
- package/edit/Sketch.d.ts +19 -2
- package/edit/Sketch.js +1 -1
- package/engine/GeometryOptions.d.ts +22 -2
- package/engine/GeometryOptions.js +1 -1
- package/engine/GeometryView.d.ts +17 -0
- package/engine/GeometryView.js +1 -1
- package/engine/Labels.d.ts +9 -0
- package/engine/Labels.js +1 -1
- package/index.d.ts +1 -0
- package/index.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 -1
- package/three/CanvasGeometryEngine.js +1 -1
- package/three/Ground.d.ts +5 -0
- package/three/Ground.js +1 -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
|
@@ -108,6 +108,66 @@ meanwhile: switching the demo to its City size keeps every frame under 150 ms, w
|
|
|
108
108
|
shaders inside the frames took up to 530 ms. What was compiled once draws at once when it comes
|
|
109
109
|
back, as a 2D map toggled back to 3D does. `engine.compilingShaders` says whether any are being made.
|
|
110
110
|
|
|
111
|
+
## Theming
|
|
112
|
+
|
|
113
|
+
The view's own chrome - the clear colour, the outline round what is lit, the ground grid, labels,
|
|
114
|
+
what a controller draws - is styled by the Protomaze theme, the design tokens every @protomaze
|
|
115
|
+
package shares (`src/theme/Theme.ts`): CSS custom properties, `--pm-*`, read where the view sits.
|
|
116
|
+
Set them once round the application and the view follows, as time, charts and the rest do. What is
|
|
117
|
+
left unset keeps Protomaze's own look, dark or light. The data's colours - styles, `CATEGORY_COLORS`,
|
|
118
|
+
`RAMPS`, the heatmap's ramp - are the application's and stay as they are.
|
|
119
|
+
|
|
120
|
+
| Token | Property | In the view |
|
|
121
|
+
|---|---|---|
|
|
122
|
+
| `background` | `--pm-color-background` | the canvas's clear colour: what a 2D map shows past its ground |
|
|
123
|
+
| `highlight` | `--pm-color-highlight` | the outline round what is lit (`highlight: { look: 'outline' }`): lines, icons, bodies |
|
|
124
|
+
| `text` | `--pm-color-text` | the ground grid's lines (drawn faint); labels' text; a sketch's vertex handles |
|
|
125
|
+
| `textMuted` | `--pm-color-text-muted` | `info` labels |
|
|
126
|
+
| `surface` | `--pm-color-surface` | labels' background, a little see-through over the map |
|
|
127
|
+
| `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 |
|
|
128
|
+
| `accent` | `--pm-color-accent` | what a controller draws: the shape, the rubber band, the handle in hand |
|
|
129
|
+
| `fontFamily`, `fontSize`, `fontWeight`, `fontWeightStrong` | `--pm-font-*` | labels |
|
|
130
|
+
| `radius`, `shadow` | `--pm-radius`, `--pm-shadow` | labels' corners and shadow |
|
|
131
|
+
|
|
132
|
+
What wins: what the application passes the view - a `theme` object's colours, `highlight.outlineColor`,
|
|
133
|
+
a controller's `theme`, the styles - over the `--pm-*` tokens round the view, over Protomaze's
|
|
134
|
+
defaults for the look.
|
|
135
|
+
|
|
136
|
+
```css
|
|
137
|
+
:root {
|
|
138
|
+
--pm-color-background: #1A1A1A;
|
|
139
|
+
--pm-color-surface: #1A1A1A;
|
|
140
|
+
--pm-color-text: #EBE8E0;
|
|
141
|
+
--pm-color-accent: #9AC0A6;
|
|
142
|
+
--pm-color-highlight: #9AC0A6;
|
|
143
|
+
--pm-font-family: 'Source Sans 3', sans-serif;
|
|
144
|
+
--pm-radius: 0px;
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
import { applyTheme } from '@protomaze/geometry';
|
|
150
|
+
|
|
151
|
+
const undo = applyTheme({ accent: '#9AC0A6', highlight: '#9AC0A6', text: '#EBE8E0', radius: 0 }); // on <html>, or pass an element
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
The tokens are read at the view's own element, so they can be set on any element round it, for one
|
|
155
|
+
view and not another. The view resolves them when it starts and whenever they change - a stylesheet
|
|
156
|
+
or class switching the application's theme, `applyTheme`, `color-scheme`, the system's dark mode -
|
|
157
|
+
and rewrites its uniforms, labels and sketches then, without a reload; never per frame. `view.tokens`
|
|
158
|
+
is what it resolved. The GPU draws its colours opaque: a token's alpha is dropped there.
|
|
159
|
+
|
|
160
|
+
`theme` picks the look whose defaults fill in what the tokens leave: `'dark'` (the default), `'light'`,
|
|
161
|
+
or `'auto'`, which follows the page's `color-scheme` where it names one, else the system's
|
|
162
|
+
preference. The look also decides what the rest is shaded towards while something is lit (black on
|
|
163
|
+
dark, white on light). The scene's own colours are not tokens - the ground, the sky in perspective,
|
|
164
|
+
whether the buildings' windows are lit - and stay in the `theme` object, one set per look
|
|
165
|
+
(`DARK_THEME`, `LIGHT_THEME`), where an application overrides them:
|
|
166
|
+
|
|
167
|
+
```tsx
|
|
168
|
+
<ReactGeometry theme={{ scheme: 'auto', ground: '#202020', sky: { zenith: '#000', horizon: '#222', glow: '#333' } }} />
|
|
169
|
+
```
|
|
170
|
+
|
|
111
171
|
## Calculations
|
|
112
172
|
|
|
113
173
|
Plain functions on GeoJSON-shaped geometry, in world units - metres in a projected or local
|
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"}}
|
package/edit/EditController.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatAngle as t,formatArea as e,formatLength as s}from"../engine/Labels.js";import{closestOnSegment as i,selfIntersections as n}from"../math/Lines.js";import{area as r,distance as o,pathLength as h,pointOnSurface as a}from"../math/Measure.js";import{pointInPolygon as d}from"../math/Polygons.js";import{snapRole as l}from"./CreateController.js";import{EditHistory as p}from"./EditHistory.js";import{cloneEditShape as c,fillsOf as u,fromEditShape as f,midpoints as m,orientRings as g,outlines as y,removeVertex as x,toEditShape as k,vertices as v}from"./EditShape.js";import{GeometryController as b}from"./GeometryController.js";import{Sketch as M,SKETCH_THEME as P}from"./Sketch.js";import{Snapper as A}from"./Snapper.js";export class EditController extends b{constructor(t){super(),this.options=t,this.snapper=null,this.target=null,this.mode="vertices",this.hovered=null,this.overBody=!1,this.selectedVertex=null,this.drag=null,this.problem=null,this.offHistory=null,this.history=t.history??new p,this.sketch=new M({...P,...t.theme})}setOptions(t){this.options={...this.options,...t},this.snapper&&void 0!==t.snapping&&(this.snapper.options=!1===t.snapping?{vertices:!1,edges:!1}:t.snapping),this.render()}getTarget(){const t=this.target;return t?{layer:t.layer,feature:t.feature,geometry:f(t.shape)}:null}getMode(){return this.mode}setMode(t){t!==this.mode&&(this.mode=t,this.selectedVertex=null,this.render(),this.emit("mode",t))}edit(t,e){const s=t.getFeature(e);return!!s?.geometry&&(this.target?.layer===t&&this.target.feature.id===e||(this.stop(),this.target={layer:t,feature:s,shape:k(s.geometry)},this.render(),this.emit("select",this.getTarget())),!0)}stop(){const t=this.target;t&&(t.layer.setOverride([t.feature.id],null),this.target=null,this.drag=null,this.selectedVertex=null,this.hovered=null,this.problem=null,this.render(),this.emit("select",null))}deleteFeature(){const t=this.target;return!!t&&(this.stop(),t.layer.removeFeatures([t.feature.id]),this.history.push("Delete feature",[{layer:t.layer,before:t.feature,after:null}]),this.emit("delete",{layer:t.layer,feature:t.feature}),!0)}undo(){return null!==this.history.undo()}redo(){return null!==this.history.redo()}onAttach(t){this.sketch.attach(t),!1!==this.options.snapping&&(this.snapper=new A(t,this.options.snapping??{}),this.snapper.warm()),this.offHistory=this.history.on("apply",({step:t})=>{const e=this.target;if(!e)return;if(!t.records.find(t=>t.layer===e.layer&&(t.before?.id??t.after?.id)===e.feature.id))return;const s=e.layer.getFeature(e.feature.id);s?.geometry?(e.feature=s,e.shape=k(s.geometry),this.selectedVertex=null,this.render()):this.stop()}),this.render()}onDetach(t){this.stop(),this.offHistory?.(),this.offHistory=null,this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,t.labels?.clear("edit")}onPointerMove(t){if(!this.target)return this.cursor=null,!1;const e=this.handleAt(t.x,t.y),s=!e&&this.bodyAt(t.x,t.y);return e?.kind===this.hovered?.kind&&e?.path===this.hovered?.path&&e?.index===this.hovered?.index&&s===this.overBody||(this.hovered=e,this.overBody=s,this.render()),this.cursor=e?"rotate"===e.kind?"grab":"pointer":s?"move":null,!!e||s}onPointerDown(t){const e=this.target,s=this.host;if(!e||!s||0!==t.button)return!1;const i=this.handleAt(t.x,t.y),n=c(e.shape),r=this.centerOf(e.shape);if(i){let{path:o,index:h}=i,a="vertex",d="Move vertex";return"mid"===i.kind?(e.shape.paths[o].points.splice(h,0,[...i.point]),d="Add vertex"):"vertex"===i.kind&&t.alt&&!1!==this.options.heights&&"3d"===s.mode?(a="height",d="Change height"):"scale"===i.kind?(a="scale",d="Scale"):"rotate"===i.kind&&(a="rotate",d="Rotate"),"scale"!==i.kind&&"rotate"!==i.kind||(o=-1,h=-1),this.drag={kind:a,path:o,index:h,start:"mid"===i.kind?c(e.shape):n,before:n,startPoint:[...i.point],center:r,moved:"mid"===i.kind,snap:null,label:d},"vertex"!==i.kind&&"mid"!==i.kind||(this.selectedVertex={path:o,index:h}),this.cursor="rotate"===a?"grabbing":"move",this.render(),!0}if(this.bodyAt(t.x,t.y)){const e=s.toGround(t.x,t.y,r[2]);return!!e&&(this.drag={kind:"move",path:-1,index:-1,start:n,before:n,startPoint:e,center:r,moved:!1,snap:null,label:"Move"},this.cursor="move",!0)}return!1}onPointerDrag(e){const s=this.drag,i=this.target,n=this.host;if(!s||!i||!n)return;s.moved&&"vertex"!==s.kind&&"height"!==s.kind||i.layer.setOverride([i.feature.id],"faded"),s.moved=!0;const r=c(s.start);if("vertex"===s.kind){const t=r.paths[s.path],o=t.points[s.index],h=t.points.length>1?[t.points[(s.index+t.points.length-1)%t.points.length]]:[],a=this.snapper?.snap(e.x,e.y,e.shift,{z:o[2],from:h[0]??null,exclude:{layer:i.layer,id:i.feature.id}})??(()=>{const t=n.toGround(e.x,e.y,o[2]);return t?{point:t,kind:"none"}:null})();a&&(t.points[s.index]=[a.point[0],a.point[1],"vertex"===a.kind||"edge"===a.kind?a.point[2]:o[2]],"vertex"!==a.kind&&"edge"!==a.kind||(r.has3D=r.has3D||0!==a.point[2])),s.snap=a}else if("height"===s.kind){const t=r.paths[s.path].points[s.index],i=this.heightAt(e.x,e.y,t);null!==i&&(t[2]=i,r.has3D=!0)}else{const i=n.toGround(e.x,e.y,s.center[2]);if(!i)return;const o=s.center;let h;if("move"===s.kind){const t=i[0]-s.startPoint[0],e=i[1]-s.startPoint[1];h=s=>[s[0]+t,s[1]+e,s[2]]}else if("rotate"===s.kind){let n=Math.atan2(i[1]-o[1],i[0]-o[0])-Math.atan2(s.startPoint[1]-o[1],s.startPoint[0]-o[0]);e.shift&&(n=Math.round(n/(Math.PI/12))*(Math.PI/12));const r=Math.cos(n),a=Math.sin(n);h=t=>[o[0]+(t[0]-o[0])*r-(t[1]-o[1])*a,o[1]+(t[0]-o[0])*a+(t[1]-o[1])*r,t[2]],s.label=`Rotate ${t(180*n/Math.PI)}`}else{const t=Math.hypot(s.startPoint[0]-o[0],s.startPoint[1]-o[1]),e=t>0?Math.hypot(i[0]-o[0],i[1]-o[1])/t:1;h=t=>[o[0]+(t[0]-o[0])*e,o[1]+(t[1]-o[1])*e,t[2]],s.label=`Scale × ${e.toFixed(2)}`}r.paths.forEach(t=>{t.points=t.points.map(h)})}i.shape=r,this.problem=null,this.render(),this.emit("change",this.getTarget())}onPointerUp(){const t=this.drag;this.drag=null,t&&this.target&&(this.target.layer.setOverride([this.target.feature.id],null),t.moved?this.commit("move"===t.kind?"Move":"rotate"===t.kind?"Rotate":"scale"===t.kind?"Scale":t.label,t.before):this.render())}onClick(t){const e=this.host;return e&&0===t.button&&!1!==this.options.clickToEdit?(e.pickAt(t.x,t.y).then(t=>{t&&this.options.layers.includes(t.layer)?this.edit(t.layer,t.id):this.target&&this.stop()}),!0):!!this.target}onDoubleClick(t){const e=this.target;if(!e||"vertices"!==this.mode)return!1;const s=this.handleAt(t.x,t.y),i=c(e.shape);if("vertex"===s?.kind)return x(e.shape,s.path,s.index)&&(this.selectedVertex=null,this.commit("Delete vertex",i)),!0;const n=this.edgeAt(t.x,t.y);return!!n&&(e.shape.paths[n.path].points.splice(n.index,0,n.point),this.selectedVertex={path:n.path,index:n.index},this.commit("Add vertex",i),!0)}onKeyDown(t){const e=t.ctrlKey||t.metaKey,s=t.key.toLowerCase();if(e&&"z"===s)return t.shiftKey?this.redo():this.undo();if(e&&"y"===s)return this.redo();const i=this.target;if(!i)return!1;if("Escape"===t.key)return this.drag?(i.shape=this.drag.before,this.drag=null,i.layer.setOverride([i.feature.id],null),this.render()):this.stop(),!0;if("Delete"===t.key||"Backspace"===t.key){if(this.selectedVertex&&"vertices"===this.mode){const t=c(i.shape);return x(i.shape,this.selectedVertex.path,this.selectedVertex.index)?(this.selectedVertex=null,this.commit("Delete vertex",t)):this.refuse("A shape needs more vertices than that",i.shape.paths[this.selectedVertex.path].points[0]),!0}return this.deleteFeature()}return"t"===s&&!e&&(this.setMode("vertices"===this.mode?"transform":"vertices"),!0)}onPointerLeave(){(this.hovered||this.overBody)&&(this.hovered=null,this.overBody=!1,this.render())}commit(t,e){const s=this.target;if(!s)return;g(s.shape);const i=f(s.shape),n=this.check(i,s.feature);if(n)return s.shape=e,void this.refuse(n.message,n.at);const r=s.feature,o={...r,geometry:i};s.layer.updateFeatures([o]),s.feature=o,s.shape=k(i),this.history.push(t,[{layer:s.layer,before:r,after:o}]),this.render(),this.emit("commit",{layer:s.layer,before:r,after:o,label:t})}refuse(t,e){this.problem={message:t,at:e},this.render(),this.emit("problem",{message:t}),window.setTimeout(()=>{this.problem?.message===t&&(this.problem=null,this.render())},2200)}check(t,e){const s=function(t){let e=[0,0];switch(t.type){case"Point":e=t.coordinates;break;case"MultiPoint":case"LineString":e=t.coordinates[0];break;case"MultiLineString":case"Polygon":e=t.coordinates[0][0];break;case"MultiPolygon":e=t.coordinates[0][0][0]}return[e[0],e[1],e[2]??0]}(t);if(this.options.validate){const i=this.options.validate(t,e);return i?{message:i,at:s}:null}if("Polygon"===t.type||"MultiPolygon"===t.type){const e="Polygon"===t.type?[t.coordinates]:t.coordinates;for(const t of e)for(const e of t){const t=n(e,!0)[0];if(t)return{message:"Edges cross",at:t.point}}}return null}handles(){const t=this.target,e=this.host;if(!t||!e)return[];if("transform"===this.mode){const e=this.boxOf(t.shape),s=e.corners.map((t,e)=>({kind:"scale",path:-1,index:e,point:t}));return s.push({kind:"rotate",path:-1,index:0,point:e.rotate}),s}const s=v(t.shape).map(t=>({kind:"vertex",...t}));for(const i of m(t.shape)){const n=t.shape.paths[i.path],r=e.toScreen(n.points[i.index-1]),o=e.toScreen(n.points[i.index%n.points.length]);r&&o&&Math.hypot(r[0]-o[0],r[1]-o[1])>36&&s.push({kind:"mid",...i})}return s}handleAt(t,e){const s=this.host;if(!s)return null;let i=null,n=1/0;for(const r of this.handles()){const o=s.toScreen(r.point);if(!o)continue;const h=Math.hypot(o[0]-t,o[1]-e),a="mid"===r.kind?7:9,d=h+("mid"===r.kind?4:0);h<=a&&d<n&&(n=d,i=r)}return i}bodyAt(t,e){const s=this.target,i=this.host;if(!s||!i)return!1;if(this.edgeAt(t,e,7))return!0;const n=this.centerOf(s.shape),r=i.toGround(t,e,n[2]);if(r&&u(s.shape).some(t=>d(r,t)))return!0;for(const n of s.shape.paths){if("point"!==n.kind)continue;const s=i.toScreen(n.points[0]);if(s&&Math.hypot(s[0]-t,s[1]-e)<=11)return!0}return!1}edgeAt(t,e,s=7){const n=this.target,r=this.host;if(!n||!r)return null;let o=null,h=s;return n.shape.paths.forEach((s,n)=>{if("point"===s.kind)return;const a=s.points.length,d="ring"===s.kind?a:a-1;for(let l=0;l<d;l++){const d=s.points[l],p=s.points[(l+1)%a],c=r.toScreen(d),u=r.toScreen(p);if(!c||!u)continue;const f=i([t,e],c,u,2);if(f.distance<h){h=f.distance;const t=f.t;o={path:n,index:l+1,point:[d[0]+(p[0]-d[0])*t,d[1]+(p[1]-d[1])*t,d[2]+(p[2]-d[2])*t]}}}}),o}heightAt(t,e,s){const i=this.host;if(!i)return null;const{origin:n,direction:r}=i.rayAt(t,e),{f:o}=i.camera.basis();let h=o[0],a=o[1];const d=Math.hypot(h,a);if(d<1e-6)return null;h/=d,a/=d;const l=h*r[0]+a*r[1];if(Math.abs(l)<1e-6)return null;const p=(h*(s[0]-n[0])+a*(s[1]-n[1]))/l;return p>0?n[2]+r[2]*p:null}centerOf(t){return this.boxOf(t).center}boxOf(t){let e=1/0,s=1/0,i=-1/0,n=-1/0,r=0,o=0;t.paths.forEach(t=>t.points.forEach(t=>{e=Math.min(e,t[0]),s=Math.min(s,t[1]),i=Math.max(i,t[0]),n=Math.max(n,t[1]),r+=t[2],o++})),r=o>0?r/o:0;const h=[(e+i)/2,(s+n)/2,r],a=[[e,s,r],[i,s,r],[i,n,r],[e,n,r]],d=this.host?.pixelSizeAt(h)??1;return{center:h,corners:a,rotate:[h[0],n+32*d,r],top:[h[0],n,r]}}render(){const t=this.host;if(!t)return;const i=this.target,n=[];if(!i)return this.sketch.clear(),t.labels?.set("edit",n),void t.requestRepaint();const d=i.shape,p=this.drag,c=!!this.problem,m={fills:[],lines:[],points:[]};if(u(d).forEach(t=>m.fills.push({rings:t,role:c?"invalid":"fill"})),y(d).forEach(t=>m.lines.push({coordinates:t,role:c?"invalid":"edge"})),"transform"===this.mode){const t=this.boxOf(d);m.lines.push({coordinates:[...t.corners,t.corners[0]],role:"guide"}),m.lines.push({coordinates:[t.top,t.rotate],role:"guide"}),m.points.push({position:t.center,role:"center"})}const g=t=>this.selectedVertex&&"vertex"===t.kind&&t.path===this.selectedVertex.path&&t.index===this.selectedVertex.index||this.hovered&&t.kind===this.hovered.kind&&t.path===this.hovered.path&&t.index===this.hovered.index;for(const t of this.handles()){const e=g(t)?"active":"mid"===t.kind?"mid":"scale"===t.kind?"scale":"rotate"===t.kind?"rotate":d.type.includes("Point")?"point":"vertex";m.points.push({position:t.point,role:e})}if(p?.snap&&"none"!==p.snap.kind&&m.points.push({position:p.snap.point,role:l(p.snap)}),!1!==this.options.measure){const t=f(d),i=p&&p.path>=0?{path:p.path,index:p.index}:this.selectedVertex;if(i){const t=d.paths[i.path],e=t?.points.length??0;if(t&&"point"!==t.kind)for(const r of[i.index-1,i.index]){if(!("ring"===t.kind)&&(r<0||r+1>=e))continue;const i=t.points[(r+e)%e],h=t.points[(r+1)%e];n.push({id:`e${r}`,position:S(i,h),text:s(o(i,h)),kind:"segment"})}if("height"===p?.kind&&t){const e=t.points[i.index],s=p.start.paths[i.path].points[i.index][2],r=e[2]-s;n.push({id:"z",position:e,text:`z ${e[2].toFixed(2)} m (${r>=0?"+":""}${r.toFixed(2)})`,kind:"measure",offset:[0,-24]})}}if("Polygon"===t.type||"MultiPolygon"===t.type){const s=a(t);s&&n.push({id:"area",position:s,text:e(r(t)),kind:"measure"})}else if("LineString"===t.type||"MultiLineString"===t.type){const e="LineString"===t.type?[t.coordinates]:t.coordinates,i=e.reduce((t,e)=>t+h(e),0),r=e.reduce((t,e)=>h(e)>h(t)?e:t,e[0]);n.push({id:"length",position:V(r),text:s(i),kind:"measure",offset:[0,-18]})}if(p&&p.moved&&("move"===p.kind||"rotate"===p.kind||"scale"===p.kind)){const t=this.centerOf(d),e="move"===p.kind?`Δ ${s(Math.hypot(t[0]-p.center[0],t[1]-p.center[1]))}`:p.label.replace(/^(Rotate|Scale) /,"");n.push({id:"transform",position:t,text:e,kind:"info",offset:[0,24]})}}this.problem&&n.push({id:"problem",position:this.problem.at,text:this.problem.message,kind:"warning",offset:[0,22]}),this.sketch.set(m),t.labels?.set("edit",n),t.requestRepaint()}}function S(t,e){return[(t[0]+e[0])/2,(t[1]+e[1])/2,((t[2]??0)+(e[2]??0))/2]}function V(t){const e=h(t)/2;let s=0;for(let i=1;i<t.length;i++){const n=o(t[i-1],t[i]);if(s+n>=e&&n>0){const r=(e-s)/n,o=t[i-1],h=t[i];return[o[0]+(h[0]-o[0])*r,o[1]+(h[1]-o[1])*r,(o[2]??0)+((h[2]??0)-(o[2]??0))*r]}s+=n}const i=t[0];return[i[0],i[1],i[2]??0]}
|
|
1
|
+
import{formatAngle as t,formatArea as e,formatLength as s}from"../engine/Labels.js";import{closestOnSegment as i,selfIntersections as n}from"../math/Lines.js";import{area as r,distance as o,pathLength as h,pointOnSurface as a}from"../math/Measure.js";import{pointInPolygon as d}from"../math/Polygons.js";import{snapRole as l}from"./CreateController.js";import{EditHistory as p}from"./EditHistory.js";import{cloneEditShape as c,fillsOf as u,fromEditShape as f,midpoints as m,orientRings as g,outlines as y,removeVertex as x,toEditShape as k,vertices as v}from"./EditShape.js";import{GeometryController as b}from"./GeometryController.js";import{Sketch as M,SKETCH_THEME as P}from"./Sketch.js";import{Snapper as A}from"./Snapper.js";export class EditController extends b{constructor(t){super(),this.options=t,this.snapper=null,this.target=null,this.mode="vertices",this.hovered=null,this.overBody=!1,this.selectedVertex=null,this.drag=null,this.problem=null,this.offHistory=null,this.history=t.history??new p,this.sketch=new M({...P,...t.theme},t.theme??{})}setOptions(t){this.options={...this.options,...t},this.snapper&&void 0!==t.snapping&&(this.snapper.options=!1===t.snapping?{vertices:!1,edges:!1}:t.snapping),this.render()}getTarget(){const t=this.target;return t?{layer:t.layer,feature:t.feature,geometry:f(t.shape)}:null}getMode(){return this.mode}setMode(t){t!==this.mode&&(this.mode=t,this.selectedVertex=null,this.render(),this.emit("mode",t))}edit(t,e){const s=t.getFeature(e);return!!s?.geometry&&(this.target?.layer===t&&this.target.feature.id===e||(this.stop(),this.target={layer:t,feature:s,shape:k(s.geometry)},this.render(),this.emit("select",this.getTarget())),!0)}stop(){const t=this.target;t&&(t.layer.setOverride([t.feature.id],null),this.target=null,this.drag=null,this.selectedVertex=null,this.hovered=null,this.problem=null,this.render(),this.emit("select",null))}deleteFeature(){const t=this.target;return!!t&&(this.stop(),t.layer.removeFeatures([t.feature.id]),this.history.push("Delete feature",[{layer:t.layer,before:t.feature,after:null}]),this.emit("delete",{layer:t.layer,feature:t.feature}),!0)}undo(){return null!==this.history.undo()}redo(){return null!==this.history.redo()}onAttach(t){this.sketch.attach(t),!1!==this.options.snapping&&(this.snapper=new A(t,this.options.snapping??{}),this.snapper.warm()),this.offHistory=this.history.on("apply",({step:t})=>{const e=this.target;if(!e)return;if(!t.records.find(t=>t.layer===e.layer&&(t.before?.id??t.after?.id)===e.feature.id))return;const s=e.layer.getFeature(e.feature.id);s?.geometry?(e.feature=s,e.shape=k(s.geometry),this.selectedVertex=null,this.render()):this.stop()}),this.render()}onDetach(t){this.stop(),this.offHistory?.(),this.offHistory=null,this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,t.labels?.clear("edit")}onPointerMove(t){if(!this.target)return this.cursor=null,!1;const e=this.handleAt(t.x,t.y),s=!e&&this.bodyAt(t.x,t.y);return e?.kind===this.hovered?.kind&&e?.path===this.hovered?.path&&e?.index===this.hovered?.index&&s===this.overBody||(this.hovered=e,this.overBody=s,this.render()),this.cursor=e?"rotate"===e.kind?"grab":"pointer":s?"move":null,!!e||s}onPointerDown(t){const e=this.target,s=this.host;if(!e||!s||0!==t.button)return!1;const i=this.handleAt(t.x,t.y),n=c(e.shape),r=this.centerOf(e.shape);if(i){let{path:o,index:h}=i,a="vertex",d="Move vertex";return"mid"===i.kind?(e.shape.paths[o].points.splice(h,0,[...i.point]),d="Add vertex"):"vertex"===i.kind&&t.alt&&!1!==this.options.heights&&"3d"===s.mode?(a="height",d="Change height"):"scale"===i.kind?(a="scale",d="Scale"):"rotate"===i.kind&&(a="rotate",d="Rotate"),"scale"!==i.kind&&"rotate"!==i.kind||(o=-1,h=-1),this.drag={kind:a,path:o,index:h,start:"mid"===i.kind?c(e.shape):n,before:n,startPoint:[...i.point],center:r,moved:"mid"===i.kind,snap:null,label:d},"vertex"!==i.kind&&"mid"!==i.kind||(this.selectedVertex={path:o,index:h}),this.cursor="rotate"===a?"grabbing":"move",this.render(),!0}if(this.bodyAt(t.x,t.y)){const e=s.toGround(t.x,t.y,r[2]);return!!e&&(this.drag={kind:"move",path:-1,index:-1,start:n,before:n,startPoint:e,center:r,moved:!1,snap:null,label:"Move"},this.cursor="move",!0)}return!1}onPointerDrag(e){const s=this.drag,i=this.target,n=this.host;if(!s||!i||!n)return;s.moved&&"vertex"!==s.kind&&"height"!==s.kind||i.layer.setOverride([i.feature.id],"faded"),s.moved=!0;const r=c(s.start);if("vertex"===s.kind){const t=r.paths[s.path],o=t.points[s.index],h=t.points.length>1?[t.points[(s.index+t.points.length-1)%t.points.length]]:[],a=this.snapper?.snap(e.x,e.y,e.shift,{z:o[2],from:h[0]??null,exclude:{layer:i.layer,id:i.feature.id}})??(()=>{const t=n.toGround(e.x,e.y,o[2]);return t?{point:t,kind:"none"}:null})();a&&(t.points[s.index]=[a.point[0],a.point[1],"vertex"===a.kind||"edge"===a.kind?a.point[2]:o[2]],"vertex"!==a.kind&&"edge"!==a.kind||(r.has3D=r.has3D||0!==a.point[2])),s.snap=a}else if("height"===s.kind){const t=r.paths[s.path].points[s.index],i=this.heightAt(e.x,e.y,t);null!==i&&(t[2]=i,r.has3D=!0)}else{const i=n.toGround(e.x,e.y,s.center[2]);if(!i)return;const o=s.center;let h;if("move"===s.kind){const t=i[0]-s.startPoint[0],e=i[1]-s.startPoint[1];h=s=>[s[0]+t,s[1]+e,s[2]]}else if("rotate"===s.kind){let n=Math.atan2(i[1]-o[1],i[0]-o[0])-Math.atan2(s.startPoint[1]-o[1],s.startPoint[0]-o[0]);e.shift&&(n=Math.round(n/(Math.PI/12))*(Math.PI/12));const r=Math.cos(n),a=Math.sin(n);h=t=>[o[0]+(t[0]-o[0])*r-(t[1]-o[1])*a,o[1]+(t[0]-o[0])*a+(t[1]-o[1])*r,t[2]],s.label=`Rotate ${t(180*n/Math.PI)}`}else{const t=Math.hypot(s.startPoint[0]-o[0],s.startPoint[1]-o[1]),e=t>0?Math.hypot(i[0]-o[0],i[1]-o[1])/t:1;h=t=>[o[0]+(t[0]-o[0])*e,o[1]+(t[1]-o[1])*e,t[2]],s.label=`Scale × ${e.toFixed(2)}`}r.paths.forEach(t=>{t.points=t.points.map(h)})}i.shape=r,this.problem=null,this.render(),this.emit("change",this.getTarget())}onPointerUp(){const t=this.drag;this.drag=null,t&&this.target&&(this.target.layer.setOverride([this.target.feature.id],null),t.moved?this.commit("move"===t.kind?"Move":"rotate"===t.kind?"Rotate":"scale"===t.kind?"Scale":t.label,t.before):this.render())}onClick(t){const e=this.host;return e&&0===t.button&&!1!==this.options.clickToEdit?(e.pickAt(t.x,t.y).then(t=>{t&&this.options.layers.includes(t.layer)?this.edit(t.layer,t.id):this.target&&this.stop()}),!0):!!this.target}onDoubleClick(t){const e=this.target;if(!e||"vertices"!==this.mode)return!1;const s=this.handleAt(t.x,t.y),i=c(e.shape);if("vertex"===s?.kind)return x(e.shape,s.path,s.index)&&(this.selectedVertex=null,this.commit("Delete vertex",i)),!0;const n=this.edgeAt(t.x,t.y);return!!n&&(e.shape.paths[n.path].points.splice(n.index,0,n.point),this.selectedVertex={path:n.path,index:n.index},this.commit("Add vertex",i),!0)}onKeyDown(t){const e=t.ctrlKey||t.metaKey,s=t.key.toLowerCase();if(e&&"z"===s)return t.shiftKey?this.redo():this.undo();if(e&&"y"===s)return this.redo();const i=this.target;if(!i)return!1;if("Escape"===t.key)return this.drag?(i.shape=this.drag.before,this.drag=null,i.layer.setOverride([i.feature.id],null),this.render()):this.stop(),!0;if("Delete"===t.key||"Backspace"===t.key){if(this.selectedVertex&&"vertices"===this.mode){const t=c(i.shape);return x(i.shape,this.selectedVertex.path,this.selectedVertex.index)?(this.selectedVertex=null,this.commit("Delete vertex",t)):this.refuse("A shape needs more vertices than that",i.shape.paths[this.selectedVertex.path].points[0]),!0}return this.deleteFeature()}return"t"===s&&!e&&(this.setMode("vertices"===this.mode?"transform":"vertices"),!0)}onPointerLeave(){(this.hovered||this.overBody)&&(this.hovered=null,this.overBody=!1,this.render())}commit(t,e){const s=this.target;if(!s)return;g(s.shape);const i=f(s.shape),n=this.check(i,s.feature);if(n)return s.shape=e,void this.refuse(n.message,n.at);const r=s.feature,o={...r,geometry:i};s.layer.updateFeatures([o]),s.feature=o,s.shape=k(i),this.history.push(t,[{layer:s.layer,before:r,after:o}]),this.render(),this.emit("commit",{layer:s.layer,before:r,after:o,label:t})}refuse(t,e){this.problem={message:t,at:e},this.render(),this.emit("problem",{message:t}),window.setTimeout(()=>{this.problem?.message===t&&(this.problem=null,this.render())},2200)}check(t,e){const s=function(t){let e=[0,0];switch(t.type){case"Point":e=t.coordinates;break;case"MultiPoint":case"LineString":e=t.coordinates[0];break;case"MultiLineString":case"Polygon":e=t.coordinates[0][0];break;case"MultiPolygon":e=t.coordinates[0][0][0]}return[e[0],e[1],e[2]??0]}(t);if(this.options.validate){const i=this.options.validate(t,e);return i?{message:i,at:s}:null}if("Polygon"===t.type||"MultiPolygon"===t.type){const e="Polygon"===t.type?[t.coordinates]:t.coordinates;for(const t of e)for(const e of t){const t=n(e,!0)[0];if(t)return{message:"Edges cross",at:t.point}}}return null}handles(){const t=this.target,e=this.host;if(!t||!e)return[];if("transform"===this.mode){const e=this.boxOf(t.shape),s=e.corners.map((t,e)=>({kind:"scale",path:-1,index:e,point:t}));return s.push({kind:"rotate",path:-1,index:0,point:e.rotate}),s}const s=v(t.shape).map(t=>({kind:"vertex",...t}));for(const i of m(t.shape)){const n=t.shape.paths[i.path],r=e.toScreen(n.points[i.index-1]),o=e.toScreen(n.points[i.index%n.points.length]);r&&o&&Math.hypot(r[0]-o[0],r[1]-o[1])>36&&s.push({kind:"mid",...i})}return s}handleAt(t,e){const s=this.host;if(!s)return null;let i=null,n=1/0;for(const r of this.handles()){const o=s.toScreen(r.point);if(!o)continue;const h=Math.hypot(o[0]-t,o[1]-e),a="mid"===r.kind?7:9,d=h+("mid"===r.kind?4:0);h<=a&&d<n&&(n=d,i=r)}return i}bodyAt(t,e){const s=this.target,i=this.host;if(!s||!i)return!1;if(this.edgeAt(t,e,7))return!0;const n=this.centerOf(s.shape),r=i.toGround(t,e,n[2]);if(r&&u(s.shape).some(t=>d(r,t)))return!0;for(const n of s.shape.paths){if("point"!==n.kind)continue;const s=i.toScreen(n.points[0]);if(s&&Math.hypot(s[0]-t,s[1]-e)<=11)return!0}return!1}edgeAt(t,e,s=7){const n=this.target,r=this.host;if(!n||!r)return null;let o=null,h=s;return n.shape.paths.forEach((s,n)=>{if("point"===s.kind)return;const a=s.points.length,d="ring"===s.kind?a:a-1;for(let l=0;l<d;l++){const d=s.points[l],p=s.points[(l+1)%a],c=r.toScreen(d),u=r.toScreen(p);if(!c||!u)continue;const f=i([t,e],c,u,2);if(f.distance<h){h=f.distance;const t=f.t;o={path:n,index:l+1,point:[d[0]+(p[0]-d[0])*t,d[1]+(p[1]-d[1])*t,d[2]+(p[2]-d[2])*t]}}}}),o}heightAt(t,e,s){const i=this.host;if(!i)return null;const{origin:n,direction:r}=i.rayAt(t,e),{f:o}=i.camera.basis();let h=o[0],a=o[1];const d=Math.hypot(h,a);if(d<1e-6)return null;h/=d,a/=d;const l=h*r[0]+a*r[1];if(Math.abs(l)<1e-6)return null;const p=(h*(s[0]-n[0])+a*(s[1]-n[1]))/l;return p>0?n[2]+r[2]*p:null}centerOf(t){return this.boxOf(t).center}boxOf(t){let e=1/0,s=1/0,i=-1/0,n=-1/0,r=0,o=0;t.paths.forEach(t=>t.points.forEach(t=>{e=Math.min(e,t[0]),s=Math.min(s,t[1]),i=Math.max(i,t[0]),n=Math.max(n,t[1]),r+=t[2],o++})),r=o>0?r/o:0;const h=[(e+i)/2,(s+n)/2,r],a=[[e,s,r],[i,s,r],[i,n,r],[e,n,r]],d=this.host?.pixelSizeAt(h)??1;return{center:h,corners:a,rotate:[h[0],n+32*d,r],top:[h[0],n,r]}}render(){const t=this.host;if(!t)return;const i=this.target,n=[];if(!i)return this.sketch.clear(),t.labels?.set("edit",n),void t.requestRepaint();const d=i.shape,p=this.drag,c=!!this.problem,m={fills:[],lines:[],points:[]};if(u(d).forEach(t=>m.fills.push({rings:t,role:c?"invalid":"fill"})),y(d).forEach(t=>m.lines.push({coordinates:t,role:c?"invalid":"edge"})),"transform"===this.mode){const t=this.boxOf(d);m.lines.push({coordinates:[...t.corners,t.corners[0]],role:"guide"}),m.lines.push({coordinates:[t.top,t.rotate],role:"guide"}),m.points.push({position:t.center,role:"center"})}const g=t=>this.selectedVertex&&"vertex"===t.kind&&t.path===this.selectedVertex.path&&t.index===this.selectedVertex.index||this.hovered&&t.kind===this.hovered.kind&&t.path===this.hovered.path&&t.index===this.hovered.index;for(const t of this.handles()){const e=g(t)?"active":"mid"===t.kind?"mid":"scale"===t.kind?"scale":"rotate"===t.kind?"rotate":d.type.includes("Point")?"point":"vertex";m.points.push({position:t.point,role:e})}if(p?.snap&&"none"!==p.snap.kind&&m.points.push({position:p.snap.point,role:l(p.snap)}),!1!==this.options.measure){const t=f(d),i=p&&p.path>=0?{path:p.path,index:p.index}:this.selectedVertex;if(i){const t=d.paths[i.path],e=t?.points.length??0;if(t&&"point"!==t.kind)for(const r of[i.index-1,i.index]){if(!("ring"===t.kind)&&(r<0||r+1>=e))continue;const i=t.points[(r+e)%e],h=t.points[(r+1)%e];n.push({id:`e${r}`,position:S(i,h),text:s(o(i,h)),kind:"segment"})}if("height"===p?.kind&&t){const e=t.points[i.index],s=p.start.paths[i.path].points[i.index][2],r=e[2]-s;n.push({id:"z",position:e,text:`z ${e[2].toFixed(2)} m (${r>=0?"+":""}${r.toFixed(2)})`,kind:"measure",offset:[0,-24]})}}if("Polygon"===t.type||"MultiPolygon"===t.type){const s=a(t);s&&n.push({id:"area",position:s,text:e(r(t)),kind:"measure"})}else if("LineString"===t.type||"MultiLineString"===t.type){const e="LineString"===t.type?[t.coordinates]:t.coordinates,i=e.reduce((t,e)=>t+h(e),0),r=e.reduce((t,e)=>h(e)>h(t)?e:t,e[0]);n.push({id:"length",position:V(r),text:s(i),kind:"measure",offset:[0,-18]})}if(p&&p.moved&&("move"===p.kind||"rotate"===p.kind||"scale"===p.kind)){const t=this.centerOf(d),e="move"===p.kind?`Δ ${s(Math.hypot(t[0]-p.center[0],t[1]-p.center[1]))}`:p.label.replace(/^(Rotate|Scale) /,"");n.push({id:"transform",position:t,text:e,kind:"info",offset:[0,24]})}}this.problem&&n.push({id:"problem",position:this.problem.at,text:this.problem.message,kind:"warning",offset:[0,22]}),this.sketch.set(m),t.labels?.set("edit",n),t.requestRepaint()}}function S(t,e){return[(t[0]+e[0])/2,(t[1]+e[1])/2,((t[2]??0)+(e[2]??0))/2]}function V(t){const e=h(t)/2;let s=0;for(let i=1;i<t.length;i++){const n=o(t[i-1],t[i]);if(s+n>=e&&n>0){const r=(e-s)/n,o=t[i-1],h=t[i];return[o[0]+(h[0]-o[0])*r,o[1]+(h[1]-o[1])*r,(o[2]??0)+((h[2]??0)-(o[2]??0))*r]}s+=n}const i=t[0];return[i[0],i[1],i[2]??0]}
|
|
@@ -5,6 +5,7 @@ import type { MapCamera } from '../engine/MapCamera';
|
|
|
5
5
|
import { TypedEventEmitter } from '../event/TypedEventEmitter';
|
|
6
6
|
import type { GeometryLayer } from '../layers/GeometryLayer';
|
|
7
7
|
import type { Vec3 } from '../math/Vector';
|
|
8
|
+
import type { ThemeTokens } from '../theme/Theme';
|
|
8
9
|
/** A pointer event as a controller gets it: where in the view, which button, which keys held. */
|
|
9
10
|
export interface ControllerPointer {
|
|
10
11
|
/** View pixels from the view's top-left. */
|
|
@@ -47,6 +48,11 @@ export interface ControllerHost {
|
|
|
47
48
|
pixelSizeAt(p: Position): number;
|
|
48
49
|
pickAt(x: number, y: number): Promise<GeometryHit | null>;
|
|
49
50
|
requestRepaint(): void;
|
|
51
|
+
/**
|
|
52
|
+
* The theme's tokens in force at the view, what a sketch is drawn in; a new object when they
|
|
53
|
+
* change, with the overlays restyled. A host without them leaves the sketch's own colours.
|
|
54
|
+
*/
|
|
55
|
+
readonly tokens?: ThemeTokens;
|
|
50
56
|
}
|
|
51
57
|
/**
|
|
52
58
|
* Something that takes over the pointer and keys of a view for a while - drawing new geometry,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatArea as
|
|
1
|
+
import{formatArea as e,formatLength as t,formatSlope as i}from"../engine/Labels.js";import{area as s,distance as n,distance2D as o,pathLength as h,perimeter as r,pointOnSurface as a,slope as p}from"../math/Measure.js";import{geometryDistance as c}from"../math/Relations.js";import{snapRole as l}from"./CreateController.js";import{GeometryController as d}from"./GeometryController.js";import{Sketch as u,SKETCH_THEME as f}from"./Sketch.js";import{Snapper as m}from"./Snapper.js";export class MeasureController extends d{constructor(e){super(),this.options=e,this.snapper=null,this.points=[],this.hover=null,this.done=!1,this.picked=[],this.clearance=null,this.queue=Promise.resolve(),this.pointer=null,this.hoverPicking=!1,this.sketch=new u({...f,...e.theme},e.theme??{}),this.cursor="crosshair"}get mode(){return this.options.mode}setMode(e){this.options={...this.options,mode:e},this.clear()}clear(){this.points=[],this.picked=[],this.clearance=null,this.done=!1,this.render()}onAttach(e){this.sketch.attach(e),!1!==this.options.snapping&&(this.snapper=new m(e,this.options.snapping??{}),this.snapper.warm()),this.render()}onDetach(e){this.sketch.detach(),this.snapper?.dispose(),this.snapper=null,e.labels?.clear("measure"),this.points=[],this.picked=[],this.clearance=null}onPointerMove(e){return"clearance"!==this.options.mode&&(this.hover=this.done?null:this.locate(e),this.render(),this.pickHover(e),!0)}pickHover(e){this.pointer={x:e.x,y:e.y};const t=this.host;if(!t||this.done||!1===this.options.surface||this.hoverPicking)return;this.hoverPicking=!0;const{x:i,y:s}=this.pointer;t.pickAt(i,s).then(t=>{this.hoverPicking=!1;const n=this.pointer;if(!n||this.done||!this.host)return;if(n.x!==i||n.y!==s)return void this.pickHover({...e,x:n.x,y:n.y});const o=this.hover,h=o&&("vertex"===o.kind||"edge"===o.kind||"self"===o.kind);!t||h&&!this.behind(o.point,t.point)||(this.hover={point:t.point,kind:"none"},this.render())},()=>{this.hoverPicking=!1})}onPointerLeave(){this.hover=null,this.render()}onClick(e){if(0!==e.button)return!1;const t=this.host;if(!t)return!0;this.done&&(this.points=[],this.picked=[],this.clearance=null,this.done=!1);const i=this.locate(e),s="clearance"===this.options.mode||!1!==this.options.surface;return this.queue=this.queue.then(async()=>{const n=s?await t.pickAt(e.x,e.y):null;this.place(i,n)}),!0}onDoubleClick(){return"clearance"===this.options.mode||(this.queue=this.queue.then(()=>{const e=this.points.length;e>=2&&n(this.points[e-1],this.points[e-2])<1e-6&&this.points.pop(),this.finish()})),!0}onKeyDown(e){return"Escape"===e.key?(0!==this.points.length||0!==this.picked.length)&&(this.clear(),!0):"Enter"===e.key?(this.finish(),!0):("Backspace"===e.key||"Delete"===e.key)&&(0!==this.points.length&&!this.done&&(this.points.pop(),this.render(),!0))}place(e,t){const i=this.options.mode;if("clearance"===i){if(!t)return;if(this.picked.length>=2&&(this.picked=[],this.clearance=null,this.done=!1),1===this.picked.length&&this.picked[0].layer===t.layer&&this.picked[0].feature.id===t.id)return;return this.picked.push({layer:t.layer,feature:t.feature,point:t.point}),2===this.picked.length&&this.measureClearance(),void this.render()}let s=e?.point??null;const n=e&&("vertex"===e.kind||"edge"===e.kind||"self"===e.kind);!t||n&&!this.behind(e.point,t.point)||(s=t.point),s&&(this.points.push([...s]),"height"===i&&this.points.length>=2&&(this.done=!0),this.render())}behind(e,t){const i=this.host;if(!i||i.camera.orthographic)return!1;const{f:s,eye:n}=i.camera.basis(),o=e=>(e[0]-n[0])*s[0]+(e[1]-n[1])*s[1]+(e[2]-n[2])*s[2],h=o(t);return o(e)>h+Math.max(.3,.01*h)}finish(){const e="area"===this.options.mode?3:2;this.points.length>=e&&(this.done=!0),this.hover=null,this.render()}measureClearance(){const[e,t]=this.picked;if(!e.feature.geometry||!t.feature.geometry)return;const i=c(e.feature.geometry,t.feature.geometry,3);if(!Number.isFinite(i.distance))return;const s=this.options.radius?.(e.layer,e.feature)??0,n=this.options.radius?.(t.layer,t.feature)??0;this.clearance={a:i.pointA,b:i.pointB,gap:Math.max(0,i.distance-s-n)},this.done=!0}locate(e){const t=this.host;if(!t)return null;const i=this.options.z??t.camera.state.target[2],s=this.points[this.points.length-1]??null;if(this.snapper)return this.snapper.snap(e.x,e.y,e.shift,{z:i,from:s});const n=t.toGround(e.x,e.y,i);return n?{point:n,kind:"none"}:null}measurement(){const e=this.options.mode;if("clearance"===e){if(0===this.picked.length)return null;const[t,i]=this.picked;return{mode:e,points:this.clearance?[this.clearance.a,this.clearance.b]:[],clearance:this.clearance?.gap,a:t,b:i,done:this.done}}const t=!this.done&&this.hover?[...this.points,this.hover.point]:[...this.points];if(0===t.length)return null;const i=t[0],n=t[t.length-1],o={mode:e,points:t,done:this.done};if(o.length=h(t),o.horizontal=h(t,2),o.rise=n[2]-i[2],o.slope=p(i,n),"area"===e&&t.length>=3){const e={type:"Polygon",coordinates:[[...t,t[0]]]};o.area=s(e),o.perimeter=r(e)}return o}render(){const s=this.host;if(!s)return;const h=this.options.mode,r=this.measurement(),c={fills:[],lines:[],points:[]},d=[];if("clearance"===h)if(this.picked.forEach(e=>c.points.push({position:e.point,role:"vertex"})),this.clearance){const{a:e,b:i,gap:s}=this.clearance;c.lines.push({coordinates:[e,i],role:"measure"}),c.points.push({position:e,role:"active"},{position:i,role:"active"}),d.push({id:"gap",position:g(e,i),text:`${t(s)} clear`,kind:"measure",anchor:"left",offset:[14,-10]});const n=Math.abs(e[2]-i[2]);n>.005&&d.push({id:"dz",position:g(e,i),text:`${t(n)} apart in height`,kind:"info",anchor:"left",offset:[14,12]})}else 1===this.picked.length&&d.push({id:"hint",position:this.picked[0].point,text:"Now click the second",kind:"info",offset:[0,-22]});else if(r){const s=r.points;"area"===h&&s.length>=3&&c.fills.push({rings:[[...s,s[0]]],role:"fill"});const u=this.points;if(u.length>=2&&c.lines.push({coordinates:"area"===h&&this.done?[...u,u[0]]:u,role:"measure"}),!this.done&&this.hover&&u.length>=1&&(c.lines.push({coordinates:[u[u.length-1],this.hover.point],role:"rubber"}),"area"===h&&u.length>=2&&c.lines.push({coordinates:[this.hover.point,u[0]],role:"guide"})),u.forEach(e=>c.points.push({position:e,role:"vertex"})),!this.done&&this.hover&&c.points.push({position:this.hover.point,role:l(this.hover)}),"height"===h&&s.length>=2){const[e,h]=[s[0],s[1]],[r,a]=e[2]<=h[2]?[e,h]:[h,e],l=[r[0],r[1],a[2]];c.lines.push({coordinates:[r,l],role:"guide"},{coordinates:[l,a],role:"guide"}),d.push({id:"rise",position:g(r,l),text:`↕ ${t(Math.abs(h[2]-e[2]))}`,kind:"measure",offset:[34,0]}),d.push({id:"across",position:g(l,a),text:`↔ ${t(o(e,h))}`,kind:"segment"}),d.push({id:"slope",position:g(e,h),text:`${t(n(e,h))} · ${i(p(e,h))}`,kind:"info",offset:[0,20]})}else if("distance"===h||"area"===h){const i="area"===h&&s.length>=3?[[s[s.length-1],s[0]]]:[];if([...s.slice(1).map((e,t)=>[s[t],e]),...i].forEach(([e,i],s)=>{const o=n(e,i);o>0&&d.push({id:`s${s}`,position:g(e,i),text:t(o),kind:"segment"})}),"area"===h&&void 0!==r.area&&s.length>=3){const i=a({type:"Polygon",coordinates:[[...s,s[0]]]});i&&d.push({id:"area",position:i,text:`${e(r.area)} · ${t(r.perimeter??0)} round`,kind:"measure"})}else if("distance"===h&&s.length>=2){const e=r.rise??0,i=Math.abs(e)>.005?`${t(r.length??0)} · ${t(r.horizontal??0)} across · ${e>=0?"+":""}${t(e)}`:t(r.length??0);d.push({id:"total",position:s[s.length-1],text:i,kind:"measure",offset:[0,-24]})}}}this.sketch.set(c),s.labels?.set("measure",d),s.requestRepaint(),this.emit("change",r)}}function g(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2,((e[2]??0)+(t[2]??0))/2]}
|
package/edit/Sketch.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { ColorLike } from '../common/Colors';
|
|
2
2
|
import type { Position } from '../data/Geometry';
|
|
3
3
|
import { AreaLayer } from '../layers/AreaLayer';
|
|
4
4
|
import { LineLayer } from '../layers/LineLayer';
|
|
5
5
|
import { PointLayer } from '../layers/PointLayer';
|
|
6
|
+
import { ThemeTokens } from '../theme/Theme';
|
|
6
7
|
import type { ControllerHost } from './GeometryController';
|
|
7
8
|
/** The colours a sketch is drawn in. */
|
|
8
9
|
export interface SketchTheme {
|
|
@@ -22,6 +23,12 @@ export interface SketchTheme {
|
|
|
22
23
|
/** Construction lines: the rubber band's guides, a transform's box. */
|
|
23
24
|
guide: ColorLike;
|
|
24
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* A sketch's colours from the theme's tokens: what is drawn in the accent, handles in the text's
|
|
28
|
+
* colour, what was snapped to in the highlight's, a shape that cannot be in danger's.
|
|
29
|
+
*/
|
|
30
|
+
export declare function sketchTheme(tokens: ThemeTokens): SketchTheme;
|
|
31
|
+
/** A sketch's colours where its view has no theme: Protomaze's, dark. */
|
|
25
32
|
export declare const SKETCH_THEME: SketchTheme;
|
|
26
33
|
export type SketchLineRole = 'edge' | 'rubber' | 'guide' | 'invalid' | 'measure';
|
|
27
34
|
export type SketchPointRole = 'vertex' | 'mid' | 'active' | 'snap-vertex' | 'snap-edge' | 'snap-other' | 'center' | 'rotate' | 'scale' | 'point';
|
|
@@ -57,7 +64,17 @@ export declare class Sketch {
|
|
|
57
64
|
readonly points: PointLayer;
|
|
58
65
|
private host;
|
|
59
66
|
private last;
|
|
60
|
-
|
|
67
|
+
/** The colours the application chose: over the view's theme, which gives the rest. */
|
|
68
|
+
private readonly own;
|
|
69
|
+
private themed;
|
|
70
|
+
/**
|
|
71
|
+
* `theme` is what the sketch is drawn in where its host has no theme tokens; in a view that
|
|
72
|
+
* has them, the tokens' colours (`sketchTheme`) with `own` over them - by default whatever of
|
|
73
|
+
* `theme` is not `SKETCH_THEME` itself.
|
|
74
|
+
*/
|
|
75
|
+
constructor(theme?: SketchTheme, own?: Partial<SketchTheme>);
|
|
76
|
+
/** The colours drawn in now: the host's theme, the application's own over it; `theme` without one. */
|
|
77
|
+
private colors;
|
|
61
78
|
attach(host: ControllerHost): void;
|
|
62
79
|
private warming;
|
|
63
80
|
/**
|
package/edit/Sketch.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{parseColor as e}from"../common/Colors.js";import{AreaLayer as t}from"../layers/AreaLayer.js";import{LineLayer as s}from"../layers/LineLayer.js";import{PointLayer as i}from"../layers/PointLayer.js";import{PROTOMAZE_DARK as r}from"../theme/Theme.js";export function sketchTheme(t){const s=(t,s)=>{const[i,r,o]=e(t);return[i,r,o,s]};return{stroke:t.accent,fill:s(t.accent,.18),vertex:t.text,border:t.background,active:t.accent,snap:t.highlight,invalid:t.danger,guide:s(t.text,.67)}}export const SKETCH_THEME=sketchTheme(r);const o={vertex:{shape:"circle",size:11,color:"vertex"},point:{shape:"circle",size:13,color:"stroke"},mid:{shape:"circle",size:8,color:"vertex",opacity:.55},active:{shape:"circle",size:15,color:"active"},"snap-vertex":{shape:"ring",size:22,color:"snap"},"snap-edge":{shape:"diamond",size:15,color:"snap"},"snap-other":{shape:"cross",size:14,color:"snap"},center:{shape:"cross",size:14,color:"guide"},rotate:{shape:"circle",size:13,color:"active"},scale:{shape:"square",size:11,color:"vertex"}};export class Sketch{constructor(e=SKETCH_THEME,r){this.theme=e,this.host=null,this.last={fills:"",lines:"",points:""},this.themed=null,this.warming=!1,this.own=r??(e===SKETCH_THEME?{}:e),this.fills=new t({id:"sketch-fills",outlines:!1,pickable:!1,style:e=>{const t=this.colors();return{color:"invalid"===e.properties.role?l(t.invalid,.2):t.fill}}}),this.lines=new s({id:"sketch-lines",mode:"space",pickable:!1,style:e=>{const t=this.colors();switch(e.properties.role){case"rubber":return{color:t.stroke,width:2,dashed:!0,arrow:!1};case"guide":return{color:t.guide,width:1.25,dashed:!0,arrow:!1};case"invalid":return{color:t.invalid,width:2.5,arrow:!1};case"measure":return{color:t.stroke,width:2.25,arrow:!1};default:return{color:t.stroke,width:2.5,arrow:!1}}}}),this.points=new i({id:"sketch-points",pickable:!1,depthTest:!1,border:1.5,style:e=>{const t=o[e.properties.role]??o.vertex;return{shape:t.shape,size:t.size,color:this.colors()[t.color],opacity:t.opacity}}})}colors(){const e=this.host?.tokens;return e?(this.themed?.tokens!==e&&(this.themed={tokens:e,theme:{...sketchTheme(e),...this.own}}),this.themed.theme):this.theme}attach(e){this.host!==e&&(this.detach(),this.host=e,e.addOverlay(this.fills),e.addOverlay(this.lines),e.addOverlay(this.points),this.warm(e))}warm(e){if(this.points.primitive)return;const t=e.camera.state.target,s=[t[0],t[1],t[2]],i=[t[0]+.01,t[1],t[2]],r=[t[0],t[1]+.01,t[2]];this.set({fills:[{rings:[[s,i,r,s]],role:"fill"}],lines:[{coordinates:[s,i],role:"edge"}],points:[{position:s,role:"vertex"}]}),this.warming=!0,[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(0));const o=this.points.on("build",()=>{o(),[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(1)),this.warming&&this.clear(),this.warming=!1})}detach(){const e=this.host;e&&(e.removeOverlay(this.fills),e.removeOverlay(this.lines),e.removeOverlay(this.points),this.host=null)}set(e){this.warming=!1,[this.fills,this.lines,this.points].forEach(e=>e.setOpacity(1));const t=(e.fills??[]).filter(e=>e.rings.length>0&&e.rings[0].length>=3).map((e,t)=>({id:`fill-${t}`,geometry:{type:"Polygon",coordinates:e.rings},properties:{role:e.role}})),s=(e.lines??[]).filter(e=>e.coordinates.length>=2).map((e,t)=>({id:`line-${t}`,geometry:{type:"LineString",coordinates:e.coordinates},properties:{role:e.role}})),i=(e.points??[]).map((e,t)=>({id:`point-${t}`,geometry:{type:"Point",coordinates:e.position},properties:{role:e.role}}));this.update(this.fills,t,"fills"),this.update(this.lines,s,"lines"),this.update(this.points,i,"points")}clear(){this.set({})}update(e,t,s){const i=JSON.stringify(t.map(e=>[e.geometry,e.properties.role]));i!==this.last[s]&&(this.last[s]=i,e.setFeatures(t))}}function l(t,s){const[i,r,o,l]=e(t);return[i,r,o,l*s]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ColorRamp } from '../common/Colors';
|
|
2
2
|
import type { CameraLimits, CameraState } from './MapCamera';
|
|
3
|
+
import { ThemeScheme } from '../theme/Theme';
|
|
3
4
|
/** How what is lit - selected, pointed at, emphasized - is set off. */
|
|
4
5
|
export interface GeometryHighlightOptions {
|
|
5
6
|
/** A glow round it, or an outline. A glow by default. */
|
|
@@ -16,12 +17,20 @@ export interface GeometryHighlightOptions {
|
|
|
16
17
|
/** Whether pointing at a feature lights it as the selection is. On by default. */
|
|
17
18
|
hoverLights?: boolean;
|
|
18
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* What a view draws its scene in. `background`, `outline`, `grid` and `othersToward` come from the
|
|
22
|
+
* Protomaze theme's tokens (`--pm-*`, see `Theme.ts`); `ground`, `sky` and `windowsLit` are the
|
|
23
|
+
* scene's own, one set per look. Any of them given in the `theme` option wins over both.
|
|
24
|
+
*/
|
|
19
25
|
export interface GeometryTheme {
|
|
26
|
+
/** Under everything: what a 2D map shows past its ground. The `background` token. */
|
|
20
27
|
background: string;
|
|
21
28
|
ground: string;
|
|
29
|
+
/** The ground grid's lines, drawn faint. The `text` token. */
|
|
22
30
|
grid: string;
|
|
31
|
+
/** The outline round what is lit, `highlight.look` 'outline'. The `highlight` token. */
|
|
23
32
|
outline: string;
|
|
24
|
-
/** What the rest is shaded towards while something is lit: 0 black, 1 white. */
|
|
33
|
+
/** What the rest is shaded towards while something is lit: 0 black, 1 white. The look's. */
|
|
25
34
|
othersToward: number;
|
|
26
35
|
/** The sky in perspective: overhead, at the horizon, and the glow just above it. */
|
|
27
36
|
sky: {
|
|
@@ -32,12 +41,23 @@ export interface GeometryTheme {
|
|
|
32
41
|
/** Windows on volumes lit at night (dark), or dark glass (light). */
|
|
33
42
|
windowsLit: number;
|
|
34
43
|
}
|
|
44
|
+
/** The `theme` option as an object: scene colours of the application's own, over the look `scheme` names (dark by default). */
|
|
45
|
+
export type GeometryThemeOptions = Partial<GeometryTheme> & {
|
|
46
|
+
scheme?: ThemeScheme;
|
|
47
|
+
};
|
|
48
|
+
/** The dark look: Protomaze's dark tokens, a night sky. */
|
|
35
49
|
export declare const DARK_THEME: GeometryTheme;
|
|
50
|
+
/** The light look: Protomaze's light tokens, a day sky. */
|
|
36
51
|
export declare const LIGHT_THEME: GeometryTheme;
|
|
37
52
|
export interface GeometryViewOptions {
|
|
38
53
|
/** A 2D map (orthographic, straight down) or 3D (perspective, tilting). 3D by default. */
|
|
39
54
|
mode?: '2d' | '3d';
|
|
40
|
-
|
|
55
|
+
/**
|
|
56
|
+
* The look: 'dark' (the default), 'light', or 'auto' - the page's `color-scheme`, else the
|
|
57
|
+
* system's. Colours follow the `--pm-*` tokens set round the view; an object sets scene
|
|
58
|
+
* colours of its own over them.
|
|
59
|
+
*/
|
|
60
|
+
theme?: ThemeScheme | GeometryThemeOptions;
|
|
41
61
|
/** Where the camera starts. */
|
|
42
62
|
camera?: Partial<CameraState>;
|
|
43
63
|
limits?: Partial<CameraLimits>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const DARK_THEME={background:
|
|
1
|
+
import{PROTOMAZE_DARK as o,PROTOMAZE_LIGHT as t}from"../theme/Theme.js";export const DARK_THEME={background:o.background,ground:"#14181d",grid:o.text,outline:o.highlight,othersToward:0,sky:{zenith:"#05080d",horizon:"#1d2938",glow:"#2e4d6c"},windowsLit:.35};export const LIGHT_THEME={background:t.background,ground:"#f8f9fa",grid:t.text,outline:t.highlight,othersToward:1,sky:{zenith:"#9fb7cf",horizon:"#e8eef3",glow:"#ffffff"},windowsLit:0};
|
package/engine/GeometryView.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { Lighting } from '../three/Shading';
|
|
|
10
10
|
import { GeometryFrameStats } from './GeometryEngine';
|
|
11
11
|
import { GeometryViewOptions } from './GeometryOptions';
|
|
12
12
|
import { CameraState, MapCamera } from './MapCamera';
|
|
13
|
+
import { ResolvedTheme } from '../theme/Theme';
|
|
13
14
|
/** What the pointer is on, or a click hit: a layer's feature, and the point on it. */
|
|
14
15
|
export interface GeometryHit<F = GeometryFeature> extends LayerHit<F> {
|
|
15
16
|
point: [number, number, number];
|
|
@@ -71,6 +72,8 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
71
72
|
labels: LabelOverlay | null;
|
|
72
73
|
private options;
|
|
73
74
|
private theme;
|
|
75
|
+
private resolved;
|
|
76
|
+
private resolvedKey;
|
|
74
77
|
private layers;
|
|
75
78
|
private overlays;
|
|
76
79
|
private controller;
|
|
@@ -97,7 +100,19 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
97
100
|
get element(): HTMLDivElement | null;
|
|
98
101
|
setOptions(options: Partial<GeometryViewOptions>): void;
|
|
99
102
|
getOptions(): Readonly<GeometryViewOptions>;
|
|
103
|
+
/**
|
|
104
|
+
* The theme's tokens in force at the view: Protomaze's for its look, then the `--pm-*`
|
|
105
|
+
* properties the page sets round it. What its chrome - outline, labels, sketches - is drawn in.
|
|
106
|
+
*/
|
|
107
|
+
get tokens(): ResolvedTheme;
|
|
108
|
+
/** The options, and the theme as it stands, onto the engine, the ground, the labels and the sketches. */
|
|
100
109
|
private applyOptions;
|
|
110
|
+
/**
|
|
111
|
+
* The scene's colours: the look's own, then the tokens at the view's element (none before
|
|
112
|
+
* `init`), then what the application's `theme` object sets. New tokens restyle the labels
|
|
113
|
+
* and the sketches.
|
|
114
|
+
*/
|
|
115
|
+
private resolveColors;
|
|
101
116
|
/** What needs the engine started: the bloom's settings, the halo's, the heatmap's. */
|
|
102
117
|
private applyRuntimeOptions;
|
|
103
118
|
/** Adds a layer on top, or under `below`. */
|
|
@@ -138,6 +153,8 @@ export declare class GeometryView extends TypedEventEmitter<GeometryViewEvents>
|
|
|
138
153
|
bounds(): Bounds3 | null;
|
|
139
154
|
/** A ground under everything: its depth is the scene's, what lies under it ghosted. Null for none. */
|
|
140
155
|
setGround(options: GroundOptions | null): void;
|
|
156
|
+
/** The ground's colour and its grid's: the application's, else the theme's. */
|
|
157
|
+
private applyGroundColors;
|
|
141
158
|
getGround(): Ground | null;
|
|
142
159
|
/** The heatmap of these layers - all, by default - instead of them; null to draw them again. */
|
|
143
160
|
setDensity(spec: {
|
package/engine/GeometryView.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseColor as t}from"../common/Colors.js";import{Disposables as e}from"../common/Disposables.js";import{isEmptyBounds as i,unionBounds as s}from"../data/Geometry.js";import{TypedEventEmitter as n}from"../event/TypedEventEmitter.js";import{LabelOverlay as o}from"./Labels.js";import{CanvasGeometryEngine as r}from"../three/CanvasGeometryEngine.js";import{Ground as h}from"../three/Ground.js";import{Lighting as a}from"../three/Shading.js";import{DARK_THEME as l,LIGHT_THEME as c}from"./GeometryOptions.js";import{MapCamera as d}from"./MapCamera.js";export class GeometryView extends n{constructor(t={}){super(),this.lighting=new a,this.up=[0,0,1],this.labels=null,this.layers=[],this.overlays=[],this.controller=null,this.controllerDrag=null,this.root=null,this.disposables=new e,this.hovered=null,this.ground=null,this.groundOptions=null,this.lastCamera="",this.frames=[],this.pendingMode=null,this.hoverQueued=!1,this.pointer=null,this.drag=null,this.touches=new Map,this.pinch=null,this.options=t,this.mode=t.mode??"3d",this.engine=new r({antialias:t.antialias,forceWebGL:t.forceWebGL,maxPixelRatio:t.maxPixelRatio}),this.camera=new d(t.camera),this.camera.orthographic="2d"===this.mode,t.fov&&(this.camera.fovY=t.fov),t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),this.applyOptions()}async init(t){this.disposables=new e;const i=document.createElement("div");i.style.position="relative",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden",i.style.outline="none",i.tabIndex=0,t.appendChild(i),i.appendChild(this.engine.canvas),this.root=i,this.disposables.add(()=>i.remove());const s=new o(i,t=>this.toScreen(t));this.labels=s,this.disposables.add(()=>{s.dispose(),this.labels=null});const n=()=>{const t=i.getBoundingClientRect();this.engine.setSize(t.width,t.height,window.devicePixelRatio||1)};n();const r=new ResizeObserver(n);r.observe(i),this.disposables.add(()=>r.disconnect()),this.listen(),this.engine.setCamera((t,e)=>(this.camera.tick()?this.engine.setAnimating("camera",!0):(this.engine.setAnimating("camera",!1),this.finishModeSwitch()),this.emitCamera(),this.ground?.setViewDistance(this.camera.state.distance),this.camera.frame(t,e))),this.disposables.add(this.engine.onBeforeRender(()=>{let t=!1;for(const e of[...this.layers,...this.overlays]){const i=e.wantsBuild;e.beforeRender(!t),i&&(t&&this.requestRepaint(),t=!0)}})),this.disposables.add(this.engine.on("frame",t=>this.onFrame(t))),await this.engine.init(),this.applyRuntimeOptions(),this.emit("ready")}dispose(){this.setController(null),this.disposables.dispose(),this.layers.forEach(t=>t.detach()),this.overlays.forEach(t=>t.detach()),this.ground?.dispose(),this.ground=null,this.engine.dispose(),this.root=null}get element(){return this.root}setOptions(t){const e=void 0!==t.mode&&t.mode!==this.mode;this.options={...this.options,...t},t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),t.fov&&(this.camera.fovY=t.fov),this.applyOptions(),this.applyRuntimeOptions(),e&&this.setMode(t.mode),this.requestRepaint()}getOptions(){return this.options}applyOptions(){const e=this.options.theme;this.theme="light"===e?c:"dark"!==e&&e?{...l,...e}:l;const i=this.options.highlight??{};this.highlight={look:i.look??"glow",glow:i.glow??"bloom",outlineColor:t(i.outlineColor??this.theme.outline),outlineWidth:i.outlineWidth??2,hoverFades:i.hoverFades??!0,othersShade:i.othersShade??.55,othersToward:this.theme.othersToward,hoverLights:i.hoverLights??!0},this.engine.setBackground(this.theme.background),this.engine.sky.setColors({...this.theme.sky,below:this.theme.sky.horizon})}applyRuntimeOptions(){const t=this.options.bloom;this.engine.bloom&&(this.engine.bloom.strength.value=t?.strength??1.2,this.engine.bloom.radius.value=t?.radius??.5,this.engine.bloom.threshold.value=t?.threshold??0);const e=this.options.halo;this.engine.halo.strength.value=!1===e?0:e?.strength??.55,this.engine.halo.blur.value=!1===e?0:e?.blur??12;const i=this.options.density;(i?.ramp||i?.top)&&this.engine.density.setColorMap(i.ramp??this.engine.density.colorMap,i.top),void 0!==i?.opacity&&(this.engine.density.opacity.value=i.opacity)}addLayer(t,e){if(this.layers.includes(t))return t;const i=e?this.layers.indexOf(e):-1;return i>=0?this.layers.splice(i,0,t):this.layers.push(t),t.attach(this),this.requestRepaint(),t}removeLayer(t){const e=this.layers.indexOf(t);e<0||(this.hovered?.layer===t&&this.setHover(null),this.layers.splice(e,1),t.detach(),this.requestRepaint())}getLayers(){return this.layers}getLayer(t){return this.layers.find(e=>e.id===t)}addOverlay(t){this.overlays.includes(t)||(this.overlays.push(t),t.setOverlay(!0,this.overlays.length),t.setPickable(!1),t.attach(this),this.requestRepaint())}removeOverlay(t){const e=this.overlays.indexOf(t);e<0||(this.overlays.splice(e,1),t.detach(),this.requestRepaint())}setController(t){t!==this.controller&&(this.controller?.detach(),this.controller=t,this.controllerDrag=null,t?.attach(this),this.applyCursor(),this.requestRepaint())}getController(){return this.controller}get viewSize(){return this.engine.viewSize}toScreen(t){const{width:e,height:i}=this.engine.viewSize;if(e<=0||i<=0)return null;const s=this.camera.frame(e,i).viewProjection,n=t[0],o=t[1],r=t[2]??0,h=s[0]*n+s[1]*o+s[2]*r+s[3],a=s[4]*n+s[5]*o+s[6]*r+s[7],l=s[12]*n+s[13]*o+s[14]*r+s[15];return l<=1e-9?null:[(h/l+1)/2*e,(1-a/l)/2*i]}rayAt(t,e){const{width:i,height:s}=this.engine.viewSize;return this.camera.ray(t,e,i,s)}toGround(t,e,i=this.camera.state.target[2]){const{width:s,height:n}=this.engine.viewSize;return this.camera.groundAt(t,e,s,n,i)}pixelSizeAt(t){const{height:e}=this.engine.viewSize,i=Math.tan(this.camera.fovY*Math.PI/360);if(this.camera.orthographic)return 2*this.camera.state.distance*i/Math.max(1,e);const{f:s,eye:n}=this.camera.basis(),o=(t[0]-n[0])*s[0]+(t[1]-n[1])*s[1]+((t[2]??0)-n[2])*s[2];return 2*Math.max(o,this.camera.near())*i/Math.max(1,e)}bounds(){let t=null;for(const e of this.layers){const n=e.bounds();i(n)||(t=t?s(t,n):n)}return t}setGround(t){if(this.ground&&(this.engine.baseScene.remove(this.ground.mesh),this.ground.dispose(),this.ground=null),this.groundOptions=t,!t)return void this.requestRepaint();const[e,i,s,n]=t.bounds,o=this.engine.originFor([(e+s)/2,(i+n)/2,t.z??0]);this.ground=new h({color:this.theme.ground,grid:{spacing:10,major:10,color:this.theme.grid},...t},o,{eye:this.engine.sky.eye,fog:this.engine.sky.horizon}),this.engine.baseScene.add(this.ground.mesh),this.requestRepaint()}getGround(){return this.ground}setDensity(t){const e=t?.layers?.map(t=>"string"==typeof t?this.getLayer(t):t);this.layers.forEach(i=>i.setDensity(!!t&&(!e||e.includes(i)))),(t?.ramp||t?.top)&&this.engine.density.setColorMap(t.ramp??this.engine.density.colorMap,t.top),this.requestRepaint()}getCamera(){return{...this.camera.state,target:[...this.camera.state.target]}}setCamera(t){this.camera.set(t),this.requestRepaint()}flyTo(t,e=900){this.camera.flyTo(t,e),this.engine.setAnimating("camera",!0)}fit(t=this.bounds(),e=900,s=.1){if(!t||i(t))return;const{width:n,height:o}=this.engine.viewSize,r=this.camera.fit(t.min,t.max,n,o,s);e>0?this.flyTo(r,e):this.setCamera(r)}setMode(t,e=55){if(this.options.mode=t,"2d"===t){if("2d"===this.mode&&this.camera.orthographic)return;this.pendingMode="2d",this.flyTo({tilt:0},450)}else{this.pendingMode=null;const t="2d"===this.mode;this.mode="3d",this.camera.orthographic=!1,t&&this.flyTo({tilt:Math.max(this.camera.state.tilt,e)},800),this.emit("mode","3d"),this.requestRepaint()}}finishModeSwitch(){"2d"===this.pendingMode&&(this.pendingMode=null,this.mode="2d",this.camera.orthographic=!0,this.emit("mode","2d"),this.requestRepaint())}async pickAt(t,e){const i=await this.engine.pick(t,e);return i?{...i.hit,point:i.point}:null}setHover(t){const e=this.hovered;e?.layer===t?.layer&&e?.id===t?.id||(e?.layer.setHovered(null),t?.layer.setHovered(t.id),this.hovered=t?{...e??{},...t}:null,this.applyCursor(),this.requestRepaint())}select(t,e,i="replace"){t.select(e,i),this.emitSelection()}clearSelection(){this.layers.forEach(t=>t.clearSelection()),this.emitSelection()}getSelection(){const t=this.layers.map(t=>({layer:t,ids:t.selection()})).filter(t=>t.ids.length>0);return{layers:t,count:t.reduce((t,e)=>t+e.ids.length,0)}}rankOf(t){const e=this.layers.indexOf(t);if(e>=0)return e;const i=this.overlays.indexOf(t);return i>=0?this.layers.length+i:0}get anyHovered(){return null!==this.hovered}get windowsLit(){return this.theme.windowsLit}requestRepaint(){this.engine.requestRepaint()}setAnimating(t,e){this.engine.setAnimating(t,e)}emitSelection(){this.emit("select",this.getSelection())}emitCamera(){const t=this.camera.state,e=`${t.target.join(",")}|${t.distance}|${t.heading}|${t.tilt}`;e!==this.lastCamera&&(this.lastCamera=e,this.emit("camera",this.getCamera()))}onFrame(t){this.labels?.update();const e=performance.now();for(this.frames.push(e);this.frames.length>0&&e-this.frames[0]>1e3;)this.frames.shift();const i=this.engine.getRenderer()?.info?.render??{};this.emit("frame",{...t,fps:this.frames.length,drawCalls:i.drawCalls??i.calls??0,triangles:i.triangles??0,backend:this.engine.webgpu?"webgpu":"webgl"})}local(t){const e=this.root.getBoundingClientRect();return{x:t.clientX-e.left,y:t.clientY-e.top}}pointerOf(t){const{x:e,y:i}=this.local(t);return{x:e,y:i,button:t.button,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,pointerType:t.pointerType??"mouse",native:t}}capture(t){try{this.engine.canvas.setPointerCapture(t)}catch{}}applyCursor(){if(!this.root)return;const t=this.hovered?"pointer":this.drag?.moved?"pan"===this.drag.kind?"grabbing":"move":"grab";this.engine.canvas.style.cursor=this.controller?.cursor??t}listen(){const t=this.engine.canvas;t.style.cursor="grab";const e=(t,e,i,s)=>{t.addEventListener(e,i,s),this.disposables.add(()=>t.removeEventListener(e,i,s))};e(t,"contextmenu",t=>t.preventDefault()),e(t,"pointerdown",t=>this.onDown(t)),e(t,"pointermove",t=>this.onMove(t)),e(t,"pointerup",t=>this.onUp(t)),e(t,"pointercancel",t=>this.onUp(t,!0)),e(t,"pointerleave",()=>{this.pointer=null,this.controller?.onPointerLeave(),this.drag||this.setHover(null),this.emit("hover",null)}),e(t,"wheel",t=>this.onWheel(t),{passive:!1}),e(t,"dblclick",t=>{if(this.controller?.onDoubleClick(this.pointerOf(t)))return void this.applyCursor();if(!1===this.options.interactive)return;const{x:e,y:i}=this.local(t),{width:s,height:n}=this.engine.viewSize,o=this.camera.groundAt(e,i,s,n);o&&this.flyTo({target:o,distance:this.camera.state.distance*(t.shiftKey?2:.45)},600)}),e(this.root,"keydown",t=>{if(this.controller?.onKeyDown(t))return t.preventDefault(),void this.applyCursor();"Escape"===t.key&&this.clearSelection()})}onDown(t){this.root?.focus({preventScroll:!0});const{x:e,y:i}=this.local(t);if("touch"===t.pointerType&&(this.touches.set(t.pointerId,{x:e,y:i}),2===this.touches.size))return this.drag=null,void(this.pinch=this.pinchOf());if(this.controller&&null===this.controllerDrag&&this.controller.onPointerDown(this.pointerOf(t)))return this.controllerDrag=t.pointerId,this.camera.stop(),this.capture(t.pointerId),void this.applyCursor();this.camera.stop();const s=2===t.button||1===t.button||t.ctrlKey&&0===t.button&&"none"===this.options.selection,{width:n,height:o}=this.engine.viewSize;this.drag={id:t.pointerId,kind:s?"rotate":"pan",x:e,y:i,startX:e,startY:i,time:performance.now(),anchor:s?null:this.camera.groundAt(e,i,n,o),moved:!1,history:[]},this.capture(t.pointerId)}onMove(t){const{x:e,y:i}=this.local(t);if(this.pointer={x:e,y:i},this.controllerDrag===t.pointerId)return this.controller?.onPointerDrag(this.pointerOf(t)),void this.applyCursor();if("touch"===t.pointerType&&this.touches.has(t.pointerId)&&(this.touches.set(t.pointerId,{x:e,y:i}),this.pinch&&2===this.touches.size))return void this.onPinch();const s=this.drag;if(!s||s.id!==t.pointerId){return(this.controller?.onPointerMove(this.pointerOf(t))??!1)||this.queueHover(),void this.applyCursor()}if(!s.moved&&Math.hypot(e-s.startX,i-s.startY)>5&&(s.moved=!0,this.applyCursor()),!s.moved||!1===this.options.interactive)return;const{width:n,height:o}=this.engine.viewSize;if("pan"===s.kind&&s.anchor){this.camera.panTo(s.anchor,e,i,n,o);const t=performance.now();for(s.history.push({t:t,target:[this.camera.state.target[0],this.camera.state.target[1]]});s.history.length>0&&t-s.history[0].t>100;)s.history.shift()}else"rotate"===s.kind&&this.camera.rotate(.3*(e-s.x),"3d"===this.mode?.25*(i-s.y):0);s.x=e,s.y=i,this.requestRepaint()}onUp(t,e=!1){if(this.touches.delete(t.pointerId),this.touches.size<2&&(this.pinch=null),this.controllerDrag===t.pointerId){this.controllerDrag=null;try{this.engine.canvas.releasePointerCapture(t.pointerId)}catch{}return this.controller?.onPointerUp(this.pointerOf(t)),void this.applyCursor()}const i=this.drag;if(i&&i.id===t.pointerId){this.drag=null;try{this.engine.canvas.releasePointerCapture(t.pointerId)}catch{}if(this.applyCursor(),!e){if(i.moved&&"pan"===i.kind&&i.history.length>1){const t=i.history[0],e=i.history[i.history.length-1],s=(e.t-t.t)/1e3;s>.01&&performance.now()-e.t<60&&(this.camera.glide([(e.target[0]-t.target[0])/s,(e.target[1]-t.target[1])/s]),this.engine.setAnimating("camera",!0))}!i.moved&&performance.now()-i.time<600&&0===t.button&&this.onClick(t)}}}async onClick(t){if(this.controller?.onClick(this.pointerOf(t)))return void this.applyCursor();const{x:e,y:i}=this.local(t),s=await this.pickAt(e,i),n={hit:s,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,x:e,y:i,native:t};this.emit("click",n);const o=this.options.selection??"multi";if("none"===o)return;const r="multi"===o&&(n.ctrl||n.shift);if(s){if(r)s.layer.select([s.id],n.ctrl?"toggle":"add");else{this.layers.forEach(t=>{t!==s.layer&&t.clearSelection()});const t=s.layer.selection(),e=1===t.length&&t[0]===s.id;s.layer.select(e?[]:[s.id],"replace")}this.emitSelection()}else r||this.clearSelection()}onWheel(t){if(!1===this.options.interactive)return;t.preventDefault();const{x:e,y:i}=this.local(t),{width:s,height:n}=this.engine.viewSize,o=1===t.deltaMode?33:2===t.deltaMode?400:1,r=Math.exp(t.deltaY*o*.0016);this.camera.stop(),this.camera.zoomAt(r,e,i,s,n),this.requestRepaint(),this.queueHover()}pinchOf(){const[t,e]=[...this.touches.values()];return{distance:Math.hypot(e.x-t.x,e.y-t.y),angle:Math.atan2(e.y-t.y,e.x-t.x),midY:(t.y+e.y)/2}}onPinch(){const t=this.pinch,e=this.pinchOf(),[i,s]=[...this.touches.values()],{width:n,height:o}=this.engine.viewSize;this.camera.zoomAt(t.distance/Math.max(1,e.distance),(i.x+s.x)/2,(i.y+s.y)/2,n,o),this.camera.rotate(180*-(e.angle-t.angle)/Math.PI,"3d"===this.mode?.25*(e.midY-t.midY):0),this.pinch=e,this.requestRepaint()}queueHover(){!1===this.options.hover||this.hoverQueued||this.drag?.moved||(this.hoverQueued=!0,requestAnimationFrame(async()=>{this.hoverQueued=!1;const t=this.pointer;if(!t||this.drag?.moved)return;const e=await this.pickAt(t.x,t.y);if(!this.pointer)return;const i=e?.layer!==this.hovered?.layer||e?.id!==this.hovered?.id;this.setHover(e),e&&(this.hovered=e),i&&this.emit("hover",e)}))}}
|
|
1
|
+
import{parseColor as t,toCss as e}from"../common/Colors.js";import{Disposables as i}from"../common/Disposables.js";import{isEmptyBounds as s,unionBounds as o}from"../data/Geometry.js";import{TypedEventEmitter as r}from"../event/TypedEventEmitter.js";import{LabelOverlay as n}from"./Labels.js";import{CanvasGeometryEngine as h}from"../three/CanvasGeometryEngine.js";import{Ground as a}from"../three/Ground.js";import{Lighting as l}from"../three/Shading.js";import{DARK_THEME as c,LIGHT_THEME as d}from"./GeometryOptions.js";import{MapCamera as p}from"./MapCamera.js";import{resolveTheme as u,watchTheme as m}from"../theme/Theme.js";export class GeometryView extends r{constructor(t={}){super(),this.lighting=new l,this.up=[0,0,1],this.labels=null,this.resolvedKey="",this.layers=[],this.overlays=[],this.controller=null,this.controllerDrag=null,this.root=null,this.disposables=new i,this.hovered=null,this.ground=null,this.groundOptions=null,this.lastCamera="",this.frames=[],this.pendingMode=null,this.hoverQueued=!1,this.pointer=null,this.drag=null,this.touches=new Map,this.pinch=null,this.options=t,this.mode=t.mode??"3d",this.engine=new h({antialias:t.antialias,forceWebGL:t.forceWebGL,maxPixelRatio:t.maxPixelRatio}),this.camera=new p(t.camera),this.camera.orthographic="2d"===this.mode,t.fov&&(this.camera.fovY=t.fov),t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),this.applyOptions()}async init(t){this.disposables=new i;const e=document.createElement("div");e.style.position="relative",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=0,t.appendChild(e),e.appendChild(this.engine.canvas),this.root=e,this.disposables.add(()=>e.remove());const s=new n(e,t=>this.toScreen(t));this.labels=s,this.disposables.add(()=>{s.dispose(),this.labels=null}),this.resolvedKey="",this.applyOptions(),this.disposables.add(m(e,()=>{this.applyOptions(),this.requestRepaint()}));const o=()=>{const t=e.getBoundingClientRect();this.engine.setSize(t.width,t.height,window.devicePixelRatio||1)};o();const r=new ResizeObserver(o);r.observe(e),this.disposables.add(()=>r.disconnect()),this.listen(),this.engine.setCamera((t,e)=>(this.camera.tick()?this.engine.setAnimating("camera",!0):(this.engine.setAnimating("camera",!1),this.finishModeSwitch()),this.emitCamera(),this.ground?.setViewDistance(this.camera.state.distance),this.camera.frame(t,e))),this.disposables.add(this.engine.onBeforeRender(()=>{let t=!1;for(const e of[...this.layers,...this.overlays]){const i=e.wantsBuild;e.beforeRender(!t),i&&(t&&this.requestRepaint(),t=!0)}})),this.disposables.add(this.engine.on("frame",t=>this.onFrame(t))),await this.engine.init(),this.applyRuntimeOptions(),this.emit("ready")}dispose(){this.setController(null),this.disposables.dispose(),this.layers.forEach(t=>t.detach()),this.overlays.forEach(t=>t.detach()),this.ground?.dispose(),this.ground=null,this.engine.dispose(),this.root=null}get element(){return this.root}setOptions(t){const e=void 0!==t.mode&&t.mode!==this.mode;this.options={...this.options,...t},t.limits&&(this.camera.limits={...this.camera.limits,...t.limits}),t.fov&&(this.camera.fovY=t.fov),this.applyOptions(),this.applyRuntimeOptions(),e&&this.setMode(t.mode),this.requestRepaint()}getOptions(){return this.options}get tokens(){return this.resolved}applyOptions(){this.resolveColors();const e=this.options.highlight??{};this.highlight={look:e.look??"glow",glow:e.glow??"bloom",outlineColor:t(e.outlineColor??this.theme.outline),outlineWidth:e.outlineWidth??2,hoverFades:e.hoverFades??!0,othersShade:e.othersShade??.55,othersToward:this.theme.othersToward,hoverLights:e.hoverLights??!0},this.engine.setBackground(g(this.theme.background));const i=this.theme.sky;this.engine.sky.setColors({zenith:g(i.zenith),horizon:g(i.horizon),glow:g(i.glow),below:g(i.horizon)}),this.applyGroundColors()}resolveColors(){const t=this.options.theme,e="object"==typeof t&&t?t:{},i=u(this.root,"string"==typeof t?t:e.scheme??"dark"),s="light"===i.scheme?d:c,o={...s,background:i.background,outline:i.highlight,grid:i.text,othersToward:"light"===i.scheme?1:0};for(const t of Object.keys(s))void 0!==e[t]&&(o[t]=e[t]);this.theme=o,this.resolved=i;const r=JSON.stringify(i);r!==this.resolvedKey&&(this.resolvedKey=r,this.labels?.setTheme(i),this.overlays.forEach(t=>t.restyle()))}applyRuntimeOptions(){const t=this.options.bloom;this.engine.bloom&&(this.engine.bloom.strength.value=t?.strength??1.2,this.engine.bloom.radius.value=t?.radius??.5,this.engine.bloom.threshold.value=t?.threshold??0);const e=this.options.halo;this.engine.halo.strength.value=!1===e?0:e?.strength??.55,this.engine.halo.blur.value=!1===e?0:e?.blur??12;const i=this.options.density;(i?.ramp||i?.top)&&this.engine.density.setColorMap(i.ramp??this.engine.density.colorMap,i.top),void 0!==i?.opacity&&(this.engine.density.opacity.value=i.opacity)}addLayer(t,e){if(this.layers.includes(t))return t;const i=e?this.layers.indexOf(e):-1;return i>=0?this.layers.splice(i,0,t):this.layers.push(t),t.attach(this),this.requestRepaint(),t}removeLayer(t){const e=this.layers.indexOf(t);e<0||(this.hovered?.layer===t&&this.setHover(null),this.layers.splice(e,1),t.detach(),this.requestRepaint())}getLayers(){return this.layers}getLayer(t){return this.layers.find(e=>e.id===t)}addOverlay(t){this.overlays.includes(t)||(this.overlays.push(t),t.setOverlay(!0,this.overlays.length),t.setPickable(!1),t.attach(this),this.requestRepaint())}removeOverlay(t){const e=this.overlays.indexOf(t);e<0||(this.overlays.splice(e,1),t.detach(),this.requestRepaint())}setController(t){t!==this.controller&&(this.controller?.detach(),this.controller=t,this.controllerDrag=null,t?.attach(this),this.applyCursor(),this.requestRepaint())}getController(){return this.controller}get viewSize(){return this.engine.viewSize}toScreen(t){const{width:e,height:i}=this.engine.viewSize;if(e<=0||i<=0)return null;const s=this.camera.frame(e,i).viewProjection,o=t[0],r=t[1],n=t[2]??0,h=s[0]*o+s[1]*r+s[2]*n+s[3],a=s[4]*o+s[5]*r+s[6]*n+s[7],l=s[12]*o+s[13]*r+s[14]*n+s[15];return l<=1e-9?null:[(h/l+1)/2*e,(1-a/l)/2*i]}rayAt(t,e){const{width:i,height:s}=this.engine.viewSize;return this.camera.ray(t,e,i,s)}toGround(t,e,i=this.camera.state.target[2]){const{width:s,height:o}=this.engine.viewSize;return this.camera.groundAt(t,e,s,o,i)}pixelSizeAt(t){const{height:e}=this.engine.viewSize,i=Math.tan(this.camera.fovY*Math.PI/360);if(this.camera.orthographic)return 2*this.camera.state.distance*i/Math.max(1,e);const{f:s,eye:o}=this.camera.basis(),r=(t[0]-o[0])*s[0]+(t[1]-o[1])*s[1]+((t[2]??0)-o[2])*s[2];return 2*Math.max(r,this.camera.near())*i/Math.max(1,e)}bounds(){let t=null;for(const e of this.layers){const i=e.bounds();s(i)||(t=t?o(t,i):i)}return t}setGround(t){if(this.ground&&(this.engine.baseScene.remove(this.ground.mesh),this.ground.dispose(),this.ground=null),this.groundOptions=t,!t)return void this.requestRepaint();const[e,i,s,o]=t.bounds,r=this.engine.originFor([(e+s)/2,(i+o)/2,t.z??0]),n={spacing:10,major:10,color:this.theme.grid};this.ground=new a({color:this.theme.ground,...t,grid:t.grid?{...n,...t.grid}:"grid"in t?t.grid:n},r,{eye:this.engine.sky.eye,fog:this.engine.sky.horizon}),this.applyGroundColors(),this.engine.baseScene.add(this.ground.mesh),this.requestRepaint()}applyGroundColors(){const t=this.ground,e=this.groundOptions;if(!t||!e)return;const i=e.grid?e.grid.color:void 0;t.setColors({color:g(e.color??this.theme.ground),grid:g(i??this.theme.grid)})}getGround(){return this.ground}setDensity(t){const e=t?.layers?.map(t=>"string"==typeof t?this.getLayer(t):t);this.layers.forEach(i=>i.setDensity(!!t&&(!e||e.includes(i)))),(t?.ramp||t?.top)&&this.engine.density.setColorMap(t.ramp??this.engine.density.colorMap,t.top),this.requestRepaint()}getCamera(){return{...this.camera.state,target:[...this.camera.state.target]}}setCamera(t){this.camera.set(t),this.requestRepaint()}flyTo(t,e=900){this.camera.flyTo(t,e),this.engine.setAnimating("camera",!0)}fit(t=this.bounds(),e=900,i=.1){if(!t||s(t))return;const{width:o,height:r}=this.engine.viewSize,n=this.camera.fit(t.min,t.max,o,r,i);e>0?this.flyTo(n,e):this.setCamera(n)}setMode(t,e=55){if(this.options.mode=t,"2d"===t){if("2d"===this.mode&&this.camera.orthographic)return;this.pendingMode="2d",this.flyTo({tilt:0},450)}else{this.pendingMode=null;const t="2d"===this.mode;this.mode="3d",this.camera.orthographic=!1,t&&this.flyTo({tilt:Math.max(this.camera.state.tilt,e)},800),this.emit("mode","3d"),this.requestRepaint()}}finishModeSwitch(){"2d"===this.pendingMode&&(this.pendingMode=null,this.mode="2d",this.camera.orthographic=!0,this.emit("mode","2d"),this.requestRepaint())}async pickAt(t,e){const i=await this.engine.pick(t,e);return i?{...i.hit,point:i.point}:null}setHover(t){const e=this.hovered;e?.layer===t?.layer&&e?.id===t?.id||(e?.layer.setHovered(null),t?.layer.setHovered(t.id),this.hovered=t?{...e??{},...t}:null,this.applyCursor(),this.requestRepaint())}select(t,e,i="replace"){t.select(e,i),this.emitSelection()}clearSelection(){this.layers.forEach(t=>t.clearSelection()),this.emitSelection()}getSelection(){const t=this.layers.map(t=>({layer:t,ids:t.selection()})).filter(t=>t.ids.length>0);return{layers:t,count:t.reduce((t,e)=>t+e.ids.length,0)}}rankOf(t){const e=this.layers.indexOf(t);if(e>=0)return e;const i=this.overlays.indexOf(t);return i>=0?this.layers.length+i:0}get anyHovered(){return null!==this.hovered}get windowsLit(){return this.theme.windowsLit}requestRepaint(){this.engine.requestRepaint()}setAnimating(t,e){this.engine.setAnimating(t,e)}emitSelection(){this.emit("select",this.getSelection())}emitCamera(){const t=this.camera.state,e=`${t.target.join(",")}|${t.distance}|${t.heading}|${t.tilt}`;e!==this.lastCamera&&(this.lastCamera=e,this.emit("camera",this.getCamera()))}onFrame(t){this.labels?.update();const e=performance.now();for(this.frames.push(e);this.frames.length>0&&e-this.frames[0]>1e3;)this.frames.shift();const i=this.engine.getRenderer()?.info?.render??{};this.emit("frame",{...t,fps:this.frames.length,drawCalls:i.drawCalls??i.calls??0,triangles:i.triangles??0,backend:this.engine.webgpu?"webgpu":"webgl"})}local(t){const e=this.root.getBoundingClientRect();return{x:t.clientX-e.left,y:t.clientY-e.top}}pointerOf(t){const{x:e,y:i}=this.local(t);return{x:e,y:i,button:t.button,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,pointerType:t.pointerType??"mouse",native:t}}capture(t){try{this.engine.canvas.setPointerCapture(t)}catch{}}applyCursor(){if(!this.root)return;const t=this.hovered?"pointer":this.drag?.moved?"pan"===this.drag.kind?"grabbing":"move":"grab";this.engine.canvas.style.cursor=this.controller?.cursor??t}listen(){const t=this.engine.canvas;t.style.cursor="grab";const e=(t,e,i,s)=>{t.addEventListener(e,i,s),this.disposables.add(()=>t.removeEventListener(e,i,s))};e(t,"contextmenu",t=>t.preventDefault()),e(t,"pointerdown",t=>this.onDown(t)),e(t,"pointermove",t=>this.onMove(t)),e(t,"pointerup",t=>this.onUp(t)),e(t,"pointercancel",t=>this.onUp(t,!0)),e(t,"pointerleave",()=>{this.pointer=null,this.controller?.onPointerLeave(),this.drag||this.setHover(null),this.emit("hover",null)}),e(t,"wheel",t=>this.onWheel(t),{passive:!1}),e(t,"dblclick",t=>{if(this.controller?.onDoubleClick(this.pointerOf(t)))return void this.applyCursor();if(!1===this.options.interactive)return;const{x:e,y:i}=this.local(t),{width:s,height:o}=this.engine.viewSize,r=this.camera.groundAt(e,i,s,o);r&&this.flyTo({target:r,distance:this.camera.state.distance*(t.shiftKey?2:.45)},600)}),e(this.root,"keydown",t=>{if(this.controller?.onKeyDown(t))return t.preventDefault(),void this.applyCursor();"Escape"===t.key&&this.clearSelection()})}onDown(t){this.root?.focus({preventScroll:!0});const{x:e,y:i}=this.local(t);if("touch"===t.pointerType&&(this.touches.set(t.pointerId,{x:e,y:i}),2===this.touches.size))return this.drag=null,void(this.pinch=this.pinchOf());if(this.controller&&null===this.controllerDrag&&this.controller.onPointerDown(this.pointerOf(t)))return this.controllerDrag=t.pointerId,this.camera.stop(),this.capture(t.pointerId),void this.applyCursor();this.camera.stop();const s=2===t.button||1===t.button||t.ctrlKey&&0===t.button&&"none"===this.options.selection,{width:o,height:r}=this.engine.viewSize;this.drag={id:t.pointerId,kind:s?"rotate":"pan",x:e,y:i,startX:e,startY:i,time:performance.now(),anchor:s?null:this.camera.groundAt(e,i,o,r),moved:!1,history:[]},this.capture(t.pointerId)}onMove(t){const{x:e,y:i}=this.local(t);if(this.pointer={x:e,y:i},this.controllerDrag===t.pointerId)return this.controller?.onPointerDrag(this.pointerOf(t)),void this.applyCursor();if("touch"===t.pointerType&&this.touches.has(t.pointerId)&&(this.touches.set(t.pointerId,{x:e,y:i}),this.pinch&&2===this.touches.size))return void this.onPinch();const s=this.drag;if(!s||s.id!==t.pointerId){return(this.controller?.onPointerMove(this.pointerOf(t))??!1)||this.queueHover(),void this.applyCursor()}if(!s.moved&&Math.hypot(e-s.startX,i-s.startY)>5&&(s.moved=!0,this.applyCursor()),!s.moved||!1===this.options.interactive)return;const{width:o,height:r}=this.engine.viewSize;if("pan"===s.kind&&s.anchor){this.camera.panTo(s.anchor,e,i,o,r);const t=performance.now();for(s.history.push({t:t,target:[this.camera.state.target[0],this.camera.state.target[1]]});s.history.length>0&&t-s.history[0].t>100;)s.history.shift()}else"rotate"===s.kind&&this.camera.rotate(.3*(e-s.x),"3d"===this.mode?.25*(i-s.y):0);s.x=e,s.y=i,this.requestRepaint()}onUp(t,e=!1){if(this.touches.delete(t.pointerId),this.touches.size<2&&(this.pinch=null),this.controllerDrag===t.pointerId){this.controllerDrag=null;try{this.engine.canvas.releasePointerCapture(t.pointerId)}catch{}return this.controller?.onPointerUp(this.pointerOf(t)),void this.applyCursor()}const i=this.drag;if(i&&i.id===t.pointerId){this.drag=null;try{this.engine.canvas.releasePointerCapture(t.pointerId)}catch{}if(this.applyCursor(),!e){if(i.moved&&"pan"===i.kind&&i.history.length>1){const t=i.history[0],e=i.history[i.history.length-1],s=(e.t-t.t)/1e3;s>.01&&performance.now()-e.t<60&&(this.camera.glide([(e.target[0]-t.target[0])/s,(e.target[1]-t.target[1])/s]),this.engine.setAnimating("camera",!0))}!i.moved&&performance.now()-i.time<600&&0===t.button&&this.onClick(t)}}}async onClick(t){if(this.controller?.onClick(this.pointerOf(t)))return void this.applyCursor();const{x:e,y:i}=this.local(t),s=await this.pickAt(e,i),o={hit:s,shift:t.shiftKey,ctrl:t.ctrlKey||t.metaKey,alt:t.altKey,x:e,y:i,native:t};this.emit("click",o);const r=this.options.selection??"multi";if("none"===r)return;const n="multi"===r&&(o.ctrl||o.shift);if(s){if(n)s.layer.select([s.id],o.ctrl?"toggle":"add");else{this.layers.forEach(t=>{t!==s.layer&&t.clearSelection()});const t=s.layer.selection(),e=1===t.length&&t[0]===s.id;s.layer.select(e?[]:[s.id],"replace")}this.emitSelection()}else n||this.clearSelection()}onWheel(t){if(!1===this.options.interactive)return;t.preventDefault();const{x:e,y:i}=this.local(t),{width:s,height:o}=this.engine.viewSize,r=1===t.deltaMode?33:2===t.deltaMode?400:1,n=Math.exp(t.deltaY*r*.0016);this.camera.stop(),this.camera.zoomAt(n,e,i,s,o),this.requestRepaint(),this.queueHover()}pinchOf(){const[t,e]=[...this.touches.values()];return{distance:Math.hypot(e.x-t.x,e.y-t.y),angle:Math.atan2(e.y-t.y,e.x-t.x),midY:(t.y+e.y)/2}}onPinch(){const t=this.pinch,e=this.pinchOf(),[i,s]=[...this.touches.values()],{width:o,height:r}=this.engine.viewSize;this.camera.zoomAt(t.distance/Math.max(1,e.distance),(i.x+s.x)/2,(i.y+s.y)/2,o,r),this.camera.rotate(180*-(e.angle-t.angle)/Math.PI,"3d"===this.mode?.25*(e.midY-t.midY):0),this.pinch=e,this.requestRepaint()}queueHover(){!1===this.options.hover||this.hoverQueued||this.drag?.moved||(this.hoverQueued=!0,requestAnimationFrame(async()=>{this.hoverQueued=!1;const t=this.pointer;if(!t||this.drag?.moved)return;const e=await this.pickAt(t.x,t.y);if(!this.pointer)return;const i=e?.layer!==this.hovered?.layer||e?.id!==this.hovered?.id;this.setHover(e),e&&(this.hovered=e),i&&this.emit("hover",e)}))}}function g(i){const[s,o,r]=t(i);return e([s,o,r,1])}
|
package/engine/Labels.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Position } from '../data/Geometry';
|
|
2
|
+
import { ThemeTokens } from '../theme/Theme';
|
|
2
3
|
/** How a label looks: a measurement, a figure along an edge, a note, a warning. */
|
|
3
4
|
export type LabelKind = 'measure' | 'segment' | 'info' | 'warning';
|
|
4
5
|
/** A label on a world position, kept there as the camera moves. */
|
|
@@ -23,7 +24,15 @@ export declare class LabelOverlay {
|
|
|
23
24
|
private readonly project;
|
|
24
25
|
readonly element: HTMLDivElement;
|
|
25
26
|
private readonly groups;
|
|
27
|
+
private theme;
|
|
26
28
|
constructor(parent: HTMLElement, project: (p: Position) => [number, number] | null);
|
|
29
|
+
/**
|
|
30
|
+
* The tokens labels are drawn in - surface, text, muted text, danger, font, radius, shadow -
|
|
31
|
+
* as `resolveTheme` gives them: a view sets its own, and again when they change.
|
|
32
|
+
*/
|
|
33
|
+
setTheme(theme: ThemeTokens): void;
|
|
34
|
+
/** A label's look, for its kind in the theme. */
|
|
35
|
+
private paint;
|
|
27
36
|
/** Sets a group's labels: new ones made, gone ones removed, the rest moved and re-texted. */
|
|
28
37
|
set(group: string, labels: readonly LabelSpec[]): void;
|
|
29
38
|
/** Removes a group's labels, or every label. */
|
package/engine/Labels.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{parseColor as t,toCss as e}from"../common/Colors.js";import{PROTOMAZE_DARK as o}from"../theme/Theme.js";function n(e,o){const n=e=>{const o=t(e).slice(0,3).map(t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4));return.2126*o[0]+.7152*o[1]+.0722*o[2]},s=(t,e)=>(Math.max(t,e)+.05)/(Math.min(t,e)+.05),i=n(e);return s(i,n(o))>=s(i,1)?o:"#FFFFFF"}export class LabelOverlay{constructor(t,e){this.project=e,this.groups=new Map,this.theme=o;const n=document.createElement("div");n.style.position="absolute",n.style.inset="0",n.style.pointerEvents="none",n.style.overflow="hidden",t.appendChild(n),this.element=n,this.setTheme(this.theme)}setTheme(t){this.theme=t,this.element.style.fontFamily=t.fontFamily,this.element.style.fontSize=`${t.fontSize}px`,this.groups.forEach(t=>t.forEach(({spec:t,node:e})=>this.paint(e,t.kind)))}paint(o,s="measure"){o.style.borderRadius=`${this.theme.radius}px`,o.style.boxShadow=this.theme.shadow,Object.assign(o.style,function(o,s){const i=`${Math.max(9,s.fontSize-1)}px`,r=o=>e(function([t,e,o,n],s){return[t,e,o,n*s]}(t(s.surface),o));switch(o){case"segment":return{background:r(.78),color:s.text,fontWeight:String(s.fontWeight),fontSize:i,padding:"2px 5px"};case"info":return{background:r(.78),color:s.textMuted,fontWeight:String(s.fontWeight),fontSize:i,padding:"2px 6px"};case"warning":return{background:s.danger,color:n(s.danger,s.onAccent),fontWeight:String(s.fontWeightStrong),fontSize:i,padding:"2px 6px"};default:return{background:r(.88),color:s.text,fontWeight:String(s.fontWeightStrong),fontSize:`${s.fontSize}px`,padding:"3px 7px"}}}(s,this.theme)),o.dataset.kind=s}set(t,e){let o=this.groups.get(t);o||(o=new Map,this.groups.set(t,o));const n=new Set(e.map(t=>t.id));o.forEach((t,e)=>{n.has(e)||(t.node.remove(),o.delete(e))});for(const t of e){let e=o.get(t.id);if(!e){const n=document.createElement("div");n.style.position="absolute",n.style.left="0",n.style.top="0",n.style.whiteSpace="nowrap",n.style.fontVariantNumeric="tabular-nums",n.style.letterSpacing="0.2px",n.style.willChange="transform",this.element.appendChild(n),e={spec:t,node:n},o.set(t.id,e)}e.node.textContent!==t.text&&(e.node.textContent=t.text),e.spec.kind===t.kind&&e.node.dataset.kind||this.paint(e.node,t.kind),e.spec=t}this.update()}clear(t){const e=t?[t]:[...this.groups.keys()];for(const t of e)this.groups.get(t)?.forEach(t=>t.node.remove()),this.groups.delete(t)}update(){this.groups.forEach(t=>t.forEach(({spec:t,node:e})=>{const o=this.project(t.position);if(!o)return void(e.style.display="none");e.style.display="";const[n,s]=t.offset??[0,0];e.style.transform=`translate(${Math.round(o[0]+n)}px, ${Math.round(o[1]+s)}px) translate(${"left"===t.anchor?"0":"-50%"}, -50%)`}))}dispose(){this.clear(),this.element.remove()}}export function formatLength(t){const e=Math.abs(t);return e<1?`${(100*t).toFixed(e<.1?1:0)} cm`:e<1e4?`${t.toFixed(e<100?2:1)} m`:`${(t/1e3).toFixed(2)} km`}export function formatArea(t){const e=Math.abs(t);return e<1e4?`${t.toFixed(e<100?2:1)} m²`:e<1e6?`${(t/1e4).toFixed(2)} ha`:`${(t/1e6).toFixed(3)} km²`}export function formatAngle(t){return`${t.toFixed(1)}°`}export function formatSlope(t){if(!Number.isFinite(t))return"vertical";return Math.abs(t)<.1?`${(1e3*t).toFixed(1)} ‰`:`${(100*t).toFixed(1)} %`}
|
package/index.d.ts
CHANGED
|
@@ -48,6 +48,7 @@ export * from './layers/TubeLayer';
|
|
|
48
48
|
export * from './layers/SphereLayer';
|
|
49
49
|
export * from './layers/AreaLayer';
|
|
50
50
|
export * from './react/ReactGeometry';
|
|
51
|
+
export * from './theme/Theme';
|
|
51
52
|
export * from './common/Colors';
|
|
52
53
|
export * from './common/Disposables';
|
|
53
54
|
export * from './event/TypedEventEmitter';
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./data/Geometry.js";export*from"./math/Triangulate.js";export*from"./math/Projection.js";export*from"./math/Vector.js";export*from"./math/Measure.js";export*from"./math/Lines.js";export*from"./math/Polygons.js";export*from"./math/Boolean.js";export*from"./math/Transform.js";export*from"./math/Relations.js";export*from"./math/Geodesy.js";export*from"./math/SpatialIndex.js";export*from"./math/FeatureIndex.js";export*from"./engine/GeometryFrame.js";export*from"./engine/GeometryEngine.js";export*from"./engine/GeometryOptions.js";export*from"./engine/GeometryView.js";export*from"./engine/MapCamera.js";export*from"./engine/Labels.js";export*from"./edit/GeometryController.js";export*from"./edit/Snapper.js";export*from"./edit/Sketch.js";export*from"./edit/EditShape.js";export*from"./edit/EditHistory.js";export*from"./edit/CreateController.js";export*from"./edit/EditController.js";export*from"./edit/MeasureController.js";export*from"./three/CanvasGeometryEngine.js";export*from"./three/HostedGeometryEngine.js";export*from"./three/RiaGeometryEngine.js";export*from"./three/FeatureLook.js";export*from"./three/Shading.js";export*from"./three/DensityMap.js";export*from"./three/Halo.js";export*from"./three/Ground.js";export*from"./three/Tsl.js";export*from"./three/primitives/GpuLines.js";export*from"./three/primitives/GpuIcons.js";export*from"./three/primitives/GpuTubes.js";export*from"./three/primitives/GpuSpheres.js";export*from"./three/primitives/GpuAreas.js";export*from"./three/primitives/IconAtlas.js";export*from"./three/primitives/Body.js";export*from"./layers/GeometryLayer.js";export*from"./layers/LineLayer.js";export*from"./layers/PointLayer.js";export*from"./layers/TubeLayer.js";export*from"./layers/SphereLayer.js";export*from"./layers/AreaLayer.js";export*from"./react/ReactGeometry.js";export*from"./common/Colors.js";export*from"./common/Disposables.js";export*from"./event/TypedEventEmitter.js";
|
|
1
|
+
export*from"./data/Geometry.js";export*from"./math/Triangulate.js";export*from"./math/Projection.js";export*from"./math/Vector.js";export*from"./math/Measure.js";export*from"./math/Lines.js";export*from"./math/Polygons.js";export*from"./math/Boolean.js";export*from"./math/Transform.js";export*from"./math/Relations.js";export*from"./math/Geodesy.js";export*from"./math/SpatialIndex.js";export*from"./math/FeatureIndex.js";export*from"./engine/GeometryFrame.js";export*from"./engine/GeometryEngine.js";export*from"./engine/GeometryOptions.js";export*from"./engine/GeometryView.js";export*from"./engine/MapCamera.js";export*from"./engine/Labels.js";export*from"./edit/GeometryController.js";export*from"./edit/Snapper.js";export*from"./edit/Sketch.js";export*from"./edit/EditShape.js";export*from"./edit/EditHistory.js";export*from"./edit/CreateController.js";export*from"./edit/EditController.js";export*from"./edit/MeasureController.js";export*from"./three/CanvasGeometryEngine.js";export*from"./three/HostedGeometryEngine.js";export*from"./three/RiaGeometryEngine.js";export*from"./three/FeatureLook.js";export*from"./three/Shading.js";export*from"./three/DensityMap.js";export*from"./three/Halo.js";export*from"./three/Ground.js";export*from"./three/Tsl.js";export*from"./three/primitives/GpuLines.js";export*from"./three/primitives/GpuIcons.js";export*from"./three/primitives/GpuTubes.js";export*from"./three/primitives/GpuSpheres.js";export*from"./three/primitives/GpuAreas.js";export*from"./three/primitives/IconAtlas.js";export*from"./three/primitives/Body.js";export*from"./layers/GeometryLayer.js";export*from"./layers/LineLayer.js";export*from"./layers/PointLayer.js";export*from"./layers/TubeLayer.js";export*from"./layers/SphereLayer.js";export*from"./layers/AreaLayer.js";export*from"./react/ReactGeometry.js";export*from"./theme/Theme.js";export*from"./common/Colors.js";export*from"./common/Disposables.js";export*from"./event/TypedEventEmitter.js";
|
package/package.json
CHANGED
package/theme/Theme.d.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Protomaze theme: how every @protomaze package - time, charts, geometry, demo-engine - is
|
|
3
|
+
* styled, and how an application gives them its own look.
|
|
4
|
+
*
|
|
5
|
+
* The contract is a set of CSS custom properties, `--pm-*` (THEME_PROPERTIES), read where a
|
|
6
|
+
* package's UI sits. Set them on `:root`, or on any element around a package's UI, and every
|
|
7
|
+
* package follows: its HTML through `var(--pm-…)`, its canvas and GPU drawing through
|
|
8
|
+
* `resolveTheme`, which reads them there, and `watchTheme`, which sees them change. Whatever is left
|
|
9
|
+
* unset keeps Protomaze's own look (PROTOMAZE_DARK, PROTOMAZE_LIGHT).
|
|
10
|
+
*
|
|
11
|
+
* ```css
|
|
12
|
+
* :root {
|
|
13
|
+
* --pm-color-accent: #9AC0A6;
|
|
14
|
+
* --pm-font-family: 'IP Klartext', sans-serif;
|
|
15
|
+
* --pm-radius: 0px;
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* or, from code, `applyTheme({ accent: '#9AC0A6', fontFamily: "'IP Klartext', sans-serif", radius: 0 })`.
|
|
20
|
+
*
|
|
21
|
+
* This file is the same in @protomaze/time, @protomaze/charts and @protomaze/geometry
|
|
22
|
+
* (src/theme/Theme.ts): change them together.
|
|
23
|
+
*/
|
|
24
|
+
/** The two looks every token has a Protomaze default for. */
|
|
25
|
+
export type ColorScheme = 'dark' | 'light';
|
|
26
|
+
/** A package's `theme` option: one of the looks, or 'auto' - the page's `color-scheme`, else the system's. */
|
|
27
|
+
export type ThemeScheme = ColorScheme | 'auto';
|
|
28
|
+
/**
|
|
29
|
+
* The design tokens every package is styled with. Colours are any CSS colour; what a GPU draws
|
|
30
|
+
* should be opaque (a colour with alpha is drawn as its colour, its alpha ignored, where a
|
|
31
|
+
* package says so).
|
|
32
|
+
*/
|
|
33
|
+
export interface ThemeTokens {
|
|
34
|
+
/** Behind what a package draws: a time slider's track, a map's clear colour, a page. */
|
|
35
|
+
background: string;
|
|
36
|
+
/** Panels, menus, dialogs, tooltips: what floats on the background. */
|
|
37
|
+
surface: string;
|
|
38
|
+
/** A step up from the surface: buttons, fields, chips, a hovered row. */
|
|
39
|
+
surfaceRaised: string;
|
|
40
|
+
/** Hairlines: dividers, the borders of fields and panels. */
|
|
41
|
+
border: string;
|
|
42
|
+
/** Text, icons, a chart's labels and lines. */
|
|
43
|
+
text: string;
|
|
44
|
+
/** Secondary text: captions, hints, a lane's name. */
|
|
45
|
+
textMuted: string;
|
|
46
|
+
/** Text that is off: disabled, or a category with nothing in it. */
|
|
47
|
+
textDisabled: string;
|
|
48
|
+
/** Grid lines and ticks behind data. */
|
|
49
|
+
grid: string;
|
|
50
|
+
/** The one active thing: a primary button, the current time, what is being drawn. */
|
|
51
|
+
accent: string;
|
|
52
|
+
/** Text and icons on the accent. */
|
|
53
|
+
onAccent: string;
|
|
54
|
+
/** The outline round hovered or selected data. */
|
|
55
|
+
highlight: string;
|
|
56
|
+
/** The keyboard focus ring. */
|
|
57
|
+
focus: string;
|
|
58
|
+
danger: string;
|
|
59
|
+
success: string;
|
|
60
|
+
warning: string;
|
|
61
|
+
/** The UI's font, as CSS font-family. */
|
|
62
|
+
fontFamily: string;
|
|
63
|
+
/** Times, numbers and code. */
|
|
64
|
+
fontFamilyMono: string;
|
|
65
|
+
/** The UI's text size, px. */
|
|
66
|
+
fontSize: number;
|
|
67
|
+
/** Body text's weight. */
|
|
68
|
+
fontWeight: number;
|
|
69
|
+
/** Headings', buttons' and emphasized text's weight. */
|
|
70
|
+
fontWeightStrong: number;
|
|
71
|
+
/** Corner radius of buttons, fields and panels, px: 0 for square corners. */
|
|
72
|
+
radius: number;
|
|
73
|
+
/** The shadow under what floats: menus, dialogs, bars. CSS box-shadow. */
|
|
74
|
+
shadow: string;
|
|
75
|
+
}
|
|
76
|
+
/** Tokens resolved for one place in the page, with the look they started from. */
|
|
77
|
+
export type ResolvedTheme = ThemeTokens & {
|
|
78
|
+
scheme: ColorScheme;
|
|
79
|
+
};
|
|
80
|
+
/** The CSS custom property of each token. */
|
|
81
|
+
export declare const THEME_PROPERTIES: {
|
|
82
|
+
readonly [K in keyof ThemeTokens]: string;
|
|
83
|
+
};
|
|
84
|
+
/** Protomaze, dark: near black, white text, lime for the one active thing. The default. */
|
|
85
|
+
export declare const PROTOMAZE_DARK: Readonly<ThemeTokens>;
|
|
86
|
+
/**
|
|
87
|
+
* Protomaze, light: near white, black text. Lime does not read on white, so the active thing is
|
|
88
|
+
* a dark lime that does (4.7:1), with white on it.
|
|
89
|
+
*/
|
|
90
|
+
export declare const PROTOMAZE_LIGHT: Readonly<ThemeTokens>;
|
|
91
|
+
/** Protomaze's own tokens for a look. */
|
|
92
|
+
export declare function protomazeTheme(scheme: ColorScheme): Readonly<ThemeTokens>;
|
|
93
|
+
/** Tokens as CSS custom properties: `{ '--pm-color-accent': '#9AC0A6', '--pm-radius': '0px' }`. A React `style` takes it as it is. */
|
|
94
|
+
export declare function themeProperties(tokens: Partial<ThemeTokens>): Record<string, string>;
|
|
95
|
+
/** Tokens as a stylesheet rule, to put in the application's CSS: `:root { --pm-color-accent: #9AC0A6; … }`. */
|
|
96
|
+
export declare function themeCss(tokens: Partial<ThemeTokens>, selector?: string): string;
|
|
97
|
+
/**
|
|
98
|
+
* Sets tokens on an element - the whole page by default - as inline custom properties, so every
|
|
99
|
+
* package inside it follows at once. Gives back an undo that puts the element's own values back.
|
|
100
|
+
*/
|
|
101
|
+
export declare function applyTheme(tokens: Partial<ThemeTokens>, element?: HTMLElement): () => void;
|
|
102
|
+
/**
|
|
103
|
+
* The look a `theme` option means at an element: 'dark' and 'light' as they are; 'auto' the
|
|
104
|
+
* element's `color-scheme` where it names one, else the system's preference; nothing, `fallback`.
|
|
105
|
+
*/
|
|
106
|
+
export declare function resolveScheme(scheme: ThemeScheme | undefined, element?: Element | null, fallback?: ColorScheme): ColorScheme;
|
|
107
|
+
/**
|
|
108
|
+
* The tokens in force at an element: Protomaze's for the look `scheme` means there, then the
|
|
109
|
+
* `--pm-*` properties the page sets around it, then `overrides`. Colours come back as `rgb(…)` or
|
|
110
|
+
* `rgba(…)`, in sRGB, whatever a token is written in - `light-dark()`, `color-mix()`, `oklch()`,
|
|
111
|
+
* `var()` - so a GPU's colour parser reads them all; sizes in px.
|
|
112
|
+
* Without a document, or with the element not in one, Protomaze's tokens with the overrides.
|
|
113
|
+
*/
|
|
114
|
+
export declare function resolveTheme(element: Element | null | undefined, scheme?: ThemeScheme, overrides?: Partial<ThemeTokens>): ResolvedTheme;
|
|
115
|
+
/**
|
|
116
|
+
* Calls `onChange` (once a frame at most) whenever the tokens in force at `element` change: a
|
|
117
|
+
* `--pm-*` property set or changed anywhere above it - a class or stylesheet that switches the
|
|
118
|
+
* application's theme, `applyTheme` - its `color-scheme`, or the system's dark mode. A package
|
|
119
|
+
* then resolves its theme again. Gives back a stop.
|
|
120
|
+
*
|
|
121
|
+
* It watches through a hidden element it puts inside `element`, whose colours and fonts are the
|
|
122
|
+
* tokens', with a one-millisecond transition: the browser starts one whenever a token changes, and
|
|
123
|
+
* says so. An element the package made itself is the one to give, not one React renders.
|
|
124
|
+
*/
|
|
125
|
+
export declare function watchTheme(element: HTMLElement, onChange: () => void): () => void;
|
package/theme/Theme.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const THEME_PROPERTIES={background:"--pm-color-background",surface:"--pm-color-surface",surfaceRaised:"--pm-color-surface-raised",border:"--pm-color-border",text:"--pm-color-text",textMuted:"--pm-color-text-muted",textDisabled:"--pm-color-text-disabled",grid:"--pm-color-grid",accent:"--pm-color-accent",onAccent:"--pm-color-on-accent",highlight:"--pm-color-highlight",focus:"--pm-color-focus",danger:"--pm-color-danger",success:"--pm-color-success",warning:"--pm-color-warning",fontFamily:"--pm-font-family",fontFamilyMono:"--pm-font-family-mono",fontSize:"--pm-font-size",fontWeight:"--pm-font-weight",fontWeightStrong:"--pm-font-weight-strong",radius:"--pm-radius",shadow:"--pm-shadow"};const e=Object.keys(THEME_PROPERTIES),t=e.filter(e=>"shadow"!==e&&!e.startsWith("font")&&"radius"!==e),o=["fontSize","radius"];export const PROTOMAZE_DARK=Object.freeze({background:"#121212",surface:"#1E1E1E",surfaceRaised:"#2A2A2A",border:"#333333",text:"#FFFFFF",textMuted:"#B8B8B8",textDisabled:"#6C6C6C",grid:"#474747",accent:"#D9FF00",onAccent:"#000000",highlight:"#FFFFFF",focus:"#D9FF00",danger:"#FF6B6B",success:"#3ECF8E",warning:"#FFB300",fontFamily:"Arial, Roboto, Helvetica, sans-serif",fontFamilyMono:'ui-monospace, Menlo, Consolas, "Cascadia Mono", monospace',fontSize:12,fontWeight:400,fontWeightStrong:600,radius:6,shadow:"0 10px 40px rgba(0, 0, 0, 0.45)"});export const PROTOMAZE_LIGHT=Object.freeze({background:"#F5F5F5",surface:"#FFFFFF",surfaceRaised:"#EBEBEB",border:"#D6D6D6",text:"#121212",textMuted:"#5C5C5C",textDisabled:"#9E9E9E",grid:"#C8C8C8",accent:"#5A7D00",onAccent:"#FFFFFF",highlight:"#121212",focus:"#5A7D00",danger:"#D32F2F",success:"#1E8E5A",warning:"#B26A00",fontFamily:"Arial, Roboto, Helvetica, sans-serif",fontFamilyMono:'ui-monospace, Menlo, Consolas, "Cascadia Mono", monospace',fontSize:12,fontWeight:400,fontWeightStrong:600,radius:6,shadow:"0 10px 40px rgba(0, 0, 0, 0.18)"});export function protomazeTheme(e){return"light"===e?PROTOMAZE_LIGHT:PROTOMAZE_DARK}export function themeProperties(t){const n={};for(const r of e){const e=t[r];null!=e&&""!==e&&(n[THEME_PROPERTIES[r]]="number"==typeof e&&o.includes(r)?`${e}px`:String(e))}return n}export function themeCss(e,t=":root"){return`${t} {\n${Object.entries(themeProperties(e)).map(([e,t])=>` ${e}: ${t};`).join("\n")}\n}`}export function applyTheme(e,t){const o=t??("undefined"!=typeof document?document.documentElement:void 0);if(!o)return()=>{};const n=new Map;for(const[t,r]of Object.entries(themeProperties(e)))n.set(t,o.style.getPropertyValue(t)),o.style.setProperty(t,r);return()=>n.forEach((e,t)=>e?o.style.setProperty(t,e):o.style.removeProperty(t))}function n(e){const t=e?.ownerDocument?.defaultView;return t||("undefined"!=typeof window?window:void 0)}export function resolveScheme(e,t,o="dark"){if("dark"===e||"light"===e)return e;if("auto"!==e)return o;const r=n(t);if(!r)return o;if(t?.isConnected){const e=(r.getComputedStyle(t).colorScheme||"").split(/\s+/),o=e.includes("dark");if(o!==e.includes("light"))return o?"dark":"light"}const i=r.matchMedia?.("(prefers-color-scheme: dark)");return i?i.matches?"dark":"light":o}export function resolveTheme(t,o="dark",r){const a=resolveScheme(o,t),c={...protomazeTheme(a),scheme:a},l=n(t);if(t?.isConnected&&l){const o=l.getComputedStyle(t);let n;for(const r of e){const e=o.getPropertyValue(THEME_PROPERTIES[r]).trim();if(!e)continue;n??(n=i(t));const a=s(r,e,n,l);void 0!==a&&(c[r]=a)}n?.remove()}if(r)for(const t of e){const e=r[t];null!=e&&""!==e&&(c[t]=e)}return c}const r="position:absolute;left:0;top:0;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;";function i(e){const t=e.ownerDocument.createElement("span");return t.setAttribute("aria-hidden","true"),t.style.cssText=r,e.appendChild(t),t}function s(e,o,n,r){if(t.includes(e)){if(n.style.color="",n.style.color=o,!n.style.color)return;const e=r.getComputedStyle(n).color;return e?function(e,t){if(/^rgba?\(/i.test(e))return e;if(a??(a=t.createElement("canvas").getContext("2d",{willReadFrequently:!0})),!a)return e;a.clearRect(0,0,1,1),a.fillStyle="#000",a.fillStyle=e,a.fillRect(0,0,1,1);const[o,n,r,i]=a.getImageData(0,0,1,1).data;return 255===i?`rgb(${o}, ${n}, ${r})`:`rgba(${o}, ${n}, ${r}, ${Math.round(i/255*1e3)/1e3})`}(e,n.ownerDocument):void 0}if("fontSize"===e){if(n.style.fontSize="",n.style.fontSize=o,!n.style.fontSize)return;const e=parseFloat(r.getComputedStyle(n).fontSize);return Number.isFinite(e)?e:void 0}if("radius"===e){if(n.style.borderTopLeftRadius="",n.style.borderTopLeftRadius=o,!n.style.borderTopLeftRadius)return;const e=parseFloat(r.getComputedStyle(n).borderTopLeftRadius);return Number.isFinite(e)?e:void 0}if("fontWeight"===e||"fontWeightStrong"===e){if(n.style.fontWeight="",n.style.fontWeight=o,!n.style.fontWeight)return;const e=parseFloat(r.getComputedStyle(n).fontWeight);return Number.isFinite(e)?e:void 0}return o}let a;function c(t,o){if(!t.isConnected)return"";const n=o.getComputedStyle(t),r=o.matchMedia?.("(prefers-color-scheme: dark)").matches;return e.map(e=>n.getPropertyValue(THEME_PROPERTIES[e]).trim()).join("|")+`|${n.colorScheme}|${r}`}export function watchTheme(e,o){const i=n(e);if(!i||"function"!=typeof i.requestAnimationFrame)return()=>{};let s=c(e,i),a=0;const l=()=>{if(a=0,!e.isConnected)return;const t=c(e,i);t!==s&&(s=t,o())},f=()=>{a||(a=i.requestAnimationFrame(l))},d=e.ownerDocument,u=d.createElement("span");u.setAttribute("aria-hidden","true"),u.dataset.pmThemeWatch="",u.style.cssText=r;const m=e=>{const t=d.createElement("span");t.style.cssText=e,u.appendChild(t)},p=(e,t)=>`var(${THEME_PROPERTIES[e]}, ${t})`;for(const e of t)m(`color:${p(e,"rgba(1, 2, 3, 0.004)")};transition:color 1ms;`);m(`font-family:${p("fontFamily","pm-unset")};font-size:${p("fontSize","1234px")};font-weight:${p("fontWeight","1")};border-top-left-radius:${p("radius","1234px")};box-shadow:${p("shadow","1px 2px 3px 4px rgb(1, 2, 3)")};transition:all 1ms;transition-behavior:allow-discrete;`),m(`font-family:${p("fontFamilyMono","pm-unset")};font-weight:${p("fontWeightStrong","1")};color-scheme:inherit;transition:all 1ms;transition-behavior:allow-discrete;`);const h=e=>e.stopPropagation(),g=["transitionrun","transitionstart","transitionend","transitioncancel"];g.forEach(e=>u.addEventListener(e,h)),u.addEventListener("transitionrun",f),e.appendChild(u);const F=i.matchMedia?.("(prefers-color-scheme: dark)");F?.addEventListener?.("change",f);const y="function"==typeof i.ResizeObserver?new i.ResizeObserver(f):void 0;return y?.observe(e),()=>{a&&i.cancelAnimationFrame(a),u.removeEventListener("transitionrun",f),g.forEach(e=>u.removeEventListener(e,h)),u.remove(),F?.removeEventListener?.("change",f),y?.disconnect()}}
|
|
@@ -8,7 +8,7 @@ export interface CanvasGeometryEngineOptions {
|
|
|
8
8
|
antialias?: boolean;
|
|
9
9
|
/** Draw with WebGL 2 even where WebGPU is there. */
|
|
10
10
|
forceWebGL?: boolean;
|
|
11
|
-
/** The colour under everything. */
|
|
11
|
+
/** The colour under everything: Protomaze's dark background by default. A view sets its theme's. */
|
|
12
12
|
background?: string;
|
|
13
13
|
/** The most frame pixels per view pixel drawn: 2 keeps a 4K screen cheap. */
|
|
14
14
|
maxPixelRatio?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DepthTexture as e,FloatType as t,Mesh as i,NearestFilter as s,PlaneGeometry as a,RenderTarget as h,Scene as r,Vector2 as n,WebGPURenderer as
|
|
1
|
+
import{DepthTexture as e,FloatType as t,Mesh as i,NearestFilter as s,PlaneGeometry as a,RenderTarget as h,Scene as r,Vector2 as n,WebGPURenderer as o}from"three/webgpu";import{Fn as d,ivec2 as c,positionGeometry as l,screenCoordinate as m,textureLoad as u,vec4 as g}from"three/tsl";import{GeometryEngine as b}from"../engine/GeometryEngine.js";import{Sky as p}from"./Sky.js";import{disposeMaterial as w,nodeMaterial as f,rawColor as y,unculled as z}from"./Tsl.js";import{PROTOMAZE_DARK as x}from"../theme/Theme.js";export class CanvasGeometryEngine extends b{constructor(e={}){super(),this.options=e,this.baseScene=new r,this.sky=new p,this.blitScene=new r,this.blit=null,this.camera3d=null,this.scheduled=0,this.animators=new Set,this.size={width:1,height:1,ratio:1},this.background=y(x.background),this.initialising=null,this.drewBase=!1,this.bufferSize=new n,this.baseDrawn=!1,this.canvas=document.createElement("canvas"),this.canvas.style.display="block",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.touchAction="none",e.background&&y(e.background,this.background),this.baseScene.add(this.sky.mesh)}createDepthTexture(){const i=new e(1,1,t);return i.minFilter=s,i.magFilter=s,this.baseTarget=new h(1,1,{depthBuffer:!0,generateMipmaps:!1}),this.baseTarget.depthTexture=i,i}init(){return this.initialising??(this.initialising=this.start()),this.initialising}async start(){const e=new o({canvas:this.canvas,antialias:!1!==this.options.antialias,alpha:!1,forceWebGL:!!this.options.forceWebGL});e.setPixelRatio(1),e.info.autoReset=!1,this.adoptRenderer(e),await e.init(),this.disposed||(this.blit=z(new i(new a(2,2),this.blitMaterial())),this.blitScene.add(this.blit),this.ready=!0,this.emit("ready"),this.requestRepaint())}setCamera(e){this.camera3d=e,this.requestRepaint()}setBackground(e){y(e,this.background),this.requestRepaint()}setSize(e,t,i=window.devicePixelRatio||1){const s=Math.min(i,this.options.maxPixelRatio??2);this.size={width:Math.max(1,e),height:Math.max(1,t),ratio:s},this.requestRepaint()}get frameSize(){return{width:Math.max(1,Math.round(this.size.width*this.size.ratio)),height:Math.max(1,Math.round(this.size.height*this.size.ratio))}}get viewSize(){return{width:this.size.width,height:this.size.height,pixelRatio:this.size.ratio}}setAnimating(e,t){t?this.animators.add(e):this.animators.delete(e),t&&this.requestRepaint()}requestRepaint(){this.scheduled||this.disposed||(this.scheduled=requestAnimationFrame(()=>{this.scheduled=0,this.draw(),this.animators.size>0&&this.requestRepaint()}))}draw(){const e=this.renderer;if(!this.ready||!e||!this.camera3d)return;const{width:t,height:i}=this.frameSize,s=e.getDrawingBufferSize(this.bufferSize);s.x===t&&s.y===i||e.setSize(t,i,!1),e.info.reset();const a={...this.camera3d(t,i),width:t,height:i,pixelRatio:this.size.ratio,glDepth:!0},h=this.baseScene.children.some(e=>e.visible);!h||this.baseTarget.width===t&&this.baseTarget.height===i||this.baseTarget.setSize(t,i),this.drewBase=!1;this.renderFrame(a,()=>(this.drawBase(h,e),!0))||this.drawBase(h,e)}drawBase(e,t){if(this.drewBase)return;this.drewBase=!0,t.setClearColor(this.background,1),this.sky.eye.value.copy(this.frame.eye),this.sky.mesh.visible=!this.frame.orthographic,e&&(t.setRenderTarget(this.baseTarget),t.clear(!0,!0,!0),t.render(this.baseScene,this.camera)),t.setRenderTarget(null);const i=t.backend;!this.webgpu&&i?.gl&&i.state?.bindFramebuffer&&i.state.bindFramebuffer(i.gl.FRAMEBUFFER,null),t.clear(!0,!0,!0),e&&this.blit&&t.render(this.blitScene,this.camera),this.baseDrawn=e}depthReady(){return!this.frame.orthographic}dispose(){this.scheduled&&cancelAnimationFrame(this.scheduled),this.scheduled=0,this.animators.clear(),this.baseTarget.dispose(),this.blit&&(this.blit.geometry.dispose(),w(this.blit)),this.sky.dispose(),super.dispose(),this.canvas.remove()}blitMaterial(){const e=f();e.depthTest=!1,e.depthWrite=!1;const t=this.baseTarget.texture;return e.vertexNode=d(()=>g(l.xy,0,1))(),e.fragmentNode=d(()=>u(t,c(m.xy)))(),e}get hasBase(){return this.baseDrawn}}
|
package/three/Ground.d.ts
CHANGED
|
@@ -45,6 +45,11 @@ export declare class Ground {
|
|
|
45
45
|
eye?: N;
|
|
46
46
|
fog?: N;
|
|
47
47
|
});
|
|
48
|
+
/** The ground's colour and its grid's, as CSS colours: a view's theme, changed while it is drawn. */
|
|
49
|
+
setColors(colors: {
|
|
50
|
+
color?: string;
|
|
51
|
+
grid?: string;
|
|
52
|
+
}): void;
|
|
48
53
|
/** Tells the ground the picture changed (a canvas drawn again). */
|
|
49
54
|
refresh(): void;
|
|
50
55
|
/** Fog for a camera this far from what it looks at. */
|
package/three/Ground.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CanvasTexture as t,ClampToEdgeWrapping as e,LinearFilter as i,LinearMipmapLinearFilter as s,Mesh as r,NoColorSpace as o,PlaneGeometry as h,TextureLoader as a,Vector3 as
|
|
1
|
+
import{CanvasTexture as t,ClampToEdgeWrapping as e,LinearFilter as i,LinearMipmapLinearFilter as s,Mesh as r,NoColorSpace as o,PlaneGeometry as h,TextureLoader as a,Vector3 as l}from"three/webgpu";import{abs as u,clamp as d,float as g,Fn as n,fract as c,fwidth as m,length as p,max as f,min as x,mix as y,positionLocal as v,smoothstep as w,texture as b,uniform as C,vec2 as O,vec4 as F}from"three/tsl";import{disposeMaterial as M,nodeMaterial as N,rawColor as j}from"./Tsl.js";export class Ground{constructor(u,d,g){this.options=u,this.texture=null,this.color=C(j("#14181d")),this.gridColor=C(new l(1,1,1)),this.gridOpacity=C(.06),this.fogNear=C(1500),this.fogFar=C(9e3),this.offset=C(new l);const[n,c,m,p]=u.bounds,f=Math.max(1,m-n),x=Math.max(1,p-c);if(this.eye=g?.eye??C(new l),this.fogColor=g?.fog??C(j("#18222f")),u.color&&j(u.color,this.color.value),u.grid&&u.grid.color){const t=j(u.grid.color);this.gridColor.value.set(t.r,t.g,t.b)}u.grid&&void 0!==u.grid.opacity&&(this.gridOpacity.value=u.grid.opacity),u.image&&(this.texture="string"==typeof u.image?(new a).load(u.image):new t(u.image),this.texture.colorSpace=o,this.texture.wrapS=this.texture.wrapT=e,this.texture.minFilter=s,this.texture.magFilter=i,this.texture.anisotropy=8),this.offset.value.set((n+m)/2-d[0],(c+p)/2-d[1],(u.z??0)-(d[2]??0));const y=u.margin??Math.max(2e4,8*Math.max(f,x)),v=[f+2*y,x+2*y];this.mesh=new r(new h(v[0],v[1]),this.material(f,x,v[0],v[1])),this.mesh.position.copy(this.offset.value),this.mesh.frustumCulled=!1,this.mesh.renderOrder=-1e3}setColors(t){if(t.color&&j(t.color,this.color.value),t.grid){const e=j(t.grid);this.gridColor.value.set(e.r,e.g,e.b)}}refresh(){this.texture&&(this.texture.needsUpdate=!0)}setViewDistance(t){this.fogNear.value=1.4*t+600,this.fogFar.value=7*t+4e3}dispose(){this.mesh.geometry.dispose(),M(this.mesh),this.texture?.dispose()}material(t,e,i,s){const r=N();r.transparent=!0,r.depthWrite=!0;const o=this.options,h=o.grid,a=this.texture;return r.colorNode=n(()=>{const r=v.xy;let l=this.color;if(a){const i=r.div(O(t,e)).add(.5),s=x(x(i.x,g(1).sub(i.x)),x(i.y,g(1).sub(i.y))),h=w(0,.03,s),u=b(a,d(i,0,1));l=y(l,u.xyz,u.w.mul(o.imageOpacity??1).mul(h))}if(h){const t=t=>{const e=r.div(t),i=u(c(e.sub(.5)).sub(.5)).div(m(e));return g(1).sub(x(x(i.x,i.y),g(1)))},e=t(h.spacing),i=t(h.spacing*(h.major??10)),s=f(e.mul(this.gridOpacity),i.mul(this.gridOpacity.mul(2.2)));l=y(l,this.gridColor,d(s,0,1))}const n=p(v.add(this.offset).sub(this.eye));l=y(l,this.fogColor,w(this.fogNear,this.fogFar,n));const C=O(i/2,s/2),M=C.sub(u(r)),N=w(0,1,x(M.x.div(C.x),M.y.div(C.y)).mul(8));return F(l,d(N,0,1))})(),r}}
|