134 lines
10 KiB
JavaScript
134 lines
10 KiB
JavaScript
/* 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 = [];
|
|
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 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]];
|
|
return { 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:'' };
|
|
}
|
|
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)) 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];});
|
|
});
|
|
}
|
|
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;}}});
|
|
return {features:result,warnings};
|
|
}
|
|
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 angle=Math.atan2(point[1]-fixed[1],point[0]-fixed[0])-Math.atan2(moving[1]-fixed[1],moving[0]-fixed[0]),ratio=nextLength/oldLength;
|
|
const x=f.x-fixed[0],y=f.y-fixed[1];f.x=fixed[0]+(x*Math.cos(angle)-y*Math.sin(angle))*ratio;f.y=fixed[1]+(x*Math.sin(angle)+y*Math.cos(angle))*ratio;
|
|
f.width*=ratio;f.height*=ratio;f.rotation=normalAngle(f.rotation+angle*180/Math.PI);return f;
|
|
}
|
|
const normalAngle=value=>((value+180)%360+360)%360-180;
|
|
return {transformEndpoint,normalAngle,library,directions,distances,copy,geometry,makeFeature,localToWorld,pathPoints,curve,coastline,suggestedDirection,arrange};
|
|
});
|