Commit 245cfb8d authored by rockyl's avatar rockyl

修改了好多东西啊

parent d45fe6f0
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -146,7 +146,20 @@ export const URL_FILE_EXTENSION: any; ...@@ -146,7 +146,20 @@ export const URL_FILE_EXTENSION: any;
export const DATA_URI: any; export const DATA_URI: any;
export enum SCROLL_DIRECTION {
HORIZONTAL = "horizontal",
VERTICAL = "vertical"
}
export class Container extends DisplayObject { export class Container extends DisplayObject {
percentWidth: number;
percentHeight: number;
left: number;
top: number;
right: number;
bottom: number;
horizonCenter: number;
verticalCenter: number;
mouseChildren: boolean; mouseChildren: boolean;
children: any[]; children: any[];
containerUpdateTransform: any; containerUpdateTransform: any;
...@@ -668,14 +681,14 @@ export abstract class HashObject { ...@@ -668,14 +681,14 @@ export abstract class HashObject {
export class Loader extends EventDispatcher { export class Loader extends EventDispatcher {
caches: {}; caches: {};
_req: XMLHttpRequest; crossOrigin: boolean;
constructor(); constructor();
loadSheet(callback: Function, url: string): void; loadSheet(url: string): Promise<void>;
loadRaw(callback: Function, url: string, type: 'text' | 'json'): void; loadRaw(url: string, uuid?: string, type?: 'text' | 'json'): Promise<any>;
loadJson(callback: Function, url: string): void; loadJson(url: string, uuid?: string): Promise<any>;
loadText(callback: Function, url: string): void; loadText(url: string, uuid?: string): Promise<any>;
loadTexture(callback: Function, url: string): void; loadImage(url: string, uuid?: string): Promise<{}>;
loadImage(callback: Function, url: string, crossOrigin?: boolean): HTMLImageElement; loadTexture(url: string, uuid?: string): Promise<Texture>;
cache(name: string, data: any): void; cache(name: string, data: any): void;
} }
...@@ -808,9 +821,9 @@ export class Transform extends HashObject { ...@@ -808,9 +821,9 @@ export class Transform extends HashObject {
destroy(): void; destroy(): void;
} }
export function httpRequest(callback: Function, url: string, method?: string, params?: any, type?: 'text' | 'json' | 'jsonp'): void; export function httpRequest(url: string, method?: string, params?: any, type?: 'text' | 'json' | 'jsonp'): Promise<{}>;
export function jsonp(callback: any, url: any, params: any): void; export function jsonp(url: any, params: any): Promise<{}>;
export function urlJoin(url: any, query: any): any; export function urlJoin(url: any, query: any): any;
...@@ -1470,7 +1483,7 @@ export class TextField extends Sprite { ...@@ -1470,7 +1483,7 @@ export class TextField extends Sprite {
private _lineType; private _lineType;
text: string; text: string;
protected _setText(value: any): void; protected _setText(value: any): void;
private _text; protected _text: string;
font: string; font: string;
private _font; private _font;
size: number; size: number;
...@@ -1584,14 +1597,14 @@ export class Texture extends EventDispatcher { ...@@ -1584,14 +1597,14 @@ export class Texture extends EventDispatcher {
} }
export class TextureSheet { export class TextureSheet {
baseTexture: BaseTexture; baseTexture: any;
textures: {}; textures: {};
animations: {}; animations: {};
data: any; data: any;
_frames: any; _frames: any;
_frameKeys: string[]; _frameKeys: string[];
_callback: Function; _callback: Function;
constructor(baseTexture: BaseTexture, data: any); constructor(baseTexture: BaseTexture | Texture, data: any);
parse(callback: Function): void; parse(callback: Function): void;
_processFrames(initialFrameIndex: number): void; _processFrames(initialFrameIndex: number): void;
_processAnimations(): void; _processAnimations(): void;
...@@ -1762,13 +1775,42 @@ export class FrameAni extends Sprite { ...@@ -1762,13 +1775,42 @@ export class FrameAni extends Sprite {
private changeTexture; private changeTexture;
} }
export class ScrollContainer extends Container {
private _direction;
protected distance: number;
private minDis;
private maskObj;
viewPort: Container;
private lastValue;
protected speed: number;
private addSpeed;
isStop: boolean;
maxSpeed: number;
fSpeed: number;
protected paramXY: string;
protected paramSize: string;
private stopTimes;
private isMouseDownState;
private autoScroll;
isSpringBack: boolean;
constructor(maxDistance?: number, isFull?: boolean);
readonly maxDistance: any;
direction: SCROLL_DIRECTION;
protected updateDirection(): void;
updateViewRect(): void;
cancelScroll(): void;
private onMouseEvent;
scrollTo(dis: number, time?: number): void;
destroy(): void;
}
export interface IScrollListItem extends DisplayObject { export interface IScrollListItem extends DisplayObject {
initData(id: number, data: any): void; initData(id: number, data: any): void;
id: number; id: number;
data: number; data: number;
} }
export class ScrollList extends ScrollPage { export class ScrollList extends ScrollContainer {
private _items; private _items;
private _itemW; private _itemW;
private _itemH; private _itemH;
...@@ -1783,42 +1825,15 @@ export class ScrollList extends ScrollPage { ...@@ -1783,42 +1825,15 @@ export class ScrollList extends ScrollPage {
private _disParam; private _disParam;
private _lastFirstId; private _lastFirstId;
readonly loadingView: DisplayObject; readonly loadingView: DisplayObject;
constructor(itemClassName: any, itemWidth: number, itemHeight: number, vW: number, vH: number, isVertical?: boolean, cols?: number); constructor(itemClassName: any, itemWidth: number, itemHeight: number, cols?: number);
updateData(data: Array<any>, isReset?: boolean): void; updateData(data: Array<any>, isReset?: boolean): void;
private flushData; private flushData;
setViewRect(w: number, h: number, isVertical: boolean): void; updateViewRect(): void;
private _updateViewRect; private _updateViewRect;
setLoading(downLoading: DisplayObject): void; setLoading(downLoading: DisplayObject): void;
destroy(): void; destroy(): void;
} }
export class ScrollPage extends Container {
protected isVertical: boolean;
private viewWidth;
private viewHeight;
maxDistance: number;
protected distance: number;
private minDis;
private maskObj;
view: Container;
private lastValue;
protected speed: number;
private addSpeed;
isStop: boolean;
maxSpeed: number;
fSpeed: number;
protected paramXY: string;
private stopTimes;
private isMouseDownState;
private autoScroll;
isSpringBack: boolean;
constructor(vW: number, vH: number, maxDistance: number, isVertical?: boolean, isFull?: boolean);
setViewRect(w: number, h: number, isVertical: boolean): void;
private onMouseEvent;
scrollTo(dis: number, time?: number): void;
destroy(): void;
}
export class ShowWord extends TextField { export class ShowWord extends TextField {
playWords(text: string, deltaTime?: number, callback?: Function): void; playWords(text: string, deltaTime?: number, callback?: Function): void;
} }
...@@ -2044,6 +2059,8 @@ export function setProcessMetaLibs(...metaContexts: any[]): void; ...@@ -2044,6 +2059,8 @@ export function setProcessMetaLibs(...metaContexts: any[]): void;
export function setGlobalContext(context: any): void; export function setGlobalContext(context: any): void;
export function setScriptMap(_scriptMap: any): void;
export function executeBehavior(sequence: any, subEntry: string, target: any, args?: any): void; export function executeBehavior(sequence: any, subEntry: string, target: any, args?: any): void;
export class Process { export class Process {
...@@ -2074,7 +2091,7 @@ export class Process { ...@@ -2074,7 +2091,7 @@ export class Process {
}>; }>;
getProcessMeta(id: any): any; getProcessMeta(id: any): any;
getProps(key?: any): any; getProps(key?: any): any;
updateProps(args: any): void; updateProps(props: any, args: any, originProps: any, propsConfig: any): void;
resolveLinkedProp(data: any, key: any): any; resolveLinkedProp(data: any, key: any): any;
} }
...@@ -2083,9 +2100,11 @@ export class VM { ...@@ -2083,9 +2100,11 @@ export class VM {
_globalContext: any; _globalContext: any;
_target: any; _target: any;
_id: any; _id: any;
_scriptMap: any;
setup(context: any): void; setup(context: any): void;
executeProcess(sequence: any, id: any, parentProcess: any, args: any): Promise<any>; executeProcess(sequence: any, id: any, parentProcess: any, args: any): Promise<any>;
getMeta(id: any): any; getMeta(id: any): any;
getScript(hash: any): any;
readonly globalContext: any; readonly globalContext: any;
readonly id: any; readonly id: any;
} }
...@@ -2114,8 +2133,9 @@ export function applyScript(ctor: Function): void; ...@@ -2114,8 +2133,9 @@ export function applyScript(ctor: Function): void;
export class ScriptBase { export class ScriptBase {
private _host; private _host;
disabled: boolean; private _disabled;
readonly host: Container; readonly host: Container;
disabled: boolean;
mounted(): void; mounted(): void;
destroy(): void; destroy(): void;
update(t: number): void; update(t: number): void;
...@@ -2133,6 +2153,14 @@ export function getAssetByUUID(uuid: any): any; ...@@ -2133,6 +2153,14 @@ export function getAssetByUUID(uuid: any): any;
export function getAssetByName(name: any): any; export function getAssetByName(name: any): any;
export function registerCustomModule(id: any, def: any): void;
export function registerCustomCodeModule(config: any): void;
export function registerCustomModuleFromConfig(config: any): void;
export function addCustomModule(id: any, container: Container, options?: any): any;
export class DataCenter extends EventDispatcher { export class DataCenter extends EventDispatcher {
store: {}; store: {};
watchers: any[]; watchers: any[];
...@@ -2140,10 +2168,11 @@ export class DataCenter extends EventDispatcher { ...@@ -2140,10 +2168,11 @@ export class DataCenter extends EventDispatcher {
registerGroup(name: any, origin?: any): void; registerGroup(name: any, origin?: any): void;
unregisterGroup(name: any): void; unregisterGroup(name: any): void;
getGroup(name: any): any; getGroup(name: any): any;
getDataByPath(path: any, throwException?: any): any; getDataByPath(path: any, groupName?: any, throwException?: any): any;
getDataByName(name: any, throwException?: any): any; getDataByName(name: any, throwException?: any): any;
formatString(str: any, escapes: any): any; formatString(str: any, escapes: any): any;
mutate(name: any, data?: any, path?: any, dispatch?: boolean): void; increase(groupName: any, step?: any, path?: any, dispatch?: boolean): void;
mutate(groupName: any, data?: any, path?: any, dispatch?: boolean): void;
watch(name: any, path: any): void; watch(name: any, path: any): void;
getWatcher(name: any): any; getWatcher(name: any): any;
registerDataMapping(dataMapping: any): void; registerDataMapping(dataMapping: any): void;
...@@ -2158,21 +2187,31 @@ export function injectEnv(data: any): void; ...@@ -2158,21 +2187,31 @@ export function injectEnv(data: any): void;
export class GameStage extends Container { export class GameStage extends Container {
private _sceneContainer; private _sceneContainer;
private _popupContainer; private _popupContainer;
private _toast;
private _blackLayer; private _blackLayer;
private _stage; private _stage;
private _dataCenter; private _dataCenter;
private _config; private _config;
private _viewCache;
constructor(stage: Stage); constructor(stage: Stage);
readonly sceneContainer: StackContainer; readonly sceneContainer: StackContainer;
readonly popupContainer: StackContainer; readonly popupContainer: StackContainer;
readonly toast: Toast;
readonly dataCenter: DataCenter; readonly dataCenter: DataCenter;
launch(config: any, onAssetsProgress: any, onAssetsComplete: any): void; launch(config: any, onAssetsProgress?: any, onAssetsComplete?: any): Promise<void>;
start(): void; start(): void;
instantiateView(name: any, cache?: boolean): any;
getViewConfigByName(name: any): any; getViewConfigByName(name: any): any;
setBlackLayerVisible(visible: any): void; setBlackLayerVisible(visible: any): void;
onPopupContainerChange(e: any): void; onPopupContainerChange(e: any): void;
} }
export function showLoadingView(): void;
export function hideLoadingView(): void;
export function setLoadingViewProgress(current: any, total: any): void;
export class Image extends Sprite { export class Image extends Sprite {
private _originText; private _originText;
private _escapes; private _escapes;
...@@ -2190,9 +2229,17 @@ export class Label extends TextField { ...@@ -2190,9 +2229,17 @@ export class Label extends TextField {
private _originText; private _originText;
private _escapes; private _escapes;
private _registeredEvents; private _registeredEvents;
private _htmlText;
protected _setText(value: any): void; protected _setText(value: any): void;
private dealEscape;
htmlText: any;
private unregisterEvents; private unregisterEvents;
private onDataMutated; private onTextMutated;
private onHtmlMutated;
}
export class ScrollView extends ScrollContainer {
constructor();
} }
export class ShapeBase extends Shape { export class ShapeBase extends Shape {
...@@ -2219,32 +2266,50 @@ export {}; ...@@ -2219,32 +2266,50 @@ export {};
export class StackContainer extends Container { export class StackContainer extends Container {
private _mutex; private _mutex;
private _stack;
constructor(mutex?: boolean); constructor(mutex?: boolean);
push(view: DisplayObject, options?: any, dispatch?: boolean): void; push(view: DisplayObject, options?: any, dispatch?: boolean): void;
replace(view: DisplayObject, options?: any): void; replace(view: DisplayObject, options?: any): void;
pop(): boolean; pop(dispatch?: boolean): boolean;
popAll(view?: DisplayObject, options?: any): void; popAll(view?: DisplayObject, options?: any): void;
} }
export function createTextureSheet(baseTexture: BaseTexture, altaData: any): void;
export class Toast extends Container {
private _contentSample;
private _content;
private _gameStage;
constructor(gameStage: GameStage);
show(props?: any): void;
hide(animation?: boolean, hideDuration?: number): void;
private removeContentView;
private getContent;
}
export function instantiate(config: any): any; export function instantiate(config: any): any;
export { instantiate }; export { instantiate };
export let gameStage: any; export let gameStage: GameStage;
export function launch(url: any, onAssetsProgress: any, onAssetsComplete: any): Promise<{}>; export function launch(url: any, onAssetsProgress: any, onAssetsComplete: any): Promise<{}>;
export function launchWithLocalStorage(id: any, onAssetsProgress: any, onAssetsComplete: any): Promise<{}>;
export function launchWithConfig(config: any, onAssetsProgress: any, onAssetsComplete: any): Promise<{}>; export function launchWithConfig(config: any, onAssetsProgress: any, onAssetsComplete: any): Promise<{}>;
export function findNodeByUUID(node: any, uuid: any): any; export function findNodeByUUID(node: any, uuid: any): any;
export function md5(string: any): string;
export const ESCAPE_REG_EXP: RegExp; export const ESCAPE_REG_EXP: RegExp;
export const linkedFlag = "$_linked_$"; export const linkedFlag = "$_linked_$";
export const nodeScheme = "node://"; export const nodeScheme = "node://";
export function arrayFind(arr: any, callback: any): any; export function arrayFind(arr: any, predicate: any): any;
export function objClone(obj: any): any; export function objClone(obj: any): any;
...@@ -2257,4 +2322,16 @@ export function injectProp(target: any, data?: any, callback?: Function, ignore ...@@ -2257,4 +2322,16 @@ export function injectProp(target: any, data?: any, callback?: Function, ignore
export function copyProp(target: any, data: any, config?: any): void; export function copyProp(target: any, data: any, config?: any): void;
export function obj2query(obj: any): string; export function obj2query(obj: any): string;
export function importCJSCode(code: any, node?: any): any;
export function importUMDCode(code: any): any;
export function trimChar(str: string, char: string): string;
export function joinPath(...segments: string[]): string;
export function findVariable(name: string, ...contexts: any[]): any;
export function htmlToPureText(htmlText: any): any;
} }
...@@ -5,15 +5,16 @@ ...@@ -5,15 +5,16 @@
"main": "index.js", "main": "index.js",
"types": "index.d.ts", "types": "index.d.ts",
"dependencies": { "dependencies": {
"glob": "^7.1.6", "color": "^3.1.2"
"rollup-plugin-typescript": "^1.0.1"
}, },
"devDependencies": { "devDependencies": {
"dts-bundle": "^0.7.3", "dts-bundle": "^0.7.3",
"glob": "^7.1.6",
"protobufjs": "^6.8.0", "protobufjs": "^6.8.0",
"rollup-plugin-commonjs": "^10.1.0", "rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0", "rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-progress": "^1.1.1", "rollup-plugin-progress": "^1.1.1",
"rollup-plugin-typescript": "^1.0.1",
"rollup-plugin-typescript2": "^0.25.2", "rollup-plugin-typescript2": "^0.25.2",
"rollup-plugin-uglify": "^6.0.3", "rollup-plugin-uglify": "^6.0.3",
"ts-loader": "^4.0.0", "ts-loader": "^4.0.0",
...@@ -25,10 +26,12 @@ ...@@ -25,10 +26,12 @@
}, },
"scripts": { "scripts": {
"build-webpack": "webpack", "build-webpack": "webpack",
"rollup": "rollup -c -o dist/engine.js --environment BUILD:production1", "rollup:prod": "rollup -c -o dist/engine.js --environment BUILD:production",
"rollup": "rollup -c -o dist/engine.js",
"rollup:debug": "rollup -c -m ", "rollup:debug": "rollup -c -m ",
"rename": "node scripts/rename-hash.js dist/engine.js", "rename": "node scripts/rename-hash.js dist/engine.js",
"build": "rm -rf dist&&yarn rollup && yarn rename && ali-oss-publish -c oss.config.js -e dist", "build": "rm -rf dist&&yarn rollup:prod && yarn rename && ali-oss-publish -c oss.config.js -e dist",
"build:debug": "rm -rf dist&&yarn rollup && yarn rename && ali-oss-publish -c oss.config.js -e dist",
"ts": "dts-bundle --name engine --main types/src/index.d.ts --out ../../dist/index.d.ts", "ts": "dts-bundle --name engine --main types/src/index.d.ts --out ../../dist/index.d.ts",
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack -w", "dev": "webpack -w",
......
...@@ -54,5 +54,5 @@ ${allExports} ...@@ -54,5 +54,5 @@ ${allExports}
} }
`; `;
fs.writeFileSync('dist/types.d.ts', content); fs.writeFileSync('debug/types.d.ts', content);
}); });
...@@ -153,9 +153,9 @@ export const DEG_TO_RAD: number = PI / 180; ...@@ -153,9 +153,9 @@ export const DEG_TO_RAD: number = PI / 180;
* @property {number} CANVAS - Canvas render type. * @property {number} CANVAS - Canvas render type.
*/ */
export enum RENDERER_TYPE { export enum RENDERER_TYPE {
UNKNOWN = 0, UNKNOWN = 'unknown',
WEBGL, WEBGL = 'webgl',
CANVAS, CANVAS = 'canvas',
}; };
/** /**
......
import { ObservablePoint, Point, Rectangle } from '../math'; import {ObservablePoint, Point, Rectangle} from '../math';
import { sign, TextureCache } from '../utils'; import {sign, TextureCache} from '../utils';
// import { BLEND_MODES } from '../const'; // import { BLEND_MODES } from '../const';
import Texture from '../texture/Texture'; import Texture from '../texture/Texture';
import {Event} from '../events/Event'; import {Event} from '../events/Event';
import Container from './Container'; import Container from './Container';
import { DisplayObject } from "./DisplayObject"; import {DisplayObject} from "./DisplayObject";
import CanvasRenderer from '../renderers/CanvasRenderer'; import CanvasRenderer from '../renderers/CanvasRenderer';
import { SCALE_MODES } from '../const'; import {SCALE_MODES} from '../const';
import { WebglRenderer } from '../renderers/WebglRenderer'; import {WebglRenderer} from '../renderers/WebglRenderer';
const indices = new Uint16Array([0, 1, 2, 0, 2, 3]); const indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
/** /**
...@@ -21,7 +21,7 @@ export default class Sprite extends Container { ...@@ -21,7 +21,7 @@ export default class Sprite extends Container {
* 关于贴图的锚点,0到1,默认为texture自己的 * 关于贴图的锚点,0到1,默认为texture自己的
* *
*/ */
private _anchorTexture: ObservablePoint private _anchorTexture: ObservablePoint;
/** /**
* 使用的贴图 * 使用的贴图
* @member {Texture} * @member {Texture}
...@@ -124,13 +124,13 @@ export default class Sprite extends Container { ...@@ -124,13 +124,13 @@ export default class Sprite extends Container {
//可用才赋值uv //可用才赋值uv
if (this._texture.valid) this.uvs = this._texture._uvs.uvsFloat32; if (this._texture.valid) this.uvs = this._texture._uvs.uvsFloat32;
//设置过宽高的话,就需要改变缩放值,废弃先 //设置过宽高的话,就需要改变缩放值,废弃先
// if (this._width) { if (this._width) {
// this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width; this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
// } }
// if (this._height) { if (this._height) {
// this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height; this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
// } }
//修改_localBoundsSelf //修改_localBoundsSelf
const width = this._texture.orig.width; const width = this._texture.orig.width;
...@@ -435,7 +435,6 @@ export default class Sprite extends Container { ...@@ -435,7 +435,6 @@ export default class Sprite extends Container {
} }
//一些静态类方法 //一些静态类方法
/** /**
* 方便创建sprite * 方便创建sprite
......
...@@ -724,7 +724,7 @@ export class Stage extends Container { ...@@ -724,7 +724,7 @@ export class Stage extends Container {
for (let j = 0; j < eLen; j++) { for (let j = 0; j < eLen; j++) {
if (!events[j]["_bpd"]) { if (!events[j]["_bpd"]) {
//有事件,且mouseEnabled为true //有事件,且mouseEnabled为true
if (d.hasEventListener(events[j].type) && d.mouseEnabled) { if (d.hasEventListener(events[j].type, false) && d.mouseEnabled) {
events[j].target = d; events[j].target = d;
events[j].currentTarget = displayList[eLen - 1]; events[j].currentTarget = displayList[eLen - 1];
lp = d.globalToLocal(cp, DisplayObject._bp); lp = d.globalToLocal(cp, DisplayObject._bp);
......
...@@ -220,7 +220,7 @@ export default class Graphics extends Container { ...@@ -220,7 +220,7 @@ export default class Graphics extends Container {
* 克隆该Graphics的几何绘制,不包括它自身的transform * 克隆该Graphics的几何绘制,不包括它自身的transform
* @return {Graphics} A clone of the graphics object * @return {Graphics} A clone of the graphics object
*/ */
clone(): Graphics { cloneSelf(): Graphics {
const clone = new Graphics(); const clone = new Graphics();
clone.renderable = this.renderable; clone.renderable = this.renderable;
......
...@@ -4,6 +4,8 @@ import {EventDispatcher} from "../events/EventDispatcher"; ...@@ -4,6 +4,8 @@ import {EventDispatcher} from "../events/EventDispatcher";
import {TextureCache} from "../utils"; import {TextureCache} from "../utils";
import {Texture} from "../texture"; import {Texture} from "../texture";
import {httpRequest} from "../net"; import {httpRequest} from "../net";
import TextureSheet from "../texture/TextureSheet";
import {createTextureSheet} from "../../zeroing/game-warpper/texture-sheet";
export class Loader extends EventDispatcher { export class Loader extends EventDispatcher {
...@@ -11,12 +13,10 @@ export class Loader extends EventDispatcher { ...@@ -11,12 +13,10 @@ export class Loader extends EventDispatcher {
* 记录原始数据,json和image,贴图在建立时会被缓存 * 记录原始数据,json和image,贴图在建立时会被缓存
*/ */
caches = {}; caches = {};
crossOrigin: boolean = true;
//parser: Parser; //parser: Parser;
_req: XMLHttpRequest = null;
/** /**
* *
*/ */
...@@ -27,75 +27,73 @@ export class Loader extends EventDispatcher { ...@@ -27,75 +27,73 @@ export class Loader extends EventDispatcher {
/** /**
* *
* @param callback * @param url
* @param url 图集一般是png格式,传的是json,在callback自行拆分
*/ */
loadSheet(callback: Function, url: string) { loadSheet(url: string) {
let pngFile = url.substring(0, url.lastIndexOf('.')) + '.png'; let config;
this.loadImage((suc, data) => { return this.loadJson(url)
if (suc) { .then(json => {
if (this.caches[url]) { const {file} = config = json;
callback(true, {json: this.caches[url], img: data}) return this.loadTexture(file)
} })
} else { .then(texture => {
callback(false, data) createTextureSheet(texture.baseTexture, config.frames);
} })
}, pngFile);
this.loadJson((suc, data) => {
if (suc) {
if (this.caches[pngFile]) {
callback(true, {json: data, img: this.caches[pngFile]})
}
} else {
callback(false, data)
}
}, url)
} }
loadRaw(callback: Function, url: string, type: 'text' | 'json') { loadRaw(url: string, uuid?: string, type?: 'text' | 'json') {
httpRequest((s, p) => { let data = this.caches[uuid || url];
if (s) { if (data) {
this.cache(url, p); return Promise.resolve(data);
} } else {
callback(s, p); return httpRequest(url, 'get', {}, type)
}, url, 'get', {}, type); .then(data => {
this.cache(uuid || url, data);
return data;
});
}
} }
loadJson(callback: Function, url: string) { loadJson(url: string, uuid?: string) {
this.loadRaw(callback, url, 'json'); return this.loadRaw(url, uuid, 'json');
} }
loadText(callback: Function, url: string) { loadText(url: string, uuid?: string) {
this.loadRaw(callback, url, 'text'); return this.loadRaw(url, uuid, 'text');
} }
loadTexture(callback: Function, url: string) { loadImage(url: string, uuid?: string) {
this.loadImage((s, payload) => { return new Promise((resolve, reject) => {
if (s) { let img = this.caches[uuid || url];
this.cache(url, payload); if (img) {
callback(s, TextureCache[url] = Texture.from(payload)); resolve(img);
} else { } else {
callback(s, payload); img = new Image();
if (this.crossOrigin) {
img.setAttribute('crossOrigin', 'anonymous');
}
img.onload = () => {
this.cache(uuid || url, img);
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
img.src = url;
} }
}, url) })
} }
loadImage(callback: Function, url: string, crossOrigin: boolean = true) { /**
let self = this * 加载纹理
let img = new Image(); * @param url
if (crossOrigin) { * @param uuid
img.setAttribute('crossOrigin', 'anonymous'); */
} loadTexture(url: string, uuid?: string) {
img.onload = function (e) { return this.loadImage(url)
self.cache(url, img); .then(image => {
callback(true, img); return TextureCache[uuid || url] = Texture.from(image);
}; })
img.onerror = function (e) {
callback(false, e);
};
img.src = url;
return img
} }
/*loadSvga(callback: (suc: boolean, data: VideoEntity) => void, url: string) { /*loadSvga(callback: (suc: boolean, data: VideoEntity) => void, url: string) {
...@@ -113,10 +111,8 @@ export class Loader extends EventDispatcher { ...@@ -113,10 +111,8 @@ export class Loader extends EventDispatcher {
if (this.caches[name]) { if (this.caches[name]) {
//console.log("覆盖原先数据:" + name); //console.log("覆盖原先数据:" + name);
} }
this.caches[name] = data this.caches[name] = data;
} }
} }
async function fetchAsync(url: string) { async function fetchAsync(url: string) {
......
...@@ -6,69 +6,77 @@ import {obj2query} from "../zeroing/utils"; ...@@ -6,69 +6,77 @@ import {obj2query} from "../zeroing/utils";
/** /**
* http请求 * http请求
* @param callback
* @param url * @param url
* @param method * @param method
* @param params * @param params
* @param type * @param type
*/ */
export function httpRequest(callback: Function, url: string, method: string = 'get', params?: any, type: 'text' | 'json' | 'jsonp' = 'text') { export function httpRequest(url: string, method: string = 'get', params?: any, type: 'text' | 'json' | 'jsonp' = 'text') {
if (type === "jsonp") { if (type === "jsonp") {
jsonp(callback, url, params); return jsonp(url, params);
} else { } else {
let _req; return new Promise((resolve, reject) => {
if (window["XMLHttpRequest"]) { let _req;
_req = new XMLHttpRequest(); if (window["XMLHttpRequest"]) {
} else if (window["ActiveXObject"]) { _req = new XMLHttpRequest();
_req = new window["ActiveXObject"](); } else if (window["ActiveXObject"]) {
} else { _req = new window["ActiveXObject"]();
console.log('no xhr');
}
if (_req != null) {
const isGet = method.toUpperCase() === 'GET';
const queryStr = obj2query(params);
if (isGet) {
url = urlJoin(url, queryStr);
}
_req.open(method, url, true);
if(!isGet){
_req.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
}
_req.responseType = type;
if (isGet) {
_req.send();
} else { } else {
_req.send(queryStr); console.log('no xhr');
} }
_req.onreadystatechange = () => { if (_req != null) {
if (_req.readyState == 4 && _req.status == 200) { const isGet = method.toUpperCase() === 'GET';
callback && callback(true, _req.response) const queryStr = obj2query(params);
if (isGet) {
url = urlJoin(url, queryStr);
}
_req.open(method, url, true);
if (!isGet) {
_req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
}
_req.responseType = type;
if (isGet) {
_req.send();
} else {
_req.send(queryStr);
}
_req.onreadystatechange = () => {
if (_req.readyState == 4 && _req.status == 200) {
resolve(_req.response)
}
};
_req.onerror = (reason): void => {
reject(reason)
} }
};
_req.onerror = (reason): void => {
callback && callback(false, reason)
} }
} });
} }
} }
export function jsonp(callback, url, params) { /**
const src = urlJoin(url, obj2query(params)); * jsonp请求
const scriptEl = document.createElement('script'); * @param url
scriptEl.src = src; * @param params
scriptEl.onload = function () { */
callback && callback(true); export function jsonp(url, params) {
document.body.removeChild(scriptEl); return new Promise((resolve, reject) => {
}; const src = urlJoin(url, obj2query(params));
scriptEl.onerror = function () { const scriptEl = document.createElement('script');
callback && callback(false); scriptEl.src = src;
document.body.removeChild(scriptEl); scriptEl.onload = function () {
}; resolve();
/*const callbackFuncName = '__zeroing_jsonp_callback__' + Math.random(); document.body.removeChild(scriptEl);
window[callbackFuncName] = function () { };
callback(result); scriptEl.onerror = function () {
};*/ reject();
document.body.appendChild(scriptEl); document.body.removeChild(scriptEl);
};
/*const callbackFuncName = '__zeroing_jsonp_callback__' + Math.random();
window[callbackFuncName] = function () {
callback(result);
};*/
document.body.appendChild(scriptEl);
})
} }
export function urlJoin(url, query) { export function urlJoin(url, query) {
......
...@@ -113,7 +113,7 @@ export class EditableText extends TextField { ...@@ -113,7 +113,7 @@ export class EditableText extends TextField {
} }
//font包括字体和大小 //font包括字体和大小
s.htmlElement.style.font = s.size + "px " + this.font; s.htmlElement.style.font = s.size + "px " + this.font;
s.htmlElement.style.color = s.textColor; s.htmlElement.style.colorD = s.textColor;
s.htmlElement.style.textAlign = s["_textWidth"] ? s.textAlign : TEXT_ALIGN.LEFT; s.htmlElement.style.textAlign = s["_textWidth"] ? s.textAlign : TEXT_ALIGN.LEFT;
// s.htmlElement.setAttribute("class", "inputTextFor"); // s.htmlElement.setAttribute("class", "inputTextFor");
// .inputTextFor:: -webkit - input - placeholder { // .inputTextFor:: -webkit - input - placeholder {
......
...@@ -127,7 +127,7 @@ export class InputText extends FloatDisplay { ...@@ -127,7 +127,7 @@ export class InputText extends FloatDisplay {
s.htmlElement.placeholder = text; s.htmlElement.placeholder = text;
//font包括字体和大小 //font包括字体和大小
s.htmlElement.style.font = size + "px " + font; s.htmlElement.style.font = size + "px " + font;
s.htmlElement.style.color = color; s.htmlElement.style.colorD = color;
s.htmlElement.style.textAlign = align; s.htmlElement.style.textAlign = align;
/////////////////////设置边框////////////// /////////////////////设置边框//////////////
s.border = showBorder; s.border = showBorder;
...@@ -233,11 +233,11 @@ export class InputText extends FloatDisplay { ...@@ -233,11 +233,11 @@ export class InputText extends FloatDisplay {
*/ */
public set color(value: string) { public set color(value: string) {
var ss = this.htmlElement.style; var ss = this.htmlElement.style;
ss.color = value; ss.colorD = value;
} }
public get color(): string { public get color(): string {
return this.htmlElement.style.color; return this.htmlElement.style.colorD;
} }
/** /**
......
...@@ -12,7 +12,7 @@ export default class TextureSheet { ...@@ -12,7 +12,7 @@ export default class TextureSheet {
/** /**
* Reference to ths source texture * Reference to ths source texture
*/ */
baseTexture: BaseTexture; baseTexture;
/** /**
* A map containing all textures of the sprite sheet. * A map containing all textures of the sprite sheet.
* Can be used to create a {@link Sprite|Sprite}: * Can be used to create a {@link Sprite|Sprite}:
...@@ -56,7 +56,7 @@ export default class TextureSheet { ...@@ -56,7 +56,7 @@ export default class TextureSheet {
* @param {BaseTexture} baseTexture Reference to the source BaseTexture object. * @param {BaseTexture} baseTexture Reference to the source BaseTexture object.
* @param {Object} data - TextureSheet image data. * @param {Object} data - TextureSheet image data.
*/ */
constructor(baseTexture: BaseTexture, data: any) { constructor(baseTexture: BaseTexture | Texture, data: any) {
this.baseTexture = baseTexture; this.baseTexture = baseTexture;
this.textures = {}; this.textures = {};
this.animations = {}; this.animations = {};
......
...@@ -6,20 +6,6 @@ import {SCROLL_DIRECTION} from "../const"; ...@@ -6,20 +6,6 @@ import {SCROLL_DIRECTION} from "../const";
// import Tween from "../../tweenSimple/Tween"; // import Tween from "../../tweenSimple/Tween";
let queue: ScrollContainer[] = [];
function registerScrollInstance(scrollContainer?) {
while (queue.length > 0) {
let item = queue.shift();
if(scrollContainer){
item.cancelScroll();
}
}
if(scrollContainer){
queue.push(scrollContainer);
}
}
/** /**
* 滚动视图 * 滚动视图
* @class ScrollPage * @class ScrollPage
...@@ -200,7 +186,7 @@ export class ScrollContainer extends Container { ...@@ -200,7 +186,7 @@ export class ScrollContainer extends Container {
s.stage.removeEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s); s.stage.removeEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s);
s.stage.removeEventListener(MouseEvent.MOUSE_MOVE, s.onMouseEvent, s); s.stage.removeEventListener(MouseEvent.MOUSE_MOVE, s.onMouseEvent, s);
}); });
s.addEventListener(MouseEvent.MOUSE_DOWN, s.onMouseEvent, s); s.addEventListener(MouseEvent.MOUSE_DOWN, s.onMouseEvent, s, false);
// s.addEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s); // s.addEventListener(MouseEvent.MOUSE_UP, s.onMouseEvent, s);
// s.addEventListener(MouseEvent.MOUSE_OUT, s.onMouseEvent, s); // s.addEventListener(MouseEvent.MOUSE_OUT, s.onMouseEvent, s);
s.addEventListener(Event.ENTER_FRAME, function () { s.addEventListener(Event.ENTER_FRAME, function () {
...@@ -327,6 +313,7 @@ export class ScrollContainer extends Container { ...@@ -327,6 +313,7 @@ export class ScrollContainer extends Container {
let view: any = s.viewPort; let view: any = s.viewPort;
// if (s.distance < s.maxDistance) { // if (s.distance < s.maxDistance) {
if (e.type == MouseEvent.MOUSE_DOWN) { if (e.type == MouseEvent.MOUSE_DOWN) {
e.stopPropagation();
if (!s.isStop) { if (!s.isStop) {
s.isStop = true; s.isStop = true;
} }
...@@ -341,8 +328,6 @@ export class ScrollContainer extends Container { ...@@ -341,8 +328,6 @@ export class ScrollContainer extends Container {
} }
s.speed = 0; s.speed = 0;
s.isMouseDownState = 1; s.isMouseDownState = 1;
registerScrollInstance(this);
} else if (e.type == MouseEvent.MOUSE_MOVE) { } else if (e.type == MouseEvent.MOUSE_MOVE) {
if (s.isMouseDownState == 0) return; if (s.isMouseDownState == 0) return;
if (s.isMouseDownState == 1) { if (s.isMouseDownState == 1) {
...@@ -385,8 +370,6 @@ export class ScrollContainer extends Container { ...@@ -385,8 +370,6 @@ export class ScrollContainer extends Container {
s.dispatchEvent(Event.ON_SCROLL_STOP); s.dispatchEvent(Event.ON_SCROLL_STOP);
} }
s.isMouseDownState = 0; s.isMouseDownState = 0;
registerScrollInstance();
} }
// } // }
} }
......
...@@ -55,14 +55,11 @@ export class ScrollList extends ScrollContainer { ...@@ -55,14 +55,11 @@ export class ScrollList extends ScrollContainer {
* @param {Class} itemClassName 可以做为Item的类 * @param {Class} itemClassName 可以做为Item的类
* @param {number} itemWidth item宽 * @param {number} itemWidth item宽
* @param {number} itemHeight item高 * @param {number} itemHeight item高
* @param {number} vW 列表的宽
* @param {number} vH 列表的高
* @param {boolean} isVertical 是横向滚动还是纵向滚动 默认是纵向
* @param {number} cols 分几列,默认是1列 * @param {number} cols 分几列,默认是1列
* @since 1.0.9 * @since 1.0.9
*/ */
constructor(itemClassName: any, itemWidth: number, itemHeight: number, vW: number, vH: number, isVertical: boolean = true, cols: number = 1) { constructor(itemClassName: any, itemWidth: number, itemHeight: number, cols: number = 1) {
super(vW, vH, 0, isVertical); super();
let s = this; let s = this;
s._instanceType = "ScrollList"; s._instanceType = "ScrollList";
s._itemW = itemWidth; s._itemW = itemWidth;
...@@ -145,14 +142,11 @@ export class ScrollList extends ScrollContainer { ...@@ -145,14 +142,11 @@ export class ScrollList extends ScrollContainer {
/** /**
* 设置可见区域,可见区域的坐标始终在本地坐标中0,0点位置 * 设置可见区域,可见区域的坐标始终在本地坐标中0,0点位置
* @method setViewRect * @method setViewRect
* @param {number}w 设置可见区域的宽
* @param {number}h 设置可见区域的高
* @param {boolean} isVertical 方向
* @public * @public
* @since 1.1.1 * @since 1.1.1
*/ */
public updateViewRect(w: number, h: number, isVertical: boolean): void { public updateViewRect(): void {
super.updateViewRect(w, h, isVertical); super.updateViewRect();
let s = this; let s = this;
if (s._itemRow && s._itemCol) { if (s._itemRow && s._itemCol) {
s._updateViewRect(); s._updateViewRect();
......
...@@ -35,10 +35,7 @@ export * from './2d/const' ...@@ -35,10 +35,7 @@ export * from './2d/const'
export * from './zeroing' export * from './zeroing'
export {default as Color} from 'color'
// function aa(){ // function aa(){
// HashObject // HashObject
......
...@@ -8,11 +8,13 @@ import {getDataByPath, linkedFlag, nodeScheme, objClone} from "../utils"; ...@@ -8,11 +8,13 @@ import {getDataByPath, linkedFlag, nodeScheme, objClone} from "../utils";
import {findNodeByUUID} from "../node-utils"; import {findNodeByUUID} from "../node-utils";
import {dataCenter} from "../game-warpper/data-center"; import {dataCenter} from "../game-warpper/data-center";
import {env} from "../game-warpper/enviroment"; import {env} from "../game-warpper/enviroment";
import {getLogSwitch, Logs} from "../log-switch";
const log = true; const log = getLogSwitch(Logs.PROCESS);
const linkScheme = 'link://'; const linkScheme = 'link://';
export class Process { export class Process {
private readonly id;
private _config; private _config;
private _parent: Process; private _parent: Process;
private _vm: VM; private _vm: VM;
...@@ -21,8 +23,8 @@ export class Process { ...@@ -21,8 +23,8 @@ export class Process {
private _target; private _target;
private _originProps; private _originProps;
constructor() { constructor(id) {
this.id = id;
} }
get processConfig() { get processConfig() {
...@@ -45,8 +47,8 @@ export class Process { ...@@ -45,8 +47,8 @@ export class Process {
this._sequence = sequence; this._sequence = sequence;
this._target = target; this._target = target;
if (!this._originProps && this._config.props) { if (!this._config._originProps && this._config.props) {
this._originProps = objClone(this._config.props) this._config._originProps = objClone(this._config.props)
} }
} }
...@@ -98,7 +100,7 @@ export class Process { ...@@ -98,7 +100,7 @@ export class Process {
if (this._meta) { if (this._meta) {
let metaConfig = this._meta; let metaConfig = this._meta;
if (metaConfig) { if (metaConfig) {
this.updateProps(this._config.props = {}, payload, this._originProps, this._meta.props); this.updateProps(this._config.props = {}, payload, this._config._originProps, this._meta.props);
if (metaConfig.script) { if (metaConfig.script) {
let func; let func;
if (metaConfig.script.indexOf(linkScheme) === 0) { if (metaConfig.script.indexOf(linkScheme) === 0) {
...@@ -106,12 +108,18 @@ export class Process { ...@@ -106,12 +108,18 @@ export class Process {
} else { } else {
func = new Function('args', 'props', 'target', 'global', 'vm', warpAsyncScript(metaConfig.script)); func = new Function('args', 'props', 'target', 'global', 'vm', warpAsyncScript(metaConfig.script));
} }
if (!func) { if (func) {
console.log(); let globalContext = this._vm.globalContext;
globalContext.dataCenter = globalContext.gameStage.dataCenter;
result = await func(payload, this._config.props, this._target, globalContext, this._vm);
if (log){
console.log(`[${this._vm.id}:${this.id}] output: <${result.type}>`, result.payload ? JSON.stringify(result.payload) : '');
}
} else {
if (log){
console.log('script lose');
}
} }
let globalContext = this._vm.globalContext;
globalContext.dataCenter = globalContext.gameStage.dataCenter;
result = await func(payload, this._config.props, this._target, globalContext, this._vm);
} }
} else { } else {
console.warn(`process meta [${meta}] not found`) console.warn(`process meta [${meta}] not found`)
......
...@@ -14,6 +14,8 @@ export class VM { ...@@ -14,6 +14,8 @@ export class VM {
_id; _id;
_scriptMap; _scriptMap;
_pid = 0;
setup(context) { setup(context) {
const {processMetaLibs, globalContext, target, scriptMap} = context; const {processMetaLibs, globalContext, target, scriptMap} = context;
...@@ -25,7 +27,7 @@ export class VM { ...@@ -25,7 +27,7 @@ export class VM {
} }
async executeProcess(sequence, id, parentProcess, args) { async executeProcess(sequence, id, parentProcess, args) {
const process = new Process(); const process = new Process(this._pid++);
process.init({ process.init({
sequence, sequence,
id, id,
...@@ -46,7 +48,7 @@ export class VM { ...@@ -46,7 +48,7 @@ export class VM {
} }
} }
getScript(hash){ getScript(hash) {
return this._scriptMap[hash]; return this._scriptMap[hash];
} }
......
...@@ -3,6 +3,9 @@ ...@@ -3,6 +3,9 @@
*/ */
import {VM} from "./VM"; import {VM} from "./VM";
import {getLogSwitch, Logs} from "../log-switch";
const log = getLogSwitch(Logs.PROCESS);
let processMetaLibs = []; let processMetaLibs = [];
let globalContext = {}; let globalContext = {};
...@@ -14,7 +17,9 @@ let scriptMap = {}; ...@@ -14,7 +17,9 @@ let scriptMap = {};
*/ */
export function setProcessMetaLibs(...metaContexts) { export function setProcessMetaLibs(...metaContexts) {
for (let context of metaContexts) { for (let context of metaContexts) {
processMetaLibs.push(context); if(context){
processMetaLibs.push(context);
}
} }
} }
......
/** /**
* Created by rockyl on 2019-11-08. * Created by rockyl on 2019-11-08.
*/ */
import {propertyParse} from "../utils"; import {injectProperties, instantiateScript, propertyParse} from "../utils";
const cloneFields = [ const cloneFields = [
/*node*/ 'x', 'y', 'width', 'height', 'rotation', 'alpha', 'scaleX', 'scaleY', 'visible', /*node*/ 'x', 'y', 'width', 'height', 'rotation', 'alpha', 'scaleX', 'scaleY', 'visible',
...@@ -22,17 +22,29 @@ export function afterConstructor(ctor: Function) { ...@@ -22,17 +22,29 @@ export function afterConstructor(ctor: Function) {
this.applyEvents(); this.applyEvents();
}; };
ctor.prototype.clone = function () { ctor.prototype.clone = function (withEvents = false, withScripts: false) {
let target = this.constructor.apply(Object.create(this.constructor.prototype)); let target = this.constructor.apply(Object.create(this.constructor.prototype));
let originConfig = this.__originConfig; const {name, properties, events, scripts} = this.__originConfig;
target.name = originConfig.name; target.name = name;
for (let field in originConfig.properties) { injectProperties(target, properties);
propertyParse(field, target, originConfig.properties);
if(withScripts){
if (scripts && scripts.length > 0) {
for (let scriptConfig of scripts) {
instantiateScript(target, scriptConfig);
}
}
}
if(withEvents){
if (events) {
target.eventsProxy.eventsConfig = events;
}
target.eventsProxy.start();
} }
for(let child of this.children){ for(let child of this.children){
let childCopy = child.clone(); let childCopy = child.clone(withEvents, withScripts);
target.addChild(childCopy); target.addChild(childCopy);
} }
......
...@@ -98,8 +98,8 @@ export function registerScriptDef(id, def) { ...@@ -98,8 +98,8 @@ export function registerScriptDef(id, def) {
} }
export function registerScripts(scripts) { export function registerScripts(scripts) {
for (let id in scripts) { for (let script of scripts) {
let code = scripts[id]; let {id, code} = script;
let def = importCJSCode(code); let def = importCJSCode(code);
registerScriptDef(id, def); registerScriptDef(id, def);
} }
......
...@@ -15,6 +15,7 @@ import {injectEnv} from "./enviroment"; ...@@ -15,6 +15,7 @@ import {injectEnv} from "./enviroment";
import {registerCustomModuleFromConfig} from "./custom-module"; import {registerCustomModuleFromConfig} from "./custom-module";
import {hideLoadingView, showLoadingView} from "./loading-view"; import {hideLoadingView, showLoadingView} from "./loading-view";
import {Toast} from "./Toast"; import {Toast} from "./Toast";
import {arrayFind} from "../utils";
/** /**
* 游戏舞台 * 游戏舞台
...@@ -104,18 +105,22 @@ export class GameStage extends Container { ...@@ -104,18 +105,22 @@ export class GameStage extends Container {
let total = assets.length; let total = assets.length;
if (customs) { if (customs) {
for (let custom of customs) { for (let custom of customs) {
if(custom.assets){ if (custom.assets) {
total += custom.assets.length; total += custom.assets.length;
} }
} }
} }
showLoadingView(); showLoadingView();
await loadAssets(assets, p); await loadAssets(assets, p).catch(e => {
console.log(e);
});
if (customs) { if (customs) {
for (let custom of customs) { for (let custom of customs) {
if(custom.assets){ if (custom.assets) {
await loadAssets(custom.assets, p); await loadAssets(custom.assets, p).catch(e => {
console.log(e);
});
} }
} }
} }
...@@ -183,7 +188,7 @@ export class GameStage extends Container { ...@@ -183,7 +188,7 @@ export class GameStage extends Container {
* @param name * @param name
*/ */
getViewConfigByName(name) { getViewConfigByName(name) {
return this._config.views.find(view => view.name === name); return arrayFind(this._config.views, view => view.name === name);
} }
/** /**
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
*/ */
import {globalLoader} from "../../2d/loader/Loader"; import {globalLoader} from "../../2d/loader/Loader";
import {arrayFind} from "../utils";
let assetsConfig = []; let assetsConfig = [];
...@@ -16,6 +17,7 @@ const loaderMapping = { ...@@ -16,6 +17,7 @@ const loaderMapping = {
'.json': 'Json', '.json': 'Json',
'.svga': 'Svga', '.svga': 'Svga',
'.sht': 'Sheet', '.sht': 'Sheet',
'': 'Raw',
}; };
/** /**
...@@ -29,18 +31,17 @@ export function loadAssets(config, onProgress?, onComplete?) { ...@@ -29,18 +31,17 @@ export function loadAssets(config, onProgress?, onComplete?) {
return Promise.all( return Promise.all(
config.map(assetConfig => { config.map(assetConfig => {
assetsConfig.push(assetConfig); assetsConfig.push(assetConfig);
return new Promise((resolve) => { const loadFunc = loaderMapping[assetConfig.ext] || 'Raw';
const loadFunc = loaderMapping[assetConfig.ext] || 'Raw'; let method = globalLoader['load' + loadFunc] || globalLoader.loadRaw;
globalLoader['load' + loadFunc](function (result, payload) { return method.call(globalLoader, assetConfig.url, assetConfig.uuid).then(
if (result) { (data)=>{
loaded++; loaded++;
onProgress && onProgress(loaded, total); onProgress && onProgress(loaded, total);
} else { },
failedList.push(assetConfig.url); (error)=>{
} failedList.push(assetConfig.url);
resolve(); }
}, assetConfig.url); );
})
}) })
).then( ).then(
() => { () => {
...@@ -58,7 +59,7 @@ export function loadAssets(config, onProgress?, onComplete?) { ...@@ -58,7 +59,7 @@ export function loadAssets(config, onProgress?, onComplete?) {
* @param uuid * @param uuid
*/ */
export function getAssetByUUID(uuid) { export function getAssetByUUID(uuid) {
return assetsConfig.find(item => item.uuid === uuid); return arrayFind(assetsConfig,item => item.uuid === uuid);
} }
/** /**
...@@ -66,5 +67,5 @@ export function getAssetByUUID(uuid) { ...@@ -66,5 +67,5 @@ export function getAssetByUUID(uuid) {
* @param name * @param name
*/ */
export function getAssetByName(name) { export function getAssetByName(name) {
return assetsConfig.find(item => item.name === name); return arrayFind(assetsConfig,item => item.name === name);
} }
...@@ -24,7 +24,7 @@ export class DataCenter extends EventDispatcher { ...@@ -24,7 +24,7 @@ export class DataCenter extends EventDispatcher {
* @param origin * @param origin
*/ */
registerGroup(name, origin?) { registerGroup(name, origin?) {
this.store[name] = origin || {}; return this.store[name] = origin || {};
} }
/** /**
...@@ -125,7 +125,7 @@ export class DataCenter extends EventDispatcher { ...@@ -125,7 +125,7 @@ export class DataCenter extends EventDispatcher {
let group = this.getGroup(groupName); let group = this.getGroup(groupName);
if (!group) { if (!group) {
this.registerGroup(groupName); group = this.registerGroup(groupName);
} }
if (data !== undefined) { if (data !== undefined) {
if (path) { if (path) {
......
...@@ -32,11 +32,12 @@ export class Image extends Sprite { ...@@ -32,11 +32,12 @@ export class Image extends Sprite {
if(url.indexOf('://') >= 0){ //如果是有协议的地址 if(url.indexOf('://') >= 0){ //如果是有协议的地址
if (url.indexOf(assetScheme) === 0) { if (url.indexOf(assetScheme) === 0) {
let uuid = url.replace(assetScheme, ''); let uuid = url.replace(assetScheme, '');
const assetConfig = getAssetByUUID(uuid); /*const assetConfig = getAssetByUUID(uuid);
if(assetConfig){ if(assetConfig){
url = assetConfig.url; url = assetConfig.url;
this.texture = Texture.fromImage(url); this.texture = Texture.fromImage(url);
} }*/
this.texture = Texture.from(uuid);
} }
} else{ //否则就使用素材名 } else{ //否则就使用素材名
const assetConfig = getAssetByName(url); const assetConfig = getAssetByName(url);
......
/** /**
* Created by rockyl on 2019-11-06. * Created by rockyl on 2019-11-06.
*/ */
import Color from "color";
import {Shape} from "../../../"; import {Shape} from "../../../";
import {Event} from "../../../2d/events"; import {Event} from "../../../2d/events";
import {dirtyFieldDetector} from "../../decorators"; import {dirtyFieldDetector} from "../../decorators";
import Graphics from "../../../2d/graphics/Graphics";
/** /**
* 图形基类 * 图形基类
*/ */
class ShapeBase extends Shape { class ShapeBase extends Graphics {
protected __fieldDirty = true; protected __fieldDirty = true;
@dirtyFieldDetector @dirtyFieldDetector
...@@ -36,15 +38,12 @@ class ShapeBase extends Shape { ...@@ -36,15 +38,12 @@ class ShapeBase extends Shape {
const {fillColor, strokeColor, strokeWidth} = this; const {fillColor, strokeColor, strokeWidth} = this;
this.clear(); this.clear();
this.beginFill(fillColor); this.beginFill(new Color(fillColor).rgbNumber());
if (strokeWidth > 0) { if (strokeWidth > 0) {
this.beginStroke(strokeColor, strokeWidth); this.lineStyle(strokeWidth, new Color(strokeColor).rgbNumber());
} }
this.redraw(); this.redraw();
this.endFill(); this.endFill();
if (strokeWidth > 0) {
this.endStroke();
}
} }
} }
...@@ -64,7 +63,7 @@ export class Rect extends ShapeBase { ...@@ -64,7 +63,7 @@ export class Rect extends ShapeBase {
const {width, height, borderRadius,} = this; const {width, height, borderRadius,} = this;
if (borderRadius > 0) { if (borderRadius > 0) {
this.drawRoundRect(0, 0, width, height, borderRadius, borderRadius, borderRadius, borderRadius) this.drawRoundedRect(0, 0, width, height, borderRadius);
} else { } else {
this.drawRect(0, 0, width, height); this.drawRect(0, 0, width, height);
} }
......
/**
* Created by rockyl on 2019-12-09.
*/
import BaseTexture from "../../2d/texture/BaseTexture";
import {Rectangle} from "../../2d/math";
import Texture from "../../2d/texture/Texture";
interface dataTm {
x: number, //x,y,w,h为图集上的切图位置数据
y: number,
w: number,
h: number,
ox: number, //ox,oy为偏移数据,trim裁剪的数据,在orig上的偏移{x:0,y:0,width:200,height:200}
oy: number,
sw: number, //sw,sh为原始宽高
sh: number,
ro: boolean, //是否旋转
}
export function createTextureSheet(baseTexture: BaseTexture, altaData) {
var frames = altaData;
var frameKeys = Object.keys(frames);
let frameIndex = 0;
while (frameIndex < frameKeys.length) {
//名字
const i = frameKeys[frameIndex];
//数据
const data: dataTm = frames[i];
//切图上的数据
let frame: Rectangle = null;
//裁切的数据
let trim: Rectangle = null;
//贴图原始尺寸
const orig = new Rectangle(
0,
0,
Math.floor(data.sw),
Math.floor(data.sh)
);
//如果旋转过
if (data.ro) {
frame = new Rectangle(
Math.floor(data.x),
Math.floor(data.y),
Math.floor(data.h),
Math.floor(data.w)
);
} else {
frame = new Rectangle(
Math.floor(data.x),
Math.floor(data.y),
Math.floor(data.w),
Math.floor(data.h)
);
}
//如果是被截掉过透明边界的
if (data.ox || data.oy) {
//其实就是在orig上切图,偏移
trim = new Rectangle(
Math.floor(data.ox),
Math.floor(data.oy),
Math.floor(data.w),
Math.floor(data.h)
);
}
var texture = new Texture(
baseTexture,
frame,
orig,
trim,
data.ro ? 2 : 0,
// data.anchor
);
//缓存下
Texture.addToCache(texture, i);
frameIndex++;
}
}
\ No newline at end of file
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
import {Container} from "../../2d/display"; import {Container} from "../../2d/display";
import {Rect, Image, Label, Circle, ScrollView} from "./nodes"; import {Rect, Image, Label, Circle, ScrollView} from "./nodes";
import {propertyParse} from "../utils"; import {injectProperties, instantiateScript, propertyParse} from "../utils";
const nodeTypeMapping = { const nodeTypeMapping = {
node: Container, node: Container,
...@@ -20,7 +20,7 @@ export function instantiate(config) { ...@@ -20,7 +20,7 @@ export function instantiate(config) {
} }
function instantiateView(config) { function instantiateView(config) {
const {type, scripts} = config; const {type} = config;
const nodeTypeDef = nodeTypeMapping[type]; const nodeTypeDef = nodeTypeMapping[type];
if (!nodeTypeDef) { if (!nodeTypeDef) {
...@@ -29,7 +29,7 @@ function instantiateView(config) { ...@@ -29,7 +29,7 @@ function instantiateView(config) {
} }
const node = new nodeTypeDef(); const node = new nodeTypeDef();
const {name, uuid, properties, children, events} = config; const {name, uuid, properties, children, events, scripts} = config;
node.name = name; node.name = name;
node.uuid = uuid; node.uuid = uuid;
node.__originConfig = config; node.__originConfig = config;
...@@ -56,14 +56,3 @@ function instantiateView(config) { ...@@ -56,14 +56,3 @@ function instantiateView(config) {
return node; return node;
} }
function instantiateScript(node, ScriptConfig) {
const {script: scriptName, props, disabled} = ScriptConfig;
const script = node.scriptsProxy.add(scriptName, props, disabled);
}
function injectProperties(target, source) {
for (let key in source) {
propertyParse(key, target, source);
}
}
...@@ -9,6 +9,8 @@ export * from './utils' ...@@ -9,6 +9,8 @@ export * from './utils'
export * from './decorators' export * from './decorators'
export * from './game-warpper' export * from './game-warpper'
export * from './behavior-runtime' export * from './behavior-runtime'
export * from './web'
export * from './log-switch'
import {instantiate} from './game-warpper/view-interpreter' import {instantiate} from './game-warpper/view-interpreter'
export { export {
......
...@@ -3,43 +3,38 @@ ...@@ -3,43 +3,38 @@
*/ */
import {Stage} from "../2d/display"; import {Stage} from "../2d/display";
import {RENDERER_TYPE, StageScaleMode} from ".."; import {registerCustomModuleFromConfig, registerScripts, RENDERER_TYPE, setProcessMetaLibs, StageScaleMode} from "..";
import {GameStage} from "./game-warpper"; import {GameStage} from "./game-warpper";
import {setGlobalContext} from "./behavior-runtime"; import {setGlobalContext} from "./behavior-runtime";
import {globalLoader} from "../2d/loader/Loader"; import {globalLoader} from "../2d/loader/Loader";
import {Event} from "../2d/events/Event"; import {Event} from "../2d/events/Event";
export let gameStage; export let gameStage: GameStage;
export function launch(url, onAssetsProgress, onAssetsComplete) { export function launch(url, onAssetsProgress, onAssetsComplete) {
return new Promise((resolve, reject) => { return globalLoader.loadJson(url)
globalLoader.loadJson((s, payload) => { .then(config => {
if(s){
resolve(payload);
}else{
reject(payload);
}
}, url);
}).then(
config=>{
return launchWithConfig(config, onAssetsProgress, onAssetsComplete); return launchWithConfig(config, onAssetsProgress, onAssetsComplete);
} });
)
} }
export function launchWithLocalStorage(id, onAssetsProgress, onAssetsComplete){ export function launchWithLocalStorage(id, onAssetsProgress, onAssetsComplete) {
const storeKey = 'preview-project-' + id; const storeKey = 'preview-project-' + id;
let data = localStorage.getItem(storeKey); let storeData = localStorage.getItem(storeKey);
let dataObj = JSON.parse(data); let {data, processes, scripts, customs,} = JSON.parse(storeData);
setProcessMetaLibs(processes);
registerScripts(scripts);
registerCustomModuleFromConfig(customs);
return launchWithConfig(dataObj, onAssetsProgress, onAssetsComplete); return launchWithConfig(data, onAssetsProgress, onAssetsComplete);
} }
export function launchWithConfig(config, onAssetsProgress, onAssetsComplete) { export function launchWithConfig(config, onAssetsProgress, onAssetsComplete) {
return new Promise(resolve => { return new Promise(resolve => {
const {containerID, designWidth, designHeight, frameRate, scaleMode, rendererType,} = config.options; const {containerId, designWidth, designHeight, frameRate, scaleMode, rendererType,} = config.options;
let stage = window['stage'] = new Stage( let stage = window['stage'] = new Stage(
containerID || "game-container", containerId || "game-container",
designWidth || 750, designWidth || 750,
designHeight || 1334, designHeight || 1334,
frameRate || 60, frameRate || 60,
...@@ -48,7 +43,7 @@ export function launchWithConfig(config, onAssetsProgress, onAssetsComplete) { ...@@ -48,7 +43,7 @@ export function launchWithConfig(config, onAssetsProgress, onAssetsComplete) {
); );
Stage.flushAll(); Stage.flushAll();
stage.addEventListener(Event.ON_INIT_STAGE, ()=>{ stage.addEventListener(Event.ON_INIT_STAGE, () => {
gameStage = new GameStage(stage); gameStage = new GameStage(stage);
setGlobalContext({ setGlobalContext({
gameStage gameStage
......
/**
* Created by rockyl on 2019-12-11.
*/
const storeKey = 'zlog-switch';
export enum Logs{
PROCESS = 'process',
}
let store;
try {
store = JSON.parse(localStorage.getItem(storeKey));
store = store === null ? false : store;
} catch (e) {
store = false;
localStorage.setItem(storeKey, JSON.stringify(store));
}
export function getLogSwitch(id) {
return typeof store === 'object' ? (!!store[id]) : !!store;
}
...@@ -8,11 +8,14 @@ export const ESCAPE_REG_EXP = /\$\{[\u4e00-\u9fa5_a-zA-Z0-9\|]+\}/g; ...@@ -8,11 +8,14 @@ export const ESCAPE_REG_EXP = /\$\{[\u4e00-\u9fa5_a-zA-Z0-9\|]+\}/g;
export const linkedFlag = '$_linked_$'; export const linkedFlag = '$_linked_$';
export const nodeScheme = 'node://'; export const nodeScheme = 'node://';
export function arrayFind(arr, callback) { export function arrayFind(arr, predicate) {
if(!arr){
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 (callback(item, i, arr)) { if (predicate(item, i, arr)) {
return item; return item;
} }
} }
...@@ -212,9 +215,49 @@ export function htmlToPureText(htmlText) { ...@@ -212,9 +215,49 @@ export function htmlToPureText(htmlText) {
el = document.createElement('div'); el = document.createElement('div');
} }
el.innerHTML = htmlText; el.innerHTML = htmlText;
document.body.append(el); document.body.appendChild(el);
let pureText = el.innerText; let pureText = el.innerText;
document.body.removeChild(el); document.body.removeChild(el);
return pureText; return pureText;
} }
const zhReg = /[\u4e00-\u9fa5]/;
export function strLen(str){
let len = 0;
for(let char of str){
len += char.match(zhReg) ? 2 : 1;
}
return len;
}
export function strShort(str, limit, replace = '…'){
let result = '';
if(strLen(str) > limit){
let len = 0;
for (let i = 0, li = str.length; i < li; i++) {
const char = str[i];
len += char.match(zhReg) ? 2 : 1;
if(len > limit){
result += replace;
break;
}else{
result += char;
}
}
}else{
result = str;
}
return result;
}
export function instantiateScript(node, ScriptConfig) {
const {script: scriptName, props, disabled} = ScriptConfig;
const script = node.scriptsProxy.add(scriptName, props, disabled);
}
export function injectProperties(target, source) {
for (let key in source) {
propertyParse(key, target, source);
}
}
/**
* Created by rockyl on 2019-12-10.
*/
export let queryParams:any = {};
for(let item of location.search.replace('?', '').split('&')){
let arr = item.split('=');
queryParams[arr[0]] = arr.length === 1 ? true : arr[1];
}
...@@ -811,7 +811,7 @@ collection-visit@^1.0.0: ...@@ -811,7 +811,7 @@ collection-visit@^1.0.0:
map-visit "^1.0.0" map-visit "^1.0.0"
object-visit "^1.0.0" object-visit "^1.0.0"
color-convert@^1.9.0: color-convert@^1.9.0, color-convert@^1.9.1:
version "1.9.3" version "1.9.3"
resolved "https://registry.npm.taobao.org/color-convert/download/color-convert-1.9.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcolor-convert%2Fdownload%2Fcolor-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" resolved "https://registry.npm.taobao.org/color-convert/download/color-convert-1.9.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcolor-convert%2Fdownload%2Fcolor-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"
integrity sha1-u3GFBpDh8TZWfeYp0tVHHe2kweg= integrity sha1-u3GFBpDh8TZWfeYp0tVHHe2kweg=
...@@ -823,6 +823,27 @@ color-name@1.1.3: ...@@ -823,6 +823,27 @@ color-name@1.1.3:
resolved "https://registry.npm.taobao.org/color-name/download/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" resolved "https://registry.npm.taobao.org/color-name/download/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=
color-name@^1.0.0:
version "1.1.4"
resolved "https://registry.npm.taobao.org/color-name/download/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"
integrity sha1-wqCah6y95pVD3m9j+jmVyCbFNqI=
color-string@^1.5.2:
version "1.5.3"
resolved "https://registry.npm.taobao.org/color-string/download/color-string-1.5.3.tgz#c9bbc5f01b58b5492f3d6857459cb6590ce204cc"
integrity sha1-ybvF8BtYtUkvPWhXRZy2WQziBMw=
dependencies:
color-name "^1.0.0"
simple-swizzle "^0.2.2"
color@^3.1.2:
version "3.1.2"
resolved "https://registry.npm.taobao.org/color/download/color-3.1.2.tgz#68148e7f85d41ad7649c5fa8c8106f098d229e10"
integrity sha1-aBSOf4XUGtdknF+oyBBvCY0inhA=
dependencies:
color-convert "^1.9.1"
color-string "^1.5.2"
commander@^2.20.0, commander@^2.9.0, commander@~2.20.3: commander@^2.20.0, commander@^2.9.0, commander@~2.20.3:
version "2.20.3" version "2.20.3"
resolved "https://registry.npm.taobao.org/commander/download/commander-2.20.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcommander%2Fdownload%2Fcommander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" resolved "https://registry.npm.taobao.org/commander/download/commander-2.20.3.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcommander%2Fdownload%2Fcommander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"
...@@ -2054,6 +2075,11 @@ is-arguments@^1.0.4: ...@@ -2054,6 +2075,11 @@ is-arguments@^1.0.4:
resolved "https://registry.npm.taobao.org/is-arguments/download/is-arguments-1.0.4.tgz#3faf966c7cba0ff437fb31f6250082fcf0448cf3" resolved "https://registry.npm.taobao.org/is-arguments/download/is-arguments-1.0.4.tgz#3faf966c7cba0ff437fb31f6250082fcf0448cf3"
integrity sha1-P6+WbHy6D/Q3+zH2JQCC/PBEjPM= integrity sha1-P6+WbHy6D/Q3+zH2JQCC/PBEjPM=
is-arrayish@^0.3.1:
version "0.3.2"
resolved "https://registry.npm.taobao.org/is-arrayish/download/is-arrayish-0.3.2.tgz#4574a2ae56f7ab206896fb431eaeed066fdf8f03"
integrity sha1-RXSirlb3qyBolvtDHq7tBm/fjwM=
is-binary-path@^1.0.0: is-binary-path@^1.0.0:
version "1.0.1" version "1.0.1"
resolved "https://registry.npm.taobao.org/is-binary-path/download/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" resolved "https://registry.npm.taobao.org/is-binary-path/download/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898"
...@@ -3636,6 +3662,13 @@ signal-exit@^3.0.0: ...@@ -3636,6 +3662,13 @@ signal-exit@^3.0.0:
resolved "https://registry.npm.taobao.org/signal-exit/download/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" resolved "https://registry.npm.taobao.org/signal-exit/download/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d"
integrity sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0= integrity sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=
simple-swizzle@^0.2.2:
version "0.2.2"
resolved "https://registry.npm.taobao.org/simple-swizzle/download/simple-swizzle-0.2.2.tgz#a4da6b635ffcccca33f70d17cb92592de95e557a"
integrity sha1-pNprY1/8zMoz9w0Xy5JZLeleVXo=
dependencies:
is-arrayish "^0.3.1"
snapdragon-node@^2.0.1: snapdragon-node@^2.0.1:
version "2.1.1" version "2.1.1"
resolved "https://registry.npm.taobao.org/snapdragon-node/download/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b" resolved "https://registry.npm.taobao.org/snapdragon-node/download/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b"
...@@ -4005,7 +4038,7 @@ ts-loader@^4.0.0: ...@@ -4005,7 +4038,7 @@ ts-loader@^4.0.0:
micromatch "^3.1.4" micromatch "^3.1.4"
semver "^5.0.1" semver "^5.0.1"
tslib@1.10.0, tslib@^1.10.0, tslib@^1.9.0: tslib@1.10.0, tslib@^1.9.0:
version "1.10.0" version "1.10.0"
resolved "https://registry.npm.taobao.org/tslib/download/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" resolved "https://registry.npm.taobao.org/tslib/download/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a"
integrity sha1-w8GflZc/sKYpc/sJ2Q2WHuQ+XIo= integrity sha1-w8GflZc/sKYpc/sJ2Q2WHuQ+XIo=
......
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