/* Canonical visual geometry is in author-controlled canvas units, never physical distance. */ (function (root, factory) { const api = factory(); if (typeof module === 'object' && module.exports) module.exports = api; else root.PlotDirectorMaps = api; })(typeof globalThis !== 'undefined' ? globalThis : this, function () { 'use strict'; const library = []; let topologyAdapter=null;const setTopologyAdapter=api=>topologyAdapter=api; function group(category, names, geometryClass = 'Marker', layer = 'Places', symbol = '◆') { names.split('|').forEach(type => library.push({ type, category, geometryClass, layer, symbol })); } group('Places', 'Capital|City|Town|Village|Hamlet|Settlement', 'Marker', 'Places', '⌂'); group('Buildings', 'House|Cottage|Farm|Manor|Palace|Castle|Fortress|Tower|Inn|Ruin', 'Marker', 'Places', '▥'); group('Culture', 'Church|Cathedral|Abbey|Monastery|Temple|Shrine|Sacred site|Monument', 'Marker', 'Places', '♜'); group('Transport', 'Bridge|Ford|Port|Harbour|Dock|Station|Crossroads|Gate|Airport', 'Marker', 'Places', '⚑'); group('Landmarks', 'Peak|Cave|Waterfall|Spring|Volcano|Significant tree|Landmark', 'Marker', 'Places', '▲'); group('Working places', 'Mine|Quarry|Forge|Factory|Mill|Warehouse|Camp|Custom', 'Marker', 'Places', '◇'); group('Land & terrain', 'Land Mass|Island|Mountain Range|Hills|Desert|Plains|Farmland', 'Area', 'Terrain', '▱'); group('Vegetation', 'Forest|Marsh', 'Area', 'Vegetation', '♣'); group('Water', 'Lake', 'Area', 'Water', '≈'); group('Water', 'River|Stream|Canal', 'Path', 'Water', '≈'); group('Routes', 'Major road|Road|Track|Trail|Railway|Sea route|Wall|Mountain ridge', 'Path', 'Routes', '↝'); group('Borders & regions', 'Kingdom|Province|County|Territory|Faction area|Disputed area', 'Area', 'Regions', '▧'); const settlements = ['Capital','City','Town','Village','Hamlet','Settlement']; const directions = ['N','NE','E','SE','S','SW','W','NW']; const distances = ['Very close','Close','Moderate','Far','Very far']; const vectors = [[0,-1],[.707,-.707],[1,0],[.707,.707],[0,1],[-.707,.707],[-1,0],[-.707,-.707]]; const copy = value => JSON.parse(JSON.stringify(value)); function geometry(f) { try { return JSON.parse(f.geometryJson || '{}'); } catch { return {}; } } function makeFeature(type, x, y, id) { const a = library.find(a => a.type === type) || library.find(a => a.type === 'Custom'); const area = a.geometryClass === 'Area', path = a.geometryClass === 'Path'; const points = area ? [[-.48,-.22],[-.20,-.5],[.17,-.43],[.48,-.18],[.4,.26],[.1,.48],[-.26,.35],[-.5,.1]] : [[-.5,-.25],[-.18,.08],[.15,-.1],[.5,.25]]; const feature = { featureID: id, name: type, type, geometryClass:a.geometryClass, layer:a.layer, x,y,width:area?330:path?260:42,height:area?220:path?130:42,rotation:0,zOrder:area?(a.layer==='Regions'?20:0):path?30:40,isPlaced:true,isProvisional:true,isLocked:false,showLabel:true,labelX:0,labelY:0,locationID:null,createLocation:false,floorPlanID:null,startFeatureID:null,endFeatureID:null,geometryJson:JSON.stringify({points,coast:'Natural'}),notes:'' }; if(settlements.includes(type))convertToArea(feature); return feature; } // Defaults are semantic and size-aware; explicit author ordering takes precedence. function drawingPriority(f){ const manual=geometry(f).drawingOrder;if(Number.isFinite(manual))return manual; const category=f.layer==='Regions'||['Land Mass','Kingdom','Province','County','Territory','Faction area','Disputed area'].includes(f.type)?0:hasBoundary(f)?1:f.geometryClass==='Area'?2:f.geometryClass==='Path'||['Bridge','Ford','Port','Harbour','Dock','Station','Crossroads','Gate','Airport'].includes(f.type)?3:4; const frame=areaFrame(f),size=isArea(f)?Math.abs(frame.width*frame.height):0; return category*100000+(isArea(f)?99999/(1+size/1000):0); } function drawingOrder(features){ const settlements=features.filter(hasBoundary),priorities=new Map(features.map(f=>[f.featureID,drawingPriority(f)])); // A large natural background (for example an island starter) must not bury a settlement on it. // Use containment of the boundary's frame, not physical-distance thresholds or manuscript names. for(const f of features){ if(f.geometryClass!=='Area'||f.layer==='Regions'||Number.isFinite(geometry(f).drawingOrder))continue; const size=Math.abs(f.width*f.height),possible=settlements.filter(s=>{const b=areaFrame(s);return size>Math.abs(b.width*b.height);}); if(!possible.length)continue;const polygon=outline(f,features); if(possible.some(s=>{const b=areaFrame(s);return [[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]].every(p=>pointInPolygon(localToWorld(b,p),polygon));}))priorities.set(f.featureID,99999/(1+size/1000)); } return [...features].sort((a,b)=>priorities.get(a.featureID)-priorities.get(b.featureID)||(a.zOrder||0)-(b.zOrder||0)||a.featureID.localeCompare(b.featureID)); } function reorder(features,ids,command){ const order=drawingOrder(features),chosen=new Set(ids),movable=f=>chosen.has(f.featureID)&&!f.isLocked; if(!order.some(movable))return false; const before=order.map(f=>f.featureID).join(); if(command==='front'||command==='back'){ const moving=order.filter(movable),rest=order.filter(f=>!movable(f));order.splice(0,order.length,...(command==='front'?[...rest,...moving]:[...moving,...rest])); }else if(command==='forward'){ for(let i=order.length-2;i>=0;i--)if(movable(order[i])&&!movable(order[i+1]))[order[i],order[i+1]]=[order[i+1],order[i]]; }else if(command==='backward'){ for(let i=1;if.featureID).join())return false; // Store a complete, deterministic order. New pieces still receive semantic defaults. order.forEach((f,i)=>{const g=geometry(f);g.drawingOrder=(i+1)*500000/(order.length+1);f.geometryJson=JSON.stringify(g);});return true; } function localToWorld(f,p) { const a=f.rotation*Math.PI/180, x=p[0]*f.width,y=p[1]*f.height; return [f.x+x*Math.cos(a)-y*Math.sin(a),f.y+x*Math.sin(a)+y*Math.cos(a)]; } function pathPoints(f,features) { const points=(geometry(f).points || [[-.5,0],[.5,0]]).map(p=>localToWorld(f,p)); for (const [index,key] of [[0,'startFeatureID'],[points.length-1,'endFeatureID']]) { const end=features.find(x=>x.featureID===f[key]); if(end) points[index]=[end.x,end.y]; } return points; } function curve(points,closed=false) { if(!points.length) return ''; let d=`M ${points[0][0]} ${points[0][1]}`; const n=points.length; for(let i=0;i<(closed?n:n-1);i++) { const p0=points[(i-1+n)%n],p1=points[i],p2=points[(i+1)%n],p3=points[(i+2)%n]; const a=(!closed&&i===0)?p1:p0,b=(!closed&&i===n-2)?p2:p3; d+=` C ${p1[0]+(p2[0]-a[0])/6} ${p1[1]+(p2[1]-a[1])/6} ${p2[0]-(b[0]-p1[0])/6} ${p2[1]-(b[1]-p1[1])/6} ${p2[0]} ${p2[1]}`; } return d+(closed?' Z':''); } function coastline(f) { const g=geometry(f),points=g.points || [],rough={Gentle:0,Natural:.018,Rugged:.045,Cliffs:.025,Fjords:.07,'Marsh/Delta':.035}[g.coast]??.018; if(!['Land Mass','Island'].includes(f.type)&&!hasBoundary(f)&&!f.settlementBoundary) return points; // Stable detail follows simple author control points; no random state or physical coordinates. return points.flatMap((p,i)=>{ const q=points[(i+1)%points.length],dx=q[0]-p[0],dy=q[1]-p[1]; return Array.from({length:5},(_,k)=>{const t=k/5,w=Math.sin((i*5+k)*2.399)*rough*Math.sin(t*Math.PI);return [p[0]+dx*t-dy*w,p[1]+dy*t+dx*w];}); }); } const isSettlement=f=>f.geometryClass==='Marker'&&settlements.includes(f.type); const hasBoundary=f=>isSettlement(f)&&!!geometry(f).boundary; const isArea=f=>f.geometryClass==='Area'||hasBoundary(f); function convertToArea(f){ if(!isSettlement(f)||hasBoundary(f)||f.isLocked)return false; const g=geometry(f); const size=({Capital:[560,360],City:[480,320],Town:[330,220],Village:[240,160],Hamlet:[180,120],Settlement:[300,200]})[f.type]; g.boundary={offsetX:0,offsetY:0,width:size[0],height:size[1],rotation:0,points:[[-.48,-.22],[-.20,-.5],[.17,-.43],[.48,-.18],[.4,.26],[.1,.48],[-.26,.35],[-.5,.1]],coast:'Natural'}; f.geometryJson=JSON.stringify(g);return true; } function areaGeometry(f){return hasBoundary(f)?geometry(f).boundary:geometry(f);} function updateArea(f,change){const g=geometry(f);change(hasBoundary(f)?g.boundary:g);f.geometryJson=JSON.stringify(g);} function areaFrame(f){ if(!hasBoundary(f))return f; const b=areaGeometry(f); return {x:f.x+b.offsetX,y:f.y+b.offsetY,width:b.width,height:b.height,rotation:b.rotation,geometryClass:'Area',type:f.type,settlementBoundary:true,geometryJson:JSON.stringify(b)}; } function worldToLocal(f,p){const a=-f.rotation*Math.PI/180,dx=p[0]-f.x,dy=p[1]-f.y;return [(dx*Math.cos(a)-dy*Math.sin(a))/f.width,(dx*Math.sin(a)+dy*Math.cos(a))/f.height];} function translate(f,dx,dy){f.x+=dx;f.y+=dy;} function moveAnchor(f,x,y){if(f.isLocked)return false;const dx=x-f.x,dy=y-f.y;if(hasBoundary(f))updateArea(f,b=>{b.offsetX-=dx;b.offsetY-=dy;});f.x=x;f.y=y;return true;} function featureBounds(f,features=[]){ const frame=areaFrame(f),pts=isArea(f)?(topologyAdapter&&features.length&&(topologyAdapter.linked(f)||areaGeometry(f).edgeShapes)?topologyAdapter.outline(f,features):coastline(frame).map(p=>localToWorld(frame,p))):f.geometryClass==='Path'?pathPoints(f,features):[[f.x-f.width/2,f.y-f.height/2],[f.x+f.width/2,f.y+f.height/2]]; if(!pts.length)pts.push(localToWorld(frame,[-.5,-.5]),localToWorld(frame,[.5,.5])); if(hasBoundary(f))pts.push([f.x,f.y]); return {left:Math.min(...pts.map(p=>p[0])),right:Math.max(...pts.map(p=>p[0])),top:Math.min(...pts.map(p=>p[1])),bottom:Math.max(...pts.map(p=>p[1]))}; } // Sample the same cubic segments used by curve(); containment follows the rendered, smoothed outline. function outline(f,features=[]){ if(topologyAdapter&&features.length&&(topologyAdapter.linked(f)||areaGeometry(f).edgeShapes))return topologyAdapter.outline(f,features); const frame=areaFrame(f),p=coastline(frame).map(p=>localToWorld(frame,p)),result=[],n=p.length; for(let i=0;i=Math.min(ax,bx)-1e-7&&x<=Math.max(ax,bx)+1e-7&&y>=Math.min(ay,by)-1e-7&&y<=Math.max(ay,by)+1e-7)return true; if(ay<=y&&by>y&&cross<0)winding++;else if(ay>y&&by<=y&&cross>0)winding--; } return winding!==0; } function containment(features){ const cell=300,buckets=new Map(),placed=features.filter(f=>f.isPlaced),byID=new Map(placed.map(f=>[f.featureID,f])); const areas=new Map(placed.filter(isArea).map(area=>[area.featureID,{area,bounds:null,polygon:null}])); for(const f of placed){const key=Math.floor(f.x/cell)+','+Math.floor(f.y/cell);if(!buckets.has(key))buckets.set(key,[]);buckets.get(key).push(f);} function bounds(record){ if(!record.bounds){const b=featureBounds(record.area,features),dx=(b.right-b.left)/6+1e-7,dy=(b.bottom-b.top)/6+1e-7;record.bounds={left:b.left-dx,right:b.right+dx,top:b.top-dy,bottom:b.bottom+dy};} return record.bounds; } function contains(record,f){ if(record.area===f)return false; const b=bounds(record);if(f.xb.right||f.yb.bottom)return false; record.polygon||=outline(record.area,features); return record.polygon.length>=3&&pointInPolygon([f.x,f.y],record.polygon); } // Lazy lists avoid materialising an O(n²) containment graph for heavily overlapping maps. function lists(ids,compute){const map=new Map(ids.map(id=>[id,undefined]));map.get=function(id){let value=Map.prototype.get.call(this,id);if(value===undefined&&this.has(id)){value=compute(id);this.set(id,value);}return value;};return map;} const inside=lists(features.map(f=>f.featureID),id=>{const f=byID.get(id);return f?[...areas.values()].filter(a=>contains(a,f)).map(a=>a.area.featureID):[];}); const contents=lists([...areas.keys()],id=>{ const record=areas.get(id),b=bounds(record),x1=Math.floor(b.left/cell),x2=Math.floor(b.right/cell),y1=Math.floor(b.top/cell),y2=Math.floor(b.bottom/cell),candidates=[]; if((x2-x1+1)*(y2-y1+1)>placed.length*2)candidates.push(...placed); else for(let x=x1;x<=x2;x++)for(let y=y1;y<=y2;y++)candidates.push(...(buckets.get(x+','+y)||[])); return candidates.filter(f=>contains(record,f)).map(f=>f.featureID); }); return {inside,contents}; } function fitBoundary(f,items,features){ if(f.isLocked||!hasBoundary(f)||!items.length)return false; const boxes=items.map(p=>featureBounds(p,features)),left=Math.min(...boxes.map(b=>b.left)),right=Math.max(...boxes.map(b=>b.right)),top=Math.min(...boxes.map(b=>b.top)),bottom=Math.max(...boxes.map(b=>b.bottom)); const margin=Math.max(35,(right-left)*.1,(bottom-top)*.1),width=Math.max(100,right-left+margin*2),height=Math.max(100,bottom-top+margin*2),offsetX=(left+right)/2-f.x,offsetY=(top+bottom)/2-f.y; if(width>100000||height>100000||Math.abs(offsetX)>200000||Math.abs(offsetY)>200000)return false; updateArea(f,b=>Object.assign(b,{offsetX,offsetY,width,height,rotation:0,points:[[-.5,-.5],[0,-.5],[.5,-.5],[.5,0],[.5,.5],[0,.5],[-.5,.5],[-.5,0]]}));return true; } function suggestedDirection(a,b) { const angle=Math.atan2(a.x-b.x,-(a.y-b.y)); return directions[(Math.round(angle/(Math.PI/4))+8)%8]; } function arrange(features,relationships,onlyNew=false) { const result=copy(features),byId=new Map(result.map(f=>[f.featureID,f])); const movable=f=>!f.isLocked&&(!onlyNew||!f.isPlaced); const original=new Map(features.map(f=>[f.featureID,f])); const constraints=relationships.filter(r=>byId.has(r.sourceID)&&byId.has(r.targetID)).map(copy).sort((a,b)=>a.relationshipID.localeCompare(b.relationshipID)); for(const route of result.filter(f=>f.geometryClass==='Path'&&f.startFeatureID&&f.endFeatureID)) { if(!byId.has(route.startFeatureID)||!byId.has(route.endFeatureID)||constraints.some(r=>(r.sourceID===route.startFeatureID&&r.targetID===route.endFeatureID)||(r.targetID===route.startFeatureID&&r.sourceID===route.endFeatureID)))continue; constraints.push({relationshipID:'route-'+route.featureID,sourceID:route.endFeatureID,targetID:route.startFeatureID,direction:suggestedDirection(byId.get(route.endFeatureID),byId.get(route.startFeatureID)),relativeDistance:'Moderate',connection:true}); } const adjacency=new Map(result.map(f=>[f.featureID,[]])); for(const r of constraints){adjacency.get(r.sourceID).push(r.targetID);adjacency.get(r.targetID).push(r.sourceID);} const spacing=(a,b,r)=>([100,180,290,430,600][distances.indexOf(r.relativeDistance)]||240)+Math.min(Math.max(a.width,a.height,b.width,b.height)/2,180); const markers=result.filter(f=>f.geometryClass==='Marker'),cellSize=Math.max(120,...markers.map(f=>Math.max(f.width,f.height)+60)); // An established anchor per component prevents drift. Unplaced pieces stay free. const anchored=new Set(),visited=new Set(); for(const seed of result) { if(visited.has(seed.featureID))continue; const queue=[seed],component=[];visited.add(seed.featureID); while(queue.length){const f=queue.shift();component.push(f);for(const other of adjacency.get(f.featureID))if(!visited.has(other)){visited.add(other);queue.push(byId.get(other));}} const anchor=component.find(f=>f.isLocked)||component.find(f=>f.isPlaced); if(anchor)anchored.add(anchor.featureID); } for(let pass=0;pass<100;pass++) { for(const r of constraints) { const a=byId.get(r.sourceID),b=byId.get(r.targetID),v=vectors[directions.indexOf(r.direction||suggestedDirection(original.get(a.featureID),original.get(b.featureID)))]; if(!r.direction&&!r.relativeDistance)continue; const distance=spacing(a,b,r); const dx=(a.x-b.x)-v[0]*distance,dy=(a.y-b.y)-v[1]*distance; const ma=movable(a)&&!anchored.has(a.featureID),mb=movable(b)&&!anchored.has(b.featureID),n=Number(ma)+Number(mb); if(ma){a.x-=dx*.35/n;a.y-=dy*.35/n;} if(mb){b.x+=dx*.35/n;b.y+=dy*.35/n;} } // Existing manual placement has a persistent restoring weight. for(const f of result)if(movable(f)&&!anchored.has(f.featureID)&&f.isPlaced){const o=original.get(f.featureID);f.x+=(o.x-f.x)*.012;f.y+=(o.y-f.y)*.012;} const buckets=new Map(); for(const a of markers){const cx=Math.floor(a.x/cellSize),cy=Math.floor(a.y/cellSize);for(let ox=-1;ox<=1;ox++)for(let oy=-1;oy<=1;oy++)for(const b of buckets.get(`${cx+ox},${cy+oy}`)||[]){ const min=(Math.max(a.width,a.height)+Math.max(b.width,b.height))/2+30,dx=b.x-a.x,dy=b.y-a.y,len=Math.hypot(dx,dy); if(len>=min)continue; const shift=(min-len)*.5,ux=len?dx/len:1,uy=len?dy/len:0; if(movable(b)&&!anchored.has(b.featureID)){b.x+=ux*shift;b.y+=uy*shift;} if(movable(a)&&!anchored.has(a.featureID)){a.x-=ux*shift;a.y-=uy*shift;} }const key=`${cx},${cy}`;if(!buckets.has(key))buckets.set(key,[]);buckets.get(key).push(a);} } const warnings=[]; for(const r of constraints) { const a=byId.get(r.sourceID),b=byId.get(r.targetID); if(!r.connection&&((r.direction&&suggestedDirection(a,b)!==r.direction)||(r.relativeDistance&&Math.abs(Math.hypot(a.x-b.x,a.y-b.y)-spacing(a,b,r))>spacing(a,b,r)*.5)))warnings.push(`${a.name} ${r.direction} of ${b.name}`); } result.forEach(f=>{if(movable(f)){f.isPlaced=true;if(!anchored.has(f.featureID)){f.x=Math.round(f.x*100)/100;f.y=Math.round(f.y*100)/100;}}}); if(topologyAdapter&&features.some(topologyAdapter.hasStore)){const adjusted=topologyAdapter.reposition(features,result);result.splice(0,result.length,...adjusted);} return {features:result,warnings}; } // Shared endpoint similarity transform: proportional along-line and perpendicular offsets. function connectionTransform(a,b,c,d){ const oldLength=Math.hypot(b[0]-a[0],b[1]-a[1]),nextLength=Math.hypot(d[0]-c[0],d[1]-c[1]); if(oldLength<.01||nextLength<.01)return null; const angle=Math.atan2(d[1]-c[1],d[0]-c[0])-Math.atan2(b[1]-a[1],b[0]-a[0]),ratio=nextLength/oldLength; return {angle,ratio,point:p=>{const x=p[0]-a[0],y=p[1]-a[1];return [c[0]+(x*Math.cos(angle)-y*Math.sin(angle))*ratio,c[1]+(x*Math.sin(angle)+y*Math.cos(angle))*ratio];}}; } function transformAnchoredPath(feature,before,after){ const points=pathPoints(feature,before),ends=pathPoints(feature,after),a=points[0],b=points.at(-1),c=ends[0],d=ends.at(-1); const transform=connectionTransform(a,b,c,d); // Degenerate connections have no unique direction; blend endpoint displacements, retaining bends. const moved=points.map((p,i)=>{const t=i/(points.length-1);return transform?transform.point(p):[p[0]+(c[0]-a[0])*(1-t)+(d[0]-b[0])*t,p[1]+(c[1]-a[1])*(1-t)+(d[1]-b[1])*t];}); if(moved.some(p=>p.some(n=>!Number.isFinite(n)||Math.abs(n)>100000)))throw Error('The proposed path exceeds safe canvas limits.'); const xs=moved.map(p=>p[0]),ys=moved.map(p=>p[1]),left=Math.min(...xs),right=Math.max(...xs),top=Math.min(...ys),bottom=Math.max(...ys); const f=copy(feature),g=geometry(f);f.x=(left+right)/2;f.y=(top+bottom)/2;f.width=Math.max(1,right-left);f.height=Math.max(1,bottom-top);f.rotation=0; if(f.width>100000||f.height>100000)throw Error('The proposed path is too large.'); const oldLabel=[feature.x+(feature.labelX||0),feature.y+(feature.labelY||0)],label=transform?transform.point(oldLabel):[oldLabel[0]+((c[0]-a[0])+(d[0]-b[0]))/2,oldLabel[1]+((c[1]-a[1])+(d[1]-b[1]))/2]; f.labelX=label[0]-f.x;f.labelY=label[1]-f.y; if(![f.labelX,f.labelY].every(n=>Number.isFinite(n)&&Math.abs(n)<=100000))throw Error('The proposed path label exceeds safe canvas limits.'); g.points=moved.map(p=>[(p[0]-f.x)/f.width,(p[1]-f.y)/f.height]);f.geometryJson=JSON.stringify(g);return f; } function transformEndpoint(feature,index,point,features){ const f=copy(feature),points=pathPoints(f,features),last=points.length-1; if(f.geometryClass!=='Path'||![0,last].includes(index)||(index===0?f.startFeatureID:f.endFeatureID))return f; const fixed=points[index===0?last:0],moving=points[index],oldLength=Math.hypot(moving[0]-fixed[0],moving[1]-fixed[1]); const nextLength=Math.hypot(point[0]-fixed[0],point[1]-fixed[1]);if(oldLength<.01||nextLength<10)return f; const transform=connectionTransform(fixed,moving,fixed,point),center=transform.point([f.x,f.y]);f.x=center[0];f.y=center[1]; f.width*=transform.ratio;f.height*=transform.ratio;f.rotation=normalAngle(f.rotation+transform.angle*180/Math.PI);return f; } const normalAngle=value=>((value+180)%360+360)%360-180; return {setTopologyAdapter,connectionTransform,transformAnchoredPath,drawingPriority,drawingOrder,reorder,settlements,isSettlement,hasBoundary,isArea,convertToArea,areaGeometry,updateArea,areaFrame,worldToLocal,translate,moveAnchor,featureBounds,outline,pointInPolygon,containment,fitBoundary,transformEndpoint,normalAngle,library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange}; });