Repository navigation
Expand file tree
/
Copy pathnovaphoenix-campaign-map.html
More file actions
582 lines (496 loc) · 27.3 KB
/
Copy pathnovaphoenix-campaign-map.html
File metadata and controls
582 lines (496 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Nova Phoenix Saga - Galaxy Map</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/5/w3.css">
<link rel="stylesheet" href="./css/main.css">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="apple-touch-icon" sizes="180x180" href="./images/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="./images/favicon-16x16.png">
<link rel="manifest" href="./images/site.webmanifest">
<script src="./js/nav.js"></script>
<!-- Leaflet.js -->
<link rel="stylesheet" href="./css/leaflet.css" />
<script src="./js/leaflet.js"></script>
<!-- Turf.js -->
<script src="https://unpkg.com/@turf/turf@6/turf.min.js"></script>
<style>
#map {
height: 80vh;
background: #000; /* pure black space */
border: 2px solid #444;
border-radius: 8px;
}
.leaflet-container {
background: #000 !important;
}
</style>
</head>
<body class="w3-gray">
<header id="top" class="w3-container w3-center">
<h1>The Nova Phoenix Saga</h1>
<div class="w3-padding" style="width:100%">
<img src="./images/nova.jpg" class="w3-image">
</div>
<nav id="navbar" class="w3-bar w3-border w3-card">
</nav>
<script>
loadNavbar("./nav-gaming-rpgs-campaigns-novaphoenix.html");
</script>
<h2>Galaxy Map</h2>
</header>
<section class="w3-container">
<div id="map"></div>
</section>
<section class="w3-container">
<div id="controls" class="w3-container w3-card">
<h3>Hyperspace Navicomputer</h3>
<p><strong>Waypoints:</strong></p>
<ul id="waypointList" style="margin:0; padding-left:20px; font-size:0.9em;"></ul>
<button class="w3-border w3-button" onclick="clearWaypoints()" style="margin:8px 0;">Clear All Waypoints</button><br>
<label>Hyperdrive Class: <input id="hdClass" type="number" value="1" step="0.5" style="width:60px"></label><br>
<label>User Modifier (e.g. superior nav): <input id="userMod" type="number" value="1" step="0.1" style="width:60px"></label><br><br>
<button class="w3-border w3-button" onclick="calculateRoute('waypoint', parseFloat(document.getElementById('hdClass').value), parseFloat(document.getElementById('userMod').value))">Calculate Waypoint Route</button>
<button class="w3-border w3-button" onclick="calculateRoute('fastest', parseFloat(document.getElementById('hdClass').value), parseFloat(document.getElementById('userMod').value))">Fastest Route (Lanes, First 2 Points)</button>
<button class="w3-border w3-button" onclick="calculateRoute('direct', parseFloat(document.getElementById('hdClass').value), parseFloat(document.getElementById('userMod').value))">Direct Jump (Off-Route, First 2 Points)</button>
<div id="result" style="margin-top:15px; font-size:0.9em;"></div>
</div>
</section>
<footer class="w3-container">
<p><i>
Uses <a href="https://leafletjs.com/">Leaflet</a>, <a href="https://turfjs.org/">Turf</a>, and
<a href="https://github.com/Wason1797/StarWarsMap">Wladymir Brborich (StarWarsMap)</a> for initial planet data and for initial route information.
</i></p>
</footer>
<script>
// Map Init
const map = L.map('map', {
minZoom: -8,
maxZoom: 6,
zoomSnap: 0.5, // Smoother zoom steps
zoomDelta: 0.5,
center: [0, 0],
zoom: -4,
crs: L.CRS.Simple
});
L.tileLayer('', {
attribution: 'Star Wars Galaxy – Data: Wladymir Brborich (StarWarsMap)',
}).addTo(map);
const galaxyBounds = L.latLngBounds(
L.latLng(-85, -95), // SW corner (y min, x min)
L.latLng(70, 135) // NE corner (y max, x max)
);
map.fitBounds(galaxyBounds, { padding: [50, 50] });
//var boradin = L.marker([4740, 8365]).addTo(map);
//boradin.bindTooltip('Boradin')
//var unknown = L.marker([2300, 9450]).addTo(map);
//unknown.bindTooltip('[Unkown System]')
// ====================== CONFIG ======================
const MAX_WAYPOINTS = 10;
const GRID_UNITS_PER_SQUARE = 100; // Tune this once so a typical Core-to-Rim major route = ~40-80 hours on Class 1
const HOURS_PER_SQUARE = {
major: 8,
minor: 14,
offroute: 20,
deepCore: 24
};
// Major route names (add more as needed)
const MAJOR_ROUTES = new Set([
"Corellian Run", "Hydian Way", "Perlemian Trade Route", "Rimma Trade Route",
"Corellian Trade Spine", "Corellian Trade Route", "Hydian", "Perlemian"
]);
// ====================== HELPERS ======================
function isMajorRoute(name) {
if (!name) return false;
return MAJOR_ROUTES.has(name) || name.toLowerCase().includes("corellian") || name.toLowerCase().includes("hydian");
}
function planarLength(coords) { // LineString or array of [x,y]
let total = 0;
for (let i = 1; i < coords.length; i++) {
const dx = coords[i][0] - coords[i-1][0];
const dy = coords[i][1] - coords[i-1][1];
total += Math.hypot(dx, dy);
}
return total;
}
function planarDistance(pt1, pt2) {
return Math.hypot(pt1[0] - pt2[0], pt1[1] - pt2[1]);
}
function getRegionModifier(region1, region2) {
const deep = ["Deep Core", "Core Worlds"];
if (deep.some(r => region1.includes(r) || region2.includes(r))) return 1.5;
return 1.0;
}
// ====================== PRIORITY QUEUE (Binary Min-Heap) ======================
// Simple, efficient binary heap for numbers/strings (min-heap: smallest first)
class MinHeap {
constructor() {
this.heap = []; // { priority: number, key: string, data?: any }
}
push(priority, key) {
this.heap.push({ priority, key });
this._bubbleUp(this.heap.length - 1);
}
pop() {
if (this.heap.length === 0) return null;
if (this.heap.length === 1) return this.heap.pop();
const min = this.heap[0];
this.heap[0] = this.heap.pop();
this._sinkDown(0);
return min;
}
isEmpty() {
return this.heap.length === 0;
}
_bubbleUp(index) {
const element = this.heap[index];
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
const parent = this.heap[parentIndex];
if (parent.priority <= element.priority) break;
this.heap[index] = parent;
index = parentIndex;
}
this.heap[index] = element;
}
_sinkDown(index) {
const length = this.heap.length;
const element = this.heap[index];
while (true) {
let left = 2 * index + 1;
let right = 2 * index + 2;
let swap = null;
let smallest = index;
if (left < length && this.heap[left].priority < this.heap[smallest].priority) {
smallest = left;
}
if (right < length && this.heap[right].priority < this.heap[smallest].priority) {
smallest = right;
}
if (smallest === index) break;
this.heap[index] = this.heap[smallest];
index = smallest;
}
this.heap[index] = element;
}
}
// ====================== OPTIMIZED DIJKSTRA FOR PLANET-TO-PLANET GRAPH ======================
function findShortestPath(startKey, endKey) {
// startKey and endKey are planet names (strings), e.g. "Coruscant", "Tatooine"
if (typeof startKey !== 'string' || typeof endKey !== 'string') {
console.error("findShortestPath: startKey and endKey must be planet name strings");
return null;
}
if (!graph.has(startKey) || !graph.has(endKey)) {
console.warn(`No path possible: ${startKey} or ${endKey} not in graph`);
return null;
}
const distances = new Map(); // planetName → best known total cost
const previous = new Map(); // planetName → previous planetName
const pq = new MinHeap(); // min-heap priority queue
// Initialize
distances.set(startKey, 0);
pq.push(0, startKey);
while (!pq.isEmpty()) {
const { priority: currentCost, key: current } = pq.pop();
// Skip outdated entries (multiple entries allowed for same node)
if (currentCost > (distances.get(current) || Infinity)) continue;
// Early exit when we dequeue the destination (optimal path found)
if (current === endKey) break;
const node = graph.get(current);
if (!node) continue;
for (const { key: neighbor, weight } of node.neighbors) {
// weight is pre-calculated (distance × hours_per_square)
const alt = currentCost + weight;
if (alt < (distances.get(neighbor) || Infinity)) {
distances.set(neighbor, alt);
previous.set(neighbor, current);
pq.push(alt, neighbor); // push new better estimate
}
}
}
if (!distances.has(endKey)) {
console.warn(`No route found between ${startKey} and ${endKey}`);
return null;
}
// Reconstruct path as array of planet names
const pathNames = [];
let current = endKey;
while (current !== startKey) {
pathNames.unshift(current);
current = previous.get(current);
if (!current) {
console.error("Path reconstruction failed - broken previous map");
return null;
}
}
pathNames.unshift(startKey);
return {
path: pathNames, // e.g. ["Coruscant", "Corellia", "Tatooine"]
cost: distances.get(endKey) // total base hours (before hyperdrive class / modifiers)
};
}
// ====================== LOAD DATA ======================
let pathFinder, hyperspaceFC, planetsData, planetLayer, routeLayer, lanesLayer;
let userWaypoints = [];
let graph = new Map(); // key: "x,y" → { neighbors: [{key: "x2,y2", weight: number, type: "major"|"minor"}], ... }
async function initNavigator() {
try
{
// Load hyperspace (your existing GeoJSON)
const hsRes = await fetch('./data/hyperlanes.json');
if (!hsRes.ok) throw new Error(`Hyperspace fetch failed: ${hsRes.status}`);
hyperspaceFC = await hsRes.json();
// Load planets (parzivail style)
const pRes = await fetch('./data/planet.geojson');
if (!pRes.ok) throw new Error(`Planets fetch failed: ${pRes.status}`);
const planetsGeo = await pRes.json();
planetsData = planetsGeo.features;
} catch(err) {
console.error(err);
alert("Failed to load galaxy data: check console & file paths");
}
// Add planets to map (assume your map var is called "map")
planetLayer = L.layerGroup().addTo(map);
planetsData.forEach(feature => {
const props = feature.properties;
if(!props.name) return;
const coords = feature.geometry.coordinates; // [lng/x, lat/y]
const marker = L.circleMarker([coords[1], coords[0]], { // Leaflet [lat, lng]
radius: 6,
color: '#00ff00',
fillColor: '#0066cc',
fillOpacity: 0.8,
interactive: true
});
marker.planetData = { // mimic your old structure
name: props.name,
region: props.region,
sector: props.sector
};
marker.on('click', (e) => {
e.originalEvent.stopPropagation();
addWaypoint(marker);
});
marker.bindTooltip(`<b>${marker.planetData.name}</b><br>${marker.planetData.region || 'Unknown'}`);
planetLayer.addLayer(marker);
});
// ====================== BUILD GRAPH ONCE ======================
hyperspaceFC.forEach(route => {
const type = route.type; // 'major' or 'minor' (already tagged)
const nodes = route.nodes;
const planets = planetLayer.getLayers()
for (let i = 0; i < nodes.length - 1; i++) {
const fromName = nodes[i];
const toName = nodes[i + 1];
const fromPlanet = planets.find(p => p.planetData.name.toLowerCase() === fromName.toLowerCase());
const toPlanet = planets.find(p => p.planetData.name.toLowerCase() === toName.toLowerCase());
if (!fromPlanet || !toPlanet) {
console.warn(`Skipping connection ${fromName} → ${toName} (planet not found in data)`);
continue;
}
const fromKey = fromPlanet.planetData.name; // or normalize: fromPlanet.name.replace(/\s+/g, '_')
const toKey = toPlanet.planetData.name;
// Calculate distance between planets (your planarDistance function)
const fromCoord = fromPlanet.getLatLng();
const toCoord = toPlanet.getLatLng();
const dist = planarDistance([fromCoord.lng, fromCoord.lat], [toCoord.lng, toCoord.lat]);
// Convert to "travel cost" (same as before)
const weight = (dist / GRID_UNITS_PER_SQUARE) *
(type === 'major' ? HOURS_PER_SQUARE.major : HOURS_PER_SQUARE.minor);
// Add bidirectional edge
if (!graph.has(fromKey)) graph.set(fromKey, { neighbors: [] });
if (!graph.has(toKey)) graph.set(toKey, { neighbors: [] });
graph.get(fromKey).neighbors.push({ key: toKey, weight, type, route: route.name });
graph.get(toKey).neighbors.push( { key: fromKey, weight, type, route: route.name });
}
});
console.log(`Graph built with ${graph.size} planet nodes and ${hyperspaceFC.length} routes`);
routeLayer = L.layerGroup().addTo(map);
updateWaypointList();
console.log('✅ Star Wars Hyperspace Navigator ready!');
}
// ====================== WAYPOINTS ======================
function addWaypoint(marker) {
if (userWaypoints.length >= MAX_WAYPOINTS) {
alert(`Max ${MAX_WAYPOINTS} waypoints reached. Clear first.`);
return;
}
userWaypoints.push(marker);
marker.setStyle({fillColor: '#ff6600', color: '#ff9900'}); // Highlight added
updateWaypointList();
}
function clearWaypoints() {
userWaypoints.forEach(m => {
m.setStyle({fillColor: '#0066cc', color: '#00ccff'});
});
userWaypoints = [];
routeLayer.clearLayers();
updateWaypointList();
}
function updateWaypointList() {
const list = document.getElementById('waypointList');
if (!list) return;
list.innerHTML = userWaypoints.map((m, i) =>
`<li>#${i+1}: ${m.planetData.name}</li>`
).join('') || '<li>No waypoints added yet</li>';
}
// ====================== CALCULATORS ======================
function calculateRoute(mode = 'fastest', hyperdriveClass = 1, userMod = 1) {
if (userWaypoints.length < 2) return alert('Add at least 2 waypoints by clicking planets');
routeLayer.clearLayers();
let segments = [];
let totalHours = 0;
let breakdown = [];
let start;
let end;
if (mode === 'fastest') {
const startName = userWaypoints[0].planetData.name;
const endName = userWaypoints[1].planetData.name;
const pathResult = findShortestPath(startName, endName);
if (pathResult) {
// Build coordinates for polyline from planet positions
const pathCoords = pathResult.path.map(name => {
const planet = planetsData.find(p => p.properties?.name === name || p.Name === name);
if (!planet) return null;
const coords = planet.geometry?.coordinates || [planet.X, planet.Y];
return [coords[1], coords[0]]; // [lat=Y, lng=X]
}).filter(Boolean);
L.polyline(pathCoords, {
color: '#00ff00',
weight: 5,
opacity: 0.8
}).addTo(routeLayer);
const baseHours = pathResult.cost;
const regionMod = getRegionModifier(
userWaypoints[0].planetData.properties.region,
userWaypoints[1].planetData.properties.region
);
totalHours = baseHours * hyperdriveClass * regionMod * userMod;
breakdown.push(`Network route via ${pathResult.path.length - 2} intermediate systems: ${baseHours.toFixed(1)} base hours`);
} else {
start = userWaypoints[0];
end = userWaypoints[1];
const startPt = [start.X, start.Y];
const endPt = [end.X, end.Y];
const dist = planarDistance(startPt, endPt);
const baseHours = (dist / GRID_UNITS_PER_SQUARE) * HOURS_PER_SQUARE.offroute;
const regionMod = getRegionModifier(start.Region, end.Region);
totalHours = baseHours * hyperdriveClass * regionMod * userMod * 1.3; // off-route penalty
L.polyline([[start.Y, start.X], [end.Y, end.X]], {color: '#ff0000', dashArray: '5,10'}).addTo(routeLayer);
breakdown.push(`Direct off-route: ${baseHours.toFixed(1)} base hours`);
}
}
else if (mode === 'direct') {
start = userWaypoints[0];
end = userWaypoints[1];
const startPt = [start.X, start.Y];
const endPt = [end.X, end.Y];
const dist = planarDistance(startPt, endPt);
const baseHours = (dist / GRID_UNITS_PER_SQUARE) * HOURS_PER_SQUARE.offroute;
const regionMod = getRegionModifier(start.Region, end.Region);
totalHours = baseHours * hyperdriveClass * regionMod * userMod * 1.3; // off-route penalty
L.polyline([[start.Y, start.X], [end.Y, end.X]], {color: '#ff0000', dashArray: '5,10'}).addTo(routeLayer);
breakdown.push(`Direct off-route: ${baseHours.toFixed(1)} base hours`);
}
else if (mode === 'waypoint') {
for (let i = 0; i < userWaypoints.length - 1; i++) {
const startKey = userWaypoints[i].planetData.name;
const endKey = userWaypoints[i+1].planetData.name;
let segment = {
from: startKey,
to: endKey,
type: 'unknown',
baseHours: 0,
color: '#888'
};
// Try network route first
const pathResult = findShortestPath(startKey, endKey);
if (pathResult) {
// Build coordinates for polyline from planet positions
const pathCoords = pathResult.path.map(name => {
const planet = planetsData.find(p => p.properties?.name === name || p.Name === name);
if (!planet) return null;
const coords = planet.geometry?.coordinates || [planet.X, planet.Y];
return [coords[1], coords[0]]; // [lat=Y, lng=X]
}).filter(Boolean);
L.polyline(pathCoords, {
color: '#00ff00',
weight: 5,
opacity: 0.8
}).addTo(routeLayer);
const baseHours = pathResult.cost;
const regionMod = getRegionModifier(
userWaypoints[0].planetData.properties.region,
userWaypoints[1].planetData.properties.region
);
totalHours = baseHours * hyperdriveClass * regionMod * userMod;
breakdown.push(`Network route via ${pathResult.path.length - 2} intermediate systems: ${baseHours.toFixed(1)} base hours`);
} else {
// Fallback: direct off-route
const dist = planarDistance([start.X, start.Y], [end.X, end.Y]);
const baseHours = (dist / GRID_UNITS_PER_SQUARE) * HOURS_PER_SQUARE.offroute;
segment.baseHours = baseHours;
segment.type = 'direct/off-route';
segment.color = '#ff0000';
L.polyline([[start.Y, start.X], [end.Y, end.X]], {
color: segment.color,
dashArray: '10, 5',
weight: 4
}).addTo(routeLayer).bindTooltip(`${start.Name} → ${end.Name}<br>Direct jump (off-route)<br>${baseHours.toFixed(1)} base hrs`);
}
// Apply modifiers per segment
const regionMod = getRegionModifier(start.Region, end.Region);
const segmentHours = segment.baseHours * hyperdriveClass * regionMod * userMod;
totalHours += segmentHours;
breakdown.push({
leg: `${i+1}: ${start.Name} → ${end.Name}`,
type: segment.type,
base: segment.baseHours.toFixed(1),
mod: `×${hyperdriveClass.toFixed(1)} ×${regionMod.toFixed(1)} ×${userMod.toFixed(1)}`,
hours: segmentHours.toFixed(1)
});
segments.push(segment);
}
}
// Final display
const hours = totalHours.toFixed(1);
const days = (totalHours / 24).toFixed(1);
let title = 'Route Calculation';
let extraInfo = '';
if (mode === 'waypoint') {
title = `Waypoint Route (${userWaypoints.length} stops)`;
extraInfo = `
<small>User mod: ×${userMod} | Segments: ${userWaypoints.length - 1}</small>
<table style="width:100%; margin-top:10px; border-collapse:collapse;">
<tr><th>Leg</th><th>Type</th><th>Base hrs</th><th>Mods</th><th>Final hrs</th></tr>
${breakdown.map(b => `
<tr style="border-bottom:1px solid #ddd;">
<td>${b.leg}</td><td>${b.type}</td><td>${b.base}</td><td>${b.mod}</td><td><b>${b.hours}</b></td>
</tr>
`).join('')}
</table>
`;
} else {
const startName = userWaypoints[0].planetData.name || 'Start';
const endName = userWaypoints[1].planetData.name || 'End';
title = `${startName} → ${endName}`;
extraInfo = `
<small>Region mod: ×${getRegionModifier(userWaypoints[0].planetData.region || '', userWaypoints[1].planetData.region || '').toFixed(1)} | User mod: ×${userMod}</small>
<ul>${breakdown.map(b => `<li>${b}</li>`).join('')}</ul>
`;
}
document.getElementById('result').innerHTML = `
<h3>${title}</h3>
<p><strong>${hours} hours (${days} days)</strong> at Class ${hyperdriveClass}</p>
${extraInfo}
`;
}
document.addEventListener('DOMContentLoaded', () => {
initNavigator();
});
</script>
</body>
</html>