Commit 7576e313 authored by wildfirecode's avatar wildfirecode

1

parent acea8926
{"ver":"1.0.1","uuid":"d79519a3-915b-4a9f-9303-a15b642cfe24","subMetas":{},"isGroup":true}
{
"name": "main",
"root": {
"components": [
{
"script": "components/base/Transform"
}
],
"children": [
{
"name": "MainStage",
"uuid": "20181212032053",
"components": [
{
"script": "components/base/Transform",
"properties": {}
},
{
"script": "components/other/CameraController",
"properties": {
"viewportAnchor": {}
}
}
],
"children": [
{
"name": "SceneContainer",
"components": [
{
"script": "components/base/Transform",
"properties": {}
},
{
"script": "./scripts/navigator/SingleSceneNavigator",
"properties": {}
},
{
"script": "components/other/FullStageSize",
"properties": {}
}
],
"uuid": "cc59b006-7d2e-4c7a-bf0b-f52b46c45e85",
"children": [
{
"name": "ScenePlay",
"components": [
{
"script": "components/base/Transform",
"properties": {
"alpha": 1,
"position": {
"x": 0,
"y": 0,
"_type_": "scilla/support/Vector2D"
}
}
},
{
"script": "components/other/FullStageSize",
"properties": {}
},
{
"script": "./scripts/scenes/ScenePlay",
"properties": {}
}
],
"uuid": "1265b761-1b67-4d76-9526-78c457a8d113",
"children": [
{
"name": "bg",
"components": [
{
"script": "components/base/Transform",
"properties": {}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|676f7693-a304-44e6-990d-c969603c8f84"
}
}
],
"uuid": "e17e5bf3-d95a-432c-ba97-23800560f2c7"
},
{
"name": "Image",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"x": -239,
"y": -713
}
}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|94680781-2b1b-432e-9858-4ff21dd04d0c"
}
},
{
"script": "components/other/RelativeLayout",
"properties": {}
}
],
"uuid": "1d05d0fd-4aba-4603-a1e8-02e7a6ab6fd0",
"children": []
},
{
"name": "Image",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"x": -65,
"y": -751
}
}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|2f8360c7-b059-4f1e-b651-37a32eb4a247"
}
},
{
"script": "components/other/RelativeLayout",
"properties": {}
}
],
"uuid": "ca297e3f-1c5e-4526-b0cc-a759377cc364"
}
]
},
{
"name": "SceneStart",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"_x": 0,
"_y": 0
},
"alpha": 0
}
},
{
"script": "components/other/FullStageSize",
"properties": {}
},
{
"script": "./scripts/scenes/SceneStart",
"properties": {
"startbtn": "entity|91e550e7-aba1-4eaf-bb74-04c7e7789102",
"rankbtn": "entity|3b5cb573-bb7b-46f2-af0b-8e6ca7380dcc",
"rulebtn": "entity|adf5cdd6-0cff-47a1-b3ae-8a28fc11b29c"
}
}
],
"uuid": "de98b4b1-6565-4e30-aac8-9f23c1b11a12",
"children": [
{
"name": "bg",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"_x": 0,
"_y": 0
}
}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|5250a5c7-c8ef-4c54-8578-26b68360d3d2"
}
},
{
"script": "components/other/RelativeLayout",
"properties": {}
}
],
"uuid": "bfec7671-c361-4aa2-91b9-aa3ea9cb8162"
},
{
"name": "startbtn",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"_x": -226,
"_y": -438,
"x": 0,
"y": 141
}
}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|fc8debf8-e3e5-4b11-b3fa-3eba3fe274e8"
}
},
{
"script": "components/animation/TouchZoom",
"properties": {
"easeName": "backOut"
}
},
{
"script": "components/ui/Button",
"properties": {
"disabledRes": "res|fc8debf8-e3e5-4b11-b3fa-3eba3fe274e8",
"downRes": "res|fc8debf8-e3e5-4b11-b3fa-3eba3fe274e8",
"upRes": "res|fc8debf8-e3e5-4b11-b3fa-3eba3fe274e8",
"onClick": [
{
"entity": "entity|cc59b006-7d2e-4c7a-bf0b-f52b46c45e85",
"component": 1,
"method": "push",
"param": "play"
}
]
}
}
],
"children": [
{
"name": "label",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"_x": 0,
"_y": 0
}
}
},
{
"script": "components/renderer/TextRenderer",
"properties": {
"text": "",
"fillColor": "rgba(255, 255, 255, 1)"
}
}
],
"uuid": "a2a94b59-b6a5-4b81-9e25-f6cc03e4bdfc"
}
],
"uuid": "91e550e7-aba1-4eaf-bb74-04c7e7789102"
},
{
"name": "rankbtn",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"x": -110,
"y": 350,
"_type_": "scilla/support/Vector2D"
}
}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|6a8d16c4-8f7e-4136-b06a-e29d8f0c6b4b"
}
},
{
"script": "components/animation/TouchZoom",
"properties": {
"easeName": "backOut"
}
},
{
"script": "components/ui/Button",
"properties": {
"upRes": "res|6a8d16c4-8f7e-4136-b06a-e29d8f0c6b4b",
"downRes": "res|6a8d16c4-8f7e-4136-b06a-e29d8f0c6b4b",
"disabledRes": "res|6a8d16c4-8f7e-4136-b06a-e29d8f0c6b4b",
"onClick": [
{
"entity": "entity|de98b4b1-6565-4e30-aac8-9f23c1b11a12",
"component": 2,
"method": "onClick_rankbtn"
}
]
}
}
],
"children": [],
"uuid": "3b5cb573-bb7b-46f2-af0b-8e6ca7380dcc"
},
{
"name": "rulebtn",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"x": 101,
"y": 350
}
}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|e71b9d21-8d94-4fe5-afe4-96ac3abe75dd"
}
},
{
"script": "components/animation/TouchZoom",
"properties": {
"easeName": "backOut"
}
},
{
"script": "components/ui/Button",
"properties": {
"disabledRes": "res|e71b9d21-8d94-4fe5-afe4-96ac3abe75dd",
"downRes": "res|e71b9d21-8d94-4fe5-afe4-96ac3abe75dd",
"upRes": "res|e71b9d21-8d94-4fe5-afe4-96ac3abe75dd",
"onClick": [
{
"entity": "entity|de98b4b1-6565-4e30-aac8-9f23c1b11a12",
"component": 2,
"method": "onClick_startbtn"
}
]
}
}
],
"children": [],
"uuid": "adf5cdd6-0cff-47a1-b3ae-8a28fc11b29c"
}
]
}
]
},
{
"name": "PanelContainer",
"components": [
{
"script": "components/base/Transform",
"properties": {}
},
{
"script": "./scripts/popup/Popup",
"properties": {}
},
{
"script": "components/other/FullStageSize",
"properties": {}
},
{
"script": "components/base/TouchInterrupt",
"properties": {}
},
{
"script": "components/renderer/RectRenderer",
"properties": {
"fillColor": "rgba(0, 0, 0, 0.7)"
},
"disabled": true
}
],
"uuid": "49d80737-0cf1-4eb9-ae3d-1e8d9ec41cc5",
"children": [
{
"name": "RulePanel",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"_x": 0,
"_y": 0,
"x": 0,
"y": -169.5
},
"alpha": 0
}
},
{
"script": "./scripts/dialogs/RulePanel",
"properties": {}
},
{
"script": "components/other/RelativeLayout",
"properties": {
"horizontalCenter": 0,
"top": 500
}
}
],
"uuid": "e8ff44d9-9664-426f-aa46-7e2c57f36634",
"children": [
{
"name": "Image",
"components": [
{
"script": "components/base/Transform",
"properties": {}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|1622356e-272a-47d8-866c-bd519f6c9f6c"
}
}
],
"uuid": "8b33f6a6-6a33-40bc-b09c-b4bcf8b17458"
},
{
"name": "Button",
"components": [
{
"script": "components/base/Transform",
"properties": {
"position": {
"x": 0,
"y": 342.5
}
}
},
{
"script": "components/renderer/TextureRenderer",
"properties": {
"texture": "res|c9c03b0a-1a91-49f1-b28d-bfeff883ad3c"
}
},
{
"script": "components/animation/TouchZoom",
"properties": {
"easeName": "backOut"
}
},
{
"script": "components/ui/Button",
"properties": {
"disabledRes": "res|c9c03b0a-1a91-49f1-b28d-bfeff883ad3c",
"downRes": "res|c9c03b0a-1a91-49f1-b28d-bfeff883ad3c",
"upRes": "res|c9c03b0a-1a91-49f1-b28d-bfeff883ad3c",
"onClick": [
{
"entity": "entity|49d80737-0cf1-4eb9-ae3d-1e8d9ec41cc5",
"component": 1,
"method": "hideDialog",
"param": "RulePanel"
}
]
}
}
],
"children": [],
"uuid": "70bfc19c-8490-450f-8182-bffae001f0ef"
}
]
}
]
}
]
}
]
},
"entity-cache": [
"91e550e7-aba1-4eaf-bb74-04c7e7789102",
"3b5cb573-bb7b-46f2-af0b-8e6ca7380dcc",
"adf5cdd6-0cff-47a1-b3ae-8a28fc11b29c",
"cc59b006-7d2e-4c7a-bf0b-f52b46c45e85",
"de98b4b1-6565-4e30-aac8-9f23c1b11a12",
"de98b4b1-6565-4e30-aac8-9f23c1b11a12",
"49d80737-0cf1-4eb9-ae3d-1e8d9ec41cc5"
],
"resource-groups": {
"preload": [
{
"uuid": "e00fab97-a62c-459b-a61b-a9d7a1e10a21",
"url": "sheets/play.sht-disperse",
"config": {
"textures": [
{
"name": "火-1.png",
"uuid": "94680781-2b1b-432e-9858-4ff21dd04d0c"
},
{
"name": "火箭-1.png",
"uuid": "2f8360c7-b059-4f1e-b651-37a32eb4a247"
}
]
}
},
{
"uuid": "8f66fcf4-2eff-4d68-b65c-710ce6e3a4c9",
"url": "sheets/rule.sht-disperse",
"config": {
"textures": [
{
"name": "closeBtn-1.png",
"uuid": "c9c03b0a-1a91-49f1-b28d-bfeff883ad3c"
},
{
"name": "游戏说明-1.png",
"uuid": "1622356e-272a-47d8-866c-bd519f6c9f6c"
}
]
}
},
{
"uuid": "065474c4-463f-4abd-9e49-fef8358decee",
"url": "sheets/start.sht-disperse",
"config": {
"textures": [
{
"name": "btn1.png",
"uuid": "fc8debf8-e3e5-4b11-b3fa-3eba3fe274e8"
},
{
"name": "按钮-2.png",
"uuid": "4e06ec01-eef0-4a2c-9e42-99d365650985"
},
{
"name": "按钮gray.png",
"uuid": "44563b27-de1f-43dc-a58d-8d5138a11ebf"
},
{
"name": "排行榜.png",
"uuid": "6a8d16c4-8f7e-4136-b06a-e29d8f0c6b4b"
},
{
"name": "规则-1.png",
"uuid": "e71b9d21-8d94-4fe5-afe4-96ac3abe75dd"
}
]
}
},
{
"uuid": "676f7693-a304-44e6-990d-c969603c8f84",
"url": "singles/bg_play.jpg"
},
{
"uuid": "5250a5c7-c8ef-4c54-8578-26b68360d3d2",
"url": "singles/bg.jpg"
}
]
}
}
\ No newline at end of file
{"ver":"1.0.1","uuid":"1f50815f-bf2f-4cf6-8432-f56f3aa834ef","subMetas":{},"type":"scene"}
{"ver":"1.0.1","uuid":"def65e96-eed7-44b3-9804-e76dea9e5062","subMetas":{},"isGroup":true}
/**
* Created by rockyl on 2019-04-09.
*/
import {createTween, ease, Entity} from "scilla";
export async function playAnimation(config, context){
for(let partName in config){
let partConfig = config[partName];
let part:Entity = context[partName];
for(let componentName in partConfig){
let component = part.getComponent(componentName);
let {params, duration, ease: easeName} = partConfig[componentName];
createTween(context, component)
.to(params, duration, ease[easeName]);
}
}
}
\ No newline at end of file
{"ver":"1.0.1","uuid":"e8fac37e-73fa-44ec-b2c7-6c42eeed48fd","subMetas":{},"type":"script"}
{"ver":"1.0.1","uuid":"b64ff277-7d22-4207-9f2b-d3f5669feeca","subMetas":{},"isGroup":true}
import { Transform } from 'scilla-components/src';
import DialogContent from "../popup/DialogContent";
export default class RulePanel extends DialogContent {
// Title: Entity;
// Content: Entity;
// ConfirmButton: Entity;
setup(data: any = {}) {
this.entity.getComponent(Transform).alpha = 1;
// const { title = 'Alert', content = '', button = 'Confirm' } = data;
// this.Title.getComponent(TextRenderer).text = title;
// this.Content.getComponent(TextRenderer).text = content;
// this.ConfirmButton.getChildrenByName('Label')[0].getComponent(TextRenderer).text = button;
}
}
{"ver":"1.0.1","uuid":"ba14eec1-ec40-4288-b685-c3e46ee67149","subMetas":{},"type":"script"}
{"ver":"1.0.1","uuid":"db2a042c-d8d8-4bd6-bc1f-60a10c41bdd6","subMetas":{},"isGroup":true}
/**
* Created by rocky.l on 2017/1/19.
*
* 场景导航器
*/
import { alien } from "./StackNavigator";
import NavigatorAction = alien.NavigatorAction;
export interface INavigatorViewBase {
onAddView(): boolean;
onWillMount(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillUnMount(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillEnter(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidEnter(last: string, action: NavigatorAction, parameters: any): void;
onWillLeave(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidLeave(next: string, action: NavigatorAction, parameters: any): void;
}
{"ver":"1.0.1","uuid":"ea74b1a5-4d17-4b99-8e60-1e3b5aabf31b","subMetas":{},"type":"script"}
/**
* Created by rockyl on 2019-04-09.
*
* 单场景导航器
*/
import { Component } from "scilla";
import { ScenePlay, SceneStart } from "../scenes";
import { VirtualNavigator } from "./VirtualNavigator";
export default class SingleSceneNavigator extends Component {
_navigator: VirtualNavigator;
onCreate() {
super.onCreate();
this._navigator = new VirtualNavigator(this.entity);
this._navigator.register('start', 'SceneStart', SceneStart);
this._navigator.register('play', 'ScenePlay', ScenePlay);
}
onAwake() {
super.onAwake();
this.push('start');
}
onUpdate(t) {
super.onUpdate(t);
}
onSleep() {
super.onSleep();
}
onDestroy() {
super.onDestroy();
}
push(name: string, parameters: any = null) {
this._navigator.stack.push(name, parameters);
}
pop(parameters: any = null) {
this._navigator.stack.pop(parameters);
}
popToBottom(parameters: any = null) {
this._navigator.stack.popTo(0, null, parameters);
}
popAll(name: string, parameters: any = null) {
this._navigator.stack.popAll(name, parameters);
}
replace(name: string, parameters: any = null) {
this._navigator.stack.replace(name, parameters);
}
jump(name: string, parameters: any = null) {
this._navigator.stack.jump(name, parameters);
}
}
{"ver":"1.0.1","uuid":"b9511adc-3aea-4f7e-a864-7dd8cd77f1ea","subMetas":{},"type":"script"}
/**
* Created by rocky.l on 2017/1/17.
*
* 堆栈导航器
*/
export module alien {
export enum NavigatorAction {Push, Pop, Replace, Jump}
export interface INavigatorDelegate {
onEnter(name: string, last: string, action: NavigatorAction, parameters: any);
onLeave(name: string, next: string, action: NavigatorAction, parameters: any);
onError(error: Error);
}
export class StackNavigator {
private _stack: string[];
private _delegate: INavigatorDelegate;
constructor(delegate: INavigatorDelegate) {
this._stack = [];
this._delegate = delegate;
}
private catchPromise(p: Promise<any>) {
if (p) {
p.catch((e => {
this._delegate.onError(e);
}))
}
}
push(name: string, parameters: any = null) {
let last: string = this.getTopSceneName();//获取当前的场景名称
if (last) {
if (last == name) {//如果当前场景和切换场景名称相同,那么不进行场景切换
return;
}
//老的场景进行leave
this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Push, parameters));
}
this._stack.push(name);
//新的场景进行enter
this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Push, parameters));
}
popTo(index, name?: string, parameters: any = null) {
if (this._stack.length > 0 && this._stack.length < (index + 1)) {
return;
}
let last: string = this.getTopSceneName();
this._stack.splice(Math.max(index + 1, 0));
let next: string = this._stack[index];
if (!next) {
this._stack.push(next = name);
}
if (last) {
this.catchPromise(this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters));
}
this.catchPromise(this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters));
}
pop(parameters: any = null) {
this.popTo(this._stack.length - 2, null, parameters);
}
popAll(name: string, parameters: any = null) {
this.popTo(-1, name, parameters);
}
replace(name: string, parameters: any = null) {
let last: string = this._stack.pop();
this._stack.push(name);
this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Replace, parameters));
this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Replace, parameters));
}
jump(name: string, parameters: any = null){
if(this._stack.length < 2){
this.push(name, parameters);
return;
}
let last:string = this._stack.pop();
this._stack.splice(1);
let next:string = name;
this._stack.push(next);
this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters);
this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters);
}
private getTopSceneName(): string {
return this._stack.length > 0 ? this._stack[this._stack.length - 1] : null;
}
private getBottomSceneName(): string {
return this._stack.length > 0 ? this._stack[0] : null;
}
}
}
{"ver":"1.0.1","uuid":"f5068160-2556-48f9-9e64-05ed06dd74d9","subMetas":{},"type":"script"}
/**
* Created by rocky.l on 2017/1/19.
*
* 场景导航器
*/
import {Entity, EventEmitter} from 'scilla'
import {alien} from "./StackNavigator";
import NavigatorAction = alien.NavigatorAction;
import INavigatorDelegate = alien.INavigatorDelegate;
import StackNavigator = alien.StackNavigator;
const showLog = true;
export const VIEW_WILL_ENTER: string = 'VIEW_WILL_ENTER';
export const VIEW_DID_ENTER: string = 'VIEW_DID_ENTER';
export const VIEW_WILL_LEAVE: string = 'VIEW_WILL_LEAVE';
export const VIEW_DID_LEAVE: string = 'VIEW_DID_LEAVE';
export interface INavigatorViewBase {
onWillMount(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillUnMount(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillEnter(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidEnter(last: string, action: NavigatorAction, parameters: any): void;
onWillLeave(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidLeave(next: string, action: NavigatorAction, parameters: any): void;
}
export class VirtualNavigator extends EventEmitter implements INavigatorDelegate {
stack: StackNavigator;
protected _currentName: string;
protected _currentView: INavigatorViewBase;
protected _classDic: any;
protected _container: Entity;
constructor(container) {
super();
this._container = container;
this._classDic = {};
this.stack = new StackNavigator(this);
}
register(alias: string, childName: string, componentDef): void {
this._classDic[alias] = {
childName,
componentDef,
};
}
get currentView(): INavigatorViewBase {
return this._currentView;
}
get currentName(): string {
return this._currentName;
}
protected getViewInstanceByName(name: string): any {
let {childName, componentDef,} = this._classDic[name];
let scene: Entity = this._container.getChildrenByName(childName)[0];
return scene.getComponent(componentDef) ;
}
/**
* 栈入实现
* @param name
* @param last
* @param action
* @param parameters
* @returns {Promise<void>}
*/
async onEnter(name: string, last: string, action: NavigatorAction, parameters: any) {
let view: INavigatorViewBase = this.getViewInstanceByName(name);
this._currentView = view;
this._currentName = name;
if (showLog) console.log(name + ' will mount.');
await view.onWillMount(last, action, parameters);
if (showLog) console.log(name + ' will enter.');
this.emit(VIEW_WILL_ENTER, {name, last, action, parameters});
await view.onWillEnter(last, action, parameters);
if (showLog) console.log(name + ' did enter.');
this.emit(VIEW_DID_ENTER, {name, last, action, parameters});
view.onDidEnter(last, action, parameters);
}
/**
* 栈出实现
* @param name
* @param next
* @param action
* @param parameters
* @returns {Promise<void>}
*/
async onLeave(name: string, next: string, action: NavigatorAction, parameters: any) {
let view: INavigatorViewBase = this.getViewInstanceByName(name);
await view.onWillUnMount(name, action, parameters);
if (showLog) console.log(name + ' will leave.');
this.emit(VIEW_WILL_LEAVE, {name, next, action, parameters});
await view.onWillLeave(next, action, parameters);
if (showLog) console.log(name + ' did leave.');
this.emit(VIEW_DID_LEAVE, {name, next, action, parameters});
view.onDidLeave(next, action, parameters);
}
/**
* 当收到错误实现
* @param error
*/
onError(error: Error) {
}
}
{"ver":"1.0.1","uuid":"aaca9542-45fc-4165-be5d-5f2f916b9238","subMetas":{},"type":"script"}
{"ver":"1.0.1","uuid":"983dc353-e2f8-408e-a725-99f9824dd27e","subMetas":{},"isGroup":true}
/**
* Created by rockyl on 2018-12-12.
*
* 对话框内容组件
*/
import { Component } from 'scilla/src';
export default class DialogContent extends Component {
setup(data) {
}
}
{"ver":"1.0.1","uuid":"2657ed67-fc9d-48b4-9ffa-dc242e49f212","subMetas":{},"type":"script"}
/**
* Created by rockyl on 2018-12-12.
*
* 弹层
*/
import {
ease,
getRenderContext, createTween, Component,
} from "scilla";
import DialogContent from "./DialogContent";
import RectRenderer from "components/renderer/RectRenderer";
import TouchInterrupt from "components/base/TouchInterrupt";
import Transform from "components/base/Transform";
import globalEvent from "globalEvent";
export default class Popup extends Component {
showDuration: number = 300;
hideDuration: number = 200;
private _bgRenderer: RectRenderer;
private _touchInterrupt: TouchInterrupt;
private _stageSize: any;
private _callback;
onAwake() {
super.onAwake();
this._stageSize = getRenderContext().getStageSize();
this._touchInterrupt = this.entity.getComponent(TouchInterrupt);
this._touchInterrupt.enabled = false;
const bgRenderer = this._bgRenderer = this.entity.getComponent(RectRenderer);
bgRenderer.enabled = false;
globalEvent.on('popup', this.onShowAlert, this);
/*setTimeout(() => {
this.showDialog('Alert', {title: 'hello', content: 'fuck you!!!'});
}, 1000);*/
}
onUpdate(t) {
super.onUpdate(t);
}
onSleep() {
super.onSleep();
}
onDestroy() {
super.onDestroy();
}
setBgVisible(visible) {
this._bgRenderer.enabled = visible;
this._touchInterrupt.enabled = visible;
}
setupDialog(dialog, data) {
dialog.enabled = true;
const content: DialogContent = dialog.getComponent(DialogContent);
content.setup(data);
}
showDialog(name, params?, callback?) {
let dialog = this.entity.getChildrenByName(name)[0];
const parent = dialog.parent;
parent.removeChild(dialog);
parent.addChildAt(dialog, parent.children.length);
this._callback = callback;
this.setBgVisible(true);
this.setupDialog(dialog, params);
const transform = dialog.getComponent(Transform);
transform.position.setXY(0, -this._stageSize.height);
createTween(this, transform.position)
.to({ x: 0, y: 0 }, this.showDuration, ease.backOut);
}
hideDialog(name) {
let dialog = this.entity.getChildrenByName(name)[0];
this.setBgVisible(false);
const transform = dialog.getComponent(Transform);
createTween(this, transform.position)
.to({ y: -this._stageSize.height }, this.hideDuration, ease.backIn)
.call(function () {
this._callback && this._callback();
this._callback = null;
}, this);
}
onShowAlert(data, callback) {
const { name,params } = data;
this.showDialog(name, params, callback);
}
}
{"ver":"1.0.1","uuid":"403a3aeb-aa5d-4957-8be4-1ab61fd1b4aa","subMetas":{},"type":"script"}
{"ver":"1.0.1","uuid":"d7c0243c-754a-4082-89b0-5d93cc2f8cae","subMetas":{},"isGroup":true}
/**
* Created by rockyl on 2019-04-09.
*/
import { Component } from "scilla";
import { alien } from "../navigator/StackNavigator";
import { INavigatorViewBase } from "../navigator/VirtualNavigator";
import { Transform } from 'scilla-components/src';
export default class ScenePlay extends Component implements INavigatorViewBase{
onAwake() {
super.onAwake();
}
onDidEnter(last: string, action: alien.NavigatorAction, parameters: any): void {
(this.entity.getComponent(Transform) as Transform).alpha = 1;
}
onDidLeave(next: string, action: alien.NavigatorAction, parameters: any): void {
(this.entity.getComponent(Transform) as Transform).alpha = 0;
}
async onWillEnter(last: string, action: alien.NavigatorAction, parameters: any) {
}
async onWillLeave(next: string, action: alien.NavigatorAction, parameters: any) {
}
onWillMount(last: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
return undefined;
}
onWillUnMount(next: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
return undefined;
}
}
{"ver":"1.0.1","uuid":"511bb8db-5e80-4646-9205-c9fa93f120c3","subMetas":{},"type":"script"}
/**
* Created by rockyl on 2019-04-09.
*/
import { Component, Entity } from "scilla";
import { alien } from "../navigator/StackNavigator";
import { INavigatorViewBase } from "../navigator/VirtualNavigator";
import { Transform } from 'scilla-components/src';
import globalEvent from "globalEvent";
export default class SceneStart extends Component implements INavigatorViewBase {
startbtn: Entity;
rankbtn: Entity;
rulebtn: Entity;
onAwake() {
super.onAwake();
}
onClick_startbtn() {
console.log('onClick_startbtn');
globalEvent.emit('popup', { name: 'RulePanel', params: {} }, this.onAlertClose);
}
onAlertClose() {
console.log('onAlertClose');
};
onClick_rankbtn() {
alert('onClick_rankbtn')
// globalEvent.emit('alert', {title: 'Success', content: 'You complete this puzzle', button: 'Next level'}, this.onAlertClose);
}
onDidEnter(last: string, action: alien.NavigatorAction, parameters: any): void {
(this.entity.getComponent(Transform) as Transform).alpha = 1;
}
onDidLeave(next: string, action: alien.NavigatorAction, parameters: any): void {
(this.entity.getComponent(Transform) as Transform).alpha = 0;
}
async onWillEnter(last: string, action: alien.NavigatorAction, parameters: any) {
}
async onWillLeave(next: string, action: alien.NavigatorAction, parameters: any) {
}
onWillMount(last: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
return undefined;
}
onWillUnMount(next: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
return undefined;
}
}
{"ver":"1.0.1","uuid":"6bd4a810-2792-482e-a03a-5caa2506781c","subMetas":{},"type":"script"}
/**
* Created by rockyl on 2019-04-09.
*/
export {default as SceneStart} from "./SceneStart";
export {default as ScenePlay} from "./ScenePlay";
{"ver":"1.0.1","uuid":"58b64019-1aee-4bb2-81f9-d964e2f1bfaa","subMetas":{},"type":"script"}
{"ver":"1.0.1","uuid":"cdb89785-2908-4cb5-8b14-75d02e37d808","subMetas":{},"isGroup":true}
{"ver":"1.0.1","uuid":"e00fab97-a62c-459b-a61b-a9d7a1e10a21","subMetas":{"火-1.png":{"ver":"1.0.1","uuid":"94680781-2b1b-432e-9858-4ff21dd04d0c","rawTextureUuid":"e00fab97-a62c-459b-a61b-a9d7a1e10a21","type":"texture"},"火箭-1.png":{"ver":"1.0.1","uuid":"2f8360c7-b059-4f1e-b651-37a32eb4a247","rawTextureUuid":"e00fab97-a62c-459b-a61b-a9d7a1e10a21","type":"texture"}},"type":"sheet"}
{"ver":"1.0.1","uuid":"8f66fcf4-2eff-4d68-b65c-710ce6e3a4c9","subMetas":{"closeBtn-1.png":{"ver":"1.0.1","uuid":"c9c03b0a-1a91-49f1-b28d-bfeff883ad3c","rawTextureUuid":"8f66fcf4-2eff-4d68-b65c-710ce6e3a4c9","type":"texture"},"游戏说明-1.png":{"ver":"1.0.1","uuid":"1622356e-272a-47d8-866c-bd519f6c9f6c","rawTextureUuid":"8f66fcf4-2eff-4d68-b65c-710ce6e3a4c9","type":"texture"}},"type":"sheet"}
{"ver":"1.0.1","uuid":"065474c4-463f-4abd-9e49-fef8358decee","subMetas":{"btn1.png":{"ver":"1.0.1","uuid":"fc8debf8-e3e5-4b11-b3fa-3eba3fe274e8","rawTextureUuid":"065474c4-463f-4abd-9e49-fef8358decee","type":"texture"},"按钮-2.png":{"ver":"1.0.1","uuid":"4e06ec01-eef0-4a2c-9e42-99d365650985","rawTextureUuid":"065474c4-463f-4abd-9e49-fef8358decee","type":"texture"},"按钮gray.png":{"ver":"1.0.1","uuid":"44563b27-de1f-43dc-a58d-8d5138a11ebf","rawTextureUuid":"065474c4-463f-4abd-9e49-fef8358decee","type":"texture"},"排行榜.png":{"ver":"1.0.1","uuid":"6a8d16c4-8f7e-4136-b06a-e29d8f0c6b4b","rawTextureUuid":"065474c4-463f-4abd-9e49-fef8358decee","type":"texture"},"规则-1.png":{"ver":"1.0.1","uuid":"e71b9d21-8d94-4fe5-afe4-96ac3abe75dd","rawTextureUuid":"065474c4-463f-4abd-9e49-fef8358decee","type":"texture"}},"type":"sheet"}
{"ver":"1.0.1","uuid":"a67a10bf-16e9-47b7-8f10-ee7dcdeb2551","subMetas":{},"isGroup":true}
{"ver":"1.0.1","uuid":"5250a5c7-c8ef-4c54-8578-26b68360d3d2","subMetas":{"bg":{"ver":"1.0.1","uuid":"32f7dcb5-758e-4267-aa81-a90c7062d2dc","rawTextureUuid":"5250a5c7-c8ef-4c54-8578-26b68360d3d2","type":"texture"}},"type":"texture","imagePath":"/Users/wanghongyuan/kickball0417/assets/singles/bg.jpg"}
{"ver":"1.0.1","uuid":"676f7693-a304-44e6-990d-c969603c8f84","subMetas":{"bg_play":{"ver":"1.0.1","uuid":"65004490-148c-4f78-a8ce-3169e813b971","rawTextureUuid":"676f7693-a304-44e6-990d-c969603c8f84","type":"texture"}},"type":"texture","imagePath":"/Users/wanghongyuan/kickball0417/assets/singles/bg_play.jpg"}
{
"ver": "1.0.1",
"uuid": "8ad59445-0ff2-4382-bb1c-9f7a07845e48",
"subMetas": {
"logo": {
"ver": "1.0.1",
"uuid": "c4c4d4b8-5178-4468-9460-c95435abefb8",
"rawTextureUuid": "8ad59445-0ff2-4382-bb1c-9f7a07845e48",
"type": "texture"
}
},
"type": "texture",
"imagePath": "/Users/rockyl/WorkSpaces/scilla/hello-scilla/assets/singles/logo.png"
}
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>kickball0417</title>
<meta name="viewport"
content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="full-screen" content="true"/>
<meta name="screen-orientation" content="portrait"/>
<meta name="x5-fullscreen" content="true"/>
<meta name="360-fullscreen" content="true"/>
<style>
html, body {
padding: 0;
margin: 0;
border: 0;
height: 100%;
background-color: #282C34;
}
</style>
</head>
<body>
<div id="gameContainer" style="width: 100%;height: 100%;overflow: hidden;"></div>
<script src="debug/bundle.js"></script>
<script>
setTimeout(function(){
var options = window['inputOptions'] || {};
window['kickball0417'].startup(document.getElementById('gameContainer'), options);
}, 100);
</script>
<script src='http://127.0.0.1:35729/livereload.js?ext=Chrome&extver=2.1.0'></script>
</body>
</html>
{
"name": "kickball0417",
"engineConfig": {
"fps": 60,
"designWidth": 750,
"designHeight": 1624,
"scaleMode": "fixedWidth",
"modifyCanvasSize": false,
"resPath": ""
},
"customConfig": {
"scene": {
"scenes": {
"main": "scenes/main.scene"
},
"entryScene": "main"
},
"webServiceUrl": "http://localhost:4001"
}
}
{
"code": "0000000000",
"data": {
"creditsConf": {
"creditsUp": 100,
"creditsType": "virtual",
"creditsDown": 50,
"prize": [
{
"img": "adsfsadf",
"credits": 20,
"id": 4,
"title": "0.3"
},
{
"img": "sadfasdf",
"credits": 150,
"id": 3,
"title": "1.5倍"
},
{
"img": "sadfasdf",
"credits": 100,
"id": 2,
"title": "1倍"
},
{
"img": "sadfasdf",
"credits": 50,
"id": 1,
"title": "0.5倍"
}
]
},
"floating": {
"jsTest": "//yun1.duiba.com.cn/h5/showCouponPrize/4.0.0/index_201710191434.js",
"cssTest": "//yun1.duiba.com.cn/h5/showCouponPrize/4.0.0/index_201710191440.css"
},
"options": [
{
"hidden": false,
"prizeType": "thanks",
"name": "谢谢参与",
"description": "",
"logo": "//yun1.duiba.com.cn/upload/uP99F1462438316972.png",
"id": 15581
},
{
"hidden": false,
"prizeType": "lucky",
"name": "幸运福袋",
"description": "",
"logo": "//yun1.duiba.com.cn/webapp/img/luckynewn.png",
"id": 15582
},
{
"itemId": 47861,
"scoreArea": "",
"hidden": false,
"prizeType": "alipay",
"name": "支付宝1",
"description": "",
"logo": "//yun1.duiba.com.cn/developer/img/activityTool/slotMachine/alipay.png",
"id": 15585
}
],
"rule": "adsfasdf",
"type": "hdtool",
"element": {
"isCreditsTypeOpen": false,
"myCreditsLong": 999999632167,
"freeLimit": -1,
"success": false,
"myCredits": "999999632167",
"needCredits": "100",
"freeEmpty": true,
"needCreditsLong": 100,
"status": 1
}
},
"success": true,
"desc": "OK",
"timestamp": 1548832971636
}
\ No newline at end of file
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1550564744291,
"data": {
"skincontent": "f2fcc331f44c98883f3a5b4868d7d7f4",
"throughInfo": [
{
"step": 3,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 4,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 5,
"prizeType": 2,
"description": null,
"img": ""
},
{
"step": 6,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 7,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 9,
"prizeType": 2,
"description": null,
"img": ""
},
{
"step": 10,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 11,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 13,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 15,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 16,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 18,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 19,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 21,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 22,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 24,
"prizeType": 1,
"description": null,
"img": ""
},
{
"step": 27,
"prizeType": 4,
"description": null,
"img": ""
}
]
}
}
\ No newline at end of file
{
"success":true,
"code":"0000000000",
"desc":"OK",
"timestamp":1548915321930,
"data":1
}
\ No newline at end of file
{"success":true,"code":"0000000000","desc":"OK","timestamp":1548915321930,"data":123456}
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1550569853824,
"data": {
"prizeType": "alipay",
"facePrice": "100",
"title": "1"
}
}
\ No newline at end of file
{
"success":true,
"code": 1,
"desc":"L(*ythj",
"timestamp":1548923950498
}
\ No newline at end of file
{"success":true,"code":"0000000000","desc":"OK","timestamp":1548923950498,"data":{"element":{"success":false,"isCreditsTypeOpen":false,"needCredits":"100","myCredits":"999999630434","myCreditsLong":999999630434,"needCreditsLong":100,"freeLimit":-1,"status":1,"freeEmpty":true},"lottery":{"id":null,"type":"thanks","imgUrl":null,"link":null,"title":null,"itemId":null,"appItemId":null,"bonus":null,"bonusMin":null,"bonusMax":null,"needAccount":null,"appLucky":null,"tip":null,"useBtnText":null,"validate":null,"couponCode":null,"couponKey":null,"stInfoDpmImg":null,"stInfoDpmClose":null,"stInfoDpmGoUse":null,"showUse":null,"openUrl":null,"iosDownloadUrl":null,"androidDownloadUrl":null,"isDownloadUrl":null,"confirm":null,"phaseNumber":null,"happyCode":null,"appHidden":true,"zybangJson":null},"exposure":null,"creditsInfo":{"activityId":82567,"prizeId":4,"orderNum":null,"developerBizId":"3029576","score":null,"recordStatus":1,"errorMsg":null},"againTag":null}}
{
"success":true,
"code":"0000000000",
"desc":"OK",
"timestamp":1548915321930,
"data":1
}
\ No newline at end of file
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1550570639368,
"data": {
"orderId": "883006813674240289",
"submitToken": "d895deb9118f4b938d0b70a3dd2ace19",
"credits": "999999491765",
"unitName": "金币",
"consumerCredits": 999999491765
}
}
\ No newline at end of file
{
"success":true,
"code":"0000000000",
"desc":"OK",
"timestamp":1548915321930,
"data":123456
}
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1550646190489,
"data": {
"score": 100,
"maxScore": 100
}
}
\ No newline at end of file
{
"success": true,
"code": 1,
"desc": "Hl7&L",
"timestamp": "1548915321930",
"data": "123123123"
}
\ No newline at end of file
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1551066205001,
"data": {
"resurrectionStatus": true,
"resurrectionCount": 2,
"resurrectionCredits": 300
}
}
\ No newline at end of file
{
"success": true,
"code": 0,
"desc": "ok",
"timestamp": "1519442544000",
"data": {
"valiDate": "2019-04-11 11:11:11",
"description": "xxx",
"title": "title",
"img": "//yun1.duiba.com.cn/upload/uP99F1462438316972.png"
}
}
\ No newline at end of file
{
"success":true,
"code":"0000000000",
"desc":"OK",
"timestamp":1548915321930,
"data":1
}
\ No newline at end of file
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1550647892216,
"data": "扣积分成功"
}
\ No newline at end of file
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1550568405622,
"data": {
"needPrize": true,
"lastThrough": null,
"currentLocation": 6,
"prizeType": 5,
"retreat": null,
"forward": null,
"url": null,
"plginOrderId": null,
"point": 5
}
}
\ No newline at end of file
{
"success": true,
"code": "0000000000",
"desc": "OK",
"timestamp": 1552025592298,
"data": {
"element": null,
"rule": null,
"questions": [
{
"id": 1,
"type": "text",
"name": "题目1",
"options": [
{
"optionId": 1,
"option": "1"
},
{
"optionId": 2,
"option": "2"
},
{
"optionId": 3,
"option": "3"
},
{
"optionId": 4,
"option": "4"
}
]
},
{
"id": 3,
"type": "text",
"name": "题目3",
"options": [
{
"optionId": 1,
"option": "1"
},
{
"optionId": 2,
"option": "2"
},
{
"optionId": 3,
"option": "3"
},
{
"optionId": 4,
"option": "4"
}
]
}
]
}
}
\ No newline at end of file
/**
* Created by rockyl on 2019-03-19.
*/
const glob = require('glob');
const fs = require('fs');
let files = glob.sync('src/**/!(index|registerAllComponents).ts');
let fileContent = `import {registerDef} from "scilla-core"
`;
const imports = [];
const contents = [];
for(let file of files){
let requirePath = '.' + file.replace('src', '').replace('.ts', '');
let fullClassName = file.replace('src', 'components').replace('.ts', '');
let shortClassName = fullClassName.substr(fullClassName.lastIndexOf('/') + 1);
imports.push(`import ${shortClassName} from '${requirePath}';`);
contents.push(` registerDef('${fullClassName}', ${shortClassName});`);
}
fileContent += imports.join('\n') + `
export function registerAllComponents(){
` + contents.join('\n') + '\n}';
fs.writeFileSync('src/registerAllComponents.ts', fileContent);
\ No newline at end of file
{
"_from": "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git",
"_id": "scilla-components@1.0.0",
"_inBundle": false,
"_integrity": "",
"_location": "/scilla-components",
"_phantomChildren": {},
"_requested": {
"type": "git",
"raw": "scilla-components@git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git",
"name": "scilla-components",
"escapedName": "scilla-components",
"rawSpec": "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git",
"saveSpec": "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git",
"fetchSpec": "http://gitlab2.dui88.com/laoqifeng/scilla-components.git",
"gitCommittish": null
},
"_requiredBy": [
"/"
],
"_resolved": "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git#7dbeb2b004d67c960aa4f52b679d80bb5f4c9110",
"_spec": "scilla-components@git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git",
"_where": "/Users/wanghongyuan/kickball0417",
"bundleDependencies": false,
"deprecated": false,
"devDependencies": {
"glob": "^7.1.3",
"rollup-plugin-commonjs": "^9.2.2",
"rollup-plugin-node-resolve": "^4.0.1",
"rollup-plugin-typescript2": "^0.20.1",
"rollup-plugin-uglify": "^6.0.2",
"tslib": "^1.9.3",
"typescript": "^3.3.4000"
},
"license": "MIT",
"main": "./dist/index.js",
"name": "scilla-components",
"scripts": {},
"types": "./types/index.d.ts",
"version": "1.0.0"
}
/**
* Created by rockyl on 2018/11/16.
*/
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const typescript = require('rollup-plugin-typescript2');
const {uglify} = require('rollup-plugin-uglify');
const name = 'scilla-components';
export default {
input: 'src/index.ts',
output: {
file: `dist/${name}.js`,
format: 'umd',
name,
//sourcemap: true,
},
plugins: [
resolve({
browser: true,
}),
typescript({
typescript: require('typescript'),
tslib: require('tslib'),
declaration: false,
}),
commonjs(),
//uglify({}),
],
external: ['scilla']
};
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
/**
* Created by rockyl on 2019-01-04.
*
* 弹动缩放
*/
import {createTween, Tween, Vector2D, createVector2D} from "scilla";
import ScillaComponent from "../base/ScillaComponent";
const originScale: Vector2D = createVector2D(1, 1);
export default class BounceZoom extends ScillaComponent {
targetScale: Vector2D = createVector2D(1.5, 1.5);
duration:number = 100;
private _tween: Tween;
onAwake() {
super.onAwake();
this._tween = createTween(this, this.transform, false,
{clazz: Vector2D, fields: ['x', 'y'], autoPlay: false}
)
.to({scale: this.targetScale.clone()}, this.duration * 0.5)
.to({scale: originScale.clone()}, this.duration * 0.5)
}
play(){
this._tween.play(true);
}
}
/**
* Created by rockyl on 2019-01-04.
*
* 渐变组件
*/
import {math} from "scilla";
import ScillaComponent from "../base/ScillaComponent";
export default class Fade extends ScillaComponent {
fromAlpha: number = 0;
toAlpha: number = 1;
duration: number = 1000;
private _startTime: number;
private _playing: boolean;
onUpdate(t) {
super.onUpdate(t);
if(this._playing){
if(!this._startTime){
this._startTime = t;
}
let ratio = (t - this._startTime) / this.duration;
this.transform.alpha = math.lerp(this.fromAlpha, this.toAlpha, ratio);
if(ratio >= 1){
this.stop();
}
}
}
play(){
this._startTime = 0;
this._playing = true;
}
stop(){
this._playing = false;
}
}
/**
* Created by rockyl on 2018/11/5.
*
* 自转组件
*/
import {createTween, ScillaEvent, Tween} from "scilla";
import ScillaComponent from "../base/ScillaComponent";
export default class Rotation extends ScillaComponent {
duration: number = 10000;
autoPlay: boolean = false;
loop: number = -1;
onComplete: ScillaEvent = new ScillaEvent();
private _tween: Tween;
onCreate() {
super.onCreate();
}
onAwake() {
super.onAwake();
if(!this._tween){
this._tween = createTween(this, this.transform, false, {autoPlay: this.autoPlay, loop: this.loop, initFields: ['_rotation']})
.to({rotation: 360}, this.duration)
.call(()=>{
this.onComplete.invoke();
});
}
}
play(){
this._tween.play(true);
}
stop(){
this._tween.stop();
}
}
/**
* Created by rockyl on 2018/11/5.
*/
import ScillaComponent from "../base/ScillaComponent";
export default class RoundLoop extends ScillaComponent {
transform;
duration: number = 10000;
onUpdate(t) {
super.onUpdate(t);
const {position} = this.transform;
position.setXY(
Math.cos(t * 0.001) * 100,
Math.sin(t * 0.001) * 100,
)
}
}
/**
* Created by rockyl on 2018/11/5.
*
* 摇摆组件
*/
import ScillaComponent from "../base/ScillaComponent";
export default class Swing extends ScillaComponent {
duration: number = 10000;
onUpdate(t) {
super.onUpdate(t);
this.transform.rotation = Math.sin(t / 100) * 5;
}
}
/**
* Created by rockyl on 2018-11-27.
*
* 触摸缩放交互效果组件
*/
import {createTween, createVector2D, ease, Ease, Tween, Vector2D,} from "scilla";
import {InteractComponent} from "../base";
export default class TouchZoom extends InteractComponent {
scaleOffset: Vector2D = createVector2D(0.1, 0.1);
duration: number = 200;
easeName: Ease = Ease.backOut;
private _zoomIn: Tween;
private _zoomOut: Tween;
private _touchBegin: boolean;
onAwake() {
super.onAwake();
if (!this._zoomIn) {
const {scaleOffset, duration, transform} = this;
const easeFunc = ease[this.easeName];
const scaleFrom = transform.scale.clone();
const scaleTo = transform.scale.clone().add(scaleOffset);
this._zoomIn = createTween(this, transform, false, {autoPlay: false, clazz: Vector2D, fields: ['x', 'y']})
.to({scale: scaleTo}, duration, easeFunc);
this._zoomOut = createTween(this, transform, false, {autoPlay: false, clazz: Vector2D, fields: ['x', 'y']})
.to({scale: scaleFrom}, duration, easeFunc);
}
}
onTouchBegin(e) {
super.onTouchOver(e);
if (this.interactable) {
this._touchBegin = true;
this._zoomIn.play(true);
}
}
onGlobalTouchEnd(e): boolean {
super.onGlobalTouchEnd(e);
if (this._touchBegin) {
this._touchBegin = false;
this._zoomOut.play(true);
}
return false;
}
}
/**
* Created by rockyl on 2018/11/5.
*
* 波动组件
*/
import {raw, ScillaEvent} from "scilla";
import ScillaComponent from "../base/ScillaComponent";
const PI2 = Math.PI * 2;
export enum WaveMethod {
/**
* 公转
*/
round = 'round',
/**
* 自转
*/
rotate = 'rotate',
/**
* 缩放
*/
zoom = 'zoom',
/**
* 透明渐变
*/
fade = 'fade',
/**
* 横向波动
*/
cosWave = 'cosWave',
/**
* 纵向波动
*/
sinWave = 'sinWave',
/**
* 抖动
*/
shake = 'shake',
/**
* 呼吸
*/
breath = 'breath',
}
export default class Wave extends ScillaComponent {
duration: number = 1000;
waveMethod: WaveMethod;
waveParams: raw;
loop: number = -1;
autoPlay: boolean = true;
onComplete: ScillaEvent = new ScillaEvent();
onLoopComplete: ScillaEvent = new ScillaEvent();
private _playing;
private _waveMethod;
private _startTime;
private _oldProps: any = {};
private _loopCounting;
onAwake() {
super.onAwake();
this._waveMethod = waveLibs[this.waveMethod];
this._startTime = 0;
const {transform: {position}} = this;
this._oldProps.x = position.x;
this._oldProps.y = position.y;
if (this.autoPlay) {
this.play();
}
}
onUpdate(t) {
super.onUpdate(t);
if (this._playing) {
if (!this._startTime) {
this._startTime = t;
}
const {duration, waveParams, _waveMethod, transform, transform: {position, scale}, _oldProps} = this;
let pass = (t - this._startTime) % duration;
let r = pass / duration * PI2;
let loopCounting = Math.floor((t - this._startTime) / duration);
if(loopCounting != this._loopCounting){
this._loopCounting = loopCounting;
if(this.onLoopEnd()){
r = PI2;
}
}
let params = waveParams || [];
let props = _waveMethod(...params, r);
if (props.hasOwnProperty('x')) {
position.x = (props.x || 0) + _oldProps.x;
}
if (props.hasOwnProperty('y')) {
position.y = (props.y || 0) + _oldProps.y;
}
if (props.hasOwnProperty('sx')) {
scale.x = props.sx;
}
if (props.hasOwnProperty('sy')) {
scale.y = props.sy;
}
if (props.hasOwnProperty('r')) {
transform.rotation = props.r;
}
}
}
private onLoopEnd(){
if (this.loop < 0) {
this.onLoopComplete.invoke();
} else if (this._loopCounting < this.loop) {
this.onLoopComplete.invoke();
} else {
this._playing = false;
this.onComplete.invoke();
return true;
}
}
play() {
this._loopCounting = 0;
this._playing = true;
this._startTime = 0;
}
stop() {
this._playing = false;
}
}
const {cos, sin, PI} = Math;
const waveLibs = {
round: function (h: number, t: number): any {
return {x: cos(t) * h, y: sin(t) * h};
},
cosWave: function (h: number, t: number): any {
return {x: cos(t) * h, y: 0};
},
sinWave: function (h: number, t: number): any {
h = h || 1;
return {x: 0, y: sin(t) * h};
},
rotate: function (t: number): any {
return {r: 360 * t / PI / 2};
},
shake: function (angle: number, count: number, t: number): any {
return {r: sin(t * count) * angle};
},
breath: function (scale: number = 0.1, t: number): any {
return {sx: sin(t) * scale + 1, sy: -sin(t + PI / 4) * scale + 1};
},
zoom: function (scale: number = 0.1, t: number): any {
return {sx: sin(t) * scale + 1, sy: sin(t) * scale + 1};
},
fade: function (base = 1, t: number): any {
return {alpha: (sin(t) + 1) * 0.5 + base};
},
};
/**
* Created by rockyl on 2018/11/5.
*/
import ScillaComponent from "../base/ScillaComponent";
export default class ZoomLoop extends ScillaComponent{
onUpdate(t) {
super.onUpdate(t);
this.transform.scale.x = this.transform.scale.y = Math.abs(Math.sin(t * 0.001)) * 0.15 + 1;
}
}
/**
* Created by rockyl on 2019-01-10.
*/
export {default as BounceZoom} from './BounceZoom'
export {default as Fade} from './Fade'
export {default as Rotation} from './Rotation'
export {default as RoundLoop} from './RoundLoop'
export {default as Swing} from './Swing'
export {default as TouchZoom} from './TouchZoom'
export {default as Wave} from './Wave'
export {default as ZoomLoop} from './ZoomLoop'
/**
* Created by rockyl on 2018/11/7.
*/
import {Matrix, decorators} from "scilla";
import Renderer from "../renderer/Renderer";
import ScillaComponent from "./ScillaComponent";
const {dirtyFieldTrigger} = decorators;
/**
* 可交互组件
*/
export default class InteractComponent extends ScillaComponent {
/**
* 是否可交互
*/
@dirtyFieldTrigger
interactable = true;
/**
* 触摸中断
*/
touchInterrupt: boolean = false;
protected invertMatrix = Matrix.create();
protected localPos: any = {};
protected isOut = true;
private _touchBeginFlag: boolean;
constructor() {
super();
}
_dealGlobalTouchBegin(e): boolean {
let interrupt = super._dealGlobalTouchBegin(e);
const hitOn = this.hitTest(e);
if (hitOn) {
this._touchBeginFlag = true;
this.onTouchBegin(e);
this._dealTouchOver(e);
}
return hitOn && (interrupt || this.touchInterrupt);
}
_dealGlobalTouchMove(e): boolean {
let interrupt = super._dealGlobalTouchMove(e);
const hitOn = this.hitTest(e);
if (hitOn) {
this._dealTouchOver(e);
this.onTouchMove(e);
} else {
this._dealTouchOut(e);
}
return hitOn && (interrupt || this.touchInterrupt);
}
_dealGlobalTouchEnd(e): boolean {
let interrupt = super._dealGlobalTouchEnd(e);
const hitOn = this.hitTest(e);
if (hitOn) {
this.onTouchEnd(e);
if(this._touchBeginFlag){
this.onTouchTap(e);
this._touchBeginFlag = false;
}
}
this.isOut = true;
return hitOn && (interrupt || this.touchInterrupt);
}
_dealTouchOver(e) {
if (this.isOut) {
this.isOut = false;
this.onTouchOver(e);
}
}
_dealTouchOut(e) {
if (!this.isOut) {
this.isOut = true;
this.onTouchOut(e);
}
}
onTouchBegin(e) {
//console.log('onTouchBegin', e);
}
onTouchMove(e) {
//console.log('onTouchMove', e);
}
onTouchOver(e) {
//console.log('onTouchOver', e);
}
onTouchOut(e) {
//console.log('onTouchOut', e);
}
onTouchEnd(e) {
//console.log('onTouchEnd', e);
}
onTouchTap(e) {
//console.log('onTouchTap', e);
}
/**
* 碰撞检测
* @param e
*/
hitTest(e): boolean {
const matrix = this.transform.getMatrix(true, true, true);
matrix.transformPoint(e.x, e.y, this.localPos);
let result = false;
const renderers = this.entity.getComponents(Renderer);
for (let renderer of renderers) {
if (renderer.hitTest(this.localPos.x, this.localPos.y)) {
if (!renderer['isUsedToMask']) {
result = true;
break
}
} else if (renderer['isUsedToMask']) {
return false
}
}
return result;
}
}
/**
* Created by rockyl on 2019-04-17.
*/
import {Component} from 'scilla'
import Transform from "./Transform";
export default class ScillaComponent extends Component{
get transform():Transform {
return this.entity.getComponentByName('components/base/Transform');
}
}
/**
* Created by rockyl on 2018-12-13.
*
* 触摸中断组件
*/
import InteractComponent from "./InteractComponent";
export default class TouchInterrupt extends InteractComponent {
touchInterrupt: boolean = true;
}
/**
* Created by rockyl on 2018/11/5.
*/
import {Vector2D, Matrix, decorators} from "scilla";
import Renderer from "../renderer/Renderer";
import ScillaComponent from "./ScillaComponent";
const {dirtyFieldDetector, dirtyFieldTrigger} = decorators;
/**
* 矩阵处理顺序
* SCALE_ROTATE: 先缩放后旋转
* ROTATE_SCALE: 先旋转后缩放
*/
export enum MATRIX_ORDER {
SCALE_ROTATE,
ROTATE_SCALE,
}
/**
* 矩阵转换组件
* 缩放、旋转、位移
*/
export default class Transform extends ScillaComponent {
onVector2DModify = (value, key, oldValue) => {
this.makeDirty(value, key, oldValue);
};
/**
* 坐标
*/
@dirtyFieldTrigger
position: Vector2D = new Vector2D(0, 0);
/**
* 全局坐标
*/
private _globalPosition: Vector2D = new Vector2D(0, 0);
/**
* 节点透明度
*/
@dirtyFieldTrigger
alpha: number = 1;
/**
* 节点渲染透明度
*/
private _renderAlpha: number;
get renderAlpha(): number {
return this._renderAlpha;
}
/**
* 影响子节点
*/
@dirtyFieldTrigger
affectChildren: boolean = true;
/**
* 尺寸
* 对于不同的子类渲染都有不同的效果
*/
private _width: number = NaN;
private _height: number = NaN;
/**
* 缩放
*/
@dirtyFieldTrigger
scale: Vector2D = new Vector2D(1, 1);
/**
* 轴距
*/
@dirtyFieldTrigger
pivot: Vector2D = new Vector2D(0.5, 0.5);
/**
* 旋转
*/
@dirtyFieldDetector
rotation = 0;
private order: MATRIX_ORDER = MATRIX_ORDER.SCALE_ROTATE;
protected _localMatrix: Matrix = Matrix.create();
protected _globalMatrix: Matrix = Matrix.create();
protected _globalInvertMatrix: Matrix = Matrix.create();
protected _globalPivotMatrix: Matrix = Matrix.create();
protected dirty: boolean;
get width(): number {
const renderer = this.entity.getComponent(Renderer);
return renderer ? renderer.bounds.width : (isNaN(this._width) ? 0 : this._width);
}
get explicitWidth(): number {
return this._width;
}
set width(value: number) {
if (this._width != value) {
this._width = value;
this.makeDirty(value, 'width');
}
}
get height(): number {
const renderer = this.entity.getComponent(Renderer);
return renderer ? renderer.bounds.height : (isNaN(this._height) ? 0 : this._height);
}
get explicitHeight(): number {
return this._height;
}
set height(value: number) {
if (this._height != value) {
this._height = value;
this.makeDirty(value, 'height');
}
}
/**
* 获取全局坐标
*/
get globalPosition() {
this._globalPosition.setXY(this._globalMatrix.tx, this._globalMatrix.ty);
return this._globalPosition;
}
/**
* 获取全局角度
*/
get globalRotation() {
return this._globalMatrix.rotation * 180 / Math.PI;
}
makeDirty(value, key, oldValue?) {
this.dirty = true;
switch (key) {
case 'width':
case 'height':
const renderers = this.entity.getComponents(Renderer);
for (let renderer of renderers) {
renderer.makeDirty();
}
break;
}
}
/**
* @inheritDoc
*/
onModify(value, key, oldValue) {
super.onModify(value, key, oldValue);
this.makeDirty(value, key, oldValue);
switch (key) {
case 'position':
case 'scale':
//case 'size':
value.onChange = this.onVector2DModify;
break;
}
}
/**
* 更新本地矩阵
*/
protected updateLocalMatrix() {
const {
position: {x, y},
scale: {x: sx, y: sy}, rotation,
} = this;
const matrix = this._localMatrix;
matrix.identity();
if (this.order === MATRIX_ORDER.SCALE_ROTATE) {
matrix.scale(sx, sy);
matrix.rotate(rotation * Math.PI / 180);
} else {
matrix.rotate(rotation * Math.PI / 180);
matrix.scale(sx, sy);
}
matrix.translate(
x,
y,
);
}
/**
* 更新全局矩阵
*/
protected updateGlobalMatrix() {
const {
entity, _globalMatrix, _localMatrix, _globalPivotMatrix,
pivot: {x: px, y: py},
width, height,
} = this;
_globalMatrix.copyFrom(_localMatrix);
if (entity.parent) {
const parentTransform: Transform = <Transform>entity.parent.getComponent(Transform);
if (parentTransform) {
this._renderAlpha = parentTransform._renderAlpha * this.alpha;
_globalMatrix.concat(parentTransform.getMatrix(true, false));
} else {
this._renderAlpha = this.alpha;
}
} else {
this._renderAlpha = this.alpha;
}
_globalPivotMatrix.copyFrom(_globalMatrix);
const {a, d} = _globalMatrix;
_globalPivotMatrix.translate(
-(px - 0.5) * width * a,
-(py - 0.5) * height * d,
);
}
/**
* 获取矩阵
*/
getMatrix(withPivot: boolean = false, invert: boolean = false, affectChildren = false): Matrix {
let matrix;
if(this.affectChildren || affectChildren){
matrix = withPivot ? this._globalPivotMatrix : this._globalMatrix;
if (invert) {
const invertMatrix = this._globalInvertMatrix;
invertMatrix.copyFrom(matrix);
invertMatrix.invert();
return invertMatrix;
}
}else{
matrix = this.entity.parent.getComponent(Transform).getMatrix(withPivot, invert);
}
return matrix;
}
onUpdate(t) {
if (this.dirty) {
this.updateLocalMatrix();
this.dirty = false;
}
this.updateGlobalMatrix();
super.onUpdate(t);
}
onEditorUpdate(t) {
this.onUpdate(t);
}
}
/**
* Created by rockyl on 2019-01-10.
*/
export {default as InteractComponent} from './InteractComponent'
export {default as TouchInterrupt} from './TouchInterrupt'
export {default as Transform} from './Transform'
/**
* Created by rockyl on 2019-01-24.
*/
export * from './animation';
export * from './base';
export * from './other';
export * from './renderer';
export * from './ui';
export * from './net';
export * from './registerAllComponents'
\ No newline at end of file
/**
* Created by rockyl on 2018-12-16.
*
* Api接口组件基类
*/
import {ScillaEvent} from "scilla";
import ScillaComponent from "../base/ScillaComponent";
export default class ApiComponent extends ScillaComponent {
onResponse: ScillaEvent = new ScillaEvent();
onError: ScillaEvent = new ScillaEvent();
onFinish: ScillaEvent = new ScillaEvent();
autoCall: boolean = false;
private _args;
onAwake() {
super.onAwake();
if(this.autoCall){
this.execute();
}
}
protected async execute(paramsInput?, ...args) {
this._args = args;
}
onGotResponse(response: any) {
if(this._args && this._args.length > 0){
this.onResponse.invoke(response, ...this._args);
}else{
this.onResponse.invoke(response);
}
this.onCallFinish();
}
onGotError(e) {
if(this._args && this._args.length > 0){
this.onError.invoke(e, ...this._args);
}else{
this.onError.invoke(e);
}
this.onCallFinish();
}
onCallFinish(){
if(this._args && this._args.length > 0){
this.onFinish.invoke(...this._args);
}else{
this.onFinish.invoke();
}
}
}
/**
* Created by hwj on 2018/12/1.
*
* 简单的api组件
*/
import {utils} from 'scilla'
import ApiComponent from "./ApiComponent";
import {callApi} from "./webService";
export default class SampleApi extends ApiComponent {
name: string;
uri: string;
method: string = 'POST';
params: any = {};
ignoreSuccessField: boolean = false;
async callApi(name, paramsInput, ...args){
if(this.name == name){
await this.execute(paramsInput, ...args);
}
}
protected async execute(paramsInput?, ...args) {
await super.execute(paramsInput, ...args);
const params = {
};
if(this.params){
utils.injectProp(params, this.params);
}
if(paramsInput){
utils.injectProp(params, paramsInput);
}
const {uri, method} = this;
try {
const response = await callApi(uri, params, method, 'json', this.ignoreSuccessField);
this.onGotResponse(response);
return response.data;
} catch (e) {
this.onGotError(e);
}
}
}
/**
* Created by hwj on 2018/12/1.
*
* 简单的api组件
*/
import {utils} from 'scilla'
import ApiComponent from "./ApiComponent";
import {callApi, polling} from "./webService";
export default class SamplePollingApi extends ApiComponent {
name: string;
successField: string;
successValues: any[];
uri: string;
method: string = 'GET';
params: any = {};
maxTimes: number = 5;
delay: number = 500;
async callApi(name, paramsInput, ...args) {
if (this.name == name) {
await this.execute(paramsInput, ...args);
}
}
protected async execute(paramsInput?, ...args) {
await super.execute(paramsInput, ...args);
const params = {
};
if (this.params) {
utils.injectProp(params, this.params);
}
if (paramsInput) {
utils.injectProp(params, paramsInput);
}
const {uri, method} = this;
try {
const response = await polling(this.successFunc, uri, params, this.maxTimes, this.delay, method);
this.onGotResponse(response);
return response.data;
} catch (e) {
this.onGotError(e);
}
}
successFunc=(response)=> {
const {successField, successValues} = this;
let v = successField ? response.data[successField] : response.data;
return successValues.indexOf(v) >= 0;
}
}
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 获取渲染数据
*/
export default class AjaxElementComponent extends SampleApi {
//唯一标识
name: string = 'ajaxElement';
//访问路径
uri: string = '/hdtool/recon/ajaxElement';
//请求方式
method: string = 'GET';
//duiba活动ID
duibaId: string;
//入库活动ID
activityId: string;
protected async execute() {
utils.injectProp(this.params, { duibaId: this.duibaId, activityId: this.activityId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 获取渲染数据
*/
export default class DoJoinComponent extends SampleApi {
//唯一标识
name: string = 'doJoin';
//访问路径
uri: string = '/hdtool/recon/doJoin';
//请求方式
method: string = 'GET';
//入库活动ID
activityId: string;
//token
token: string;
//再来一次订单ID
againOrderId: string;
//活动类型
activityType: string;
//用户ID
consumerId: string;
//积分
credits: number;
//分数 分段发奖
score: number;
protected async execute() {
utils.injectProp(this.params, {
activityId: this.activityId, token: this.token, againOrderId: this.againOrderId,
activityType: this.activityType, consumerId: this.consumerId, credits: this.credits, score: this.score
});
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 查询订单状态
*/
export default class GetOrderStatusComponent extends SampleApi {
//唯一标识
name: string = 'getOrderStatus';
//访问路径
uri: string = '/hdtool/recon/getOrderStatus';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 查询奖品信息
*/
export default class PrizeDetailComponent extends SampleApi {
//唯一标识
name: string = 'prizeDetail';
//访问路径
uri: string = '/hdtool/recon/prizeDetail';
//请求方式
method: string = 'GET';
//
appItemId: string;
//
itemId: string;
//
appId: string;
protected async execute() {
utils.injectProp(this.params, { appItemId: this.appItemId, itemId: this.itemId, appId: this.appId });
super.execute();
}
}
import { utils } from "scilla";
import SamplePollingApi from "../../../SamplePollingApi";
export default class SubCreditsStatusComponent extends SamplePollingApi {
//唯一标识
name: string = 'subCreditsStatus';
//访问路径
uri: string = '/hdtool/recon/subCreditsStatus';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
export default class DatapashComponent extends SampleApi {
//唯一标识
name: string = 'datapash';
//访问路径
uri: string = '/hdtool/recon/ngame/datapash';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
//防作弊数据
dynamicData: any;
//duiba活动ID
duibaId: any;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId, duibaId: this.duibaId, dynamicData: this.dynamicData });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SamplePollingApi from "../../../SamplePollingApi";
/**
* 查询游戏开始订单状态
*/
export default class GetNgameStartStatusComponent extends SamplePollingApi {
//唯一标识
name: string = 'getNgameStartStatus';
//访问路径
uri: string = '/hdtool/recon/ngame/getNgameStartStatus';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 游戏提交成绩接口
*/
export default class NgameManySubmitComponent extends SampleApi {
//唯一标识
name: string = 'ngameManySubmit';
//访问路径
uri: string = '/hdtool/recon/ngame/ngameManySubmit';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
//分数
score: string;
//无用
gameData: any;
//签名
sgin: string;
//防作弊数据
dynamicData: any;
protected async execute() {
utils.injectProp(this.params, {
orderId: this.orderId, score: this.score, gameData: this.gameData, sgin: this.sgin,
dynamicData: this.dynamicData
});
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 游戏提交成绩接口
*/
export default class NgameSubmitComponent extends SampleApi {
//唯一标识
name: string = 'ngameSubmit';
//访问路径
uri: string = '/hdtool/recon/ngame/ngameSubmit';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
//分数
score: string;
//无用
gameData: any;
//签名
sgin: string;
//防作弊数据
dynamicData: any;
protected async execute() {
utils.injectProp(this.params, {
orderId: this.orderId, score: this.score, gameData: this.gameData, sgin: this.sgin,
dynamicData: this.dynamicData
});
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 游戏复活接口
*/
export default class ResurrectionComponent extends SampleApi {
//唯一标识
name: string = 'resurrection';
//访问路径
uri: string = '/hdtool/recon/ngame/resurrection';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SamplePollingApi from "../../../SamplePollingApi";
/**
* 查询复活状态
*/
export default class ResurrectionStatusComponent extends SamplePollingApi {
//唯一标识
name: string = 'resurrectionStatus';
//访问路径
uri: string = '/hdtool/recon/ngame/resurrectionStatus';
//请求方式
method: string = 'POST';
//doJoin订单ID
orderId: string;
//resurrec订单ID
resurrecOrderId: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId, resurrecOrderId: this.resurrecOrderId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SamplePollingApi from "../../../SamplePollingApi";
/**
* 查询前置开奖结果
*/
export default class GetGameOrderInfoComponent extends SamplePollingApi {
//唯一标识
name: string = 'getGameOrderInfo';
//访问路径
uri: string = '/hdtool/recon/getGameOrderInfo';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 前置开奖提交成绩接口
*/
export default class GetGameSubmitComponent extends SampleApi {
//唯一标识
name: string = 'getGameSubmit';
//访问路径
uri: string = '/hdtool/recon/getGameSubmit';
//请求方式
method: string = 'POST';
//订单ID
orderId: string;
//价值
facePrice: number;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId, facePrice: this.facePrice });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 检查题目答案是否正确
*/
export default class CheckOutAnswerComponent extends SampleApi {
//唯一标识
name: string = 'checkOutAnswer';
//访问路径
uri: string = '/hdtool/recon/checkOutAnswer';
//请求方式
method: string = 'GET';
//订单ID
orderId: string;
//答案
answerData: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId, answerData: this.answerData });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 获取题目数据
*/
export default class GetQuestionComponent extends SampleApi {
//唯一标识
name: string = 'getQuestionInfo';
//访问路径
uri: string = '/recon/getQuestionInfo';
//请求方式
method: string = 'GET';
//入库活动ID
activityId: string;
protected async execute() {
utils.injectProp(this.params, { activityId: this.activityId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 获取题目数据
*/
export default class QuestionSubmitComponent extends SampleApi {
//唯一标识
name: string = 'questionSubmit';
//访问路径
uri: string = '/hdtool/recon/questionSubmit';
//请求方式
method: string = 'POST';
//doJoin订单ID
orderId: string;
//答案
answerData: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId, answerData: this.answerData });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 获取渲染数据
*/
export default class AjaxThroughInfoComponent extends SampleApi {
//唯一标识
name: string = 'ajaxThroughInfo';
//访问路径
uri: string = '/hdtool/recon/ajaxThroughInfo';
//请求方式
method: string = 'GET';
//duiba活动ID
duibaId: string;
//关卡ID
throughId: string;
protected async execute() {
utils.injectProp(this.params, { duibaId: this.duibaId, throughId: this.throughId });
super.execute();
}
}
\ No newline at end of file
import { utils } from "scilla";
import SampleApi from "../../../SampleApi";
/**
* 获取渲染数据
*/
export default class ThroughSubmitComponent extends SampleApi {
//唯一标识
name: string = 'throughSubmit';
//访问路径
uri: string = '/hdtool/recon/throughSubmit';
//请求方式
method: string = 'GET';
//duiba活动ID
orderId: string;
protected async execute() {
utils.injectProp(this.params, { orderId: this.orderId });
super.execute();
}
}
\ No newline at end of file
export { default as SampleApi } from './SampleApi'
\ No newline at end of file
/**
* Created by hwj on 2018/11/22.
* 网络组件
*/
import {utils, customConfig} from "scilla";
/**
* 调用接口
* @param uri
* @param params
* @param method
* @param responseType
* @param ignoreSuccessField
*/
export function callApi(uri: string, params: any = null, method: string = 'post', responseType = 'json', ignoreSuccessField = false): Promise<any> {
let ts = Date.now() + Math.floor(Math.random() * 9999999);
let url = uri.indexOf('//') === 0 ? uri : `${uri}?_=${ts}`;
params = params || {};
let options: any = {
method,
};
let baseUrl = customConfig.webServiceUrl;
if (!baseUrl) {
options.credentials = 'include';
}
let temp = typeof params === 'string' ? params : utils.objectStringify(params);
switch (method.toUpperCase()) {
case 'GET':
if(temp && temp.length > 0){
url += (url.indexOf('?') < 0 ? '?' : '') + '&' + temp;
}
break;
case 'POST':
options.body = temp;
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
};
break;
}
const fetchMethod = responseType == 'jsonp' ? window['fetchJsonp'] : fetch;
url = baseUrl ? baseUrl + url : url
return fetchMethod(url, options)
.then((response) => {
if (response.type === 'opaque') {
return null;
}
return response.text();
})
.then((response) => {
//console.log('fetch ==>', url, response);
if (response) {
let data;
switch (responseType) {
case 'json':
try {
/*console.log('debug', GameConfig.debug);
console.log(url, options);
console.log(response);*/
data = JSON.parse(response);
} catch (e) {
console.log('decode json failed: ' + url);
return Promise.reject({});
}
if (ignoreSuccessField || data.success) {
return {
data: data.hasOwnProperty('data') ? data.data : data,
origin: data,
};
} else {
return Promise.reject(data.code);
}
case 'html':
let html = null;//DOMParser.parseFromString(response, 'text/html');
return html;
case 'txt':
return response;
}
}
return Promise.reject();
})
}
/**
* 轮训请求
* @param successFunc
* @param maxTimes
* @param delay
* @param uri
* @param params
* @param method
* @param responseType
*/
export function polling(successFunc, uri, params, maxTimes = 10, delay = 500, method = 'POST', responseType = 'json'): Promise<any> {
let p = Promise.resolve();
for (let i = 0; i < maxTimes; i++) {
p = p.then(func);
p = p.then(() => {
return utils.waitPromise(delay)
})
}
let lastData;
return p.then(
() => {
return Promise.reject(null);
},
(e) => {
if (e === 'success') {
return Promise.resolve(lastData);
}
return Promise.reject(e);
}
);
function func() {
return callApi(uri, params, method, responseType).then(
(data) => {
if (successFunc(data)) {
lastData = data;
return Promise.reject('success');
}
},
(e) => {
return Promise.reject(e);
}
)
}
}
/**
* 获取token并发送
* @param uri
* @param params
* @param method
* @param responseType
*/
export async function getToken(uri: string, params: any, method: string = 'POST', responseType: string = 'json') {
if (window['getDuibaToken']) {
window['getDuibaToken'](async (tokenObj: any) => {
params.token = tokenObj.token;
await this.send(uri, params, method, responseType);
}, () => {
});
} else {
await this.send(uri, params, method, responseType);
}
}
// /**
// * 通讯底层错误
// */
// protected onError(key,msgObj): void {
// const msg = `${key}:${msgObj}`
// this.dispatchEvent('Error', msg );
// }
/**
* 生成签名
* @param {number} ticketId
* @param {number} score
* @param {any} gameData
* @param {string} submitToken 提交
* @returns {string} 签名
*/
export function createSgin(ticketId: number, score: number, gameData: any, submitToken: string): string {
return window['duiba_md5'](ticketId + '' + score + '' + gameData + '' + submitToken);
}
/**
* Created by rockyl on 2018/11/15.
*
*/
import {Entity, createVector2D, Vector2D, math, getRenderContext} from "scilla";
import Transform from "../base/Transform";
import ScillaComponent from "../base/ScillaComponent";
/**
* 相机控制组件
*/
export default class CameraController extends ScillaComponent {
viewportAnchor: Vector2D = createVector2D(0.5, 0.5);
target: Entity;
maxScale = 1.2;
once: boolean = true;
private targetPosition: Vector2D;
private followPosition: Vector2D;
private _stageSize;
onAwake() {
super.onAwake();
const {target,} = this;
if (target) {
this.targetPosition = target.getComponent(Transform).position;
}
this.followPosition = createVector2D();
if(this.once){
this.updateViewport();
}
}
get stageSize(){
if(!this._stageSize){
this._stageSize = getRenderContext().getStageSize();
}
return this._stageSize;
}
onUpdate(t) {
super.onUpdate(t);
if(!this.once){
this.updateViewport();
}
this.followTarget();
}
onEditorUpdate(t){
this.updateViewport();
}
updateViewport() {
if (this.viewportAnchor) {
const {width, height} = this.stageSize;
const {x, y} = this.viewportAnchor;
this.transform.position.setXY(width * x, height * y);
}
}
followTarget() {
if (!this.targetPosition) {
return;
}
const {transform: {scale, position}, stageSize: {width, height}, targetPosition: {x, y, length}, maxScale} = this;
const newScale = maxScale - length * maxScale / 2048;
scale.setXY(newScale, newScale);
this.followPosition.setXY(width / 2, height / 2).subtract(this.targetPosition);
position.copyFrom(math.lerpObj(position, this.followPosition, 0.1, Vector2D, ['x', 'y']));
}
}
/**
* Created by rockyl on 2018-12-17.
*
* 内容组件尺寸自适应组件
*/
import {Size} from "scilla";
import Transform from "../base/Transform";
import ScillaComponent from "../base/ScillaComponent";
export default class ContentSizeFitter extends ScillaComponent {
private _measureSize: Size = new Size();
afterUpdate() {
super.afterUpdate();
const measureSize = this._measureSize;
measureSize.set(0, 0);
for(let child of this.entity.children){
const transform = child.getComponent(Transform);
if(transform){
const {width, height, pivot} = transform;
measureSize.width += width;
measureSize.height += height;
}
}
this.transform.width = measureSize.width;
this.transform.height = measureSize.height;
}
}
/**
* Created by rockyl on 2018/11/15.
*
*/
import {getRenderContext, } from "scilla";
import ScillaComponent from "../base/ScillaComponent";
/**
* 全舞台尺寸组件
*/
export default class FullStageSize extends ScillaComponent {
once: boolean = true;
applyWidth: boolean = true;
applyHeight: boolean = true;
private _stageSize;
get stageSize(){
if(!this._stageSize){
this._stageSize = getRenderContext().getStageSize();
}
return this._stageSize;
}
onCreate() {
super.onCreate();
}
onAwake() {
super.onAwake();
this.execute();
}
onUpdate(t) {
super.onUpdate(t);
if(!this.once){
this.execute();
}
}
onEditorUpdate(t) {
super.onEditorUpdate(t);
this.execute();
}
execute() {
const {width, height} = this.stageSize;
if(this.applyWidth){
this.transform.width = width;
}
if(this.applyHeight){
this.transform.height = height;
}
}
}
/**
* Created by rockyl on 2018-12-05.
*
*/
import Renderer from "../renderer/Renderer";
import Transform from "../base/Transform";
import ScillaComponent from "../base/ScillaComponent";
/**
* 相对布局组件
*/
export default class RelativeLayout extends ScillaComponent {
left: number = NaN;
right: number = NaN;
top: number = NaN;
bottom: number = NaN;
horizontalCenter: number = NaN;
verticalCenter: number = NaN;
once: boolean = true;
onCreate() {
super.onCreate();
}
onAwake() {
super.onAwake();
this.adjust();
}
onUpdate(t) {
super.onUpdate(t);
if (!this.once) {
this.adjust();
}
}
onEditorUpdate(t){
this.adjust();
}
onSleep() {
super.onSleep();
}
onDestroy() {
super.onDestroy();
}
adjust = () => {
const {
entity, entity: {parent}, transform, transform: {position, pivot: {x: ax, y: ay},},
left, right, top, bottom, horizontalCenter, verticalCenter
} = this;
const hasLeft = !isNaN(left);
const hasRight = !isNaN(right);
const hasTop = !isNaN(top);
const hasBottom = !isNaN(bottom);
const hasHorizontalCenter = !isNaN(horizontalCenter);
const hasVerticalCenter = !isNaN(verticalCenter);
const parentRenderers = parent.getComponents(Renderer);
for (let parentRenderer of parentRenderers) {
parentRenderer.measureBounds();
}
const parentTransform:Transform = parent.getComponent(Transform);
let pWidth, pHeight;
if(parentRenderers.length > 0){
const parentBounds = parentRenderers[0].bounds;
pWidth = parentBounds.width;
pHeight = parentBounds.height;
}else{
pWidth = parentTransform.explicitWidth;
pHeight = parentTransform.explicitHeight;
}
const {x: pax, y: pay} = parentTransform.pivot;
const renderers = entity.getComponents(Renderer);
for (let renderer of renderers) {
renderer.measureBounds();
}
let {width, height, } = transform;
let {x, y} = position;
let widthModified = false, heightModified = false;
//adjust
{
if (hasHorizontalCenter) {
x = (pWidth - width) / 2 - pWidth * pax + width * ax;
} else if (hasLeft) {
if (hasRight) {
widthModified = true;
width = pWidth - right - left;
x = (left - right) / 2 - (0.5 - ax) * width;
} else {
x = left - pWidth * pax + width * ax;
}
} else if (hasRight) {
x = -right + pWidth * (1 - pax) - width * (1 - ax);
}
if (hasVerticalCenter) {
y = (pHeight - height) / 2 - pHeight * pay + height * ay;
} else if (hasTop) {
if (hasBottom) {
heightModified = true;
height = pHeight - bottom - top;
y = (top - bottom) / 2 - (0.5 - ay) * height;
} else {
y = top - pHeight * pay + height * ay;
}
} else if (hasBottom) {
y = -bottom + pHeight * (1 - pay) - height * (1 - ay);
}
}
position.x = x;
position.y = y;
if(widthModified){
transform.width = width;
}
if(heightModified){
transform.height = height;
}
if(widthModified || heightModified){
for (let renderer of renderers) {
renderer.measureBounds();
}
}
}
}
/**
* Created by rockyl on 2019-01-10.
*/
export {default as CameraController} from './CameraController'
export {default as ContentSizeFitter} from './ContentSizeFitter'
export {default as RelativeLayout} from './RelativeLayout'
export {default as FullStageSize} from './FullStageSize'
import {registerDef} from "scilla"
import ScillaComponent from './base/ScillaComponent';
import BounceZoom from './animation/BounceZoom';
import Fade from './animation/Fade';
import Rotation from './animation/Rotation';
import RoundLoop from './animation/RoundLoop';
import Swing from './animation/Swing';
import TouchZoom from './animation/TouchZoom';
import Wave from './animation/Wave';
import ZoomLoop from './animation/ZoomLoop';
import InteractComponent from './base/InteractComponent';
import TouchInterrupt from './base/TouchInterrupt';
import Transform from './base/Transform';
import CameraController from './other/CameraController';
import ContentSizeFitter from './other/ContentSizeFitter';
import RelativeLayout from './other/RelativeLayout';
import FullStageSize from './other/FullStageSize';
import CircleRenderer from './renderer/CircleRenderer';
import FrameAnimationRenderer from './renderer/FrameAnimationRenderer';
import GraphicRenderer from './renderer/GraphicRenderer';
import LineRenderer from './renderer/LineRenderer';
import RectRenderer from './renderer/RectRenderer';
import Renderer from './renderer/Renderer';
import TextRenderer from './renderer/TextRenderer';
import TextureRenderer from './renderer/TextureRenderer';
import Button from './ui/Button';
import ProgressBar from './ui/ProgressBar';
import ScrollView from './ui/ScrollView';
export function registerAllComponents(){
registerDef('components/base/ScillaComponent', ScillaComponent);
registerDef('components/animation/BounceZoom', BounceZoom);
registerDef('components/animation/Fade', Fade);
registerDef('components/animation/Rotation', Rotation);
registerDef('components/animation/RoundLoop', RoundLoop);
registerDef('components/animation/Swing', Swing);
registerDef('components/animation/TouchZoom', TouchZoom);
registerDef('components/animation/Wave', Wave);
registerDef('components/animation/ZoomLoop', ZoomLoop);
registerDef('components/base/InteractComponent', InteractComponent);
registerDef('components/base/TouchInterrupt', TouchInterrupt);
registerDef('components/base/Transform', Transform);
registerDef('components/other/CameraController', CameraController);
registerDef('components/other/ContentSizeFitter', ContentSizeFitter);
registerDef('components/other/RelativeLayout', RelativeLayout);
registerDef('components/other/FullStageSize', FullStageSize);
registerDef('components/renderer/CircleRenderer', CircleRenderer);
registerDef('components/renderer/FrameAnimationRenderer', FrameAnimationRenderer);
registerDef('components/renderer/GraphicRenderer', GraphicRenderer);
registerDef('components/renderer/LineRenderer', LineRenderer);
registerDef('components/renderer/RectRenderer', RectRenderer);
registerDef('components/renderer/Renderer', Renderer);
registerDef('components/renderer/TextRenderer', TextRenderer);
registerDef('components/renderer/TextureRenderer', TextureRenderer);
registerDef('components/ui/Button', Button);
registerDef('components/ui/ProgressBar', ProgressBar);
registerDef('components/ui/ScrollView', ScrollView);
}
\ No newline at end of file
/**
* Created by rockyl on 2018/11/6.
*/
import GraphicRenderer from "./GraphicRenderer";
import {decorators} from "scilla";
const {dirtyFieldDetector} = decorators;
/**
* 圆形渲染组件
*/
export default class CircleRenderer extends GraphicRenderer {
/**
* 半径
*/
@dirtyFieldDetector
radius = 50;
/**
* 开始角度
*/
@dirtyFieldDetector
startAngle: number = 0;
/**
* 结束角度
*/
@dirtyFieldDetector
endAngle: number = 360;
/**
* 是否回归到圆心
*/
@dirtyFieldDetector
backToCenter: boolean = true;
protected getRenderSize(): any {
const {radius} = this;
return {width: radius * 2, height: radius * 2};
}
/**
* @inheritDoc
*/
protected draw() {
const {context, bounds: {width, height}, startAngle, endAngle, backToCenter, _margin, _useCacheMode} = this;
let offset = _useCacheMode ? _margin : 0;
const radius = Math.min(width, height) / 2;
const pos = offset + radius;
if(startAngle == 0 && endAngle == 360){
context.arc(pos, pos, radius, 0, 2 * Math.PI);
}else{
if(backToCenter){
context.moveTo(pos, pos);
}
context.arc(pos, pos, radius, startAngle * Math.PI / 180, endAngle * Math.PI / 180);
if(backToCenter){
context.lineTo(pos, pos);
}
}
super.draw();
}
}
/**
* Created by rockyl on 2018-11-30.
*
* 帧动画组件
*
* todo 倒置播放
*/
import Renderer from "./Renderer";
import {FrameAnimation, ScillaEvent} from "scilla";
/**
* 帧动画渲染组件
*/
export default class FrameAnimationRenderer extends Renderer {
/**
* 帧动画资源
*/
public frameAnimation: FrameAnimation;
/**
* 是否自动播放
*/
public autoPlay: boolean = false;
/**
* 帧率
* 不设置就读取动画文件的帧率
*/
public fps: number = NaN;
public onComplete: ScillaEvent = new ScillaEvent();
public onLoopComplete: ScillaEvent = new ScillaEvent();
private _playing;
private _startTime;
private _startFrame;
private _endFrame;
private _currentFrameIndex;
private _startFlag;
private _loop;
private _loopCounting;
private _flag;
/**
* @inheritDoc
*/
onAwake() {
super.onAwake();
if(this.autoPlay){
this.play(0, -1);
}
}
/**
* @inheritDoc
*/
onUpdate(t) {
if (this._playing) {
const {frameAnimation, _startFrame, _endFrame, fps} = this;
if (this._startFlag) {
this._startFlag = false;
this._startTime = t;
this._loopCounting ++;
}
const mFPS = isNaN(fps) ? frameAnimation.fps : fps;
const passTime = t - this._startTime;
const passFrameCount = Math.floor(passTime / (1000 / mFPS));
const passFrameInRegion = passFrameCount % (_endFrame - _startFrame + 1);
this._currentFrameIndex = _startFrame + passFrameInRegion;
if(passFrameInRegion == 0 && passFrameCount > 0){
this._currentFrameIndex = _endFrame;
this.onLoopEnd();
}
}
super.onUpdate(t);
}
/**
* @inheritDoc
*/
onSleep() {
super.onSleep();
}
/**
* 当一遍播放结束时
*/
onLoopEnd(){
if (this._loop < 0) {
this._startFlag = true;
this.onLoopComplete.invoke();
} else if (this._loopCounting < this._loop) {
this._startFlag = true;
this.onLoopComplete.invoke();
} else {
this._playing = false;
this.onComplete.invoke();
}
}
/**
* 播放
* @param frame
* @param loop
* @param force
*/
play(frame: number | string = 0, loop: number = 0, force = true) {
this._loop = loop;
this._loopCounting = 0;
if (!this.frameAnimation) {
return;
}
let startFrame = 0, endFrame = this.frameAnimation.frameCount - 1;
if (typeof frame == 'string') {
const label = this.frameAnimation.getLabel(frame);
if (label) {
startFrame = label.frame - 1;
endFrame = label.end;
}
} else {
startFrame = frame;
}
this._startFrame = startFrame;
this._endFrame = endFrame;
this._currentFrameIndex = this._startFrame;
this._startFlag = true;
this._playing = true;
}
/**
* 停止
*/
stop() {
this._playing = false;
}
/**
* @inheritDoc
*/
protected draw() {
super.draw();
if (!this.frameAnimation) {
return;
}
const {context, frameAnimation, _currentFrameIndex, bounds} = this;
const {texture, data} = frameAnimation.getFrame(_currentFrameIndex);
if (texture) {
const {img, bounds: {x, y, width: textureWidth, height: textureHeight}} = texture;
bounds.setTo(data.x, data.y, textureWidth, textureHeight);
context.drawImage(img, x, y, textureWidth, textureHeight, data.x, data.y, textureWidth, textureHeight);
}
}
}
/**
* Created by rockyl on 2018/11/6.
*
* todo 如果isUsedToMask,就禁用缓存
*/
import Renderer from "./Renderer";
import {color} from "scilla";
/**
* 图形渲染组件
*/
export default class GraphicRenderer extends Renderer {
fillColor: color = '#42bce4';
borderColor: color = '#0899d0';
borderWidth = 0;
//是否为mask
isMask = false;
//是否显示mask
maskVisible = false;
protected getUseCacheMode(){
return this._useCacheMode && !this.isMask;
}
/**
* 获取图形尺寸
*/
protected getRenderSize(): any {
return {width: 0, height: 0};
}
/**
* @inheritDoc
*/
protected beforeDraw() {
super.beforeDraw();
this.applyStyle();
this.context.beginPath();
}
/**
* @inheritDoc
*/
protected draw() {
super.draw();
if (this.isMask) {
this._context.clip();
this.maskVisible && this.fillAndStoke()
} else {
this.fillAndStoke()
}
}
/**
* 应用渲染样式
*/
protected applyStyle() {
const {context, fillColor, borderColor, borderWidth} = this;
context.fillStyle = fillColor;
if (borderWidth > 0) {
context.strokeStyle = borderColor;
context.lineWidth = borderWidth;
}
}
/**
* 绘制
*/
protected fillAndStoke() {
const {context, borderWidth} = this;
context.fill();
if (borderWidth > 0) {
context.stroke();
}
}
/**
* @inheritDoc
*/
protected drawClip() {
this.isMask && this.context.save();
}
/**
* @inheritDoc
*/
afterUpdate() {
this.isMask && this.context.restore();
}
afterEditorUpdate(){
this.afterUpdate();
}
measureBounds() {
if(this.entity.name == 'content'){
console.log();
}
if (!this.dirty) {
return;
}
this._margin = this.borderWidth;
const {bounds, transform: {explicitWidth: tWidth, explicitHeight: tHeight}} = this;
const {width: sWidth, height: sHeight} = this.getRenderSize();
bounds.width = isNaN(tWidth) ? sWidth : tWidth;
bounds.height = isNaN(tHeight) ? sHeight : tHeight;
super.measureBounds();
}
}
/**
* Created by rockyl on 2018/11/6.
*/
import GraphicRenderer from "./GraphicRenderer";
/**
* 线段渲染组件
*/
export default class LineRenderer extends GraphicRenderer {
x0: number = 0;
y0: number = 0;
x1: number = 0;
y1: number = 0;
/**
* @inheritDoc
*/
draw() {
super.draw();
const {context, x0, y0, x1, y1} = this;
context.moveTo(x0, y0);
context.lineTo(x1, y1);
}
/**
* @inheritDoc
*/
measureBounds() {
const {bounds} = this;
bounds.width = 0;
bounds.height = 0;
super.measureBounds();
}
}
/**
* Created by rockyl on 2018/11/6.
*/
import GraphicRenderer from "./GraphicRenderer";
import {decorators} from "scilla"
const {dirtyFieldDetector} = decorators;
/**
* (圆角)矩形渲染器
*/
export default class RectRenderer extends GraphicRenderer {
@dirtyFieldDetector
width = 100;
@dirtyFieldDetector
height = 100;
@dirtyFieldDetector
cornerRadius = 0;
protected getRenderSize(): any {
const {width, height} = this;
return {width, height};
}
/**
* @inheritDoc
*/
protected draw() {
const {PI} = Math;
const {context, cornerRadius: r, bounds: {width, height}, _margin, _useCacheMode} = this;
let offset = _useCacheMode ? _margin : 0;
if (r) {
context.moveTo(offset + r, offset + 0);
context.lineTo(offset + width - r, offset + 0);
context.arc(offset + width - r, offset + r, r, PI * 3 / 2, PI * 2);
context.lineTo(offset + width, offset + height - r);
context.arc(offset + width - r, offset + height - r, r, 0, PI / 2);
context.lineTo(offset + r, offset + height);
context.arc(offset + r, offset + height - r, r, PI / 2, PI);
context.lineTo(offset + 0, offset + r);
context.arc(offset + r, offset + r, r, PI, PI * 3 / 2);
} else {
context.rect(offset, offset, width, height);
}
super.draw();
}
}
/**
* Created by rockyl on 2018/11/6.
*/
import {createCanvas, getRenderContext, Bounds, Vector2D, math, decorators, EngineConfig} from "scilla";
import ScillaComponent from "../base/ScillaComponent";
const {dirtyFieldTrigger} = decorators;
/**
* 渲染组件基类
*/
export default class Renderer extends ScillaComponent {
protected onVector2DModify = () => {
this.makeDirty();
};
private _debugDrawColor: string;
protected dirty: boolean = true;
/**
* 是否使用缓存模式
*/
protected _useCacheMode: boolean = false;
/**
* 透明度
*/
alpha: number = 1;
//锚点:在各子render里面加,从绘制上改,将同时更改位置原点,旋转原点,缩放原点,以0到1比例形式(现用此方案)
//在该render上改transform;更改旋转和缩放原点,不改变位置原点,默认中心为位置原点,以真实数值形式
@dirtyFieldTrigger
anchor: Vector2D = new Vector2D(0.5, 0.5);
/**
* 边界
*/
bounds = new Bounds();
protected cacheCanvas = null;
/**
* 缓存用的渲染上下文
*/
protected cacheCanvasContext;
/**
* 锚点实际偏移
*/
protected _anchorOffset: Vector2D = new Vector2D();
//渲染上下文
protected _context = getRenderContext().getContext();
/**
* 扩展尺寸
*/
protected _margin: number = 0;
get useCacheMode() {
return this.getUseCacheMode();
}
set useCacheMode(value) {
this._useCacheMode = value;
}
constructor(){
super();
this._debugDrawColor = `hsl(${math.makeRandomInt(360)}, ${math.makeRandomInt(100)}%, 60%)`;
}
protected getUseCacheMode() {
return this._useCacheMode;
}
/**
* 获取渲染上下文
* 如果缓存上下文存在,则返回缓存上下文
*/
get context() {
return this.cacheCanvasContext || this._context;
}
makeDirty() {
this.dirty = true;
}
/**
* @inheritDoc
*/
protected onModify(value, key, oldValue) {
super.onModify(value, key, oldValue);
this.makeDirty();
switch (key) {
case 'anchor':
value.onChange = this.onVector2DModify;
break;
}
}
onAwake() {
super.onAwake();
if (!this.transform) {
console.warn('renderer need a transform component');
}
}
/**
* @inheritDoc
*/
onUpdate(t) {
if (this.dirty) {
if (this.useCacheMode) {
this.readyCacheCanvas();
}
this.measureBounds();
if (this.useCacheMode) {
this.updateCacheCanvas();
}
}
this.transformToLocal();
this.render();
if (EngineConfig.drawRenderRect) {
const {_context, _debugDrawColor, bounds: {width, height}, _anchorOffset: {x, y}, transform: {pivot: {x: px, y: py}}} = this;
_context.globalAlpha = 0.9;
_context.strokeStyle = _debugDrawColor;
_context.fillStyle = _debugDrawColor;
_context.beginPath();
_context.rect(0, 0, width, height);
_context.stroke();
_context.beginPath();
_context.arc(width * px, height * py, 3, 0, 2 * Math.PI);
_context.fill();
}
}
onEditorUpdate(t){
this.onUpdate(t);
}
/**
* 准备缓存渲染上下文
*/
protected readyCacheCanvas() {
let canvas = this.cacheCanvas;
if (!canvas) {
canvas = this.cacheCanvas = createCanvas();
this.cacheCanvasContext = canvas.getContext('2d');
}
}
/**
* 更新缓存属性
*/
protected updateCacheCanvas() {
let canvas = this.cacheCanvas;
const {width, height} = this.bounds;
canvas.width = width + this._margin * 2;
canvas.height = height + this._margin * 2;
}
/**
* 渲染过程
*/
protected render() {
this.beforeDraw();
this.drawClip();
if (this.dirty) {
if(this.useCacheMode){
this.draw();
}
this.dirty = false;
}
if (this.useCacheMode) {
this.drawCache();
} else {
this.draw();
}
}
/**
* 画之前
*/
protected beforeDraw() {
this.applyAlpha();
}
/**
* 执行矩阵转换
*/
protected transformToLocal() {
const {transform, _anchorOffset: {x: ax, y: ay}} = this;
if (transform && transform.enabled) {
const {a, b, c, d, tx, ty} = transform.getMatrix(true, false, true);
const offX = ax * a + ay * c;
const offY = ax * b + ay * d;
this._context.setTransform(a, b, c, d, tx - offX, ty - offY);
} else {
this._context.setTransform(1, 0, 0, 1, -ax, -ay);
}
}
/**
* 应用透明度
*/
protected applyAlpha() {
this._context.globalAlpha = this.alpha * this.transform.renderAlpha;
}
/**
* 绘制缓存
*/
protected drawCache() {
if (this.cacheCanvas.width > 0 && this.cacheCanvas.height > 0) {
this._context.drawImage(this.cacheCanvas, -this._margin, -this._margin);
}
}
/**
* 画遮罩
*/
protected drawClip() {
}
/**
* 画
*/
protected draw() {
}
/**
* 测量边界
*/
measureBounds() {
const {anchor: {x, y}, bounds, bounds: {width, height}} = this;
const anchorOffsetX = this._anchorOffset.x = width * x;
const anchorOffsetY = this._anchorOffset.y = height * y;
bounds.x = -anchorOffsetX;
bounds.y = -anchorOffsetY;
}
/**
* 碰撞检测
* @param x
* @param y
*/
hitTest(x, y) {
return this.bounds.contains(x, y);
}
}
/**
* Created by rockyl on 2018/11/6.
*/
import GraphicRenderer from "./GraphicRenderer";
import {TextStyle, EngineConfig, decorators, Texture, resource} from "scilla";
const {dirtyFieldDetector, dirtyFieldTrigger} = decorators;
export enum TextAlign{
/**
* 左对齐
*/
LEFT = 'left',
/**
* 居中对齐
*/
CENTER = 'center',
/**
* 右对齐
*/
RIGHT = 'right',
}
export enum VerticalAlign{
/**
* 顶部
*/
TOP = 'top',
/**
* 中间
*/
MIDDLE = 'middle',
/**
* 底部
*/
BOTTOM = 'bottom',
}
/**
* 文本渲染组件
*/
export default class TextRenderer extends GraphicRenderer {
/**
* 文本
*/
@dirtyFieldDetector
text: string = '';
/**
* 文本流
*/
@dirtyFieldTrigger
textFlow: any = null;
/**
* 文本对齐
*/
@dirtyFieldDetector
textAlign: TextAlign = TextAlign.CENTER;
/**
* 文本纵向对齐
*/
@dirtyFieldDetector
verticalAlign: VerticalAlign = VerticalAlign.MIDDLE;
/**
* 行间距
*/
@dirtyFieldDetector
lineSpacing: number = 0;
/**
* 字间距
*/
@dirtyFieldDetector
letterSpacing: number = 0;
/**
* 文图文本资源
*/
@dirtyFieldDetector
fontRes: resource;
protected _lineHeight: number = NaN;
protected _bmpLineHeight: number = 0;
protected _textWidth: number;
protected _textHeight: number;
/**
* 文本样式
*/
@dirtyFieldDetector
textStyle: TextStyle = new TextStyle();
@dirtyFieldDetector
useCacheMode: boolean = true;
protected _pureText: string;
protected rows: any[];
protected measureCache: any = {};
protected onModify(value, key, oldValue) {
super.onModify(value, key, oldValue);
switch (key) {
case 'textFlow':
if(value){
this.updateTextFlow();
}
break;
case 'textStyle':
value.onChange = this.makeDirty.bind(this);
this.makeDirty();
break;
}
}
updateTextFlow(){
let text = '';
if (this.textFlow) {
for (let item of this.textFlow) {
text += item.text;
}
}
this._pureText = text;
this.makeDirty();
}
/**
* 行高
* 行高如果没设定就为fontSize的1.2倍,https://developer.mozilla.org/en-US/docs/Web/CSS/line-height#Values
*/
get lineHeight(): number {
return isNaN(this._lineHeight) ? (
this.isBmpMode ? this._bmpLineHeight : this.textStyle.fontSize * EngineConfig.lineHeightRatio
) : this._lineHeight;
}
set lineHeight(value: number) {
if (this._lineHeight != value) {
this._lineHeight = value;
this.dirty = true;
}
}
/**
* 获取纯文本
*/
get pureText(): string {
return this.textFlow ? this._pureText : this.text;
}
protected getRenderSize(): any {
return {
width: this._textWidth,
height: this._textHeight,
};
}
protected beforeDraw() {
super.beforeDraw();
if (!this.isBmpMode) {
this.applyTextStyle();
}
}
/**
* 应用文本样式
*/
protected applyTextStyle() {
const {context, textStyle} = this;
const {fontStyle, fontVariant, fontWeight, fontSize, fontFamily} = textStyle;
context.font = `${fontStyle} ${fontVariant} ${fontWeight} ${fontSize}px ${fontFamily}`;
}
/**
* @inheritDoc
*/
protected fillAndStoke() {
if (!this.pureText || this.pureText.length == 0) {
return;
}
const {
context, measureCache, lineHeight, lineSpacing, letterSpacing, rows, textAlign, verticalAlign, isBmpMode,
transform: {width, height},
} = this;
//const expWidth = isNaN(width) ? boundsWidth : width;
//const expHeight = isNaN(height) ? boundsHeight : height;
const rowCount = rows.length;
let x = 0;
switch (textAlign) {
case "left":
x = 0;
break;
case "right":
x = width;
break;
case "center":
default:
x = width / 2;
break;
}
let y = 0;
const drawHeight = rowCount * lineHeight + lineSpacing * (rowCount - 1);
switch (verticalAlign) {
case "top":
y = 0;
break;
case "bottom":
y = height - drawHeight;
break;
case "middle":
default:
y = (height - drawHeight) / 2;
break;
}
y += lineHeight;
context.textAlign = letterSpacing == 0 && !this.textFlow ? textAlign : 'left';
context.textBaseline = 'bottom';
let offY = 0;
for (let i = 0; i < rowCount; i++) {
const {text, lineWidth} = rows[i];
if (letterSpacing == 0 && !isBmpMode && !this.textFlow) {
this.drawText(i, text, x, y + offY);
} else {
let offX = 0;
switch (textAlign) {
case "left":
offX = 0;
break;
case "right":
offX = -lineWidth;
break;
case "center":
default:
offX = -lineWidth / 2;
break;
}
for (let j = 0, lj = text.length; j < lj; j++) {
const char = text[j];
this.drawText(j, char, x + offX, y + offY);
if (measureCache[char].width > 0) {
offX += measureCache[char].width + letterSpacing;
}
}
}
offY += lineHeight + lineSpacing;
}
//console.log(this.cacheCanvas.toDataURL());
}
private getStyle(index){
if(!this.textFlow){
return null;
}
let targetItem;
let count = 0;
for(let item of this.textFlow){
count += item.text.length;
if(index < count){
targetItem = item;
break;
}
}
return targetItem.style;
}
protected drawText(index, text, x, y) {
const {context, borderWidth, isBmpMode, fontRes} = this;
if (isBmpMode) {
const texture: Texture = fontRes.getTexture(text);
if (!texture) {
return;
}
const {bounds: {x: textureX, y: textureY, width: textureWidth, height: textureHeight}} = texture;
context.drawImage(texture.img, textureX, textureY, textureWidth, textureHeight, x, y, textureWidth, textureHeight);
} else {
let style = this.getStyle(index);
if(style){
if(style.hasOwnProperty('textColor')){
context.fillStyle = style.textColor;
}
}else{
context.fillStyle = this.fillColor;
}
context.fillText(text, x, y + 1);
if (borderWidth > 0) {
context.strokeText(text, x, y + 1);
}
}
}
protected get isBmpMode() {
return !!this.fontRes;
}
protected measureText(text): any {
let result;
if (this.measureCache.hasOwnProperty(text)) {
result = this.measureCache[text];
} else {
const {context, letterSpacing, isBmpMode, fontRes, lineHeight} = this;
if (isBmpMode) {
if (text.length == 1) {
const texture: Texture = fontRes.getTexture(text);
result = {
width: texture ? texture.width : 0,
height: texture ? texture.height : 0,
}
} else {
let totalWidth = 0, totalHeight = 0;
for (let char of text) {
const measureResult = this.measureText(char);
totalWidth += measureResult.width;
if (measureResult.height > totalHeight) {
totalHeight = measureResult.height;
}
}
result = {
width: totalWidth,
height: totalHeight,
}
}
} else {
result = {
width: context.measureText(text).width,
height: lineHeight,
};
}
result.width += letterSpacing * (text.length - 1);
//如果是多个字且有字间距,就测量全部单个字母
if (text.length == 1) {
this.measureCache[text] = result;
}
if (letterSpacing != 0 && text.length > 1 || this.textFlow) {
for (let char of text) {
this.measureCache[char] = this.measureText(char);
}
}
}
return result;
}
protected splitText() {
const {pureText: text, letterSpacing, lineSpacing, lineHeight, isBmpMode, transform: {explicitWidth, explicitHeight}} = this;
this.measureCache = {};
let textWidth = 0, textHeight = 0, maxHeight = 0;
let rows = [], measureResult;
if (text && text.length > 0) {
if (isNaN(explicitWidth)) {
const lines = text.split('\n');
for (const line of lines) {
measureResult = this.measureText(line);
const mw = measureResult.width;
if (mw > textWidth) {
textWidth = mw;
}
if (isBmpMode) {
const mh = measureResult.height;
if (mh > maxHeight) {
maxHeight = mh;
}
}
rows.push({
text: line,
lineWidth: mw,
});
}
if (!isBmpMode) {
maxHeight = lineHeight;
}
this._bmpLineHeight = maxHeight;
} else {
const chars = text.split('');
let lineWidth = 0, charWidth = 0, index = 0;
let line = '';
for (let i = 0, li = chars.length; i < li; i++) {
const char = chars[i];
if (char == '\n') {
rows.push({
text: line,
lineWidth,
});
line = '';
lineWidth = 0;
index = 0;
} else {
measureResult = this.measureText(char);
if (measureResult.width == 0) {
continue;
}
charWidth = measureResult.width;
const mh = measureResult.height;
if (mh > maxHeight) {
maxHeight = mh;
}
if (index > 0 && lineWidth + charWidth + (index == 0 ? 0 : letterSpacing) > explicitWidth) {
rows.push({
text: line,
lineWidth,
});
line = '';
lineWidth = 0;
index = 0;
}
line += char;
lineWidth += charWidth + (index == 0 ? 0 : letterSpacing);
index++;
}
}
this._bmpLineHeight = maxHeight;
rows.push({
text: line,
lineWidth,
});
textWidth = explicitWidth;
}
textHeight = isNaN(explicitHeight) ? (
maxHeight * rows.length + lineSpacing * (rows.length - 1)
) : explicitHeight;
} else {
textWidth = isNaN(explicitWidth) ? 0 : explicitWidth;
textHeight = isNaN(explicitHeight) ? 0 : explicitHeight;
}
this.rows = rows;
this._textWidth = textWidth;
this._textHeight = textHeight;
return {
rows,
textWidth,
textHeight,
};
}
/**
* @inheritDoc
*/
measureBounds() {
if (!this.dirty) {
return;
}
if (!this.isBmpMode) {
this.applyTextStyle();
}
this.splitText();
super.measureBounds();
}
}
/**
* Created by rockyl on 2018/11/6.
*/
import Renderer from "./Renderer";
import {Texture, decorators} from "scilla";
const {dirtyFieldDetector} = decorators;
export enum FillMode {
/**
* 正常
*/
NORMAL,
/**
* 裁切
*/
SLICED,
/**
* 瓦片
*/
TILED,
}
/**
* 纹理渲染组件
*/
export default class TextureRenderer extends Renderer {
/**
* 纹理资源
*/
@dirtyFieldDetector
texture: Texture;
/**
* 填充模式
*/
@dirtyFieldDetector
fillMode: FillMode = FillMode.NORMAL;
/**
* 滤镜数组
*/
@dirtyFieldDetector
filters = [];
private get hasFilters() {
return this.filters && this.filters.length > 0;
}
/**
* 异步资源
* @param promise
*/
private set async_texture(promise: Promise<Texture>) {
if(!promise){
return;
}
promise.then(
(texture) => {
this.texture = texture;
}
)
}
/**
* @inheritDoc
*/
draw() {
super.draw();
this.drawImage();
this.applyFilters();
/*const {context, texture, hasFilters} = this;
if (texture && hasFilters) {
const {bounds: {width: textureWidth, height: textureHeight}} = texture;
//筛选阴影滤镜Shadow
let s = this;
let cf = s.filters;
let cfLen = cf.length;
let fId = -1;
if (cfLen) {
for (let i = 0; i < cfLen; i++) {
if (s.filters[i].type == "Shadow") {
fId = i;
break;
}
}
}
if (fId >= 0) {
let ctx: any = context;
ctx.shadowBlur = cf[fId].blur;
ctx.shadowColor = cf[fId].color;
ctx.shadowOffsetX = cf[fId].offsetX;
ctx.shadowOffsetY = cf[fId].offsetY;
ctx.drawImage(this.cacheCanvas, 0, 0, textureWidth, textureHeight);
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
} else {
context.drawImage(this.cacheCanvas, 0, 0, textureWidth, textureHeight);
}
// context.drawImage(texture.img, x, y, textureWidth, textureHeight, -width * this.anchor.x, -height * this.anchor.y, width, height);
}*/
}
/**
* 应用滤镜
*/
applyFilters() {
if (!this.hasFilters) return;
const {texture, filters, context} = this;
const {bounds: {width: textureWidth, height: textureHeight}} = texture;
let imageData = context.getImageData(0, 0, textureWidth, textureHeight);
for (const filter of filters) {
filter.drawFilter(imageData);
}
context.putImageData(imageData, 0, 0);
}
/**
* 根据模式绘制图片
*/
drawImage() {
if (!this.texture) {
return;
}
const {texture, fillMode, context, bounds: {width, height}} = this;
const {bounds: {x, y, width: textureWidth, height: textureHeight}} = texture;
switch (fillMode) {
case FillMode.NORMAL:
texture.drawToCanvas(context);
break;
case FillMode.SLICED:
break;
case FillMode.TILED:
const textureCanvas = texture.getCacheCanvas();
const pattern = context.createPattern(textureCanvas, 'repeat');
context.rect(0, 0, width, height);
context.fillStyle = pattern;
context.fill();
break;
}
}
/**
* @inheritDoc
*/
measureBounds() {
if (!this.dirty) {
return;
}
const {bounds, transform: {explicitWidth: tWidth, explicitHeight: tHeight}} = this;
if (this.texture) {
const {width: textureWidth, height: textureHeight} = this.texture;
bounds.width = isNaN(tWidth) ? textureWidth : tWidth;
bounds.height = isNaN(tHeight) ? textureHeight : tHeight;
} else {
bounds.width = isNaN(tWidth) ? 0 : tWidth;
bounds.height = isNaN(tHeight) ? 0 : tHeight;
}
super.measureBounds();
}
}
/**
* Created by rockyl on 2019-01-10.
*/
export {default as CircleRenderer} from './CircleRenderer'
export {default as FrameAnimationRenderer} from './FrameAnimationRenderer'
export {default as GraphicRenderer} from './GraphicRenderer'
export {default as LineRenderer} from './LineRenderer'
export {default as RectRenderer} from './RectRenderer'
export {default as Renderer} from './Renderer'
export {default as TextRenderer} from './TextRenderer'
export {default as TextureRenderer} from './TextureRenderer'
/**
* Created by rockyl on 2018/11/23.
*
* 按钮
*/
import {ScillaEvent, Texture,} from "scilla";
import TouchZoom from "../animation/TouchZoom";
import {InteractComponent} from "../base";
import {TextureRenderer} from "../renderer";
export default class Button extends InteractComponent {
upRes: Texture;
downRes: Texture;
disabledRes: Texture;
onClick: ScillaEvent;
private bgRenderer: TextureRenderer;
private currentRes: Texture;
private touchBeginWithSelf: boolean;
private touchOut: boolean;
constructor() {
super();
this.touchInterrupt = true;
}
get touchZoom(): TouchZoom{
return this.entity && this.entity.getComponent(TouchZoom);
}
onModify(value, key, oldValue) {
super.onModify(value, key, oldValue);
if (key === 'interactable') {
if(this.touchZoom){
this.touchZoom.interactable = value;
}
try {
this.changeTexture();
}catch (e) {}
}
}
onCreate() {
super.onCreate();
this.onClick = new ScillaEvent();
}
onAwake() {
super.onAwake();
this.bgRenderer = this.entity.getComponent(TextureRenderer);
this.changeTexture(this.upRes);
}
onTouchBegin(e) {
super.onTouchBegin(e);
this.touchBeginWithSelf = true;
this.changeTexture(this.downRes);
}
onTouchOver(e) {
super.onTouchOver(e);
if (this.touchBeginWithSelf) {
this.touchBeginWithSelf = true;
this.changeTexture(this.downRes);
}
this.touchOut = false;
}
onTouchOut(e) {
super.onTouchOut(e);
if (this.touchBeginWithSelf) {
this.changeTexture(this.upRes);
}
this.touchOut = true;
}
onGlobalTouchEnd(e): boolean {
if (this.touchBeginWithSelf && !this.touchOut) {
this.onClick.invoke();
}
this.touchBeginWithSelf = false;
this.changeTexture(this.upRes);
return super.onGlobalTouchEnd(e);
}
changeTexture(res?) {
if(!this.bgRenderer){
return;
}
this.currentRes = res || this.upRes;
if(this.interactable){
this.bgRenderer.texture = this.currentRes;
}else{
this.bgRenderer.texture = this.disabledRes;
}
}
}
/**
* Created by rockyl on 2018-12-26.
*
* 进度条
*/
import {Entity, decorators, createTween, ease} from "scilla";
import RectRenderer from "../renderer/RectRenderer";
import Transform from "../base/Transform";
import TextRenderer from "../renderer/TextRenderer";
import ScillaComponent from "../base/ScillaComponent";
const {dirtyFieldTrigger} = decorators;
function renderLabelFuncSample(value, maximum, minimum){
return Math.floor(value / (maximum - minimum) * 100) + '%';
}
export default class ProgressBar extends ScillaComponent {
viewport: Entity;
thumb: Entity;
widget: Entity;
label: Entity;
@dirtyFieldTrigger
value: number = 0;
@dirtyFieldTrigger
minimum: number = 0;
@dirtyFieldTrigger
maximum: number = 0;
@dirtyFieldTrigger
snapInterval: number = 1;
@dirtyFieldTrigger
renderLabelFunc: Function;
@dirtyFieldTrigger
fixWithRange: boolean = true;
private _mask: RectRenderer;
private _widgetTransform: Transform;
private _label: TextRenderer;
private _thumbSize: any;
onCreate() {
super.onCreate();
this.renderLabelFunc = renderLabelFuncSample;
}
onAwake() {
super.onAwake();
this._mask = this.viewport.getComponent(RectRenderer);
this._mask.width = 0;
if(this.widget){
this._widgetTransform = this.widget.getComponent(Transform);
}
this._label = this.label.getComponent(TextRenderer);
this.callOnNextTick(this.updateThumbSize);
}
private updateThumbSize=()=>{
const {width, height} = this.thumb.getComponent(Transform);
this._thumbSize = {width, height};
this.update();
};
onModify(value, key, oldValue) {
super.onModify(value, key, oldValue);
if(oldValue === undefined){
return;
}
this.callOnNextTick(this.update);
}
private update(){
const {minimum, maximum, _thumbSize} = this;
if(!_thumbSize){
return ;
}
const range = maximum - minimum;
let value = Math.max(minimum, Math.min(maximum, this.value));
const percentage = (value - minimum) / range;
const width = percentage * _thumbSize.width;
//this._mask.width = width;
createTween(this, this._mask, true)
.to({width}, 300, ease.cubicOut);
if(this._widgetTransform){
this._widgetTransform.position.x = width;
}
let renderValue = this.fixWithRange ? Math.max(minimum, Math.min(maximum, this.value)) : this.value;
this.value = value;
if(this._label){
let text = this.renderLabelFunc(renderValue, this.maximum, this.minimum);
if(typeof text == 'string'){
this._label.text = text;
this._label.textFlow = null;
}else{
this._label.textFlow = text;
this._label.updateTextFlow();
}
}
}
}
/**
* Created by rockyl on 2018-12-13.
*
* 滚动视图组件
*/
import {Entity, Size, createTween, createVector2D, Vector2D, ease} from "scilla";
import InteractComponent from "../base/InteractComponent";
import Transform from "../base/Transform";
enum LockingType {
NOSET,
HORIZON,
VERTICAL,
}
export default class ScrollView extends InteractComponent {
viewport: Entity;
content: Entity;
lockingType: LockingType = LockingType.NOSET;
private _beginPos: any;
private _lastPos: Vector2D = createVector2D();
private _viewportTransform: Transform;
private _contentTransform: Transform;
private _posOffset: any;
private _posRange: Size;
private _speed: Vector2D = createVector2D();
onAwake() {
super.onAwake();
this._contentTransform = this.content.getComponent(Transform);
this._viewportTransform = this.viewport.getComponent(Transform);
this.callOnNextTick(this.updatePosOffset);
}
updatePosOffset = ()=>{
const {position: {x: x, y: y}} = this._contentTransform;
this._posOffset = {x, y};
//console.log(this._posOffset);
}
updatePosRange = () => {
const {width: pWidth, height: pHeight} = this._viewportTransform;
const {width, height} = this._contentTransform;
this._posRange = new Size(pWidth - width, pHeight - height);
//console.log(this._posRange);
};
onTouchBegin(e) {
super.onTouchBegin(e);
this.updatePosRange();
const {x: tx, y: ty} = e;
const {_contentTransform: {position: {x: cx, y: cy}}} = this;
this._beginPos = {
tx,
ty,
cx,
cy,
};
this._lastPos.setXY(tx, ty);
}
onGlobalTouchMove(e): boolean {
super.onGlobalTouchMove(e);
if (!this._beginPos) {
return;
}
const {
_beginPos: {tx, ty, cx, cy},
_posOffset: {x: offX, y: offY},
_contentTransform: {position},
lockingType,
} = this;
const {x, y} = e;
let px = x - tx + cx;
let py = y - ty + cy;
const {width: rWidth, height: rHeight} = this._posRange;
const halfWidth = Math.abs( rWidth / 2);
const paddingX = halfWidth - Math.abs(offX - halfWidth - px);
if(paddingX < 0){
px += paddingX * 0.8 * (x - tx > 0 ? 1 : -1);
}
const halfHeight = Math.abs( rHeight / 2);
const paddingY = halfHeight - Math.abs(offY - halfHeight - py);
if(paddingY < 0){
py += paddingY * 0.8 * (y - ty > 0 ? 1 : -1);
}
switch (lockingType) {
case LockingType.HORIZON:
position.y = py;
break;
case LockingType.VERTICAL:
position.x = px;
break;
default:
position.setXY(px, py);
}
this._speed.copyFrom(this._lastPos.subtract({x, y}));
this._lastPos.setXY(x, y);
}
onGlobalTouchEnd(e): boolean {
super.onGlobalTouchEnd(e);
if (!this._beginPos) {
return;
}
this._beginPos = null;
const {x: offX, y: offY} = this._posOffset;
const {width: rWidth, height: rHeight} = this._posRange;
const {position, position: {x, y}} = this._contentTransform;
const tx = Math.min(Math.max(offX + rWidth, x), offX);
const ty = Math.min(Math.max(offY + rHeight, y), offY);
const targetPos = createVector2D(tx, ty);
const duration = Math.min(500, Math.max(targetPos.distance(position), 200));
createTween(this, this._contentTransform, true, {clazz: Vector2D, fields: ['x', 'y']})
.to({position: targetPos}, duration, ease.cubicOut);
}
}
/**
* Created by rockyl on 2019-01-10.
*/
export {default as Button} from './Button'
export {default as ProgressBar} from './ProgressBar'
export {default as ScrollView} from './ScrollView'
{
"compilerOptions": {
"target": "es5",
"outDir": "dist",
"experimentalDecorators": true,
"sourceMap": true,
"declarationDir": "types",
"declaration": true,
"lib": [
"es5",
"es6",
"dom",
"es2015.promise"
],
"baseUrl": "./",
"paths": {
"scilla": ["node_modules/scilla/src"]
}
},
"include": [
"src"
]
}
\ No newline at end of file
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@babel/code-frame@^7.0.0":
version "7.0.0"
resolved "http://registry.npm.taobao.org/@babel/code-frame/download/@babel/code-frame-7.0.0.tgz#06e2ab19bdb535385559aabb5ba59729482800f8"
integrity sha1-BuKrGb21NThVWaq7W6WXKUgoAPg=
dependencies:
"@babel/highlight" "^7.0.0"
"@babel/highlight@^7.0.0":
version "7.0.0"
resolved "http://registry.npm.taobao.org/@babel/highlight/download/@babel/highlight-7.0.0.tgz#f710c38c8d458e6dd9a201afb637fcb781ce99e4"
integrity sha1-9xDDjI1Fjm3ZogGvtjf8t4HOmeQ=
dependencies:
chalk "^2.0.0"
esutils "^2.0.2"
js-tokens "^4.0.0"
"@types/node@*":
version "11.12.0"
resolved "http://registry.npm.taobao.org/@types/node/download/@types/node-11.12.0.tgz#ec5594728811dc2797e42396cfcdf786f2052c12"
integrity sha1-7FWUcogR3CeX5COWz833hvIFLBI=
ansi-styles@^3.2.1:
version "3.2.1"
resolved "http://registry.npm.taobao.org/ansi-styles/download/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d"
integrity sha1-QfuyAkPlCxK+DwS43tvwdSDOhB0=
dependencies:
color-convert "^1.9.0"
arr-diff@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/arr-diff/download/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520"
integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=
arr-flatten@^1.1.0:
version "1.1.0"
resolved "http://registry.npm.taobao.org/arr-flatten/download/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1"
integrity sha1-NgSLv/TntH4TZkQxbJlmnqWukfE=
arr-union@^3.1.0:
version "3.1.0"
resolved "http://registry.npm.taobao.org/arr-union/download/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4"
integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=
array-unique@^0.3.2:
version "0.3.2"
resolved "http://registry.npm.taobao.org/array-unique/download/array-unique-0.3.2.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Farray-unique%2Fdownload%2Farray-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428"
integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=
assign-symbols@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/assign-symbols/download/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367"
integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=
atob@^2.1.1:
version "2.1.2"
resolved "http://registry.npm.taobao.org/atob/download/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9"
integrity sha1-bZUX654DDSQ2ZmZR6GvZ9vE1M8k=
balanced-match@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/balanced-match/download/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c=
base@^0.11.1:
version "0.11.2"
resolved "http://registry.npm.taobao.org/base/download/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f"
integrity sha1-e95c7RRbbVUakNuH+DxVi060io8=
dependencies:
cache-base "^1.0.1"
class-utils "^0.3.5"
component-emitter "^1.2.1"
define-property "^1.0.0"
isobject "^3.0.1"
mixin-deep "^1.2.0"
pascalcase "^0.1.1"
brace-expansion@^1.1.7:
version "1.1.11"
resolved "http://registry.npm.taobao.org/brace-expansion/download/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
integrity sha1-PH/L9SnYcibz0vUrlm/1Jx60Qd0=
dependencies:
balanced-match "^1.0.0"
concat-map "0.0.1"
braces@^2.3.1:
version "2.3.2"
resolved "http://registry.npm.taobao.org/braces/download/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729"
integrity sha1-WXn9PxTNUxVl5fot8av/8d+u5yk=
dependencies:
arr-flatten "^1.1.0"
array-unique "^0.3.2"
extend-shallow "^2.0.1"
fill-range "^4.0.0"
isobject "^3.0.1"
repeat-element "^1.1.2"
snapdragon "^0.8.1"
snapdragon-node "^2.0.1"
split-string "^3.0.2"
to-regex "^3.0.1"
builtin-modules@^3.0.0:
version "3.0.0"
resolved "http://registry.npm.taobao.org/builtin-modules/download/builtin-modules-3.0.0.tgz#1e587d44b006620d90286cc7a9238bbc6129cab1"
integrity sha1-Hlh9RLAGYg2QKGzHqSOLvGEpyrE=
cache-base@^1.0.1:
version "1.0.1"
resolved "http://registry.npm.taobao.org/cache-base/download/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2"
integrity sha1-Cn9GQWgxyLZi7jb+TnxZ129marI=
dependencies:
collection-visit "^1.0.0"
component-emitter "^1.2.1"
get-value "^2.0.6"
has-value "^1.0.0"
isobject "^3.0.1"
set-value "^2.0.0"
to-object-path "^0.3.0"
union-value "^1.0.0"
unset-value "^1.0.0"
chalk@^2.0.0:
version "2.4.2"
resolved "http://registry.npm.taobao.org/chalk/download/chalk-2.4.2.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Fchalk%2Fdownload%2Fchalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424"
integrity sha1-zUJUFnelQzPPVBpJEIwUMrRMlCQ=
dependencies:
ansi-styles "^3.2.1"
escape-string-regexp "^1.0.5"
supports-color "^5.3.0"
class-utils@^0.3.5:
version "0.3.6"
resolved "http://registry.npm.taobao.org/class-utils/download/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463"
integrity sha1-+TNprouafOAv1B+q0MqDAzGQxGM=
dependencies:
arr-union "^3.1.0"
define-property "^0.2.5"
isobject "^3.0.0"
static-extend "^0.1.1"
collection-visit@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/collection-visit/download/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0"
integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=
dependencies:
map-visit "^1.0.0"
object-visit "^1.0.0"
color-convert@^1.9.0:
version "1.9.3"
resolved "http://registry.npm.taobao.org/color-convert/download/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"
integrity sha1-u3GFBpDh8TZWfeYp0tVHHe2kweg=
dependencies:
color-name "1.1.3"
color-name@1.1.3:
version "1.1.3"
resolved "http://registry.npm.taobao.org/color-name/download/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=
commander@~2.19.0:
version "2.19.0"
resolved "http://registry.npm.taobao.org/commander/download/commander-2.19.0.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Fcommander%2Fdownload%2Fcommander-2.19.0.tgz#f6198aa84e5b83c46054b94ddedbfed5ee9ff12a"
integrity sha1-9hmKqE5bg8RgVLlN3tv+1e6f8So=
component-emitter@^1.2.1:
version "1.2.1"
resolved "http://registry.npm.taobao.org/component-emitter/download/component-emitter-1.2.1.tgz#137918d6d78283f7df7a6b7c5a63e140e69425e6"
integrity sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=
concat-map@0.0.1:
version "0.0.1"
resolved "http://registry.npm.taobao.org/concat-map/download/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=
copy-descriptor@^0.1.0:
version "0.1.1"
resolved "http://registry.npm.taobao.org/copy-descriptor/download/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d"
integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=
core-util-is@~1.0.0:
version "1.0.2"
resolved "http://registry.npm.taobao.org/core-util-is/download/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=
debug@^2.2.0, debug@^2.3.3:
version "2.6.9"
resolved "http://registry.npm.taobao.org/debug/download/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
integrity sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=
dependencies:
ms "2.0.0"
decode-uri-component@^0.2.0:
version "0.2.0"
resolved "http://registry.npm.taobao.org/decode-uri-component/download/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545"
integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=
define-property@^0.2.5:
version "0.2.5"
resolved "http://registry.npm.taobao.org/define-property/download/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116"
integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=
dependencies:
is-descriptor "^0.1.0"
define-property@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/define-property/download/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6"
integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY=
dependencies:
is-descriptor "^1.0.0"
define-property@^2.0.2:
version "2.0.2"
resolved "http://registry.npm.taobao.org/define-property/download/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d"
integrity sha1-1Flono1lS6d+AqgX+HENcCyxbp0=
dependencies:
is-descriptor "^1.0.2"
isobject "^3.0.1"
escape-string-regexp@^1.0.5:
version "1.0.5"
resolved "http://registry.npm.taobao.org/escape-string-regexp/download/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=
estree-walker@^0.6.0:
version "0.6.0"
resolved "http://registry.npm.taobao.org/estree-walker/download/estree-walker-0.6.0.tgz#5d865327c44a618dde5699f763891ae31f257dae"
integrity sha1-XYZTJ8RKYY3eVpn3Y4ka4x8lfa4=
esutils@^2.0.2:
version "2.0.2"
resolved "http://registry.npm.taobao.org/esutils/download/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b"
integrity sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=
expand-brackets@^2.1.4:
version "2.1.4"
resolved "http://registry.npm.taobao.org/expand-brackets/download/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622"
integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI=
dependencies:
debug "^2.3.3"
define-property "^0.2.5"
extend-shallow "^2.0.1"
posix-character-classes "^0.1.0"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.1"
extend-shallow@^2.0.1:
version "2.0.1"
resolved "http://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f"
integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=
dependencies:
is-extendable "^0.1.0"
extend-shallow@^3.0.0, extend-shallow@^3.0.2:
version "3.0.2"
resolved "http://registry.npm.taobao.org/extend-shallow/download/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8"
integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=
dependencies:
assign-symbols "^1.0.0"
is-extendable "^1.0.1"
extglob@^2.0.4:
version "2.0.4"
resolved "http://registry.npm.taobao.org/extglob/download/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543"
integrity sha1-rQD+TcYSqSMuhxhxHcXLWrAoVUM=
dependencies:
array-unique "^0.3.2"
define-property "^1.0.0"
expand-brackets "^2.1.4"
extend-shallow "^2.0.1"
fragment-cache "^0.2.1"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.1"
fill-range@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/fill-range/download/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7"
integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=
dependencies:
extend-shallow "^2.0.1"
is-number "^3.0.0"
repeat-string "^1.6.1"
to-regex-range "^2.1.0"
for-in@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/for-in/download/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=
fragment-cache@^0.2.1:
version "0.2.1"
resolved "http://registry.npm.taobao.org/fragment-cache/download/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19"
integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=
dependencies:
map-cache "^0.2.2"
fs-extra@7.0.1:
version "7.0.1"
resolved "http://registry.npm.taobao.org/fs-extra/download/fs-extra-7.0.1.tgz#4f189c44aa123b895f722804f55ea23eadc348e9"
integrity sha1-TxicRKoSO4lfcigE9V6iPq3DSOk=
dependencies:
graceful-fs "^4.1.2"
jsonfile "^4.0.0"
universalify "^0.1.0"
fs.realpath@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/fs.realpath/download/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8=
get-value@^2.0.3, get-value@^2.0.6:
version "2.0.6"
resolved "http://registry.npm.taobao.org/get-value/download/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28"
integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=
glob@^7.1.3:
version "7.1.3"
resolved "http://registry.npm.taobao.org/glob/download/glob-7.1.3.tgz#3960832d3f1574108342dafd3a67b332c0969df1"
integrity sha1-OWCDLT8VdBCDQtr9OmezMsCWnfE=
dependencies:
fs.realpath "^1.0.0"
inflight "^1.0.4"
inherits "2"
minimatch "^3.0.4"
once "^1.3.0"
path-is-absolute "^1.0.0"
graceful-fs@^4.1.2, graceful-fs@^4.1.6:
version "4.1.15"
resolved "http://registry.npm.taobao.org/graceful-fs/download/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00"
integrity sha1-/7cD4QZuig7qpMi4C6klPu77+wA=
has-flag@^3.0.0:
version "3.0.0"
resolved "http://registry.npm.taobao.org/has-flag/download/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0=
has-value@^0.3.1:
version "0.3.1"
resolved "http://registry.npm.taobao.org/has-value/download/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f"
integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=
dependencies:
get-value "^2.0.3"
has-values "^0.1.4"
isobject "^2.0.0"
has-value@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/has-value/download/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177"
integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=
dependencies:
get-value "^2.0.6"
has-values "^1.0.0"
isobject "^3.0.0"
has-values@^0.1.4:
version "0.1.4"
resolved "http://registry.npm.taobao.org/has-values/download/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771"
integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E=
has-values@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/has-values/download/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f"
integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=
dependencies:
is-number "^3.0.0"
kind-of "^4.0.0"
inflight@^1.0.4:
version "1.0.6"
resolved "http://registry.npm.taobao.org/inflight/download/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=
dependencies:
once "^1.3.0"
wrappy "1"
inherits@2, inherits@~2.0.3:
version "2.0.3"
resolved "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=
is-accessor-descriptor@^0.1.6:
version "0.1.6"
resolved "http://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6"
integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=
dependencies:
kind-of "^3.0.2"
is-accessor-descriptor@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656"
integrity sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=
dependencies:
kind-of "^6.0.0"
is-buffer@^1.1.5:
version "1.1.6"
resolved "http://registry.npm.taobao.org/is-buffer/download/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
integrity sha1-76ouqdqg16suoTqXsritUf776L4=
is-data-descriptor@^0.1.4:
version "0.1.4"
resolved "http://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56"
integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=
dependencies:
kind-of "^3.0.2"
is-data-descriptor@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7"
integrity sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=
dependencies:
kind-of "^6.0.0"
is-descriptor@^0.1.0:
version "0.1.6"
resolved "http://registry.npm.taobao.org/is-descriptor/download/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca"
integrity sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=
dependencies:
is-accessor-descriptor "^0.1.6"
is-data-descriptor "^0.1.4"
kind-of "^5.0.0"
is-descriptor@^1.0.0, is-descriptor@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/is-descriptor/download/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec"
integrity sha1-OxWXRqZmBLBPjIFSS6NlxfFNhuw=
dependencies:
is-accessor-descriptor "^1.0.0"
is-data-descriptor "^1.0.0"
kind-of "^6.0.2"
is-extendable@^0.1.0, is-extendable@^0.1.1:
version "0.1.1"
resolved "http://registry.npm.taobao.org/is-extendable/download/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89"
integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=
is-extendable@^1.0.1:
version "1.0.1"
resolved "http://registry.npm.taobao.org/is-extendable/download/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4"
integrity sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=
dependencies:
is-plain-object "^2.0.4"
is-module@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/is-module/download/is-module-1.0.0.tgz#3258fb69f78c14d5b815d664336b4cffb6441591"
integrity sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=
is-number@^3.0.0:
version "3.0.0"
resolved "http://registry.npm.taobao.org/is-number/download/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195"
integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=
dependencies:
kind-of "^3.0.2"
is-plain-object@^2.0.1, is-plain-object@^2.0.3, is-plain-object@^2.0.4:
version "2.0.4"
resolved "http://registry.npm.taobao.org/is-plain-object/download/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677"
integrity sha1-LBY7P6+xtgbZ0Xko8FwqHDjgdnc=
dependencies:
isobject "^3.0.1"
is-windows@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/is-windows/download/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"
integrity sha1-0YUOuXkezRjmGCzhKjDzlmNLsZ0=
isarray@1.0.0, isarray@~1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/isarray/download/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=
isobject@^2.0.0:
version "2.1.0"
resolved "http://registry.npm.taobao.org/isobject/download/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89"
integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=
dependencies:
isarray "1.0.0"
isobject@^3.0.0, isobject@^3.0.1:
version "3.0.1"
resolved "http://registry.npm.taobao.org/isobject/download/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df"
integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8=
jest-worker@^24.0.0:
version "24.4.0"
resolved "http://registry.npm.taobao.org/jest-worker/download/jest-worker-24.4.0.tgz#fbc452b0120bb5c2a70cdc88fa132b48eeb11dd0"
integrity sha1-+8RSsBILtcKnDNyI+hMrSO6xHdA=
dependencies:
"@types/node" "*"
merge-stream "^1.0.1"
supports-color "^6.1.0"
js-tokens@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/js-tokens/download/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
integrity sha1-GSA/tZmR35jjoocFDUZHzerzJJk=
jsonfile@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/jsonfile/download/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb"
integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=
optionalDependencies:
graceful-fs "^4.1.6"
kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0:
version "3.2.2"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64"
integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=
dependencies:
is-buffer "^1.1.5"
kind-of@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57"
integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc=
dependencies:
is-buffer "^1.1.5"
kind-of@^5.0.0:
version "5.1.0"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d"
integrity sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=
kind-of@^6.0.0, kind-of@^6.0.2:
version "6.0.2"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-6.0.2.tgz#01146b36a6218e64e58f3a8d66de5d7fc6f6d051"
integrity sha1-ARRrNqYhjmTljzqNZt5df8b20FE=
magic-string@^0.25.2:
version "0.25.2"
resolved "http://registry.npm.taobao.org/magic-string/download/magic-string-0.25.2.tgz#139c3a729515ec55e96e69e82a11fe890a293ad9"
integrity sha1-E5w6cpUV7FXpbmnoKhH+iQopOtk=
dependencies:
sourcemap-codec "^1.4.4"
map-cache@^0.2.2:
version "0.2.2"
resolved "http://registry.npm.taobao.org/map-cache/download/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf"
integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=
map-visit@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/map-visit/download/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f"
integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=
dependencies:
object-visit "^1.0.0"
merge-stream@^1.0.1:
version "1.0.1"
resolved "http://registry.npm.taobao.org/merge-stream/download/merge-stream-1.0.1.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Fmerge-stream%2Fdownload%2Fmerge-stream-1.0.1.tgz#4041202d508a342ba00174008df0c251b8c135e1"
integrity sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=
dependencies:
readable-stream "^2.0.1"
micromatch@^3.1.10:
version "3.1.10"
resolved "http://registry.npm.taobao.org/micromatch/download/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23"
integrity sha1-cIWbyVyYQJUvNZoGij/En57PrCM=
dependencies:
arr-diff "^4.0.0"
array-unique "^0.3.2"
braces "^2.3.1"
define-property "^2.0.2"
extend-shallow "^3.0.2"
extglob "^2.0.4"
fragment-cache "^0.2.1"
kind-of "^6.0.2"
nanomatch "^1.2.9"
object.pick "^1.3.0"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.2"
minimatch@^3.0.4:
version "3.0.4"
resolved "http://registry.npm.taobao.org/minimatch/download/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
integrity sha1-UWbihkV/AzBgZL5Ul+jbsMPTIIM=
dependencies:
brace-expansion "^1.1.7"
mixin-deep@^1.2.0:
version "1.3.1"
resolved "http://registry.npm.taobao.org/mixin-deep/download/mixin-deep-1.3.1.tgz#a49e7268dce1a0d9698e45326c5626df3543d0fe"
integrity sha1-pJ5yaNzhoNlpjkUybFYm3zVD0P4=
dependencies:
for-in "^1.0.2"
is-extendable "^1.0.1"
ms@2.0.0:
version "2.0.0"
resolved "http://registry.npm.taobao.org/ms/download/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=
nanomatch@^1.2.9:
version "1.2.13"
resolved "http://registry.npm.taobao.org/nanomatch/download/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
integrity sha1-uHqKpPwN6P5r6IiVs4mD/yZb0Rk=
dependencies:
arr-diff "^4.0.0"
array-unique "^0.3.2"
define-property "^2.0.2"
extend-shallow "^3.0.2"
fragment-cache "^0.2.1"
is-windows "^1.0.2"
kind-of "^6.0.2"
object.pick "^1.3.0"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.1"
object-copy@^0.1.0:
version "0.1.0"
resolved "http://registry.npm.taobao.org/object-copy/download/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c"
integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw=
dependencies:
copy-descriptor "^0.1.0"
define-property "^0.2.5"
kind-of "^3.0.3"
object-visit@^1.0.0:
version "1.0.1"
resolved "http://registry.npm.taobao.org/object-visit/download/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb"
integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=
dependencies:
isobject "^3.0.0"
object.pick@^1.3.0:
version "1.3.0"
resolved "http://registry.npm.taobao.org/object.pick/download/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747"
integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=
dependencies:
isobject "^3.0.1"
once@^1.3.0:
version "1.4.0"
resolved "http://registry.npm.taobao.org/once/download/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=
dependencies:
wrappy "1"
pascalcase@^0.1.1:
version "0.1.1"
resolved "http://registry.npm.taobao.org/pascalcase/download/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14"
integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=
path-is-absolute@^1.0.0:
version "1.0.1"
resolved "http://registry.npm.taobao.org/path-is-absolute/download/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18=
path-parse@^1.0.6:
version "1.0.6"
resolved "http://registry.npm.taobao.org/path-parse/download/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c"
integrity sha1-1i27VnlAXXLEc37FhgDp3c8G0kw=
posix-character-classes@^0.1.0:
version "0.1.1"
resolved "http://registry.npm.taobao.org/posix-character-classes/download/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab"
integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=
process-nextick-args@~2.0.0:
version "2.0.0"
resolved "http://registry.npm.taobao.org/process-nextick-args/download/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa"
integrity sha1-o31zL0JxtKsa0HDTVQjoKQeI/6o=
readable-stream@^2.0.1:
version "2.3.6"
resolved "http://registry.npm.taobao.org/readable-stream/download/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf"
integrity sha1-sRwn2IuP8fvgcGQ8+UsMea4bCq8=
dependencies:
core-util-is "~1.0.0"
inherits "~2.0.3"
isarray "~1.0.0"
process-nextick-args "~2.0.0"
safe-buffer "~5.1.1"
string_decoder "~1.1.1"
util-deprecate "~1.0.1"
regex-not@^1.0.0, regex-not@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/regex-not/download/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c"
integrity sha1-H07OJ+ALC2XgJHpoEOaoXYOldSw=
dependencies:
extend-shallow "^3.0.2"
safe-regex "^1.1.0"
repeat-element@^1.1.2:
version "1.1.3"
resolved "http://registry.npm.taobao.org/repeat-element/download/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce"
integrity sha1-eC4NglwMWjuzlzH4Tv7mt0Lmsc4=
repeat-string@^1.6.1:
version "1.6.1"
resolved "http://registry.npm.taobao.org/repeat-string/download/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"
integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc=
resolve-url@^0.2.1:
version "0.2.1"
resolved "http://registry.npm.taobao.org/resolve-url/download/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a"
integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=
resolve@1.10.0, resolve@^1.10.0:
version "1.10.0"
resolved "http://registry.npm.taobao.org/resolve/download/resolve-1.10.0.tgz#3bdaaeaf45cc07f375656dfd2e54ed0810b101ba"
integrity sha1-O9qur0XMB/N1ZW39LlTtCBCxAbo=
dependencies:
path-parse "^1.0.6"
ret@~0.1.10:
version "0.1.15"
resolved "http://registry.npm.taobao.org/ret/download/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc"
integrity sha1-uKSCXVvbH8P29Twrwz+BOIaBx7w=
rollup-plugin-commonjs@^9.2.2:
version "9.2.2"
resolved "http://registry.npm.taobao.org/rollup-plugin-commonjs/download/rollup-plugin-commonjs-9.2.2.tgz#4959f3ff0d9706c132e5247b47ab385f11d9aae6"
integrity sha1-SVnz/w2XBsEy5SR7R6s4XxHZquY=
dependencies:
estree-walker "^0.6.0"
magic-string "^0.25.2"
resolve "^1.10.0"
rollup-pluginutils "^2.5.0"
rollup-plugin-node-resolve@^4.0.1:
version "4.0.1"
resolved "http://registry.npm.taobao.org/rollup-plugin-node-resolve/download/rollup-plugin-node-resolve-4.0.1.tgz#f95765d174e5daeef9ea6268566141f53aa9d422"
integrity sha1-+Vdl0XTl2u756mJoVmFB9Tqp1CI=
dependencies:
builtin-modules "^3.0.0"
is-module "^1.0.0"
resolve "^1.10.0"
rollup-plugin-typescript2@^0.20.1:
version "0.20.1"
resolved "http://registry.npm.taobao.org/rollup-plugin-typescript2/download/rollup-plugin-typescript2-0.20.1.tgz#fb1d411975cd875d24882ea66f5f4fd11d2f2240"
integrity sha1-+x1BGXXNh10kiC6mb19P0R0vIkA=
dependencies:
fs-extra "7.0.1"
resolve "1.10.0"
rollup-pluginutils "2.4.1"
tslib "1.9.3"
rollup-plugin-uglify@^6.0.2:
version "6.0.2"
resolved "http://registry.npm.taobao.org/rollup-plugin-uglify/download/rollup-plugin-uglify-6.0.2.tgz#681042cfdf7ea4e514971946344e1a95bc2772fe"
integrity sha1-aBBCz99+pOUUlxlGNE4albwncv4=
dependencies:
"@babel/code-frame" "^7.0.0"
jest-worker "^24.0.0"
serialize-javascript "^1.6.1"
uglify-js "^3.4.9"
rollup-pluginutils@2.4.1:
version "2.4.1"
resolved "http://registry.npm.taobao.org/rollup-pluginutils/download/rollup-pluginutils-2.4.1.tgz#de43ab54965bbf47843599a7f3adceb723de38db"
integrity sha1-3kOrVJZbv0eENZmn863OtyPeONs=
dependencies:
estree-walker "^0.6.0"
micromatch "^3.1.10"
rollup-pluginutils@^2.5.0:
version "2.5.0"
resolved "http://registry.npm.taobao.org/rollup-pluginutils/download/rollup-pluginutils-2.5.0.tgz#23be0f05ac3972ea7b08fc7870cb91fde5b23a09"
integrity sha1-I74PBaw5cup7CPx4cMuR/eWyOgk=
dependencies:
estree-walker "^0.6.0"
micromatch "^3.1.10"
safe-buffer@~5.1.0, safe-buffer@~5.1.1:
version "5.1.2"
resolved "http://registry.npm.taobao.org/safe-buffer/download/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
integrity sha1-mR7GnSluAxN0fVm9/St0XDX4go0=
safe-regex@^1.1.0:
version "1.1.0"
resolved "http://registry.npm.taobao.org/safe-regex/download/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e"
integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4=
dependencies:
ret "~0.1.10"
serialize-javascript@^1.6.1:
version "1.6.1"
resolved "http://registry.npm.taobao.org/serialize-javascript/download/serialize-javascript-1.6.1.tgz#4d1f697ec49429a847ca6f442a2a755126c4d879"
integrity sha1-TR9pfsSUKahHym9EKip1USbE2Hk=
set-value@^0.4.3:
version "0.4.3"
resolved "http://registry.npm.taobao.org/set-value/download/set-value-0.4.3.tgz#7db08f9d3d22dc7f78e53af3c3bf4666ecdfccf1"
integrity sha1-fbCPnT0i3H945Trzw79GZuzfzPE=
dependencies:
extend-shallow "^2.0.1"
is-extendable "^0.1.1"
is-plain-object "^2.0.1"
to-object-path "^0.3.0"
set-value@^2.0.0:
version "2.0.0"
resolved "http://registry.npm.taobao.org/set-value/download/set-value-2.0.0.tgz#71ae4a88f0feefbbf52d1ea604f3fb315ebb6274"
integrity sha1-ca5KiPD+77v1LR6mBPP7MV67YnQ=
dependencies:
extend-shallow "^2.0.1"
is-extendable "^0.1.1"
is-plain-object "^2.0.3"
split-string "^3.0.1"
snapdragon-node@^2.0.1:
version "2.1.1"
resolved "http://registry.npm.taobao.org/snapdragon-node/download/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b"
integrity sha1-bBdfhv8UvbByRWPo88GwIaKGhTs=
dependencies:
define-property "^1.0.0"
isobject "^3.0.0"
snapdragon-util "^3.0.1"
snapdragon-util@^3.0.1:
version "3.0.1"
resolved "http://registry.npm.taobao.org/snapdragon-util/download/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2"
integrity sha1-+VZHlIbyrNeXAGk/b3uAXkWrVuI=
dependencies:
kind-of "^3.2.0"
snapdragon@^0.8.1:
version "0.8.2"
resolved "http://registry.npm.taobao.org/snapdragon/download/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d"
integrity sha1-ZJIufFZbDhQgS6GqfWlkJ40lGC0=
dependencies:
base "^0.11.1"
debug "^2.2.0"
define-property "^0.2.5"
extend-shallow "^2.0.1"
map-cache "^0.2.2"
source-map "^0.5.6"
source-map-resolve "^0.5.0"
use "^3.1.0"
source-map-resolve@^0.5.0:
version "0.5.2"
resolved "http://registry.npm.taobao.org/source-map-resolve/download/source-map-resolve-0.5.2.tgz#72e2cc34095543e43b2c62b2c4c10d4a9054f259"
integrity sha1-cuLMNAlVQ+Q7LGKyxMENSpBU8lk=
dependencies:
atob "^2.1.1"
decode-uri-component "^0.2.0"
resolve-url "^0.2.1"
source-map-url "^0.4.0"
urix "^0.1.0"
source-map-url@^0.4.0:
version "0.4.0"
resolved "http://registry.npm.taobao.org/source-map-url/download/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3"
integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=
source-map@^0.5.6:
version "0.5.7"
resolved "http://registry.npm.taobao.org/source-map/download/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=
source-map@~0.6.1:
version "0.6.1"
resolved "http://registry.npm.taobao.org/source-map/download/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
integrity sha1-dHIq8y6WFOnCh6jQu95IteLxomM=
sourcemap-codec@^1.4.4:
version "1.4.4"
resolved "http://registry.npm.taobao.org/sourcemap-codec/download/sourcemap-codec-1.4.4.tgz#c63ea927c029dd6bd9a2b7fa03b3fec02ad56e9f"
integrity sha1-xj6pJ8Ap3WvZorf6A7P+wCrVbp8=
split-string@^3.0.1, split-string@^3.0.2:
version "3.1.0"
resolved "http://registry.npm.taobao.org/split-string/download/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2"
integrity sha1-fLCd2jqGWFcFxks5pkZgOGguj+I=
dependencies:
extend-shallow "^3.0.0"
static-extend@^0.1.1:
version "0.1.2"
resolved "http://registry.npm.taobao.org/static-extend/download/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6"
integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=
dependencies:
define-property "^0.2.5"
object-copy "^0.1.0"
string_decoder@~1.1.1:
version "1.1.1"
resolved "http://registry.npm.taobao.org/string_decoder/download/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8"
integrity sha1-nPFhG6YmhdcDCunkujQUnDrwP8g=
dependencies:
safe-buffer "~5.1.0"
supports-color@^5.3.0:
version "5.5.0"
resolved "http://registry.npm.taobao.org/supports-color/download/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f"
integrity sha1-4uaaRKyHcveKHsCzW2id9lMO/I8=
dependencies:
has-flag "^3.0.0"
supports-color@^6.1.0:
version "6.1.0"
resolved "http://registry.npm.taobao.org/supports-color/download/supports-color-6.1.0.tgz#0764abc69c63d5ac842dd4867e8d025e880df8f3"
integrity sha1-B2Srxpxj1ayELdSGfo0CXogN+PM=
dependencies:
has-flag "^3.0.0"
to-object-path@^0.3.0:
version "0.3.0"
resolved "http://registry.npm.taobao.org/to-object-path/download/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af"
integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=
dependencies:
kind-of "^3.0.2"
to-regex-range@^2.1.0:
version "2.1.1"
resolved "http://registry.npm.taobao.org/to-regex-range/download/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38"
integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=
dependencies:
is-number "^3.0.0"
repeat-string "^1.6.1"
to-regex@^3.0.1, to-regex@^3.0.2:
version "3.0.2"
resolved "http://registry.npm.taobao.org/to-regex/download/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce"
integrity sha1-E8/dmzNlUvMLUfM6iuG0Knp1mc4=
dependencies:
define-property "^2.0.2"
extend-shallow "^3.0.2"
regex-not "^1.0.2"
safe-regex "^1.1.0"
tslib@1.9.3, tslib@^1.9.3:
version "1.9.3"
resolved "http://registry.npm.taobao.org/tslib/download/tslib-1.9.3.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Ftslib%2Fdownload%2Ftslib-1.9.3.tgz#d7e4dd79245d85428c4d7e4822a79917954ca286"
integrity sha1-1+TdeSRdhUKMTX5IIqeZF5VMooY=
typescript@^3.3.4000:
version "3.3.4000"
resolved "http://registry.npm.taobao.org/typescript/download/typescript-3.3.4000.tgz#76b0f89cfdbf97827e1112d64f283f1151d6adf0"
integrity sha1-drD4nP2/l4J+ERLWTyg/EVHWrfA=
uglify-js@^3.4.9:
version "3.5.2"
resolved "http://registry.npm.taobao.org/uglify-js/download/uglify-js-3.5.2.tgz#dc0c7ac2da0a4b7d15e84266818ff30e82529474"
integrity sha1-3Ax6wtoKS30V6EJmgY/zDoJSlHQ=
dependencies:
commander "~2.19.0"
source-map "~0.6.1"
union-value@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/union-value/download/union-value-1.0.0.tgz#5c71c34cb5bad5dcebe3ea0cd08207ba5aa1aea4"
integrity sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=
dependencies:
arr-union "^3.1.0"
get-value "^2.0.6"
is-extendable "^0.1.1"
set-value "^0.4.3"
universalify@^0.1.0:
version "0.1.2"
resolved "http://registry.npm.taobao.org/universalify/download/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66"
integrity sha1-tkb2m+OULavOzJ1mOcgNwQXvqmY=
unset-value@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/unset-value/download/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559"
integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=
dependencies:
has-value "^0.3.1"
isobject "^3.0.0"
urix@^0.1.0:
version "0.1.0"
resolved "http://registry.npm.taobao.org/urix/download/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72"
integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=
use@^3.1.0:
version "3.1.1"
resolved "http://registry.npm.taobao.org/use/download/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f"
integrity sha1-1QyMrHmhn7wg8pEfVuuXP04QBw8=
util-deprecate@~1.0.1:
version "1.0.2"
resolved "http://registry.npm.taobao.org/util-deprecate/download/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=
wrappy@1:
version "1.0.2"
resolved "http://registry.npm.taobao.org/wrappy/download/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
/**
* Created by rockyl on 2018/11/23.
*/
import {Entity, traverse, traversePostorder} from "./Entity";
import {injectProp} from "../tools/utils";
import {setupContext as setupInteractContext} from "./context/InteractContext";
import {clear, ScaleMode, setupContext as setupRenderContext} from "./context/RenderContext";
import './requestAnimationFrame';
/**
* 创建引擎实例
* @param options
*/
export function createEngineInstance(options?) {
let instance = new ScillaEngine();
instance.setup(options);
}
/**
* 引擎类
*/
class ScillaEngine {
/**
* 默认配置
*/
options: any = {
fps: 60,
designWidth: 750,
designHeight: 1334,
scaleMode: ScaleMode.FIXED_WIDTH,
touchEnabled: true,
};
_flush: number = 0;
_currentFlush: number = 0;
tsStart: number;
tsLast: number;
lastFPS: number = 0;
private readonly root: Entity;
constructor() {
this.root = new Entity('root');
this.root._restrict();
}
setup(options?){
injectProp(this.options, options);
const {canvas, designWidth, designHeight, scaleMode, modifyCanvasSize, touchEnabled} = options;
let canvasElement = typeof canvas == 'object' ? canvas : document.getElementById(canvas);
setupInteractContext({
canvas: canvasElement,
touchHandler: {
onTouchBegin: this.onTouchBegin.bind(this),
onTouchMove: this.onTouchMove.bind(this),
onTouchEnd: this.onTouchEnd.bind(this),
},
touchEnabled,
});
setupRenderContext({
canvas: canvasElement,
designWidth,
designHeight,
scaleMode,
modifyCanvasSize,
});
}
/**
* 开始引擎
*/
start() {
this.root.enabled = true;
this.tsStart = Date.now();
this.startTick();
}
/**
* 暂停引擎
*/
pause() {
this.root.enabled = false;
this.stopTick();
}
/**
* 获取节点路径
* @param entity
*/
getEntityPath(entity?: Entity): string {
let path = '';
let current = entity || this.root;
while (current.parent) {
path = current.parent.children.indexOf(current) + (path.length > 0 ? '|' : '') + path;
current = current.parent;
}
return path;
}
/**
* 根据节点路径获取节点
* @param path
*/
getEntityByPath(path?: string): Entity {
let target = this.root;
if (path.length > 0) {
let arr = path.split('|');
for (let item of arr) {
target = target.children[item];
if (!target) {
target = null;
break;
}
}
}
return target;
}
/**
* 获取当前帧率
*/
get fps() {
return this.lastFPS;
}
/**
* 开始时钟
*/
private startTick() {
this._flush = 60 / this.options.fps - 1 >> 0;
if (this._flush < 0) {
this._flush = 0;
}
requestAnimationFrame(this.flush);
}
/**
* 停止时钟
*/
private stopTick() {
}
/**
* 时钟触发
*/
private flush(tsNow): void {
if (this._flush == 0) {
this.onFrameTick(tsNow);
} else {
if (this._currentFlush == 0) {
this.onFrameTick(tsNow);
this._currentFlush = this._flush;
} else {
this._currentFlush--;
}
}
requestAnimationFrame(this.flush);
}
nextTicks = [];
nextTick(func, tickCount = 1) {
this.nextTicks.push({func, tickCount});
}
private onFrameTick(tsNow) {
clear();
this.lastFPS = Math.floor(1000 / (tsNow - this.tsLast));
this.tsLast = tsNow;
const ts = tsNow - this.tsStart;
traverse(this.root, function (child) {
if (!child.isFree && child.enabled) {
child.onUpdate(ts);
} else {
return true;
}
}, -1, true, function (current) {
current.afterUpdate();
});
//const tsPass = Date.now() - tsNow;
for (let i = 0, li = this.nextTicks.length; i < li; i++) {
const item = this.nextTicks[i];
item.tickCount--;
if (item.tickCount <= 0) {
item.func(ts);
this.nextTicks.splice(i, 1);
i--;
li--;
}
}
}
/**
* 代理出来的onTouchBegin方法
* @param event
*/
private onTouchBegin(event) {
traversePostorder(this.root, function (child) {
return child.onInteract(0, event);
})
}
/**
* 代理出来的onTouchMove方法
* @param event
*/
private onTouchMove(event) {
traversePostorder(this.root, function (child) {
return child.onInteract(1, event);
})
}
/**
* 代理出来的onTouchEnd方法
* @param event
*/
private onTouchEnd(event) {
traversePostorder(this.root, function (child) {
return child.onInteract(2, event);
})
}
}
{
"_from": "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git",
"_id": "scilla@1.0.1",
"_inBundle": false,
"_integrity": "",
"_location": "/scilla",
"_phantomChildren": {},
"_requested": {
"type": "git",
"raw": "scilla@git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git",
"name": "scilla",
"escapedName": "scilla",
"rawSpec": "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git",
"saveSpec": "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git",
"fetchSpec": "http://gitlab2.dui88.com/laoqifeng/scilla-core.git",
"gitCommittish": null
},
"_requiredBy": [
"/"
],
"_resolved": "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git#b807e097f6e526fa58e88dff09ef162c3bf89b59",
"_spec": "scilla@git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git",
"_where": "/Users/wanghongyuan/kickball0417",
"bundleDependencies": false,
"deprecated": false,
"description": "## game engine for HTML5",
"devDependencies": {
"rollup-plugin-commonjs": "^9.2.2",
"rollup-plugin-node-resolve": "^4.0.1",
"rollup-plugin-typescript2": "^0.20.1",
"rollup-plugin-uglify": "^6.0.2",
"tslib": "^1.9.3",
"typescript": "^3.3.4000"
},
"license": "MIT",
"main": "./dist/index.js",
"name": "scilla",
"scripts": {},
"types": "./types/index.d.ts",
"version": "1.0.1"
}
# scilla
## game engine for HTML5
\ No newline at end of file
/**
* Created by rockyl on 2018/11/16.
*/
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const typescript = require('rollup-plugin-typescript2');
const {uglify} = require('rollup-plugin-uglify');
const name = 'scilla';
export default {
input: 'src/index.ts',
output: {
file: `dist/${name}.js`,
format: 'umd',
name,
},
plugins: [
resolve({
browser: true,
}),
typescript({
typescript: require('typescript'),
tslib: require('tslib'),
declaration: false,
}),
commonjs(),
//uglify({}),
]
};
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
/**
* 一些重定义的类型
*/
/**
* 颜色
*/
export type color = string;
/**
* 资源
*/
export type resource = any;
/**
* 原数据
*/
export type raw = any;
/**
* 动态数据
*/
export type dynamic = string;
/**
* 常用框类型
*/
export interface Frame{
x?: number;
y?: number;
w?: number;
h?: number;
}
/**
* Created by rockyl on 2018/7/11.
*
* 资源管理
* 加载资源
*/
import {createTexture} from '../core/Texture'
import {FrameAnimation, getFrameAnimation, putFrameAnim} from '../core/FrameAnimation'
import {Sheet} from '../core/Sheet'
import {Texture} from "../core";
import {EngineConfig} from "../engine-config";
let resCache = {};
let resPath = '';
let resCacheProxy;
const resLoaderType = {
'.json': loadJson,
'.json5': loadJson5,
'.txt': loadTxt,
'.png': loadTexture,
'.jpg': loadTexture,
'.svg': loadTexture,
'.bimg': loadTextureFromBlob,
'.sht': loadSheet,
'.sht-disperse': loadSheetDisperse,
'.fnt': loadFont,
'.anim': loadAnim,
};
/**
* 设置资源根路径
* @param path
*/
export function setResPath(path: string) {
resPath = path;
}
/**
* 加载一批资源
* @param items 资源数组: ['aaa.png', {uuid: 'bbb', url: 'alias.png'}]
* @param progress 进度回调,参数为加载百分比
* @return Promise<Array<any>> 资源组
*/
export function loadResItems(items: Array<any | string>, progress?: (percentage: number) => void): Promise<Array<any>> {
let total = items.length;
let count = 0;
return Promise.all(
items.map(item => {
let uuid, url, config, ext;
if (typeof item === 'string') {
url = item;
} else {
url = item.url;
}
if (!url) {
return Promise.resolve();
}
if (typeof item === 'string') {
uuid = getUUIDFromUrl(url);
} else {
uuid = item.uuid || getUUIDFromUrl(url);
ext = item.ext;
config = item.config;
}
let loader = getLoader(ext, url);
return loader(url, uuid, true, config).then((res) => {
count++;
progress && progress(count / total);
return res;
})
})
);
}
/**
* 加载任意网络资源
* @param url url
* @param uuid
* @param type 类型(json|text|arraybuffer|blob)
* @param cache 是否缓存
* @param config 资源配置
* @param options 请求配置
* @return Promise<any> 资源
*/
export async function loadAny(url: string, uuid?: string, cache: boolean = true, config?: any, options = {}, type = 'arraybuffer'): Promise<any> {
let response = await fetch(resolveUrl(url), options);
let result;
switch (type) {
case 'json':
result = response.json();
break;
case 'text':
result = response.text();
break;
case 'arraybuffer':
result = response.arrayBuffer();
break;
case 'blob':
result = response.blob();
break;
}
return await result;
}
/**
* 加载文本资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export function loadTxt(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<string> {
let p = loadAny(url, uuid, cache, config, undefined, 'text');
if (cache) {
p.then(data => {
cacheRes(data, url, uuid);
return data;
})
}
return p;
}
/**
* 加载json资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export function loadJson(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<any> {
let p = loadAny(url, uuid, cache, config, undefined, 'json');
if (cache) {
p.then(data => {
cacheRes(data, url, uuid);
return data;
})
}
return p;
}
/**
* 加载json5资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export async function loadJson5(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<any> {
let txt = await loadTxt(url, uuid);
const jsonData = window['eval'](`(${txt})`);
cacheRes(jsonData, url, uuid);
return jsonData;
}
/**
* 加载图集资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export function loadSheet(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<Sheet> {
let pngFile = url.substring(0, url.lastIndexOf('.')) + '.png';
return Promise.all([
loadJson(url, null, false),
loadImage(pngFile, null, false),
]).then(
(result) => {
let data: any = result[0];
let img: any = result[1];
let sheet: Sheet = new Sheet(img, data.frames);
sheet.generateAll();
if (cache) {
cacheRes(sheet, url, uuid);
if (config) {
for (let textureConfig of config.textures) {
const {name, uuid} = textureConfig;
const texture = sheet.getTexture(name);
cacheRes(texture, name, uuid);
}
} else {
let textures = sheet.getAllTextures();
for (let key in textures) {
cacheRes(textures[key], key, key);
}
}
}
return sheet;
}
)
}
/**
* 加载散列的图集
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export async function loadSheetDisperse(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<Sheet> {
for (let {name, uuid} of config.textures) {
let subUrl = url.replace('-disperse', '') + '/' + name;
await loadTexture(subUrl, uuid);
}
return null;
}
/**
* 加载文图字资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export function loadFont(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<Sheet> {
return loadSheet(url, null, false).then(
sheet => {
if (cache) {
cacheRes(sheet, url, uuid);
}
return sheet;
}
)
}
function findAnimConfig(animations, name) {
let result;
animations.some((item: any) => {
if (item.name === name) {
result = item;
return true;
}
});
return result;
}
/**
* 加载帧动画资源(多个)
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export function loadAnim(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<FrameAnimation[]> {
let pngFile = url.substring(0, url.lastIndexOf('.')) + '.png';
return Promise.all([
loadJson(url, null, false),
loadImage(pngFile, null, false),
]).then(
(result) => {
let data: any = result[0];
let img: any = result[1];
putFrameAnim(img, data);
const animations = [];
for (let name in data.mc) {
const animation = getFrameAnimation(name);
if (cache) {
let uuid = name;
if (config) {
const cfg = findAnimConfig(config.animations, name);
uuid = cfg.uuid;
}
cacheRes(animation, name, uuid);
}
animations.push(animation);
}
return animations;
}
)
}
/**
* 加载图片资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export function loadImage(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<any> {
return new Promise((resolve, reject) => {
let img = new Image();
if (EngineConfig.imgCrossOrigin) {
img.setAttribute('crossOrigin', 'anonymous');
}
img.onload = function (e) {
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
img.src = resolveUrl(url);
});
}
/**
* 加载blob图片资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export async function loadImageFromBlob(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<any> {
try {
const imgBlob = await loadAny(url, uuid, false, config, undefined, 'blob');
return await blobToImage(imgBlob);
} catch (e) {
console.log(e);
}
}
/**
* 加载纹理资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export async function loadTexture(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<Texture> {
const img: any = await loadImage(url, uuid, false);
const texture = createTexture(img);
if (cache) {
cacheRes(texture, url, uuid);
}
return texture;
}
/**
* 加载blob纹理资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config 资源配置
* @return Promise<any> 资源
*/
export async function loadTextureFromBlob(url: string, uuid?: string, cache: boolean = true, config?: any): Promise<Texture> {
const img: any = await loadImageFromBlob(url, uuid, false);
const texture = createTexture(img);
if (cache) {
cacheRes(texture, url, uuid);
}
return texture;
}
/**
* 处理url
* @param url url
* @return string 处理后的url
*/
function resolveUrl(url: string): string {
if (url.indexOf('//') === 0 || url.indexOf('http:') === 0 || url.indexOf('https:') === 0) {
return url;
}
return resPath + url;
}
/**
* 获取一个加载器
* @param ext
* @param url
*/
function getLoader(ext: string, url: string): Function {
ext = ext || url.substr(url.lastIndexOf('.'));
return resLoaderType[ext] || loadAny;
}
/**
* 根据url推断名称,只是获取短文件名
* @param url
*/
function getUUIDFromUrl(url): string {
return url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'))
}
/**
* 缓存资源
* @param res
* @param url
* @param uuid
*/
export function cacheRes(res, url: string, uuid?: string) {
uuid = uuid || getUUIDFromUrl(url);
resCache[uuid] = res;
}
/**
* 增加加载器
* @param ext 需加载的文件后缀
* @param loader 加载方法,返回携带最终资源的Promise
*/
export function addLoader(ext: string, loader: Function) {
resLoaderType[ext] = loader;
}
/**
* 获取资源
* @param uuid
*/
export function getRes(uuid: string) {
if (resCacheProxy) {
return resCacheProxy(uuid);
}
return resCache[uuid];
}
export function setResCacheProxy(proxyFunc: Function) {
resCacheProxy = proxyFunc;
}
/**
* 销毁资源
* @param uuidOrUuids
*/
export function destroyRes(uuidOrUuids: string | Array<string>) {
if (Array.isArray(uuidOrUuids)) {
while (uuidOrUuids.length > 0) {
delete resCache[uuidOrUuids.pop()];
}
} else {
delete resCache[uuidOrUuids];
}
}
/**
* 销毁全部资源
*/
export function destroyAllRes(): any {
for (let key in resCache) {
destroyRes(key);
}
}
/**
* 获取所有uuid值
*/
export function getAllResUuids(): string[] {
return Object.keys(resCache);
}
function fileOrBlobToDataURL(obj): Promise<string> {
return new Promise((resolve, reject) => {
let a = new FileReader();
a.readAsDataURL(obj);
a.onload = function (e) {
resolve(e.target['result']);
};
a.onerror = function (e) {
reject(e);
}
});
}
async function blobToImage(blob) {
const dataUrl = await fileOrBlobToDataURL(blob);
return new Promise((resolve, reject) => {
let img = new Image();
if (EngineConfig.imgCrossOrigin) {
img.setAttribute('crossOrigin', 'anonymous');
}
img.onload = function () {
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
img.src = dataUrl;
})
}
/**
* Created by rockyl on 2018/11/5.
*/
import HashObject from "./HashObject";
import {Entity,} from "./Entity";
import {EngineConfig} from "../engine-config";
const interactiveMap = [
'_dealGlobalTouchBegin',
'_dealGlobalTouchMove',
'_dealGlobalTouchEnd',
];
/**
* 组件基类
*/
export class Component extends HashObject {
/**
* 所依附的实体
*/
entity: Entity;
protected delayCallbacks = [];
private _firstUpdate: boolean;
//是否有效
protected _enabled: boolean = EngineConfig.componentEnabled;
/**
* 是否有效状态
*/
get enabled(): boolean {
return this._enabled;
}
set enabled(value: boolean) {
if (this._enabled !== value) {
this._enabled = value;
if (this.entity && this.entity.isActive) {
if(!EngineConfig.editorMode){
if (this._enabled) {
this.onEnable();
} else {
this.onDisable();
}
}
}
}
}
/**
* 装配实体
* @param entity
*/
_setup(entity: Entity) {
this.entity = entity;
if(!EngineConfig.editorMode){
this.onCreate();
}
}
/**
* 卸载实体
*/
_unSetup() {
this.entity = null;
if(!EngineConfig.editorMode){
this.onDestroy();
}
}
/**
* 当组件被创建时
*/
onCreate() {
}
$onAwake(){
if(!EngineConfig.editorMode){
this.onAwake();
}
}
/**
* 当组件被唤醒时
*/
onAwake() {
this._firstUpdate = true;
}
/**
* 当组件生效时
*/
onEnable() {
}
/**
* 当组件失效时
*/
onDisable() {
}
$onUpdate(t) {
this.onUpdate(t);
if (!this._firstUpdate) {
this.invokeDelayCallback(t);
}
this._firstUpdate = false;
}
$onEditorUpdate(t) {
this.onEditorUpdate(t);
}
$afterUpdate(){
this.afterUpdate();
}
$afterEditorUpdate() {
this.afterEditorUpdate();
}
private invokeDelayCallback(t) {
for (let i = 0, li = this.delayCallbacks.length; i < li; i++) {
let {callback, once} = this.delayCallbacks[i];
if (once) {
this.delayCallbacks.splice(i, 1);
i--;
li--;
}
callback.call(this, t);
}
}
/**
* 当时钟更新时
* @param t 从引擎开始到当前的毫秒数
*/
onUpdate(t) {
}
onEditorUpdate(t) {
}
/**
* 当子节点的时钟更新结束后
*/
afterUpdate() {
}
afterEditorUpdate(){
}
$onSleep() {
if(!EngineConfig.editorMode){
this.onSleep();
}
}
/**
* 当组件沉睡时
*/
onSleep() {
}
/**
* 当组件被销毁时
*/
onDestroy() {
}
/**
* 当被监听的属性被修改时
* @param value
* @param key
* @param oldValue
*/
protected onModify(value, key, oldValue) {
}
private getDelayCallback(callback) {
let result;
for (let item of this.delayCallbacks) {
if (item.callback == callback) {
result = item;
break;
}
}
return result;
}
/**
* 执行延迟回调
* @param callback
* @param once 是否只执行一次
*/
callOnNextTick(callback, once = true) {
const item = this.getDelayCallback(callback);
if (!item) {
this.delayCallbacks.push({callback, once});
}
}
cancelOnNextTick(callback) {
const item = this.getDelayCallback(callback);
const index = this.delayCallbacks.indexOf(item);
if (index >= 0) {
this.delayCallbacks.splice(index, 1);
}
}
/**
* 当交互时
* @param type
* @param event
*/
onInteract(type, event) {
try {
const hitOn = this[interactiveMap[type]](event);
return hitOn;
} catch (e) {
console.warn(e);
}
}
_dealGlobalTouchBegin(e): boolean {
return this.onGlobalTouchBegin(e);
}
_dealGlobalTouchMove(e): boolean {
return this.onGlobalTouchMove(e);
}
_dealGlobalTouchEnd(e): boolean {
return this.onGlobalTouchEnd(e);
}
/**
* 当全局触摸开始
* @param e
*/
onGlobalTouchBegin(e): boolean {
return false;
}
/**
* 当全触摸移动
* @param e
*/
onGlobalTouchMove(e): boolean {
return false;
}
/**
* 当全触摸结束
* @param e
*/
onGlobalTouchEnd(e): boolean {
return false;
}
/**
* 向下广播
* 如果某组件调用后返回true,将结束整条链
* @param method 方法名
* @param level 深度,默认全部遍历
* @param params 参数
*/
broadcast(method, level = -1, ...params) {
this.entity.broadcast(method, level, ...params);
}
/**
* 向上冒泡
* 如果某组件调用后返回true,将结束整条链
* @param method 方法名
* @param params 参数
*/
bubbling(method, ...params) {
this.entity.bubbling(method, ...params);
}
}
/**
* Created by rockyl on 2018/11/5.
*/
import HashObject from "./HashObject";
import {Component} from "./Component";
import {EngineConfig} from "../engine-config";
/**
* 节点遍历(先序遍历)
* @param target 目标节点
* @param hitChild 遇到子节点回调
* @param level 深度,默认全部遍历
* @param includeSelf 是否包括自身
* @param fullCallback 子节点遍历完后回调
* @param params 其他参数
*/
export function traverse(target: Entity, hitChild: (child: Entity, ...params) => boolean, level = -1, includeSelf = false, fullCallback?: (current: Entity) => void, ...params) {
let interrupt;
if (includeSelf) {
hitChild(target, ...params);
}
if (level !== 0) {
for (let child of target.children) {
if (hitChild(child, ...params)) {
interrupt = true;
continue;
}
if (child.children.length > 0) {
traverse(child, hitChild, level - 1, false, fullCallback, ...params);
}
}
}
fullCallback && fullCallback(target);
}
/**
* 节点遍历(后序遍历且倒序)
* @param target 目标节点
* @param hitChild 遇到子节点回调
* @param level 深度,默认全部遍历
* @param includeSelf 是否包括自身
* @param fullCallback 子节点遍历完后回调
* @param params 其他参数
*/
export function traversePostorder(target: Entity, hitChild: (child: Entity, ...params) => boolean, level = -1, includeSelf = false, fullCallback?: (current: Entity) => void, ...params) {
let interrupt;
if (level !== 0) {
for (let i = target.children.length - 1; i >= 0; i--) {
const child = target.children[i];
if (traversePostorder(child, hitChild, level - 1, false, fullCallback, ...params)) {
return true;
}
if (hitChild(child, ...params)) {
return true;
}
}
}
if (includeSelf) {
hitChild(target, ...params);
}
!interrupt && fullCallback && fullCallback(target);
}
/**
* 节点冒泡
* @param target 目标节点
* @param hitParent 遇到父节点回调
* @param includeSelf 是否包括自身
* @param params 其他参数
*/
export function bubbling(target: Entity, hitParent: (parent: Entity, ...params) => boolean, includeSelf = false, ...params) {
if (includeSelf) {
hitParent(target, ...params);
}
let entity = target;
while (entity = entity.parent) {
if (hitParent(entity, ...params)) {
break;
}
}
}
/**
* 实体类
* 实体类只是单纯的父子节点逻辑,不含有其他逻辑
*/
export class Entity extends HashObject {
name: string = 'Entity';
protected _uuid: string;
//是否游离状态
protected _isFree: boolean = true;
//是否有效
protected _enabled: boolean = EngineConfig.entityEnabled;
protected _parent: Entity = null;
protected _children: Entity[] = [];
protected _components: Component[] = [];
constructor(name?: string, uuid?: string) {
super();
if (name) {
this.name = name;
}
if (uuid) {
this._uuid = uuid;
}
}
get uuid(): string {
return this._uuid;
}
/**
* 是否有效状态
*/
get enabled(): boolean {
return this._enabled;
}
set enabled(value: boolean) {
if (this._enabled !== value) {
this._enabled = value;
traverse(this, function (child: Entity) {
child._invokeEnabledState(value);
return false;
}, -1, true)
}
}
_invokeEnabledState(enabled: boolean) {
if (this._enabled && enabled) {
this.onEnable();
} else if (!this._enabled && !enabled) {
this.onDisable();
}
}
get isParentActive(): boolean {
return this._parent && this._parent.enabled && !this._parent.isFree;
}
get isActive(): boolean {
return this.isParentActive && this._enabled;
}
/**
* 是否游离状态
*/
get isFree(): boolean {
return this._isFree;
}
/**
* 使游离
*/
_free() {
this._isFree = true;
let that = this;
traverse(this, function (child: Entity) {
/*if (child.isParentActive) {
that._invokeEnabledState(false);
}*/
child._free();
return false;
}, 1)
}
/**
* 使约束
*/
_restrict() {
this._isFree = false;
let that = this;
traverse(this, function (child: Entity) {
/*if (child.isParentActive) {
that._invokeEnabledState(true);
}*/
child._restrict();
return false;
}, 1)
}
//----- tree
/**
* 获取父节点
*/
get parent(): Entity {
return this._parent;
}
/**
* 是否含有子节点
* @param child
*/
containsChild(child: Entity): boolean {
return this.getChildIndex(child) >= 0;
}
/**
* 添加子节点时
* @param child
* @private
*/
protected _onChildAdded(child: Entity) {
child._parent = this;
if (!this._isFree && child._isFree) {
if (child.isParentActive) {
child._invokeEnabledState(true);
}
child._restrict();
}
}
/**
* 子节点被移除时
* @param child
* @private
*/
_onChildRemoved(child: Entity) {
child._parent = null;
if (!this._isFree && !child._isFree) {
if (child.isActive) {
child._invokeEnabledState(false);
}
child._free();
}
}
/**
* 添加子节点,重复添加则会加到最后
* @param child
*/
addChild(child: Entity) {
this.addChildAt(child, this._children.length);
}
/**
* 添加子节点到指定索引,重复添加可作为顺序交换
* @param child
* @param index
*/
addChildAt(child: Entity, index) {
if (child.parent && child.parent !== this) {
child.parent.removeChild(child);
}
const currentIndex = this.getChildIndex(child);
if (index < 0 || currentIndex == index) { //如果索引小于0或没变化
return;
}
index = Math.min(this._children.length, index);
if (currentIndex >= 0 || index < this._children.length) {
if (currentIndex >= 0) {
this._children.splice(currentIndex, 1);
}
this._children.splice(index, 0, child);
} else {
this._children.push(child);
}
this._onChildAdded(child);
}
/**
* 移除节点
* @param child
*/
removeChild(child: Entity) {
const index = this.getChildIndex(child);
if (index >= 0) {
this.removeChildAt(index);
}
}
/**
* 移除指定索引的节点
* @param index
*/
removeChildAt(index: number) {
const child = this._children[index];
this._onChildRemoved(child);
this._children.splice(index, 1);
}
/**
* 根据节点获取索引
* @param child
*/
getChildIndex(child: Entity): number {
return this._children.indexOf(child)
}
/**
* 获取指定索引的节点
* @param index
*/
getChildByIndex(index): Entity {
return this._children[index];
}
/**
* 获取指定名字的节点
* @param name
*/
getChildrenByName(name): Entity[] {
let children = [];
for (let child of this._children) {
if (child.name === name) {
children.push(child);
}
}
return children;
}
/**
* 移除所有子节点
*/
removeChildren() {
while (this._children.length > 0) {
this.removeChildAt(0);
}
}
/**
* 获取所有子节点
*/
get children(): Entity[] {
return this._children;
}
//----- component
/**
* 增加组件
* @param component
*/
addComponent(component: Component) {
this.onAddComponent(component);
this._components.push(component);
}
/**
* 在指定索引增加组件,重复添加可作为顺序交换
* @param component
* @param index
*/
addComponentAt(component: Component, index: number) {
const currentIndex = this._components.indexOf(component);
if (currentIndex == index) {
return;
}
if (currentIndex >= 0) {
this._components.splice(currentIndex, 1);
}
this._components.splice(index, 0, component);
this.onAddComponent(component);
}
/**
* 移除组件
* @param component
*/
removeComponent(component: Component) {
this.onRemoveComponent(component);
const index = this._components.indexOf(component);
if (index >= 0) {
this._components.splice(index, 1);
}
}
/**
* 移除所有组件
*/
removeAllComponents() {
while (this._components.length > 0) {
this.removeComponent(this._components[0]);
}
}
/**
* 根据组件名称获取指定类的组件列表
* @param name
*/
getComponentsByName<T extends Component>(name: string): T[] {
return <T[]>this._components.filter((value: Component) => {
return value.constructor['__class__'] === name;
});
}
/**
* 获取指定类的组件列表
* @param clazz
*/
getComponents<T extends Component>(clazz: new()=> T): T[] {
return <T[]>this._components.filter((component: Component) => {
return component instanceof clazz;
});
}
/**
* 获取指定类的组件
* @param name
*/
getComponentByName<T extends Component>(name: string): T {
return this.getComponentsByName<T>(name)[0];
}
/**
* 获取指定类的组件
* @param clazz
*/
getComponent<T extends Component>(clazz: new()=> T): T {
return this.getComponents<T>(clazz)[0];
}
/**
* 获取所有组件
*/
get components(): Component[] {
return this._components;
}
//----- lifecycle
/**
* 遍历所有组件
* @param func
*/
forEachComponent(func: (component) => boolean) {
for (let component of this._components) {
if (func(component)) {
break;
}
}
}
/**
* 当组件生效时
*/
onEnable() {
this.forEachComponent(comp => {
if (comp.enabled) {
return comp.$onAwake();
}
});
}
/**
* 当组件失效时
*/
onDisable() {
this.forEachComponent(comp => {
if (comp.enabled) {
return comp.$onSleep();
}
});
}
/**
* 当时钟更新时
* @param t
*/
onUpdate(t) {
this.forEachComponent(comp => {
if (comp.enabled) {
if (EngineConfig.editorMode) {
return comp.$onEditorUpdate(t);
} else {
return comp.$onUpdate(t);
}
}
});
}
/**
* 当子节点遍历结束后
*/
afterUpdate() {
this.forEachComponent(comp => {
if (comp.enabled) {
if (EngineConfig.editorMode) {
return comp.$afterEditorUpdate();
} else {
return comp.$afterUpdate();
}
}
});
}
/**
* 当交互时
* @param type
* @param event
*/
onInteract(type, event) {
if (!this.isFree && this.enabled) {
let interrupt = false;
this.forEachComponent(comp => {
if (comp.enabled && comp.interactable) {
const r = comp.onInteract(type, event);
if (r) {
interrupt = true;
}
return false;
}
});
return interrupt;
} else {
return false;
}
}
/**
* 当添加组件时
* @param component
*/
onAddComponent(component: Component) {
component._setup(this);
if (EngineConfig.awakeComponentWhenAdded) {
this.awakeComponent(component);
}
}
/**
* 唤醒组件
* @param component
*/
awakeComponent(component) {
if (!this._isFree && this._enabled) {
component.$onAwake();
}
}
/**
* 当移除组件时
* @param component
*/
onRemoveComponent(component: Component) {
if (EngineConfig.sleepComponentWhenRemoved) {
this.sleepComponent(component);
}
component._unSetup();
}
/**
* 睡眠组件
* @param component
*/
sleepComponent(component: Component) {
if (!this._isFree && this._enabled) {
component.$onSleep();
}
}
/**
* 向下广播
* 如果某组件调用后返回true,将结束整条链
* @param method 方法名
* @param level 深度,默认全部遍历
* @param params 参数
*/
broadcast(method: string, level = -1, ...params) {
traverse(this, this.invokeOnEntity, level, true, null, method, ...params)
}
/**
* 向上冒泡
* 如果某组件调用后返回true,将结束整条链
* @param method 方法名
* @param params 参数
*/
bubbling(method: string, ...params) {
bubbling(this, this.invokeOnEntity, false, method, ...params);
}
/**
* 调用实体上的组件的方法
* @param hitEntity 遇到的实体
* @param method 方法名
* @param params 参数
*/
private invokeOnEntity = (hitEntity: Entity, method: string, ...params): boolean => {
let hitBreak = false;
hitEntity.forEachComponent(comp => {
const m = comp[method];
if (m) {
const result = m.apply(comp, params);
if (result) {
hitBreak = true;
}
}
return false;
});
if (hitBreak) {
return true;
}
};
}
/**
* Created by rockyl on 2018-11-30.
*/
import {Sheet} from "./Sheet";
const animationMap = {};
const animDataMap = {};
const textureMap = {};
/**
* 获取一个帧动画资源
* @param name
*/
export function getFrameAnimation(name: string): FrameAnimation {
let animation: FrameAnimation = animationMap[name];
if (!animation) {
animation = animationMap[name] = new FrameAnimationImpl(name);
animation.fillMcData(name);
}
return animation;
}
/**
* 放置帧动画图片和数据
* @param img
* @param data
*/
export function putFrameAnim(img: any, data: any) {
const {mc, res} = data;
let sheet: Sheet = new Sheet(img, res);
for (let key in mc) {
const animData = animDataMap[key] = mc[key];
animData.sheet = sheet;
}
}
/**
* 帧动画资源
*/
export interface FrameAnimation {
/**
* 填充帧数据
* @param name
*/
fillMcData(name: string);
/**
* 获取帧率
*/
readonly fps: number;
/**
* 获取所有帧标签
*/
readonly labels: any[];
/**
* 获取帧数
*/
readonly frameCount: number;
/**
* 根据名字获取帧标签
* @param name
*/
getLabel(name: string): any;
/**
* 获取帧
* @param frameIndex
*/
getFrame(frameIndex: number): any;
/**
* 销毁自身
*/
destroy()
}
/**
* 帧动画资源实现
*/
export class FrameAnimationImpl implements FrameAnimation {
private readonly _name: string;
private _animData;
constructor(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
fillMcData(name: string) {
const animData = animDataMap[name];
if (animData) {
this._animData = animData;
} else {
console.warn(`anim data [${name}] is not exist`)
}
}
get fps(): number {
return this._animData.frameRate;
}
get labels(): any[] {
return this._animData.labels;
}
get frameCount(): number {
return this._animData.frames.length;
}
getLabel(name: string): any {
let result;
for (let label of this._animData.labels) {
if (label.name == name) {
result = label;
break;
}
}
return result;
}
getFrame(frameIndex: number): any {
const {_animData,} = this;
let texture, frameData;
if (_animData) {
const {frames} = _animData;
frameData = frames[frameIndex];
if (frameData) {
const res = frameData.res;
texture = textureMap[res];
if (!texture) {
texture = textureMap[res] = _animData.sheet.getTexture(res);
}
}
}
return {
texture,
data: frameData,
};
}
destroy() {
this._animData = null;
}
}
/**
* Created by rockyl on 2018/11/5.
*/
let HASH_CODE_INK: number = 0;
function getHashCode() {
return ++HASH_CODE_INK;
}
/**
* 哈希对象
*/
export default class HashObject {
_hashCode: number;
constructor() {
this._hashCode = getHashCode();
}
get hashCode(): number {
return this._hashCode;
}
}
/**
* Created by rockyl on 2018-12-03.
*/
import {Entity} from "./Entity";
import {loadResItems} from "../assets-manager";
/**
* 场景
*/
export class Scene {
name: string;
root: Entity;
resourceGroups: any = {
preload: [],
delay: [],
};
config: any;
/**
* 初始化
* @param config
*/
initByConfig(config: any){
this.config = config;
this.name = config.name;
const resourceGroups = config['resource-groups'];
for(let key in resourceGroups){
this.resourceGroups[key] = resourceGroups[key];
}
}
/**
* 加载资源组
* @param name
* @param progress
*/
async loadResGroup(name, progress?){
await loadResItems(this.resourceGroups[name], progress);
}
}
/**
* Created by rockyl on 2018-11-27.
*/
/**
* 单一事件类
* 一对多形式的订阅分发机制
*/
export class ScillaEvent {
private _subscribers: any[];
constructor() {
this._subscribers = [];
}
private findListener(callback) {
const {_subscribers} = this;
let result;
for (let i = 0, li = _subscribers.length; i < li; i++) {
const subscriber = _subscribers[i];
if (subscriber.callback == callback) {
result = {
subscriber,
index: i,
};
break;
}
}
return result;
}
/**
* 添加侦听
* @param callback
* @param thisObj
* @param priority
* @param params
*/
addListener(callback, thisObj?, priority = 0, ...params) {
if (!callback) {
return;
}
const {_subscribers} = this;
const listener = this.findListener(callback);
if (!listener) {
_subscribers.push({
callback,
thisObj,
priority,
params,
});
}
}
/**
* 添加单次侦听
* @param callback
* @param thisObj
* @param priority
* @param params
*/
once(callback, thisObj?, priority = 0, ...params) {
if (!callback) {
return;
}
const {_subscribers} = this;
const listener = this.findListener(callback);
if (!listener) {
_subscribers.push({
callback,
thisObj,
priority,
params,
once: true,
});
}
}
/**
* 移除侦听
* @param callback
*/
removeListener(callback) {
if (!callback) {
return;
}
const {_subscribers} = this;
const listener = this.findListener(callback);
if (listener) {
_subscribers.splice(listener.index, 1);
}
}
/**
* 是否已经侦听
* @param callback
*/
hasListener(callback) {
return !!this.findListener(callback);
}
/**
* 调用派发
* @param paramsNew
*/
invoke(...paramsNew) {
const {_subscribers} = this;
//按优先级降序
_subscribers.sort((a, b) => {
return a.priority - b.priority;
});
for (const subscriber of _subscribers) {
if(subscriber){
const {callback, thisObj, once, params}= subscriber;
const allParams = params.concat(paramsNew);
try {
callback.apply(thisObj, allParams);
}catch (e) {
console.log(e);
}
if(once){
this.removeListener(callback);
}
}
}
}
}
/**
* Created by rockyl on 2018-11-30.
*/
import HashObject from "../core/HashObject";
import Texture, {createTexture} from "./Texture";
import {Frame} from "../ReType";
/**
* 图集
*/
export class Sheet extends HashObject{
/**
* 图集原图
*/
img: any;
/**
* 图集分割配置
*/
frames: any;
private _textureCache: any = {};
constructor(img?, frames?: Frame) {
super();
if(img){
this.img = img;
}
if(frames){
this.frames = frames;
}
}
/**
* 生成全部纹理
*/
generateAll() {
for (let key in this.frames) {
this.generateTexture(key);
}
}
/**
* 生成一个纹理
* @param name
* @param force
*/
generateTexture(name: string, force = false): Texture {
const {img, frames, _textureCache} = this;
if (!force && _textureCache[name]) {
return _textureCache[name];
}
const frame = frames[name];
if (frame) {
return _textureCache[name] = createTexture(img, frame);
}
}
/**
* 是否有这个纹理
* @param name
*/
hasTexture(name): boolean {
return !!frames[name];
}
/**
* 获取纹理
* @param name
*/
getTexture(name): Texture {
let texture = this._textureCache[name];
if (texture) {
return texture;
} else {
return this.generateTexture(name);
}
}
/**
* 获取全部存在的纹理
*/
getAllTextures(): Texture[] {
return this._textureCache;
}
/**
* 销毁自身
*/
destroy() {
this.img = null;
for (let key in this._textureCache) {
this._textureCache[key].destroy();
delete this._textureCache[key];
}
}
}
/**
* Created by rockyl on 2018/7/12.
*/
import Bounds from "../support/Bounds";
import HashObject from "../core/HashObject";
import {createCanvas} from "./context/RenderContext";
import {Frame} from "../ReType";
/**
* 纹理类
*/
export default class Texture extends HashObject {
img: any;
bounds: Bounds;
_cacheCanvas;
constructor() {
super();
this.bounds = new Bounds();
}
/**
* 设置图集中的坐标和尺寸
* @param frame
*/
setFrame(frame: Frame) {
let {x, y, w, h} = frame;
this.bounds.setTo(x, y, w, h);
}
/**
* 设置图片
* @param img
*/
setImg(img) {
this.img = img;
}
/**
* 获取纹理宽度
*/
get width() {
return this.bounds.width;
}
/**
* 获取纹理高度
*/
get height() {
return this.bounds.height;
}
/**
* 产生一个缓存画布
*/
getCacheCanvas() {
const {width, height} = this.bounds;
let canvas = this._cacheCanvas;
if (!canvas) {
canvas = this._cacheCanvas = createCanvas();
}
canvas.stageWidth = width;
canvas.stageHeight = height;
const context = canvas.getContext('2d');
this.drawToCanvas(context);
return canvas;
}
/**
* 绘制到一个画布上
* @param context
* @param dx
* @param dy
* @param sx
* @param sy
* @param dw
* @param dh
*/
drawToCanvas(context, dx = 0, dy = 0, sx?, sy?, dw?, dh?) {
const {x, y, width, height} = this.bounds;
context.drawImage(this.img, sx || x, sy || y, width, height, dx, dy, dw || width, dh || height);
}
/**
* 销毁自身
*/
destroy() {
this.img = null;
this.bounds = null;
this.destroyCacheCanvas();
}
/**
* 销毁缓存画布
*/
destroyCacheCanvas() {
this._cacheCanvas = null;
}
}
/**
* 快捷创建纹理
* @param img
* @param frame
*/
export function createTexture(img, frame?: Frame): Texture {
const texture = new Texture();
texture.setImg(img);
texture.setFrame(frame || {x: 0, y: 0, w: img.width, h: img.height});
return texture;
}
/**
* Created by rockyl on 2018/11/7.
*
* 交互上下文
*/
let _canvas;
let _touchHandler;
let _scaleX, _scaleY, _rotation;
const ua = navigator.userAgent.toLowerCase();
const isMobile = (ua.indexOf('mobile') !== -1 || ua.indexOf('android') !== -1);
/**
* 装配上下文
* @param options
*/
export function setupContext(options:any = {}) {
const {canvas, touchHandler, touchEnabled} = options;
_touchHandler = touchHandler;
_canvas = canvas;
if(touchEnabled){
addListeners();
}
}
/**
* 更新缩放模式
* @param scaleX
* @param scaleY
* @param rotation
*/
export function updateScaleMode(scaleX, scaleY, rotation) {
_scaleX = scaleX;
_scaleY = scaleY;
_rotation = rotation;
}
/**
* 适配鼠标事件
*/
function addListeners() {
if (window.navigator.msPointerEnabled) {
_canvas.addEventListener("MSPointerDown", (event) => {
event.identifier = event.pointerId;
onTouchBegin(event);
prevent(event);
}, false);
_canvas.addEventListener("MSPointerMove", (event) => {
event.identifier = event.pointerId;
onTouchMove(event);
prevent(event);
}, false);
_canvas.addEventListener("MSPointerUp", (event) => {
event.identifier = event.pointerId;
onTouchEnd(event);
prevent(event);
}, false);
}
else {
if (!isMobile) {
addMouseListener();
}
addTouchListener();
}
}
/**
* 阻断页面拖动
* @param event
*/
function prevent(event) {
event.stopPropagation();
if (event["isScroll"] != true && !_canvas['userTyping']) {
event.preventDefault();
}
}
/**
* 增加鼠标事件
*/
function addMouseListener() {
_canvas.addEventListener("mousedown", onTouchBegin);
_canvas.addEventListener("mousemove", onMouseMove);
_canvas.addEventListener("mouseup", onTouchEnd);
}
/**
* 增加触摸事件
*/
function addTouchListener() {
_canvas.addEventListener("touchstart", (event) => {
for(let touch of event.changedTouches){
onTouchBegin(touch);
}
prevent(event);
}, false);
_canvas.addEventListener("touchmove", (event) => {
for(let touch of event.changedTouches){
onTouchMove(touch);
}
prevent(event);
}, false);
_canvas.addEventListener("touchend", (event) => {
for(let touch of event.changedTouches){
onTouchEnd(touch);
}
prevent(event);
}, false);
_canvas.addEventListener("touchcancel", (event) => {
for(let touch of event.changedTouches){
onTouchEnd(touch);
}
prevent(event);
}, false);
}
function onTouchBegin(event) {
let location = getLocation(event);
_touchHandler.onTouchBegin(location);
}
function onMouseMove(event) {
if (event.buttons === 0) {
onTouchEnd(event);
} else {
onTouchMove(event);
}
}
function onTouchMove(event) {
let location = getLocation(event);
_touchHandler.onTouchMove(location);
}
function onTouchEnd(event) {
let location = getLocation(event);
_touchHandler.onTouchEnd(location);
}
function getLocation(event){
return pagePosToCanvasPos(event.pageX, event.pageY, event.identifier)
}
/**
* 页面坐标转画布坐标
* @param pageX
* @param pageY
* @param identifier
* @param isLocalPos
*/
export function pagePosToCanvasPos(pageX, pageY, identifier?, isLocalPos:boolean = false) {
let x = pageX, y = pageY;
let box = _canvas.getBoundingClientRect();
if(!isLocalPos){
let doc = document.documentElement;
let left = box.left + window.pageXOffset - doc.clientLeft;
let top = box.top + window.pageYOffset - doc.clientTop;
x = pageX - left;
y = pageY - top;
}
let newX = x;
let newY = y;
if (_rotation === 90) {
newX = y;
newY = box.width - x;
}
else if (_rotation === -90) {
newX = box.height - y;
newY = x;
}
newX = newX / _scaleX;
newY = newY / _scaleY;
return {
x: Math.round(newX),
y: Math.round(newY),
identifier: identifier || 0,
};
}
/**
* 画布坐标转页面坐标
* @param x
* @param y
* @param isLocalPos
*/
export function canvasPosToPagePos(x, y, isLocalPos:boolean = true){
x = x * _scaleX;
y = y * _scaleY;
if(!isLocalPos){
let box = _canvas.getBoundingClientRect();
let doc = document.documentElement;
let left = box.left + window.pageXOffset - doc.clientLeft;
let top = box.top + window.pageYOffset - doc.clientTop;
x += left;
y += top;
}
return {
x, y,
}
}
/**
* Created by rockyl on 2018/11/5.
*
* 渲染上下文
*/
import {updateScaleMode} from "./InteractContext";
import Bounds from "../../support/Bounds";
import {dirtyFieldTrigger} from "../../tools/decorators";
/**
* 缩放模式
*
* SHOW_ALL: 全可见
* FIXED_WIDTH: 宽度固定
* FIXED_HEIGHT: 高度固定
*/
export const ScaleMode = {
SHOW_ALL: 'showAll',
FIXED_WIDTH: 'fixedWidth',
FIXED_HEIGHT: 'fixedHeight',
NO_SCALE: 'noScale',
NO_FIXED: 'noFixed',
};
/**
* 渲染上下文
*/
export default class RenderContext{
protected canvas;
protected context;
protected stageWidth;
protected stageHeight;
protected scaleX;
protected scaleY;
protected rotation = 0;
protected dirtyFieldTriggerLock = false;
private shortcutCanvas;
@dirtyFieldTrigger
designWidth;
@dirtyFieldTrigger
designHeight;
@dirtyFieldTrigger
scaleMode;
@dirtyFieldTrigger
modifyCanvasSize;
@dirtyFieldTrigger
autoAdjustSize;
private onModify(value, key, oldValue){
if(!this.dirtyFieldTriggerLock){
this.updateScaleModeSelf();
}
}
/**
* 装配上下文
* @param options
*/
setup(options: any = {}){
const {canvas, designWidth, designHeight, scaleMode = ScaleMode.SHOW_ALL, modifyCanvasSize = false, autoAdjustSize = false} = options;
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.dirtyFieldTriggerLock = true;
this.designWidth = designWidth;
this.designHeight = designHeight;
this.scaleMode = scaleMode;
this.modifyCanvasSize = modifyCanvasSize;
this.autoAdjustSize = autoAdjustSize;
this.dirtyFieldTriggerLock = false;
this.updateScaleModeSelf();
}
/**
* 清空渲染上下文
*/
clear() {
this.context.setTransform(1, 0, 0, 1, 0, 0);
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
/**
* 获取渲染上下文
*/
getContext() {
return this.context;
}
/**
* 获取舞台尺寸
*/
getStageSize() {
return {
width: this.stageWidth,
height: this.stageHeight,
}
}
/**
* 获取舞台缩放
*/
getStageScale() {
return {
x: this.scaleX,
y: this.scaleY,
}
}
/**
* 获取舞台中心
*/
getStageCenter() {
return {
x: this.stageWidth / 2,
y: this.stageHeight / 2,
}
}
/**
* 更新缩放模式
*/
private updateScaleModeSelf() {
let {canvas, designWidth, designHeight, scaleMode, rotation, modifyCanvasSize} = this;
let parent = canvas.parentElement;
let containerWidth = parent.clientWidth;
let containerHeight = parent.clientHeight;
const dWidth = designWidth || containerWidth;
const dHeight = designHeight || containerHeight;
let width, stageWidth;
let height, stageHeight;
let scaleX = containerWidth / dWidth;
let scaleY = containerHeight / dHeight;
let styleWidth;
let styleHeight;
//scale
switch (scaleMode) {
case ScaleMode.SHOW_ALL:
let scale = Math.max(scaleX, scaleY);
scaleX = scaleY = scale;
break;
case ScaleMode.NO_SCALE:
scaleX = scaleY = 1;
break;
case ScaleMode.NO_FIXED:
scaleX = scaleY = 1;
break;
case ScaleMode.FIXED_WIDTH:
case ScaleMode.FIXED_HEIGHT:
break;
}
//size
switch (scaleMode) {
case ScaleMode.SHOW_ALL:
width = dWidth;
height = dHeight;
stageWidth = dWidth;
stageHeight = dHeight;
break;
case ScaleMode.NO_SCALE:
width = dWidth;
height = dHeight;
stageWidth = dWidth;
stageHeight = dHeight;
break;
case ScaleMode.NO_FIXED:
width = containerWidth;
height = containerHeight;
stageWidth = dWidth;
stageHeight = dHeight;
break;
case ScaleMode.FIXED_WIDTH:
width = dWidth;
if(modifyCanvasSize){
height = dHeight;
}else{
height = containerHeight / scaleX;
}
scaleY = scaleX;
stageWidth = width;
stageHeight = height;
break;
case ScaleMode.FIXED_HEIGHT:
if(modifyCanvasSize){
width = dWidth;
}else{
width = containerWidth / scaleY;
}
height = dHeight;
scaleX = scaleY;
stageWidth = width;
stageHeight = height;
break;
}
//styleSize
switch (scaleMode) {
case ScaleMode.SHOW_ALL:
styleWidth = containerWidth;
styleHeight = containerHeight;
break;
case ScaleMode.NO_FIXED:
styleWidth = containerWidth;
styleHeight = containerHeight;
break;
case ScaleMode.NO_SCALE:
styleWidth = designWidth;
styleHeight = designHeight;
break;
case ScaleMode.FIXED_WIDTH:
case ScaleMode.FIXED_HEIGHT:
styleWidth = modifyCanvasSize ? designWidth * scaleX : containerWidth;
styleHeight = modifyCanvasSize ? designHeight * scaleY : containerHeight;
break;
}
updateScaleMode(scaleX, scaleY, rotation);
this.stageWidth = stageWidth;
this.stageHeight = stageHeight;
this.scaleX = scaleX;
this.scaleY = scaleY;
canvas.width = width;
canvas.height = height;
canvas.style.display = 'block';
canvas.style.width = styleWidth + 'px';
canvas.style.height = styleHeight + 'px';
}
/**
* 截图
* @param type 目标格式 0:Image, 1:DataURL
* @param params
*/
async shortcut(type: number = 0, params: ShortcutParams) {
let targetImg;
if(params.bounds || params.zoomToDom){
const dataUrl = this.canvas.toDataURL('image/png');
const img = await dataUrlToImage(dataUrl);
targetImg = await this.shortcutWithSize(img, type, params.imgType, params.quality, params.bounds, params.zoomToDom ? this.scaleX : 1);
}else{
targetImg = this.canvas.toDataURL(params.imgType, params.quality);
}
return targetImg;
}
private async shortcutWithSize(img, type, imgType, quality?, bounds?:Bounds, scale = 1) {
let {shortcutCanvas, stageWidth, stageHeight} = this;
if (!shortcutCanvas) {
this.shortcutCanvas = createCanvas();
}
const sx = bounds ? bounds.x || 0 : 0;
const sy = bounds ? bounds.y || 0 : 0;
const sw = bounds ? (bounds.width ? Math.min(bounds.width, stageWidth) : stageWidth) : stageWidth;
const sh = bounds ? (bounds.height ? Math.min(bounds.height, stageHeight) : stageHeight) : stageHeight;
const dw = sw * scale;
const dh = sh * scale;
shortcutCanvas.width = dw;
shortcutCanvas.height = dh;
const context = shortcutCanvas.getContext('2d');
context.drawImage(img, sx, sy, sw, sh, 0, 0, dw, dh);
const dataUrl = shortcutCanvas.toDataURL('image/' + imgType, quality);
switch (type) {
case 0:
return await dataUrlToImage(dataUrl);
case 1:
return dataUrl;
}
}
}
interface ShortcutParams {
imgType: string;
zoomToDom?: boolean;
quality?: number;
bounds?: Bounds;
}
function dataUrlToImage(dataUrl) {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = function () {
resolve(image);
};
image.onerror = function (e) {
reject(e);
};
image.src = dataUrl;
})
}
/**
* 创建canvas
*/
export function createCanvas() {
return document.createElement('canvas');
}
/**
* Created by rockyl on 2018/11/5.
*/
export {Component} from "./Component";
export {Entity} from './Entity'
export {Scene} from './Scene'
export {ScillaEvent} from './ScillaEvent'
export {createCanvas, ScaleMode} from './context/RenderContext';
export {pagePosToCanvasPos, canvasPosToPagePos} from './context/InteractContext';
export * from './manager'
export {default as Texture, createTexture} from './Texture'
export * from './Sheet'
export * from './FrameAnimation'
/**
* Created by rockyl on 2018/11/23.
*/
import {Entity, traverse, traversePostorder} from "./Entity";
import {injectProp} from "../tools/utils";
import {setupContext as setupInteractContext} from "./context/InteractContext";
import RenderContext, {ScaleMode} from "./context/RenderContext";
import './requestAnimationFrame';
/**
* 默认配置
*/
export const engineConfig: any = {
fps: 60,
designWidth: 750,
designHeight: 1334,
scaleMode: ScaleMode.FIXED_WIDTH,
touchEnabled: true,
};
/**
* 自定义参数
*/
export const customConfig: any = {};
let root: Entity;
let _flush = 0, _currentFlush = 0;
let tsStart, tsLast;
let lastFPS = 0;
let renderContext, interactContext;
/**
* 装配引擎
* @param _engineConfig
* @param _customConfig
*/
export function setup(_engineConfig?, _customConfig?) {
injectProp(engineConfig, _engineConfig);
injectProp(customConfig, _customConfig);
const {canvas, designWidth, designHeight, scaleMode, modifyCanvasSize, touchEnabled} = engineConfig;
let canvasElement = typeof canvas == 'object' ? canvas : document.getElementById(canvas);
interactContext = setupInteractContext({
canvas: canvasElement,
touchHandler: {
onTouchBegin,
onTouchMove,
onTouchEnd,
},
touchEnabled,
});
renderContext = new RenderContext();
renderContext.setup({
canvas: canvasElement,
designWidth,
designHeight,
scaleMode,
modifyCanvasSize,
});
root = new Entity('root');
root._restrict();
}
/**
* 开始引擎
*/
export function start() {
root.enabled = true;
tsStart = Date.now();
startTick();
}
/**
* 暂停引擎
*/
export function pause() {
root.enabled = false;
stopTick();
}
/**
* 获取根Entity
*/
export function getRoot(): Entity {
return root;
}
/**
* 获取节点路径
* @param entity
*/
export function getEntityPath(entity?: Entity): string {
let path = '';
let current = entity || root;
while (current.parent) {
path = current.parent.children.indexOf(current) + (path.length > 0 ? '|' : '') + path;
current = current.parent;
}
return path;
}
/**
* 根据节点路径获取节点
* @param path
*/
export function getEntityByPath(path?: string): Entity {
let target = root;
if (path.length > 0) {
let arr = path.split('|');
for (let item of arr) {
target = target.children[item];
if (!target) {
target = null;
break;
}
}
}
return target;
}
/**
* 获取当前帧率
*/
export function getFPS() {
return lastFPS;
}
/**
* 获取渲染上下文
*/
export function getRenderContext(): RenderContext {
return renderContext;
}
/**
* 开始时钟
*/
function startTick() {
_flush = 60 / engineConfig.fps - 1 >> 0;
if (_flush < 0) {
_flush = 0;
}
requestAnimationFrame(flush);
}
/**
* 停止时钟
*/
function stopTick() {
}
let tsLast2;
/**
* 时钟触发
*/
function flush(tsNow): void {
if (_flush == 0) {
onFrameTick(tsNow);
} else {
if (_currentFlush == 0) {
onFrameTick(tsNow);
_currentFlush = _flush;
} else {
_currentFlush--;
}
}
requestAnimationFrame(flush);
}
const nextTicks = [];
/**
* 下一帧执行
* @param func
* @param tickCount
*/
export function nextTick(func, tickCount = 1) {
nextTicks.push({func, tickCount});
}
function onFrameTick(tsNow) {
renderContext.clear();
const tsNow2 = Date.now();
lastFPS = Math.floor(1000 / (tsNow - tsLast));
tsLast = tsNow;
tsLast2 = tsNow2;
const ts = tsNow - tsStart;
traverse(root, function (child) {
if (!child.isFree && child.enabled) {
child.onUpdate(ts);
} else {
return true;
}
}, -1, true, function (current) {
current.afterUpdate();
});
//const tsPass = Date.now() - tsNow;
for (let i = 0, li = nextTicks.length; i < li; i++) {
const item = nextTicks[i];
item.tickCount--;
if (item.tickCount <= 0) {
item.func(ts);
nextTicks.splice(i, 1);
i--;
li--;
}
}
}
/**
* 代理出来的onTouchBegin方法
* @param event
*/
function onTouchBegin(event) {
traversePostorder(root, function (child) {
return child.onInteract(0, event);
})
}
/**
* 代理出来的onTouchMove方法
* @param event
*/
function onTouchMove(event) {
traversePostorder(root, function (child) {
return child.onInteract(1, event);
})
}
/**
* 代理出来的onTouchEnd方法
* @param event
*/
function onTouchEnd(event) {
traversePostorder(root, function (child) {
return child.onInteract(2, event);
})
}
\ No newline at end of file
/**
* Created by Administrator on 2017/7/12.
*/
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || // name has changed in Webkit
window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
/**
* Created by rockyl on 2018-12-04.
*/
import {cleanEntity, setupScene, } from "./interpreter";
import {addLoader, cacheRes, destroyRes, getAllResUuids, loadJson5} from "../assets-manager";
import {customConfig, getRoot, pause, Scene, start} from "../core";
export * from './interpreter'
let currentScene: Scene;
let resUUIDs;
/**
* 启动场景
* @param sceneNameOrPath
* @param progress
*/
export async function launchScene(sceneNameOrPath, progress?) {
const sceneConfig = customConfig.scene;
let sceneFile = sceneConfig.scenes[sceneNameOrPath];
if(!sceneFile){
sceneFile = sceneNameOrPath;
}
const scene = await loadScene(sceneFile, 'scene_' + sceneFile);
resUUIDs = getAllResUuids();
await scene.loadResGroup('preload', progress);
if(currentScene){
unmountScene(currentScene);
}
currentScene = scene;
mountScene(scene);
scene.loadResGroup('delay', progress);
}
/**
* 装载场景
* @param scene
*/
export function mountScene(scene){
pause();
setupScene(scene, getRoot());
start();
}
/**
* 卸载场景
* @param scene
*/
export function unmountScene(scene){
pause();
cleanEntity(scene.root);
destroyRes(resUUIDs);
}
/**
* 加载场景资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config
* @return Promise<any> 资源
*/
async function loadScene(url, uuid?, cache = false, config?) {
const sceneConfig = await loadJson5(url);
const scene = new Scene();
scene.initByConfig(sceneConfig);
return scene;
}
/**
* 加载预制资源
* @param url url
* @param uuid 唯一名
* @param cache 是否缓存
* @param config
* @return Promise<any> 资源
*/
export async function loadPrefab(url, uuid?, cache = true, config?) {
let data = await loadJson5(url, uuid, false);
cacheRes(data, url, uuid);
return data;
}
addLoader('.pfb', loadPrefab);
/**
* Created by rockyl on 2018-12-03.
*
* 配置文件解释器
*/
import {Entity, Scene, ScillaEvent} from "../core";
import {getRes} from "../assets-manager";
import {EngineConfig} from "../engine-config";
let entityCache = {};
let entityCacheConfig;
const defMap = {};
let prefabID: number = 0;
/**
* 注册组件
* @param name
* @param def
*/
export function registerDef(name: string, def) {
defMap[name] = def;
def.__class__ = name;
}
function getEntityCacheConfig(config) {
return config['entity-cache'] ? config['entity-cache'].concat() : [];
}
/**
* 装配场景
* @param scene
* @param root
*/
export function setupScene(scene: Scene, root: Entity): Scene {
scene.root = root;
const config = scene.config;
entityCacheConfig = getEntityCacheConfig(config);
instantiateConfig(config.root, root);
entityCache = {};
return scene;
}
/**
* 清空实体
* @param entity
*/
export function cleanEntity(entity: Entity) {
entity.removeAllComponents();
entity.removeChildren();
}
/**
* 装配预制体
* @param config
*/
export function instantiate(config: any): Entity {
let pid = ++prefabID;
entityCacheConfig = getEntityCacheConfig(config);
for (let i = 0, li = entityCacheConfig.length; i < li; i++) {
entityCacheConfig[i] = pid + '_' + entityCacheConfig[i];
}
let rootConfig = config.root;
const entity = setupEntity(rootConfig, null, pid);
setupComponent(rootConfig, entity, true);
injectComponent(rootConfig, entity, true, pid);
entityCache = {};
return entity.children[0];
}
/**
* 装配树节点
* @param config
* @param root
*/
function instantiateConfig(config, root?: Entity): Entity {
const entity = setupEntity(config, root);
setupComponent(config, entity, true);
injectComponent(config, entity, true);
return entity;
}
/**
* 装配实体
* @param config
* @param root
* @param pid
*/
function setupEntity(config, root?: Entity, pid?: number): Entity {
let entity: Entity = null;
if (config) {
let {name, uuid, children} = config;
if (pid !== undefined && uuid !== undefined) {
uuid = pid + '_' + uuid;
}
entity = root || new Entity(name, uuid);
if (entityCacheConfig.indexOf(uuid) >= 0) {
entityCache[uuid] = entity;
}
if (children) {
for (let i = 0, li = children.length; i < li; i++) {
let child = children[i];
const childEntity = setupEntity(child, null, pid);
entity.addChild(childEntity);
}
}
if (!root) {
entity.enabled = !config.disabled;
}
}
return entity;
}
/**
* 装配组件
* @param config
* @param root
* @param includeSelf
*/
function setupComponent(config, root: Entity, includeSelf: boolean = false) {
if (includeSelf) {
instantiateComponents(root, config);
}
if (config && config.children) {
for (let i = 0, li = root.children.length; i < li; i++) {
const child = config.children[i];
const entity = root.children[i];
instantiateComponents(entity, child);
setupComponent(child, entity);
}
}
}
/**
* 注入组件参数
* @param config
* @param root
* @param includeSelf
* @param pid
*/
function injectComponent(config, root: Entity, includeSelf = false, pid?: number) {
if (includeSelf) {
injectComponents(root, config, pid);
}
if (config && config.children) {
for (let i = 0, li = root.children.length; i < li; i++) {
const child = config.children[i];
const entity = root.children[i];
injectComponents(entity, child, pid);
injectComponent(child, entity, false, pid);
}
}
}
/**
* 实例化组件列表
* @param entity
* @param config
*/
function instantiateComponents(entity: Entity, config: any) {
if (config.components) {
for (const component of config.components) {
instantiateComponent(entity, component);
}
}
}
/**
* 注入组件列表参数
* @param entity
* @param config
* @param pid
*/
function injectComponents(entity: Entity, config: any, pid?: number) {
if (config.components) {
const components = entity.components;
for (let i = 0, li = config.components.length; i < li; i++) {
const component = config.components[i];
injectComponentProperties(components[i], component, pid);
}
}
}
/**
* 注入组件属性
* @param component
* @param config
* @param pid
*/
export function injectComponentProperties(component, config, pid?: number){
const {properties} = config;
if (properties) {
injectProperties(component, properties, pid);
}
}
/**
* 实例化组件
* @param entity
* @param config
*/
export function instantiateComponent(entity: Entity, config: any) {
const {script, } = config;
let def = getDefByName(script);
if (!def) {
return;
}
const instance: any = new def();
instance.enabled = !config.disabled;
entity.addComponent(instance);
return instance;
}
/**
* 根据名称获取定义
* @param name
* @param showWarn
*/
export function getDefByName(name: string, showWarn: boolean = true): any {
let def;
/*if (name.indexOf('/') >= 0) {//addition
name = name.substr(name.lastIndexOf('/') + 1);
}*/
def = defMap[name];
if (!def && showWarn) {
console.warn('missing def:', name);
return;
}
return def;
}
const skipKeys = ['_type_', '_constructor_'];
/**
* 属性注入
* @param node
* @param propertiesConfig
* @param pid
*/
function injectProperties(node, propertiesConfig, pid?: number) {
if (!node) {
console.warn('node is null.');
return;
}
for (const key in propertiesConfig) {
if (skipKeys.indexOf(key) >= 0) {
continue;
}
const propertyOfConfig: any = propertiesConfig[key];
let propertyOfInstance = node[key];
if (typeof propertyOfConfig === 'object') {
if (propertyOfInstance instanceof ScillaEvent) {
if(!EngineConfig.editorMode){
injectEvent(propertyOfInstance, propertyOfConfig, pid);
}
} else if (propertyOfConfig._type_ === 'raw') {
node[key] = propertyOfInstance = propertyOfConfig.data;
} else {
if (Array.isArray(propertyOfConfig) && !propertyOfInstance) {
node[key] = propertyOfInstance = []
}
node[key] = injectObject(propertyOfInstance, propertyOfConfig, pid);
}
} else {
injectBaseType(node, key, propertyOfConfig, pid);
}
}
}
function injectObject(propertyOfInstance, propertyOfConfig, pid?: number) {
if (propertyOfInstance === undefined) {
if (propertyOfConfig._type_) {
let def = getDefByName(propertyOfConfig._type_);
if (def) {
let constructorArgs = propertyOfConfig._constructor_;
if (constructorArgs && constructorArgs.length > 0) {
propertyOfInstance = def.constructor.apply(null, constructorArgs);
} else {
propertyOfInstance = new def();
}
}
}
}
if (propertyOfInstance) {
injectProperties(propertyOfInstance, propertyOfConfig, pid);
}
return propertyOfInstance;
}
function injectBaseType(node, key, propertyOfConfig, pid?: number) {
let propertyValue;
if (typeof propertyOfConfig === 'string') {
propertyValue = getLink(propertyOfConfig, pid);
} else {
propertyValue = propertyOfConfig;
}
let keyAvatar = key;
if(propertyValue instanceof Promise){
keyAvatar = 'async_' + keyAvatar;
}
node[keyAvatar] = propertyValue;
}
function injectEvent(event: ScillaEvent, config, pid?) {
for (const {entity: entityName, component: componentIndex, method: methodName, param} of config) {
if (entityName && componentIndex >= 0 && methodName) {
const entity = getLink(entityName, pid);
const component = entity.components[componentIndex];
const method = component[methodName];
if (method) {
if (param == undefined) {
event.addListener(method, component, 0);
} else {
event.addListener(method, component, 0, param);
}
}
}
}
}
function getLink(str: string, pid?: number) {
let result;
if (str.indexOf('res|') == 0) { //res uuid
const uuid = str.substr(4);
result = getRes(uuid);
} else if (str.indexOf('entity|') == 0) { //entity uuid
const uuid = transPrefabUUID(str.substr(7), pid);
result = entityCache[uuid];
} else {
result = str;
}
return result;
}
function transPrefabUUID(uuid, pid: number) {
return pid ? pid + '_' + uuid : uuid;
}
/**
* Created by rockyl on 2018-12-05.
*/
import {injectProp} from "./tools/utils";
export const EngineConfig = {
lineHeightRatio: 1.2,
entityEnabled: true,
componentEnabled: true,
awakeComponentWhenAdded: true,
sleepComponentWhenRemoved: true,
drawRenderRect: false,
imgCrossOrigin: true,
editorMode: false,
};
export function modifyEngineConfig(_options) {
injectProp(EngineConfig, _options);
}
/**
* 投影或者发光滤镜
* @class ShadowFilter
* @public
* @since 1.0.0
*/
export class ShadowFilter {
/**
* 颜色值
* @property color
* @public
* @readonly
* @since 1.0.0
* @default black
* @type {string}
*/
public color: string = "black";
/**
* x方向投影距离
* @property offsetX
* @public
* @readonly
* @since 1.0.0
* @default 2
* @type {number}
*/
public offsetX: number = 2;
/**
* y方向投影距离
* @property offsetY
* @public
* @readonly
* @since 1.0.0
* @default 2
* @type {number}
*/
public offsetY: number = 2;
/**
* 模糊值
* @property blur
* @public
* @readonly
* @since 1.0.0
* @default 2
* @type {number}
*/
public blur: number = 2;
/**
* 滤镜类型 只读
* @property color
* @public
* @readonly
* @since 1.0.0
* @default Shadow
* @type {string}
*/
public type: string = "Shadow";
/**
* @method ShadowFilter
* @param {string} color
* @param {number} offsetX
* @param {number} offsetY
* @param {number} blur
*/
public constructor(color: string = "black", offsetX: number = 2, offsetY: number = 2, blur: number = 2) {
let s = this;
s.offsetX = offsetX;
s.offsetY = offsetY;
s.blur = blur;
s.color = color;
}
/**
*获取滤镜的字符串表现形式以方便比较两个滤镜是否效果一样
* @method toString
* @public
* @since 1.0.0
* @return {string}
*/
public toString(): string {
let s = this;
return s.type + s.offsetX + s.offsetY + s.blur + s.color;
}
/**
* 绘画滤镜效果
* @method drawFilter
* @public
* @since 1.0.0
* @param {ImageData} imageData
*/
public drawFilter(imageData: ImageData = null) {
//什么也不要做
}
public destroy(): void {
}
}
/**
* 普通变色滤镜
* @class ColorFilter
* @public
* @since 1.0.0
*/
export class ColorFilter {
/**
* @property redMultiplier
* @public
* @since 1.0.0
* @readonly
* @type {number}
*/
public redMultiplier: number = 0;
/**
* @property redOffset
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public redOffset: number = 0;
/**
* @property greenMultiplier
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public greenMultiplier: number = 0;
/**
* @property greenOffset
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public greenOffset: number = 0;
/**
* @property blueMultiplier
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public blueMultiplier: number = 0;
/**
* @property blueOffset
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public blueOffset: number = 0;
/**
* @property alphaMultiplier
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public alphaMultiplier: number = 0;
/**
* @property alphaOffset
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public alphaOffset: number = 0;
/**
* @property type
* @public
* @readonly
* @since 1.0.0
* @type {string}
*/
public type: string = "Color";
/**
* @method ColorFilter
* @param {number} colorArrays 颜色值数据
*/
public constructor(colorArrays: number[]) {
let s = this;
s.redMultiplier = colorArrays[0];
s.greenMultiplier = colorArrays[1];
s.blueMultiplier = colorArrays[2];
s.alphaMultiplier = colorArrays[3];
s.redOffset = colorArrays[4];
s.greenOffset = colorArrays[5];
s.blueOffset = colorArrays[6];
s.alphaOffset = colorArrays[7];
}
/**
* 绘画滤镜效果
* @method drawFilter
* @param {ImageData} imageData
* @since 1.0.0
* @public
*/
public drawFilter(imageData: ImageData = null) {
if (!imageData) return;
let s = this;
let data = imageData.data;
let l = data.length;
for (let i = 0; i < l; i += 4) {
data[i] = data[i] * s.redMultiplier + s.redOffset;
data[i + 1] = data[i + 1] * s.greenMultiplier + s.greenOffset;
data[i + 2] = data[i + 2] * s.blueMultiplier + s.blueOffset;
data[i + 3] = data[i + 3] * s.alphaMultiplier + s.alphaOffset;
}
}
/**
*获取滤镜的字符串表现形式以方便比较两个滤镜是否效果一样
* @method toString
* @public
* @since 1.0.0
* @return {string}
*/
public toString(): string {
let s = this;
return s.type + s.redMultiplier + s.greenMultiplier + s.blueMultiplier + s.alphaMultiplier + s.redOffset + s.greenOffset + s.blueOffset + s.alphaOffset;
}
public destroy(): void {
}
}
/**
* 矩阵变色滤镜
* @class ColorMatrixFilter
* @public
* @since 1.0.0
*/
export class ColorMatrixFilter {
/**
* @property brightness
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public brightness: number = 0;
/**
* @property contrast
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public contrast: number = 0;
/**
* @property saturation
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public saturation: number = 0;
/**
* @property hue
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public hue: number = 0;
/**
* 滤镜类型 只读
* @property type
* @public
* @readonly
* @since 1.0.0
* @type {string}
*/
public type: string = "ColorMatrix";
private colorMatrix: any;
/**
* @method ColorMatrixFilter
* @param {number} brightness
* @param {number} contrast
* @param {number} saturation
* @param {number} hue
* @public
* @since 1.0.0
*/
public constructor(brightness: number, contrast: number, saturation: number, hue: number) {
let s = this;
s.brightness = brightness;
s.contrast = contrast;
s.saturation = saturation;
s.hue = hue;
s.colorMatrix = [
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
];
//brightness
brightness = s._cleanValue(brightness, 255);
if (brightness != 0) {
s._multiplyMatrix([
1, 0, 0, 0, brightness,
0, 1, 0, 0, brightness,
0, 0, 1, 0, brightness,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
//contrast
contrast = this._cleanValue(contrast, 100);
let x: number;
if (contrast != 0) {
if (contrast < 0) {
x = 127 + contrast / 100 * 127;
} else {
x = contrast % 1;
if (x == 0) {
x = ColorMatrixFilter.DELTA_INDEX[contrast];
} else {
x = ColorMatrixFilter.DELTA_INDEX[(contrast << 0)] * (1 - x) + ColorMatrixFilter.DELTA_INDEX[(contrast << 0) + 1] * x; // use linear interpolation for more granularity.
}
x = x * 127 + 127;
}
s._multiplyMatrix([
x / 127, 0, 0, 0, 0.5 * (127 - x),
0, x / 127, 0, 0, 0.5 * (127 - x),
0, 0, x / 127, 0, 0.5 * (127 - x),
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
//saturation
saturation = this._cleanValue(saturation, 100);
if (saturation != 0) {
x = 1 + ((saturation > 0) ? 3 * saturation / 100 : saturation / 100);
let lumR = 0.3086;
let lumG = 0.6094;
let lumB = 0.0820;
s._multiplyMatrix([
lumR * (1 - x) + x, lumG * (1 - x), lumB * (1 - x), 0, 0,
lumR * (1 - x), lumG * (1 - x) + x, lumB * (1 - x), 0, 0,
lumR * (1 - x), lumG * (1 - x), lumB * (1 - x) + x, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
//hue
hue = this._cleanValue(hue, 180) / 180 * Math.PI;
if (hue != 0) {
let cosVal = Math.cos(hue);
let sinVal = Math.sin(hue);
let lumR = 0.213;
let lumG = 0.715;
let lumB = 0.072;
s._multiplyMatrix([
lumR + cosVal * (1 - lumR) + sinVal * (-lumR), lumG + cosVal * (-lumG) + sinVal * (-lumG), lumB + cosVal * (-lumB) + sinVal * (1 - lumB), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (0.143), lumG + cosVal * (1 - lumG) + sinVal * (0.140), lumB + cosVal * (-lumB) + sinVal * (-0.283), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (-(1 - lumR)), lumG + cosVal * (-lumG) + sinVal * (lumG), lumB + cosVal * (1 - lumB) + sinVal * (lumB), 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
}
/**
* 绘画滤镜效果
* @method drawFilter
* @param {ImageData} imageData
* @since 1.0.0
* @public
*/
public drawFilter(imageData: ImageData = null): void {
if (!imageData) return;
let data: any = imageData.data;
let l = data.length;
let r: number, g: number, b: number, a: number;
let mtx = this.colorMatrix;
let m0 = mtx[0], m1 = mtx[1], m2 = mtx[2], m3 = mtx[3], m4 = mtx[4];
let m5 = mtx[5], m6 = mtx[6], m7 = mtx[7], m8 = mtx[8], m9 = mtx[9];
let m10 = mtx[10], m11 = mtx[11], m12 = mtx[12], m13 = mtx[13], m14 = mtx[14];
let m15 = mtx[15], m16 = mtx[16], m17 = mtx[17], m18 = mtx[18], m19 = mtx[19];
for (let i = 0; i < l; i += 4) {
r = data[i];
g = data[i + 1];
b = data[i + 2];
a = data[i + 3];
data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4; //red
data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9; //green
data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14; //blue
data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19; //alpha
}
}
public static DELTA_INDEX = [
0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11,
0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24,
0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42,
0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68,
0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98,
1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54,
1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25,
2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8,
4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0,
7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8,
10.0
];
private _multiplyMatrix(colorMat: any) {
let i: number, j: number, k: number, col: any = [];
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
col[j] = this.colorMatrix[j + i * 5];
}
for (j = 0; j < 5; j++) {
let val = 0;
for (k = 0; k < 5; k++) {
val += colorMat[j + k * 5] * col[k];
}
this.colorMatrix[j + i * 5] = val;
}
}
}
private _cleanValue(value: number, limit: number): number {
return Math.min(limit, Math.max(-limit, value));
}
/**
*获取滤镜的字符串表现形式以方便比较两个滤镜是否效果一样
* @method toString
* @public
* @since 1.0.0
* @return {string}
*/
public toString(): string {
let s = this;
return s.type + s.brightness + s.hue + s.saturation + s.contrast;
}
public destroy(): void {
this.colorMatrix = null;
}
}
/**
* 模糊滤镜
* @class BlurFilter
* @public
* @since 1.0.0
*/
export class BlurFilter {
/**
* 滤镜类型 只读
* @property type
* @public
* @readonly
* @since 1.0.0
* @type {string}
*/
public type: string = "blur";
/**
* 水平模糊量
* @property blurX
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public blurX: number = 0;
/**
* 垂直模糊量
* @property blurY
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public blurY: number = 0;
/**
* 模糊品质
* @property quality
* @public
* @readonly
* @since 1.0.0
* @type {number}
*/
public quality: number = 1;
/**
* @method BlurFilter
* @public
* @since 1.0.0
* @param {number} blurX
* @param {number} blurY
* @param {number} quality
*/
public constructor(blurX: number = 2, blurY: number = 2, quality: number = 1) {
let s = this;
s.blurX = blurX;
s.blurY = blurY;
s.quality = quality;
}
/**
*获取滤镜的字符串表现形式以方便比较两个滤镜是否效果一样
* @method toString
* @public
* @since 1.0.0
* @return {string}
*/
public toString(): string {
let s = this;
return s.type + s.blurX + s.blurY + s.quality;
}
private static SHG_TABLE: any = [0, 9, 10, 11, 9, 12, 10, 11, 12, 9, 13, 13, 10, 9, 13, 13, 14, 14, 14, 14, 10, 13, 14, 14, 14, 13, 13, 13, 9, 14, 14, 14, 15, 14, 15, 14, 15, 15, 14, 15, 15, 15, 14, 15, 15, 15, 15, 15, 14, 15, 15, 15, 15, 15, 15, 12, 14, 15, 15, 13, 15, 15, 15, 15, 16, 16, 16, 15, 16, 14, 16, 16, 14, 16, 13, 16, 16, 16, 15, 16, 13, 16, 15, 16, 14, 9, 16, 16, 16, 16, 16, 16, 16, 16, 16, 13, 14, 16, 16, 15, 16, 16, 10, 16, 15, 16, 14, 16, 16, 14, 16, 16, 14, 16, 16, 14, 15, 16, 16, 16, 14, 15, 14, 15, 13, 16, 16, 15, 17, 17, 17, 17, 17, 17, 14, 15, 17, 17, 16, 16, 17, 16, 15, 17, 16, 17, 11, 17, 16, 17, 16, 17, 16, 17, 17, 16, 17, 17, 16, 17, 17, 16, 16, 17, 17, 17, 16, 14, 17, 17, 17, 17, 15, 16, 14, 16, 15, 16, 13, 16, 15, 16, 14, 16, 15, 16, 12, 16, 15, 16, 17, 17, 17, 17, 17, 13, 16, 15, 17, 17, 17, 16, 15, 17, 17, 17, 16, 15, 17, 17, 14, 16, 17, 17, 16, 17, 17, 16, 15, 17, 16, 14, 17, 16, 15, 17, 16, 17, 17, 16, 17, 15, 16, 17, 14, 17, 16, 15, 17, 16, 17, 13, 17, 16, 17, 17, 16, 17, 14, 17, 16, 17, 16, 17, 16, 17, 9];
private static MUL_TABLE: any = [1, 171, 205, 293, 57, 373, 79, 137, 241, 27, 391, 357, 41, 19, 283, 265, 497, 469, 443, 421, 25, 191, 365, 349, 335, 161, 155, 149, 9, 278, 269, 261, 505, 245, 475, 231, 449, 437, 213, 415, 405, 395, 193, 377, 369, 361, 353, 345, 169, 331, 325, 319, 313, 307, 301, 37, 145, 285, 281, 69, 271, 267, 263, 259, 509, 501, 493, 243, 479, 118, 465, 459, 113, 446, 55, 435, 429, 423, 209, 413, 51, 403, 199, 393, 97, 3, 379, 375, 371, 367, 363, 359, 355, 351, 347, 43, 85, 337, 333, 165, 327, 323, 5, 317, 157, 311, 77, 305, 303, 75, 297, 294, 73, 289, 287, 71, 141, 279, 277, 275, 68, 135, 67, 133, 33, 262, 260, 129, 511, 507, 503, 499, 495, 491, 61, 121, 481, 477, 237, 235, 467, 232, 115, 457, 227, 451, 7, 445, 221, 439, 218, 433, 215, 427, 425, 211, 419, 417, 207, 411, 409, 203, 202, 401, 399, 396, 197, 49, 389, 387, 385, 383, 95, 189, 47, 187, 93, 185, 23, 183, 91, 181, 45, 179, 89, 177, 11, 175, 87, 173, 345, 343, 341, 339, 337, 21, 167, 83, 331, 329, 327, 163, 81, 323, 321, 319, 159, 79, 315, 313, 39, 155, 309, 307, 153, 305, 303, 151, 75, 299, 149, 37, 295, 147, 73, 291, 145, 289, 287, 143, 285, 71, 141, 281, 35, 279, 139, 69, 275, 137, 273, 17, 271, 135, 269, 267, 133, 265, 33, 263, 131, 261, 130, 259, 129, 257, 1];
/**
* 绘画滤镜效果
* @method drawFilter
* @param {ImageData} imageData
* @since 1.0.0
* @public
*/
public drawFilter(imageData: ImageData = null) {
let s = this;
let radiusX = s.blurX >> 1;
if (isNaN(radiusX) || radiusX < 0) return false;
let radiusY = s.blurY >> 1;
if (isNaN(radiusY) || radiusY < 0) return false;
if (radiusX == 0 && radiusY == 0) return false;
let iterations = s.quality;
if (isNaN(iterations) || iterations < 1) iterations = 1;
iterations |= 0;
if (iterations > 3) iterations = 3;
if (iterations < 1) iterations = 1;
let px: any = imageData.data;
let x = 0, y = 0, i = 0, p = 0, yp = 0, yi = 0, yw = 0, r = 0, g = 0, b = 0, a = 0, pr = 0, pg = 0, pb = 0, pa = 0;
let divx = (radiusX + radiusX + 1) | 0;
let divy = (radiusY + radiusY + 1) | 0;
let w = imageData.width | 0;
let h = imageData.height | 0;
let w1 = (w - 1) | 0;
let h1 = (h - 1) | 0;
let rxp1 = (radiusX + 1) | 0;
let ryp1 = (radiusY + 1) | 0;
let ssx = { r: 0, b: 0, g: 0, a: 0 };
let sx: any = ssx;
for (i = 1; i < divx; i++) {
sx = sx.n = { r: 0, b: 0, g: 0, a: 0 };
}
sx.n = ssx;
let ssy = { r: 0, b: 0, g: 0, a: 0 };
let sy: any = ssy;
for (i = 1; i < divy; i++) {
sy = sy.n = { r: 0, b: 0, g: 0, a: 0 };
}
sy.n = ssy;
let si: any = null;
let mtx = BlurFilter.MUL_TABLE[radiusX] | 0;
let stx = BlurFilter.SHG_TABLE[radiusX] | 0;
let mty = BlurFilter.MUL_TABLE[radiusY] | 0;
let sty = BlurFilter.SHG_TABLE[radiusY] | 0;
while (iterations-- > 0) {
yw = yi = 0;
let ms = mtx;
let ss = stx;
for (y = h; --y > -1;) {
r = rxp1 * (pr = px[(yi) | 0]);
g = rxp1 * (pg = px[(yi + 1) | 0]);
b = rxp1 * (pb = px[(yi + 2) | 0]);
a = rxp1 * (pa = px[(yi + 3) | 0]);
sx = ssx;
for (i = rxp1; --i > -1;) {
sx.r = pr;
sx.g = pg;
sx.b = pb;
sx.a = pa;
sx = sx.n;
}
for (i = 1; i < rxp1; i++) {
p = (yi + ((w1 < i ? w1 : i) << 2)) | 0;
r += (sx.r = px[p]);
g += (sx.g = px[p + 1]);
b += (sx.b = px[p + 2]);
a += (sx.a = px[p + 3]);
sx = sx.n;
}
si = ssx;
for (x = 0; x < w; x++) {
px[yi++] = (r * ms) >>> ss;
px[yi++] = (g * ms) >>> ss;
px[yi++] = (b * ms) >>> ss;
px[yi++] = (a * ms) >>> ss;
p = ((yw + ((p = x + radiusX + 1) < w1 ? p : w1)) << 2);
r -= si.r - (si.r = px[p]);
g -= si.g - (si.g = px[p + 1]);
b -= si.b - (si.b = px[p + 2]);
a -= si.a - (si.a = px[p + 3]);
si = si.n;
}
yw += w;
}
ms = mty;
ss = sty;
for (x = 0; x < w; x++) {
yi = (x << 2) | 0;
r = (ryp1 * (pr = px[yi])) | 0;
g = (ryp1 * (pg = px[(yi + 1) | 0])) | 0;
b = (ryp1 * (pb = px[(yi + 2) | 0])) | 0;
a = (ryp1 * (pa = px[(yi + 3) | 0])) | 0;
sy = ssy;
for (i = 0; i < ryp1; i++) {
sy.r = pr;
sy.g = pg;
sy.b = pb;
sy.a = pa;
sy = sy.n;
}
yp = w;
for (i = 1; i <= radiusY; i++) {
yi = (yp + x) << 2;
r += (sy.r = px[yi]);
g += (sy.g = px[yi + 1]);
b += (sy.b = px[yi + 2]);
a += (sy.a = px[yi + 3]);
sy = sy.n;
if (i < h1) {
yp += w;
}
}
yi = x;
si = ssy;
if (iterations > 0) {
for (y = 0; y < h; y++) {
p = yi << 2;
px[p + 3] = pa = (a * ms) >>> ss;
if (pa > 0) {
px[p] = ((r * ms) >>> ss);
px[p + 1] = ((g * ms) >>> ss);
px[p + 2] = ((b * ms) >>> ss);
} else {
px[p] = px[p + 1] = px[p + 2] = 0
}
p = (x + (((p = y + ryp1) < h1 ? p : h1) * w)) << 2;
r -= si.r - (si.r = px[p]);
g -= si.g - (si.g = px[p + 1]);
b -= si.b - (si.b = px[p + 2]);
a -= si.a - (si.a = px[p + 3]);
si = si.n;
yi += w;
}
} else {
for (y = 0; y < h; y++) {
p = yi << 2;
px[p + 3] = pa = (a * ms) >>> ss;
if (pa > 0) {
pa = 255 / pa;
px[p] = ((r * ms) >>> ss) * pa;
px[p + 1] = ((g * ms) >>> ss) * pa;
px[p + 2] = ((b * ms) >>> ss) * pa;
} else {
px[p] = px[p + 1] = px[p + 2] = 0
}
p = (x + (((p = y + ryp1) < h1 ? p : h1) * w)) << 2;
r -= si.r - (si.r = px[p]);
g -= si.g - (si.g = px[p + 1]);
b -= si.b - (si.b = px[p + 2]);
a -= si.a - (si.a = px[p + 3]);
si = si.n;
yi += w;
}
}
}
}
}
public destroy(): void {
}
}
\ No newline at end of file
export { ShadowFilter } from './Filters';
export { ColorFilter } from './Filters';
export { ColorMatrixFilter } from './Filters';
export { BlurFilter } from './Filters';
\ No newline at end of file
/**
* Created by rockyl on 2018/11/15.
*/
export * from './core'
export * from './editor'
export * from './assets-manager'
export * from './support'
export * from './tools'
export * from './filter'
export * from './engine-config'
export * from './ReType'
\ No newline at end of file
/**
* Created by rockyl on 2018/11/7.
*
*/
/**
* 边界类
*/
export default class Bounds {
x: number;
y: number;
width: number;
height: number;
constructor(x: number = 0, y: number = 0, width: number = 0, height: number = 0) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
get left(): number {
return this.x;
}
set left(v: number) {
this.x = v;
}
get top(): number {
return this.y;
}
set top(v: number) {
this.y = v;
}
get right(): number {
return this.x + this.width;
}
set right(v: number) {
this.width = v - this.x;
}
get bottom(): number {
return this.y + this.height;
}
set bottom(v: number) {
this.height = v - this.y;
}
/**
* 是否包含点
* @param x
* @param y
*/
contains(x: number, y: number): boolean {
return this.x <= x &&
this.x + this.width >= x &&
this.y <= y &&
this.y + this.height >= y;
}
/**
* 设置
* @param x
* @param y
* @param width
* @param height
*/
setTo(x: number, y: number, width: number, height: number) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* 复制一个边界
* @param target
*/
copyFrom(target: Bounds) {
this.x = target.x;
this.y = target.y;
this.width = target.width;
this.height = target.height;
}
/**
* 克隆
*/
clone(): Bounds {
return new Bounds(this.x, this.y, this.width, this.height)
}
/**
* 扩展
* @param dx
* @param dy
*/
inflate(dx: number, dy: number) {
this.x -= dx;
this.width += 2 * dx;
this.y -= dy;
this.height += 2 * dy;
}
/**
* 是否是空边界
*/
isEmpty(): boolean {
return this.width <= 0 || this.height <= 0;
}
/**
* 置空
*/
setEmpty() {
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
}
/**
* 横切
* @param toIntersect
*/
intersects(toIntersect: Bounds): boolean {
return Math.max(this.x, toIntersect.x) <= Math.min(this.right, toIntersect.right)
&& Math.max(this.y, toIntersect.y) <= Math.min(this.bottom, toIntersect.bottom);
}
/**
* 是否包含另一个边界
* @param bounds
*/
containsBounds(bounds: Bounds): boolean {
let r1 = bounds.x + bounds.width;
let b1 = bounds.y + bounds.height;
let r2 = this.x + this.width;
let b2 = this.y + this.height;
return (bounds.x >= this.x) && (bounds.x < r2) && (bounds.y >= this.y) && (bounds.y < b2) && (r1 > this.x) && (r1 <= r2) && (b1 > this.y) && (b1 <= b2);
}
/**
* 判断是否相等
* @param toCompare
*/
equals(toCompare: Bounds): boolean {
if (this === toCompare) {
return true;
}
return this.x === toCompare.x && this.y === toCompare.y
&& this.width === toCompare.width && this.height === toCompare.height;
}
toString(): string {
const {x, y, width, height} = this;
return "(x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + ")";
}
}
/**
* Created by rockyl on 2018-11-25.
*/
'use strict';
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = '';
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Add a listener for a given event.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} once Specify if the listener is a one-time listener.
* @returns {EventEmitter}
* @private
*/
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
/**
* Clear event by name.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} evt The Event name.
* @private
*/
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
/**
* 事件发射器
*/
export default class EventEmitter{
_events;
_eventsCount;
off;
addListener;
static get prefixed(){
return prefix;
}
constructor() {
this._events = new Events();
this._eventsCount = 0;
this.off = this.removeListener;
this.addListener = this.on;
}
/**
* 正在侦听的事件名
*/
eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
//if (Object.getOwnPropertySymbols) {
// return names.concat(Object.getOwnPropertySymbols(events));
//}
return names;
}
/**
* 获取侦听者
* @param event
*/
listeners(event) {
var evt = prefix ? prefix + event : event
, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
}
/**
* 获取侦听者数量
* @param event
*/
listenerCount(event) {
var evt = prefix ? prefix + event : event
, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
}
/**
* 发送事件
* @param event
* @param a1
* @param a2
* @param a3
* @param a4
* @param a5
*/
emit(event, a1?, a2?, a3?, a4?, a5?) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
}
/**
* 侦听
* @param event
* @param fn
* @param context
*/
on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
/**
* 侦听一次
* @param event
* @param fn
* @param context
*/
once(event, fn, context) {
return addListener(this, event, fn, context, true);
}
/**
* 移除侦听
* @param event
* @param fn
* @param context
* @param once
*/
removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn &&
(!once || listeners.once) &&
(!context || listeners.context === context)
) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn ||
(once && !listeners[i].once) ||
(context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
}
/**
* 移除全部侦听
* @param event
*/
removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
}
}
\ No newline at end of file
/**
* Created by rockyl on 2019-01-04.
*/
/**
* 本地存储
*/
export default class LocalStorage {
ID: string;
constructor(ID: string) {
this.ID = ID;
}
private getName(key: string, prefix: string = null): string {
return (prefix || !this.ID || this.ID == '' ? prefix : this.ID) + '_' + key;
}
/**
* 获取数据
* @param key
* @param prefix
*/
getItem(key: string, prefix: string = null): string {
return localStorage.getItem(this.getName(key, prefix));
}
/**
* 设置数据
* @param key
* @param value
* @param prefix
*/
setItem(key: string, value: string, prefix: string = null) {
localStorage.setItem(this.getName(key, prefix), value);
}
/**
* 获取json数据对象
* @param key
* @param defaultObj
* @param prefix
*/
getItemObj(key: string, defaultObj: any = null, prefix: string = null): any {
let result: any;
try {
result = JSON.parse(this.getItem(key, prefix));
} catch (e) {
}
if (!result) {
result = defaultObj;
}
return result;
}
/**
* 设置json数据对象
* @param key
* @param itemObj
* @param prefix
*/
setItemObj(key: string, itemObj: any, prefix: string = null) {
this.setItem(key, JSON.stringify(itemObj), prefix);
}
}
/**
* Created by rockyl on 2018/11/6.
*
* 矩阵 3x3
*/
let PI = Math.PI;
let TwoPI = PI * 2;
let DEG_TO_RAD = PI / 180;
let matrixPool = [];
/**
* Matrix 类表示一个转换矩阵,它确定如何将点从一个坐标空间映射到另一个坐标空间。
* 您可以对一个显示对象执行不同的图形转换,方法是设置 Matrix 对象的属性,将该 Matrix
* 对象应用于显示对象的 matrix 属性。这些转换函数包括平移(x 和 y 重新定位)、旋转、缩放和倾斜。
*/
export default class Matrix {
a;
b;
c;
d;
tx;
ty;
/**
* 释放一个Matrix实例到对象池
* @param matrix 需要回收的 matrix
*/
static release(matrix) {
if (!matrix) {
return;
}
matrixPool.push(matrix);
}
/**
* 从对象池中取出或创建一个新的Matrix对象。
*/
static create() {
let matrix = matrixPool.pop();
if (!matrix) {
matrix = new Matrix();
}
return matrix;
}
/**
* 使用指定参数创建一个 Matrix 对象
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值。
* @param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。
* @param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值。
* @param tx 沿 x 轴平移每个点的距离。
* @param ty 沿 y 轴平移每个点的距离。
*/
constructor(a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.tx = tx;
this.ty = ty;
}
/**
* 返回一个新的 Matrix 对象,它是此矩阵的克隆,带有与所含对象完全相同的副本。
*/
clone() {
const m = Matrix.create();
m.setTo(this.a, this.b, this.c, this.d, this.tx, this.ty)
return m
}
/**
* 将某个矩阵与当前矩阵连接,从而将这两个矩阵的几何效果有效地结合在一起。在数学术语中,将两个矩阵连接起来与使用矩阵乘法将它们结合起来是相同的。
* @param other 要连接到源矩阵的矩阵。
*/
concat(other) {
let a = this.a * other.a;
let b = 0.0;
let c = 0.0;
let d = this.d * other.d;
let tx = this.tx * other.a + other.tx;
let ty = this.ty * other.d + other.ty;
if (this.b !== 0.0 || this.c !== 0.0 || other.b !== 0.0 || other.c !== 0.0) {
a += this.b * other.c;
d += this.c * other.b;
b += this.a * other.b + this.b * other.d;
c += this.c * other.a + this.d * other.c;
tx += this.ty * other.c;
ty += this.tx * other.b;
}
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.tx = tx;
this.ty = ty;
}
/**
* 将源 Matrix 对象中的所有矩阵数据复制到调用方 Matrix 对象中。
* @param other 要拷贝的目标矩阵
*/
copyFrom(other) {
this.a = other.a;
this.b = other.b;
this.c = other.c;
this.d = other.d;
this.tx = other.tx;
this.ty = other.ty;
return this;
}
/**
* 为每个矩阵属性设置一个值,该值将导致矩阵无转换。通过应用恒等矩阵转换的对象将与原始对象完全相同。
* 调用 identity() 方法后,生成的矩阵具有以下属性:a=1、b=0、c=0、d=1、tx=0 和 ty=0。
*/
identity() {
this.a = this.d = 1;
this.b = this.c = this.tx = this.ty = 0;
}
/**
* 执行原始矩阵的逆转换。
* 您可以将一个逆矩阵应用于对象来撤消在应用原始矩阵时执行的转换。
*/
invert() {
this.$invertInto(this);
}
/**
* @private
*/
$invertInto(target) {
let a = this.a;
let b = this.b;
let c = this.c;
let d = this.d;
let tx = this.tx;
let ty = this.ty;
if (b == 0 && c == 0) {
target.b = target.c = 0;
if (a == 0 || d == 0) {
target.a = target.d = target.tx = target.ty = 0;
}
else {
a = target.a = 1 / a;
d = target.d = 1 / d;
target.tx = -a * tx;
target.ty = -d * ty;
}
return;
}
let determinant = a * d - b * c;
if (determinant == 0) {
target.identity();
return;
}
determinant = 1 / determinant;
let k = target.a = d * determinant;
b = target.b = -b * determinant;
c = target.c = -c * determinant;
d = target.d = a * determinant;
target.tx = -(k * tx + c * ty);
target.ty = -(b * tx + d * ty);
}
/**
* 对 Matrix 对象应用旋转转换。
* rotate() 方法将更改 Matrix 对象的 a、b、c 和 d 属性。
* @param radian 以弧度为单位的旋转角度。
*/
rotate(radian) {
radian = +radian;
if (radian !== 0) {
//angle = angle / DEG_TO_RAD;
let u = Math.cos(radian);
let v = Math.sin(radian);
const {a, b, c, d, tx, ty} = this;
this.a = a * u - b * v;
this.b = a * v + b * u;
this.c = c * u - d * v;
this.d = c * v + d * u;
this.tx = tx * u - ty * v;
this.ty = tx * v + ty * u;
}
}
/**
* 获取弧度
*/
get rotation(){
return Math.atan2(this.b, this.a);
}
/**
* 对矩阵应用缩放转换。x 轴乘以 sx,y 轴乘以 sy。
* scale() 方法将更改 Matrix 对象的 a 和 d 属性。
* @param sx 用于沿 x 轴缩放对象的乘数。
* @param sy 用于沿 y 轴缩放对象的乘数。
*/
scale(sx, sy) {
if (sx !== 1) {
this.a *= sx;
this.c *= sx;
this.tx *= sx;
}
if (sy !== 1) {
this.b *= sy;
this.d *= sy;
this.ty *= sy;
}
}
/**
* 将 Matrix 的成员设置为指定值
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值。
* @param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。
* @param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值。
* @param tx 沿 x 轴平移每个点的距离。
* @param ty 沿 y 轴平移每个点的距离。
*/
setTo(a, b, c, d, tx, ty) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.tx = tx;
this.ty = ty;
return this;
}
/**
* 返回将 Matrix 对象表示的几何转换应用于指定点所产生的结果。
* @param pointX 想要获得其矩阵转换结果的点的x坐标。
* @param pointY 想要获得其矩阵转换结果的点的y坐标。
* @param resultPoint 框架建议尽可能减少创建对象次数来优化性能,可以从外部传入一个复用的Point对象来存储结果,若不传入将创建一个新的Point对象返回。
* @returns Object 由应用矩阵转换所产生的点。
*/
transformPoint(pointX, pointY, resultPoint) {
const {a, b, c, d, tx, ty} = this;
let x = a * pointX + c * pointY + tx;
let y = b * pointX + d * pointY + ty;
if (resultPoint) {
resultPoint.x = x;
resultPoint.y = y;
return resultPoint;
}
return {x, y};
}
/**
* 如果给定预转换坐标空间中的点,则此方法返回发生转换后该点的坐标。
* 与使用 transformPoint() 方法应用的标准转换不同,deltaTransformPoint() 方法的转换不考虑转换参数 tx 和 ty。
* @param pointX 想要获得其矩阵转换结果的点的x坐标。
* @param pointY 想要获得其矩阵转换结果的点的y坐标。
* @param resultPoint 框架建议尽可能减少创建对象次数来优化性能,可以从外部传入一个复用的Point对象来存储结果,若不传入将创建一个新的Point对象返回。
*/
deltaTransformPoint(pointX, pointY, resultPoint) {
const {a, b, c, d} = this;
let x = a * pointX + c * pointY;
let y = b * pointX + d * pointY;
if (resultPoint) {
resultPoint.x = x;
resultPoint.y = y;
return resultPoint;
}
return {x, y};
}
/**
* 沿 x 和 y 轴平移矩阵,由 dx 和 dy 参数指定。
* @param dx 沿 x 轴向右移动的量(以像素为单位)。
* @param dy 沿 y 轴向下移动的量(以像素为单位)。
*/
translate(dx, dy) {
this.tx += dx;
this.ty += dy;
}
/**
* 是否与另一个矩阵数据相等
* @param other 要比较的另一个矩阵对象。
* @returns 是否相等,ture表示相等。
*/
equals(other) {
return this.a == other.a && this.b == other.b &&
this.c == other.c && this.d == other.d &&
this.tx == other.tx && this.ty == other.ty;
}
/**
* 前置矩阵
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param b 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param c 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param tx 沿 x 轴平移每个点的距离
* @param ty 沿 y 轴平移每个点的距离
* @returns 矩阵自身
*/
prepend(a, b, c, d, tx, ty) {
let tx1 = this.tx;
if (a != 1 || b != 0 || c != 0 || d != 1) {
let a1 = this.a;
let c1 = this.c;
this.a = a1 * a + this.b * c;
this.b = a1 * b + this.b * d;
this.c = c1 * a + this.d * c;
this.d = c1 * b + this.d * d;
}
this.tx = tx1 * a + this.ty * c + tx;
this.ty = tx1 * b + this.ty * d + ty;
return this;
}
/**
* 后置矩阵
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param b 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param c 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param tx 沿 x 轴平移每个点的距离
* @param ty 沿 y 轴平移每个点的距离
* @returns 矩阵自身
*/
append(a, b, c, d, tx, ty) {
let a1 = this.a;
let b1 = this.b;
let c1 = this.c;
let d1 = this.d;
if (a != 1 || b != 0 || c != 0 || d != 1) {
this.a = a * a1 + b * c1;
this.b = a * b1 + b * d1;
this.c = c * a1 + d * c1;
this.d = c * b1 + d * d1;
}
this.tx = tx * a1 + ty * c1 + this.tx;
this.ty = tx * b1 + ty * d1 + this.ty;
return this;
}
/**
* 返回将 Matrix 对象表示的几何转换应用于指定点所产生的结果。
* @returns 一个字符串,它包含 Matrix 对象的属性值:a、b、c、d、tx 和 ty。
*/
toString() {
return "(a=" + this.a + ", b=" + this.b + ", c=" + this.c + ", d=" + this.d + ", tx=" + this.tx + ", ty=" + this.ty + ")";
}
/**
* 包括用于缩放、旋转和转换的参数。当应用于矩阵时,该方法会基于这些参数设置矩阵的值。
* @param scaleX 水平缩放所用的系数
* @param scaleY 垂直缩放所用的系数
* @param rotation 旋转量(以弧度为单位)
* @param tx 沿 x 轴向右平移(移动)的像素数
* @param ty 沿 y 轴向下平移(移动)的像素数
*/
createBox(scaleX, scaleY, rotation = 0, tx = 0, ty = 0) {
let self = this;
if (rotation !== 0) {
rotation = rotation / DEG_TO_RAD;
let u = Math.cos(rotation);
let v = Math.sin(rotation);
self.a = u * scaleX;
self.b = v * scaleY;
self.c = -v * scaleX;
self.d = u * scaleY;
} else {
self.a = scaleX;
self.b = 0;
self.c = 0;
self.d = scaleY;
}
self.tx = tx;
self.ty = ty;
}
/**
* 创建 Graphics 类的 beginGradientFill() 和 lineGradientStyle() 方法所需的矩阵的特定样式。
* 宽度和高度被缩放为 scaleX/scaleY 对,而 tx/ty 值偏移了宽度和高度的一半。
* @param width 渐变框的宽度
* @param height 渐变框的高度
* @param rotation 旋转量(以弧度为单位)
* @param tx 沿 x 轴向右平移的距离(以像素为单位)。此值将偏移 width 参数的一半
* @param ty 沿 y 轴向下平移的距离(以像素为单位)。此值将偏移 height 参数的一半
*/
createGradientBox(width, height, rotation = 0, tx = 0, ty = 0) {
this.createBox(width / 1638.4, height / 1638.4, rotation, tx + width / 2, ty + height / 2);
}
/**
* @private
*/
$transformBounds(bounds) {
let a = this.a;
let b = this.b;
let c = this.c;
let d = this.d;
let tx = this.tx;
let ty = this.ty;
let x = bounds.x;
let y = bounds.y;
let xMax = x + bounds.width;
let yMax = y + bounds.height;
let x0 = a * x + c * y + tx;
let y0 = b * x + d * y + ty;
let x1 = a * xMax + c * y + tx;
let y1 = b * xMax + d * y + ty;
let x2 = a * xMax + c * yMax + tx;
let y2 = b * xMax + d * yMax + ty;
let x3 = a * x + c * yMax + tx;
let y3 = b * x + d * yMax + ty;
let tmp = 0;
if (x0 > x1) {
tmp = x0;
x0 = x1;
x1 = tmp;
}
if (x2 > x3) {
tmp = x2;
x2 = x3;
x3 = tmp;
}
bounds.x = Math.floor(x0 < x2 ? x0 : x2);
bounds.width = Math.ceil((x1 > x3 ? x1 : x3) - bounds.x);
if (y0 > y1) {
tmp = y0;
y0 = y1;
y1 = tmp;
}
if (y2 > y3) {
tmp = y2;
y2 = y3;
y3 = tmp;
}
bounds.y = Math.floor(y0 < y2 ? y0 : y2);
bounds.height = Math.ceil((y1 > y3 ? y1 : y3) - bounds.y);
}
/**
* @private
*/
getDeterminant() {
return this.a * this.d - this.b * this.c;
}
/**
* @private
*/
$getScaleX() {
let m = this;
if (m.b == 0) {
return m.a;
}
let result = Math.sqrt(m.a * m.a + m.b * m.b);
return this.getDeterminant() < 0 ? -result : result;
}
/**
* @private
*/
$getScaleY() {
let m = this;
if (m.c == 0) {
return m.d;
}
let result = Math.sqrt(m.c * m.c + m.d * m.d);
return this.getDeterminant() < 0 ? -result : result;
}
/**
* @private
*/
$getSkewX() {
if (this.d < 0) {
return Math.atan2(this.d, this.c) + (PI / 2);
}
else {
return Math.atan2(this.d, this.c) - (PI / 2);
}
}
/**
* @private
*/
$getSkewY() {
if (this.a < 0) {
return Math.atan2(this.b, this.a) - PI;
}
else {
return Math.atan2(this.b, this.a);
}
}
/**
* @private
*/
$updateScaleAndRotation(scaleX, scaleY, skewX, skewY) {
if ((skewX == 0 || skewX == TwoPI) && (skewY == 0 || skewY == TwoPI)) {
this.a = scaleX;
this.b = this.c = 0;
this.d = scaleY;
return;
}
skewX = skewX / DEG_TO_RAD;
skewY = skewY / DEG_TO_RAD;
let u = Math.cos(skewX);
let v = Math.sin(skewX);
if (skewX == skewY) {
this.a = u * scaleX;
this.b = v * scaleX;
} else {
this.a = Math.cos(skewY) * scaleX;
this.b = Math.sin(skewY) * scaleX;
}
this.c = -v * scaleY;
this.d = u * scaleY;
}
/**
* @private
* target = other * this
*/
$preMultiplyInto(other, target) {
let a = other.a * this.a;
let b = 0.0;
let c = 0.0;
let d = other.d * this.d;
let tx = other.tx * this.a + this.tx;
let ty = other.ty * this.d + this.ty;
if (other.b !== 0.0 || other.c !== 0.0 || this.b !== 0.0 || this.c !== 0.0) {
a += other.b * this.c;
d += other.c * this.b;
b += other.a * this.b + other.b * this.d;
c += other.c * this.a + other.d * this.c;
tx += other.ty * this.c;
ty += other.tx * this.b;
}
target.a = a;
target.b = b;
target.c = c;
target.d = d;
target.tx = tx;
target.ty = ty;
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/8/1.
*
* 对象池
*/
let all = {};
function getGroup(name){
let group = all[name];
if(!group){
throw new Error('group ' + name + ' not registered.');
}
return group;
}
export function register(name, newFunc, initFunc){
all[name] = {name, newFunc, initFunc, pool: []};
}
export function get(name, ...params){
let group = getGroup(name);
let {newFunc, initFunc, pool} = group;
let instance;
if(pool.length == 0){
instance = newFunc();
}else{
instance = pool.pop();
}
initFunc(instance, ...params);
return instance;
}
export function recycle(name, instance){
let group = getGroup(name);
group.pool.push(instance);
}
\ No newline at end of file
/**
* Created by rockyl on 2018-12-07.
*/
import {dirtyFieldTrigger} from "../tools/decorators";
/**
* 尺寸
*/
export default class Size {
@dirtyFieldTrigger
width: number;
@dirtyFieldTrigger
height: number;
onChange;
constructor(width = NaN, height = NaN) {
this.width = width;
this.height = height;
}
setNaN(){
this.width = NaN;
this.height = NaN;
}
isEmpty(){
}
set(width?, height?) {
if (width !== undefined) {
this.width = width;
}
if (height !== undefined) {
this.height = height;
}
}
clone() {
return new Size(this.width, this.height);
}
copyFrom(target) {
this.width = target.width;
this.height = target.height;
}
onModify(value, key, oldValue) {
this.onChange && this.onChange(value, key, oldValue);
}
}
/**
* Created by rockyl on 2018-11-29.
*/
import {dirtyFieldTrigger} from "../tools/decorators";
export enum FontStyle{
/**
* 正常
*/
NORMAL = 'normal',
/**
* 斜体
*/
ITALIC = 'italic',
/**
* 倾斜
*/
OBLIQUE = 'oblique',
}
export enum FontVariant{
/**
* 正常
*/
NORMAL = 'normal',
/**
* 小型大写
*/
SMALL_CAPS = 'small-caps',
}
export enum FontWeight{
/**
* 正常
*/
NORMAL = 'normal',
/**
* 粗体
*/
BOLD = 'bold',
/**
* 更粗
*/
BOLDER = 'bolder',
/**
* 更细
*/
LIGHTER = 'lighter',
}
/**
* 文本样式
*/
export class TextStyle {
private readonly _callback;
onChange;
/**
* 字体样式
*/
@dirtyFieldTrigger
fontStyle: FontStyle = FontStyle.NORMAL;
/**
* 字体倾斜
*/
@dirtyFieldTrigger
fontVariant: FontVariant = FontVariant.NORMAL;
/**
* 字体宽度
*/
@dirtyFieldTrigger
fontWeight: FontWeight = FontWeight.NORMAL;
/**
* 字体尺寸
*/
@dirtyFieldTrigger
fontSize: number = 25;
/**
* 字体名称
*/
@dirtyFieldTrigger
fontFamily: string = 'Arial';
onModify(value, key, oldValue) {
this.onChange && this.onChange(value, key, oldValue, 'textStyle');
}
}
/**
* Created by rockyl on 2018/11/8.
*
*/
import {Component} from "../core";
import {lerp, lerpObj} from "../tools/math";
import {injectProp} from "../tools/utils";
import HashObject from "../core/HashObject";
enum STATUS {
IDLE,
PENDING,
DO_SET,
DO_TO,
DO_WAIT,
DO_CALL,
}
export interface ITweenPlugin {
//resolveLerp(fromValue, toValue, ratio, allowOutOfBounds):any;
}
export interface TweenOptions {
loop?: number;
autoPlay?: boolean;
initFields?: string[];
clazz?: any;
fields?: string[];
}
/**
* 补间动画
* @param host
* @param target
* @param override
* @param options
* @param plugins
*/
export function createTween(host: any, target: any, override = false, options?: TweenOptions, plugins = []) {
if (override) {
killTweens(target);
}
const tween = new Tween(host, target, options);
addTween(target, tween);
return tween;
}
/**
* 移除对象上所有的Tween实例
* @param target
*/
export function killTweens(target: any) {
let tweens: Tween[] = target['tweens'];
if (tweens) {
for (let tween of tweens) {
tween.stop();
}
tweens.splice(0);
}
}
function addTween(target, tween: Tween) {
let tweens: Tween[] = target['tweens'];
if (!tweens) {
tweens = target['tweens'] = [];
}
tweens.push(tween);
}
export class Tween extends HashObject {
host: any;
target: any;
loop: number;
queue = [];
loopCounting: number = 0;
step: number;
status: STATUS = STATUS.IDLE;
t;
startTime;
plugins: ITweenPlugin[];
clazz;
fields;
autoPlay: boolean;
initProps: any;
fromProps: any;
toProps: any;
ease: Function;
duration: number;
constructor(host: any, target: any, options?: TweenOptions, plugins = []) {
super();
this.host = host;
this.target = target;
this.loop = options ? options.loop : 0;
this.autoPlay = options ? (options.hasOwnProperty('autoPlay') ? options.autoPlay : true) : true;
this.clazz = options ? options.clazz : null;
this.fields = options ? options.fields : null;
this.plugins = plugins;
if (options && options.initFields && options.initFields.length > 0) {
this.initProps = this.getInitProps(options.initFields);
}
}
onUpdate = (t) => {
this.t = t;
switch (this.status) {
case STATUS.DO_TO:
var {target, startTime, fromProps, toProps, duration, ease, clazz, fields} = this;
var passTime = t - startTime;
let timeRatio = Math.min(1, passTime / duration);
let ratio = timeRatio;
if (ease) {
ratio = ease(ratio);
}
for (let key in fromProps) {
const toValue = toProps[key];
const fromValue = fromProps[key];
let currentValue;
if (timeRatio < 1) {
if (typeof toValue == 'object') {
currentValue = lerpObj(fromValue, toValue, ratio, clazz, fields || Object.keys(toValue), true);
} else {
currentValue = lerp(fromValue, toValue, ratio, true);
}
} else {
currentValue = toValue;
}
target[key] = currentValue;
}
if (timeRatio >= 1) {
this._doNextAction();
}
break;
case STATUS.DO_WAIT:
var {startTime, duration} = this;
var passTime = t - startTime;
if (passTime > duration) {
this._doNextAction();
}
break;
}
};
private getInitProps(fields) {
const props = {};
for (let field of fields) {
if (field in this.target) {
props[field] = this.target[field];
}
}
return props;
}
set(props) {
this.queue.push({action: 'set', props});
if (this.autoPlay) {
this._start();
}
return this;
}
to(props, duration?, ease?) {
this.queue.push({action: 'to', props, duration, ease});
if (this.autoPlay) {
this._start();
}
return this;
}
wait(duration) {
this.queue.push({action: 'wait', duration});
if (this.autoPlay) {
this._start();
}
return this;
}
call(func, thisObj?, params?) {
this.queue.push({action: 'call', func, thisObj, params});
if (this.autoPlay) {
this._start();
}
return this;
}
play(override = false, delay: number = 0, resetLoopCounting: boolean = true) {
if (override) {
killTweens(this.target);
}
if(delay > 0){
setTimeout(this._doPlay, delay, resetLoopCounting)
}else{
this._doPlay(resetLoopCounting);
}
}
private _doPlay=(resetLoopCounting)=>{
addTween(this.target, this);
this._start(resetLoopCounting);
};
stop() {
this.status = STATUS.IDLE;
this.host.cancelOnNextTick(this.onUpdate);
}
_set(props) {
this.status = STATUS.DO_SET;
injectProp(this.target, props);
this._doNextAction();
}
_to(props, duration, ease) {
this.status = STATUS.DO_TO;
this.startTime = this.t;
this.fromProps = {};
for (let key in props) {
this.fromProps[key] = this.target[key];
}
this.toProps = {};
injectProp(this.toProps, props);
this.ease = ease;
this.duration = duration;
//this.tween = annie.Tween.to(this.target, (duration / 1000) || 0, _props)
}
_wait(duration) {
this.status = STATUS.DO_WAIT;
this.startTime = this.t;
this.duration = duration;
/*setTimeout(() => {
this._doNextAction();
}, duration)*/
}
_call(func, thisObj, params) {
this.status = STATUS.DO_CALL;
func.apply(thisObj, params);
this._doNextAction();
}
_start(resetLoopCounting: boolean = true) {
this.status = STATUS.PENDING;
if(resetLoopCounting){
this.loopCounting = 0;
}
this.host.callOnNextTick(this._readyStart);
this.host.callOnNextTick(this.onUpdate, false);
}
_readyStart = (t) => {
this.t = t;
this._doStart();
};
_doStart() {
if (this.status == STATUS.IDLE) {
return;
}
this.step = 0;
this.loopCounting++;
if (this.loopCounting > 1 && this.initProps) {
injectProp(this.target, this.initProps);
}
this._doNextAction();
};
_doNextAction = () => {
if (this.step < this.queue.length) {
let action = this.queue[this.step++];
switch (action.action) {
case 'set':
this._set(action.props);
break;
case 'to':
if (action.duration > 0) {
this._to(action.props, action.duration, action.ease);
} else {
this._set(action.props);
}
break;
case 'wait':
this._wait(action.duration);
break;
case 'call':
this._call(action.func, action.thisObj, action.params);
break;
}
} else {
if (this.loop < 0) {
this._doStart();
} else if (this.loopCounting < this.loop) {
this._doStart();
} else {
this.status = STATUS.IDLE;
}
}
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/11/6.
*
*/
import {get, recycle, register} from "./ObjectPool";
const name = 'Vector2D';
register(name, function () {
return new Vector2D();
}, function (instance: Vector2D, x, y) {
instance.setXY(x, y);
});
/**
* 创建2D矢量
* @param x
* @param y
*/
export function createVector2D(x = 0, y = 0) {
return get(name, x, y);
}
/**
* 回收2D矢量
* @param target
*/
export function releaseVector2D(target) {
recycle(name, target);
}
/**
* 2D矢量
*/
export default class Vector2D {
_x: number;
_y: number;
onChange;
public static get zero(): Vector2D {
return zero;
}
constructor(x = 0, y = 0, onChange?) {
this.onChange = onChange;
this._x = 0;
this._y = 0;
this.setXY(x, y);
}
get x(): number {
return this._x;
}
set x(v: number) {
if (this._x !== v) {
const old = this._x;
this._x = v;
this.onChange && this.onChange(v, 'x', old);
}
}
get y(): number {
return this._y;
}
set y(v: number) {
if (this._y !== v) {
const old = this._y;
this._y = v;
this.onChange && this.onChange(v, 'y', old);
}
}
setXY(x = 0, y = 0): Vector2D {
this.x = x;
this.y = y;
return this;
}
copyFrom(v2): Vector2D {
this.x = v2.x;
this.y = v2.y;
return this;
}
clone(): Vector2D {
return new Vector2D(this.x, this.y);
}
zero(): Vector2D {
this.x = 0;
this.y = 0;
return this;
}
get isZero(): boolean {
return this.x == 0 && this.y == 0;
}
normalize(): Vector2D {
let len = this.length;
if (len == 0) {
this.x = 1;
return this;
}
this.x /= len;
this.y /= len;
return this;
}
get isNormalized(): boolean {
return this.length == 1.0;
}
truncate(max): Vector2D {
this.length = Math.min(max, this.length);
return this;
}
reverse(): Vector2D {
this.x = -this.x;
this.y = -this.y;
return this;
}
dotProd(v2): number {
return this.x * v2.x + this.y * v2.y;
}
crossProd(v2): number {
return this.x * v2.y - this.y * v2.x;
}
distSQ(v2): number {
let dx = v2.x - this.x;
let dy = v2.y - this.y;
return dx * dx + dy * dy;
}
distance(v2): number {
return Math.sqrt(this.distSQ(v2));
}
add(v2): Vector2D {
this.x += v2.x;
this.y += v2.y;
return this;
}
subtract(v2): Vector2D {
this.x -= v2.x;
this.y -= v2.y;
return this;
}
multiply(value): Vector2D {
this.x *= value;
this.y *= value;
return this;
}
divide(value): Vector2D {
this.x /= value;
this.y /= value;
return this;
}
set angle(value: number) {
this.radian = value * Math.PI / 180;
}
get angle(): number {
return this.radian * 180 / Math.PI;
}
set radian(value: number) {
let len = this.length;
this.setXY(Math.cos(value) * len, Math.sin(value) * len);
}
get radian(): number {
return Math.atan2(this.y, this.x);
}
equals(v2): boolean {
return this.x == v2.x && this.y == v2.y;
}
set length(value: number) {
let a = this.radian;
this.setXY(Math.cos(a) * value, Math.sin(a) * value);
}
get length(): number {
return Math.sqrt(this.lengthSQ);
}
get lengthSQ(): number {
return this.x * this.x + this.y * this.y;
}
get slope(): number {
return this.y / this.x;
}
toString(): string {
return "[Vector2D (x:" + this.x + ", y:" + this.y + ")]";
}
static corner(v1, v2) {
return Math.acos(v1.dotProd(v2) / (v1.length * v2.length));
}
}
const zero = new Vector2D();
/**
* Created by rockyl on 2018/11/15.
*
* 支撑类库
*/
export {default as Bounds} from './Bounds'
export {default as Vector2D, createVector2D, releaseVector2D} from './Vector2D'
export {createTween, Tween} from './Tween'
export {default as Matrix} from './Matrix'
export {default as Size} from './Size'
//export {default as Color} from './Color'
export {default as LocalStorage} from './LocalStorage'
export {TextStyle} from './TextStyle'
export {default as EventEmitter} from './EventEmitter';
\ No newline at end of file
/**
* Created by rockyl on 2018/11/9.
*
* 装饰器
*/
/**
* 属性修改时触发
* @param onChange
*/
export function fieldChanged(onChange) {
return function (target: any, key: string) {
const privateKey = '_' + key;
Object.defineProperty(target, key, {
enumerable: true,
get: function () {
return this[privateKey];
},
set: function (v) {
const oldValue = this[privateKey];
if (oldValue !== v) {
this[privateKey] = v;
onChange.apply(this, [v, key, oldValue]);
}
}
})
}
}
/**
* 属性变脏时设置宿主的dirty属性为true
*/
export const dirtyFieldDetector = fieldChanged(
function (value, key, oldValue) {
this['dirty'] = true;
}
);
/**
* 属性变脏时触发onModify方法
*/
export const dirtyFieldTrigger = fieldChanged(
function (value, key, oldValue) {
this['onModify'] && this['onModify'](value, key, oldValue);
}
);
/**
* Created by rockyl on 2018/11/8.
*
* 缓动函数集合,使用不同的缓动函数使得动画按照对应的方程进行
*/
export enum Ease {
quadIn = 'quadIn',
quadOut = 'quadOut',
quadInOut = 'quadInOut',
cubicIn = 'cubicIn',
cubicOut = 'cubicOut',
cubicInOut = 'cubicInOut',
quartIn = 'quartIn',
quartOut = 'quartOut',
quartInOut = 'quartInOut',
quintIn = 'quintIn',
quintOut = 'quintOut',
quintInOut = 'quintInOut',
sineIn = 'sineIn',
sineOut = 'sineOut',
sineInOut = 'sineInOut',
backIn = 'backIn',
backOut = 'backOut',
backInOut = 'backInOut',
circIn = 'circIn',
circOut = 'circOut',
circInOut = 'circInOut',
bounceIn = 'bounceIn',
bounceOut = 'bounceOut',
bounceInOut = 'bounceInOut',
elasticIn = 'elasticIn',
elasticOut = 'elasticOut',
elasticInOut = 'elasticInOut',
}
export function get(amount) {
if (amount < -1) {
amount = -1;
}
if (amount > 1) {
amount = 1;
}
return function (t) {
if (amount == 0) {
return t;
}
if (amount < 0) {
return t * (t * -amount + 1 + amount);
}
return t * ((2 - t) * amount + (1 - amount));
}
}
export function getPowIn(pow) {
return function (t) {
return Math.pow(t, pow);
}
}
export function getPowOut(pow) {
return function (t) {
return 1 - Math.pow(1 - t, pow);
}
}
export function getPowInOut(pow) {
return function (t) {
if ((t *= 2) < 1) return 0.5 * Math.pow(t, pow);
return 1 - 0.5 * Math.abs(Math.pow(2 - t, pow));
}
}
export const quadIn = getPowIn(2);
export const quadOut = getPowOut(2);
export const quadInOut = getPowInOut(2);
export const cubicIn = getPowIn(3);
export const cubicOut = getPowOut(3);
export const cubicInOut = getPowInOut(3);
export const quartIn = getPowIn(4);
export const quartOut = getPowOut(4);
export const quartInOut = getPowInOut(4);
export const quintIn = getPowIn(5);
export const quintOut = getPowOut(5);
export const quintInOut = getPowInOut(5);
export function sineIn(t) {
return 1 - Math.cos(t * Math.PI / 2);
}
export function sineOut(t) {
return Math.sin(t * Math.PI / 2);
}
export function sineInOut(t) {
return -0.5 * (Math.cos(Math.PI * t) - 1)
}
export function getBackIn(amount) {
return function (t) {
return t * t * ((amount + 1) * t - amount);
}
}
export const backIn = getBackIn(1.7);
export function getBackOut(amount) {
return function (t) {
return (--t * t * ((amount + 1) * t + amount) + 1);
}
}
export const backOut = getBackOut(1.7);
export function getBackInOut(amount) {
amount *= 1.525;
return function (t) {
if ((t *= 2) < 1) return 0.5 * (t * t * ((amount + 1) * t - amount));
return 0.5 * ((t -= 2) * t * ((amount + 1) * t + amount) + 2);
}
}
export const backInOut = getBackInOut(1.7);
export function circIn(t) {
return -(Math.sqrt(1 - t * t) - 1);
}
export function circOut(t) {
return Math.sqrt(1 - (--t) * t);
}
export function circInOut(t) {
if ((t *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - t * t) - 1);
}
return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
}
export function bounceIn(t) {
return 1 - bounceOut(1 - t);
}
export function bounceOut(t) {
if (t < 1 / 2.75) {
return (7.5625 * t * t);
} else if (t < 2 / 2.75) {
return (7.5625 * (t -= 1.5 / 2.75) * t + 0.75);
} else if (t < 2.5 / 2.75) {
return (7.5625 * (t -= 2.25 / 2.75) * t + 0.9375);
} else {
return (7.5625 * (t -= 2.625 / 2.75) * t + 0.984375);
}
}
export function bounceInOut(t) {
if (t < 0.5) return bounceIn(t * 2) * .5;
return bounceOut(t * 2 - 1) * 0.5 + 0.5;
}
export function getElasticIn(amplitude, period) {
let pi2 = Math.PI * 2;
return function (t) {
if (t == 0 || t == 1) return t;
let s = period / pi2 * Math.asin(1 / amplitude);
return -(amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period));
}
}
export const elasticIn = getElasticIn(1, 0.3);
export function getElasticOut(amplitude, period) {
let pi2 = Math.PI * 2;
return function (t) {
if (t == 0 || t == 1) return t;
let s = period / pi2 * Math.asin(1 / amplitude);
return (amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1);
}
}
export const elasticOut = getElasticOut(1, 0.3);
export function getElasticInOut(amplitude, period) {
let pi2 = Math.PI * 2;
return function (t) {
let s = period / pi2 * Math.asin(1 / amplitude);
if ((t *= 2) < 1) return -0.5 * (amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period));
return amplitude * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * pi2 / period) * 0.5 + 1;
}
}
export const elasticInOut = getElasticInOut(1, 0.3 * 1.5);
/**
* Created by rockyl on 2018/11/16.
*/
import * as decorators from './decorators'
import * as ease from './ease'
import * as math from './math'
import * as utils from './utils'
import * as timeUtils from './time'
import {Ease} from "./ease";
export {
decorators,
ease,
Ease,
math,
utils,
timeUtils,
}
/**
* Created by rockyl on 2018/11/8.
*
* 数学工具
*/
/**
* 线性插值
* @param begin number
* @param end number
* @param t number
* @param allowOutOfBounds
* @return number
*/
export function lerp(begin, end, t, allowOutOfBounds = false) {
const type = typeof begin;
if (type !== typeof end) {
console.error('begin and end need same type')
}
if (!allowOutOfBounds) {
t = Math.max(0, Math.min(1, t));
}
let sign = end - begin;
sign = sign > 0 ? 1 : (sign < 0 ? -1 : 0);
const distance = Math.abs(end - begin);
return begin + distance * t * sign;
}
/**
* 线性插值对象
* @param begin
* @param end
* @param t
* @param clazz
* @param fields
* @param allowOutOfBounds
* @return
*/
export function lerpObj(begin, end, t, clazz, fields, allowOutOfBounds = false) {
const type = typeof begin;
if (type !== typeof end) {
console.error('begin and end need same type')
}
const temp = new clazz();
for (let field of fields) {
temp[field] = lerp(begin[field], end[field], t, allowOutOfBounds);
}
return temp;
}
/**
* 随机生成一个整数
* @param max
* @param min
*/
export function makeRandomInt(max: number, min: number = 0): number {
return Math.floor(Math.random() * (max - min)) + min;
}
/**
* 打乱一个数组
* @param arr
* @returns {any}
*/
export function mixArray(arr: any): Array<any> {
for (let i: number = 0, len: number = Math.round(arr.length / 2); i < len; i++) {
let a: number = makeRandomInt(arr.length);
let b: number = makeRandomInt(arr.length);
let temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
return arr;
}
/**
* Created by rockyl on 2019-01-01.
*/
import {format as stringFormat, supplement} from './utils'
/**
* 时间戳转日期
* @param ts
*/
export function ts2Date(ts) {
let newDate:Date = new Date();
newDate.setTime(ts);
return newDate;
}
export function dateToDateString(date:Date, format:string = '{0}/{1}/{2}'):string{
return stringFormat(format, date.getFullYear(), supplement(date.getMonth() + 1, 2), supplement(date.getDate(), 2))
}
export function dateToTimeString(date:Date, format:string = '{0}:{1}:{2}'):string{
return stringFormat(format, supplement(date.getHours(), 2), supplement(date.getMinutes(), 2), supplement(date.getSeconds(), 2))
}
export function dateToString(date: Date, dayFormat, timeFormat){
return dateToDateString(date, dayFormat) + dateToTimeString(date, timeFormat);
}
export function tsToTimeString(ts, format:string = '{0}:{1}:{2}'):string{
let date = ts2Date(ts);
return stringFormat(format, supplement(date.getHours(), 2), supplement(date.getMinutes(), 2), supplement(date.getSeconds(), 2))
}
export function secondFormat(second:number, format:string = '{2}:{1}:{0}', placeZero:boolean = true):string {
let ss:any = second % 60;
let mm:any = Math.floor(second / 60) % 60;
let hh:any = Math.floor(second / 3600) % 24;
let dd:any = Math.floor(second / 3600 / 24);
if (placeZero) {
ss = supplement(ss, 2);
mm = supplement(mm, 2);
hh = supplement(hh, 2);
dd = supplement(dd, 2);
}
return stringFormat(format, ss, mm, hh, dd);
}
/**
* Created by rockyl on 2018/11/9.
*
* 常用工具
*/
export function injectProp(target: any, data?: any, callback?: Function, ignoreMethod: boolean = true, ignoreNull: boolean = true): boolean {
if (!target || !data) {
return false;
}
let result = true;
for (let key in data) {
let value: any = data[key];
if ((!ignoreMethod || typeof value != 'function') && (!ignoreNull || value != null)) {
if (callback) {
callback(target, key, value);
} else {
target[key] = value;
}
}
}
return result;
}
export function objectStringify(obj) {
if (!obj) {
return '';
}
let arr = [];
for (let key in obj) {
arr.push(key + '=' + obj[key]);
}
return arr.join('&');
}
export function waitPromise(duration): Promise<void> {
return new Promise(resolve => {
setTimeout(resolve, duration);
});
}
export function format(formatStr: string, ...params): string {
return formatApply(formatStr, params);
}
export function formatApply(formatStr: string, params: any[]): string {
let result: string = formatStr;
for (let i = 0, len = params.length; i < len; i++) {
let reg = new RegExp("\\{" + i + "\\}", 'g');
result = result.replace(reg, params[i]);
}
return result;
}
const zeros: Array<string> = [
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
"00000000",
"000000000",
"0000000000"
];
export function supplement(value: number, count: number): string {
let index = count - value.toString().length - 1;
if (index < 0) {
return value.toString();
}
return zeros[index] + value;
}
{
"compilerOptions": {
"target": "es5",
"outDir": "dist",
"experimentalDecorators": true,
"sourceMap": true,
"declarationDir": "types",
"declaration": true,
"lib": [
"es5",
"es6",
"dom",
"es2015.promise"
]
},
"include": [
"src"
]
}
\ No newline at end of file
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@babel/code-frame@^7.0.0":
version "7.0.0"
resolved "http://registry.npm.taobao.org/@babel/code-frame/download/@babel/code-frame-7.0.0.tgz#06e2ab19bdb535385559aabb5ba59729482800f8"
integrity sha1-BuKrGb21NThVWaq7W6WXKUgoAPg=
dependencies:
"@babel/highlight" "^7.0.0"
"@babel/highlight@^7.0.0":
version "7.0.0"
resolved "http://registry.npm.taobao.org/@babel/highlight/download/@babel/highlight-7.0.0.tgz#f710c38c8d458e6dd9a201afb637fcb781ce99e4"
integrity sha1-9xDDjI1Fjm3ZogGvtjf8t4HOmeQ=
dependencies:
chalk "^2.0.0"
esutils "^2.0.2"
js-tokens "^4.0.0"
"@types/node@*":
version "11.12.0"
resolved "http://registry.npm.taobao.org/@types/node/download/@types/node-11.12.0.tgz#ec5594728811dc2797e42396cfcdf786f2052c12"
integrity sha1-7FWUcogR3CeX5COWz833hvIFLBI=
ansi-styles@^3.2.1:
version "3.2.1"
resolved "http://registry.npm.taobao.org/ansi-styles/download/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d"
integrity sha1-QfuyAkPlCxK+DwS43tvwdSDOhB0=
dependencies:
color-convert "^1.9.0"
arr-diff@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/arr-diff/download/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520"
integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=
arr-flatten@^1.1.0:
version "1.1.0"
resolved "http://registry.npm.taobao.org/arr-flatten/download/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1"
integrity sha1-NgSLv/TntH4TZkQxbJlmnqWukfE=
arr-union@^3.1.0:
version "3.1.0"
resolved "http://registry.npm.taobao.org/arr-union/download/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4"
integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=
array-unique@^0.3.2:
version "0.3.2"
resolved "http://registry.npm.taobao.org/array-unique/download/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428"
integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=
assign-symbols@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/assign-symbols/download/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367"
integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=
atob@^2.1.1:
version "2.1.2"
resolved "http://registry.npm.taobao.org/atob/download/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9"
integrity sha1-bZUX654DDSQ2ZmZR6GvZ9vE1M8k=
base@^0.11.1:
version "0.11.2"
resolved "http://registry.npm.taobao.org/base/download/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f"
integrity sha1-e95c7RRbbVUakNuH+DxVi060io8=
dependencies:
cache-base "^1.0.1"
class-utils "^0.3.5"
component-emitter "^1.2.1"
define-property "^1.0.0"
isobject "^3.0.1"
mixin-deep "^1.2.0"
pascalcase "^0.1.1"
braces@^2.3.1:
version "2.3.2"
resolved "http://registry.npm.taobao.org/braces/download/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729"
integrity sha1-WXn9PxTNUxVl5fot8av/8d+u5yk=
dependencies:
arr-flatten "^1.1.0"
array-unique "^0.3.2"
extend-shallow "^2.0.1"
fill-range "^4.0.0"
isobject "^3.0.1"
repeat-element "^1.1.2"
snapdragon "^0.8.1"
snapdragon-node "^2.0.1"
split-string "^3.0.2"
to-regex "^3.0.1"
builtin-modules@^3.0.0:
version "3.0.0"
resolved "http://registry.npm.taobao.org/builtin-modules/download/builtin-modules-3.0.0.tgz#1e587d44b006620d90286cc7a9238bbc6129cab1"
integrity sha1-Hlh9RLAGYg2QKGzHqSOLvGEpyrE=
cache-base@^1.0.1:
version "1.0.1"
resolved "http://registry.npm.taobao.org/cache-base/download/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2"
integrity sha1-Cn9GQWgxyLZi7jb+TnxZ129marI=
dependencies:
collection-visit "^1.0.0"
component-emitter "^1.2.1"
get-value "^2.0.6"
has-value "^1.0.0"
isobject "^3.0.1"
set-value "^2.0.0"
to-object-path "^0.3.0"
union-value "^1.0.0"
unset-value "^1.0.0"
chalk@^2.0.0:
version "2.4.2"
resolved "http://registry.npm.taobao.org/chalk/download/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424"
integrity sha1-zUJUFnelQzPPVBpJEIwUMrRMlCQ=
dependencies:
ansi-styles "^3.2.1"
escape-string-regexp "^1.0.5"
supports-color "^5.3.0"
class-utils@^0.3.5:
version "0.3.6"
resolved "http://registry.npm.taobao.org/class-utils/download/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463"
integrity sha1-+TNprouafOAv1B+q0MqDAzGQxGM=
dependencies:
arr-union "^3.1.0"
define-property "^0.2.5"
isobject "^3.0.0"
static-extend "^0.1.1"
collection-visit@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/collection-visit/download/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0"
integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=
dependencies:
map-visit "^1.0.0"
object-visit "^1.0.0"
color-convert@^1.9.0:
version "1.9.3"
resolved "http://registry.npm.taobao.org/color-convert/download/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"
integrity sha1-u3GFBpDh8TZWfeYp0tVHHe2kweg=
dependencies:
color-name "1.1.3"
color-name@1.1.3:
version "1.1.3"
resolved "http://registry.npm.taobao.org/color-name/download/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"
integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=
commander@~2.19.0:
version "2.19.0"
resolved "http://registry.npm.taobao.org/commander/download/commander-2.19.0.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Fcommander%2Fdownload%2Fcommander-2.19.0.tgz#f6198aa84e5b83c46054b94ddedbfed5ee9ff12a"
integrity sha1-9hmKqE5bg8RgVLlN3tv+1e6f8So=
component-emitter@^1.2.1:
version "1.2.1"
resolved "http://registry.npm.taobao.org/component-emitter/download/component-emitter-1.2.1.tgz#137918d6d78283f7df7a6b7c5a63e140e69425e6"
integrity sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=
copy-descriptor@^0.1.0:
version "0.1.1"
resolved "http://registry.npm.taobao.org/copy-descriptor/download/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d"
integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=
core-util-is@~1.0.0:
version "1.0.2"
resolved "http://registry.npm.taobao.org/core-util-is/download/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=
debug@^2.2.0, debug@^2.3.3:
version "2.6.9"
resolved "http://registry.npm.taobao.org/debug/download/debug-2.6.9.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Fdebug%2Fdownload%2Fdebug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"
integrity sha1-XRKFFd8TT/Mn6QpMk/Tgd6U2NB8=
dependencies:
ms "2.0.0"
decode-uri-component@^0.2.0:
version "0.2.0"
resolved "http://registry.npm.taobao.org/decode-uri-component/download/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545"
integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=
define-property@^0.2.5:
version "0.2.5"
resolved "http://registry.npm.taobao.org/define-property/download/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116"
integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=
dependencies:
is-descriptor "^0.1.0"
define-property@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/define-property/download/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6"
integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY=
dependencies:
is-descriptor "^1.0.0"
define-property@^2.0.2:
version "2.0.2"
resolved "http://registry.npm.taobao.org/define-property/download/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d"
integrity sha1-1Flono1lS6d+AqgX+HENcCyxbp0=
dependencies:
is-descriptor "^1.0.2"
isobject "^3.0.1"
escape-string-regexp@^1.0.5:
version "1.0.5"
resolved "http://registry.npm.taobao.org/escape-string-regexp/download/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=
estree-walker@^0.6.0:
version "0.6.0"
resolved "http://registry.npm.taobao.org/estree-walker/download/estree-walker-0.6.0.tgz#5d865327c44a618dde5699f763891ae31f257dae"
integrity sha1-XYZTJ8RKYY3eVpn3Y4ka4x8lfa4=
esutils@^2.0.2:
version "2.0.2"
resolved "http://registry.npm.taobao.org/esutils/download/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b"
integrity sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=
expand-brackets@^2.1.4:
version "2.1.4"
resolved "http://registry.npm.taobao.org/expand-brackets/download/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622"
integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI=
dependencies:
debug "^2.3.3"
define-property "^0.2.5"
extend-shallow "^2.0.1"
posix-character-classes "^0.1.0"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.1"
extend-shallow@^2.0.1:
version "2.0.1"
resolved "http://registry.npm.taobao.org/extend-shallow/download/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f"
integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=
dependencies:
is-extendable "^0.1.0"
extend-shallow@^3.0.0, extend-shallow@^3.0.2:
version "3.0.2"
resolved "http://registry.npm.taobao.org/extend-shallow/download/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8"
integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=
dependencies:
assign-symbols "^1.0.0"
is-extendable "^1.0.1"
extglob@^2.0.4:
version "2.0.4"
resolved "http://registry.npm.taobao.org/extglob/download/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543"
integrity sha1-rQD+TcYSqSMuhxhxHcXLWrAoVUM=
dependencies:
array-unique "^0.3.2"
define-property "^1.0.0"
expand-brackets "^2.1.4"
extend-shallow "^2.0.1"
fragment-cache "^0.2.1"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.1"
fill-range@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/fill-range/download/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7"
integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=
dependencies:
extend-shallow "^2.0.1"
is-number "^3.0.0"
repeat-string "^1.6.1"
to-regex-range "^2.1.0"
for-in@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/for-in/download/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=
fragment-cache@^0.2.1:
version "0.2.1"
resolved "http://registry.npm.taobao.org/fragment-cache/download/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19"
integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=
dependencies:
map-cache "^0.2.2"
fs-extra@7.0.1:
version "7.0.1"
resolved "http://registry.npm.taobao.org/fs-extra/download/fs-extra-7.0.1.tgz#4f189c44aa123b895f722804f55ea23eadc348e9"
integrity sha1-TxicRKoSO4lfcigE9V6iPq3DSOk=
dependencies:
graceful-fs "^4.1.2"
jsonfile "^4.0.0"
universalify "^0.1.0"
get-value@^2.0.3, get-value@^2.0.6:
version "2.0.6"
resolved "http://registry.npm.taobao.org/get-value/download/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28"
integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=
graceful-fs@^4.1.2, graceful-fs@^4.1.6:
version "4.1.15"
resolved "http://registry.npm.taobao.org/graceful-fs/download/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00"
integrity sha1-/7cD4QZuig7qpMi4C6klPu77+wA=
has-flag@^3.0.0:
version "3.0.0"
resolved "http://registry.npm.taobao.org/has-flag/download/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0=
has-value@^0.3.1:
version "0.3.1"
resolved "http://registry.npm.taobao.org/has-value/download/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f"
integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=
dependencies:
get-value "^2.0.3"
has-values "^0.1.4"
isobject "^2.0.0"
has-value@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/has-value/download/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177"
integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=
dependencies:
get-value "^2.0.6"
has-values "^1.0.0"
isobject "^3.0.0"
has-values@^0.1.4:
version "0.1.4"
resolved "http://registry.npm.taobao.org/has-values/download/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771"
integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E=
has-values@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/has-values/download/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f"
integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=
dependencies:
is-number "^3.0.0"
kind-of "^4.0.0"
inherits@~2.0.3:
version "2.0.3"
resolved "http://registry.npm.taobao.org/inherits/download/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=
is-accessor-descriptor@^0.1.6:
version "0.1.6"
resolved "http://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6"
integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=
dependencies:
kind-of "^3.0.2"
is-accessor-descriptor@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/is-accessor-descriptor/download/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656"
integrity sha1-FpwvbT3x+ZJhgHI2XJsOofaHhlY=
dependencies:
kind-of "^6.0.0"
is-buffer@^1.1.5:
version "1.1.6"
resolved "http://registry.npm.taobao.org/is-buffer/download/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
integrity sha1-76ouqdqg16suoTqXsritUf776L4=
is-data-descriptor@^0.1.4:
version "0.1.4"
resolved "http://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56"
integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=
dependencies:
kind-of "^3.0.2"
is-data-descriptor@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/is-data-descriptor/download/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7"
integrity sha1-2Eh2Mh0Oet0DmQQGq7u9NrqSaMc=
dependencies:
kind-of "^6.0.0"
is-descriptor@^0.1.0:
version "0.1.6"
resolved "http://registry.npm.taobao.org/is-descriptor/download/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca"
integrity sha1-Nm2CQN3kh8pRgjsaufB6EKeCUco=
dependencies:
is-accessor-descriptor "^0.1.6"
is-data-descriptor "^0.1.4"
kind-of "^5.0.0"
is-descriptor@^1.0.0, is-descriptor@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/is-descriptor/download/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec"
integrity sha1-OxWXRqZmBLBPjIFSS6NlxfFNhuw=
dependencies:
is-accessor-descriptor "^1.0.0"
is-data-descriptor "^1.0.0"
kind-of "^6.0.2"
is-extendable@^0.1.0, is-extendable@^0.1.1:
version "0.1.1"
resolved "http://registry.npm.taobao.org/is-extendable/download/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89"
integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=
is-extendable@^1.0.1:
version "1.0.1"
resolved "http://registry.npm.taobao.org/is-extendable/download/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4"
integrity sha1-p0cPnkJnM9gb2B4RVSZOOjUHyrQ=
dependencies:
is-plain-object "^2.0.4"
is-module@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/is-module/download/is-module-1.0.0.tgz#3258fb69f78c14d5b815d664336b4cffb6441591"
integrity sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=
is-number@^3.0.0:
version "3.0.0"
resolved "http://registry.npm.taobao.org/is-number/download/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195"
integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=
dependencies:
kind-of "^3.0.2"
is-plain-object@^2.0.1, is-plain-object@^2.0.3, is-plain-object@^2.0.4:
version "2.0.4"
resolved "http://registry.npm.taobao.org/is-plain-object/download/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677"
integrity sha1-LBY7P6+xtgbZ0Xko8FwqHDjgdnc=
dependencies:
isobject "^3.0.1"
is-windows@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/is-windows/download/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"
integrity sha1-0YUOuXkezRjmGCzhKjDzlmNLsZ0=
isarray@1.0.0, isarray@~1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/isarray/download/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=
isobject@^2.0.0:
version "2.1.0"
resolved "http://registry.npm.taobao.org/isobject/download/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89"
integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=
dependencies:
isarray "1.0.0"
isobject@^3.0.0, isobject@^3.0.1:
version "3.0.1"
resolved "http://registry.npm.taobao.org/isobject/download/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df"
integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8=
jest-worker@^24.0.0:
version "24.4.0"
resolved "http://registry.npm.taobao.org/jest-worker/download/jest-worker-24.4.0.tgz#fbc452b0120bb5c2a70cdc88fa132b48eeb11dd0"
integrity sha1-+8RSsBILtcKnDNyI+hMrSO6xHdA=
dependencies:
"@types/node" "*"
merge-stream "^1.0.1"
supports-color "^6.1.0"
js-tokens@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/js-tokens/download/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
integrity sha1-GSA/tZmR35jjoocFDUZHzerzJJk=
jsonfile@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/jsonfile/download/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb"
integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=
optionalDependencies:
graceful-fs "^4.1.6"
kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0:
version "3.2.2"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64"
integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=
dependencies:
is-buffer "^1.1.5"
kind-of@^4.0.0:
version "4.0.0"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57"
integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc=
dependencies:
is-buffer "^1.1.5"
kind-of@^5.0.0:
version "5.1.0"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d"
integrity sha1-cpyR4thXt6QZofmqZWhcTDP1hF0=
kind-of@^6.0.0, kind-of@^6.0.2:
version "6.0.2"
resolved "http://registry.npm.taobao.org/kind-of/download/kind-of-6.0.2.tgz#01146b36a6218e64e58f3a8d66de5d7fc6f6d051"
integrity sha1-ARRrNqYhjmTljzqNZt5df8b20FE=
magic-string@^0.25.2:
version "0.25.2"
resolved "http://registry.npm.taobao.org/magic-string/download/magic-string-0.25.2.tgz#139c3a729515ec55e96e69e82a11fe890a293ad9"
integrity sha1-E5w6cpUV7FXpbmnoKhH+iQopOtk=
dependencies:
sourcemap-codec "^1.4.4"
map-cache@^0.2.2:
version "0.2.2"
resolved "http://registry.npm.taobao.org/map-cache/download/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf"
integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=
map-visit@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/map-visit/download/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f"
integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=
dependencies:
object-visit "^1.0.0"
merge-stream@^1.0.1:
version "1.0.1"
resolved "http://registry.npm.taobao.org/merge-stream/download/merge-stream-1.0.1.tgz#4041202d508a342ba00174008df0c251b8c135e1"
integrity sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=
dependencies:
readable-stream "^2.0.1"
micromatch@^3.1.10:
version "3.1.10"
resolved "http://registry.npm.taobao.org/micromatch/download/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23"
integrity sha1-cIWbyVyYQJUvNZoGij/En57PrCM=
dependencies:
arr-diff "^4.0.0"
array-unique "^0.3.2"
braces "^2.3.1"
define-property "^2.0.2"
extend-shallow "^3.0.2"
extglob "^2.0.4"
fragment-cache "^0.2.1"
kind-of "^6.0.2"
nanomatch "^1.2.9"
object.pick "^1.3.0"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.2"
mixin-deep@^1.2.0:
version "1.3.1"
resolved "http://registry.npm.taobao.org/mixin-deep/download/mixin-deep-1.3.1.tgz#a49e7268dce1a0d9698e45326c5626df3543d0fe"
integrity sha1-pJ5yaNzhoNlpjkUybFYm3zVD0P4=
dependencies:
for-in "^1.0.2"
is-extendable "^1.0.1"
ms@2.0.0:
version "2.0.0"
resolved "http://registry.npm.taobao.org/ms/download/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=
nanomatch@^1.2.9:
version "1.2.13"
resolved "http://registry.npm.taobao.org/nanomatch/download/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
integrity sha1-uHqKpPwN6P5r6IiVs4mD/yZb0Rk=
dependencies:
arr-diff "^4.0.0"
array-unique "^0.3.2"
define-property "^2.0.2"
extend-shallow "^3.0.2"
fragment-cache "^0.2.1"
is-windows "^1.0.2"
kind-of "^6.0.2"
object.pick "^1.3.0"
regex-not "^1.0.0"
snapdragon "^0.8.1"
to-regex "^3.0.1"
object-copy@^0.1.0:
version "0.1.0"
resolved "http://registry.npm.taobao.org/object-copy/download/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c"
integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw=
dependencies:
copy-descriptor "^0.1.0"
define-property "^0.2.5"
kind-of "^3.0.3"
object-visit@^1.0.0:
version "1.0.1"
resolved "http://registry.npm.taobao.org/object-visit/download/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb"
integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=
dependencies:
isobject "^3.0.0"
object.pick@^1.3.0:
version "1.3.0"
resolved "http://registry.npm.taobao.org/object.pick/download/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747"
integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=
dependencies:
isobject "^3.0.1"
pascalcase@^0.1.1:
version "0.1.1"
resolved "http://registry.npm.taobao.org/pascalcase/download/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14"
integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=
path-parse@^1.0.6:
version "1.0.6"
resolved "http://registry.npm.taobao.org/path-parse/download/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c"
integrity sha1-1i27VnlAXXLEc37FhgDp3c8G0kw=
posix-character-classes@^0.1.0:
version "0.1.1"
resolved "http://registry.npm.taobao.org/posix-character-classes/download/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab"
integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=
process-nextick-args@~2.0.0:
version "2.0.0"
resolved "http://registry.npm.taobao.org/process-nextick-args/download/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa"
integrity sha1-o31zL0JxtKsa0HDTVQjoKQeI/6o=
readable-stream@^2.0.1:
version "2.3.6"
resolved "http://registry.npm.taobao.org/readable-stream/download/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf"
integrity sha1-sRwn2IuP8fvgcGQ8+UsMea4bCq8=
dependencies:
core-util-is "~1.0.0"
inherits "~2.0.3"
isarray "~1.0.0"
process-nextick-args "~2.0.0"
safe-buffer "~5.1.1"
string_decoder "~1.1.1"
util-deprecate "~1.0.1"
regex-not@^1.0.0, regex-not@^1.0.2:
version "1.0.2"
resolved "http://registry.npm.taobao.org/regex-not/download/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c"
integrity sha1-H07OJ+ALC2XgJHpoEOaoXYOldSw=
dependencies:
extend-shallow "^3.0.2"
safe-regex "^1.1.0"
repeat-element@^1.1.2:
version "1.1.3"
resolved "http://registry.npm.taobao.org/repeat-element/download/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce"
integrity sha1-eC4NglwMWjuzlzH4Tv7mt0Lmsc4=
repeat-string@^1.6.1:
version "1.6.1"
resolved "http://registry.npm.taobao.org/repeat-string/download/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"
integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc=
resolve-url@^0.2.1:
version "0.2.1"
resolved "http://registry.npm.taobao.org/resolve-url/download/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a"
integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=
resolve@1.10.0, resolve@^1.10.0:
version "1.10.0"
resolved "http://registry.npm.taobao.org/resolve/download/resolve-1.10.0.tgz#3bdaaeaf45cc07f375656dfd2e54ed0810b101ba"
integrity sha1-O9qur0XMB/N1ZW39LlTtCBCxAbo=
dependencies:
path-parse "^1.0.6"
ret@~0.1.10:
version "0.1.15"
resolved "http://registry.npm.taobao.org/ret/download/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc"
integrity sha1-uKSCXVvbH8P29Twrwz+BOIaBx7w=
rollup-plugin-commonjs@^9.2.2:
version "9.2.2"
resolved "http://registry.npm.taobao.org/rollup-plugin-commonjs/download/rollup-plugin-commonjs-9.2.2.tgz#4959f3ff0d9706c132e5247b47ab385f11d9aae6"
integrity sha1-SVnz/w2XBsEy5SR7R6s4XxHZquY=
dependencies:
estree-walker "^0.6.0"
magic-string "^0.25.2"
resolve "^1.10.0"
rollup-pluginutils "^2.5.0"
rollup-plugin-node-resolve@^4.0.1:
version "4.0.1"
resolved "http://registry.npm.taobao.org/rollup-plugin-node-resolve/download/rollup-plugin-node-resolve-4.0.1.tgz#f95765d174e5daeef9ea6268566141f53aa9d422"
integrity sha1-+Vdl0XTl2u756mJoVmFB9Tqp1CI=
dependencies:
builtin-modules "^3.0.0"
is-module "^1.0.0"
resolve "^1.10.0"
rollup-plugin-typescript2@^0.20.1:
version "0.20.1"
resolved "http://registry.npm.taobao.org/rollup-plugin-typescript2/download/rollup-plugin-typescript2-0.20.1.tgz#fb1d411975cd875d24882ea66f5f4fd11d2f2240"
integrity sha1-+x1BGXXNh10kiC6mb19P0R0vIkA=
dependencies:
fs-extra "7.0.1"
resolve "1.10.0"
rollup-pluginutils "2.4.1"
tslib "1.9.3"
rollup-plugin-uglify@^6.0.2:
version "6.0.2"
resolved "http://registry.npm.taobao.org/rollup-plugin-uglify/download/rollup-plugin-uglify-6.0.2.tgz#681042cfdf7ea4e514971946344e1a95bc2772fe"
integrity sha1-aBBCz99+pOUUlxlGNE4albwncv4=
dependencies:
"@babel/code-frame" "^7.0.0"
jest-worker "^24.0.0"
serialize-javascript "^1.6.1"
uglify-js "^3.4.9"
rollup-pluginutils@2.4.1:
version "2.4.1"
resolved "http://registry.npm.taobao.org/rollup-pluginutils/download/rollup-pluginutils-2.4.1.tgz#de43ab54965bbf47843599a7f3adceb723de38db"
integrity sha1-3kOrVJZbv0eENZmn863OtyPeONs=
dependencies:
estree-walker "^0.6.0"
micromatch "^3.1.10"
rollup-pluginutils@^2.5.0:
version "2.5.0"
resolved "http://registry.npm.taobao.org/rollup-pluginutils/download/rollup-pluginutils-2.5.0.tgz#23be0f05ac3972ea7b08fc7870cb91fde5b23a09"
integrity sha1-I74PBaw5cup7CPx4cMuR/eWyOgk=
dependencies:
estree-walker "^0.6.0"
micromatch "^3.1.10"
safe-buffer@~5.1.0, safe-buffer@~5.1.1:
version "5.1.2"
resolved "http://registry.npm.taobao.org/safe-buffer/download/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
integrity sha1-mR7GnSluAxN0fVm9/St0XDX4go0=
safe-regex@^1.1.0:
version "1.1.0"
resolved "http://registry.npm.taobao.org/safe-regex/download/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e"
integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4=
dependencies:
ret "~0.1.10"
serialize-javascript@^1.6.1:
version "1.6.1"
resolved "http://registry.npm.taobao.org/serialize-javascript/download/serialize-javascript-1.6.1.tgz#4d1f697ec49429a847ca6f442a2a755126c4d879"
integrity sha1-TR9pfsSUKahHym9EKip1USbE2Hk=
set-value@^0.4.3:
version "0.4.3"
resolved "http://registry.npm.taobao.org/set-value/download/set-value-0.4.3.tgz#7db08f9d3d22dc7f78e53af3c3bf4666ecdfccf1"
integrity sha1-fbCPnT0i3H945Trzw79GZuzfzPE=
dependencies:
extend-shallow "^2.0.1"
is-extendable "^0.1.1"
is-plain-object "^2.0.1"
to-object-path "^0.3.0"
set-value@^2.0.0:
version "2.0.0"
resolved "http://registry.npm.taobao.org/set-value/download/set-value-2.0.0.tgz#71ae4a88f0feefbbf52d1ea604f3fb315ebb6274"
integrity sha1-ca5KiPD+77v1LR6mBPP7MV67YnQ=
dependencies:
extend-shallow "^2.0.1"
is-extendable "^0.1.1"
is-plain-object "^2.0.3"
split-string "^3.0.1"
snapdragon-node@^2.0.1:
version "2.1.1"
resolved "http://registry.npm.taobao.org/snapdragon-node/download/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b"
integrity sha1-bBdfhv8UvbByRWPo88GwIaKGhTs=
dependencies:
define-property "^1.0.0"
isobject "^3.0.0"
snapdragon-util "^3.0.1"
snapdragon-util@^3.0.1:
version "3.0.1"
resolved "http://registry.npm.taobao.org/snapdragon-util/download/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2"
integrity sha1-+VZHlIbyrNeXAGk/b3uAXkWrVuI=
dependencies:
kind-of "^3.2.0"
snapdragon@^0.8.1:
version "0.8.2"
resolved "http://registry.npm.taobao.org/snapdragon/download/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d"
integrity sha1-ZJIufFZbDhQgS6GqfWlkJ40lGC0=
dependencies:
base "^0.11.1"
debug "^2.2.0"
define-property "^0.2.5"
extend-shallow "^2.0.1"
map-cache "^0.2.2"
source-map "^0.5.6"
source-map-resolve "^0.5.0"
use "^3.1.0"
source-map-resolve@^0.5.0:
version "0.5.2"
resolved "http://registry.npm.taobao.org/source-map-resolve/download/source-map-resolve-0.5.2.tgz#72e2cc34095543e43b2c62b2c4c10d4a9054f259"
integrity sha1-cuLMNAlVQ+Q7LGKyxMENSpBU8lk=
dependencies:
atob "^2.1.1"
decode-uri-component "^0.2.0"
resolve-url "^0.2.1"
source-map-url "^0.4.0"
urix "^0.1.0"
source-map-url@^0.4.0:
version "0.4.0"
resolved "http://registry.npm.taobao.org/source-map-url/download/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3"
integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=
source-map@^0.5.6:
version "0.5.7"
resolved "http://registry.npm.taobao.org/source-map/download/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=
source-map@~0.6.1:
version "0.6.1"
resolved "http://registry.npm.taobao.org/source-map/download/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
integrity sha1-dHIq8y6WFOnCh6jQu95IteLxomM=
sourcemap-codec@^1.4.4:
version "1.4.4"
resolved "http://registry.npm.taobao.org/sourcemap-codec/download/sourcemap-codec-1.4.4.tgz#c63ea927c029dd6bd9a2b7fa03b3fec02ad56e9f"
integrity sha1-xj6pJ8Ap3WvZorf6A7P+wCrVbp8=
split-string@^3.0.1, split-string@^3.0.2:
version "3.1.0"
resolved "http://registry.npm.taobao.org/split-string/download/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2"
integrity sha1-fLCd2jqGWFcFxks5pkZgOGguj+I=
dependencies:
extend-shallow "^3.0.0"
static-extend@^0.1.1:
version "0.1.2"
resolved "http://registry.npm.taobao.org/static-extend/download/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6"
integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=
dependencies:
define-property "^0.2.5"
object-copy "^0.1.0"
string_decoder@~1.1.1:
version "1.1.1"
resolved "http://registry.npm.taobao.org/string_decoder/download/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8"
integrity sha1-nPFhG6YmhdcDCunkujQUnDrwP8g=
dependencies:
safe-buffer "~5.1.0"
supports-color@^5.3.0:
version "5.5.0"
resolved "http://registry.npm.taobao.org/supports-color/download/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f"
integrity sha1-4uaaRKyHcveKHsCzW2id9lMO/I8=
dependencies:
has-flag "^3.0.0"
supports-color@^6.1.0:
version "6.1.0"
resolved "http://registry.npm.taobao.org/supports-color/download/supports-color-6.1.0.tgz#0764abc69c63d5ac842dd4867e8d025e880df8f3"
integrity sha1-B2Srxpxj1ayELdSGfo0CXogN+PM=
dependencies:
has-flag "^3.0.0"
to-object-path@^0.3.0:
version "0.3.0"
resolved "http://registry.npm.taobao.org/to-object-path/download/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af"
integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=
dependencies:
kind-of "^3.0.2"
to-regex-range@^2.1.0:
version "2.1.1"
resolved "http://registry.npm.taobao.org/to-regex-range/download/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38"
integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=
dependencies:
is-number "^3.0.0"
repeat-string "^1.6.1"
to-regex@^3.0.1, to-regex@^3.0.2:
version "3.0.2"
resolved "http://registry.npm.taobao.org/to-regex/download/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce"
integrity sha1-E8/dmzNlUvMLUfM6iuG0Knp1mc4=
dependencies:
define-property "^2.0.2"
extend-shallow "^3.0.2"
regex-not "^1.0.2"
safe-regex "^1.1.0"
tslib@1.9.3, tslib@^1.9.3:
version "1.9.3"
resolved "http://registry.npm.taobao.org/tslib/download/tslib-1.9.3.tgz#d7e4dd79245d85428c4d7e4822a79917954ca286"
integrity sha1-1+TdeSRdhUKMTX5IIqeZF5VMooY=
typescript@^3.3.4000:
version "3.3.4000"
resolved "http://registry.npm.taobao.org/typescript/download/typescript-3.3.4000.tgz#76b0f89cfdbf97827e1112d64f283f1151d6adf0"
integrity sha1-drD4nP2/l4J+ERLWTyg/EVHWrfA=
uglify-js@^3.4.9:
version "3.5.2"
resolved "http://registry.npm.taobao.org/uglify-js/download/uglify-js-3.5.2.tgz#dc0c7ac2da0a4b7d15e84266818ff30e82529474"
integrity sha1-3Ax6wtoKS30V6EJmgY/zDoJSlHQ=
dependencies:
commander "~2.19.0"
source-map "~0.6.1"
union-value@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/union-value/download/union-value-1.0.0.tgz#5c71c34cb5bad5dcebe3ea0cd08207ba5aa1aea4"
integrity sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=
dependencies:
arr-union "^3.1.0"
get-value "^2.0.6"
is-extendable "^0.1.1"
set-value "^0.4.3"
universalify@^0.1.0:
version "0.1.2"
resolved "http://registry.npm.taobao.org/universalify/download/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66"
integrity sha1-tkb2m+OULavOzJ1mOcgNwQXvqmY=
unset-value@^1.0.0:
version "1.0.0"
resolved "http://registry.npm.taobao.org/unset-value/download/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559"
integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=
dependencies:
has-value "^0.3.1"
isobject "^3.0.0"
urix@^0.1.0:
version "0.1.0"
resolved "http://registry.npm.taobao.org/urix/download/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72"
integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=
use@^3.1.0:
version "3.1.1"
resolved "http://registry.npm.taobao.org/use/download/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f"
integrity sha1-1QyMrHmhn7wg8pEfVuuXP04QBw8=
util-deprecate@~1.0.1:
version "1.0.2"
resolved "http://registry.npm.taobao.org/util-deprecate/download/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=
*.js linguist-language=TypeScript
\ No newline at end of file
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
# tslib
This is a runtime library for [TypeScript](http://www.typescriptlang.org/) that contains all of the TypeScript helper functions.
This library is primarily used by the `--importHelpers` flag in TypeScript.
When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file:
```ts
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
exports.x = {};
exports.y = __assign({}, exports.x);
```
will instead be emitted as something like the following:
```ts
var tslib_1 = require("tslib");
exports.x = {};
exports.y = tslib_1.__assign({}, exports.x);
```
Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead.
For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`.
# Installing
For the latest stable version, run:
## npm
```sh
# TypeScript 2.3.3 or later
npm install --save tslib
# TypeScript 2.3.2 or earlier
npm install --save tslib@1.6.1
```
## bower
```sh
# TypeScript 2.3.3 or later
bower install tslib
# TypeScript 2.3.2 or earlier
bower install tslib@1.6.1
```
## JSPM
```sh
# TypeScript 2.3.3 or later
jspm install tslib
# TypeScript 2.3.2 or earlier
jspm install tslib@1.6.1
```
# Usage
Set the `importHelpers` compiler option on the command line:
```
tsc --importHelpers file.ts
```
or in your tsconfig.json:
```json
{
"compilerOptions": {
"importHelpers": true
}
}
```
#### For bower and JSPM users
You will need to add a `paths` mapping for `tslib`, e.g. For Bower users:
```json
{
"compilerOptions": {
"module": "amd",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["bower_components/tslib/tslib.d.ts"]
}
}
}
```
For JSPM users:
```json
{
"compilerOptions": {
"module": "system",
"importHelpers": true,
"baseUrl": "./",
"paths": {
"tslib" : ["jspm_packages/npm/tslib@1.9.3/tslib.d.ts"]
}
}
}
```
# Contribute
There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript).
* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md).
* Read the language specification ([docx](http://go.microsoft.com/fwlink/?LinkId=267121), [pdf](http://go.microsoft.com/fwlink/?LinkId=267238)).
# Documentation
* [Quick tutorial](http://www.typescriptlang.org/Tutorial)
* [Programming handbook](http://www.typescriptlang.org/Handbook)
* [Language specification](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)
* [Homepage](http://www.typescriptlang.org/)
{
"name": "tslib",
"authors": [
"Microsoft Corp."
],
"homepage": "http://typescriptlang.org/",
"version": "1.9.3",
"license": "Apache-2.0",
"description": "Runtime library for TypeScript helper functions",
"keywords": [
"TypeScript",
"Microsoft",
"compiler",
"language",
"javascript",
"tslib",
"runtime"
],
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/tslib.git"
},
"main": "tslib.js",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"docs",
"package.json",
".npmignore",
".gitignore",
".gitattributes"
]
}
# The `__generator` helper
The `__generator` helper is a function designed to support TypeScript's down-level emit for
async functions when targeting ES5 and earlier. But how, exactly, does it work?
Here's the body of the `__generator` helper:
```js
__generator = function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
```
And here's an example of it in use:
```ts
// source
async function func(x) {
try {
await x;
}
catch (e) {
console.error(e);
}
finally {
console.log("finally");
}
}
// generated
function func(x) {
return __awaiter(this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 1, 3, 4]);
return [4 /*yield*/, x];
case 1:
_a.sent();
return [3 /*break*/, 4];
case 2:
e_1 = _a.sent();
console.error(e_1);
return [3 /*break*/, 4];
case 3:
console.log("finally");
return [7 /*endfinally*/];
case 4: return [2 /*return*/];
}
});
});
}
```
There is a lot going on in this function, so the following will break down what each part of the
`__generator` helper does and how it works.
# Opcodes
The `__generator` helper uses opcodes which represent various operations that are interpreted by
the helper to affect its internal state. The following table lists the various opcodes, their
arguments, and their purpose:
| Opcode | Arguments | Purpose |
|----------------|-----------|--------------------------------------------------------------------------------------------------------------------------------|
| 0 (next) | *value* | Starts the generator, or resumes the generator with *value* as the result of the `AwaitExpression` where execution was paused. |
| 1 (throw) | *value* | Resumes the generator, throwing *value* at `AwaitExpression` where execution was paused. |
| 2 (return) | *value* | Exits the generator, executing any `finally` blocks starting at the `AwaitExpression` where execution was paused. |
| 3 (break) | *label* | Performs an unconditional jump to the specified label, executing any `finally` between the current instruction and the label. |
| 4 (yield) | *value* | Suspends the generator, setting the resume point at the next label and yielding the value. |
| 5 (yieldstar) | *value* | Suspends the generator, setting the resume point at the next label and delegating operations to the supplied value. |
| 6 (catch) | *error* | An internal instruction used to indicate an exception that was thrown from the body of the generator. |
| 7 (endfinally) | | Exits a finally block, resuming any previous operation (such as a break, return, throw, etc.) |
# State
The `_`, `f`, `y`, and `t` variables make up the persistent state of the `__generator` function. Each variable
has a specific purpose, as described in the following sections:
## The `_` variable
The `__generator` helper must share state between its internal `step` orchestration function and
the `body` function passed to the helper.
```ts
var _ = {
label: 0,
sent: function() {
if (t[0] & 1) // NOTE: true for `throw`, but not `next` or `catch`
throw t[1];
return sent[1];
},
trys: [],
ops: []
};
```
The following table describes the members of the `_` state object and their purpose:
| Name | Description |
|---------|---------------------------------------------------------------------------------------------------------------------------|
| `label` | Specifies the next switch case to execute in the `body` function. |
| `sent` | Handles the completion result passed to the generator. |
| `trys` | A stack of **Protected Regions**, which are 4-tuples that describe the labels that make up a `try..catch..finally` block. |
| `ops` | A stack of pending operations used for `try..finally` blocks. |
The `__generator` helper passes this state object to the `body` function for use with switching
between switch cases in the body, handling completions from `AwaitExpression`, etc.
## The `f` variable
The `f` variable indicates whether the generator is currently executing, to prevent re-entry of
the same generator during its execution.
## The `y` variable
The `y` variable stores the iterator passed to a `yieldstar` instruction to which operations should be delegated.
## The `t` variable
The `t` variable is a temporary variable that stores one of the following values:
- The completion value when resuming from a `yield` or `yield*`.
- The error value for a catch block.
- The current **Protected Region**.
- The verb (`next`, `throw`, or `return` method) to delegate to the expression of a `yield*`.
- The result of evaluating the verb delegated to the expression of a `yield*`.
> NOTE: None of the above cases overlap.
# Protected Regions
A **Protected Region** is a region within the `body` function that indicates a
`try..catch..finally` statement. It consists of a 4-tuple that contains 4 labels:
| Offset | Description |
|--------|-----------------------------------------------------------------------------------------|
| 0 | *Required* The label that indicates the beginning of a `try..catch..finally` statement. |
| 1 | *Optional* The label that indicates the beginning of a `catch` clause. |
| 2 | *Optional* The label that indicates the beginning of a `finally` clause. |
| 3 | *Required* The label that indicates the end of the `try..catch..finally` statement. |
# The generator object
The final step of the `__generator` helper is the allocation of an object that implements the
`Generator` protocol, to be used by the `__awaiter` helper:
```ts
return { next: verb(0), "throw": verb(1), "return": verb(2) };
function verb(n) { return function (v) { return step([n, v]); }; }
```
This object translates calls to `next`, `throw`, and `return` to the appropriate Opcodes and
invokes the `step` orchestration function to continue execution. The `throw` and `return` method
names are quoted to better support ES3.
# Orchestration
The `step` function is the main orechestration mechanism for the `__generator` helper. It
interprets opcodes, handles **protected regions**, and communicates results back to the caller.
Here's a closer look at the `step` function:
```ts
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
```
The main body of `step` exists in a `while` loop. This allows us to continually interpret
operations until we have reached some completion value, be it a `return`, `await`, or `throw`.
## Preventing re-entry
The first part of the `step` function is used as a check to prevent re-entry into a currently
executing generator:
```ts
if (f) throw new TypeError("Generator is already executing.");
```
## Running the generator
The main body of the `step` function consists of a `while` loop which continues to evaluate
instructions until the generator exits or is suspended:
```ts
while (_) try ...
```
When the generator has run to completion, the `_` state variable will be cleared, forcing the loop
to exit.
## Evaluating the generator body.
```ts
try {
...
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
```
Depending on the current operation, we re-enter the generator body to start or continue execution.
Here we invoke `body` with `thisArg` as the `this` binding and the `_` state object as the only
argument. The result is a tuple that contains the next Opcode and argument.
If evaluation of the body resulted in an exception, we convert this into an Opcode 6 ("catch")
operation to be handled in the next spin of the `while` loop. We also clear the `y` variable in
case it is set to ensure we are no longer delegating operations as the exception occurred in
user code *outside* of, or at the function boundary of, the delegated iterator (otherwise the
iterator would have handled the exception itself).
After executing user code, we clear the `f` flag that indicates we are executing the generator,
as well as the `t` temporary value so that we don't hold onto values sent to the generator for
longer than necessary.
Inside of the `try..finally` statement are a series of statements that are used to evaluate the
operations of the transformed generator body.
The first thing we do is mark the generator as executing:
```ts
if (f = 1, ...)
```
Despite the fact this expression is part of the head of an `if` statement, the comma operator
causes it to be evaluated and the result thrown out. This is a minification added purely to
reduce the overall footprint of the helper.
## Delegating `yield*`
The first two statements of the `try..finally` statement handle delegation for `yield*`:
```ts
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
```
If the `y` variable is set, and `y` has a `next`, `throw`, or `return` method (depending on the
current operation), we invoke this method and store the return value (an IteratorResult) in `t`.
If `t` indicates it is a yielded value (e.g. `t.done === false`), we return `t` to the caller.
If `t` indicates it is a returned value (e.g. `t.done === true`), we mark the operation with the
`next` Opcode, and the returned value.
If `y` did not have the appropriate method, or `t` was a returned value, we reset `y` to a falsey
value and continue processing the operation.
## Handling operations
The various Opcodes are handled in the following switch statement:
```ts
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
```
The following sections describe the various Opcodes:
### Opcode 0 ("next") and Opcode 1 ("throw")
```ts
case 0: // next
case 1: // throw
t = op;
break;
```
Both Opcode 0 ("next") and Opcode 1 ("throw") have the same behavior. The current operation is
stored in the `t` variable and the `body` function is invoked. The `body` function should call
`_.sent()` which will evaluate the appropriate completion result.
### Opcode 4 ("yield")
```ts
case 4: // yield
_.label++;
return { value: op[1], done: false };
```
When we encounter Opcode 4 ("yield"), we increment the label by one to indicate the point at which
the generator will resume execution. We then return an `IteratorResult` whose `value` is the
yielded value, and `done` is `false`.
### Opcode 5 ("yieldstar")
```ts
case 5: // yieldstar
_.label++;
y = op[1];
op = [0];
continue;
```
When we receive Opcode 5 ("yieldstar"), we increment the label by one to indicate the point at which
the generator will resume execution. We then store the iterator in `op[1]` in the `y` variable, and
set the operation to delegate to Opcode 0 ("next") with no value. Finally, we continue execution at
the top of the loop to start delegation.
### Opcode 7 ("endfinally")
```ts
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
```
Opcode 7 ("endfinally") indicates that we have hit the end of a `finally` clause, and that the last
operation recorded before entering the `finally` block should be evaluated.
### Opcode 2 ("return"), Opcode 3 ("break"), and Opcode 6 ("catch")
```ts
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
```
The handling for Opcode 2 ("return"), Opcode 3 ("break") and Opcode 6 ("catch") is more
complicated, as we must obey the specified runtime semantics of generators. The first line in this
clause gets the current **Protected Region** if found and stores it in the `t` temp variable:
```ts
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && ...) ...
```
The remainder of this statement, as well as the following by several `if` statements test for more
complex conditions. The first of these is the following:
```ts
if (!(t = ...) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
```
If we encounter an Opcode 6 ("catch") or Opcode 2 ("return"), and we are not in a protected region,
then this operation completes the generator by setting the `_` variable to a falsey value. The
`continue` statement resumes execution at the top of the `while` statement, which will exit the loop
so that we continue execution at the statement following the loop.
```ts
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
```
The `if` statement above handles Opcode 3 ("break") when we are either not in a **protected region**, or
are performing an unconditional jump to a label inside of the current **protected region**. In this case
we can unconditionally jump to the specified label.
```ts
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
```
The `if` statement above handles Opcode 6 ("catch") when inside the `try` block of a **protected
region**. In this case we jump to the `catch` block, if present. We replace the value of `t` with
the operation so that the exception can be read as the first statement of the transformed `catch`
clause of the transformed generator body.
```ts
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
```
This `if` statement handles all Opcodes when in a **protected region** with a `finally` clause.
As long as we are not already inside the `finally` clause, we jump to the `finally` clause and
push the pending operation onto the `_.ops` stack. This allows us to resume execution of the
pending operation once we have completed execution of the `finally` clause, as long as it does not
supersede this operation with its own completion value.
```ts
if (t[2])
_.ops.pop();
```
Any other completion value inside of a `finally` clause will supersede the pending completion value
from the `try` or `catch` clauses. The above `if` statement pops the pending completion from the
stack.
```ts
_.trys.pop();
continue;
```
The remaining statements handle the point at which we exit a **protected region**. Here we pop the
current **protected region** from the stack and spin the `while` statement to evaluate the current
operation again in the next **protected region** or at the function boundary.
## Handling a completed generator
Once the generator has completed, the `_` state variable will be falsey. As a result, the `while`
loop will terminate and hand control off to the final statement of the orchestration function,
which deals with how a completed generator is evaluated:
```ts
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
```
If the caller calls `throw` on the generator it will send Opcode 1 ("throw"). If an exception
is uncaught within the body of the generator, it will send Opcode 6 ("catch"). As the generator has
completed, it throws the exception. Both of these cases are caught by the bitmask `5`, which does
not collide with the only two other valid completion Opcodes.
If the caller calls `next` on the generator, it will send Opcode 0 ("next"). As the generator has
completed, it returns an `IteratorResult` where `value` is `undefined` and `done` is true.
If the caller calls `return` on the generator, it will send Opcode 2 ("return"). As the generator
has completed, it returns an `IteratorResult` where `value` is the value provided to `return`, and
`done` is true.
\ No newline at end of file
{
"_from": "tslib@^1.9.3",
"_id": "tslib@1.9.3",
"_inBundle": false,
"_integrity": "sha1-1+TdeSRdhUKMTX5IIqeZF5VMooY=",
"_location": "/tslib",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "tslib@^1.9.3",
"name": "tslib",
"escapedName": "tslib",
"rawSpec": "^1.9.3",
"saveSpec": null,
"fetchSpec": "^1.9.3"
},
"_requiredBy": [
"/"
],
"_resolved": "http://registry.npm.taobao.org/tslib/download/tslib-1.9.3.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Ftslib%2Fdownload%2Ftslib-1.9.3.tgz",
"_shasum": "d7e4dd79245d85428c4d7e4822a79917954ca286",
"_spec": "tslib@^1.9.3",
"_where": "/Users/wanghongyuan/kickball0417",
"author": {
"name": "Microsoft Corp."
},
"bugs": {
"url": "https://github.com/Microsoft/TypeScript/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Runtime library for TypeScript helper functions",
"homepage": "http://typescriptlang.org/",
"jsnext:main": "tslib.es6.js",
"keywords": [
"TypeScript",
"Microsoft",
"compiler",
"language",
"javascript",
"tslib",
"runtime"
],
"license": "Apache-2.0",
"main": "tslib.js",
"module": "tslib.es6.js",
"name": "tslib",
"repository": {
"type": "git",
"url": "git+https://github.com/Microsoft/tslib.git"
},
"typings": "tslib.d.ts",
"version": "1.9.3"
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
export declare function __extends(d: Function, b: Function): void;
export declare function __assign(t: any, ...sources: any[]): any;
export declare function __rest(t: any, propertyNames: (string | symbol)[]): any;
export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any;
export declare function __param(paramIndex: number, decorator: Function): Function;
export declare function __metadata(metadataKey: any, metadataValue: any): Function;
export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any;
export declare function __generator(thisArg: any, body: Function): any;
export declare function __exportStar(m: any, exports: any): void;
export declare function __values(o: any): any;
export declare function __read(o: any, n?: number): any[];
export declare function __spread(...args: any[]): any[];
export declare function __await(v: any): any;
export declare function __asyncGenerator(thisArg: any, _arguments: any, generator: Function): any;
export declare function __asyncDelegator(o: any): any;
export declare function __asyncValues(o: any): any;
export declare function __makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray;
export declare function __importStar<T>(mod: T): T;
export declare function __importDefault<T>(mod: T): T | { default: T };
<script src="tslib.es6.js"></script>
\ No newline at end of file
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
export function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
export var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
export function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
}
export function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
export function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
export function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
export function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
export function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
export function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
export function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
export function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
export function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
export function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
export function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
export function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
export function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
export function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
export function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
export function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
<script src="tslib.js"></script>
\ No newline at end of file
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global global, define, System, Reflect, Promise */
var __extends;
var __assign;
var __rest;
var __decorate;
var __param;
var __metadata;
var __awaiter;
var __generator;
var __exportStar;
var __values;
var __read;
var __spread;
var __await;
var __asyncGenerator;
var __asyncDelegator;
var __asyncValues;
var __makeTemplateObject;
var __importStar;
var __importDefault;
(function (factory) {
var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
if (typeof define === "function" && define.amd) {
define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
}
else if (typeof module === "object" && typeof module.exports === "object") {
factory(createExporter(root, createExporter(module.exports)));
}
else {
factory(createExporter(root));
}
function createExporter(exports, previous) {
if (exports !== root) {
if (typeof Object.create === "function") {
Object.defineProperty(exports, "__esModule", { value: true });
}
else {
exports.__esModule = true;
}
}
return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
}
})
(function (exporter) {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
__extends = function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
__assign = Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
__rest = function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
__decorate = function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
__param = function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
__metadata = function (metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
};
__awaiter = function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
__generator = function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
__exportStar = function (m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
};
__values = function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
__read = function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
__spread = function () {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
};
__await = function (v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
};
__asyncGenerator = function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
__asyncDelegator = function (o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
};
__asyncValues = function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
__makeTemplateObject = function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
__importStar = function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
__importDefault = function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exporter("__extends", __extends);
exporter("__assign", __assign);
exporter("__rest", __rest);
exporter("__decorate", __decorate);
exporter("__param", __param);
exporter("__metadata", __metadata);
exporter("__awaiter", __awaiter);
exporter("__generator", __generator);
exporter("__exportStar", __exportStar);
exporter("__values", __values);
exporter("__read", __read);
exporter("__spread", __spread);
exporter("__await", __await);
exporter("__asyncGenerator", __asyncGenerator);
exporter("__asyncDelegator", __asyncDelegator);
exporter("__asyncValues", __asyncValues);
exporter("__makeTemplateObject", __makeTemplateObject);
exporter("__importStar", __importStar);
exporter("__importDefault", __importDefault);
});
{
"name": "kickball0417",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"scilla": {
"version": "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git#b807e097f6e526fa58e88dff09ef162c3bf89b59",
"from": "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git"
},
"scilla-components": {
"version": "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git#7dbeb2b004d67c960aa4f52b679d80bb5f4c9110",
"from": "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git"
},
"tslib": {
"version": "1.9.3",
"resolved": "http://registry.npm.taobao.org/tslib/download/tslib-1.9.3.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Ftslib%2Fdownload%2Ftslib-1.9.3.tgz",
"integrity": "sha1-1+TdeSRdhUKMTX5IIqeZF5VMooY="
}
}
}
{
"name": "kickball0417",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"mock": "game-cli m -p 4001 -f './mock' "
},
"build": {
"build-process": "scilla",
"release-path": "./dist",
"remote-path": "activity/kickball0417",
"version": ""
},
"dependencies": {
"scilla": "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git",
"scilla-components": "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git",
"tslib": "^1.9.3"
},
"devDependencies": {}
}
/**
* Created by rockyl on 2018-12-12.
*/
import {EventEmitter} from 'scilla'
const eventEmitter = new EventEmitter();
export default eventEmitter;
/**
* Created by rockyl on 2019-03-08.
*/
import {
utils,
} from 'scilla'
const options: any = {};
export function inject(data){
utils.injectProp(options, data);
}
export default options;
\ No newline at end of file
declare const DEBUG: boolean;
declare const RELEASE: boolean;
\ No newline at end of file
/**
* THIS FILE WAS GENERATE BY COMPILER
* DO NOT MODIFY THIS FILE
*/
import {registerDef} from 'scilla'
import component0 from 'components/base/Transform';
registerDef('components/base/Transform', component0);
import component1 from 'components/other/FullStageSize';
registerDef('components/other/FullStageSize', component1);
import component2 from 'components/renderer/TextureRenderer';
registerDef('components/renderer/TextureRenderer', component2);
import component3 from 'components/other/RelativeLayout';
registerDef('components/other/RelativeLayout', component3);
import component4 from 'components/other/CameraController';
registerDef('components/other/CameraController', component4);
import component5 from 'components/animation/TouchZoom';
registerDef('components/animation/TouchZoom', component5);
import component6 from 'components/ui/Button';
registerDef('components/ui/Button', component6);
import component7 from 'components/renderer/TextRenderer';
registerDef('components/renderer/TextRenderer', component7);
import component8 from 'components/base/TouchInterrupt';
registerDef('components/base/TouchInterrupt', component8);
import component9 from 'components/renderer/RectRenderer';
registerDef('components/renderer/RectRenderer', component9);
import component10 from '../../assets/scripts/scenes/ScenePlay';
registerDef('./scripts/scenes/ScenePlay', component10);
import component11 from '../../assets/scripts/popup/Popup';
registerDef('./scripts/popup/Popup', component11);
import component12 from '../../assets/scripts/navigator/SingleSceneNavigator';
registerDef('./scripts/navigator/SingleSceneNavigator', component12);
import component13 from '../../assets/scripts/dialogs/RulePanel';
registerDef('./scripts/dialogs/RulePanel', component13);
import component14 from '../../assets/scripts/scenes/SceneStart';
registerDef('./scripts/scenes/SceneStart', component14);
/**
* Created by rockyl on 2018/11/5.
*
* 游戏入口
*/
import {
setup,
launchScene, modifyEngineConfig,
loadJson,
setResPath,
} from 'scilla'
import './generated/MustCompile'
import {injectProp} from "scilla/src/tools/utils";
modifyEngineConfig({
lineHeightRatio: 1.2,
entityEnabled: false,
awakeComponentWhenAdded: false,
sleepComponentWhenRemoved: false,
drawRenderRect: false,
});
export async function startup(containerElement, options:any = {}, onProgress: Function) {
const manifest = await loadJson('manifest.json');
let engineConfig:any = {};
injectProp(engineConfig, manifest.engineConfig);
injectProp(engineConfig, options.engineConfig);
let customConfig:any = {};
injectProp(customConfig, manifest.customConfig);
injectProp(customConfig, options.customConfig);
setResPath(DEBUG ? 'assets/' : engineConfig.resPath);
let canvas = document.createElement('canvas');
containerElement.appendChild(canvas);
engineConfig.canvas = canvas;
setup(engineConfig, customConfig);
let entryScene = options.scene || customConfig.scene.entryScene;
launchScene(entryScene, onProgress).catch(e => {
console.log(e);
});
}
{
"replaces": {
"constants": {
"projectName": null
},
"contentInFiles": [
"index.html",
"manifest.json",
"package.json"
],
"nameOfFiles": []
}
}
{
"compilerOptions": {
"target": "es5",
"experimentalDecorators": true,
"removeComments": true,
"sourceMap": true,
"importHelpers": true,
"noImplicitAny": false,
"noEmitOnError": false,
"downlevelIteration": true,
"lib": [
"es5",
"es6",
"dom",
"es2015.promise"
],
"baseUrl": "./",
"paths": {
"scilla": ["node_modules/scilla/src/index"],
"components/*": ["node_modules/scilla-components/src/*"],
"lang": ["src/lang.ts"],
"globalEvent": ["src/GlobalEvent.ts"],
"launchOptions": ["src/LaunchOptions.ts"]
}
},
"include": [
"src",
"assets",
"node_modules/scilla/src",
"node_modules/scilla-components/src"
]
}
\ No newline at end of file
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"scilla-components@git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git":
version "1.0.0"
resolved "git+http://gitlab2.dui88.com/laoqifeng/scilla-components.git#a89dec7ac10c31b45e5050b849710a66e51ec3af"
"scilla@git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git":
version "1.0.1"
resolved "git+http://gitlab2.dui88.com/laoqifeng/scilla-core.git#cb530246b6b84a84e8f94abd8b96955538bb2cb6"
tslib@^1.9.3:
version "1.9.3"
resolved "http://registry.npm.taobao.org/tslib/download/tslib-1.9.3.tgz?cache=0&other_urls=http%3A%2F%2Fregistry.npm.taobao.org%2Ftslib%2Fdownload%2Ftslib-1.9.3.tgz#d7e4dd79245d85428c4d7e4822a79917954ca286"
integrity sha1-1+TdeSRdhUKMTX5IIqeZF5VMooY=
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