forked from rieseted/pygjs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gamejs.js
789 lines (710 loc) · 20.5 KB
/
gamejs.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
var matrix = require('./gamejs/math/matrix');
var objects = require('./gamejs/utils/objects');
var Callback = require('./gamejs/utils/callback').Callback;
/**
* @fileoverview `gamejs.ready()` is maybe the most important function as it kickstarts your app:
*
* var gamejs = require('gamejs');
* ready(function() {
* gamejs.logging.info('I am ready!')
* });
*
* If you use images or sounds preload all assets with `gamejs.preload(['./files/foo.png'])` before calling `ready()`.
*
* Also in this module is the `Rect` class which is generally useful when dealing with Surfaces and simple rectangles (e.g. for collisions).
*/
// preloading stuff
var gamejs = exports;
var RESOURCES = {};
/**
* @ignore
*/
exports.thread = require('./gamejs/thread');
/**
* ReadyFn is called once all modules and assets are loaded.
* @param {Function} callbackFunction the function to be called once gamejs finished loading
* @name ready
*/
if (gamejs.thread.inWorker === true) {
exports.ready = function(readyFn) {
require('./gamejs/thread')._ready();
gamejs.init();
readyFn();
};
} else {
exports.ready = function(readyFn) {
var getMixerProgress = null;
var getImageProgress = null;
var getFontProgresss = null;
// init time instantly - we need it for preloaders
gamejs.time.init();
// 2.
function _ready() {
if (!document.body) {
return window.setTimeout(_ready, 50);
}
getImageProgress = gamejs.image.preload(RESOURCES);
try {
getMixerProgress = gamejs.audio.preload(RESOURCES);
} catch (e) {
gamejs.debug('Error loading audio files ', e);
}
try {
getFontProgress = gamejs.font.preload(RESOURCES);
} catch (e) {
console.log("error", e);
gamejs.debug('Error loading font files ', e);
}
window.setTimeout(_readyResources, 50);
}
// 3.
function _readyResources() {
if (getImageProgress() < 1 || getMixerProgress() < 1 || getFontProgress() < 1) {
return window.setTimeout(_readyResources, 100);
}
gamejs.display.init();
gamejs.image.init();
gamejs.font.init();
gamejs.audio.init();
gamejs.event.init();
// must be called after event
gamejs.gamepad.joystick.init();
gamejs.gamepad.joystick.deadzone = 0.08;
gamejs.math.random.init();
readyFn();
}
// 1.
window.setTimeout(_ready, 13);
function getLoadProgress() {
if (getImageProgress) {
return (0.5 * getImageProgress()) + (0.5 * getMixerProgress());
}
return 0.1;
}
return getLoadProgress;
};
}
/**
* Initialize all gamejs modules. This is automatically called
* by `gamejs.ready()`.
* @returns {Object} the properties of this objecte are the moduleIds that failed, they value are the exceptions
* @ignore
*/
exports.init = function() {
var errorModules = {};
['time', 'display', 'image', 'audio', 'event'].forEach(function(moduleName) {
try {
gamejs[moduleName].init();
} catch (e) {
errorModules[moduleName] = e.toString();
}
});
gamejs.gamepad.joystick.init();
return errorModules;
};
var resourceBaseHref = function() {
return (window.$g && window.$g.resourceBaseHref) || document.location.href;
};
var resolveURIs = exports.resolveURIs = function(resources) {
var uri = require('./gamejs/utils/uri');
var baseHref = resourceBaseHref();
var ret = {}
resources.forEach(function(res) {
ret[res] = uri.resolve(baseHref, res);
}, this);
return ret;
}
/**
* Preload resources.
* @param {Array} resources list of resources paths
* @name preload
*/
var preload = exports.preload = function(resources) {
RESOURCES = resolveURIs(resources);
};
exports.clearResources = function() {
RESOURCES = {};
}
/**
* The function passed to `onTick` will continously be called at a
* frequency determined by the browser (typically between 1 and 60 times per second).
* @param {Function} callbackFunction the function you want to be called
* @param {Function} callbackScope optional scope for the function call
*/
exports.onTick = function(fn, scope) {
/** ignore **/
exports.time._CALLBACKS.push(new Callback(fn, scope));
};
/**
* Normalize various ways to specify a Rect into {left, top, width, height} form.
* @ignore
*
*/
var normalizeRectArguments = exports.normalizeRectArguments = function () {
var left = 0;
var top = 0;
var width = 0;
var height = 0;
if (arguments.length === 2) {
if (arguments[0] instanceof Array && arguments[1] instanceof Array) {
left = arguments[0][0];
top = arguments[0][1];
width = arguments[1][0];
height = arguments[1][1];
} else {
left = arguments[0];
top = arguments[1];
}
} else if (arguments.length === 1 && arguments[0] instanceof Array) {
left = arguments[0][0];
top = arguments[0][1];
width = arguments[0][2];
height = arguments[0][3];
} else if (arguments.length === 1 && arguments[0] instanceof Rect) {
left = arguments[0].left;
top = arguments[0].top;
width = arguments[0].width;
height = arguments[0].height;
} else if (arguments.length === 4) {
left = arguments[0];
top = arguments[1];
width = arguments[2];
height = arguments[3];
} else {
throw new Error('not a valid rectangle specification');
}
return {left: left || 0, top: top || 0, width: width || 0, height: height || 0};
};
/**
* Creates a Rect. Rects are used to hold rectangular areas. There are a couple
* of convinient ways to create Rects with different arguments and defaults.
*
* Any function that requires a `gamejs.Rect` argument also accepts any of the
* constructor value combinations `Rect` accepts.
*
* Rects are used a lot. They are good for collision detection, specifying
* an area on the screen (for blitting) or just to hold an objects position.
*
* The Rect object has several virtual attributes which can be used to move and align the Rect:
*
* top, left, bottom, right
* topleft, bottomleft, topright, bottomright
* center
* width, height
* w,h
*
* All of these attributes can be assigned to.
* Assigning to width or height changes the dimensions of the rectangle; all other
* assignments move the rectangle without resizing it. Notice that some attributes
* are Numbers and others are pairs of Numbers.
*
* @example
* new Rect([left, top]) // width & height default to 0
* new Rect(left, top) // width & height default to 0
* new Rect(left, top, width, height)
* new Rect([left, top], [width, height])
* new Rect(oldRect) // clone of oldRect is created
*
* @property {Number} right
* @property {Number} bottom
* @property {Number} center
* @constructor
* @param {Array|gamejs.Rect} position Array holding left and top coordinates
* @param {Array} dimensions Array holding width and height
*/
var Rect = exports.Rect = function() {
var args = normalizeRectArguments.apply(this, arguments);
/**
* Left, X coordinate
* @type Number
*/
this.left = args.left;
/**
* Top, Y coordinate
* @type Number
*/
this.top = args.top;
/**
* Width of rectangle
* @type Number
*/
this.width = args.width;
/**
* Height of rectangle
* @type Number
*/
this.height = args.height;
return this;
};
objects.accessors(Rect.prototype, {
/**
* Bottom, Y coordinate
* @name Rect.prototype.bottom
* @type Number
*/
'bottom': {
get: function() {
return this.top + this.height;
},
set: function(newValue) {
this.top = newValue - this.height;
return;
}
},
/**
* Right, X coordinate
* @name Rect.prototype.right
* @type Number
*/
'right': {
get: function() {
return this.left + this.width;
},
set: function(newValue) {
this.left = newValue - this.width;
}
},
/**
* Center Position. You can assign a rectangle form.
* @name Rect.prototype.center
* @type Array
*/
'center': {
get: function() {
return [this.left + (this.width / 2) | 0,
this.top + (this.height / 2) | 0
];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left = args.left - (this.width / 2) | 0;
this.top = args.top - (this.height / 2) | 0;
return;
}
},
/**
* Top-left Position. You can assign a rectangle form.
* @name Rect.prototype.topleft
* @type Array
*/
'topleft': {
get: function() {
return [this.left, this.top];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left = args.left;
this.top = args.top;
return;
}
},
/**
* Bottom-left Position. You can assign a rectangle form.
* @name Rect.prototype.bottomleft
* @type Array
*/
'bottomleft': {
get: function() {
return [this.left, this.bottom];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left = args.left;
this.bottom = args.top;
return;
}
},
/**
* Top-right Position. You can assign a rectangle form.
* @name Rect.prototype.topright
* @type Array
*/
'topright': {
get: function() {
return [this.right, this.top];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.right = args.left;
this.top = args.top;
return;
}
},
/**
* Bottom-right Position. You can assign a rectangle form.
* @name Rect.prototype.bottomright
* @type Array
*/
'bottomright': {
get: function() {
return [this.right, this.bottom];
},
set: function() {
var args = normalizeRectArguments.apply(this, arguments);
this.right = args.left;
this.bottom = args.top;
return;
}
},
/**
* Position x value, alias for `left`.
* @name Rect.prototype.y
* @type Array
*/
'x': {
get: function() {
return this.left;
},
set: function(newValue) {
this.left = newValue;
return;
}
},
/**
* Position y value, alias for `top`.
* @name Rect.prototype.y
* @type Array
*/
'y': {
get: function() {
return this.top;
},
set: function(newValue) {
this.top = newValue;
return;
}
}
});
/**
* Move returns a new Rect, which is a version of this Rect
* moved by the given amounts. Accepts any rectangle form.
* as argument.
*
* @param {Number|gamejs.Rect} x amount to move on x axis
* @param {Number} y amount to move on y axis
*/
Rect.prototype.move = function() {
var args = normalizeRectArguments.apply(this, arguments);
return new Rect(this.left + args.left, this.top + args.top, this.width, this.height);
};
/**
* Move this Rect in place - not returning a new Rect like `move(x, y)` would.
*
* `moveIp(x,y)` or `moveIp([x,y])`
*
* @param {Number|gamejs.Rect} x amount to move on x axis
* @param {Number} y amount to move on y axis
*/
Rect.prototype.moveIp = function() {
var args = normalizeRectArguments.apply(this, arguments);
this.left += args.left;
this.top += args.top;
return;
};
/**
* Return the area in which this Rect and argument Rect overlap.
*
* @param {gamejs.Rect} Rect to clip this one into
* @returns {gamejs.Rect} new Rect which is completely inside the argument Rect,
* zero sized Rect if the two rectangles do not overlap
*/
Rect.prototype.clip = function(rect) {
if(!this.collideRect(rect)) {
return new Rect(0,0,0,0);
}
var x, y, width, height;
// Left
if ((this.left >= rect.left) && (this.left < rect.right)) {
x = this.left;
} else if ((rect.left >= this.left) && (rect.left < this.right)) {
x = rect.left;
}
// Right
if ((this.right > rect.left) && (this.right <= rect.right)) {
width = this.right - x;
} else if ((rect.right > this.left) && (rect.right <= this.right)) {
width = rect.right - x;
}
// Top
if ((this.top >= rect.top) && (this.top < rect.bottom)) {
y = this.top;
} else if ((rect.top >= this.top) && (rect.top < this.bottom)) {
y = rect.top;
}
// Bottom
if ((this.bottom > rect.top) && (this.bottom <= rect.bottom)) {
height = this.bottom - y;
} else if ((rect.bottom > this.top) && (rect.bottom <= this.bottom)) {
height = rect.bottom - y;
}
return new Rect(x, y, width, height);
};
/**
* Join two rectangles
*
* @param {gamejs.Rect} union with this rectangle
* @returns {gamejs.Rect} rectangle containing area of both rectangles
*/
Rect.prototype.union = function(rect) {
var x, y, width, height;
x = Math.min(this.left, rect.left);
y = Math.min(this.top, rect.top);
width = Math.max(this.right, rect.right) - x;
height = Math.max(this.bottom, rect.bottom) - y;
return new Rect(x, y, width, height);
};
/**
* Grow or shrink the rectangle size
*
* @param {Number} amount to change in the width
* @param {Number} amount to change in the height
* @returns {gamejs.Rect} inflated rectangle centered on the original rectangle's center
*/
Rect.prototype.inflate = function(x, y) {
var copy = this.clone();
copy.inflateIp(x, y);
return copy;
};
/**
* Grow or shrink this Rect in place - not returning a new Rect like `inflate(x, y)` would.
*
* @param {Number} amount to change in the width
* @param {Number} amount to change in the height
*/
Rect.prototype.inflateIp = function(x, y) {
// Use Math.floor here to deal with rounding of negative numbers the
// way this relies on.
this.left -= Math.floor(x / 2);
this.top -= Math.floor(y / 2);
this.width += x;
this.height += y;
};
/**
* Check for collision with a point.
*
* `collidePoint(x,y)` or `collidePoint([x,y])` or `collidePoint(new Rect(x,y))`
*
* @param {Array|gamejs.Rect} point the x and y coordinates of the point to test for collision
* @returns {Boolean} true if the point collides with this Rect
*/
Rect.prototype.collidePoint = function() {
var args = normalizeRectArguments.apply(this, arguments);
return (this.left <= args.left && args.left <= this.right) &&
(this.top <= args.top && args.top <= this.bottom);
};
/**
* Check for collision with a Rect.
* @param {gamejs.Rect} rect the Rect to test check for collision
* @returns {Boolean} true if the given Rect collides with this Rect
*/
Rect.prototype.collideRect = function(rect) {
return !(this.left > rect.right || this.right < rect.left ||
this.top > rect.bottom || this.bottom < rect.top);
};
/**
* @param {Array} pointA start point of the line
* @param {Array} pointB end point of the line
* @returns true if the line intersects with the rectangle
* @see http://stackoverflow.com/questions/99353/how-to-test-if-a-line-segment-intersects-an-axis-aligned-rectange-in-2d/293052#293052
*
*/
Rect.prototype.collideLine = function(p1, p2) {
var x1 = p1[0];
var y1 = p1[1];
var x2 = p2[0];
var y2 = p2[1];
function linePosition(point) {
var x = point[0];
var y = point[1];
return (y2 - y1) * x + (x1 - x2) * y + (x2 * y1 - x1 * y2);
}
var relPoses = [[this.left, this.top],
[this.left, this.bottom],
[this.right, this.top],
[this.right, this.bottom]
].map(linePosition);
var noNegative = true;
var noPositive = true;
var noZero = true;
relPoses.forEach(function(relPos) {
if (relPos > 0) {
noPositive = false;
} else if (relPos < 0) {
noNegative = false;
} else if (relPos === 0) {
noZero = false;
}
}, this);
if ( (noNegative || noPositive) && noZero) {
return false;
}
return !((x1 > this.right && x2 > this.right) ||
(x1 < this.left && x2 < this.left) ||
(y1 < this.top && y2 < this.top) ||
(y1 > this.bottom && y2 > this.bottom)
);
};
/**
* @returns {String} Like "[x, y][w, h]"
*/
Rect.prototype.toString = function() {
return ["[", this.left, ",", this.top, "]"," [",this.width, ",", this.height, "]"].join("");
};
/**
* @returns {gamejs.Rect} A new copy of this rect
*/
Rect.prototype.clone = function() {
return new Rect(this);
};
// adapted from pygame/src/rect.c [rect_clamp()]
Rect.prototype.clamp = function(rect) {
var x = 0, y = 0;
if (this.width >= rect.width) {
x = this.x + rect.width / 2 - this.width / 2;
} else if (this.x < rect.x) {
x = rect.x;
} else if ((this.x + this.width) > (rect.x + rect.width)) {
x = rect.x + rect.width - this.width;
} else {
x = this.x;
}
if (this.height >= rect.height) {
y = rect.y + rect.height / 2 - this.height / 2;
} else if (this.y < rect.y) {
y = rect.y;
} else if ((this.y + this.height) > (rect.y + rect.height)) {
y = rect.y + rect.height + self.height;
} else {
y = this.y;
}
return new Rect(x, y, this.width, this.height);
};
// adapted from pygame/src/rect.c [rect_clamp_ip()]
Rect.prototype.clampIp = function(rect) {
var x = 0, y = 0;
if (this.width >= rect.width) {
x = this.x + rect.width / 2 - this.width / 2;
} else if (this.x < rect.x) {
x = rect.x;
} else if ((this.x + this.width) > (rect.x + rect.width)) {
x = rect.x + rect.width - this.width;
} else {
x = this.x;
}
if (this.height >= rect.height) {
y = rect.y + rect.height / 2 - this.height / 2;
} else if (this.y < rect.y) {
y = rect.y;
} else if ((this.y + this.height) > (rect.y + rect.height)) {
y = rect.y + rect.height + self.height;
} else {
y = this.y;
}
this.x = x;
this.y = y;
};
// adapted from pygame/src/rect.c [rect_fit()]
Rect.prototype.fit = function (rect) {
var w = 0, h = 0, x = 0, y = 0, xratio = 0, yratio = 0, maxratio = 0;
xratio = this.width / rect.width;
yratio = this.height / rect.height;
maxratio = (xratio > yratio) ? xratio : yratio;
w = this.width / maxratio;
h = this.height / maxratio;
x = rect.x + (rect.width - w) / 2;
y = rect.y + (rect.height - h) / 2;
return new Rect(x, y, w, h);
};
// adapted from pygame/src/rect.c [rect_normalize()]
Rect.prototype.normalize = function () {
if (this.width < 0) {
this.x += this.width;
this.width = -this.width;
}
if (this.height < 0) {
this.y += this.height;
this.height = -this.height;
}
};
// adapted from pygame/src/rect.c [rect_contains()]
Rect.prototype.contains = function (rect) {
return ((this.x <= rect.x) && (this.y <= rect.y) &&
((this.x + this.width) >= (rect.x + rect.width)) &&
((this.y + this.height) >= (rect.y + rect.height)) &&
((this.x + this.width) > rect.x) &&
((this.y + this.height) > rect.y));
};
/**
* @ignore
*/
exports.event = require('./gamejs/event');
/**
* @ignore
*/
exports.font = require('./gamejs/font');
/**
* @ignore
*/
exports.http = require('./gamejs/http');
/**
* @ignore
*/
exports.image = require('./gamejs/image');
/**
* @ignore
*/
exports.audio = require('./gamejs/audio');
/**
* @ignore
*/
exports.graphics = require('./gamejs/graphics');
/**
* @ignore
*/
exports.logging = require('./gamejs/logging');
/**
* @ignore
*/
exports.math = {
matrix: require('./gamejs/math/matrix'),
vectors: require('./gamejs/math/vectors'),
angles: require('./gamejs/math/angles'),
binaryheap: require('./gamejs/math/binaryheap'),
random: require('./gamejs/math/random'),
noise: require('./gamejs/math/noise'),
};
/**
* @ignore
*/
exports.utils = {
arrays: require('./gamejs/utils/arrays'),
objects: require('./gamejs/utils/objects'),
uri: require('./gamejs/utils/uri'),
strings: require('./gamejs/utils/strings'),
xml: require('./gamejs/utils/xml'),
base64: require('./gamejs/utils/base64')
};
/**
* @ignore
*/
exports.display = require('./gamejs/display');
/**
* @ignore
*/
exports.pathfinding = require('./gamejs/pathfinding');
/**
* @ignore
*/
exports.tiledmap = require('./gamejs/tiledmap');
/**
* @ignore
*/
exports.time = require('./gamejs/time');
/**
* @ignore
*/
exports.pixelcollision = require('./gamejs/pixelcollision');
/**
* @ignore
*/
exports.gamepad = require('./gamejs/gamepad');