forked from inexorabletash/travellermap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.js
1785 lines (1494 loc) · 53.6 KB
/
map.js
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ======================================================================
// Exported Functionality
// ======================================================================
// NOTE: Used by other scripts
var Util = {
makeURL: function(base, params) {
'use strict';
base = String(base).replace(/\?.*/, '');
if (!params) return base;
var keys = Object.keys(params), args = '';
for (var i = 0; i < keys.length; ++i) {
var key = keys[i], value = params[key];
if (value === undefined || value === null) continue;
args += (args ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
}
return args ? base + '?' + args : base;
},
// Replace with URL/searchParams
parseURLQuery: function(url) {
'use strict';
var o = Object.create(null);
if (url.search && url.search.length > 1) {
url.search.substring(1).split('&').forEach(function(pair) {
if (!pair) return;
var kv = pair.split('=', 2);
if (kv.length === 2)
o[kv[0]] = decodeURIComponent(kv[1].replace(/\+/g, ' '));
else
o[kv[0]] = true;
});
}
return o;
},
escapeHTML: function(s) {
'use strict';
return String(s).replace(/[&<>"']/g, function(c) {
switch (c) {
case '&': return '&';
case '<': return '<';
case '>': return '>';
case '"': return '"';
case "'": return ''';
default: return c;
}
});
},
once: function(func) {
var run = false;
return function() {
if (run) return;
run = true;
func.apply(this, arguments);
};
},
debounce: function(func, delay, immediate) {
var timeoutId = 0;
if (immediate) {
return function() {
if (timeoutId)
clearTimeout(timeoutId);
else
func.apply(this, arguments);
timeoutId = setTimeout(function() { timeoutId = 0; }, delay);
};
} else {
return function() {
var $this = this, $arguments = arguments;
if (timeoutId)
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
func.apply($this, $arguments);
timeoutId = 0;
}, delay);
};
}
},
memoize: function(f) {
var cache = Object.create(null);
return function() {
var key = JSON.stringify([].slice.call(arguments));
return (key in cache) ? cache[key] : cache[key] = f.apply(this, arguments);
};
},
// p = ignorable(other_promise);
// p.then(...);
// p.ignore(); // p will neither resolve nor reject
// WARNING: p = ignorable(...).then(...); p.ignore(); will fail
// (Promise subclassing is not used)
ignorable: function(p) {
var ignored = false;
var q = new Promise(function(resolve, reject) {
p.then(function(r) { if (!ignored) resolve(r); },
function(r) { if (!ignored) reject(r); });
});
q.ignore = function() { ignored = true; };
return q;
},
fetchImage: function(url, img) {
return new Promise(function(resolve, reject) {
img = img || document.createElement('img');
img.src = url;
img.onload = function() { resolve(img); };
img.onerror = function(e) { reject(Error('Image failed to load')); };
});
}
};
(function(global) {
'use strict';
//----------------------------------------------------------------------
// General Traveller stuff
//----------------------------------------------------------------------
var SERVICE_BASE = (function(l) {
'use strict';
if (l.hostname === 'localhost' && l.pathname.indexOf('~') !== -1)
return 'https://travellermap.com';
return '';
}(window.location));
var LEGACY_STYLES = true;
function fromHex(c) {
return '0123456789ABCDEFGHJKLMNPQRSTUVW'.indexOf(c.toUpperCase());
}
//----------------------------------------------------------------------
// Enumerated types
//----------------------------------------------------------------------
var MapOptions = {
SectorGrid: 0x0001,
SubsectorGrid: 0x0002,
GridMask: 0x0003,
SectorsSelected: 0x0004,
SectorsAll: 0x0008,
SectorsMask: 0x000c,
BordersMajor: 0x0010,
BordersMinor: 0x0020,
BordersMask: 0x0030,
NamesMajor: 0x0040,
NamesMinor: 0x0080,
NamesMask: 0x00c0,
WorldsCapitals: 0x0100,
WorldsHomeworlds: 0x0200,
WorldsMask: 0x0300,
RoutesSelectedDeprecated: 0x0400,
PrintStyleDeprecated: 0x0800,
CandyStyleDeprecated: 0x1000,
StyleMaskDeprecated: 0x1800,
ForceHexes: 0x2000,
WorldColors: 0x4000,
FilledBorders: 0x8000,
Mask: 0xffff
};
var Styles = {
Poster: 'poster',
Atlas: 'atlas',
Print: 'print',
Candy: 'candy',
Draft: 'draft',
FASA: 'fasa'
};
//----------------------------------------------------------------------
// Astrometric Constants
//----------------------------------------------------------------------
var Astrometrics = {
ParsecScaleX: Math.cos(Math.PI / 6), // cos(30)
ParsecScaleY: 1.0,
SectorWidth: 32,
SectorHeight: 40,
ReferenceHexX: 1, // Reference is at Core 0140
ReferenceHexY: 40,
TileWidth: 256,
TileHeight: 256,
MinScale: 0.0078125,
MaxScale: 512,
// World-space: Hex coordinate, centered on Reference
sectorHexToWorld: function(sx, sy, hx, hy) {
return {
x: (sx * Astrometrics.SectorWidth) + hx - Astrometrics.ReferenceHexX,
y: (sy * Astrometrics.SectorHeight) + hy - Astrometrics.ReferenceHexY
};
},
worldToSectorHex: function(x, y) {
x += Astrometrics.ReferenceHexX - 1;
y += Astrometrics.ReferenceHexY - 1;
var sx = Math.floor(x / Astrometrics.SectorWidth);
var sy = Math.floor(y / Astrometrics.SectorHeight);
var hx = (x - (sx * Astrometrics.SectorWidth) + 1);
var hy = (y - (sy * Astrometrics.SectorHeight) + 1);
return {sx:sx, sy:sy, hx:hx, hy:hy};
},
// Map-space: Cartesian coordinates, centered on Reference
sectorHexToMap: function(sx, sy, hx, hy) {
var world = Astrometrics.sectorHexToWorld(sx, sy, hx, hy);
return Astrometrics.worldToMap(world.x, world.y);
},
worldToMap: function(wx, wy) {
var x = wx;
var y = wy;
// Offset from the "corner" of the hex
x -= 0.5;
y -= ((wx % 2) !== 0) ? 0 : 0.5;
// Scale to non-homogenous coordinates
x *= Astrometrics.ParsecScaleX;
y *= -Astrometrics.ParsecScaleY;
// Drop precision (avoid animations, etc)
x = Math.round(x * 1000) / 1000;
y = Math.round(y * 1000) / 1000;
return {x: x, y: y};
},
mapToWorld: function(x, y) {
var wx = Math.round((x / Astrometrics.ParsecScaleX) + 0.5);
var wy = Math.round((-y / Astrometrics.ParsecScaleY) + ((wx % 2 === 0) ? 0.5 : 0));
return {x: wx, y: wy};
},
// World-space Coordinates (Reference is 0,0)
hexDistance: function(ax, ay, bx, by) {
function even(x) { return (x % 2) == 0; }
function odd (x) { return (x % 2) != 0; }
var dx = bx - ax;
var dy = by - ay;
var adx = Math.abs(dx);
var ody = dy + Math.floor(adx / 2);
if (even(ax) && odd(bx))
ody += 1;
return Math.max(adx - ody, ody, adx);
}
};
var Defaults = {
options:
MapOptions.SectorGrid | MapOptions.SubsectorGrid |
MapOptions.SectorsSelected |
MapOptions.BordersMajor | MapOptions.BordersMinor |
MapOptions.NamesMajor |
MapOptions.WorldsCapitals | MapOptions.WorldsHomeworlds,
scale: 2,
style: Styles.Poster
};
var styleLookup = (function() {
var sheets = {};
var base = {
overlay_color: '#8080ff',
route_color: 'green',
main_color: 'cyan',
main_opacity: 0.25,
ew_color: 'yellow',
you_are_here_url: 'res/ui/youarehere.png'
};
sheets[Styles.Poster] = base;
sheets[Styles.Candy] = base;
sheets[Styles.Draft] = base;
sheets[Styles.Atlas] = Object.assign({}, base, {
overlay_color: '#808080',
you_are_here_url: 'res/ui/youarehere_gray.png'
});
sheets[Styles.FASA] = sheets[Styles.Print] =
Object.assign({}, base, {
you_are_here_url: 'res/ui/youarehere_gray.png'
});
return function(style, property) {
var sheet = sheets[style] || sheets[Defaults.style];
return sheet[property];
};
}());
// ======================================================================
// Data Services
// ======================================================================
var MapService = (function() {
function service(url, contentType, method) {
return fetch(url, {method: method || 'GET',
headers: {Accept: contentType}})
.then(function(response) {
if (!response.ok)
throw Error(response.statusText);
return (contentType === 'application/json') ?
response.json() : response.text();
});
}
function url(path, options) {
return Util.makeURL(SERVICE_BASE + path, options);
}
return {
makeURL: function(path, options) {
return url(path, options);
},
coordinates: function(sector, hex, options) {
options = Object.assign({}, options, {sector: sector, hex: hex});
return service(url('/api/coordinates', options),
options.accept || 'application/json');
},
credits: function(worldX, worldY, options) {
options = Object.assign({}, options, {x: worldX, y: worldY});
return service(url('/api/credits', options),
options.accept || 'application/json');
},
search: function(query, options, method) {
options = Object.assign({}, options, {q: query});
return service(url('/api/search', options),
options.accept || 'application/json', method);
},
sectorData: function(sector, options) {
options = Object.assign({}, options, {sector: sector});
return service(url('/api/sec', options),
options.accept || 'text/plain');
},
sectorDataTabDelimited: function(sector, options) {
options = Object.assign({}, options, {sector: sector, type: 'TabDelimited'});
return service(url('/api/sec', options),
options.accept || 'text/plain');
},
sectorMetaData: function(sector, options) {
options = Object.assign({}, options, {sector: sector});
return service(url('/api/metadata', options),
options.accept || 'application/json');
},
MSEC: function(sector, options) {
options = Object.assign({}, options, {sector: sector});
return service(url('/api/msec', options),
options.accept || 'text/plain');
},
universe: function(options) {
options = Object.assign({}, options);
return service(url('/api/universe', options),
options.accept || 'application/json');
}
};
}());
// ======================================================================
// Least-Recently-Used Cache
// ======================================================================
function LRUCache(capacity) {
this.capacity = capacity;
this.map = {};
this.queue = [];
}
LRUCache.prototype = {
ensureCapacity: function(capacity) {
if (this.capacity < capacity)
this.capacity = capacity;
},
clear: function() {
this.map = {};
this.queue = [];
},
fetch: function(key) {
key = '$' + key;
var value = this.map[key];
if (value === undefined)
return undefined;
var index = this.queue.indexOf(key);
if (index !== -1)
this.queue.splice(index, 1);
this.queue.push(key);
return value;
},
insert: function(key, value) {
key = '$' + key;
// Remove previous instances
var index = this.queue.indexOf(key);
if (index !== -1)
this.queue.splice(index, 1);
this.map[key] = value;
this.queue.push(key);
while (this.queue.length > this.capacity) {
key = this.queue.shift();
delete this.map[key];
}
}
};
// ======================================================================
// Image Stash
// ======================================================================
function ImageStash() {
this.map = new Map();
}
ImageStash.prototype = {
get: function(url, callback) {
if (this.map.has(url))
return this.map.get(url);
this.map.set(url, undefined);
Util.fetchImage(url).then(function(img) {
this.map.set(url, img);
callback(img);
}.bind(this));
return undefined;
}
};
var stash = new ImageStash();
// ======================================================================
// Animation Utilities
// ======================================================================
var Animation = (function() {
function isCallable(o) {
return typeof o === 'function';
}
//
// dur = total duration (seconds)
// smooth = optional smoothing function
// set onanimate to function called with animation position (0.0 ... 1.0)
//
function Animation(dur, smooth) {
var start = Date.now();
this.onanimate = null;
this.oncancel = null;
this.oncomplete = null;
var tickFunc = function() {
var f = (Date.now() - start) / 1000 / dur;
if (f < 1.0)
this.timerid = requestAnimationFrame(tickFunc);
var p = f;
if (isCallable(smooth))
p = smooth(p);
if (isCallable(this.onanimate))
this.onanimate(p);
if (f >= 1.0 && isCallable(this.oncomplete))
this.oncomplete();
}.bind(this);
this.timerid = requestAnimationFrame(tickFunc);
}
Animation.prototype = {
cancel: function() {
if (this.timerid) {
cancelAnimationFrame(this.timerid);
if (isCallable(this.oncancel))
this.oncancel();
}
}
};
Animation.interpolate = function(a, b, p) {
return a * (1.0 - p) + b * p;
};
// Time smoothing function - input time is t within duration dur.
// Acceleration period is a, deceleration period is d.
//
// Example: t_filtered = smooth( t, 1.0, 0.25, 0.25 );
//
// Reference: http://www.w3.org/TR/2005/REC-SMIL2-20050107/smil-timemanip.html
Animation.smooth = function(t, dur, a, d) {
var dacc = dur * a;
var ddec = dur * d;
var r = 1 / (1 - a / 2 - d / 2);
var r_t, tdec, pd;
if (t < dacc) {
r_t = r * (t / dacc);
return t * r_t / 2;
} else if (t <= (dur - ddec)) {
return r * (t - dacc / 2);
} else {
tdec = t - (dur - ddec);
pd = tdec / ddec;
return r * (dur - dacc / 2 - ddec + tdec * (2 - pd) / 2);
}
};
return Animation;
}());
// ======================================================================
// Observable name/value map
// ======================================================================
function NamedOptions(notify) {
this._options = {};
this._notify = notify;
}
NamedOptions.prototype = {
keys: function() { return Object.keys(this._options); },
get: function(key) { return this._options[key]; },
set: function(key, value) { this._options[key] = value; this._notify(key); },
delete: function(key) { delete this._options[key]; this._notify(key); },
forEach: function(fn, thisArg) {
var keys = Object.keys(this._options);
for (var i = 0; i < keys.length; ++i) {
var k = keys[i];
fn.call(thisArg, this._options[k], k, i);
}
}
};
//----------------------------------------------------------------------
//
// Usage:
//
// var map = new Map( document.getElementById('YourMapDiv') );
//
// map.OnPositionChanged = function() { update permalink }
// map.OnScaleChanged = function() { update scale indicator }
// map.OnStyleChanged = function() { update control panel }
// map.OnOptionsChanged = function() { update control panel }
//
// map.OnHover = function( {x, y} ) { show data }
// map.OnClick = function( {x, y} ) { show data }
// map.OnDoubleClick = function( {x, y} ) { show data }
//
// Read-Only:
// map.worldX
// map.worldY
//
// Read/Write:
// map.x
// map.y
// map.position ~= [map.x, map.y]
// map.scale
// map.style
// map.options
//
// map.namedOptions
// .keys()
// .get(k)
// .set(k, v)
// .delete(k)
// .forEach(function(value, key, index) { ... });
//
// map.CenterAtSectorHex( sx, sy, hx, hy, {scale, immediate} );
// map.Scroll( dx, dy, fAnimate );
// map.ZoomIn();
// map.ZoomOut();
//
// map.ApplyURLParameters()
//
// map.SetRoute()
// map.AddMarker(id, x, y, opt_url); // should have CSS style for .marker#<id>
// map.AddOverlay({type:'rectangle', x, y, w, h}); // should have CSS style for .overlay
// map.AddOverlay({type:'circle', x, y, r}); // should have CSS style for .overlay
//
//----------------------------------------------------------------------
function fireEvent(target, event, data) {
if (typeof target['On' + event] !== 'function') return;
setTimeout(function() { target['On' + event](data); }, 0);
}
// ======================================================================
// Slippy Map using Tiles
// ======================================================================
function log2(v) { return Math.log(v) / Math.LN2; }
function pow2(v) { return Math.pow(2, v); }
function dist(x, y) { return Math.sqrt(x*x + y*y); }
var SINK_OFFSET = 1000;
function TravellerMap(container, boundingElement) {
this.container = container;
this.rect = boundingElement.getBoundingClientRect();
this.min_scale = -5;
this.max_scale = 10;
// Exposed via getters/setters
this._options = Defaults.options;
this._style = Defaults.style;
this._logScale = 1;
this._tx = 0;
this._ty = 0;
this.tilesize = 256;
this.cache = new LRUCache(64);
this.namedOptions = new NamedOptions(function(key) {
this.invalidate();
fireEvent(this, 'OptionsChanged', this.options);
}.bind(this));
this.loading = {};
this.defer_loading = false;
var CLICK_SCALE_DELTA = -0.5;
var SCROLL_SCALE_DELTA = -0.15;
var KEY_SCROLL_DELTA = 25;
container.style.position = 'relative';
// Event target, so it doesn't change during refreshes
var sink = document.createElement('div');
sink.style.position = 'absolute';
sink.style.left = sink.style.top = sink.style.right = sink.style.bottom = (-SINK_OFFSET) + 'px';
sink.style.zIndex = 1000;
container.appendChild(sink);
this.canvas = document.createElement('canvas');
this.canvas.style.position = 'absolute';
this.canvas.style.zIndex = 0;
container.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
this.markers = [];
this.overlays = [];
this.route = null;
this.main = null;
// ======================================================================
// Event Handlers
// ======================================================================
var dragging, drag_coords, was_dragged;
container.addEventListener('mousedown', function(e) {
this.cancelAnimation();
container.focus();
dragging = true;
was_dragged = false;
drag_coords = this.eventCoords(e);
container.classList.add('dragging');
e.preventDefault();
e.stopPropagation();
}.bind(this), true);
var hover_coords;
container.addEventListener('mousemove', function(e) {
if (dragging) {
was_dragged = true;
var coords = this.eventCoords(e);
this._offset(drag_coords.x - coords.x, drag_coords.y - coords.y);
drag_coords = coords;
e.preventDefault();
e.stopPropagation();
}
var wc = this.eventToWorldCoords(e);
// Throttle the events
if (hover_coords && hover_coords.x === wc.x && hover_coords.y === wc.y)
return;
hover_coords = wc;
fireEvent(this, 'Hover', hover_coords);
}.bind(this), true);
document.addEventListener('mouseup', function(e) {
if (dragging) {
dragging = false;
container.classList.remove('dragging');
e.preventDefault();
e.stopPropagation();
}
});
container.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
if (!was_dragged)
fireEvent(this, 'Click', this.eventToWorldCoords(e));
}.bind(this));
container.addEventListener('dblclick', function(e) {
e.preventDefault();
e.stopPropagation();
this.cancelAnimation();
var MAX_DOUBLECLICK_SCALE = 9;
if (this._logScale < MAX_DOUBLECLICK_SCALE) {
var newscale = this._logScale + CLICK_SCALE_DELTA * (e.altKey ? 1 : -1);
newscale = Math.min(newscale, MAX_DOUBLECLICK_SCALE);
var coords = this.eventCoords(e);
this._setScale(newscale, coords.x, coords.y);
}
fireEvent(this, 'DoubleClick', this.eventToWorldCoords(e));
}.bind(this));
container.addEventListener('wheel', function(e) {
this.cancelAnimation();
var newscale = this._logScale + SCROLL_SCALE_DELTA * Math.sign(e.deltaY);
var coords = this.eventCoords(e);
this._setScale(newscale, coords.x, coords.y);
e.preventDefault();
e.stopPropagation();
}.bind(this));
window.addEventListener('resize', function() {
var rect = boundingElement.getBoundingClientRect();
if (rect.left === this.rect.left &&
rect.top === this.rect.top &&
rect.width === this.rect.width &&
rect.height === this.rect.height) return;
this.rect = rect;
this.resetCanvas();
}.bind(this));
var pinch1, pinch2;
var touch_coords, touch_wx, touch_wc, was_touch_dragged;
container.addEventListener('touchmove', function(e) {
was_touch_dragged = true;
if (e.touches.length === 1) {
var coords = this.eventCoords(e.touches[0]);
this._offset(touch_coords.x - coords.x, touch_coords.y - coords.y);
touch_coords = coords;
touch_wc = this.eventToWorldCoords(e.touches[0]);
} else if (e.touches.length === 2) {
var od = dist(pinch2.x - pinch1.x, pinch2.y - pinch1.y),
ocx = (pinch1.x + pinch2.x) / 2,
ocy = (pinch1.y + pinch2.y) / 2;
pinch1 = this.eventCoords(e.touches[0]),
pinch2 = this.eventCoords(e.touches[1]);
var nd = dist(pinch2.x - pinch1.x, pinch2.y - pinch1.y),
ncx = (pinch1.x + pinch2.x) / 2,
ncy = (pinch1.y + pinch2.y) / 2;
this._offset(ocx - ncx, ocy - ncy);
var newscale = this._logScale + log2(nd / od);
this._setScale(newscale, ncx, ncy);
}
e.preventDefault();
e.stopPropagation();
}.bind(this), true);
container.addEventListener('touchend', function(e) {
if (e.touches.length < 2) {
this.defer_loading = false;
this.invalidate();
}
if (e.touches.length === 1)
touch_coords = this.eventCoords(e.touches[0]);
if (e.touches.length === 0 && !was_touch_dragged)
fireEvent(this, 'Click', touch_wc);
e.preventDefault();
e.stopPropagation();
}.bind(this), true);
container.addEventListener('touchstart', function(e) {
was_touch_dragged = false;
if (e.touches.length === 1) {
touch_coords = this.eventCoords(e.touches[0]);
touch_wc = this.eventToWorldCoords(e.touches[0]);
} else if (e.touches.length === 2) {
this.defer_loading = true;
pinch1 = this.eventCoords(e.touches[0]),
pinch2 = this.eventCoords(e.touches[1]);
}
e.preventDefault();
e.stopPropagation();
}.bind(this), true);
container.addEventListener('keydown', function(e) {
if (e.ctrlKey || e.altKey || e.metaKey)
return;
// TODO: Use KeyboardEvent.prototype.key if available
var VK_I = KeyboardEvent.DOM_VK_I || 0x49,
VK_J = KeyboardEvent.DOM_VK_J || 0x4A,
VK_K = KeyboardEvent.DOM_VK_K || 0x4B,
VK_L = KeyboardEvent.DOM_VK_L || 0x4C,
VK_LEFT = KeyboardEvent.DOM_VK_LEFT || 0x25,
VK_UP = KeyboardEvent.DOM_VK_UP || 0x26,
VK_RIGHT = KeyboardEvent.DOM_VK_RIGHT || 0x27,
VK_DOWN = KeyboardEvent.DOM_VK_DOWN || 0x28,
VK_SUBTRACT = KeyboardEvent.DOM_VK_HYPHEN_MINUS || 0xBD,
VK_EQUALS = KeyboardEvent.DOM_VK_EQUALS || 0xBB;
switch (e.keyCode) {
case VK_UP:
case VK_I: this.Scroll(0, -KEY_SCROLL_DELTA); break;
case VK_LEFT:
case VK_J: this.Scroll(-KEY_SCROLL_DELTA, 0); break;
case VK_DOWN:
case VK_K: this.Scroll(0, KEY_SCROLL_DELTA); break;
case VK_RIGHT:
case VK_L: this.Scroll(KEY_SCROLL_DELTA, 0); break;
case VK_SUBTRACT: this.ZoomOut(); break;
case VK_EQUALS: this.ZoomIn(); break;
default: return;
}
e.preventDefault();
e.stopPropagation();
}.bind(this));
this.resetCanvas();
if (window == window.top) // == for IE
container.focus();
}
// ======================================================================
// Internal Methods
// ======================================================================
TravellerMap.prototype._offset = function(dx, dy) {
this.position = [this.x + dx / this.scale, this.y - dy / this.scale];
};
TravellerMap.prototype._setScale = function(newscale, px, py) {
newscale = Math.max(Math.min(newscale, this.max_scale), this.min_scale);
if (newscale === this._logScale)
return;
var cw = this.rect.width,
ch = this.rect.height;
// Mathmagic to preserve hover coordinates
var hx, hy;
if (arguments.length >= 3) {
hx = (this.x + (px - cw / 2) / this.scale) / this.tilesize;
hy = (-this.y + (py - ch / 2) / this.scale) / this.tilesize;
}
this._logScale = newscale;
if (arguments.length >= 3) {
this.position = [hx * this.tilesize - (px - cw / 2) / this.scale,
-(hy * this.tilesize - (py - ch / 2) / this.scale)];
}
this.invalidate();
fireEvent(this, 'ScaleChanged', this.scale);
};
TravellerMap.prototype.resetCanvas = function() {
var cw = this.rect.width;
var ch = this.rect.height;
var dpr = 'devicePixelRatio' in window ? window.devicePixelRatio : 1;
// iOS devices have a limit of 3 or 5 megapixels for canvas backing
// store; given screen resolution * ~3x size for "tilt" display this
// can easily be reached, so reduce effective dpr.
if (dpr > 1 && /\biPad\b/.test(navigator.userAgent) &&
this.tilt_enabled &&
(cw * ch * dpr * dpr * 2 * 2) > 3e6) {
dpr = 1;
}
// Scale factor for canvas to accomodate tilt.
var sx = 1, sy = 1;
if (this.tilt_enabled) {
sx = 1.75;
sy = 1.85;
}
// Pixel size of the canvas backing store.
var pw = (cw * sx * dpr) | 0;
var ph = (ch * sy * dpr) | 0;
// Offset of the canvas against the container.
var ox = 0, oy = 0;
if (this.tilt_enabled) {
ox = (-((cw * sx) - cw) / 2) | 0;
oy = (-((ch * sy) - ch) * 0.8) | 0;
}
this.canvas.width = pw;
this.canvas.height = ph;
this.canvas.style.width = ((cw * sx) | 0) + 'px';
this.canvas.style.height = ((ch * sy) | 0) + 'px';
this.canvas.offset_x = ox;
this.canvas.offset_y = oy;
this.canvas.style.left = ox + 'px';
this.canvas.style.top = oy + 'px';
this.ctx.setTransform(1,0,0,1,0,0);
this.ctx.scale(dpr, dpr);
this.redraw(true);
};
TravellerMap.prototype.invalidate = function() {
this.dirty = true;
if (this._raf_handle) return;
this._raf_handle = requestAnimationFrame(function invalidationRAF(ms) {
this._raf_handle = null;
this.redraw();
}.bind(this));
};
TravellerMap.prototype.redraw = function(force) {
if (!this.dirty && !force)
return;
this.dirty = false;
// Integral scale (the tiles that will be used)
var tscale = Math.round(this._logScale);
// Tile URL (apart from x/y/scale)
var params = {options: this.options, style: this.style};
this.namedOptions.forEach(function(value, key) {
if (key === 'ew') return;
params[key] = value;
});
if ('devicePixelRatio' in window && window.devicePixelRatio > 1)
params.dpr = window.devicePixelRatio;
this._tile_url_base = Util.makeURL(SERVICE_BASE + '/api/tile', params);
// How the tiles themselves are scaled (naturally 1, unless pinched)
var tmult = pow2(this._logScale - tscale),
// From map space to tile space
// (Traveller map coords change at each integral zoom level)
cf = pow2(tscale - 1), // Coordinate factor (integral)
// Compute edges in tile space
cw = this.rect.width,
ch = this.rect.height,
l = this._tx * cf - (cw / 2) / (this.tilesize * tmult),
r = this._tx * cf + (cw / 2) / (this.tilesize * tmult),
t = this._ty * cf - (ch / 2) / (this.tilesize * tmult),
b = this._ty * cf + (ch / 2) / (this.tilesize * tmult);
// Quantize to bounding tiles
l = Math.floor(l) - 1;
t = Math.floor(t) - 1;
r = Math.floor(r) + 1;
b = Math.floor(b) + 1;