/* Optional shared geometry in the existing GeometryJson contract. Coordinates are canvas units. */ (function(root,factory){const E=typeof module==='object'&&module.exports?require('./maps-engine.js'):root.PlotDirectorMaps,api=factory(E);if(typeof module==='object'&&module.exports)module.exports=api;else root.PlotDirectorTopology=api;E.setTopologyAdapter(api);})(typeof globalThis!=='undefined'?globalThis:this,function(E){ 'use strict'; const styles=['Natural','Gentle','Rugged','Cliffs','Fjords','Marsh/Delta'],factor={Gentle:.5,Natural:1,Rugged:1.7,Cliffs:1.3,Fjords:2,'Marsh/Delta':1.2},EPS=1e-5; const parsedRoots=new WeakMap(); const uid=()=>globalThis.crypto.randomUUID(),dist=(a,b)=>Math.hypot(a[0]-b[0],a[1]-b[1]),copy=E.copy; const linked=f=>!!E.areaGeometry(f).edgeRefs?.some(Boolean),hasStore=f=>f.geometryJson?.includes('"topologyStore"'),mix=(a,b,t)=>[a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t]; function context(features){ const byId=new Map(features.map(f=>[f.featureID,f])),roots=new Map(),dirty=new Set(),vertices=new Map(),edges=new Map(),vo=new Map(),eo=new Map(); const root=(id,write=false)=>{if(!roots.has(id)){const f=byId.get(id);if(!f)throw Error('A shared area is missing.');let cached=parsedRoots.get(f);if(!cached||cached.json!==f.geometryJson){cached={json:f.geometryJson,value:E.geometry(f)};parsedRoots.set(f,cached);}roots.set(id,cached.value);}if(write&&!dirty.has(id)){roots.set(id,copy(roots.get(id)));dirty.add(id);}return roots.get(id);}; const area=(id,write=false)=>{const g=root(id,write);return byId.get(id).geometryClass==='Marker'&&g.boundary?g.boundary:g;}; for(const f of features)if(hasStore(f)){const s=root(f.featureID).topologyStore;for(const[id,p]of Object.entries(s.vertices||{})){if(vertices.has(id))throw Error('Duplicate shared vertex.');vertices.set(id,p);vo.set(id,f.featureID);}for(const[id,e]of Object.entries(s.edges||{})){if(edges.has(id))throw Error('Duplicate shared edge.');edges.set(id,e);eo.set(id,f.featureID);}} const store=id=>{const g=root(id,true);return g.topologyStore||=( {version:1,vertices:{},edges:{}} );}; const members=(id,kind='edge')=>features.filter(f=>E.isArea(f)&&f.geometryJson?.includes(id)&&((kind==='edge'?area(f.featureID).edgeRefs:area(f.featureID).vertexRefs)||[]).includes(id)).map(f=>f.featureID); // Dirty rings may have acquired a reference not yet serialized. const users=(id,kind='edge')=>[...new Set([...members(id,kind),...[...dirty].filter(fid=>E.isArea(byId.get(fid))&&((kind==='edge'?area(fid).edgeRefs:area(fid).vertexRefs)||[]).includes(id))])].filter(fid=>((kind==='edge'?area(fid).edgeRefs:area(fid).vertexRefs)||[]).includes(id)); const vertex=(p,owner)=>{if(p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000))throw Error('Shared vertex exceeds safe canvas limits.');const id=uid();store(owner).vertices[id]=p;vertices.set(id,p);vo.set(id,owner);return id;}; const edge=(value,owner)=>{const id=uid();store(owner).edges[id]=value;edges.set(id,value);eo.set(id,owner);return id;}; const setVertex=(id,p)=>{if(p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000))throw Error('Shared vertex exceeds safe canvas limits.');if(!vo.has(id))throw Error('Missing shared vertex.');store(vo.get(id)).vertices[id]=p;vertices.set(id,p);}; const setEdge=(id,e)=>{store(eo.get(id)).edges[id]=e;edges.set(id,e);}; const frame=id=>{const f=byId.get(id),g=root(id);return f.geometryClass==='Marker'&&g.boundary?{x:f.x+g.boundary.offsetX,y:f.y+g.boundary.offsetY,width:g.boundary.width,height:g.boundary.height,rotation:g.boundary.rotation,type:f.type,geometryClass:'Area',settlementBoundary:true}:f;}; const commit=()=>features.map(f=>{if(!dirty.has(f.featureID))return f;const json=JSON.stringify(root(f.featureID));if(json.length>64000)throw Error('Shared geometry is too detailed for this area. Unjoin or simplify some segments first.');return {...f,geometryJson:json};}); return {features,byId,root,area,vertices,edges,vo,eo,dirty,frame,store,users,vertex,edge,setVertex,setEdge,commit}; } const ctx=(features)=>features?.byId?features:context(features); function controls(f,features){const c=ctx(features),g=c.area(f.featureID),frame=c.frame(f.featureID);return (g.points||[]).map((p,i)=>g.vertexRefs?.[i]?[...c.vertices.get(g.vertexRefs[i])]:E.localToWorld(frame,p));} function refs(c,id){const g=c.area(id,true),n=g.points.length;g.vertexRefs||=Array(n).fill(null);g.edgeRefs||=Array(n).fill(null);g.edgeShapes||=Array(n).fill(null);g.edgeStyles||=Array(n).fill(null);return g;} function cubic(points,i,closed=true){const n=points.length,p=points[i],q=points[(i+1)%n],a=closed?points[(i-1+n)%n]:points[Math.max(0,i-1)],b=closed?points[(i+2)%n]:points[Math.min(n-1,i+2)];return [p,[p[0]+(q[0]-a[0])/6,p[1]+(q[1]-a[1])/6],[q[0]-(b[0]-p[0])/6,q[1]-(b[1]-p[1])/6],q];} function point(q,t){const u=1-t;return [u*u*u*q[0][0]+3*u*u*t*q[1][0]+3*u*t*t*q[2][0]+t*t*t*q[3][0],u*u*u*q[0][1]+3*u*u*t*q[1][1]+3*u*t*t*q[2][1]+t*t*t*q[3][1]];} function encode(curves){const a=curves[0][0],b=curves.at(-1)[3],dx=b[0]-a[0],dy=b[1]-a[1],d=dx*dx+dy*dy;if(d[((p[0]-a[0])*dx+(p[1]-a[1])*dy)/d,((p[1]-a[1])*dx-(p[0]-a[0])*dy)/d];const shape=curves.map(q=>q.slice(1).map(local));if(shape.flat(2).some(n=>!Number.isFinite(n)||Math.abs(n)>10000))throw Error('This edge is too close to collapsing to share safely.');return shape;} function decode(shape,a,b,coast,baseCoast){const dx=b[0]-a[0],dy=b[1]-a[1],ratio=(factor[coast]||1)/(factor[baseCoast]||1),world=p=>{const u=p[1]*ratio+Math.max(0,(factor[coast]||1)-(factor[baseCoast]||1))*.015*Math.sin(p[0]*Math.PI*2)*Math.sin(p[0]*Math.PI);return [a[0]+dx*p[0]-dy*u,a[1]+dy*p[0]+dx*u];};let p=a;return shape.map(row=>{const values=row.map(world),q=[p,...values];p=values[2];return q;});} const reverse=curves=>[...curves].reverse().map(q=>[q[3],q[2],q[1],q[0]]); function sharedCurves(id,features){const c=ctx(features),e=c.edges.get(id);if(!e)throw Error('A shared edge is missing.');return decode(e.shape,c.vertices.get(e.a),c.vertices.get(e.b),e.coast,e.baseCoast);} function edgeCurves(f,index,features){ const c=ctx(features),g=c.area(f.featureID),points=controls(f,c),n=points.length,id=g.edgeRefs?.[index]; if(id){const e=c.edges.get(id),q=sharedCurves(id,c);return g.vertexRefs[index]===e.a?q:reverse(q);} if(g.edgeShapes?.[index]){const s=g.edgeShapes[index];return decode(s.shape,points[index],points[(index+1)%n],g.coast||'Natural',s.baseCoast);} const frame=c.frame(f.featureID),local=points.map(p=>E.worldToLocal(frame,p)),coast=E.coastline({...frame,geometryJson:JSON.stringify({...g,points:local})}),world=coast.map(p=>E.localToWorld(frame,p)),per=world.length/n,result=[]; for(let k=0;kedgeCurves(f,i,c));} function path(curves,start=true){return (start?`M ${curves[0][0][0]} ${curves[0][0][1]} `:'')+curves.map(q=>`C ${q[1][0]} ${q[1][1]} ${q[2][0]} ${q[2][1]} ${q[3][0]} ${q[3][1]}`).join(' ');} function outline(f,features){return paths(f,features).flatMap(cs=>cs.flatMap(q=>Array.from({length:8},(_,i)=>point(q,i/8))));} function simple(points){ if(points.length<3||points.some(p=>!p||p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000)))return false; let area=0;for(let i=0;i(b[0]-a[0])*(p[1]-a[1])-(b[1]-a[1])*(p[0]-a[0]),xs=points.map(p=>p[0]),ys=points.map(p=>p[1]),cell=Math.max(EPS,Math.max(Math.max(...xs)-Math.min(...xs),Math.max(...ys)-Math.min(...ys))/Math.sqrt(points.length)),buckets=new Map(),long=[]; const intersect=(i,j)=>{if(Math.abs(i-j)===1||i===points.length-1&&j===0)return false;const a=points[i],b=points[(i+1)%points.length],c=points[j],d=points[(j+1)%points.length];if(Math.max(a[0],b[0])+EPSMath.abs(v)<1e-8&&r[0]>=Math.min(p[0],q[0])-1e-8&&r[0]<=Math.max(p[0],q[0])+1e-8&&r[1]>=Math.min(p[1],q[1])-1e-8&&r[1]<=Math.max(p[1],q[1])+1e-8;return x*y< -1e-10&&z*w< -1e-10||on(a,b,c,x)||on(a,b,d,y)||on(c,d,a,z)||on(c,d,b,w);}; for(let i=0;i128){for(let j=0;jedgeId&&dist(c.vertices.get(c.edges.get(edgeId).a),c.vertices.get(c.edges.get(edgeId).b))p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000)))throw Error('Boundary curves exceed safe canvas limits.');if(g.points.length<3||g.points.length>64||g.points.some(p=>p.some(n=>!Number.isFinite(n)||Math.abs(n)>10))||!simple(controls(f,c))||!simple(outline(f,c)))throw Error('This edit would make an area self-intersect, collapse or exceed 64 vertices. Adjust the endpoints or choose the other boundary section.');}} function unlocked(c,ids){if(ids.some(id=>c.byId.get(id)?.isLocked))throw Error('Unlock all participating areas before editing this shared geometry.');} function style(f){return {theme:E.hasBoundary(f)?'settlement':f.layer==='Regions'?'region':'terrain',...(E.areaGeometry(f).appearance||{})};} function clearVertexRefs(c,id){const g=refs(c,id),f=c.byId.get(id),points=controls(f,c);for(let i=0;ifreeze(c,fid));if(users.some(fid=>c.area(fid).points.length>=64))throw Error('This boundary already has 64 control points.'); if(old){const e=c.edges.get(old),owner=c.eo.get(old),canonical=g.vertexRefs[index]===e.a,vid=c.vertex(p,owner),l=c.edge({a:e.a,b:vid,shape:encode(canonical?left:reverse(right)),coast:e.coast,baseCoast:e.coast,style:copy(e.style)},owner),r=c.edge({a:vid,b:e.b,shape:encode(canonical?right:reverse(left)),coast:e.coast,baseCoast:e.coast,style:copy(e.style)},owner); for(const fid of users){const a=refs(c,fid),i=a.edgeRefs.indexOf(old),forward=a.vertexRefs[i]===e.a;const ids=forward?[l,r]:[r,l];a.points.splice(i+1,0,E.worldToLocal(c.frame(fid),p));a.vertexRefs.splice(i+1,0,vid);a.edgeRefs.splice(i,1,...ids);a.edgeShapes.splice(i,1,null,null);a.edgeStyles.splice(i,1,null,null);} gc(c); }else{g.points.splice(index+1,0,E.worldToLocal(c.frame(f.featureID),p));g.vertexRefs.splice(index+1,0,null);g.edgeRefs.splice(index,1,null,null);g.edgeShapes.splice(index,1,{shape:encode(left),baseCoast:g.coast||'Natural'},{shape:encode(right),baseCoast:g.coast||'Natural'});g.edgeStyles.splice(index,1,g.edgeStyles[index],g.edgeStyles[index]);} } function removePoint(features,id,index){ const c=context(features),f=c.byId.get(id),g=refs(c,id),n=g.points.length,prev=(index-1+n)%n,left=g.edgeRefs[prev],right=g.edgeRefs[index],v=g.vertexRefs[index];unlocked(c,[id]);if(n<=3)throw Error('An area needs at least three vertices.'); if(v){if(!left||!right||left===right)throw Error('Unjoin this junction before removing its endpoint.');const affected=c.users(v,'vertex');unlocked(c,affected);const lu=c.users(left).sort().join(),ru=c.users(right).sort().join();if(lu!==ru||affected.sort().join()!==lu)throw Error('A shared junction cannot be deleted while other segments meet there.'); const cs=[...edgeCurves(f,prev,c),...edgeCurves(f,index,c)],a=g.vertexRefs[prev],b=g.vertexRefs[(index+1)%n],e=c.edges.get(left),joined=c.edge({a,b,shape:encode(cs),coast:e.coast,baseCoast:e.coast,style:copy(e.style)},c.eo.get(left)); for(const fid of affected){const q=refs(c,fid),i=q.vertexRefs.indexOf(v),p=(i-1+q.points.length)%q.points.length;q.edgeRefs[p]=joined;q.points.splice(i,1);q.vertexRefs.splice(i,1);q.edgeRefs.splice(i,1);q.edgeShapes.splice(i,1);q.edgeStyles.splice(i,1);}gc(c);validate(c,affected); }else{g.points.splice(index,1);for(const key of ['vertexRefs','edgeRefs','edgeShapes','edgeStyles'])g[key].splice(index,1);g.edgeShapes[(index-1+g.points.length)%g.points.length]=null;validate(c,[id]);} return c.commit(); } function smooth(features,id,coast){if(!styles.includes(coast))throw Error('Choose an existing smoothing style.');const c=context(features),e=c.edges.get(id);if(!e)throw Error('Select a shared edge.');unlocked(c,c.users(id));c.setEdge(id,{...e,coast});validate(c,c.users(id));return c.commit();} function unjoin(features,fid,edgeId=null){const c=context(features),g=refs(c,fid);unlocked(c,[fid]);for(let i=0;iMath.floor(x/cell)+','+Math.floor(y/cell),put=(map,k,v)=>{if(!map.has(k))map.set(k,[]);map.get(k).push(v);}; for(const f of features.filter(E.isArea)){const ps=controls(f,c),g=c.area(f.featureID);ps.forEach((p,i)=>put(vertices,key(...p),{point:p,areaID:f.featureID,index:i,vertexID:g.vertexRefs?.[i]}));paths(f,c).forEach((cs,i)=>cs.forEach((q,k)=>{const xs=q.map(p=>p[0]),ys=q.map(p=>p[1]),box={left:Math.min(...xs),right:Math.max(...xs),top:Math.min(...ys),bottom:Math.max(...ys)},item={q,box,areaID:f.featureID,index:i,curveIndex:k,vertexIDs:[g.vertexRefs?.[i],g.vertexRefs?.[(i+1)%ps.length]]};const x0=Math.floor(box.left/cell),x1=Math.floor(box.right/cell),y0=Math.floor(box.top/cell),y1=Math.floor(box.bottom/cell);if((x1-x0+1)*(y1-y0+1)>64)long.push(item);else for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)put(segments,x+','+y,item);}));} return {c,cell,vertices,segments,long,key}; } function snap(index,p,tolerance,options={}){if(options.disabled)return null;const {cell,key}=index,candidates=(map)=>{const items=new Set();for(let x=p[0]-tolerance;x<=p[0]+tolerance+cell;x+=cell)for(let y=p[1]-tolerance;y<=p[1]+tolerance+cell;y+=cell)for(const item of map.get(key(x,y))||[])items.add(item);return [...items];}; const valid=v=>v.areaID!==options.areaID&&(!v.vertexID||v.vertexID!==options.vertexID);let best=null; if(options.vertex!==false)for(const v of candidates(index.vertices))if(valid(v)){const d=dist(p,v.point);if(d<=tolerance&&(!best||ds.box.right+tolerance||p[1]s.box.bottom+tolerance)continue;const n=nearestOnCurves([s.q],p);if(n.distance<=tolerance&&(!best||n.distancen)throw Error('Ambiguous boundary section.');}return ids;} function sectionLength(c,id,indices){const f=c.byId.get(id),n=c.area(id).points.length;let length=0;for(let k=0;kdist(p,q)=0)return i;let best=null;paths(c.byId.get(id),c).forEach((cs,index)=>{const hit=nearestOnCurves(cs,p,60);if(!best||hit.distanceEPS)throw Error('Snap both selected endpoints precisely to the neighbouring boundary first.');insertIn(c,id,best.index,best.curveIndex,best.t);ps=controls(c.byId.get(id),c);i=ps.findIndex(q=>dist(p,q)v===from?to:v);}for(const[id,e]of c.edges)if(e.a===from||e.b===from)c.setEdge(id,{...e,a:e.a===from?to:e.a,b:e.b===from?to:e.b});} function join(features,options){ const c=context(features);let {areaID,neighborID,start,end,sourceDirection='shorter',neighborDirection='shorter',retain='neighbor'}=options;if(areaID===neighborID)throw Error('Choose a different adjoining area.');unlocked(c,[areaID,neighborID]);const source=c.byId.get(areaID),target=c.byId.get(neighborID);if(!source||!target||!E.isArea(source)||!E.isArea(target))throw Error('Choose two geographical areas.'); freeze(c,areaID);freeze(c,neighborID);const ps=controls(source,c);if(start===end||!ps[start]||!ps[end])throw Error('Select two different boundary vertices.');const a=ps[start],b=ps[end];endpoint(c,neighborID,a);endpoint(c,neighborID,b);let targetPoints=controls(target,c),ta=targetPoints.findIndex(p=>dist(p,a)dist(p,b)sectionLength(c,areaID,ids)),dst=choose(ta,tb,tg.points.length,neighborDirection,ids=>sectionLength(c,neighborID,ids)); // Replace only a forward slice of the joining ring, retaining its winding. if(src[1]!==((src[0]+1)%sg.points.length)){src.reverse();dst.reverse();} const sp=controls(c.byId.get(areaID),c),tp=controls(c.byId.get(neighborID),c);if(src.slice(0,-1).some(i=>sg.edgeRefs[i]))throw Error('That section is already shared. Unjoin it first; existing shared boundaries are preserved.'); for(const i of dst){tg.vertexRefs[i]||=c.vertex(tp[i],neighborID);} mergeVertex(c,sg.vertexRefs[src[0]],tg.vertexRefs[dst[0]]);mergeVertex(c,sg.vertexRefs[src.at(-1)],tg.vertexRefs[dst.at(-1)]); const vertices=dst.map(i=>tg.vertexRefs[i]),edges=[]; for(let k=0;k(s+i)%n),privateIndices=rot.slice(length),newIndices=[...dst.slice(0,-1)],frame=c.frame(areaID); sg.points=[...newIndices.map(i=>E.worldToLocal(frame,tp[i])),...privateIndices.map(i=>sg.points[i])];sg.vertexRefs=[...vertices.slice(0,-1),...privateIndices.map(i=>sg.vertexRefs[i])];sg.vertexRefs[vertices.length-1]=vertices.at(-1); sg.edgeRefs=[...edges,...privateIndices.map(i=>sg.edgeRefs[i])];sg.edgeShapes=[...edges.map(()=>null),...privateIndices.map(i=>sg.edgeShapes[i])];sg.edgeStyles=[...edges.map(()=>null),...privateIndices.map(i=>sg.edgeStyles[i])]; gc(c);validate(c,[...new Set([...c.dirty,...vertices.flatMap(v=>c.users(v,'vertex'))])]);return c.commit(); } function detachCopies(features,copies,mapping){const c=context(features);return copies.map(f=>{const original=features.find(x=>mapping.get(x.featureID)===f.featureID);if(!original||!E.isArea(original))return f;const g=E.geometry(f),a=E.hasBoundary(f)?g.boundary:g,old=c.area(original.featureID);delete g.topologyStore;if(old.edgeRefs?.some(Boolean)){a.points=controls(original,c).map(p=>E.worldToLocal(c.frame(original.featureID),p));a.edgeShapes=paths(original,c).map(cs=>({shape:encode(cs),baseCoast:a.coast||'Natural'}));a.edgeStyles=old.points.map((_,i)=>old.edgeRefs?.[i]?{...copy(c.edges.get(old.edgeRefs[i]).style),reverseStroke:Boolean(c.edges.get(old.edgeRefs[i]).style.reverseStroke)!==(old.vertexRefs[i]!==c.edges.get(old.edgeRefs[i]).a)}:old.edgeStyles?.[i]||null);delete a.vertexRefs;delete a.edgeRefs;}return {...f,geometryJson:JSON.stringify(g)};});} function remove(features,ids){let output=features;for(const id of ids)if(output.some(f=>f.featureID===id&&E.isArea(f)))output=unjoin(output,id);const c=context(output),remaining=output.filter(f=>!ids.has(f.featureID)),survivors=new Set(remaining.map(f=>f.featureID)); for(const [kind,defs,owners]of [['vertices',c.vertices,c.vo],['edges',c.edges,c.eo]])for(const[id,value]of defs)if(!survivors.has(owners.get(id))){const users=c.users(id,kind==='vertices'?'vertex':'edge').filter(fid=>survivors.has(fid));if(!users.length)continue;const owner=users[0];c.store(owner)[kind][id]=copy(value);owners.set(id,owner);} return c.commit().filter(f=>survivors.has(f.featureID)); } function reposition(before,after){const c=context(after),old=new Map(before.map(f=>[f.featureID,f]));for(const[id,p]of c.vertices){const users=c.users(id,'vertex');if(!users.length)continue;const deltas=users.map(fid=>{const a=old.get(fid),b=c.byId.get(fid);return [b.x-a.x,b.y-a.y];}),delta=deltas[0];if(deltas.some(d=>dist(d,delta)>1e-6))throw Error('Shared areas '+users.map(fid=>c.byId.get(fid).name).join(', ')+' have incompatible geographical displacements. Unjoin their shared boundaries before repositioning.');if(Math.hypot(...delta)>1e-8)c.setVertex(id,[p[0]+delta[0],p[1]+delta[1]]);}return c.commit();} return {reverse,context,linked,hasStore,controls,paths,path,outline,edgeCurves,sharedCurves,style,point,encode,simple,movePoint,insert,removePoint,smooth,unjoin,join,snapIndex,snap,detachCopies,remove,reposition}; });