Farewell TypeScript, see you on the other side.

This commit is contained in:
Richard Davey
2013-08-28 07:02:57 +01:00
parent 0e55e644a9
commit 09def364c3
989 changed files with 67634 additions and 14984 deletions
+96
View File
@@ -0,0 +1,96 @@
/// <reference path="../_definitions.ts" />
/**
* Phaser - AnimationLoader
*
* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
*/
var Phaser;
(function (Phaser) {
var AnimationLoader = (function () {
function AnimationLoader() { }
AnimationLoader.parseSpriteSheet = /**
* Parse a sprite sheet from asset data.
* @param key {string} Asset key for the sprite sheet data.
* @param frameWidth {number} Width of animation frame.
* @param frameHeight {number} Height of animation frame.
* @param frameMax {number} Number of animation frames.
* @return {FrameData} Generated FrameData object.
*/
function parseSpriteSheet(game, key, frameWidth, frameHeight, frameMax) {
// How big is our image?
var img = game.cache.getImage(key);
if(img == null) {
return null;
}
var width = img.width;
var height = img.height;
var row = Math.round(width / frameWidth);
var column = Math.round(height / frameHeight);
var total = row * column;
if(frameMax !== -1) {
total = frameMax;
}
// Zero or smaller than frame sizes?
if(width == 0 || height == 0 || width < frameWidth || height < frameHeight || total === 0) {
throw new Error("AnimationLoader.parseSpriteSheet: width/height zero or width/height < given frameWidth/frameHeight");
return null;
}
// Let's create some frames then
var data = new Phaser.FrameData();
var x = 0;
var y = 0;
for(var i = 0; i < total; i++) {
data.addFrame(new Phaser.Frame(x, y, frameWidth, frameHeight, ''));
x += frameWidth;
if(x === width) {
x = 0;
y += frameHeight;
}
}
return data;
};
AnimationLoader.parseJSONData = /**
* Parse frame datas from json.
* @param json {object} Json data you want to parse.
* @return {FrameData} Generated FrameData object.
*/
function parseJSONData(game, json) {
// Malformed?
if(!json['frames']) {
console.log(json);
throw new Error("Phaser.AnimationLoader.parseJSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
}
// Let's create some frames then
var data = new Phaser.FrameData();
// By this stage frames is a fully parsed array
var frames = json['frames'];
var newFrame;
for(var i = 0; i < frames.length; i++) {
newFrame = data.addFrame(new Phaser.Frame(frames[i].frame.x, frames[i].frame.y, frames[i].frame.w, frames[i].frame.h, frames[i].filename));
newFrame.setTrim(frames[i].trimmed, frames[i].sourceSize.w, frames[i].sourceSize.h, frames[i].spriteSourceSize.x, frames[i].spriteSourceSize.y, frames[i].spriteSourceSize.w, frames[i].spriteSourceSize.h);
}
return data;
};
AnimationLoader.parseXMLData = function parseXMLData(game, xml, format) {
// Malformed?
if(!xml.getElementsByTagName('TextureAtlas')) {
throw new Error("Phaser.AnimationLoader.parseXMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
}
// Let's create some frames then
var data = new Phaser.FrameData();
var frames = xml.getElementsByTagName('SubTexture');
var newFrame;
for(var i = 0; i < frames.length; i++) {
var frame = frames[i].attributes;
newFrame = data.addFrame(new Phaser.Frame(frame.x.nodeValue, frame.y.nodeValue, frame.width.nodeValue, frame.height.nodeValue, frame.name.nodeValue));
// Trimmed?
if(frame.frameX.nodeValue != '-0' || frame.frameY.nodeValue != '-0') {
newFrame.setTrim(true, frame.width.nodeValue, frame.height.nodeValue, Math.abs(frame.frameX.nodeValue), Math.abs(frame.frameY.nodeValue), frame.frameWidth.nodeValue, frame.frameHeight.nodeValue);
}
}
return data;
};
return AnimationLoader;
})();
Phaser.AnimationLoader = AnimationLoader;
})(Phaser || (Phaser = {}));
+153
View File
@@ -0,0 +1,153 @@
/// <reference path="../_definitions.ts" />
/**
* Phaser - AnimationLoader
*
* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
*/
module Phaser {
export class AnimationLoader {
/**
* Parse a sprite sheet from asset data.
* @param key {string} Asset key for the sprite sheet data.
* @param frameWidth {number} Width of animation frame.
* @param frameHeight {number} Height of animation frame.
* @param frameMax {number} Number of animation frames.
* @return {FrameData} Generated FrameData object.
*/
public static parseSpriteSheet(game: Game, key: string, frameWidth: number, frameHeight: number, frameMax: number): FrameData {
// How big is our image?
var img = game.cache.getImage(key);
if (img == null)
{
return null;
}
var width = img.width;
var height = img.height;
var row = Math.round(width / frameWidth);
var column = Math.round(height / frameHeight);
var total = row * column;
if (frameMax !== -1)
{
total = frameMax;
}
// Zero or smaller than frame sizes?
if (width == 0 || height == 0 || width < frameWidth || height < frameHeight || total === 0)
{
throw new Error("AnimationLoader.parseSpriteSheet: width/height zero or width/height < given frameWidth/frameHeight");
return null;
}
// Let's create some frames then
var data: FrameData = new FrameData();
var x = 0;
var y = 0;
for (var i = 0; i < total; i++)
{
data.addFrame(new Frame(x, y, frameWidth, frameHeight, ''));
x += frameWidth;
if (x === width)
{
x = 0;
y += frameHeight;
}
}
return data;
}
/**
* Parse frame datas from json.
* @param json {object} Json data you want to parse.
* @return {FrameData} Generated FrameData object.
*/
public static parseJSONData(game: Game, json): FrameData {
// Malformed?
if (!json['frames'])
{
console.log(json);
throw new Error("Phaser.AnimationLoader.parseJSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
}
// Let's create some frames then
var data: FrameData = new FrameData();
// By this stage frames is a fully parsed array
var frames = json['frames'];
var newFrame: Frame;
for (var i = 0; i < frames.length; i++)
{
newFrame = data.addFrame(new Frame(
frames[i].frame.x,
frames[i].frame.y,
frames[i].frame.w,
frames[i].frame.h,
frames[i].filename));
newFrame.setTrim(
frames[i].trimmed,
frames[i].sourceSize.w,
frames[i].sourceSize.h,
frames[i].spriteSourceSize.x,
frames[i].spriteSourceSize.y,
frames[i].spriteSourceSize.w,
frames[i].spriteSourceSize.h);
}
return data;
}
public static parseXMLData(game: Game, xml, format: number): FrameData {
// Malformed?
if (!xml.getElementsByTagName('TextureAtlas'))
{
throw new Error("Phaser.AnimationLoader.parseXMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
}
// Let's create some frames then
var data: FrameData = new FrameData();
var frames = xml.getElementsByTagName('SubTexture');
var newFrame: Frame;
for (var i = 0; i < frames.length; i++)
{
var frame = frames[i].attributes;
newFrame = data.addFrame(new Frame(frame.x.nodeValue, frame.y.nodeValue, frame.width.nodeValue, frame.height.nodeValue, frame.name.nodeValue));
// Trimmed?
if (frame.frameX.nodeValue != '-0' || frame.frameY.nodeValue != '-0')
{
newFrame.setTrim(true, frame.width.nodeValue, frame.height.nodeValue, Math.abs(frame.frameX.nodeValue), Math.abs(frame.frameY.nodeValue), frame.frameWidth.nodeValue, frame.frameHeight.nodeValue);
}
}
return data;
}
}
}
+318
View File
@@ -0,0 +1,318 @@
/// <reference path="../_definitions.ts" />
/**
* Phaser - Cache
*
* A game only has one instance of a Cache and it is used to store all externally loaded assets such
* as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up.
*/
var Phaser;
(function (Phaser) {
var Cache = (function () {
/**
* Cache constructor
*/
function Cache(game) {
this.onSoundUnlock = new Phaser.Signal();
this.game = game;
this._canvases = {
};
this._images = {
};
this._sounds = {
};
this._text = {
};
}
Cache.prototype.addCanvas = /**
* Add a new canvas.
* @param key {string} Asset key for this canvas.
* @param canvas {HTMLCanvasElement} Canvas DOM element.
* @param context {CanvasRenderingContext2D} Render context of this canvas.
*/
function (key, canvas, context) {
this._canvases[key] = {
canvas: canvas,
context: context
};
};
Cache.prototype.addSpriteSheet = /**
* Add a new sprite sheet.
* @param key {string} Asset key for the sprite sheet.
* @param url {string} URL of this sprite sheet file.
* @param data {object} Extra sprite sheet data.
* @param frameWidth {number} Width of the sprite sheet.
* @param frameHeight {number} Height of the sprite sheet.
* @param frameMax {number} How many frames stored in the sprite sheet.
*/
function (key, url, data, frameWidth, frameHeight, frameMax) {
this._images[key] = {
url: url,
data: data,
spriteSheet: true,
frameWidth: frameWidth,
frameHeight: frameHeight
};
this._images[key].frameData = Phaser.AnimationLoader.parseSpriteSheet(this.game, key, frameWidth, frameHeight, frameMax);
};
Cache.prototype.addTextureAtlas = /**
* Add a new texture atlas.
* @param key {string} Asset key for the texture atlas.
* @param url {string} URL of this texture atlas file.
* @param data {object} Extra texture atlas data.
* @param atlasData {object} Texture atlas frames data.
*/
function (key, url, data, atlasData, format) {
this._images[key] = {
url: url,
data: data,
spriteSheet: true
};
if(format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY) {
this._images[key].frameData = Phaser.AnimationLoader.parseJSONData(this.game, atlasData);
} else if(format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) {
this._images[key].frameData = Phaser.AnimationLoader.parseXMLData(this.game, atlasData, format);
}
};
Cache.prototype.addImage = /**
* Add a new image.
* @param key {string} Asset key for the image.
* @param url {string} URL of this image file.
* @param data {object} Extra image data.
*/
function (key, url, data) {
this._images[key] = {
url: url,
data: data,
spriteSheet: false
};
};
Cache.prototype.addSound = /**
* Add a new sound.
* @param key {string} Asset key for the sound.
* @param url {string} URL of this sound file.
* @param data {object} Extra sound data.
*/
function (key, url, data, webAudio, audioTag) {
if (typeof webAudio === "undefined") { webAudio = true; }
if (typeof audioTag === "undefined") { audioTag = false; }
var locked = this.game.sound.touchLocked;
var decoded = false;
if(audioTag) {
decoded = true;
}
this._sounds[key] = {
url: url,
data: data,
locked: locked,
isDecoding: false,
decoded: decoded,
webAudio: webAudio,
audioTag: audioTag
};
};
Cache.prototype.reloadSound = function (key) {
var _this = this;
if(this._sounds[key]) {
this._sounds[key].data.src = this._sounds[key].url;
this._sounds[key].data.addEventListener('canplaythrough', function () {
return _this.reloadSoundComplete(key);
}, false);
this._sounds[key].data.load();
}
};
Cache.prototype.reloadSoundComplete = function (key) {
if(this._sounds[key]) {
this._sounds[key].locked = false;
this.onSoundUnlock.dispatch(key);
}
};
Cache.prototype.updateSound = function (key, property, value) {
if(this._sounds[key]) {
this._sounds[key][property] = value;
}
};
Cache.prototype.decodedSound = /**
* Add a new decoded sound.
* @param key {string} Asset key for the sound.
* @param data {object} Extra sound data.
*/
function (key, data) {
this._sounds[key].data = data;
this._sounds[key].decoded = true;
this._sounds[key].isDecoding = false;
};
Cache.prototype.addText = /**
* Add a new text data.
* @param key {string} Asset key for the text data.
* @param url {string} URL of this text data file.
* @param data {object} Extra text data.
*/
function (key, url, data) {
this._text[key] = {
url: url,
data: data
};
};
Cache.prototype.getCanvas = /**
* Get canvas by key.
* @param key Asset key of the canvas you want.
* @return {object} The canvas you want.
*/
function (key) {
if(this._canvases[key]) {
return this._canvases[key].canvas;
}
return null;
};
Cache.prototype.getImage = /**
* Get image data by key.
* @param key Asset key of the image you want.
* @return {object} The image data you want.
*/
function (key) {
if(this._images[key]) {
return this._images[key].data;
}
return null;
};
Cache.prototype.getFrameData = /**
* Get frame data by key.
* @param key Asset key of the frame data you want.
* @return {object} The frame data you want.
*/
function (key) {
if(this._images[key] && this._images[key].spriteSheet == true) {
return this._images[key].frameData;
}
return null;
};
Cache.prototype.getSound = /**
* Get sound by key.
* @param key Asset key of the sound you want.
* @return {object} The sound you want.
*/
function (key) {
if(this._sounds[key]) {
return this._sounds[key];
}
return null;
};
Cache.prototype.getSoundData = /**
* Get sound data by key.
* @param key Asset key of the sound you want.
* @return {object} The sound data you want.
*/
function (key) {
if(this._sounds[key]) {
return this._sounds[key].data;
}
return null;
};
Cache.prototype.isSoundDecoded = /**
* Check whether an asset is decoded sound.
* @param key Asset key of the sound you want.
* @return {object} The sound data you want.
*/
function (key) {
if(this._sounds[key]) {
return this._sounds[key].decoded;
}
};
Cache.prototype.isSoundReady = /**
* Check whether an asset is decoded sound.
* @param key Asset key of the sound you want.
* @return {object} The sound data you want.
*/
function (key) {
if(this._sounds[key] && this._sounds[key].decoded == true && this._sounds[key].locked == false) {
return true;
}
return false;
};
Cache.prototype.isSpriteSheet = /**
* Check whether an asset is sprite sheet.
* @param key Asset key of the sprite sheet you want.
* @return {object} The sprite sheet data you want.
*/
function (key) {
if(this._images[key]) {
return this._images[key].spriteSheet;
}
};
Cache.prototype.getText = /**
* Get text data by key.
* @param key Asset key of the text data you want.
* @return {object} The text data you want.
*/
function (key) {
if(this._text[key]) {
return this._text[key].data;
}
return null;
};
Cache.prototype.getImageKeys = /**
* Returns an array containing all of the keys of Images in the Cache.
* @return {Array} The string based keys in the Cache.
*/
function () {
var output = [];
for(var item in this._images) {
output.push(item);
}
return output;
};
Cache.prototype.getSoundKeys = /**
* Returns an array containing all of the keys of Sounds in the Cache.
* @return {Array} The string based keys in the Cache.
*/
function () {
var output = [];
for(var item in this._sounds) {
output.push(item);
}
return output;
};
Cache.prototype.getTextKeys = /**
* Returns an array containing all of the keys of Text Files in the Cache.
* @return {Array} The string based keys in the Cache.
*/
function () {
var output = [];
for(var item in this._text) {
output.push(item);
}
return output;
};
Cache.prototype.removeCanvas = function (key) {
delete this._canvases[key];
};
Cache.prototype.removeImage = function (key) {
delete this._images[key];
};
Cache.prototype.removeSound = function (key) {
delete this._sounds[key];
};
Cache.prototype.removeText = function (key) {
delete this._text[key];
};
Cache.prototype.destroy = /**
* Clean up cache memory.
*/
function () {
for(var item in this._canvases) {
delete this._canvases[item['key']];
}
for(var item in this._images) {
delete this._images[item['key']];
}
for(var item in this._sounds) {
delete this._sounds[item['key']];
}
for(var item in this._text) {
delete this._text[item['key']];
}
};
return Cache;
})();
Phaser.Cache = Cache;
})(Phaser || (Phaser = {}));
+431
View File
@@ -0,0 +1,431 @@
/// <reference path="../_definitions.ts" />
/**
* Phaser - Cache
*
* A game only has one instance of a Cache and it is used to store all externally loaded assets such
* as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up.
*/
module Phaser {
export class Cache {
/**
* Cache constructor
*/
constructor(game: Game) {
this.game = game;
this._canvases = {};
this._images = {};
this._sounds = {};
this._text = {};
}
/**
* Local reference to Game.
*/
public game: Phaser.Game;
/**
* Canvas key-value container.
* @type {object}
*/
private _canvases;
/**
* Image key-value container.
* @type {object}
*/
private _images;
/**
* Sound key-value container.
* @type {object}
*/
private _sounds;
/**
* Text key-value container.
* @type {object}
*/
private _text;
/**
* Add a new canvas.
* @param key {string} Asset key for this canvas.
* @param canvas {HTMLCanvasElement} Canvas DOM element.
* @param context {CanvasRenderingContext2D} Render context of this canvas.
*/
public addCanvas(key: string, canvas: HTMLCanvasElement, context: CanvasRenderingContext2D) {
this._canvases[key] = { canvas: canvas, context: context };
}
/**
* Add a new sprite sheet.
* @param key {string} Asset key for the sprite sheet.
* @param url {string} URL of this sprite sheet file.
* @param data {object} Extra sprite sheet data.
* @param frameWidth {number} Width of the sprite sheet.
* @param frameHeight {number} Height of the sprite sheet.
* @param frameMax {number} How many frames stored in the sprite sheet.
*/
public addSpriteSheet(key: string, url: string, data, frameWidth: number, frameHeight: number, frameMax: number) {
this._images[key] = { url: url, data: data, spriteSheet: true, frameWidth: frameWidth, frameHeight: frameHeight };
this._images[key].frameData = AnimationLoader.parseSpriteSheet(this.game, key, frameWidth, frameHeight, frameMax);
}
/**
* Add a new texture atlas.
* @param key {string} Asset key for the texture atlas.
* @param url {string} URL of this texture atlas file.
* @param data {object} Extra texture atlas data.
* @param atlasData {object} Texture atlas frames data.
*/
public addTextureAtlas(key: string, url: string, data, atlasData, format: number) {
this._images[key] = { url: url, data: data, spriteSheet: true };
if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY)
{
this._images[key].frameData = AnimationLoader.parseJSONData(this.game, atlasData);
}
else if (format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
{
this._images[key].frameData = AnimationLoader.parseXMLData(this.game, atlasData, format);
}
}
/**
* Add a new image.
* @param key {string} Asset key for the image.
* @param url {string} URL of this image file.
* @param data {object} Extra image data.
*/
public addImage(key: string, url: string, data) {
this._images[key] = { url: url, data: data, spriteSheet: false };
}
/**
* Add a new sound.
* @param key {string} Asset key for the sound.
* @param url {string} URL of this sound file.
* @param data {object} Extra sound data.
*/
public addSound(key: string, url: string, data, webAudio: bool = true, audioTag: bool = false) {
var locked: bool = this.game.sound.touchLocked;
var decoded: bool = false;
if (audioTag) {
decoded = true;
}
this._sounds[key] = { url: url, data: data, locked: locked, isDecoding: false, decoded: decoded, webAudio: webAudio, audioTag: audioTag };
}
public reloadSound(key: string) {
if (this._sounds[key])
{
this._sounds[key].data.src = this._sounds[key].url;
this._sounds[key].data.addEventListener('canplaythrough', () => this.reloadSoundComplete(key), false);
this._sounds[key].data.load();
}
}
public onSoundUnlock: Phaser.Signal = new Phaser.Signal;
public reloadSoundComplete(key: string) {
if (this._sounds[key])
{
this._sounds[key].locked = false;
this.onSoundUnlock.dispatch(key);
}
}
public updateSound(key: string, property: string, value) {
if (this._sounds[key])
{
this._sounds[key][property] = value;
}
}
/**
* Add a new decoded sound.
* @param key {string} Asset key for the sound.
* @param data {object} Extra sound data.
*/
public decodedSound(key: string, data) {
this._sounds[key].data = data;
this._sounds[key].decoded = true;
this._sounds[key].isDecoding = false;
}
/**
* Add a new text data.
* @param key {string} Asset key for the text data.
* @param url {string} URL of this text data file.
* @param data {object} Extra text data.
*/
public addText(key: string, url: string, data) {
this._text[key] = { url: url, data: data };
}
/**
* Get canvas by key.
* @param key Asset key of the canvas you want.
* @return {object} The canvas you want.
*/
public getCanvas(key: string) {
if (this._canvases[key])
{
return this._canvases[key].canvas;
}
return null;
}
/**
* Get image data by key.
* @param key Asset key of the image you want.
* @return {object} The image data you want.
*/
public getImage(key: string) {
if (this._images[key])
{
return this._images[key].data;
}
return null;
}
/**
* Get frame data by key.
* @param key Asset key of the frame data you want.
* @return {object} The frame data you want.
*/
public getFrameData(key: string): FrameData {
if (this._images[key] && this._images[key].spriteSheet == true)
{
return this._images[key].frameData;
}
return null;
}
/**
* Get sound by key.
* @param key Asset key of the sound you want.
* @return {object} The sound you want.
*/
public getSound(key: string) {
if (this._sounds[key])
{
return this._sounds[key];
}
return null;
}
/**
* Get sound data by key.
* @param key Asset key of the sound you want.
* @return {object} The sound data you want.
*/
public getSoundData(key: string) {
if (this._sounds[key])
{
return this._sounds[key].data;
}
return null;
}
/**
* Check whether an asset is decoded sound.
* @param key Asset key of the sound you want.
* @return {object} The sound data you want.
*/
public isSoundDecoded(key: string): bool {
if (this._sounds[key])
{
return this._sounds[key].decoded;
}
}
/**
* Check whether an asset is decoded sound.
* @param key Asset key of the sound you want.
* @return {object} The sound data you want.
*/
public isSoundReady(key: string): bool {
if (this._sounds[key] && this._sounds[key].decoded == true && this._sounds[key].locked == false)
{
return true;
}
return false;
}
/**
* Check whether an asset is sprite sheet.
* @param key Asset key of the sprite sheet you want.
* @return {object} The sprite sheet data you want.
*/
public isSpriteSheet(key: string): bool {
if (this._images[key])
{
return this._images[key].spriteSheet;
}
}
/**
* Get text data by key.
* @param key Asset key of the text data you want.
* @return {object} The text data you want.
*/
public getText(key: string) {
if (this._text[key])
{
return this._text[key].data;
}
return null;
}
/**
* Returns an array containing all of the keys of Images in the Cache.
* @return {Array} The string based keys in the Cache.
*/
public getImageKeys() {
var output = [];
for (var item in this._images)
{
output.push(item);
}
return output;
}
/**
* Returns an array containing all of the keys of Sounds in the Cache.
* @return {Array} The string based keys in the Cache.
*/
public getSoundKeys() {
var output = [];
for (var item in this._sounds)
{
output.push(item);
}
return output;
}
/**
* Returns an array containing all of the keys of Text Files in the Cache.
* @return {Array} The string based keys in the Cache.
*/
public getTextKeys() {
var output = [];
for (var item in this._text)
{
output.push(item);
}
return output;
}
public removeCanvas(key: string) {
delete this._canvases[key];
}
public removeImage(key: string) {
delete this._images[key];
}
public removeSound(key: string) {
delete this._sounds[key];
}
public removeText(key: string) {
delete this._text[key];
}
/**
* Clean up cache memory.
*/
public destroy() {
for (var item in this._canvases)
{
delete this._canvases[item['key']];
}
for (var item in this._images)
{
delete this._images[item['key']];
}
for (var item in this._sounds)
{
delete this._sounds[item['key']];
}
for (var item in this._text)
{
delete this._text[item['key']];
}
}
}
}
+503
View File
@@ -0,0 +1,503 @@
/// <reference path="../_definitions.ts" />
/**
* Phaser - Loader
*
* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks.
*/
var Phaser;
(function (Phaser) {
var Loader = (function () {
/**
* Loader constructor
*
* @param game {Phaser.Game} Current game instance.
*/
function Loader(game) {
/**
* The crossOrigin value applied to loaded images
* @type {string}
*/
this.crossOrigin = '';
// If you want to append a URL before the path of any asset you can set this here.
// Useful if you need to allow an asset url to be configured outside of the game code.
// MUST have / on the end of it!
this.baseURL = '';
this.game = game;
this._keys = [];
this._fileList = {
};
this._xhr = new XMLHttpRequest();
this._queueSize = 0;
this.isLoading = false;
this.onFileComplete = new Phaser.Signal();
this.onFileError = new Phaser.Signal();
this.onLoadStart = new Phaser.Signal();
this.onLoadComplete = new Phaser.Signal();
}
Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
Loader.TEXTURE_ATLAS_JSON_HASH = 1;
Loader.TEXTURE_ATLAS_XML_STARLING = 2;
Loader.prototype.reset = /**
* Reset loader, this will remove all loaded assets.
*/
function () {
this._queueSize = 0;
this.isLoading = false;
};
Object.defineProperty(Loader.prototype, "queueSize", {
get: function () {
return this._queueSize;
},
enumerable: true,
configurable: true
});
Loader.prototype.image = /**
* Add a new image asset loading request with key and url.
* @param key {string} Unique asset key of this image file.
* @param url {string} URL of image file.
*/
function (key, url, overwrite) {
if (typeof overwrite === "undefined") { overwrite = false; }
if(overwrite == true || this.checkKeyExists(key) == false) {
this._queueSize++;
this._fileList[key] = {
type: 'image',
key: key,
url: url,
data: null,
error: false,
loaded: false
};
this._keys.push(key);
}
};
Loader.prototype.spritesheet = /**
* Add a new sprite sheet loading request.
* @param key {string} Unique asset key of the sheet file.
* @param url {string} URL of sheet file.
* @param frameWidth {number} Width of each single frame.
* @param frameHeight {number} Height of each single frame.
* @param frameMax {number} How many frames in this sprite sheet.
*/
function (key, url, frameWidth, frameHeight, frameMax) {
if (typeof frameMax === "undefined") { frameMax = -1; }
if(this.checkKeyExists(key) === false) {
this._queueSize++;
this._fileList[key] = {
type: 'spritesheet',
key: key,
url: url,
data: null,
frameWidth: frameWidth,
frameHeight: frameHeight,
frameMax: frameMax,
error: false,
loaded: false
};
this._keys.push(key);
}
};
Loader.prototype.atlas = /**
* Add a new texture atlas loading request.
* @param key {string} Unique asset key of the texture atlas file.
* @param textureURL {string} The url of the texture atlas image file.
* @param [atlasURL] {string} The url of the texture atlas data file (json/xml)
* @param [atlasData] {object} A JSON or XML data object.
* @param [format] {number} A value describing the format of the data.
*/
function (key, textureURL, atlasURL, atlasData, format) {
if (typeof atlasURL === "undefined") { atlasURL = null; }
if (typeof atlasData === "undefined") { atlasData = null; }
if (typeof format === "undefined") { format = Loader.TEXTURE_ATLAS_JSON_ARRAY; }
if(this.checkKeyExists(key) === false) {
if(atlasURL !== null) {
// A URL to a json/xml file has been given
this._queueSize++;
this._fileList[key] = {
type: 'textureatlas',
key: key,
url: textureURL,
atlasURL: atlasURL,
data: null,
format: format,
error: false,
loaded: false
};
this._keys.push(key);
} else {
if(format == Loader.TEXTURE_ATLAS_JSON_ARRAY) {
// A json string or object has been given
if(typeof atlasData === 'string') {
atlasData = JSON.parse(atlasData);
}
this._queueSize++;
this._fileList[key] = {
type: 'textureatlas',
key: key,
url: textureURL,
data: null,
atlasURL: null,
atlasData: atlasData,
format: format,
error: false,
loaded: false
};
this._keys.push(key);
} else if(format == Loader.TEXTURE_ATLAS_XML_STARLING) {
// An xml string or object has been given
if(typeof atlasData === 'string') {
var xml;
try {
if(window['DOMParser']) {
var domparser = new DOMParser();
xml = domparser.parseFromString(atlasData, "text/xml");
} else {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = 'false';
xml.loadXML(atlasData);
}
} catch (e) {
xml = undefined;
}
if(!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
} else {
atlasData = xml;
}
}
this._queueSize++;
this._fileList[key] = {
type: 'textureatlas',
key: key,
url: textureURL,
data: null,
atlasURL: null,
atlasData: atlasData,
format: format,
error: false,
loaded: false
};
this._keys.push(key);
}
}
}
};
Loader.prototype.audio = /**
* Add a new audio file loading request.
* @param key {string} Unique asset key of the audio file.
* @param urls {Array} An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ]
* @param autoDecode {bool} When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process.
*/
function (key, urls, autoDecode) {
if (typeof autoDecode === "undefined") { autoDecode = true; }
if(this.checkKeyExists(key) === false) {
this._queueSize++;
this._fileList[key] = {
type: 'audio',
key: key,
url: urls,
data: null,
buffer: null,
error: false,
loaded: false,
autoDecode: autoDecode
};
this._keys.push(key);
}
};
Loader.prototype.text = /**
* Add a new text file loading request.
* @param key {string} Unique asset key of the text file.
* @param url {string} URL of text file.
*/
function (key, url) {
if(this.checkKeyExists(key) === false) {
this._queueSize++;
this._fileList[key] = {
type: 'text',
key: key,
url: url,
data: null,
error: false,
loaded: false
};
this._keys.push(key);
}
};
Loader.prototype.removeFile = /**
* Remove loading request of a file.
* @param key {string} Key of the file you want to remove.
*/
function (key) {
delete this._fileList[key];
};
Loader.prototype.removeAll = /**
* Remove all file loading requests.
*/
function () {
this._fileList = {
};
};
Loader.prototype.start = /**
* Load assets.
*/
function () {
if(this.isLoading) {
return;
}
this.progress = 0;
this.hasLoaded = false;
this.isLoading = true;
this.onLoadStart.dispatch(this.queueSize);
if(this._keys.length > 0) {
this._progressChunk = 100 / this._keys.length;
this.loadFile();
} else {
this.progress = 100;
this.hasLoaded = true;
this.onLoadComplete.dispatch();
}
};
Loader.prototype.loadFile = /**
* Load files. Private method ONLY used by loader.
*/
function () {
var _this = this;
var file = this._fileList[this._keys.pop()];
// Image or Data?
switch(file.type) {
case 'image':
case 'spritesheet':
case 'textureatlas':
file.data = new Image();
file.data.name = file.key;
file.data.onload = function () {
return _this.fileComplete(file.key);
};
file.data.onerror = function () {
return _this.fileError(file.key);
};
file.data.crossOrigin = this.crossOrigin;
file.data.src = this.baseURL + file.url;
break;
case 'audio':
file.url = this.getAudioURL(file.url);
if(file.url !== null) {
// WebAudio or Audio Tag?
if(this.game.sound.usingWebAudio) {
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "arraybuffer";
this._xhr.onload = function () {
return _this.fileComplete(file.key);
};
this._xhr.onerror = function () {
return _this.fileError(file.key);
};
this._xhr.send();
} else if(this.game.sound.usingAudioTag) {
if(this.game.sound.touchLocked) {
// If audio is locked we can't do this yet, so need to queue this load request somehow. Bum.
file.data = new Audio();
file.data.name = file.key;
file.data.preload = 'auto';
file.data.src = this.baseURL + file.url;
this.fileComplete(file.key);
} else {
file.data = new Audio();
file.data.name = file.key;
file.data.onerror = function () {
return _this.fileError(file.key);
};
file.data.preload = 'auto';
file.data.src = this.baseURL + file.url;
file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(file.key), false);
file.data.load();
}
}
}
break;
case 'text':
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "text";
this._xhr.onload = function () {
return _this.fileComplete(file.key);
};
this._xhr.onerror = function () {
return _this.fileError(file.key);
};
this._xhr.send();
break;
}
};
Loader.prototype.getAudioURL = function (urls) {
var extension;
for(var i = 0; i < urls.length; i++) {
extension = urls[i].toLowerCase();
extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1);
if(this.game.device.canPlayAudio(extension)) {
return urls[i];
}
}
return null;
};
Loader.prototype.fileError = /**
* Error occured when load a file.
* @param key {string} Key of the error loading file.
*/
function (key) {
this._fileList[key].loaded = true;
this._fileList[key].error = true;
this.onFileError.dispatch(key);
throw new Error("Phaser.Loader error loading file: " + key);
this.nextFile(key, false);
};
Loader.prototype.fileComplete = /**
* Called when a file is successfully loaded.
* @param key {string} Key of the successfully loaded file.
*/
function (key) {
var _this = this;
if(!this._fileList[key]) {
throw new Error('Phaser.Loader fileComplete invalid key ' + key);
return;
}
this._fileList[key].loaded = true;
var file = this._fileList[key];
var loadNext = true;
switch(file.type) {
case 'image':
this.game.cache.addImage(file.key, file.url, file.data);
break;
case 'spritesheet':
this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax);
break;
case 'textureatlas':
if(file.atlasURL == null) {
this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
} else {
// Load the JSON or XML before carrying on with the next file
loadNext = false;
this._xhr.open("GET", this.baseURL + file.atlasURL, true);
this._xhr.responseType = "text";
if(file.format == Loader.TEXTURE_ATLAS_JSON_ARRAY) {
this._xhr.onload = function () {
return _this.jsonLoadComplete(file.key);
};
} else if(file.format == Loader.TEXTURE_ATLAS_XML_STARLING) {
this._xhr.onload = function () {
return _this.xmlLoadComplete(file.key);
};
}
this._xhr.onerror = function () {
return _this.dataLoadError(file.key);
};
this._xhr.send();
}
break;
case 'audio':
if(this.game.sound.usingWebAudio) {
file.data = this._xhr.response;
this.game.cache.addSound(file.key, file.url, file.data, true, false);
if(file.autoDecode) {
this.game.cache.updateSound(key, 'isDecoding', true);
var that = this;
var key = file.key;
this.game.sound.context.decodeAudioData(file.data, function (buffer) {
if(buffer) {
that.game.cache.decodedSound(key, buffer);
}
});
}
} else {
file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete);
this.game.cache.addSound(file.key, file.url, file.data, false, true);
}
break;
case 'text':
file.data = this._xhr.response;
this.game.cache.addText(file.key, file.url, file.data);
break;
}
if(loadNext) {
this.nextFile(key, true);
}
};
Loader.prototype.jsonLoadComplete = /**
* Successfully loaded a JSON file.
* @param key {string} Key of the loaded JSON file.
*/
function (key) {
var data = JSON.parse(this._xhr.response);
var file = this._fileList[key];
this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
this.nextFile(key, true);
};
Loader.prototype.dataLoadError = /**
* Error occured when load a JSON.
* @param key {string} Key of the error loading JSON file.
*/
function (key) {
var file = this._fileList[key];
file.error = true;
throw new Error("Phaser.Loader dataLoadError: " + key);
this.nextFile(key, true);
};
Loader.prototype.xmlLoadComplete = function (key) {
var atlasData = this._xhr.response;
var xml;
try {
if(window['DOMParser']) {
var domparser = new DOMParser();
xml = domparser.parseFromString(atlasData, "text/xml");
} else {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = 'false';
xml.loadXML(atlasData);
}
} catch (e) {
xml = undefined;
}
if(!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
throw new Error("Phaser.Loader. Invalid XML given");
}
var file = this._fileList[key];
this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
this.nextFile(key, true);
};
Loader.prototype.nextFile = /**
* Handle loading next file.
* @param previousKey {string} Key of previous loaded asset.
* @param success {bool} Whether the previous asset loaded successfully or not.
*/
function (previousKey, success) {
this.progress = Math.round(this.progress + this._progressChunk);
if(this.progress > 100) {
this.progress = 100;
}
this.onFileComplete.dispatch(this.progress, previousKey, success, this._queueSize - this._keys.length, this._queueSize);
if(this._keys.length > 0) {
this.loadFile();
} else {
this.hasLoaded = true;
this.isLoading = false;
this.removeAll();
this.onLoadComplete.dispatch();
}
};
Loader.prototype.checkKeyExists = /**
* Check whether asset exists with a specific key.
* @param key {string} Key of the asset you want to check.
* @return {bool} Return true if exists, otherwise return false.
*/
function (key) {
if(this._fileList[key]) {
return true;
} else {
return false;
}
};
return Loader;
})();
Phaser.Loader = Loader;
})(Phaser || (Phaser = {}));
+641
View File
@@ -0,0 +1,641 @@
/// <reference path="../_definitions.ts" />
/**
* Phaser - Loader
*
* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks.
*/
module Phaser {
export class Loader {
/**
* Loader constructor
*
* @param game {Phaser.Game} Current game instance.
*/
constructor(game: Game) {
this.game = game;
this._keys = [];
this._fileList = {};
this._xhr = new XMLHttpRequest();
this._queueSize = 0;
this.isLoading = false;
this.onFileComplete = new Phaser.Signal;
this.onFileError = new Phaser.Signal;
this.onLoadStart = new Phaser.Signal;
this.onLoadComplete = new Phaser.Signal;
}
/**
* Local reference to Game.
*/
public game: Phaser.Game;
/**
* Array stores assets keys. So you can get that asset by its unique key.
*/
private _keys: string[];
/**
* Contains all the assets file infos.
*/
private _fileList;
/**
* Indicates assets loading progress. (from 0 to 100)
* @type {number}
*/
private _progressChunk: number;
private _xhr: XMLHttpRequest;
/**
* Length of assets queue.
* @type {number}
*/
private _queueSize: number;
/**
* True if the Loader is in the process of loading a queue.
* @type {bool}
*/
public isLoading: bool;
/**
* True if game is completely loaded.
* @type {bool}
*/
public hasLoaded: bool;
/**
* Loading progress (from 0 to 100)
* @type {number}
*/
public progress: number;
/**
* The crossOrigin value applied to loaded images
* @type {string}
*/
public crossOrigin: string = '';
// If you want to append a URL before the path of any asset you can set this here.
// Useful if you need to allow an asset url to be configured outside of the game code.
// MUST have / on the end of it!
public baseURL: string = '';
public onFileComplete: Phaser.Signal;
public onFileError: Phaser.Signal;
public onLoadStart: Phaser.Signal;
public onLoadComplete: Phaser.Signal;
/**
* TextureAtlas data format constants
*/
public static TEXTURE_ATLAS_JSON_ARRAY: number = 0;
public static TEXTURE_ATLAS_JSON_HASH: number = 1;
public static TEXTURE_ATLAS_XML_STARLING: number = 2;
/**
* Reset loader, this will remove all loaded assets.
*/
public reset() {
this._queueSize = 0;
this.isLoading = false;
}
public get queueSize(): number {
return this._queueSize;
}
/**
* Add a new image asset loading request with key and url.
* @param key {string} Unique asset key of this image file.
* @param url {string} URL of image file.
*/
public image(key: string, url: string, overwrite: bool = false) {
if (overwrite == true || this.checkKeyExists(key) == false)
{
this._queueSize++;
this._fileList[key] = { type: 'image', key: key, url: url, data: null, error: false, loaded: false };
this._keys.push(key);
}
}
/**
* Add a new sprite sheet loading request.
* @param key {string} Unique asset key of the sheet file.
* @param url {string} URL of sheet file.
* @param frameWidth {number} Width of each single frame.
* @param frameHeight {number} Height of each single frame.
* @param frameMax {number} How many frames in this sprite sheet.
*/
public spritesheet(key: string, url: string, frameWidth: number, frameHeight: number, frameMax: number = -1) {
if (this.checkKeyExists(key) === false)
{
this._queueSize++;
this._fileList[key] = { type: 'spritesheet', key: key, url: url, data: null, frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, error: false, loaded: false };
this._keys.push(key);
}
}
/**
* Add a new texture atlas loading request.
* @param key {string} Unique asset key of the texture atlas file.
* @param textureURL {string} The url of the texture atlas image file.
* @param [atlasURL] {string} The url of the texture atlas data file (json/xml)
* @param [atlasData] {object} A JSON or XML data object.
* @param [format] {number} A value describing the format of the data.
*/
public atlas(key: string, textureURL: string, atlasURL: string = null, atlasData = null, format:number = Loader.TEXTURE_ATLAS_JSON_ARRAY) {
if (this.checkKeyExists(key) === false)
{
if (atlasURL !== null)
{
// A URL to a json/xml file has been given
this._queueSize++;
this._fileList[key] = { type: 'textureatlas', key: key, url: textureURL, atlasURL: atlasURL, data: null, format: format, error: false, loaded: false };
this._keys.push(key);
}
else
{
if (format == Loader.TEXTURE_ATLAS_JSON_ARRAY)
{
// A json string or object has been given
if (typeof atlasData === 'string')
{
atlasData = JSON.parse(atlasData);
}
this._queueSize++;
this._fileList[key] = { type: 'textureatlas', key: key, url: textureURL, data: null, atlasURL: null, atlasData: atlasData, format: format, error: false, loaded: false };
this._keys.push(key);
}
else if (format == Loader.TEXTURE_ATLAS_XML_STARLING)
{
// An xml string or object has been given
if (typeof atlasData === 'string')
{
var xml;
try
{
if (window['DOMParser'])
{
var domparser = new DOMParser();
xml = domparser.parseFromString(atlasData, "text/xml");
}
else
{
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = 'false';
xml.loadXML(atlasData);
}
}
catch (e)
{
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
{
throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
}
else
{
atlasData = xml;
}
}
this._queueSize++;
this._fileList[key] = { type: 'textureatlas', key: key, url: textureURL, data: null, atlasURL: null, atlasData: atlasData, format: format, error: false, loaded: false };
this._keys.push(key);
}
}
}
}
/**
* Add a new audio file loading request.
* @param key {string} Unique asset key of the audio file.
* @param urls {Array} An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ]
* @param autoDecode {bool} When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process.
*/
public audio(key: string, urls: string[], autoDecode: bool = true) {
if (this.checkKeyExists(key) === false)
{
this._queueSize++;
this._fileList[key] = { type: 'audio', key: key, url: urls, data: null, buffer: null, error: false, loaded: false, autoDecode: autoDecode };
this._keys.push(key);
}
}
/**
* Add a new text file loading request.
* @param key {string} Unique asset key of the text file.
* @param url {string} URL of text file.
*/
public text(key: string, url: string) {
if (this.checkKeyExists(key) === false)
{
this._queueSize++;
this._fileList[key] = { type: 'text', key: key, url: url, data: null, error: false, loaded: false };
this._keys.push(key);
}
}
/**
* Remove loading request of a file.
* @param key {string} Key of the file you want to remove.
*/
public removeFile(key: string) {
delete this._fileList[key];
}
/**
* Remove all file loading requests.
*/
public removeAll() {
this._fileList = {};
}
/**
* Load assets.
*/
public start() {
if (this.isLoading)
{
return;
}
this.progress = 0;
this.hasLoaded = false;
this.isLoading = true;
this.onLoadStart.dispatch(this.queueSize);
if (this._keys.length > 0)
{
this._progressChunk = 100 / this._keys.length;
this.loadFile();
}
else
{
this.progress = 100;
this.hasLoaded = true;
this.onLoadComplete.dispatch();
}
}
/**
* Load files. Private method ONLY used by loader.
*/
private loadFile() {
var file = this._fileList[this._keys.pop()];
// Image or Data?
switch (file.type)
{
case 'image':
case 'spritesheet':
case 'textureatlas':
file.data = new Image();
file.data.name = file.key;
file.data.onload = () => this.fileComplete(file.key);
file.data.onerror = () => this.fileError(file.key);
file.data.crossOrigin = this.crossOrigin;
file.data.src = this.baseURL + file.url;
break;
case 'audio':
file.url = this.getAudioURL(file.url);
if (file.url !== null)
{
// WebAudio or Audio Tag?
if (this.game.sound.usingWebAudio)
{
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "arraybuffer";
this._xhr.onload = () => this.fileComplete(file.key);
this._xhr.onerror = () => this.fileError(file.key);
this._xhr.send();
}
else if (this.game.sound.usingAudioTag)
{
if (this.game.sound.touchLocked)
{
// If audio is locked we can't do this yet, so need to queue this load request somehow. Bum.
file.data = new Audio();
file.data.name = file.key;
file.data.preload = 'auto';
file.data.src = this.baseURL + file.url;
this.fileComplete(file.key);
}
else
{
file.data = new Audio();
file.data.name = file.key;
file.data.onerror = () => this.fileError(file.key);
file.data.preload = 'auto';
file.data.src = this.baseURL + file.url;
file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(file.key), false);
file.data.load();
}
}
}
break;
case 'text':
this._xhr.open("GET", this.baseURL + file.url, true);
this._xhr.responseType = "text";
this._xhr.onload = () => this.fileComplete(file.key);
this._xhr.onerror = () => this.fileError(file.key);
this._xhr.send();
break;
}
}
private getAudioURL(urls): string {
var extension: string;
for (var i = 0; i < urls.length; i++)
{
extension = urls[i].toLowerCase();
extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1);
if (this.game.device.canPlayAudio(extension))
{
return urls[i];
}
}
return null;
}
/**
* Error occured when load a file.
* @param key {string} Key of the error loading file.
*/
private fileError(key: string) {
this._fileList[key].loaded = true;
this._fileList[key].error = true;
this.onFileError.dispatch(key);
throw new Error("Phaser.Loader error loading file: " + key);
this.nextFile(key, false);
}
/**
* Called when a file is successfully loaded.
* @param key {string} Key of the successfully loaded file.
*/
private fileComplete(key: string) {
if (!this._fileList[key])
{
throw new Error('Phaser.Loader fileComplete invalid key ' + key);
return;
}
this._fileList[key].loaded = true;
var file = this._fileList[key];
var loadNext: bool = true;
switch (file.type)
{
case 'image':
this.game.cache.addImage(file.key, file.url, file.data);
break;
case 'spritesheet':
this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax);
break;
case 'textureatlas':
if (file.atlasURL == null)
{
this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
}
else
{
// Load the JSON or XML before carrying on with the next file
loadNext = false;
this._xhr.open("GET", this.baseURL + file.atlasURL, true);
this._xhr.responseType = "text";
if (file.format == Loader.TEXTURE_ATLAS_JSON_ARRAY)
{
this._xhr.onload = () => this.jsonLoadComplete(file.key);
}
else if (file.format == Loader.TEXTURE_ATLAS_XML_STARLING)
{
this._xhr.onload = () => this.xmlLoadComplete(file.key);
}
this._xhr.onerror = () => this.dataLoadError(file.key);
this._xhr.send();
}
break;
case 'audio':
if (this.game.sound.usingWebAudio)
{
file.data = this._xhr.response;
this.game.cache.addSound(file.key, file.url, file.data, true, false);
if (file.autoDecode)
{
this.game.cache.updateSound(key, 'isDecoding', true);
var that = this;
var key = file.key;
this.game.sound.context.decodeAudioData(file.data, function (buffer) {
if (buffer)
{
that.game.cache.decodedSound(key, buffer);
}
});
}
}
else
{
file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete);
this.game.cache.addSound(file.key, file.url, file.data, false, true);
}
break;
case 'text':
file.data = this._xhr.response;
this.game.cache.addText(file.key, file.url, file.data);
break;
}
if (loadNext)
{
this.nextFile(key, true);
}
}
/**
* Successfully loaded a JSON file.
* @param key {string} Key of the loaded JSON file.
*/
private jsonLoadComplete(key: string) {
var data = JSON.parse(this._xhr.response);
var file = this._fileList[key];
this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
this.nextFile(key, true);
}
/**
* Error occured when load a JSON.
* @param key {string} Key of the error loading JSON file.
*/
private dataLoadError(key: string) {
var file = this._fileList[key];
file.error = true;
throw new Error("Phaser.Loader dataLoadError: " + key);
this.nextFile(key, true);
}
private xmlLoadComplete(key: string) {
var atlasData = this._xhr.response;
var xml;
try
{
if (window['DOMParser'])
{
var domparser = new DOMParser();
xml = domparser.parseFromString(atlasData, "text/xml");
}
else
{
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = 'false';
xml.loadXML(atlasData);
}
}
catch (e)
{
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
{
throw new Error("Phaser.Loader. Invalid XML given");
}
var file = this._fileList[key];
this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
this.nextFile(key, true);
}
/**
* Handle loading next file.
* @param previousKey {string} Key of previous loaded asset.
* @param success {bool} Whether the previous asset loaded successfully or not.
*/
private nextFile(previousKey: string, success: bool) {
this.progress = Math.round(this.progress + this._progressChunk);
if (this.progress > 100)
{
this.progress = 100;
}
this.onFileComplete.dispatch(this.progress, previousKey, success, this._queueSize - this._keys.length, this._queueSize);
if (this._keys.length > 0)
{
this.loadFile();
}
else
{
this.hasLoaded = true;
this.isLoading = false;
this.removeAll();
this.onLoadComplete.dispatch();
}
}
/**
* Check whether asset exists with a specific key.
* @param key {string} Key of the asset you want to check.
* @return {bool} Return true if exists, otherwise return false.
*/
private checkKeyExists(key: string): bool {
if (this._fileList[key])
{
return true;
}
else
{
return false;
}
}
}
}