Merge pull request #352 from pandamicro/master

Add audio downloader
This commit is contained in:
pandamicro
2016-02-20 00:45:47 +08:00
10 changed files with 630 additions and 112 deletions
+26 -25
View File
@@ -24,6 +24,8 @@
THE SOFTWARE.
****************************************************************************/
var JS = require('../core/platform/js');
/**
* Audio support in the browser
*
@@ -131,40 +133,39 @@
/**
* Encapsulate DOM and webAudio
*/
cc.Audio = cc._Class.extend({
cc.Audio = function (context, volume, url) {
//TODO Maybe loader shift in will be better
volume: 1,
loop: false,
src: null,
_touch: false,
this.volume = 1;
this.loop = false;
this._touch = false;
_playing: false,
_AUDIO_TYPE: "AUDIO",
_pause: false,
this._playing = false;
this._AUDIO_TYPE = "AUDIO";
this._pause = false;
//Web Audio
_buffer: null,
_currentSource: null,
_startTime: null,
_currentTime: null,
_context: null,
_volume: null,
this._buffer = null;
this._currentSource = null;
this._startTime = null;
this._currentTime = null;
this._context = null;
this._volume = null;
_ignoreEnded: false,
_manualLoop: false,
this._ignoreEnded = false;
this._manualLoop = false;
//DOM Audio
_element: null,
this._element = null;
ctor: function(context, volume, url){
context && (this._context = context);
volume && (this._volume = volume);
if(context && volume){
this._AUDIO_TYPE = "WEBAUDIO";
}
this.src = url;
},
context && (this._context = context);
volume && (this._volume = volume);
if (context && volume) {
this._AUDIO_TYPE = "WEBAUDIO";
}
this.src = url;
};
JS.mixin(cc.Audio.prototype, {
_setBufferCallback: null,
setBuffer: function(buffer){
if(!buffer) return;
+140
View File
@@ -0,0 +1,140 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
var JS = require('../platform/js');
var Pipeline = require('./pipeline');
var Downloader = require('./downloader');
var Loader = require('./loader');
var downloader = new Downloader();
var loader = new Loader();
/**
* Loader for resource loading process. It's a singleton object.
* @class loader
* @static
*/
cc._loader = new Pipeline([
downloader,
loader
]);
JS.mixin(cc._loader, {
/**
* Get XMLHttpRequest.
* @returns {XMLHttpRequest}
*/
getXMLHttpRequest: function () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
},
/**
* Add custom supported types handler or modify existing type handler for download process.
* @example
* cc.loader.addDownloadHandlers({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* @method addDownloadHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addDownloadHandlers: function (extMap) {
downloader.addHandlers(extMap);
},
/**
* Add custom supported types handler or modify existing type handler for load process.
* @example
* cc.loader.addLoadHandlers({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* @method addLoadHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addLoadHandlers: function (extMap) {
loader.addHandlers(extMap);
},
/**
* Load resources with a progression callback and a complete callback.
* The progression callback is the same as Pipeline's {{#crossLink "Pipeline/onProgress:method"}}onProgress{{/crossLink}}
* The complete callback is the same as Pipeline's {{#crossLink "Pipeline/onComplete:method"}}onComplete{{/crossLink}}
*
* @method load
* @param {Array} resources - Url list in an array
* @param {[Function]} progressCallback - Callback invoked when progression change
* @param {Function} completeCallback - Callback invoked when all resources loaded
*/
load: function(resources, progressCallback, completeCallback) {
if (completeCallback === undefined) {
completeCallback = progressCallback;
progressCallback = null;
}
this.onProgress = progressCallback;
this.onComplete = completeCallback;
this.flowIn(resources);
},
/**
* Get resource data by url.
*
* @method getRes
* @param {String} url
* @returns {*}
*/
getRes: function (url) {
var item = this._items[url];
if (item.complete) {
return item.content;
}
else {
return null;
}
},
/**
* Release the cache of resource by url.
*
* @method release
* @param {String} url
*/
release: function (url) {
this.removeItem(url);
},
/**
* Resource cache of all resources.
*
* @method releaseAll
*/
releaseAll: function () {
this.clear();
}
});
module.exports = cc._loader;
@@ -0,0 +1,308 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
var Path = require('../utils/CCPath');
var Sys = require('../platform/CCSys');
var Pipeline = require('./pipeline');
require('../../audio/CCAudio');
var __audioSupport;
/**
* Audio support in the browser
*
* MULTI_CHANNEL : Multiple audio while playing - If it doesn't, you can only play background music
* WEB_AUDIO : Support for WebAudio - Support W3C WebAudio standards, all of the audio can be played
* AUTOPLAY : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay
* REPLAY_AFTER_TOUCH : The first music will fail, must be replay after touchstart
* USE_EMPTIED_EVENT : Whether to use the emptied event to replace load callback
* DELAY_CREATE_CTX : delay created the context object - only webAudio
* NEED_MANUAL_LOOP : WebAudio loop attribute failure, need to manually perform loop
*
* May be modifications for a few browser version
*/
(function(){
var DEBUG = false;
var version = Sys.browserVersion;
// check if browser supports Web Audio
// check Web Audio's context
var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
var supportTable = {
'common' : {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true }
};
supportTable[Sys.BROWSER_TYPE_IE] = {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true, USE_EMPTIED_EVENT: true};
// ANDROID //
supportTable[Sys.BROWSER_TYPE_ANDROID] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false};
supportTable[Sys.BROWSER_TYPE_CHROME] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false};
supportTable[Sys.BROWSER_TYPE_FIREFOX] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: true , DELAY_CREATE_CTX: true};
supportTable[Sys.BROWSER_TYPE_UC] = {MULTI_CHANNEL: true , WEB_AUDIO: false, AUTOPLAY: false};
supportTable[Sys.BROWSER_TYPE_QQ] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[Sys.BROWSER_TYPE_OUPENG] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[Sys.BROWSER_TYPE_WECHAT] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[Sys.BROWSER_TYPE_360] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[Sys.BROWSER_TYPE_MIUI] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[Sys.BROWSER_TYPE_LIEBAO] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[Sys.BROWSER_TYPE_SOUGOU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
//'Baidu' browser can automatically play
//But because it may be play failed, so need to replay and auto
supportTable[Sys.BROWSER_TYPE_BAIDU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[Sys.BROWSER_TYPE_BAIDU_APP]= {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
// APPLE //
supportTable[Sys.BROWSER_TYPE_SAFARI] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false, webAudioCallback: function(realUrl){
document.createElement('audio').src = realUrl;
}};
if(Sys.isMobile){
if(Sys.os !== Sys.OS_IOS)
__audioSupport = supportTable[Sys.browserType] || supportTable['common'];
else
__audioSupport = supportTable[Sys.BROWSER_TYPE_SAFARI];
}else{
switch(Sys.browserType){
case Sys.BROWSER_TYPE_IE:
__audioSupport = supportTable[Sys.BROWSER_TYPE_IE];
break;
case Sys.BROWSER_TYPE_FIREFOX:
__audioSupport = supportTable[Sys.BROWSER_TYPE_FIREFOX];
break;
default:
__audioSupport = supportTable['common'];
}
}
///////////////////////////
// Browser compatibility//
///////////////////////////
if(version){
switch(Sys.browserType){
case Sys.BROWSER_TYPE_CHROME:
version = parseInt(version);
if(version < 30){
__audioSupport = {MULTI_CHANNEL: false , WEB_AUDIO: true , AUTOPLAY: false};
}else if(version === 42){
__audioSupport.NEED_MANUAL_LOOP = true;
}
break;
case Sys.BROWSER_TYPE_MIUI:
if(Sys.isMobile){
version = version.match(/\d+/g);
if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){
__audioSupport.AUTOPLAY = false;
}
}
break;
}
}
if(DEBUG){
setTimeout(function(){
cc.log('browse type: ' + Sys.browserType);
cc.log('browse version: ' + version);
cc.log('MULTI_CHANNEL: ' + __audioSupport.MULTI_CHANNEL);
cc.log('WEB_AUDIO: ' + __audioSupport.WEB_AUDIO);
cc.log('AUTOPLAY: ' + __audioSupport.AUTOPLAY);
}, 0);
}
window.__audioSupport = __audioSupport;
})();
var context;
try {
if (__audioSupport.WEB_AUDIO) {
context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
if(__audioSupport.DELAY_CREATE_CTX) {
setTimeout(function(){ context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0);
}
}
} catch(error) {
__audioSupport.WEB_AUDIO = false;
cc.log("browser don't support web audio");
}
var formatSupport = [];
(function(){
var audio = document.createElement('audio');
if(audio.canPlayType) {
var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"');
if (ogg && ogg !== '') formatSupport.push('.ogg');
var mp3 = audio.canPlayType('audio/mpeg');
if (mp3 && mp3 !== '') formatSupport.push('.mp3');
var wav = audio.canPlayType('audio/wav; codecs="1"');
if (wav && wav !== '') formatSupport.push('.wav');
var mp4 = audio.canPlayType('audio/mp4');
if (mp4 && mp4 !== '') formatSupport.push('.mp4');
var m4a = audio.canPlayType('audio/x-m4a');
if (m4a && m4a !== '') formatSupport.push('.m4a');
}
})();
function loadAudioFromExtList (url, typeList, audio, cb){
if(typeList.length === 0){
var ERRSTR = 'can not found the resource of audio! Last match url is : ';
ERRSTR += url.replace(/\.(.*)?$/, '(');
formatSupport.forEach(function(ext){
ERRSTR += ext + '|';
});
ERRSTR = ERRSTR.replace(/\|$/, ')');
return cb({status: 520, errorMessage: ERRSTR}, null);
}
url = Path.changeExtname(url, typeList.splice(0, 1));
if (__audioSupport.WEB_AUDIO) {//Buffer
if (__audioSupport.webAudioCallback) {
__audioSupport.webAudioCallback(url);
}
var request = Pipeline.getXMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function () {
context['decodeAudioData'](request.response, function (buffer) {
//success
audio.setBuffer(buffer);
cb(null, audio);
}, function() {
//error
loadAudioFromExtList(url, typeList, audio, cb);
});
};
request.onerror = function () {
cb({status: 520, errorMessage: ERRSTR}, null);
};
request.send();
} else {//DOM
var element = document.createElement('audio');
var cbCheck = false;
var termination = false;
var timer = setTimeout(function () {
if (element.readyState === 0) {
emptied();
} else {
termination = true;
element.pause();
document.body.removeChild(element);
cb('Audio load timeout : ' + url, audio);
}
}, 8000);
var success = function () {
if (!cbCheck) {
//element.pause();
try {
element.currentTime = 0;
element.volume = 1;
} catch (e) {}
document.body.removeChild(element);
audio.setElement(element);
element.removeEventListener('canplaythrough', success, false);
element.removeEventListener('error', failure, false);
element.removeEventListener('emptied', emptied, false);
!termination && cb(null, audio);
cbCheck = true;
clearTimeout(timer);
}
};
var failure = function(){
if (!cbCheck) return;
//element.pause();
document.body.removeChild(element);
element.removeEventListener('canplaythrough', success, false);
element.removeEventListener('error', failure, false);
element.removeEventListener('emptied', emptied, false);
!termination && loadAudioFromExtList(url, typeList, audio, cb);
cbCheck = true;
clearTimeout(timer);
};
var emptied = function(){
termination = true;
success();
cb(null, audio);
};
element.addEventListener('canplaythrough', success, false);
element.addEventListener('error', failure, false);
if(__audioSupport.USE_EMPTIED_EVENT)
element.addEventListener('emptied', emptied, false);
element.src = url;
document.body.appendChild(element);
element.volume = 0;
//some browsers cannot pause(qq 6.1)
//element.play();
}
}
function downloadAudio (url, callback) {
if (formatSupport.length === 0) {
return callback( new Error('Audio Downloader: audio not supported on this browser!') );
}
var i,
extname = Path.extname(url),
typeList = [extname],
audio;
// Generate all types
for (i = 0; i < formatSupport.length; i++) {
if (extname !== formatSupport[i]) {
typeList.push(formatSupport[i]);
}
}
if (__audioSupport.WEB_AUDIO) {
try {
var volume = context['createGain']();
volume['gain'].value = 1;
volume['connect'](context['destination']);
audio = new cc.Audio(context, volume, url);
if (__audioSupport.NEED_MANUAL_LOOP) {
audio._manualLoop = true;
}
} catch(err) {
__audioSupport.WEB_AUDIO = false;
cc.warn('The current browser don\'t support web audio');
audio = new cc.Audio(null, null, url);
}
} else {
audio = new cc.Audio(null, null, url);
}
loadAudioFromExtList(url, typeList, audio, callback);
}
module.exports = downloadAudio;
+19 -13
View File
@@ -25,6 +25,7 @@
var JS = require('../platform/js');
var Pipeline = require('./pipeline');
var downloadAudio = require('./audio-downloader');
// var downloadBinary = require('binary-downloader');
var _noCacheRex = /\?/;
@@ -38,10 +39,6 @@ function urlAppendTimestamp (url) {
return url;
}
function getXMLHttpRequest () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP');
}
function downloadScript (url, callback, isAsync) {
var d = document, s = document.createElement('script');
s.async = isAsync;
@@ -64,7 +61,7 @@ function downloadScript (url, callback, isAsync) {
}
function downloadText (url, callback) {
var xhr = getXMLHttpRequest(),
var xhr = Pipeline.getXMLHttpRequest(),
errInfo = 'Load ' + url + ' failed!',
navigator = window.navigator;
@@ -104,7 +101,7 @@ function downloadText (url, callback) {
}
function downloadTextSync (url) {
var xhr = getXMLHttpRequest();
var xhr = Pipeline.getXMLHttpRequest();
xhr.open('GET', url, false);
if (/msie/i.test(window.navigator.userAgent) && !/opera/i.test(window.navigator.userAgent)) {
// IE-specific logic here
@@ -175,11 +172,11 @@ var defaultMap = {
'webp' : downloadImage,
// Audio
// "mp3",
// "ogg",
// "wav",
// "mp4",
// "m4a",
'mp3' : downloadAudio,
'ogg' : downloadAudio,
'wav' : downloadAudio,
'mp4' : downloadAudio,
'm4a' : downloadAudio,
// Txt
'txt' : downloadText,
@@ -221,16 +218,25 @@ var defaultMap = {
* });
*
* @method Downloader
* @param {Object} extMap
* @param {Object} extMap Custom supported types with corresponded handler
*/
var Downloader = function (extMap) {
this.id = 'Downloader';
this.async = true;
this.pipeline = null;
this.extMap = JS.addon(extMap, defaultMap);
this.addHandlers(extMap);
};
JS.mixin(Downloader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
this.extMap = JS.addon(extMap, defaultMap);
},
handle: function (item, callback) {
var downloadFunc = this.extMap[item.type] || this.extMap['default'];
downloadFunc.call(this, item.src, function (err, result) {
+3
View File
@@ -1,5 +1,8 @@
require('./audio-downloader');
require('./downloader');
require('./loader');
require('./loading-items');
require('./pipeline');
require('./CCLoader');
+11 -8
View File
@@ -97,12 +97,6 @@ var defaultMap = {
'svg' : loadFont,
'ttc' : loadFont,
// "mp3",
// "ogg",
// "wav",
// "mp4",
// "m4a",
'default' : loadNothing
};
@@ -127,16 +121,25 @@ var defaultMap = {
* });
*
* @method Loader
* @param {Object} extMap
* @param {Object} extMap Custom supported types with corresponded handler
*/
var Loader = function (extMap) {
this.id = 'Loader';
this.async = true;
this.pipeline = null;
this.extMap = JS.addon(extMap, defaultMap);
this.addHandlers(extMap);
};
JS.mixin(Loader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
this.extMap = JS.addon(extMap, defaultMap);
},
handle: function (item, callback) {
var loadFunc = this.extMap[item.type] || this.extMap['default'];
loadFunc.call(this, item, function (err, result) {
+37 -7
View File
@@ -50,6 +50,13 @@ var LoadingItems = function () {
*/
this.map = {};
/**
* The map of completed items
* @property completed
* @type {Object}
*/
this.completed = {};
/**
* Total count of all items
* @property totalCount
@@ -67,17 +74,18 @@ var LoadingItems = function () {
JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, {
append: function (items) {
var count = 0;
var list = [];
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var url = item.src;
// No duplicated url
if (!this.map[url]) {
this.map[item.src] = item;
count++;
list.push(item);
}
}
this.totalCount += count;
this.totalCount += list.length;
return list;
},
/**
@@ -93,13 +101,35 @@ JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, {
* @return {Boolean}
*/
isItemCompleted: function (url) {
var item = this.map[url];
return item && item.complete;
return !!this.completed[url];
},
complete: function (item) {
if (this.map[item.src] === item) {
/**
* Check whether an item exists
* @return {Boolean}
*/
exists: function (url) {
return !!this.map[url];
},
/**
* Remove an item, can only remove completed item, ongoing item can not be removed
* @param {String} url
*/
remove: function (url) {
if (this.completed[url]) {
delete this.completed[url];
delete this.map[url];
this.completedCount--;
this.totalCount--;
}
},
complete: function (url) {
if (this.map[url] && !this.completed[url]) {
var item = this.map[url];
item.complete = true;
this.completed[url] = item;
this.completedCount++;
}
}
+59 -16
View File
@@ -143,6 +143,10 @@ function createItem (url) {
return result;
}
function getXMLHttpRequest () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP');
}
/**
* A pipeline describes a sequence of manipulations, each manipulation is called a pipe.
* It's designed for loading process, so items should be urls, and the url will be the identity of each item during the process.
@@ -194,6 +198,7 @@ var Pipeline = function (pipes) {
};
Pipeline.ItemState = new cc.Enum(ItemState);
Pipeline.getXMLHttpRequest = getXMLHttpRequest;
JS.mixin(Pipeline.prototype, {
/**
@@ -217,10 +222,6 @@ JS.mixin(Pipeline.prototype, {
* @return {Array} Items accepted by the pipeline
*/
flowIn: function (urlList) {
if (!this._flowing) {
this._flowing = true;
}
var items = [], i, url, item;
for (i = 0; i < urlList.length; ++i) {
url = urlList[i];
@@ -232,15 +233,24 @@ JS.mixin(Pipeline.prototype, {
throw new Error('Pipeline flowIn: Invalid url: ' + (url.src || url));
}
}
this._items.append(items);
var acceptedItems = this._items.append(items);
// Manually complete
if ((this._pipes.length | acceptedItems.length) === 0) {
this.complete();
return acceptedItems;
}
if (!this._flowing) {
this._flowing = true;
}
// Flow in after appended to loading items
if (this._pipes.length > 0) {
for (i = 0; i < items.length; i++) {
this._pipes[0].flowIn(items[i]);
for (i = 0; i < acceptedItems.length; i++) {
this._pipes[0].flowIn(acceptedItems[i]);
}
}
return items;
return acceptedItems;
},
/**
@@ -273,7 +283,7 @@ JS.mixin(Pipeline.prototype, {
// Add loaded listeners
for (var i = 0; i < urlList.length; ++i) {
var url = urlList[i].src || urlList[i];
if (isUrlValid(url)) {
if (isUrlValid(url) && !this._items.exists(url)) {
this._items.add(url, loadedCheck);
checker[url] = null;
}
@@ -281,6 +291,14 @@ JS.mixin(Pipeline.prototype, {
return this.flowIn(urlList);
},
complete: function () {
// All completed
if (this._items.isCompleted()) {
this._flowing = false;
this.onComplete && this.onComplete(this._items);
}
},
flowOut: function (item) {
var url = item.src;
var items = this._items;
@@ -290,15 +308,11 @@ JS.mixin(Pipeline.prototype, {
return;
}
items.complete(item);
items.complete(item.src);
this.onProgress && this.onProgress(this._items.completedCount, this._items.totalCount, item);
this.onProgress && this.onProgress(items.completedCount, items.totalCount, item);
// All completed
if (this._items.isCompleted()) {
this._flowing = false;
this.onComplete && this.onComplete(this._items);
}
this.complete();
items.invoke(url, item);
},
@@ -334,6 +348,34 @@ JS.mixin(Pipeline.prototype, {
return this._flowing;
},
/**
* Returns all items in pipeline.
* @method getItems
* @return {LoadingItems}
*/
getItems: function () {
return this._items;
},
/**
* Removes an item in pipeline, no matter it's in progress or completed.
* @method removeItem
* @return {Boolean} succeed or not
*/
removeItem: function (url) {
var item = this._items[url];
if (item) {
if (!item.complete) {
item.error = new Error('Canceled manually');
this.flowOut(item);
}
this._items.remove(url);
}
else {
return false;
}
},
/**
* Clear the current pipeline, this function will clean up the items.
* @method clear
@@ -345,6 +387,7 @@ JS.mixin(Pipeline.prototype, {
var item = items[url];
if (!item.complete) {
item.error = new Error('Canceled manually');
this.flowOut(item);
}
}
}
-2
View File
@@ -144,8 +144,6 @@ var srcs = [
'./cocos2d/parallax/CCParallaxNode.js',
'./cocos2d/parallax/CCParallaxNodeRenderCmd.js',
'./cocos2d/audio/CCAudio.js',
'./extensions/ccpool/CCPool.js',
'./cocos2d/physics/CCPhysicsDebugNode.js',
+27 -41
View File
@@ -1,22 +1,8 @@
largeModule('Loader');
var loader = cc._loader;
asyncTest('Load', function () {
var loader = new cc.Pipeline([
new cc.Pipeline.Downloader(),
new cc.Pipeline.Loader()
]);
loader.load = function (resources, progressCallback, completeCallback) {
if (completeCallback === undefined) {
completeCallback = progressCallback;
progressCallback = null;
}
this.onProgress = progressCallback;
this.onComplete = completeCallback;
this.flowIn(resources);
};
var image1 = assetDir + '/button.png';
var json1 = assetDir + '/library/12/123200.json';
var json2 = assetDir + '/library/deferred-loading/74/748321.json';
@@ -27,7 +13,6 @@ asyncTest('Load', function () {
];
loader.load(resources, function (completedCount, totalCount, item) {
console.log((100 * completedCount / totalCount).toFixed(2) + '%');
if (item.src === image1) {
ok(item.content instanceof cc.Texture2D, 'image url\'s result should be Texture2D');
}
@@ -42,6 +27,10 @@ asyncTest('Load', function () {
}
}, function (items) {
ok(items.isCompleted(), 'Able to load all resources');
loader.releaseAll();
strictEqual(Object.keys(this.getItems().map).length, 0, 'should clear loading items after releaseAll called');
clearTimeout(timeoutId);
start();
});
@@ -74,44 +63,35 @@ asyncTest('Load with dependencies', function () {
});
}
var loader = new cc.Pipeline([
new cc.Pipeline.Downloader(),
new cc.Pipeline.Loader({
'deps': loadWithDeps
})
]);
loader.load = function (resources, progressCallback, completeCallback) {
if (completeCallback === undefined) {
completeCallback = progressCallback;
progressCallback = null;
}
this.onProgress = new Callback(progressCallback).enable();
this.onComplete = completeCallback;
this.flowIn(resources);
};
loader.addLoadHandlers({
'deps': loadWithDeps
});
var json1 = {
src: assetDir + '/library/65/6545543',
type: 'deps'
};
var json2 = assetDir + '/library/deferred-loading/74/748321.json';
var audio = assetDir + '/background.mp3';
var resources = [
json1,
json2,
audio
];
var total = resources.length + 3;
var dep1Loaded = false;
var dep2Loaded = false;
var dep3Loaded = false;
loader.load(resources, function (completedCount, totalCount, item) {
console.log((100 * completedCount / totalCount).toFixed(2) + '%');
var items = loader.getItems();
var progressCallback = new Callback(function (completedCount, totalCount, item) {
if (item.src === json1.src) {
var depsLoaded = this._items.isItemCompleted(dep1) &&
this._items.isItemCompleted(dep2) &&
this._items.isItemCompleted(dep3);
var depsLoaded = items.isItemCompleted(dep1) &&
items.isItemCompleted(dep2) &&
items.isItemCompleted(dep3);
ok(depsLoaded, 'should load all dependencies before complete parent resources');
var depsCallbackCalled = dep1Loaded && dep2Loaded && dep3Loaded;
ok(depsCallbackCalled, 'should call all dependencies complete callback before complete parent resources');
@@ -132,12 +112,18 @@ asyncTest('Load with dependencies', function () {
dep3Loaded = true;
ok(item.content instanceof cc.Texture2D, 'image url\'s result should be Texture2D');
}
else if (item.src === audio) {
// Test environment doesn't support audio
ok((item.content instanceof cc.Audio) || true, 'audio url\'s result should be Audio');
}
else {
ok(false, 'should not load an unknown url: ' + item.src);
}
}, function (items) {
}).enable();
loader.load(resources, progressCallback, function (items) {
ok(items.isCompleted(), 'be able to load all resources');
this.onProgress.expect(5, 'should call 5 times progress callback for 5 resources');
progressCallback.expect(total, 'should call ' + total + ' times progress callback for 5 resources');
clearTimeout(timeoutId);
start();
});