Some core code modify to TS(assets/ & components/) (#4418)

This commit is contained in:
ChiaNing
2019-05-14 18:37:08 +08:00
committed by Weiliang Wang
parent c248a20262
commit fbbf5366ac
8 changed files with 2011 additions and 1867 deletions
+9
View File
@@ -67,6 +67,11 @@ interface Document{
webkitHidden: any;
}
interface HTMLElement{
content: any;
name: any;
}
interface ActiveXObject {
new (s: string): any;
}
@@ -96,5 +101,9 @@ declare namespace Editor {
function log (message?: any, ...optionalParams: any[]): void;
function error (message?: any, ...optionalParams: any[]): void;
function warn (message?: any, ...optionalParams: any[]): void;
function require(str:String): any;
const isMainProcess: boolean | undefined;
const Ipc: any;
const Utils: any;
const assets: any;
}
+1
View File
@@ -16,6 +16,7 @@ declare namespace wx {
function getFileSystemManager(): FileSystemManager;
function getSharedCanvas(): any;
function getOpenDataContext(): any;
const onShow: any;
const onHide: any;
@@ -24,15 +24,17 @@
THE SOFTWARE.
****************************************************************************/
import {createMap, isChildClassOf, _getClassById} from '../core/utils/js';
import { Asset } from './asset';
import {callInNextTick} from '../core/utils/misc';
import decodeUuid from '../core/utils/decode-uuid';
import Loader from '../load-pipeline/CCLoader';
import {initPacks} from '../load-pipeline/pack-downloader';
import {getDependsRecursively} from '../load-pipeline/auto-release-utils';
import MD5Pipe from '../load-pipeline/md5-pipe';
import {_getClassById, createMap, isChildClassOf} from '../core/utils/js';
import {callInNextTick} from '../core/utils/misc';
import AssetTable from '../load-pipeline/asset-table';
import {getDependsRecursively} from '../load-pipeline/auto-release-utils';
import Loader from '../load-pipeline/CCLoader';
import MD5Pipe from '../load-pipeline/md5-pipe';
import {initPacks} from '../load-pipeline/pack-downloader';
import { Asset } from './asset';
// tslint:disable: max-line-length
/**
* The asset library which managing loading/unloading assets in project.
@@ -43,9 +45,9 @@ import AssetTable from '../load-pipeline/asset-table';
// configs
var _libraryBase = '';
var _rawAssetsBase = ''; // The base dir for raw assets in runtime
var _uuidToRawAsset = createMap(true);
let _libraryBase = '';
let _rawAssetsBase = ''; // The base dir for raw assets in runtime
const _uuidToRawAsset = createMap(true);
function isScene (asset) {
return asset && (asset.constructor === cc.SceneAsset || asset instanceof cc.Scene);
@@ -60,7 +62,7 @@ function RawAssetEntry (url, type) {
// publics
let AssetLibrary = {
const AssetLibrary = {
/**
* !#en Caches uuid to all loaded assets in scenes.
*
@@ -93,20 +95,20 @@ let AssetLibrary = {
* @param {Asset} options.existingAsset - load to existing asset, this argument is only available in editor
* @private
*/
loadAsset: function (uuid, callback, options) {
loadAsset (uuid, callback, options) {
if (typeof uuid !== 'string') {
return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null);
}
// var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true;
// var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true;
var item = {
uuid: uuid,
type: 'uuid'
const item: any = {
uuid,
type: 'uuid',
};
if (options && options.existingAsset) {
item.existingAsset = options.existingAsset;
}
cc.loader.load(item, function (error, asset) {
cc.loader.load(item, (error, asset) => {
if (error || !asset) {
error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + (error ? error.message : 'Unknown error'));
}
@@ -116,12 +118,12 @@ let AssetLibrary = {
Editor.error('Sorry, the scene data of "%s" is corrupted!', uuid);
}
else {
var key = cc.loader._getReferenceKey(uuid);
const key = cc.loader._getReferenceKey(uuid);
asset.scene.dependAssets = getDependsRecursively(key);
}
}
if (isScene(asset)) {
var id = cc.loader._getReferenceKey(uuid);
const id = cc.loader._getReferenceKey(uuid);
cc.loader.removeItem(id);
}
}
@@ -131,22 +133,22 @@ let AssetLibrary = {
});
},
getLibUrlNoExt: function (uuid, inRawAssetsDir) {
getLibUrlNoExt (uuid, inRawAssetsDir?: any) {
if (CC_BUILD) {
uuid = decodeUuid(uuid);
}
var base = (CC_BUILD && inRawAssetsDir) ? (_rawAssetsBase + 'assets/') : _libraryBase;
const base = (CC_BUILD && inRawAssetsDir) ? (_rawAssetsBase + 'assets/') : _libraryBase;
return base + uuid.slice(0, 2) + '/' + uuid;
},
_queryAssetInfoInEditor: function (uuid, callback) {
_queryAssetInfoInEditor (uuid, callback) {
if (CC_EDITOR) {
Editor.Ipc.sendToMain('scene:query-asset-info-by-uuid', uuid, function (err, info) {
Editor.Ipc.sendToMain('scene:query-asset-info-by-uuid', uuid, (err, info) => {
if (info) {
Editor.Utils.UuidCache.cache(info.url, uuid);
var ctor = Editor.assets[info.type];
const ctor = Editor.assets[info.type];
if (ctor) {
var isRawAsset = !isChildClassOf(ctor, Asset);
const isRawAsset = !isChildClassOf(ctor, Asset);
callback(null, info.url, isRawAsset, ctor);
}
else {
@@ -154,7 +156,7 @@ let AssetLibrary = {
}
}
else {
var error = new Error('Can not get asset url by uuid "' + uuid + '", the asset may be deleted.');
const error: any = new Error('Can not get asset url by uuid "' + uuid + '", the asset may be deleted.');
error.errorCode = 'db.NOTFOUND';
callback(error);
}
@@ -162,9 +164,9 @@ let AssetLibrary = {
}
},
_getAssetInfoInRuntime: function (uuid, result) {
_getAssetInfoInRuntime (uuid, result?: any) {
result = result || {url: null, raw: false};
var info = _uuidToRawAsset[uuid];
const info = _uuidToRawAsset[uuid];
if (info && !isChildClassOf(info.type, cc.Asset)) {
// backward compatibility since 1.10
result.url = _rawAssetsBase + info.url;
@@ -177,7 +179,7 @@ let AssetLibrary = {
return result;
},
_uuidInSettings: function (uuid) {
_uuidInSettings (uuid) {
return uuid in _uuidToRawAsset;
},
@@ -190,29 +192,29 @@ let AssetLibrary = {
* @param {Boolean} callback.raw - indicates whether the asset is raw asset
* @param {Function} callback.ctorInEditor - the actual type of asset, used in editor only
*/
queryAssetInfo: function (uuid, callback) {
queryAssetInfo (uuid, callback) {
if (CC_EDITOR && !CC_TEST) {
this._queryAssetInfoInEditor(uuid, callback);
}
else {
var info = this._getAssetInfoInRuntime(uuid);
const info = this._getAssetInfoInRuntime(uuid);
callback(null, info.url, info.raw);
}
},
// parse uuid out of url
parseUuidInEditor: function (url) {
parseUuidInEditor (url) {
if (CC_EDITOR) {
var uuid = '';
var isImported = url.startsWith(_libraryBase);
let uuid = '';
const isImported = url.startsWith(_libraryBase);
if (isImported) {
var dir = cc.path.dirname(url);
var dirBasename = cc.path.basename(dir);
const dir = cc.path.dirname(url);
const dirBasename = cc.path.basename(dir);
var isAssetUrl = dirBasename.length === 2;
const isAssetUrl = dirBasename.length === 2;
if (isAssetUrl) {
uuid = cc.path.basename(url);
var index = uuid.indexOf('.');
const index = uuid.indexOf('.');
if (index !== -1) {
uuid = uuid.slice(0, index);
}
@@ -234,25 +236,25 @@ let AssetLibrary = {
* @return {LoadingHandle}
* @private
*/
loadJson: function (json, callback) {
var randomUuid = '' + ((new Date()).getTime() + Math.random());
var item = {
loadJson (json, callback) {
const randomUuid = '' + ((new Date()).getTime() + Math.random());
const item = {
uuid: randomUuid,
type: 'uuid',
content: json,
skips: [ cc.loader.assetLoader.id, cc.loader.downloader.id ]
skips: [ cc.loader.assetLoader.id, cc.loader.downloader.id ],
};
cc.loader.load(item, function (error, asset) {
cc.loader.load(item, (error, asset) => {
if (error) {
error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message);
}
else {
if (asset.constructor === cc.SceneAsset) {
var key = cc.loader._getReferenceKey(randomUuid);
const key = cc.loader._getReferenceKey(randomUuid);
asset.scene.dependAssets = getDependsRecursively(key);
}
if (CC_EDITOR || isScene(asset)) {
var id = cc.loader._getReferenceKey(randomUuid);
const id = cc.loader._getReferenceKey(randomUuid);
cc.loader.removeItem(id);
}
}
@@ -271,10 +273,11 @@ let AssetLibrary = {
* @return {Asset} - the existing asset, if not loaded, just returns null.
* @private
*/
getAssetByUuid: function (uuid) {
getAssetByUuid (uuid) {
return AssetLibrary._uuidToAsset[uuid] || null;
},
// tslint:disable: no-shadowed-variable
/**
* init the asset library
*
@@ -286,60 +289,61 @@ let AssetLibrary = {
* @param {String} [options.rawAssetsBase] - base of raw asset's urls (only used in runtime)
* @param {String} [options.packedAssets] - packed assets (only used in runtime)
*/
init: function (options) {
init (options) {
if (CC_EDITOR && _libraryBase) {
cc.errorID(6402);
return;
}
// 这里将路径转 url,不使用路径的原因是有的 runtime 不能解析 "\" 符号。
// 不使用 url.format 的原因是 windows 不支持 file:// 和 /// 开头的协议,所以只能用 replace 操作直接把路径转成 URL。
var libraryPath = options.libraryPath;
let libraryPath = options.libraryPath;
libraryPath = libraryPath.replace(/\\/g, '/');
_libraryBase = cc.path.stripSep(libraryPath) + '/';
_rawAssetsBase = options.rawAssetsBase;
var md5AssetsMap = options.md5AssetsMap;
const md5AssetsMap = options.md5AssetsMap;
if (md5AssetsMap && md5AssetsMap.import) {
// decode uuid
var i = 0, uuid = 0;
var md5ImportMap = createMap(true);
var md5Entries = md5AssetsMap.import;
let i = 0;
let uuid = 0;
const md5ImportMap = createMap(true);
let md5Entries = md5AssetsMap.import;
for (i = 0; i < md5Entries.length; i += 2) {
uuid = decodeUuid(md5Entries[i]);
md5ImportMap[uuid] = md5Entries[i + 1];
}
var md5RawAssetsMap = createMap(true);
const md5RawAssetsMap = createMap(true);
md5Entries = md5AssetsMap['raw-assets'];
for (i = 0; i < md5Entries.length; i += 2) {
uuid = decodeUuid(md5Entries[i]);
md5RawAssetsMap[uuid] = md5Entries[i + 1];
}
var md5Pipe = new MD5Pipe(md5ImportMap, md5RawAssetsMap, _libraryBase);
const md5Pipe = new MD5Pipe(md5ImportMap, md5RawAssetsMap, _libraryBase);
cc.loader.insertPipeAfter(cc.loader.assetLoader, md5Pipe);
cc.loader.md5Pipe = md5Pipe;
}
// init raw assets
var assetTables = Loader._assetTables;
for (var mount in assetTables) {
const assetTables = Loader._assetTables;
// tslint:disable: forin
for (const mount in assetTables) {
assetTables[mount].reset();
}
var rawAssets = options.rawAssets;
const rawAssets = options.rawAssets;
if (rawAssets) {
for (var mountPoint in rawAssets) {
var assets = rawAssets[mountPoint];
for (var uuid in assets) {
var info = assets[uuid];
var url = info[0];
var typeId = info[1];
var type = _getClassById(typeId);
for (const mountPoint in rawAssets) {
const assets = rawAssets[mountPoint];
for (const uuid in assets) {
const info = assets[uuid];
const url = info[0];
const typeId = info[1];
const type = _getClassById(typeId);
if (!type) {
cc.error('Cannot get', typeId);
continue;
@@ -347,7 +351,7 @@ let AssetLibrary = {
// backward compatibility since 1.10
_uuidToRawAsset[uuid] = new RawAssetEntry(mountPoint + '/' + url, type);
// init resources
var isSubAsset = info[2] === 1;
const isSubAsset = info[2] === 1;
if (!assetTables[mountPoint]) {
assetTables[mountPoint] = new AssetTable();
@@ -364,18 +368,18 @@ let AssetLibrary = {
// init cc.url
cc.url._init((options.mountPaths && options.mountPaths.assets) || _rawAssetsBase + 'assets');
}
}
},
};
//暂时屏蔽,因为目前没有缓存任何asset
//if (CC_DEV && Asset.prototype._onPreDestroy) {
// 暂时屏蔽,因为目前没有缓存任何asset
// if (CC_DEV && Asset.prototype._onPreDestroy) {
// cc.error('_onPreDestroy of Asset has already defined');
//}
//Asset.prototype._onPreDestroy = function () {
// }
// Asset.prototype._onPreDestroy = function () {
// if (AssetLibrary._uuidToAsset[this._uuid] === this) {
// AssetLibrary.unloadAsset(this);
// }
//};
// };
cc.AssetLibrary = AssetLibrary;
export default AssetLibrary;
@@ -24,11 +24,11 @@
THE SOFTWARE.
****************************************************************************/
import {compile} from '../core/data/instantiate-jit';
import Enum from '../core/value-types/enum';
import {obsolete} from '../core/utils/js';
import { Asset } from './asset';
import {ccclass, property} from '../core/data/class-decorator';
import {compile} from '../core/data/instantiate-jit';
import {obsolete} from '../core/utils/js';
import Enum from '../core/value-types/enum';
import { Asset } from './asset';
/**
* !#zh
@@ -40,7 +40,7 @@ import {ccclass, property} from '../core/data/class-decorator';
* @enum Prefab.OptimizationPolicy
* @since 1.10.0
*/
var OptimizationPolicy = Enum({
const OptimizationPolicy = Enum({
/**
* !#zh
* 根据创建次数自动调整优化策略。初次创建实例时,行为等同 SINGLE_INSTANCE,多次创建后将自动采用 MULTI_INSTANCE。
@@ -83,23 +83,15 @@ var OptimizationPolicy = Enum({
*/
@ccclass('cc.Prefab')
export default class Prefab extends Asset {
constructor () {
super();
/**
* Cache function to optimize instance creaton.
* @property {Function} _createFunction
* @private
*/
this._createFunction = null;
this._instantiatedTimes = 0;
}
public static OptimizationPolicy = OptimizationPolicy;
public static OptimizationPolicyThreshold = 3;
/**
* @property {Node} data - the main cc.Node in the prefab
*/
@property
data = null;
public data: any = null;
/**
* !#zh
@@ -115,7 +107,7 @@ export default class Prefab extends Asset {
* prefab.optimizationPolicy = cc.Prefab.OptimizationPolicy.MULTI_INSTANCE;
*/
@property
optimizationPolicy = OptimizationPolicy.AUTO;
public optimizationPolicy = OptimizationPolicy.AUTO;
/**
* !#en Indicates the raw assets of this prefab can be load after prefab loaded.
@@ -124,14 +116,24 @@ export default class Prefab extends Asset {
* @default false
*/
@property
asyncLoadAssets = false;
public asyncLoadAssets = false;
static OptimizationPolicy = OptimizationPolicy;
private _createFunction: Function | null;
private _instantiatedTimes: number;
constructor () {
super();
/**
* Cache function to optimize instance creaton.
* @property {Function} _createFunction
* @private
*/
this._createFunction = null;
static OptimizationPolicyThreshold = 3;
this._instantiatedTimes = 0;
}
createNode (cb) {
var node = cc.instantiate(this);
public createNode (cb: Function): void {
const node = cc.instantiate(this);
node.name = this.name;
cb(null, node);
}
@@ -142,14 +144,14 @@ export default class Prefab extends Asset {
* but you can re-call to refresh the create function once you modified the original prefab data in script.
* @method compileCreateFunction
*/
compileCreateFunction () {
public compileCreateFunction (): void {
this._createFunction = compile(this.data);
}
// just instantiate, will not initialize the Node, this will be called during Node's initialization.
// @param {Node} [rootToRedirect] - specify an instantiated prefabRoot that all references to prefabRoot in prefab
// will redirect to
_doInstantiate (rootToRedirect) {
private _doInstantiate (rootToRedirect?: any) {
if (this.data._prefab) {
// prefab asset is always synced
this.data._prefab._synced = true;
@@ -161,11 +163,12 @@ export default class Prefab extends Asset {
if (!this._createFunction) {
this.compileCreateFunction();
}
return this._createFunction(rootToRedirect); // this.data._instantiate();
return this._createFunction!(rootToRedirect); // this.data._instantiate();
}
_instantiate () {
var node, useJit = false;
private _instantiate () {
let node;
let useJit: Boolean = false;
if (CC_SUPPORT_JIT) {
if (this.optimizationPolicy === OptimizationPolicy.SINGLE_INSTANCE) {
useJit = false;
@@ -194,7 +197,7 @@ export default class Prefab extends Asset {
// link prefab in editor
if (CC_EDITOR || CC_TEST) {
var PrefabUtils = Editor.require('scene://utils/prefab');
const PrefabUtils = Editor.require('scene://utils/prefab');
// This operation is not necessary, but some old prefab asset may not contain complete data.
PrefabUtils.linkPrefab(this, node);
}
@@ -1,137 +1,139 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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.
****************************************************************************/
import { Component } from './component';
const { ImageAsset } = require('../assets/image-asset');
let WXSubContextView;
if (!CC_EDITOR && !CC_WECHATGAME) {
WXSubContextView = cc.Class({
name: 'cc.WXSubContextView',
extends: Component,
})
}
else {
/**
* !#en WXSubContextView is a view component which controls open data context viewport in Wechat game platform.<br/>
* The component's node size decide the viewport of the sub context content in main context,
* the entire sub context texture will be scaled to the node's bounding box area.<br/>
* This component provides multiple important features:<br/>
* 1. Sub context could use its own resolution size and policy.<br/>
* 2. Sub context could be minized to smallest size it needed.<br/>
* 3. Resolution of sub context content could be increased.<br/>
* 4. User touch input is transformed to the correct viewport.<br/>
* 5. Texture update is handled by this component. User don't need to worry.<br/>
* One important thing to be noted, whenever the node's bounding box change,
* you need to manually reset the viewport of sub context using updateSubContextViewport.
* !#zh WXSubContextView 可以用来控制微信小游戏平台开放数据域在主域中的视窗的位置。<br/>
* 这个组件的节点尺寸决定了开放数据域内容在主域中的尺寸,整个开放数据域会被缩放到节点的包围盒范围内。<br/>
* 在这个组件的控制下,用户可以更自由得控制开放数据域:<br/>
* 1. 子域中可以使用独立的设计分辨率和适配模式<br/>
* 2. 子域区域尺寸可以缩小到只容纳内容即可<br/>
* 3. 子域的分辨率也可以被放大,以便获得更清晰的显示效果<br/>
* 4. 用户输入坐标会被自动转换到正确的子域视窗中<br/>
* 5. 子域内容贴图的更新由组件负责,用户不需要处理<br/>
* 唯一需要注意的是,当子域节点的包围盒发生改变时,开发者需要使用 `updateSubContextViewport` 来手动更新子域视窗。
* @class WXSubContextView
* @extends Component
*/
WXSubContextView = cc.Class({
name: 'cc.WXSubContextView',
extends: Component,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.others/WXSubContextView',
help: 'i18n:COMPONENT.help_url.wxSubContextView'
},
ctor () {
this._sprite = null;
this._tex = new cc.Texture2D();
this._context = null;
},
onLoad () {
// Setup subcontext canvas size
if (wx.getOpenDataContext) {
this._context = wx.getOpenDataContext();
let sharedCanvas = this._context.canvas;
if (sharedCanvas) {
sharedCanvas.width = this.node.width;
sharedCanvas.height = this.node.height;
}
this._tex.setPremultiplyAlpha(true);
this._tex.image = new ImageAsset(sharedCanvas);
this._sprite = this.node.getComponent(cc.Sprite);
if (!this._sprite) {
this._sprite = this.node.addComponent(cc.Sprite);
this._sprite.srcBlendFactor = cc.macro.BlendFactor.ONE;
}
this._sprite.spriteFrame = new cc.SpriteFrame(this._tex);
}
else {
this.enabled = false;
}
},
onEnable () {
this.updateSubContextViewport();
},
update () {
if (!this._tex || !this._context) {
return;
}
this._tex.updateImage(this._context.canvas);
this._sprite._activateMaterial();
},
/**
* !#en Update the sub context viewport manually, it should be called whenever the node's bounding box changes.
* !#zh 更新开放数据域相对于主域的 viewport,这个函数应该在节点包围盒改变时手动调用。
* @method updateSubContextViewport
*/
updateSubContextViewport () {
if (this._context) {
let box = this.node.getBoundingBoxToWorld();
let sx = cc.view._scaleX;
let sy = cc.view._scaleY;
this._context.postMessage({
fromEngine: true,
event: 'viewport',
x: box.x * sx + cc.view._viewportRect.x,
y: box.y * sy + cc.view._viewportRect.y,
width: box.width * sx,
height: box.height * sy
});
}
}
});
}
cc.WXSubContextView = module.exports = WXSubContextView;
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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.
****************************************************************************/
import { Component } from './component';
import { ImageAsset } from '../assets/image-asset';
let WXSubContextView;
if (!CC_EDITOR && !CC_WECHATGAME) {
WXSubContextView = cc.Class({
name: 'cc.WXSubContextView',
extends: Component,
});
}
else {
/**
* !#en WXSubContextView is a view component which controls open data context viewport in Wechat game platform.<br/>
* The component's node size decide the viewport of the sub context content in main context,
* the entire sub context texture will be scaled to the node's bounding box area.<br/>
* This component provides multiple important features:<br/>
* 1. Sub context could use its own resolution size and policy.<br/>
* 2. Sub context could be minized to smallest size it needed.<br/>
* 3. Resolution of sub context content could be increased.<br/>
* 4. User touch input is transformed to the correct viewport.<br/>
* 5. Texture update is handled by this component. User don't need to worry.<br/>
* One important thing to be noted, whenever the node's bounding box change,
* you need to manually reset the viewport of sub context using updateSubContextViewport.
* !#zh WXSubContextView 可以用来控制微信小游戏平台开放数据域在主域中的视窗的位置。<br/>
* 这个组件的节点尺寸决定了开放数据域内容在主域中的尺寸,整个开放数据域会被缩放到节点的包围盒范围内。<br/>
* 在这个组件的控制下,用户可以更自由得控制开放数据域:<br/>
* 1. 子域中可以使用独立的设计分辨率和适配模式<br/>
* 2. 子域区域尺寸可以缩小到只容纳内容即可<br/>
* 3. 子域的分辨率也可以被放大,以便获得更清晰的显示效果<br/>
* 4. 用户输入坐标会被自动转换到正确的子域视窗中<br/>
* 5. 子域内容贴图的更新由组件负责,用户不需要处理<br/>
* 唯一需要注意的是,当子域节点的包围盒发生改变时,开发者需要使用 `updateSubContextViewport` 来手动更新子域视窗。
* @class WXSubContextView
* @extends Component
*/
WXSubContextView = cc.Class({
name: 'cc.WXSubContextView',
extends: Component,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.others/WXSubContextView',
help: 'i18n:COMPONENT.help_url.wxSubContextView',
},
ctor () {
this._sprite = null;
this._tex = new cc.Texture2D();
this._context = null;
},
onLoad () {
// Setup subcontext canvas size
if (wx.getOpenDataContext) {
this._context = wx.getOpenDataContext();
const sharedCanvas = this._context.canvas;
if (sharedCanvas) {
sharedCanvas.width = this.node.width;
sharedCanvas.height = this.node.height;
}
this._tex.setPremultiplyAlpha(true);
this._tex.image = new ImageAsset(sharedCanvas);
this._sprite = this.node.getComponent(cc.Sprite);
if (!this._sprite) {
this._sprite = this.node.addComponent(cc.Sprite);
this._sprite.srcBlendFactor = cc.macro.BlendFactor.ONE;
}
this._sprite.spriteFrame = new cc.SpriteFrame(this._tex);
}
else {
this.enabled = false;
}
},
onEnable () {
this.updateSubContextViewport();
},
update () {
if (!this._tex || !this._context) {
return;
}
this._tex.updateImage(this._context.canvas);
this._sprite._activateMaterial();
},
/**
* !#en Update the sub context viewport manually, it should be called whenever the node's bounding box changes.
* !#zh 更新开放数据域相对于主域的 viewport,这个函数应该在节点包围盒改变时手动调用。
* @method updateSubContextViewport
*/
updateSubContextViewport () {
if (this._context) {
const box = this.node.getBoundingBoxToWorld();
const sx = cc.view._scaleX;
const sy = cc.view._scaleY;
this._context.postMessage({
fromEngine: true,
event: 'viewport',
x: box.x * sx + cc.view._viewportRect.x,
y: box.y * sy + cc.view._viewportRect.y,
width: box.width * sx,
height: box.height * sy,
});
}
},
});
}
export default WXSubContextView;
cc.WXSubContextView = WXSubContextView;
@@ -1,130 +1,131 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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.
****************************************************************************/
import {_getClassById} from '../core/utils/js';
import {BUILTIN_CLASSID_RE} from '../core/utils/misc';
import { Component } from './component';
import {ccclass, property, inspector} from '../core/data/class-decorator';
/*
* A temp fallback to contain the original serialized data which can not be loaded.
*/
@ccclass('cc.MissingClass')
class MissingClass {
// the serialized data for original object
@property({
visible: false,
editorOnly: true
})
_$erialized = null;
}
/*
* A temp fallback to contain the original component which can not be loaded.
*/
@ccclass('cc.MissingScript')
@inspector('packages://inspector/inspectors/comps/missing-script.js')
export default class MissingScript extends Component {
//_scriptUuid: {
// get: function () {
// var id = this._$erialized.__type__;
// if (Editor.Utils.UuidUtils.isUuid(id)) {
// return Editor.Utils.UuidUtils.decompressUuid(id);
// }
// return '';
// },
// set: function (value) {
// if ( !sandbox.compiled ) {
// cc.error('Scripts not yet compiled, please fix script errors and compile first.');
// return;
// }
// if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) {
// var classId = Editor.Utils.UuidUtils.compressUuid(value);
// if (_getClassById(classId)) {
// this._$erialized.__type__ = classId;
// Editor.Ipc.sendToWins('reload:window-scripts', sandbox.compiled);
// }
// else {
// cc.error('Can not find a component in the script which uuid is "%s".', value);
// }
// }
// else {
// cc.error('invalid script');
// }
// }
//},
@property({
serializable: false
})
compiled = false;
// the serialized data for original script object
@property({
visible: false,
editorOnly: true
})
_$erialized = null;
constructor () {
super();
if (CC_EDITOR) {
this.compiled = _Scene.Sandbox.compiled;
}
}
/*
* @param {string} id
* @return {function} constructor
*/
static safeFindClass (id, data) {
var cls = _getClassById(id);
if (cls) {
return cls;
}
if (id) {
cc.deserialize.reportMissingClass(id);
return MissingScript.getMissingWrapper(id, data);
}
return null;
}
static getMissingWrapper (id, data) {
if (data.node && (/^[0-9a-zA-Z+/]{23}$/.test(id) || BUILTIN_CLASSID_RE.test(id))) {
// is component
return MissingScript;
}
else {
return MissingClass;
}
}
onLoad () {
cc.warnID(4600, this.node.name);
}
}
cc._MissingScript = MissingScript;
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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.
****************************************************************************/
import {ccclass, inspector, property} from '../core/data/class-decorator';
import {_getClassById} from '../core/utils/js';
import {BUILTIN_CLASSID_RE} from '../core/utils/misc';
import { Component } from './component';
/*
* A temp fallback to contain the original serialized data which can not be loaded.
*/
@ccclass('cc.MissingClass')
class MissingClass {
// the serialized data for original object
@property({
visible: false,
editorOnly: true,
})
public _$erialized = null;
}
/*
* A temp fallback to contain the original component which can not be loaded.
*/
@ccclass('cc.MissingScript')
@inspector('packages://inspector/inspectors/comps/missing-script.js')
export default class MissingScript extends Component {
// _scriptUuid: {
// get: function () {
// var id = this._$erialized.__type__;
// if (Editor.Utils.UuidUtils.isUuid(id)) {
// return Editor.Utils.UuidUtils.decompressUuid(id);
// }
// return '';
// },
// set: function (value) {
// if ( !sandbox.compiled ) {
// cc.error('Scripts not yet compiled, please fix script errors and compile first.');
// return;
// }
// if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) {
// var classId = Editor.Utils.UuidUtils.compressUuid(value);
// if (_getClassById(classId)) {
// this._$erialized.__type__ = classId;
// Editor.Ipc.sendToWins('reload:window-scripts', sandbox.compiled);
// }
// else {
// cc.error('Can not find a component in the script which uuid is "%s".', value);
// }
// }
// else {
// cc.error('invalid script');
// }
// }
// },
/*
* @param {string} id
* @return {function} constructor
*/
public static safeFindClass (id, data) {
const cls = _getClassById(id);
if (cls) {
return cls;
}
if (id) {
cc.deserialize.reportMissingClass(id);
return MissingScript.getMissingWrapper(id, data);
}
return null;
}
public static getMissingWrapper (id, data) {
if (data.node && (/^[0-9a-zA-Z+/]{23}$/.test(id) || BUILTIN_CLASSID_RE.test(id))) {
// is component
return MissingScript;
}
else {
return MissingClass;
}
}
@property({
serializable: false,
})
public compiled = false;
// the serialized data for original script object
@property({
visible: false,
editorOnly: true,
})
public _$erialized = null;
constructor () {
super();
if (CC_EDITOR) {
// @ts-ignore
this.compiled = _Scene.Sandbox.compiled;
}
}
public onLoad () {
cc.warnID(4600, this.node.name);
}
}
cc._MissingScript = MissingScript;
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -100,8 +100,8 @@ class CCLoader extends Pipeline {
public downloader: Downloader;
public loader: Loader;
public onProgress: null;
public _assetTables: any;
private _assetTables: any;
private _autoReleaseSetting: any;
private _releasedAssetChecker_DEBUG: any;
private _ownerQueue: any;