PlotDirector/PlotLine/wwwroot/js/maps-geography-engine.js

82 lines
9.7 KiB
JavaScript

/* Spherical azimuthal equidistant projection, north up at the centre.
Refuse large extents: no flat projection preserves all worldwide distances/directions. */
(function(root){
'use strict';
const E=typeof module!=='undefined'&&module.exports?require('./maps-engine.js'):root.PlotDirectorMaps;
const T=typeof module!=='undefined'&&module.exports?require('./maps-topology-engine.js'):root.PlotDirectorTopology;
function position(features,states,bounds,locations=[]){
const rad=Math.PI/180,R=6371008.8,wrap=a=>Math.atan2(Math.sin(a),Math.cos(a));
if(![bounds.x,bounds.y,bounds.w,bounds.h].every(Number.isFinite)||bounds.w<=0||bounds.h<=0)throw Error('Map area is unavailable.');
const skipped=[],points=[],output=JSON.parse(JSON.stringify(features)),inherited=[],paths=[],attention=[],stateById=new Map(states.map(s=>[s.locationID,s])),original=new Map(features.map(f=>[f.featureID,f]));
const anchored=f=>f.geometryClass==='Path'&&!!(f.startFeatureID||f.endFeatureID);
const validMatch=s=>{let m;try{m=JSON.parse(s?.matchJson||'null');}catch{}return s?.status==='Resolved'&&m&&Number.isFinite(m.Latitude)&&Number.isFinite(m.Longitude)&&Math.abs(m.Latitude)<=90&&Math.abs(m.Longitude)<=180?m:null;};
for(const f of output){
if(!f.locationID||anchored(f))continue;
const state=stateById.get(f.locationID);
let match=null;try{match=JSON.parse(state?.matchJson||'null');}catch{}
const pendingLabel=state?.status==='Pending'?({'Awaiting hierarchy request':'Not requested','Queued':state.attempts?'Retry scheduled':'Queued','Processing':'Looking up','Waiting configuration':'Lookup disabled'}[state.jobState]||'Pending'):state?.status;
const reason=f.isLocked?'Locked':state?.status!=='Resolved'?(pendingLabel||'Pending'):!match?'Unresolved':null;
if(reason){skipped.push({featureID:f.featureID,name:f.name,reason,locationID:f.locationID,message:state?.message,canRequest:reason==='Not requested'});continue;}
if(!Number.isFinite(match.Latitude)||!Number.isFinite(match.Longitude)||Math.abs(match.Latitude)>90||Math.abs(match.Longitude)>180){skipped.push({featureID:f.featureID,name:f.name,locationID:f.locationID,reason:'Invalid geographical coordinates'});continue;}
points.push({feature:f,lat:match.Latitude*rad,lon:match.Longitude*rad,attribution:match.Attribution});
}
const positioned=points.map(p=>({name:p.feature.name,locationID:p.feature.locationID,featureID:p.feature.featureID,attribution:p.attribution}));
if(new Set(positioned.map(p=>p.locationID)).size<2)return {features:output,positioned,skipped,canApply:false,message:'At least two different resolved, unlocked locations are required. Request unsubmitted lookups or confirm matches in Location Details, then refresh status.'};
const sin=points.reduce((s,p)=>s+Math.sin(p.lon),0),cos=points.reduce((s,p)=>s+Math.cos(p.lon),0);
if(Math.hypot(sin,cos)<1e-9)throw Error('These locations span too much of the world. Use separate regional maps.');
const lon0=Math.atan2(sin,cos),lat0=points.reduce((s,p)=>s+p.lat,0)/points.length;
for(const p of points){
const dl=wrap(p.lon-lon0),cosc=Math.max(-1,Math.min(1,Math.sin(lat0)*Math.sin(p.lat)+Math.cos(lat0)*Math.cos(p.lat)*Math.cos(dl))),c=Math.acos(cosc);
if(c>15*rad)throw Error('These locations cover too large an area for reliable local positioning. Use separate regional maps (within about 1,650 km of their centre).');
const k=c<1e-10?1:c/Math.sin(c);
p.x=R*k*Math.cos(p.lat)*Math.sin(dl);
p.y=-R*k*(Math.cos(lat0)*Math.sin(p.lat)-Math.sin(lat0)*Math.cos(p.lat)*Math.cos(dl));
}
const xs=points.map(p=>p.x),ys=points.map(p=>p.y),left=Math.min(...xs),right=Math.max(...xs),top=Math.min(...ys),bottom=Math.max(...ys);
const pad=Math.min(80,bounds.w*.12,bounds.h*.12),w=bounds.w-2*pad,h=bounds.h-2*pad;
const scale=Math.min(right-left>1e-6?w/(right-left):Infinity,bottom-top>1e-6?h/(bottom-top):Infinity);
for(const p of points){p.feature.x=bounds.x+bounds.w/2+(p.x-(left+right)/2)*(Number.isFinite(scale)?scale:0);p.feature.y=bounds.y+bounds.h/2+(p.y-(top+bottom)/2)*(Number.isFinite(scale)?scale:0);p.feature.isPlaced=true;}
const byLocation=new Map(),locationById=new Map(locations.map(l=>[l.locationID,l])),own=new Set(points.map(p=>p.feature.featureID));
for(const p of points){const before=original.get(p.feature.featureID),delta=[p.feature.x-before.x,p.feature.y-before.y];if(!byLocation.has(p.feature.locationID))byLocation.set(p.feature.locationID,[]);byLocation.get(p.feature.locationID).push({feature:p.feature,delta});}
for(const f of output){
if(!f.locationID||own.has(f.featureID)||anchored(f))continue;
if(f.isLocked){attention.push({featureID:f.featureID,name:f.name,reason:'Locked; stays in place',locationID:f.locationID});continue;}
// A resolved location is never silently replaced by an ancestor's displacement.
if(validMatch(stateById.get(f.locationID)))continue;
const chain=[],visited=new Set();let id=f.locationID,problem=null;
while(id!=null){if(visited.has(id)){problem='Cyclic Location hierarchy';break;}visited.add(id);const l=locationById.get(id);if(!l){problem='Missing Location hierarchy entry';break;}chain.push(l);id=l.parentLocationID;}
if(problem){attention.push({featureID:f.featureID,name:f.name,reason:problem,locationID:f.locationID});continue;}
const index=chain.findIndex((l,i)=>i>0&&byLocation.has(l.locationID));if(index<0)continue;
if(chain.slice(1,index).some(l=>features.some(p=>p.locationID===l.locationID&&p.isLocked)&&validMatch(stateById.get(l.locationID)))){attention.push({featureID:f.featureID,name:f.name,reason:'A nearer geographical ancestor is locked',locationID:f.locationID});continue;}
const references=byLocation.get(chain[index].locationID),reference=references[0];
if(references.some(r=>Math.hypot(r.delta[0]-reference.delta[0],r.delta[1]-reference.delta[1])>1e-6)){attention.push({featureID:f.featureID,name:f.name,reason:'Ancestor has several map anchors with different displacements',locationID:f.locationID});continue;}
f.x+=reference.delta[0];f.y+=reference.delta[1];f.isPlaced=true;
inherited.push({featureID:f.featureID,name:f.name,locationID:f.locationID,ancestor:chain[index].locationName||reference.feature.name,via:chain.slice(1,index).map(l=>l.locationName||'Unnamed location'),kind:f.geometryClass});
}
// Endpoints always win over a path's optional Location association. Each existing path is one segment.
let blocked=false;
const current=new Map(output.map(f=>[f.featureID,f]));
for(let i=0;i<output.length;i++){
const f=output[i];if(!anchored(f))continue;
const ids=[f.startFeatureID,f.endFeatureID].filter(Boolean),missing=ids.some(id=>!original.has(id)||original.get(id).geometryClass!=='Marker');
const moved=ids.some(id=>{const a=original.get(id),b=current.get(id);return a&&b&&(Math.abs(a.x-b.x)>1e-7||Math.abs(a.y-b.y)>1e-7);});
if(missing)attention.push({featureID:f.featureID,name:f.name,reason:'Missing or invalid endpoint anchor'});
if(!moved)continue;
if(missing||f.isLocked){blocked=true;if(f.isLocked)attention.push({featureID:f.featureID,name:f.name,reason:'Unlock this path before repositioning its endpoints'});continue;}
try{output[i]=E.transformAnchoredPath(original.get(f.featureID),features,output);paths.push({name:f.name,featureID:f.featureID});}
catch(error){blocked=true;attention.push({featureID:f.featureID,name:f.name,reason:error.message});}
}
for(const f of output)if(![f.x,f.y].every(n=>Number.isFinite(n)&&Math.abs(n)<=100000)){blocked=true;attention.push({featureID:f.featureID,name:f.name,reason:'Proposed position exceeds safe canvas limits'});}
for(const f of output)if(f.geometryClass==='Path'&&JSON.stringify(f)!==JSON.stringify(original.get(f.featureID))&&!paths.some(p=>p.featureID===f.featureID))paths.push({name:f.name,featureID:f.featureID});
if(T)try{const adjusted=T.reposition(features,output);output.splice(0,output.length,...adjusted);}catch(error){blocked=true;attention.push({featureID:'shared-geometry',name:'Shared boundaries',reason:error.message});}
// Inherited pieces are no longer reported as pending objects that will stay behind.
const following=new Set(inherited.map(p=>p.featureID));
const kept=skipped.filter(p=>!following.has(p.featureID));
const changed=output.filter(f=>JSON.stringify(f)!==JSON.stringify(original.get(f.featureID))).length;
const counts={positioned:new Set(positioned.map(p=>p.locationID)).size,descendants:new Set(inherited.map(p=>p.locationID)).size,paths:paths.length,otherPieces:inherited.filter(p=>p.kind!=='Marker').length,unchanged:blocked?output.length:output.length-changed,attention:new Set(attention.map(p=>p.featureID)).size};
return {features:blocked?E.copy(features):output,positioned,skipped:kept,inherited,paths,attention,counts,canApply:!blocked&&changed>0,message:blocked?'Some paths or positions cannot be transformed safely. Resolve the attention items before applying; no changes will be applied.':changed?`${positioned.length} geographical pieces, ${inherited.length} descendants and ${paths.length} paths are included in this proposal.`:'These places are already in the proposed positions. No changes are needed.'};
}
root.PlotDirectorGeography={position};
if(typeof module!=='undefined')module.exports={position};
})(typeof window!=='undefined'?window:globalThis);