-
Notifications
You must be signed in to change notification settings - Fork 1
/
melonJS-0.9.7.js
executable file
·13358 lines (11550 loc) · 330 KB
/
melonJS-0.9.7.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
/**
* @license MelonJS Game Engine
* Copyright (C) 2011 - 2013, Olivier BIOT
* http://www.melonjs.org
*
* melonJS is licensed under the MIT License.
* http://www.opensource.org/licenses/mit-license.php
*
*/
/**
* (<b>m</b>)elonJS (<b>e</b>)ngine : All melonJS functions are defined inside of this namespace.<p>
* You generally should not add new properties to this namespace as it may be overwritten in future versions.
* @namespace
*/
var me = me || {};
(function($) {
// Use the correct document accordingly to window argument
var document = $.document;
/**
* me global references
* @namespace
*/
me = {
// settings & configuration
// library name & version
mod : "melonJS",
version : "0.9.7",
nocache : '',
// Public Object (To be completed)
audio : null,
video : null,
timer : null,
input : null,
state : null,
game : null,
entityPool : null,
levelDirector : null,
// System Object (instances)
TMXParser : null,
loadingScreen : null,
// TMX Stuff
TMXTileMap : null
};
/**
* global system settings and browser capabilities
* @namespace
*/
me.sys = {
// Browser capabilities
/**
* Browser User Agent (read-only)
* @type Boolean
* @memberOf me.sys
*/
ua : navigator.userAgent.toLowerCase(),
/**
* Browser Audio capabilities (read-only) <br>
* @type Boolean
* @memberOf me.sys
*/
sound : false,
/**
* Browser Local Storage capabilities (read-only) <br>
* @type Boolean
* @memberOf me.sys
*/
localStorage : (typeof($.localStorage) == 'object'),
/**
* Browser Gyroscopic Motion Event capabilities (read-only) <br>
* @type Boolean
* @memberOf me.sys
*/
gyro : ($.DeviceMotionEvent !== undefined),
/**
* Browser Base64 decoding capability (read-only) <br>
* @type Boolean
* @memberOf me.sys
*/
nativeBase64 : (typeof($.atob) == 'function'),
/**
* Touch capabilities <br>
* @type Boolean
* @memberOf me.sys
*/
touch : false,
// Global settings
/**
* Game FPS (default 60)
* @type Int
* @memberOf me.sys
*/
fps : 40,
/**
* enable/disable frame interpolation (default disable)<br>
* @type Boolean
* @memberOf me.sys
*/
interpolation : false,
/**
* Global scaling factor(default 1.0)
* @type me.Vector2d
* @memberOf me.sys
*/
scale : null, //initialized by me.video.init
/**
* Global gravity settings <br>
* will override entities init value if defined<br>
* default value : undefined
* @type Number
* @memberOf me.sys
*/
gravity : undefined,
/**
* Use native "requestAnimFrame" function if supported <br>
* fallback to clearInterval if not supported by the browser<br>
* @type Boolean
* @memberOf me.sys
*/
useNativeAnimFrame : false,
/**
* cache Image using a Canvas element, instead of directly using the Image Object<br>
* using this, performances are lower on OSX desktop (others, including mobile untested)<br>
* default value : false
* @type Boolean
* @memberOf me.sys
*/
cacheImage : false,
/**
* Enable dirtyRegion Feature <br>
* default value : false<br>
* (!) not fully implemented/supported (!)
* @type Boolean
* @memberOf me.sys
*/
dirtyRegion : false,
/**
* Specify either to stop on audio loading error or not<br>
* if me.debug.stopOnAudioLoad is true, melonJS will throw an exception and stop loading<br>
* if me.debug.stopOnAudioLoad is false, melonJS will disable sounds and output a warning message in the console <br>
* default value : true<br>
* @type Boolean
* @memberOf me.sys
*/
stopOnAudioError : true,
/**
* Specify either to pause the game when losing focus or not<br>
* default value : true<br>
* @type Boolean
* @memberOf me.sys
*/
pauseOnBlur : false,
/**
* Specify the rendering method for layers <br>
* if false, visible part of the layers are rendered dynamically (default)<br>
* if true, the entire layers are first rendered into an offscreen canvas<br>
* the "best" rendering method depends of your game<br>
* (amount of layer, layer size, amount of tiles per layer, etc…)<br>
* note : rendering method is also configurable per layer by adding this property to your layer (in Tiled)<br>
* @type Boolean
* @memberOf me.sys
*/
preRender : false,
// System methods
/**
* Compare two version strings
* @public
* @function
* @param {String} first First version string to compare
* @param {String} [second="0.9.7"] Second version string to compare
* @return {Integer} comparison result <br>< 0 : first < second <br>0 : first == second <br>> 0 : first > second
* @example
* if (me.sys.checkVersion("0.9.5") > 0) {
* console.error("melonJS is too old. Expected: 0.9.5, Got: " + me.version);
* }
*/
checkVersion : function (first, second) {
second = second || me.version;
var a = first.split(".");
var b = second.split(".");
var len = Math.min(a.length, b.length);
var result = 0;
for (var i = 0; i < len; i++) {
if (result = +a[i] - +b[i]) {
break;
}
}
return result ? result : a.length - b.length;
}
};
// a flag to know if melonJS
// is initialized
var me_initialized = false;
/*---
DOM loading stuff
---*/
var readyBound = false, isReady = false, readyList = [];
// Handle when the DOM is ready
function domReady() {
// Make sure that the DOM is not already loaded
if (!isReady) {
// be sure document.body is there
if (!document.body) {
return setTimeout(domReady, 13);
}
// clean up loading event
if (document.removeEventListener)
document.removeEventListener("DOMContentLoaded", domReady, false);
else
$.removeEventListener("load", domReady, false);
// Remember that the DOM is ready
isReady = true;
// execute the defined callback
for ( var fn = 0; fn < readyList.length; fn++) {
readyList[fn].call($, []);
}
readyList.length = 0;
}
}
;
// bind ready
function bindReady() {
if (readyBound) {
return;
}
readyBound = true;
// directly call domReady if document is already "ready"
if (document.readyState === "complete") {
return domReady();
} else {
if (document.addEventListener) {
// Use the handy event callback
document.addEventListener("DOMContentLoaded", domReady, false);
}
// A fallback to window.onload, that will always work
$.addEventListener("load", domReady, false);
}
};
/**
* Specify a function to execute when the DOM is fully loaded
* @param {Function} handler A function to execute after the DOM is ready.
* @example
* // small main skeleton
* var jsApp =
* {
* // Initialize the jsApp
* // called by the window.onReady function
* onload: function()
* {
* // init video
* if (!me.video.init('jsapp', 640, 480))
* {
* alert("Sorry but your browser does not support html 5 canvas. ");
* return;
* }
*
* // initialize the "audio"
* me.audio.init("mp3,ogg");
*
* // set callback for ressources loaded event
* me.loader.onload = this.loaded.bind(this);
*
* // set all ressources to be loaded
* me.loader.preload(g_ressources);
*
* // load everything & display a loading screen
* me.state.change(me.state.LOADING);
* },
*
* // callback when everything is loaded
* loaded: function ()
* {
* // define stuff
* // ....
*
* // change to the menu screen
* me.state.change(me.state.MENU);
* }
* }; // jsApp
*
* // "bootstrap"
* window.onReady(function()
* {
* jsApp.onload();
* });
*/
$.onReady = function(fn) {
// Attach the listeners
bindReady();
// If the DOM is already ready
if (isReady) {
// Execute the function immediately
fn.call($, []);
} else {
// Add the function to the wait list
readyList.push(function() {
return fn.call($, []);
});
}
return this;
};
// call the library init function when ready
$.onReady(function() {
_init_ME();
});
/************************************************************************************/
/*---
some "Javascript API" patch & enhancement
---*/
var initializing = false,
fnTest = /xyz/.test(function() {/**@nosideeffects*/xyz;}) ? /\bparent\b/ : /.*/;
/**
* JavaScript Inheritance Helper <br>
* Based on <a href="http://ejohn.org/">John Resig</a> Simple Inheritance<br>
* MIT Licensed.<br>
* Inspired by <a href="http://code.google.com/p/base2/">base2</a> and <a href="http://www.prototypejs.org/">Prototype</a><br>
* @param {Object} object Object (or Properties) to inherit from
* @example
* var Person = Object.extend(
* {
* init: function(isDancing)
* {
* this.dancing = isDancing;
* },
* dance: function()
* {
* return this.dancing;
* }
* });
*
* var Ninja = Person.extend(
* {
* init: function()
* {
* this.parent( false );
* },
*
* dance: function()
* {
* // Call the inherited version of dance()
* return this.parent();
* },
*
* swingSword: function()
* {
* return true;
* }
* });
*
* var p = new Person(true);
* p.dance(); // => true
*
* var n = new Ninja();
* n.dance(); // => false
* n.swingSword(); // => true
*
* // Should all be true
* p instanceof Person && p instanceof Class &&
* n instanceof Ninja && n instanceof Person && n instanceof Class
*/
Object.extend = function(prop) {
// _super rename to parent to ease code reading
var parent = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var proto = new this();
initializing = false;
// Copy the properties over onto the new prototype
for ( var name in prop) {
// Check if we're overwriting an existing function
proto[name] = typeof prop[name] == "function"
&& typeof parent[name] == "function"
&& fnTest.test(prop[name]) ? (function(name, fn) {
return function() {
var tmp = this.parent;
// Add a new ._super() method that is the same method
// but on the super-class
this.parent = parent[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this.parent = tmp;
return ret;
};
})(name, prop[name]) : prop[name];
}
// The dummy class constructor
function Class() {
if (!initializing && this.init) {
this.init.apply(this, arguments);
}
//return this;
}
// Populate our constructed prototype object
Class.prototype = proto;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = Object.extend;//arguments.callee;
return Class;
};
if (typeof Object.create !== 'function') {
/**
* Prototypal Inheritance Create Helper
* @param {Object} Object
* @example
* // declare oldObject
* oldObject = new Object();
* // make some crazy stuff with oldObject (adding functions, etc...)
* ...
* ...
*
* // make newObject inherits from oldObject
* newObject = Object.create(oldObject);
*/
Object.create = function(o) {
function _fn() {};
_fn.prototype = o;
return new _fn();
};
};
if (!Function.prototype.bind) {
/** @private */
function Empty() {};
/**
* Binds this function to the given context by wrapping it in another function and returning the wrapper.<p>
* Whenever the resulting "bound" function is called, it will call the original ensuring that this is set to context. <p>
* Also optionally curries arguments for the function.
* @param {Object} context the object to bind to.
* @param {Array.<string>} [args] Optional additional arguments to curry for the function.
* @example
* // Ensure that our callback is triggered with the right object context (this):
* myObject.onComplete(this.callback.bind(this));
*/
Function.prototype.bind = function bind(that) {
// ECMAScript 5 compliant implementation
// http://es5.github.com/#x15.3.4.5
// from https://github.com/kriskowal/es5-shim
var target = this;
if (typeof target != "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
var args = Array.prototype.slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
var result = target.apply( this, args.concat(Array.prototype.slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(that, args.concat(Array.prototype.slice.call(arguments)));
}
};
if(target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
};
if (typeof Date.now === "undefined") {
/**
* provide a replacement for browser not
* supporting Date.now (JS 1.5)
* @private
*/
Date.now = function(){return new Date().getTime()};
}
if(typeof console === "undefined") {
/**
* Dummy console.log to avoid crash
* in case the browser does not support it
* @private
*/
console = {
log: function() {},
info: function() {},
error: function() {alert(Array.prototype.slice.call(arguments).join(", "));}
};
}
/**
* Executes a function as soon as the interpreter is idle (stack empty).
* @param {Args} [args] Optional additional arguments to curry for the function.
* @return {Int} id that can be used to clear the deferred function using clearTimeout
* @example
*
* // execute myFunc() when the stack is empty, with 'myArgument' as parameter
* myFunc.defer('myArgument');
*
*/
Function.prototype.defer = function() {
var fn = this, args = Array.prototype.slice.call(arguments);
return window.setTimeout(function() {
return fn.apply(fn, args);
}, 0.01);
};
if (!Object.defineProperty) {
/**
* simple defineProperty function definition (if not supported by the browser)<br>
* if defineProperty is redefined, internally use __defineGetter__/__defineSetter__ as fallback
* @param {Object} obj The object on which to define the property.
* @param {String} prop The name of the property to be defined or modified.
* @param {Object} desc The descriptor for the property being defined or modified.
*/
Object.defineProperty = function(obj, prop, desc) {
// check if Object support __defineGetter function
if (obj.__defineGetter__) {
if (desc.get) {
obj.__defineGetter__(prop, desc.get);
}
if (desc.set) {
obj.__defineSetter__(prop, desc.set);
}
} else {
// we should never reach this point....
throw "melonJS: Object.defineProperty not supported";
}
}
};
if(!String.prototype.trim) {
/**
* returns the string stripped of whitespace from both ends
* @extends String
* @return {String} trimmed string
*/
String.prototype.trim = function () {
return (this.replace(/^\s+/, '')).replace(/\s+$/, '');
};
};
/**
* add isNumeric fn to the string object
* @extends String
* @return {Boolean} true if string contains only digits
*/
String.prototype.isNumeric = function() {
return (this != null && !isNaN(this) && this.trim() != "");
};
/**
* add a isBoolean fn to the string object
* @extends String
* @return {Boolean} true if the string is either true or false
*/
String.prototype.isBoolean = function() {
return (this != null && ("true" == this.trim() || "false" == this
.trim()));
};
/**
* add a contains fn to the string object
* @param {String} string to test for
* @extends String
* @return {Boolean} true if contains the specified string
*/
String.prototype.contains = function(word) {
return this.indexOf(word) > -1;
};
/**
* convert the string to hex value
* @extends String
* @return {String}
*/
String.prototype.toHex = function() {
var res = "", c = 0;
while(c<this.length){
res += this.charCodeAt(c++).toString(16);
}
return res;
};
/**
* add a clamp fn to the Number object
* @param {Number} low lower limit
* @param {Number} high higher limit
* @extends Number
* @return {Number} clamped value
*/
Number.prototype.clamp = function(low, high) {
return this < low ? low : this > high ? high : +this;
};
/**
* return a random between min, max
* @param {Number} min minimum value.
* @param {Number} max maximum value.
* @extends Number
* @return {Number} random value
*/
Number.prototype.random = function(min, max) {
return (~~(Math.random() * (max - min + 1)) + min);
};
/**
* round a value to the specified number of digit
* @param {Number} [num="Object value"] value to be rounded.
* @param {Number} dec number of decimal digit to be rounded to.
* @extends Number
* @return {Number} rounded value
* @example
* // round a specific value to 2 digits
* Number.prototype.round (10.33333, 2); // return 10.33
* // round a float value to 4 digits
* num = 10.3333333
* num.round(4); // return 10.3333
*/
Number.prototype.round = function() {
// if only one argument use the object value
var num = (arguments.length < 2) ? this : arguments[0];
var powres = Math.pow(10, arguments[1] || arguments[0] || 0);
return (Math.round(num * powres) / powres);
};
/**
* a quick toHex function<br>
* given number <b>must</b> be an int, with a value between 0 and 255
* @extends Number
* @return {String} converted hexadecimal value
*/
Number.prototype.toHex = function() {
return "0123456789ABCDEF".charAt((this - this % 16) >> 4)
+ "0123456789ABCDEF".charAt(this % 16);
};
/**
* Returns a value indicating the sign of a number<br>
* @extends Number
* @return {Number} sign of a the number
*/
Number.prototype.sign = function() {
return this < 0 ? -1 : (this > 0 ? 1 : 0);
};
/**
* Converts an angle in degrees to an angle in radians
* @param {Number} [angle="angle"] angle in degrees
* @extends Number
* @return {Number} corresponding angle in radians
* @example
* // convert a specific angle
* Number.prototype.degToRad (60); // return 1.0471...
* // convert object value
* var num = 60
* num.degToRad(); // return 1.0471...
*/
Number.prototype.degToRad = function (angle) {
return (angle||this) / 180.0 * Math.PI;
};
/**
* Converts an angle in radians to an angle in degrees.
* @param {Number} [angle="angle"] angle in radians
* @extends Number
* @return {Number} corresponding angle in degrees
* @example
* // convert a specific angle
* Number.prototype.radToDeg (1.0471975511965976); // return 59.9999...
* // convert object value
* num = 1.0471975511965976
* Math.ceil(num.radToDeg()); // return 60
*/
Number.prototype.radToDeg = function (angle) {
return (angle||this) * (180.0 / Math.PI);
};
/**
* Remove the specified object from the Array<br>
* @param {Object} object to be removed
* @extends Array
*/
Array.prototype.remove = function(obj) {
var i = Array.prototype.indexOf.call(this, obj);
if( i !== -1 ) {
Array.prototype.splice.call(this, i, 1);
}
return this;
};
if (!Array.prototype.forEach) {
/**
* provide a replacement for browsers that don't
* support Array.prototype.forEach (JS 1.6)
* @private
*/
Array.prototype.forEach = function (callback, scope) {
for (var i = 0, j = this.length; j--; i++) {
callback.call(scope || this, this[i], i, this);
}
};
}
Object.defineProperty(me, "initialized", {
get : function get() {
return me_initialized;
}
});
/*---
ME init stuff
---*/
function _init_ME() {
// don't do anything if already initialized (should not happen anyway)
if (me_initialized)
return;
// enable/disable the cache
me.utils.setNocache(document.location.href.match(/\?nocache/)||false);
// detect audio capabilities
me.audio.detectCapabilities();
// detect touch capabilities
me.sys.touch = ('createTouch' in document) || ('ontouchstart' in $) || (navigator.isCocoonJS);
// init the FPS counter if needed
me.timer.init();
// create a new map reader instance
me.mapReader = new me.TMXMapReader();
// create a default loading screen
me.loadingScreen = new me.DefaultLoadingScreen();
// init the App Manager
me.state.init();
// init the Entity Pool
me.entityPool.init();
// init the level Director
me.levelDirector.reset();
me_initialized = true;
};
/******************************************/
/* OBJECT DRAWING MANAGEMENT */
/* hold & manage app/game objects */
/******************************************/
/**
* a object drawing manager
* only used by the game manager
* @ignore
*/
var drawManager = (function() {
// hold public stuff in our singletong
var api = {};
// list of region to redraw
// valid for any updated object
var dirtyRects = [];
// cache the full screen area rect
var fullscreen_rect;
// list of object to redraw
// only valid for visible and update object
var dirtyObjects = [];
var drawCount = 0;
// a flag indicating if we need a redraw
api.isDirty = false;
/**
* init function
*/
api.reset = function() {
// make sure it's empty
dirtyRects.length = 0;
dirtyObjects.length = 0;
// set our cached rect to the actual screen size
fullscreen_rect = me.game.viewport.getRect();
// make everything dirty
api.makeAllDirty();
};
/**
* add a dirty object
* I should find a cleaner way to manage old/new object rect
*/
api.makeDirty = function(obj, updated, oldRect) {
// object updated ?
if (updated) {
// yeah some drawing job to do !
api.isDirty = true;
// add a dirty rect if feature enable
if (me.sys.dirtyRegion) {
// TODO : HOW DO WE MANAGE COORDINATES
// OF FLOATING OBJECT'S RECTS ?
// some stuff to optimize the amount
// of dirty rect would be nice here
// instead of adding everything :)
// this is for later I guess !
if (oldRect) {
// merge both rect, and add it to the list
// directly pass object, since anyway it inherits from rect
dirtyRects.push(oldRect.union(obj));
} else if (obj.getRect) {
dirtyRects.push(obj.getRect());
}
}
}
// if obj is in the viewport add it to the list of obj to draw
if (obj.inViewport) {
// add obj at index 0, so that we can keep
// our inverted loop later
dirtyObjects.unshift(obj);
}
};
/**
* make all object dirty
*/
api.makeAllDirty = function() {
//empty the dirty rect list
dirtyRects.length = 0;
//and add a dirty region with the screen area size
dirtyRects.push(fullscreen_rect);
// make sure it's dirty
api.isDirty = true;
// they are maybe too much call to this function
// to be checked later...
//console.log("making everything dirty!");
};
/**
* remove an object
*/
api.remove = function(obj) {
var idx = dirtyObjects.indexOf(obj);
if (idx != -1) {
// remove the object from the list of obj to draw
dirtyObjects.splice(idx, 1);
// mark the object as not within the viewport
// so it won't be added (again) in the list object to be draw
obj.inViewport = false;
// and flag the area as dirty
api.makeDirty(obj, true);
}
};
/**
* return the amount of draw object per frame
*/
api.getDrawCount = function() {
return drawCount;
};
/**
* draw all dirty objects/regions
*/
api.draw = function(context) {
// cache viewport position vector
var posx = me.game.viewport.pos.x;
var posy = me.game.viewport.pos.y;
// save the current context
context.save();
// translate by default to screen coordinates
context.translate(-posx, -posy)
// substract the map offset to current the current pos
posx -= me.game.currentLevel.pos.x;
posy -= me.game.currentLevel.pos.y;
// if feature disable, we only have one dirty rect (the viewport area)
for ( var r = dirtyRects.length, rect; r--, rect = dirtyRects[r];) {
// parse all objects
for ( var o = dirtyObjects.length, obj; o--, obj = dirtyObjects[o];) {
// if dirty region enabled, make sure the object is in the area to be refreshed
if (me.sys.dirtyRegion && obj.isSprite && !obj.overlaps(rect)) {
continue;
}
if (obj.floating===true) {
context.save();
// cancel the previous translate
context.translate(posx, posy);
}
// draw the object using the dirty area to be updated
obj.draw(context, rect);
if (obj.floating===true) {
context.restore();
}
drawCount++;
}
// some debug stuff
if (me.debug.renderDirty) {
rect.draw(context, "white");
}
}
// restore initial context
context.restore();
};
/**
* flush all rect
*/
api.flush = function() {
// only empty dirty area list if dirtyRec feature is enable
// allows to keep the viewport area as a default dirty rect
if (me.sys.dirtyRegion) {
dirtyRects.length = 0;
}
// empty the dirty object list
dirtyObjects.length = 0;
// clear the flag
api.isDirty = false;
// reset draw count for debug panel
drawCount = 0;
};
return api;
})();
/**
* me.game represents your current game, it contains all the objects, tilemap layers,<br>