@kineviz/gl 0.7.0 → 0.8.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.
@@ -0,0 +1,2875 @@
1
+ import{createContext as et}from"react";var W=et(null);import{useContext as ee,useState as te,useEffect as ne,useCallback as j,useSyncExternalStore as $}from"react";function re(t){return t._viewState}function S(){let t=ee(W);if(!t)throw new Error("useGraphHandle must be used within a GraphRenderer");return t}function y(t){let n=re(S()),e=j(()=>n.getSnapshot()[t],[n,t]);return $(n.subscribe,e,e)}function oe(){return y("isMapMode")}function mn(){return y("mapDamping")}function ae(){return y("mapSphereRadius")}function vn(){return y("theme")}function xn(){return y("effectiveMapProjection")}function bn(){return{textScale:y("textScale"),edgeTextScale:y("edgeTextScale")}}function ie(){return{iconAtlasManager:y("iconAtlasManager"),imageAtlasManager:y("imageAtlasManager"),glyphAtlasManager:y("glyphAtlasManager")}}function yn(){return y("layoutController")}function Sn(){return y("layoutPositionProvider")}function wn(){let t=ee(W);if(!t)throw new Error("useGraph must be used within a GraphRenderer");let n=re(t);return $(n.subscribe,n.getSnapshot,n.getSnapshot),t}function Pn(){let{store:t}=S();return t}function se(){let{store:t}=S(),[n,e]=te(t.version);return ne(()=>{let r=t.subscribeVersionChanged(()=>{e(t.version)});return e(t.version),r},[t]),n}function Cn(t){let{store:n}=S(),e=j(o=>n.changes.subscribe(t,o),[n,t]),r=j(()=>n.changes.versionOf(t),[n,t]);return $(e,r,r)}function Tn(){let{store:t}=S(),[n,e]=te(t.iconVersion);return ne(()=>{let r=t.subscribeIconVersionChanged(()=>{e(t.iconVersion)});return e(t.iconVersion),r},[t]),n}function Rn(){let{scene:t}=S();return t}function kn(){let{camera:t}=S();return t}function zn(){let{cloudScene:t}=S();return t}function _n(){let{interaction:t}=S();return t}function Mn(){let t=S();return{is3D:y("is3D"),setIs3D:t.setIs3D}}import{createContext as tt,useContext as le}from"react";var ce=tt(null);function Fn(){let t=le(ce);if(!t)throw new Error("useRenderEngineApi must be used within <GraphRenderer>");return t}function En(){return le(ce)}import{Box3 as ut,Mesh as ft,MeshBasicMaterial as gt,PlaneGeometry as mt}from"three";import{Camera as nt,Frustum as rt,Group as ot,Matrix4 as at,PerspectiveCamera as it,SRGBColorSpace as st,Texture as lt,Vector3 as ct}from"three";var pe=1.3,he=160,dt=256,ue=2,pt=4e3,de=22;function I(t,n,e){return(t*4194304+n)*32+e}var ht=async(t,n)=>{if(typeof fetch=="function"&&typeof createImageBitmap=="function"){let e=await fetch(t,{signal:n,mode:"cors",credentials:"omit"});if(!e.ok)throw new Error(`tile ${e.status}`);let r=await e.blob();return createImageBitmap(r,{imageOrientation:"flipY"})}return new Promise((e,r)=>{let o=new Image;o.crossOrigin="anonymous",o.onload=()=>e(o),o.onerror=()=>r(new Error("tile load failed")),n.addEventListener("abort",()=>{o.src="",r(new Error("aborted"))}),o.src=t})},q=()=>typeof performance<"u"?performance.now():Date.now(),O=class extends ot{constructor(e,r){super();this._tiles=new Map;this._fading=new Set;this._inFlight=0;this._serial=0;this._changed=!0;this._lastView=new Float64Array(17);this._m=new at;this._frustum=new rt;this._cam=new ct;this._stack=[];this._wanted=[];this._queue=[];this._shown=new Set;this._measuredDist=0;this.minLevel=e.minLevel??0,this.maxLevel=Math.min(de,e.maxLevel??r),this.tileSize=e.tileSize??256,this.maxConcurrent=e.maxConcurrent??8,this.cacheSize=e.cacheSize??400,this._loadImage=e.loadImage??ht,this._anisotropy=e.anisotropy??8,this._tileUrl=e.tileUrl}_prepare(e){}_disposeMesh(e){}get tileUrl(){return this._tileUrl}set tileUrl(e){e!==this._tileUrl&&(this._tileUrl=e,this.clearTiles())}setSource(e){let r=e.tileSize??this.tileSize,o=Math.min(de,e.maxLevel??this.maxLevel);e.tileUrl===this._tileUrl&&r===this.tileSize&&o===this.maxLevel||(this._tileUrl=e.tileUrl,this.tileSize=r,this.maxLevel=o,this.clearTiles())}get level(){return this._level??0}setInvalidate(e){this._invalidate=e}updatePov(e,r){if(!e||!(e instanceof nt))return!1;let o=q();if(this._advanceFades(o)&&(this._changed=!0),!this._tileUrl)return this._fading.size>0;e.updateMatrixWorld(),this.updateWorldMatrix(!0,!1);let a=this._m.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse).multiply(this.matrixWorld),s=r?.bufferHeight??800,i=this._lastView,l=!this._changed&&i[16]===s;for(let g=0;l&&g<16;g++)l=i[g]===a.elements[g];if(l)return this._fading.size>0;for(let g=0;g<16;g++)i[g]=a.elements[g];i[16]=s,this._changed=!1,this._frustum.setFromProjectionMatrix(a);let d=this._cam.setFromMatrixPosition(e.matrixWorld);this._m.copy(this.matrixWorld).invert(),d.applyMatrix4(this._m);let p=e instanceof it?e.fov:42,h=s/(2*Math.tan(p*Math.PI/360));this._serial+=1,this._prepare(d);let u=this._cover(d,h);return this._show(u,o),this._request(this._withBackstops(u)),this._evict(),this._fading.size>0}clearTiles(){for(let e of this._tiles.values())this._free(e);this._tiles.clear(),this._fading.clear(),this._inFlight=0,this._changed=!0}dispose(){this.clearTiles()}stats(){let e=0,r=0,o=0;for(let a of this._tiles.values())a.state==="loaded"&&e++,a.state==="loading"&&r++,a.mesh?.visible&&o++;return{loaded:e,loading:r,shown:o,total:this._tiles.size}}_tile(e,r,o){let a=I(e,r,o),s=this._tiles.get(a);return s||(s={key:a,x:e,y:r,z:o,state:"idle",mesh:null,abort:null,used:0,dist:0,failedAt:-1/0,fadeStart:0},this._tiles.set(a,s)),s}_cover(e,r){let o=this._wanted;o.length=0;let a=this._stack;a.length=0,a.push(0,0,0);let s=0;for(;a.length>0;){let i=a.pop(),l=a.pop(),d=a.pop(),p=this._measure(d,l,i,e,r);if(p<0)continue;if(i<this.maxLevel&&(i<this.minLevel||p>this.tileSize*pe)&&o.length+a.length/3<dt){let g=i+1,w=d*2,x=l*2;a.push(w,x,g,w+1,x,g,w,x+1,g,w+1,x+1,g);continue}let u=this._tile(d,l,i);u.dist=this._measuredDist,u.used=this._serial,o.push(u),i>s&&(s=i)}return this._level=s,o.sort((i,l)=>i.dist-l.dist),o}_withBackstops(e){let r=this._queue;r.length=0;let o=Math.min(ue,this.maxLevel);for(let a of e){if(a.z<=o)continue;let s=a.z-o,i=this._tile(a.x>>s,a.y>>s,o);i.used!==this._serial&&(i.used=this._serial,r.push(i))}for(let a of e)r.push(a);return r}_show(e,r){let o=this._shown;o.clear();for(let a of e){if(a.state==="loaded"&&(o.add(a),a.fadeStart!==0&&!this._fading.has(a)))continue;let s=a.x,i=a.y;for(let l=a.z-1;l>=0;l--){s>>=1,i>>=1;let d=this._tiles.get(I(s,i,l));if(d?.state==="loaded"){d.used=this._serial,o.add(d);break}}for(let l=0;l<4;l++){let d=this._tiles.get(I(a.x*2+(l&1),a.y*2+(l>>1),a.z+1));d?.state==="loaded"&&(d.used=this._serial,o.add(d))}}for(let a of this._tiles.values()){if(!a.mesh)continue;let s=o.has(a);s&&!a.mesh.visible&&a.fadeStart===0&&(a.fadeStart=r,this._setOpacity(a,0),this._fading.add(a)),a.mesh.visible=s}}_request(e){for(let o of this._tiles.values())o.state==="loading"&&o.used!==this._serial&&(o.abort?.abort(),o.abort=null,o.state="idle",this._inFlight--);let r=q();for(let o of e){if(this._inFlight>=this.maxConcurrent)break;(o.state==="idle"||o.state==="error"&&r-o.failedAt>pt)&&this._load(o)}}_load(e){let r=this._tileUrl;if(!r)return;let o=new AbortController;e.abort=o,e.state="loading",this._inFlight++;let a=()=>e.abort!==o||this._tiles.get(e.key)!==e?!1:(e.abort=null,this._inFlight--,this._changed=!0,!0);Promise.resolve(r(e.x,e.y,e.z)).then(s=>this._loadImage(s,o.signal)).then(s=>{if(!a()){s.close?.();return}let i=new lt(s);i.flipY=!(typeof ImageBitmap<"u"&&s instanceof ImageBitmap),i.colorSpace=st,i.anisotropy=this._anisotropy,i.needsUpdate=!0;let l=this._createMesh(e,i);l.visible=!1,e.mesh=l,e.state="loaded",e.fadeStart=0,this.add(l),this._invalidate?.()},()=>{a()&&(e.state="error",e.failedAt=q(),this._invalidate?.())})}_advanceFades(e){let r=!1;for(let o of this._fading){let a=Math.min(1,(e-o.fadeStart)/he);this._setOpacity(o,a),a>=1&&(this._fading.delete(o),r=!0)}return r}_setOpacity(e,r){let o=e.mesh?.material;if(!o)return;let a=r<1;o.transparent!==a&&(o.transparent=a,o.needsUpdate=!0),o.opacity=r}_evict(){let e=this._tiles.size-this.cacheSize;if(e<=0)return;let r=[];for(let o of this._tiles.values())o.used!==this._serial&&o.state!=="loading"&&r.push(o);r.sort((o,a)=>o.used-a.used);for(let o=0;o<e&&o<r.length;o++)this._free(r[o]),this._tiles.delete(r[o].key)}_free(e){e.abort&&(e.abort.abort(),e.abort=null,this._inFlight--),this._fading.delete(e);let r=e.mesh;if(!r)return;this.remove(r);let o=r.material,a=o.map?.image;o.map?.dispose(),o.dispose(),a?.close?.(),this._disposeMesh(r),e.mesh=null}};var fe=256,ge=800,me=21*(Math.PI/180),ve=class extends O{constructor(e,r={}){super(r,17);this._geometry=new mt(1,1);this._box=new ut;this._mapSize=e}get mapSize(){return this._mapSize}latLngToWorld(e,r){let o=(r+180)/360,a=Math.max(-1.484,Math.min(1.484,e*Math.PI/180)),s=(1-Math.log(Math.tan(a)+1/Math.cos(a))/Math.PI)/2;return{x:(o-.5)*this._mapSize,y:(.5-s)*this._mapSize}}snapViewDistToIntegerLevel(e){let r=Math.max(1e-4,e),o=ge/(2*Math.tan(me)*r),a=Math.log2(this._mapSize*o/fe),s=Math.min(this.maxLevel,Math.max(this.minLevel,Math.round(a)));return this._mapSize*ge/(2*Math.tan(me)*fe*Math.pow(2,s))}dispose(){super.dispose(),this._geometry.dispose()}_measure(e,r,o,a,s){let i=this._mapSize/2,l=this._mapSize/2**o,d=-i+e*l,p=d+l,h=i-r*l,u=h-l;if(this._box.min.set(d,u,-1e-6),this._box.max.set(p,h,1e-6),!this._frustum.intersectsBox(this._box))return-1;let g=Math.min(Math.max(a.x,d),p)-a.x,w=Math.min(Math.max(a.y,u),h)-a.y,x=Math.max(1e-9,Math.hypot(g,w,a.z));return this._measuredDist=x,l*s/x}_createMesh(e,r){let o=this._mapSize/2**e.z,a=new ft(this._geometry,new gt({map:r,depthWrite:!1,depthTest:!1}));return a.scale.set(o,o,1),a.position.set(-this._mapSize/2+(e.x+.5)*o,this._mapSize/2-(e.y+.5)*o,0),a.renderOrder=-100+e.z,a.matrixAutoUpdate=!1,a.updateMatrix(),a}};var L=null,xe=null;function vt(){return xe??(xe=import("./world-rings-6GQ4OWZC.mjs").then(t=>{L=(t.default??t).rings})),xe}function xt(t={}){let n=t.ocean??"#0b1a2e",e=t.land??"#1c3147",r=t.border??"#315a80",o=t.grid??"#1a3a55",a=t.gridStepDeg??15,s=new Map,i=(l,d,p,h)=>{let u=`${p}/${l}/${d}`,g=s.get(u);if(g)return g;let w=2**p,x=v=>(v+180)/360*w*256-l*256,_=v=>{let b=Math.max(-85,Math.min(85,v));return(1-Math.log(Math.tan(Math.PI/4+b*Math.PI/360))/Math.PI)/2*w*256-d*256},P=document.createElement("canvas");P.width=256,P.height=256;let f=P.getContext("2d");f.fillStyle=n,f.fillRect(0,0,256,256),f.fillStyle=e,f.lineJoin="round";let H=r!=="";H&&(f.strokeStyle=r,f.lineWidth=.5);for(let v of h){f.beginPath();for(let b=0;b<v.length;b+=2){let B=x(v[b]),J=_(v[b+1]);b===0?f.moveTo(B,J):f.lineTo(B,J)}f.closePath(),f.fill(),H&&f.stroke()}if(o!==""&&a>0){f.strokeStyle=o,f.lineWidth=.4;for(let v=-180;v<=180;v+=a){let b=x(v);f.beginPath(),f.moveTo(b,0),f.lineTo(b,256),f.stroke()}for(let v=-75;v<=75;v+=a){let b=_(v);f.beginPath(),f.moveTo(0,b),f.lineTo(256,b),f.stroke()}}let M=P.toDataURL();return s.set(u,M),M};return(l,d,p)=>L?i(l,d,p,L):vt().then(()=>i(l,d,p,L))}var be=xt();function C(t){let n=["a","b","c"];return n[Math.abs(t)%n.length]}var bt=(t,n,e)=>`https://${C(t)}.basemaps.cartocdn.com/dark_all/${e}/${t}/${n}.png`,yt=(t,n,e)=>`https://${C(t)}.basemaps.cartocdn.com/dark_nolabels/${e}/${t}/${n}.png`,St=(t,n,e)=>`https://${C(t)}.basemaps.cartocdn.com/dark_nolabels/${e}/${t}/${n}@2x.png`,wt=(t,n,e)=>`https://${C(t)}.basemaps.cartocdn.com/light_all/${e}/${t}/${n}.png`,Pt=(t,n,e)=>`https://${C(t)}.basemaps.cartocdn.com/light_nolabels/${e}/${t}/${n}.png`,Ct=(t,n,e)=>`https://${C(t)}.basemaps.cartocdn.com/rastertiles/voyager/${e}/${t}/${n}.png`,Tt=(t,n,e)=>`https://${C(t)}.tile.openstreetmap.org/${e}/${t}/${n}.png`,Rt=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=s&x=${t}&y=${n}&z=${e}`,kt=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=s&x=${t}&y=${n}&z=${e}&scale=2`,zt=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=y&x=${t}&y=${n}&z=${e}`,_t=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=y&x=${t}&y=${n}&z=${e}&scale=2`,Mt=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=m&x=${t}&y=${n}&z=${e}`,Dt=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=m&x=${t}&y=${n}&z=${e}&scale=2`,At=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=p&x=${t}&y=${n}&z=${e}`,Ft=(t,n,e)=>`https://mt${Math.abs(t)%4}.google.com/vt/lyrs=p&x=${t}&y=${n}&z=${e}&scale=2`,Et=(t,n,e)=>`https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/${e}/${n}/${t}`,It=(t,n,e)=>`https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/${e}/${n}/${t}`,Ot=(t,n,e)=>`https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/${e}/${n}/${t}`,Lt=(t,n,e)=>`https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/${e}/${n}/${t}`,Nt=(t,n,e)=>`https://tiles.stadiamaps.com/tiles/stamen_toner/${e}/${t}/${n}.png`,Gt=(t,n,e)=>`https://tiles.stadiamaps.com/tiles/stamen_watercolor/${e}/${t}/${n}.jpg`,Vt=(t,n,e)=>`https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/${e}/${t}/${n}.png`;function Ut(t){return(n,e,r)=>`https://api.mapbox.com/styles/v1/mapbox/streets-v12/tiles/${r}/${n}/${e}?access_token=${t}`}function Ht(t){return(n,e,r)=>`https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/${r}/${n}/${e}?access_token=${t}`}function Bt(t){return(n,e,r)=>`https://api.mapbox.com/styles/v1/mapbox/dark-v11/tiles/${r}/${n}/${e}?access_token=${t}`}var K={cartoDark:bt,cartoDarkNoLabels:yt,cartoDarkNoLabelsRetina:St,cartoLight:wt,cartoLightNoLabels:Pt,cartoVoyager:Ct,openStreetMap:Tt,googleSatellite:Rt,googleHybrid:zt,googleRoads:Mt,googleTerrain:At,vectorDark:be,esriDarkGray:It,esriLightGray:Ot,esriWorldImagery:Et,esriWorldTopo:Lt,stamenToner:Nt,stamenWatercolor:Gt,stadiaAlidadeDark:Vt,mapboxStreets:Ut,mapboxSatellite:Ht,mapboxDark:Bt},R=" (needs a Carto API key)",Wt={cartoDark:{name:"Carto Dark",description:"Dark basemap for data visualization"+R,requiresKey:!0},cartoDarkNoLabels:{name:"Carto Dark (no labels)",description:"Dark basemap without baked-in text"+R,requiresKey:!0},cartoDarkNoLabelsRetina:{name:"Carto Dark (no labels, HD)",description:"Dark no-labels basemap at @2x"+R,requiresKey:!0},cartoLight:{name:"Carto Light",description:"Light basemap"+R,requiresKey:!0},cartoLightNoLabels:{name:"Carto Light (no labels)",description:"Light basemap without baked-in text"+R,requiresKey:!0},cartoVoyager:{name:"Carto Voyager",description:"Colorful map with labels"+R,requiresKey:!0},vectorDark:{name:"Vector (offline)",description:"Flat-shaded vector earth rendered from a bundled world outline \u2014 no network, crisp at any zoom"},openStreetMap:{name:"OpenStreetMap",description:"Community street map",maxLevel:19},googleSatellite:{name:"Google Satellite",description:"Aerial/satellite imagery",maxLevel:20,tileUrl2x:kt},googleHybrid:{name:"Google Hybrid",description:"Satellite + road labels",maxLevel:20,tileUrl2x:_t},googleRoads:{name:"Google Roads",description:"Standard road map",maxLevel:20,tileUrl2x:Dt},googleTerrain:{name:"Google Terrain",description:"Terrain with labels",maxLevel:20,tileUrl2x:Ft},esriDarkGray:{name:"ESRI Dark Gray",description:"Dark basemap without labels for data visualization (default)",maxLevel:16},esriLightGray:{name:"ESRI Light Gray",description:"Light basemap without labels for data visualization",maxLevel:16},esriWorldImagery:{name:"ESRI Satellite",description:"High-res satellite imagery",maxLevel:19},esriWorldTopo:{name:"ESRI Topo",description:"Topographic map",maxLevel:19},stamenToner:{name:"Stamen Toner",description:"High-contrast B&W (needs a Stadia API key)",requiresKey:!0},stamenWatercolor:{name:"Stamen Watercolor",description:"Artistic watercolor (needs a Stadia API key)",requiresKey:!0},stadiaAlidadeDark:{name:"Stadia Dark",description:"Modern dark theme (needs a Stadia API key)",requiresKey:!0}},jt="esriDarkGray";function Kn(t,n=1,e=18){let r=Wt[t],o=r?.maxLevel??e;return r?.tileUrl2x&&n>=1.5?{tileUrl:r.tileUrl2x,tileSize:512,maxLevel:o}:{tileUrl:K[t]??K[jt],tileSize:256,maxLevel:o}}function Yn(t){return K[t]}function Zn(t,n,e){let r=(90-t)*Math.PI/180,o=(90-n)*Math.PI/180;return{x:e*Math.sin(r)*Math.cos(o),y:e*Math.cos(r),z:e*Math.sin(r)*Math.sin(o)}}function Qn({x:t,y:n,z:e}){let r=Math.sqrt(t*t+n*n+e*e),o=Math.acos(n/r),a=Math.atan2(e,t);return{lat:90-o*180/Math.PI,lng:90-a*180/Math.PI-(a<-Math.PI/2?360:0),r}}function Jn(t){return t*Math.PI/180}function er(t){return t/Math.PI*180}function Se(t,n=0){switch(t){case"underlay":return-50+ye(n,0,40);case"overlay":return 2+ye(n,0,96);default:return 100+Math.max(0,n)}}function ye(t,n,e){return t<n?n:t>e?e:t}import{useEffect as N,useRef as D}from"react";import*as we from"three";function Pe(t){return{damping:t.mapDamping,maxGrowth:t.api?.map.getMaxNodeGrowth()??4}}function Ce(t,n,e,r,o){let a=e(),s=()=>{let p=new we.Vector2;return t.getRenderer()?.getDrawingBufferSize(p),{width:p.x||1,height:p.y||1}},i={cloudScene:t.cloudScene,camera:t.camera,store:t.store,iconAtlasManager:t.iconAtlasManager,invalidate:t.invalidate,isMapMode:t.isMapMode(),sphereRadius:t.mapSphereRadius(),...t.mapNodeSizing?{getMapNodeSizing:t.mapNodeSizing}:{},renderOrder:Se,getDrawingBufferSize:s,getEdgeOpacity:p=>{let h=t.store.index.getEdgeIndex(p),u=t.store.edgeState?.opacities;return h!==void 0&&u?u[h]:1},getNodeOpacity:p=>{let h=t.store.index.getNodeIndex?.(p),u=t.store.nodeState?.opacities;return h!==void 0&&h>=0&&u?u[h]:1},getHitTest:()=>t.getHitTest?.()??null};a.mount(i),a.update?.(r),t.invalidate();let l=0,d=!1;if(o?.frame===!0){let p=performance.now(),h=()=>{if(d)return;let u=performance.now(),g=(u-p)/1e3;p=u,i.sphereRadius=t.mapSphereRadius(),i.isMapMode=t.isMapMode(),a.frame?.(g,i)&&t.invalidate(),l=requestAnimationFrame(h)};l=requestAnimationFrame(h)}return t.registerMapModeCallback(n,(p,h=0)=>{i.sphereRadius=h,i.isMapMode=p,a.onMapMode?.(p,h),t.invalidate()}),{update(p){a.update?.(p),t.invalidate()},dispose(){d=!0,l&&cancelAnimationFrame(l),t.registerMapModeCallback(n,null),a.dispose(),t.invalidate()}}}function lr(t,n=[]){let{store:e,cloudScene:r,invalidate:o}=S(),a=D(null),s=se();N(()=>{let i=t.init(r,e);return a.current=i,o(),()=>{a.current!==null&&(t.dispose(a.current,r),a.current=null)}},[r,e,...n]),N(()=>{a.current!==null&&t.update&&(t.update(a.current,e),o())},[s,e,o])}function cr(t,n,e,r,o){let a=S(),{store:s,cloudScene:i,camera:l,renderer:d,invalidate:p,registerMapModeCallback:h}=a,u=oe(),g=ae(),{iconAtlasManager:w}=ie(),x=D(null);x.current=d;let _=D(u);_.current=u;let P=D(g);P.current=g;let f=D(null);N(()=>{let M=Ce({cloudScene:i,camera:l,getRenderer:()=>x.current,store:s,invalidate:p,registerMapModeCallback:h,iconAtlasManager:w,isMapMode:()=>_.current,mapSphereRadius:()=>P.current,mapNodeSizing:()=>Pe(a),getHitTest:()=>a.interaction?.picker??null},t,n,e,o);return f.current=M,()=>{M.dispose(),f.current=null}},[t,i,l,s,...r]),N(()=>{f.current?.update(e)},[e])}function pr(t,n){let e;if(t.source.startsWith("property:")?e=n.properties[t.source.slice(9)]:t.source==="category"?e=n.category??"":t.source==="relationship"?e=n.relationship??"":t.source==="id"?e=n.id:t.source.startsWith("static:")?e=t.source.slice(7):e=null,e==null||e==="")return t.whenEmpty==="blank"?"":null;let r=String(e);return t.template?t.template.replace(/\{value\}/g,r):r}var $t=["name","title","label","displayName","display_name","Name","Title","Label"];function hr(t){let n=t.properties;for(let e of $t)if(n[e]!=null&&String(n[e]).trim()!=="")return String(n[e]);for(let e of Object.keys(n)){let r=n[e];if(typeof r=="string"&&r.trim()!=="")return r}return t.category}var Te=`// kv_mapGrowth \u2014 the shared soft caps on how big geometry may appear:
2
+ // \`kvMapGrowth\` for map-mode inverse-zoom growth, \`kvScreenCap\` (below, built
3
+ // on it) for the near-camera cap that applies in every mode.
4
+ //
5
+ // \`raw\` is pow(refDepth / viewDepth, mapDamping): how much a node would grow
6
+ // versus the reference depth. Below the knee the growth passes through; above it
7
+ // a rational asymptote A\xB7t/(A+t) approaches \`maxGrowth\` (C\xB9-continuous at the
8
+ // knee, so no kink). \`maxGrowth < 0\` is the "Infinity" sentinel: no cap.
9
+ //
10
+ // Every shader that has to agree on a node's on-screen size (node, picking,
11
+ // edge, arrow, badge, tag) calls this, so the visible bubble, its hitbox, the
12
+ // edge endpoint and the decorations freeze in lockstep. Keep the operations in
13
+ // this order: the A/B screenshot gate expects bit-identical output to the
14
+ // per-shader copies this replaced.
15
+ float kvMapGrowth(float raw, float maxGrowth) {
16
+ if (maxGrowth < 0.0) return raw;
17
+ float softKnee = maxGrowth * 0.5;
18
+ float overflow = max(raw - softKnee, 0.0);
19
+ float A = maxGrowth - softKnee;
20
+ return min(raw, softKnee) + (A * overflow) / (A + overflow);
21
+ }
22
+
23
+ // kvScreenCap \u2014 the single definition of the near-camera size cap.
24
+ //
25
+ // \`px\` is an uncapped on-screen size in CSS pixels (a node diameter, an edge
26
+ // width). \`maxFraction\` is the share of the SMALLER viewport dimension that one
27
+ // piece of geometry may cover. \`maxFraction < 0\` is the "Infinity" sentinel and
28
+ // returns \`px\` untouched \u2014 bit-identical to the engine before the cap existed.
29
+ //
30
+ // Why this exists: outside map mode the apparent size is \`size * 50 / depth\`, so
31
+ // a scene flight that passes a node at depth 0.02 asks for a ~4000 px quad. The
32
+ // hard 4096 px clamp in node.vert.glsl allowed exactly that: the node covered
33
+ // the frame and the shot was unreadable. kvMapGrowth already has the right curve \u2014 below
34
+ // half the cap it is the identity, so ordinary zooming is untouched to the bit,
35
+ // and above it the same C\xB9 rational asymptote map mode uses.
36
+ //
37
+ // Callers MUST cap the NOMINAL size (before selection / halo expansion) so the
38
+ // node quad, its hitbox, the edge endpoint pullback and the arrow cone agree on
39
+ // where the bubble boundary is: node.vert, picking.vert, edge.vert, arrow.vert.
40
+ float kvScreenCap(float px, float maxFraction, vec2 resolution) {
41
+ if (maxFraction < 0.0) return px;
42
+ return kvMapGrowth(px, maxFraction * min(resolution.x, resolution.y));
43
+ }
44
+ `;var Re=`// kv_shapes \u2014 built-in node outlines. Mirrors core/shapes/reference.ts (the source of
45
+ // truth); scripts/glsl-conformance.mjs compares the two on a fixed grid (tolerance 1e-4).
46
+ //
47
+ // Unit box [-0.5, 0.5]\xB2, y UP. kvShapeSdf is a signed distance: negative inside, 0 on the
48
+ // outline. Callers use \`0.5 + kvShapeSdf(...)\` where the circle code used length(p), so soft
49
+ // edges, rings and icon clipping follow the outline. Shape ids: 0 circle, 1 rect,
50
+ // 2 roundRect, 3 diamond, 4 triangle, 5 hexagon, 6 star, 7 ring.
51
+
52
+ float kvSdBox(vec2 p, vec2 h) {
53
+ vec2 q = abs(p) - h;
54
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
55
+ }
56
+
57
+ float kvSdStar5(vec2 p, float r, float rf) {
58
+ const vec2 k1 = vec2(0.809016994375, -0.587785252292);
59
+ const vec2 k2 = vec2(-0.809016994375, -0.587785252292);
60
+ p.x = abs(p.x);
61
+ p -= 2.0 * max(dot(k1, p), 0.0) * k1;
62
+ p -= 2.0 * max(dot(k2, p), 0.0) * k2;
63
+ p.x = abs(p.x);
64
+ p.y -= r;
65
+ vec2 ba = rf * vec2(-k1.y, k1.x) - vec2(0.0, 1.0);
66
+ float h = clamp(dot(p, ba) / dot(ba, ba), 0.0, r);
67
+ return length(p - ba * h) * sign(p.y * ba.x - p.x * ba.y);
68
+ }
69
+
70
+ float kvShapeSdf(float shapeId, vec2 p) {
71
+ float id = floor(shapeId + 0.5);
72
+ if (id < 0.5) return length(p) - 0.5;
73
+ if (id < 1.5) return kvSdBox(p, vec2(0.5));
74
+ if (id < 2.5) return kvSdBox(p, vec2(0.5 - 0.18)) - 0.18;
75
+ if (id < 3.5) return (abs(p.x) + abs(p.y) - 0.5) * 0.70710678118;
76
+ if (id < 4.5) {
77
+ float l = -0.894427191 * p.x + 0.4472135955 * p.y - 0.2236067977;
78
+ float r = 0.894427191 * p.x + 0.4472135955 * p.y - 0.2236067977;
79
+ return max(max(l, r), -p.y - 0.5);
80
+ }
81
+ if (id < 5.5) {
82
+ vec2 a = abs(p);
83
+ return max(a.y, 0.86602540378 * a.x + 0.5 * a.y) - 0.43301270189;
84
+ }
85
+ if (id < 6.5) return kvSdStar5(p, 0.5, 0.5);
86
+ if (id < 7.5) return abs(length(p) - 0.4) - 0.1;
87
+ return length(p) - 0.5;
88
+ }
89
+
90
+ // Coverage 0..1. edgeOuter = node radius in unit-box units (0.5; 0.38 selected; 0.40 highlighted).
91
+ float kvShapeMask(float shapeId, vec2 p, float edgeOuter) {
92
+ float d = kvShapeSdf(shapeId, p) + (0.5 - edgeOuter);
93
+ return 1.0 - smoothstep(-0.02, 0.0, d);
94
+ }
95
+
96
+ // \u2500\u2500 edge endpoint clipping (mirrors shapeCode / shapeRadiusAlong in reference.ts) \u2500\u2500
97
+
98
+ float kvCodeShape(float code) { return mod(code, 16.0); }
99
+ float kvCodeAspect(float code) {
100
+ float q = floor(code / 16.0);
101
+ return q > 0.5 ? q / 1024.0 : 1.0;
102
+ }
103
+
104
+ float kvOuterSdf(float id, vec2 p) {
105
+ return (id > 6.5 && id < 7.5) ? length(p) - 0.5 : kvShapeSdf(id, p);
106
+ }
107
+
108
+ // Distance from the node centre to its outline along unit screen direction u (y up), for a node
109
+ // \`widthPx\` wide. A plain circle returns exactly 0.5 * widthPx (the pre-shape behaviour).
110
+ float kvShapeRadiusAlong(float shapeId, float aspect, float widthPx, vec2 u) {
111
+ if (shapeId < 0.5 && abs(aspect - 1.0) < 1e-4) return 0.5 * widthPx;
112
+ vec2 d = vec2(u.x, u.y * aspect);
113
+ float lo = 0.0;
114
+ float hi = 0.7072 / length(d);
115
+ for (int i = 0; i < 14; i++) {
116
+ float mid = 0.5 * (lo + hi);
117
+ if (kvOuterSdf(shapeId, d * mid) < 0.0) lo = mid; else hi = mid;
118
+ }
119
+ return widthPx * 0.5 * (lo + hi);
120
+ }
121
+ `;var ke=`// kv_orthoEdge \u2014 the \`orthogonal\` edge shape (shape id 3), evaluated per vertex.
122
+ //
123
+ // Routed from the two endpoints alone: leg1 leaves the source along the routing
124
+ // axis, leg2 runs across at the bend, leg3 drops into the target along the axis.
125
+ // Both corners are quarter circles. Nothing per edge is uploaded beyond the
126
+ // bend, so nodes can move every frame (force layout, drag, tweens) at no CPU cost.
127
+ //
128
+ // S \u25CF axis = vertical
129
+ // \u2502 leg1 bend = where leg2 sits between S and E
130
+ // \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u256E leg2
131
+ // \u2502 leg3
132
+ // E \u25CF
133
+ //
134
+ // Vertex budget. A strip vertex is addressed by k = along * segments. Corners
135
+ // get most of the vertices, straight legs need only their two ends:
136
+ // k = 0 start of leg1
137
+ // k = 1 .. 1+a corner 1 (a = floor((segments - 4) / 2) segments)
138
+ // k = 1+a .. 2+a leg2
139
+ // k = 2+a .. 2+2a corner 2
140
+ // k = 2+2a .. N leg3
141
+ // With the default 20 segments each corner gets 8, which reads as a smooth arc
142
+ // at any zoom; the legs stay exactly straight. \`segments\` < 8 degrades to
143
+ // chamfered corners, still correct.
144
+ //
145
+ // Bend encoding (controlOffset.x / .y, written by GPUEdgeRenderer):
146
+ // .y >= 9999 explicit bend in .x: 0..1 = fraction of the S\u2192E span along
147
+ // the axis; < 0 = absolute world distance from S (family-tree
148
+ // "comb": every child of one couple shares one bar height)
149
+ // otherwise 0.5 + .x (multi-edge curvature spreads parallel edges)
150
+ //
151
+ // MUST match: arrow.vert.glsl (end direction), edge/orthoPath.ts (CPU mirror
152
+ // used by labels and tests).
153
+
154
+ const float KV_ORTHO_EXPLICIT = 9999.0;
155
+
156
+ // Routing frame. Fills the corner points and leg directions; returns false when
157
+ // the axis span is ~0 (both ends level) and the caller should draw straight.
158
+ bool kvOrthoFrame(vec3 S, vec3 E, vec2 ctrl, float axisMode,
159
+ out vec3 P1, out vec3 P2, out vec3 d1, out vec3 d3) {
160
+ vec3 dir = E - S;
161
+ bool vertical;
162
+ if (axisMode > 1.5) vertical = false;
163
+ else if (axisMode > 0.5) vertical = true;
164
+ else vertical = abs(dir.y) >= abs(dir.x);
165
+
166
+ float span = vertical ? dir.y : dir.x;
167
+ float sgn = span >= 0.0 ? 1.0 : -1.0;
168
+ float m; // position of leg2 along the axis, relative to S
169
+ if (ctrl.y >= KV_ORTHO_EXPLICIT) {
170
+ m = ctrl.x < 0.0 ? sgn * min(-ctrl.x, abs(span)) : span * clamp(ctrl.x, 0.0, 1.0);
171
+ } else {
172
+ m = span * clamp(0.5 + ctrl.x, 0.05, 0.95);
173
+ }
174
+ if (vertical) {
175
+ P1 = vec3(S.x, S.y + m, S.z);
176
+ P2 = vec3(E.x, S.y + m, E.z);
177
+ d1 = vec3(0.0, sgn, 0.0);
178
+ } else {
179
+ P1 = vec3(S.x + m, S.y, S.z);
180
+ P2 = vec3(S.x + m, E.y, E.z);
181
+ d1 = vec3(sgn, 0.0, 0.0);
182
+ }
183
+ d3 = d1;
184
+ return abs(span) > 1e-5;
185
+ }
186
+
187
+ // Point on the routed polyline at strip coordinate k (0..segments).
188
+ // A, B leg1 start / leg3 end (already pulled back from the node discs)
189
+ // r corner-radius fraction 0..1 (uniform orthoCornerRadius)
190
+ // s out: arc length from A, for dash / flow counters
191
+ // L out: total arc length
192
+ vec3 kvOrthoPoint(float k, float segments, vec3 A, vec3 P1, vec3 P2, vec3 B,
193
+ vec3 d1, float r, out float s, out float L) {
194
+ vec3 across = P2 - P1;
195
+ float L1 = max(dot(P1 - A, d1), 0.0);
196
+ float L2 = length(across);
197
+ float L3 = max(dot(B - P2, d1), 0.0);
198
+ vec3 d2 = L2 > 1e-6 ? across / L2 : d1;
199
+
200
+ // Corner radii scale with the outer legs only, so every edge of a comb
201
+ // (one parent, same level gap) gets the same arc whatever its cross leg;
202
+ // then capped to the leg it sits on and to half the cross leg. A floor
203
+ // keeps the arcs from collapsing to a point (strip joints need distinct
204
+ // neighbours) without visibly rounding a tight bend.
205
+ float tot = L1 + L2 + L3;
206
+ float rMin = 1e-4 * tot;
207
+ float rr = r * min(L1, L3);
208
+ float r1 = max(min(rr, min(L1, 0.5 * L2)), rMin);
209
+ float r2 = max(min(rr, min(L3, 0.5 * L2)), rMin);
210
+
211
+ float a = max(floor((segments - 4.0) * 0.5), 1.0);
212
+ float qArc = 1.5707963 ;
213
+ float l1 = max(L1 - r1, 0.0), l2 = max(L2 - r1 - r2, 0.0), l3 = max(L3 - r2, 0.0);
214
+ float c1 = qArc * r1, c2 = qArc * r2;
215
+ L = l1 + c1 + l2 + c2 + l3;
216
+
217
+ vec3 p;
218
+ if (k <= 1.0) { // leg1
219
+ float u = clamp(k, 0.0, 1.0);
220
+ p = A + d1 * (l1 * u);
221
+ s = l1 * u;
222
+ } else if (k <= 1.0 + a) { // corner 1
223
+ float phi = qArc * (k - 1.0) / a;
224
+ vec3 O = P1 - d1 * r1 + d2 * r1;
225
+ p = O - d2 * (r1 * cos(phi)) + d1 * (r1 * sin(phi));
226
+ s = l1 + r1 * phi;
227
+ } else if (k <= 2.0 + a) { // leg2
228
+ float u = k - (1.0 + a);
229
+ p = P1 + d2 * (r1 + l2 * u);
230
+ s = l1 + c1 + l2 * u;
231
+ } else if (k <= 2.0 + 2.0 * a) { // corner 2
232
+ float phi = qArc * (k - (2.0 + a)) / a;
233
+ vec3 O = P2 - d2 * r2 + d1 * r2;
234
+ p = O - d1 * (r2 * cos(phi)) + d2 * (r2 * sin(phi));
235
+ s = l1 + c1 + l2 + r2 * phi;
236
+ } else { // leg3
237
+ float rest = max(segments - (2.0 + 2.0 * a), 1e-3);
238
+ float u = clamp((k - (2.0 + 2.0 * a)) / rest, 0.0, 1.0);
239
+ p = P2 + d1 * (r2 + l3 * u);
240
+ s = l1 + c1 + l2 + c2 + l3 * u;
241
+ }
242
+ return p;
243
+ }
244
+ `;var ze=`// kv_routedEdge \u2014 the \`routed\` (id 4) and \`family\` (id 5) edge shapes.
245
+ //
246
+ // routed: the edge bends through stored points. Each point is kept relative to
247
+ // the two node centres S and E, as (u, v) in the chord frame:
248
+ // P.xy = S.xy + u * d.xy + v * perp(d.xy), P.z = S.z + u * d.z, d = E - S
249
+ // That is a similarity in the xy plane, so the route follows its nodes every
250
+ // frame with nothing recomputed or uploaded. Points live in a float RGBA
251
+ // texture, one texel each: (u, v, fraction of the route's length, unused).
252
+ // controlOffset.x = the edge's first texel, .y = its point count.
253
+ //
254
+ // One strip vertex sits on each bend (vertex k = point k), so corners are
255
+ // exact; vertices past the last point collapse onto the end.
256
+ //
257
+ // family: an orthogonal edge from the midpoint of its source and an anchor
258
+ // node (the other parent). controlOffset.y = KV_ORTHO_EXPLICIT + 1 + anchor
259
+ // slot, which still reads as "explicit bend in .x" to kvOrthoFrame.
260
+ //
261
+ // MUST match edge/edgePath.ts.
262
+
263
+ const float KV_ROUTED_SHAPE = 4.0;
264
+ const float KV_FAMILY_SHAPE = 5.0;
265
+
266
+ vec4 kvRouteTexel(sampler2D tex, float size, float i) {
267
+ vec2 uv = vec2(mod(i, size) + 0.5, floor(i / size) + 0.5) / size;
268
+ return texture2D(tex, uv);
269
+ }
270
+
271
+ vec3 kvRouteToWorld(vec2 uv, vec3 S, vec3 E) {
272
+ vec3 d = E - S;
273
+ return vec3(S.x + uv.x * d.x - uv.y * d.y, S.y + uv.x * d.y + uv.y * d.x, S.z + uv.x * d.z);
274
+ }
275
+
276
+ // Point \`i\` of a routed edge with \`count\` bends: 0 = A, count + 1 = B.
277
+ // S, E are the node centres the route is stored against; A, B the drawn ends.
278
+ vec3 kvRoutedPoint(sampler2D tex, float size, float first, float count, float i,
279
+ vec3 S, vec3 E, vec3 A, vec3 B, out float frac) {
280
+ if (i < 0.5) { frac = 0.0; return A; }
281
+ if (i > count + 0.5) { frac = 1.0; return B; }
282
+ vec4 t = kvRouteTexel(tex, size, first + i - 1.0);
283
+ frac = t.z;
284
+ return kvRouteToWorld(t.xy, S, E);
285
+ }
286
+ `;var qt=Te,Kt=Re,Yt=ke,Xt=ze;function Y(t){return`${Yt}
287
+ ${Xt}
288
+ ${t}`}function T(t){return`${qt}
289
+ ${t}`}function A(t){return`${Kt}
290
+ ${t}`}var _e=`precision highp float;
291
+ const float HALO_EXPAND = 2.2; // quad expansion when halo active
292
+
293
+ // Position texture (from GPU layout controller)
294
+ uniform sampler2D positionTexture;
295
+ uniform float textureSize;
296
+ uniform float spaceSize;
297
+ uniform float fixedSize;
298
+ uniform float nodeSizeScale;
299
+ uniform float mapMode;
300
+ uniform float mapDamping; // 0.0 = constant screen size, 1.0 = full perspective (used when mapMode > 0.5)
301
+ uniform float mapMaxGrowth; // default 4.0; -1.0 sentinel \u21D2 Infinity / unbounded
302
+ uniform float maxScreenFraction; // share of the smaller viewport one node may cover; -1.0 \u21D2 unbounded
303
+ uniform float pixelRatio;
304
+ uniform float minPixelSize; // CSS px floor; nodes never draw under one device pixel
305
+ uniform float sphereRadius;
306
+ uniform vec2 resolution;
307
+
308
+ // Animation
309
+ uniform float animate;
310
+ uniform float t;
311
+
312
+ // Per-vertex attributes
313
+ attribute float nodeIndex;
314
+ attribute vec3 nodeColor;
315
+ attribute float nodeSize;
316
+ attribute float nodeOpacity;
317
+ attribute float nodeIcon;
318
+ attribute vec4 nodeIconUV;
319
+ attribute vec4 nodeImageUV;
320
+ attribute float nodeFlags;
321
+ attribute float aNodeCollect;
322
+ attribute float nodeSuppressFill;
323
+ attribute vec3 toPosition;
324
+ attribute vec4 nodeEffects; // x ripple, y breathe, z halo, w aspect (width / height)
325
+ #ifndef KV_POINT_PRIMITIVE
326
+ attribute vec2 corner; // [-0.5, 0.5]\xB2 quad corner offset
327
+ #else
328
+ uniform float maxPointSize; // ALIASED_POINT_SIZE_RANGE max, device px
329
+ #endif
330
+
331
+ // Time uniform for shader-driven effects
332
+ uniform float time;
333
+ // Hover-neighbor-highlight: current frame timestamp (ms, mod 2^19 = 524288)
334
+ // + ramp duration. Lets each instance fade independently when hover-move
335
+ // in Steady state diffs only a subset of instances.
336
+ uniform float u_hoverTime;
337
+ uniform float u_hoverDuration;
338
+
339
+ // Varyings
340
+ varying vec3 vColor;
341
+ varying float vOpacity;
342
+ varying float vIcon;
343
+ varying vec4 vIconUV;
344
+ varying vec4 vImageUV;
345
+ varying float vSelected;
346
+ varying float vHighlighted;
347
+ varying float vPinned;
348
+ varying float vNodeCollect;
349
+ varying float vSuppressFill;
350
+ varying float vHidden;
351
+ varying float vHoverDim;
352
+ varying float vRipple;
353
+ varying float vBreathe;
354
+ varying float vHalo;
355
+ #ifndef KV_POINT_PRIMITIVE
356
+ varying vec2 vUv; // [0,1]\xB2 fragment-local coordinate (replaces gl_PointCoord)
357
+ #endif
358
+ varying float vShape; // built-in shape id (0 = circle)
359
+ varying float vCoverage; // area alpha of a node under one device pixel, else 1
360
+ varying float vDevicePx; // drawn diameter in device pixels
361
+
362
+ vec3 samplePosition(float idx) {
363
+ float texX = mod(idx, textureSize) + 0.5;
364
+ float texY = floor(idx / textureSize) + 0.5;
365
+ vec2 texCoord = vec2(texX, texY) / textureSize;
366
+ vec4 posData = texture2D(positionTexture, texCoord);
367
+ return posData.xyz;
368
+ }
369
+
370
+ void main() {
371
+ // Unpack nodeFlags. Low 5 bits = flag bits (sel/hi/pin/hid/hoverDim);
372
+ // upper 19 bits = the timestamp (ms mod 2^19) when the hoverDim bit last
373
+ // flipped. The flag-bit unpack lines below keep working because the
374
+ // timestamp portion is always a multiple of 32 (= 2^5) \u2192 even when
375
+ // divided by 16, so it doesn't pollute the 0/1 result of \`mod ... 2\`.
376
+ vSelected = mod(nodeFlags, 2.0);
377
+ vHighlighted = mod(floor(nodeFlags / 2.0), 2.0);
378
+ vPinned = mod(floor(nodeFlags / 4.0), 2.0);
379
+ vHidden = mod(floor(nodeFlags / 8.0), 2.0);
380
+ float _hoverTarget = mod(floor(nodeFlags / 16.0), 2.0);
381
+ // Per-instance fade. \`_hoverStart\` is 0 for instances that have never
382
+ // flipped (sentinel: skip animation, render at the target value).
383
+ // For instances that have flipped, modular ms arithmetic gives
384
+ // \`diff = (u_hoverTime - start) mod 524288\`. When diff > duration the
385
+ // ramp is done; when 0 \u2264 diff < duration the instance is mid-fade.
386
+ float _hoverStart = floor(nodeFlags / 32.0);
387
+ float _hoverDiff = u_hoverTime - _hoverStart;
388
+ if (_hoverDiff < 0.0) _hoverDiff += 524288.0;
389
+ float _hoverT = _hoverStart < 0.5
390
+ ? 1.0 // never animated \u2192 snap to target
391
+ : clamp(_hoverDiff / max(u_hoverDuration, 1.0), 0.0, 1.0);
392
+ float _hoverEased = _hoverT < 0.5
393
+ ? 4.0 * _hoverT * _hoverT * _hoverT
394
+ : 1.0 - pow(-2.0 * _hoverT + 2.0, 3.0) / 2.0;
395
+ vHoverDim = mix(1.0 - _hoverTarget, _hoverTarget, _hoverEased);
396
+ vColor = nodeColor;
397
+ vOpacity = nodeOpacity;
398
+ vIcon = nodeIcon;
399
+ vIconUV = nodeIconUV;
400
+ vNodeCollect = aNodeCollect;
401
+ // nodeSuppressFill = suppress (0/1) + 2 * shapeId \u2014 packed to stay within the attribute budget.
402
+ vSuppressFill = mod(nodeSuppressFill, 2.0);
403
+ vImageUV = nodeImageUV;
404
+ vRipple = nodeEffects.x;
405
+ vBreathe = nodeEffects.y;
406
+ vHalo = nodeEffects.z;
407
+
408
+ vec3 sampledPos = samplePosition(nodeIndex);
409
+
410
+ vec3 finalPosition = sampledPos;
411
+ if (animate > 0.5) {
412
+ finalPosition = mix(sampledPos, toPosition, t);
413
+ }
414
+
415
+ vec4 mvCenter = modelViewMatrix * vec4(finalPosition, 1.0);
416
+
417
+ // Per-node perspective sizing (matches legacy nodeVertex.glsl).
418
+ // \`pixelSize\` is the on-screen diameter of the node in physical pixels.
419
+ float scaledSize = nodeSize * nodeSizeScale;
420
+ if (vBreathe > 0.0) {
421
+ scaledSize *= 1.0 + vBreathe * 0.15 * sin(time * 3.0);
422
+ }
423
+ float viewDepth = max(-mvCenter.z, 0.001);
424
+ float baseSize;
425
+ if (mapMode > 0.5) {
426
+ // Map mode: damped scaling so nodes stay roughly constant screen size.
427
+ // refDepth=10 is the anchor depth where sizes match the designed CSS px.
428
+ // damping=0 \u2192 constant size, damping=1 \u2192 full perspective (same as normal).
429
+ float refDepth = 10.0;
430
+ float refSize = scaledSize * (50.0 / refDepth);
431
+ // \`growth\` is the inverse-zoom multiplier vs the refDepth baseline.
432
+ // Soft-cap curve to prevent nodes from covering the map at deep zoom while
433
+ // keeping the "still growing" feel users expect when they zoom in:
434
+ // - Below softKnee: pass through (full damped growth).
435
+ // - Above softKnee: rational asymptote A\xB7t/(A+t) toward mapMaxGrowth.
436
+ // The curve is C\xB9-continuous at the knee (matches derivative, no kink).
437
+ // Curve MUST stay in sync with picking.vert.glsl, badge.vert.glsl, and
438
+ // tag.vert.glsl so hitbox and decorations freeze in lockstep with the bubble.
439
+ float raw = pow(refDepth / viewDepth, mapDamping);
440
+ float growth = kvMapGrowth(raw, mapMaxGrowth);
441
+ baseSize = refSize * growth;
442
+ } else {
443
+ baseSize = scaledSize * (50.0 / viewDepth);
444
+ }
445
+ float sizeMultiplier = (vSelected > 0.5 || vHighlighted > 0.5) ? 1.5 : 1.0;
446
+ float rippleExpand = vRipple > 0.0 ? 3.0 : 1.0;
447
+ float expand = max(rippleExpand, nodeEffects.z > 0.0 ? HALO_EXPAND : 1.0);
448
+ // pixelSize is the on-screen diameter in CSS pixels. Do NOT multiply by pixelRatio:
449
+ // resolution is in CSS px (container.clientWidth/Height), and gl_PointSize in the
450
+ // legacy Point pipeline included pixelRatio only because gl_PointSize is in physical
451
+ // pixels \u2014 the browser then halved it for display, cancelling out. Quads work in CSS
452
+ // px directly, so multiplying by pixelRatio would double-scale on Retina.
453
+ float pixelSize = baseSize * sizeMultiplier * expand;
454
+
455
+ // Near-camera cap: what the budget protects is the FRAME, so it is the whole
456
+ // quad that gets capped \u2014 selection multiplier and ripple/halo expansion
457
+ // included. A node the scene flies past otherwise covers everything, and a
458
+ // highlighted one covers 1.5\xD7 everything. MUST stay in sync with
459
+ // picking.vert.glsl (hitbox), edge.vert.glsl (endpoint pullback) and
460
+ // arrow.vert.glsl (cone): all four cap the same expression with the same
461
+ // call, so for an ordinary node \u2014 multiplier 1, expand 1 \u2014 they agree
462
+ // exactly. For a selected or rippling one they differ by the multipliers,
463
+ // which those three shaders have never known about anyway (an edge has
464
+ // always stopped at the unselected radius); the cap inherits that
465
+ // approximation rather than adding one.
466
+ //
467
+ // Cap ONCE. \`kvScreenCap\` is not idempotent above its knee \u2014 capping both
468
+ // \`baseSize\` and \`pixelSize\` would shrink the quad below the fill radius the
469
+ // fragment shader derives from \`expand\`, and the node would clip itself.
470
+ pixelSize = kvScreenCap(pixelSize, maxScreenFraction, resolution);
471
+
472
+ // Clamp pixelSize to a sane range:
473
+ // - Lower bound \`minPixelSize\` (CSS px, default 1.5): WebGL does not
474
+ // anti-alias triangle edges below ~1 px without MSAA, so very small quads
475
+ // alias badly. The floor restores the visual stability point primitives
476
+ // provided implicitly. Whatever the floor, a node never draws under one
477
+ // device pixel: one that is smaller draws one device pixel with its alpha
478
+ // scaled by its area (vCoverage), so a cloud of sub-pixel nodes keeps the
479
+ // brightness of their true size instead of flickering or filling in.
480
+ // MUST stay in sync with picking.vert.glsl.
481
+ // - Upper bound 4096 px: nodes very near the camera otherwise produce
482
+ // screen-spanning quads with extreme fragment cost. Replaces the implicit
483
+ // hardware \u2264255 px cap that gl_PointSize used to enforce.
484
+ float devicePx = pixelSize * pixelRatio;
485
+ vCoverage = devicePx < 1.0 ? devicePx * devicePx : 1.0;
486
+ pixelSize = clamp(pixelSize, max(minPixelSize, 1.0 / pixelRatio), 4096.0);
487
+ vDevicePx = pixelSize * pixelRatio;
488
+
489
+ vec4 clipCenter = projectionMatrix * mvCenter;
490
+ vShape = floor(nodeSuppressFill * 0.5);
491
+ #ifdef KV_POINT_PRIMITIVE
492
+ // Point primitive: one vertex per node. gl_PointSize is in device pixels and
493
+ // the GPU caps it; past the cap the sprite stops growing (the trade-off this
494
+ // primitive makes, see GPUNodeRendererConfig.primitive). A shape's aspect is
495
+ // not applied: the sprite is square. The fragment reads gl_PointCoord, which
496
+ // has the same [0,1]\xB2, Y-down convention as the quad's vUv.
497
+ vDevicePx = min(vDevicePx, maxPointSize);
498
+ gl_PointSize = vDevicePx;
499
+ gl_Position = clipCenter;
500
+ #else
501
+ // Project the center to clip space, then offset by corner * pixelSize / viewport.
502
+ // Multiplying by gl_Position.w preserves the offset after perspective divide.
503
+ float shapeAspect = nodeEffects.w > 0.0 ? nodeEffects.w : 1.0; // 0 (unset) -> square
504
+ // Height = width / aspect; aspect 1 divides by exactly 1.0, so square nodes are unchanged.
505
+ vec2 offsetClip = vec2(corner.x, corner.y / shapeAspect) * pixelSize / resolution * 2.0 * clipCenter.w;
506
+ gl_Position = clipCenter + vec4(offsetClip, 0.0, 0.0);
507
+
508
+ // Fragment-local UV: [0,1]\xB2 with (0.5, 0.5) at the node center, matching gl_PointCoord.
509
+ // gl_PointCoord is Y-DOWN (origin at top-left), but clip-space Y is Y-UP (top corners have
510
+ // corner.y = +0.5). We invert Y here so vUv.y = 0 at the visual top of the node \u2014 keeps
511
+ // icon/image atlas UVs (which are Y-down via Three.js flipY=true) right-side up.
512
+ vUv = vec2(corner.x + 0.5, 0.5 - corner.y);
513
+ #endif
514
+ // Globe mode: vertex-level back-face culling.
515
+ // depthTest is disabled in globe mode to prevent billboard clipping against
516
+ // the occlusion sphere. Instead, we hide back-facing nodes here.
517
+ if (sphereRadius > 0.001) {
518
+ vec3 wN = normalize(mat3(modelMatrix) * normalize(finalPosition));
519
+ vec3 wP = (modelMatrix * vec4(finalPosition, 1.0)).xyz;
520
+ if (dot(wN, normalize(cameraPosition - wP)) < 0.0) {
521
+ // Push the quad off-screen (NDC outside [-1,1]) so all 4 corners are clipped.
522
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
523
+ }
524
+ }
525
+ }
526
+ `;var Me=`precision highp float;
527
+
528
+ const float HALO_EXPAND = 2.2; // MUST match node.vert.glsl
529
+ const float HALO_EDGE = 1.7; // outer radius (in node-radius units) where halo fades to 0
530
+ const float HALO_GAIN = 0.9; // (unused after translucent-disk rewrite \u2014 kept to minimize churn)
531
+ const float HALO_ALPHA = 0.35; // halo alpha ceiling
532
+
533
+ // Uniforms
534
+ uniform float hideRing;
535
+ uniform float useCircle;
536
+ uniform float lightMode;
537
+ uniform sampler2D iconSdfAtlas;
538
+ uniform float hasIconSdfAtlas;
539
+ uniform sampler2D imageAtlas;
540
+ uniform float hasImageAtlas;
541
+ uniform float iconDisplayMode;
542
+
543
+ // Pin icon (push-pin texture overlay). When vPinned > 0.5 and hidePin == 0,
544
+ // the pinTexture is sampled in the upper-right quadrant of the node sprite
545
+ // (matches legacy nodeImageFragment.glsl renderPin pattern).
546
+ uniform sampler2D pinTexture;
547
+ uniform float hidePin;
548
+
549
+ // Time uniform for shader-driven effects
550
+ uniform float time;
551
+ // Ripple effect configuration
552
+ uniform vec3 uRippleColor;
553
+ uniform float uRippleSpeed;
554
+ uniform float uRippleRings;
555
+
556
+ // Hover dim: when a node is hovered, non-neighbor nodes fade to u_hoverDimOpacity.
557
+ // u_hoverProgress animates 0\u21921 over the hover-in duration (driven by HoverApi).
558
+ uniform float u_hoverProgress;
559
+ uniform float u_hoverDimOpacity;
560
+
561
+ // Varyings
562
+ varying vec3 vColor;
563
+ varying float vOpacity;
564
+ varying float vIcon;
565
+ varying vec4 vIconUV;
566
+ varying vec4 vImageUV;
567
+ varying float vSelected;
568
+ varying float vHighlighted;
569
+ varying float vPinned;
570
+ varying float vNodeCollect;
571
+ varying float vSuppressFill;
572
+ varying float vHidden;
573
+ varying float vHoverDim;
574
+ varying float vRipple;
575
+ varying float vBreathe;
576
+ varying float vHalo;
577
+ #ifdef KV_POINT_PRIMITIVE
578
+ // Point primitive: the sprite's own [0,1]\xB2 coordinate, Y-down like the quad's vUv.
579
+ #define vUv gl_PointCoord
580
+ #else
581
+ varying vec2 vUv;
582
+ #endif
583
+ varying float vShape;
584
+ varying float vCoverage;
585
+ varying float vDevicePx;
586
+
587
+ void main() {
588
+ // Discard hidden nodes
589
+ if (vHidden > 0.5) discard;
590
+ if (vSuppressFill > 0.5) discard;
591
+
592
+ // A node under 1.5 device pixels is a dot: no shape, ring or icon would be
593
+ // visible, and on a quad this small the pixel centre can fall outside the
594
+ // circle, so a shape mask would drop the node. Fill the pixel instead, with
595
+ // the area alpha of a node under one device pixel. Only reachable when the
596
+ // host lowers \`minPixelSize\` below the default 1.5 CSS px.
597
+ if (vDevicePx < 1.5) {
598
+ float dotAlpha = vOpacity * vCoverage * mix(1.0, u_hoverDimOpacity, vHoverDim * u_hoverProgress);
599
+ if (dotAlpha < 0.001) discard;
600
+ gl_FragColor = vec4(vColor, dotAlpha);
601
+ return;
602
+ }
603
+
604
+ // When ripple is active, the billboard quad is 3x larger (rippleExpand in node.vert.glsl).
605
+ // Remap coordinates so the node draws at its normal size in the center. Ripples use raw coords.
606
+ float rippleExpand = vRipple > 0.0 ? 3.0 : 1.0;
607
+ float expand = max(rippleExpand, vHalo > 0.0 ? HALO_EXPAND : 1.0);
608
+ vec2 nodeCoord = (vUv - 0.5) * expand + 0.5;
609
+ vec2 center = nodeCoord - vec2(0.5);
610
+ float dist = length(center);
611
+ // Non-circle shapes: 0.5 + signed distance plays the role of the radius, so the soft edge,
612
+ // rings, icon clip and collect gate below follow the outline. y flipped: vUv is y-down.
613
+ if (vShape > 0.5) dist = 0.5 + kvShapeSdf(vShape, vec2(center.x, -center.y));
614
+
615
+ // Discard pixels outside the expanded area that are also outside the node
616
+ // (when ripple is off, this has no effect since rippleExpand = 1)
617
+ if (vRipple > 0.0 && dist > 0.5) {
618
+ // Outside node circle \u2014 only keep if a ripple ring will draw here
619
+ float rawDist = length(vUv - vec2(0.5)) * 2.0;
620
+ if (rawDist > 1.0) discard;
621
+ }
622
+
623
+ // Circle mode
624
+ // Circle clip: discard pixels outside node radius.
625
+ // When ripple is active, keep outer pixels alive for the ripple rings.
626
+ if (useCircle > 0.5 && dist > 0.5 && vRipple <= 0.0 && vHalo <= 0.0) discard;
627
+ // For ripple nodes: pixels outside the node circle start fully transparent
628
+ // (the ripple code below will add ring color to them).
629
+ bool outsideNodeCircle = (dist > 0.5);
630
+
631
+ // Check if node has an SDF icon (and no image override)
632
+ bool hasIcon = hasIconSdfAtlas > 0.5 && vIconUV.x >= 0.0 && !(hasImageAtlas > 0.5 && vImageUV.x >= 0.0);
633
+ bool transparentBg = hasIcon && iconDisplayMode > 0.5;
634
+
635
+ // Base color: transparent for ring/plain icon modes, solid for filled mode
636
+ if (transparentBg) {
637
+ gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
638
+ } else {
639
+ gl_FragColor = vec4(vColor, vOpacity);
640
+ }
641
+
642
+ // Soft edge for circle (skip for transparent bg modes)
643
+ if (useCircle > 0.5 && !transparentBg) {
644
+ float edgeOuter = 0.5;
645
+ if (vSelected > 0.5) edgeOuter = 0.38;
646
+ else if (vHighlighted > 0.5) edgeOuter = 0.40;
647
+ float alpha = 1.0 - smoothstep(edgeOuter - 0.02, edgeOuter, dist);
648
+ gl_FragColor.a *= alpha;
649
+ }
650
+
651
+ // Image overlay: photo inside node circle
652
+ if (hasImageAtlas > 0.5 && vImageUV.x >= 0.0) {
653
+ float imgSize = 0.88;
654
+ vec2 imgLocal = (nodeCoord - 0.5) / imgSize + 0.5;
655
+ float imgInBounds = step(0.0, imgLocal.x) * step(imgLocal.x, 1.0)
656
+ * step(0.0, imgLocal.y) * step(imgLocal.y, 1.0);
657
+ if (imgInBounds > 0.5) {
658
+ vec2 imgUV = mix(vImageUV.xy, vImageUV.zw, clamp(imgLocal, 0.0, 1.0));
659
+ vec4 imgColor = texture2D(imageAtlas, imgUV);
660
+ float imgAlpha = imgColor.a * (1.0 - smoothstep(0.42, 0.48, dist));
661
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, imgColor.rgb, imgAlpha);
662
+ gl_FragColor.a = max(gl_FragColor.a, imgAlpha * vOpacity);
663
+ }
664
+ }
665
+
666
+ // Icon SDF overlay \u2014 mode-aware rendering
667
+ // Skip icon when image is present \u2014 image takes priority.
668
+ if (hasIcon) {
669
+ // Plain mode uses larger icon since there's no ring
670
+ float iconSize = (iconDisplayMode > 1.5) ? 0.80 : 0.70;
671
+ vec2 local = (nodeCoord - 0.5) / iconSize + 0.5;
672
+ float inBounds = step(0.0, local.x) * step(local.x, 1.0)
673
+ * step(0.0, local.y) * step(local.y, 1.0);
674
+ if (inBounds > 0.5) {
675
+ vec2 iconUV = mix(vIconUV.xy, vIconUV.zw, clamp(local, 0.0, 1.0));
676
+ float sdf = texture2D(iconSdfAtlas, iconUV).r;
677
+ float fw = fwidth(sdf);
678
+ // SDF_EDGE = 1.0 - TinySDF cutoff (0.25) = 0.75. Using 0.5 dilates the
679
+ // glyph by ~radius*0.25 px, which fills small interior holes (e.g.
680
+ // bomb sparkle gap) and bloats fine details. Tag/badge/text shaders
681
+ // already use 0.75 \u2014 node icon was the outlier.
682
+ const float SDF_EDGE = 0.75;
683
+ float iconAlpha = smoothstep(SDF_EDGE - fw, SDF_EDGE + fw, sdf);
684
+ // Soft circular clip: fade out near circle edge
685
+ float clipEdge = transparentBg ? 0.40 : 0.42;
686
+ iconAlpha *= 1.0 - smoothstep(clipEdge, clipEdge + 0.06, dist);
687
+ // Icon color: dark gray for filled, node color for ring/plain
688
+ vec3 iconCol;
689
+ if (iconDisplayMode < 0.5) {
690
+ iconCol = vColor * 0.3;
691
+ } else {
692
+ iconCol = vColor;
693
+ }
694
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, iconCol, iconAlpha);
695
+ if (transparentBg) gl_FragColor.a = max(gl_FragColor.a, iconAlpha * vOpacity);
696
+ }
697
+ }
698
+
699
+ // --- Border ring / Selection ring ---
700
+ if (useCircle > 0.5) {
701
+ // Ring-only mode: always draw colored ring first (underneath sel/hl).
702
+ // Pin state has no ring treatment \u2014 the push-pin texture overlay
703
+ // below is the sole pin indicator (matches legacy GraphXR).
704
+ if (transparentBg && iconDisplayMode < 1.5) {
705
+ float ringOuter = 0.50;
706
+ float ringInner = 0.43;
707
+ float ring = smoothstep(ringInner - 0.02, ringInner, dist)
708
+ * (1.0 - smoothstep(ringOuter - 0.02, ringOuter, dist));
709
+ float boost = lightMode > 0.5 ? 0.85 : 1.2;
710
+ vec3 ringCol = vColor * boost;
711
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, ringCol, ring);
712
+ gl_FragColor.a = max(gl_FragColor.a, ring * vOpacity);
713
+ }
714
+ // Selection/highlight rings (all modes)
715
+ if (vSelected > 0.5) {
716
+ vec3 selColor = lightMode > 0.5 ? vec3(0.40, 0.42, 0.48) : vec3(1.0, 1.0, 1.0);
717
+ float selRing = smoothstep(0.41, 0.42, dist) * (1.0 - smoothstep(0.48, 0.50, dist));
718
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, selColor, selRing);
719
+ gl_FragColor.a = max(gl_FragColor.a, selRing * vOpacity);
720
+ } else if (vHighlighted > 0.5) {
721
+ vec3 hlColor = lightMode > 0.5 ? vec3(0.55, 0.57, 0.62) : vec3(0.85, 0.85, 0.85);
722
+ float hlRing = smoothstep(0.42, 0.43, dist) * (1.0 - smoothstep(0.48, 0.50, dist));
723
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, hlColor, hlRing * 0.9);
724
+ gl_FragColor.a = max(gl_FragColor.a, hlRing * 0.9 * vOpacity);
725
+ } else if (!transparentBg && hideRing < 0.5) {
726
+ // Normal filled mode: border ring on node edge.
727
+ // Pin state has no ring treatment \u2014 the push-pin texture overlay
728
+ // below is the sole pin indicator (matches legacy GraphXR).
729
+ float ring = smoothstep(0.42, 0.44, dist) * (1.0 - smoothstep(0.48, 0.50, dist));
730
+ float boost = lightMode > 0.5 ? 0.76 : 1.3;
731
+ vec3 ringColor = vColor * boost;
732
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, ringColor, ring * 0.5);
733
+ }
734
+ }
735
+
736
+ // Collect indicator: legacy-style overlay \u2014 4 corner balls + center circle, NO digits.
737
+ // Pulled inward vs. legacy so a visible gap separates the inner symbol from the outer ring;
738
+ // the count display is delegated to BadgeCloud (top-right anchor by convention).
739
+ //
740
+ // Layout (in node-local coords, node center at 0.5, node radius at 0.5):
741
+ // 4 balls \u2014 centers at (0.32, 0.32) / (0.32, 0.68) / (0.68, 0.32) / (0.68, 0.68), r=0.13
742
+ // \u2192 ball outer edge reaches dist \u2248 0.385 from node center
743
+ // center \u2014 circle at (0.5, 0.5), r=0.10 with thin darker border (mirrors legacy badge,
744
+ // digits removed per Phase-5 redesign)
745
+ // gap \u2014 interior gate at dist < 0.40 leaves dist \u2208 [0.40, 0.50] as deadband + ring,
746
+ // giving ~0.035 of clear space between symbol and outer ring (\u22487% of diameter)
747
+ // ring \u2014 drawn by the base shader's selection/highlight/normal ring code below
748
+ if (useCircle > 0.5 && vNodeCollect > 0.5) {
749
+ float ballR = 0.13;
750
+ vec2 c0 = vec2(0.32, 0.32);
751
+ vec2 c1 = vec2(0.32, 0.68);
752
+ vec2 c2 = vec2(0.68, 0.32);
753
+ vec2 c3 = vec2(0.68, 0.68);
754
+ float d0 = length(nodeCoord - c0);
755
+ float d1 = length(nodeCoord - c1);
756
+ float d2 = length(nodeCoord - c2);
757
+ float d3 = length(nodeCoord - c3);
758
+ float minBallDist = min(min(d0, d1), min(d2, d3));
759
+
760
+ // Center circle (no digits)
761
+ float centerR = 0.10;
762
+ float centerDist = length(nodeCoord - vec2(0.5));
763
+
764
+ // Interior zone \u2014 anything outside is left to base shader (preserves outer ring zone).
765
+ bool inInterior = dist < 0.40;
766
+ if (inInterior) {
767
+ if (minBallDist < ballR) {
768
+ // Inside a corner ball \u2014 node color with soft AA edge.
769
+ float ballAlpha = 1.0 - smoothstep(ballR - 0.015, ballR, minBallDist);
770
+ gl_FragColor = vec4(vColor, vOpacity * ballAlpha);
771
+ } else if (centerDist < centerR) {
772
+ // Center circle \u2014 node color with thin darker border (legacy badge look, no digit).
773
+ float centerAlpha = 1.0 - smoothstep(centerR - 0.015, centerR, centerDist);
774
+ float borderW = 0.015;
775
+ float innerMask = 1.0 - smoothstep(centerR - borderW - 0.008, centerR - borderW, centerDist);
776
+ vec3 borderColor = vColor * (lightMode > 0.5 ? 0.6 : 1.4);
777
+ vec3 fillColor = mix(borderColor, vColor, innerMask);
778
+ gl_FragColor = vec4(fillColor, vOpacity * centerAlpha);
779
+ } else {
780
+ // Between elements \u2014 clear so background shows through (creates the visible gap).
781
+ gl_FragColor.a = 0.0;
782
+ }
783
+ }
784
+ }
785
+
786
+ // Ripple effect: concentric rings expanding OUTSIDE the node.
787
+ // The billboard quad was expanded 3x (rippleExpand) for ripple nodes \u2014 the node occupies
788
+ // the inner 1/3. 'dist' uses nodeCoord (remapped to node space). Raw vUv covers the full area.
789
+ if (vRipple > 0.0) {
790
+ // Use raw vUv for ripple (covers the full 3x expanded area)
791
+ float rawDist = length(vUv - vec2(0.5)) * 2.0;
792
+ float nodeEdge = 1.0 / 3.0;
793
+ float speed = uRippleSpeed > 0.0 ? uRippleSpeed : 0.5;
794
+ float rings = uRippleRings > 0.0 ? uRippleRings : 3.0;
795
+ float rippleAlphaSum = 0.0;
796
+ vec3 rColor = uRippleColor.r + uRippleColor.g + uRippleColor.b > 0.01 ? uRippleColor : vec3(0.0, 0.9, 1.0);
797
+ for (float i = 0.0; i < 4.0; i++) {
798
+ if (i >= rings) break;
799
+ float phase = fract(time * speed + i / rings);
800
+ // Ring starts at node edge and expands to the full area
801
+ float ringRadius = nodeEdge + phase * (1.0 - nodeEdge);
802
+ float ringWidth = 0.03;
803
+ float ringDist = abs(rawDist - ringRadius) / ringWidth;
804
+ if (ringDist < 1.0 && rawDist > nodeEdge * 0.9) {
805
+ float alpha = (1.0 - phase) * (1.0 - ringDist * ringDist) * vRipple;
806
+ rippleAlphaSum += alpha;
807
+ }
808
+ }
809
+ // \xD7 vOpacity: rings must dim with their node under focusContext \u2014 the
810
+ // ring/additive writes below otherwise ignore the per-node dim opacity.
811
+ rippleAlphaSum *= vOpacity;
812
+ if (rippleAlphaSum > 0.0) {
813
+ if (outsideNodeCircle) {
814
+ // Outside node: paint the ring on transparent background
815
+ gl_FragColor = vec4(rColor * rippleAlphaSum, rippleAlphaSum * 0.7);
816
+ } else {
817
+ // Inside node: additive blend over existing node color
818
+ gl_FragColor.rgb += rColor * rippleAlphaSum * 0.3;
819
+ }
820
+ } else if (outsideNodeCircle && vHalo <= 0.0) {
821
+ // Outside node and no ripple ring here \u2014 fully transparent
822
+ discard;
823
+ }
824
+ }
825
+
826
+ // \u2500\u2500 Pin icon overlay (push-pin texture) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
827
+ // Render the pin icon last so it sits above ring + icon, like the legacy
828
+ // GraphXR nodeImageFragment.glsl renderPin() pattern. Sized so the pin
829
+ // appears in the upper-right quadrant of the node sprite. The pulsing
830
+ // blue ring above is the secondary "anchored" indicator; this is the
831
+ // primary one (matches user expectation from legacy).
832
+ if (vPinned > 0.5 && hidePin < 0.5) {
833
+ float pinScale = (vSelected > 0.5 || vHighlighted > 0.5) ? 6.0 : 4.0;
834
+ float pinAngle = 0.7853981633974483; // PI / 4
835
+ float c = cos(pinAngle);
836
+ float s = sin(pinAngle);
837
+ // Flip y so coords match the pin PNG orientation (matches legacy
838
+ // \`normalCoord = vec2(gl_PointCoord.s, 1.0 - gl_PointCoord.t)\`).
839
+ vec2 normalCoord = vec2(vUv.x, 1.0 - vUv.y);
840
+ // Rotate + scale around (0.5, 0.5), no extra translation.
841
+ vec2 centered = normalCoord - vec2(0.5);
842
+ vec2 pinUV = vec2(
843
+ pinScale * (c * centered.x - s * centered.y) + 0.5,
844
+ pinScale * (s * centered.x + c * centered.y) + 0.5
845
+ );
846
+ if (pinUV.x >= 0.0 && pinUV.x <= 1.0 && pinUV.y >= 0.0 && pinUV.y <= 1.0) {
847
+ vec4 pinSample = texture2D(pinTexture, pinUV);
848
+ // Selected/highlighted nodes get a slightly stronger pin overlay so
849
+ // it stays visible above selection rings.
850
+ float pinStrength = (vSelected > 0.5 || vHighlighted > 0.5) ? 0.95 : 0.85;
851
+ pinSample.a *= pinStrength;
852
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, pinSample.rgb, pinSample.a);
853
+ gl_FragColor.a = max(gl_FragColor.a, pinSample.a * vOpacity);
854
+ }
855
+ }
856
+
857
+ // Node halo: a soft SEMI-TRANSPARENT disk in the node's OWN color (no
858
+ // brightening \u2014 a brightened/additive halo reads as a glow/bloom). Pure
859
+ // translucency via alpha under NormalBlending.
860
+ if (vHalo > 0.0 && outsideNodeCircle) {
861
+ float rr = length(nodeCoord - vec2(0.5)) * 2.0; // 1.0 at circle edge, grows outward
862
+ // Pure-color flat disk: UNIFORM alpha all the way to HALO_EDGE, then a
863
+ // crisp ~1px anti-aliased cutoff (fwidth \u2014 resolution independent, same as
864
+ // the icon/text shaders). No gradient band \u2192 reads as a solid colored
865
+ // disk, not a glow/bloom. (Previously a 0.15-wide smoothstep band made the
866
+ // edge fade over ~15% of the node radius, which read as a soft glow.)
867
+ float aa = fwidth(rr);
868
+ float falloff = 1.0 - smoothstep(HALO_EDGE - aa, HALO_EDGE, rr);
869
+ gl_FragColor.rgb = vColor; // node's own color, NOT brightened
870
+ // \xD7 vOpacity: the max() must not resurrect alpha focusContext dimmed.
871
+ gl_FragColor.a = max(gl_FragColor.a, falloff * vHalo * HALO_ALPHA * vOpacity);
872
+ }
873
+
874
+ // Hover dim: dim non-neighbor nodes when a hover is active.
875
+ float hoverDimMul = mix(1.0, u_hoverDimOpacity, vHoverDim * u_hoverProgress);
876
+ gl_FragColor.a *= hoverDimMul;
877
+
878
+ // Alpha test
879
+ if (gl_FragColor.a < 0.01) discard;
880
+ }
881
+ `;var De=`precision highp float;
882
+ const float GLOW_WIDEN_K = 3.0; // max strip widen = 1 + strength*K (strength 1 \u2192 4x)
883
+ const float EDGE_WIDTH_SHARE = 0.125; // a capped strip's share of a capped bubble's budget
884
+ const float KV_NEAR_Z = 1e-3; // view depth the strip must stay in front of (camera looks down -z)
885
+
886
+ uniform sampler2D positionTexture;
887
+ uniform float textureSize;
888
+ uniform float spaceSize;
889
+ uniform vec2 resolution;
890
+ uniform float sizeAttenuation;
891
+ uniform float lineWidthScale;
892
+ uniform float nodeSizeScale;
893
+ uniform float fixedSize;
894
+ uniform float mapMode;
895
+ uniform float mapDamping;
896
+ uniform float mapMaxGrowth; // shared semantics with node.vert.glsl; -1.0 = Infinity sentinel
897
+ uniform float maxScreenFraction; // shared semantics with node.vert.glsl; -1.0 = unbounded
898
+ uniform float sphereRadius;
899
+ uniform float arrowLengthWorld;
900
+ uniform float defaultEdgeShape;
901
+ uniform float radialAxis;
902
+ uniform float orthoCornerRadius; // 0..1, orthogonal corner rounding (see kv_orthoEdge.glsl)
903
+ uniform float edgeSegments; // strip segments per edge (geometry constant)
904
+ uniform sampler2D routeTexture; // routed edges' bend points (see kv_routedEdge.glsl)
905
+ uniform float routeTextureSize;
906
+ // Projection-consistent formula computes node world radius from shader size
907
+
908
+ attribute float sourceIndex;
909
+ attribute float targetIndex;
910
+ attribute float side;
911
+ attribute float along;
912
+ attribute float counters;
913
+ attribute vec3 edgeColor;
914
+ attribute float edgeWidth;
915
+ attribute float edgeOpacity;
916
+ attribute float edgeSelected;
917
+ attribute float edgeHighlighted;
918
+ attribute vec3 controlOffset;
919
+ attribute vec4 nodeSizes; // x,y: source / target size; z,w: their shape codes (see kv_shapes.glsl)
920
+ attribute float edgeFlags;
921
+
922
+ // Time uniform for shader-driven effects
923
+ uniform float time;
924
+ // Hover-neighbor-highlight: per-instance fade driven by edgeFlags upper bits
925
+ // (the timestamp, ms mod 2^19) compared against u_hoverTime.
926
+ uniform float u_hoverTime;
927
+ uniform float u_hoverDuration;
928
+
929
+ varying vec4 vColor;
930
+ varying float vCounters;
931
+ varying float vOpacity;
932
+ varying float vUseDash;
933
+ varying float vSelected;
934
+ varying float vFlow;
935
+ varying float vGlow;
936
+ varying float vSide;
937
+ varying float vTubeGlow;
938
+ varying float vHoverDim;
939
+ // Fine-line coverage: |vSide| at which the desired (possibly sub-pixel) line
940
+ // edge sits inside the min-width geometric strip. 1.0 = no thinning; <1 fades a
941
+ // thin line's alpha so it stays a crisp hairline instead of shimmering/fattening.
942
+ varying float vCoreEdge;
943
+
944
+ vec3 samplePosition(float idx) {
945
+ float texX = mod(idx, textureSize) + 0.5;
946
+ float texY = floor(idx / textureSize) + 0.5;
947
+ vec2 texCoord = vec2(texX, texY) / textureSize;
948
+ return texture2D(positionTexture, texCoord).xyz;
949
+ }
950
+
951
+ vec3 bezier(vec3 p0, vec3 p1, vec3 p2, float t) {
952
+ float t1 = 1.0 - t;
953
+ return t1 * t1 * p0 + 2.0 * t1 * t * p1 + t * t * p2;
954
+ }
955
+
956
+ // Spherical linear interpolation between two unit vectors \`a\` and \`b\`.
957
+ // Used by globe-mode edges to ride the great-circle arc instead of a
958
+ // chord-proportional bezier bulge. Falls back to straight \`mix\` when the
959
+ // endpoints are near-coincident (sinOmega \u2248 0) to avoid divide-by-zero.
960
+ vec3 slerp(vec3 a, vec3 b, float t) {
961
+ float cosOmega = clamp(dot(a, b), -1.0, 1.0);
962
+ float omega = acos(cosOmega);
963
+ float sinOmega = sin(omega);
964
+ if (sinOmega < 1e-5) return normalize(mix(a, b, t));
965
+ return (sin((1.0 - t) * omega) * a + sin(t * omega) * b) / sinOmega;
966
+ }
967
+
968
+ vec2 fix(vec4 pos, float aspect) {
969
+ vec2 res = pos.xy / pos.w;
970
+ res.x *= aspect;
971
+ return res;
972
+ }
973
+
974
+ vec3 rotateAroundAxis(vec3 v, vec3 axis, float angle) {
975
+ float c = cos(angle);
976
+ float s = sin(angle);
977
+ return v * c + cross(axis, v) * s + axis * dot(axis, v) * (1.0 - c);
978
+ }
979
+
980
+ vec3 computePerpendicular(vec3 dir) {
981
+ // Modified: Use Z-axis as reference for vertical plane curves
982
+ vec3 ref = abs(dir.z) < 0.99 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
983
+ return normalize(cross(dir, ref));
984
+ }
985
+
986
+ // Cubic bezier for S-curve tree edges
987
+ vec3 cubicBezier(vec3 p0, vec3 p1, vec3 p2, vec3 p3, float t) {
988
+ float t1 = 1.0 - t;
989
+ return t1*t1*t1*p0 + 3.0*t1*t1*t*p1 + 3.0*t1*t*t*p2 + t*t*t*p3;
990
+ }
991
+
992
+ // Radial S-curve: smooth tree edge using cubic bezier
993
+ // P0=src, P1=(src.x, midY), P2=(tgt.x, midY), P3=tgt (vertical routing)
994
+ // Creates smooth S-curve that exits parent vertically and arrives at child vertically
995
+ vec3 radialInterpolate(vec3 src, vec3 tgt, vec3 dir, float t, float axisMode) {
996
+ bool useVertical;
997
+ if (axisMode > 1.5) { useVertical = false; }
998
+ else if (axisMode > 0.5) { useVertical = true; }
999
+ else { useVertical = abs(dir.y) >= abs(dir.x); }
1000
+ vec3 cp1, cp2;
1001
+ if (useVertical) {
1002
+ float midY = (src.y + tgt.y) * 0.5;
1003
+ cp1 = vec3(src.x, midY, src.z);
1004
+ cp2 = vec3(tgt.x, midY, tgt.z);
1005
+ } else {
1006
+ float midX = (src.x + tgt.x) * 0.5;
1007
+ cp1 = vec3(midX, src.y, src.z);
1008
+ cp2 = vec3(midX, tgt.y, tgt.z);
1009
+ }
1010
+ return cubicBezier(src, cp1, cp2, tgt, t);
1011
+ }
1012
+
1013
+ void main() {
1014
+ float aspect = resolution.x / resolution.y;
1015
+
1016
+ vColor = vec4(edgeColor, edgeOpacity);
1017
+ vCounters = counters;
1018
+ vOpacity = edgeOpacity;
1019
+ // Unpack edgeFlags. Low 5 bits = flag bits (dashed/flow/glow/hoverDim);
1020
+ // upper 19 bits = hoverDim flip timestamp (ms mod 2^19). The flag-bit
1021
+ // unpacks below stay correct because timestamp*32 is always even when
1022
+ // divided by {2,4,8,16}.
1023
+ vUseDash = mod(edgeFlags, 2.0);
1024
+ vSelected = edgeSelected;
1025
+ vFlow = mod(floor(edgeFlags / 2.0), 2.0);
1026
+ vGlow = mod(floor(edgeFlags / 4.0), 2.0);
1027
+ vTubeGlow = mod(floor(edgeFlags / 8.0), 2.0);
1028
+ float _hoverTarget = mod(floor(edgeFlags / 16.0), 2.0);
1029
+ float _hoverStart = floor(edgeFlags / 32.0);
1030
+ float _hoverDiff = u_hoverTime - _hoverStart;
1031
+ if (_hoverDiff < 0.0) _hoverDiff += 524288.0;
1032
+ float _hoverT = _hoverStart < 0.5
1033
+ ? 1.0
1034
+ : clamp(_hoverDiff / max(u_hoverDuration, 1.0), 0.0, 1.0);
1035
+ float _hoverEased = _hoverT < 0.5
1036
+ ? 4.0 * _hoverT * _hoverT * _hoverT
1037
+ : 1.0 - pow(-2.0 * _hoverT + 2.0, 3.0) / 2.0;
1038
+ vHoverDim = mix(1.0 - _hoverTarget, _hoverTarget, _hoverEased);
1039
+ vSide = side;
1040
+
1041
+ // Self-loops are drawn by SelfLoopCloud. Eject this vertex outside clip
1042
+ // space so the GPU never rasterizes it (CPU-side zeroing can leave a
1043
+ // black phantom in some drivers \u2014 see arrow.vert.glsl for the same pattern).
1044
+ if (sourceIndex == targetIndex) {
1045
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
1046
+ return;
1047
+ }
1048
+
1049
+ vec3 srcPos = samplePosition(sourceIndex);
1050
+ vec3 tgtPos = samplePosition(targetIndex);
1051
+
1052
+ // Family (shape 5): the edge starts halfway between its source and the
1053
+ // anchor node (the other parent), and from there routes as orthogonal.
1054
+ float shape0 = controlOffset.z >= 0.0 ? controlOffset.z : defaultEdgeShape;
1055
+ bool familyAnchored = false;
1056
+ if (shape0 > 4.5 && shape0 < 5.5) {
1057
+ float anchorSlot = controlOffset.y - KV_ORTHO_EXPLICIT - 1.0;
1058
+ if (anchorSlot > -0.5) {
1059
+ srcPos = 0.5 * (srcPos + samplePosition(anchorSlot));
1060
+ familyAnchored = true;
1061
+ }
1062
+ }
1063
+
1064
+ vec3 edgeDir = tgtPos - srcPos;
1065
+ float edgeLength = length(edgeDir);
1066
+ // Threshold for the degenerate (overlapping endpoints) fallback. Was 0.001
1067
+ // \u2014 far too coarse for map mode, where world-coord positions are tiny
1068
+ // (lat/lng-derived ~0.06) and typical inter-station chords sit around
1069
+ // 1e-4..1e-3. Under the old threshold ~76% of metro edges fell back to
1070
+ // (0,1,0), causing arrows to point straight up and edge geometry to
1071
+ // mis-orient. The fallback is only needed for true self-overlap, so we
1072
+ // drop to 1e-9 (well above f32 division underflow) to keep the
1073
+ // degenerate guard without ever firing for distinct nodes.
1074
+ vec3 edgeNorm = edgeLength > 1e-9 ? edgeDir / edgeLength : vec3(0.0, 1.0, 0.0);
1075
+
1076
+ float curvature = controlOffset.x;
1077
+ float planeRotation = controlOffset.y;
1078
+
1079
+ // Node world radius per endpoint \u2014 perspective-correct with screen-pixel clamp.
1080
+ // Node shader (node.vert.glsl): pixelSize = nodeSize * 50.0 / viewDist * pixelRatio (clamped to [1.5, 4096]).
1081
+ // We replicate the formula, clamp to the same 4096 physical-pixel cap, then convert back to
1082
+ // world-space radius. The legacy 256 cap was a gl_PointSize hardware limit and no longer applies
1083
+ // to quad billboards; the previous detachment at high zoom is resolved by matching the node cap.
1084
+ float srcViewZ = abs((modelViewMatrix * vec4(srcPos, 1.0)).z);
1085
+ float tgtViewZ = abs((modelViewMatrix * vec4(tgtPos, 1.0)).z);
1086
+ float maxPS = 4096.0;
1087
+ float srcPixDiam, tgtPixDiam;
1088
+ if (mapMode > 0.5) {
1089
+ // MUST mirror node.vert.glsl's soft-asymptote curve so the edge endpoint
1090
+ // lands on the actual visible bubble boundary. Without this, edges stop
1091
+ // short of (or punch through) the bubble at deep zoom.
1092
+ // MUST stay in sync with node.vert.glsl / picking.vert.glsl.
1093
+ float refDepth = 10.0;
1094
+ float srcRef = nodeSizes.x * nodeSizeScale * (50.0 / refDepth);
1095
+ float tgtRef = nodeSizes.y * nodeSizeScale * (50.0 / refDepth);
1096
+ float srcRaw = pow(refDepth / srcViewZ, mapDamping);
1097
+ float tgtRaw = pow(refDepth / tgtViewZ, mapDamping);
1098
+ float srcGrowth = kvMapGrowth(srcRaw, mapMaxGrowth);
1099
+ float tgtGrowth = kvMapGrowth(tgtRaw, mapMaxGrowth);
1100
+ srcPixDiam = min(srcRef * srcGrowth, maxPS);
1101
+ tgtPixDiam = min(tgtRef * tgtGrowth, maxPS);
1102
+ } else {
1103
+ srcPixDiam = min(nodeSizes.x * nodeSizeScale * 50.0 / srcViewZ, maxPS);
1104
+ tgtPixDiam = min(nodeSizes.y * nodeSizeScale * 50.0 / tgtViewZ, maxPS);
1105
+ }
1106
+ // Near-camera cap on both endpoints \u2014 the same call, on the same nominal
1107
+ // diameter, as node.vert.glsl. Applied after the mode branch so it caps map
1108
+ // mode too, and before the shape-outline adjustment below so a capped square
1109
+ // still stops at its own outline.
1110
+ srcPixDiam = kvScreenCap(srcPixDiam, maxScreenFraction, resolution);
1111
+ tgtPixDiam = kvScreenCap(tgtPixDiam, maxScreenFraction, resolution);
1112
+ // Non-circle endpoints: stop at the outline along the edge direction, not at the bounding circle.
1113
+ // The arrow cone keeps the nominal (circle) radius, see arrow.vert.glsl.
1114
+ float tgtNominalDiam = tgtPixDiam;
1115
+ // Plain circles skip this block entirely, so their output is unchanged bit for bit.
1116
+ float srcShape = kvCodeShape(nodeSizes.z);
1117
+ float tgtShape = kvCodeShape(nodeSizes.w);
1118
+ float srcAspect = kvCodeAspect(nodeSizes.z);
1119
+ float tgtAspect = kvCodeAspect(nodeSizes.w);
1120
+ bool srcPlain = srcShape < 0.5 && abs(srcAspect - 1.0) < 1e-4;
1121
+ bool tgtPlain = tgtShape < 0.5 && abs(tgtAspect - 1.0) < 1e-4;
1122
+ if (!(srcPlain && tgtPlain)) {
1123
+ vec4 srcClip = projectionMatrix * (modelViewMatrix * vec4(srcPos, 1.0));
1124
+ vec4 tgtClip = projectionMatrix * (modelViewMatrix * vec4(tgtPos, 1.0));
1125
+ vec2 chordPx = (tgtClip.xy / tgtClip.w - srcClip.xy / srcClip.w) * resolution * 0.5;
1126
+ float chordLen = length(chordPx);
1127
+ vec2 chordDir = chordLen > 1e-4 ? chordPx / chordLen : vec2(1.0, 0.0);
1128
+ if (!srcPlain) srcPixDiam = 2.0 * kvShapeRadiusAlong(srcShape, srcAspect, srcPixDiam, chordDir);
1129
+ if (!tgtPlain) tgtPixDiam = 2.0 * kvShapeRadiusAlong(tgtShape, tgtAspect, tgtPixDiam, -chordDir);
1130
+ }
1131
+ // Shrink offset by 4% so edge overlaps with node ring instead of ending
1132
+ // at the transparent outer edge (ring fades at dist 0.48-0.50).
1133
+ float srcOffset = srcPixDiam * srcViewZ / (projectionMatrix[1][1] * resolution.y) * 0.96;
1134
+ float tgtOffset = tgtPixDiam * tgtViewZ / (projectionMatrix[1][1] * resolution.y) * 0.96;
1135
+ // A family edge starting between two parents starts on no node.
1136
+ if (familyAnchored) srcOffset = 0.0;
1137
+ // Clamp offsets so they don't exceed the edge length
1138
+ float totalOffset = srcOffset + tgtOffset;
1139
+ float clampFactor = totalOffset > edgeLength * 0.9 ? (edgeLength * 0.9) / totalOffset : 1.0;
1140
+ srcOffset *= clampFactor;
1141
+ tgtOffset *= clampFactor;
1142
+ float tgtConeOffset = tgtNominalDiam * tgtViewZ / (projectionMatrix[1][1] * resolution.y) * 0.96 * clampFactor;
1143
+ // Arrow cone clearance \u2014 used below to cap the rendered range of \`along\`
1144
+ // (see drawT_max). Bezier geometry is NOT shifted; only the visible
1145
+ // segment is shortened. Computed POST-clamp so the value matches the
1146
+ // post-clamp \`tgtWorldRadius\` arrow.vert.glsl uses to size the cone \u2014
1147
+ // otherwise edge and cone disagree on length when the clamp kicks in for
1148
+ // short edges. Mirrors arrow.vert.glsl: cone height (4) * arrowScale.y
1149
+ // (0.035) * regime factor (tgtWorldRadius*3 screen-constant, 0.3 world).
1150
+ float coneLen = 0.0;
1151
+ if (arrowLengthWorld > 0.5) {
1152
+ coneLen = (mapMode > 0.5 || fixedSize > 0.5)
1153
+ ? 4.0 * 0.035 * tgtConeOffset * 4.0
1154
+ : 4.0 * 0.035 * 0.3;
1155
+ }
1156
+ float shape = shape0;
1157
+ if (shape > 4.5 && shape < 5.5) shape = 3.0; // family: orthogonal from the moved start
1158
+ // Routed (shape 4) with no points draws straight.
1159
+ bool isRouted = shape > 3.5 && shape < 4.5 && controlOffset.y > 0.5;
1160
+ if (shape > 3.5 && shape < 4.5 && !isRouted) shape = 0.0;
1161
+ // Orthogonal (shape 3): routed by kv_orthoEdge.glsl below. Level endpoints
1162
+ // (no span along the routing axis) degrade to a straight edge.
1163
+ vec3 oP1, oP2, oD1, oD3;
1164
+ bool isOrtho = shape > 2.5 && shape < 3.5;
1165
+ if (isOrtho && !kvOrthoFrame(srcPos, tgtPos, controlOffset.xy, radialAxis, oP1, oP2, oD1, oD3)) {
1166
+ isOrtho = false;
1167
+ shape = 0.0;
1168
+ }
1169
+ // Radial: skip srcOffset (edges overlap at parent) and offset tgt along curve tangent
1170
+ vec3 tgtOffsetDir = edgeNorm;
1171
+ if (shape > 1.5 && shape < 2.5) {
1172
+ srcOffset = 0.0;
1173
+ // Cubic bezier tangent at t=1 is (P3-P2) direction
1174
+ bool ev; vec3 ecp2;
1175
+ if (radialAxis > 1.5) { ev = false; }
1176
+ else if (radialAxis > 0.5) { ev = true; }
1177
+ else { ev = abs(edgeDir.y) >= abs(edgeDir.x); }
1178
+ if (ev) { float my = (srcPos.y+tgtPos.y)*0.5; ecp2 = vec3(tgtPos.x,my,tgtPos.z); }
1179
+ else { float mx = (srcPos.x+tgtPos.x)*0.5; ecp2 = vec3(mx,tgtPos.y,tgtPos.z); }
1180
+ vec3 tang = tgtPos - ecp2;
1181
+ tgtOffsetDir = length(tang) > 0.0001 ? normalize(tang) : edgeNorm;
1182
+ }
1183
+ vec3 adjustedSrc = srcPos + edgeNorm * srcOffset;
1184
+ vec3 adjustedTgt = tgtPos - tgtOffsetDir * tgtOffset;
1185
+
1186
+ // Near-plane trim.
1187
+ //
1188
+ // This strip is built in SCREEN space: \`fix()\` divides by clip.w and the
1189
+ // widening offset is added in clip space. A vertex BEHIND the camera has
1190
+ // clip.w < 0, so that divide mirrors it through the origin, and the quad
1191
+ // between it and a still-visible neighbour stretches across the whole frame
1192
+ // as a flat sheet. No width cap can touch that \u2014 the width is right, the
1193
+ // POSITION is wrong \u2014 and a scene animation crosses the camera plane on
1194
+ // every pass, so it is the worst artifact of flying through a graph.
1195
+ //
1196
+ // Pull the endpoint that is behind forward along the segment until it sits
1197
+ // just in front of the camera plane. View-space z is affine along the
1198
+ // segment, so the crossing is exact. Done HERE, once per edge instance and
1199
+ // before the control point, the chord length and the polyline are derived
1200
+ // from these two points, so every vertex of the strip reaches the same
1201
+ // decision and the strip cannot tear. The same trim per vertex cannot: a
1202
+ // vertex whose two neighbours are both behind has nothing to lean on, and
1203
+ // its quad then straddles w = 0 anyway.
1204
+ //
1205
+ // A camera-crossing edge changes shape slightly (its curve is rebuilt from
1206
+ // the trimmed end). That is the right trade: the alternative is a sheet.
1207
+ // When BOTH ends are behind nothing is trimmed and nothing needs to be \u2014
1208
+ // every vertex has w < 0, and the hardware clips those triangles away.
1209
+ float zSrc = (modelViewMatrix * vec4(adjustedSrc, 1.0)).z;
1210
+ float zTgt = (modelViewMatrix * vec4(adjustedTgt, 1.0)).z;
1211
+ bool srcBehind = zSrc > -KV_NEAR_Z;
1212
+ bool tgtBehind = zTgt > -KV_NEAR_Z;
1213
+ if (srcBehind != tgtBehind) {
1214
+ // The ends straddle the plane, so zTgt - zSrc cannot be zero.
1215
+ float tNear = (-KV_NEAR_Z - zSrc) / (zTgt - zSrc);
1216
+ if (srcBehind) adjustedSrc = mix(adjustedSrc, adjustedTgt, tNear);
1217
+ else adjustedTgt = mix(adjustedSrc, adjustedTgt, tNear);
1218
+ }
1219
+ float effectiveCurvature = curvature;
1220
+ if (shape > 0.5 && shape < 1.5 && abs(curvature) < 0.001) { effectiveCurvature = 0.15; }
1221
+ vec3 adjustedDir = adjustedTgt - adjustedSrc;
1222
+
1223
+ // Globe mode: regular edges (shape < 1.5, excluding radial S-curves) ride
1224
+ // the great-circle arc via slerp instead of a chord-proportional bezier
1225
+ // bulge. Multi-edge fan separation is layered on as a perpendicular offset
1226
+ // scaled by sin(omega/2), so short Paris-internal edges collapse to near-
1227
+ // straight while cross-continent edges spread visibly. Per the design spec
1228
+ // (2026-05-25-globe-edge-greatcircle-design.md \xA76) this branch ignores the
1229
+ // legacy \`effectiveCurvature\` / \`isGlobeStraight\` synthesis.
1230
+ // Only ride the great-circle arc when BOTH endpoints are actually pinned on
1231
+ // the sphere surface (geo nodes: |pos| ~= sphereRadius). Non-geo (force-
1232
+ // layout) nodes sit at arbitrary radii near the origin; projecting their
1233
+ // edges onto the sphere (slerp(normalize(pos)) * sphereRadius) makes the
1234
+ // edge radiate off the node toward the silhouette. Those fall through to the
1235
+ // chord/curve branch so the edge connects the two real node positions.
1236
+ // Geo nodes land exactly on the radius; force clusters sit well inside it,
1237
+ // so a 10% band cleanly separates the two. MUST match arrow.vert.glsl.
1238
+ float srcSphereDist = length(srcPos);
1239
+ float tgtSphereDist = length(tgtPos);
1240
+ float sphereBand = sphereRadius * 0.1;
1241
+ bool bothOnSphere = abs(srcSphereDist - sphereRadius) < sphereBand
1242
+ && abs(tgtSphereDist - sphereRadius) < sphereBand;
1243
+ // Short arcs (city-scale edges on a globe) are visually straight, and the
1244
+ // great-circle endpoint pullback degenerates for them: when a node's radius
1245
+ // is a large fraction of the tiny arc, the arc-fraction saturates (clamped)
1246
+ // and the edge/arrow stops well inside the node \u2014 visible as edges punching
1247
+ // through the bubble at deep map zoom (e.g. adjacent Tube stations). Only ride
1248
+ // the great-circle arc for arcs long enough to visibly curve (~1.1\xB0); shorter
1249
+ // ones fall through to the straight/curve branch, whose chord pullback reaches
1250
+ // the node surface correctly (no 0.49 clamp). MUST match arrow.vert.glsl.
1251
+ float arcOmega = acos(clamp(dot(normalize(srcPos), normalize(tgtPos)), -1.0, 1.0));
1252
+ bool isSphereEdge = sphereRadius > 0.001 && shape < 1.5 && bothOnSphere && arcOmega > 0.02;
1253
+
1254
+ // Globe straight edges: DISABLED. The old behavior synthesized a 0.15*len
1255
+ // bulge for every straight edge in globe mode \u2014 but non-geo edges (now that
1256
+ // isSphereEdge is gated to geo-on-sphere endpoints) must look exactly like
1257
+ // 2D straight edges: dead straight unless the user actually enabled curve.
1258
+ // Keeping this true added an unwanted arc to non-geo edges even with curve
1259
+ // off. Geo edges ride isSphereEdge; curved edges ride shape/curvature below.
1260
+ bool isGlobeStraight = false;
1261
+ bool isCurveBranch = !isSphereEdge && !isOrtho && !isRouted && (shape > 0.5 || abs(effectiveCurvature) > 0.001);
1262
+
1263
+ // Sphere-edge precomputed quantities (only meaningful when isSphereEdge).
1264
+ // Kept at outer scope so prev/next sampling can reuse without recomputing.
1265
+ vec3 dirSrcS, dirTgtS, planeNormalS, arcMidDirS, perpMidS;
1266
+ float omegaS = 0.0;
1267
+ if (isSphereEdge) {
1268
+ // The node-radius gap (srcOffset/tgtOffset, a world-space radius) must be
1269
+ // applied as an ARC-LENGTH pullback along the great circle, NOT as a chord
1270
+ // subtraction. \`normalize(tgtPos - edgeNorm * tgtOffset)\` (the old form)
1271
+ // retreats the endpoint along the straight chord; for long edges the chord
1272
+ // dives through the globe interior, so re-normalizing barely changes the
1273
+ // angular position and the rendered arc \u2014 and the arrowhead mirroring it \u2014
1274
+ // collapse onto the node center instead of stopping one node-radius back
1275
+ // along the visible arc. Stepping each endpoint direction along the arc by
1276
+ // offset / sphereRadius radians keeps the gap a true on-surface distance,
1277
+ // so the edge/arrow meet the node boundary at every edge length and zoom.
1278
+ // MUST stay in sync with arrow.vert.glsl's isSphereArrow branch.
1279
+ vec3 dSrcRaw = normalize(srcPos);
1280
+ vec3 dTgtRaw = normalize(tgtPos);
1281
+ float omegaFull = acos(clamp(dot(dSrcRaw, dTgtRaw), -1.0, 1.0));
1282
+ // Pull each endpoint back along the arc by its node-radius worth of arc
1283
+ // length. Capping each fraction independently at 0.49 (the old form)
1284
+ // under-pulls the LARGER endpoint on short arcs \u2014 the pullback ends up far
1285
+ // less than the node radius, so the edge end lands INSIDE the node (visible
1286
+ // as edges punching through the bubble at deep map zoom). Instead cap the
1287
+ // COMBINED pullback at 0.98 of the arc and split it proportionally, so each
1288
+ // endpoint keeps as much of its full node-radius pullback as the arc allows
1289
+ // and the bigger node still wins its share. MUST stay in sync with
1290
+ // arrow.vert.glsl.
1291
+ //
1292
+ // Screen-foreshorten compensation: the node is a screen-facing billboard
1293
+ // (constant screen radius) but this pullback is a world arc-length along the
1294
+ // surface tangent. When that tangent dives toward the camera the pullback
1295
+ // projects to far fewer pixels than the node radius and the edge enters the
1296
+ // node disc (verified numerically: penetrating edges had foreshorten<0.6).
1297
+ // Scale each endpoint's pullback up by 1/foreshorten (clamped to 3.3x) so the
1298
+ // ON-SCREEN gap clears the node's screen radius; foreshorten==1 (tangent in
1299
+ // screen plane) leaves normal edges unchanged. MUST stay in sync with
1300
+ // arrow.vert.glsl.
1301
+ vec3 tanSrc = normalize(dTgtRaw - dot(dTgtRaw, dSrcRaw) * dSrcRaw);
1302
+ vec3 tanTgt = normalize(dSrcRaw - dot(dSrcRaw, dTgtRaw) * dTgtRaw);
1303
+ vec3 vDirSrc = normalize((modelViewMatrix * vec4(srcPos, 1.0)).xyz);
1304
+ vec3 vDirTgt = normalize((modelViewMatrix * vec4(tgtPos, 1.0)).xyz);
1305
+ vec3 tanSrcV = normalize((modelViewMatrix * vec4(tanSrc, 0.0)).xyz);
1306
+ vec3 tanTgtV = normalize((modelViewMatrix * vec4(tanTgt, 0.0)).xyz);
1307
+ float foreSrc = max(sqrt(max(0.0, 1.0 - pow(dot(tanSrcV, vDirSrc), 2.0))), 0.3);
1308
+ float foreTgt = max(sqrt(max(0.0, 1.0 - pow(dot(tanTgtV, vDirTgt), 2.0))), 0.3);
1309
+ float srcOffsetAdj = srcOffset / foreSrc;
1310
+ float tgtOffsetAdj = tgtOffset / foreTgt;
1311
+ float srcFracRaw = omegaFull > 1e-6 ? (srcOffsetAdj / sphereRadius) / omegaFull : 0.0;
1312
+ float tgtFracRaw = omegaFull > 1e-6 ? (tgtOffsetAdj / sphereRadius) / omegaFull : 0.0;
1313
+ float fracSum = srcFracRaw + tgtFracRaw;
1314
+ float fracK = fracSum > 0.98 ? 0.98 / fracSum : 1.0;
1315
+ float srcFrac = srcFracRaw * fracK;
1316
+ float tgtFrac = tgtFracRaw * fracK;
1317
+ dirSrcS = slerp(dSrcRaw, dTgtRaw, srcFrac);
1318
+ dirTgtS = slerp(dTgtRaw, dSrcRaw, tgtFrac);
1319
+ float cosO = clamp(dot(dirSrcS, dirTgtS), -1.0, 1.0);
1320
+ omegaS = acos(cosO);
1321
+ float sinO = sin(omegaS);
1322
+ // Plane normal of the great circle; degenerate (near-coincident
1323
+ // endpoints) falls back to world +Y to avoid NaN perp downstream.
1324
+ planeNormalS = sinO < 1e-5 ? vec3(0.0, 1.0, 0.0) : normalize(cross(dirSrcS, dirTgtS));
1325
+ }
1326
+
1327
+ // Compute controlPoint once (shared by drawT_max + position + prev/next).
1328
+ // For straight edges controlPoint is unused; reference distance falls back
1329
+ // to chord length.
1330
+ vec3 controlPoint;
1331
+ if (isCurveBranch) {
1332
+ vec3 midPoint = (adjustedSrc + adjustedTgt) * 0.5;
1333
+ // Bulge direction (issue: edge arc top up after 3D pitch).
1334
+ //
1335
+ // Goal: in map mode the arc crest must always face the viewport's top,
1336
+ // regardless of edge direction or scene pitch. The most robust reference
1337
+ // for "up in viewport" inside a vertex shader is the camera's local +Y
1338
+ // expressed in model space \u2014 derived as the first row of the upper-3x3
1339
+ // of \`modelViewMatrix\`, which is equivalent to \`transpose(mat3(mvm)) *
1340
+ // (0,1,0)\`. For pitched planar maps this resolves to a direction that
1341
+ // rotates back to world +Y after the scene's X rotation; for pitched
1342
+ // (camera-orbit) spherical maps it resolves to whatever world direction
1343
+ // the orbiting camera now treats as "up." Either way, after the full
1344
+ // model\u2192view transform the perpendicular ends up aligned with viewport +Y.
1345
+ //
1346
+ // Replaces both (a) the great-circle approximation used previously for
1347
+ // globeStraight edges (which produced direction-dependent bulges that
1348
+ // flipped above/below the horizon under pitch) and (b) the surface-normal
1349
+ // approach used in the prior fix (which only solved the planar case).
1350
+ //
1351
+ // Outside map mode the legacy lateral \`cross(edgeNorm, +Z)\` is kept so
1352
+ // non-map graphs retain their existing look.
1353
+ vec3 perp;
1354
+ if (mapMode > 0.5) {
1355
+ vec3 camUpInModel = vec3(
1356
+ modelViewMatrix[0][1],
1357
+ modelViewMatrix[1][1],
1358
+ modelViewMatrix[2][1]
1359
+ );
1360
+ vec3 proj = camUpInModel - dot(camUpInModel, edgeNorm) * edgeNorm;
1361
+ float l = length(proj);
1362
+ perp = l > 0.001 ? proj / l : computePerpendicular(edgeNorm);
1363
+ } else {
1364
+ perp = computePerpendicular(edgeNorm);
1365
+ }
1366
+ if (abs(planeRotation) > 0.001) {
1367
+ perp = rotateAroundAxis(perp, edgeNorm, planeRotation);
1368
+ }
1369
+ // Bulge magnitude: for explicitly curved edges use effectiveCurvature *
1370
+ // edgeLength (legacy). For globeStraight (sphere mode, curvature=0,
1371
+ // shape<0.5) synthesize a magnitude proportional to chord length so the
1372
+ // arc has visible height \u2014 tuned to roughly match the previous
1373
+ // great-circle crest height for typical inter-city edges.
1374
+ float bulgeMag = isGlobeStraight
1375
+ ? edgeLength * 0.15
1376
+ : effectiveCurvature * edgeLength;
1377
+ controlPoint = midPoint + perp * bulgeMag;
1378
+ }
1379
+
1380
+ // Cap the rendered range of \`along\` so the visible edge stops at the cone
1381
+ // base while the bezier geometry stays anchored at adjustedTgt (cone apex
1382
+ // position). For a quadratic bezier the tangent at t=1 is 2*(P2 - P1), so
1383
+ // near t=1 the curve advances ~ 2*|P2 - P1| world units per unit of t. That
1384
+ // makes 2*|P2 - P1| the right reference length to convert coneLen into a
1385
+ // parametric back-off \u2014 using chord length over-retracts on curves because
1386
+ // the curve's tangent at the endpoint is longer than the chord direction.
1387
+ // For straight edges controlPoint is the chord midpoint, so 2*|P2 - P1|
1388
+ // collapses back to chord length and the formula stays exact.
1389
+ float adjustedChordLen = length(adjustedDir);
1390
+ // Reference length used to convert world-space \`coneLen\` into a parametric
1391
+ // back-off (drawT_max). For straight edges it's the chord; for bezier
1392
+ // curves it's 2*|P2-P1| (tangent speed at t=1); for slerp arcs it's the
1393
+ // arc length omega*R (slerp has constant speed = omega*R per unit t).
1394
+ float refLen = isSphereEdge
1395
+ ? omegaS * sphereRadius
1396
+ : (isCurveBranch ? 2.0 * length(adjustedTgt - controlPoint) : adjustedChordLen);
1397
+ float drawT_max = refLen > 0.001
1398
+ ? clamp(1.0 - coneLen / refLen, 0.001, 1.0)
1399
+ : 1.0;
1400
+ float effAlong = along * drawT_max;
1401
+
1402
+ // Routed: one strip vertex per bend point; the ends leave the source towards
1403
+ // the first bend and enter the target from the last, pulled back off the discs.
1404
+ float rFirst = controlOffset.x, rCount = controlOffset.y;
1405
+ vec3 rA = srcPos, rB = tgtPos;
1406
+ float rI = 0.0;
1407
+ if (isRouted) {
1408
+ float f0, fN;
1409
+ vec3 firstBend = kvRoutedPoint(routeTexture, routeTextureSize, rFirst, rCount, 1.0, srcPos, tgtPos, srcPos, tgtPos, f0);
1410
+ vec3 lastBend = kvRoutedPoint(routeTexture, routeTextureSize, rFirst, rCount, rCount, srcPos, tgtPos, srcPos, tgtPos, fN);
1411
+ vec3 out0 = firstBend - srcPos, in1 = tgtPos - lastBend;
1412
+ rA = srcPos + (length(out0) > 1e-9 ? normalize(out0) : edgeNorm) * srcOffset;
1413
+ rB = tgtPos - (length(in1) > 1e-9 ? normalize(in1) : edgeNorm) * (tgtOffset + coneLen);
1414
+ rI = min(floor(along * edgeSegments + 0.5), rCount + 1.0);
1415
+ }
1416
+
1417
+ vec3 edgePosition;
1418
+ // Orthogonal: the whole strip comes from kvOrthoPoint. Ends leave / enter the
1419
+ // nodes along the routing axis; the arrow cone is cleared off leg3.
1420
+ vec3 oA = srcPos + oD1 * srcOffset;
1421
+ vec3 oB = tgtPos - oD1 * (tgtOffset + coneLen);
1422
+ float oS = 0.0, oL = 1.0;
1423
+ float oK = along * edgeSegments;
1424
+ if (isRouted) {
1425
+ float rf;
1426
+ edgePosition = kvRoutedPoint(routeTexture, routeTextureSize, rFirst, rCount, rI, srcPos, tgtPos, rA, rB, rf);
1427
+ vCounters = rf;
1428
+ } else if (isOrtho) {
1429
+ edgePosition = kvOrthoPoint(oK, edgeSegments, oA, oP1, oP2, oB, oD1, orthoCornerRadius, oS, oL);
1430
+ // Dash / flow / reveal run on arc length so they do not bunch up in corners.
1431
+ vCounters = oL > 1e-6 ? oS / oL : along;
1432
+ } else if (isSphereEdge) {
1433
+ // Great-circle arc on the sphere surface, plus a perpendicular fan
1434
+ // offset for multi-edges. Fan magnitude \`controlOffset.x * sin(omega/2)
1435
+ // * sphereRadius\` is the design's \u03B8-scaled separation rule \u2014 see
1436
+ // sphereMath.fanOffsetMag for the CPU mirror.
1437
+ vec3 arcDir = slerp(dirSrcS, dirTgtS, effAlong);
1438
+ vec3 arcPos = arcDir * sphereRadius;
1439
+ vec3 perpOnSphere = normalize(cross(arcDir, planeNormalS));
1440
+ float offsetMag = controlOffset.x * sin(omegaS * 0.5) * sphereRadius;
1441
+ edgePosition = arcPos + perpOnSphere * offsetMag;
1442
+ } else if (shape > 1.5 && shape < 2.5) {
1443
+ edgePosition = radialInterpolate(adjustedSrc, adjustedTgt, adjustedDir, effAlong, radialAxis);
1444
+ } else if (isCurveBranch) {
1445
+ // Straighten last 15% of curve into a straight line toward target.
1446
+ // This ensures the edge connects cleanly to the arrow at the node boundary.
1447
+ float blendStart = 0.85;
1448
+ vec3 bAtBlend = bezier(adjustedSrc, controlPoint, adjustedTgt, blendStart);
1449
+ if (effAlong > blendStart) {
1450
+ edgePosition = mix(bAtBlend, adjustedTgt, (effAlong - blendStart) / (1.0 - blendStart));
1451
+ } else {
1452
+ edgePosition = bezier(adjustedSrc, controlPoint, adjustedTgt, effAlong);
1453
+ }
1454
+ } else {
1455
+ edgePosition = mix(adjustedSrc, adjustedTgt, effAlong);
1456
+ }
1457
+
1458
+ mat4 mvp = projectionMatrix * modelViewMatrix;
1459
+ vec4 currentClip = mvp * vec4(edgePosition, 1.0);
1460
+
1461
+ // Prev/next sample neighbors on the rendered (capped) curve so the line
1462
+ // direction at the visible endpoint reflects the cone-aligned tangent.
1463
+ float prevEff = max(0.0, effAlong - 0.01);
1464
+ float nextEff = min(drawT_max, effAlong + 0.01);
1465
+
1466
+ vec3 prevPos, nextPos;
1467
+ if (isRouted) {
1468
+ float rf;
1469
+ prevPos = kvRoutedPoint(routeTexture, routeTextureSize, rFirst, rCount, max(rI - 1.0, 0.0), srcPos, tgtPos, rA, rB, rf);
1470
+ nextPos = kvRoutedPoint(routeTexture, routeTextureSize, rFirst, rCount, min(rI + 1.0, rCount + 1.0), srcPos, tgtPos, rA, rB, rf);
1471
+ } else if (isOrtho) {
1472
+ float dS, dL;
1473
+ prevPos = kvOrthoPoint(max(oK - 0.2, 0.0), edgeSegments, oA, oP1, oP2, oB, oD1, orthoCornerRadius, dS, dL);
1474
+ nextPos = kvOrthoPoint(min(oK + 0.2, edgeSegments), edgeSegments, oA, oP1, oP2, oB, oD1, orthoCornerRadius, dS, dL);
1475
+ } else if (isSphereEdge) {
1476
+ vec3 prevArcDir = slerp(dirSrcS, dirTgtS, prevEff);
1477
+ vec3 nextArcDir = slerp(dirSrcS, dirTgtS, nextEff);
1478
+ vec3 prevArcPos = prevArcDir * sphereRadius;
1479
+ vec3 nextArcPos = nextArcDir * sphereRadius;
1480
+ vec3 prevPerp = normalize(cross(prevArcDir, planeNormalS));
1481
+ vec3 nextPerp = normalize(cross(nextArcDir, planeNormalS));
1482
+ float prevOff = controlOffset.x * sin(omegaS * 0.5) * sphereRadius;
1483
+ float nextOff = controlOffset.x * sin(omegaS * 0.5) * sphereRadius;
1484
+ prevPos = prevArcPos + prevPerp * prevOff;
1485
+ nextPos = nextArcPos + nextPerp * nextOff;
1486
+ } else if (shape > 1.5 && shape < 2.5) {
1487
+ prevPos = radialInterpolate(adjustedSrc, adjustedTgt, adjustedDir, prevEff, radialAxis);
1488
+ nextPos = radialInterpolate(adjustedSrc, adjustedTgt, adjustedDir, nextEff, radialAxis);
1489
+ } else if (isCurveBranch) {
1490
+ float blendStart = 0.85;
1491
+ vec3 bAtBlend = bezier(adjustedSrc, controlPoint, adjustedTgt, blendStart);
1492
+ prevPos = prevEff > blendStart
1493
+ ? mix(bAtBlend, adjustedTgt, (prevEff - blendStart) / (1.0 - blendStart))
1494
+ : bezier(adjustedSrc, controlPoint, adjustedTgt, prevEff);
1495
+ nextPos = nextEff > blendStart
1496
+ ? mix(bAtBlend, adjustedTgt, (nextEff - blendStart) / (1.0 - blendStart))
1497
+ : bezier(adjustedSrc, controlPoint, adjustedTgt, nextEff);
1498
+ } else {
1499
+ prevPos = mix(adjustedSrc, adjustedTgt, prevEff);
1500
+ nextPos = mix(adjustedSrc, adjustedTgt, nextEff);
1501
+ }
1502
+
1503
+ vec4 prevClip = mvp * vec4(prevPos, 1.0);
1504
+ vec4 nextClip = mvp * vec4(nextPos, 1.0);
1505
+
1506
+ vec2 currentP = fix(currentClip, aspect);
1507
+ vec2 prevP = fix(prevClip, aspect);
1508
+ vec2 nextP = fix(nextClip, aspect);
1509
+
1510
+ float baseWidth = edgeWidth * lineWidthScale;
1511
+ if (edgeSelected > 0.5) baseWidth += 2.0 * lineWidthScale;
1512
+
1513
+ float pixelWidth = currentClip.w;
1514
+ float w;
1515
+
1516
+ // Two width regimes (mirrored in arrow.vert.glsl):
1517
+ // - World-scaled (legacy parity, default): w is clip-space constant, so
1518
+ // screen size = w/clip.w shrinks with distance \u2014 edges visibly grow on
1519
+ // zoom-in / shrink on zoom-out like legacy.
1520
+ // - Screen-constant: multiply by clip.w so it cancels in the perspective
1521
+ // divide. Used when nodes are at fixed screen size (fixedSize), and in
1522
+ // mapMode where camera-z range is huge (city-street \u2194 continent) and a
1523
+ // world-scaled line would either vanish or blow up.
1524
+ //
1525
+ // edgeScale = base screen-pixel thickness for the screen-constant regime
1526
+ // (fixedSize bumps it to 0.15 to match larger fixedSize nodes).
1527
+ // worldScale = 0.16 matches legacy clip-space width: legacy used 0.008
1528
+ // directly, new engine multiplies through lineWidthScale (default 0.05),
1529
+ // so 0.008 / 0.05 = 0.16 gives a default edge the same legacy look.
1530
+ float edgeScale = 1.0 / 15.0;
1531
+ float worldScale = 0.16;
1532
+ if (mapMode > 0.5 || fixedSize > 0.5) {
1533
+ float k = fixedSize > 0.5 ? 0.15 : edgeScale;
1534
+ w = 1.8 * pixelWidth * baseWidth * k;
1535
+ } else {
1536
+ w = 1.8 * baseWidth * worldScale;
1537
+ }
1538
+
1539
+ // Fine-line anti-aliasing (the deck.gl / Mapbox technique). Do NOT fatten a
1540
+ // thin line to stop it shimmering \u2014 instead draw it at a minimum geometric
1541
+ // width so the strip always covers \u2265~1px (MSAA-safe, no sub-pixel drop-out),
1542
+ // then carry the *desired* width as a coverage fraction so the fragment shader
1543
+ // fades the strip's alpha to match. A 0.3px arc is drawn ~1px wide at 0.3
1544
+ // coverage, reading as a delicate hairline \u2014 neither shimmering (sub-pixel)
1545
+ // nor fat (a hard min-width clamp). The on-screen half-width of the current
1546
+ // \`w\` is \`0.25 * w * resolution.y / pixelWidth\` (clip\u2192NDC divide then NDC\u2192px).
1547
+ float desiredHalfPx = 0.25 * w * resolution.y / max(pixelWidth, 1e-6);
1548
+ // Near-camera cap on the strip itself. The world-scaled regime keeps \`w\`
1549
+ // constant in clip space, so the on-screen width goes as 1/clip.w \u2014 an edge
1550
+ // the scene flies past had no upper bound at all and swept a band across the
1551
+ // frame. Cap the FULL width (hence \xD72 in, \xD70.5 out); everything downstream
1552
+ // still uses the real \`pixelWidth\`, so the clip\u2192pixel round-trip below stays
1553
+ // exact.
1554
+ //
1555
+ // An edge gets a SMALLER share of the budget than a node, because it spends
1556
+ // it differently: a capped bubble is a disc of the cap, a capped strip is a
1557
+ // band of the cap running the whole length of the frame. At EDGE_WIDTH_SHARE
1558
+ // an edge at its limit is about an eighth of a bubble at its limit, which is
1559
+ // roughly the proportion the two have at ordinary distances \u2014 so the cap
1560
+ // reads as "the line got thick", not as "a wall crossed the screen". The
1561
+ // first version of this gave both the same share, and the A/B screenshots
1562
+ // showed the bubble tamed and the band still taking a third of the frame.
1563
+ desiredHalfPx = kvScreenCap(
1564
+ desiredHalfPx * 2.0, maxScreenFraction * EDGE_WIDTH_SHARE, resolution) * 0.5;
1565
+ float MIN_HALF_PX = 0.5;
1566
+ float drawHalfPx = max(desiredHalfPx, MIN_HALF_PX);
1567
+ vCoreEdge = clamp(desiredHalfPx / drawHalfPx, 0.0, 1.0); // 1 for thick, <1 fades sub-pixel
1568
+ w = drawHalfPx * 4.0 * pixelWidth / resolution.y; // round-trips to the original w when not thinning
1569
+
1570
+ vec2 dir;
1571
+ if (nextP == currentP) dir = normalize(currentP - prevP);
1572
+ else if (prevP == currentP) dir = normalize(nextP - currentP);
1573
+ else dir = normalize(normalize(currentP - prevP) + normalize(nextP - currentP));
1574
+
1575
+ vec2 normal = vec2(-dir.y, dir.x);
1576
+ normal.x /= aspect;
1577
+ // Tube glow: widen the strip so the soft halo has room outside the solid core.
1578
+ // The visible solid core stays at the original width (the fragment uses coreFrac).
1579
+ w *= 1.0 + vTubeGlow * GLOW_WIDEN_K;
1580
+ normal *= 0.5 * w;
1581
+
1582
+ vec4 finalPosition = currentClip;
1583
+ finalPosition.xy += normal * side;
1584
+
1585
+ // Globe mode: per-vertex back-face culling (same approach as nodes).
1586
+ // depthTest is disabled in globe mode, so we hide back-facing edges here.
1587
+ // Each vertex along the edge is checked individually using its actual
1588
+ // position on the great-circle arc \u2014 not just the midpoint.
1589
+ // This correctly hides the portion of an edge that crosses the globe horizon.
1590
+ if (sphereRadius > 0.001) {
1591
+ vec3 wN = normalize(mat3(modelMatrix) * normalize(edgePosition));
1592
+ vec3 wP = (modelMatrix * vec4(edgePosition, 1.0)).xyz;
1593
+ if (dot(wN, normalize(cameraPosition - wP)) < 0.0) {
1594
+ vOpacity = 0.0;
1595
+ }
1596
+ }
1597
+
1598
+ gl_Position = finalPosition;
1599
+ }
1600
+ `;var Ae=`precision highp float;
1601
+
1602
+ const float GLOW_WIDEN_K = 3.0; // MUST match edge.vert.glsl
1603
+ const float GLOW_GAIN = 1.2; // additive rgb gain
1604
+ const float GLOW_ALPHA = 0.6; // halo alpha ceiling
1605
+
1606
+ uniform float globalUseDash;
1607
+ uniform float globalDashArray;
1608
+ uniform float globalDashOffset;
1609
+ uniform float globalDashRatio;
1610
+ uniform float visibility;
1611
+ uniform float alphaTest;
1612
+
1613
+ // Time uniform for shader-driven effects
1614
+ uniform float time;
1615
+
1616
+ // Flow particles (EdgeFlowEffect): global speed multiplier (1.0 = base
1617
+ // 0.8 counters/sec) and particle color. Synced from edgeState by the renderer.
1618
+ uniform float flowSpeed;
1619
+ uniform vec3 flowColor;
1620
+
1621
+ // Hover dim: when a node/edge is hovered, non-neighbor edges fade to
1622
+ // u_hoverDimOpacity. u_hoverProgress animates 0\u21921 over the hover-in duration.
1623
+ uniform float u_hoverProgress;
1624
+ uniform float u_hoverDimOpacity;
1625
+
1626
+ varying vec4 vColor;
1627
+ varying float vCounters;
1628
+ varying float vOpacity;
1629
+ varying float vUseDash;
1630
+ varying float vSelected;
1631
+ varying float vFlow;
1632
+ varying float vGlow;
1633
+ varying float vHoverDim;
1634
+ varying float vSide;
1635
+ varying float vTubeGlow;
1636
+ varying float vCoreEdge;
1637
+
1638
+ void main() {
1639
+ vec4 c = vColor;
1640
+
1641
+ if (c.a < alphaTest) discard;
1642
+
1643
+ if (vUseDash > 0.5) {
1644
+ c.a *= ceil(mod(vCounters, 0.05) - 0.025);
1645
+ } else if (globalUseDash > 0.5) {
1646
+ c.a *= ceil(mod(vCounters - globalDashOffset, globalDashArray) - (globalDashArray * globalDashRatio));
1647
+ }
1648
+
1649
+ gl_FragColor = c;
1650
+ gl_FragColor.a *= vOpacity * step(vCounters, visibility);
1651
+
1652
+ // Coverage-based anti-aliasing for crisp, fine hairlines. \`vCoreEdge\` is the
1653
+ // |vSide| where the desired line edge sits inside the min-width geometric
1654
+ // strip (1.0 for normal lines; <1 when the vertex shader widened a sub-pixel
1655
+ // line and asked us to fade it back). The fade spans ~1px (fwidth) centred on
1656
+ // that edge, so a thin line resolves to a smooth, delicate stroke instead of
1657
+ // a shimmering sub-pixel ribbon or a fattened band. Skipped when tube-glow
1658
+ // owns the border region (it has its own soft falloff).
1659
+ if (vTubeGlow <= 0.0) {
1660
+ float aa = fwidth(vSide);
1661
+ float edgeAA = 1.0 - smoothstep(vCoreEdge - aa, vCoreEdge + aa, abs(vSide));
1662
+ gl_FragColor.a *= edgeAA;
1663
+ }
1664
+
1665
+ if (vSelected > 0.5) {
1666
+ gl_FragColor.rgb = gl_FragColor.rgb * 1.2 + vec3(0.0, 0.2, 0.5) * 0.3;
1667
+ }
1668
+
1669
+ // Effect dim factor: the alpha-raising effects below (flow, glow stream)
1670
+ // use max() against the base alpha, which would otherwise RESURRECT
1671
+ // fragments that were dimmed or hidden upstream. They must respect:
1672
+ // - vOpacity: focusContext / per-edge dim (also 0 on the globe's far
1673
+ // side \u2014 the vertex shader culls back-facing edges via vOpacity = 0,
1674
+ // so this is what keeps particles from shining through the planet);
1675
+ // - step(vCounters, visibility): the edgeDraw reveal front.
1676
+ float effectDim = vOpacity * step(vCounters, visibility);
1677
+
1678
+ // Flow particles: dots moving along edge. flowSpeed/flowColor come from
1679
+ // EdgeFlowConfig via the renderer uniforms (1.0 = base 0.8 counters/sec).
1680
+ if (vFlow > 0.0) {
1681
+ float gap = 0.08;
1682
+ float dotSize = 0.015;
1683
+ float phase = mod(vCounters - time * 0.8 * flowSpeed, gap);
1684
+ float dist = abs(phase - gap * 0.5) / dotSize;
1685
+ if (dist < 1.0) {
1686
+ float flowGlow = (1.0 - dist * dist) * vFlow * effectDim;
1687
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, flowColor, flowGlow * 0.9);
1688
+ gl_FragColor.a = max(gl_FragColor.a, flowGlow * 0.8);
1689
+ }
1690
+ }
1691
+
1692
+ // Glow stream: traveling light along edge
1693
+ if (vGlow > 0.0) {
1694
+ float glowSpeed = 0.5;
1695
+ float tailLen = 0.15;
1696
+ float headPos = fract(time * glowSpeed);
1697
+ float d = vCounters - headPos;
1698
+ if (d < 0.0) d += 1.0;
1699
+ if (d < tailLen) {
1700
+ float intensity = (1.0 - d / tailLen);
1701
+ intensity = intensity * intensity * vGlow * effectDim;
1702
+ gl_FragColor.rgb += vec3(0.3, 0.6, 1.0) * intensity * 1.5;
1703
+ gl_FragColor.a = max(gl_FragColor.a, intensity * 0.7);
1704
+ }
1705
+ }
1706
+
1707
+ // Tube glow \u2192 additive light (premultiplied-alpha pipeline). In the halo
1708
+ // region we KILL the solid base (a=0) and emit additive glow instead; the
1709
+ // solid core (|vSide| < coreFrac) is left untouched.
1710
+ vec3 glowAdd = vec3(0.0);
1711
+ if (vTubeGlow > 0.0) {
1712
+ float coreFrac = 1.0 / (1.0 + vTubeGlow * GLOW_WIDEN_K);
1713
+ float a = abs(vSide);
1714
+ if (a > coreFrac) {
1715
+ float preA = gl_FragColor.a; // dash/visibility/opacity mask
1716
+ float edgeDist = (a - coreFrac) / max(1.0 - coreFrac, 1e-3);
1717
+ float falloff = 1.0 - smoothstep(0.0, 1.0, edgeDist);
1718
+ gl_FragColor.a = 0.0; // no solid fill in the halo region
1719
+ // \xD7 vOpacity: preA is only a binary gate; the additive halo must dim
1720
+ // with the edge under focusContext, not just vanish at preA == 0.
1721
+ glowAdd = vColor.rgb * falloff * GLOW_GAIN * step(0.0001, preA) * vOpacity;
1722
+ }
1723
+ }
1724
+
1725
+ // Hover dim (straight alpha) \u2014 also dims residual glow.
1726
+ float hoverDimMul = mix(1.0, u_hoverDimOpacity, vHoverDim * u_hoverProgress);
1727
+ gl_FragColor.a *= hoverDimMul;
1728
+ glowAdd *= hoverDimMul;
1729
+
1730
+ // Premultiplied-alpha output: premultiply the solid part, then add additive glow.
1731
+ gl_FragColor.rgb *= gl_FragColor.a;
1732
+ gl_FragColor.rgb += glowAdd;
1733
+
1734
+ // Keep additive-only pixels (a\u22480 but glow present).
1735
+ if (gl_FragColor.a < 0.01 && dot(glowAdd, glowAdd) < 1e-8) discard;
1736
+ }
1737
+ `;var Fe=`// Mirrors node.vert.glsl billboard math. Intentionally omits breathe / ripple
1738
+ // (animation) \u2014 picking should be stable, not pulse with visual effects. But
1739
+ // MUST mirror the min/max pixelSize clamp from node.vert.glsl (\`minPixelSize\`
1740
+ // floor, default 1.5 px, never under 1.5 px here; 4096 px ceil): the visual quad
1741
+ // is floored so far-camera nodes stay visible, and the picker hitbox MUST match \u2014 otherwise distant nodes become
1742
+ // sub-pixel in the picking buffer and clicks miss them entirely (only a few
1743
+ // near-camera nodes register). Keep the size + projection block in sync with
1744
+ // node.vert.glsl when changing per-node sizing semantics.
1745
+ precision highp float;
1746
+
1747
+ uniform sampler2D positionTexture;
1748
+ uniform float textureSize;
1749
+ uniform float spaceSize;
1750
+ uniform float fixedSize;
1751
+ uniform float nodeSizeScale;
1752
+ uniform float mapMode;
1753
+ uniform float mapDamping;
1754
+ uniform float mapMaxGrowth; // shared semantics with node.vert.glsl
1755
+ uniform float maxScreenFraction; // MUST match node.vert.glsl, or the hitbox outgrows the quad
1756
+ uniform float pixelRatio;
1757
+ uniform float minPixelSize; // node.vert.glsl's floor; the hitbox never goes under 1.5 px
1758
+ uniform float sphereRadius;
1759
+ uniform vec2 resolution;
1760
+ attribute float nodeIndex;
1761
+ attribute vec3 idColor;
1762
+ attribute float nodeSize;
1763
+ attribute float nodeFlags;
1764
+ #ifndef KV_POINT_PRIMITIVE
1765
+ attribute vec2 corner;
1766
+ #else
1767
+ uniform float maxPointSize; // ALIASED_POINT_SIZE_RANGE max, device px; as node.vert.glsl
1768
+ #endif
1769
+ attribute float nodeSuppressFill; // suppress + 2 * shapeId; must match node.vert.glsl
1770
+ attribute vec4 nodeEffects; // w = aspect
1771
+
1772
+ varying vec3 vIdColor;
1773
+ varying float vHidden;
1774
+ #ifndef KV_POINT_PRIMITIVE
1775
+ varying vec2 vUv;
1776
+ #endif
1777
+ varying float vShape;
1778
+
1779
+ vec3 samplePosition(float idx) {
1780
+ float texX = mod(idx, textureSize) + 0.5;
1781
+ float texY = floor(idx / textureSize) + 0.5;
1782
+ vec2 texCoord = vec2(texX, texY) / textureSize;
1783
+ return texture2D(positionTexture, texCoord).xyz;
1784
+ }
1785
+
1786
+ void main() {
1787
+ vIdColor = idColor;
1788
+ // Unpack nodeFlags
1789
+ float nodeSelected = mod(nodeFlags, 2.0);
1790
+ float nodeHighlighted = mod(floor(nodeFlags / 2.0), 2.0);
1791
+ vHidden = mod(floor(nodeFlags / 8.0), 2.0);
1792
+
1793
+ vec3 sampledPos = samplePosition(nodeIndex);
1794
+ vec3 finalPosition = sampledPos;
1795
+
1796
+ vec4 mvCenter = modelViewMatrix * vec4(finalPosition, 1.0);
1797
+
1798
+ // Must match nodeVertexShader exactly (same formula) so picking hitbox aligns with visual.
1799
+ // The 1.1 factor is picking-only \u2014 adds slack to the hitbox so edge clicks still register.
1800
+ float scaledSize = nodeSize * nodeSizeScale;
1801
+ float viewDepth = max(-mvCenter.z, 0.001);
1802
+ float baseSize;
1803
+ if (mapMode > 0.5) {
1804
+ float refDepth = 10.0;
1805
+ float refSize = scaledSize * (50.0 / refDepth);
1806
+ // MUST mirror the soft-asymptote curve in node.vert.glsl exactly \u2014 same
1807
+ // softKnee derivation, same mapMaxGrowth \u2014 so the hitbox tracks the visible
1808
+ // bubble at every zoom level (no click-far-from-node bug).
1809
+ float raw = pow(refDepth / viewDepth, mapDamping);
1810
+ float growth = kvMapGrowth(raw, mapMaxGrowth);
1811
+ baseSize = refSize * growth;
1812
+ } else {
1813
+ baseSize = scaledSize * (50.0 / viewDepth);
1814
+ }
1815
+ float sizeMultiplier = (nodeSelected > 0.5 || nodeHighlighted > 0.5) ? 1.5 : 1.0;
1816
+ // Match node.vert.glsl: pixelSize is in CSS pixels, NOT physical pixels.
1817
+ // node.vert.glsl does NOT multiply by pixelRatio (see its comments).
1818
+ // The render target is at physical-pixel resolution, but offsetClip divides
1819
+ // by CSS-px resolution, and the viewport transform multiplies by pixelRatio \u2014
1820
+ // so pixelRatio cancels naturally. Adding it here would make the hitbox
1821
+ // pixelRatio\xD7 too large (2.2\xD7 on Retina instead of 1.1\xD7).
1822
+ float pixelSize = baseSize * sizeMultiplier * 1.1;
1823
+ // Mirror node.vert.glsl's near-camera cap, at the same point: on the finished
1824
+ // quad. Without it a node the camera passes close renders capped but stays
1825
+ // clickable across the whole screen, and every click in the frame hits it.
1826
+ // The 1.1 slack is inside the cap on both sides of the comparison, so the
1827
+ // hitbox keeps its relationship to the visible quad at the limit too.
1828
+ pixelSize = kvScreenCap(pixelSize, maxScreenFraction, resolution);
1829
+ // Mirror node.vert.glsl's clamp(1.5, 4096). The 1.5 floor is critical:
1830
+ // node.vert.glsl applies it so far-camera nodes stay at least 1.5 px on
1831
+ // screen (visible). Without the same floor here, the picker hitbox shrinks
1832
+ // sub-pixel for distant nodes and they vanish from the picking buffer \u2014
1833
+ // result: only near-camera nodes are clickable. The 4096 ceil prevents
1834
+ // near-camera zoom-in from growing hitbox past the visible quad.
1835
+ // A host floor above 1.5 (\`minPixelSize\`) raises the hitbox with the quad;
1836
+ // one below it does not shrink the hitbox, so dots stay clickable.
1837
+ pixelSize = clamp(pixelSize, max(minPixelSize, 1.5), 4096.0);
1838
+
1839
+ vec4 clipCenter = projectionMatrix * mvCenter;
1840
+ vShape = floor(nodeSuppressFill * 0.5);
1841
+ #ifdef KV_POINT_PRIMITIVE
1842
+ // Point primitive: one vertex per node, as node.vert.glsl. gl_PointSize is in
1843
+ // device px and capped by the GPU at the same size the visible sprite is.
1844
+ gl_PointSize = min(pixelSize * pixelRatio, maxPointSize);
1845
+ gl_Position = clipCenter;
1846
+ #else
1847
+ float shapeAspect = nodeEffects.w > 0.0 ? nodeEffects.w : 1.0;
1848
+ vec2 offsetClip = vec2(corner.x, corner.y / shapeAspect) * pixelSize / resolution * 2.0 * clipCenter.w;
1849
+ gl_Position = clipCenter + vec4(offsetClip, 0.0, 0.0);
1850
+ // Y-down to match node.vert.glsl (gl_PointCoord convention). See node.vert.glsl for rationale.
1851
+ vUv = vec2(corner.x + 0.5, 0.5 - corner.y);
1852
+ #endif
1853
+
1854
+ // Globe mode: vertex-level back-face culling (must match nodeVertexShader).
1855
+ if (sphereRadius > 0.001) {
1856
+ vec3 wN = normalize(mat3(modelMatrix) * normalize(finalPosition));
1857
+ vec3 wP = (modelMatrix * vec4(finalPosition, 1.0)).xyz;
1858
+ if (dot(wN, normalize(cameraPosition - wP)) < 0.0) {
1859
+ // Push the quad off-screen (NDC outside [-1,1]) so all 4 corners are clipped.
1860
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
1861
+ }
1862
+ }
1863
+ }
1864
+ `;var Ee=`precision highp float;
1865
+
1866
+ varying vec3 vIdColor;
1867
+ varying float vHidden;
1868
+ #ifndef KV_POINT_PRIMITIVE
1869
+ varying vec2 vUv;
1870
+ #endif
1871
+ varying float vShape;
1872
+
1873
+ uniform float useCircle;
1874
+
1875
+ void main() {
1876
+ if (vHidden > 0.5) discard;
1877
+
1878
+ if (useCircle > 0.5) {
1879
+ #ifdef KV_POINT_PRIMITIVE
1880
+ vec2 c = gl_PointCoord - vec2(0.5);
1881
+ #else
1882
+ vec2 c = vUv - vec2(0.5);
1883
+ #endif
1884
+ // Same outline the node fragment shader draws: the hitbox IS the visible shape.
1885
+ float r = vShape > 0.5 ? 0.5 + kvShapeSdf(vShape, vec2(c.x, -c.y)) : length(c);
1886
+ if (r > 0.5) discard;
1887
+ }
1888
+
1889
+ gl_FragColor = vec4(vIdColor, 1.0);
1890
+ }
1891
+ `;var Ie=`precision highp float;
1892
+
1893
+ uniform sampler2D positionTexture;
1894
+ uniform float textureSize;
1895
+ uniform float spaceSize;
1896
+ uniform float useCurve;
1897
+ uniform vec2 resolution;
1898
+ uniform float fixedSize;
1899
+ uniform float nodeSizeScale;
1900
+ uniform float mapMode;
1901
+ uniform float mapDamping;
1902
+ uniform float mapMaxGrowth; // shared semantics with node.vert.glsl; -1.0 = Infinity sentinel
1903
+ uniform float maxScreenFraction; // shared semantics with node.vert.glsl; -1.0 = unbounded
1904
+ uniform float sphereRadius;
1905
+
1906
+ // Per-instance attributes
1907
+ attribute float sourceIndex;
1908
+ attribute float targetIndex;
1909
+ attribute vec3 arrowColor;
1910
+ attribute float arrowOpacity;
1911
+ attribute vec3 arrowScale;
1912
+ attribute float arrowRotation;
1913
+ attribute vec2 targetSize; // x size, y shape code
1914
+ attribute vec2 sourceSize;
1915
+ attribute vec3 controlOffset;
1916
+ attribute float edgeSelected;
1917
+ // Hover-neighbor-highlight: packed \`target + start_ts * 2\`. Low bit = the
1918
+ // target dim state (0/1); upper 23 bits = ms-since-epoch (mod 2^19) when
1919
+ // the target last flipped. Start = 0 is a sentinel: never animated \u2192 no
1920
+ // fade, render at target.
1921
+ attribute float aHoverDim;
1922
+
1923
+ uniform float u_hoverTime;
1924
+ uniform float u_hoverDuration;
1925
+
1926
+ uniform float defaultEdgeShape;
1927
+ uniform float radialAxis;
1928
+ uniform sampler2D routeTexture; // routed edges' bend points (see kv_routedEdge.glsl)
1929
+ uniform float routeTextureSize;
1930
+
1931
+ varying vec3 vColor;
1932
+ varying float vOpacity;
1933
+ varying float vSelected;
1934
+ varying float vHoverDim;
1935
+
1936
+ vec3 samplePosition(float idx) {
1937
+ float texX = mod(idx, textureSize) + 0.5;
1938
+ float texY = floor(idx / textureSize) + 0.5;
1939
+ vec2 texCoord = vec2(texX, texY) / textureSize;
1940
+ return texture2D(positionTexture, texCoord).xyz;
1941
+ }
1942
+
1943
+ // Apply quaternion rotation to position (matches CPU quaternion() helper)
1944
+ vec3 applyQuaternion(vec3 pos, vec4 q) {
1945
+ return pos + 2.0 * cross(q.xyz, cross(q.xyz, pos) + q.w * pos);
1946
+ }
1947
+
1948
+ // Build rotation matrix around axis - matches lineCloud.js rotationMatrix()
1949
+ mat4 rotationMatrix(vec3 axis, float angle) {
1950
+ axis = normalize(axis);
1951
+ float s = sin(angle);
1952
+ float c = cos(angle);
1953
+ float oc = 1.0 - c;
1954
+ return mat4(
1955
+ oc*axis.x*axis.x+c, oc*axis.x*axis.y-axis.z*s, oc*axis.z*axis.x+axis.y*s, 0.0,
1956
+ oc*axis.x*axis.y+axis.z*s, oc*axis.y*axis.y+c, oc*axis.y*axis.z-axis.x*s, 0.0,
1957
+ oc*axis.z*axis.x-axis.y*s, oc*axis.y*axis.z+axis.x*s, oc*axis.z*axis.z+c, 0.0,
1958
+ 0.0, 0.0, 0.0, 1.0);
1959
+ }
1960
+
1961
+ // Compute direction quaternion - matches lineCloud.js getDirection()
1962
+ vec4 getDirectionQuaternion(vec3 dir) {
1963
+ vec4 q;
1964
+ if (dir.y > 0.99999) {
1965
+ q = vec4(0.0, 0.0, 0.0, 1.0);
1966
+ } else if (dir.y < -0.99999) {
1967
+ q = vec4(1.0, 0.0, 0.0, 0.0);
1968
+ } else {
1969
+ vec3 axis = normalize(vec3(dir.z, 0.0, -dir.x));
1970
+ float angle = acos(dir.y);
1971
+ float s = sin(angle * 0.5);
1972
+ float c = cos(angle * 0.5);
1973
+ q = vec4(axis * s, c);
1974
+ }
1975
+ return q;
1976
+ }
1977
+
1978
+ // Compute perpendicular vector to a direction (matches edge shader)
1979
+ vec3 computePerpendicular(vec3 dir) {
1980
+ vec3 ref = abs(dir.z) < 0.99 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
1981
+ return normalize(cross(dir, ref));
1982
+ }
1983
+
1984
+ // Rotate vector around axis by angle (matches edge shader)
1985
+ vec3 rotateAroundAxis(vec3 v, vec3 axis, float angle) {
1986
+ float c = cos(angle);
1987
+ float s = sin(angle);
1988
+ return v * c + cross(axis, v) * s + axis * dot(axis, v) * (1.0 - c);
1989
+ }
1990
+
1991
+ // Quadratic bezier evaluation
1992
+ vec3 bezier(vec3 p0, vec3 p1, vec3 p2, float t) {
1993
+ float t1 = 1.0 - t;
1994
+ return t1 * t1 * p0 + 2.0 * t1 * t * p1 + t * t * p2;
1995
+ }
1996
+
1997
+ // Quadratic bezier tangent (derivative): B'(t) = 2(1-t)(P1-P0) + 2t(P2-P1)
1998
+ vec3 bezierTangent(vec3 p0, vec3 p1, vec3 p2, float t) {
1999
+ return 2.0 * (1.0 - t) * (p1 - p0) + 2.0 * t * (p2 - p1);
2000
+ }
2001
+
2002
+ // Great-circle slerp + tangent-at-endpoint helpers. MUST stay in sync with
2003
+ // edge.vert.glsl \`slerp\` so the arrow tip sits exactly on the arc geometry
2004
+ // the edge shader rendered. See sphereMath.ts for the CPU mirror used by
2005
+ // EdgeTextCloud and the acceptance probes.
2006
+ vec3 slerp(vec3 a, vec3 b, float t) {
2007
+ float cosOmega = clamp(dot(a, b), -1.0, 1.0);
2008
+ float omega = acos(cosOmega);
2009
+ float sinOmega = sin(omega);
2010
+ if (sinOmega < 1e-5) return normalize(mix(a, b, t));
2011
+ return (sin((1.0 - t) * omega) * a + sin(t * omega) * b) / sinOmega;
2012
+ }
2013
+
2014
+ // Unit tangent at the slerp endpoint (t = 1). Used to orient the arrowhead
2015
+ // along the arc rather than along the chord \u2014 without this, arrowheads for
2016
+ // long-arc edges (e.g. Paris\u2192Tokyo) point in the wrong direction at the
2017
+ // target node.
2018
+ vec3 arcTangentAtEnd(vec3 a, vec3 b) {
2019
+ float cosOmega = clamp(dot(a, b), -1.0, 1.0);
2020
+ float omega = acos(cosOmega);
2021
+ float sinOmega = sin(omega);
2022
+ if (sinOmega < 1e-5) return normalize(b - a);
2023
+ return normalize((cosOmega * b - a) * (omega / sinOmega));
2024
+ }
2025
+
2026
+ void main() {
2027
+ vColor = arrowColor;
2028
+ vOpacity = arrowOpacity;
2029
+ vSelected = edgeSelected;
2030
+ // Unpack hoverDim: low bit = target, upper bits = start timestamp.
2031
+ float _hoverTarget = mod(aHoverDim, 2.0);
2032
+ float _hoverStart = floor(aHoverDim / 2.0);
2033
+ float _hoverDiff = u_hoverTime - _hoverStart;
2034
+ if (_hoverDiff < 0.0) _hoverDiff += 524288.0;
2035
+ float _hoverT = _hoverStart < 0.5
2036
+ ? 1.0
2037
+ : clamp(_hoverDiff / max(u_hoverDuration, 1.0), 0.0, 1.0);
2038
+ float _hoverEased = _hoverT < 0.5
2039
+ ? 4.0 * _hoverT * _hoverT * _hoverT
2040
+ : 1.0 - pow(-2.0 * _hoverT + 2.0, 3.0) / 2.0;
2041
+ vHoverDim = mix(1.0 - _hoverTarget, _hoverTarget, _hoverEased);
2042
+
2043
+ // Self-loops are drawn by SelfLoopCloud, not here. The CPU side zeros all
2044
+ // attributes (arrowScale, arrowOpacity, etc.) hoping the cone collapses to a
2045
+ // point, but that left a visible black phantom in some drivers (degenerate
2046
+ // triangles aren't reliably culled, or pos*scale=0 hits FP edge cases).
2047
+ // Ejecting the vertex outside clip space is the only deterministic discard.
2048
+ if (sourceIndex == targetIndex) {
2049
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
2050
+ return;
2051
+ }
2052
+
2053
+ vec3 srcPos = samplePosition(sourceIndex);
2054
+ vec3 tgtPos = samplePosition(targetIndex);
2055
+
2056
+ // Family (shape 5): starts halfway between source and anchor. MUST match edge.vert.glsl.
2057
+ float shape0 = controlOffset.z >= 0.0 ? controlOffset.z : defaultEdgeShape;
2058
+ if (shape0 > 4.5 && shape0 < 5.5) {
2059
+ float anchorSlot = controlOffset.y - KV_ORTHO_EXPLICIT - 1.0;
2060
+ if (anchorSlot > -0.5) srcPos = 0.5 * (srcPos + samplePosition(anchorSlot));
2061
+ }
2062
+
2063
+ vec3 edgeDir = tgtPos - srcPos;
2064
+ float edgeLength = length(edgeDir);
2065
+ // Degenerate-fallback threshold MUST match edge.vert.glsl. Old 0.001 was
2066
+ // too coarse for map mode (positions ~0.06, typical chords ~1e-4..1e-3)
2067
+ // and caused arrows to flip to (0,1,0) \u2014 visible as "arrows pointing
2068
+ // straight up" in dense metro clusters. 1e-9 keeps the guard against
2069
+ // true zero-length self-overlap without false positives.
2070
+ vec3 edgeNorm = edgeLength > 1e-9 ? edgeDir / edgeLength : vec3(0.0, 1.0, 0.0);
2071
+
2072
+ // Node world radius \u2014 MUST mirror node.vert.glsl pixelSize formula so the
2073
+ // arrow tip lands exactly on the visible bubble edge. In map mode this means
2074
+ // using the SAME soft-asymptote growth curve driven by the \`mapMaxGrowth\`
2075
+ // uniform; otherwise the arrow shader thinks the bubble is bigger than it
2076
+ // actually renders, and the arrow floats away from the bubble edge at deep
2077
+ // zoom. MUST stay in sync with node.vert.glsl / picking.vert.glsl.
2078
+ float srcViewZ = abs((modelViewMatrix * vec4(srcPos, 1.0)).z);
2079
+ float tgtViewZ = abs((modelViewMatrix * vec4(tgtPos, 1.0)).z);
2080
+ float maxPS = 4096.0;
2081
+ float srcPixDiam, tgtPixDiam;
2082
+ float srcScaled = sourceSize.x * nodeSizeScale;
2083
+ float tgtScaled = targetSize.x * nodeSizeScale;
2084
+ if (mapMode > 0.5) {
2085
+ float refDepth = 10.0;
2086
+ float srcRaw = pow(refDepth / srcViewZ, mapDamping);
2087
+ float tgtRaw = pow(refDepth / tgtViewZ, mapDamping);
2088
+ float srcGrowth = kvMapGrowth(srcRaw, mapMaxGrowth);
2089
+ float tgtGrowth = kvMapGrowth(tgtRaw, mapMaxGrowth);
2090
+ srcPixDiam = min((srcScaled * 50.0 / refDepth) * srcGrowth, maxPS);
2091
+ tgtPixDiam = min((tgtScaled * 50.0 / refDepth) * tgtGrowth, maxPS);
2092
+ } else {
2093
+ srcPixDiam = min(srcScaled * 50.0 / srcViewZ, maxPS);
2094
+ tgtPixDiam = min(tgtScaled * 50.0 / tgtViewZ, maxPS);
2095
+ }
2096
+ // Near-camera cap \u2014 same call on the same nominal diameter as
2097
+ // node.vert.glsl, so the cone keeps landing on the capped bubble edge.
2098
+ // \`tgtNominalDiam\` below is taken from the capped value on purpose: the cone
2099
+ // must not outgrow the node it points at.
2100
+ srcPixDiam = kvScreenCap(srcPixDiam, maxScreenFraction, resolution);
2101
+ tgtPixDiam = kvScreenCap(tgtPixDiam, maxScreenFraction, resolution);
2102
+ // The cone is sized by the node's nominal (circle) radius, not by how far the outline is along
2103
+ // this edge: a triangle's narrow side must not shrink its arrowhead.
2104
+ float tgtNominalDiam = tgtPixDiam;
2105
+ // Non-circle endpoints (must mirror edge.vert.glsl): stop at the outline along the chord.
2106
+ float srcShape = kvCodeShape(sourceSize.y);
2107
+ float tgtShape = kvCodeShape(targetSize.y);
2108
+ float srcAspect = kvCodeAspect(sourceSize.y);
2109
+ float tgtAspect = kvCodeAspect(targetSize.y);
2110
+ bool srcPlain = srcShape < 0.5 && abs(srcAspect - 1.0) < 1e-4;
2111
+ bool tgtPlain = tgtShape < 0.5 && abs(tgtAspect - 1.0) < 1e-4;
2112
+ if (!(srcPlain && tgtPlain)) {
2113
+ vec4 srcClip = projectionMatrix * (modelViewMatrix * vec4(srcPos, 1.0));
2114
+ vec4 tgtClip = projectionMatrix * (modelViewMatrix * vec4(tgtPos, 1.0));
2115
+ vec2 chordPx = (tgtClip.xy / tgtClip.w - srcClip.xy / srcClip.w) * resolution * 0.5;
2116
+ float chordLen = length(chordPx);
2117
+ vec2 chordDir = chordLen > 1e-4 ? chordPx / chordLen : vec2(1.0, 0.0);
2118
+ if (!srcPlain) srcPixDiam = 2.0 * kvShapeRadiusAlong(srcShape, srcAspect, srcPixDiam, chordDir);
2119
+ if (!tgtPlain) tgtPixDiam = 2.0 * kvShapeRadiusAlong(tgtShape, tgtAspect, tgtPixDiam, -chordDir);
2120
+ }
2121
+ // 0.96 factor matches edge.vert.glsl so both shaders build the same bezier
2122
+ // (cone apex at adjustedTgt = edge bezier endpoint). The edge shader caps
2123
+ // its rendered range so the visible line stops at the cone base; the
2124
+ // bezier itself still runs all the way to adjustedTgt, keeping the curve's
2125
+ // end-tangent identical to the arrow direction we derive here.
2126
+ float srcWorldRadius = srcPixDiam * srcViewZ / (projectionMatrix[1][1] * resolution.y) * 0.96;
2127
+ float tgtWorldRadius = tgtPixDiam * tgtViewZ / (projectionMatrix[1][1] * resolution.y) * 0.96;
2128
+ // Clamp offsets so they don't exceed 90% of edge length (must match edge shader).
2129
+ float totalOff = srcWorldRadius + tgtWorldRadius;
2130
+ float clampFac = totalOff > edgeLength * 0.9 ? (edgeLength * 0.9) / totalOff : 1.0;
2131
+ srcWorldRadius *= clampFac;
2132
+ tgtWorldRadius *= clampFac;
2133
+ float tgtConeRadius = tgtNominalDiam * tgtViewZ / (projectionMatrix[1][1] * resolution.y) * 0.96 * clampFac;
2134
+ float arrowLength = 4.0 * arrowScale.y; // Cone height * Y scale
2135
+
2136
+ float curvature = controlOffset.x;
2137
+ float planeRotation = controlOffset.y;
2138
+
2139
+ vec3 dir;
2140
+ vec3 arrowPos;
2141
+
2142
+ float shape = shape0;
2143
+ if (shape > 4.5 && shape < 5.5) shape = 3.0; // family routes as orthogonal
2144
+ bool isRouted = shape > 3.5 && shape < 4.5 && controlOffset.y > 0.5;
2145
+ if (shape > 3.5 && shape < 4.5 && !isRouted) shape = 0.0;
2146
+
2147
+ // Globe-mode regular edges (shape < 1.5) ride a true great-circle arc;
2148
+ // arrowhead orientation = arc tangent at the target end. MUST stay in sync
2149
+ // with edge.vert.glsl's \`isSphereEdge\` branch.
2150
+ // MUST match edge.vert.glsl isSphereEdge gating: only geo endpoints (on the
2151
+ // sphere, |pos| ~= sphereRadius) ride the great-circle arrow. Non-geo (force)
2152
+ // arrows fall through to the curve branch so the arrowhead sits on the actual
2153
+ // rendered edge instead of radiating onto the sphere.
2154
+ float srcSphereDist = length(srcPos);
2155
+ float tgtSphereDist = length(tgtPos);
2156
+ float sphereBand = sphereRadius * 0.1;
2157
+ bool bothOnSphere = abs(srcSphereDist - sphereRadius) < sphereBand
2158
+ && abs(tgtSphereDist - sphereRadius) < sphereBand;
2159
+ // Short arcs (city-scale edges on a globe) are visually straight, and the
2160
+ // great-circle endpoint pullback degenerates for them: when a node's radius
2161
+ // is a large fraction of the tiny arc, the arc-fraction saturates (clamped)
2162
+ // and the arrow stops well inside the node \u2014 visible as arrows floating mid-
2163
+ // edge at deep map zoom (e.g. adjacent Tube stations). Only ride the great-
2164
+ // circle arc for arcs long enough to visibly curve (~1.1\xB0); shorter ones fall
2165
+ // through to the straight/curve branch, whose chord pullback reaches the node
2166
+ // surface correctly (no 0.49 clamp). MUST match edge.vert.glsl.
2167
+ float arcOmega = acos(clamp(dot(normalize(srcPos), normalize(tgtPos)), -1.0, 1.0));
2168
+ bool isSphereArrow = sphereRadius > 0.001 && shape < 1.5 && bothOnSphere && arcOmega > 0.02;
2169
+
2170
+ vec3 oP1, oP2, oD1, oD3;
2171
+ bool isOrtho = shape > 2.5 && shape < 3.5
2172
+ && kvOrthoFrame(srcPos, tgtPos, controlOffset.xy, radialAxis, oP1, oP2, oD1, oD3);
2173
+ if (shape > 2.5 && shape < 3.5 && !isOrtho) shape = 0.0; // level ends: straight, as edge.vert
2174
+
2175
+ if (isRouted) {
2176
+ // --- Routed: the last leg, from the last bend into the target ---
2177
+ float rf;
2178
+ vec3 lastBend = kvRoutedPoint(routeTexture, routeTextureSize, controlOffset.x, controlOffset.y,
2179
+ controlOffset.y, srcPos, tgtPos, srcPos, tgtPos, rf);
2180
+ vec3 inLeg = tgtPos - lastBend;
2181
+ dir = length(inLeg) > 1e-9 ? normalize(inLeg) : edgeNorm;
2182
+ arrowPos = tgtPos - dir * tgtWorldRadius;
2183
+ } else if (isOrtho) {
2184
+ // --- Orthogonal: leg3 runs along the routing axis into the target ---
2185
+ dir = oD1;
2186
+ arrowPos = tgtPos - dir * tgtWorldRadius;
2187
+ } else if (shape > 1.5 && shape < 2.5) {
2188
+ // --- Radial S-curve: arrow direction = cubic bezier tangent at t=1 ---
2189
+ // Tangent at t=1 of cubic bezier = 3*(P3-P2), where P2=(tgt.x, midY)
2190
+ vec3 eDir = tgtPos - srcPos;
2191
+ bool useVert;
2192
+ if (radialAxis > 1.5) { useVert = false; }
2193
+ else if (radialAxis > 0.5) { useVert = true; }
2194
+ else { useVert = abs(eDir.y) >= abs(eDir.x); }
2195
+
2196
+ vec3 cp2;
2197
+ if (useVert) {
2198
+ float midY = (srcPos.y + tgtPos.y) * 0.5;
2199
+ cp2 = vec3(tgtPos.x, midY, tgtPos.z);
2200
+ } else {
2201
+ float midX = (srcPos.x + tgtPos.x) * 0.5;
2202
+ cp2 = vec3(midX, tgtPos.y, tgtPos.z);
2203
+ }
2204
+ vec3 tangent = tgtPos - cp2;
2205
+ dir = length(tangent) > 0.0001 ? normalize(tangent) : edgeNorm;
2206
+ arrowPos = tgtPos - dir * tgtWorldRadius;
2207
+ } else if (isSphereArrow) {
2208
+ // --- Globe great-circle arrow ---
2209
+ // Mirror edge.vert.glsl: arc end position = dirTgt * R + perp * fanOff.
2210
+ // Tangent at the arc endpoint (used to orient the cone) = arcTangentAtEnd.
2211
+ //
2212
+ // The node-radius gap (srcWorldRadius/tgtWorldRadius) is an ARC-LENGTH
2213
+ // pullback along the great circle, NOT a chord subtraction. The old form
2214
+ // \`normalize(tgtPos - edgeNorm * tgtWorldRadius)\` retreats along the
2215
+ // straight chord; for long edges the chord cuts through the globe, so
2216
+ // re-normalizing barely moves the angular position and the arrowhead
2217
+ // collapses onto the node center (visible as the arrow not reaching the
2218
+ // node at deep zoom). Step the endpoint directions along the arc by
2219
+ // worldRadius / sphereRadius radians so the tip lands exactly one
2220
+ // node-radius back along the visible arc. MUST match edge.vert.glsl.
2221
+ vec3 dSrcRaw = normalize(srcPos);
2222
+ vec3 dTgtRaw = normalize(tgtPos);
2223
+ float omegaFull = acos(clamp(dot(dSrcRaw, dTgtRaw), -1.0, 1.0));
2224
+ // Pull each endpoint back along the arc by its node-radius worth of arc
2225
+ // length. Capping each fraction independently at 0.49 (the old form)
2226
+ // under-pulls the LARGER endpoint on short arcs \u2014 the pullback ends up far
2227
+ // less than the node radius, so the arrow/edge tip lands INSIDE the node
2228
+ // (visible as edges/arrows punching through the bubble at deep map zoom).
2229
+ // Instead cap the COMBINED pullback at 0.98 of the arc and split it
2230
+ // proportionally, so each endpoint keeps as much of its full node-radius
2231
+ // pullback as the arc allows and the bigger node still wins its share.
2232
+ // MUST stay in sync with edge.vert.glsl.
2233
+ //
2234
+ // Screen-foreshorten compensation (MUST stay in sync with edge.vert.glsl):
2235
+ // the node is a screen-facing billboard but the pullback is a world arc-length
2236
+ // along the surface tangent; when that tangent dives toward the camera it
2237
+ // projects to too few pixels and the arrow enters the node. Scale each
2238
+ // endpoint's pullback up by 1/foreshorten (clamped) so the arrow tip clears
2239
+ // the node's screen radius.
2240
+ vec3 tanSrc = normalize(dTgtRaw - dot(dTgtRaw, dSrcRaw) * dSrcRaw);
2241
+ vec3 tanTgt = normalize(dSrcRaw - dot(dSrcRaw, dTgtRaw) * dTgtRaw);
2242
+ vec3 vDirSrc = normalize((modelViewMatrix * vec4(srcPos, 1.0)).xyz);
2243
+ vec3 vDirTgt = normalize((modelViewMatrix * vec4(tgtPos, 1.0)).xyz);
2244
+ vec3 tanSrcV = normalize((modelViewMatrix * vec4(tanSrc, 0.0)).xyz);
2245
+ vec3 tanTgtV = normalize((modelViewMatrix * vec4(tanTgt, 0.0)).xyz);
2246
+ float foreSrc = max(sqrt(max(0.0, 1.0 - pow(dot(tanSrcV, vDirSrc), 2.0))), 0.3);
2247
+ float foreTgt = max(sqrt(max(0.0, 1.0 - pow(dot(tanTgtV, vDirTgt), 2.0))), 0.3);
2248
+ float srcRadiusAdj = srcWorldRadius / foreSrc;
2249
+ float tgtRadiusAdj = tgtWorldRadius / foreTgt;
2250
+ float srcFracRaw = omegaFull > 1e-6 ? (srcRadiusAdj / sphereRadius) / omegaFull : 0.0;
2251
+ float tgtFracRaw = omegaFull > 1e-6 ? (tgtRadiusAdj / sphereRadius) / omegaFull : 0.0;
2252
+ float fracSum = srcFracRaw + tgtFracRaw;
2253
+ float fracK = fracSum > 0.98 ? 0.98 / fracSum : 1.0;
2254
+ float srcFrac = srcFracRaw * fracK;
2255
+ float tgtFrac = tgtFracRaw * fracK;
2256
+ vec3 dirSrcS = slerp(dSrcRaw, dTgtRaw, srcFrac);
2257
+ vec3 dirTgtS = slerp(dTgtRaw, dSrcRaw, tgtFrac);
2258
+ float cosO = clamp(dot(dirSrcS, dirTgtS), -1.0, 1.0);
2259
+ float omegaS = acos(cosO);
2260
+ float sinO = sin(omegaS);
2261
+ vec3 planeNormalS = sinO < 1e-5
2262
+ ? vec3(0.0, 1.0, 0.0)
2263
+ : normalize(cross(dirSrcS, dirTgtS));
2264
+ vec3 perpAtTgt = normalize(cross(dirTgtS, planeNormalS));
2265
+ float fanOff = curvature * sin(omegaS * 0.5) * sphereRadius;
2266
+ dir = arcTangentAtEnd(dirSrcS, dirTgtS);
2267
+ arrowPos = dirTgtS * sphereRadius + perpAtTgt * fanOff;
2268
+ } else if (shape > 0.5 || abs(curvature) > 0.001) {
2269
+ // --- Curve arrow: unified bezier arrow alignment ---
2270
+ // Control point math MUST mirror edge.vert.glsl exactly so the arrow's
2271
+ // tangent direction lands on the actual rendered curve. Any divergence
2272
+ // here makes the arrow head point along a different bezier and visibly
2273
+ // floats off the curve at the node boundary.
2274
+ // Globe-straight synthesis removed (mirror edge.vert.glsl isGlobeStraight=false):
2275
+ // non-geo straight arrows fall through to the plain straight branch below.
2276
+ bool isGlobe = false;
2277
+ float effCurvature = curvature;
2278
+ if (shape > 0.5 && shape < 1.5 && abs(curvature) < 0.001) { effCurvature = 0.15; }
2279
+ vec3 edgeSrc = srcPos + edgeNorm * srcWorldRadius;
2280
+ vec3 edgeTgt = tgtPos - edgeNorm * tgtWorldRadius;
2281
+ vec3 midPoint = (edgeSrc + edgeTgt) * 0.5;
2282
+
2283
+ // Bulge direction (matches edge.vert.glsl): in map mode use the camera's
2284
+ // up-in-model derived from modelViewMatrix so the bezier always bulges
2285
+ // toward viewport up; outside map mode fall back to the legacy lateral
2286
+ // cross-product perpendicular.
2287
+ vec3 perp;
2288
+ if (mapMode > 0.5) {
2289
+ vec3 camUpInModel = vec3(
2290
+ modelViewMatrix[0][1],
2291
+ modelViewMatrix[1][1],
2292
+ modelViewMatrix[2][1]
2293
+ );
2294
+ vec3 proj = camUpInModel - dot(camUpInModel, edgeNorm) * edgeNorm;
2295
+ float l = length(proj);
2296
+ perp = l > 0.001 ? proj / l : computePerpendicular(edgeNorm);
2297
+ } else {
2298
+ perp = computePerpendicular(edgeNorm);
2299
+ }
2300
+ if (abs(planeRotation) > 0.001) {
2301
+ perp = rotateAroundAxis(perp, edgeNorm, planeRotation);
2302
+ }
2303
+
2304
+ // Bulge magnitude: same regime as edge.vert.glsl \u2014 synthesized for
2305
+ // globeStraight, effCurvature \xD7 edgeLength otherwise.
2306
+ float bulgeMag = isGlobe
2307
+ ? edgeLength * 0.15
2308
+ : effCurvature * edgeLength;
2309
+ vec3 controlPoint = midPoint + perp * bulgeMag;
2310
+
2311
+ // Arrow direction from bezier tangent near endpoint (matches edge straightening)
2312
+ vec3 bAt85 = bezier(edgeSrc, controlPoint, edgeTgt, 0.85);
2313
+ dir = normalize(edgeTgt - bAt85);
2314
+ arrowPos = edgeTgt;
2315
+ } else {
2316
+ // --- Straight edge mode ---
2317
+ dir = edgeNorm;
2318
+ arrowPos = tgtPos - dir * tgtWorldRadius;
2319
+ }
2320
+
2321
+ // Compute direction quaternion from arrow direction
2322
+ vec4 qDirection = getDirectionQuaternion(dir);
2323
+
2324
+ // Transform vertex:
2325
+ // 1. Scale
2326
+ // 2. Apply direction quaternion
2327
+ // 3. Translate to arrow position
2328
+ vec3 pos = position;
2329
+ vec3 scale = arrowScale;
2330
+ if (edgeSelected > 0.5) { scale.x *= 3.0; scale.z *= 3.0; }
2331
+ // Two arrow sizing regimes (must match edge.vert.glsl width regimes):
2332
+ // - World-scaled (legacy parity, default): arrowScale buffer values are
2333
+ // interpreted as world-space scale of the cone geometry; perspective
2334
+ // does the rest, so arrows shrink/grow with zoom like edges.
2335
+ // - Screen-constant: multiply by tgtWorldRadius so the arrow size tracks
2336
+ // the node's projected on-screen radius \u2014 necessary in mapMode where
2337
+ // camera-z range is too large for world units to look right, and in
2338
+ // fixedSize mode where nodes are already screen-constant.
2339
+ //
2340
+ // X/Z (base width) and Y (length) take DIFFERENT multipliers because the
2341
+ // base arrowScale buffer (0.012, 0.035, 0.012) bakes in a ~2.92\xD7 ratio of
2342
+ // height-multiplier to radius-multiplier; with three.js cone geometry
2343
+ // (height=4 along Y, base radius=1 at scale 1) a uniform per-axis \xD7 3.0
2344
+ // would render an 11.7:1 height-to-base-radius needle \u2014 visually a line
2345
+ // extension rather than a recognizable arrow. Non-map mode fixes that by
2346
+ // \`scale.y *= 0.3\` AFTER the 1:1 buffer scale, landing on a 3.5:1 cone.
2347
+ // Mirror that proportion here by giving the width axes a larger multiplier
2348
+ // so the rendered aspect (X:Y of final scale \xD7 geometry aspect) lands
2349
+ // around 3:1.
2350
+ if (mapMode > 0.5 || fixedSize > 0.5) {
2351
+ scale.x *= tgtConeRadius * 18.0;
2352
+ scale.y *= tgtConeRadius * 4.0;
2353
+ scale.z *= tgtConeRadius * 18.0;
2354
+ // Cap the cone's base radius to a sane arrowhead aspect. The base width is
2355
+ // edge-width-driven (arrowScale.x = w\xB71.5) AND node-radius-driven
2356
+ // (\xD7 tgtWorldRadius), so a wide edge into a big node compounds into a fat
2357
+ // chevron far wider than its own length (which is edge-width-INdependent).
2358
+ // Clamp base \u2264 ~0.55\xD7 cone height (= 4\xB7scale.y) so the arrow keeps a
2359
+ // recognizable shape; default-width edges sit below the cap and are
2360
+ // unchanged. Width still grows with edge thickness up to the cap.
2361
+ float maxHalfWidth = scale.y * 2.2;
2362
+ scale.x = min(scale.x, maxHalfWidth);
2363
+ scale.z = min(scale.z, maxHalfWidth);
2364
+ } else {
2365
+ // arrowScale.y default (0.035) was tuned for the screen-constant path
2366
+ // where it gets multiplied by tgtWorldRadius * 3. In the world-scaled
2367
+ // path that multiplier is gone, so the cone would render ~3.5x longer
2368
+ // than legacy. Bring length back to legacy proportions (~3x cone radius).
2369
+ scale.y *= 0.3;
2370
+ // Floor against node radius: world-scaled cone is constant in world units
2371
+ // (lineWidth-driven), so on hubs sized by sizeByDegree / per-node setSize
2372
+ // the arrow:radius ratio collapses and the cone gets swallowed by the
2373
+ // node's soft edge. Mirror the screen-constant ratio (X/Z = radius * 0.216,
2374
+ // Y = radius * 0.14) as a lower bound \u2014 small nodes pass through
2375
+ // unchanged because their radius-derived size is below the lineWidth
2376
+ // baseline; only big nodes get bumped up to a visible cone.
2377
+ float growX = tgtConeRadius * 0.216;
2378
+ float growY = tgtConeRadius * 0.140;
2379
+ scale.x = max(scale.x, growX);
2380
+ scale.y = max(scale.y, growY);
2381
+ scale.z = max(scale.z, growX);
2382
+ }
2383
+ pos *= scale;
2384
+ pos = applyQuaternion(pos, qDirection);
2385
+ pos += arrowPos;
2386
+
2387
+ vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
2388
+ gl_Position = projectionMatrix * mvPosition;
2389
+
2390
+ // Globe mode: vertex-level back-face culling.
2391
+ // depthTest is disabled in globe mode, so we hide back-facing arrows here.
2392
+ if (sphereRadius > 0.001) {
2393
+ vec3 wN = normalize(mat3(modelMatrix) * normalize(arrowPos));
2394
+ vec3 wP = (modelMatrix * vec4(arrowPos, 1.0)).xyz;
2395
+ if (dot(wN, normalize(cameraPosition - wP)) < 0.0) {
2396
+ vOpacity = 0.0;
2397
+ }
2398
+ }
2399
+ }
2400
+ `;var Oe=`precision highp float;
2401
+
2402
+ uniform float u_hoverProgress;
2403
+ uniform float u_hoverDimOpacity;
2404
+
2405
+ varying vec3 vColor;
2406
+ varying float vOpacity;
2407
+ varying float vSelected;
2408
+ varying float vHoverDim;
2409
+
2410
+ void main() {
2411
+ gl_FragColor = vec4(vColor, vOpacity);
2412
+ if (vSelected > 0.5) {
2413
+ gl_FragColor.rgb = gl_FragColor.rgb * 1.2 + vec3(0.0, 0.2, 0.5) * 0.3;
2414
+ }
2415
+ // Hover-neighbor-highlight: dim 2-hop arrows along with their edge lines.
2416
+ float hoverDimMul = mix(1.0, u_hoverDimOpacity, vHoverDim * u_hoverProgress);
2417
+ gl_FragColor.a *= hoverDimMul;
2418
+ if (gl_FragColor.a < 0.01) discard;
2419
+ }
2420
+ `;var Le=`precision highp float;
2421
+
2422
+ // Position texture (from GPU layout controller)
2423
+ uniform sampler2D positionTexture;
2424
+ uniform float textureSize;
2425
+ uniform float spaceSize;
2426
+
2427
+ // Loop parameters
2428
+ uniform float loopRadiusMult;
2429
+ uniform float centerOffsetMult;
2430
+ uniform vec2 resolution;
2431
+ uniform float lineWidthScale;
2432
+ uniform float nodeSizeScale;
2433
+
2434
+ // Per-vertex attributes (arc geometry)
2435
+ attribute float loopProgress; // [0, 1] along the arc
2436
+ attribute float side; // -1 or 1 for line thickness
2437
+
2438
+ // Per-instance attributes
2439
+ attribute float nodeIndex; // Node index for position lookup
2440
+ attribute float nodeSize; // Node size for radius calculation
2441
+ attribute vec3 loopColor;
2442
+ attribute float loopOpacity;
2443
+ attribute float loopWidth;
2444
+ attribute float loopSelected;
2445
+
2446
+ // Varyings
2447
+ varying vec3 vColor;
2448
+ varying float vOpacity;
2449
+ varying float vProgress;
2450
+ varying float vSelected;
2451
+
2452
+ vec3 samplePosition(float idx) {
2453
+ float texX = mod(idx, textureSize) + 0.5;
2454
+ float texY = floor(idx / textureSize) + 0.5;
2455
+ vec2 texCoord = vec2(texX, texY) / textureSize;
2456
+ return texture2D(positionTexture, texCoord).xyz;
2457
+ }
2458
+
2459
+ void main() {
2460
+ vColor = loopColor;
2461
+ vOpacity = loopOpacity;
2462
+ vProgress = loopProgress;
2463
+ vSelected = loopSelected;
2464
+
2465
+ // Get node position
2466
+ vec3 nodePos = samplePosition(nodeIndex);
2467
+
2468
+ // Node world radius \u2014 match nodeVertexShader's per-node perspective sizing (50/viewZ).
2469
+ // For perspective cameras projMatrix[3][3]==0: distance cancels, formula is exact.
2470
+ // For orthographic cameras projMatrix[3][3]==1 (minimap): distance does NOT cancel,
2471
+ // so we must divide by viewZ to keep loops proportional to node dot size.
2472
+ float nodeWorldRadius = nodeSize * nodeSizeScale * 50.0 / (projectionMatrix[1][1] * resolution.y);
2473
+ if (projectionMatrix[3][3] > 0.5) {
2474
+ // Orthographic: correct for camera distance (matches node.vert.glsl pixelSize = size*50/dist)
2475
+ vec4 viewPos = modelViewMatrix * vec4(nodePos, 1.0);
2476
+ float viewDist = max(1.0, abs(viewPos.z));
2477
+ nodeWorldRadius /= viewDist;
2478
+ }
2479
+
2480
+ // Loop geometry: circle centered directly above node
2481
+ float d = nodeWorldRadius * centerOffsetMult; // distance node-center \u2192 loop-center
2482
+ float r = nodeWorldRadius * loopRadiusMult; // loop circle radius
2483
+
2484
+ // Guard against degenerate cases
2485
+ if (r < 0.0001 || d < 0.0001) {
2486
+ gl_Position = vec4(0.0);
2487
+ return;
2488
+ }
2489
+
2490
+ // Loop center: directly above node
2491
+ vec3 loopCenter = nodePos + vec3(0.0, d, 0.0);
2492
+
2493
+ // Compute arc endpoints from circle-circle intersection.
2494
+ float PI = 3.14159265;
2495
+ float cosAlpha = (d * d + r * r - nodeWorldRadius * nodeWorldRadius) / (2.0 * d * r);
2496
+ cosAlpha = clamp(cosAlpha, -1.0, 1.0);
2497
+ float alpha = acos(cosAlpha);
2498
+
2499
+ // Arc from right intersection (start) to left intersection (end),
2500
+ // going CCW over the top \u2014 the "long way" around.
2501
+ float startAngle = -PI * 0.5 + alpha;
2502
+ float endAngle = -PI * 0.5 - alpha + PI * 2.0;
2503
+
2504
+ float angle = mix(startAngle, endAngle, loopProgress);
2505
+
2506
+ // Position on arc
2507
+ vec3 arcPos = vec3(
2508
+ loopCenter.x + cos(angle) * r,
2509
+ loopCenter.y + sin(angle) * r,
2510
+ loopCenter.z
2511
+ );
2512
+
2513
+ // Tangent direction for line thickness
2514
+ float tangentAngle = angle + PI * 0.5;
2515
+ vec2 tangent = vec2(cos(tangentAngle), sin(tangentAngle));
2516
+
2517
+ // Transform to clip space
2518
+ vec4 clipPos = projectionMatrix * modelViewMatrix * vec4(arcPos, 1.0);
2519
+
2520
+ // \u2500\u2500 Arrowhead integrated into the arc strip \u2500\u2500
2521
+ // The last arrowFrac of the arc tapers from a wide base to a point.
2522
+ // This creates a triangular arrowhead as part of the same geometry.
2523
+ float arrowFrac = 0.12; // last 12% of arc is the arrowhead
2524
+ // Shaft width: constant screen-space width (no zoom-dependent scaling needed).
2525
+ // With per-node 50/viewZ sizing, perspective handles everything naturally.
2526
+ float edgeScaleFactor = 50.0 / 15.0;
2527
+ float shaftW = loopWidth * lineWidthScale * clipPos.w * edgeScaleFactor * 0.5;
2528
+ if (loopSelected > 0.5) shaftW *= 1.8; // selection: 1.8x thicker (subtle highlight)
2529
+
2530
+ float w;
2531
+ if (loopProgress < (1.0 - arrowFrac)) {
2532
+ // Normal shaft region
2533
+ w = shaftW;
2534
+ } else {
2535
+ // Arrowhead region: taper from wide base to tip (0)
2536
+ float t = (loopProgress - (1.0 - arrowFrac)) / arrowFrac; // 0 at base, 1 at tip
2537
+ float arrowBaseW = shaftW * 5.0; // arrowhead base is 5x wider than shaft
2538
+ w = mix(arrowBaseW, 0.0, t);
2539
+ }
2540
+
2541
+ // Offset perpendicular to tangent
2542
+ float aspect = resolution.x / resolution.y;
2543
+ vec2 normal = vec2(-tangent.y, tangent.x) / aspect;
2544
+ clipPos.xy += normal * side * w * 0.5;
2545
+
2546
+ gl_Position = clipPos;
2547
+ }
2548
+ `;var Ne=`precision highp float;
2549
+
2550
+ varying vec3 vColor;
2551
+ varying float vOpacity;
2552
+ varying float vProgress;
2553
+ varying float vSelected;
2554
+
2555
+ void main() {
2556
+ vec4 color = vec4(vColor, vOpacity);
2557
+
2558
+ // Selection highlight
2559
+ if (vSelected > 0.5) {
2560
+ color.rgb = color.rgb * 1.2 + vec3(0.0, 0.2, 0.5) * 0.3;
2561
+ }
2562
+
2563
+ // Alpha test
2564
+ if (color.a < 0.01) discard;
2565
+
2566
+ gl_FragColor = color;
2567
+ }
2568
+ `;var Ge=`attribute vec3 aCenter;
2569
+ attribute float aRadius;
2570
+ attribute vec3 aColor;
2571
+ attribute float aFillOpacity;
2572
+ attribute float aFalloff;
2573
+ attribute vec3 aRingColor;
2574
+ attribute float aRingWidth;
2575
+ attribute float aRingOpacity; // boundary-ring opacity, independent of fillOpacity
2576
+ attribute vec3 aPulse; // x=flag, y=speed, z=rings
2577
+ attribute float aDim; // anchor node render opacity (focus / click-dim); 1 = full
2578
+ attribute float aSelected; // 1 when the anchor node is selected
2579
+ attribute vec3 aSector; // x=azimuth(deg CW from N), y=beamWidth(deg; 360=full disc), z=innerRadius(fraction). One attribute (not 3) to stay under MAX_VERTEX_ATTRIBS.
2580
+ uniform float uSphereRadius; // > 0 in globe mode: lay discs flat in the surface tangent plane
2581
+ varying vec2 vLocal; // [-1,1]; length 1 at the circle edge
2582
+ varying vec3 vColor; varying float vFill; varying float vFalloff;
2583
+ varying vec3 vRingColor; varying float vRingWidth; varying vec3 vPulse;
2584
+ varying float vRingOpacity;
2585
+ varying float vDim;
2586
+ varying float vSelected;
2587
+ varying vec3 vSector; // x=azimuth, y=beamWidth, z=innerRadius
2588
+ void main() {
2589
+ vLocal = position.xy * 2.0; // position.xy in [-0.5,0.5]
2590
+ vColor = aColor; vFill = aFillOpacity; vFalloff = aFalloff;
2591
+ vRingColor = aRingColor; vRingWidth = aRingWidth; vPulse = aPulse;
2592
+ vRingOpacity = aRingOpacity;
2593
+ vDim = aDim;
2594
+ vSelected = aSelected;
2595
+ vSector = aSector;
2596
+ vec2 offset = position.xy * 2.0 * aRadius; // disc-local offset, world units
2597
+ vec3 world;
2598
+ if (uSphereRadius > 0.0 && length(aCenter) > 1e-4) {
2599
+ // Globe mode: build the disc in the sphere's surface TANGENT plane at the
2600
+ // anchor so the ring stays parallel to the ground. The globe is centred at
2601
+ // the model origin, so normalize(aCenter) is the outward surface normal.
2602
+ // Without this the disc sits in the fixed cloudScene XY plane and looks
2603
+ // tilted/deformed everywhere except the front-facing point of the globe.
2604
+ vec3 N = normalize(aCenter);
2605
+ // Tangent basis: east = poleAxis \xD7 N, north = N \xD7 east. The pole axis is +Y
2606
+ // (datumsToVector maps latitude \u2192 Y). Guard the pole singularity (N \u2225 Y) by
2607
+ // switching the reference axis to +X there.
2608
+ vec3 ref = abs(N.y) > 0.999 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);
2609
+ vec3 east = normalize(cross(ref, N));
2610
+ vec3 north = cross(N, east);
2611
+ world = aCenter + east * offset.x + north * offset.y;
2612
+ } else {
2613
+ world = aCenter + vec3(offset, 0.0); // flat disc in cloudScene XY (planar map / no map)
2614
+ }
2615
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(world, 1.0);
2616
+ }
2617
+ `;var Ve=`precision highp float;
2618
+ uniform float uTime;
2619
+ varying vec2 vLocal;
2620
+ varying vec3 vColor; varying float vFill; varying float vFalloff;
2621
+ varying vec3 vRingColor; varying float vRingWidth; varying vec3 vPulse;
2622
+ varying float vRingOpacity;
2623
+ varying float vDim;
2624
+ varying float vSelected; // 1 when the anchor node is selected
2625
+ varying vec3 vSector; // x=azimuth(deg CW from N), y=beamWidth(deg; 360=full disc), z=innerRadius(fraction)
2626
+ void main() {
2627
+ float d = length(vLocal);
2628
+ if (d > 1.0) discard;
2629
+ // Sector mask: keep only fragments inside the wedge. beamWidth>=360 \u2192 full disc.
2630
+ if (vSector.y < 359.999) {
2631
+ float ang = degrees(atan(vLocal.x, vLocal.y)); // bearing CW from north, (-180,180]
2632
+ float delta = mod(ang - vSector.x + 540.0, 360.0) - 180.0; // signed wrap
2633
+ if (abs(delta) > vSector.y * 0.5) discard;
2634
+ }
2635
+ if (d < vSector.z) discard; // annular gap
2636
+ bool sel = vSelected > 0.5;
2637
+ // radial signal falloff shape (strong center -> weak edge), 0..1
2638
+ float fill = pow(1.0 - clamp(d, 0.0, 1.0), max(vFalloff, 0.0));
2639
+ // boundary ring shape near d == 1, 0..1.
2640
+ float ring = (vRingWidth > 0.0) ? (1.0 - smoothstep(0.0, vRingWidth, abs(d - 1.0))) : 0.0;
2641
+ // optional expanding pulse rings (radar ping), bounded by the real radius
2642
+ float pulse = 0.0;
2643
+ if (vPulse.x > 0.5) {
2644
+ float rings = max(vPulse.z, 1.0);
2645
+ // Fixed bound <4 keeps this WebGL2-portable; variable \`break\` is safe under GLSL ES 3.00 (WebGL2 context).
2646
+ for (int i = 0; i < 4; i++) {
2647
+ if (float(i) >= rings) break;
2648
+ float phase = fract(d - uTime * vPulse.y - float(i) / rings);
2649
+ pulse += (1.0 - phase) * (1.0 - d) * 0.5;
2650
+ }
2651
+ }
2652
+ // A selected disc stays un-dimmed so it remains prominent while its
2653
+ // focus-dimmed neighbours fade (click-to-isolate). Its boundary keeps its own
2654
+ // colour/opacity \u2014 the selection is marked by a dashed RADIUS SPOKE (below).
2655
+ float dim = sel ? 1.0 : vDim;
2656
+ vec3 col = mix(vColor, vRingColor, ring);
2657
+ // fillOpacity (vFill) scales ONLY the interior fill and the radar pulse, so you
2658
+ // can fade the fill to let the basemap show through. The boundary ring has its
2659
+ // OWN opacity (vRingOpacity) and is unaffected by fillOpacity \u2014 it stays crisp.
2660
+ // Then * dim so a disc fades with its node under focus / click-dim.
2661
+ float alpha = clamp(max(vFill * fill, vRingOpacity * ring) + vFill * pulse, 0.0, 1.0) * dim;
2662
+
2663
+ // Selection marker: a dashed RADIUS spoke from the centre (d=0) out to the +X
2664
+ // edge (d=1), drawn in the coverage's own fill colour \u2014 reads as a literal
2665
+ // radius line annotating the coverage reach.
2666
+ if (sel) {
2667
+ const float halfThick = 0.008 / 3.0; // spoke half-width in local units (fraction of radius); 3x thinner
2668
+ const float dashFreq = 7.0; // ~7 dashes from centre to edge
2669
+ // Spoke direction: +X for a full disc (back-compat); along the sector azimuth for a wedge.
2670
+ vec2 dir = (vSector.y < 359.999) ? vec2(sin(radians(vSector.x)), cos(radians(vSector.x))) : vec2(1.0, 0.0);
2671
+ float along = dot(vLocal, dir);
2672
+ float perp = dot(vLocal, vec2(dir.y, -dir.x));
2673
+ float onAxis = 1.0 - smoothstep(halfThick * 0.5, halfThick, abs(perp));
2674
+ float onSide = step(0.0, along); // centre -> edge along the spoke direction
2675
+ float dash = step(fract(d * dashFreq), 0.55); // alternating dash/gap along the radius
2676
+ float spoke = onAxis * onSide * dash;
2677
+ if (spoke > 0.0) {
2678
+ col = mix(col, vColor, spoke); // spoke in the coverage's own fill colour
2679
+ alpha = max(alpha, spoke); // spoke at full opacity (sel => dim == 1)
2680
+ }
2681
+ }
2682
+
2683
+ if (alpha <= 0.0) discard;
2684
+ gl_FragColor = vec4(col, alpha);
2685
+ }
2686
+ `;var Ue=`precision highp float;
2687
+
2688
+ // Position texture (from GPU layout controller)
2689
+ uniform sampler2D positionTexture;
2690
+ uniform float textureSize;
2691
+
2692
+ // Viewport in CSS pixels (not physical pixels)
2693
+ uniform vec2 uViewportPx;
2694
+ uniform float mapMode;
2695
+ uniform float mapDamping;
2696
+ uniform float mapMaxGrowth; // shared semantics with node.vert.glsl; -1.0 = Infinity sentinel
2697
+
2698
+ // Per-instance attributes
2699
+ attribute float aParentNodeIndex;
2700
+ attribute vec2 aAnchorOffsetPx;
2701
+ attribute vec2 aSizePx;
2702
+ attribute vec4 aUvRect;
2703
+ attribute vec3 aBgRgb;
2704
+ attribute vec3 aFgRgb;
2705
+ attribute float aGroupRole; // 0 = background quad, 1 = glyph quad
2706
+ attribute vec2 aGlyphOffsetPx; // glyph pixel offset within badge (CSS px)
2707
+ attribute vec2 aGlyphSizePx; // glyph quad size in CSS px
2708
+
2709
+ // Varyings to fragment shader
2710
+ varying vec2 vUv;
2711
+ varying vec4 vUvRect;
2712
+ varying vec3 vBgRgb;
2713
+ varying vec3 vFgRgb;
2714
+ varying float vGroupRole;
2715
+ varying vec2 vSizePx; // background pill dimensions in CSS px (used by frag for aspect)
2716
+
2717
+ // Helper: Sample position from position texture using ES 1.0 pattern
2718
+ vec3 samplePosition(float idx) {
2719
+ float texX = mod(idx, textureSize) + 0.5;
2720
+ float texY = floor(idx / textureSize) + 0.5;
2721
+ vec2 texCoord = vec2(texX, texY) / textureSize;
2722
+ vec4 posData = texture2D(positionTexture, texCoord);
2723
+ return posData.xyz;
2724
+ }
2725
+
2726
+ void main() {
2727
+ vUv = uv;
2728
+ vUvRect = aUvRect;
2729
+ vBgRgb = aBgRgb;
2730
+ vFgRgb = aFgRgb;
2731
+ vGroupRole = aGroupRole;
2732
+ vSizePx = aSizePx;
2733
+
2734
+ // 1. Sample parent position from the position texture
2735
+ vec3 parentPos = samplePosition(aParentNodeIndex);
2736
+
2737
+ // 2. Project parent center to clip space using the standard MVP
2738
+ vec4 mvParent = modelViewMatrix * vec4(parentPos, 1.0);
2739
+ vec4 clip = projectionMatrix * mvParent;
2740
+
2741
+ // 3. Compute screen-space pixel offset based on group role.
2742
+ // \`position.xy\` is [-0.5, 0.5]\xB2 for a Three.js PlaneGeometry of size 1.
2743
+ // ANCHOR_OFFSETS use CSS screen convention (Y increases downward). NDC uses
2744
+ // Y-up, so we negate the anchor Y component. \`position.xy\` already uses the
2745
+ // correct NDC sign (positive Y = up), so only the anchor needs flipping.
2746
+ vec2 anchorNdc = vec2(aAnchorOffsetPx.x, -aAnchorOffsetPx.y);
2747
+ vec2 pxOffset;
2748
+ if (aGroupRole < 0.5) {
2749
+ // Background quad \u2014 centre the pill at anchor + size offset
2750
+ pxOffset = anchorNdc + (position.xy * aSizePx);
2751
+ } else {
2752
+ // Glyph quad \u2014 position glyph within the badge at its measured offset
2753
+ pxOffset = anchorNdc + aGlyphOffsetPx + (position.xy * aGlyphSizePx);
2754
+ }
2755
+
2756
+ // 4. Apply pixel offset in NDC, scaled by scene depth so badges grow/shrink
2757
+ // proportionally with nodes as the user zooms.
2758
+ // Nodes use: pixelSize = nodeSize * 50 / max(-mvCenter.z, 0.001)
2759
+ // We match that depth curve: REF_DEPTH=10 is the depth where a size-10
2760
+ // node appears as 50 CSS px \u2014 matching the designed sizes in TypeScript.
2761
+ // At half the depth (zoom in 2\xD7), depthFactor=2 \u2192 badge is 2\xD7 bigger, same
2762
+ // as the node. At REF_DEPTH=10 exactly, depthFactor=1 \u2192 defined CSS px sizes.
2763
+ // Beyond softKnee (raw > mapMaxGrowth \xD7 0.5) the growth softly asymptotes
2764
+ // to mapMaxGrowth \u2014 see the soft-knee block below. Tracks node.vert.glsl
2765
+ // identically.
2766
+ float viewDepth = max(-mvParent.z, 0.001);
2767
+ float depthFactor;
2768
+ // Soft-knee curve \u2014 MUST mirror node.vert.glsl / picking.vert.glsl exactly so
2769
+ // badge/tag freeze in lockstep with the parent bubble (see spec G4).
2770
+ if (mapMode > 0.5) {
2771
+ float raw = pow(10.0 / viewDepth, mapDamping);
2772
+ depthFactor = kvMapGrowth(raw, mapMaxGrowth);
2773
+ } else {
2774
+ depthFactor = 10.0 / viewDepth;
2775
+ }
2776
+ vec2 ndc = clip.xy / clip.w;
2777
+ ndc += (pxOffset * depthFactor * 2.0) / uViewportPx;
2778
+ gl_Position = vec4(ndc * clip.w, clip.z, clip.w);
2779
+ }
2780
+ `;var He=`precision highp float;
2781
+
2782
+ // Position texture (from GPU layout controller)
2783
+ uniform sampler2D positionTexture;
2784
+ uniform float textureSize;
2785
+
2786
+ // Viewport in CSS pixels (not physical pixels)
2787
+ uniform vec2 uViewportPx;
2788
+ uniform float mapMode;
2789
+ uniform float mapDamping;
2790
+ uniform float mapMaxGrowth; // shared semantics with node.vert.glsl; -1.0 = Infinity sentinel
2791
+
2792
+ // Per-instance attributes
2793
+ attribute float aParentNodeIndex;
2794
+ attribute vec2 aAnchorOffsetPx;
2795
+ attribute vec2 aSizePx;
2796
+ attribute vec4 aUvRect;
2797
+ attribute vec3 aBgRgb;
2798
+ attribute vec3 aFgRgb;
2799
+ attribute float aGroupRole; // 0 = background quad, 1 = glyph quad
2800
+ attribute vec2 aGlyphOffsetPx; // glyph pixel offset within tag (CSS px)
2801
+ attribute vec2 aGlyphSizePx; // glyph quad size in CSS px
2802
+
2803
+ // Varyings to fragment shader
2804
+ varying vec2 vUv;
2805
+ varying vec4 vUvRect;
2806
+ varying vec3 vBgRgb;
2807
+ varying vec3 vFgRgb;
2808
+ varying float vGroupRole;
2809
+ varying vec2 vSizePx; // background pill dimensions in CSS px (used by frag for aspect)
2810
+
2811
+ // Helper: Sample position from position texture using ES 1.0 pattern
2812
+ vec3 samplePosition(float idx) {
2813
+ float texX = mod(idx, textureSize) + 0.5;
2814
+ float texY = floor(idx / textureSize) + 0.5;
2815
+ vec2 texCoord = vec2(texX, texY) / textureSize;
2816
+ vec4 posData = texture2D(positionTexture, texCoord);
2817
+ return posData.xyz;
2818
+ }
2819
+
2820
+ void main() {
2821
+ vUv = uv;
2822
+ vUvRect = aUvRect;
2823
+ vBgRgb = aBgRgb;
2824
+ vFgRgb = aFgRgb;
2825
+ vGroupRole = aGroupRole;
2826
+ vSizePx = aSizePx;
2827
+
2828
+ // 1. Sample parent position from the position texture
2829
+ vec3 parentPos = samplePosition(aParentNodeIndex);
2830
+
2831
+ // 2. Project parent center to clip space using the standard MVP
2832
+ vec4 mvParent = modelViewMatrix * vec4(parentPos, 1.0);
2833
+ vec4 clip = projectionMatrix * mvParent;
2834
+
2835
+ // 3. Compute screen-space pixel offset based on group role.
2836
+ // \`position.xy\` is [-0.5, 0.5]\xB2 for a Three.js PlaneGeometry of size 1.
2837
+ // ANCHOR_OFFSETS use CSS screen convention (Y increases downward). NDC uses
2838
+ // Y-up, so we negate the anchor Y component. \`position.xy\` already uses the
2839
+ // correct NDC sign (positive Y = up), so only the anchor needs flipping.
2840
+ vec2 anchorNdc = vec2(aAnchorOffsetPx.x, -aAnchorOffsetPx.y);
2841
+ vec2 pxOffset;
2842
+ if (aGroupRole < 0.5) {
2843
+ // Background quad \u2014 centre the pill at anchor + size offset
2844
+ pxOffset = anchorNdc + (position.xy * aSizePx);
2845
+ } else {
2846
+ // Glyph quad \u2014 position glyph within the tag at its measured offset
2847
+ pxOffset = anchorNdc + aGlyphOffsetPx + (position.xy * aGlyphSizePx);
2848
+ }
2849
+
2850
+ // 4. Apply pixel offset in NDC, scaled by scene depth so tags grow/shrink
2851
+ // proportionally with nodes as the user zooms.
2852
+ // Nodes use: pixelSize = nodeSize * 50 / max(-mvCenter.z, 0.001)
2853
+ // We match that depth curve: REF_DEPTH=10 is the depth where a size-10
2854
+ // node appears as 50 CSS px \u2014 matching the designed sizes in TypeScript.
2855
+ // At half the depth (zoom in 2\xD7), depthFactor=2 \u2192 tag is 2\xD7 bigger, same
2856
+ // as the node. At REF_DEPTH=10 exactly, depthFactor=1 \u2192 defined CSS px sizes.
2857
+ // Beyond softKnee (raw > mapMaxGrowth \xD7 0.5) the growth softly asymptotes
2858
+ // to mapMaxGrowth \u2014 see the soft-knee block below. Tracks node.vert.glsl
2859
+ // identically.
2860
+ float viewDepth = max(-mvParent.z, 0.001);
2861
+ float depthFactor;
2862
+ // Soft-knee curve \u2014 MUST mirror node.vert.glsl / picking.vert.glsl exactly so
2863
+ // badge/tag freeze in lockstep with the parent bubble (see spec G4).
2864
+ if (mapMode > 0.5) {
2865
+ float raw = pow(10.0 / viewDepth, mapDamping);
2866
+ depthFactor = kvMapGrowth(raw, mapMaxGrowth);
2867
+ } else {
2868
+ depthFactor = 10.0 / viewDepth;
2869
+ }
2870
+ vec2 ndc = clip.xy / clip.w;
2871
+ ndc += (pxOffset * depthFactor * 2.0) / uViewportPx;
2872
+ gl_Position = vec4(ndc * clip.w, clip.z, clip.w);
2873
+ }
2874
+ `;var Qr=T(_e),Jr=A(Me),eo=T(A(Y(De))),to=Ae,no=T(Fe),ro=A(Ee),oo=T(A(Y(Ie))),ao=Oe,io=Le,so=Ne,lo=Ge,co=Ve,uo=T(Ue),fo=T(He);function X(t,n,e){let[r,o]=n,[a,s]=e;if(r===o)return(a+s)/2;let i=Math.max(0,Math.min(1,(t-r)/(o-r)));return a+i*(s-a)}function Zt(t,n,e){let r=Math.log10(Math.max(t,1e-10)),o=Math.log10(Math.max(n[0],1e-10)),a=Math.log10(Math.max(n[1],1e-10));return X(r,[o,a],e)}function Qt(t,n,e){return X(Math.sqrt(Math.max(t,0)),[Math.sqrt(Math.max(n[0],0)),Math.sqrt(Math.max(n[1],0))],e)}function vo(t){return t==="log"?Zt:t==="sqrt"?Qt:X}function xo(t,n){let e=1/0,r=-1/0;for(let o of t){let a=Number(o.properties[n]);isNaN(a)||(a<e&&(e=a),a>r&&(r=a))}return e===1/0?[0,1]:[e,r]}function Jt(t,n,e){return[t[0]+(n[0]-t[0])*e,t[1]+(n[1]-t[1])*e,t[2]+(n[2]-t[2])*e]}function Be(t,n){if(t.length===0)return[.5,.5,.5];if(t.length===1)return t[0][1];for(let e=0;e<t.length-1;e++)if(n<=t[e+1][0]){let r=(n-t[e][0])/(t[e+1][0]-t[e][0]);return Jt(t[e][1],t[e+1][1],r)}return t[t.length-1][1]}var F={viridis:[[0,[.267,.004,.329]],[.25,[.229,.322,.545]],[.5,[.128,.566,.551]],[.75,[.369,.788,.384]],[1,[.993,.906,.144]]],plasma:[[0,[.05,.03,.53]],[.25,[.55,.05,.65]],[.5,[.93,.26,.38]],[.75,[.99,.68,.12]],[1,[.94,.97,.13]]],inferno:[[0,[0,0,.015]],[.25,[.34,.06,.43]],[.5,[.73,.21,.33]],[.75,[.97,.56,.04]],[1,[.99,1,.64]]],magma:[[0,[0,0,.015]],[.25,[.32,.06,.48]],[.5,[.72,.15,.43]],[.75,[.99,.49,.3]],[1,[.99,.99,.75]]],blues:[[0,[.97,.98,1]],[.25,[.62,.79,.88]],[.5,[.26,.57,.78]],[.75,[.13,.37,.66]],[1,[.03,.19,.42]]],reds:[[0,[1,.96,.94]],[.25,[.99,.73,.63]],[.5,[.98,.42,.29]],[.75,[.8,.15,.11]],[1,[.4,0,.05]]],greens:[[0,[.97,.99,.96]],[.25,[.7,.87,.67]],[.5,[.35,.73,.38]],[.75,[.14,.55,.17]],[1,[0,.27,.11]]],oranges:[[0,[1,.96,.92]],[.25,[.99,.82,.64]],[.5,[.99,.62,.31]],[.75,[.9,.4,.09]],[1,[.55,.22,.02]]],rdylgn:[[0,[.84,.19,.15]],[.25,[.99,.75,.43]],[.5,[1,1,.75]],[.75,[.65,.87,.44]],[1,[.1,.59,.31]]],rdbu:[[0,[.4,0,.12]],[.25,[.84,.38,.3]],[.5,[.97,.97,.97]],[.75,[.36,.65,.86]],[1,[.02,.19,.58]]],spectral:[[0,[.62,0,.26]],[.25,[.96,.43,.26]],[.5,[1,1,.75]],[.75,[.4,.76,.65]],[1,[.37,.31,.64]]],brbg:[[0,[.33,.19,.02]],[.25,[.75,.51,.18]],[.5,[.96,.96,.96]],[.75,[.35,.71,.67]],[1,[0,.24,.19]]]};function bo(t){return F[t]}function yo(t,n,e){let r=Math.max(0,Math.min(1,(t-n[0])/(n[1]-n[0]||1))),o=typeof e=="string"?F[e]??F.viridis:e;return Be(o,r)}function So(t,n,e,r){let o=typeof r=="string"?F[r]??F.rdbu:r,a;return t<=e?a=.5*(1-Math.max(0,Math.min(1,(e-t)/(e-n[0]||1)))):a=.5+.5*Math.max(0,Math.min(1,(t-e)/(n[1]-e||1))),Be(o,a)}function wo(t,n,e=[.6,.6,.6]){return n[t]??e}function Po(t,n,e){for(let r=0;r<n.length;r++)if(t<n[r])return e[r]??[.5,.5,.5];return e[n.length]??[.5,.5,.5]}function Co(t){let n=t.replace("#","");if(n.length!==3&&n.length!==6)return[.5,.5,.5];let e=parseInt(n,16);return isNaN(e)?[.5,.5,.5]:n.length===3?[(e>>8&15)/15,(e>>4&15)/15,(e&15)/15]:[(e>>16&255)/255,(e>>8&255)/255,(e&255)/255]}import*as We from"three";var Z=6378137,Ro=2*Math.PI*Z;function ko(t,n){let e=n*Math.PI/180,r=t*Math.PI/180,o=Z*e,a=Z*Math.log(Math.tan(Math.PI/4+r/2));return{x:o,y:a}}function zo(t,n){let e=t*Math.PI/180,r=n*Math.PI/180,o=Math.cos(e);return new We.Vector3(o*Math.sin(r),Math.sin(e),o*Math.cos(r))}function _o(t){let n=Math.asin(Math.max(-1,Math.min(1,t.y)))*180/Math.PI,e=Math.atan2(t.x,t.z)*180/Math.PI;return{latitude:n,longitude:e}}var c={Structure:1,Data:2,Style:4,Icons:8,Labels:16,Selection:32,Hover:64,Visibility:128,Pin:256,Position:512,Decorations:1024,All:2047},Do=11,en=c.Selection|c.Visibility|c.Pin|c.Hover,tn=c.Selection|c.Visibility|c.Hover,je={color:c.Style,size:c.Style,opacity:c.Style,icon:c.Icons,iconUV:c.Icons,imageUV:c.Icons,ringColor:c.Style,flags:en,effects:c.Style,collect:c.Decorations,suppressFill:c.Style,shape:c.Style},$e={color:c.Style,width:c.Style,opacity:c.Style,flags:tn,shape:c.Style,endpoints:c.Structure,flow:c.Style,glow:c.Style,tubeGlow:c.Style},nn=new Map(Object.entries(je)),rn=new Map(Object.entries($e));function Ao(t,n){return(t==="node"?nn:rn).get(n)}function Fo(t){return t==="node"?on:an}var on=Object.keys(je),an=Object.keys($e);var Oo=c.Decorations|c.Structure,Lo=c.Style|c.Visibility,No=c.Decorations|c.Structure|c.Position|c.Style,Go=c.Structure|c.Style|c.Position|c.Visibility,Vo=c.Structure|c.Position|c.Visibility|c.Style|c.Decorations;var k=Object.freeze([Object.freeze({key:"frame-time",kind:"frame-time"}),Object.freeze({key:"draw-call-count",kind:"draw-call-count"}),Object.freeze({key:"pick-latency",kind:"pick-latency"}),Object.freeze({key:"position-readback-time:layout-position",kind:"position-readback-time",site:"layout-position"}),Object.freeze({key:"position-readback-time:picking",kind:"position-readback-time",site:"picking"}),Object.freeze({key:"position-readback-time:minimap",kind:"position-readback-time",site:"minimap"})]);function G(t,n){return n?`${t}:${n}`:t}var E=600,qe=30;var Q=class{constructor(n,e,r=E){this.writeIndex=0;this.retained=0;this.observed=0;if(!Number.isInteger(r)||r<1)throw new Error(`[perf] SampleBuffer capacity must be a positive integer, received: ${r}`);this.kind=n,this.site=e,this.capacity=r,this.values=new Float64Array(r)}get sampleCount(){return this.retained}get totalObserved(){return this.observed}append(n){return typeof n!="number"||!Number.isFinite(n)?!1:(this.values[this.writeIndex]=n,this.writeIndex=(this.writeIndex+1)%this.capacity,this.retained<this.capacity&&this.retained++,this.observed++,!0)}toArrayOldestFirst(){let n=new Array(this.retained),e=this.retained<this.capacity?0:this.writeIndex;for(let r=0;r<this.retained;r++)n[r]=this.values[(e+r)%this.capacity];return n}};function Ke(t=E){let n=new Map;for(let e of k)n.set(e.key,new Q(e.kind,e.site,t));return n}function Ye(t){let n=t?.info?.render;return n?typeof n.drawCalls=="number"&&Number.isFinite(n.drawCalls)?{value:n.drawCalls,accurate:!0}:typeof n.calls=="number"&&Number.isFinite(n.calls)?{value:n.calls,accurate:!1}:null:null}function Xe(t){return t.accurate?"accurate":"approximate"}var V=class{constructor(n){this.pending=null;this.claimed=null;this.sequence=0;this.now=n}nextCorrelationId(){return this.sequence++,`pick-${this.sequence}`}markStart(n){let e=this.now();if(!Number.isFinite(e))return null;let r=n??this.nextCorrelationId();return this.pending={correlationId:r,startedAt:e},r}claim(){return this.pending?(this.claimed=this.pending,this.pending=null,!0):!1}settle(){let n=this.claimed;if(!n)return null;this.claimed=null;let e=this.now();return Number.isFinite(e)?{correlationId:n.correlationId,value:e-n.startedAt}:null}get hasPending(){return this.pending!==null}get hasClaimed(){return this.claimed!==null}};function sn(t){t.sort((e,r)=>e-r);let n=Math.ceil(.95*t.length);return t[Math.min(t.length,Math.max(1,n))-1]}function Ze(t){let n={kind:t.kind,sampleCount:t.sampleCount,totalObserved:t.totalObserved};if(t.site!==void 0&&(n.site=t.site),t.sampleCount===0)return n;let e=t.toArrayOldestFirst(),r=0,o=Number.NEGATIVE_INFINITY;for(let a=0;a<e.length;a++)r+=e[a],e[a]>o&&(o=e[a]);return n.mean=r/e.length,n.max=o,n.p95=sn(e),n}function ln(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Number.NaN}var U=class{constructor(n={}){this.channels=new Map;this.loggedReasons=new Set;this.renderFaultsSource=null;this.collecting=!0;this.frameCounter=0;this.pathId="webgl";this.drawCallAccuracyValue="unknown";this.nowFn=n.now??ln,this.suspendThreshold=n.suspendThreshold??qe,this.warnFn=n.warn??(e=>console.warn(e)),this.buffers=Ke(n.capacity??E);for(let e of k)this.channels.set(e.key,{kind:e.kind,site:e.site,buffer:this.buffers.get(e.key),state:"active",consecutiveFailures:0,suspendReason:null,lastFrameId:-1});this.pickTracker=new V(this.nowFn)}get collectionEnabled(){return this.collecting}setCollectionEnabled(n){this.collecting=n}get frameId(){return this.frameCounter}beginFrame(){return this.frameCounter++,this.frameCounter}get activePathId(){return this.pathId}setActivePathId(n){this.pathId=n}get drawCallAccuracy(){return this.drawCallAccuracyValue}now(){return this.nowFn()}frameTimeStart(){return this.nowFn()}readbackStart(){return this.nowFn()}recordFrameTime(n){let e=this.channels.get("frame-time");if(!this.canCollect(e)||e.lastFrameId===this.frameCounter)return;let r=this.nowFn();if(!Number.isFinite(n)||!Number.isFinite(r)){this.noteFailure(e,"clock-unavailable");return}this.append(e,r-n)&&(e.lastFrameId=this.frameCounter)}recordDrawCalls(n){let e=this.channels.get("draw-call-count");if(!this.canCollect(e)||e.lastFrameId===this.frameCounter)return;let r=Ye(n);if(r===null){this.noteFailure(e,"counter-unreadable");return}this.drawCallAccuracyValue=Xe(r),this.append(e,r.value)&&(e.lastFrameId=this.frameCounter)}recordReadback(n,e){let r=this.channels.get(G("position-readback-time",n));if(!this.canCollect(r))return;let o=this.nowFn();if(!Number.isFinite(e)||!Number.isFinite(o)){this.noteFailure(r,"clock-unavailable");return}this.append(r,o-e)}recordReadbackDuration(n,e){let r=this.channels.get(G("position-readback-time",n));if(this.canCollect(r)){if(!Number.isFinite(e)){this.noteFailure(r,"clock-unavailable");return}this.append(r,e)}}markPickStart(n){let e=this.channels.get("pick-latency");this.canCollect(e)&&this.pickTracker.markStart(n)===null&&this.noteFailure(e,"clock-unavailable")}claimPickStart(){let n=this.channels.get("pick-latency");this.canCollect(n)&&this.pickTracker.claim()}settlePickLatency(){let n=this.channels.get("pick-latency");if(!this.canCollect(n))return;let e=this.pickTracker.settle();e!==null&&this.append(n,e.value)}get pickLatencyTracker(){return this.pickTracker}setRenderFaultsSource(n){this.renderFaultsSource=n}renderFaults(){let n={total:0,lostCount:0,compileFailedCount:0,lastOccurredAt:null,permanentlyFellBack:!1,failedEngineShaderCount:0,failedHostShaderLayerIndices:[]};if(!this.renderFaultsSource)return n;try{let e=this.renderFaultsSource();return{...e,failedHostShaderLayerIndices:[...e.failedHostShaderLayerIndices]}}catch{return n}}noteEntryPointFailure(n,e,r){try{let o=this.channels.get(G(n,e));if(!o||o.state!=="active")return;this.noteFailure(o,r)}catch{}}summaries(){let n=[];for(let e of k)n.push(Ze(this.channels.get(e.key).buffer));return n}channelHealth(){let n=[];for(let e of k){let r=this.channels.get(e.key),o={kind:r.kind,state:r.state,consecutiveFailures:r.consecutiveFailures,suspendReason:r.suspendReason};r.site!==void 0&&(o.site=r.site),n.push(o)}return n}canCollect(n){return this.collecting&&n.state==="active"}append(n,e){let r=!1;try{r=n.buffer.append(e)}catch{r=!1}return r?(this.noteSuccess(n),!0):(this.noteFailure(n,"buffer-write-failed"),!1)}noteFailure(n,e){if(n.consecutiveFailures++,!this.loggedReasons.has(e)){this.loggedReasons.add(e);let r=n.site?`:${n.site}`:"";this.warnFn(`[perf] collection failed (${e}); first seen on channel ${n.kind}${r}. This reason is reported once per session; see channel health for the full picture.`)}n.state==="active"&&n.consecutiveFailures>=this.suspendThreshold&&(n.state="suspended",n.suspendReason=e)}noteSuccess(n){n.consecutiveFailures=0}};var Qe="__kinevizPerf";function cn(t){return{readAt:t.now(),activePathId:t.activePathId,collectionEnabled:t.collectionEnabled,drawCallAccuracy:t.drawCallAccuracy,summaries:t.summaries(),channelHealth:t.channelHealth(),renderFaults:t.renderFaults()}}function dn(t){return Object.freeze({read:()=>cn(t),setCollectionEnabled:n=>t.setCollectionEnabled(!!n)})}function Je(t,n=globalThis){let e=dn(t);try{n[Qe]=e}catch{}return e}var m=new U;Je(m);function oa(){try{m.beginFrame()}catch{}}function aa(){try{return m.frameTimeStart()}catch{return Number.NaN}}function ia(t){try{m.recordFrameTime(t)}catch{m.noteEntryPointFailure("frame-time",void 0,"buffer-write-failed")}}function sa(t){try{m.recordDrawCalls(t)}catch{m.noteEntryPointFailure("draw-call-count",void 0,"counter-unreadable")}}function la(){try{return m.readbackStart()}catch{return Number.NaN}}function ca(t,n){try{m.recordReadback(t,n)}catch{m.noteEntryPointFailure("position-readback-time",t,"buffer-write-failed")}}function da(t){try{m.recordReadbackDuration("layout-position",t)}catch{m.noteEntryPointFailure("position-readback-time","layout-position","buffer-write-failed")}}function pa(){try{m.markPickStart()}catch{m.noteEntryPointFailure("pick-latency",void 0,"clock-unavailable")}}function ha(){try{m.claimPickStart()}catch{m.noteEntryPointFailure("pick-latency",void 0,"clock-unavailable")}}function ua(){try{m.settlePickLatency()}catch{m.noteEntryPointFailure("pick-latency",void 0,"buffer-write-failed")}}function fa(t){try{m.setActivePathId(t)}catch{}}function ga(t){try{m.setRenderFaultsSource(t)}catch{}}import*as z from"three";function pn(t,n,e,r,o){n.updateMatrixWorld(!1);let a=t.clone().applyMatrix4(n.matrixWorld).project(e);return{x:(a.x+1)/2*r,y:(1-a.y)/2*o,z:a.z}}function xa(t,n,e,r,o){let{x:a,y:s}=pn(t,n,e,r,o);return{x:a,y:s}}function ba(t,n,e,r,o,a){let s=t/o*2-1,i=-(n/a)*2+1;e.updateMatrixWorld(!1),r.updateMatrixWorld(!1);let l=new z.Raycaster;l.setFromCamera(new z.Vector2(s,i),r);let d=e.matrixWorld.clone().invert(),p=l.ray.origin.clone().applyMatrix4(d),h=l.ray.direction.clone().transformDirection(d).normalize();if(Math.abs(h.z)<1e-10)return null;let u=-p.z/h.z;return u<0?null:new z.Vector3(p.x+u*h.x,p.y+u*h.y,0)}function Sa(t,n){let e=t*n;return Math.ceil(e/256)*256}function wa(t,n){let{width:e,height:r,bytesPerPixel:o,bytesPerRow:a,orientation:s}=n;if(e<=0||r<=0)return new Uint8Array(0);let i=e*o;if(a<i)throw new RangeError(`normalizeReadback: bytesPerRow ${a} cannot hold a ${i}-byte row`);let l=new Uint8Array(i*r);for(let d=0;d<r;d++){let h=(s==="bottom-left"?r-1-d:d)*a,u=Math.min(i,t.length-h);u<=0||l.set(t.subarray(h,h+u),d*i)}return l}export{W as a,S as b,y as c,oe as d,mn as e,ae as f,vn as g,xn as h,bn as i,ie as j,yn as k,Sn as l,wn as m,Pn as n,se as o,Cn as p,Tn as q,Rn as r,kn as s,zn as t,_n as u,Mn as v,ce as w,Fn as x,En as y,O as z,ve as A,xt as B,be as C,K as D,Wt as E,jt as F,Kn as G,Yn as H,Zn as I,Qn as J,Jn as K,er as L,Z as M,Ro as N,ko as O,zo as P,_o as Q,Se as R,Pe as S,Ce as T,lr as U,cr as V,c as W,Do as X,Ao as Y,Fo as Z,Oo as _,Lo as $,No as aa,Go as ba,Vo as ca,oa as da,aa as ea,ia as fa,sa as ga,la as ha,ca as ia,da as ja,pa as ka,ha as la,ua as ma,fa as na,ga as oa,Sa as pa,wa as qa,pn as ra,xa as sa,ba as ta,pr as ua,hr as va,qt as wa,A as xa,Qr as ya,Jr as za,eo as Aa,to as Ba,no as Ca,ro as Da,oo as Ea,ao as Fa,io as Ga,so as Ha,lo as Ia,co as Ja,uo as Ka,fo as La,Qt as Ma,vo as Na,xo as Oa,bo as Pa,yo as Qa,So as Ra,wo as Sa,Po as Ta,Co as Ua};
2875
+ //# sourceMappingURL=chunk-67FBXXN6.mjs.map