Commit 9b8ae891 authored by haiyoucuv's avatar haiyoucuv

1

parent a3eb0863
File added
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="TsLint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="JavaScriptSettings"> <component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" /> <option name="languageLevel" value="FLOW" />
</component> </component>
</project> </project>
\ No newline at end of file
<changelist name="Uncommitted_changes_before_Checkout_at_2020_5_15,_2_12_下午_[Default_Changelist]" date="1589523138013" recycled="false" toDelete="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Checkout_at_2020_5_15,_2_12_下午_[Default_Changelist]/shelved.patch" />
<option name="DESCRIPTION" value="Uncommitted changes before Checkout at 2020/5/15, 2:12 下午 [Default Changelist]" />
</changelist>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
<changelist name="Uncommitted_changes_before_Update_at_2020_5_14,_2_47_下午_[Default_Changelist]" date="1589438835098" recycled="false" toDelete="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Update_at_2020_5_14,_2_47_下午_[Default_Changelist]/shelved.patch" />
<option name="DESCRIPTION" value="Uncommitted changes before Update at 2020/5/14, 2:47 下午 [Default Changelist]" />
</changelist>
\ No newline at end of file
<changelist name="Uncommitted_changes_before_Update_at_2020_5_14,_2_47_下午_[Default_Changelist]1" date="1589438857749" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Update_at_2020_5_14,_2_47_下午_[Default_Changelist]1/shelved.patch" />
<option name="DESCRIPTION" value="Uncommitted changes before Update at 2020/5/14, 2:47 下午 [Default Changelist]" />
</changelist>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -26,10 +26,10 @@ export default { ...@@ -26,10 +26,10 @@ export default {
}, },
], ],
plugins: [ plugins: [
progress(), // progress(),
resolve({}), resolve({}),
typescript({ typescript({
//useTsconfigDeclarationDir: true, // useTsconfigDeclarationDir: true,
}), }),
commonjs(), commonjs(),
process.env.BUILD === 'production' && uglify({}) process.env.BUILD === 'production' && uglify({})
......
This diff is collapsed.
...@@ -395,10 +395,19 @@ export default class Sprite extends Container { ...@@ -395,10 +395,19 @@ export default class Sprite extends Container {
} }
set width(value) { set width(value) {
value = Math.abs(value);
const s = sign(this.scale.x) || 1; const s = sign(this.scale.x) || 1;
this.scale.x = s * value / this._texture.orig.width; this.scale.x = s * value / this._texture.orig.width;
this._width = value; this._width = value;
this.dispatchEvent(Event.MAYBE_ALIGN);
if(isNaN(this.percentWidth) || this.percentWidth === null) {
this.__width = value;
} else {
this.__width = 0;
}
} }
/** /**
...@@ -410,9 +419,17 @@ export default class Sprite extends Container { ...@@ -410,9 +419,17 @@ export default class Sprite extends Container {
} }
set height(value) { set height(value) {
value = Math.abs(value);
const s = sign(this.scale.y) || 1; const s = sign(this.scale.y) || 1;
this.scale.y = s * value / this._texture.orig.height; this.scale.y = s * value / this._texture.orig.height;
this._height = value; this._height = value;
this.dispatchEvent(Event.MAYBE_ALIGN);
if(isNaN(this.percentHeight) || this.percentHeight === null) {
this.__height = value;
} else {
this.__height= 0;
}
} }
/** /**
......
...@@ -12,6 +12,7 @@ import {WebglRenderer} from "../renderers/WebglRenderer"; ...@@ -12,6 +12,7 @@ import {WebglRenderer} from "../renderers/WebglRenderer";
import {GDispatcher} from "../events/GDispatcher"; import {GDispatcher} from "../events/GDispatcher";
import CanvasRenderer from "../renderers/CanvasRenderer"; import CanvasRenderer from "../renderers/CanvasRenderer";
import {GlobalPro, isWebGLSupported} from "../utils/index"; import {GlobalPro, isWebGLSupported} from "../utils/index";
import { alignMgr } from "../../zeroing/decorators/AlignManager";
//如果以后还出现帧率问题,使用ticker; //如果以后还出现帧率问题,使用ticker;
//兼容requestAnimationFrame //兼容requestAnimationFrame
...@@ -972,12 +973,13 @@ export class Stage extends Container { ...@@ -972,12 +973,13 @@ export class Stage extends Container {
if (!GlobalPro.startTime) GlobalPro.startTime = Date.now(); if (!GlobalPro.startTime) GlobalPro.startTime = Date.now();
//console.log('flushAll', Date.now()); //console.log('flushAll', Date.now());
alignMgr.flush();
if (!Stage._pause) { if (!Stage._pause) {
let len = Stage.allUpdateObjList.length; let len = Stage.allUpdateObjList.length;
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
Stage.allUpdateObjList[i] && Stage.allUpdateObjList[i].flush(); Stage.allUpdateObjList[i] && Stage.allUpdateObjList[i].flush();
} }
} }
requestAnimationFrame(Stage.flushAll); requestAnimationFrame(Stage.flushAll);
} }
......
...@@ -9,8 +9,9 @@ import {HashObject} from "../HashObject"; ...@@ -9,8 +9,9 @@ import {HashObject} from "../HashObject";
*/ */
export class Event extends HashObject { export class Event extends HashObject {
// public static IMAGE_LOADED: string = "onImageLoaded" public static MAYBE_ALIGN: string = "maybeAlign";
// public static IMAGE_LOADED: string = "onImageLoaded"
/** /**
* 舞台尺寸发生变化时触发 * 舞台尺寸发生变化时触发
* @Event * @Event
......
import { ALIGN_MODE } from "./auto-adjust";
import { toBoolean } from "../utils/utils";
/**
* 自适应管理器
* @constructor
*/
class AlignManager {
// 这个列表里的对象会在渲染前被自动调整
private alignList = [];
constructor() {
}
/**
* flash (渲染前)
*/
public flush() {
this.alignList.forEach((v) => {
this.autoSize(v); // 去调整大小
this.align(v); // 去自动对齐
});
// 要在这里单独检查,因为对齐一次后可能遇到其父节点需要对齐导致其再对齐一次
this.alignList.forEach((v) => {
if(v.alignMode === ALIGN_MODE.ONCE) { // 如果是单次对齐则一次运算之后就关闭它
v.alignEnabled = false;
}
});
// 干掉列表
this.alignList.length = 0;
}
/**
* align
* @param that
*/
private align(that) {
// if(that)
if(!that.alignEnabled) return; // 如果的自动对齐关闭里则啥也不干
// if(that.alignMode === ALIGN_MODE.ONCE) { // 如果是单次对齐则一次运算之后就关闭它
// that.alignEnabled = false;
// }
const {percentWidth, percentHeight, left, top, right, bottom, horizonCenter, verticalCenter} = that;
let {_width: tW_Z = 0, _height: tH_Z = 0} = that;
const {_width: pW_Z = 0, _height: pH_Z = 0} = (that.parent || {});
/**
* 计算 width 和 x 值
*/
if(toBoolean(left) && toBoolean(right)) { // left right 都有则直接拉伸或缩小
that.x = left;
that.width = pW_Z - left - right;
} else {
// 先设置下自己的 width
toBoolean(percentWidth) && (tW_Z = that.width = pW_Z * percentWidth / 100);
// 先考虑 horizonCenter 属性
if(toBoolean(horizonCenter)) {
// x 值 = 父节点的中间值 - 自己宽度的一半 - 居中差值
that.x = pW_Z / 2 - tW_Z / 2 + horizonCenter;
} else if(toBoolean(left)) { // 假如有左边距
that.x = left;
} else if(toBoolean(right)) { // 假如有右边距
that.x = pW_Z - right - tW_Z;
}
}
/**
* 计算 height 和 y 值
*/
if(toBoolean(top) && toBoolean(bottom)) { // top bottom 都有则直接拉伸或缩小
that.y = top;
that.height = pH_Z - top - bottom;
} else {
// 先设置下自己的 height
toBoolean(percentHeight) && (tH_Z = that.height = pH_Z * percentHeight / 100);
// 先考虑 horizonCenter 属性
if(toBoolean(verticalCenter)) {
// x 值 = 父节点的中间值 - 自己高度的一半 - 居中差值
that.y = pH_Z / 2 - tH_Z / 2 + verticalCenter;
} else if(toBoolean(top)) { // 假如有 top
that.y = top;
} else if(toBoolean(bottom)) { // 假如有 bottom
that.y = pH_Z - bottom - tH_Z;
}
}
// console.log(that.name, that.width, that.height);
that.children.forEach(v => this.align(v));
}
/**
* 自动大小
* @param that
*/
private autoSize(that) {
let len = that.children.length
if(len > 0) {
// 检测本身的是否是可以自动宽
if(that.autoWidth && !toBoolean(that.right) && !toBoolean(that.percentWidth)) {
// 找出子节点最小x
// let minX = 0;
// for(let i = 0; i < len; i++) {
// if(that.children[i].x < minX) {
// minX = that.children[i].x;
// }
// }
// if(minX < 0) {
// that.children.forEach(v => v.x -= minX);
// that.x += minX;
// that.width -= minX;
// }
// 找出最右值
let max = 0;
for(let i = 0; i < len; i++) {
if(toBoolean(that.children[i].right)) continue;
let _x = that.children[i].x || 0;
let _w = that.children[i].__width || 0;
if(_x + _w > max) {
max = _x + _w;
}
}
that.width = max;
}
// 检测本身的是否是可以自动高
if(that.autoHeight && !toBoolean(that.bottom) && !toBoolean(that.percentHeight)) {
// 找出子节点最小y
// let minY = 0;
// for(let i = 1; i < len; i++) {
// if(that.children[i].y < minY) {
// minY = that.children[i].y;
// }
// }
// if(minY < 0) {
// that.children.forEach(v => v.y -= minY);
// that.y += minY;
// that.height -= minY;
// }
// 找出最下值
let max = 0;
for(let i = 0; i < len; i++) {
if(toBoolean(that.children[i].bottom)) continue;
let _y = that.children[i].y || 0;
let _h = that.children[i].__height || 0;
if(_y + _h > max) {
max = _y + _h;
}
}
that.height = max;
}
}
}
/**
* 添加一个变脏的对象
* @param obj
*/
public addAlign(obj) {
if(this.alignList.indexOf(obj) < 0) {
this.alignList.push(obj);
}
}
}
export let alignMgr = new AlignManager();
This diff is collapsed.
...@@ -2,23 +2,23 @@ ...@@ -2,23 +2,23 @@
* Created by rockyl on 2019-11-05. * Created by rockyl on 2019-11-05.
*/ */
import {Stage} from "../../2d/display/index"; import { Stage } from "../../2d/display/index";
import {StackContainer} from "./StackContainer"; import { StackContainer } from "./StackContainer";
import {checkAssetGroupLoaded, loadAssetsGroup, loadAssets, loadAssetsGroups} from "./assets-manager"; import { checkAssetGroupLoaded, loadAssetsGroup, loadAssets, loadAssetsGroups } from "./assets-manager";
import {instantiate} from "./view-interpreter"; import { instantiate } from "./view-interpreter";
import {dataCenter, DataCenter} from "./data-center"; import { dataCenter, DataCenter } from "./data-center";
import {setProcessMetaLibs} from "../behavior-runtime/index"; import { setProcessMetaLibs } from "../behavior-runtime/index";
import {Tween} from "../../2d/tween/index"; import { Tween } from "../../2d/tween/index";
import {Rect} from "./nodes/index"; import { Rect } from "./nodes/index";
import {injectEnv} from "./enviroment"; import { injectEnv } from "./enviroment";
import {Toast} from "./Toast"; import { Toast } from "./Toast";
import {arrayFind} from "../utils/index"; import { arrayFind } from "../utils/index";
import {Node} from "./nodes/Node"; import { Node } from "./nodes/Node";
import {bind, createStore} from "./mvvm/index"; import { bind, createStore } from "./mvvm/index";
import {registerCustomModules} from "./custom-module"; import { registerCustomModules } from "./custom-module";
import {dealPageRemainTime, dealPxEnv} from "../px-logics"; import { dealPageRemainTime, dealPxEnv } from "../px-logics";
import Container from "../../2d/display/Container"; import Container from "../../2d/display/Container";
import {Event} from "../../2d/events/Event"; import { Event } from "../../2d/events/Event";
/** /**
* 游戏舞台 * 游戏舞台
...@@ -123,7 +123,7 @@ export class GameStage extends Node { ...@@ -123,7 +123,7 @@ export class GameStage extends Node {
registerCustomModules(customs); registerCustomModules(customs);
if (dataMapping) { if(dataMapping) {
this.dataCenter.registerDataMapping(dataMapping); this.dataCenter.registerDataMapping(dataMapping);
} }
setProcessMetaLibs(processes, builtinProcesses); setProcessMetaLibs(processes, builtinProcesses);
...@@ -145,12 +145,12 @@ export class GameStage extends Node { ...@@ -145,12 +145,12 @@ export class GameStage extends Node {
* 开始游戏 * 开始游戏
*/ */
start() { start() {
const {options: {entrySceneView, }, } = this._config; const {options: {entrySceneView,},} = this._config;
setTimeout(async () => { setTimeout(async () => {
let sceneEntry = await this.instantiateView(entrySceneView); let sceneEntry = await this.instantiateView(entrySceneView);
if (sceneEntry) { if(sceneEntry) {
this._sceneContainer.push(sceneEntry); this._sceneContainer.push(sceneEntry);
} }
}) })
...@@ -162,7 +162,7 @@ export class GameStage extends Node { ...@@ -162,7 +162,7 @@ export class GameStage extends Node {
async showInnerLoadingView() { async showInnerLoadingView() {
let loadingViewName = this._config.options.loadingView; let loadingViewName = this._config.options.loadingView;
let loadingView = this._loadingView.getChildAt(0); let loadingView = this._loadingView.getChildAt(0);
if (this._loadingView.children.length == 0 && loadingViewName) { if(this._loadingView.children.length == 0 && loadingViewName) {
loadingView = await this.instantiateView(loadingViewName, true, false); loadingView = await this.instantiateView(loadingViewName, true, false);
this._loadingView.addChild(loadingView); this._loadingView.addChild(loadingView);
} }
...@@ -173,7 +173,7 @@ export class GameStage extends Node { ...@@ -173,7 +173,7 @@ export class GameStage extends Node {
* 隐藏加载视图 * 隐藏加载视图
*/ */
hideInnerLoadingView() { hideInnerLoadingView() {
if (this._loadingView.visible) { if(this._loadingView.visible) {
this._loadingView.visible = false; this._loadingView.visible = false;
} }
} }
...@@ -186,40 +186,40 @@ export class GameStage extends Node { ...@@ -186,40 +186,40 @@ export class GameStage extends Node {
*/ */
async instantiateView(name, cache = true, showLoadingView = true) { async instantiateView(name, cache = true, showLoadingView = true) {
let view; let view;
if (cache) { if(cache) {
view = this._viewCache[name]; view = this._viewCache[name];
} }
if (!view) { if(!view) {
let viewConfig = this.getViewConfigByName(name); let viewConfig = this.getViewConfigByName(name);
if (viewConfig) { if(viewConfig) {
const {assets, customs} = this._config; const {assets, customs} = this._config;
if (!Array.isArray(assets)) { if(!Array.isArray(assets)) {
let groups = {}; let groups = {};
let {depCustoms} = viewConfig; let {depCustoms} = viewConfig;
if (depCustoms && depCustoms.length > 0) { if(depCustoms && depCustoms.length > 0) {
for (let custom of customs) { for(let custom of customs) {
if (depCustoms.indexOf(custom.id) >= 0 && custom.assets) { if(depCustoms.indexOf(custom.id) >= 0 && custom.assets) {
if (!checkAssetGroupLoaded(custom.id)) { if(!checkAssetGroupLoaded(custom.id)) {
groups[custom.id] = custom.assets; groups[custom.id] = custom.assets;
} }
} }
} }
} }
if (!checkAssetGroupLoaded(viewConfig.uuid)) { if(!checkAssetGroupLoaded(viewConfig.uuid)) {
let depAssets = assets[viewConfig.uuid]; let depAssets = assets[viewConfig.uuid];
if (depAssets && depAssets.length > 0) { if(depAssets && depAssets.length > 0) {
groups[viewConfig.uuid] = depAssets; groups[viewConfig.uuid] = depAssets;
} }
} }
if(Object.keys(groups).length > 0){ if(Object.keys(groups).length > 0) {
await loadAssetsGroups(groups, async () => { await loadAssetsGroups(groups, async () => {
if (showLoadingView) { if(showLoadingView) {
await this.showInnerLoadingView(); await this.showInnerLoadingView();
} }
}, async () => { }, async () => {
if (showLoadingView) { if(showLoadingView) {
this.hideInnerLoadingView(); this.hideInnerLoadingView();
} }
}); });
...@@ -228,7 +228,7 @@ export class GameStage extends Node { ...@@ -228,7 +228,7 @@ export class GameStage extends Node {
view = instantiate(viewConfig); view = instantiate(viewConfig);
let store = {}; let store = {};
if (viewConfig.store) { if(viewConfig.store) {
const {exp, computed} = viewConfig.store; const {exp, computed} = viewConfig.store;
store = createStore(exp, computed); store = createStore(exp, computed);
} }
...@@ -240,7 +240,7 @@ export class GameStage extends Node { ...@@ -240,7 +240,7 @@ export class GameStage extends Node {
bind(store, view); bind(store, view);
console.timeEnd('bind'); console.timeEnd('bind');
if (cache) { if(cache) {
this._viewCache[name] = view; this._viewCache[name] = view;
} }
} else { } else {
...@@ -262,11 +262,11 @@ export class GameStage extends Node { ...@@ -262,11 +262,11 @@ export class GameStage extends Node {
const {action, view, lastView, options, hasView} = e.data; const {action, view, lastView, options, hasView} = e.data;
const target = <StackContainer>e.target; const target = <StackContainer>e.target;
switch (action) { switch(action) {
case 'push': case 'push':
case 'replace': case 'replace':
case 'popAll': case 'popAll':
if (options && options.center) { if(options && options.center) {
view.x = (target.width - view.width) / 2; view.x = (target.width - view.width) / 2;
view.y = (target.height - view.height) / 2; view.y = (target.height - view.height) / 2;
} }
...@@ -275,18 +275,18 @@ export class GameStage extends Node { ...@@ -275,18 +275,18 @@ export class GameStage extends Node {
let blackLayer = this._blackLayer; let blackLayer = this._blackLayer;
let pParent = blackLayer.parent; let pParent = blackLayer.parent;
if (hasView) { if(hasView) {
target.addChildAt(blackLayer, target.childNum - 1 - (view ? 0 : 1)); target.addChildAt(blackLayer, target.childNum - 1 - (view ? 0 : 1));
let modalAlpha = 0.7; let modalAlpha = 0.7;
if(options && options.hasOwnProperty('modalAlpha')){ if(options && options.hasOwnProperty('modalAlpha')) {
modalAlpha = options.modalAlpha; modalAlpha = options.modalAlpha;
} }
if (!pParent || blackLayer['tween_count'] > 0) { if(!pParent || blackLayer['tween_count'] > 0) {
blackLayer.alpha = 0; blackLayer.alpha = 0;
Tween.get(blackLayer, null, null, true) Tween.get(blackLayer, null, null, true)
.to({alpha: modalAlpha}, 300); .to({alpha: modalAlpha}, 300);
} }
} else if (pParent) { } else if(pParent) {
Tween.get(blackLayer, null, null, true) Tween.get(blackLayer, null, null, true)
.to({alpha: 0}, 300) .to({alpha: 0}, 300)
.call(() => { .call(() => {
...@@ -301,32 +301,32 @@ export class GameStage extends Node { ...@@ -301,32 +301,32 @@ export class GameStage extends Node {
lazyLoadAllAssets = async () => { lazyLoadAllAssets = async () => {
let {assets, customs} = this._config; let {assets, customs} = this._config;
if (!Array.isArray(assets)) { if(!Array.isArray(assets)) {
for (let uuid in assets) { for(let uuid in assets) {
let group = assets[uuid]; let group = assets[uuid];
if (group && group.length > 0) { if(group && group.length > 0) {
await loadAssetsGroup(group, uuid); await loadAssetsGroup(group, uuid);
} }
} }
} }
for (let custom of customs) { for(let custom of customs) {
let group = custom.assets; let group = custom.assets;
if (group && group.length > 0) { if(group && group.length > 0) {
await loadAssetsGroup(group, custom.id); await loadAssetsGroup(group, custom.id);
} }
} }
}; };
async loadPreloadAssets(onPreloadAssetsProgress, onPreloadAssetsComplete){ async loadPreloadAssets(onPreloadAssetsProgress, onPreloadAssetsComplete) {
const {assets, } = this._config; const {assets,} = this._config;
let loaded = 0; let loaded = 0;
let assetsToLoad = assets; let assetsToLoad = assets;
let total; let total;
if (!Array.isArray(assets)) { //如果是分组后的配置就加载共用分组,否则加载全部 if(!Array.isArray(assets)) { //如果是分组后的配置就加载共用分组,否则加载全部
assetsToLoad = assets['common']; assetsToLoad = assets['common'];
if(assetsToLoad.length > 0){ if(assetsToLoad.length > 0) {
await this.showInnerLoadingView(); await this.showInnerLoadingView();
await loadAssetsGroups({ await loadAssetsGroups({
preload: assetsToLoad, preload: assetsToLoad,
...@@ -336,7 +336,7 @@ export class GameStage extends Node { ...@@ -336,7 +336,7 @@ export class GameStage extends Node {
this.hideInnerLoadingView(); this.hideInnerLoadingView();
}); });
} }
}else{ } else {
total = assetsToLoad.length; total = assetsToLoad.length;
await loadAssets(assetsToLoad, p).catch(e => { await loadAssets(assetsToLoad, p).catch(e => {
console.log(e); console.log(e);
...@@ -347,7 +347,7 @@ export class GameStage extends Node { ...@@ -347,7 +347,7 @@ export class GameStage extends Node {
loaded++; loaded++;
onPreloadAssetsProgress && onPreloadAssetsProgress(loaded, total); onPreloadAssetsProgress && onPreloadAssetsProgress(loaded, total);
if (loaded >= total) { if(loaded >= total) {
onPreloadAssetsComplete && onPreloadAssetsComplete(); onPreloadAssetsComplete && onPreloadAssetsComplete();
} }
} }
......
...@@ -2,21 +2,23 @@ ...@@ -2,21 +2,23 @@
* Created by rockyl on 2019-11-08. * Created by rockyl on 2019-11-08.
*/ */
import {Stage} from "../2d/display/index"; import { Stage } from "../2d/display/index";
import {GameStage, registerCustomModuleFromConfig} from "./game-warpper/index"; import { GameStage, registerCustomModuleFromConfig } from "./game-warpper/index";
import {setGlobalContext, setProcessMetaLibs} from "./behavior-runtime/index"; import { setGlobalContext, setProcessMetaLibs } from "./behavior-runtime/index";
import {globalLoader} from "../2d/loader/Loader"; import { globalLoader } from "../2d/loader/Loader";
import {Event} from "../2d/events/Event"; import { Event } from "../2d/events/Event";
import builtinLoadingView from "./game-warpper/LoadingView"; import builtinLoadingView from "./game-warpper/LoadingView";
import {queryParams} from "./web"; import { queryParams } from "./web";
import {initAutoLayout} from "./game-warpper/auto-layout"; import { initAutoLayout } from "./game-warpper/auto-layout";
import {registerScripts} from "./decorators/scripts"; import { registerScripts } from "./decorators/scripts";
import {RENDERER_TYPE, StageScaleMode} from "../2d/const"; import { RENDERER_TYPE, StageScaleMode } from "../2d/const";
import { alignMgr } from "./decorators/AlignManager";
export let gameStage: GameStage; export let gameStage: GameStage;
export let alignManager = alignMgr;
export function launch(url, loadingDelegate?, onStart?) { export function launch(url, loadingDelegate?, onStart?) {
if (queryParams.__proxy_mode__) { if(queryParams.__proxy_mode__) {
return Promise.resolve('cancel launch'); return Promise.resolve('cancel launch');
} }
return globalLoader.loadJson(url) return globalLoader.loadJson(url)
...@@ -52,6 +54,7 @@ export async function launchWithConfig(config, loadingDelegate?, onStart?) { ...@@ -52,6 +54,7 @@ export async function launchWithConfig(config, loadingDelegate?, onStart?) {
setTimeout(resolve, 300); setTimeout(resolve, 300);
}); });
return await new Promise(resolve => { return await new Promise(resolve => {
const {containerId, designWidth, designHeight, frameRate, scaleMode, rendererType, bgColor, autoResize,} = config.options; const {containerId, designWidth, designHeight, frameRate, scaleMode, rendererType, bgColor, autoResize,} = config.options;
let stage = window['stage'] = new Stage( let stage = window['stage'] = new Stage(
containerId || "game-container", containerId || "game-container",
...@@ -67,6 +70,8 @@ export async function launchWithConfig(config, loadingDelegate?, onStart?) { ...@@ -67,6 +70,8 @@ export async function launchWithConfig(config, loadingDelegate?, onStart?) {
initAutoLayout(stage); initAutoLayout(stage);
Stage.flushAll(); Stage.flushAll();
// Stage.addUpdateObj(alignMgr);
stage.addEventListener(Event.ON_INIT_STAGE, () => { stage.addEventListener(Event.ON_INIT_STAGE, () => {
gameStage = new GameStage(stage); gameStage = new GameStage(stage);
setGlobalContext({ setGlobalContext({
...@@ -76,9 +81,9 @@ export async function launchWithConfig(config, loadingDelegate?, onStart?) { ...@@ -76,9 +81,9 @@ export async function launchWithConfig(config, loadingDelegate?, onStart?) {
let delegate = loadingDelegate || builtinLoadingView; let delegate = loadingDelegate || builtinLoadingView;
gameStage.launch(config, function (done, total) { gameStage.launch(config, function(done, total) {
delegate.onProgress && delegate.onProgress(done, total) delegate.onProgress && delegate.onProgress(done, total)
}, function () { }, function() {
delegate.onComplete && delegate.onComplete(); delegate.onComplete && delegate.onComplete();
}, onStart); }, onStart);
}); });
......
...@@ -14,13 +14,13 @@ export const linkScheme = 'link://'; ...@@ -14,13 +14,13 @@ export const linkScheme = 'link://';
* @param predicate * @param predicate
*/ */
export function arrayFind(arr, predicate) { export function arrayFind(arr, predicate) {
if (!arr) { if(!arr) {
return; return;
} }
for (let i = 0, li = arr.length; i < li; i++) { for(let i = 0, li = arr.length; i < li; i++) {
const item = arr[i]; const item = arr[i];
if (predicate(item, i, arr)) { if(predicate(item, i, arr)) {
return item; return item;
} }
} }
...@@ -39,9 +39,9 @@ const percentKeys = ['width', 'height']; ...@@ -39,9 +39,9 @@ const percentKeys = ['width', 'height'];
export function propertyParse(key, node, properties) { export function propertyParse(key, node, properties) {
let value = properties[key]; let value = properties[key];
let targetKey = key; let targetKey = key;
if (percentKeys.indexOf(key) >= 0) { if(percentKeys.indexOf(key) >= 0) {
if (typeof value === 'string') { if(typeof value === 'string') {
if (value[value.length - 1] === '%') { if(value[value.length - 1] === '%') {
targetKey = 'percent' + key[0].toUpperCase() + key.substr(1); targetKey = 'percent' + key[0].toUpperCase() + key.substr(1);
} }
value = parseInt(value); value = parseInt(value);
...@@ -60,9 +60,9 @@ export function getDataByPath(scope, path, throwException?) { ...@@ -60,9 +60,9 @@ export function getDataByPath(scope, path, throwException?) {
let func = new Function('scope', `return scope` + (path ? ('.' + path) : '')); let func = new Function('scope', `return scope` + (path ? ('.' + path) : ''));
try { try {
return func(scope); return func(scope);
} catch (e) { } catch(e) {
//console.warn(e); //console.warn(e);
if (throwException) { if(throwException) {
throw e; throw e;
} }
} }
...@@ -77,8 +77,8 @@ export function safeEval(code, throwException = false) { ...@@ -77,8 +77,8 @@ export function safeEval(code, throwException = false) {
let func = new Function(code); let func = new Function(code);
try { try {
return func(); return func();
} catch (e) { } catch(e) {
if (throwException) { if(throwException) {
throw e; throw e;
} }
} }
...@@ -95,20 +95,20 @@ export function safeEval(code, throwException = false) { ...@@ -95,20 +95,20 @@ export function safeEval(code, throwException = false) {
* @return 是否有字段注入 * @return 是否有字段注入
*/ */
export function injectProp(target: any, data?: any, callback?: Function, ignoreMethod: boolean = true, ignoreNull: boolean = true): boolean { export function injectProp(target: any, data?: any, callback?: Function, ignoreMethod: boolean = true, ignoreNull: boolean = true): boolean {
if (!target || !data) { if(!target || !data) {
return false; return false;
} }
let result = false; let result = false;
for (let key in data) { for(let key in data) {
let value: any = data[key]; let value: any = data[key];
if ((!ignoreMethod || typeof value != 'function') && (!ignoreNull || value != null)) { if((!ignoreMethod || typeof value != 'function') && (!ignoreNull || value != null)) {
if (callback) { if(callback) {
callback(target, key, value); callback(target, key, value);
} else { } else {
try { try {
target[key] = value; target[key] = value;
} catch (e) { } catch(e) {
} }
} }
...@@ -126,17 +126,17 @@ export function injectProp(target: any, data?: any, callback?: Function, ignoreM ...@@ -126,17 +126,17 @@ export function injectProp(target: any, data?: any, callback?: Function, ignoreM
* @param config * @param config
*/ */
export function copyProp(target, data, config?) { export function copyProp(target, data, config?) {
if (data) { if(data) {
for (let key in config) { for(let key in config) {
let valueConfig = config[key]; let valueConfig = config[key];
if (Array.isArray(valueConfig)) { if(Array.isArray(valueConfig)) {
target[key] = {}; target[key] = {};
for (let field of valueConfig) { for(let field of valueConfig) {
target[key][field] = data[key][field]; target[key][field] = data[key][field];
} }
} else if (typeof valueConfig === 'string') { } else if(typeof valueConfig === 'string') {
target[valueConfig] = data[valueConfig]; target[valueConfig] = data[valueConfig];
} else if (typeof valueConfig === 'object') { } else if(typeof valueConfig === 'object') {
target[key] = {}; target[key] = {};
copyProp(target[key], data[key], valueConfig) copyProp(target[key], data[key], valueConfig)
} }
...@@ -149,11 +149,11 @@ export function copyProp(target, data, config?) { ...@@ -149,11 +149,11 @@ export function copyProp(target, data, config?) {
* @param obj * @param obj
*/ */
export function obj2query(obj: any): string { export function obj2query(obj: any): string {
if (!obj) { if(!obj) {
return ''; return '';
} }
let arr: string[] = []; let arr: string[] = [];
for (let key in obj) { for(let key in obj) {
arr.push(key + (key ? '=' : '') + obj[key]); arr.push(key + (key ? '=' : '') + obj[key]);
} }
return arr.join('&'); return arr.join('&');
...@@ -169,7 +169,7 @@ function requireForCJS(id) { ...@@ -169,7 +169,7 @@ function requireForCJS(id) {
* @param node * @param node
*/ */
export function importCJSCode(code, node?) { export function importCJSCode(code, node?) {
if (node) { if(node) {
let create = new Function('module', 'require', code); let create = new Function('module', 'require', code);
let module = { let module = {
exports: {}, exports: {},
...@@ -201,19 +201,19 @@ export function importUMDCode(code) { ...@@ -201,19 +201,19 @@ export function importUMDCode(code) {
* @param char * @param char
*/ */
export function trimChar(str: string, char: string) { export function trimChar(str: string, char: string) {
if (!str || !char) { if(!str || !char) {
return; return;
} }
while (true) { while(true) {
let len = str.length, from = 0, end = len; let len = str.length, from = 0, end = len;
if (str[0] === char) { if(str[0] === char) {
from = 1; from = 1;
} }
if (str[len - 1] === char) { if(str[len - 1] === char) {
end = len - 1; end = len - 1;
} }
str = str.substring(from, end); str = str.substring(from, end);
if (str.length == len) { if(str.length == len) {
break; break;
} }
} }
...@@ -227,7 +227,7 @@ export function trimChar(str: string, char: string) { ...@@ -227,7 +227,7 @@ export function trimChar(str: string, char: string) {
*/ */
export function joinPath(...segments: string[]) { export function joinPath(...segments: string[]) {
let result = []; let result = [];
for (let segment of segments) { for(let segment of segments) {
result.push(trimChar(segment, '/')); result.push(trimChar(segment, '/'));
} }
return result.join('/'); return result.join('/');
...@@ -240,10 +240,10 @@ export function joinPath(...segments: string[]) { ...@@ -240,10 +240,10 @@ export function joinPath(...segments: string[]) {
*/ */
export function findVariable(name: string, ...contexts) { export function findVariable(name: string, ...contexts) {
let result; let result;
for (let context of contexts) { for(let context of contexts) {
if (context) { if(context) {
result = context[name]; result = context[name];
if (result !== undefined) { if(result !== undefined) {
break; break;
} }
} }
...@@ -258,7 +258,7 @@ let el; ...@@ -258,7 +258,7 @@ let el;
* @param htmlText * @param htmlText
*/ */
export function htmlToPureText(htmlText) { export function htmlToPureText(htmlText) {
if (!el) { if(!el) {
el = document.createElement('div'); el = document.createElement('div');
} }
el.innerHTML = htmlText; el.innerHTML = htmlText;
...@@ -277,7 +277,7 @@ const zhReg = /[\u4e00-\u9fa5]/; ...@@ -277,7 +277,7 @@ const zhReg = /[\u4e00-\u9fa5]/;
*/ */
export function strLen(str) { export function strLen(str) {
let len = 0; let len = 0;
for (let char of str) { for(let char of str) {
len += char.match(zhReg) ? 2 : 1; len += char.match(zhReg) ? 2 : 1;
} }
return len; return len;
...@@ -291,12 +291,12 @@ export function strLen(str) { ...@@ -291,12 +291,12 @@ export function strLen(str) {
*/ */
export function strShort(str, limit, replace = '…') { export function strShort(str, limit, replace = '…') {
let result = ''; let result = '';
if (strLen(str) > limit) { if(strLen(str) > limit) {
let len = 0; let len = 0;
for (let i = 0, li = str.length; i < li; i++) { for(let i = 0, li = str.length; i < li; i++) {
const char = str[i]; const char = str[i];
len += char.match(zhReg) ? 2 : 1; len += char.match(zhReg) ? 2 : 1;
if (len > limit) { if(len > limit) {
result += replace; result += replace;
break; break;
} else { } else {
...@@ -328,8 +328,8 @@ export const cmdOldPrefix = '//z-'; ...@@ -328,8 +328,8 @@ export const cmdOldPrefix = '//z-';
* @param source * @param source
*/ */
export function injectProperties(target, source) { export function injectProperties(target, source) {
for (let key in source) { for(let key in source) {
if (key.indexOf('//') !== 0 && !source.hasOwnProperty(cmdPrefix + key)) { if(key.indexOf('//') !== 0 && !source.hasOwnProperty(cmdPrefix + key)) {
propertyParse(key, target, source); propertyParse(key, target, source);
} }
} }
...@@ -344,14 +344,25 @@ export function injectProperties(target, source) { ...@@ -344,14 +344,25 @@ export function injectProperties(target, source) {
* @param includeSelf * @param includeSelf
*/ */
export function traverseViewNode(node: Container, callback: Function, includeSelf = false) { export function traverseViewNode(node: Container, callback: Function, includeSelf = false) {
if (includeSelf) { if(includeSelf) {
callback(node); callback(node);
} }
for (let child of node.children) { for(let child of node.children) {
callback(child, node); callback(child, node);
if (child.children && child.children.length > 0) { if(child.children && child.children.length > 0) {
traverseViewNode(child, callback); traverseViewNode(child, callback);
} }
} }
} }
/**
* 数字转化为boolean值
* NaN -> false 'aaa' -> false null -> false undefined -> false
* 666 -> true '007' -> true Infinity -> true
* @param v
* @returns {boolean}
*/
export function toBoolean(v): boolean {
return !isNaN(v) && v !== null && v !== undefined;
}
...@@ -438,10 +438,10 @@ rollup-plugin-node-resolve@^5.2.0: ...@@ -438,10 +438,10 @@ rollup-plugin-node-resolve@^5.2.0:
resolve "^1.11.1" resolve "^1.11.1"
rollup-pluginutils "^2.8.1" rollup-pluginutils "^2.8.1"
rollup-plugin-progress@^1.1.1: rollup-plugin-progress@^1.1.2:
version "1.1.1" version "1.1.2"
resolved "https://registry.npm.taobao.org/rollup-plugin-progress/download/rollup-plugin-progress-1.1.1.tgz#fcce2f915d545014ac89ea0927ee97cb48052f60" resolved "https://registry.npm.taobao.org/rollup-plugin-progress/download/rollup-plugin-progress-1.1.2.tgz#5c1dfe7c50f654906bc34d167d5512ee1a4b72d5"
integrity sha1-/M4vkV1UUBSsieoJJ+6Xy0gFL2A= integrity sha1-XB3+fFD2VJBrw00WfVUS7hpLctU=
dependencies: dependencies:
chalk "^2.4.2" chalk "^2.4.2"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment