-
Notifications
You must be signed in to change notification settings - Fork 25
/
matter.js
11001 lines (9339 loc) · 349 KB
/
matter.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
/*!
* matter-js 0.19.0 by @liabru
* http://brm.io/matter-js/
* License MIT
*
* The MIT License (MIT)
*
* Copyright (c) Liam Brummitt and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("Matter", [], factory);
else if(typeof exports === 'object')
exports["Matter"] = factory();
else
root["Matter"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 20);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
/**
* The `Matter.Common` module contains utility functions that are common to all modules.
*
* @class Common
*/
var Common = {};
module.exports = Common;
(function() {
Common._baseDelta = 1000 / 60;
Common._nextId = 0;
Common._seed = 0;
Common._nowStartTime = +(new Date());
Common._warnedOnce = {};
Common._decomp = null;
/**
* Extends the object in the first argument using the object in the second argument.
* @method extend
* @param {} obj
* @param {boolean} deep
* @return {} obj extended
*/
Common.extend = function(obj, deep) {
var argsStart,
args,
deepClone;
if (typeof deep === 'boolean') {
argsStart = 2;
deepClone = deep;
} else {
argsStart = 1;
deepClone = true;
}
for (var i = argsStart; i < arguments.length; i++) {
var source = arguments[i];
if (source) {
for (var prop in source) {
if (deepClone && source[prop] && source[prop].constructor === Object) {
if (!obj[prop] || obj[prop].constructor === Object) {
obj[prop] = obj[prop] || {};
Common.extend(obj[prop], deepClone, source[prop]);
} else {
obj[prop] = source[prop];
}
} else {
obj[prop] = source[prop];
}
}
}
}
return obj;
};
/**
* Creates a new clone of the object, if deep is true references will also be cloned.
* @method clone
* @param {} obj
* @param {bool} deep
* @return {} obj cloned
*/
Common.clone = function(obj, deep) {
return Common.extend({}, deep, obj);
};
/**
* Returns the list of keys for the given object.
* @method keys
* @param {} obj
* @return {string[]} keys
*/
Common.keys = function(obj) {
if (Object.keys)
return Object.keys(obj);
// avoid hasOwnProperty for performance
var keys = [];
for (var key in obj)
keys.push(key);
return keys;
};
/**
* Returns the list of values for the given object.
* @method values
* @param {} obj
* @return {array} Array of the objects property values
*/
Common.values = function(obj) {
var values = [];
if (Object.keys) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
values.push(obj[keys[i]]);
}
return values;
}
// avoid hasOwnProperty for performance
for (var key in obj)
values.push(obj[key]);
return values;
};
/**
* Gets a value from `base` relative to the `path` string.
* @method get
* @param {} obj The base object
* @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'
* @param {number} [begin] Path slice begin
* @param {number} [end] Path slice end
* @return {} The object at the given path
*/
Common.get = function(obj, path, begin, end) {
path = path.split('.').slice(begin, end);
for (var i = 0; i < path.length; i += 1) {
obj = obj[path[i]];
}
return obj;
};
/**
* Sets a value on `base` relative to the given `path` string.
* @method set
* @param {} obj The base object
* @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'
* @param {} val The value to set
* @param {number} [begin] Path slice begin
* @param {number} [end] Path slice end
* @return {} Pass through `val` for chaining
*/
Common.set = function(obj, path, val, begin, end) {
var parts = path.split('.').slice(begin, end);
Common.get(obj, path, 0, -1)[parts[parts.length - 1]] = val;
return val;
};
/**
* Shuffles the given array in-place.
* The function uses a seeded random generator.
* @method shuffle
* @param {array} array
* @return {array} array shuffled randomly
*/
Common.shuffle = function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Common.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
/**
* Randomly chooses a value from a list with equal probability.
* The function uses a seeded random generator.
* @method choose
* @param {array} choices
* @return {object} A random choice object from the array
*/
Common.choose = function(choices) {
return choices[Math.floor(Common.random() * choices.length)];
};
/**
* Returns true if the object is a HTMLElement, otherwise false.
* @method isElement
* @param {object} obj
* @return {boolean} True if the object is a HTMLElement, otherwise false
*/
Common.isElement = function(obj) {
if (typeof HTMLElement !== 'undefined') {
return obj instanceof HTMLElement;
}
return !!(obj && obj.nodeType && obj.nodeName);
};
/**
* Returns true if the object is an array.
* @method isArray
* @param {object} obj
* @return {boolean} True if the object is an array, otherwise false
*/
Common.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
/**
* Returns true if the object is a function.
* @method isFunction
* @param {object} obj
* @return {boolean} True if the object is a function, otherwise false
*/
Common.isFunction = function(obj) {
return typeof obj === "function";
};
/**
* Returns true if the object is a plain object.
* @method isPlainObject
* @param {object} obj
* @return {boolean} True if the object is a plain object, otherwise false
*/
Common.isPlainObject = function(obj) {
return typeof obj === 'object' && obj.constructor === Object;
};
/**
* Returns true if the object is a string.
* @method isString
* @param {object} obj
* @return {boolean} True if the object is a string, otherwise false
*/
Common.isString = function(obj) {
return toString.call(obj) === '[object String]';
};
/**
* Returns the given value clamped between a minimum and maximum value.
* @method clamp
* @param {number} value
* @param {number} min
* @param {number} max
* @return {number} The value clamped between min and max inclusive
*/
Common.clamp = function(value, min, max) {
if (value < min)
return min;
if (value > max)
return max;
return value;
};
/**
* Returns the sign of the given value.
* @method sign
* @param {number} value
* @return {number} -1 if negative, +1 if 0 or positive
*/
Common.sign = function(value) {
return value < 0 ? -1 : 1;
};
/**
* Returns the current timestamp since the time origin (e.g. from page load).
* The result is in milliseconds and will use high-resolution timing if available.
* @method now
* @return {number} the current timestamp in milliseconds
*/
Common.now = function() {
if (typeof window !== 'undefined' && window.performance) {
if (window.performance.now) {
return window.performance.now();
} else if (window.performance.webkitNow) {
return window.performance.webkitNow();
}
}
if (Date.now) {
return Date.now();
}
return (new Date()) - Common._nowStartTime;
};
/**
* Returns a random value between a minimum and a maximum value inclusive.
* The function uses a seeded random generator.
* @method random
* @param {number} min
* @param {number} max
* @return {number} A random number between min and max inclusive
*/
Common.random = function(min, max) {
min = (typeof min !== "undefined") ? min : 0;
max = (typeof max !== "undefined") ? max : 1;
return min + _seededRandom() * (max - min);
};
var _seededRandom = function() {
// https://en.wikipedia.org/wiki/Linear_congruential_generator
Common._seed = (Common._seed * 9301 + 49297) % 233280;
return Common._seed / 233280;
};
/**
* Converts a CSS hex colour string into an integer.
* @method colorToNumber
* @param {string} colorString
* @return {number} An integer representing the CSS hex string
*/
Common.colorToNumber = function(colorString) {
colorString = colorString.replace('#','');
if (colorString.length == 3) {
colorString = colorString.charAt(0) + colorString.charAt(0)
+ colorString.charAt(1) + colorString.charAt(1)
+ colorString.charAt(2) + colorString.charAt(2);
}
return parseInt(colorString, 16);
};
/**
* The console logging level to use, where each level includes all levels above and excludes the levels below.
* The default level is 'debug' which shows all console messages.
*
* Possible level values are:
* - 0 = None
* - 1 = Debug
* - 2 = Info
* - 3 = Warn
* - 4 = Error
* @static
* @property logLevel
* @type {Number}
* @default 1
*/
Common.logLevel = 1;
/**
* Shows a `console.log` message only if the current `Common.logLevel` allows it.
* The message will be prefixed with 'matter-js' to make it easily identifiable.
* @method log
* @param ...objs {} The objects to log.
*/
Common.log = function() {
if (console && Common.logLevel > 0 && Common.logLevel <= 3) {
console.log.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));
}
};
/**
* Shows a `console.info` message only if the current `Common.logLevel` allows it.
* The message will be prefixed with 'matter-js' to make it easily identifiable.
* @method info
* @param ...objs {} The objects to log.
*/
Common.info = function() {
if (console && Common.logLevel > 0 && Common.logLevel <= 2) {
console.info.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));
}
};
/**
* Shows a `console.warn` message only if the current `Common.logLevel` allows it.
* The message will be prefixed with 'matter-js' to make it easily identifiable.
* @method warn
* @param ...objs {} The objects to log.
*/
Common.warn = function() {
if (console && Common.logLevel > 0 && Common.logLevel <= 3) {
console.warn.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));
}
};
/**
* Uses `Common.warn` to log the given message one time only.
* @method warnOnce
* @param ...objs {} The objects to log.
*/
Common.warnOnce = function() {
var message = Array.prototype.slice.call(arguments).join(' ');
if (!Common._warnedOnce[message]) {
Common.warn(message);
Common._warnedOnce[message] = true;
}
};
/**
* Shows a deprecated console warning when the function on the given object is called.
* The target function will be replaced with a new function that first shows the warning
* and then calls the original function.
* @method deprecated
* @param {object} obj The object or module
* @param {string} name The property name of the function on obj
* @param {string} warning The one-time message to show if the function is called
*/
Common.deprecated = function(obj, prop, warning) {
obj[prop] = Common.chain(function() {
Common.warnOnce('🔅 deprecated 🔅', warning);
}, obj[prop]);
};
/**
* Returns the next unique sequential ID.
* @method nextId
* @return {Number} Unique sequential ID
*/
Common.nextId = function() {
return Common._nextId++;
};
/**
* A cross browser compatible indexOf implementation.
* @method indexOf
* @param {array} haystack
* @param {object} needle
* @return {number} The position of needle in haystack, otherwise -1.
*/
Common.indexOf = function(haystack, needle) {
if (haystack.indexOf)
return haystack.indexOf(needle);
for (var i = 0; i < haystack.length; i++) {
if (haystack[i] === needle)
return i;
}
return -1;
};
/**
* A cross browser compatible array map implementation.
* @method map
* @param {array} list
* @param {function} func
* @return {array} Values from list transformed by func.
*/
Common.map = function(list, func) {
if (list.map) {
return list.map(func);
}
var mapped = [];
for (var i = 0; i < list.length; i += 1) {
mapped.push(func(list[i]));
}
return mapped;
};
/**
* Takes a directed graph and returns the partially ordered set of vertices in topological order.
* Circular dependencies are allowed.
* @method topologicalSort
* @param {object} graph
* @return {array} Partially ordered set of vertices in topological order.
*/
Common.topologicalSort = function(graph) {
// https://github.com/mgechev/javascript-algorithms
// Copyright (c) Minko Gechev (MIT license)
// Modifications: tidy formatting and naming
var result = [],
visited = [],
temp = [];
for (var node in graph) {
if (!visited[node] && !temp[node]) {
Common._topologicalSort(node, visited, temp, graph, result);
}
}
return result;
};
Common._topologicalSort = function(node, visited, temp, graph, result) {
var neighbors = graph[node] || [];
temp[node] = true;
for (var i = 0; i < neighbors.length; i += 1) {
var neighbor = neighbors[i];
if (temp[neighbor]) {
// skip circular dependencies
continue;
}
if (!visited[neighbor]) {
Common._topologicalSort(neighbor, visited, temp, graph, result);
}
}
temp[node] = false;
visited[node] = true;
result.push(node);
};
/**
* Takes _n_ functions as arguments and returns a new function that calls them in order.
* The arguments applied when calling the new function will also be applied to every function passed.
* The value of `this` refers to the last value returned in the chain that was not `undefined`.
* Therefore if a passed function does not return a value, the previously returned value is maintained.
* After all passed functions have been called the new function returns the last returned value (if any).
* If any of the passed functions are a chain, then the chain will be flattened.
* @method chain
* @param ...funcs {function} The functions to chain.
* @return {function} A new function that calls the passed functions in order.
*/
Common.chain = function() {
var funcs = [];
for (var i = 0; i < arguments.length; i += 1) {
var func = arguments[i];
if (func._chained) {
// flatten already chained functions
funcs.push.apply(funcs, func._chained);
} else {
funcs.push(func);
}
}
var chain = function() {
// https://github.com/GoogleChrome/devtools-docs/issues/53#issuecomment-51941358
var lastResult,
args = new Array(arguments.length);
for (var i = 0, l = arguments.length; i < l; i++) {
args[i] = arguments[i];
}
for (i = 0; i < funcs.length; i += 1) {
var result = funcs[i].apply(lastResult, args);
if (typeof result !== 'undefined') {
lastResult = result;
}
}
return lastResult;
};
chain._chained = funcs;
return chain;
};
/**
* Chains a function to excute before the original function on the given `path` relative to `base`.
* See also docs for `Common.chain`.
* @method chainPathBefore
* @param {} base The base object
* @param {string} path The path relative to `base`
* @param {function} func The function to chain before the original
* @return {function} The chained function that replaced the original
*/
Common.chainPathBefore = function(base, path, func) {
return Common.set(base, path, Common.chain(
func,
Common.get(base, path)
));
};
/**
* Chains a function to excute after the original function on the given `path` relative to `base`.
* See also docs for `Common.chain`.
* @method chainPathAfter
* @param {} base The base object
* @param {string} path The path relative to `base`
* @param {function} func The function to chain after the original
* @return {function} The chained function that replaced the original
*/
Common.chainPathAfter = function(base, path, func) {
return Common.set(base, path, Common.chain(
Common.get(base, path),
func
));
};
/**
* Provide the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module to enable
* concave vertex decomposition support when using `Bodies.fromVertices` e.g. `Common.setDecomp(require('poly-decomp'))`.
* @method setDecomp
* @param {} decomp The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module.
*/
Common.setDecomp = function(decomp) {
Common._decomp = decomp;
};
/**
* Returns the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module provided through `Common.setDecomp`,
* otherwise returns the global `decomp` if set.
* @method getDecomp
* @return {} The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module if provided.
*/
Common.getDecomp = function() {
// get user provided decomp if set
var decomp = Common._decomp;
try {
// otherwise from window global
if (!decomp && typeof window !== 'undefined') {
decomp = window.decomp;
}
// otherwise from node global
if (!decomp && typeof global !== 'undefined') {
decomp = global.decomp;
}
} catch (e) {
// decomp not available
decomp = null;
}
return decomp;
};
})();
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/**
* The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB).
*
* @class Bounds
*/
var Bounds = {};
module.exports = Bounds;
(function() {
/**
* Creates a new axis-aligned bounding box (AABB) for the given vertices.
* @method create
* @param {vertices} vertices
* @return {bounds} A new bounds object
*/
Bounds.create = function(vertices) {
var bounds = {
min: { x: 0, y: 0 },
max: { x: 0, y: 0 }
};
if (vertices)
Bounds.update(bounds, vertices);
return bounds;
};
/**
* Updates bounds using the given vertices and extends the bounds given a velocity.
* @method update
* @param {bounds} bounds
* @param {vertices} vertices
* @param {vector} velocity
*/
Bounds.update = function(bounds, vertices, velocity) {
bounds.min.x = Infinity;
bounds.max.x = -Infinity;
bounds.min.y = Infinity;
bounds.max.y = -Infinity;
for (var i = 0; i < vertices.length; i++) {
var vertex = vertices[i];
if (vertex.x > bounds.max.x) bounds.max.x = vertex.x;
if (vertex.x < bounds.min.x) bounds.min.x = vertex.x;
if (vertex.y > bounds.max.y) bounds.max.y = vertex.y;
if (vertex.y < bounds.min.y) bounds.min.y = vertex.y;
}
if (velocity) {
if (velocity.x > 0) {
bounds.max.x += velocity.x;
} else {
bounds.min.x += velocity.x;
}
if (velocity.y > 0) {
bounds.max.y += velocity.y;
} else {
bounds.min.y += velocity.y;
}
}
};
/**
* Returns true if the bounds contains the given point.
* @method contains
* @param {bounds} bounds
* @param {vector} point
* @return {boolean} True if the bounds contain the point, otherwise false
*/
Bounds.contains = function(bounds, point) {
return point.x >= bounds.min.x && point.x <= bounds.max.x
&& point.y >= bounds.min.y && point.y <= bounds.max.y;
};
/**
* Returns true if the two bounds intersect.
* @method overlaps
* @param {bounds} boundsA
* @param {bounds} boundsB
* @return {boolean} True if the bounds overlap, otherwise false
*/
Bounds.overlaps = function(boundsA, boundsB) {
return (boundsA.min.x <= boundsB.max.x && boundsA.max.x >= boundsB.min.x
&& boundsA.max.y >= boundsB.min.y && boundsA.min.y <= boundsB.max.y);
};
/**
* Translates the bounds by the given vector.
* @method translate
* @param {bounds} bounds
* @param {vector} vector
*/
Bounds.translate = function(bounds, vector) {
bounds.min.x += vector.x;
bounds.max.x += vector.x;
bounds.min.y += vector.y;
bounds.max.y += vector.y;
};
/**
* Shifts the bounds to the given position.
* @method shift
* @param {bounds} bounds
* @param {vector} position
*/
Bounds.shift = function(bounds, position) {
var deltaX = bounds.max.x - bounds.min.x,
deltaY = bounds.max.y - bounds.min.y;
bounds.min.x = position.x;
bounds.max.x = position.x + deltaX;
bounds.min.y = position.y;
bounds.max.y = position.y + deltaY;
};
})();
/***/ }),
/* 2 */
/***/ (function(module, exports) {
/**
* The `Matter.Vector` module contains methods for creating and manipulating vectors.
* Vectors are the basis of all the geometry related operations in the engine.
* A `Matter.Vector` object is of the form `{ x: 0, y: 0 }`.
*
* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).
*
* @class Vector
*/
// TODO: consider params for reusing vector objects
var Vector = {};
module.exports = Vector;
(function() {
/**
* Creates a new vector.
* @method create
* @param {number} x
* @param {number} y
* @return {vector} A new vector
*/
Vector.create = function(x, y) {
return { x: x || 0, y: y || 0 };
};
/**
* Returns a new vector with `x` and `y` copied from the given `vector`.
* @method clone
* @param {vector} vector
* @return {vector} A new cloned vector
*/
Vector.clone = function(vector) {
return { x: vector.x, y: vector.y };
};
/**
* Returns the magnitude (length) of a vector.
* @method magnitude
* @param {vector} vector
* @return {number} The magnitude of the vector
*/
Vector.magnitude = function(vector) {
return Math.sqrt((vector.x * vector.x) + (vector.y * vector.y));
};
/**
* Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation).
* @method magnitudeSquared
* @param {vector} vector
* @return {number} The squared magnitude of the vector
*/
Vector.magnitudeSquared = function(vector) {
return (vector.x * vector.x) + (vector.y * vector.y);
};
/**
* Rotates the vector about (0, 0) by specified angle.
* @method rotate
* @param {vector} vector
* @param {number} angle
* @param {vector} [output]
* @return {vector} The vector rotated about (0, 0)
*/
Vector.rotate = function(vector, angle, output) {
var cos = Math.cos(angle), sin = Math.sin(angle);
if (!output) output = {};
var x = vector.x * cos - vector.y * sin;
output.y = vector.x * sin + vector.y * cos;
output.x = x;
return output;
};
/**
* Rotates the vector about a specified point by specified angle.
* @method rotateAbout
* @param {vector} vector
* @param {number} angle
* @param {vector} point
* @param {vector} [output]
* @return {vector} A new vector rotated about the point
*/
Vector.rotateAbout = function(vector, angle, point, output) {
var cos = Math.cos(angle), sin = Math.sin(angle);
if (!output) output = {};
var x = point.x + ((vector.x - point.x) * cos - (vector.y - point.y) * sin);
output.y = point.y + ((vector.x - point.x) * sin + (vector.y - point.y) * cos);
output.x = x;
return output;
};
/**
* Normalises a vector (such that its magnitude is `1`).
* @method normalise
* @param {vector} vector
* @return {vector} A new vector normalised
*/
Vector.normalise = function(vector) {
var magnitude = Vector.magnitude(vector);
if (magnitude === 0)
return { x: 0, y: 0 };
return { x: vector.x / magnitude, y: vector.y / magnitude };
};
/**
* Returns the dot-product of two vectors.
* @method dot
* @param {vector} vectorA
* @param {vector} vectorB
* @return {number} The dot product of the two vectors
*/
Vector.dot = function(vectorA, vectorB) {
return (vectorA.x * vectorB.x) + (vectorA.y * vectorB.y);
};
/**
* Returns the cross-product of two vectors.
* @method cross
* @param {vector} vectorA
* @param {vector} vectorB
* @return {number} The cross product of the two vectors
*/
Vector.cross = function(vectorA, vectorB) {
return (vectorA.x * vectorB.y) - (vectorA.y * vectorB.x);
};