Merge pull request #362 from pandamicro/master

Replace cc.loader with pipeline loader
This commit is contained in:
pandamicro
2016-02-25 13:40:40 +08:00
56 changed files with 1508 additions and 3366 deletions
+4 -4
View File
@@ -192,8 +192,8 @@ cc.formatStr = function(){
};
require('../cocos2d/core/utils');
require('../cocos2d/core/platform/CCLoader');
require('../cocos2d/core/platform/CCSys');
require('../cocos2d/core/load-pipeline/CCLoader');
require('../cocos2d/core/CCGame');
@@ -276,7 +276,7 @@ function _load(config) {
} else {
// Load cocos modules
var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json");
loader.loadJson(ccModulesPath, function (err, modulesJson) {
loader.load(ccModulesPath, function (err, modulesJson) {
if (err) throw new Error(err);
var modules = config["modules"] || [];
var moduleMap = modulesJson["module"];
@@ -287,8 +287,8 @@ function _load(config) {
var arr = _getJsListOfModule(moduleMap, modules[i], engineDir);
if (arr) jsList = jsList.concat(arr);
}
cc.loader.loadJsWithImg(jsList, function (err) {
if (err) throw err;
loader.load(jsList, function (err) {
if (err) throw new Error(JSON.stringify(err));
_afterEngineLoaded(config);
});
});
+18 -302
View File
@@ -26,114 +26,6 @@
var JS = require('../core/platform/js');
/**
* 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
*/
var __audioSupport;
(function(){
var DEBUG = false;
var sys = cc.sys;
var version = sys.browserVersion;
var supportTable = {
"common" : {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true }
};
// check if browser supports Web Audio
// check Web Audio's context
var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
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(cc.sys.isMobile){
if(cc.sys.os !== cc.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(cc.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;
})();
/**
* Encapsulate DOM and webAudio
*/
@@ -445,190 +337,6 @@ JS.mixin(cc.Audio.prototype, {
SWB = polyfill.MULTI_CHANNEL,
SWC = polyfill.AUTOPLAY;
var support = [];
(function(){
var audio = document.createElement("audio");
if(audio.canPlayType) {
var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"');
if (ogg && ogg !== "") support.push(".ogg");
var mp3 = audio.canPlayType("audio/mpeg");
if (mp3 && mp3 !== "") support.push(".mp3");
var wav = audio.canPlayType('audio/wav; codecs="1"');
if (wav && wav !== "") support.push(".wav");
var mp4 = audio.canPlayType("audio/mp4");
if (mp4 && mp4 !== "") support.push(".mp4");
var m4a = audio.canPlayType("audio/x-m4a");
if (m4a && m4a !== "") support.push(".m4a");
}
})();
try{
if(SWA){
var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
if(polyfill.DELAY_CREATE_CTX)
setTimeout(function(){ context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0);
}
}catch(error){
SWA = false;
cc.log("browser don't support web audio");
}
var loader = {
cache: {},
load: function(realUrl, url, res, cb){
if(support.length === 0)
return cb("can not support audio!");
var i;
if(cc.loader.audioPath)
realUrl = cc.path.join(cc.loader.audioPath, realUrl);
var extname = cc.path.extname(realUrl);
var typeList = [extname];
for(i=0; i<support.length; i++){
if(extname !== support[i]){
typeList.push(support[i]);
}
}
var audio;
if(loader.cache[url])
return cb(null, loader.cache[url]);
if(SWA){
try{
var volume = context["createGain"]();
volume["gain"].value = 1;
volume["connect"](context["destination"]);
audio = new cc.Audio(context, volume, realUrl);
if(polyfill.NEED_MANUAL_LOOP)
audio._manualLoop = true;
}catch(err){
SWA = false;
cc.log("browser don't support web audio");
audio = new cc.Audio(null, null, realUrl);
}
}else{
audio = new cc.Audio(null, null, realUrl);
}
this.loadAudioFromExtList(realUrl, typeList, audio, cb);
loader.cache[url] = audio;
},
loadAudioFromExtList: function(realUrl, typeList, audio, cb){
if(typeList.length === 0){
var ERRSTR = "can not found the resource of audio! Last match url is : ";
ERRSTR += realUrl.replace(/\.(.*)?$/, "(");
support.forEach(function(ext){
ERRSTR += ext + "|";
});
ERRSTR = ERRSTR.replace(/\|$/, ")");
return cb({status:520, errorMessage:ERRSTR}, null);
}
realUrl = cc.path.changeExtname(realUrl, typeList.splice(0, 1));
if(SWA){//Buffer
if(polyfill.webAudioCallback)
polyfill.webAudioCallback(realUrl);
var request = new XMLHttpRequest();
request.open("GET", realUrl, true);
request.responseType = "arraybuffer";
// Our asynchronous callback
request.onload = function () {
context["decodeAudioData"](request.response, function(buffer){
//success
audio.setBuffer(buffer);
cb(null, audio);
}, function(){
//error
loader.loadAudioFromExtList(realUrl, 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 : " + realUrl, audio);
}
}, 10000);
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 && loader.loadAudioFromExtList(realUrl, 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(polyfill.USE_EMPTIED_EVENT)
element.addEventListener("emptied", emptied, false);
element.src = realUrl;
document.body.appendChild(element);
element.volume = 0;
//some browsers cannot pause(qq 6.1)
//element.play();
}
}
};
cc.loader.register(["mp3", "ogg", "wav", "mp4", "m4a"], loader);
/**
* cc.audioEngine is the singleton object, it provide simple audio APIs.
* @class audioEngine
@@ -661,10 +369,16 @@ JS.mixin(cc.Audio.prototype, {
if(bgMusic && bgMusic.src !== url && bgMusic.getPlaying()){
bgMusic.stop();
}
var audio = loader.cache[url];
var audio = cc.loader.getRes(url);
if(!audio){
cc.loader.load(url);
audio = loader.cache[url];
var self = this;
cc.loader.load(url, function () {
audio = cc.loader.getRes(url);
audio.play(0, loop);
audio.setVolume(self._musicVolume);
self._currMusic = audio;
});
return;
}
audio.play(0, loop);
audio.setVolume(this._musicVolume);
@@ -811,14 +525,13 @@ JS.mixin(cc.Audio.prototype, {
effectList = this._audioPool[url] = [];
}
var i;
for(i=0; i<effectList.length; i++){
for(var i=0; i<effectList.length; i++){
if(!effectList[i].getPlaying()){
break;
}
}
var audio;
if(effectList[i]){
audio = effectList[i];
audio.setVolume(this._effectVolume);
@@ -826,10 +539,14 @@ JS.mixin(cc.Audio.prototype, {
}else if(!SWA && i > this._maxAudioInstance){
cc.log("Error: %s greater than %d", url, this._maxAudioInstance);
}else{
var audio = loader.cache[url];
audio = cc.loader.getRes(url);
if(!audio){
cc.loader.load(url);
audio = loader.cache[url];
var item = cc.loader.getItems().map[url];
audio = item ? item.content : null;
if (!audio) {
return;
}
}
audio = audio.cloneNode();
audio.setVolume(this._effectVolume);
@@ -988,7 +705,6 @@ JS.mixin(cc.Audio.prototype, {
var pool = this._audioPool[url];
if(pool) pool.length = 0;
delete this._audioPool[url];
delete loader.cache[url];
},
/**
@@ -1056,4 +772,4 @@ JS.mixin(cc.Audio.prototype, {
}, 150);
}
})(__audioSupport);
})(cc.sys.__audioSupport);
+3 -43
View File
@@ -617,43 +617,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
}
},
// load raw assets
_loadRawAssets: function (assetObjects, done) {
var urls = assetObjects.map(function (asset) {
return asset.url;
});
//var info = 'preload ' + urls;
//console.time(info);
// currently cocos jsb 3.3 not support preload too much assets
// so we divide assets to 30 a group
var index = 0;
var count = 30;
var total = urls.length;
function preload () {
if (index + count > total) {
// the last time
count = total - index;
}
var assets = urls.slice(index, count);
index += count;
if (index < total) {
cc.loader.load(assets, preload);
}
else {
//console.timeEnd(info);
done();
}
}
preload();
},
/**
* Loads the scene by its uuid.
* @method _loadSceneByUuid
@@ -664,7 +627,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
*/
_loadSceneByUuid: function (uuid, onLaunched, onUnloaded) {
//cc.AssetLibrary.unloadAsset(uuid); // force reload
var handle = cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) {
cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) {
var self = cc.director;
var scene;
if (error) {
@@ -684,10 +647,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
scene = sceneAsset;
}
if (scene instanceof cc.Scene) {
self._loadRawAssets(handle.assetsNeedPostLoad,
function () {
self.runScene(scene, onUnloaded);
});
self.runScene(scene, onUnloaded);
}
else {
error = 'The asset ' + uuid + ' is not a scene';
@@ -699,7 +659,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
if (onLaunched) {
onLaunched(error, scene);
}
}, { recordAssets: true });
});
},
/**
+3 -3
View File
@@ -259,9 +259,9 @@ var game = /** @lends cc.game# */{
// Load game scripts
var jsList = config[CONFIG_KEY.jsList];
if (jsList) {
cc.loader.loadJsWithImg(jsList, function (err) {
if (err) throw new Error(err);
if (jsList && jsList.length > 0) {
cc.loader.load(jsList, function (err) {
if (err) throw new Error(JSON.stringify(err));
self._prepared = true;
if (cb) cb();
});
+1 -3
View File
@@ -336,8 +336,6 @@ _ccsg.Label = _ccsg.Node.extend({
this.emit('load');
return;
}
//add resource path
fontHandle = cc.path.join(cc.loader.resPath, fontHandle);
this._isUseSystemFont = false;
if (extName === ".ttf") {
@@ -1100,7 +1098,7 @@ cc.BMFontHelper = {
cc.log("_ccsg.Label._initBMFontWithString(): Impossible to create font. Please check file");
}
self._config = results[0];
self._config = results.getContent(self._fontHandle);
self._createFontChars();
texture = cc.textureCache.addImage(self._config.atlasName);
var locIsLoaded = texture.isLoaded();
-103
View File
@@ -1,103 +0,0 @@
cc._fntLoader = {
INFO_EXP: /info [^\n]*(\n|$)/gi,
COMMON_EXP: /common [^\n]*(\n|$)/gi,
PAGE_EXP: /page [^\n]*(\n|$)/gi,
CHAR_EXP: /char [^\n]*(\n|$)/gi,
KERNING_EXP: /kerning [^\n]*(\n|$)/gi,
ITEM_EXP: /\w+=[^ \r\n]+/gi,
INT_EXP: /^[\-]?\d+$/,
_parseStrToObj: function (str) {
var arr = str.match(this.ITEM_EXP);
var obj = {};
if (arr) {
for (var i = 0, li = arr.length; i < li; i++) {
var tempStr = arr[i];
var index = tempStr.indexOf("=");
var key = tempStr.substring(0, index);
var value = tempStr.substring(index + 1);
if (value.match(this.INT_EXP)) value = parseInt(value);
else if (value[0] === '"') value = value.substring(1, value.length - 1);
obj[key] = value;
}
}
return obj;
},
/**
* Parse Fnt string.
* @param fntStr
* @param url
* @returns {{}}
*/
parseFnt: function (fntStr, url) {
var self = this, fnt = {};
//padding
var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]);
var paddingArr = infoObj["padding"].split(",");
var padding = {
left: parseInt(paddingArr[0]),
top: parseInt(paddingArr[1]),
right: parseInt(paddingArr[2]),
bottom: parseInt(paddingArr[3])
};
//common
var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]);
fnt.commonHeight = commonObj["lineHeight"];
//font size
fnt.fontSize = infoObj["size"];
if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
var texSize = cc.configuration.getMaxTextureSize();
if (commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height)
cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported");
}
if (commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page");
//page
var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]);
if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found");
fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]);
//char
var charLines = fntStr.match(self.CHAR_EXP);
var fontDefDictionary = fnt.fontDefDictionary = {};
for (var i = 0, li = charLines.length; i < li; i++) {
var charObj = self._parseStrToObj(charLines[i]);
var charId = charObj["id"];
fontDefDictionary[charId] = {
rect: {x: charObj["x"], y: charObj["y"], width: charObj["width"], height: charObj["height"]},
xOffset: charObj["xoffset"],
yOffset: charObj["yoffset"],
xAdvance: charObj["xadvance"]
};
}
//kerning
var kerningDict = fnt.kerningDict = {};
var kerningLines = fntStr.match(self.KERNING_EXP);
if (kerningLines) {
for (var i = 0, li = kerningLines.length; i < li; i++) {
var kerningObj = self._parseStrToObj(kerningLines[i]);
kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"];
}
}
return fnt;
},
/**
* load the fnt
* @param realUrl
* @param url
* @param res
* @param cb
*/
load: function (realUrl, url, res, cb) {
var self = this;
cc.loader.loadTxt(realUrl, function (err, txt) {
if (err) return cb(err);
cb(null, self.parseFnt(txt, url));
});
}
};
cc.loader.register(["fnt"], cc._fntLoader);
+88 -11
View File
@@ -35,20 +35,36 @@ var loader = new Loader();
* @class loader
* @static
*/
cc._loader = new Pipeline([
cc.loader = new Pipeline([
downloader,
loader
]);
JS.mixin(cc._loader, {
JS.mixin(cc.loader, {
/**
* The downloader in cc.loader's pipeline, it's by default the first pipe.
* It's used to download files with several handlers: pure text, image, script, audio, font, uuid.
* You can add your own download function with addDownloadHandlers
* @property downloader
* @type {Object}
*/
downloader: downloader,
/**
* The downloader in cc.loader's pipeline, it's by default the second pipe.
* It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid.
* You can add your own download function with addLoadHandlers
* @property loader
* @type {Object}
*/
loader: loader,
/**
* Get XMLHttpRequest.
* @returns {XMLHttpRequest}
*/
getXMLHttpRequest: function () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
},
getXMLHttpRequest: Pipeline.getXMLHttpRequest,
/**
* Add custom supported types handler or modify existing type handler for download process.
@@ -94,10 +110,71 @@ JS.mixin(cc._loader, {
progressCallback = null;
}
this.onProgress = progressCallback;
this.onComplete = completeCallback;
if (!(resources instanceof Array)) {
resources = resources ? [resources] : [];
}
// Return directly if no resources
if (resources.length === 0) {
completeCallback && completeCallback.call(this, null, this._items);
}
this.flowIn(resources);
// Resolve callback
var error = null;
var checker = {};
var totalCount = 0;
var completedCount = 0;
var self = this;
function loadedCheck (item) {
checker[item.src] = item;
if (item.error) {
error = error || [];
error.push(item.src);
}
completedCount++;
progressCallback && progressCallback.call(self, completedCount, totalCount, item);
for (var url in checker) {
// Not done yet
if (!checker[url]) {
return;
}
}
// All url completed
if (completeCallback) {
setTimeout(function () {
completeCallback.call(self, error, self._items);
completeCallback = null;
}, 0);
}
}
// Add loaded listeners
for (var i = 0; i < resources.length; ++i) {
var url = resources[i].src || resources[i];
if (typeof url !== 'string')
continue;
var item = this._items.map[url];
if ( !item || (item && !item.complete) ) {
this._items.add(url, loadedCheck);
checker[url] = null;
totalCount++;
}
else if (item && item.complete) {
checker[url] = item;
totalCount++;
completedCount++;
}
}
// No new resources, complete directly
if (totalCount === completedCount) {
completeCallback && completeCallback.call(this, null, this._items);
}
else {
this.flowIn(resources);
}
},
/**
@@ -108,8 +185,8 @@ JS.mixin(cc._loader, {
* @returns {*}
*/
getRes: function (url) {
var item = this._items[url];
if (item.complete) {
var item = this._items.map[url];
if (item && item.complete) {
return item.content;
}
else {
@@ -137,4 +214,4 @@ JS.mixin(cc._loader, {
}
});
module.exports = cc._loader;
module.exports = cc.loader;
+6 -140
View File
@@ -25,147 +25,11 @@
var Path = require('../utils/CCPath');
var Sys = require('../platform/CCSys');
var Pipeline = require('./pipeline');
if (!CC_EDITOR || !Editor.isCoreLevel) {
require('../../audio/CCAudio');
}
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;
var supportTable = {
'common' : {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true }
};
// check if browser supports Web Audio
// check Web Audio's context
var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
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');
}
})();
var __audioSupport = Sys.__audioSupport;
var formatSupport = __audioSupport.format;
var context = __audioSupport.context;
function loadAudioFromExtList (url, typeList, audio, cb){
if(typeList.length === 0){
@@ -304,6 +168,8 @@ function downloadAudio (item, callback) {
audio = new cc.Audio(null, null, url);
}
// hack for audio to be found before loaded
item.content = audio;
loadAudioFromExtList(url, typeList, audio, callback);
}
+79 -8
View File
@@ -23,6 +23,7 @@
****************************************************************************/
var JS = require('../platform/js');
var Path = require('../utils/CCPath');
var Pipeline = require('./pipeline');
var downloadAudio;
@@ -211,7 +212,7 @@ function _loadFont (name, srcs, type){
_divStyle.top = '-100px';
doc.body.appendChild(preloadDiv);
}
function downloadFont (item, callback){
function downloadFont (item, callback) {
var url = item.src,
type = item.type,
name = item.name,
@@ -237,6 +238,36 @@ function downloadFont (item, callback){
}
}
function downloadUuid (item, callback) {
var uuid = item.src;
var self = this;
cc.AssetLibrary.queryAssetInfo(uuid, function (error, url, isRawAsset) {
if (error) {
callback(error);
}
else {
item.url = url;
item.isRawAsset = isRawAsset;
if (isRawAsset) {
var ext = Path.extname(url).toLowerCase();
if (!ext) {
callback(new Error('Download Uuid: can not find type of raw asset[' + uuid + ']: ' + url));
return;
}
ext = ext.substr(1);
// Dispatch to other raw type downloader
var downloadFunc = self.extMap[ext] || self.extMap['default'];
item.type = ext;
downloadFunc({src: url}, callback);
}
else {
self.extMap['json']({src: url}, callback);
}
}
});
}
var defaultMap = {
// JS
'js' : downloadScript,
@@ -265,20 +296,31 @@ var defaultMap = {
'fsh' : downloadText,
'atlas' : downloadText,
'tmx' : downloadText,
'tsx' : downloadText,
'json' : downloadText,
'ExportJson' : downloadText,
'plist' : downloadText,
'fnt' : downloadText,
// Font
'font' : downloadFont,
'eot' : downloadFont,
'ttf' : downloadFont,
'woff' : downloadFont,
'svg' : downloadFont,
'ttc' : downloadFont,
'plist' : downloadText,
// Uuid
'uuid' : downloadUuid,
'default' : downloadText
};
var ID = 'Downloader';
/**
* The downloader pipe, it can download several types of files:
* 1. Text
@@ -301,12 +343,16 @@ var defaultMap = {
* @param {Object} extMap Custom supported types with corresponded handler
*/
var Downloader = function (extMap) {
this.id = 'Downloader';
this.id = ID;
this.async = true;
this.pipeline = null;
this.maxConcurrent = 2;
this._curConcurrent = 0;
this._loadQueue = [];
this.addHandlers(extMap);
this.extMap = JS.mixin(extMap, defaultMap);
};
Downloader.ID = ID;
JS.mixin(Downloader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
@@ -314,14 +360,39 @@ JS.mixin(Downloader.prototype, {
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
this.extMap = JS.addon(extMap, defaultMap);
this.extMap = JS.mixin(this.extMap, extMap);
},
handle: function (item, callback) {
var self = this;
var downloadFunc = this.extMap[item.type] || this.extMap['default'];
downloadFunc.call(this, item, function (err, result) {
callback && callback(err, result);
});
if (this._curConcurrent < this.maxConcurrent) {
if (cc.sys.isMobile) {
this._curConcurrent++;
}
downloadFunc.call(this, item, function (err, result) {
if (cc.sys.isMobile) {
// Concurrent logic
self._curConcurrent = Math.max(0, self._curConcurrent - 1);
while (self._curConcurrent < self.maxConcurrent) {
var nextOne = self._loadQueue.shift();
if (!nextOne) {
break;
}
self.handle(nextOne.item, nextOne.callback);
}
}
callback && callback(err, result);
});
}
else {
this._loadQueue.push({
item: item,
callback: callback
});
}
}
});
+104 -19
View File
@@ -24,6 +24,8 @@
var JS = require('../platform/js');
var Pipeline = require('./pipeline');
var Texture2D = require('../textures/CCTexture2D');
var loadUuid = require('./uuid-loader');
function loadNothing (item, callback) {
callback(null, null);
@@ -47,14 +49,13 @@ function loadImage (item, callback) {
if (!(item.content instanceof Image)) {
callback( new Error('Image Loader: Input item doesn\'t contain Image content') );
}
cc.textureCache.handleLoadedTexture(item.src);
var texture = cc.textureCache.getTextureForKey(item.src);
if (texture) {
callback(null, texture);
}
else {
callback( new Error('Image Loader: Create texture for [' + item.src + '] failed') );
}
var url = item.url || item.src;
var tex = cc.textureCache.getTextureForKey(url) || new Texture2D();
tex.url = url;
tex.initWithElement(item.content);
tex.handleLoadedTexture();
cc.textureCache.cacheImage(url, tex);
callback(null, tex);
}
function loadPlist (item, callback) {
@@ -70,8 +71,92 @@ function loadPlist (item, callback) {
}
}
function loadFont (item, callback) {
callback(null, null);
var fntRE = {
INFO_EXP: /info [^\n]*(\n|$)/gi,
COMMON_EXP: /common [^\n]*(\n|$)/gi,
PAGE_EXP: /page [^\n]*(\n|$)/gi,
CHAR_EXP: /char [^\n]*(\n|$)/gi,
KERNING_EXP: /kerning [^\n]*(\n|$)/gi,
ITEM_EXP: /\w+=[^ \r\n]+/gi,
INT_EXP: /^[\-]?\d+$/,
};
function _parseFntStrToObj (str) {
var arr = str.match(fntRE.ITEM_EXP);
var obj = {};
if (arr) {
for (var i = 0, li = arr.length; i < li; i++) {
var tempStr = arr[i];
var index = tempStr.indexOf('=');
var key = tempStr.substring(0, index);
var value = tempStr.substring(index + 1);
if (value.match(fntRE.INT_EXP)) value = parseInt(value);
else if (value[0] === '"') value = value.substring(1, value.length - 1);
obj[key] = value;
}
}
return obj;
}
function loadFnt (item, callback) {
var fntStr = item.content;
var url = item.src;
var fnt = {}, i, li;
//padding
var infoObj = _parseFntStrToObj(fntStr.match(fntRE.INFO_EXP)[0]);
var paddingArr = infoObj['padding'].split(',');
var padding = {
left: parseInt(paddingArr[0]),
top: parseInt(paddingArr[1]),
right: parseInt(paddingArr[2]),
bottom: parseInt(paddingArr[3])
};
//common
var commonObj = _parseFntStrToObj(fntStr.match(fntRE.COMMON_EXP)[0]);
fnt.commonHeight = commonObj['lineHeight'];
//font size
fnt.fontSize = infoObj['size'];
if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
var texSize = cc.configuration.getMaxTextureSize();
if (commonObj['scaleW'] > texSize.width || commonObj['scaleH'] > texSize.height) {
cc.log('cc.LabelBMFont._parseCommonArguments(): page can\'t be larger than supported');
}
}
if (commonObj['pages'] !== 1) {
cc.log('cc.LabelBMFont._parseCommonArguments(): only supports 1 page');
}
//page
var pageObj = _parseFntStrToObj(fntStr.match(fntRE.PAGE_EXP)[0]);
if (pageObj['id'] !== 0) {
cc.log('cc.LabelBMFont._parseImageFileName() : file could not be found');
}
fnt.atlasName = cc.path.changeBasename(url, pageObj['file']);
//char
var charLines = fntStr.match(fntRE.CHAR_EXP);
var fontDefDictionary = fnt.fontDefDictionary = {};
for (i = 0, li = charLines.length; i < li; i++) {
var charObj = _parseFntStrToObj(charLines[i]);
var charId = charObj['id'];
fontDefDictionary[charId] = {
rect: {x: charObj['x'], y: charObj['y'], width: charObj['width'], height: charObj['height']},
xOffset: charObj['xoffset'],
yOffset: charObj['yoffset'],
xAdvance: charObj['xadvance']
};
}
//kerning
var kerningDict = fnt.kerningDict = {};
var kerningLines = fntStr.match(fntRE.KERNING_EXP);
if (kerningLines) {
for (i = 0, li = kerningLines.length; i < li; i++) {
var kerningObj = _parseFntStrToObj(kerningLines[i]);
kerningDict[(kerningObj['first'] << 16) | (kerningObj['second'] & 0xffff)] = kerningObj['amount'];
}
}
callback(null, fnt);
}
var defaultMap = {
@@ -90,16 +175,15 @@ var defaultMap = {
'plist' : loadPlist,
'font' : loadFont,
'eot' : loadFont,
'ttf' : loadFont,
'woff' : loadFont,
'svg' : loadFont,
'ttc' : loadFont,
'fnt' : loadFnt,
'uuid' : loadUuid,
'default' : loadNothing
};
var ID = 'Loader';
/**
* The loader pipe, it can load several types of files:
* 1. Images
@@ -124,12 +208,13 @@ var defaultMap = {
* @param {Object} extMap Custom supported types with corresponded handler
*/
var Loader = function (extMap) {
this.id = 'Loader';
this.id = ID;
this.async = true;
this.pipeline = null;
this.addHandlers(extMap);
this.extMap = JS.mixin(extMap, defaultMap);
};
Loader.ID = ID;
JS.mixin(Loader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
@@ -137,7 +222,7 @@ JS.mixin(Loader.prototype, {
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
this.extMap = JS.addon(extMap, defaultMap);
this.extMap = JS.mixin(this.extMap, extMap);
},
handle: function (item, callback) {
@@ -112,6 +112,16 @@ JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, {
return !!this.map[url];
},
getContent: function (url) {
var item = this.map[url];
return item ? item.content : null;
},
getError: function (url) {
var item = this.map[url];
return item ? item.error : null;
},
/**
* Remove an item, can only remove completed item, ongoing item can not be removed
* @param {String} url
+106 -27
View File
@@ -35,13 +35,14 @@ var ItemState = {
function asyncFlow (item) {
var pipeId = this.id;
var itemState = item.states[pipeId];
var next = this.next;
if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) {
return;
}
else if (itemState === ItemState.COMPLETE) {
if (this.next) {
this.next.flowIn(item);
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
this.pipeline.flowOut(item);
@@ -62,8 +63,8 @@ function asyncFlow (item) {
item.content = result;
}
item.states[pipeId] = ItemState.COMPLETE;
if (pipe.next) {
pipe.next.flowIn(item);
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
pipe.pipeline.flowOut(item);
@@ -75,13 +76,14 @@ function asyncFlow (item) {
function syncFlow (item) {
var pipeId = this.id;
var itemState = item.states[pipeId];
var next = this.next;
if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) {
return;
}
else if (itemState === ItemState.COMPLETE) {
if (this.next) {
this.next.flowIn(item);
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
this.pipeline.flowOut(item);
@@ -101,8 +103,8 @@ function syncFlow (item) {
item.content = result;
}
item.states[pipeId] = ItemState.COMPLETE;
if (this.next) {
this.next.flowIn(item);
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
this.pipeline.flowOut(item);
@@ -140,6 +142,13 @@ function createItem (url) {
};
}
if (result.skips) {
for (var i = 0, l = result.skips.length; i < l; i++) {
var skip = result.skips[i];
result.states[skip] = ItemState.COMPLETE;
}
}
return result;
}
@@ -176,6 +185,7 @@ function getXMLHttpRequest () {
var Pipeline = function (pipes) {
this._pipes = pipes;
this._items = new LoadingItems();
this._errorUrls = [];
this._flowing = false;
for (var i = 0; i < pipes.length; ++i) {
@@ -187,13 +197,6 @@ var Pipeline = function (pipes) {
pipe.pipeline = this;
pipe.next = i < pipes.length - 1 ? pipes[i+1] : null;
if (pipe.async) {
pipe.flowIn = asyncFlow;
}
else {
pipe.flowIn = syncFlow;
}
}
};
@@ -201,11 +204,55 @@ Pipeline.ItemState = new cc.Enum(ItemState);
Pipeline.getXMLHttpRequest = getXMLHttpRequest;
JS.mixin(Pipeline.prototype, {
/**
* Insert a new pipe at the given index of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
*
* @method insertPipe
* @param {Object} pipe The pipe to be inserted
* @param {Number} index The index to insert
*/
insertPipe: function (pipe, index) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
pipe.pipeline = this;
if (index < this._pipes.length) {
pipe.next = this._pipes[index];
this._pipes.splice(index, 0, pipe);
}
else {
pipe.next = null;
this._pipes.push(pipe);
}
},
/**
* Add a new pipe at the end of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
*
* @method appendPipe
* @param {Object} pipe The pipe to be appended
*/
appendPipe: function (pipe) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
pipe.pipeline = this;
pipe.next = null;
this._pipes.push(pipe);
},
/**
* Let new items flow into the pipeline.
* Each item can be a simple url string or an object,
* if it's an object, it must contain `src` property.
* You can also specify its type by `type` property, by default, the type is the extension name in `src`.
* You can specify its type by `type` property, by default, the type is the extension name in `src`.
* By adding a `skips` property including pipe ids, you can skip these pipe.
* The object can contain any supplementary property as you want.
* @example
* pipeline.flowIn([
@@ -213,7 +260,8 @@ JS.mixin(Pipeline.prototype, {
* {
* src: 'res/scene.json',
* type: 'scene',
* name: 'scene'
* name: 'scene',
* skips: ['Downloader']
* }
* ]);
*
@@ -236,7 +284,7 @@ JS.mixin(Pipeline.prototype, {
var acceptedItems = this._items.append(items);
// Manually complete
if ((this._pipes.length | acceptedItems.length) === 0) {
if (this._pipes.length === 0 || acceptedItems.length === 0) {
this.complete();
return acceptedItems;
}
@@ -245,9 +293,10 @@ JS.mixin(Pipeline.prototype, {
this._flowing = true;
}
// Flow in after appended to loading items
if (this._pipes.length > 0) {
var pipe = this._pipes[0];
if (pipe) {
for (i = 0; i < acceptedItems.length; i++) {
this._pipes[0].flowIn(acceptedItems[i]);
pipe.async ? asyncFlow.call(pipe, acceptedItems[i]) : syncFlow.call(pipe, acceptedItems[i]);
}
}
return acceptedItems;
@@ -267,6 +316,7 @@ JS.mixin(Pipeline.prototype, {
*/
flowInDeps: function (urlList, callback) {
var checker = {};
var count = 0;
function loadedCheck (item) {
checker[item.src] = item;
@@ -278,15 +328,26 @@ JS.mixin(Pipeline.prototype, {
}
}
// All url completed
callback(checker);
callback && callback.call(this, checker);
}
// Add loaded listeners
for (var i = 0; i < urlList.length; ++i) {
var url = urlList[i].src || urlList[i];
if (isUrlValid(url) && !this._items.exists(url)) {
if (typeof url !== 'string')
continue;
var item = this._items.map[url];
if ( !item ) {
this._items.add(url, loadedCheck);
checker[url] = null;
count++;
}
else {
checker[url] = item;
}
}
// No new resources, complete directly
if (count === 0) {
callback && callback.call(this, checker);
}
return this.flowIn(urlList);
},
@@ -295,7 +356,11 @@ JS.mixin(Pipeline.prototype, {
// All completed
if (this._items.isCompleted()) {
this._flowing = false;
this.onComplete && this.onComplete(this._items);
if (this.onComplete) {
var error = this._errorUrls.length === 0 ? null : this._errorUrls;
this.onComplete(error, this._items);
this._errorUrls = [];
}
}
},
@@ -308,6 +373,15 @@ JS.mixin(Pipeline.prototype, {
return;
}
// Register or unregister errors
var errorListId = this._errorUrls.indexOf(url);
if (item.error && errorListId === -1) {
this._errorUrls.push(url);
}
else if (!item.error && errorListId !== -1) {
this._errorUrls.splice(errorListId, 1);
}
items.complete(item.src);
this.onProgress && this.onProgress(items.completedCount, items.totalCount, item);
@@ -363,7 +437,7 @@ JS.mixin(Pipeline.prototype, {
* @return {Boolean} succeed or not
*/
removeItem: function (url) {
var item = this._items[url];
var item = this._items.map[url];
if (item) {
if (!item.complete) {
item.error = new Error('Canceled manually');
@@ -393,6 +467,7 @@ JS.mixin(Pipeline.prototype, {
}
this._items = new LoadingItems();
this._errorUrls = [];
this._flowing = false;
},
@@ -413,13 +488,17 @@ JS.mixin(Pipeline.prototype, {
/**
* This is a callback which will be invoked while all items flow out the pipeline, you should overwirte this function.
* @example
* pipeline.onComplete = function (items) {
* cc.log('Completed ' + items.totalCount + ' items');
* pipeline.onComplete = function (error, items) {
* if (error)
* cc.log('Completed with ' + error.length + ' errors');
* else
* cc.log('Completed ' + items.totalCount + ' items');
* }
* @method onComplete
* @param {Array} error All errored urls will be stored in this array, if no error happened, then it will be null
* @param {LoadingItems} items All items.
*/
onComplete: function (items) {}
onComplete: function (error, items) {}
});
cc.Pipeline = module.exports = Pipeline;
+138
View File
@@ -0,0 +1,138 @@
/****************************************************************************
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');
require('../platform/deserialize');
// temp deserialize info
var _tdInfo = new cc.deserialize.Details();
var SCENE_ID = 'cc.Scene';
function loadUuid (item, callback) {
var json,
uuid = item.src,
url = item.url;
if (typeof item.content === 'string') {
try {
json = JSON.parse(item.content);
}
catch (e) {
callback( new Error('Uuid Loader: Parse asset [' + item.src + '] failed : ' + e) );
return;
}
}
else if (typeof item.content === 'object') {
json = item.content;
}
else {
callback( new Error('JSON Loader: Input item doesn\'t contain string content') );
return;
}
var isScene = json && (
(json[0] && json[0].__type__ === SCENE_ID) ||
(json[1] && json[1].__type__ === SCENE_ID)
);
var classFinder = isScene ? cc._MissingScript.safeFindClass : function (id) {
var cls = JS._getClassById(id);
if (cls) {
return cls;
}
cc.warn('Can not get class "%s"', id);
return Object;
};
var tdInfo = cc.sys.isNative ? new cc.deserialize.Details() : (item.deserializeInfo || _tdInfo);
var asset = cc.deserialize(json, tdInfo, {
classFinder: classFinder,
target: item.existingAsset
});
var dependsSrcs = JS.array.copy(tdInfo.uuidList);
var ownerList = JS.array.copy(tdInfo.uuidObjList);
var propList = JS.array.copy(tdInfo.uuidPropList);
var depends = new Array(dependsSrcs.length);
// load depends assets
for (var i = 0; i < dependsSrcs.length; i++) {
var dependSrc = dependsSrcs[i];
depends[i] = {
src: dependSrc,
type: 'uuid',
uuid: dependSrc
};
}
// load raw
if (tdInfo.rawProp) {
dependsSrcs.push(url);
ownerList.push(asset);
propList.push(tdInfo.rawProp);
depends.push(url);
}
var pipeline = this.pipeline;
if (depends.length > 0) {
this.pipeline.flowInDeps(depends, function (items) {
var item;
for (var src in items) {
item = items[src];
if (item.uuid && item.content) {
item.content._uuid = item.uuid;
}
}
for (var i = 0; i < dependsSrcs.length; i++) {
var dependSrc = dependsSrcs[i];
var obj = ownerList[i];
var dependProp = propList[i];
item = items[dependSrc];
if (item) {
if (item.complete) {
var value = item.isRawAsset ? (item.url || item.src) : item.content;
obj[dependProp] = value;
}
else {
this.getItems().add(dependSrc, function (item) {
var value = item.isRawAsset ? (item.url || item.src) : item.content;
this.obj[this.prop] = value;
}, {
obj: obj,
prop: dependProp
});
}
}
}
callback(null, asset);
});
}
else {
callback(null, asset);
}
asset._uuid = uuid;
// tdInfo 是用来重用的临时对象,每次使用后都要重设,这样才对 GC 友好。
tdInfo.reset();
}
module.exports = loadUuid;
+68 -319
View File
@@ -1,8 +1,6 @@
var JS = require('./js');
var Asset = require('../assets/CCAsset');
var Asset = require('../assets/CCAsset');
var callInNextTick = require('./utils').callInNextTick;
var LoadManager = require('./load-manager');
var CallbacksInvoker = require('./callbacks-invoker');
var Loader = require('../load-pipeline/CCLoader');
/**
* The asset library which managing loading/unloading assets in project.
@@ -17,66 +15,9 @@ var _libraryBase = '';
var _rawAssetsBase = ''; // The base dir for raw assets in runtime
var _uuidToRawAssets;
// variables
// the loading uuid's callbacks
var _uuidToCallbacks = new CallbacksInvoker();
// temp deserialize info
var _tdInfo = new cc.deserialize.Details();
var _cc_loader_loadJson = cc.loader.loadJson.bind(cc.loader);
var SCENE_ID = 'cc.Scene';
// create a loading context which reserves all relevant parameters
function LoadingHandle (readMainCache, writeMainCache, recordAssets, deserializeInfo) {
//this.readMainCache = readMainCache;
//this.writeMainCache = writeMainCache;
// FORCE ignore global cache in fireball lite
this.readMainCache = false;
this.writeMainCache = false;
// 缓存同一个任务中已经加载好的资源
var needIndieCache = !(this.readMainCache && this.writeMainCache);
this.taskIndieCache = needIndieCache ? {} : null;
// 保存正在等待依赖项加载完毕的资源,防止循环依赖
// (其它缓存包含的是已经加载完毕的资源,如果已经缓存会立即结束并回调,而这个缓存存的是还在加载中的资源,不会影响加载也不会触发回调)
this.pendingCache = {};
// 需要让场景 preload 的 asset(所有包含 raw file 后缀名的 asset 并且不含 rawType 属性的 asset)
this.assetsNeedPostLoad = recordAssets ? [] : null;
// 可以提供一个反序列化句柄,用来在执行反序列化任务时,做一些特殊处理
this.deserializeInfo = deserializeInfo;
function isScene (asset) {
return asset.constructor === cc.SceneAsset || asset instanceof cc.Scene;
}
LoadingHandle.prototype.readCache = function (uuid) {
if (this.readMainCache && this.writeMainCache) {
return AssetLibrary._uuidToAsset[uuid];
}
else {
if (this.readMainCache) {
// writeMainCache == false
return AssetLibrary._uuidToAsset[uuid] || this.taskIndieCache[uuid];
}
else {
return this.taskIndieCache[uuid];
}
}
};
LoadingHandle.prototype.writeCache = function (uuid, asset, hasRawType) {
if (this.writeMainCache) {
AssetLibrary._uuidToAsset[uuid] = asset;
}
if (this.taskIndieCache) {
this.taskIndieCache[uuid] = asset;
}
if (this.assetsNeedPostLoad && asset._rawFiles && !hasRawType) {
this.assetsNeedPostLoad.push(asset);
}
};
// publics
@@ -95,25 +36,27 @@ var AssetLibrary = {
* @param {Boolean} options.readMainCache - Default is true. If false, the asset and all its depends assets will reload and create new instances from library.
* @param {Boolean} options.writeMainCache - Default is true. If true, the result will cache to AssetLibrary, and MUST be unload by user manually.
* @param {Asset} options.existingAsset - load to existing asset, this argument is only available in editor
* @param {Boolean} options.recordAssets - Default is false. If true, tracking statistics associated with the assets which needs to preload(All the assets contains "urls" but dont have "_rawFiles")
* @param {deserialize.Details} options.deserializeInfo - specified a DeserializeInfo object if you want,
* this parameter is only available in editor.
* @private
*/
loadAsset: function (uuid, callback, options) {
var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true;
var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true;
// var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true;
// var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true;
var handle = new LoadingHandle(readMainCache,
writeMainCache,
options && options.recordAssets,
options && options.deserializeInfo);
this._loadAssetByUuid(uuid, callback, handle, options && options.existingAsset);
return handle;
var item = {
src: uuid,
type: 'uuid'
};
if (options && options.deserializeInfo) {
item.deserializeInfo = options.deserializeInfo;
}
if (options && options.existingAsset) {
item.existingAsset = options.existingAsset;
}
this._loadAssetByUuid(item, callback);
},
_LoadingHandle: LoadingHandle,
getImportedDir: function (uuid) {
return _libraryBase + uuid.slice(0, 2)/* + cc.path.sep + uuid*/;
},
@@ -178,7 +121,7 @@ var AssetLibrary = {
// parse uuid out of url
parseUuidInEditor: function (url) {
if (CC_EDITOR) {
var uuid = "";
var uuid = '';
var isImported = url.startsWith(_libraryBase);
if (isImported) {
var dir = cc.path.dirname(url);
@@ -210,275 +153,81 @@ var AssetLibrary = {
* 4. 递归加载Asset及其引用到的其它Asset
*
* @method _loadAssetByUuid
* @param {String} uuid
* @param {Object} item - loading item including uuid, type and extra infos
* @param {loadCallback} callback - the callback to receive the asset, can be null
* @param {LoadingHandle} handle - the loading context which reserves all relevant parameters
* @param {Asset} [existingAsset] - load to existing asset, this argument is only available in editor
* @private
*/
_loadAssetByUuid: function (uuid, callback, handle, existingAsset) {
_loadAssetByUuid: function (item, callback) {
var uuid = item.src;
var thisTick = true;
if (typeof uuid !== 'string') {
return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null);
}
// step 1
if ( !existingAsset ) {
var asset = handle.readCache(uuid);
if (asset) {
return callInNextTick(callback, null, asset);
if (CC_EDITOR) {
Loader.removeItem(uuid);
}
Loader.load(item, function (error, items) {
var asset = items.getContent(uuid);
if (error || !asset) {
error = new Error('[AssetLibrary] loading JSON or dependencies failed : ' + JSON.stringify(error));
}
}
// step 2
// 如果必须重新加载,则不能合并到到 _uuidToCallbacks,否则现有的加载成功后会同时触发回调,
// 导致提前返回的之前的资源。
var canShareLoadingTask = handle.readMainCache && !existingAsset;
if ( canShareLoadingTask && !_uuidToCallbacks.add(uuid, callback) ) {
// already loading
return;
}
// 防止循环加载
var loading = handle.pendingCache[uuid];
if (loading) {
// already loading
return callInNextTick(callback, null, loading);
}
//if (CC_EDITOR && !_libraryBase) {
// callInNextTick(callback, new Error('Cannot load ' + uuid + ' in editor because AssetLibrary not yet initialized!'), null);
// return;
//}
function onload (error, json, url) {
function onDeserializedWithDepends (err, asset, hasRawType) {
if (asset) {
asset._uuid = uuid;
handle.writeCache(uuid, asset, hasRawType);
}
if ( canShareLoadingTask ) {
_uuidToCallbacks.invokeAndRemove(uuid, err, asset);
}
else if (callback) {
callback(err, asset);
}
}
if (json) {
AssetLibrary._deserializeWithDepends(json, url, uuid, onDeserializedWithDepends, handle, existingAsset);
if (thisTick) {
callInNextTick(function () {
if (isScene(asset)) {
Loader.removeItem(uuid);
}
callback(error, asset);
});
}
else {
onDeserializedWithDepends(error, null);
}
}
if (CC_EDITOR && !CC_TEST) {
this._queryAssetInfoInEditor(uuid, function (err, url, isRawAsset) {
if (err) {
callback(err);
if (isScene(asset)) {
Loader.removeItem(uuid);
}
else {
var shouldLoadByEngine = !isRawAsset;
if (!shouldLoadByEngine) {
return callback(new Error('Should not load raw file in AssetLibrary, uuid: ' + uuid));
}
LoadManager.loadByLoader(_cc_loader_loadJson, url, function (error, json) {
onload(error, json, url);
});
}
});
}
else {
var info = this._getAssetInfoInRuntime(uuid);
if (info.raw) {
return callback(new Error('Should not load raw file in AssetLibrary, uuid: ' + uuid));
callback(error, asset);
}
LoadManager.loadByLoader(_cc_loader_loadJson, info.url, function (error, json) {
onload(error, json, info.url);
});
}
});
thisTick = false;
},
/**
* @method loadJson
* @param {String|Object} json
* @param {String} json
* @param {loadCallback} callback
* @param {Boolean} [dontCache=false] - If false, the result will cache to AssetLibrary, and MUST be unload by user manually.
* @param {Boolean} [recordAssets=false] - 是否统计新加载的需要让场景 preload 的 asset(所有包含 raw file 后缀名的 asset 并且不含 rawType 属性的 asset)
* @return {LoadingHandle}
* @private
*/
loadJson: function (json, callback, dontCache, recordAssets) {
var handle = new LoadingHandle(!dontCache, !dontCache, recordAssets);
loadJson: function (json, callback) {
var randomUuid = '' + ((new Date()).getTime() + Math.random());
var thisTick = true;
if (typeof json === 'string') {
try {
json = JSON.parse(json);
var item = {
src: randomUuid,
type: 'uuid',
content: json,
skips: [ Loader.downloader.id ]
};
Loader.load(item, function (error, items) {
var asset = items.getContent(randomUuid);
if (error || !asset) {
error = new Error('[AssetLibrary] loading JSON or dependencies failed : ' + JSON.stringify(error));
}
catch (e) {
callInNextTick(callback, e, null);
return handle;
}
}
this._deserializeWithDepends(json, '', '', function (p1, p2) {
if (thisTick) {
callInNextTick(callback, p1, p2);
callInNextTick(function () {
if (CC_EDITOR || isScene(asset)) {
Loader.removeItem(randomUuid);
}
callback(error, asset);
});
}
else {
callback(p1, p2);
if (CC_EDITOR || isScene(asset)) {
Loader.removeItem(randomUuid);
}
callback(error, asset);
}
}, handle);
});
thisTick = false;
return handle;
},
_loadDepends: function (asset, _tdInfo, url, handle, callback) {
// load depends
var pendingCount = _tdInfo.uuidList.length;
// load raw
var rawProp = _tdInfo.rawProp; // _tdInfo不能用在回调里!
if (rawProp) {
// load depends raw objects
var attrs = cc.Class.attr(asset.constructor, _tdInfo.rawProp);
var rawType = attrs.rawType;
++pendingCount;
LoadManager.load(url, rawType, asset._rawext, function onRawObjLoaded (error, raw) {
if (error) {
cc.error('[AssetLibrary] Failed to load %s of %s. %s', rawType, url, error);
}
asset[rawProp] = raw;
--pendingCount;
if (pendingCount === 0) {
callback();
callback = null;
}
});
}
if (pendingCount === 0) {
if (callback) {
callback();
}
return;
}
/*
如果依赖的所有资源都要重新下载,批量操作时将会导致同时执行多次重复下载。优化方法是增加一全局事件队列,
队列保存每个任务的注册,启动,结束事件,任务从注册到启动要延迟几帧,每个任务都存有父任务。
这样通过队列的事件序列就能做到合并批量任务。
如果依赖的资源不重新下载也行,但要判断是否刚好在下载过程中,如果是的话必须等待下载完成才能结束本资源的加载,
否则外部获取到的依赖资源就会是旧的。
*/
// load depends assets
for (var i = 0; i < _tdInfo.uuidList.length; i++) {
var dependsUuid = _tdInfo.uuidList[i];
(function (dependsUuid, obj, prop) {
AssetLibrary.queryAssetInfo(dependsUuid, function (err, dependsUrl, isRawAsset) {
if (err) {
cc.error('[AssetLibrary] Failed to load "%s", %s', dependsUuid, err);
--pendingCount;
if (callback && pendingCount === 0) {
callback();
callback = null;
}
obj[prop] = obj[prop]; // ensures forEach worked
return;
}
else if (isRawAsset) {
cc.loader.load(dependsUrl, function (err, assets) {
if (err) {
cc.error('[AssetLibrary] Failed to load "%s"', dependsUrl);
obj[prop] = '';
}
else {
obj[prop] = dependsUrl;
}
--pendingCount;
if (callback && pendingCount === 0) {
callback();
callback = null;
}
});
return;
}
var onDependsAssetLoaded = function (error, dependsAsset, hasRawType) {
if (CC_EDITOR && error) {
if (Editor.AssetDB && Editor.AssetDB.isValidUuid(dependsUuid)) {
cc.error('[AssetLibrary] Failed to load "%s", %s', dependsUuid, error);
}
}
//else {
// dependsAsset._uuid = dependsUuid;
//}
// update reference
obj[prop] = dependsAsset;
//
--pendingCount;
if (callback && pendingCount === 0) {
callback();
callback = null;
}
};
AssetLibrary._loadAssetByUuid(dependsUuid, onDependsAssetLoaded, handle);
});
})( dependsUuid, _tdInfo.uuidObjList[i], _tdInfo.uuidPropList[i] );
}
// AssetLibrary._loadAssetByUuid 的回调有可能在当帧也可能延后执行,所以这里要判断 callback 来防止多次调用
if (callback && pendingCount === 0) {
callback();
callback = null;
}
},
/**
* @method _deserializeWithDepends
* @param {Object} json
* @param {String} url
* @param {String} uuid
* @param {loadCallback} callback
* @param {Object} handle - the loading context which reserves all relevant parameters
* @param {Asset} [existingAsset] - existing asset to reload
* @private
*/
_deserializeWithDepends: function (json, url, uuid, callback, handle, existingAsset) {
// deserialize asset
var isScene = json && (
(json[0] && json[0].__type__ === SCENE_ID) ||
(json[1] && json[1].__type__ === SCENE_ID)
);
var classFinder = isScene ? cc._MissingScript.safeFindClass : function (id) {
var cls = JS._getClassById(id);
if (cls) {
return cls;
}
cc.warn('Can not get class "%s"', id);
return Object;
};
var tdInfo = cc.sys.isNative ? new cc.deserialize.Details() : (handle.deserializeInfo || _tdInfo);
var asset = cc.deserialize(json, tdInfo, {
classFinder: classFinder,
target: existingAsset
});
var hasRawType = !!tdInfo.rawProp;
if (uuid) {
handle.pendingCache[uuid] = asset;
}
this._loadDepends(asset, tdInfo, url, handle, function () {
if (uuid) {
delete handle.pendingCache[uuid];
}
callback(null, asset, hasRawType);
});
// tdInfo 是用来重用的临时对象,每次使用后都要重设,这样才对 GC 友好。
tdInfo.reset();
},
/**
@@ -537,7 +286,7 @@ var AssetLibrary = {
mountPaths = {
assets: _rawAssetsBase + 'assets',
internal: _rawAssetsBase + 'internal',
}
};
}
cc.url._init(mountPaths);
}
-595
View File
@@ -1,595 +0,0 @@
var _noCacheRex = /\?/;
function urlAppendTimestamp (url) {
if (cc.game.config['noCache'] && typeof url === 'string') {
if(_noCacheRex.test(url))
url += '&_t=' + (new Date() - 0);
else
url += '?_t=' + (new Date() - 0);
}
return url;
}
/**
* Loader for resource loading process. It's a singleton object.
* @class loader
* @static
*/
cc.loader = cc.loader || (function () {
var _jsCache = {}, //cache for js
_register = {}, //register of loaders
_langPathCache = {}, //cache for lang path
_aliases = {}, //aliases for res url
_urlRegExp = new RegExp(
"^" +
// protocol identifier
"(?:(?:https?|ftp)://)" +
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
// host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
// domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
// TLD identifier
"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
"|" +
"(?:localhost)" +
")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:/\\S*)?" +
"$", "i"
);
return /** @lends cc.loader# */{
resPath: "",//root path of resource
audioPath: "",//root path of audio
cache: {},//cache for data loaded
/**
* Get XMLHttpRequest.
* @returns {XMLHttpRequest}
*/
getXMLHttpRequest: function () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
},
//@MODE_BEGIN DEV
_getArgs4Js: function (args) {
var a0 = args[0], a1 = args[1], a2 = args[2], results = ["", null, null];
if (args.length === 1) {
results[1] = a0 instanceof Array ? a0 : [a0];
} else if (args.length === 2) {
if (typeof a1 === "function") {
results[1] = a0 instanceof Array ? a0 : [a0];
results[2] = a1;
} else {
results[0] = a0 || "";
results[1] = a1 instanceof Array ? a1 : [a1];
}
} else if (args.length === 3) {
results[0] = a0 || "";
results[1] = a1 instanceof Array ? a1 : [a1];
results[2] = a2;
} else throw new Error("arguments error to load js!");
return results;
},
/**
* Load js files.
* If the third parameter doesn't exist, then the baseDir turns to be "".
*
* @method loadJs
* @param {String} [baseDir] - The pre path for jsList or the list of js path.
* @param {Array} jsList - List of js path.
* @param {Function} [cb] - Callback function
* @returns {*}
*/
loadJs: function (baseDir, jsList, cb) {
var self = this,
args = self._getArgs4Js(arguments);
var preDir = args[0], list = args[1], callback = args[2];
if (navigator.userAgent.indexOf("Trident/5") > -1) {
self._loadJs4Dependency(preDir, list, 0, callback);
} else {
cc.async.map(list, function (item, index, cb1) {
var jsPath = cc.path.join(preDir, item);
if (_jsCache[jsPath]) return cb1(null);
self._createScript(jsPath, false, cb1);
}, callback);
}
},
/**
* Load js width loading image.
*
* @method loadJsWithImg
* @param {String} [baseDir]
* @param {Array} jsList
* @param {Function} [cb]
*/
loadJsWithImg: function (baseDir, jsList, cb) {
var self = this, jsLoadingImg = self._loadJsImg(),
args = self._getArgs4Js(arguments);
this.loadJs(args[0], args[1], function (err) {
if (err) throw new Error(err);
jsLoadingImg.parentNode.removeChild(jsLoadingImg);//remove loading gif
if (args[2]) args[2]();
});
},
_createScript: function (jsPath, isAsync, cb) {
var d = document, self = this, s = document.createElement('script');
s.async = isAsync;
_jsCache[jsPath] = true;
s.src = urlAppendTimestamp(jsPath);
s.addEventListener('load', function () {
s.parentNode.removeChild(s);
s.removeEventListener('load', arguments.callee, false);
cb();
}, false);
s.addEventListener('error', function () {
s.parentNode.removeChild(s);
cb("Load " + jsPath + " failed!");
}, false);
d.body.appendChild(s);
},
_loadJs4Dependency: function (baseDir, jsList, index, cb) {
if (index >= jsList.length) {
if (cb) cb();
return;
}
var self = this;
self._createScript(cc.path.join(baseDir, jsList[index]), false, function (err) {
if (err) return cb(err);
self._loadJs4Dependency(baseDir, jsList, index + 1, cb);
});
},
_loadJsImg: function () {
var d = document, jsLoadingImg = d.getElementById("cocos2d_loadJsImg");
if (!jsLoadingImg) {
jsLoadingImg = document.createElement('img');
if (cc._loadingImage)
jsLoadingImg.src = cc._loadingImage;
var canvasNode = d.getElementById(cc.game.config["id"]);
canvasNode.style.backgroundColor = "transparent";
canvasNode.parentNode.appendChild(jsLoadingImg);
var canvasStyle = getComputedStyle ? getComputedStyle(canvasNode) : canvasNode.currentStyle;
if (!canvasStyle)
canvasStyle = {width: canvasNode.width, height: canvasNode.height};
jsLoadingImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - jsLoadingImg.width) / 2 + "px";
jsLoadingImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - jsLoadingImg.height) / 2 + "px";
jsLoadingImg.style.position = "absolute";
}
return jsLoadingImg;
},
//@MODE_END DEV
/**
* Load a single resource as txt.
*
* @method loadTxt
* @param {String} url
* @param {Function} [cb] - arguments are : err, txt
*/
loadTxt: function (url, cb) {
var xhr = this.getXMLHttpRequest(),
errInfo = "load " + url + " failed!";
url = urlAppendTimestamp(url);
xhr.open("GET", url, true);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "utf-8");
xhr.onreadystatechange = function () {
if(xhr.readyState === 4)
(xhr.status === 200 || xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
xhr.onload = function () {
if(xhr.readyState === 4) {
(xhr.status === 200 || xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
}
};
xhr.onerror = function(){
cb({status:xhr.status, errorMessage:errInfo}, null);
};
}
xhr.send(null);
},
_loadTxtSync: function (url) {
var xhr = this.getXMLHttpRequest();
xhr.open("GET", url, false);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "utf-8");
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
}
xhr.send(null);
if (!xhr.readyState === 4 || !(xhr.status === 200 || xhr.status === 0)) {
return null;
}
return xhr.responseText;
},
loadCsb: function(url, cb){
var xhr = new XMLHttpRequest(),
errInfo = "load " + url + " failed!";
url = urlAppendTimestamp(url);
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
var arrayBuffer = xhr.response; // Note: not oReq.responseText
if (arrayBuffer) {
window.msg = arrayBuffer;
}
if(xhr.readyState === 4)
xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null);
};
xhr.onerror = function(){
cb({status:xhr.status, errorMessage:errInfo}, null);
};
xhr.send(null);
},
/**
* Load a single resource as json.
*
* @method loadJson
* @param {String} url
* @param {Function} [cb] - arguments are : err, json
*/
loadJson: function (url, cb) {
this.loadTxt(url, function (err, txt) {
if (err) {
cb(err);
}
else {
try {
var result = JSON.parse(txt);
}
catch (e) {
throw new Error("parse json [" + url + "] failed : " + e);
return;
}
cb(null, result);
}
});
},
_checkIsImageURL: function (url) {
var ext = /(\.png)|(\.jpg)|(\.bmp)|(\.jpeg)|(\.gif)/.exec(url);
return (ext != null);
},
/**
* Load a single image.
*
* @method loadImg
* @param {String} url
* @param {Object} [option]
* @param {Function} callback
* @returns {Image}
*/
loadImg: function (url, option, callback) {
var opt = {
isCrossOrigin: true
};
if (callback !== undefined)
opt.isCrossOrigin = option.isCrossOrigin === null ? opt.isCrossOrigin : option.isCrossOrigin;
else if (option !== undefined)
callback = option;
url = urlAppendTimestamp(url);
var isNew = false;
var img = this.getRes(url);
if (!img) {
img = new Image();
isNew = true;
if (opt.isCrossOrigin && location.origin !== "file://")
img.crossOrigin = "Anonymous";
}
if (!isNew && img.complete && img.naturalWidth > 0) {
callback && callback(null, img);
}
else {
function loadCallback () {
img.removeEventListener('load', loadCallback);
img.removeEventListener('error', errorCallback);
if (callback)
callback(null, img);
}
var self = this;
function errorCallback () {
img.removeEventListener('load', loadCallback);
img.removeEventListener('error', errorCallback);
if (img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") {
opt.isCrossOrigin = false;
self.release(url);
cc.loader.loadImg(url, opt, callback);
}
else {
typeof callback === "function" && callback("load image failed");
}
}
img.addEventListener("load", loadCallback);
img.addEventListener("error", errorCallback);
}
if (isNew) {
img.src = url;
}
return img;
},
/**
* Iterator function to load res.
*
* @method _loadResIterator
* @param {Object} item
* @param {Number} index
* @param {Function} [cb]
* @returns {*}
* @private
*/
_loadResIterator: function (item, index, cb) {
var self = this, url = null;
var type = item.type;
if (type) {
type = "." + type.toLowerCase();
url = item.src ? item.src : item.name + type;
} else {
url = item;
type = cc.path.extname(url);
}
var obj = self.getRes(url);
if (obj)
return cb(null, obj);
var loader = null;
if (type) {
loader = _register[type.toLowerCase()];
}
if (!loader) {
cc.error("loader for [" + type + "] not exists!");
return cb();
}
var realUrl = url;
if (!_urlRegExp.test(url))
{
var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
realUrl = self.getUrl(basePath, url);
}
loader.load(realUrl, url, item, function (err, data) {
if (err) {
cc.log(err);
self.cache[url] = null;
delete self.cache[url];
cb({status:520, errorMessage:err}, null);
} else {
self.cache[url] = data;
cb(null, data);
}
});
},
/**
* Get url with basePath.
*
* @method getUrl
* @param {String} basePath
* @param {String} [url]
* @returns {*}
*/
getUrl: function (basePath, url) {
var self = this, path = cc.path;
if (basePath !== undefined && url === undefined) {
url = basePath;
var type = path.extname(url);
type = type ? type.toLowerCase() : "";
var loader = _register[type];
if (!loader)
basePath = self.resPath;
else
basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
}
url = cc.path.join(basePath || "", url);
if (url.match(/[\/(\\\\)]lang[\/(\\\\)]/i)) {
if (_langPathCache[url])
return _langPathCache[url];
var extname = path.extname(url) || "";
url = _langPathCache[url] = url.substring(0, url.length - extname.length) + "_" + cc.sys.language + extname;
}
return url;
},
/**
* Load resources then call the callback.
*
* @method load
* @param {String} resources
* @param {Function} [option] - callback or trigger
* @param {Function|Object} [loadCallback]
* @return {AsyncPool}
*/
load: function(resources, option, loadCallback){
'use strict';
var self = this;
var len = arguments.length;
if(len === 0)
throw new Error("arguments error!");
if(len === 3){
if(typeof option === "function"){
if(typeof loadCallback === "function")
option = {trigger : option, cb : loadCallback };
else
option = { cb : option, cbTarget : loadCallback};
}
}else if(len === 2){
if(typeof option === "function")
option = {cb : option};
}else if(len === 1){
option = {};
}
if(!(resources instanceof Array))
resources = [resources];
var asyncPool = new cc.AsyncPool(
resources, 0,
function (value, index, AsyncPoolCallback, aPool) {
self._loadResIterator(value, index, function (err, res) {
if (option.trigger)
option.trigger.call(option.triggerTarget, res, aPool.size, aPool.finishedSize); //call trigger
AsyncPoolCallback(err, res);
});
},
option.cb, option.cbTarget);
asyncPool.flow();
return asyncPool;
},
_handleAliases: function (fileNames, cb) {
var self = this;
var resList = [];
for (var key in fileNames) {
var value = fileNames[key];
_aliases[key] = value;
resList.push(value);
}
this.load(resList, cb);
},
/**
* <p>
* Loads alias map from the contents of a filename. <br/>
* <br/>
* @note The plist file name should follow the format below: <br/>
* <?xml version="1.0" encoding="UTF-8"?> <br/>
* <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <br/>
* <plist version="1.0"> <br/>
* <dict> <br/>
* <key>filenames</key> <br/>
* <dict> <br/>
* <key>sounds/click.wav</key> <br/>
* <string>sounds/click.caf</string> <br/>
* <key>sounds/endgame.wav</key> <br/>
* <string>sounds/endgame.caf</string> <br/>
* <key>sounds/gem-0.wav</key> <br/>
* <string>sounds/gem-0.caf</string> <br/>
* </dict> <br/>
* <key>metadata</key> <br/>
* <dict> <br/>
* <key>version</key> <br/>
* <integer>1</integer> <br/>
* </dict> <br/>
* </dict> <br/>
* </plist> <br/>
* </p>
*
* @method loadAliases
* @param {String} url - The plist file name.
* @param {Function} [callback]
*/
loadAliases: function (url, callback) {
var self = this, dict = self.getRes(url);
if (!dict) {
self.load(url, function (err, results) {
self._handleAliases(results[0]["filenames"], callback);
});
} else
self._handleAliases(dict["filenames"], callback);
},
/**
* Register a resource loader into loader.
*
* @method register
* @param {String} extNames
* @param {Function} loader
*/
register: function (extNames, loader) {
if (!extNames || !loader) return;
var self = this;
if (typeof extNames === "string")
return _register[extNames.trim().toLowerCase()] = loader;
for (var i = 0, li = extNames.length; i < li; i++) {
_register["." + extNames[i].trim().toLowerCase()] = loader;
}
},
/**
* Get resource data by url.
*
* @method getRes
* @param {String} url
* @returns {*}
*/
getRes: function (url) {
return this.cache[url] || this.cache[_aliases[url]];
},
/**
* Get aliase by url.
*
* @method getAliase
* @param {String} url
* @returns {*}
*/
getAliase: function (url) {
return _aliases[url];
},
/**
* Release the cache of resource by url.
*
* @method release
* @param {String} url
*/
release: function (url) {
var cache = this.cache;
delete cache[url];
delete cache[_aliases[url]];
delete _aliases[url];
},
/**
* Resource cache of all resources.
*
* @method releaseAll
*/
releaseAll: function () {
var locCache = this.cache;
for (var key in locCache)
delete locCache[key];
for (var key in _aliases)
delete _aliases[key];
}
};
})();
-156
View File
@@ -1,156 +0,0 @@
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 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.
****************************************************************************/
cc._txtLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadTxt(realUrl, cb);
}
};
cc.loader.register(["txt", "xml", "vsh", "fsh", "atlas"], cc._txtLoader);
cc._jsonLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadJson(realUrl, cb);
}
};
cc.loader.register(["json", "ExportJson"], cc._jsonLoader);
cc._jsLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadJs(realUrl, cb);
}
};
cc.loader.register(["js"], cc._jsLoader);
cc._imgLoader = {
load : function(realUrl, url, res, cb){
cc.loader.cache[url] = cc.loader.loadImg(realUrl, function(err, img){
if(err)
return cb(err);
cc.textureCache.handleLoadedTexture(url);
cb(null, img);
});
}
};
cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff", "webp"], cc._imgLoader);
cc._serverImgLoader = {
load : function(realUrl, url, res, cb){
cc.loader.cache[url] = cc.loader.loadImg(res.src, function(err, img){
if(err)
return cb(err);
cc.textureCache.handleLoadedTexture(url);
cb(null, img);
});
}
};
cc.loader.register(["serverImg"], cc._serverImgLoader);
cc._plistLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadTxt(realUrl, function(err, txt){
if(err)
return cb(err);
cb(null, cc.plistParser.parse(txt));
});
}
};
cc.loader.register(["plist"], cc._plistLoader);
cc._fontLoader = {
TYPE : {
".eot" : "embedded-opentype",
".ttf" : "truetype",
".ttc" : "truetype",
".woff" : "woff",
".svg" : "svg"
},
_loadFont : function(name, srcs, type){
var doc = document, path = cc.path, TYPE = this.TYPE, fontStyle = document.createElement("style");
fontStyle.type = "text/css";
doc.body.appendChild(fontStyle);
var fontStr = "";
if(isNaN(name - 0))
fontStr += "@font-face { font-family:" + name + "; src:";
else
fontStr += "@font-face { font-family:'" + name + "'; src:";
if(srcs instanceof Array){
for(var i = 0, li = srcs.length; i < li; i++){
var src = srcs[i];
type = path.extname(src).toLowerCase();
fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')";
fontStr += (i === li - 1) ? ";" : ",";
}
}else{
type = type.toLowerCase();
fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');";
}
fontStyle.textContent += fontStr + "}";
//<div style="font-family: PressStart;">.</div>
var preloadDiv = document.createElement("div");
var _divStyle = preloadDiv.style;
_divStyle.fontFamily = name;
preloadDiv.innerHTML = ".";
_divStyle.position = "absolute";
_divStyle.left = "-100px";
_divStyle.top = "-100px";
doc.body.appendChild(preloadDiv);
},
load : function(realUrl, url, res, cb){
var self = this;
var type = res.type, name = res.name, srcs = res.srcs;
if(cc.js.isString(res)){
type = cc.path.extname(res);
name = cc.path.basename(res, type);
self._loadFont(name, res, type);
}else{
self._loadFont(name, srcs);
}
if(document.fonts){
document.fonts.load("1em " + name).then(function(){
cb(null, true);
}, function(err){
cb(err);
});
}else{
cb(null, true);
}
}
};
cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader);
cc._binaryLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadBinary(realUrl, cb);
}
};
cc._csbLoader = {
load: function(realUrl, url, res, cb){
cc.loader.loadCsb(realUrl, cb);
}
};
cc.loader.register(["csb"], cc._csbLoader);
+139
View File
@@ -450,6 +450,7 @@ if (typeof Editor !== 'undefined' && Editor.isCoreLevel) {
width: 0,
height: 0
};
sys.__audioSupport = {};
}
else {
// browser or runtime
@@ -698,6 +699,144 @@ else {
delete _tmpCanvas1;
delete _tmpCanvas2;
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);
}
})();
try {
if (__audioSupport.WEB_AUDIO) {
__audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
if(__audioSupport.DELAY_CREATE_CTX) {
setTimeout(function(){ __audioSupport.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) formatSupport.push('.ogg');
var mp3 = audio.canPlayType('audio/mpeg');
if (mp3) formatSupport.push('.mp3');
var wav = audio.canPlayType('audio/wav; codecs="1"');
if (wav) formatSupport.push('.wav');
var mp4 = audio.canPlayType('audio/mp4');
if (mp4) formatSupport.push('.mp4');
var m4a = audio.canPlayType('audio/x-m4a');
if (m4a) formatSupport.push('.m4a');
}
})();
__audioSupport.format = formatSupport;
sys.__audioSupport = __audioSupport;
}
/**
-2
View File
@@ -34,10 +34,8 @@ require('./instantiate');
require('./prefab-info');
require('./requiring-frame');
require('./CCSys');
require('./CCLoader');
require('./CCMacro');
if (cc.sys.isBrowser || cc.sys.isNative) {
require('./load-manager');
require('./CCAssetLibrary');
}
-204
View File
@@ -1,204 +0,0 @@
var CallbacksInvoker = require('./callbacks-invoker');
function getBuiltinRawTypes () {
return {
image: {
loader: cc.loader.loadImg.bind(cc.loader),
defaultExtname: '.host'
},
json: {
loader: cc.loader.loadJson.bind(cc.loader),
defaultExtname: '.json'
},
text: {
loader: cc.loader.loadTxt.bind(cc.loader),
defaultExtname: '.txt'
}
};
}
var urlToCallbacks = new CallbacksInvoker();
// list of elements to load, the element type is {
// url: url,
// loader: loader,
// callback: callback,
// }
var loadQueue = [];
var loadNext = function () {
if (LoadManager._curConcurrent >= LoadManager.maxConcurrent) {
cc.error('too many concurrent requests');
return;
}
var nextOne = loadQueue.pop();
if (nextOne) {
doLoad(nextOne.loader, nextOne.url, nextOne.callback);
}
};
function doLoad (loader, url, callback) {
LoadManager._curConcurrent += 1;
loader(url, function doLoadCB (error, asset) {
callback(error, asset);
LoadManager._curConcurrent = Math.max(0, LoadManager._curConcurrent - 1);
loadNext();
});
}
/**
* The manager scheduling resources loading
* - It will:
* - select registered loader
* - merge same url request
* - limit the max concurrent request
* - It will NOT:
* - cache what has being loaded
* - load depends of resource
* @class LoadManager
* @static
*/
var LoadManager = {
/**
* Max allowed concurrent request count
* @property {Number} maxConcurrent
* @default 2
*/
maxConcurrent: 2,
/**
* Current concurrent request count
* @property {Number} _curConcurrent
* @readOnly
*/
_curConcurrent: 0,
/**
* NOTE: Request the same url with different loader is disallowed
* @method loadByLoader
* @param {Function} loader
* @param {String} url
* @param {Function} callback
* @param {String} callback.param error - null or the error info
* @param {any} callback.param data - the loaded data
* @private
*/
loadByLoader: function (loader, url, callback) {
if (urlToCallbacks.add(url, callback)) {
var callbackBundle = urlToCallbacks.bindKey(url, true);
if (this._curConcurrent < this.maxConcurrent) {
doLoad(loader, url, callbackBundle);
}
else {
loadQueue.push({
url: url,
loader: loader,
callback: callbackBundle
});
}
}
},
/**
* @method load
* @param {String} url
* @param {String} rawType
* @param {String} [rawExtname]
* @param {Function} callback
* @param {String} callback.param error - null or the error info
* @param {any} callback.param data - the loaded data
* @private
*/
load: function (url, rawType, rawExtname, callback) {
if (typeof rawExtname === 'function') {
callback = rawExtname;
}
var typeInfo = this._rawTypes[rawType];
if (typeInfo) {
var extname = rawExtname ? ('.' + rawExtname) : typeInfo.defaultExtname;
if (extname) {
var rawUrl = url + extname;
this.loadByLoader(typeInfo.loader, rawUrl, callback);
}
else {
callback(new Error('Undefined extname for the raw ' + rawType + ' file of ' + url), null);
}
}
else {
callback(new Error('Unknown raw type "' + rawType + '" of ' + url), null);
}
},
_rawTypes: getBuiltinRawTypes(),
/**
* @method registerRawTypes
* @param {String} rawType
* @param {Function} loader
* @param {String} defaultExtname
*/
registerRawTypes: function (rawType, loader, defaultExtname) {
if (CC_DEV) {
if (!rawType) {
cc.error('[AssetLibrary.registerRawTypes] rawType must be non-nil');
return;
}
if (typeof rawType !== 'string') {
cc.error('[AssetLibrary.registerRawTypes] rawType must be string');
return;
}
if (!loader) {
cc.error('[AssetLibrary.registerRawTypes] loader must be non-nil');
return;
}
if (typeof loader !== 'function') {
cc.error('[AssetLibrary.registerRawTypes] loader must be function');
return;
}
}
if (this._rawTypes[rawType]) {
cc.error('rawType "%s" has already defined', rawType);
return;
}
if (defaultExtname && defaultExtname[0] !== '.') {
defaultExtname = '.' + defaultExtname;
}
this._rawTypes[rawType] = {
loader: loader,
defaultExtname: defaultExtname
};
},
reset: function () {
if (CC_EDITOR) {
var audio = this._rawTypes.audio;
this._rawTypes = getBuiltinRawTypes();
this._rawTypes.audio = audio;
}
},
isLoading: function (url, alsoCheckRaw) {
if (CC_EDITOR) {
if (this._curConcurrent === 0) {
return false;
}
if (urlToCallbacks.has(url)) {
return true;
}
if (alsoCheckRaw) {
for (var u in urlToCallbacks._callbackTable) {
if (u.indexOf(url) === 0) {
return true;
}
}
}
return false;
}
}
};
// TODO - merge with cc.loader
cc._LoadManager = LoadManager;
module.exports = LoadManager;
+9 -8
View File
@@ -56,11 +56,12 @@ cc.LoaderScene = _ccsg.Scene.extend({
var fontSize = 24, lblHeight = -logoHeight / 2 + 100;
if(cc._loaderImage){
//loading logo
cc.loader.loadImg(cc._loaderImage, {isCrossOrigin : false }, function(err, img){
logoWidth = img.width;
logoHeight = img.height;
self._initStage(img, cc.visibleRect.center);
});
var img = new Image();
img.src = cc._loaderImage;
logoWidth = img.width;
logoHeight = img.height;
self._initStage(img, cc.visibleRect.center);
fontSize = 14;
lblHeight = -logoHeight / 2 - 10;
}
@@ -123,13 +124,13 @@ cc.LoaderScene = _ccsg.Scene.extend({
self.unschedule(self._startLoading);
var res = self.resources;
cc.loader.load(res,
function (result, count, loadedCount) {
function (loadedCount, count) {
var percent = (loadedCount / count * 100) | 0;
percent = Math.min(percent, 100);
self._label.setString("Loading... " + percent + "%");
}, function () {
}, function (error, items) {
if (self.cb)
self.cb.call(self.target);
self.cb.call(self.target, error, items);
});
},
+1 -1
View File
@@ -305,7 +305,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
* @return {SpriteFrame}
*/
clone: function () {
return new cc.SpriteFrame(this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize);
return new cc.SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize);
},
/**
+11 -11
View File
@@ -83,7 +83,7 @@ var textureCache = /** @lends cc.textureCache# */{
* @example {@link utils/api/engine/docs/cocos2d/core/textures/getTextureForKey.js}
*/
getTextureForKey: function(textureKeyName){
return this._textures[textureKeyName] || this._textures[cc.loader.getAliase(textureKeyName)];
return this._textures[textureKeyName];
},
/**
@@ -301,7 +301,7 @@ game.once(game.EVENT_RENDERER_INITED, function () {
var locTexs = this._textures;
//remove judge
var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)];
var tex = locTexs[url];
if (tex) {
if(tex.isLoaded()) {
cb && cb.call(target, tex);
@@ -318,11 +318,11 @@ game.once(game.EVENT_RENDERER_INITED, function () {
tex = locTexs[url] = new Texture2D();
tex.url = url;
cc.loader.loadImg(url, function (err, img) {
if (err)
return cb && cb.call(target, err);
cc.loader.load(url, function (err, items) {
if (err) {
return cb && cb.call(target, items.getError(url) || new Error('Unknown error'));
}
tex.initWithElement(img);
textureCache.handleLoadedTexture(url);
cb && cb.call(target, tex);
@@ -359,7 +359,7 @@ game.once(game.EVENT_RENDERER_INITED, function () {
if (!cc.game._rendererInitialized) {
locTexs = this._loadedTexturesBefore;
}
var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)];
var tex = locTexs[url];
if (tex) {
if(tex.isLoaded()) {
cb && cb.call(target, tex);
@@ -376,11 +376,11 @@ game.once(game.EVENT_RENDERER_INITED, function () {
tex = locTexs[url] = new Texture2D();
tex.url = url;
cc.loader.loadImg(url, function (err, img) {
if (err)
return cb && cb.call(target, err);
cc.loader.load(url, function (err, items) {
if (err) {
return cb && cb.call(target, items.getError(url) || new Error('Unknown error'));
}
tex.initWithElement(img);
textureCache.handleLoadedTexture(url);
cb && cb.call(target, tex);
-2
View File
@@ -24,8 +24,6 @@
THE SOFTWARE.
****************************************************************************/
require('../platform/CCLoader');
/**
* @module cc
* @class loader
-104
View File
@@ -866,107 +866,3 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
cc.LabelBMFont.create = function (str, fntFile, width, alignment, imageOffset) {
return new cc.LabelBMFont(str, fntFile, width, alignment, imageOffset);
};
cc._fntLoader = {
INFO_EXP: /info [^\n]*(\n|$)/gi,
COMMON_EXP: /common [^\n]*(\n|$)/gi,
PAGE_EXP: /page [^\n]*(\n|$)/gi,
CHAR_EXP: /char [^\n]*(\n|$)/gi,
KERNING_EXP: /kerning [^\n]*(\n|$)/gi,
ITEM_EXP: /\w+=[^ \r\n]+/gi,
INT_EXP: /^[\-]?\d+$/,
_parseStrToObj: function (str) {
var arr = str.match(this.ITEM_EXP);
var obj = {};
if (arr) {
for (var i = 0, li = arr.length; i < li; i++) {
var tempStr = arr[i];
var index = tempStr.indexOf("=");
var key = tempStr.substring(0, index);
var value = tempStr.substring(index + 1);
if (value.match(this.INT_EXP)) value = parseInt(value);
else if (value[0] === '"') value = value.substring(1, value.length - 1);
obj[key] = value;
}
}
return obj;
},
/**
* Parse Fnt string.
* @param fntStr
* @param url
* @returns {{}}
*/
parseFnt: function (fntStr, url) {
var self = this, fnt = {};
//padding
var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]);
var paddingArr = infoObj["padding"].split(",");
var padding = {
left: parseInt(paddingArr[0]),
top: parseInt(paddingArr[1]),
right: parseInt(paddingArr[2]),
bottom: parseInt(paddingArr[3])
};
//common
var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]);
fnt.commonHeight = commonObj["lineHeight"];
//font size
fnt.fontSize = infoObj["size"];
if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
var texSize = cc.configuration.getMaxTextureSize();
if (commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height)
cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported");
}
if (commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page");
//page
var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]);
if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found");
fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]);
//char
var charLines = fntStr.match(self.CHAR_EXP);
var fontDefDictionary = fnt.fontDefDictionary = {};
for (var i = 0, li = charLines.length; i < li; i++) {
var charObj = self._parseStrToObj(charLines[i]);
var charId = charObj["id"];
fontDefDictionary[charId] = {
rect: {x: charObj["x"], y: charObj["y"], width: charObj["width"], height: charObj["height"]},
xOffset: charObj["xoffset"],
yOffset: charObj["yoffset"],
xAdvance: charObj["xadvance"]
};
}
//kerning
var kerningDict = fnt.kerningDict = {};
var kerningLines = fntStr.match(self.KERNING_EXP);
if (kerningLines) {
for (var i = 0, li = kerningLines.length; i < li; i++) {
var kerningObj = self._parseStrToObj(kerningLines[i]);
kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"];
}
}
return fnt;
},
/**
* load the fnt
* @param realUrl
* @param url
* @param res
* @param cb
*/
load: function (realUrl, url, res, cb) {
var self = this;
cc.loader.loadTxt(realUrl, function (err, txt) {
if (err) return cb(err);
cb(null, self.parseFnt(txt, url));
});
}
};
cc.loader.register(["fnt"], cc._fntLoader);
+8 -5
View File
@@ -724,7 +724,10 @@ var ParticleSystem = cc.Class({
if (file) {
var self = this;
cc.loader.load(file, function (err, results) {
if (err) throw err;
var content = results.getContent(file);
if (err || !content) {
throw results.getError(file) || new Error('Unkown error');
}
sgNode.particleCount = 0;
@@ -733,15 +736,15 @@ var ParticleSystem = cc.Class({
// To avoid it export custom particle data textureImageData too large,
// so use the texutreUuid instead of textureImageData
if (results[0].textureUuid) {
cc.AssetLibrary.queryAssetInfo(results[0].textureUuid, function (err, url, raw) {
if (content.textureUuid) {
cc.AssetLibrary.queryAssetInfo(content.textureUuid, function (err, url, raw) {
self.texture = url;
});
}
// For custom data export
if (results[0].emissionRate) {
self.emissionRate = results[0].emissionRate;
if (content.emissionRate) {
self.emissionRate = content.emissionRate;
}
// recover sgNode properties
-3
View File
@@ -925,9 +925,6 @@ cc.TMXMapInfo.create = function (tmxFile, resourcePath) {
};
cc.loader.register(["tmx", "tsx"], cc._txtLoader);
/**
* @constant
* @type Number
+2 -2
View File
@@ -298,9 +298,9 @@ var TiledMap = cc.Class({
},
_preloadTmx: function(file, cb) {
cc.loader.load(file, function (err) {
cc.loader.load(file, function (err, items) {
if (err) {
if (cb) cb(err);
if (cb) cb(items.getError(file) || new Error('Unknown error'));
return;
}
+2 -2
View File
@@ -214,7 +214,7 @@ cc.LoaderLayer = cc.Layer.extend({
}
var self = this;
//var progressFunction = self.config.progressCallback ? self.config.progressCallback : null;
cc.loader.load(res, function (result, count, loadedCount) {
cc.loader.load(res, function (loadedCount, count) {
var checkGroupName = function (loadedCount) {
for (var i = 0; i < groupIndex.length; i++) {
if (groupIndex[i] >= loadedCount) {
@@ -451,7 +451,7 @@ cc.LoaderLayer.preload = function (groupname, callback, target) {
cc.Dialog._finalConfig.cancelBtn.normalRes,
cc.Dialog._finalConfig.cancelBtn.pressRes
],
function (result, count, loadedCount) {
function (loadedCount, count, result) {
var percent = (loadedCount / count * 100) | 0;
percent = Math.min(percent, 100);
cc.log("Preloading engine resources... " + percent + "%");
-2
View File
@@ -12,7 +12,6 @@ var srcs = [
'./cocos2d/core/platform/CCCommon.js',
'./cocos2d/core/platform/CCSAXParser.js',
'./cocos2d/core/platform/CCLoaders.js',
'./cocos2d/core/platform/CCConfig.js',
'./cocos2d/core/platform/miniFramework.js',
'./cocos2d/core/platform/CCEGLView.js',
@@ -65,7 +64,6 @@ var srcs = [
'./cocos2d/core/CCDrawingPrimitivesCanvas.js',
'./cocos2d/core/CCDrawingPrimitivesWebGL.js',
'./cocos2d/core/label/FNTLoader.js',
'./cocos2d/core/label/CCSGLabel.js',
'./cocos2d/core/label/CCSGLabelCanvasRenderCmd.js',
'./cocos2d/core/label/CCSGLabelWebGLRenderCmd.js',
+2 -2
View File
@@ -20,9 +20,9 @@ paths = {
'../../cocos2d/core/CCGame',
'../../cocos2d/core/textures/CCTexture2D',
'../../cocos2d/core/sprites/CCSpriteFrame',
'../../cocos2d/core/platform/CCLoader',
'../../cocos2d/core/platform/CCLoaders',
'../../cocos2d/core/event/event',
'../../cocos2d/core/load-pipeline/audio-downloader',
'../../cocos2d/audio/CCAudio',
'../../extensions/spine/SGSkeleton',
'../../extensions/spine/SGSkeletonAnimation',
'../../extensions/spine/SGSkeletonCanvasRenderCmd',
+1
View File
@@ -11,6 +11,7 @@ cc.initEngine = function (config, cb) {
};
require('./jsb-predefine');
require('./jsb-loader');
require('./jsb-game');
require('./jsb-director');
require('./jsb-tex-sprite-frame');
+2 -2
View File
@@ -97,8 +97,8 @@ cc.js.mixin(cc.game, {
// Load game scripts
var jsList = config[CONFIG_KEY.jsList];
if (jsList) {
cc.loader.loadJs(jsList, function (err) {
if (err) throw new Error(err);
cc.loader.load(jsList, function (err) {
if (err) throw new Error(JSON.stringify(err));
self._prepared = true;
if (cb) cb();
});
+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.
****************************************************************************/
'use strict';
require('../cocos2d/core/load-pipeline');
function empty (item, callback) {
callback(null, null);
}
function downloadScript (item, callback) {
var url = item.src;
require(url);
callback(null, url);
}
function downloadText (item, callback) {
var url = item.src;
var result = jsb.fileUtils.getStringFromFile(url);
if (typeof result === 'string') {
callback(null, result);
}
else {
callback(new Error('Download text failed: ' + url));
}
}
cc.loader.addDownloadHandlers({
// JS
'js' : downloadScript,
// Images
'png' : empty,
'jpg' : empty,
'bmp' : empty,
'jpeg' : empty,
'gif' : empty,
'ico' : empty,
'tiff' : empty,
'webp' : empty,
// Audio
'mp3' : empty,
'ogg' : empty,
'wav' : empty,
'mp4' : empty,
'm4a' : empty,
// Txt
'txt' : downloadText,
'xml' : downloadText,
'vsh' : downloadText,
'fsh' : downloadText,
'atlas' : downloadText,
'tmx' : downloadText,
'tsx' : downloadText,
'json' : downloadText,
'ExportJson' : downloadText,
'plist' : downloadText,
'fnt' : downloadText,
// Font
'font' : empty,
'eot' : empty,
'ttf' : empty,
'woff' : empty,
'svg' : empty,
'ttc' : empty,
'default' : downloadText
});
function loadImage (item, callback) {
var url = item.src;
var cachedTex = cc.textureCache.getTextureForKey(url);
if (cachedTex) {
callback && callback(null, cachedTex);
}
else if (url.match(jsb.urlRegExp)) {
jsb.loadRemoteImg(url, function(succeed, tex) {
if (succeed) {
callback && callback(null, tex);
}
else {
callback && callback(new Error('Load image failed: ' + url));
}
});
}
else {
cc.textureCache._addImageAsync(url, function (tex){
if (tex instanceof cc.Texture2D) {
callback && callback(null, tex);
}
else {
callback && callback(new Error('Load image failed: ' + url));
}
});
}
}
cc.loader.addLoadHandlers({
// Images
'png' : loadImage,
'jpg' : loadImage,
'bmp' : loadImage,
'jpeg' : loadImage,
'gif' : loadImage,
'ico' : loadImage,
'tiff' : loadImage,
'webp' : loadImage,
'default' : empty
});
-1
View File
@@ -45,7 +45,6 @@
"cocos2d/core/platform/CCClass.js",
"cocos2d/core/platform/CCCommon.js",
"cocos2d/core/platform/CCSAXParser.js",
"cocos2d/core/platform/CCLoaders.js",
"cocos2d/core/platform/CCConfig.js",
"cocos2d/core/platform/miniFramework.js",
"cocos2d/core/platform/CCMacro.js",
-1
View File
@@ -56,7 +56,6 @@ require('./cocos2d/core/platform/CCInputManager');
require('./cocos2d/core/platform/CCInputExtension');
require('./cocos2d/core/event');
require('./cocos2d/core/platform/CCSys');
require('./cocos2d/core/platform/CCLoader');
require('./cocos2d/core/load-pipeline');
require('./cocos2d/core/CCDirector');
require('./cocos2d/core/CCDirectorWebGL');
-68
View File
@@ -1,68 +0,0 @@
module('LoadManager', {
setup: function () {
}
});
asyncTest('base', function () {
var dummyAsset = {};
var myLoader = function (url, callback, onProgress) {
setTimeout(function () {
cb.enable();
callback(null, dummyAsset);
}, 1);
};
var cb = new Callback(function (err, asset) {
strictEqual(asset, dummyAsset, 'should return the right asset');
clearTimeout(timerId);
start();
});
LoadManager.loadByLoader(myLoader, '', cb);
var timerId = setTimeout(function () {
ok(false, 'time out!');
start();
}, 100);
});
asyncTest('Concurrent', function () {
strictEqual(LoadManager._curConcurrent, 0, 'should finish all tasks');
LoadManager.maxConcurrent = 1;
var cb = new Callback().enable();
var immediateLoader = function (url, callback, onProgress) {
callback();
};
LoadManager.loadByLoader(immediateLoader, '', cb);
cb.once('should load immediate if concurrent < max');
LoadManager.loadByLoader(immediateLoader, '', cb);
cb.once('should load immediate again');
var asyncLoader = function (url, callback, onProgress) {
setTimeout(function () {
callback();
}, 1);
};
cb.disable('should wait for first loaded');
// load first
LoadManager.loadByLoader(asyncLoader, '', function () {
cb.enable();
});
cb.callbackFunction(function () {
clearTimeout(timerId);
start();
});
// deferred load second
LoadManager.loadByLoader(asyncLoader, '', cb);
var timerId = setTimeout(function () {
ok(false, 'time out!');
start();
}, 100);
});
+12 -23
View File
@@ -1,6 +1,6 @@
largeModule('Loader');
var loader = cc._loader;
var loader = cc.loader;
asyncTest('Load', function () {
var image1 = assetDir + '/button.png';
@@ -25,7 +25,7 @@ asyncTest('Load', function () {
else {
ok(false, 'should not load an unknown url');
}
}, function (items) {
}, function (error, items) {
ok(items.isCompleted(), 'be able to load all resources');
loader.releaseAll();
@@ -79,11 +79,7 @@ asyncTest('Load with dependencies', function () {
audio
];
var total = resources.length + 3;
var dep1Loaded = false;
var dep2Loaded = false;
var dep3Loaded = false;
var total = resources.length;
var items = loader.getItems();
@@ -93,25 +89,18 @@ asyncTest('Load with dependencies', function () {
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');
var dep = this.getRes(dep1);
ok(dep instanceof cc.Texture2D, 'should correctly load dependent image1');
dep = this.getRes(dep2);
strictEqual(dep.width, 89, 'should correctly load dependent JSON');
dep = this.getRes(dep3);
ok(dep instanceof cc.Texture2D, 'should correctly load dependent image2');
strictEqual(item.content.__type__, 'TestTexture', 'should give correct js object as result of deps type');
}
else if (item.src === json2) {
strictEqual(item.content._rawFiles[0], 'YouKnowEverything', 'should give correct js object as result of JSON');
}
else if (item.src === dep1) {
dep1Loaded = true;
ok(item.content instanceof cc.Texture2D, 'image url\'s result should be Texture2D');
}
else if (item.src === dep2) {
dep2Loaded = true;
strictEqual(item.content.width, 89, 'should give correct js object as result of JSON');
}
else if (item.src === dep3) {
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');
@@ -121,7 +110,7 @@ asyncTest('Load with dependencies', function () {
}
}).enable();
loader.load(resources, progressCallback, function (items) {
loader.load(resources, progressCallback, function (error, items) {
ok(items.isCompleted(), 'be able to load all resources');
progressCallback.expect(total, 'should call ' + total + ' times progress callback for ' + total + ' resources');
loader.releaseAll();
@@ -162,7 +151,7 @@ asyncTest('Loading font', function () {
}
}).enable();
loader.load(resources, progressCallback, function (items) {
loader.load(resources, progressCallback, function (error, items) {
ok(items.isCompleted(), 'be able to load all resources');
progressCallback.expect(total, 'should call ' + total + ' times progress callback for ' + total + ' resources');
+22 -2
View File
@@ -96,7 +96,11 @@ test('pipeline flow', function () {
}
]);
var onComplete = new Callback().enable();
var onComplete = new Callback(function (error, items) {
ok(error instanceof Array, 'should return error array in onComplete when error happened');
strictEqual(error[0], 'res/role', 'should contains correct errored url in error array');
ok(items.getError('res/role') !== null, 'should set error property in errored item.');
}).enable();
var onProgress = new Callback().enable();
pipeline.onComplete = onComplete;
pipeline.onProgress = onProgress;
@@ -125,6 +129,22 @@ test('pipeline flow', function () {
onProgress.expect(4, 'should call onProgress callback 4 times');
});
test('flow empty array', function () {
var onComplete = new Callback(function (error, items) {
strictEqual(error, null, 'shouldn\'t return error after flowIn empty array');
strictEqual(items.totalCount, 0, 'should contains zero item in items');
strictEqual(items.completedCount, 0, 'should contains zero completed item');
}).enable();
var onProgress = new Callback().enable();
pipeline.onComplete = onComplete;
pipeline.onProgress = onProgress;
pipeline.flowIn([]);
onComplete.expect(1, 'should call onComplete after flowIn empty array');
onProgress.expect(0, 'shouldn\'t call onProgress after flowIn empty array');
});
asyncTest('content manipulation', function () {
var init = function (item) {
if (!item.type) {
@@ -160,7 +180,7 @@ asyncTest('content manipulation', function () {
}
]);
pipeline.onComplete = function (items) {
pipeline.onComplete = function (error, items) {
ok(true, 'should call onComplete at the end');
strictEqual(items.completedCount, 4, 'should complete all 4 items');
strictEqual(items.isCompleted(), true, 'should be completed');
+13 -9
View File
@@ -139,15 +139,20 @@
asyncTest('revert prefab', function () {
// stub
var restore = cc.loader.loadTxt;
cc.loader.loadTxt = function (url, callback) {
if (url.endsWith(UUID + '.json')) {
callback(null, JSON.stringify(prefabJson));
cc.loader.insertPipe({
id : 'Prefab_Provider',
async : false,
handle : function (item) {
var url = item.src;
if (url === UUID) {
item.states['Downloader'] = cc.Pipeline.ItemState.COMPLETE;
return JSON.stringify(prefabJson);
}
else {
return;
}
}
else {
restore(url, callback);
}
};
}, 0);
var testNode = cc.instantiate(prefab);
var testChild = testNode.children[0];
@@ -166,7 +171,6 @@
newNode2.setSiblingIndex(0);
_Scene.PrefabUtils.revertPrefab(testNode, function () {
cc.loader.loadTxt = restore;
ok(testNode.getScaleX() === 123 && testNode.getScaleY() === 432, 'Revert property of the parent node');
ok(testNode.getComponent(TestScript).constructor === TestScript, 'Restore removed component');
var c = testNode.children[0];
-5
View File
@@ -116,7 +116,6 @@ cc.game.run({
"src/tests-main.js",
"src/PathTest/PathTest.js",
"src/LoaderTest/LoaderTest.js",
"src/BakeLayerTest/BakeLayerTest.js",
@@ -189,10 +188,6 @@ cc.game.run({
}
jsb.fileUtils.setSearchPaths(searchPaths);
}
else
{
cc.loader.resPath = 'res';
}
cc.LoaderScene.preload(g_resources, function () {
if(window.sideIndexBar && typeof sideIndexBar.start === 'function'){
@@ -73,20 +73,20 @@ var ActionsDemo = BaseTestLayer.extend({
this._tamara.visible = false;
this._kathia.visible = false;
this._grossini.visible = false;
} else if (numberOfSprites == 1) {
} else if (numberOfSprites === 1) {
this._tamara.visible = false;
this._kathia.visible = false;
this._grossini.x = winSize.width / 2;
this._grossini.y = winSize.height / 2;
}
else if (numberOfSprites == 2) {
else if (numberOfSprites === 2) {
this._kathia.x = winSize.width / 3;
this._kathia.y = winSize.height / 2;
this._tamara.x = 2 * winSize.width / 3;
this._tamara.y = winSize.height / 2;
this._grossini.visible = false;
}
else if (numberOfSprites == 3) {
else if (numberOfSprites === 3) {
this._grossini.x = winSize.width / 2;
this._grossini.y = winSize.height / 2;
this._tamara.x = winSize.width / 4;
@@ -974,7 +974,7 @@ var ActionAnimate = ActionsDemo.extend({
//
var animation = new cc.SpriteFrameAnimation();
for (var i = 1; i < 15; i++) {
var frameName = "Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png";
var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png";
animation.addSpriteFrameWithFile(frameName);
}
animation.setDelayPerUnit(2.8 / 14);
@@ -1668,7 +1668,7 @@ var ActionFollow = ActionsDemo.extend({
this._grossini.runAction(rep);
this.runAction(cc.follow(this._grossini, cc.rect(0, 0, s.width * 2 - 100, s.height)));
this.runAction(cc.follow(this._grossini));
//----end30----
},
subtitle:function () {
@@ -2515,7 +2515,7 @@ var Issue1438 = ActionsDemo.extend({
// Add 60 frames
for (var j = 0; j < 4; j++) {
for (var i = 1; i < 15; i++) {
var frameName = "Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png";
var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png";
animation.addSpriteFrameWithFile(frameName);
}
}
@@ -2837,7 +2837,7 @@ var ActionCustomTest = ActionsDemo.extend({
spriteTemp = this.addandCreateSpriteTemp("cc.Animate");
var animation = new cc.SpriteFrameAnimation();
for (var i = 1; i < 15; i++) {
var frameName = "Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png";
var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png";
animation.addSpriteFrameWithFile(frameName);
}
animation.setDelayPerUnit(5 / 14);
@@ -26,8 +26,8 @@
var audioEngine = cc.audioEngine;
var MUSIC_FILE = cc.sys.os == cc.sys.OS_WINRT ? "background.wav" : "background.mp3";
var EFFECT_FILE = cc.sys.os == cc.sys.OS_WINRT ? "effect1.wav" : "effect2.mp3";
var MUSIC_FILE = "res/background.mp3";
var EFFECT_FILE = "res/effect2.mp3";
var _DenshionTests = [
'Music Test'
@@ -738,7 +738,7 @@ var SchedulerTest = EaseSpriteDemo.extend({
var emitter = new cc.ParticleFireworks();
emitter.setTotalParticles(250);
emitter.texture = cc.textureCache.addImage("Images/fire.png");
emitter.texture = cc.textureCache.addImage("res/Images/fire.png");
this.addChild(emitter);
//----end13----
},
@@ -111,7 +111,7 @@ var S9CreationTest = S9SpriteTestDemo.extend({
var x = winSize.width;
var y = 0 + (winSize.height/2);
var s9sprite1 = new cc.Scale9Sprite("Images/blocks.png");
var s9sprite1 = new cc.Scale9Sprite("res/Images/blocks.png");
var s9sprite2 = new cc.Scale9Sprite("blocks9.png");
+46 -46
View File
@@ -98,13 +98,13 @@ var LabelAtlasOpacityTest = AtlasDemo.extend({
this._super();
this.time = 0;
var label1 = new cc.LabelAtlas("123 Test", s_resprefix + "fonts/tuffy_bold_italic-charmap.plist");
var label1 = new cc.LabelAtlas("123 Test", "res/fonts/tuffy_bold_italic-charmap.plist");
this.addChild(label1, 0, TAG_LABEL_SPRITE1);
label1.x = 10;
label1.y = 100;
label1.opacity = 200;
var label2 = new cc.LabelAtlas("0123456789", s_resprefix + "fonts/tuffy_bold_italic-charmap.plist");
var label2 = new cc.LabelAtlas("0123456789", "res/fonts/tuffy_bold_italic-charmap.plist");
this.addChild(label2, 0, TAG_LABEL_SPRITE12);
label2.x = 10;
label2.y = 200;
@@ -164,13 +164,13 @@ var LabelAtlasOpacityColorTest = AtlasDemo.extend({
ctor:function () {
//----start1----ctor
this._super();
var label1 = new cc.LabelAtlas("123 Test", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' ');
var label1 = new cc.LabelAtlas("123 Test", "res/fonts/tuffy_bold_italic-charmap.png", 48, 64, ' ');
this.addChild(label1, 0, TAG_LABEL_SPRITE1);
label1.x = 10;
label1.y = 100;
label1.opacity = 200;
var label2 = new cc.LabelAtlas("0123456789", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' ');
var label2 = new cc.LabelAtlas("0123456789", "res/fonts/tuffy_bold_italic-charmap.png", 48, 64, ' ');
this.addChild(label2, 0, TAG_LABEL_SPRITE12);
label2.x = 10;
label2.y = 200;
@@ -242,7 +242,7 @@ var LabelAtlasHD = AtlasDemo.extend({
var s = director.getWinSize();
// cc.LabelBMFont
var label1 = new cc.LabelAtlas("TESTING RETINA DISPLAY", s_resprefix + "fonts/larabie-16.plist");
var label1 = new cc.LabelAtlas("TESTING RETINA DISPLAY", "res/fonts/larabie-16.plist");
label1.anchorX = 0.5;
label1.anchorY = 0.5;
@@ -298,7 +298,7 @@ var BMFontOpacityColorAlignmentTest = AtlasDemo.extend({
var col = new cc.LayerColor(cc.color(128, 128, 128, 255));
this.addChild(col, -10);
var label1 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt");
var label1 = new cc.LabelBMFont("Test", "res/fonts/bitmapFontTest2.fnt");
// testing anchors
label1.anchorX = 0;
@@ -314,7 +314,7 @@ var BMFontOpacityColorAlignmentTest = AtlasDemo.extend({
// color and opacity work OK because bitmapFontAltas2 loads a BMP image (not a PNG image)
// If you want to use both opacity and color, it is recommended to use NON premultiplied images like BMP images
// Of course, you can also tell XCode not to compress PNG images, but I think it doesn't work as expected
var label2 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt");
var label2 = new cc.LabelBMFont("Test", "res/fonts/bitmapFontTest2.fnt");
// testing anchors
label2.anchorX = 0.5;
label2.anchorY = 0.5;
@@ -322,7 +322,7 @@ var BMFontOpacityColorAlignmentTest = AtlasDemo.extend({
this.addChild(label2, 0, TAG_BITMAP_ATLAS2);
label2.runAction(repeat.clone());
var label3 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt");
var label3 = new cc.LabelBMFont("Test", "res/fonts/bitmapFontTest2.fnt");
// testing anchors
label3.anchorX = 1;
label3.anchorY = 1;
@@ -408,7 +408,7 @@ var BMFontSubSpriteTest = AtlasDemo.extend({
drawNode.drawSegment(cc.p(s.width / 2, 0), cc.p(s.width / 2, s.height), 2);
// Upper Label
var label = new cc.LabelBMFont("Bitmap Font Atlas", s_resprefix + "fonts/bitmapFontTest.fnt");
var label = new cc.LabelBMFont("Bitmap Font Atlas", "res/fonts/bitmapFontTest.fnt");
this.labelObj = label;
this.addChild(label);
@@ -453,7 +453,7 @@ var BMFontSubSpriteTest = AtlasDemo.extend({
AChar.runAction(fade_4ever);
// Bottom Label
var label2 = new cc.LabelBMFont("00.0", s_resprefix + "fonts/bitmapFontTest.fnt");
var label2 = new cc.LabelBMFont("00.0", "res/fonts/bitmapFontTest.fnt");
this.addChild(label2, 0, TAG_BITMAP_ATLAS2);
label2.x = s.width / 2.0;
label2.y = 80;
@@ -510,7 +510,7 @@ var BMFontPaddingTest = AtlasDemo.extend({
ctor:function () {
//----start5----
this._super();
var label = new cc.LabelBMFont("abcdefg", s_resprefix + "fonts/bitmapFontTest4.fnt");
var label = new cc.LabelBMFont("abcdefg", "res/fonts/bitmapFontTest4.fnt");
this.addChild(label);
var s = director.getWinSize();
@@ -563,21 +563,21 @@ var BMFontOffsetTest = AtlasDemo.extend({
var s = director.getWinSize();
var label = null;
label = new cc.LabelBMFont("FaFeFiFoFu", s_resprefix + "fonts/bitmapFontTest5.fnt");
label = new cc.LabelBMFont("FaFeFiFoFu", "res/fonts/bitmapFontTest5.fnt");
this.addChild(label);
label.x = s.width / 2;
label.y = s.height / 2 + 50;
label.anchorX = 0.5;
label.anchorY = 0.5;
label = new cc.LabelBMFont("fafefifofu", s_resprefix + "fonts/bitmapFontTest5.fnt");
label = new cc.LabelBMFont("fafefifofu", "res/fonts/bitmapFontTest5.fnt");
this.addChild(label);
label.x = s.width / 2;
label.y = s.height / 2;
label.anchorX = 0.5;
label.anchorY = 0.5;
label = new cc.LabelBMFont("aeiou", s_resprefix + "fonts/bitmapFontTest5.fnt");
label = new cc.LabelBMFont("aeiou", "res/fonts/bitmapFontTest5.fnt");
this.addChild(label);
label.x = s.width / 2;
label.y = s.height / 2 - 50;
@@ -628,7 +628,7 @@ var BMFontTintTest = AtlasDemo.extend({
var s = director.getWinSize();
var label = null;
label = new cc.LabelBMFont("Blue", s_resprefix + "fonts/bitmapFontTest5.fnt");
label = new cc.LabelBMFont("Blue", "res/fonts/bitmapFontTest5.fnt");
label.color = cc.color(0, 0, 255);
this.addChild(label);
label.x = s.width / 2;
@@ -636,7 +636,7 @@ var BMFontTintTest = AtlasDemo.extend({
label.anchorX = 0.5;
label.anchorY = 0.5;
label = new cc.LabelBMFont("Red", s_resprefix + "fonts/bitmapFontTest5.fnt");
label = new cc.LabelBMFont("Red", "res/fonts/bitmapFontTest5.fnt");
this.addChild(label);
label.x = s.width / 2;
label.y = 2 * s.height / 4;
@@ -644,7 +644,7 @@ var BMFontTintTest = AtlasDemo.extend({
label.anchorY = 0.5;
label.color = cc.color(255, 0, 0);
label = new cc.LabelBMFont("G", s_resprefix + "fonts/bitmapFontTest5.fnt");
label = new cc.LabelBMFont("G", "res/fonts/bitmapFontTest5.fnt");
this.addChild(label);
label.x = s.width / 2;
label.y = 3 * s.height / 4;
@@ -698,7 +698,7 @@ var BMFontSpeedTest = AtlasDemo.extend({
// Upper Label
for (var i = 0; i < 100; i++) {
var str = "-" + i + "-";
var label = new cc.LabelBMFont(str, s_resprefix + "fonts/bitmapFontTest.fnt");
var label = new cc.LabelBMFont(str, "res/fonts/bitmapFontTest.fnt");
this.addChild(label);
var s = director.getWinSize();
@@ -729,7 +729,7 @@ var BMFontMultiLineTest = AtlasDemo.extend({
this._super();
// Left
var label1 = new cc.LabelBMFont("Multi line\nLeft", s_resprefix + "fonts/bitmapFontTest3.fnt");
var label1 = new cc.LabelBMFont("Multi line\nLeft", "res/fonts/bitmapFontTest3.fnt");
label1.anchorX = 0;
label1.anchorY = 0;
this.addChild(label1, 0, TAG_BITMAP_ATLAS1);
@@ -737,14 +737,14 @@ var BMFontMultiLineTest = AtlasDemo.extend({
// Center
var label2 = new cc.LabelBMFont("Multi line\nCenter", s_resprefix + "fonts/bitmapFontTest3.fnt");
var label2 = new cc.LabelBMFont("Multi line\nCenter", "res/fonts/bitmapFontTest3.fnt");
label2.anchorX = 0.5;
label2.anchorY = 0.5;
this.addChild(label2, 0, TAG_BITMAP_ATLAS2);
cc.log("content size:" + label2.width + "," + label2.height);
// right
var label3 = new cc.LabelBMFont("Multi line\nRight\nThree lines Three", s_resprefix + "fonts/bitmapFontTest3.fnt");
var label3 = new cc.LabelBMFont("Multi line\nRight\nThree lines Three", "res/fonts/bitmapFontTest3.fnt");
label3.anchorX = 1;
label3.anchorY = 1;
this.addChild(label3, 0, TAG_BITMAP_ATLAS3);
@@ -804,7 +804,7 @@ var BMFontMultiLine2Test = AtlasDemo.extend({
this._super();
// Left
var label1 = new cc.LabelBMFont("Multi line\n\nAligned to the left", s_resprefix + "fonts/bitmapFontTest3.fnt");
var label1 = new cc.LabelBMFont("Multi line\n\nAligned to the left", "res/fonts/bitmapFontTest3.fnt");
label1.anchorX = 0;
label1.anchorY = 0;
label1.textAlign = cc.TextAlignment.LEFT;
@@ -814,7 +814,7 @@ var BMFontMultiLine2Test = AtlasDemo.extend({
// Center
var label2 = new cc.LabelBMFont("Error\n\nSome error message", s_resprefix + "fonts/bitmapFontTest3.fnt");
var label2 = new cc.LabelBMFont("Error\n\nSome error message", "res/fonts/bitmapFontTest3.fnt");
label2.anchorX = 0.5;
label2.anchorY = 0.5;
label2.textAlign = cc.TextAlignment.CENTER;
@@ -823,7 +823,7 @@ var BMFontMultiLine2Test = AtlasDemo.extend({
cc.log("content size:" + label2.width + "," + label2.height);
// right
var label3 = new cc.LabelBMFont("Multi line\n\nAligned to the right", s_resprefix + "fonts/bitmapFontTest3.fnt");
var label3 = new cc.LabelBMFont("Multi line\n\nAligned to the right", "res/fonts/bitmapFontTest3.fnt");
label3.anchorX = 1;
label3.anchorY = 1;
label3.textAlign = cc.TextAlignment.RIGHT;
@@ -884,7 +884,7 @@ var LabelsEmpty = AtlasDemo.extend({
// cc.LabelBMFont
var label1 = new cc.LabelBMFont("", s_resprefix + "fonts/bitmapFontTest3.fnt");
var label1 = new cc.LabelBMFont("", "res/fonts/bitmapFontTest3.fnt");
this.addChild(label1, 0, TAG_BITMAP_ATLAS1);
label1.x = winSize.width / 2;
label1.y = winSize.height - 100;
@@ -896,7 +896,7 @@ var LabelsEmpty = AtlasDemo.extend({
label2.y = winSize.height / 2;
// cc.LabelAtlas
var label3 = new cc.LabelAtlas("", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' ');
var label3 = new cc.LabelAtlas("", "res/fonts/tuffy_bold_italic-charmap.png", 48, 64, ' ');
this.addChild(label3, 0, TAG_BITMAP_ATLAS3);
label3.x = winSize.width / 2;
label3.y = 0 + 100;
@@ -948,7 +948,7 @@ var BMFontHDTest = AtlasDemo.extend({
var s = director.getWinSize();
// cc.LabelBMFont
var label1 = new cc.LabelBMFont("TESTING RETINA DISPLAY", s_resprefix + "fonts/konqa32.fnt");
var label1 = new cc.LabelBMFont("TESTING RETINA DISPLAY", "res/fonts/konqa32.fnt");
this.addChild(label1);
label1.x = s.width / 2;
label1.y = s.height / 2;
@@ -1001,7 +1001,7 @@ var BMFontGlyphDesignerTest = AtlasDemo.extend({
this.addChild(layer, -10);
// cc.LabelBMFont
var label1 = new cc.LabelBMFont("Testing Glyph Designer", s_resprefix + "fonts/futura-48.fnt");
var label1 = new cc.LabelBMFont("Testing Glyph Designer", "res/fonts/futura-48.fnt");
this.addChild(label1);
label1.x = s.width / 2;
label1.y = s.height / 2;
@@ -1354,7 +1354,7 @@ var BMFontChineseTest = AtlasDemo.extend({
//----start18----ctor
this._super();
var size = director.getWinSize();
var label = new cc.LabelBMFont("中国", s_resprefix + "fonts/bitmapFontChinese.fnt");
var label = new cc.LabelBMFont("中国", "res/fonts/bitmapFontChinese.fnt");
label.x = size.width / 2;
label.y = size.height / 2;
this.addChild(label);
@@ -1449,9 +1449,9 @@ var BMFontMultiLineAlignmentTest = AtlasDemo.extend({
var size = director.getWinSize();
// create and initialize a Label
this.labelShouldRetain = new cc.LabelBMFont(LongSentencesExample, s_resprefix + "fonts/markerFelt.fnt", size.width / 2, cc.TextAlignment.CENTER, cc.p(0, 0));
this.arrowsBarShouldRetain = new _ccsg.Sprite(s_resprefix + "Images/arrowsBar.png");
this.arrowsShouldRetain = new _ccsg.Sprite(s_resprefix + "Images/arrows.png");
this.labelShouldRetain = new cc.LabelBMFont(LongSentencesExample, "res/fonts/markerFelt.fnt", size.width / 2, cc.TextAlignment.CENTER, cc.p(0, 0));
this.arrowsBarShouldRetain = new _ccsg.Sprite("res/Images/arrowsBar.png");
this.arrowsShouldRetain = new _ccsg.Sprite("res/Images/arrows.png");
cc.MenuItemFont.setFontSize(20);
var longSentences = new cc.MenuItemFont("Long Flowing Sentences", this.onStringChanged, this);
@@ -1558,26 +1558,26 @@ var BMFontMultiLineAlignmentTest = AtlasDemo.extend({
switch (sender.tag) {
case LongSentences:
this.labelShouldRetain.setString(LongSentencesExample);
this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt");
this.labelShouldRetain.setFntFile("res/fonts/markerFelt.fnt");
break;
case LineBreaks:
this.labelShouldRetain.setString(LineBreaksExample);
this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt");
this.labelShouldRetain.setFntFile("res/fonts/markerFelt.fnt");
break;
case Mixed:
this.labelShouldRetain.setString(MixedExample);
this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt");
this.labelShouldRetain.setFntFile("res/fonts/markerFelt.fnt");
break;
case chineseText:
this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt");
this.labelShouldRetain.setFntFile("res/fonts/arial-unicode-26.fnt");
this.labelShouldRetain.setString(chineseExampleText);
break;
case chineseMixEnglish:
this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt");
this.labelShouldRetain.setFntFile("res/fonts/arial-unicode-26.fnt");
this.labelShouldRetain.setString(chineseMixEnglishText);
break;
case mixAllLanguage:
this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt");
this.labelShouldRetain.setFntFile("res/fonts/arial-unicode-26.fnt");
this.labelShouldRetain.setString(mixAllLanguageText);
break;
default:
@@ -1698,12 +1698,12 @@ var BMFontOneAtlas = AtlasDemo.extend({
this._super();
var s = director.getWinSize();
var label1 = new cc.LabelBMFont("This is Helvetica", s_resprefix + "fonts/helvetica-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 0));
var label1 = new cc.LabelBMFont("This is Helvetica", "res/fonts/helvetica-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 0));
this.addChild(label1);
label1.x = s.width / 2;
label1.y = s.height * 2 / 3;
var label2 = new cc.LabelBMFont("And this is Geneva", s_resprefix + "fonts/geneva-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 128));
var label2 = new cc.LabelBMFont("And this is Geneva", "res/fonts/geneva-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 128));
this.addChild(label2);
label2.x = s.width / 2;
label2.y = s.height / 3;
@@ -1728,17 +1728,17 @@ var BMFontUnicode = AtlasDemo.extend({
var japanese = "良い一日を";
var spanish = "Buen día";
var label1 = new cc.LabelBMFont(spanish, s_resprefix + "fonts/arial-unicode-26.fnt", 200, cc.TextAlignment.LEFT);
var label1 = new cc.LabelBMFont(spanish, "res/fonts/arial-unicode-26.fnt", 200, cc.TextAlignment.LEFT);
this.addChild(label1);
label1.x = winSize.width / 2;
label1.y = winSize.height / 4;
var label2 = new cc.LabelBMFont(chinese, s_resprefix + "fonts/arial-unicode-26.fnt");
var label2 = new cc.LabelBMFont(chinese, "res/fonts/arial-unicode-26.fnt");
this.addChild(label2);
label2.x = winSize.width / 2;
label2.y = winSize.height / 2.2;
var label3 = new cc.LabelBMFont(japanese, s_resprefix + "fonts/arial-unicode-26.fnt");
var label3 = new cc.LabelBMFont(japanese, "res/fonts/arial-unicode-26.fnt");
this.addChild(label3);
label3.x = winSize.width / 2;
label3.y = winSize.height / 1.5;
@@ -1759,7 +1759,7 @@ var BMFontInit = AtlasDemo.extend({
this._super();
var bmFont = new cc.LabelBMFont();
bmFont.setFntFile(s_resprefix + "fonts/helvetica-32.fnt");
bmFont.setFntFile("res/fonts/helvetica-32.fnt");
bmFont.setString("It is working!");
this.addChild(bmFont);
bmFont.x = winSize.width / 2;
@@ -1857,7 +1857,7 @@ var BMFontColorParentChild = AtlasDemo.extend({
//----start15----ctor
this._super();
this.label = new cc.LabelBMFont("YRGB", s_resprefix + "fonts/konqa32.fnt");
this.label = new cc.LabelBMFont("YRGB", "res/fonts/konqa32.fnt");
this.addChild(this.label);
this.label.x = winSize.width / 2;
this.label.y = winSize.height / 2;
@@ -2324,7 +2324,7 @@ var LabelLayoutBaseTest = AtlasDemo.extend({
_initTestLabel: function(winSize){
var center = cc.visibleRect.center;
this._label = new _ccsg.Label("Hello World. This is a very long sentence Hehe.", s_resprefix + "fonts/bitmapFontTest2.fnt", _ccsg.Label.Type.BMFont);
this._label = new _ccsg.Label("Hello World. This is a very long sentence Hehe.", "res/fonts/bitmapFontTest2.fnt", _ccsg.Label.Type.BMFont);
this._label.setDimensions(winSize.width/2, winSize.height/2);
this._label.setLineBreakWithoutSpace(true);
this._label.setPosition(center);
@@ -1,221 +0,0 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
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.
****************************************************************************/
//------------------------------------------------------------------
//
// LoaderTestLayer
//
//------------------------------------------------------------------
var LoaderTestLayer = BaseTestLayer.extend({
_title:"Loader Test",
_subtitle:"",
ctor:function() {
var self = this;
self._super(cc.color(0,0,0,255), cc.color(98,99,117,255));
var winSize = cc.winSize;
cc.loader.load(s_helloWorld, function(err, results){
if(err){
cc.log("Failed to load %s.", s_helloWorld);
return;
}
cc.log(s_helloWorld + "--->");
cc.log(results[0]);
var bg = new _ccsg.Sprite(s_helloWorld);
self.addChild(bg);
bg.x = winSize.width/2;
bg.y = winSize.height/2;
});
// cc.loader.load([s_Cowboy_plist, s_Cowboy_png], function(err, results){
// if(err){
// cc.log("Failed to load %s, %s .", s_Cowboy_plist, s_Cowboy_png);
// return;
// }
// cc.log(s_Cowboy_plist + "--->");
// cc.log(results[0]);
// cc.log(s_Cowboy_png + "--->");
// cc.log(results[1]);
// cc.spriteFrameCache.addSpriteFrames(s_Cowboy_plist);
// var frame = new _ccsg.Sprite("#testAnimationResource/1.png");
// self.addChild(frame);
// frame.x = winSize.width/4;
// frame.y = winSize.height/4;
// });
var str;
if(cc.sys.isNative) {
str = s_lookup_desktop_plist;
} else if(cc.sys.isMobile) {
str = s_lookup_mobile_plist;
} else {
str = s_lookup_html5_plist;
}
cc.loader.loadAliases(str, function(){
var sprite = new _ccsg.Sprite("grossini.bmp");
self.addChild( sprite );
sprite.x = winSize.width/2;
sprite.y = winSize.height/2;
});
},
onNextCallback: function(){
var parent = this.getParent();
parent.removeChild(this);
parent.addChild(new LoaderCycleLayer());
}
});
var LoaderCycleLayer = BaseTestLayer.extend({
_title:"Failed to load Test",
_subtitle:"",
ctor: function(){
BaseTestLayer.prototype.ctor.call(this);
var index = 0;
var winSize = cc.director.getWinSize();
var t = this,
cb = function(num){
var labelTTF = new cc.LabelTTF(num + " file failed");
labelTTF.x = index++*100 + winSize.width - 150;
labelTTF.y = winSize.height / 2 - 20;
if(num === 1)
labelTTF.setColor(cc.Color.GREEN);
else
labelTTF.setColor(cc.Color.RED);
t.addChild(labelTTF);
if(index < 4)
t.test(cb);
};
this.createInfo();
this.regLoad();
this.test(cb);
},
regLoad: function(){
cc.loader.register(["_test1"], {
load: function(realUrl, url, res, cb){
cc.loader.cache[url] = {};
setTimeout(function(){
cb && cb(null, cc.loader.cache[url]);
return cc.loader.cache[url];
}, Math.random()*1000);
}
});
cc.loader.register(["_test2"], {
load: function(realUrl, url, res, cb){
cb && cb({});
return null;
}
});
},
list: [
"1._test2",
"1._test1",
"2._test1",
"3._test1",
"4._test1"
],
createInfo: function(){
var winSize = cc.director.getWinSize();
var info1 = new cc.LabelTTF("Load 5 files");
info1.x = winSize.width / 2;
info1.y = winSize.height / 2 + 80;
var info2 = new cc.LabelTTF("1 file does not exist");
info2.x = winSize.width / 2;
info2.y = winSize.height / 2 + 60;
var info3 = new cc.LabelTTF("The other 4 files should be loaded.");
info3.x = winSize.width / 2;
info3.y = winSize.height / 2 + 40;
this.addChild(info1);
this.addChild(info2);
this.addChild(info3);
var info4 = new cc.LabelTTF("test 1");
info4.x = winSize.width / 2 - 50;
info4.y = winSize.height / 2;
var info5 = new cc.LabelTTF("test 2");
info5.x = winSize.width / 2 - 150;
info5.y = winSize.height / 2;
var info6 = new cc.LabelTTF("test 3");
info6.x = winSize.width / 2 + 50;
info6.y = winSize.height / 2;
var info7 = new cc.LabelTTF("test 4");
info7.x = winSize.width / 2 + 150;
info7.y = winSize.height / 2;
this.addChild(info4);
this.addChild(info5);
this.addChild(info6);
this.addChild(info7);
},
test: function(cb){
this.clearRes();
var layer = this;
cc.loader.load(layer.list, function(){
var num = 0;
layer.list.forEach(function(item){
if(!cc.loader.getRes(item)){
num++;
}
});
cb(num);
});
},
clearRes: function(){
this.list.forEach(function(item){
cc.loader.release(item);
});
},
onRestartCallback: function(){
var parent = this._parent;
parent.removeChild(this);
parent.addChild(new LoaderCycleLayer());
},
onBackCallback: function(){
var parent = this._parent;
parent.removeChild(this);
parent.addChild(new LoaderTestLayer());
}
});
var LoaderTestScene = TestScene.extend({
runThisTest:function () {
this.addChild(new LoaderTestLayer());
director.runScene(this);
}
});
@@ -75,16 +75,16 @@ var TouchableSpriteTest = EventDispatcherTestDemo.extend({
var size = director.getVisibleSize();
var containerForSprite1 = new _ccsg.Node();
var sprite1 = new _ccsg.Sprite("Images/CyanSquare.png");
var sprite1 = new _ccsg.Sprite("res/Images/CyanSquare.png");
sprite1.setPosition(origin.x + size.width/2 - 80, origin.y + size.height/2 + 80);
containerForSprite1.addChild(sprite1);
this.addChild(containerForSprite1, 10);
var sprite2 = new _ccsg.Sprite("Images/MagentaSquare.png");
var sprite2 = new _ccsg.Sprite("res/Images/MagentaSquare.png");
sprite2.setPosition(origin.x + size.width/2, origin.y + size.height/2);
this.addChild(sprite2, 20);
var sprite3 = new _ccsg.Sprite("Images/YellowSquare.png");
var sprite3 = new _ccsg.Sprite("res/Images/YellowSquare.png");
sprite3.setPosition(0,0);
sprite2.addChild(sprite3, 1);
@@ -254,19 +254,19 @@ var FixedPriorityTest = EventDispatcherTestDemo.extend({
var size = director.getVisibleSize();
var sprite1 = TouchableSprite.create(30);
sprite1.setTexture("Images/CyanSquare.png");
sprite1.setTexture("res/Images/CyanSquare.png");
sprite1.x = origin.x + size.width / 2 - 80;
sprite1.y = origin.y + size.height / 2 + 40;
this.addChild(sprite1, 10);
var sprite2 = TouchableSprite.create(20);
sprite2.setTexture("Images/MagentaSquare.png");
sprite2.setTexture("res/Images/MagentaSquare.png");
sprite2.x = origin.x + size.width / 2;
sprite2.y = origin.y + size.height / 2;
this.addChild(sprite2, 20);
var sprite3 = TouchableSprite.create(10);
sprite3.setTexture("Images/YellowSquare.png");
sprite3.setTexture("res/Images/YellowSquare.png");
sprite3.x = 0;
sprite3.y = 0;
sprite2.addChild(sprite3, 1);
@@ -296,7 +296,7 @@ var RemoveListenerWhenDispatching = EventDispatcherTestDemo.extend({
var origin = director.getVisibleOrigin();
var size = director.getVisibleSize();
var sprite1 = new _ccsg.Sprite("Images/CyanSquare.png");
var sprite1 = new _ccsg.Sprite("res/Images/CyanSquare.png");
sprite1.setPosition(origin.x + size.width/2, origin.y + size.height/2);
this.addChild(sprite1, 10);
@@ -516,7 +516,7 @@ var SpriteAccelerationEventTest = EventDispatcherTestDemo.extend({
cc.inputManager.setAccelerometerEnabled(true);
var sprite = new _ccsg.Sprite("Images/ball.png");
var sprite = new _ccsg.Sprite("res/Images/ball.png");
sprite.setPosition(origin.x + size.width/2, origin.y + size.height/2);
this.addChild(sprite);
@@ -580,7 +580,7 @@ var RemoveAndRetainNodeTest = EventDispatcherTestDemo.extend({
var origin = director.getVisibleOrigin();
var size = director.getVisibleSize();
this._sprite = new _ccsg.Sprite("Images/CyanSquare.png");
this._sprite = new _ccsg.Sprite("res/Images/CyanSquare.png");
this._sprite.setPosition(origin.x + size.width/2, origin.y + size.height/2);
this.addChild(this._sprite, 10);
@@ -878,11 +878,11 @@ var GlobalZTouchTest = EventDispatcherTestDemo.extend({
var SPRITE_COUNT = 8, sprite;
for (var i = 0; i < SPRITE_COUNT; i++) {
if(i==4) {
sprite = new _ccsg.Sprite("Images/CyanSquare.png");
sprite = new _ccsg.Sprite("res/Images/CyanSquare.png");
this._sprite = sprite;
this._sprite.setGlobalZOrder(-1);
} else
sprite = new _ccsg.Sprite("Images/YellowSquare.png");
sprite = new _ccsg.Sprite("res/Images/YellowSquare.png");
cc.eventManager.addListener(listener.clone(), sprite);
this.addChild(sprite);
@@ -998,17 +998,17 @@ var StopPropagationTest = EventDispatcherTestDemo.extend({
for (var i = 0; i < SPRITE_COUNT; i++) {
if(i==4) {
sprite1 = new _ccsg.Sprite("Images/CyanSquare.png");
sprite1 = new _ccsg.Sprite("res/Images/CyanSquare.png");
sprite1.setTag(StopPropagationTest._TAG_BLUE_SPRITE);
this.addChild(sprite1, 100);
sprite2 = new _ccsg.Sprite("Images/CyanSquare.png");
sprite2 = new _ccsg.Sprite("res/Images/CyanSquare.png");
sprite2.setTag(StopPropagationTest._TAG_BLUE_SPRITE2);
this.addChild(sprite2, 100);
} else {
sprite1 = new _ccsg.Sprite("Images/YellowSquare.png");
sprite1 = new _ccsg.Sprite("res/Images/YellowSquare.png");
this.addChild(sprite1, 0);
sprite2 = new _ccsg.Sprite("Images/YellowSquare.png");
sprite2 = new _ccsg.Sprite("res/Images/YellowSquare.png");
this.addChild(sprite2, 0);
}
@@ -1068,20 +1068,20 @@ var Issue4160 = EventDispatcherTestDemo.extend({
var size = cc.director.getVisibleSize();
var sprite1 = TouchableSprite.create(-30);
sprite1.setTexture("Images/CyanSquare.png");
sprite1.setTexture("res/Images/CyanSquare.png");
sprite1.x = origin.x + (size.width/2) - 80;
sprite1.y = origin.y + (size.height/2) + 40;
this.addChild(sprite1, 5);
var sprite2 = TouchableSprite.create(-20);
sprite2.setTexture("Images/MagentaSquare.png");
sprite2.setTexture("res/Images/MagentaSquare.png");
sprite2.removeListenerOnTouchEnded(true);
sprite2.x = origin.x + (size.width/2);
sprite2.y = origin.y + (size.height/2);
this.addChild(sprite2, 10);
var sprite3 = TouchableSprite.create(-10);
sprite3.setTexture("Images/YellowSquare.png");
sprite3.setTexture("res/Images/YellowSquare.png");
sprite3.x = 0;
sprite3.y = 0;
sprite2.addChild(sprite3, 21);
@@ -1112,19 +1112,19 @@ var PauseResumeTargetTest = EventDispatcherTestDemo.extend({
var size = cc.director.getVisibleSize();
var sprite1 = TouchableSprite.create();
sprite1.setTexture("Images/CyanSquare.png");
sprite1.setTexture("res/Images/CyanSquare.png");
sprite1.x = origin.x + size.width / 2 - 180;
sprite1.y = origin.y + size.height / 2 + 40;
this.addChild(sprite1, 10);
var sprite2 = TouchableSprite.create();
sprite2.setTexture("Images/MagentaSquare.png");
sprite2.setTexture("res/Images/MagentaSquare.png");
sprite2.x = origin.x + size.width / 2 - 100;
sprite2.y = origin.y + size.height / 2;
this.addChild(sprite2, 1);
var sprite3 = TouchableSprite.create(100); // Sprite3 uses fixed priority listener
sprite3.setTexture("Images/YellowSquare.png");
sprite3.setTexture("res/Images/YellowSquare.png");
sprite3.x = 0;
sprite3.y = 0;
sprite2.addChild(sprite3, -1);
+12 -12
View File
@@ -644,7 +644,7 @@ var ShaderHeartTest = OpenGLTestLayer.extend({
this._super();
if( 'opengl' in cc.sys.capabilities ) {
var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Heart.vsh", ccbjs + "Shaders/example_Heart.fsh");
var shaderNode = new ShaderNode("res/Shaders/example_Heart.vsh", "res/Shaders/example_Heart.fsh");
this.addChild(shaderNode,10);
shaderNode.x = winSize.width/2;
shaderNode.y = winSize.height/2;
@@ -684,7 +684,7 @@ var ShaderMandelbrotTest = OpenGLTestLayer.extend({
this._super();
if( 'opengl' in cc.sys.capabilities ) {
var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Mandelbrot.vsh", ccbjs + "Shaders/example_Mandelbrot.fsh");
var shaderNode = new ShaderNode("res/Shaders/example_Mandelbrot.vsh", "res/Shaders/example_Mandelbrot.fsh");
this.addChild(shaderNode,10);
shaderNode.x = winSize.width/2;
shaderNode.y = winSize.height/2;
@@ -719,7 +719,7 @@ var ShaderMonjoriTest = OpenGLTestLayer.extend({
this._super();
if( 'opengl' in cc.sys.capabilities ) {
var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Monjori.vsh", ccbjs + "Shaders/example_Monjori.fsh");
var shaderNode = new ShaderNode("res/Shaders/example_Monjori.vsh", "res/Shaders/example_Monjori.fsh");
this.addChild(shaderNode,10);
shaderNode.x = winSize.width/2;
shaderNode.y = winSize.height/2;
@@ -754,7 +754,7 @@ var ShaderPlasmaTest = OpenGLTestLayer.extend({
this._super();
if( 'opengl' in cc.sys.capabilities ) {
var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Plasma.vsh", ccbjs + "Shaders/example_Plasma.fsh");
var shaderNode = new ShaderNode("res/Shaders/example_Plasma.vsh", "res/Shaders/example_Plasma.fsh");
this.addChild(shaderNode,10);
shaderNode.x = winSize.width/2;
shaderNode.y = winSize.height/2;
@@ -793,7 +793,7 @@ var ShaderFlowerTest = OpenGLTestLayer.extend({
if( 'opengl' in cc.sys.capabilities ) {
var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Flower.vsh", ccbjs + "Shaders/example_Flower.fsh");
var shaderNode = new ShaderNode("res/Shaders/example_Flower.vsh", "res/Shaders/example_Flower.fsh");
this.addChild(shaderNode,10);
shaderNode.x = winSize.width/2;
shaderNode.y = winSize.height/2;
@@ -832,7 +832,7 @@ var ShaderJuliaTest = OpenGLTestLayer.extend({
if( 'opengl' in cc.sys.capabilities ) {
var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Julia.vsh", ccbjs + "Shaders/example_Julia.fsh");
var shaderNode = new ShaderNode("res/Shaders/example_Julia.vsh", "res/Shaders/example_Julia.fsh");
this.addChild(shaderNode,10);
shaderNode.x = winSize.width/2;
shaderNode.y = winSize.height/2;
@@ -873,12 +873,12 @@ var ShaderOutlineEffect = OpenGLTestLayer.extend({
if( 'opengl' in cc.sys.capabilities ) {
if(cc.sys.isNative){
this.shader = new cc.GLProgram(ccbjs + "Shaders/example_Outline_noMVP.vsh", ccbjs + "Shaders/example_Outline.fsh");
this.shader = new cc.GLProgram("res/Shaders/example_Outline_noMVP.vsh", "res/Shaders/example_Outline.fsh");
this.shader.link();
this.shader.updateUniforms();
}
else{
this.shader = new cc.GLProgram(ccbjs + "Shaders/example_Outline.vsh", ccbjs + "Shaders/example_Outline.fsh");
this.shader = new cc.GLProgram("res/Shaders/example_Outline.vsh", "res/Shaders/example_Outline.fsh");
this.shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
this.shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
this.shader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
@@ -890,7 +890,7 @@ var ShaderOutlineEffect = OpenGLTestLayer.extend({
this.shader.setUniformLocationWith3f(this.shader.getUniformLocationForName('u_outlineColor'), 0 / 255, 255 / 255, 0 / 255);
}
this.sprite = new _ccsg.Sprite('Images/grossini.png');
this.sprite = new _ccsg.Sprite('res/Images/grossini.png');
this.sprite.attr({
x: winSize.width / 2,
y: winSize.height / 2
@@ -949,13 +949,13 @@ var ShaderRetroEffect = OpenGLTestLayer.extend({
this._super();
if( 'opengl' in cc.sys.capabilities ) {
var program = new cc.GLProgram(ccbjs + "Shaders/example_ColorBars.vsh", ccbjs + "Shaders/example_ColorBars.fsh");
var program = new cc.GLProgram("res/Shaders/example_ColorBars.vsh", "res/Shaders/example_ColorBars.fsh");
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
program.link();
program.updateUniforms();
var label = new cc.LabelBMFont("RETRO EFFECT","fonts/west_england-64.fnt");
var label = new cc.LabelBMFont("RETRO EFFECT", "res/fonts/west_england-64.fnt");
if(cc.sys.isNative)
label.children[0].shaderProgram = program;
@@ -1019,7 +1019,7 @@ var GLGetActiveTest = OpenGLTestLayer.extend({
this._super();
if( 'opengl' in cc.sys.capabilities ) {
var sprite = this.sprite = new _ccsg.Sprite("Images/grossini.png");
var sprite = this.sprite = new _ccsg.Sprite("res/Images/grossini.png");
sprite.x = winSize.width/2;
sprite.y = winSize.height/2;
this.addChild( sprite );
@@ -84,7 +84,7 @@ var Parallax1 = ParallaxDemo.extend({
// Middle layer: a Tile map atlas
//var tilemap = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16);
this._tilemap = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx");
this._tilemap = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx");
// change the transform anchor to 0,0 (optional)
this._tilemap.anchorX = 0;
@@ -197,7 +197,7 @@ var Parallax2 = ParallaxDemo.extend({
// Middle layer: a Tile map atlas
//var tilemap = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16);
var tilemap = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx");
var tilemap = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx");
// change the transform anchor to 0,0 (optional)
tilemap.anchorX = 0;
@@ -879,9 +879,9 @@ var DemoParticleFromFile = ParticleDemo.extend({
this.removeChild(this._background, true);
this._background = null;
this._emitter = new _ccsg.ParticleSystem(s_resprefix + "Particles/" + this._title + ".plist");
this._emitter = new _ccsg.ParticleSystem("res/Particles/" + this._title + ".plist");
// test create from a object
// var plistData = jsb.fileUtils.getValueMapFromFile(s_resprefix + "Particles/" + this._title + ".plist");
// var plistData = jsb.fileUtils.getValueMapFromFile("res/Particles/" + this._title + ".plist");
// this._emitter = new _ccsg.ParticleSystem(plistData);
this.addChild(this._emitter, 10);
@@ -1134,7 +1134,7 @@ var Issue870 = ParticleDemo.extend({
this.removeChild(this._background, true);
this._background = null;
var system = new _ccsg.ParticleSystem(s_resprefix + "Particles/SpinningPeas.plist");
var system = new _ccsg.ParticleSystem("res/Particles/SpinningPeas.plist");
system.setTextureWithRect(cc.textureCache.addImage(s_particles), cc.rect(0, 0, 32, 32));
this.addChild(system, 10);
this._emitter = system;
@@ -1162,11 +1162,11 @@ var ParticleBatchTest = ParticleDemo.extend({
onEnter:function () {
this._super();
var emitter1 = new _ccsg.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist');
var emitter1 = new _ccsg.ParticleSystem('res/Particles/LavaFlow.plist');
emitter1.startColor = cc.color(255, 0, 0, 255);
var emitter2 = new _ccsg.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist');
var emitter2 = new _ccsg.ParticleSystem('res/Particles/LavaFlow.plist');
emitter2.startColor = cc.color(0, 255, 0, 255);
var emitter3 = new _ccsg.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist');
var emitter3 = new _ccsg.ParticleSystem('res/Particles/LavaFlow.plist');
emitter3.startColor = cc.color(0, 0, 255, 255);
emitter1.x = winSize.width / 1.25;
@@ -1203,7 +1203,7 @@ var ParticleResizeTest = ParticleDemo.extend({
onEnter:function () {
this._super();
var emitter1 = new _ccsg.ParticleSystem( s_resprefix + 'Particles/LavaFlow.plist');
var emitter1 = new _ccsg.ParticleSystem( 'res/Particles/LavaFlow.plist');
emitter1.x = winSize.width/2;
emitter1.y = winSize.height/2;
this.addChild(emitter1);
+4 -4
View File
@@ -97,10 +97,10 @@ var SpineTestLayerNormal = SpineTestLayer.extend({
// No JS binding for spine-c in this version. So, only file loading is supported.
var spineBoy;
if (idx % 2 == 0) {
spineBoy = new customSkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas');
spineBoy = new customSkeletonAnimation('res/spine/spineboy.json', 'res/spine/spineboy.atlas');
}
else {
spineBoy = new sp._SGSkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas');
spineBoy = new sp._SGSkeletonAnimation('res/spine/spineboy.json', 'res/spine/spineboy.atlas');
}
spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150));
spineBoy.setMix('walk', 'jump', 0.2);
@@ -223,7 +223,7 @@ var SpineTestLayerFFD = SpineTestLayer.extend({
ctor: function(){
this._super(cc.color(0,0,0,255), cc.color(98,99,117,255));
var skeletonNode = new sp._SGSkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5);
var skeletonNode = new sp._SGSkeletonAnimation("res/spine/goblins-ffd.json", "res/spine/goblins-ffd.atlas", 1.5);
skeletonNode.setAnimation(0, "walk", true);
skeletonNode.setSkin("goblin");
@@ -267,7 +267,7 @@ var SpineTestPerformanceLayer = SpineTestLayer.extend({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
onTouchBegan: function(touch, event){
var pos = self.convertToNodeSpace(touch.getLocation());
var skeletonNode = new sp._SGSkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5);
var skeletonNode = new sp._SGSkeletonAnimation("res/spine/goblins-ffd.json", "res/spine/goblins-ffd.atlas", 1.5);
skeletonNode.setAnimation(0, "walk", true);
skeletonNode.setSkin("goblin");
@@ -5232,7 +5232,7 @@ var SpriteBlendFuncTest = SpriteTestDemo.extend({
var destTitles = ["ZERO", "ONE", "DST_COLOR", "ONE_MINUS_DST_COLOR", "DST_ALPHA", "ONE_MINUS_DST_ALPHA"],
srcTitles = ["ZERO", "ONE", "SRC_COLOR", "ONE_MINUS_SRC_COLOR", "SRC_ALPHA", "ONE_MINUS_SRC_ALPHA"];
var sourceImg = "Images/dot.png", destImg = "Images/wood.jpg";
var sourceImg = "res/Images/dot.png", destImg = "res/Images/wood.jpg";
var sourceTexture = cc.textureCache.addImage(sourceImg);
sourceTexture.handleLoadedTexture(true);
var sourceSprite = new _ccsg.Sprite(sourceImg);
@@ -147,57 +147,57 @@ var TextureCacheTest = TextureCacheTestBase.extend({
var texCache = cc.textureCache;
// load textrues
texCache.addImageAsync("Images/HelloWorld.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_01.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_02.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_03.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_04.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_05.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_06.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_07.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_08.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_09.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_10.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_11.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_12.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_13.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/grossini_dance_14.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/HelloWorld.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_01.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_02.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_03.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_04.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_05.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_06.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_07.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_08.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_09.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_10.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_11.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_12.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_13.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/grossini_dance_14.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/background1.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/background2.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/background3.png", this.loadingCallBack, this);
texCache.addImageAsync("Images/blocks.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/background3.png", this.loadingCallBack, this);
texCache.addImageAsync("res/Images/blocks.png", this.loadingCallBack, this);
},
addSprite:function () {
var size = cc.director.getWinSize();
// create sprites
var bg = new _ccsg.Sprite("Images/HelloWorld.png");
var bg = new _ccsg.Sprite("res/Images/HelloWorld.png");
bg.x = size.width / 2;
bg.y = size.height / 2;
//bg.scale = 1.7;
var s1 = new _ccsg.Sprite("Images/grossini.png");
var s2 = new _ccsg.Sprite("Images/grossini_dance_01.png");
var s3 = new _ccsg.Sprite("Images/grossini_dance_02.png");
var s4 = new _ccsg.Sprite("Images/grossini_dance_03.png");
var s5 = new _ccsg.Sprite("Images/grossini_dance_04.png");
var s6 = new _ccsg.Sprite("Images/grossini_dance_05.png");
var s7 = new _ccsg.Sprite("Images/grossini_dance_06.png");
var s8 = new _ccsg.Sprite("Images/grossini_dance_07.png");
var s9 = new _ccsg.Sprite("Images/grossini_dance_08.png");
var s10 = new _ccsg.Sprite("Images/grossini_dance_09.png");
var s11 = new _ccsg.Sprite("Images/grossini_dance_10.png");
var s12 = new _ccsg.Sprite("Images/grossini_dance_11.png");
var s13 = new _ccsg.Sprite("Images/grossini_dance_12.png");
var s14 = new _ccsg.Sprite("Images/grossini_dance_13.png");
var s15 = new _ccsg.Sprite("Images/grossini_dance_14.png");
var s1 = new _ccsg.Sprite("res/Images/grossini.png");
var s2 = new _ccsg.Sprite("res/Images/grossini_dance_01.png");
var s3 = new _ccsg.Sprite("res/Images/grossini_dance_02.png");
var s4 = new _ccsg.Sprite("res/Images/grossini_dance_03.png");
var s5 = new _ccsg.Sprite("res/Images/grossini_dance_04.png");
var s6 = new _ccsg.Sprite("res/Images/grossini_dance_05.png");
var s7 = new _ccsg.Sprite("res/Images/grossini_dance_06.png");
var s8 = new _ccsg.Sprite("res/Images/grossini_dance_07.png");
var s9 = new _ccsg.Sprite("res/Images/grossini_dance_08.png");
var s10 = new _ccsg.Sprite("res/Images/grossini_dance_09.png");
var s11 = new _ccsg.Sprite("res/Images/grossini_dance_10.png");
var s12 = new _ccsg.Sprite("res/Images/grossini_dance_11.png");
var s13 = new _ccsg.Sprite("res/Images/grossini_dance_12.png");
var s14 = new _ccsg.Sprite("res/Images/grossini_dance_13.png");
var s15 = new _ccsg.Sprite("res/Images/grossini_dance_14.png");
// just loading textures to slow down
var s16 = new _ccsg.Sprite("res/Images/background1.png");
var s17 = new _ccsg.Sprite("res/Images/background2.png");
var s18 = new _ccsg.Sprite("Images/background3.png");
var s19 = new _ccsg.Sprite("Images/blocks.png");
var s18 = new _ccsg.Sprite("res/Images/background3.png");
var s19 = new _ccsg.Sprite("res/Images/blocks.png");
s1.x = 50;
s1.y = 50;
@@ -175,7 +175,7 @@ var TileMapEditTest = TileDemo.extend({
var TMXOrthoTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test1.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test1.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.runAction(new cc.ScaleBy(2, 0.5));
@@ -217,7 +217,7 @@ var TMXOrthoTest2 = TileDemo.extend({
//
// it should not flicker. No artifacts should appear
//
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
},
title:function () {
@@ -260,7 +260,7 @@ var TMXOrthoTest2 = TileDemo.extend({
var TMXOrthoTest3 = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test3.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test3.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.scale = 0.2;
@@ -298,7 +298,7 @@ var TMXOrthoTest3 = TileDemo.extend({
var TMXOrthoTest4 = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test4.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test4.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.anchorX = 0;
@@ -368,7 +368,7 @@ var TMXReadWriteTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
var layer = map.getLayer("Layer 0");
@@ -490,7 +490,7 @@ var TMXHexTest = TileDemo.extend({
var color = new cc.LayerColor(cc.color(64, 64, 64, 255));
this.addChild(color, -1);
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/hexa-test.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/hexa-test.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
},
title:function () {
@@ -526,7 +526,7 @@ var TMXIsoTest = TileDemo.extend({
var color = new cc.LayerColor(cc.color(64, 64, 64, 255));
this.addChild(color, -1);
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
// move map to the center of the screen
@@ -570,7 +570,7 @@ var TMXIsoTest1 = TileDemo.extend({
var color = new cc.LayerColor(cc.color(64, 64, 64, 255));
this.addChild(color, -1);
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test1.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test1.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.anchorX = 0.5;
@@ -612,7 +612,7 @@ var TMXIsoTest2 = TileDemo.extend({
var color = new cc.LayerColor(cc.color(64, 64, 64, 255));
this.addChild(color, -1);
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test2.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test2.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
// move map to the center of the screen
@@ -657,7 +657,7 @@ var TMXUncompressedTest = TileDemo.extend({
var color = new cc.LayerColor(cc.color(64, 64, 64, 255));
this.addChild(color, -1);
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test2-uncompressed.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test2-uncompressed.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
// move map to the center of the screen
@@ -710,7 +710,7 @@ var TMXUncompressedTest = TileDemo.extend({
var TMXTilesetTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test5.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test5.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
if ("opengl" in cc.sys.capabilities) {
@@ -760,7 +760,7 @@ var TMXOrthoObjectsTest = TileDemo.extend({
drawNode.setLineWidth(3);
drawNode.setDrawColor(cc.color(255,255,255,255));
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-objects.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/ortho-objects.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
var group = map.getObjectGroup("Object Group 1");
@@ -835,7 +835,7 @@ var TMXIsoObjectsTest = TileDemo.extend({
drawNode.setDrawColor(cc.color(255,255,255,255));
this.addChild(drawNode);
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-objectgroup.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test-objectgroup.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
var group = map.getObjectGroup("Object Group 1");
@@ -906,7 +906,7 @@ var TMXIsoObjectsTest = TileDemo.extend({
var TMXResizeTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test5.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test5.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
var layer;
@@ -950,7 +950,7 @@ var TMXIsoZorder = TileDemo.extend({
tamara:null,
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-zorder.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test-zorder.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.x = -map.width / 2;
@@ -1019,7 +1019,7 @@ var TMXOrthoZorder = TileDemo.extend({
tamara:null,
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-zorder.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test-zorder.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
this.tamara = new _ccsg.Sprite(s_pathSister1);
@@ -1082,7 +1082,7 @@ var TMXIsoVertexZ = TMXFixBugLayer.extend({
tamara:null,
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-vertexz.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test-vertexz.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.x = -map.width / 2;
@@ -1157,7 +1157,7 @@ var TMXOrthoVertexZ = TMXFixBugLayer.extend({
tamara:null,
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-vertexz.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test-vertexz.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
// because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you
@@ -1231,7 +1231,7 @@ var TMXOrthoVertexZ = TMXFixBugLayer.extend({
var TMXIsoMoveLayer = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-movelayer.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test-movelayer.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.x = -700;
map.y = -50;
@@ -1252,7 +1252,7 @@ var TMXIsoMoveLayer = TileDemo.extend({
var TMXOrthoMoveLayer = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-movelayer.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test-movelayer.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
},
title:function () {
@@ -1271,7 +1271,7 @@ var TMXOrthoMoveLayer = TileDemo.extend({
var TMXTilePropertyTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-tile-property.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/ortho-tile-property.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
for (var i = 1; i <= 6; i++) {
@@ -1314,7 +1314,7 @@ var TMXTilePropertyTest = TileDemo.extend({
var TMXOrthoFlipTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-rotation-test.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/ortho-rotation-test.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
this.log("ContentSize:" + map.width + "," + map.height);
@@ -1350,7 +1350,7 @@ var TMXOrthoFlipTest = TileDemo.extend({
var TMXOrthoFlipRunTimeTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-rotation-test.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/ortho-rotation-test.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
this.log("ContentSize:" + map.width + "," + map.height);
@@ -1435,8 +1435,8 @@ var TMXOrthoFromXMLTest = TileDemo.extend({
ctor:function () {
this._super();
var resources = s_resprefix + "TileMaps";
var filePath = s_resprefix + "TileMaps/orthogonal-test1.tmx";
var resources = "res/TileMaps";
var filePath = "res/TileMaps/orthogonal-test1.tmx";
var xmlStr = cc.loader.getRes(filePath);
var map = new cc.TMXTiledMap(xmlStr, resources);
this.addChild(map, 0, TAG_TILE_MAP);
@@ -1485,7 +1485,7 @@ var TMXOrthoFromXMLTest = TileDemo.extend({
var TMXBug987 = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test6.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test6.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
this.log("ContentSize:" + map.width + "," + map.height);
@@ -1540,7 +1540,7 @@ var TMXBug987 = TileDemo.extend({
var TMXBug787 = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-bug787.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/iso-test-bug787.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
map.scale = 0.25;
@@ -1576,7 +1576,7 @@ var TMXGIDObjectsTest = TileDemo.extend({
drawNode.setDrawColor(cc.color(255,255,255,255));
this.addChild(drawNode);
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/test-object-layer.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/test-object-layer.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
this.log("ContentSize:" + map.width + "," + map.height);
@@ -1639,7 +1639,7 @@ var TMXGIDObjectsTest = TileDemo.extend({
var TMXIsoOffsetTest = TileDemo.extend({
ctor:function () {
this._super();
var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/tile_iso_offset.tmx");
var map = new cc.TMXTiledMap("res/TileMaps/tile_iso_offset.tmx");
this.addChild(map, 0, TAG_TILE_MAP);
},
-8
View File
@@ -333,14 +333,6 @@ var testNames = [
return new LayerTestScene();
}
},
{
title:"Loader Test",
platforms: PLATFORM_ALL,
linksrc:"src/LoaderTest/LoaderTest.js",
testScene:function () {
return new LoaderTestScene();
}
},
{
title:"Node Test",
platforms: PLATFORM_ALL,
File diff suppressed because it is too large Load Diff