repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
zzm2q/WOZLLA.js
src/core/GameObject.ts
/// <reference path="Transform.ts"/> /// <reference path="RectTransform.ts"/> /// <reference path="Collider.ts"/> /// <reference path="../event/EventDispatcher.ts"/> module WOZLLA { var comparator = function(a:GameObject, b:GameObject) { return a.z - b.z; }; var idMap:any = {}; /** * GameObject is the base element in WOZLLA engine. It contains * many child instance of {@link WOZLLA.GameObject} and many * instance of {@link WOZLLA.Component}. * <br/> * <br/> * Tree structure of the GameObject is the core of WOZLLA engine. * * @class WOZLLA.GameObject * @extends WOZLLA.event.EventDispatcher */ export class GameObject extends WOZLLA.event.EventDispatcher { public static MASK_TRANSFORM_DIRTY:number = 0x1; public static MASK_VISIBLE = 0x10; /** * return the GameObject with the specified id. * @method {WOZLLA.GameObject} getById * @static * @param id the specified id * @member WOZLLA.GameObject */ public static getById(id:string):GameObject { return idMap[id]; } /** * get or set the id of this game object * @property {string} id * @member WOZLLA.GameObject */ get id():string { return this._id; } set id(value:string) { var oldId = this._id; this._id = value; if(oldId) { delete idMap[oldId]; } idMap[value] = this; } /** * get or set the name of this game object * @property {string} name * @member WOZLLA.GameObject */ get name():string { return this._name; } set name(value:string) { this._name = value; } /** * get transform of this game object * @property {WOZLLA.Transform} transform * @member WOZLLA.GameObject * @readonly */ get transform():Transform { return this._transform; } /** * get rect transform of this game object * @property {WOZLLA.RectTransform} rectTransform * @member WOZLLA.GameObject * @readonly */ get rectTransform():RectTransform { return this._rectTransform; } /** * get parent game object * @property {WOZLLA.GameObject} parent * @member WOZLLA.GameObject * @readonly */ get parent():GameObject { return this._parent; } /** * get children of this game object * @property {WOZLLA.GameObject[]} children * @member WOZLLA.GameObject * @readonly */ get children():GameObject[] { return this._children.slice(0); } /** * get raw children * @returns {WOZLLA.GameObject[]} */ get rawChildren():GameObject[] { return this._children; } /** * get child count * @property {number} childCount * @member WOZLLA.GameObject * @readonly */ get childCount():number { return this._children.length; } /** * get or set z order of this game object, and then resort children. * @property {number} z * @member WOZLLA.GameObject */ get z():number { return this._z; } set z(value:number) { this.setZ(value, true); } /** * get or set active of this game object. * the update method would be call every frame when active was true, false otherwise. * if active is set from false to true, the transform dirty would be true. * @property {boolean} active * @member WOZLLA.GameObject */ get active():boolean { return this._active; } set active(value:boolean) { var oldActive = this._active; this._active = value; if(!oldActive && value) { this._transform.dirty = true; } } /** * get visible of this game object. * the render method would be call every frame when visible and active both true. * @property {boolean} visible * @member WOZLLA.GameObject */ get visible():boolean { return this._visible; } set visible(value:boolean) { this._visible = value; } /** * get initialized of this game object * @property {boolean} initialized * @member WOZLLA.GameObject * @readonly */ get initialized():boolean { return this._initialized; } /** * get destroyed of this game object * @property {boolean} destroyed * @member WOZLLA.GameObject * @readonly */ get destroyed():boolean { return this._destroyed; } /** * get or set touchable of this game object. identify this game object is interactive. * @property {boolean} touchable * @member WOZLLA.GameObject * @readonly */ get touchable():boolean { return this._touchable; } set touchable(value:boolean) { this._touchable = value; } /** * get renderer component of this game object * @property {WOZLLA.Renderer} renderer * @member WOZLLA.GameObject * @readonly */ get renderer():Renderer { return this._renderer; } /** * get collider of this game object * @property {WOZLLA.Collider} collider * @member WOZLLA.GameObject * @readonly */ get collider():Collider { return this._collider; } /** * get behaviours of this game object * @property {WOZLLA.Behaviour[]} behaviours * @member WOZLLA.GameObject * @readonly */ get behaviours():Behaviour[] { return this._behaviours.slice(0); } /** * get mask component of this game object * @property {WOZLLA.Mask} mask * @member WOZLLA.GameObject * @readonly */ get mask():Mask { return this._mask; } _uuid:string; _id:string; _name; _active:boolean = true; _visible:boolean = true; _initialized:boolean = false; _destroyed:boolean = false; _touchable:boolean = false; _loadingAssets:boolean = false; _children:GameObject[]; _components:Component[]; _transform:Transform; _rectTransform:RectTransform; _parent:GameObject; _z:number; _renderer:Renderer; _collider:Collider; _behaviours:Behaviour[]; _mask:Mask; /** * new a GameObject * @method constructor * @member WOZLLA.GameObject * @param {boolean} useRectTransform specify which transform this game object should be used. */ constructor(useRectTransform:boolean=false) { super(); this._name = 'GameObject'; this._children = []; this._components = []; this._transform = useRectTransform ? new RectTransform() : new Transform(); this._rectTransform = useRectTransform ? <RectTransform>this._transform : null; this._z = 0; this._behaviours = []; } /** * set z order * @param value * @param sort true is set to resort children */ setZ(value:number, sort:boolean=true) { if(this._z === value) return; this._z = value; if(sort) { this._children.sort(comparator); } } /** * add a child game object, it would be fail when this game object has contains the child. * @param child * @param sort true is set to resort children * @returns {boolean} true is success to, false otherwise. */ addChild(child:GameObject, sort:boolean=true):boolean { if(this._children.indexOf(child) !== -1) { return false; } if(child._parent) { child.removeMe(); } child.dispatchEvent(new CoreEvent('beforeadd', false, { parent: this })); this._children.push(child); if(sort) { this._children.sort(comparator); } child._parent = this; child._transform.dirty = true; child.dispatchEvent(new CoreEvent('add', false)); this.dispatchEvent(new CoreEvent('childadd', false, { child: child })); return true; } /** * remove the specified child. * @param child * @returns {boolean} true is success to, false otherwise. */ removeChild(child:GameObject):boolean { var idx = this._children.indexOf(child); if(idx !== -1) { child.dispatchEvent(new CoreEvent('beforeremove', false)); this._children.splice(idx, 1); child._parent = null; child.dispatchEvent(new CoreEvent('remove', false, { parent: this })); this.dispatchEvent(new CoreEvent('childremove', false, { child: child })); return true; } return false; } /** * get the first child with the specified name. * @param name * @returns {WOZLLA.GameObject} */ getChild(name:string):GameObject { var child, i, len; for(i=0,len=this._children.length; i<len; i++) { child = this._children[i]; if(child._name === name) { return child; } } return null; } /** * get all children with the specified name. * @param name * @returns {Array} */ getChildren(name:string):GameObject[] { var child, i, len; var result = []; for(i=0,len=this._children.length; i<len; i++) { child = this._children[i]; if(child._name === name) { result.push(child); } } return result; } /** * remove this game object from parent. * @returns {boolean} */ removeMe():boolean { var parent = this._parent; return parent && parent.removeChild(this); } /** * iterator children of this game object * @param func interator function. */ eachChild(func:(value: GameObject, index: number, array: GameObject[]) => any):void { this._children.forEach(func); } /** * sort children */ sortChildren():void { this._children.sort(comparator); } /** * get path of this game object * @param split delimiter * @returns {string} */ getPath(split:string='/'):string { var arr = []; var obj:GameObject = this; while(obj) { arr.unshift(obj.name); obj = obj.parent; } return arr.join(split); } /** * whether contains the specified game object of this tree structure. * @param child * @returns {boolean} */ contains(child:GameObject):boolean { if(child === this) { return true; } var parent = child; while(parent = parent.parent) { if(parent === this) { return true; } } return false; } /** * get first component of type of the specified Type(constructor). * @param Type * @returns {WOZLLA.Component} */ getComponent(Type:Function):Component { var comp, i, len; if(this._components.length <= 0) { return null; } for(i=0,len=this._components.length; i<len; i++) { comp = this._components[i]; if(comp instanceof Type) { return comp; } } return null; } /** * @method hasComponent * @param Type * @returns {boolean} */ hasComponent(Type:Function):boolean { var comp, i, len; if(Type === RectTransform) { return !!this._rectTransform; } if(this._components.length <= 0) { return false; } for(i=0,len=this._components.length; i<len; i++) { comp = this._components[i]; if(comp instanceof Type) { return true; } } return false; } /** * get all components of type of Type(constructor). * @param Type * @returns {Array} */ getComponents(Type:Function):Component[] { var comp, i, len; var result = []; if(this._components.length <= 0) { return result; } for(i=0,len=this._components.length; i<len; i++) { comp = this._components[i]; if(comp instanceof Type) { result.push(comp); } } return result; } /** * add componen to this game object. this method would check component dependency * by method of component's listRequiredComponents. * @param comp * @returns {boolean} */ addComponent(comp:Component):boolean { if(this._components.indexOf(comp) !== -1) { return false; } this.checkComponentDependency(comp); if(comp._gameObject) { comp._gameObject.removeComponent(comp); } this._components.push(comp); comp._gameObject = this; if(comp instanceof Behaviour) { this._behaviours.push(<Behaviour>comp); } else if(comp instanceof Renderer) { this._renderer = <Renderer>comp; } else if(comp instanceof Collider) { this._collider = <Collider>comp; } else if(comp instanceof Mask) { this._mask = <Mask>comp; } return true; } /** * remove the specified component * @param comp * @returns {boolean} */ removeComponent(comp:Component):boolean { var i, len, otherComp; var idx = this._components.indexOf(comp); if(idx !== -1) { for(i=0,len=this._components.length; i<len; i++) { otherComp = this._components[i]; if(otherComp !== comp) { this.checkComponentDependency(otherComp, true); } } this._components.splice(idx, 1); if(comp instanceof Behaviour) { this._behaviours.splice(this._behaviours.indexOf(<Behaviour>comp), 1); } else if(comp instanceof Renderer) { this._renderer = null; } else if(comp instanceof Collider) { this._collider = null; } else if(comp instanceof Mask) { this._mask = null; } comp._gameObject = null; return true; } return false; } /** * init this game object. */ init():void { var i, len; if(this._initialized || this._destroyed) return; for(i=0,len=this._components.length; i<len; i++) { this._components[i].init(); } for(i=0,len=this._children.length; i<len; i++) { this._children[i].init(); } this._initialized = true; } /** * destroy this game object. */ destroy():void { var i, len; if(this._destroyed || !this._initialized) return; for(i=0,len=this._components.length; i<len; i++) { this._components[i].destroy(); } for(i=0,len=this._children.length; i<len; i++) { this._children[i].destroy(); } if(this._id) { delete idMap[this._id]; } this.clearAllListeners(); this._destroyed = true; } /** * call every frame when active was true. */ update():void { var i, len, behaviour; if(!this._active) return; if(this._behaviours.length > 0) { for (i = 0, len = this._behaviours.length; i < len; i++) { behaviour = this._behaviours[i]; behaviour.enabled && behaviour.update(); } } if(this._children.length > 0) { for (i = 0, len = this._children.length; i < len; i++) { this._children[i].update(); } } } /** * visit this game object and it's all chidlren, children of children. * @param renderer * @param parentTransform * @param flags */ visit(renderer:WOZLLA.renderer.IRenderer, parentTransform:Transform, flags:number):number { var i, len; if(!this._active || !this._initialized || this._destroyed) { if((flags & GameObject.MASK_TRANSFORM_DIRTY) === GameObject.MASK_TRANSFORM_DIRTY) { this._transform.dirty = true; } return; } if(this._transform.dirty) { flags |= GameObject.MASK_TRANSFORM_DIRTY; } if((flags & GameObject.MASK_TRANSFORM_DIRTY) == GameObject.MASK_TRANSFORM_DIRTY) { this._transform.transform(parentTransform); } if(!this._visible) { flags &= (~GameObject.MASK_VISIBLE); } if((flags & GameObject.MASK_VISIBLE) === GameObject.MASK_VISIBLE) { this.render(renderer, flags); } for(i=0,len=this._children.length; i<len; i++) { this._children[i].visit(renderer, this._transform, flags); } return flags; } /** * render this game object * @param renderer * @param flags */ render(renderer:WOZLLA.renderer.IRenderer, flags:number) { this._mask && this._mask.render(renderer, flags); this._renderer && this._renderer.render(renderer, flags); } /** * get a game object under the point. * @param x * @param y * @param touchable * @returns {WOZLLA.GameObject} */ public getUnderPoint(x:number, y:number, touchable:boolean=false):GameObject { var found, localP, child; var childrenArr; if(!this._active || !this._visible) return null; childrenArr = this._children; if(childrenArr.length > 0) { for(var i=childrenArr.length-1; i>=0; i--) { child = childrenArr[i]; found = child.getUnderPoint(x, y, touchable); if(found) { return found; } } } if(!touchable || this._touchable) { localP = this.transform.globalToLocal(x, y); if(this.testHit(localP.x, localP.y)) { return this; } } return null; } /** * try to do a hit test * @param localX * @param localY * @returns {boolean} */ public testHit(localX:number, localY:number):boolean { var collider:Collider = this._collider; return collider && collider.collideXY(localX, localY); } public loadAssets(callback:Function) { var i, len, count, comp; if(this._loadingAssets) return; count = this._components.length + this._children.length; if(count === 0) { callback && callback(); return; } for(i=0,len=this._components.length; i<len; i++) { comp = this._components[i]; comp.loadAssets(() => { if(--count === 0) { callback && callback(); } }); } for(i=0,len=this._children.length; i<len; i++) { this._children[i].loadAssets(() => { if(--count === 0) { callback && callback(); } }); } } static QUERY_FULL_REGEX = /((.*?):(.*?))\[(.*?)\]$/; static QUERY_COMP_REGEX = /((.*?):(.*?))$/; static QUERY_OBJ_ATTR_REGEX = /(.*?)\[(.*?)\]$/; query(expr:string, record?:QueryRecord):any { var result, compExpr, objExpr, compName, attrName; var objArr; var hasAttr = expr.indexOf('[') !== -1 && expr.indexOf(']') !== -1; var hasComp = expr.indexOf(':') !== -1; if(hasComp && hasAttr) { result = GameObject.QUERY_FULL_REGEX.exec(expr); compExpr = result[1]; objExpr = result[2]; compName = result[3]; attrName = result[4]; } else if(hasComp && !hasAttr) { result = GameObject.QUERY_COMP_REGEX.exec(expr); compExpr = result[1]; objExpr = result[2]; compName = result[3]; } else if(!hasComp && hasAttr) { result = GameObject.QUERY_OBJ_ATTR_REGEX.exec(expr); objExpr = result[1]; attrName = result[2]; } else { objExpr = expr; } if(record) { record.compExpr = compExpr; record.objExpr = objExpr; record.compName = compName; record.attrName = attrName; } if(!objExpr) { result = this; } else { result = this; objArr = objExpr.split('/'); for(var i=0,len=objArr.length; i<len; i++) { if(!objArr[i]) { break; } result = result.getChild(objArr[i]); if(!result) { break; } } } if(result && compName) { result = result.getComponent(Component.getType(compName)); } if(result && record) { record.target = result; } if(result && attrName) { result = result[attrName]; } return result; } protected checkComponentDependency(comp:Component, isRemove:boolean=false) { var Type:Function; var requires = comp.listRequiredComponents(); if(!requires || requires.length === 0) return; for(var i=0, len=requires.length; i<len; i++) { Type = requires[i]; if(!this.hasComponent(Type)) { if(isRemove) { throw new Error('Can NOT remove: Component[' + Component.getName(comp['constructor']) + '] depend on it'); } else { var name = Type === RectTransform ? 'RectTransform' : Component.getName(Type); throw new Error('Can NOT add: Component[' + name + '] required'); } } } } } export class QueryRecord { compExpr = null; objExpr = null; compName = null; attrName = null; target = null; } }
zzm2q/WOZLLA.js
src/layout/Grid.ts
/// <reference path="LayoutBase.ts"/> /// <reference path="../math/Size.ts"/> /// <reference path="../component/PropertyConverter.ts"/> module WOZLLA.layout { var helpSize = new WOZLLA.math.Size(0, 0); export class Grid extends LayoutBase { listRequiredComponents():Array<Function> { return [RectTransform]; } get padding():Padding { return this._padding; } set padding(padding:Padding) { if(this._padding && this._padding.equals(padding)) return; this._padding = padding; this.requestLayout(); } get itemMargin():Margin { return this._itemMargin; } set itemMargin(margin:Margin) { if(this._itemMargin && this._itemMargin.equals(margin)) return; this._itemMargin = margin; this.requestLayout(); } _padding:Padding; _itemMargin:Margin; doLayout():void { var padding = this._padding; var margin = this._itemMargin; var children = this.gameObject.rawChildren; var col = 0; var row = 0; var rowHeight = 0; var x = padding.left; var y = padding.top; var child; var rect = this.gameObject.rectTransform; for(var i=0,len=children.length; i<len; i++) { child = children[i]; this.measureChildSize(child, i, helpSize); // measure x, y x += margin.left; y += margin.top; // resolve new row if(x + helpSize.width + margin.right + padding.right > rect.width) { row ++; col = 0; y += margin.bottom; y += helpSize.height; x = padding.left + margin.left; } // apply position if(child.rectTransform) { child.rectTransform.px = x; child.rectTransform.py = y; } else { child.transform.x = x; child.transform.y = y; } // determine row height if(helpSize.height > rowHeight) { rowHeight = helpSize.height; } // grow col num x += margin.right + helpSize.width; col++; } } protected measureChildSize(child:GameObject, idx:number, size:WOZLLA.math.Size) { var rectTransform = child.rectTransform; if(!rectTransform) { size.height = size.width = 0; } else { size.width = rectTransform.width; size.height = rectTransform.height; } } } Component.register(Grid, { name: 'Grid', properties: [{ name: 'padding', type: 'Padding', convert: component.PropertyConverter.array2Padding, defaultValue: [0, 0, 0, 0] }, { name: 'itemMargin', type: 'Margin', convert: component.PropertyConverter.array2Margin, defaultValue: [0, 0, 0, 0] }] }); }
zzm2q/WOZLLA.js
build/dist/WOZLLA.d.ts
<filename>build/dist/WOZLLA.d.ts /// <reference path="../../libs/hammerjs.d.ts" /> /// <reference path="../../libs/DragonBones.d.ts" /> declare module WOZLLA.event { /** * @enum {number} WOZLLA.event.EventPhase * all enumerations of event phase */ enum EventPhase { /** @property {number} [CAPTURE] */ CAPTURE = 0, /** @property {number} [BUBBLE] */ BUBBLE = 1, /** @property {number} [TARGET] */ TARGET = 2, } /** * @class WOZLLA.event.Event * Base class for all event object of WOZLLA engine. <br/> * see also: <br/> * {@link WOZLLA.event.EventPhase} <br/> * {@link WOZLLA.event.EventDispatcher} <br/> */ class Event { /** * event data. * @member WOZLLA.event.Event * @property {any} data * @readonly */ data: any; /** * event type. * @member WOZLLA.event.Event * @property {string} type * @readonly */ type: string; /** * event origin target. * @member WOZLLA.event.Event * @property {WOZLLA.event.EventDispatcher} target * @readonly */ target: EventDispatcher; /** * current event target in event bubbling. * @member WOZLLA.event.Event * @property {WOZLLA.event.EventDispatcher} currentTarget * @readonly */ currentTarget: EventDispatcher; /** * which phase this event is in. * @member WOZLLA.event.Event * @property {WOZLLA.event.EventPhase} eventPhase * @readonly */ eventPhase: EventPhase; /** * true to identify this event could be bubbled, false otherwise. * @member WOZLLA.event.Event * @property {boolean} bubbles * @readonly */ bubbles: boolean; /** * true to identify this event could be stop bubbles, false otherwise. * @member WOZLLA.event.Event * @property {boolean} canStopBubbles * @readonly */ canStopBubbles: boolean; _type: string; _target: EventDispatcher; _currentTarget: EventDispatcher; _data: any; _bubbles: boolean; _canStopBubbles: boolean; _eventPhase: EventPhase; _immediatePropagationStoped: boolean; _propagationStoped: boolean; _listenerRemove: boolean; /** * @method constructor * create a new Event object * @member WOZLLA.event.Event * @param {string} type * @param {boolean} bubbles * @param {any} data * @param {boolean} canStopBubbles */ constructor(type: string, bubbles?: boolean, data?: any, canStopBubbles?: boolean); /** * @method isStopPropagation * @member WOZLLA.event.Event * @returns {boolean} */ isStopPropagation(): boolean; /** * stop bubble to next parent * @method stopPropagation * @member WOZLLA.event.Event */ stopPropagation(): void; /** * @method isStopImmediatePropagation * @member WOZLLA.event.Event * @returns {boolean} */ isStopImmediatePropagation(): boolean; /** * stop event bubble immediately even other listeners dosen't receive this event. * @method stopImmediatePropagation * @member WOZLLA.event.Event */ stopImmediatePropagation(): void; /** * call from current listener to remove the current listener */ removeCurrentListener(): void; } } declare module WOZLLA.event { /** * @class WOZLLA.event.EventDispatcher * Base class for bubblable event system * */ class EventDispatcher { private _captureDict; private _bubbleDict; private _bubbleParent; /** * @method setBubbleParent * set bubble parent of this dispatcher * @param {WOZLLA.event.EventDispatcher} bubbleParent */ setBubbleParent(bubbleParent: EventDispatcher): void; /** * @method hasListener * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ hasListener(type: string, useCapture?: boolean): boolean; /** * @method getListenerCount * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. * @returns {number} */ getListenerCount(type: string, useCapture: boolean): number; /** * @method addListener * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ addListener(type: string, listener: Function, useCapture?: boolean): void; addListenerScope(type: string, listener: Function, scope: any, useCapture?: boolean): void; /** * @method removeListener * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ removeListener(type: string, listener: Function, useCapture?: boolean): boolean; removeListenerScope(type: string, listener: Function, scope: any, userCapture?: boolean): boolean; /** * @method clearListeners * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ clearListeners(type: string, useCapture: boolean): void; /** * @method clearAllListeners * clear all listeners */ clearAllListeners(): void; /** * @method dispatch an event * @param {WOZLLA.event.Event} event */ dispatchEvent(event: Event): void; _dispatchEventInPhase(event: Event, phase: EventPhase): boolean; private _getAncients(); private _getListenerList(type, useCapture); } } declare module WOZLLA.assets { /** * Base class of all assets in WOZLLA engine. * an asset contains a reference count which increase by **retain** function, * decrease by **release** function. * an asset would be unload when reference count reach 0. * @class WOZLLA.assets.Asset * @extends WOZLLA.event.EventDispatcher * @abstract */ class Asset extends event.EventDispatcher { static EVENT_UNLOAD: string; /** * @property {string} src * @readonly */ src: string; fullPath: string; private _src; private _baseDir; private _refCount; constructor(src: string, baseDir?: string); /** * retain this asset */ retain(): void; /** * release this asset * @param {boolean} [decreaceRefCount=true] */ release(decreaceRefCount?: boolean): void; /** * load this asset * @param onSuccess * @param onError */ load(onSuccess: () => any, onError: (error: any) => any): void; /** * unload this asset * @fires unload event */ unload(): void; } } declare module WOZLLA.assets { interface AssetDescription { src: string; AssetClass: Function; callback: Function; } /** * an singleton class for asset loading and asset management * @class WOZLLA.assets.AssetLoader * @singleton */ class AssetLoader { private static instance; /** * return the singleton of this class * @method getInstance * @static * @returns {WOZLLA.assets.AssetLoader} */ static getInstance(): AssetLoader; _loadedAssets: {}; _loadingUnits: {}; _baseDir: string; getBaseDir(): string; setBaseDir(baseDir: string): void; /** * get an asset by src * @param src * @returns {any} */ getAsset(src: any): any; /** * add asset to asset loader, the asset would be auto removed when unloaded. * @param asset */ addAsset(asset: Asset): void; /** * remove asset from asset loader * @param asset */ removeAsset(asset: Asset): void; /** * load all asset * @param items */ loadAll(items: AssetDescription[]): void; /** * load an asset by src, AssetClass(constructor/factory) * @param src * @param AssetClass * @param callback */ load(src: string, AssetClass: Function, callback?: () => any): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.ITexture * @abstract */ interface ITexture { id: any; descriptor: ITextureDescriptor; bind(gl: any): void; } module ITexture { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.ITexture */ var DOC: string; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.IRenderer * @abstract */ interface IRenderer { /** * @property {WOZLLA.renderer.ILayerManager} layerManager */ layerManager: ILayerManager; materialManager: IMaterialManager; shaderManager: IShaderManager; textureManager: ITextureManager; viewport: any; gl: any; addCommand(command: IRenderCommand): void; render(): void; flush(): void; } module IRenderer { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.IRenderer */ var DOC: string; } } declare module WOZLLA.math { /** * @class WOZLLA.math.Matrix * a util class for 2d matrix */ class Matrix { /** * @property DEG_TO_RAD * @member WOZLLA.math.Matrix * @readonly * @static */ static DEG_TO_RAD: number; values: Float32Array; constructor(); /** * apply from another matrix * @param matrix */ applyMatrix(matrix: Matrix): void; /** * identify this matrix */ identity(): void; /** * invert this matrix */ invert(): void; /** * prepend 2d params to this matrix * @param a * @param b * @param c * @param d * @param tx * @param ty */ prepend(a: number, b: number, c: number, d: number, tx: number, ty: any): void; /** * append 2d params to this matrix * @param a * @param b * @param c * @param d * @param tx * @param ty */ append(a: number, b: number, c: number, d: number, tx: number, ty: any): void; /** * prepend 2d transform params to this matrix * @param x * @param y * @param scaleX * @param scaleY * @param rotation * @param skewX * @param skewY * @param regX * @param regY * @returns {WOZLLA.math.Matrix} */ prependTransform(x: any, y: any, scaleX: any, scaleY: any, rotation: any, skewX: any, skewY: any, regX: any, regY: any): Matrix; /** * append 2d transform params to this matrix * @param x * @param y * @param scaleX * @param scaleY * @param rotation * @param skewX * @param skewY * @param regX * @param regY * @returns {WOZLLA.math.Matrix} */ appendTransform(x: any, y: any, scaleX: any, scaleY: any, rotation: any, skewX: any, skewY: any, regX: any, regY: any): Matrix; } } declare module WOZLLA.utils { class Tween { static NONE: number; static LOOP: number; static REVERSE: number; private static _tweens; private static IGNORE; private static _plugins; private static _inited; private _target; private _useTicks; private ignoreGlobalPause; private loop; private pluginData; private _curQueueProps; private _initQueueProps; private _steps; private _actions; private paused; private duration; private _prevPos; private position; private _prevPosition; private _stepPosition; private passive; static get(target: any, props?: any, pluginData?: any, override?: boolean): Tween; static removeTweens(target: any): void; static tick(delta: any, paused?: boolean): void; private static _register(tween, value); static removeAllTweens(): void; constructor(target: any, props: any, pluginData: any); private initialize(target, props, pluginData); private setPosition(value, actionsMode?); private _runActions(startPos, endPos, includeStart?); private _updateTargetProps(step, ratio); setPaused(value: boolean): Tween; private _cloneProps(props); private _addStep(o); private _appendQueueProps(o); private _addAction(o); private _set(props, o); wait(duration: number, passive?: boolean): Tween; to(props: any, duration: number, ease?: any): Tween; call(callback: Function, thisObj?: any, params?: any): Tween; set(props: any, target?: any): Tween; play(tween: Tween): Tween; pause(tween: Tween): Tween; tick(delta: number): void; } } declare module WOZLLA { /** * this class define the position, scale, rotation and about transform information of {@link WOZLLA.GameObject} * @class WOZLLA.Transform */ class Transform { __local_matrix: any; /** * @property {number} DEG_TO_RAD * @readonly * @static */ static DEG_TO_RAD: number; /** * @property {WOZLLA.math.Matrix} worldMatrix * @readonly */ worldMatrix: math.Matrix; /** * specify this tranform * @type {boolean} */ useGLCoords: boolean; _values: number[]; _relative: boolean; _dirty: boolean; constructor(); x: any; y: any; rotation: any; scaleX: any; scaleY: any; skewX: any; skewY: any; relative: boolean; dirty: boolean; setPosition(x: any, y: any): void; setAnchor(anchorX: any, anchorY: any): void; setRotation(rotation: any): void; setScale(scaleX: any, scaleY: any): void; setSkew(skewX: any, skewY: any): void; reset(): void; set(transform: any): void; transform(parentTransform?: Transform): void; updateWorldMatrix(): void; globalToLocal(x: any, y: any, updateMatrix?: boolean): { x: number; y: number; }; localToGlobal(x: any, y: any, updateMatrix?: boolean): { x: number; y: number; }; tween(override: boolean): any; clearTweens(): void; } } declare module WOZLLA { /** * RectTransform is a subclass of {@link WOZLLA.Transform}, define a rect region * for {@WOZLLA.GameObject} and a anchor mode to specify how to related to it's parent. * @class WOZLLA.RectTransform */ class RectTransform extends Transform { static getMode(name: any): number; /** * vertical anchor mode * @property {number} ANCHOR_TOP * @readonly * @static */ static ANCHOR_TOP: number; /** * vertical anchor mode * @property {number} ANCHOR_MIDDLE * @readonly * @static */ static ANCHOR_MIDDLE: number; /** * vertical anchor mode * @property {number} ANCHOR_BOTTOM * @readonly * @static */ static ANCHOR_BOTTOM: number; /** * vertical anchor mode * @property {number} ANCHOR_VERTICAL_STRENGTH * @readonly * @static */ static ANCHOR_VERTICAL_STRENGTH: number; /** * horizontal anchor mode * @property {number} ANCHOR_LEFT * @readonly * @static */ static ANCHOR_LEFT: number; /** * horizontal anchor mode * @property {number} ANCHOR_CENTER * @readonly * @static */ static ANCHOR_CENTER: number; /** * horizontal anchor mode * @property {number} ANCHOR_RIGHT * @readonly * @static */ static ANCHOR_RIGHT: number; /** * horizontal anchor mode * @property {number} ANCHOR_HORIZONTAL_STRENGTH * @readonly * @static */ static ANCHOR_HORIZONTAL_STRENGTH: number; /** * get or set width, this property only effect on fixed size mode * @property {number} width */ width: number; /** * get or set height, this property only effect on fixed size mode * @property {number} height */ height: number; /** * get or set top * @property {number} top */ top: number; /** * get or set left * @property {number} left */ left: number; /** * get or set right * @property {number} right */ right: number; /** * get or set bottom * @property {number} bottom */ bottom: number; /** * get or set px, this only effect on strengthen mode * @property {number} px specify x coords */ px: number; /** * get or set py, this only effect on strengthen mode * @property {number} py specify y coords */ py: number; /** * get or set anchor mode * @property {number} anchorMode */ anchorMode: number; _width: number; _height: number; _top: number; _left: number; _right: number; _bottom: number; _px: number; _py: number; _anchorMode: number; /** * set rect transform * @param {WOZLLA.RectTransform} rectTransform */ set(rectTransform: RectTransform): void; /** * transform with parent transform * @param {WOZLLA.Transform} parentTransform */ transform(parentTransform?: Transform): void; } } declare module WOZLLA { class Assert { static DEFAULT_MESSAGE: string; static isTrue(test: any, msg?: string): void; static isFalse(test: any, msg?: string): void; static isTypeof(test: any, type: string, msg?: string): void; static isNotTypeof(test: any, type: string, msg?: string): void; static isString(test: any, msg?: string): void; static isObject(test: any, msg?: string): void; static isUndefined(test: any, msg?: string): void; static isNotUndefined(test: any, msg?: string): void; static isFunction(test: any, msg?: string): void; } } declare module WOZLLA { /** * Top class of all components * @class WOZLLA.Component * @extends WOZLLA.event.EventDispatcher * @abstract */ class Component extends event.EventDispatcher { /** * get the GameObject of this component belongs to. * @property {WOZLLA.GameObject} gameObject */ gameObject: GameObject; /** * get transform of the gameObject of this component * @property {WOZLLA.Transform} transform */ transform: Transform; _gameObject: GameObject; _uuid: string; /** * init this component */ init(): void; /** * destroy this component */ destroy(): void; loadAssets(callback: Function): void; listRequiredComponents(): Function[]; private static ctorMap; private static configMap; static getType(name: string): any; static getName(Type: Function): any; /** * register an component class and it's configuration * @method register * @static * @param ctor * @param configuration */ static register(ctor: Function, config: any): void; static unregister(name: string): void; /** * create component by it's registed name. * @param name the component name * @returns {WOZLLA.Component} */ static create(name: string): Component; static getConfig(name: any): any; static extendConfig(Type: Function): any; } } declare module WOZLLA { /** * abstract base class for all colliders * @class WOZLLA.Collider * @extends WOZLLA.Component * @abstract */ class Collider extends Component { /** * @method {boolean} containsXY * @param localX x coords relate to the gameObject of this collider * @param localY y coords relate to the gameObject of this collider * @returns {boolean} */ collideXY(localX: number, localY: number): boolean; collide(collider: Collider): boolean; } } declare module WOZLLA { /** * GameObject is the base element in WOZLLA engine. It contains * many child instance of {@link WOZLLA.GameObject} and many * instance of {@link WOZLLA.Component}. * <br/> * <br/> * Tree structure of the GameObject is the core of WOZLLA engine. * * @class WOZLLA.GameObject * @extends WOZLLA.event.EventDispatcher */ class GameObject extends event.EventDispatcher { static MASK_TRANSFORM_DIRTY: number; static MASK_VISIBLE: number; /** * return the GameObject with the specified id. * @method {WOZLLA.GameObject} getById * @static * @param id the specified id * @member WOZLLA.GameObject */ static getById(id: string): GameObject; /** * get or set the id of this game object * @property {string} id * @member WOZLLA.GameObject */ id: string; /** * get or set the name of this game object * @property {string} name * @member WOZLLA.GameObject */ name: string; /** * get transform of this game object * @property {WOZLLA.Transform} transform * @member WOZLLA.GameObject * @readonly */ transform: Transform; /** * get rect transform of this game object * @property {WOZLLA.RectTransform} rectTransform * @member WOZLLA.GameObject * @readonly */ rectTransform: RectTransform; /** * get parent game object * @property {WOZLLA.GameObject} parent * @member WOZLLA.GameObject * @readonly */ parent: GameObject; /** * get children of this game object * @property {WOZLLA.GameObject[]} children * @member WOZLLA.GameObject * @readonly */ children: GameObject[]; /** * get raw children * @returns {WOZLLA.GameObject[]} */ rawChildren: GameObject[]; /** * get child count * @property {number} childCount * @member WOZLLA.GameObject * @readonly */ childCount: number; /** * get or set z order of this game object, and then resort children. * @property {number} z * @member WOZLLA.GameObject */ z: number; /** * get or set active of this game object. * the update method would be call every frame when active was true, false otherwise. * if active is set from false to true, the transform dirty would be true. * @property {boolean} active * @member WOZLLA.GameObject */ active: boolean; /** * get visible of this game object. * the render method would be call every frame when visible and active both true. * @property {boolean} visible * @member WOZLLA.GameObject */ visible: boolean; /** * get initialized of this game object * @property {boolean} initialized * @member WOZLLA.GameObject * @readonly */ initialized: boolean; /** * get destroyed of this game object * @property {boolean} destroyed * @member WOZLLA.GameObject * @readonly */ destroyed: boolean; /** * get or set touchable of this game object. identify this game object is interactive. * @property {boolean} touchable * @member WOZLLA.GameObject * @readonly */ touchable: boolean; /** * get renderer component of this game object * @property {WOZLLA.Renderer} renderer * @member WOZLLA.GameObject * @readonly */ renderer: Renderer; /** * get collider of this game object * @property {WOZLLA.Collider} collider * @member WOZLLA.GameObject * @readonly */ collider: Collider; /** * get behaviours of this game object * @property {WOZLLA.Behaviour[]} behaviours * @member WOZLLA.GameObject * @readonly */ behaviours: Behaviour[]; /** * get mask component of this game object * @property {WOZLLA.Mask} mask * @member WOZLLA.GameObject * @readonly */ mask: Mask; _uuid: string; _id: string; _name: any; _active: boolean; _visible: boolean; _initialized: boolean; _destroyed: boolean; _touchable: boolean; _loadingAssets: boolean; _children: GameObject[]; _components: Component[]; _transform: Transform; _rectTransform: RectTransform; _parent: GameObject; _z: number; _renderer: Renderer; _collider: Collider; _behaviours: Behaviour[]; _mask: Mask; /** * new a GameObject * @method constructor * @member WOZLLA.GameObject * @param {boolean} useRectTransform specify which transform this game object should be used. */ constructor(useRectTransform?: boolean); /** * set z order * @param value * @param sort true is set to resort children */ setZ(value: number, sort?: boolean): void; /** * add a child game object, it would be fail when this game object has contains the child. * @param child * @param sort true is set to resort children * @returns {boolean} true is success to, false otherwise. */ addChild(child: GameObject, sort?: boolean): boolean; /** * remove the specified child. * @param child * @returns {boolean} true is success to, false otherwise. */ removeChild(child: GameObject): boolean; /** * get the first child with the specified name. * @param name * @returns {WOZLLA.GameObject} */ getChild(name: string): GameObject; /** * get all children with the specified name. * @param name * @returns {Array} */ getChildren(name: string): GameObject[]; /** * remove this game object from parent. * @returns {boolean} */ removeMe(): boolean; /** * iterator children of this game object * @param func interator function. */ eachChild(func: (value: GameObject, index: number, array: GameObject[]) => any): void; /** * sort children */ sortChildren(): void; /** * get path of this game object * @param split delimiter * @returns {string} */ getPath(split?: string): string; /** * whether contains the specified game object of this tree structure. * @param child * @returns {boolean} */ contains(child: GameObject): boolean; /** * get first component of type of the specified Type(constructor). * @param Type * @returns {WOZLLA.Component} */ getComponent(Type: Function): Component; /** * @method hasComponent * @param Type * @returns {boolean} */ hasComponent(Type: Function): boolean; /** * get all components of type of Type(constructor). * @param Type * @returns {Array} */ getComponents(Type: Function): Component[]; /** * add componen to this game object. this method would check component dependency * by method of component's listRequiredComponents. * @param comp * @returns {boolean} */ addComponent(comp: Component): boolean; /** * remove the specified component * @param comp * @returns {boolean} */ removeComponent(comp: Component): boolean; /** * init this game object. */ init(): void; /** * destroy this game object. */ destroy(): void; /** * call every frame when active was true. */ update(): void; /** * visit this game object and it's all chidlren, children of children. * @param renderer * @param parentTransform * @param flags */ visit(renderer: renderer.IRenderer, parentTransform: Transform, flags: number): number; /** * render this game object * @param renderer * @param flags */ render(renderer: renderer.IRenderer, flags: number): void; /** * get a game object under the point. * @param x * @param y * @param touchable * @returns {WOZLLA.GameObject} */ getUnderPoint(x: number, y: number, touchable?: boolean): GameObject; /** * try to do a hit test * @param localX * @param localY * @returns {boolean} */ testHit(localX: number, localY: number): boolean; loadAssets(callback: Function): void; static QUERY_FULL_REGEX: RegExp; static QUERY_COMP_REGEX: RegExp; static QUERY_OBJ_ATTR_REGEX: RegExp; query(expr: string, record?: QueryRecord): any; protected checkComponentDependency(comp: Component, isRemove?: boolean): void; } class QueryRecord { compExpr: any; objExpr: any; compName: any; attrName: any; target: any; } } declare module WOZLLA { /** * the root game object of WOZLLA engine * @class WOZLLA.Stage * @extends WOZLLA.GameObject */ class Stage extends GameObject { static ID: string; viewRectTransform: RectTransform; _rootTransform: Transform; _viewRectTransform: RectTransform; constructor(); visitStage(renderer: renderer.IRenderer): void; } } declare module WOZLLA { /** * @class WOZLLA.Time * @static */ class Time { /** * @property {number} delta * @readonly * @static */ static delta: number; /** * @property {number} now * @readonly * @static */ static now: number; /** * @property {number} measuredFPS * @readonly * @static */ static measuredFPS: number; static _nowIncrease: number; static update(timeScale: any): void; static reset(): void; } } declare module WOZLLA { /** * @class WOZLLA.Scheduler * @singleton */ class Scheduler { private static instance; /** * @method {WOZLLA.Scheduler} getInstance * @static * @member WOZLLA.Scheduler */ static getInstance(): any; private _scheduleCount; private _lastSchedules; private _schedules; runSchedule(): void; /** * remove the specify schedule by id * @param id */ removeSchedule(id: any): void; /** * schedule the task to each frame * @param task * @param args * @returns {string} schedule id */ scheduleLoop(task: any, args?: any): string; /** * schedule the task to the next speficied frame * @param task * @param {number} frame * @param args * @returns {string} schedule id */ scheduleFrame(task: any, frame?: number, args?: any): string; /** * schedule the task to internal, like setInterval * @param task * @param time * @param args * @returns {string} schedule id */ scheduleInterval(task: any, time?: number, args?: any): string; /** * schedule the task to time, like setTimeout * @param task * @param time * @param args * @returns {string} schedule id */ scheduleTime(task: any, time?: number, args?: any): string; /** * resume the specified schedule * @param scheduleId */ resumeSchedule(scheduleId: any): void; /** * pause the specified schedule * @param scheduleId */ pauseSchedule(scheduleId: any): void; } } declare module WOZLLA { class GestureEvent extends event.Event { x: number; y: number; touch: any; touchMoveDetection: boolean; gesture: any; identifier: any; constructor(params: any); setTouchMoveDetection(value: boolean): void; } /** * class for touch management <br/> * get the instance form {@link WOZLLA.Director} * @class WOZLLA.Touch * @protected */ class Touch { private static enabledGestures; static setEanbledGestures(gestures: any): void; /** * get or set enabled of touch system * @property {boolean} enabled */ enabled: boolean; canvas: HTMLCanvasElement; canvasOffset: any; touchScale: number; channelMap: {}; constructor(canvas: HTMLCanvasElement, touchScale?: number); onGestureEvent(e: any): void; createDispatchChanel(touchTarget: any): { onGestureEvent: (e: any, target: any, x: any, y: any, identifier: any) => void; }; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.WebGLUtils * @abstract */ class WebGLUtils { static getGLContext(canvas: any, options?: any): any; static compileShader(gl: any, shaderType: any, shaderSrc: any): any; static compileProgram(gl: any, vertexSrc: any, fragmentSrc: any): { program: any; vertexShader: any; fragmentShader: any; }; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.ILayerManager * @abstract */ interface ILayerManager { define(layer: string, zindex: number): void; undefine(layer: string): void; getZIndex(layer: string): number; getSortedLayers(): string[]; } module ILayerManager { /** * @property {string} DEFAULT * @readonly * @static * @member WOZLLA.renderer.ILayerManager */ var DEFAULT: string; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.LayerManager * @extends WOZLLA.renderer.ILayerManager */ class LayerManager implements ILayerManager { _layerIndexMap: any; _sortedLayers: any; constructor(); define(layer: string, zindex: number): void; undefine(layer: string): void; getZIndex(layer: string): number; getSortedLayers(): string[]; _getSortedLayers(): string[]; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.BlendType */ class BlendType { static NORMAL: number; static ADD: number; static MULTIPLY: number; static SCREEN: number; srcFactor: any; distFactor: any; _srcFactor: any; _distFactor: any; constructor(srcFactor: any, distFactor: any); applyBlend(gl: any): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.Material * @extends WOZLLA.renderer.IMaterial */ class Material implements IMaterial { id: any; shaderProgramId: string; blendType: number; _id: any; _shaderProgramId: string; _blendType: number; constructor(id: any, shaderProgramId: string, blendType: number); equals(other: IMaterial): boolean; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.IMaterial * @abstract */ interface IMaterial { id: string; shaderProgramId: string; blendType: number; equals(other: IMaterial): boolean; } module IMaterial { /** * default material key of built-in * @property {string} DEFAULT * @readonly * @static * @member WOZLLA.renderer.IMaterial */ var DEFAULT: string; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.IShaderProgram * @abstract */ interface IShaderProgram { id: any; vertexShader: any; fragmentShader: any; useProgram(gl: any): void; syncUniforms(gl: any, uniforms: { projection: any; }): any; } module IShaderProgram { /** * @property {string} V2T2C1A1 * @readonly * @static * @member WOZLLA.renderer.IShaderProgram */ var V2T2C1A1: string; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.MaterialManager * @extends WOZLLA.renderer.IMaterialManager */ class MaterialManager implements IMaterialManager { _materialMap: {}; constructor(); createMaterial(id: string, shaderProgramId: string, blendType: number): IMaterial; getMaterial(id: string): IMaterial; deleteMaterial(material: IMaterial): void; clear(): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.ShaderProgram * @extends WOZLLA.renderer.IShaderProgram */ class ShaderProgram implements IShaderProgram { id: any; vertexShader: any; fragmentShader: any; _id: any; _vertexShader: any; _fragmentShader: any; constructor(id: any, vertexShader: any, fragmentShader: any); useProgram(gl: any): void; syncUniforms(gl: any, uniforms: { projection: any; }): void; } } declare module WOZLLA.renderer.shader { /** * @class WOZLLA.renderer.shader.V2T2C1A1 */ class V2T2C1A1 extends ShaderProgram implements IShaderProgram { static VERTEX_SOURCE: string; static FRAGMENT_SOURCE: string; _locations: any; constructor(id: any, vertexShader: any, fragmentShader: any); useProgram(gl: any): void; syncUniforms(gl: any, uniforms: { projection: any; }): void; _initLocaitions(gl: any): void; _activate(gl: any): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.ShaderManager * @extends WOZLLA.renderer.IShaderManager */ class ShaderManager implements IShaderManager { _gl: any; _shaderMap: any; constructor(gl: any); getShaderProgram(id: any): IShaderProgram; createShaderProgram(vertexSource: string, fragmentSource: string, ShaderClass?: Function): IShaderProgram; deleteShaderProgram(shaderProgram: IShaderProgram): void; clear(): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.Texture * @extends WOZLLA.renderer.ITexture */ class Texture implements ITexture { id: any; descriptor: ITextureDescriptor; _id: any; _descriptor: ITextureDescriptor; constructor(id: any, descriptor: ITextureDescriptor); bind(gl: any): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.TextureManager * @extends WOZLLA.renderer.ITextureManager */ class TextureManager implements ITextureManager { _gl: any; _textureMap: any; constructor(gl: any); getTexture(id: any): any; generateTexture(descriptor: ITextureDescriptor, textureId?: any): ITexture; updateTexture(texture: ITexture): void; deleteTexture(texture: ITexture): void; clear(): void; } } declare module WOZLLA.renderer { class Renderer implements IRenderer { static MAX_QUAD_SIZE: number; layerManager: ILayerManager; materialManager: IMaterialManager; shaderManager: IShaderManager; textureManager: ITextureManager; gl: any; viewport: any; _gl: any; _viewport: any; _layerManager: LayerManager; _materialManager: IMaterialManager; _shaderManager: IShaderManager; _textureManager: ITextureManager; _commandQueueMap: any; _blendModes: any; _usingMaterial: IMaterial; _usingTexture: ITexture; _uniforms: any; private _quadBatch; constructor(gl: any, viewport: any); addCommand(command: IRenderCommand): void; render(): void; flush(): void; _clearCommands(): void; _eachCommand(func: Function): void; } } declare module WOZLLA { /** * a director hold this instances: <br/> * 1. {@link WOZLLA.Stage} <br/> * 2. {@link WOZLLA.renderer.IRenderer} <br/> * 3. {@link WOZLLA.Scheduler} <br/> * 4. {@link WOZLLA.Touch} <br/> * 5. {@link WOZLLA.assets.AssetLoader} <br/> * <br/> * <br/> * and also responsable to setup engine and control main loop. * * @class WOZLLA.Director * @singleton */ class Director { private static instance; static getInstance(): Director; /** * get the canvas element * @property {any} view */ view: any; /** * get the touch instance * @property {WOZLLA.Touch} touch * @readonly */ touch: Touch; /** * get the stage instance * @property {WOZLLA.Stage} stage * @readonly */ stage: Stage; /** * get the scheduler instance * @property {WOZLLA.Scheduler} scheduler * @readonly */ scheduler: Scheduler; /** * get the renderer instance * @property {WOZLLA.renderer.IRenderer} renderer * @readonly */ renderer: renderer.IRenderer; /** * get the asset loader instance * @property {WOZLLA.assets.AssetLoader} assetLoader * @readonly */ assetLoader: assets.AssetLoader; /** * get the root instance of RectTransform * @returns {WOZLLA.RectTransform} viewRectTransform */ viewRectTransform: RectTransform; private _runing; private _paused; private _timeScale; private _view; private _touch; private _stage; private _renderer; private _scheduler; private _assetLoader; constructor(view: any, options?: any); /** * start main loop */ start(): void; /** * stop main loop */ stop(): void; /** * run one frame * @param {number} [timeScale=1] */ runStep(timeScale?: number): void; } } declare module WOZLLA.assets { /** * internal class * @class WOZLLA.assets.GLTextureAsset * @extends WOZLLA.assets.Asset * @abstract */ class GLTextureAsset extends Asset { glTexture: renderer.ITexture; _glTexture: renderer.ITexture; _generateTexture(image: HTMLImageElement): void; _generatePVRTexture(pvrSource: any): void; } class HTMLImageDescriptor implements renderer.ITextureDescriptor { width: number; height: number; source: any; textureFormat: renderer.TextureFormat; pixelFormat: renderer.PixelFormat; _source: any; _textureFormat: renderer.TextureFormat; _pixelFormat: renderer.PixelFormat; constructor(source: any); } class PVRDescriptor implements renderer.ITextureDescriptor { width: number; height: number; source: any; textureFormat: renderer.TextureFormat; pixelFormat: renderer.PixelFormat; _source: any; _textureFormat: renderer.TextureFormat; _pixelFormat: renderer.PixelFormat; constructor(source: any, pixelFormat: renderer.PixelFormat); } } declare module WOZLLA.utils { /** * @class WOZLLA.utils.Ajax */ class Ajax { /** * internal ajax error code when timeout * @property ERROR_TIMEOUT * @static * @readonly */ static ERROR_TIMEOUT: number; /** * internal ajax error code when server error * @property ERROR_SERVER * @static * @readonly */ static ERROR_SERVER: number; /** * send a request with options * @param {object} options * @param {boolean} options.async * @param {string} options.method GET/POST * @param {string} options.contentType text/json/xml * @param {string} options.responseType text/plain,text/javascript,text/css,arraybuffer * @param {number} [options.timeout=30000] * @param {function} options.success call when ajax request successfully * @param {function} options.error call when ajax request error */ static request(options?: any): void; } } declare module WOZLLA.assets { class JSONAsset extends Asset { _data: any; cloneData(): any; load(onSuccess: () => any, onError: (error: any) => any): void; unload(): void; } } declare module WOZLLA.assets.proxy { class AssetProxy { protected proxyTarget: IProxyTarget; protected asset: Asset; protected newAssetSrc: string; protected loading: boolean; constructor(proxyTarget: IProxyTarget); setAssetSrc(src: string): void; loadAsset(callback: Function): void; onDestroy(): void; protected checkDirty(): boolean; protected doLoad(callback: (asset: Asset) => void): void; } interface IProxyTarget { onAssetLoaded(asset: Asset): any; } } declare module WOZLLA.assets.proxy { class SpriteAtlasProxy extends AssetProxy { getSprite(spriteName: any): Sprite; getFrameLength(): number; protected doLoad(callback: (asset: Asset) => void): void; } } declare module WOZLLA.assets { /** * an sprite is a part of a sprite atlas * @class WOZLLA.assets.Sprite * <br/> * see also: <br/> * {@link WOZLLA.assets.SpriteAtlas}<br/> */ class Sprite { /** * get the sprite atlas of this sprite belongs to * @property {WOZLLA.assets.SpriteAtlas} spriteAltas * @readonly */ spriteAtlas: SpriteAtlas; /** * get frame info * @property {any} frame * @readonly */ frame: any; /** * get sprite name * @property {string} name * @readonly */ name: string; _spriteAtlas: SpriteAtlas; _frame: any; _name: string; /** * new a sprite * @method constructor * @param spriteAtlas * @param frame * @param name */ constructor(spriteAtlas: SpriteAtlas, frame: any, name?: any); } } declare module WOZLLA.assets { /** * a sprite atlas contains many {@link WOZLLA.assets.Sprite}. * it's recommended to user {@link WOZLLA.assets.AssetLoader} to load SpriteAtlas. * @class WOZLLA.assets.SpriteAtlas * @extends WOZLLA.assets.GLTextureAsset * <br/> * see also: * {@link WOZLLA.assets.Sprite} * {@link WOZLLA.assets.AssetLoader} */ class SpriteAtlas extends GLTextureAsset { /** * @property {string} imageSrc * @readonly */ imageSrc: string; /** * an file url descript sprite atlas infos. * @property {string} metaSrc * @readonly */ metaSrc: string; /** * @property {any} sourceImage * @readonly */ sourceImage: any; /** * @property {any} spriteData * @readonly */ spriteData: any; _imageSrc: string; _metaSrc: string; _sourceImage: any; _entireSprite: Sprite; _spriteData: any; _spriteCache: any; _frameLengthCache: number; getFrameLength(): number; /** * get sprite by name * @param name * @returns {WOZLLA.assets.Sprite} */ getSprite(name?: any): Sprite; /** * load this asset * @param onSuccess * @param onError */ load(onSuccess: () => any, onError: (error: any) => any): void; _loadImage(callback: (error: string, image?: any) => any): void; _loadSpriteAtlas(callback: (error: string, image?: any, spriteData?: any) => any): void; } } declare module WOZLLA.math { /** * @class WOZLLA.math.Rectangle * a utils class for rectangle, provider some math methods */ class Rectangle { x: number; y: number; width: number; height: number; /** * @property {number} left x * @readonly */ left: number; /** * @property {number} right x+width * @readonly */ right: number; /** * @property {number} top y * @readonly */ top: number; /** * @property {number} bottom y+height * @readonly */ bottom: number; constructor(x: number, y: number, width: number, height: number); /** * @method containsXY * @param x * @param y * @returns {boolean} */ containsXY(x: number, y: number): boolean; /** * get simple description of this object * @returns {string} */ toString(): string; } } declare module WOZLLA.component { /** * @class WOZLLA.component.CircleCollider */ class CircleCollider extends Collider { region: math.Circle; collideXY(localX: number, localY: number): boolean; collide(collider: Collider): boolean; } } declare module WOZLLA.component { /** * @class WOZLLA.component.MaskCollider */ class MaskCollider extends Collider { collideXY(localX: number, localY: number): boolean; collide(collider: Collider): boolean; } } declare module WOZLLA.component { /** * @class WOZLLA.component.RectCollider */ class RectCollider extends Collider { static fromSpriteRenderer(spriteRenderer: SpriteRenderer): RectCollider; region: math.Rectangle; collideXY(localX: number, localY: number): boolean; collide(collider: Collider): boolean; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.RenderCommandBase * @abstract */ class RenderCommandBase implements IRenderCommand { globalZ: number; layer: string; _globalZ: number; _layer: string; _addIndex: number; constructor(globalZ: number, layer: string); } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.CustomCommand * @extends WOZLLA.renderer.RenderCommandBase */ class CustomCommand extends RenderCommandBase { constructor(globalZ: number, layer: string); execute(renderer: IRenderer): void; } } declare module WOZLLA { /** * Base class for all mask, mask is based on webgl stencil. * @class WOZLLA.Mask * @extends WOZLLA.Component * @abstract */ class Mask extends Component { reverse: boolean; _startGlobalZ: number; _endGlobalZ: number; _maskLayer: string; /** * set mask range, mask range is effect on globalZ of render commmand * @param start * @param end * @param layer */ setMaskRange(start: number, end: number, layer?: string): void; /** * render this mask * @param renderer * @param flags */ render(renderer: renderer.IRenderer, flags: number): void; /** * do render mask graphics * @param renderer * @param flags */ protected renderMask(renderer: renderer.IRenderer, flags: number): void; } } declare module WOZLLA { /** * Abstract base class for Renderer component * @class WOZLLA.Renderer * @abstract */ class Renderer extends Component { /** * render this object * @param renderer * @param flags */ render(renderer: renderer.IRenderer, flags: number): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.QuadType */ class QuadType { size: number; strade: any; vertexIndex: any; texCoordIndex: any; alphaIndex: any; colorIndex: any; _info: any; constructor(info: any); } /** * @class WOZLLA.renderer.Quad */ class Quad { static V2T2C1A1: QuadType; storage: number[]; count: number; type: QuadType; renderOffset: number; renderCount: number; _storage: number[]; _count: number; _type: QuadType; _renderOffset: number; _renderCount: number; constructor(count: number, type?: QuadType); setRenderRange(offset: number, count: number): void; setVertices(x1: any, y1: any, x2: any, y2: any, x3: any, y3: any, x4: any, y4: any, offset?: number): void; setTexCoords(x1: any, y1: any, x2: any, y2: any, x3: any, y3: any, x4: any, y4: any, offset?: number): void; setAlpha(alpha: number, offset?: number): void; setColor(color: any, offset?: number): void; } } declare module WOZLLA.utils { interface Poolable { isPoolable: boolean; release(): any; } class ObjectPool<T extends Poolable> { _minCount: any; _factory: any; _pool: T[]; constructor(minCount: number, factory: () => T); retain(): T; release(obj: T): void; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.QuadCommand * @extends WOZLLA.renderer.RenderCommandBase */ class QuadCommand extends RenderCommandBase implements utils.Poolable { static init(globalZ: number, layer: string, texture: ITexture, materialId: string, quad: Quad): QuadCommand; isPoolable: boolean; texture: ITexture; materialId: string; quad: Quad; _texture: ITexture; _materialId: string; _quad: Quad; constructor(globalZ: number, layer: string); initWith(globalZ: number, layer: string, texture: ITexture, materialId: string, quad: any): void; release(): void; } } declare module WOZLLA.component { /** * @class WOZLLA.component.QuadRenderer * @abstract */ class QuadRenderer extends Renderer { _quad: renderer.Quad; _quadLayer: string; _quadMaterialId: string; _quadGlobalZ: number; _quadAlpha: number; _quadColor: number; _quadVertexDirty: boolean; _quadAlphaDirty: boolean; _quadColorDirty: boolean; _texture: renderer.ITexture; _textureOffset: any; _textureFrame: any; _textureUVS: any; _textureUpdated: boolean; setQuadRenderRange(offset: number, count: number): void; setQuadGlobalZ(globalZ: number): void; setQuadLayer(layer: string): void; setQuadMaterialId(materialId: string): void; setQuadAlpha(alpha: number): void; setQuadColor(color: number): void; setTexture(texture: renderer.ITexture): void; setTextureFrame(frame: any): void; setTextureOffset(offset: any): void; init(): void; render(renderer: renderer.IRenderer, flags: number): void; _initQuad(): void; _getTextureFrame(): any; _getTextureOffset(): any; _getTextureUVS(): any; _updateQuad(quadIndex?: number): void; _updateQuadVertices(quadIndex?: number): void; _updateQuadVerticesByArgs(uvs: any, frame: any, offset: any, matrix: any, quadIndex?: number): void; _clearQuadVertices(quadIndex?: number): void; _updateQuadAlpha(quadIndex?: number): void; _updateQuadColor(quadIndex?: number): void; } } declare module WOZLLA.component { /** * @class WOZLLA.component.RectMask */ class RectMask extends Mask { region: math.Rectangle; _helperGameObject: GameObject; _region: math.Rectangle; _maskQuadRenderer: any; protected renderMask(renderer: renderer.IRenderer, flags: number): void; private _initMaskQuadRenderer(renderer); } } declare module WOZLLA.component { class CanvasRenderer extends QuadRenderer { canvasSize: math.Size; canvasWidth: number; canvasHeight: number; _canvas: any; _context: any; _canvasSize: math.Size; _glTexture: any; _graphicsDirty: boolean; _sizeDirty: boolean; destroy(): void; draw(context: any): void; render(renderer: renderer.IRenderer, flags: number): void; clearCanvas(): void; protected initCanvas(): void; protected updateCanvas(): void; protected destroyCanvas(): void; protected generateCanvasTexture(renderer: renderer.IRenderer): void; } } declare module WOZLLA.component { class PrimitiveRenderer extends CanvasRenderer { primitiveStyle: PrimitiveStyle; _primitiveStyle: PrimitiveStyle; render(renderer: renderer.IRenderer, flags: number): void; draw(context: any): void; protected applyPrimitiveStyle(context: any): void; protected drawPrimitive(context: any): void; protected measurePrimitiveSize(): any; } class PrimitiveStyle { dirty: boolean; stroke: boolean; strokeColor: string; strokeWidth: number; fill: boolean; fillColor: string; _stroke: boolean; _fill: boolean; _strokeColor: string; _strokeWidth: number; _fillColor: string; } } declare module WOZLLA.component { class CircleRenderer extends PrimitiveRenderer { circle: math.Circle; _circle: math.Circle; drawPrimitive(context: any): void; protected measurePrimitiveSize(): any; protected generateCanvasTexture(renderer: renderer.IRenderer): void; } } declare module WOZLLA.component { class RectRenderer extends PrimitiveRenderer { rect: math.Rectangle; _rect: math.Rectangle; drawPrimitive(context: any): void; protected measurePrimitiveSize(): any; protected generateCanvasTexture(renderer: renderer.IRenderer): void; } } declare module WOZLLA.component { class PropertyConverter { static array2rect(arr: number[]): math.Rectangle; static array2circle(arr: number[]): math.Circle; static json2TextStyle(json: any): TextStyle; static array2Padding(arr: number[]): layout.Padding; static array2Margin(arr: number[]): layout.Margin; } } declare module WOZLLA.component { /** * @class WOZLLA.component.SpriteRenderer */ class SpriteRenderer extends QuadRenderer implements assets.proxy.IProxyTarget { color: number; alpha: number; materialId: string; renderLayer: string; renderOrder: number; sprite: assets.Sprite; spriteOffset: any; imageSrc: string; spriteAtlasSrc: string; spriteName: string; _spriteProxy: assets.proxy.SpriteAtlasProxy; _sprite: assets.Sprite; _spriteAtlasSrc: string; _spriteName: string; constructor(); destroy(): void; onAssetLoaded(asset: assets.Asset): void; loadAssets(callback: Function): void; } } declare module WOZLLA.component { class AnimationRenderer extends SpriteRenderer { static MODE_LOOP: string; static MODE_NONLOOP: string; autoOffset: boolean; frameNum: number; duration: number; playMode: string; frameLength: number; _frameNum: number; _frameNumDirty: boolean; _autoOffset: boolean; _playMode: string; _playing: boolean; _duration: number; _playTween: utils.Tween; play(duration?: number): void; pause(): void; resume(): void; stop(): void; render(renderer: renderer.IRenderer, flags: number): void; protected updateAnimationFrame(): void; } } declare module WOZLLA.component { /** * @class WOZLLA.component.NinePatchRenderer */ class NinePatchRenderer extends SpriteRenderer { renderRegion: math.Rectangle; patch: math.Rectangle; _patch: math.Rectangle; _renderRegion: math.Rectangle; _initQuad(): void; _updateNinePatchQuads(): void; _updateNinePatchQuadVertices(): void; _updateNinePatchQuadAlpha(): void; _updateNinePatchQuadColor(): void; render(renderer: renderer.IRenderer, flags: number): void; } } declare module WOZLLA.component { class TextRenderer extends CanvasRenderer { static measureText(style: TextStyle, text: string): { width: any; height: any; }; text: string; textStyle: TextStyle; textWidth: number; textHeight: number; _textDirty: boolean; _text: string; _textStyle: TextStyle; render(renderer: renderer.IRenderer, flags: number): void; draw(context: any): void; protected drawText(context: any, measuredWidth: any, measuredHeight: any): void; protected measureTextSize(): any; protected generateCanvasTexture(renderer: renderer.IRenderer): void; } class TextStyle { static START: string; static CENTER: string; static END: string; static TOP: string; static MIDDLE: string; static BOTTOM: string; dirty: boolean; font: string; color: string; shadow: boolean; shadowColor: string; shadowOffsetX: number; shadowOffsetY: number; stroke: boolean; strokeColor: string; strokeWidth: number; align: string; baseline: string; _font: string; _color: string; _shadow: boolean; _shadowColor: string; _shadowOffsetX: number; _shadowOffsetY: number; _stroke: boolean; _strokeColor: string; _strokeWidth: number; _align: string; _baseline: string; } } declare module WOZLLA { /** * Abstract base class for all behaviours, the {@link WOZLLA.Behaviour#update} function would be call * by WOZLLA engine every frame when the gameObject is actived and the property enabled of this behaviour is true * @class WOZLLA.Behaviour * @extends WOZLLA.Component * @abstract */ class Behaviour extends Component { /** * enabled or disabled this behaviour * @property {boolean} [enabled=true] */ enabled: boolean; /** * call by Engine every frame * @method update */ update(): void; } } declare module WOZLLA { /** * internal class * @class WOZLLA.CoreEvent * @extends WOZLLA.event.Event */ class CoreEvent extends event.Event { /** * new a CoreEvent * @method constructor * @param type * @param bubbles * @param data * @param canStopBubbles */ constructor(type: string, bubbles?: boolean, data?: any, canStopBubbles?: boolean); } } declare module WOZLLA.jsonx { class JSONXBuilder { static Factory: Function; static create(): JSONXBuilder; private src; private data; private err; private root; private newCallback; private doLoad; private doInit; private loadCallback; private async; private uuidMap; getByUUID(uuid: any): any; setSync(): void; instantiateWithSrc(src: any, callback?: (root: GameObject, done: Function) => void): JSONXBuilder; instantiateWithJSON(data: any, callback?: (root: GameObject, done: Function) => void): JSONXBuilder; load(callback?: (root: GameObject, done: Function) => void): JSONXBuilder; init(): JSONXBuilder; build(callback: (error: any, root: GameObject) => void): void; protected _checkError(callback: (error: any, root: GameObject) => void): boolean; protected _loadJSONData(callback: Function): void; protected _newGameObjectTree(callback: Function): void; protected _newGameObject(data: any, callback: (gameObj: GameObject) => void): void; protected _newReferenceObject(data: any, callback: (gameObj: GameObject) => void): void; protected _newComponent(compData: any, gameObj: GameObject): Component; protected _applyComponentProperties(component: any, properties: any, compData: any): void; protected _loadAssets(callback: Function): void; protected _init(): void; } } declare module WOZLLA.layout { class LayoutBase extends Behaviour { private _layoutRequired; init(): void; destroy(): void; doLayout(): void; requestLayout(): void; update(): void; protected onChildAdd(e: any): void; protected onChildRemove(e: any): void; } } declare module WOZLLA.math { /** * @class WOZLLA.math.Size * a util class contains width and height properties */ class Size { width: number; height: number; /** * @method constructor * create a new instance of Size * @member WOZLLA.math.Size * @param {number} width * @param {number} height */ constructor(width: number, height: number); /** * get simple description of this object * @returns {string} */ toString(): string; } } declare module WOZLLA.layout { class Grid extends LayoutBase { listRequiredComponents(): Function[]; padding: Padding; itemMargin: Margin; _padding: Padding; _itemMargin: Margin; doLayout(): void; protected measureChildSize(child: GameObject, idx: number, size: math.Size): void; } } declare module WOZLLA.layout { class Margin { top: number; left: number; bottom: number; right: number; constructor(top: number, left: number, bottom: number, right: number); equals(padding: Padding): boolean; } } declare module WOZLLA.layout { class Padding { top: number; left: number; bottom: number; right: number; constructor(top: number, left: number, bottom: number, right: number); equals(padding: Padding): boolean; } } declare module WOZLLA.layout { class VBox extends LayoutBase { padding: Padding; itemMargin: number; _padding: Padding; _itemMargin: number; doLayout(): void; protected measureChildHeight(child: GameObject, idx: number): number; } } declare module WOZLLA.math { /** * @class WOZLLA.math.Circle * a util class for circle */ class Circle { centerX: number; centerY: number; radius: number; constructor(centerX: number, centerY: number, radius: number); /** * @method containsXY * @param x * @param y * @returns {boolean} */ containsXY(x: number, y: number): boolean; /** * get simple description of this object * @returns {string} */ toString(): string; } } declare module WOZLLA.math { module MathUtils { function rectIntersect(a: any, b: any): boolean; function rectIntersect2(ax: any, ay: any, aw: any, ah: any, bx: any, by: any, bw: any, bh: any): boolean; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.IMaterialManager * @abstract */ interface IMaterialManager { createMaterial(id: string, shaderProgramId: string, blendType: number): IMaterial; getMaterial(id: string): IMaterial; deleteMaterial(material: IMaterial): void; clear(): void; } module IMaterialManager { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.IMaterialManager */ var DOC: string; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.IRenderCommand * @abstract */ interface IRenderCommand { globalZ: number; layer: string; _addIndex: number; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.IShaderManager * @abstract */ interface IShaderManager { createShaderProgram(vertexSource: string, fragmentSource: string, ShaderClass: Function): IShaderProgram; getShaderProgram(id: any): IShaderProgram; deleteShaderProgram(shaderProgram: IShaderProgram): void; clear(): void; } module IShaderManager { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.IShaderManager */ var DOC: string; } } declare module WOZLLA.renderer { /** * @enum WOZLLA.renderer.TextureFormat */ enum TextureFormat { /** @property {number} [PNG] */ PNG = 0, /** @property {number} [JPEG] */ JPEG = 1, /** @property {number} [PVR] */ PVR = 2, } /** * @enum WOZLLA.renderer.PixelFormat */ enum PixelFormat { /** @property {number} [RPGA8888] */ RGBA8888 = 0, /** @property {number} [RGBA4444] */ RGBA4444 = 1, /** @property {number} [RGB888] */ RGB888 = 2, /** @property {number} [RGB565] */ RGB565 = 3, /** @property {number} [PVRTC4] */ PVRTC4 = 4, /** @property {number} [PVRTC2] */ PVRTC2 = 5, } /** * @class WOZLLA.renderer.ITextureDescriptor * @abstract */ interface ITextureDescriptor { width: number; height: number; textureFormat: TextureFormat; pixelFormat: PixelFormat; source: any; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.ITextureManager * @abstract */ interface ITextureManager { generateTexture(descriptor: ITextureDescriptor): ITexture; updateTexture(texture: ITexture): void; deleteTexture(texture: ITexture): void; getTexture(id: any): ITexture; clear(): void; } module ITextureManager { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.ITextureManager */ var DOC: string; } } declare module WOZLLA.renderer { /** * @class WOZLLA.renderer.WebGLExtension */ class WebGLExtension { static VENDOR_WEBKIT: string; static PVRTC: string; static COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: number; static COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: number; static getExtension(gl: any, extName: any, doThrow?: boolean): any; } } declare module WOZLLA.utils { class StateMachine extends event.EventDispatcher { static INIT: string; static CHANGE: string; _defaultState: string; _currentState: string; _currentTransition: ITransition; _stateConfig: any; defineState(name: string, isDefault?: boolean): void; getStateData(state: string, key: string): any; setStateData(state: string, key: string, data: any): void; defineTransition(fromState: string, toState: string, transition: ITransition): void; init(): void; getCurrentState(): string; changeState(state: string): void; } class StateEventData { state: string; constructor(state: string); } interface ITransition { reset(): any; cancel(): any; execute(fromState: string, toState: string, onComplete: Function): any; } class EmptyTransition implements ITransition { private static instance; static getInstance(): EmptyTransition; _canceled: boolean; reset(): void; cancel(): void; execute(fromState: string, toState: string, onComplete: Function): void; } } declare module WOZLLA.ui { /** * @class WOZLLA.ui.StateWidget * @protected */ class StateWidget extends component.SpriteRenderer { _stateMachine: utils.StateMachine; constructor(); init(): void; protected initStates(): void; protected getStateSpriteName(state: string): string; protected setStateSpriteName(state: string, spriteName: string): void; protected onStateChange(e: any): void; } } declare module WOZLLA.ui { /** * @class WOZLLA.ui.Button */ class Button extends StateWidget { static STATE_NORMAL: string; static STATE_DISABLED: string; static STATE_PRESSED: string; normalSpriteName: string; disabledSpriteName: string; pressedSpriteName: string; init(): void; destroy(): void; isEnabled(): boolean; setEnabled(enabled?: boolean): void; protected initStates(): void; protected onTouch(e: any): void; protected onRelease(e: any): void; protected onTap(e: any): void; } } declare module WOZLLA.ui { /** * @class WOZLLA.ui.CheckBox */ class CheckBox extends StateWidget { static STATE_UNCHECKED: string; static STATE_CHECKED: string; static STATE_DISABLED: string; uncheckedSpriteName: string; disabledSpriteName: string; checkedSpriteName: string; init(): void; destroy(): void; isEnabled(): boolean; setEnabled(enabled?: boolean): void; protected initStates(): void; protected onTap(e: any): void; } } declare module WOZLLA.utils { class Ease { static get(amount: any): Function; static getPowIn(pow: any): Function; static getPowOut(pow: any): Function; static getPowInOut(pow: any): Function; static quadIn: Function; static quadOut: Function; static quadInOut: Function; static cubicIn: Function; static cubicOut: Function; static cubicInOut: Function; static quartIn: Function; static quartOut: Function; static quartInOut: Function; static quintIn: Function; static quintOut: Function; static quintInOut: Function; static sineIn(t: any): number; static sineOut(t: any): number; static sineInOut(t: any): number; static getBackIn(amount: any): Function; static backIn: Function; static getBackOut(amount: any): Function; static backOut: Function; static getBackInOut(amount: any): Function; static backInOut: Function; static circIn(t: any): number; static circOut(t: any): number; static circInOut(t: any): number; static bounceIn(t: any): number; static bounceOut(t: any): number; static bounceInOut(t: any): number; static getElasticIn(amplitude: any, period: any): Function; static elasticIn: Function; static getElasticOut(amplitude: any, period: any): Function; static elasticOut: Function; static getElasticInOut(amplitude: any, period: any): Function; static elasticInOut: Function; static linear(t: any): any; static expoIn(time: any): number; static expoOut(time: any): number; static expoInOut(time: any): any; static keyMap: { 0: string; 1: string; 2: string; 3: string; 4: string; 5: string; 6: string; 7: string; 8: string; 9: string; 10: string; 11: string; 12: string; 13: string; 14: string; 15: string; 16: string; 17: string; 18: string; 19: string; 20: string; 21: string; 22: string; 23: string; 24: string; 25: string; 26: string; 27: string; 28: string; 29: string; 30: string; }; static getByKey(key: any): any; } } declare module WOZLLA.DragonBones { class SkeletonRenderer extends Renderer { skeletonSrc: string; textureSrc: string; armatureName: string; armature: dragonBones.Armature; _skeletonSrc: any; _textureSrc: any; _factory: any; _skeletonJSONAsset: any; _wTextureAtlas: any; _armatureName: string; _armature: dragonBones.Armature; _container: GameObject; init(): void; destroy(): void; render(renderer: renderer.IRenderer, flags: number): void; loadAssets(callback: Function): void; protected initArmature(): void; } } declare module WOZLLA.DragonBones { class WSlot extends dragonBones.Slot { private _display; constructor(); dispose(): void; /** @private */ _updateDisplay(value: any): void; /** @private */ _getDisplayIndex(): number; /** @private */ _addDisplayToContainer(container: any, index?: number): void; /** @private */ _removeDisplayFromContainer(): void; /** @private */ _updateTransform(): void; /** @private */ _updateDisplayVisible(value: boolean): void; /** @private */ _updateDisplayColor(aOffset: number, rOffset: number, gOffset: number, bOffset: number, aMultiplier: number, rMultiplier: number, gMultiplier: number, bMultiplier: number): void; /** @private */ _updateDisplayBlendMode(value: string): void; } } declare module WOZLLA.DragonBones { class WTextureAtlas extends assets.SpriteAtlas implements dragonBones.ITextureAtlas { name: string; dispose(): void; getRegion(subTextureName: string): dragonBones.Rectangle; _loadSpriteAtlas(callback: (error: string, image?: any, spriteData?: any) => any): void; _parseData(data: any): any; } } declare module WOZLLA.DragonBones { function setupWorldClock(): void; class WFactory extends dragonBones.BaseFactory { constructor(); /** @private */ _generateArmature(): dragonBones.Armature; /** @private */ _generateSlot(): dragonBones.Slot; /** @private */ _generateDisplay(textureAtlas: WTextureAtlas, fullName: string, pivotX: number, pivotY: number): any; } }
zzm2q/WOZLLA.js
src/renderer/IRenderCommand.ts
<filename>src/renderer/IRenderCommand.ts<gh_stars>0 module WOZLLA.renderer { /** * @class WOZLLA.renderer.IRenderCommand * @abstract */ export interface IRenderCommand { globalZ:number; layer:string; _addIndex:number; } }
zzm2q/WOZLLA.js
src/component/renderer/CanvasRenderer.ts
<gh_stars>0 /// <reference path="../../assets/GLTextureAsset.ts"/> /// <reference path="QuadRenderer.ts"/> module WOZLLA.component { export class CanvasRenderer extends QuadRenderer { get canvasSize():WOZLLA.math.Size { return this._canvasSize; } set canvasSize(value:WOZLLA.math.Size) { this._canvasSize = value; this._sizeDirty = true; } get canvasWidth():number { return this._canvasSize.width; } set canvasWidth(value:number) { this._canvasSize.width = value; this._sizeDirty = true; } get canvasHeight():number { return this._canvasSize.height; } set canvasHeight(value:number) { this._canvasSize.height = value; this._sizeDirty = true; } _canvas; _context; _canvasSize:WOZLLA.math.Size = new WOZLLA.math.Size(0, 0); _glTexture; _graphicsDirty:boolean = true; _sizeDirty:boolean = true; destroy():void { this.destroyCanvas(); super.destroy(); } draw(context):void { throw new Error('abstract method'); } render(renderer: renderer.IRenderer, flags: number): void { if(!this._canvas) { this.initCanvas(); } if(!this._canvas) { return; } if(this._sizeDirty) { this.updateCanvas(); } if(this._graphicsDirty) { this.clearCanvas(); this.draw(this._context); this._graphicsDirty = false; this.generateCanvasTexture(renderer); } if(this._glTexture) { super.render(renderer, flags); } } clearCanvas() { this._context.clearRect(0, 0, this._canvasSize.width, this._canvasSize.height); } protected initCanvas() { if(this._canvasSize.width <= 0 || this._canvasSize.height <= 0) { return; } this._canvas = document.createElement('canvas'); this._canvas.width = this._canvasSize.width; this._canvas.height = this._canvasSize.height; this._context = this._canvas.getContext('2d'); this._sizeDirty = false; this._graphicsDirty = true; } protected updateCanvas() { if(this._canvasSize.width <= 0 || this._canvasSize.height <= 0) { this.destroyCanvas(); this._graphicsDirty = true; } this._canvas.width = this._canvasSize.width; this._canvas.height = this._canvasSize.height; this._sizeDirty = false; this._graphicsDirty = true; } protected destroyCanvas() { this._canvas && this._canvas.dispose && this._canvas.dispose(); this._context && this._context.dispose && this._context.dispose(); this._canvas = this._context = null; } protected generateCanvasTexture(renderer:renderer.IRenderer):void { if(!this._glTexture) { this._glTexture = renderer.textureManager.generateTexture( new WOZLLA.assets.HTMLImageDescriptor(this._canvas)); this.setTexture(this._glTexture); } else { renderer.textureManager.updateTexture(this._glTexture); this.setTexture(this._glTexture); } } } }
zzm2q/WOZLLA.js
src/assets/proxy/SpriteAtlasProxy.ts
module WOZLLA.assets.proxy { export class SpriteAtlasProxy extends AssetProxy { getSprite(spriteName:any):Sprite { if(this.asset) { return (<SpriteAtlas>this.asset).getSprite(spriteName); } return null; } getFrameLength():number { if(!this.asset) { return 0; } return (<SpriteAtlas>this.asset).getFrameLength(); } protected doLoad(callback:(asset:Asset) => void) { var src = this.newAssetSrc; if(!src) { callback(null); return; } AssetLoader.getInstance().load(src, SpriteAtlas, function() { callback(AssetLoader.getInstance().getAsset(src)); }); } } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/View.ts
///<reference path='../../../src/core/Component.ts' /> module WOZLLA.PureMVC { export class View extends WOZLLA.Component { init():void { this.onInit(); super.init(); } destroy():void { this.onDestroy(); super.destroy(); } onCreate() {} onInit() {} onDestroy() {} } }
zzm2q/WOZLLA.js
src/math/Size.ts
module WOZLLA.math { /** * @class WOZLLA.math.Size * a util class contains width and height properties */ export class Size { width: number; height: number; /** * @method constructor * create a new instance of Size * @member WOZLLA.math.Size * @param {number} width * @param {number} height */ constructor (width: number, height: number) { /** * @property {number} width * get or set width of this object * @member WOZLLA.math.Size */ this.width = width; /** * @property {number} height * get or set height of this object * @member WOZLLA.math.Size */ this.height = height; } /** * get simple description of this object * @returns {string} */ toString() { return 'Size[' + this.width + ',' + this.height + ']'; } } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/ListView.ts
///<reference path='AdapterView.ts'/> ///<reference path='ListAdapter.ts'/> module WOZLLA.PureMVC { export class ListView extends AdapterView { public static DEFAUL_ITEM_MODEL_KEY = 'item'; get itemViewSrc():string { return this._itemViewSrc; } set itemViewSrc(src:string) { this._itemViewSrc = src; } _itemViewSrc:string; _itemViews:SimpleView[]= []; addItemViewAt(itemView:SimpleView, idx:number) { this._itemViews.splice(idx, 0, itemView); itemView.gameObject.z = idx; this.gameObject.addChild(itemView.gameObject); } removeItemViewAt(idx:number) { var itemView:SimpleView = this._itemViews[idx]; this._itemViews.splice(idx, 1); itemView.gameObject.destroy(); itemView.gameObject.removeMe(); } clearItemViews() { this.gameObject.eachChild((child) => { child.destroy(); child.removeMe(); }); this._itemViews.length = 0; } addItemView(itemView:SimpleView) { this.addItemViewAt(itemView, this._itemViews.length); } getItemViewAt(idx:number):SimpleView { return this._itemViews[idx]; } removeItemView(itemView:SimpleView) { var idx = this.indexOf(itemView); this.removeItemViewAt(idx); } indexOf(itemView:SimpleView) { return this._itemViews.indexOf(itemView); } } WOZLLA.Component.register(ListView, { name: 'MVC.ListView', properties: [ Component.extendConfig(AdapterView), { name: 'itemViewSrc', type: 'string' }] }); }
zzm2q/WOZLLA.js
tests/renderer/LayerManagerTest.ts
/// <reference path="../../libs/WOZLLA.d.ts"/> /// <reference path="../../libs/jasmine.d.ts"/> /// <reference path="../data.ts"/> module WOZLLA.renderer { describe('WOZLLA.renderer', function() { describe("LayerManagerTest", function () { it("define and undefine layer", function () { var layerManager = new LayerManager(); layerManager.define('layer1', 0); expect(layerManager.getZIndex('layer1')).toBe(0); layerManager.undefine('layer1'); expect(layerManager.getZIndex('layer1')).toBeUndefined(); }); it("layer order", function() { var layerManager = new LayerManager(); layerManager.define('layer1', 0); layerManager.define('layer2', 1); expect(layerManager.getZIndex('layer1')).toBe(0); expect(layerManager.getZIndex('layer2')).toBe(1); var layers = layerManager.getSortedLayers(); expect(layers.indexOf('layer1') < layers.indexOf('layer2')).toBeTruthy(); }); }); }); }
zzm2q/WOZLLA.js
src/renderer/IMaterial.ts
<filename>src/renderer/IMaterial.ts module WOZLLA.renderer { /** * @class WOZLLA.renderer.IMaterial * @abstract */ export interface IMaterial { id:string; shaderProgramId:string; blendType:number; equals(other:IMaterial):boolean; } export module IMaterial { /** * default material key of built-in * @property {string} DEFAULT * @readonly * @static * @member WOZLLA.renderer.IMaterial */ export var DEFAULT = 'Builtin_default'; } }
zzm2q/WOZLLA.js
src/renderer/WebGLUtils.ts
module WOZLLA.renderer { function applyProperties(target, source) { for(var i in source) { if(typeof target[i] === 'undefined') { target[i] = source[i]; } } return target; } /** * @class WOZLLA.renderer.WebGLUtils * @abstract */ export class WebGLUtils { public static getGLContext(canvas, options?) { var gl; options = applyProperties(options || {}, { alpha: true, antialias: true, premultipliedAlpha: false, stencil:true }); try { gl = canvas.getContext('experimental-webgl', options); } catch (e) { try { gl = canvas.getContext('webgl', options); } catch (e2) {} } return gl; } public static compileShader(gl, shaderType, shaderSrc) { var src = shaderSrc; var shader = gl.createShader(shaderType); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(shader)); return null; } return shader; } public static compileProgram(gl, vertexSrc, fragmentSrc) { var vertexShader = WebGLUtils.compileShader(gl, gl.VERTEX_SHADER, vertexSrc); var fragmentShader = WebGLUtils.compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { console.log("Could not initialise program"); } return { program: shaderProgram, vertexShader: vertexShader, fragmentShader: fragmentShader }; } } }
zzm2q/WOZLLA.js
src/event/EventDispatcher.ts
/// <reference path="Event.ts"/> module WOZLLA.event { var SCOPE = '_EventDispatcher_scope'; class ListenerList { _listeners = []; add(listener:Function) { this._listeners.push(listener); } remove(listener:Function, scope?:any) { var i, len = this._listeners.length; var l; for(i=0; i<len; i++) { l = this._listeners[i]; if(l === listener) { if(!scope || scope === l[SCOPE]) { this._listeners.splice(i, 1); } return true; } } return false; } removeAt(idx):any { return this._listeners.splice(idx, 1); } get(idx) { return this._listeners[idx]; } length() { return this._listeners.length; } clear() { this._listeners.length = 0; } } /** * @class WOZLLA.event.EventDispatcher * Base class for bubblable event system * */ export class EventDispatcher { private _captureDict = {}; private _bubbleDict = {}; private _bubbleParent:EventDispatcher; /** * @method setBubbleParent * set bubble parent of this dispatcher * @param {WOZLLA.event.EventDispatcher} bubbleParent */ setBubbleParent(bubbleParent:EventDispatcher) { this._bubbleParent = bubbleParent; } /** * @method hasListener * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ hasListener(type:string, useCapture:boolean=false):boolean { return this._getListenerList(type, useCapture).length() > 0; } /** * @method getListenerCount * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. * @returns {number} */ getListenerCount(type:string, useCapture:boolean):number { return this._getListenerList(type, useCapture).length() } /** * @method addListener * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ addListener(type:string, listener:Function, useCapture:boolean=false) { this._getListenerList(type, useCapture).add(listener); } addListenerScope(type:string, listener:Function, scope:any, useCapture:boolean=false) { listener[SCOPE] = scope; this.addListener(type, listener, useCapture); } /** * @method removeListener * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ removeListener(type:string, listener:Function, useCapture:boolean=false):boolean { return this._getListenerList(type, useCapture).remove(listener); } removeListenerScope(type:string, listener:Function, scope:any , userCapture:boolean=false):boolean { return this._getListenerList(type, userCapture).remove(listener, scope); } /** * @method clearListeners * @param {string} type * @param {boolean} useCapture true to check capture phase, false to check bubble and target phases. */ clearListeners(type:string, useCapture:boolean) { this._getListenerList(type, useCapture).clear(); } /** * @method clearAllListeners * clear all listeners */ clearAllListeners() { this._captureDict = {}; this._bubbleDict = {}; } /** * @method dispatch an event * @param {WOZLLA.event.Event} event */ dispatchEvent(event:Event) { var i, len, ancients, ancient; event._target = this; if(!event.bubbles) { this._dispatchEventInPhase(event, EventPhase.TARGET); return; } ancients = this._getAncients(); len = ancients.length; for(i=len-1; i>=0; i--) { ancient = ancients[i]; if(ancient._dispatchEventInPhase(event, EventPhase.CAPTURE)) { return; } } if(this._dispatchEventInPhase(event, EventPhase.CAPTURE)) { return; } if(this._dispatchEventInPhase(event, EventPhase.TARGET)) { return; } for(i=0; i<len; i++) { ancient = ancients[i]; if(ancient._dispatchEventInPhase(event, EventPhase.BUBBLE)) { return; } } } _dispatchEventInPhase(event:Event, phase:EventPhase):boolean { var i, len; var listener:Function; var scope:any; var listenerList:ListenerList; event._eventPhase = phase; event._listenerRemove = false; event._currentTarget = this; listenerList = this._getListenerList(event.type, phase === EventPhase.CAPTURE); len = listenerList.length(); if(len > 0) { for (i = len-1; i >= 0; i--) { listener = listenerList.get(i); scope = listener[SCOPE]; if(scope) { listener.call(scope, event); } else { listener(event); } // handle remove listener when client call event.removeCurrentListener(); if(event._listenerRemove) { event._listenerRemove = false; listenerList.removeAt(i); } if(event.isStopImmediatePropagation()) { return true; } } if(event.isStopPropagation()) { return true; } } return false; } private _getAncients() { var ancients = []; var parent:any = this; while (parent._bubbleParent) { parent = parent._bubbleParent; ancients.push(parent); } return ancients; } private _getListenerList(type:string, useCapture:boolean):ListenerList { var listenerList; var dict = useCapture ? this._captureDict : this._bubbleDict; listenerList = dict[type]; if(!listenerList) { listenerList = new ListenerList(); dict[type] = listenerList; } return listenerList; } } }
zzm2q/WOZLLA.js
tests/renderer/TextureModuleTest.ts
/// <reference path="../../libs/WOZLLA.d.ts"/> /// <reference path="../../libs/jasmine.d.ts"/> /// <reference path="../data.ts"/> /// <reference path="test_help_classes.ts"/> module WOZLLA.renderer { describe('WOZLLA.renderer', function() { describe("TextureModuleTest", function () { var canvas:HTMLCanvasElement = <HTMLCanvasElement>document.createElement('canvas'); var gl = WebGLUtils.getGLContext(canvas); // create texture manager var textureManager = new TextureManager(gl); it("generate and delete texture from canvas", function () { var source = document.createElement('canvas'); source.width = 100; source.height = 100; source.getContext('2d').fillRect(20, 20, 60, 60); var textureDescriptor = new Test_HTMLImageDescriptor(source); var texture = textureManager.generateTexture(textureDescriptor); expect(texture).toBeDefined(); textureManager.deleteTexture(texture); expect(textureManager.getTexture(texture.id)).toBeUndefined(); }); it("generate and delete from pvrtc format", function () { if (WebGLExtension.getExtension(gl, WebGLExtension.PVRTC, false)) { var textureDescriptor = new Test_PVRDescriptor(WOZLLA.test.pvrData, PixelFormat.PVRTC4); var texture = textureManager.generateTexture(textureDescriptor); expect(texture).toBeDefined(); textureManager.deleteTexture(texture); expect(textureManager.getTexture(texture.id)).toBeUndefined(); } }); it("clear all generated texture", function () { var source = document.createElement('canvas'); source.width = 100; source.height = 100; source.getContext('2d').fillRect(20, 20, 60, 60); var textureDescriptor = new Test_HTMLImageDescriptor(source); var texture1 = textureManager.generateTexture(textureDescriptor); var texture2 = textureManager.generateTexture(new Test_HTMLImageDescriptor(source)); textureManager.clear(); expect(textureManager.getTexture(texture1.id)).toBeUndefined(); expect(textureManager.getTexture(texture2.id)).toBeUndefined(); }); }); }); }
zzm2q/WOZLLA.js
src/component/renderer/SpriteRenderer.ts
/// <reference path="QuadRenderer.ts"/> /// <reference path="../../assets/proxy/SpriteAtlasProxy.ts"/> /// <reference path="../../assets/Sprite.ts"/> /// <reference path="../../assets/SpriteAtlas.ts"/> module WOZLLA.component { /** * @class WOZLLA.component.SpriteRenderer */ export class SpriteRenderer extends QuadRenderer implements WOZLLA.assets.proxy.IProxyTarget { get color():number { return this._quadColor; } set color(value:number) { this.setQuadColor(value); } get alpha():number { return this._quadAlpha; } set alpha(value:number) { this.setQuadAlpha(value); } get materialId():string { return this._quadMaterialId; } set materialId(value:string) { this.setQuadMaterialId(value); } get renderLayer():string { return this._quadLayer; } set renderLayer(value:string) { this.setQuadLayer(value); } get renderOrder():number { return this._quadGlobalZ; } set renderOrder(value:number) { this.setQuadGlobalZ(value); } get sprite():WOZLLA.assets.Sprite { return this._sprite; } set sprite(sprite:WOZLLA.assets.Sprite) { var oldSprite = this._sprite; if(oldSprite === sprite) return; this._sprite = sprite; if(!sprite) { this.setTexture(null); this.setTextureFrame(null); } else { this.setTextureFrame(sprite.frame); if(!oldSprite || oldSprite.spriteAtlas !== sprite.spriteAtlas) { this.setTexture(sprite.spriteAtlas.glTexture); } } } get spriteOffset():any { return this._getTextureOffset(); } set spriteOffset(value) { this.setTextureOffset(value); } get imageSrc():string { return this._spriteAtlasSrc; } set imageSrc(value:string) { this.spriteAtlasSrc = value; this.spriteName = null; } get spriteAtlasSrc():string { return this._spriteAtlasSrc; } set spriteAtlasSrc(value:string) { this._spriteAtlasSrc = value; this._spriteProxy.setAssetSrc(value); } get spriteName():string { return this._spriteName; } set spriteName(value:string) { this._spriteName = value; this.sprite = this._spriteProxy.getSprite(value); } _spriteProxy:WOZLLA.assets.proxy.SpriteAtlasProxy; _sprite:WOZLLA.assets.Sprite; _spriteAtlasSrc:string; _spriteName:string; constructor() { super(); this._spriteProxy = new WOZLLA.assets.proxy.SpriteAtlasProxy(this); } destroy():void { this._spriteProxy.onDestroy(); super.destroy(); } onAssetLoaded(asset:WOZLLA.assets.Asset) { if(asset) { this.sprite = (<WOZLLA.assets.SpriteAtlas>asset).getSprite(this._spriteName); } else { this.sprite = null; } } loadAssets(callback:Function) { this._spriteProxy.loadAsset(callback); } } Component.register(SpriteRenderer, { name: "SpriteRenderer", properties: [{ name: 'color', type: 'int', defaultValue: 0xFFFFFF }, { name: 'alpha', type: 'int', defaultValue: 1 }, { name: 'spriteAtlasSrc', type: 'string' }, { name: 'spriteName', type: 'string' }, { name: 'imageSrc', type: 'string' }] }); }
zzm2q/WOZLLA.js
extensions/PureMVC/Service.ts
<reponame>zzm2q/WOZLLA.js ///<reference path='../../libs/puremvc-typescript-multicore-1.1.d.ts'/> module WOZLLA.PureMVC { export class Service extends puremvc.Proxy { } }
zzm2q/WOZLLA.js
tests/renderer/RendererTest.ts
/// <reference path="../../libs/WOZLLA.d.ts"/> /// <reference path="../../libs/jasmine.d.ts"/> /// <reference path="../data.ts"/> /// <reference path="test_help_classes.ts"/> module WOZLLA.renderer { describe('WOZLLA.renderer', function() { describe("RendererTest", function () { it("render quad with default material", function (done) { var flag = false; waitsFor(function() { return flag; }, "load image", 1000); var image = new Image(); image.src = 'images/cursor.png'; image.onload = function() { // create renderer var canvas = document.createElement('canvas'); // document.body.appendChild(canvas); Renderer.MAX_QUAD_SIZE = 1; var renderer = new Renderer(WebGLUtils.getGLContext(canvas), { x: 0, y: 0, width: canvas.width, height: canvas.height }); renderer.layerManager.define('main', 0); // create texture // var texCanvas = document.createElement('canvas'); // texCanvas.width = texCanvas.height = 50; // var texContext = texCanvas.getContext('2d'); // console.log(texContext); // texContext.fillStyle = '#000000'; // texContext.fillRect(0, 0, 50, 50); var texture = renderer.textureManager.generateTexture(new Test_HTMLImageDescriptor(image)); var frame = { x: 0, y: 0, width: 50, height: 50 }; var offset = { x: 0, y: 0 }; var tw = frame.width; var th = frame.height; var uvs:any = {}; uvs.x0 = frame.x / tw; uvs.y0 = frame.y / th; uvs.x1 = (frame.x + frame.width) / tw; uvs.y1 = frame.y / th; uvs.x2 = (frame.x + frame.width) / tw; uvs.y2 = (frame.y + frame.height) / th; uvs.x3 = frame.x / tw; uvs.y3 = (frame.y + frame.height) / th; var w1 = offset.x; var w0 = w1 + frame.width; var h1 = offset.y; var h0 = h1 + frame.height; var a = 1; var c = 0; var b = 0; var d = 1; var tx = 0; var ty = 0; var x1 = a * w1 + b * h1 + tx; var y1 = d * h1 + c * w1 + ty; var x2 = a * w0 + b * h1 + tx; var y2 = d * h1 + c * w0 + ty; var x3 = a * w0 + b * h0 + tx; var y3 = d * h0 + c * w0 + ty; var x4 = a * w1 + b * h0 + tx; var y4 = d * h0 + c * w1 + ty; var quad = new Quad(1); quad.setVertices(x1, y1, x2, y2, x3, y3, x4, y4); quad.setTexCoords(uvs.x0, uvs.y0, uvs.x1, uvs.y1, uvs.x2, uvs.y2, uvs.x3, uvs.y3); quad.setAlpha(1); quad.setColor(0xFFFFFF); renderer.addCommand(QuadCommand.init(0, 'main', texture, IMaterial.DEFAULT, quad)); renderer.render(); expect(1).toBe(1); flag = true; }; }); }); }); }
zzm2q/WOZLLA.js
src/renderer/IRenderer.ts
module WOZLLA.renderer { /** * @class WOZLLA.renderer.IRenderer * @abstract */ export interface IRenderer { /** * @property {WOZLLA.renderer.ILayerManager} layerManager */ layerManager:ILayerManager; materialManager:IMaterialManager; shaderManager:IShaderManager; textureManager:ITextureManager; viewport:any; gl:any; addCommand(command:IRenderCommand):void; render():void; flush():void; } export module IRenderer { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.IRenderer */ export var DOC = 'DOC'; } }
zzm2q/WOZLLA.js
src/renderer/Quad.ts
module WOZLLA.renderer { /** * @class WOZLLA.renderer.QuadType */ export class QuadType { get size() {return this.strade * 4; } get strade() { return this._info[0]; } get vertexIndex() { return this._info[1]; } get texCoordIndex() { return this._info[2]; } get alphaIndex() { return this._info[3]; } get colorIndex() { return this._info[4]; } _info; constructor(info) { this._info = info; } } /** * @class WOZLLA.renderer.Quad */ export class Quad { public static V2T2C1A1 = new QuadType([6, 0, 2, 4, 5]); get storage():number[] { return this._storage; } get count():number { return this._count; } get type():QuadType { return this._type; } get renderOffset():number { return this._renderOffset; } get renderCount():number { return this._renderCount; } _storage:number[]; _count:number; _type:QuadType; _renderOffset:number; _renderCount:number; constructor(count:number, type:QuadType=Quad.V2T2C1A1) { this._count = count; this._type = type; this._storage = new Array(type.size * count); this._renderOffset = 0; this._renderCount = count; } setRenderRange(offset:number, count:number):void { this._renderOffset = offset; this._renderCount = count; } setVertices(x1, y1, x2, y2, x3, y3, x4, y4, offset=0):void { var strade = this._type.strade; var size = this._type.size; var index = this._type.vertexIndex; var base = size*offset + index; this._storage[0 + base ] = x1; this._storage[1 + base ] = y1; this._storage[0 + base + strade * 1] = x2; this._storage[1 + base + strade * 1] = y2; this._storage[0 + base + strade * 2] = x3; this._storage[1 + base + strade * 2] = y3; this._storage[0 + base + strade * 3] = x4; this._storage[1 + base + strade * 3] = y4; } setTexCoords(x1, y1, x2, y2, x3, y3, x4, y4, offset=0):void { var strade = this._type.strade; var size = this._type.size; var index = this._type.texCoordIndex; var base = size*offset + index; this._storage[0 + base ] = x1; this._storage[1 + base ] = y1; this._storage[0 + base + strade * 1] = x2; this._storage[1 + base + strade * 1] = y2; this._storage[0 + base + strade * 2] = x3; this._storage[1 + base + strade * 2] = y3; this._storage[0 + base + strade * 3] = x4; this._storage[1 + base + strade * 3] = y4; } setAlpha(alpha:number, offset=0):void { var strade = this._type.strade; var size = this._type.size; var index = this._type.alphaIndex; var base = size*offset + index; this._storage[base ] = alpha; this._storage[base + strade * 1] = alpha; this._storage[base + strade * 2] = alpha; this._storage[base + strade * 3] = alpha; } setColor(color, offset=0):void { var strade = this._type.strade; var size = this._type.size; var index = this._type.colorIndex; var base = size*offset + index; this._storage[base ] = color; this._storage[base + strade * 1] = color; this._storage[base + strade * 2] = color; this._storage[base + strade * 3] = color; } } }
zzm2q/WOZLLA.js
src/math/MathUtils.ts
<filename>src/math/MathUtils.ts<gh_stars>0 module WOZLLA.math { export module MathUtils { export function rectIntersect(a, b) { return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; } export function rectIntersect2(ax, ay, aw, ah, bx, by, bw, bh) { return ax <= bx + bw && bx <= ax + aw && ay <= by + bh && by <= ay + ah; } } }
zzm2q/WOZLLA.js
src/component/mask/RectMask.ts
/// <reference path="../../core/Mask.ts"/> /// <reference path="../renderer/QuadRenderer.ts"/> module WOZLLA.component { /** * @class WOZLLA.component.RectMask */ export class RectMask extends Mask { get region():WOZLLA.math.Rectangle { return this._region; } set region(value:WOZLLA.math.Rectangle) { this._region = value; this._helperGameObject.transform.setPosition(value.x, value.y); this._helperGameObject.transform.setScale(value.width, value.height); } _helperGameObject:WOZLLA.GameObject = new WOZLLA.GameObject(); _region:WOZLLA.math.Rectangle; _maskQuadRenderer; protected renderMask(renderer:WOZLLA.renderer.IRenderer, flags:number) { if(this._region) { if(!this._maskQuadRenderer) { this._initMaskQuadRenderer(renderer); } if(this._helperGameObject.transform.dirty) { flags |= GameObject.MASK_TRANSFORM_DIRTY; } if((flags & GameObject.MASK_TRANSFORM_DIRTY) == GameObject.MASK_TRANSFORM_DIRTY) { this._helperGameObject.transform.transform(this.transform); } this._maskQuadRenderer.setQuadGlobalZ(this._startGlobalZ); this._maskQuadRenderer.render(renderer, flags); } } private _initMaskQuadRenderer(renderer:WOZLLA.renderer.IRenderer) { var canvas:any = document.createElement('canvas'); var context:any = canvas.getContext('2d'); canvas.width = 1; canvas.height = 1; context.fillStyle = '#FFFFFF'; context.fillRect(0, 0, canvas.width, canvas.height); var descriptor = new WOZLLA.assets.HTMLImageDescriptor(canvas); var texture = renderer.textureManager.generateTexture(descriptor); this._maskQuadRenderer = new WOZLLA.component.QuadRenderer(); this._maskQuadRenderer.setTexture(texture); this._helperGameObject.addComponent(this._maskQuadRenderer); this._helperGameObject.init(); } } }
zzm2q/WOZLLA.js
libs/DragonBones.d.ts
<filename>libs/DragonBones.d.ts /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Animation { static NONE: string; static SAME_LAYER: string; static SAME_GROUP: string; static SAME_LAYER_AND_GROUP: string; static ALL: string; /** * Whether animation tweening is enabled or not. */ tweenEnabled: boolean; private _armature; private _animationStateList; private _animationDataList; private _animationList; private _isPlaying; private _timeScale; /** @private */ _lastAnimationState: AnimationState; /** @private */ _isFading: boolean; /** @private */ _animationStateCount: number; /** * Creates a new Animation instance and attaches it to the passed Armature. * @param armature An Armature to attach this Animation instance to. */ constructor(armature: Armature); /** * Qualifies all resources used by this Animation instance for garbage collection. */ dispose(): void; /** * Fades the animation with name animation in over a period of time seconds and fades other animations out. * @param animationName The name of the AnimationData to play. * @param fadeInTime A fade time to apply (>= 0), -1 means use xml data's fadeInTime. * @param duration The duration of that Animation. -1 means use xml data's duration. * @param playTimes Play times(0:loop forever, >=1:play times, -1~-∞:will fade animation after play complete), 默认使用AnimationData.loop. * @param layer The layer of the animation. * @param group The group of the animation. * @param fadeOutMode Fade out mode (none, sameLayer, sameGroup, sameLayerAndGroup, all). * @param pauseFadeOut Pause other animation playing. * @param pauseFadeIn Pause this animation playing before fade in complete. * @return AnimationState. * @see dragonBones.objects.AnimationData. * @see dragonBones.animation.AnimationState. */ gotoAndPlay(animationName: string, fadeInTime?: number, duration?: number, playTimes?: number, layer?: number, group?: string, fadeOutMode?: string, pauseFadeOut?: boolean, pauseFadeIn?: boolean): AnimationState; /** * Control the animation to stop with a specified time. If related animationState haven't been created, then create a new animationState. * @param animationName The name of the animationState. * @param time * @param normalizedTime * @param fadeInTime A fade time to apply (>= 0), -1 means use xml data's fadeInTime. * @param duration The duration of that Animation. -1 means use xml data's duration. * @param layer The layer of the animation. * @param group The group of the animation. * @param fadeOutMode Fade out mode (none, sameLayer, sameGroup, sameLayerAndGroup, all). * @return AnimationState. * @see dragonBones.objects.AnimationData. * @see dragonBones.animation.AnimationState. */ gotoAndStop(animationName: string, time: number, normalizedTime?: number, fadeInTime?: number, duration?: number, layer?: number, group?: string, fadeOutMode?: string): AnimationState; /** * Play the animation from the current position. */ play(): void; stop(): void; /** * Returns the AnimationState named name. * @return A AnimationState instance. * @see dragonBones.animation.AnimationState. */ getState(name: string, layer?: number): AnimationState; /** * check if contains a AnimationData by name. * @return Boolean. * @see dragonBones.animation.AnimationData. */ hasAnimation(animationName: string): boolean; /** @private */ _advanceTime(passedTime: number): void; /** @private */ _updateAnimationStates(): void; private addState(animationState); private removeState(animationState); /** * Unrecommended API. Recommend use animationList. */ movementList: string[]; /** * Unrecommended API. Recommend use lastAnimationName. */ movementID: string; /** * The last AnimationState this Animation played. * @see dragonBones.objects.AnimationData. */ lastAnimationState: AnimationState; /** * The name of the last AnimationData played. * @see dragonBones.objects.AnimationData. */ lastAnimationName: string; /** * An vector containing all AnimationData names the Animation can play. * @see dragonBones.objects.AnimationData. */ animationList: string[]; /** * Is the animation playing. * @see dragonBones.animation.AnimationState. */ isPlaying: boolean; /** * Is animation complete. * @see dragonBones.animation.AnimationState. */ isComplete: boolean; /** * The amount by which passed time should be scaled. Used to slow down or speed up animations. Defaults to 1. */ timeScale: number; /** * The AnimationData list associated with this Animation instance. * @see dragonBones.objects.AnimationData. */ animationDataList: AnimationData[]; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class AnimationState { private static _pool; /** @private */ static _borrowObject(): AnimationState; /** @private */ static _returnObject(animationState: AnimationState): void; /** @private */ static _clear(): void; /** * Sometimes, we want slots controlled by a spedific animation state when animation is doing mix or addition. * It determine if animation's color change, displayIndex change, visible change can apply to its display */ displayControl: boolean; /** * If animation mixing use additive blending. */ additiveBlending: boolean; /** * If animation auto fade out after play complete. */ autoFadeOut: boolean; /** * Duration of fade out. By default, it equals to fade in time. */ fadeOutTime: number; /** * The weight of animation. */ weight: number; /** * If auto genterate tween between keyframes. */ autoTween: boolean; /** * If generate tween between the lastFrame to the first frame for loop animation. */ lastFrameAutoTween: boolean; /** @private */ _layer: number; /** @private */ _group: string; private _armature; private _timelineStateList; private _boneMasks; private _isPlaying; private _time; private _currentFrameIndex; private _currentFramePosition; private _currentFrameDuration; private _pausePlayheadInFade; private _isFadeOut; private _fadeTotalWeight; private _fadeWeight; private _fadeCurrentTime; private _fadeBeginTime; private _name; private _clip; private _isComplete; private _currentPlayTimes; private _totalTime; private _currentTime; private _fadeState; private _fadeTotalTime; private _timeScale; private _playTimes; constructor(); private clear(); containsBoneMask(boneName: string): boolean; /** * Adds a bone which should be animated. This allows you to reduce the number of animations you have to create. * @param boneName Bone's name. * @param ifInvolveChildBones if involve child bone's animation. */ addBoneMask(boneName: string, ifInvolveChildBones?: boolean): AnimationState; /** * Removes a bone which was supposed be animated. * @param boneName Bone's timeline name. * @param ifInvolveChildBones If involved child bone's timeline. */ removeBoneMask(boneName: string, ifInvolveChildBones?: boolean): AnimationState; removeAllMixingTransform(): AnimationState; private addBoneToBoneMask(boneName); private removeBoneFromBoneMask(boneName); /** * @private * Update timeline state based on mixing transforms and clip. */ _updateTimelineStates(): void; private addTimelineState(timelineName); private removeTimelineState(timelineState); /** * Play the current animation. 如果动画已经播放完毕, 将不会继续播放. */ play(): AnimationState; /** * Stop playing current animation. */ stop(): AnimationState; /** @private */ _fadeIn(armature: Armature, clip: AnimationData, fadeTotalTime: number, timeScale: number, playTimes: number, pausePlayhead: boolean): AnimationState; /** * Fade out the animation state * @param fadeTotalTime fadeOutTime * @param pausePlayhead pauseBeforeFadeOutComplete pause the animation before fade out complete */ fadeOut(fadeTotalTime: number, pausePlayhead: boolean): AnimationState; /** @private */ _advanceTime(passedTime: number): boolean; private advanceFadeTime(passedTime); private advanceTimelinesTime(passedTime); private updateMainTimeline(isThisComplete); private hideBones(); setAdditiveBlending(value: boolean): AnimationState; setAutoFadeOut(value: boolean, fadeOutTime?: number): AnimationState; setWeight(value: number): AnimationState; setFrameTween(autoTween: boolean, lastFrameAutoTween: boolean): AnimationState; setCurrentTime(value: number): AnimationState; setTimeScale(value: number): AnimationState; setPlayTimes(value?: number): AnimationState; /** * The name of the animation state. */ name: string; /** * The layer of the animation. When calculating the final blend weights, animations in higher layers will get their weights. */ layer: number; /** * The group of the animation. */ group: string; /** * The clip that is being played by this animation state. * @see dragonBones.objects.AnimationData. */ clip: AnimationData; /** * Is animation complete. */ isComplete: boolean; /** * Is animation playing. */ isPlaying: boolean; /** * Current animation played times */ currentPlayTimes: number; /** * The length of the animation clip in seconds. */ totalTime: number; /** * The current time of the animation. */ currentTime: number; fadeWeight: number; fadeState: number; fadeTotalTime: number; /** * The amount by which passed time should be scaled. Used to slow down or speed up the animation. Defaults to 1. */ timeScale: number; /** * playTimes Play times(0:loop forever, 1~+∞:play times, -1~-∞:will fade animation after play complete). */ playTimes: number; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { interface IAnimatable { /** * Update the animation using this method typically in an ENTERFRAME Event or with a Timer. * @param The amount of second to move the playhead ahead. */ advanceTime(passedTime: number): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class TimelineState { private static HALF_PI; private static DOUBLE_PI; private static _pool; /** @private */ static _borrowObject(): TimelineState; /** @private */ static _returnObject(timeline: TimelineState): void; /** @private */ static _clear(): void; name: string; /** @private */ _weight: number; /** @private */ _transform: DBTransform; /** @private */ _pivot: Point; /** @private */ _blendEnabled: boolean; /** @private */ _isComplete: boolean; /** @private */ _animationState: AnimationState; private _totalTime; private _currentTime; private _currentFrameIndex; private _currentFramePosition; private _currentFrameDuration; private _tweenEasing; private _tweenTransform; private _tweenScale; private _tweenColor; private _rawAnimationScale; private _updateMode; private _armature; private _animation; private _bone; private _timelineData; private _originTransform; private _originPivot; private _durationTransform; private _durationPivot; private _durationColor; constructor(); private clear(); /** @private */ _fadeIn(bone: Bone, animationState: AnimationState, timelineData: TransformTimeline): void; /** @private */ _fadeOut(): void; /** @private */ _update(progress: number): void; private updateMultipleFrame(progress); private updateToNextFrame(currentPlayTimes?); private updateTween(); private updateSingleFrame(); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class WorldClock implements IAnimatable { /** * A global static WorldClock instance ready to use. */ static clock: WorldClock; private _animatableList; private _time; time: number; private _timeScale; /** * The time scale to apply to the number of second passed to the advanceTime() method. * @param A Number to use as a time scale. */ timeScale: number; /** * Creates a new WorldClock instance. (use the static var WorldClock.clock instead). */ constructor(time?: number, timeScale?: number); /** * Returns true if the IAnimatable instance is contained by WorldClock instance. * @param An IAnimatable instance (Armature or custom) * @return true if the IAnimatable instance is contained by WorldClock instance. */ contains(animatable: IAnimatable): boolean; /** * Add a IAnimatable instance (Armature or custom) to this WorldClock instance. * @param An IAnimatable instance (Armature, WorldClock or custom) */ add(animatable: IAnimatable): void; /** * Remove a IAnimatable instance (Armature or custom) from this WorldClock instance. * @param An IAnimatable instance (Armature or custom) */ remove(animatable: IAnimatable): void; /** * Remove all IAnimatable instance (Armature or custom) from this WorldClock instance. */ clear(): void; /** * Update all registered IAnimatable instance animations using this method typically in an ENTERFRAME Event or with a Timer. * @param The amount of second to move the playhead ahead. */ advanceTime(passedTime?: number): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class EventDispatcher { private _listenersMap; constructor(); hasEventListener(type: string): boolean; addEventListener(type: string, listener: Function): void; removeEventListener(type: string, listener: Function): void; removeAllEventListeners(type: string): void; dispatchEvent(event: Event): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Armature extends EventDispatcher implements IAnimatable { __dragonBonesData: DragonBonesData; /** * The instance dispatch sound event. */ /** * The name should be same with ArmatureData's name */ name: string; /** * An object that can contain any user extra data. */ userData: any; /** @private Set it to true when slot's zorder changed*/ _slotsZOrderChanged: boolean; /** @private Store event needed to dispatch in current frame. When advanceTime execute complete, dispath them.*/ _eventList: Event[]; /** @private Store slots based on slots' zOrder*/ _slotList: Slot[]; /** @private Store bones based on bones' hierarchy (From root to leaf)*/ _boneList: Bone[]; private _delayDispose; private _lockDispose; /** @private */ _armatureData: ArmatureData; /** * ArmatureData. * @see dragonBones.objects.ArmatureData. */ armatureData: ArmatureData; /** @private */ _display: any; /** * Armature's display object. It's instance type depends on render engine. For example "flash.display.DisplayObject" or "startling.display.DisplayObject" */ display: any; /** * Unrecommended API. Please use .display instead. * @returns {any} */ getDisplay(): any; /** @private */ _animation: Animation; /** * An Animation instance * @see dragonBones.animation.Animation */ animation: Animation; /** * Creates a Armature blank instance. * @param Instance type of this object varies from flash.display.DisplayObject to startling.display.DisplayObject and subclasses. * @see #display */ constructor(display: any); /** * Cleans up any resources used by this instance. */ dispose(): void; /** * Force update bones and slots. (When bone's animation play complete, it will not update) */ invalidUpdate(boneName?: string): void; /** * Update the animation using this method typically in an ENTERFRAME Event or with a Timer. * @param The amount of second to move the playhead ahead. */ advanceTime(passedTime: number): void; /** * Get all Slot instance associated with this armature. * @param if return Vector copy * @return A Vector.&lt;Slot&gt; instance. * @see dragonBones.Slot */ getSlots(returnCopy?: boolean): Slot[]; /** * Retrieves a Slot by name * @param The name of the Bone to retrieve. * @return A Slot instance or null if no Slot with that name exist. * @see dragonBones.Slot */ getSlot(slotName: string): Slot; /** * Gets the Slot associated with this DisplayObject. * @param Instance type of this object varies from flash.display.DisplayObject to startling.display.DisplayObject and subclasses. * @return A Slot instance or null if no Slot with that DisplayObject exist. * @see dragonBones.Slot */ getSlotByDisplay(displayObj: any): Slot; /** * Add a slot to a bone as child. * @param slot A Slot instance * @param boneName bone name * @see dragonBones.core.DBObject */ addSlot(slot: Slot, boneName: string): void; /** * Remove a Slot instance from this Armature instance. * @param The Slot instance to remove. * @see dragonBones.Slot */ removeSlot(slot: Slot): void; /** * Remove a Slot instance from this Armature instance. * @param The name of the Slot instance to remove. * @see dragonBones.Slot */ removeSlotByName(slotName: string): Slot; /** * Get all Bone instance associated with this armature. * @param if return Vector copy * @return A Vector.&lt;Bone&gt; instance. * @see dragonBones.Bone */ getBones(returnCopy?: boolean): Bone[]; /** * Retrieves a Bone by name * @param The name of the Bone to retrieve. * @return A Bone instance or null if no Bone with that name exist. * @see dragonBones.Bone */ getBone(boneName: string): Bone; /** * Gets the Bone associated with this DisplayObject. * @param Instance type of this object varies from flash.display.DisplayObject to startling.display.DisplayObject and subclasses. * @return A Bone instance or null if no Bone with that DisplayObject exist.. * @see dragonBones.Bone */ getBoneByDisplay(display: any): Bone; /** * Add a Bone instance to this Armature instance. * @param A Bone instance. * @param (optional) The parent's name of this Bone instance. * @see dragonBones.Bone */ addBone(bone: Bone, parentName?: string, updateLater?: boolean): void; /** * Remove a Bone instance from this Armature instance. * @param The Bone instance to remove. * @see dragonBones.Bone */ removeBone(bone: Bone, updateLater?: boolean): void; /** * Remove a Bone instance from this Armature instance. * @param The name of the Bone instance to remove. * @see dragonBones.Bone */ removeBoneByName(boneName: string): Bone; /** @private */ _addBoneToBoneList(bone: Bone): void; /** @private */ _removeBoneFromBoneList(bone: Bone): void; /** @private */ _addSlotToSlotList(slot: Slot): void; /** @private */ _removeSlotFromSlotList(slot: Slot): void; /** * Sort all slots based on zOrder */ updateSlotsZOrder(): void; _updateAnimationAfterBoneListChanged(ifNeedSortBoneList?: boolean): void; private sortBoneList(); /** @private When AnimationState enter a key frame, call this func*/ _arriveAtFrame(frame: Frame, timelineState: TimelineState, animationState: AnimationState, isCross: boolean): void; private sortSlot(slot1, slot2); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Matrix { a: number; b: number; c: number; d: number; tx: number; ty: number; constructor(); invert(): void; concat(m: Matrix): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class DBTransform { /** * Position on the x axis. */ x: number; /** * Position on the y axis. */ y: number; /** * Skew on the x axis. */ skewX: number; /** * skew on the y axis. */ skewY: number; /** * Scale on the x axis. */ scaleX: number; /** * Scale on the y axis. */ scaleY: number; /** * The rotation of that DBTransform instance. */ rotation: number; /** * Creat a new DBTransform instance. */ constructor(); /** * Copy all properties from this DBTransform instance to the passed DBTransform instance. * @param node */ copy(transform: DBTransform): void; /** * Get a string representing all DBTransform property values. * @return String All property values in a formatted string. */ toString(): string; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class DBObject { name: string; /** * An object that can contain any user extra data. */ userData: any; /** * */ inheritRotation: boolean; /** * */ inheritScale: boolean; /** * */ inheritTranslation: boolean; /** @private */ _global: DBTransform; /** @private */ _globalTransformMatrix: Matrix; static _tempParentGlobalTransformMatrix: Matrix; static _tempParentGlobalTransform: DBTransform; /** * This DBObject instance global transform instance. * @see dragonBones.objects.DBTransform */ global: DBTransform; /** @private */ _origin: DBTransform; /** * This DBObject instance related to parent transform instance. * @see dragonBones.objects.DBTransform */ origin: DBTransform; /** @private */ _offset: DBTransform; /** * This DBObject instance offset transform instance (For manually control). * @see dragonBones.objects.DBTransform */ offset: DBTransform; /** @private */ _visible: boolean; /** @private */ _armature: Armature; /** * The armature this DBObject instance belongs to. */ armature: Armature; /** @private */ _setArmature(value: Armature): void; /** @private */ _parent: Bone; /** * Indicates the Bone instance that directly contains this DBObject instance if any. */ parent: Bone; /** @private */ _setParent(value: Bone): void; constructor(); /** * Cleans up any resources used by this DBObject instance. */ dispose(): void; _calculateRelativeParentTransform(): void; _calculateParentTransform(): any; _updateGlobal(): any; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Bone extends DBObject { static initWithBoneData(boneData: BoneData): Bone; /** * AnimationState that slots belong to the bone will be controlled by. * Sometimes, we want slots controlled by a spedific animation state when animation is doing mix or addition. */ displayController: string; applyOffsetTranslationToChild: Boolean; applyOffsetRotationToChild: Boolean; applyOffsetScaleToChild: Boolean; /** @private */ _boneList: Bone[]; /** @private */ _slotList: Slot[]; /** @private */ _timelineStateList: TimelineState[]; /** @private */ _tween: DBTransform; /** @private */ _tweenPivot: Point; /** @private */ _needUpdate: number; /** @private */ _isColorChanged: boolean; /** @private */ _globalTransformForChild: DBTransform; /** @private */ _globalTransformMatrixForChild: Matrix; private _tempGlobalTransformForChild; private _tempGlobalTransformMatrixForChild; constructor(); /** * @inheritDoc */ dispose(): void; /** * If contains some bone or slot * @param Slot or Bone instance * @return Boolean * @see dragonBones.core.DBObject */ contains(child: DBObject): boolean; addChildBone(childBone: Bone, updateLater?: boolean): void; removeChildBone(childBone: Bone, updateLater?: boolean): void; addSlot(childSlot: Slot): void; removeSlot(childSlot: Slot): void; /** @private */ _setArmature(value: Armature): void; /** * Get all Bone instance associated with this bone. * @return A Vector.&lt;Slot&gt; instance. * @see dragonBones.Slot */ getBones(returnCopy?: boolean): Bone[]; /** * Get all Slot instance associated with this bone. * @return A Vector.&lt;Slot&gt; instance. * @see dragonBones.Slot */ getSlots(returnCopy?: boolean): Slot[]; /** * Force update the bone in next frame even if the bone is not moving. */ invalidUpdate(): void; _calculateRelativeParentTransform(): void; /** @private */ _update(needUpdate?: boolean): void; /** @private */ _updateColor(aOffset: number, rOffset: number, gOffset: number, bOffset: number, aMultiplier: number, rMultiplier: number, gMultiplier: number, bMultiplier: number, colorChanged: boolean): void; /** @private */ _hideSlots(): void; /** @private When bone timeline enter a key frame, call this func*/ _arriveAtFrame(frame: Frame, timelineState: TimelineState, animationState: AnimationState, isCross: boolean): void; /** @private */ _addState(timelineState: TimelineState): void; /** @private */ _removeState(timelineState: TimelineState): void; private blendingTimeline(); private sortState(state1, state2); /** * Unrecommended API. Recommend use slot.childArmature. */ childArmature: Armature; /** * Unrecommended API. Recommend use slot.display. */ display: any; /** * Unrecommended API. Recommend use offset. */ node: DBTransform; /** @private */ visible: boolean; slot: Slot; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Slot extends DBObject { /** @private Need to keep the reference of DisplayData. When slot switch displayObject, it need to restore the display obect's origional pivot. */ _displayDataList: DisplayData[]; /** @private */ _originZOrder: number; /** @private */ _tweenZOrder: number; /** @private */ _offsetZOrder: number; _displayList: any[]; _currentDisplayIndex: number; _colorTransform: ColorTransform; _currentDisplay: any; _isShowDisplay: boolean; _blendMode: string; constructor(self: Slot); initWithSlotData(slotData: SlotData): void; /** * @inheritDoc */ dispose(): void; /** @private */ setArmature(value: Armature): void; /** @private */ _update(): void; _calculateRelativeParentTransform(): void; private updateChildArmatureAnimation(); /** @private */ _changeDisplay(displayIndex?: number): void; /** @private * Updates the display of the slot. */ _updateSlotDisplay(): void; /** @private */ visible: boolean; /** * The DisplayObject list belonging to this Slot instance (display or armature). Replace it to implement switch texture. */ displayList: any[]; /** * The DisplayObject belonging to this Slot instance. Instance type of this object varies from flash.display.DisplayObject to startling.display.DisplayObject and subclasses. */ display: any; /** * Unrecommended API. Please use .display instead. * @returns {any} */ getDisplay(): any; /** * Unrecommended API. Please use .display = instead. * @returns {any} */ setDisplay(value: any): void; /** * The sub-armature of this Slot instance. */ childArmature: Armature; /** * zOrder. Support decimal for ensure dynamically added slot work toghther with animation controled slot. * @return zOrder. */ zOrder: number; /** * blendMode * @return blendMode. */ blendMode: string; /** * @private */ _updateDisplay(value: any): void; /** * @private */ _getDisplayIndex(): number; /** * @private * Adds the original display object to another display object. * @param container * @param index */ _addDisplayToContainer(container: any, index?: number): void; /** * @private * remove the original display object from its parent. */ _removeDisplayFromContainer(): void; /** * @private * Updates the transform of the slot. */ _updateTransform(): void; /** * @private */ _updateDisplayVisible(value: boolean): void; /** * @private * Updates the color of the display object. * @param a * @param r * @param g * @param b * @param aM * @param rM * @param gM * @param bM */ _updateDisplayColor(aOffset: number, rOffset: number, gOffset: number, bOffset: number, aMultiplier: number, rMultiplier: number, gMultiplier: number, bMultiplier: number): void; /** * @private * Update the blend mode of the display object. * @param value The blend mode to use. */ _updateDisplayBlendMode(value: string): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class DragonBones { static DATA_VERSION: string; static PARENT_COORDINATE_DATA_VERSION: String; constructor(); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Event { type: string; target: EventDispatcher; constructor(type: string); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class AnimationEvent extends Event { /** * 不推荐使用. */ static MOVEMENT_CHANGE: string; /** * Dispatched when the playback of an animation fade in. */ static FADE_IN: string; /** * Dispatched when the playback of an animation fade out. */ static FADE_OUT: string; /** * Dispatched when the playback of an animation starts. */ static START: string; /** * Dispatched when the playback of a animation stops. */ static COMPLETE: string; /** * Dispatched when the playback of a animation completes a loop. */ static LOOP_COMPLETE: string; /** * Dispatched when the playback of an animation fade in complete. */ static FADE_IN_COMPLETE: string; /** * Dispatched when the playback of an animation fade out complete. */ static FADE_OUT_COMPLETE: string; /** * 不推荐的API. */ movementID: string; /** * The animationState instance. */ animationState: AnimationState; /** * The armature that is the taget of this event. */ armature: Armature; animationName: string; /** * Creates a new AnimationEvent instance. * @param type * @param cancelable */ constructor(type: string, cancelable?: boolean); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class ArmatureEvent extends Event { /** * Dispatched after a successful z order update. */ static Z_ORDER_UPDATED: string; constructor(type: string); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class FrameEvent extends Event { static MOVEMENT_FRAME_EVENT: string; /** * Dispatched when the animation of the armatrue enter a frame. */ static ANIMATION_FRAME_EVENT: string; /** * */ static BONE_FRAME_EVENT: string; /** * The entered frame label. */ frameLabel: string; bone: Bone; /** * The armature that is the target of this event. */ armature: Armature; /** * The animationState instance. */ animationState: AnimationState; /** * Creates a new FrameEvent instance. * @param type * @param cancelable */ constructor(type: string, cancelable?: boolean); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class BaseFactory extends EventDispatcher { static _helpMatrix: Matrix; /** @private */ dragonBonesDataDic: any; /** @private */ textureAtlasDic: any; constructor(self: BaseFactory); /** * Cleans up resources used by this BaseFactory instance. * @param (optional) Destroy all internal references. */ dispose(disposeData?: boolean): void; /** * Returns a DragonBonesData instance. * @param The name of an existing DragonBonesData instance. * @return A DragonBonesData instance with given name (if exist). */ getDragonBonesData(name: string): DragonBonesData; /** * Recommend using getDragonBonesData API instead. */ getSkeletonData(name: string): DragonBonesData; /** * Add a DragonBonesData instance to this BaseFactory instance. * @param A DragonBonesData instance. * @param (optional) A name for this DragonBonesData instance. */ addDragonBonesData(data: DragonBonesData, name?: string): void; /** * Recommend using addDragonBonesData API instead. */ addSkeletonData(data: DragonBonesData, name?: string): void; /** * Remove a DragonBonesData instance from this BaseFactory instance. * @param The name for the DragonBonesData instance to remove. */ removeDragonBonesData(name: string): void; /** * Recommend using removeDragonBonesData API instead. */ removeSkeletonData(name: string): void; /** * Return the TextureAtlas by name. * @param The name of the TextureAtlas to return. * @return A textureAtlas. */ getTextureAtlas(name: string): any; /** * Add a textureAtlas to this BaseFactory instance. * @param A textureAtlas to add to this BaseFactory instance. * @param (optional) A name for this TextureAtlas. */ addTextureAtlas(textureAtlas: any, name?: string): void; /** * Remove a textureAtlas from this baseFactory instance. * @param The name of the TextureAtlas to remove. */ removeTextureAtlas(name: string): void; /** * Return the TextureDisplay. * @param The name of this Texture. * @param The name of the TextureAtlas. * @param The registration pivotX position. * @param The registration pivotY position. * @return An Object. */ getTextureDisplay(textureName: string, textureAtlasName?: string, pivotX?: number, pivotY?: number): any; buildArmature(armatureName: string, fromDragonBonesDataName?: string, fromTextureAtlasName?: string, skinName?: string): Armature; buildArmatureUsingArmatureDataFromTextureAtlas(dragonBonesData: DragonBonesData, armatureData: ArmatureData, textureAtlas: any, skinName?: string): Armature; copyAnimationsToArmature(toArmature: Armature, fromArmatreName: string, fromDragonBonesDataName?: string, ifRemoveOriginalAnimationList?: boolean): boolean; private fillBuildArmatureDataPackageArmatureInfo(armatureName, dragonBonesDataName, outputBuildArmatureDataPackage); private fillBuildArmatureDataPackageTextureInfo(fromTextureAtlasName, outputBuildArmatureDataPackage); private findFirstDragonBonesData(); private findFirstTextureAtlas(); _buildBones(armature: Armature): void; _buildSlots(armature: Armature, skinName: string, textureAtlas: any): void; /** * @private * Generates an Armature instance. * @return Armature An Armature instance. */ _generateArmature(): Armature; /** * @private * Generates an Slot instance. * @return Slot An Slot instance. */ _generateSlot(): Slot; /** * @private * Generates a DisplayObject * @param textureAtlas The TextureAtlas. * @param fullName A qualified name. * @param pivotX A pivot x based value. * @param pivotY A pivot y based value. * @return */ _generateDisplay(textureAtlas: any, fullName: string, pivotX: number, pivotY: number): any; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Point { x: number; y: number; constructor(x?: number, y?: number); toString(): string; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Rectangle { x: number; y: number; width: number; height: number; constructor(x?: number, y?: number, width?: number, height?: number); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Timeline { duration: number; scale: number; private _frameList; constructor(); dispose(): void; addFrame(frame: Frame): void; frameList: Frame[]; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class AnimationData extends Timeline { name: string; frameRate: number; fadeTime: number; playTimes: number; tweenEasing: number; autoTween: boolean; lastFrameDuration: number; hideTimelineNameMap: string[]; private _timelineList; timelineList: TransformTimeline[]; constructor(); dispose(): void; getTimeline(timelineName: string): TransformTimeline; addTimeline(timeline: TransformTimeline): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class ArmatureData { name: string; private _boneDataList; private _skinDataList; private _animationDataList; static sortBoneDataHelpArray(object1: any, object2: any): number; static sortBoneDataHelpArrayDescending(object1: any, object2: any): number; constructor(); dispose(): void; getBoneData(boneName: string): BoneData; getSkinData(skinName: string): SkinData; getAnimationData(animationName: string): AnimationData; addBoneData(boneData: BoneData): void; addSkinData(skinData: SkinData): void; addAnimationData(animationData: AnimationData): void; sortBoneDataList(): void; boneDataList: BoneData[]; skinDataList: SkinData[]; animationDataList: AnimationData[]; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class BoneData { name: string; parent: string; length: number; global: DBTransform; transform: DBTransform; inheritScale: boolean; inheritRotation: boolean; constructor(); dispose(): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class ColorTransform { alphaMultiplier: number; alphaOffset: number; blueMultiplier: number; blueOffset: number; greenMultiplier: number; greenOffset: number; redMultiplier: number; redOffset: number; constructor(); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class DisplayData { static ARMATURE: string; static IMAGE: string; name: string; type: string; transform: DBTransform; pivot: Point; constructor(); dispose(): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class DragonBonesData { name: string; isGlobal: boolean; private _armatureDataList; private _displayDataDictionary; constructor(); dispose(): void; armatureDataList: ArmatureData[]; getArmatureDataByName(armatureName: string): ArmatureData; addArmatureData(armatureData: ArmatureData): void; removeArmatureData(armatureData: ArmatureData): void; removeArmatureDataByName(armatureName: string): void; getDisplayDataByName(name: string): DisplayData; addDisplayData(displayData: DisplayData): void; removeDisplayDataByName(name: string): void; removeAllDisplayData(): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class Frame { position: number; duration: number; action: string; event: string; sound: string; constructor(); dispose(): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class SkinData { name: string; private _slotDataList; constructor(); dispose(): void; getSlotData(slotName: string): SlotData; addSlotData(slotData: SlotData): void; slotDataList: SlotData[]; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class SlotData { name: string; parent: string; zOrder: number; blendMode: string; private _displayDataList; constructor(); dispose(): void; addDisplayData(displayData: DisplayData): void; getDisplayData(displayName: string): DisplayData; displayDataList: DisplayData[]; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class TransformFrame extends Frame { tweenEasing: number; tweenRotate: number; tweenScale: boolean; displayIndex: number; visible: boolean; zOrder: number; global: DBTransform; transform: DBTransform; pivot: Point; color: ColorTransform; scaleOffset: Point; constructor(); dispose(): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class TransformTimeline extends Timeline { name: string; transformed: boolean; originTransform: DBTransform; originPivot: Point; offset: number; constructor(); dispose(): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class DataParser { private static tempDragonBonesData; static parseTextureAtlasData(rawData: any, scale?: number): any; static parseDragonBonesData(rawDataToParse: any): DragonBonesData; private static parseArmatureData(armatureDataToParse, frameRate); private static parseBoneData(boneObject); private static parseSkinData(skinObject); private static parseSlotData(slotObject); private static parseDisplayData(displayObject); /** @private */ private static parseAnimationData(animationObject, frameRate); private static parseTransformTimeline(timelineObject, duration, frameRate); private static parseTransformFrame(frameObject, frameRate); private static parseTimeline(timelineObject, outputTimeline); private static parseFrame(frameObject, outputFrame, frameRate?); private static parseTransform(transformObject, transform, pivot?); private static parseColorTransform(colorTransformObject, colorTransform); private static getBoolean(data, key, defaultValue); private static getNumber(data, key, defaultValue); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { interface ITextureAtlas { /** * The name of this ITextureAtlas. */ name: string; /** * Clean up resources. */ dispose(): void; /** * Get the specific region of the TextureAtlas occupied by assets defined by that name. * @param name The name of the assets represented by that name. * @return Rectangle The rectangle area occupied by those assets. */ getRegion(name: string): Rectangle; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class TextureData { region: Rectangle; frame: Rectangle; rotated: boolean; constructor(region: Rectangle, frame: Rectangle, rotated: boolean); } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class ConstValues { static ANGLE_TO_RADIAN: number; static RADIAN_TO_ANGLE: number; static DRAGON_BONES: string; static ARMATURE: string; static SKIN: string; static BONE: string; static SLOT: string; static DISPLAY: string; static ANIMATION: string; static TIMELINE: string; static FRAME: string; static TRANSFORM: string; static COLOR_TRANSFORM: string; static RECTANGLE: string; static ELLIPSE: string; static TEXTURE_ATLAS: string; static SUB_TEXTURE: string; static A_ROTATED: string; static A_FRAME_X: string; static A_FRAME_Y: string; static A_FRAME_WIDTH: string; static A_FRAME_HEIGHT: string; static A_VERSION: string; static A_IMAGE_PATH: string; static A_FRAME_RATE: string; static A_NAME: string; static A_IS_GLOBAL: string; static A_PARENT: string; static A_LENGTH: string; static A_TYPE: string; static A_FADE_IN_TIME: string; static A_DURATION: string; static A_SCALE: string; static A_OFFSET: string; static A_LOOP: string; static A_EVENT: string; static A_EVENT_PARAMETERS: string; static A_SOUND: string; static A_ACTION: string; static A_HIDE: string; static A_AUTO_TWEEN: string; static A_TWEEN_EASING: string; static A_TWEEN_ROTATE: string; static A_TWEEN_SCALE: string; static A_DISPLAY_INDEX: string; static A_Z_ORDER: string; static A_BLENDMODE: string; static A_WIDTH: string; static A_HEIGHT: string; static A_INHERIT_SCALE: string; static A_INHERIT_ROTATION: string; static A_X: string; static A_Y: string; static A_SKEW_X: string; static A_SKEW_Y: string; static A_SCALE_X: string; static A_SCALE_Y: string; static A_PIVOT_X: string; static A_PIVOT_Y: string; static A_ALPHA_OFFSET: string; static A_RED_OFFSET: string; static A_GREEN_OFFSET: string; static A_BLUE_OFFSET: string; static A_ALPHA_MULTIPLIER: string; static A_RED_MULTIPLIER: string; static A_GREEN_MULTIPLIER: string; static A_BLUE_MULTIPLIER: string; static A_SCALE_X_OFFSET: string; static A_SCALE_Y_OFFSET: string; static A_SCALE_MODE: string; static A_FIXED_ROTATION: string; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class DBDataUtil { static transformArmatureData(armatureData: ArmatureData): void; static transformArmatureDataAnimations(armatureData: ArmatureData): void; static transformRelativeAnimationData(animationData: AnimationData, armatureData: ArmatureData): void; static transformAnimationData(animationData: AnimationData, armatureData: ArmatureData, isGlobalData: boolean): void; private static setFrameTransform(animationData, armatureData, boneData, frame); private static getTimelineTransform(timeline, position, retult, isGlobal); static addHideTimeline(animationData: AnimationData, armatureData: ArmatureData): void; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class MathUtil { /** @private */ static getEaseValue(value: number, easing: number): number; } } /** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ declare module dragonBones { class TransformUtil { private static HALF_PI; private static DOUBLE_PI; private static _helpTransformMatrix; private static _helpParentTransformMatrix; static globalToLocal(transform: DBTransform, parent: DBTransform): void; static transformToMatrix(transform: DBTransform, matrix: Matrix, keepScale?: boolean): void; static matrixToTransform(matrix: Matrix, transform: DBTransform, scaleXF: Boolean, scaleYF: Boolean): void; static formatRadian(radian: number): number; } }
zzm2q/WOZLLA.js
src/renderer/IShaderManager.ts
<gh_stars>0 module WOZLLA.renderer { /** * @class WOZLLA.renderer.IShaderManager * @abstract */ export interface IShaderManager { createShaderProgram(vertexSource:string, fragmentSource:string, ShaderClass:Function):IShaderProgram; getShaderProgram(id):IShaderProgram; deleteShaderProgram(shaderProgram:IShaderProgram):void; clear():void; } export module IShaderManager { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.IShaderManager */ export var DOC = 'DOC'; } }
zzm2q/WOZLLA.js
tests/renderer/ShaderModuleTest.ts
/// <reference path="../../libs/WOZLLA.d.ts"/> /// <reference path="../../libs/jasmine.d.ts"/> /// <reference path="../data.ts"/> module WOZLLA.renderer { describe('WOZLLA.renderer', function() { describe("ShaderModuleTest", function () { var canvas:HTMLCanvasElement = <HTMLCanvasElement>document.createElement('canvas'); var gl = WebGLUtils.getGLContext(canvas); var shaderManager = new ShaderManager(gl); it("create and delete program", function () { var shaderProgram = shaderManager.createShaderProgram(WOZLLA.test.shaderPair[0], WOZLLA.test.shaderPair[1]); expect(shaderProgram).not.toBeUndefined(); expect(shaderManager.getShaderProgram(shaderProgram.id)).not.toBeUndefined(); shaderManager.deleteShaderProgram(shaderProgram); expect(shaderManager.getShaderProgram(shaderProgram.id)).toBeUndefined(); }); it("clear shader program", function () { var shaderProgram1 = shaderManager.createShaderProgram(WOZLLA.test.shaderPair[0], WOZLLA.test.shaderPair[1]); var shaderProgram2 = shaderManager.createShaderProgram(WOZLLA.test.shaderPair[0], WOZLLA.test.shaderPair[1]); shaderManager.clear(); expect(shaderManager.getShaderProgram(shaderProgram1.id)).toBeUndefined(); expect(shaderManager.getShaderProgram(shaderProgram2.id)).toBeUndefined(); }); }); }); }
zzm2q/WOZLLA.js
src/core/Director.ts
<gh_stars>0 /// <reference path="Stage.ts"/> /// <reference path="Touch.ts"/> /// <reference path="../renderer/WebGLUtils.ts"/> /// <reference path="../renderer/internal/Renderer.ts"/> /// <reference path="Scheduler.ts"/> /// <reference path="../assets/AssetLoader.ts"/> module WOZLLA { var requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame || function(frameCall:Function, intervalTime=1000/62) { setTimeout(frameCall, intervalTime); }; /** * a director hold this instances: <br/> * 1. {@link WOZLLA.Stage} <br/> * 2. {@link WOZLLA.renderer.IRenderer} <br/> * 3. {@link WOZLLA.Scheduler} <br/> * 4. {@link WOZLLA.Touch} <br/> * 5. {@link WOZLLA.assets.AssetLoader} <br/> * <br/> * <br/> * and also responsable to setup engine and control main loop. * * @class WOZLLA.Director * @singleton */ export class Director { private static instance; public static getInstance():Director { return Director.instance; } /** * get the canvas element * @property {any} view */ get view():any { return this._view; } /** * get the touch instance * @property {WOZLLA.Touch} touch * @readonly */ get touch():Touch { return this._touch; } /** * get the stage instance * @property {WOZLLA.Stage} stage * @readonly */ get stage():Stage { return this._stage; } /** * get the scheduler instance * @property {WOZLLA.Scheduler} scheduler * @readonly */ get scheduler():Scheduler { return this._scheduler; } /** * get the renderer instance * @property {WOZLLA.renderer.IRenderer} renderer * @readonly */ get renderer():WOZLLA.renderer.IRenderer { return this._renderer; } /** * get the asset loader instance * @property {WOZLLA.assets.AssetLoader} assetLoader * @readonly */ get assetLoader():WOZLLA.assets.AssetLoader { return this._assetLoader; } /** * get the root instance of RectTransform * @returns {WOZLLA.RectTransform} viewRectTransform */ get viewRectTransform():WOZLLA.RectTransform { return this._stage.viewRectTransform; } private _runing = false; private _paused = false; private _timeScale = 1; private _view; private _touch:Touch; private _stage:Stage; private _renderer:WOZLLA.renderer.IRenderer; private _scheduler:Scheduler; private _assetLoader:WOZLLA.assets.AssetLoader; constructor(view, options:any={}) { Director.instance = this; this._view = typeof view === 'string' ? document.getElementById('canvas') : view; this._scheduler = Scheduler.getInstance(); this._assetLoader = WOZLLA.assets.AssetLoader.getInstance(); this._touch = new WOZLLA.Touch(view, options.touchScale); this._renderer = new WOZLLA.renderer.Renderer( WOZLLA.renderer.WebGLUtils.getGLContext(view, options.renderer), { x: 0, y: 0, width: view.width, height: view.height } ); this._stage = new Stage(); } /** * start main loop */ start():void { var frame; if(this._runing) { return; } this._runing = true; Time.reset(); frame = ()=> { if(this._runing) { requestAnimationFrame(frame); } this.runStep(); }; requestAnimationFrame(frame); } /** * stop main loop */ stop() { this._runing = false; } /** * run one frame * @param {number} [timeScale=1] */ public runStep(timeScale=this._timeScale) { Time.update(timeScale); this._stage.update(); this._stage.visitStage(this._renderer); this._renderer.render(); this._scheduler.runSchedule(); WOZLLA.utils.Tween.tick(Time.delta); } } }
zzm2q/WOZLLA.js
tests/renderer/test_help_classes.ts
<reponame>zzm2q/WOZLLA.js module WOZLLA.renderer { export class Test_HTMLImageDescriptor implements ITextureDescriptor { get width():number { return this._source.width; } get height():number { return this._source.height; } get source():any { return this._source; } get textureFormat():TextureFormat { return this._textureFormat; } get pixelFormat():PixelFormat { return this._pixelFormat; } _source; _textureFormat:TextureFormat; _pixelFormat:PixelFormat; constructor(source) { this._source = source; this._textureFormat = TextureFormat.PNG; this._pixelFormat = PixelFormat.RGBA8888; } } export class Test_PVRDescriptor implements ITextureDescriptor { get width():number { return this._source.width; } get height():number { return this._source.height; } get source():any { return this._source; } get textureFormat():TextureFormat { return this._textureFormat; } get pixelFormat():PixelFormat { return this._pixelFormat; } _source; _textureFormat:TextureFormat; _pixelFormat:PixelFormat; constructor(source, pixelFormat:PixelFormat) { this._source = source; this._textureFormat = TextureFormat.PVR; this._pixelFormat = pixelFormat; } } }
zzm2q/WOZLLA.js
src/assets/Asset.ts
/// <reference path="../event/EventDispatcher.ts"/> /// <reference path="../event/Event.ts"/> module WOZLLA.assets { /** * Base class of all assets in WOZLLA engine. * an asset contains a reference count which increase by **retain** function, * decrease by **release** function. * an asset would be unload when reference count reach 0. * @class WOZLLA.assets.Asset * @extends WOZLLA.event.EventDispatcher * @abstract */ export class Asset extends WOZLLA.event.EventDispatcher { public static EVENT_UNLOAD = 'unload'; /** * @property {string} src * @readonly */ get src():string { return this._src; } get fullPath():string { return this._baseDir + this._src; } private _src:string; private _baseDir:string; private _refCount = 0; constructor(src:string, baseDir:string='') { super(); this._src = src; this._baseDir = baseDir; } /** * retain this asset */ retain() { this._refCount ++; } /** * release this asset * @param {boolean} [decreaceRefCount=true] */ release(decreaceRefCount:boolean=true) { if(decreaceRefCount) { if (this._refCount > 0) { this._refCount--; } } if(this._refCount === 0) { this.unload(); } } /** * load this asset * @param onSuccess * @param onError */ load(onSuccess:()=>any, onError:(error)=>any):void { onSuccess(); } /** * unload this asset * @fires unload event */ unload():void { var event = new WOZLLA.event.Event(Asset.EVENT_UNLOAD, false); event.target = event.currentTarget = this; this.dispatchEvent(event); } } }
zzm2q/WOZLLA.js
src/core/Component.ts
/// <reference path="Transform.ts"/> /// <reference path="../utils/Assert.ts"/> module WOZLLA { /** * Top class of all components * @class WOZLLA.Component * @extends WOZLLA.event.EventDispatcher * @abstract */ export class Component extends WOZLLA.event.EventDispatcher { /** * get the GameObject of this component belongs to. * @property {WOZLLA.GameObject} gameObject */ get gameObject():GameObject { return this._gameObject; } set gameObject(value:GameObject) { this._gameObject = value; } /** * get transform of the gameObject of this component * @property {WOZLLA.Transform} transform */ get transform():Transform { return this._gameObject.transform; } _gameObject:GameObject; _uuid:string; /** * init this component */ init():void {} /** * destroy this component */ destroy():void {} loadAssets(callback:Function) { callback && callback(); } listRequiredComponents():Array<Function> { return []; } private static ctorMap:any = {}; private static configMap:any = {}; public static getType(name:string) { var ret = this.ctorMap[name] Assert.isNotUndefined(ret, 'Can\'t found component: ' + name); return ret; } public static getName(Type:Function) { return (<any>Type).componentName; } /** * register an component class and it's configuration * @method register * @static * @param ctor * @param configuration */ public static register(ctor:Function, config) { Assert.isObject(config); Assert.isString(config.name); Assert.isUndefined(Component.configMap[config.name]); Component.ctorMap[config.name] = ctor; Component.configMap[config.name] = config; (<any>ctor).componentName = config.name; } public static unregister(name:string) { Assert.isString(name); Assert.isNotUndefined(Component.configMap[name]); delete Component.ctorMap[name]; delete Component.configMap[name]; } /** * create component by it's registed name. * @param name the component name * @returns {WOZLLA.Component} */ public static create(name:string):WOZLLA.Component { Assert.isString(name); var ctor:Function = Component.ctorMap[name]; Assert.isFunction(ctor); return <WOZLLA.Component>new (<any>ctor)(); } public static getConfig(name:any):any { var config:any; Assert.isNotUndefined(name); if(typeof name === 'function') { name = Component.getName(name); } config = Component.configMap[name]; Assert.isNotUndefined(config); return config; } public static extendConfig(Type:Function):any { var name = Component.getName(Type); return { group: name, properties: Component.getConfig(name).properties }; } } }
zzm2q/WOZLLA.js
src/ui/StateWidget.ts
<reponame>zzm2q/WOZLLA.js<gh_stars>0 /// <reference path="../core/Component.ts"/> /// <reference path="../utils/StateMachine.ts"/> /// <reference path="../component/renderer/SpriteRenderer.ts"/> module WOZLLA.ui { var StateMachine = WOZLLA.utils.StateMachine; /** * @class WOZLLA.ui.StateWidget * @protected */ export class StateWidget extends WOZLLA.component.SpriteRenderer { _stateMachine:WOZLLA.utils.StateMachine = new WOZLLA.utils.StateMachine(); constructor() { super(); this.initStates(); } init():void { this._stateMachine.addListener(StateMachine.INIT, (e) => this.onStateChange(e)); this._stateMachine.addListener(StateMachine.CHANGE, (e) => this.onStateChange(e)); this._stateMachine.init(); super.init(); } protected initStates():void { } protected getStateSpriteName(state:string):string { return this._stateMachine.getStateData(state, 'spriteName'); } protected setStateSpriteName(state:string, spriteName:string) { this._stateMachine.setStateData(state, 'spriteName', spriteName); } protected onStateChange(e) { this.spriteName = this.getStateSpriteName(e.data.state); } } }
zzm2q/WOZLLA.js
src/core/Collider.ts
<filename>src/core/Collider.ts /// <reference path="Component.ts"/> module WOZLLA { /** * abstract base class for all colliders * @class WOZLLA.Collider * @extends WOZLLA.Component * @abstract */ export class Collider extends Component { /** * @method {boolean} containsXY * @param localX x coords relate to the gameObject of this collider * @param localY y coords relate to the gameObject of this collider * @returns {boolean} */ collideXY(localX:number, localY:number):boolean { return false; } collide(collider:Collider):boolean { return false; } } }
zzm2q/WOZLLA.js
src/event/Event.ts
module WOZLLA.event { /** * @enum {number} WOZLLA.event.EventPhase * all enumerations of event phase */ export enum EventPhase { /** @property {number} [CAPTURE] */ CAPTURE, /** @property {number} [BUBBLE] */ BUBBLE, /** @property {number} [TARGET] */ TARGET } /** * @class WOZLLA.event.Event * Base class for all event object of WOZLLA engine. <br/> * see also: <br/> * {@link WOZLLA.event.EventPhase} <br/> * {@link WOZLLA.event.EventDispatcher} <br/> */ export class Event { /** * event data. * @member WOZLLA.event.Event * @property {any} data * @readonly */ public get data():any { return this._data; } /** * event type. * @member WOZLLA.event.Event * @property {string} type * @readonly */ get type():string { return this._type; } /** * event origin target. * @member WOZLLA.event.Event * @property {WOZLLA.event.EventDispatcher} target * @readonly */ get target():EventDispatcher { return this._target; } /** * current event target in event bubbling. * @member WOZLLA.event.Event * @property {WOZLLA.event.EventDispatcher} currentTarget * @readonly */ get currentTarget():EventDispatcher { return this._currentTarget; } /** * which phase this event is in. * @member WOZLLA.event.Event * @property {WOZLLA.event.EventPhase} eventPhase * @readonly */ get eventPhase():EventPhase { return this._eventPhase; } /** * true to identify this event could be bubbled, false otherwise. * @member WOZLLA.event.Event * @property {boolean} bubbles * @readonly */ get bubbles():boolean { return this._bubbles; } /** * true to identify this event could be stop bubbles, false otherwise. * @member WOZLLA.event.Event * @property {boolean} canStopBubbles * @readonly */ get canStopBubbles():boolean { return this._canStopBubbles; } _type:string; _target:EventDispatcher; _currentTarget:EventDispatcher; _data:any; _bubbles:boolean; _canStopBubbles:boolean; _eventPhase:EventPhase = EventPhase.CAPTURE; _immediatePropagationStoped:boolean = false; _propagationStoped:boolean = false; _listenerRemove:boolean = false; /** * @method constructor * create a new Event object * @member WOZLLA.event.Event * @param {string} type * @param {boolean} bubbles * @param {any} data * @param {boolean} canStopBubbles */ constructor(type:string, bubbles:boolean=false, data:any=null, canStopBubbles:boolean=true) { this._type = type; this._bubbles = bubbles; this._data = data; this._canStopBubbles = canStopBubbles; } /** * @method isStopPropagation * @member WOZLLA.event.Event * @returns {boolean} */ isStopPropagation():boolean { return this._propagationStoped; } /** * stop bubble to next parent * @method stopPropagation * @member WOZLLA.event.Event */ stopPropagation() { if(!this._canStopBubbles) { return; } this._propagationStoped = true; } /** * @method isStopImmediatePropagation * @member WOZLLA.event.Event * @returns {boolean} */ isStopImmediatePropagation():boolean { return this._immediatePropagationStoped; } /** * stop event bubble immediately even other listeners dosen't receive this event. * @method stopImmediatePropagation * @member WOZLLA.event.Event */ stopImmediatePropagation() { if(!this._canStopBubbles) { return; } this._immediatePropagationStoped = true; this._propagationStoped = true; } /** * call from current listener to remove the current listener */ removeCurrentListener() { this._listenerRemove = true; } } }
zzm2q/WOZLLA.js
src/math/Matrix.ts
module WOZLLA.math { /** * @class WOZLLA.math.Matrix * a util class for 2d matrix */ export class Matrix { /** * @property DEG_TO_RAD * @member WOZLLA.math.Matrix * @readonly * @static */ public static DEG_TO_RAD = Math.PI/180; public values:Float32Array; constructor() { /** * get values of this matrix * @property {Float32Array} values * @readonly */ this.values = new Float32Array(9); this.identity(); } /** * apply from another matrix * @param matrix */ applyMatrix(matrix:Matrix) { this.values.set(matrix.values); } /** * identify this matrix */ identity() { this.values[0] = 1; // a this.values[1] = 0; // b this.values[2] = 0; this.values[3] = 0; // c this.values[4] = 1; // d this.values[5] = 0; this.values[6] = 0; // tx this.values[7] = 0; // ty this.values[8] = 1; } /** * invert this matrix */ invert() { var a1 = this.values[0]; var b1 = this.values[1]; var c1 = this.values[3]; var d1 = this.values[4]; var tx1 = this.values[6]; var ty1 = this.values[7]; var n = a1*d1-b1*c1; this.values[0] = d1/n; this.values[1] = -b1/n; this.values[3] = -c1/n; this.values[4] = a1/n; this.values[6] = (c1*ty1-d1*tx1)/n; this.values[7] = -(a1*ty1-b1*tx1)/n; } /** * prepend 2d params to this matrix * @param a * @param b * @param c * @param d * @param tx * @param ty */ prepend(a:number, b:number, c:number, d:number, tx:number, ty) { var a1, b1, c1, d1; var values = this.values; var tx1 = values[6]; var ty1 = values[7]; if (a != 1 || b != 0 || c != 0 || d != 1) { a1 = values[0]; b1 = values[1]; c1 = values[3]; d1 = values[4]; values[0] = a1*a+b1*c; values[1] = a1*b+b1*d; values[3] = c1*a+d1*c; values[4] = c1*b+d1*d; } values[6] = tx1*a+ty1*c+tx; values[7] = tx1*b+ty1*d+ty; } /** * append 2d params to this matrix * @param a * @param b * @param c * @param d * @param tx * @param ty */ append(a:number, b:number, c:number, d:number, tx:number, ty) { var a1, b1, c1, d1; var values = this.values; a1 = values[0]; b1 = values[1]; c1 = values[3]; d1 = values[4]; values[0] = a*a1+b*c1; values[1] = a*b1+b*d1; values[3] = c*a1+d*c1; values[4] = c*b1+d*d1; values[6] = tx*a1+ty*c1+values[6]; values[7] = tx*b1+ty*d1+values[7]; } /** * prepend 2d transform params to this matrix * @param x * @param y * @param scaleX * @param scaleY * @param rotation * @param skewX * @param skewY * @param regX * @param regY * @returns {WOZLLA.math.Matrix} */ prependTransform(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { if (rotation%360) { var r = rotation*Matrix.DEG_TO_RAD; var cos = Math.cos(r); var sin = Math.sin(r); } else { cos = 1; sin = 0; } if (regX || regY) { this.values[6] -= regX; this.values[7] -= regY; } if (skewX || skewY) { skewX *= Matrix.DEG_TO_RAD; skewY *= Matrix.DEG_TO_RAD; this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); this.prepend(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); } else { this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); } return this; } /** * append 2d transform params to this matrix * @param x * @param y * @param scaleX * @param scaleY * @param rotation * @param skewX * @param skewY * @param regX * @param regY * @returns {WOZLLA.math.Matrix} */ appendTransform(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { if (rotation%360) { var r = rotation*Matrix.DEG_TO_RAD; var cos = Math.cos(r); var sin = Math.sin(r); } else { cos = 1; sin = 0; } if (skewX || skewY) { skewX *= Matrix.DEG_TO_RAD; skewY *= Matrix.DEG_TO_RAD; this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); } else { this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); } if (regX || regY) { // prepend the registration offset: this.values[6] -= regX*this.values[0]+regY*this.values[3]; this.values[7] -= regX*this.values[1]+regY*this.values[4]; } return this; } } }
zzm2q/WOZLLA.js
src/renderer/internal/Renderer.ts
/// <reference path="LayerManager.ts"/> /// <reference path="../BlendType.ts"/> /// <reference path="MaterialManager.ts"/> /// <reference path="ShaderManager.ts"/> /// <reference path="TextureManager.ts"/> module WOZLLA.renderer { export class Renderer implements IRenderer { public static MAX_QUAD_SIZE = 500; get layerManager():ILayerManager { return this._layerManager; } get materialManager():IMaterialManager { return this._materialManager; } get shaderManager():IShaderManager { return this._shaderManager; } get textureManager():ITextureManager { return this._textureManager; } get gl():any { return this._gl; } get viewport():any { return this._viewport; } _gl; _viewport; _layerManager:LayerManager; _materialManager:IMaterialManager; _shaderManager:IShaderManager; _textureManager:ITextureManager; _commandQueueMap:any = {}; _blendModes:any = {}; _usingMaterial:IMaterial; _usingTexture:ITexture; _uniforms:any = {}; private _quadBatch:QuadBatch; constructor(gl, viewport) { this._gl = gl; this._viewport = viewport; this._blendModes[BlendType.NORMAL] = new BlendType(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); this._blendModes[BlendType.ADD] = new BlendType(gl.SRC_ALPHA, gl.DST_ALPHA); this._blendModes[BlendType.MULTIPLY] = new BlendType(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA); this._blendModes[BlendType.SCREEN] = new BlendType(gl.SRC_ALPHA, gl.ONE); this._layerManager = new LayerManager(); this._materialManager = new MaterialManager(); this._shaderManager = new ShaderManager(gl); this._textureManager = new TextureManager(gl); this._quadBatch = new QuadBatch(gl); this._uniforms.projection = { x: viewport.width/2, y: -viewport.height/2 }; gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.enable(gl.BLEND); } addCommand(command:IRenderCommand) { var layer = command.layer; var commandQueue = this._commandQueueMap[layer]; if(!commandQueue) { commandQueue = this._commandQueueMap[layer] = new CommandQueue(layer); } commandQueue.add(command); } render():void { var lastCommand; var currentTexture; var currentMaterial; var gl = this._gl; gl.viewport(0, 0, this._viewport.width, this._viewport.height); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); this._eachCommand((command) => { var quadCommand; var customCommand; if(!lastCommand) { this.flush(); } else if(lastCommand instanceof CustomCommand) { this.flush(); } else if(command instanceof CustomCommand) { this.flush(); } else if((<QuadCommand>command).materialId !== currentMaterial.id) { this.flush(); } else if((<QuadCommand>command).texture !== currentTexture) { this.flush(); } if(command instanceof CustomCommand) { customCommand = <CustomCommand>command; customCommand.execute(this); } else { quadCommand = <QuadCommand>command; if(this._quadBatch.canFill(quadCommand.quad)) { this._quadBatch.fillQuad(quadCommand.quad); } else { this.flush(); this._quadBatch.fillQuad(quadCommand.quad); } } this._usingMaterial = currentMaterial = this._materialManager.getMaterial(command.materialId); this._usingTexture = currentTexture = command.texture; lastCommand = command; }); if(lastCommand) { this.flush(); this._clearCommands(); this._usingTexture = null; this._usingMaterial = null; } } flush():void { var gl, shaderProgram; if(!this._usingMaterial) { return; } gl = this._gl; shaderProgram = this._shaderManager.getShaderProgram(this._usingMaterial.shaderProgramId); shaderProgram.useProgram(gl); shaderProgram.syncUniforms(gl, this._uniforms); this._blendModes[this._usingMaterial.blendType].applyBlend(gl); if(this._usingTexture) { this._usingTexture.bind(gl); } this._quadBatch.flush(gl); } _clearCommands() { var commandQueueMap = this._commandQueueMap; for(var layer in commandQueueMap) { commandQueueMap[layer].clear(); } } _eachCommand(func:Function) { var i, len, j, len2; var layer; var commandQueue; var zQueue; var command; var commandQueueMap = this._commandQueueMap; var layers = this._layerManager._getSortedLayers(); for(i=0,len=layers.length; i<len; i++) { layer = layers[i]; commandQueue = commandQueueMap[layer]; if(commandQueue) { zQueue = commandQueue.negativeZQueue; if(zQueue.length > 0) { for(j=0, len2=zQueue.length; j<len2; j++) { command = zQueue[j]; func(command); } } zQueue = commandQueue.zeroZQueue; if(zQueue.length > 0) { for(j=0, len2=zQueue.length; j<len2; j++) { command = zQueue[j]; func(command); } } zQueue = commandQueue.positiveZQueue; if(zQueue.length > 0) { for(j=0, len2=zQueue.length; j<len2; j++) { command = zQueue[j]; func(command); } } } } } } function compareCommandByGlobalZ(a, b) { if(a.globalZ === b.globalZ) { return a._addIndex - b._addIndex; } return a.globalZ - b.globalZ; } class CommandQueue { _addIndex = 0; layer:string; public negativeZQueue = []; public zeroZQueue = []; public positiveZQueue = []; constructor(layer) { this.layer = layer; } add(command:IRenderCommand) { command._addIndex = this._addIndex++; if(command.globalZ === 0) { this.zeroZQueue.push(command); } else if(command.globalZ > 0) { this.positiveZQueue.push(command); } else { this.negativeZQueue.push(command); } } clear() { var i, len, command; for(i=0,len=this.negativeZQueue.length; i<len; i++) { command = this.negativeZQueue[i]; if(command.isPoolable) { command.release(); } } for(i=0,len=this.zeroZQueue.length; i<len; i++) { command = this.zeroZQueue[i]; if(command.isPoolable) { command.release(); } } for(i=0,len=this.positiveZQueue.length; i<len; i++) { command = this.positiveZQueue[i]; if(command.isPoolable) { command.release(); } } this.negativeZQueue.length = 0; this.zeroZQueue.length = 0; this.positiveZQueue.length = 0; this._addIndex = 0; } sort() { this.positiveZQueue.sort(compareCommandByGlobalZ); this.negativeZQueue.sort(compareCommandByGlobalZ); } } class QuadBatch { private _gl; private _size = Renderer.MAX_QUAD_SIZE; private _vertices; private _indices; private _vertexBuffer; get vertexBuffer() { return this._vertexBuffer; } private _indexBuffer; get indexBuffer() { return this._indexBuffer; } private _curVertexIndex:number = 0; private _curBatchSize = 0; constructor(gl) { this._gl = gl; this._initBuffers(); } canFill(quad:Quad):boolean { return this._curVertexIndex < this._size; } fillQuad(quad:Quad):void { var vertexIndex, storage; var vertices = this._vertices; vertexIndex = this._curVertexIndex; if(quad.count === quad.renderCount) { vertices.set(quad.storage, vertexIndex); } else { var j = 0; var i = quad.renderOffset * quad.type.size; var len = quad.renderCount * quad.type.size; storage = quad.storage; for(; j<len; i++,j++) { vertices[vertexIndex+j] = storage[i]; } } this._curVertexIndex += quad.renderCount * quad.type.size; this._curBatchSize += quad.renderCount; } flush(gl):void { if (this._curBatchSize === 0) { return; } gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); gl.drawElements(gl.TRIANGLES, this._curBatchSize * 6, gl.UNSIGNED_SHORT, 0); this._curVertexIndex = 0; this._curBatchSize = 0; } _initBuffers() { var i, j; var gl = this._gl; var numVerts = this._size * 4 * 6; var numIndices = this._size * 6; this._vertices = new Float32Array(numVerts); this._indices = new Uint16Array(numIndices); for (i=0, j=0; i < numIndices; i += 6, j += 4) { this._indices[i ] = j; this._indices[i + 1] = j + 1; this._indices[i + 2] = j + 2; this._indices[i + 3] = j; this._indices[i + 4] = j + 2; this._indices[i + 5] = j + 3; } // create a couple of buffers this._vertexBuffer = gl.createBuffer(); this._indexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); } } }
zzm2q/WOZLLA.js
src/renderer/internal/TextureManager.ts
/// <reference path="Texture.ts"/> module WOZLLA.renderer { function isPowerOf2(num) { return (num & (num - 1)) === 0; } /** * @class WOZLLA.renderer.TextureManager * @extends WOZLLA.renderer.ITextureManager */ export class TextureManager implements ITextureManager { _gl:any; _textureMap:any; constructor(gl) { this._gl = gl; this._textureMap = {}; } getTexture(id) { return this._textureMap[id]; } generateTexture(descriptor:ITextureDescriptor, textureId?):ITexture { var texture; var pvrtcExt:any; var compressedType; var gl = this._gl; var id = textureId || gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, id); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); if(isPowerOf2(descriptor.width) && isPowerOf2(descriptor.height)) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); } else { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } switch(descriptor.textureFormat) { case TextureFormat.PNG: case TextureFormat.JPEG: gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, descriptor.source); break; case TextureFormat.PVR: switch(descriptor.pixelFormat) { case PixelFormat.PVRTC2: pvrtcExt = WebGLExtension.getExtension(gl, WebGLExtension.PVRTC); compressedType = pvrtcExt.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; break; case PixelFormat.PVRTC4: pvrtcExt = WebGLExtension.getExtension(gl, WebGLExtension.PVRTC); compressedType = pvrtcExt.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; break; default: throw new Error('Unsupported pixel format: ' + descriptor.pixelFormat); } gl.compressedTexImage2D(gl.TEXTURE_2D, 0, compressedType, descriptor.width, descriptor.height, 0, descriptor.source); break; default: throw new Error('Unsupported texture format: ' + descriptor.textureFormat); } texture = new Texture(id, descriptor); this._textureMap[id] = texture; return texture; } updateTexture(texture:ITexture):void { this.generateTexture(texture.descriptor, texture.id); } deleteTexture(texture:ITexture):void { this._gl.deleteTexture(texture.id); delete this._textureMap[texture.id]; } clear():void { for(var id in this._textureMap) { this.deleteTexture(this._textureMap[id]); } } } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/Adapter.ts
<filename>extensions/PureMVC/view/Adapter.ts ///<reference path='AdapterView.ts'/> ///<reference path='../model/Model.ts'/> module WOZLLA.PureMVC { export class Adapter { _adapterView:AdapterView; setAdapterView(view:AdapterView) { this._adapterView = view; } getCount():number { return 0; } getItem(index:any):Model { return null; } getView(index:any, callback:(view:SimpleView) => void) { } onStoreBind(store:Store, callback?:Function) { console.log('onbind', store, callback); callback && callback(); } onStoreUnbind(store:Store) { } } }
zzm2q/WOZLLA.js
src/assets/GLTextureAsset.ts
/// <reference path="Asset.ts"/> /// <reference path="../renderer/ITexture.ts"/> /// <reference path="../renderer/IRenderer.ts"/> /// <reference path="../core/Director.ts"/> module WOZLLA.assets { /** * internal class * @class WOZLLA.assets.GLTextureAsset * @extends WOZLLA.assets.Asset * @abstract */ export class GLTextureAsset extends Asset { get glTexture() { return this._glTexture; } _glTexture:WOZLLA.renderer.ITexture; _generateTexture(image:HTMLImageElement):void { var renderer:WOZLLA.renderer.IRenderer = Director.getInstance().renderer; if(!renderer) { throw new Error("Director not initialized"); } this._glTexture = renderer.textureManager.generateTexture(new HTMLImageDescriptor(image)); } _generatePVRTexture(pvrSource:any):void { throw new Error("Unsupported now"); } } export class HTMLImageDescriptor implements WOZLLA.renderer.ITextureDescriptor { get width():number { return this._source.width; } get height():number { return this._source.height; } get source():any { return this._source; } get textureFormat():WOZLLA.renderer.TextureFormat { return this._textureFormat; } get pixelFormat():WOZLLA.renderer.PixelFormat { return this._pixelFormat; } _source; _textureFormat:WOZLLA.renderer.TextureFormat; _pixelFormat:WOZLLA.renderer.PixelFormat; constructor(source) { this._source = source; this._textureFormat = WOZLLA.renderer.TextureFormat.PNG; this._pixelFormat = WOZLLA.renderer.PixelFormat.RGBA8888; } } export class PVRDescriptor implements WOZLLA.renderer.ITextureDescriptor { get width():number { return this._source.width; } get height():number { return this._source.height; } get source():any { return this._source; } get textureFormat():WOZLLA.renderer.TextureFormat { return this._textureFormat; } get pixelFormat():WOZLLA.renderer.PixelFormat { return this._pixelFormat; } _source; _textureFormat:WOZLLA.renderer.TextureFormat; _pixelFormat:WOZLLA.renderer.PixelFormat; constructor(source, pixelFormat:WOZLLA.renderer.PixelFormat) { this._source = source; this._textureFormat = WOZLLA.renderer.TextureFormat.PVR; this._pixelFormat = pixelFormat; } } }
zzm2q/WOZLLA.js
src/renderer/internal/Material.ts
<reponame>zzm2q/WOZLLA.js module WOZLLA.renderer { /** * @class WOZLLA.renderer.Material * @extends WOZLLA.renderer.IMaterial */ export class Material implements IMaterial { get id():any { return this._id; } get shaderProgramId():string { return this._shaderProgramId; } get blendType():number { return this._blendType; } _id:any; _shaderProgramId:string; _blendType:number; constructor(id, shaderProgramId:string, blendType:number) { this._id = id; this._shaderProgramId = shaderProgramId; this._blendType = blendType; } equals(other:IMaterial):boolean { return other.blendType === this._blendType && other.shaderProgramId === this._shaderProgramId; } } }
zzm2q/WOZLLA.js
src/component/renderer/NinePatchRenderer.ts
<filename>src/component/renderer/NinePatchRenderer.ts<gh_stars>0 /// <reference path="SpriteRenderer.ts"/> module WOZLLA.component { var QuadCommand = WOZLLA.renderer.QuadCommand; /** * @class WOZLLA.component.NinePatchRenderer */ export class NinePatchRenderer extends SpriteRenderer { get renderRegion():WOZLLA.math.Rectangle { return this._renderRegion; } set renderRegion(value:WOZLLA.math.Rectangle) { this._renderRegion = value; } get patch():WOZLLA.math.Rectangle { return this._patch; } set patch(value:WOZLLA.math.Rectangle) { this._patch = value; this._quadVertexDirty = true; } _patch:WOZLLA.math.Rectangle; _renderRegion:WOZLLA.math.Rectangle; _initQuad() { this._quad = new WOZLLA.renderer.Quad(9); } _updateNinePatchQuads() { this._updateNinePatchQuadVertices(); this._updateNinePatchQuadAlpha(); this._updateNinePatchQuadColor(); this._textureUpdated = false; } _updateNinePatchQuadVertices() { var transform = new WOZLLA.Transform(); var frame = this._getTextureFrame(); var patchUVS:any; var patchOffset = { x:0, y: 0 }; var patch = this._patch || new WOZLLA.math.Rectangle(0, 0, frame.width, frame.height); var region = this._renderRegion || patch; function getPatchUVS(patchFrame, texture) { var tw = texture.descriptor.width; var th = texture.descriptor.height; var patchUVS:any = {}; patchUVS.x0 = patchFrame.x / tw; patchUVS.y0 = patchFrame.y / th; patchUVS.x1 = (patchFrame.x + patchFrame.width) / tw; patchUVS.y1 = patchFrame.y / th; patchUVS.x2 = (patchFrame.x + patchFrame.width) / tw; patchUVS.y2 = (patchFrame.y + patchFrame.height) / th; patchUVS.x3 = patchFrame.x / tw; patchUVS.y3 = (patchFrame.y + patchFrame.height) / th; return patchUVS; } var patches = [{ // left top frame: { x : frame.x, y : frame.y, width: patch.left, height: patch.top }, pos : { x: region.x, y: region.y }, size: { width: 1, height: 1 } }, { // left center frame: { x : frame.x + patch.left, y : frame.y , width: patch.width, height: patch.top }, pos : { x: region.x + patch.left, y: region.y }, size : { width: (region.width - (patch.right-patch.width)) / patch.width, height: 1 } }, { // right top frame: { x : frame.x + patch.right, y : frame.y , width: frame.width - patch.right, height: patch.top }, pos: { x : region.right, y : region.y }, size : { width: 1, height: 1 } }, { // left middle frame: { x : frame.x, y : frame.y + patch.top, width: patch.left, height: patch.height }, pos: { x : region.x, y : region.y + patch.top }, size : { width: 1, height: (region.height - (patch.bottom - patch.height)) / patch.height } }, { // center middle frame: { x : frame.x + patch.left, y : frame.y + patch.top, width: patch.width, height: patch.height }, pos: { x : region.x + patch.left, y : region.y + patch.top }, size : { width: (region.width - (patch.right - patch.width)) / patch.width, height: (region.height - (patch.bottom - patch.height)) / patch.height } }, { // right middle frame: { x : frame.x + patch.right, y : frame.y + patch.top, width: frame.width - patch.right, height: patch.height }, pos: { x : region.right, y : region.y + patch.top }, size : { width: 1, height: (region.height - (patch.bottom - patch.height)) / patch.height } }, { // left bottom frame: { x : frame.x, y : frame.y + patch.bottom, width: frame.width - patch.right, height: frame.height - patch.bottom }, pos: { x : region.x, y : region.bottom }, size : { width: 1, height: 1 } }, { // center bottom frame: { x : frame.x + patch.left, y : frame.y + patch.bottom, width: patch.width, height: frame.height - patch.bottom }, pos: { x : region.x + patch.left, y : region.bottom }, size : { width: (region.width - (patch.right - patch.width)) / patch.width, height: 1 } }, { // right bottom frame: { x : frame.x + patch.right, y : frame.y + patch.bottom, width: frame.width - patch.right, height: frame.height - patch.bottom }, pos: { x : region.right, y : region.bottom }, size : { width: 1, height: 1 } }]; for(var i=0, p; i<9; i++) { p = patches[i]; if(p.frame.width > 0 && p.frame.height > 0) { patchUVS = getPatchUVS(p.frame, this._texture); transform.set(this.gameObject.transform); transform.x += p.pos.x; transform.y += p.pos.y; transform.setScale(p.size.width, p.size.height); transform.updateWorldMatrix(); this._updateQuadVerticesByArgs(patchUVS, p.frame, patchOffset, transform.worldMatrix, i); } else { this._clearQuadVertices(i); } } this._quadVertexDirty = false; } _updateNinePatchQuadAlpha() { for(var i=0; i<9; i++) { this._updateQuadAlpha(i); } this._quadAlphaDirty = false; } _updateNinePatchQuadColor() { for(var i=0; i<9; i++) { this._updateQuadColor(i); } this._quadColorDirty = false; } render(renderer:WOZLLA.renderer.IRenderer, flags:number):void { if (!this._texture) { return; } if((flags & GameObject.MASK_TRANSFORM_DIRTY) === GameObject.MASK_TRANSFORM_DIRTY) { this._quadVertexDirty = true; } if (this._textureUpdated) { this._updateNinePatchQuads(); } if (this._quadVertexDirty) { this._updateNinePatchQuadVertices(); this._quadVertexDirty = false; } if (this._quadAlphaDirty) { this._updateNinePatchQuadAlpha(); } if (this._quadColorDirty) { this._updateNinePatchQuadColor(); } renderer.addCommand(QuadCommand.init( this._quadGlobalZ, this._quadLayer, this._texture, this._quadMaterialId, this._quad)); } } Component.register(NinePatchRenderer, { name: "NinePatchRenderer", properties: [ Component.extendConfig(SpriteRenderer), { name: 'patch', type: 'rect', defaultValue: [0, 0, 0, 0], convert: PropertyConverter.array2rect }, { name: 'renderRegion', type: 'rect', defaultValue: [0, 0, 0, 0], convert: PropertyConverter.array2rect }] }); }
zzm2q/WOZLLA.js
src/utils/Assert.ts
<filename>src/utils/Assert.ts module WOZLLA { export class Assert { public static DEFAULT_MESSAGE = 'Assertion Fail'; public static isTrue(test:any, msg=Assert.DEFAULT_MESSAGE) { if(test !== true) { throw new Error(msg); } } public static isFalse(test:any, msg=Assert.DEFAULT_MESSAGE) { if(test !== false) { throw new Error(msg); } } public static isTypeof(test:any, type:string, msg=Assert.DEFAULT_MESSAGE) { if(typeof test !== type) { throw new Error(msg); } } public static isNotTypeof(test:any, type:string, msg=Assert.DEFAULT_MESSAGE) { if(typeof test === type) { throw new Error(msg); } } public static isString(test:any, msg=Assert.DEFAULT_MESSAGE) { Assert.isTypeof(test, 'string', msg); } public static isObject(test:any, msg=Assert.DEFAULT_MESSAGE) { Assert.isTypeof(test, 'object', msg); } public static isUndefined(test:any, msg=Assert.DEFAULT_MESSAGE) { Assert.isTypeof(test, 'undefined', msg); } public static isNotUndefined(test:any, msg=Assert.DEFAULT_MESSAGE) { Assert.isNotTypeof(test, 'undefined', msg); } public static isFunction(test:any, msg=Assert.DEFAULT_MESSAGE) { Assert.isTypeof(test, 'function', msg); } } }
zzm2q/WOZLLA.js
src/assets/JSONAsset.ts
/// <reference path="Asset.ts"/> /// <reference path="../utils/Ajax.ts"/> module WOZLLA.assets { function deepCopyJSON(o) { var copy = o,k; if (o && typeof o === 'object') { copy = Object.prototype.toString.call(o) === '[object Array]' ? [] : {}; for (k in o) { copy[k] = deepCopyJSON(o[k]); } } return copy; } export class JSONAsset extends Asset { _data:any; cloneData():any { if(!this._data) { return this._data; } return deepCopyJSON(this._data); } load(onSuccess:()=>any, onError:(error)=>any) { WOZLLA.utils.Ajax.request({ url: this.fullPath, dataType: 'json', success: (data) => { this._data = data; onSuccess(); }, error: function(error) { onError(error); } }); } unload() { this._data = null; super.unload(); } } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/SimpleBinder.ts
<filename>extensions/PureMVC/view/SimpleBinder.ts ///<reference path='../../../src/utils/Assert.ts'/> ///<reference path='../../../../WOZLLA.js/src/core/GameObject.ts'/> module WOZLLA.PureMVC { var Assert = WOZLLA.Assert; var helpRecord:WOZLLA.QueryRecord = new WOZLLA.QueryRecord(); export class SimpleBinder { _view:SimpleView; _config:any; _queryCache:any = {}; constructor(simpleView:SimpleView, config:any) { this._view = simpleView; this._config = config; for(var attrName in config) { var attrConfig = config[attrName]; if(typeof attrConfig === 'string') { config[attrName] = { bind: attrConfig, cache: true }; } } } syncAttr(name) { var target; var targetAttrName; var model = this._view.model; var attrConfig = this._config[name]; // get model value var getter = attrConfig.model && attrConfig.model.getter; var value; if(model) { if(getter) { value = getter(model); } else { value = model.get(name); } } // query bind target var cacheData; var cache = attrConfig.cache !== false; var bind = attrConfig.bind; if(cache) { cacheData = this._queryCache[bind]; target = cacheData && cacheData.target; targetAttrName = cacheData && cacheData.attrName; } if(!target) { var gameObj = this._view.gameObject; var queryRecord = helpRecord; queryRecord.target = null; gameObj.query(bind, queryRecord); Assert.isNotUndefined(queryRecord.target, 'Can\'t found "' + bind + '" for binding.'); target = queryRecord.target; targetAttrName = queryRecord.attrName; if (cache) { this._queryCache[bind] = { target: target, attrName: targetAttrName }; } } // apply model value to view target[targetAttrName] = value; target.loadAssets(); } onModelFieldChange(e) { this.syncAttr(e.data.field); } onModelBind(model:Model) { this.syncAll(); } onModelUnbind(model:Model) { this.syncAll(); } syncAll() { var config = this._config; for(var attrName in config) { this.syncAttr(attrName); } } } }
zzm2q/WOZLLA.js
src/component/renderer/QuadRenderer.ts
/// <reference path="../../core/Renderer.ts"/> /// <reference path="../../renderer/IRenderer.ts"/> /// <reference path="../../renderer/ILayerManager.ts"/> /// <reference path="../../renderer/QuadCommand.ts"/> module WOZLLA.component { var QuadCommand = WOZLLA.renderer.QuadCommand; /** * @class WOZLLA.component.QuadRenderer * @abstract */ export class QuadRenderer extends WOZLLA.Renderer { _quad:WOZLLA.renderer.Quad; _quadLayer:string = WOZLLA.renderer.ILayerManager.DEFAULT; _quadMaterialId:string = WOZLLA.renderer.IMaterial.DEFAULT; _quadGlobalZ:number = 0; _quadAlpha:number = 1; _quadColor:number = 0xFFFFFF; _quadVertexDirty:boolean = true; _quadAlphaDirty:boolean = true; _quadColorDirty:boolean = true; _texture:WOZLLA.renderer.ITexture; _textureOffset:any; _textureFrame:any; _textureUVS:any; _textureUpdated:boolean = false; setQuadRenderRange(offset:number, count:number) { this._quad.setRenderRange(offset, count); } setQuadGlobalZ(globalZ:number) { this._quadGlobalZ = globalZ; } setQuadLayer(layer:string) { this._quadLayer = layer; } setQuadMaterialId(materialId:string) { this._quadMaterialId = materialId; } setQuadAlpha(alpha:number) { this._quadAlpha = alpha; this._quadAlphaDirty = true; } setQuadColor(color:number) { this._quadColor = color; this._quadColorDirty = true; } setTexture(texture:WOZLLA.renderer.ITexture) { this._texture = texture; this._textureUVS = null; this._textureUpdated = true; } setTextureFrame(frame) { this._textureFrame = frame; this._textureUVS = null; this._textureUpdated = true; } setTextureOffset(offset) { this._textureOffset = offset; this._textureUpdated = true; } init():void { this._initQuad(); super.init(); } render(renderer:WOZLLA.renderer.IRenderer, flags:number):void { if (!this._texture) { return; } if((flags & GameObject.MASK_TRANSFORM_DIRTY) === GameObject.MASK_TRANSFORM_DIRTY) { this._quadVertexDirty = true; } if (this._textureUpdated) { this._updateQuad(); } if (this._quadVertexDirty) { this._updateQuadVertices(); this._quadVertexDirty = false; } if (this._quadAlphaDirty) { this._updateQuadAlpha(); } if (this._quadColorDirty) { this._updateQuadColor(); } renderer.addCommand(QuadCommand.init( this._quadGlobalZ, this._quadLayer, this._texture, this._quadMaterialId, this._quad)); } _initQuad():void { this._quad = new WOZLLA.renderer.Quad(1); } _getTextureFrame() { return this._textureFrame || { x: 0, y: 0, width: this._texture.descriptor.width, height: this._texture.descriptor.height }; } _getTextureOffset() { return this._textureOffset || { x: 0, y: 0 }; } _getTextureUVS() { var tw, th, frame:any, uvs:any; if(this._textureUVS) { return this._textureUVS; } tw = this._texture.descriptor.width; th = this._texture.descriptor.height; frame = this._textureFrame || { x: 0, y: 0, width: tw, height: th }; uvs = {}; uvs.x0 = frame.x / tw; uvs.y0 = frame.y / th; uvs.x1 = (frame.x + frame.width) / tw; uvs.y1 = frame.y / th; uvs.x2 = (frame.x + frame.width) / tw; uvs.y2 = (frame.y + frame.height) / th; uvs.x3 = frame.x / tw; uvs.y3 = (frame.y + frame.height) / th; this._textureUVS = uvs; return uvs; } _updateQuad(quadIndex=0) { this._updateQuadVertices(quadIndex); this._updateQuadAlpha(quadIndex); this._updateQuadColor(quadIndex); this._textureUpdated = false; } _updateQuadVertices(quadIndex=0) { var uvs = this._getTextureUVS(); var frame = this._getTextureFrame(); var offset = this._getTextureOffset(); var matrix = this._gameObject.transform.worldMatrix; this._updateQuadVerticesByArgs(uvs, frame, offset, matrix, quadIndex); this._quadVertexDirty = false; } _updateQuadVerticesByArgs(uvs, frame, offset, matrix, quadIndex=0) { var a = matrix.values[0]; var c = matrix.values[1]; var b = matrix.values[3]; var d = matrix.values[4]; var tx = matrix.values[6]; var ty = matrix.values[7]; var w1 = -offset.x * frame.width; var w0 = w1 + frame.width; var h1 = -offset.y * frame.height; var h0 = h1 + frame.height; var x1 = a * w1 + b * h1 + tx; var y1 = d * h1 + c * w1 + ty; var x2 = a * w0 + b * h1 + tx; var y2 = d * h1 + c * w0 + ty; var x3 = a * w0 + b * h0 + tx; var y3 = d * h0 + c * w0 + ty; var x4 = a * w1 + b * h0 + tx; var y4 = d * h0 + c * w1 + ty; this._quad.setVertices(x1, y1, x2, y2, x3, y3, x4, y4, quadIndex); this._quad.setTexCoords(uvs.x0, uvs.y0, uvs.x1, uvs.y1, uvs.x2, uvs.y2, uvs.x3, uvs.y3, quadIndex); } _clearQuadVertices(quadIndex=0) { this._quad.setVertices(0, 0, 0, 0, 0, 0, 0, 0); this._quad.setTexCoords(0, 0, 0, 0, 0, 0, 0, 0); } _updateQuadAlpha(quadIndex=0) { this._quad.setAlpha(this._quadAlpha, quadIndex); this._quadAlphaDirty = false; } _updateQuadColor(quadIndex=0) { this._quad.setColor(this._quadColor, quadIndex); this._quadColorDirty = false; } } }
zzm2q/WOZLLA.js
src/layout/LayoutBase.ts
module WOZLLA.layout { export class LayoutBase extends Behaviour { private _layoutRequired:boolean = true; init():void { super.init(); this.gameObject.addListenerScope('childadd', this.onChildAdd, this); this.gameObject.addListenerScope('childremove', this.onChildRemove, this); this.requestLayout(); } destroy():void { this.gameObject.removeListenerScope('childadd', this.onChildAdd, this); this.gameObject.removeListenerScope('childremove', this.onChildRemove, this); super.destroy(); } doLayout():void { } requestLayout() { this._layoutRequired = true; } update() { if(this._layoutRequired) { this._layoutRequired = false; this.doLayout(); } } protected onChildAdd(e) { this.requestLayout(); } protected onChildRemove(e) { alert('remove'); this.requestLayout(); } } }
zzm2q/WOZLLA.js
src/component/collider/CircleCollider.ts
<gh_stars>0 /// <reference path="../../core/Collider.ts"/> /// <reference path="../../math/Rectangle.ts"/> module WOZLLA.component { /** * @class WOZLLA.component.CircleCollider */ export class CircleCollider extends WOZLLA.Collider { region:WOZLLA.math.Circle; collideXY(localX:number, localY:number):boolean { return this.region && this.region.containsXY(localX, localY); } collide(collider:Collider):boolean { return false; } } }
zzm2q/WOZLLA.js
src/jsonx/JSONXBuilder.ts
module WOZLLA.jsonx { function emptyCallback(root:WOZLLA.GameObject, done:Function) { done(); } // reference: @src#asGameObject export class JSONXBuilder { public static Factory:Function; public static create():JSONXBuilder { if(JSONXBuilder.Factory) { return <JSONXBuilder>(new (<any>(JSONXBuilder.Factory))()); } return new JSONXBuilder(); } private src; private data; private err; private root:WOZLLA.GameObject; private newCallback:(root:WOZLLA.GameObject, done:Function) => void; private doLoad:boolean = false; private doInit:boolean = false; private loadCallback:(root:WOZLLA.GameObject, done:Function) => void; private async:boolean = true; private uuidMap:any = {}; getByUUID(uuid) { return this.uuidMap[uuid]; } setSync():void { this.async = false; } instantiateWithSrc(src, callback:(root:WOZLLA.GameObject, done:Function) => void = emptyCallback) { this.src = src; this.newCallback = callback; return this; } instantiateWithJSON(data:any, callback:(root:WOZLLA.GameObject, done:Function) => void = emptyCallback) { this.data = data; this.newCallback = callback; return this; } load(callback:(root:WOZLLA.GameObject, done:Function) => void = emptyCallback) { this.doLoad = true; this.loadCallback = callback; return this; } init() { if(this.doLoad) { this.doInit = true; } else { this.err = 'JSONXBuilder: init must after load'; } return this; } build(callback:(error:any, root:WOZLLA.GameObject) => void) { this._loadJSONData(() => { if(this._checkError(callback)) return; this._newGameObjectTree(() => { if(this._checkError(callback)) return; if(!this.doLoad) { callback(this.err, this.root); return; } this.newCallback(this.root, () => { this._loadAssets(() => { if(this._checkError(callback)) return; if(!this.doInit) { callback(this.err, this.root); return; } this._init(); callback(this.err, this.root); }); }); }); }); } protected _checkError(callback:(error:any, root:WOZLLA.GameObject) => void) { if(this.err) { callback(this.err, null); return true; } return false; } protected _loadJSONData(callback:Function) { if(this.src && !this.data) { WOZLLA.utils.Ajax.request({ url: Director.getInstance().assetLoader.getBaseDir() + '/' + this.src, dataType: 'json', async: this.async, withCredentials: true, success: (data) => { this.data = data; callback && callback(); }, error: (err) => { this.err = err; callback && callback() } }); } else { callback && callback(); } } protected _newGameObjectTree(callback:Function) { this._newGameObject(this.data.root, (root:WOZLLA.GameObject) => { this.root = root; callback && callback(); }); } protected _newGameObject(data:any, callback:(gameObj:WOZLLA.GameObject) => void) { var gameObj = new WOZLLA.GameObject(data.rect); gameObj._uuid = data.uuid; this.uuidMap[data.uuid] = gameObj; gameObj.id = data.id; gameObj.name = data.name; gameObj.active = data.active; gameObj.visible = data.visible; gameObj.touchable = data.touchable; gameObj.transform.set(data.transform); var components:Array<any> = data.components; if(components && components.length > 0) { components.forEach((compData:any) => { gameObj.addComponent(this._newComponent(compData, gameObj)); }); } var createdChildCount = 0; var children:Array<any> = data.children; if(!children || children.length === 0) { callback(gameObj); return; } children.forEach((childData:any) => { if(childData.reference) { this._newReferenceObject(childData, (child) => { if(child) { gameObj.addChild(child); } createdChildCount ++; if(createdChildCount === children.length) { callback(gameObj); } }); } else { this._newGameObject(childData, (child) => { gameObj.addChild(child); createdChildCount ++; if(createdChildCount === children.length) { callback(gameObj); } }); } }); } protected _newReferenceObject(data:any, callback:(gameObj:WOZLLA.GameObject) => void) { var builder = new JSONXBuilder(); builder.instantiateWithSrc(data.reference).build((err:any, root:WOZLLA.GameObject) => { if(err) { this.err = err; } else if(root) { root._uuid = data.uuid; this.uuidMap[data.uuid] = root; root.name = data.name; root.id = data.id; root.active = data.active; root.visible = data.visible; root.touchable = data.touchable; root.transform.set(data.transform); } callback(root); }); } protected _newComponent(compData:any, gameObj:WOZLLA.GameObject):WOZLLA.Component { var component = WOZLLA.Component.create(compData.name); var config = WOZLLA.Component.getConfig(compData.name); component._uuid = compData.uuid; this.uuidMap[compData.uuid] = component; component.gameObject = gameObj; this._applyComponentProperties(component, config.properties, compData); return component; } protected _applyComponentProperties(component, properties:any, compData:any) { if(properties && properties.length > 0) { properties.forEach((prop) => { if(prop.group) { this._applyComponentProperties(component, prop.properties, compData); } else if(prop.extend) { var config = Component.getConfig(prop.extend); if(config) { this._applyComponentProperties(component, config.properties, compData); } } else { var value = compData.properties[prop.name]; value = value == void 0 ? prop.defaultValue : value; if (prop.convert && value) { value = prop.convert(value); } component[prop.name] = value; } }); } } protected _loadAssets(callback:Function) { this.root.loadAssets(callback); } protected _init() { this.root.init(); } } }
zzm2q/WOZLLA.js
src/renderer/CustomCommand.ts
/// <reference path="RenderCommandBase.ts"/> /// <reference path="IRenderer.ts"/> module WOZLLA.renderer { /** * @class WOZLLA.renderer.CustomCommand * @extends WOZLLA.renderer.RenderCommandBase */ export class CustomCommand extends RenderCommandBase { constructor(globalZ:number, layer:string) { super(globalZ, layer); } execute(renderer:IRenderer):void { throw new Error('abstract method'); } } }
zzm2q/WOZLLA.js
src/renderer/IMaterialManager.ts
<gh_stars>0 module WOZLLA.renderer { /** * @class WOZLLA.renderer.IMaterialManager * @abstract */ export interface IMaterialManager { createMaterial(id:string, shaderProgramId:string, blendType:number):IMaterial; getMaterial(id:string):IMaterial; deleteMaterial(material:IMaterial):void; clear():void; } export module IMaterialManager { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.IMaterialManager */ export var DOC = 'DOC'; } }
zzm2q/WOZLLA.js
src/renderer/ITexture.ts
module WOZLLA.renderer { /** * @class WOZLLA.renderer.ITexture * @abstract */ export interface ITexture { id:any; descriptor:ITextureDescriptor; bind(gl):void; } export module ITexture { /** * @property DOC * @readonly * @static * @member WOZLLA.renderer.ITexture */ export var DOC = 'DOC'; } }
zzm2q/WOZLLA.js
src/ui/CheckBox.ts
/// <reference path="StateWidget.ts"/> /// <reference path="../component/renderer/SpriteRenderer.ts"/> module WOZLLA.ui { /** * @class WOZLLA.ui.CheckBox */ export class CheckBox extends StateWidget { public static STATE_UNCHECKED = 'unchecked'; public static STATE_CHECKED = 'checked'; public static STATE_DISABLED = 'disabled'; get uncheckedSpriteName():string { return this.getStateSpriteName(CheckBox.STATE_UNCHECKED); } set uncheckedSpriteName(spriteName:string) { this.setStateSpriteName(CheckBox.STATE_UNCHECKED, spriteName); } get disabledSpriteName():string { return this.getStateSpriteName(CheckBox.STATE_DISABLED); } set disabledSpriteName(spriteName:string) { this.setStateSpriteName(CheckBox.STATE_DISABLED, spriteName); } get checkedSpriteName():string { return this.getStateSpriteName(CheckBox.STATE_CHECKED); } set checkedSpriteName(spriteName:string) { this.setStateSpriteName(CheckBox.STATE_CHECKED, spriteName); } init() { this._gameObject.addListener('tap', (e) => this.onTap(e)); super.init(); } destroy() { this._stateMachine.clearAllListeners(); super.destroy(); } isEnabled() { return this._stateMachine.getCurrentState() !== CheckBox.STATE_DISABLED; } setEnabled(enabled:boolean=true) { this._stateMachine.changeState(enabled ? CheckBox.STATE_UNCHECKED : CheckBox.STATE_DISABLED); this._gameObject.touchable = enabled; } protected initStates():void { this._stateMachine.defineState(CheckBox.STATE_UNCHECKED, true); this._stateMachine.defineState(CheckBox.STATE_DISABLED); this._stateMachine.defineState(CheckBox.STATE_CHECKED); } protected onTap(e) { if(this._stateMachine.getCurrentState() === CheckBox.STATE_CHECKED) { this._stateMachine.changeState(CheckBox.STATE_UNCHECKED); } else { this._stateMachine.changeState(CheckBox.STATE_CHECKED); } } } }
zzm2q/WOZLLA.js
src/core/Mask.ts
<gh_stars>0 /// <reference path="Component.ts"/> /// <reference path="../renderer/ILayerManager.ts"/> /// <reference path="../renderer/CustomCommand.ts"/> module WOZLLA { /** * Base class for all mask, mask is based on webgl stencil. * @class WOZLLA.Mask * @extends WOZLLA.Component * @abstract */ export class Mask extends Component { reverse:boolean = false; _startGlobalZ:number = 0; _endGlobalZ:number = 0; _maskLayer:string = WOZLLA.renderer.ILayerManager.DEFAULT; /** * set mask range, mask range is effect on globalZ of render commmand * @param start * @param end * @param layer */ setMaskRange(start:number, end:number, layer:string=WOZLLA.renderer.ILayerManager.DEFAULT) { this._startGlobalZ = start; this._endGlobalZ = end; this._maskLayer = layer; } /** * render this mask * @param renderer * @param flags */ render(renderer:WOZLLA.renderer.IRenderer, flags:number):void { renderer.addCommand(new EnableMaskCommand(this._startGlobalZ, this._maskLayer)); this.renderMask(renderer, flags); renderer.addCommand(new EndMaskCommand(this._startGlobalZ, this._maskLayer, this.reverse)); renderer.addCommand(new DisableMaskCommand(this._endGlobalZ, this._maskLayer)); } /** * do render mask graphics * @param renderer * @param flags */ protected renderMask(renderer:WOZLLA.renderer.IRenderer, flags:number) { } } class EnableMaskCommand extends WOZLLA.renderer.CustomCommand { constructor(globalZ:number, layer:string) { super(globalZ, layer); } execute(renderer:WOZLLA.renderer.IRenderer) { var gl = renderer.gl; gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); gl.colorMask(false, false, false, false); gl.stencilFunc(gl.ALWAYS, 1, 0); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); } } class EndMaskCommand extends WOZLLA.renderer.CustomCommand { private reverse:boolean; constructor(globalZ:number, layer:string, reverse:boolean) { super(globalZ, layer); this.reverse = reverse; } execute(renderer:WOZLLA.renderer.IRenderer) { var gl = renderer.gl; gl.colorMask(true, true, true, true); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); gl.stencilFunc(this.reverse ? gl.NOTEQUAL : gl.EQUAL, 1, 0xFF); } } class DisableMaskCommand extends WOZLLA.renderer.CustomCommand { constructor(globalZ:number, layer:string) { super(globalZ, layer); } execute(renderer:WOZLLA.renderer.IRenderer) { renderer.gl.disable(renderer.gl.STENCIL_TEST); } } }
zzm2q/WOZLLA.js
extensions/PureMVC/Proxy.ts
<gh_stars>0 ///<reference path='../../libs/puremvc-typescript-multicore-1.1.d.ts'/> module WOZLLA.PureMVC { export class Proxy extends puremvc.Proxy { } }
zzm2q/WOZLLA.js
src/core/Behaviour.ts
<reponame>zzm2q/WOZLLA.js /// <reference path="Component.ts"/> module WOZLLA { /** * Abstract base class for all behaviours, the {@link WOZLLA.Behaviour#update} function would be call * by WOZLLA engine every frame when the gameObject is actived and the property enabled of this behaviour is true * @class WOZLLA.Behaviour * @extends WOZLLA.Component * @abstract */ export class Behaviour extends Component { /** * enabled or disabled this behaviour * @property {boolean} [enabled=true] */ enabled:boolean = true; /** * call by Engine every frame * @method update */ update():void {} } }
zzm2q/WOZLLA.js
src/math/Rectangle.ts
module WOZLLA.math { /** * @class WOZLLA.math.Rectangle * a utils class for rectangle, provider some math methods */ export class Rectangle { x: number; y: number; width: number; height: number; /** * @property {number} left x * @readonly */ get left():number { return this.x; } /** * @property {number} right x+width * @readonly */ get right():number { return this.x + this.width; } /** * @property {number} top y * @readonly */ get top():number { return this.y; } /** * @property {number} bottom y+height * @readonly */ get bottom():number { return this.y + this.height; } constructor (x: number, y: number, width: number, height: number) { /** * get or set x * @property {number} x */ this.x = x; /** * get or set y * @property {number} y */ this.y = y; /** * get or set width * @property {number} width */ this.width = width; /** * get or set height * @property {number} height */ this.height = height; } /** * @method containsXY * @param x * @param y * @returns {boolean} */ containsXY(x:number, y:number):boolean { return this.x <= x && this.right > x && this.y <= y && this.bottom > y; } /** * get simple description of this object * @returns {string} */ toString() { return 'Rectangle[' + this.x + ',' + this.y + ',' + this.width + ',' + this.height + ']'; } } }
zzm2q/WOZLLA.js
src/renderer/internal/MaterialManager.ts
/// <reference path="Material.ts"/> /// <reference path="../IMaterial.ts"/> /// <reference path="../IShaderProgram.ts"/> module WOZLLA.renderer { /** * @class WOZLLA.renderer.MaterialManager * @extends WOZLLA.renderer.IMaterialManager */ export class MaterialManager implements IMaterialManager { _materialMap = {}; constructor() { this._materialMap[IMaterial.DEFAULT] = this.createMaterial( IMaterial.DEFAULT, IShaderProgram.V2T2C1A1, BlendType.NORMAL ); } createMaterial(id:string, shaderProgramId:string, blendType:number):IMaterial { var material = new Material(id, shaderProgramId, blendType); this._materialMap[id] = material; return material; } getMaterial(id:string):IMaterial { return this._materialMap[id]; } deleteMaterial(material:IMaterial):void { delete this._materialMap[material.id]; } clear():void { this._materialMap = {}; } } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/SimpleView.ts
///<reference path='View.ts'/> ///<reference path='../model/Model.ts'/> module WOZLLA.PureMVC { export class SimpleView extends View { get modelKey():string { return this._modelKey; } set modelKey(key:string) { this._modelKey = key; } get model():Model { return this._model; } _model:Model; _modelKey:string; _binder:SimpleBinder; onDestroy():void { this.unbindModel(); super.onDestroy(); } bindModel(model:Model) { if(this._model) { this.unbindModel(); } model.addListenerScope('fieldchanged', this.onModelFieldChange, this); this._model = model; this.onModelBind(model); } unbindModel() { var model; if(!this._model) return; model = this._model; model.removeListenerScope('fieldchanged', this.onModelFieldChange, this); this._model = null; this.onModelUnbind(model); } onModelFieldChange(e) { this._binder.onModelFieldChange(e); } onModelBind(model:Model) { if(this._binder) { this._binder.onModelBind(model); } } onModelUnbind(model:Model) { if(this._binder) { this._binder.onModelUnbind(model); } } setBinder(binder:SimpleBinder) { if(this._binder && this._model) { this._binder.onModelUnbind(this._model); } this._binder = binder; if(this._model && binder) { this._binder.onModelBind(this._model); } } } Component.register(SimpleView, { name: 'MVC.SimpleView', properties: [{ name: 'modelKey', type: 'string' }] }); }
zzm2q/WOZLLA.js
extensions/PureMVC/Mediator.ts
<gh_stars>0 module WOZLLA.PureMVC { export class Mediator extends puremvc.Mediator { getStage():WOZLLA.Stage { return Director.getInstance().stage; } getView():View { return <View>this.getViewComponent(); } show(callback?:Function) { var view = this.getView(); this.getStage().addChild(view.gameObject); callback && callback(); } hide(callback?:Function) { var view = this.getView(); view.gameObject.removeMe(); callback && callback(); } close(callback?:Function) { var view = this.getView(); view.gameObject.destroy(); view.gameObject.removeMe(); callback && callback(); } } }
zzm2q/WOZLLA.js
src/component/primitive/PrimitiveRenderer.ts
<gh_stars>0 /// <reference path="../renderer/CanvasRenderer.ts"/> module WOZLLA.component { export class PrimitiveRenderer extends CanvasRenderer { get primitiveStyle():PrimitiveStyle { return this._primitiveStyle; } set primitiveStyle(value:PrimitiveStyle) { this._primitiveStyle = value; this._graphicsDirty = true; } _primitiveStyle:PrimitiveStyle = new PrimitiveStyle(); render(renderer: renderer.IRenderer, flags: number): void { var size; if(this._graphicsDirty || this._primitiveStyle.dirty) { size = this.measurePrimitiveSize(); this.canvasWidth = size.width; this.canvasHeight = size.height; this._graphicsDirty = true; this._primitiveStyle.dirty = false; } super.render(renderer, flags); } draw(context):void { context.save(); this.applyPrimitiveStyle(context); this.drawPrimitive(context); context.restore(); } protected applyPrimitiveStyle(context) { if(this._primitiveStyle.stroke) { context.lineWidth = this._primitiveStyle.strokeWidth; context.strokeStyle = this._primitiveStyle.strokeColor; } if(this._primitiveStyle.fill) { context.fillStyle = this._primitiveStyle.fillColor; } } protected drawPrimitive(context):void { throw new Error('abstract method'); } protected measurePrimitiveSize():any { throw new Error('abstract method'); } } export class PrimitiveStyle { dirty:boolean = true; get stroke():boolean { return this._stroke; } set stroke(value:boolean) { if(value === this._stroke) return; this._stroke = value; this.dirty = true; } get strokeColor():string { return this._strokeColor; } set strokeColor(value:string) { if(value === this._strokeColor) return; this._strokeColor = value; this.dirty = true; } get strokeWidth():number { return this._strokeWidth; } set strokeWidth(value:number) { if(value === this._strokeWidth) return; this._strokeWidth = value; this.dirty = true; } get fill():boolean { return this._fill; } set fill(value:boolean) { if(value === this._fill) return; this._fill = value; this.dirty = true; } get fillColor():string { return this._fillColor; } set fillColor(value:string) { if(value === this._fillColor) return; this._fillColor = value; this.dirty = true; } _stroke:boolean = true; _fill:boolean = false; _strokeColor:string = '#000000'; _strokeWidth:number = 1; _fillColor:string = '#FFFFFF'; } }
zzm2q/WOZLLA.js
src/component/primitive/CircleRenderer.ts
<gh_stars>0 /// <reference path="PrimitiveRenderer.ts"/> module WOZLLA.component { export class CircleRenderer extends PrimitiveRenderer { get circle():WOZLLA.math.Circle { return this._circle; } set circle(value:WOZLLA.math.Circle) { this._circle = value; this._graphicsDirty = true; } _circle:WOZLLA.math.Circle; drawPrimitive(context):void { var style = this._primitiveStyle; var centerX:number = this._canvasSize.width/2; var centerY:number = this._canvasSize.height/2; context.beginPath(); context.arc(centerX, centerY, this._circle.radius, 0, 2 * Math.PI); if(style.stroke) { context.stroke(); } if(style.fill) { context.fill(); } } protected measurePrimitiveSize():any { var style = this._primitiveStyle; if(!this._circle) { return { width: 0, height: 0 }; } return { width: Math.ceil(this._circle.radius*2 + (style.stroke ? style.strokeWidth : 0)), height: Math.ceil(this._circle.radius*2 + (style.stroke ? style.strokeWidth : 0)) }; } protected generateCanvasTexture(renderer:renderer.IRenderer):void { var offset = { x: this._circle.centerX/this._circle.radius + 0.5, y: this._circle.centerY/this._circle.radius + 0.5 }; super.generateCanvasTexture(renderer); this.setTextureOffset(offset); } } }
zzm2q/WOZLLA.js
src/utils/Ajax.ts
<filename>src/utils/Ajax.ts module WOZLLA.utils { function applyProperties(target, source) { for(var i in source) { if(typeof target[i] === 'undefined') { target[i] = source[i]; } } return target; } var contentParser = { 'json' : function(xhr) { return JSON.parse(xhr.responseText); }, 'arraybuffer' : function(xhr) { return xhr.response; } }; var empty = function() {}; /** * @class WOZLLA.utils.Ajax */ export class Ajax { /** * internal ajax error code when timeout * @property ERROR_TIMEOUT * @static * @readonly */ public static ERROR_TIMEOUT = 1; /** * internal ajax error code when server error * @property ERROR_SERVER * @static * @readonly */ public static ERROR_SERVER = 2; /** * send a request with options * @param {object} options * @param {boolean} options.async * @param {string} options.method GET/POST * @param {string} options.contentType text/json/xml * @param {string} options.responseType text/plain,text/javascript,text/css,arraybuffer * @param {number} [options.timeout=30000] * @param {function} options.success call when ajax request successfully * @param {function} options.error call when ajax request error */ public static request(options:any={}) { var xhr; var timeoutId; options = applyProperties(options, { url: '', async: true, method: 'GET', dataType: 'text', responseType: 'text/plain', timeout: 30000, success: empty, error: empty, withCredentials: false }); xhr = new XMLHttpRequest(); xhr.responseType = options.responseType; xhr.onreadystatechange = () => { var parser; if (xhr.readyState === 4) { xhr.onreadystatechange = empty; clearTimeout(timeoutId); parser = contentParser[options.dataType] || function() { return xhr.responseText; }; options.success(parser(xhr)); } }; xhr.open(options.method, options.url, options.async); xhr.withCredentials = options.withCredentials; timeoutId = setTimeout(function() { xhr.onreadystatechange = empty; xhr.abort(); options.error({ code: Ajax.ERROR_TIMEOUT, message: 'request timeout' }); }, options.timeout); xhr.send(); } } }
zzm2q/WOZLLA.js
src/assets/AssetLoader.ts
module WOZLLA.assets { export interface AssetDescription { src:string; AssetClass:Function; callback:Function; } /** * an singleton class for asset loading and asset management * @class WOZLLA.assets.AssetLoader * @singleton */ export class AssetLoader { private static instance:AssetLoader; /** * return the singleton of this class * @method getInstance * @static * @returns {WOZLLA.assets.AssetLoader} */ public static getInstance():AssetLoader { if(!AssetLoader.instance) { AssetLoader.instance = new AssetLoader(); } return AssetLoader.instance; } _loadedAssets = {}; _loadingUnits = {}; _baseDir:string = ''; getBaseDir() { return this._baseDir; } setBaseDir(baseDir:string) { this._baseDir = baseDir; } /** * get an asset by src * @param src * @returns {any} */ getAsset(src):any { return this._loadedAssets[src]; } /** * add asset to asset loader, the asset would be auto removed when unloaded. * @param asset */ addAsset(asset:Asset):void { this._loadedAssets[asset.src] = asset; asset.addListener(Asset.EVENT_UNLOAD, (e) => { e.removeCurrentListener(); this.removeAsset(asset); }); } /** * remove asset from asset loader * @param asset */ removeAsset(asset:Asset) { delete this._loadedAssets[asset.src]; } /** * load all asset * @param items */ loadAll(items:Array<AssetDescription>) { var item:any, i, len; for(i=0, len=items.length; i<len; i++) { item = items[i]; this.load(item.src, item.AssetClass, item.callback); } } /** * load an asset by src, AssetClass(constructor/factory) * @param src * @param AssetClass * @param callback */ load(src:string, AssetClass:Function, callback?:()=>any) { var asset, loadUnit:LoadUnit; asset = this._loadedAssets[src]; if(asset) { callback && callback(); return; } loadUnit = this._loadingUnits[src]; if(loadUnit) { loadUnit.addCallback(callback, callback); return; } asset = <Asset>(new (<any>AssetClass)(src, this._baseDir ? this._baseDir + "/" : "")); loadUnit = new LoadUnit(src); loadUnit.addCallback(callback, callback); this._loadingUnits[src] = loadUnit; asset.load(() => { delete this._loadingUnits[src]; this.addAsset(asset); loadUnit.complete(null, asset); }, (error) => { console.log(error); delete this._loadingUnits[src]; loadUnit.complete(error); }); } } class LoadUnit { src; callbacks = []; constructor(src) { this.src = src; } addCallback(onSuccess, onError) { this.callbacks.push({ onSuccess: onSuccess, onError: onError }); } complete(error, asset?) { this.callbacks.forEach(function(callback) { if(error) { callback.onError && callback.onError(error); } else { callback.onSuccess && callback.onSuccess(asset); } }); } } }
zzm2q/WOZLLA.js
src/utils/ObjectPool.ts
module WOZLLA.utils { export interface Poolable { isPoolable:boolean; release(); } export class ObjectPool<T extends Poolable> { _minCount; _factory; _pool:Array<T>; constructor(minCount:number, factory:()=>T) { this._minCount = minCount; this._factory = factory; this._pool = []; for(var i=0; i<this._minCount; i++) { this._pool.push(this._factory()); } } retain():T { var object:T = this._pool.shift(); if(object) { return object; } return this._factory(); } release(obj:T) { if(this._pool.indexOf(obj) !== -1) { return; } this._pool.push(obj); } } }
zzm2q/WOZLLA.js
extensions/PureMVC/view/AdapterView.ts
///<reference path='View.ts'/> ///<reference path='AdapterFactory.ts'/> ///<reference path='../model/Store.ts'/> module WOZLLA.PureMVC { export class AdapterView extends View { get adapter():Adapter { return this._adapter; } set adapter(value:Adapter) { this.setAdapter(value); } get storeKey():string { return this._storeKey; } set storeKey(key:string) { this._storeKey = key; } get store():Store { return this._store; } _store:Store; _storeKey:string; _adapter:Adapter; onDestroy():void { this.unbindStore(); super.onDestroy(); } bindStore(store:Store, callback?:Function) { this._store = store; this.onStoreBind(store, callback); } unbindStore() { var store; if(!this._store) return; store = this._store; this._store = null; this.onStoreUnbind(store); } onStoreBind(store:Store, callback?:Function) { if(this._adapter) { this._adapter.onStoreBind(store, callback); } else { callback && callback(); } } onStoreUnbind(store:Store) { if(this._adapter) { this._adapter.onStoreUnbind(store); } } setAdapter(adapter:Adapter, callback?:Function) { if(this._adapter && this._store) { this._adapter.onStoreUnbind(this._store); } this._adapter = adapter; this._adapter.setAdapterView(this); if(this._store) { this._adapter.onStoreBind(this._store, callback); } else { callback && callback(); } } } Component.register(AdapterView, { name: 'MVC.AdapterView', properties: [{ name: 'storeKey', type: 'string' }, { name: 'adapter', type: 'MVC.Adapter', convert: function(name) { if(!name) { return null; } return AdapterFactory.create(name); } }] }); }
zzm2q/WOZLLA.js
extensions/PureMVC/view/ViewBuilder.ts
///<reference path='View.ts'/> ///<reference path='../../../../WOZLLA.js/src/utils/Assert.ts'/> ///<reference path='../../../../WOZLLA.js/src/jsonx/JSONXBuilder.ts'/> module WOZLLA.PureMVC { var Assert = WOZLLA.Assert; export class ViewBuilder extends WOZLLA.jsonx.JSONXBuilder { public static fullBuild(src:any, modelMap:any , onComplete:(view:View) => void) { var builder = new WOZLLA.PureMVC.ViewBuilder(); if(typeof src === 'string') { builder.instantiateWithSrc(src); } else { builder.instantiateWithJSON(src); } for(var key in modelMap) { var modelOrStore = modelMap[key]; if(modelOrStore instanceof Model) { builder.addModel(key, modelOrStore); } else { builder.addStore(key, modelOrStore); } } builder.load().init().build((error:any, root:WOZLLA.GameObject) => { var view = <View>root.getComponent(View); onComplete && onComplete(view); }); } _modelMap:any = {}; _storeMap:any = {}; _bindList = []; addModel(key:string, model:Model) { this._modelMap[key] = model; } getModel(key:string):Model { Assert.isNotUndefined(this._modelMap[key]); return this._modelMap[key]; } addStore(key:string, store:Store) { this._storeMap[key] = store; } getStore(key:string):Store { Assert.isNotUndefined(this._storeMap[key]); return this._storeMap[key]; } protected _newGameObjectTree(callback:Function) { super._newGameObjectTree(() => { var me = this; function nextBind() { var bindExec:Function = me._bindList.shift(); if(!bindExec) { callback(); return; } bindExec(nextBind); } nextBind(); }); } protected _newComponent(compData:any, gameObj:WOZLLA.GameObject):WOZLLA.Component { var simpleView:SimpleView; var adapterView:AdapterView; var component = super._newComponent(compData, gameObj); if(component instanceof View) { (<View>component).onCreate(); if(component instanceof SimpleView) { simpleView = (<SimpleView>component); if(simpleView.modelKey) { this._bindList.push((next) => { simpleView.bindModel(this.getModel(simpleView.modelKey)); next(); }); } } else if(component instanceof AdapterView) { adapterView = <AdapterView>component; if(adapterView.storeKey) { this._bindList.push((next) => { adapterView.bindStore(this.getStore(adapterView.storeKey), next); }); } } } return component; } } }
zzm2q/WOZLLA.js
src/component/renderer/AnimationRenderer.ts
<filename>src/component/renderer/AnimationRenderer.ts /// <reference path="SpriteRenderer.ts"/> /// <reference path="../../utils/Tween.ts"/> module WOZLLA.component { export class AnimationRenderer extends SpriteRenderer { public static MODE_LOOP = 'loop'; public static MODE_NONLOOP = 'nonloop'; get autoOffset():boolean { return this._autoOffset; } set autoOffset(value:boolean) { this._autoOffset = value; } get frameNum():number { return this._frameNum; } set frameNum(value:number) { var value = Math.floor(value); if(this._frameNum === value) return; this._frameNum = value; this._frameNumDirty = true; } get duration():number { return this._duration; } set duration(value:number) { this._duration = value; } get playMode():string { return this._playMode; } set playMode(value:string) { this._playMode = value; } get frameLength():number { return this._spriteProxy.getFrameLength(); } _frameNum:number; _frameNumDirty:boolean = true; _autoOffset:boolean = true; _playMode:string = AnimationRenderer.MODE_NONLOOP; _playing:boolean = false; _duration:number; _playTween:utils.Tween; play(duration:number=this._duration) { if(this.frameLength <= 0) return; this._duration = duration; this._playing = true; this._frameNum = 0; if(this._playTween) { this._playTween.setPaused(true); } this._playTween = utils.Tween.get(this).to({ frameNum: this.frameLength }, duration); } pause() { if(this._playing) { this._playTween.setPaused(true); this._playing = false; } } resume() { if(!this._playing && this._playTween) { this._playTween.setPaused(false); this._playing = true; } } stop() { if(this._playing || this._playTween) { this._playTween.setPaused(false); this._playTween = null; } } render(renderer:WOZLLA.renderer.IRenderer, flags:number):void { if(this._frameNumDirty) { this._frameNumDirty = false; this.updateAnimationFrame(); } super.render(renderer, flags); } protected updateAnimationFrame() { var frame; var frameLength = this.frameLength; if(frameLength === 0) { this.sprite = null; } else { if(this._frameNum >= frameLength) { if(this._playMode === AnimationRenderer.MODE_LOOP) { this.play(); } else { this._frameNum = frameLength - 1; this.dispatchEvent(new WOZLLA.event.Event('animationend')); this.stop(); } } this.sprite = this._spriteProxy.getSprite(this._frameNum); frame = this.sprite.frame; if(this._autoOffset) { this.spriteOffset = { x: -frame.offsetX/frame.width || 0, y: -frame.offsetY/frame.height || 0 }; } this.dispatchEvent(new WOZLLA.event.Event('framechanged', false, { frame: this._frameNum })) } } } }
zzm2q/WOZLLA.js
src/component/collider/RectCollider.ts
<reponame>zzm2q/WOZLLA.js<filename>src/component/collider/RectCollider.ts<gh_stars>0 /// <reference path="../../core/Collider.ts"/> /// <reference path="../../math/Rectangle.ts"/> module WOZLLA.component { /** * @class WOZLLA.component.RectCollider */ export class RectCollider extends WOZLLA.Collider { public static fromSpriteRenderer(spriteRenderer:SpriteRenderer):RectCollider { var rectCollider = new WOZLLA.component.RectCollider(); var frame = spriteRenderer.sprite.frame; var offset = spriteRenderer.spriteOffset; rectCollider.region = new WOZLLA.math.Rectangle(0-frame.width*offset.x, 0-frame.height*offset.y, frame.width, frame.height); return rectCollider; } region:WOZLLA.math.Rectangle; collideXY(localX:number, localY:number):boolean { return this.region && this.region.containsXY(localX, localY); } collide(collider:Collider):boolean { return false; } } }
zzm2q/WOZLLA.js
src/component/PropertyConverter.ts
module WOZLLA.component { export class PropertyConverter { public static array2rect(arr:Array<number>):WOZLLA.math.Rectangle { return new WOZLLA.math.Rectangle(arr[0], arr[1], arr[2], arr[3]); } public static array2circle(arr:Array<number>):WOZLLA.math.Circle { return new WOZLLA.math.Circle(arr[0], arr[1], arr[2]); } public static json2TextStyle(json:any):TextStyle { var style = new TextStyle(); for(var i in json) { style[i] = json[i]; } return style; } public static array2Padding(arr:Array<number>):WOZLLA.layout.Padding { return new WOZLLA.layout.Padding(arr[0], arr[1], arr[2], arr[3]); } public static array2Margin(arr:Array<number>):WOZLLA.layout.Margin { return new WOZLLA.layout.Margin(arr[0], arr[1], arr[2], arr[3]); } } }
zzm2q/WOZLLA.js
src/core/Touch.ts
/// <reference path="../../libs/hammerjs.d.ts"/> /// <reference path="Scheduler.ts"/> /// <reference path="Stage.ts"/> /// <reference path="Director.ts"/> module WOZLLA { function getCanvasOffset(canvas:any) { var obj = canvas; var offset = { x : obj.offsetLeft, y : obj.offsetTop }; while ( obj = obj.offsetParent ) { offset.x += obj.offsetLeft; offset.y += obj.offsetTop; } return offset; } export class GestureEvent extends WOZLLA.event.Event { x:number; y:number; touch:any; touchMoveDetection:boolean = false; gesture:any; identifier:any; constructor(params:any) { super(params.type, params.bubbles, params.data); this.x = params.x; this.y = params.y; this.touch = params.touch; this.touchMoveDetection = params.touchMoveDetection; this.gesture = params.gesture; this.identifier = params.identifier; } setTouchMoveDetection(value:boolean) { this.touchMoveDetection = value; } } /** * class for touch management <br/> * get the instance form {@link WOZLLA.Director} * @class WOZLLA.Touch * @protected */ export class Touch { private static enabledGestures; public static setEanbledGestures(gestures) { this.enabledGestures = gestures; } /** * get or set enabled of touch system * @property {boolean} enabled */ enabled:boolean = true; canvas:HTMLCanvasElement = null; canvasOffset:any = null; touchScale:number; channelMap = {}; constructor(canvas:HTMLCanvasElement, touchScale:number=1) { var me = this; var nav:any = window.navigator; me.canvas = canvas; me.canvasOffset = getCanvasOffset(canvas); me.touchScale = touchScale; Hammer(nav.isCocoonJS ? document : canvas, { transform : false, doubletap : false, hold : false, rotate : false, pinch : false }).on(Touch.enabledGestures || 'touch release tap swipe drag dragstart dragend', function(e) { if(e.type === 'release' || me.enabled) { Scheduler.getInstance().scheduleFrame(function() { me.onGestureEvent(e); }); } }); } onGestureEvent(e) { var x, y, i, len, touch, identifier, channel, changedTouches, target, type = e.type, stage = Director.getInstance().stage; var me = this; var canvasScale = this.touchScale || 1; changedTouches = e.gesture.srcEvent.changedTouches; if (!changedTouches) { identifier = 1; x = e.gesture.srcEvent.pageX - me.canvasOffset.x; y = e.gesture.srcEvent.pageY - me.canvasOffset.y; x *= canvasScale; y *= canvasScale; if (type === 'touch') { target = stage.getUnderPoint(x, y, true); if (target) { me.channelMap[identifier] = me.createDispatchChanel(target); } else { delete me.channelMap[identifier]; } } channel = me.channelMap[identifier]; channel && channel.onGestureEvent(e, target, x, y, identifier); } else { len = changedTouches.length; for(i=0; i<len; i++) { touch = changedTouches[i]; identifier = parseInt(touch.identifier); x = touch.pageX - me.canvasOffset.x; y = touch.pageY - me.canvasOffset.y; x *= canvasScale; y *= canvasScale; if (type === 'touch') { target = stage.getUnderPoint(x, y, true); if (target) { me.channelMap[identifier] = me.createDispatchChanel(target); delete me.channelMap[identifier - 10]; } } channel = me.channelMap[identifier]; channel && channel.onGestureEvent(e, target, x, y, identifier); } } } createDispatchChanel(touchTarget) { var touchMoveDetection = true; return { onGestureEvent : function(e, target, x, y, identifier) { var touchEvent, type = e.type, stage = Director.getInstance().stage; switch(type) { case 'drag': if(!touchMoveDetection) { target = touchTarget; break; } case 'tap': case 'release': target = stage.getUnderPoint(x, y, true); break; } if(type === 'tap' && touchTarget !== target) { return; } touchEvent = new GestureEvent({ x: x, y: y, type: type, bubbles: true, touch: target, gesture : e.gesture, identifier : identifier, touchMoveDetection : false }); touchTarget.dispatchEvent(touchEvent); touchMoveDetection = touchEvent.touchMoveDetection; } } } } }
zzm2q/WOZLLA.js
extensions/PureMVC/AsyncMacroCommand.ts
///<reference path='../../libs/puremvc-typescript-multicore-1.1.d.ts'/> ///<reference path='AsyncCommand.ts'/> module WOZLLA.PureMVC { export class AsyncMacroCommand extends puremvc.MacroCommand { public execute(notification: puremvc.INotification):void { var me = this; var subCommands:Function[] = this.subCommands.slice(0); var idx:number = 0; function asyncExec() { var CommandClass:Function = subCommands[idx++]; if(!CommandClass) { return; } me.executeSubCommand(CommandClass, notification, asyncExec); } asyncExec(); } public executeSubCommand(CommandClass:Function, notification: puremvc.INotification, onComplete:Function):void { var commandInstance:any = new (<any>CommandClass)(); commandInstance.initializeNotifier(this.multitonKey); if(commandInstance instanceof AsyncCommand) { commandInstance.execute(notification, onComplete); } else { commandInstance.execute(notification); onComplete(); } } } }
zzm2q/WOZLLA.js
extensions/PureMVC/ApplicationFacade.ts
///<reference path='../../libs/puremvc-typescript-multicore-1.1.d.ts'/> module WOZLLA.PureMVC { export class ApplicationFacade extends puremvc.Facade { public static getInstance(key:string):ApplicationFacade { if(ApplicationFacade.instanceMap[key] == null) { ApplicationFacade.instanceMap[key] = new ApplicationFacade(key); } return ApplicationFacade.instanceMap[key]; } public sendNotification(name: string, body?: any, type?: string):void { // TODO super.sendNotification(name, body, type); } } }
zzm2q/WOZLLA.js
src/layout/Padding.ts
<reponame>zzm2q/WOZLLA.js module WOZLLA.layout { export class Padding { constructor(public top:number, public left:number, public bottom:number, public right:number) { } equals(padding:Padding) { return this.top === padding.top && this.bottom === padding.bottom && this.right === padding.right && this.left === padding.left; } } }
zzm2q/WOZLLA.js
src/core/Stage.ts
<filename>src/core/Stage.ts /// <reference path="GameObject.ts"/> module WOZLLA { /** * the root game object of WOZLLA engine * @class WOZLLA.Stage * @extends WOZLLA.GameObject */ export class Stage extends GameObject { public static ID:string = 'WOZLLAStage'; get viewRectTransform():RectTransform { return this._viewRectTransform; } _rootTransform:Transform; _viewRectTransform:RectTransform; constructor() { super(); this.id = Stage.ID; this.name = Stage.ID; this._rootTransform = new Transform(); this._viewRectTransform = new RectTransform(); this._viewRectTransform.anchorMode = RectTransform.ANCHOR_TOP | RectTransform.ANCHOR_LEFT; this._viewRectTransform.width = Director.getInstance().renderer.viewport.width; this._viewRectTransform.height = Director.getInstance().renderer.viewport.height; this._viewRectTransform.px = 0; this._viewRectTransform.py = 0; this.init(); } visitStage(renderer:WOZLLA.renderer.IRenderer):void { super.visit(renderer, this._rootTransform, GameObject.MASK_VISIBLE); } } }
zzm2q/WOZLLA.js
extensions/Cocos2dx/AnimationRenderer.ts
module WOZLLA.Cocos2dx { export class AnimationRenderer extends WOZLLA.Renderer { } }
zzm2q/WOZLLA.js
src/ui/Button.ts
<reponame>zzm2q/WOZLLA.js /// <reference path="StateWidget.ts"/> /// <reference path="../component/renderer/SpriteRenderer.ts"/> module WOZLLA.ui { /** * @class WOZLLA.ui.Button */ export class Button extends StateWidget { public static STATE_NORMAL = 'normal'; public static STATE_DISABLED = 'disabled'; public static STATE_PRESSED = 'pressed'; get normalSpriteName():string { return this.getStateSpriteName(Button.STATE_NORMAL); } set normalSpriteName(spriteName:string) { this.setStateSpriteName(Button.STATE_NORMAL, spriteName); } get disabledSpriteName():string { return this.getStateSpriteName(Button.STATE_DISABLED); } set disabledSpriteName(spriteName:string) { this.setStateSpriteName(Button.STATE_DISABLED, spriteName); } get pressedSpriteName():string { return this.getStateSpriteName(Button.STATE_PRESSED); } set pressedSpriteName(spriteName:string) { this.setStateSpriteName(Button.STATE_PRESSED, spriteName); } init() { this.gameObject.addListener('touch', (e) => this.onTouch(e)); this.gameObject.addListener('release', (e) => this.onRelease(e)); this.gameObject.addListener('tap', (e) => this.onTap(e)); super.init(); } destroy() { this._stateMachine.clearAllListeners(); super.destroy(); } isEnabled() { return this._stateMachine.getCurrentState() !== Button.STATE_DISABLED; } setEnabled(enabled:boolean=true) { this._stateMachine.changeState(enabled ? Button.STATE_NORMAL : Button.STATE_DISABLED); this._gameObject.touchable = enabled; } protected initStates():void { this._stateMachine.defineState(Button.STATE_NORMAL, true); this._stateMachine.defineState(Button.STATE_DISABLED); this._stateMachine.defineState(Button.STATE_PRESSED); } protected onTouch(e) { this._stateMachine.changeState(Button.STATE_PRESSED); } protected onRelease(e) { this._stateMachine.changeState(Button.STATE_NORMAL); } protected onTap(e) { } } }
zzm2q/WOZLLA.js
src/utils/StateMachine.ts
/// <reference path="../event/EventDispatcher.ts"/> /// <reference path="Assert.ts"/> module WOZLLA.utils { export class StateMachine extends WOZLLA.event.EventDispatcher { public static INIT:string = 'state.init'; public static CHANGE:string = 'state.change'; _defaultState:string; _currentState:string; _currentTransition:ITransition; _stateConfig:any = {}; defineState(name:string, isDefault:boolean=false) { Assert.isUndefined(this._stateConfig[name], 'state "' + name + '" has been defined'); this._stateConfig[name] = { data: {} }; if(isDefault) { this._defaultState = name; } } getStateData(state:string, key:string) { Assert.isNotUndefined(this._stateConfig[state], 'state "' + state + '" not defined'); return this._stateConfig[state].data[key]; } setStateData(state:string, key:string, data:any) { Assert.isNotUndefined(this._stateConfig[state], 'state "' + state + '" not defined'); this._stateConfig[state].data[key] = data; } defineTransition(fromState:string, toState:string, transition:ITransition) { Assert.isNotUndefined(this._stateConfig[fromState], 'state "' + fromState + '" not defined'); Assert.isNotUndefined(this._stateConfig[toState], 'state "' + toState + '" not defined'); this._stateConfig[fromState][toState] = transition; } init() { this._currentState = this._defaultState; this.dispatchEvent(new WOZLLA.event.Event(StateMachine.INIT, false, new StateEventData(this._currentState))); } getCurrentState():string { return this._currentState; } changeState(state:string) { var from, to, transition; Assert.isNotUndefined(this._stateConfig[state]); from = this._currentState; to = state; transition = this._stateConfig[state][to] || EmptyTransition.getInstance(); if(this._currentTransition) { this._currentTransition.cancel(); } transition.reset(); transition.execute(from, to, () => { this._currentTransition = null; this._currentState = to; this.dispatchEvent(new WOZLLA.event.Event(StateMachine.CHANGE, false, new StateEventData(this._currentState))); }); this._currentTransition = transition; } } export class StateEventData { public state:string; constructor(state:string) { this.state = state; } } export interface ITransition { reset(); cancel(); execute(fromState:string, toState:string, onComplete:Function); } export class EmptyTransition implements ITransition { private static instance:EmptyTransition; public static getInstance():EmptyTransition { if(!EmptyTransition.instance) { EmptyTransition.instance = new EmptyTransition(); } return EmptyTransition.instance; } _canceled:boolean = false; reset() { this._canceled = false; } cancel() { this._canceled = true; } execute(fromState:string, toState:string, onComplete:Function) { if(this._canceled) { return; } onComplete(); } } }
zzm2q/WOZLLA.js
src/renderer/internal/LayerManager.ts
<filename>src/renderer/internal/LayerManager.ts /// <reference path="../ILayerManager.ts"/> module WOZLLA.renderer { /** * @class WOZLLA.renderer.LayerManager * @extends WOZLLA.renderer.ILayerManager */ export class LayerManager implements ILayerManager { _layerIndexMap; _sortedLayers; constructor() { this._layerIndexMap = {}; this._sortedLayers = []; this.define(ILayerManager.DEFAULT, 0); } define(layer:string, zindex:number):void { if(this._layerIndexMap[layer]) { throw new Error('Layer has been defined: ' + layer); } this._layerIndexMap[layer] = zindex; this._sortedLayers.push(layer); this._sortedLayers.sort((a, b) => { return this.getZIndex(a) - this.getZIndex(b); }); } undefine(layer:string):void { this._sortedLayers.splice(this._sortedLayers.indexOf(layer), 1); delete this._layerIndexMap[layer]; } getZIndex(layer:string):number { return this._layerIndexMap[layer]; } getSortedLayers():Array<string> { return this._sortedLayers.slice(0); } _getSortedLayers():Array<string> { return this._sortedLayers; } } }
John31337/Diamond
deployment/index.ts
import "./deploy"
John31337/Diamond
test/units/ProjectToken.test.ts
import {expect} from "chai"; import {ethers} from "hardhat"; import {Contract} from "ethers"; import {SignerWithAddress} from "@nomiclabs/hardhat-ethers/signers"; export function likeProjectToken(): void { describe("- Project Token SC", function () { let projectToken: Contract; let owner: SignerWithAddress; let addr1: SignerWithAddress; let addr2: SignerWithAddress; let addr3: SignerWithAddress; const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; beforeEach(async () => { this.ctx.signers = await ethers.getSigners(); [owner, addr1, addr2, addr3] = this.ctx.signers; /// Test Project Coin Deploy const ProjectCoinFactory = await ethers.getContractFactory("ProjectCoin", owner); const projectCoin = await ProjectCoinFactory.deploy("Test Project Coin", "TPC", 1000000 * 10 ^ 18); await projectCoin.deployed(); //console.log('Project Coin Deployed At: ', projectCoin.address); /// Test Project Token Deploy const ProjectTokenFactory = await ethers.getContractFactory("ProjectToken", owner); projectToken = await ProjectTokenFactory.deploy("Test Project Token", "TETHERP"); await projectToken.deployed(); }); describe("1. Ownership", async function () { it("1.1 Verify that the crowdfunding contract is the admin", async function () { expect(await projectToken.owner()).to.eq(owner.address); }); }); describe("2. Mint", async function () { it("2.1 Succeeds when the crowdfunding contract mints token", async function () { await expect(projectToken.mint(addr1.address, 1000)).to.emit(projectToken, 'Transfer').withArgs(ZERO_ADDRESS, addr1.address, 1000); expect(await projectToken.balanceOf(addr1.address)).to.eq(1000); }); it("2.4 Fails when other address mints token", async function () { await expect(projectToken.connect(addr1).mint(addr2.address, 1000)).to.be.revertedWith('Ownable: caller is not the owner'); }); it("2.5 Fails when zero tokens minted", async function () { await expect(projectToken.mint(addr1.address, 0)).to.be.revertedWith('ERC20: mint amount zero'); }); }); describe("3. Burn", async function () { beforeEach(async () => { await projectToken.mint(owner.address, 1000); await projectToken.mint(addr1.address, 1000); }); it("3.1 Succeeds when the crowdfunding contract burns token", async function () { await expect(projectToken.burn(100)).to.be.emit(projectToken, 'Transfer').withArgs(owner.address, ZERO_ADDRESS, 100); expect(await projectToken.balanceOf(owner.address)).to.eq(900); }); it("3.4 Fails when other address burns token", async function () { await expect(projectToken.connect(addr1).burn(100)).to.be.revertedWith('Ownable: caller is not the owner'); }); it("3.5 Fails when zero tokens burnt", async function () { await expect(projectToken.burn(0)).to.be.revertedWith('ERC20: burn amount zero'); }); }); describe("4. Transfer", async function () { beforeEach(async () => { await projectToken.mint(owner.address, 1000); await projectToken.mint(addr1.address, 1000); }); it("4.1 Check it is deactivated", async function () { await expect(projectToken.connect(addr1).transfer(addr2.address, 100)).to.be.revertedWith('Ownable: caller is not the owner'); await expect(projectToken.transfer(addr1.address, 100)).to.be.emit(projectToken, 'Transfer').withArgs(owner.address, addr1.address, 100); expect(await projectToken.balanceOf(owner.address)).to.eq(900); expect(await projectToken.balanceOf(addr1.address)).to.eq(1100); }); }); describe("5. TransferFrom", async function () { beforeEach(async () => { await projectToken.mint(owner.address, 1000); await projectToken.mint(addr1.address, 1000); }); it("5.1 Check it is deactivated", async function () { await projectToken.approve(addr1.address, 100); await expect(projectToken.connect(addr1).transferFrom(owner.address, addr2.address, 100)).to.be.revertedWith('Ownable: caller is not the owner'); await projectToken.connect(addr1).approve(owner.address, 100); await expect(projectToken.transferFrom(addr1.address, addr2.address, 100)).to.be.emit(projectToken, 'Transfer').withArgs(addr1.address, addr2.address, 100); expect(await projectToken.balanceOf(addr1.address)).to.eq(900); expect(await projectToken.balanceOf(addr2.address)).to.eq(100); }); }); describe("6. Approve", async function () { beforeEach(async () => { await projectToken.mint(owner.address, 1000); }); it("6.1 Check it is deactivated", async function () { await expect(projectToken.connect(addr1).transferFrom(owner.address, addr2.address, 100)).to.be.revertedWith('Ownable: caller is not the owner'); }); }); }); }
e-ntro-py/jupyterlab-git
src/components/SinglePastCommitInfo.tsx
import { TranslationBundle } from '@jupyterlab/translation'; import { CommandRegistry } from '@lumino/commands'; import * as React from 'react'; import { LoggerContext } from '../logger'; import { GitExtension } from '../model'; import { discardIcon, rewindIcon } from '../style/icons'; import { actionButtonClass, commitBodyClass } from '../style/SinglePastCommitInfo'; import { Git } from '../tokens'; import { ActionButton } from './ActionButton'; import { CommitDiff } from './CommitDiff'; import { ResetRevertDialog } from './ResetRevertDialog'; /** * Interface describing component properties. */ export interface ISinglePastCommitInfoProps { /** * Commit data. */ commit: Git.ISingleCommitInfo; /** * Extension data model. */ model: GitExtension; /** * Jupyter App commands registry */ commands: CommandRegistry; /** * The application language translator. */ trans: TranslationBundle; /** * Returns a callback to be invoked on click to display a file diff. * * @param filePath file path * @param isText indicates whether the file supports displaying a diff * @param previousFilePath when file has been relocated * @returns callback */ onOpenDiff: ( filePath: string, isText: boolean, previousFilePath?: string ) => (event: React.MouseEvent<HTMLLIElement, MouseEvent>) => void; } /** * Interface describing component state. */ export interface ISinglePastCommitInfoState { /** * Commit information. */ info: string; /** * Commit information. */ commitBody: string; /** * Number of modified files. */ numFiles: string; /** * Number of insertions. */ insertions: string; /** * Number of deletions. */ deletions: string; /** * A list of modified files. */ modifiedFiles: Git.ICommitModifiedFile[]; /** * Current loading state for loading individual commit information. */ loadingState: 'loading' | 'error' | 'success'; /** * Boolean indicating whether to display a dialog for resetting or reverting a commit. */ resetRevertDialog: boolean; /** * Reset/revert dialog mode (i.e., whether the dialog should be for resetting to or reverting an individual commit). */ resetRevertAction: 'reset' | 'revert'; } /** * React component for rendering information about an individual commit. */ export class SinglePastCommitInfo extends React.Component< ISinglePastCommitInfoProps, ISinglePastCommitInfoState > { /** * Returns a React component for information about an individual commit. * * @param props - component properties * @returns React component */ constructor(props: ISinglePastCommitInfoProps) { super(props); this.state = { info: '', commitBody: '', numFiles: '', insertions: '', deletions: '', modifiedFiles: [], loadingState: 'loading', resetRevertDialog: false, resetRevertAction: 'reset' }; } /** * Callback invoked immediately after mounting a component (i.e., inserting into a tree). */ async componentDidMount(): Promise<void> { try { const log = await this.props.model.detailedLog(this.props.commit.commit); this.setState({ info: log.modified_file_note, commitBody: log.commit_body, numFiles: log.modified_files_count, insertions: log.number_of_insertions, deletions: log.number_of_deletions, modifiedFiles: log.modified_files, loadingState: 'success' }); } catch (err) { console.error( `Error while getting detailed log for commit ${this.props.commit.commit} and path ${this.props.model.pathRepository}`, err ); this.setState({ loadingState: 'error' }); return; } } /** * Renders the component. * * @returns React element */ render(): React.ReactElement { if (this.state.loadingState === 'loading') { return <div>…</div>; } if (this.state.loadingState === 'error') { return <div>{this.props.trans.__('Error loading commit data')}</div>; } return ( <div> <p className={commitBodyClass}>{this.state.commitBody}</p> <CommitDiff actions={ <> <ActionButton className={actionButtonClass} icon={discardIcon} title={this.props.trans.__( 'Revert changes introduced by this commit' )} onClick={this._onRevertClick} /> <ActionButton className={actionButtonClass} icon={rewindIcon} title={this.props.trans.__( 'Discard changes introduced *after* this commit (hard reset)' )} onClick={this._onResetClick} /> <LoggerContext.Consumer> {logger => ( <ResetRevertDialog open={this.state.resetRevertDialog} action={this.state.resetRevertAction} model={this.props.model} logger={logger} commit={this.props.commit} onClose={this._onResetRevertDialogClose} trans={this.props.trans} /> )} </LoggerContext.Consumer> </> } numFiles={this.state.numFiles} insertions={this.state.insertions} deletions={this.state.deletions} files={this.state.modifiedFiles} onOpenDiff={this.props.onOpenDiff} trans={this.props.trans} ></CommitDiff> </div> ); } /** * Callback invoked upon a clicking a button to revert changes. * * @param event - event object */ private _onRevertClick = (event: any): void => { event.stopPropagation(); this.setState({ resetRevertDialog: true, resetRevertAction: 'revert' }); }; /** * Callback invoked upon a clicking a button to reset changes. * * @param event - event object */ private _onResetClick = (event: any): void => { event.stopPropagation(); this.setState({ resetRevertDialog: true, resetRevertAction: 'reset' }); }; /** * Callback invoked upon closing a dialog to reset or revert changes. */ private _onResetRevertDialogClose = (): void => { this.setState({ resetRevertDialog: false }); }; }
e-ntro-py/jupyterlab-git
src/style/StatusWidget.ts
<filename>src/style/StatusWidget.ts import { keyframes, style } from 'typestyle'; const fillAnimation = keyframes({ to: { fillOpacity: 1 } }); export const statusIconClass = style({ $nest: { '& .jp-icon3': { animationName: fillAnimation, animationDuration: '1s' } } }); const pathAnimation = keyframes({ '0%': { fillOpacity: 1 }, '50%': { fillOpacity: 0.6 }, '100%': { fillOpacity: 1 } }); export const statusAnimatedIconClass = style({ $nest: { '& .jp-icon3': { animationName: pathAnimation, animationDuration: '2s', animationIterationCount: 'infinite' } } }); export const badgeClass = style({ $nest: { '& > .MuiBadge-badge': { top: 6, right: 15, backgroundColor: 'var(--jp-warn-color1)' } } }); export const currentBranchNameClass = style({ fontSize: 'var(--jp-ui-font-size1)', lineHeight: '100%' });
ExLibrisGroup/cloudapp-tutorials
cloudapp/src/app/app.module.ts
import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { BrowserModule, Title } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MaterialModule, AlertModule, MenuModule, CloudAppTranslateModule } from '@exlibris/exl-cloudapp-angular-lib'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { SelectEntitiesModule } from 'eca-components'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { MainComponent } from './main/main.component'; import { TopmenuComponent } from './topmenu/topmenu.component'; import { NewrouteComponent } from './newroute/newroute.component'; import { ThemingComponent } from './theming/theming.component'; import { SettingsComponent } from './settings/settings.component'; import { ParallelComponent } from './parallel/parallel.component'; import { ExternalComponent } from './external/external.component'; import { XmlComponent } from './xml/xml.component'; import { BindComponent } from './bind/bind.component'; import { StoreComponent } from './store/store.component'; import { TranslateComponent } from './translate/translate.component'; import { ConfigurationComponent } from './configuration/configuration.component'; import { MultiSelectComponent } from './multi-select/multi-select.component'; import { LightboxComponent } from './external/lightbox/lightbox.component' import { ErrorComponent } from './static/error.component'; import { ConfirmationDialog, StyleComponent } from './style/style.component'; @NgModule({ declarations: [ AppComponent, MainComponent, TopmenuComponent, NewrouteComponent, ThemingComponent, SettingsComponent, ParallelComponent, ExternalComponent, XmlComponent, BindComponent, StoreComponent, TranslateComponent, ConfigurationComponent, MultiSelectComponent, LightboxComponent, ErrorComponent, StyleComponent, ConfirmationDialog, ], imports: [ MaterialModule, BrowserModule, BrowserAnimationsModule, AppRoutingModule, HttpClientModule, FormsModule, ReactiveFormsModule, CloudAppTranslateModule.forRoot(), AlertModule, SelectEntitiesModule, MenuModule, ], providers: [ Title ], bootstrap: [ AppComponent ], entryComponents: [ ConfirmationDialog ] }) export class AppModule { }
brandboxmarketplace/themify
__tests__/palettes/tiny-palette.ts
export default { light: { 'primary-700': '#303030' }, dark: { 'primary-700': '#ffffff' } };
brandboxmarketplace/themify
__tests__/utils.spec.ts
import {_handleUnSupportedBrowsers, _generateNewVariables} from '../src/utils'; import palette from './palettes/palette'; const whitelabel = { "dark": { "primary-100": "#c333d3", "primary-200": "#c333d3" }, "light": { "accent-300": "#ff0000" } } const whitelabelOnlyDark = { "dark": { "primary-100": "#c333d3", "primary-200": "#c333d3" } } const fallbackJSON = { "dark": ".dark button {color: %[dark, primary-100, 1]%;background-color: %[dark, primary-200, 0.5]%;border: 1px solid %[dark, primary-300, 0.5]%}.dark h1 {color: %[dark, accent-300, 1]%;background: linear-gradient(to right, %[dark, primary-100, 1]%, %[dark, accent-100, 1]%)}.dark p {color: %[dark, primary-100, 1]%}", "light": "button {color: %[light, primary-100, 1]%;background-color: %[light, primary-200, 0.5]%;border: 1px solid %[light, primary-300, 0.5]%;}h1 {color: %[light, accent-300, 1]%;background: linear-gradient(to right, %[light, primary-100, 1]%, %[light, accent-100, 1]%);}p {color: %[light, accent-300, 1]%;}" }; describe('Utils', () => { describe('Supported Browsers', () => { it('should generate the correct scheme', () => { const output = `.dark{--primary-100: 195,51,211;--primary-200: 195,51,211;}:root{--accent-300: 255,0,0;}`; expect(_generateNewVariables(whitelabel)).toEqual(output); }); it('should work with one variation', () => { const output = `.dark{--primary-100: 195,51,211;--primary-200: 195,51,211;}`; expect(_generateNewVariables(whitelabelOnlyDark)).toEqual(output); }); }); describe('UnSupported Browsers', () => { it('should generate the correct scheme', () => { const output = ".darkbutton{color:rgba(195,51,211,1);background-color:rgba(195,51,211,0.5);border:1pxsolidrgba(156,160,160,0.5)}.darkh1{color:rgba(4,162,214,1);background:linear-gradient(toright,rgba(195,51,211,1),rgba(9,103,150,1))}.darkp{color:rgba(195,51,211,1)}button{color:rgba(242,242,244,1);background-color:rgba(204,206,206,0.5);border:1pxsolidrgba(156,160,160,0.5);}h1{color:rgba(255,0,0,1);background:linear-gradient(toright,rgba(242,242,244,1),rgba(230,249,252,1));}p{color:rgba(255,0,0,1);}" expect(_handleUnSupportedBrowsers(whitelabel, palette, fallbackJSON).replace(/\s/g, '')).toEqual(output.replace(/\s/g, '')); }); }); });
brandboxmarketplace/themify
__tests__/palettes/palette.ts
export default { light: { 'primary-700': '#303030', 'primary-600': '#383838', 'primary-500': '#505050', 'primary-400': '#666a6b', 'primary-300': '#9ca0a0', 'primary-200': '#cccece', 'primary-100': '#f2f2f4', 'primary-50': '#f8f8f9', 'primary-0': '#ffffff', 'accent-700': '#096796', 'accent-600': '#0a87c6', 'accent-500': '#04a2d6', 'accent-400': '#00bee8', 'accent-300': '#4cd1ef', 'accent-200': '#96e1ed', 'accent-100': '#e6f9fc', }, dark: { 'primary-700': '#ffffff', 'primary-600': '#f8f8f9', 'primary-500': '#f2f2f4', 'primary-400': '#cccece', 'primary-300': '#9ca0a0', 'primary-200': '#666a6b', 'primary-100': '#505050', 'primary-50': '#383838', 'primary-0': '#303030', 'accent-700': '#e6f9fc', 'accent-600': '#96e1ed', 'accent-500': '#4cd1ef', 'accent-400': '#00bee8', 'accent-300': '#04a2d6', 'accent-200': '#0a87c6', 'accent-100': '#096796', } };
brandboxmarketplace/themify
src/helpers/json.util.ts
<reponame>brandboxmarketplace/themify const removeNewLineRegex = /(\r\n|\n|\r)/gm; /** * Minify the JSON * @param jsonStr * @return {any | string | void} */ export function minifyJSON(jsonStr) { return jsonStr && jsonStr.trim().replace(removeNewLineRegex, ''); }
brandboxmarketplace/themify
__tests__/fallback.spec.ts
<gh_stars>100-1000 import {TestUtils} from "./test.util"; import {ThemifyOptions} from "../src/index"; import {minifyJSON} from "../src/helpers/json.util"; const glob = require("glob"); const tmp = require('tmp'); const options: Partial<ThemifyOptions> = { palette: TestUtils.tinyPalette, screwIE11: false, fallback: { cssPath: '', dynamicPath: '' } }; const unmatchPaletteOptions: Partial<ThemifyOptions> = {...options, palette: TestUtils.unmatchPalette }; const inputFiles = glob.sync('__tests__/fallback/*.input.spec.scss'); const inputUnmatchPaletteFiles = glob.sync('__tests__/fallback-unmatch-palette/*.input.spec.scss'); describe('Themify - Fallback', () => { inputFiles.forEach((inputFile) => { const testName = TestUtils.getTestName(inputFile); it(testName, (done) => { test(inputFile, options, done); }); }); inputUnmatchPaletteFiles.forEach((inputFile) => { const testName = TestUtils.getTestName(inputFile); it(`${testName}-unmatch-palette`, (done) => { test(inputFile, unmatchPaletteOptions, done); }); }); }); function test(inputFile, options, done) { // creating temp files for the CSS & JSON files const {cssTmp, dynamicTmp} = { cssTmp: tmp.fileSync(), dynamicTmp: tmp.fileSync() }; const myOptions = {...options, ...{ fallback: { cssPath: cssTmp.name, dynamicPath: dynamicTmp.name } } }; return TestUtils.processFile(inputFile, getPlugins(myOptions)).then(() => { setTimeout(() => { const cssTempContent = TestUtils.readFile(cssTmp.name); const jsonTempContent = minifyJSON(TestUtils.readFile(dynamicTmp.name)); const cssTempExpectedContent = TestUtils.minify(TestUtils.readFile(inputFile.replace("input", "output-css"))); const jsonTempExpectedContent = minifyJSON(TestUtils.readFile(inputFile.replace("input.spec.scss", "output-json.spec.json"))); // expect the fallback CSS file will be equal to the generated one expect(cssTempContent).toEqual(cssTempExpectedContent); // expect the fallback JSON file will be equal expect(jsonTempContent).toEqual(jsonTempExpectedContent); // cleanup cssTmp.removeCallback(); dynamicTmp.removeCallback(); done(); }, 100); }, (err) => { console.log(err); throw err; }); } function getPlugins(pluginOptions) { return [TestUtils.plugin.initThemify(pluginOptions), TestUtils.plugin.sass(), TestUtils.plugin.themify(pluginOptions)]; }
brandboxmarketplace/themify
src/helpers/js-sass.ts
<filename>src/helpers/js-sass.ts const { isArray } = Array; /** * Convert a JS object to SASS * Credits to https://github.com/acdlite/json-sass * @example {color: 'red'} -> (color: red) * @param jsValue */ function JSToSASS(jsValue) { function _JSToSASS(value, initialIndentLevel = 0) { let indentLevel = initialIndentLevel; switch (typeof value) { case 'boolean': case 'number': return value.toString(); case 'string': return value; case 'object': if (isObject(value)) { indentLevel += 1; const indent = indentsToSpaces(indentLevel); const jsObj = value; let sassKeyValPairs: string[] = []; sassKeyValPairs = Object.keys(jsObj).reduce( (result, key: string) => { const jsVal = jsObj[key]; const sassVal: string = _JSToSASS(jsVal, indentLevel); if (isNotUndefined(sassVal)) { result.push(`${key}: ${sassVal}`); } return result; }, [] as string[] ); const result = `(\n${indent + sassKeyValPairs.join(',\n' + indent)}\n${indentsToSpaces(indentLevel - 1)})`; indentLevel -= 1; return result; } else if (isArray(value)) { const sassVals: string[] = []; for (let i = 0; i < value.length; i++) { const v = value[i]; if (isNotUndefined(v)) { sassVals.push(_JSToSASS(v, indentLevel)); } } return '(' + sassVals.join(', ') + ')'; } else if (isNull(value)) { return 'null'; } else { return value.toString(); } default: return; } } return _JSToSASS(jsValue); } function indentsToSpaces(indentCount: number) { return Array(indentCount + 1).join(' '); } function isObject(value) { return Object.prototype.toString.call(value) === '[object Object]'; } function isNull(value) { return value === null; } function isNotUndefined(value) { return typeof value !== 'undefined'; } module.exports = JSToSASS;
brandboxmarketplace/themify
src/index.ts
<gh_stars>100-1000 import { minifyJSON } from './helpers/json.util'; import { minifyCSS } from './helpers/css.util'; const postcss = require('postcss'); const fs = require('fs-extra'); const THEMIFY = 'themify'; const JSToSass = require('./helpers/js-sass'); export interface ThemifyOptions { /** * Whether we would like to generate the CSS variables. * This should be true, unless you want to inject them yourself. */ createVars: boolean; /** * Palette configuration */ palette: any; /** * A class prefix to append to the generated themes classes */ classPrefix: string; /** * Whether to generate a fallback for legacy browsers (ahm..ahm..) that do not supports CSS Variables */ screwIE11: boolean; /** * Legacy browser fallback */ fallback: { /** * An absolute path to the fallback CSS. */ cssPath: string | null; /** * An absolute path to the fallback JSON. * This file contains variable that will be replace in runtime, for legacy browsers */ dynamicPath: string | null; }; } const defaultOptions: ThemifyOptions = { createVars: true, palette: {}, classPrefix: '', screwIE11: true, fallback: { cssPath: null, dynamicPath: null } }; /** supported color variations */ const ColorVariation = { DARK: 'dark', LIGHT: 'light' }; function buildOptions(options: ThemifyOptions) { if (!options) { throw new Error(`options is required.`); } // make sure we have a palette if (!options.palette) { throw new Error(`The 'palette' option is required.`); } return { ...defaultOptions, ...options }; } /** * * @param {string} filePath * @param {string} output * @returns {Promise<any>} */ function writeToFile(filePath: string, output: string) { return fs.outputFile(filePath, output); } /** * Get the rgba as 88, 88, 33 instead rgba(88, 88, 33, 1) * @param value */ function getRgbaNumbers(value: string) { return hexToRgba(value) .replace('rgba(', '') .replace(', 1)', ''); } /** Define the default variation */ const defaultVariation = ColorVariation.LIGHT; /** An array of variation values */ const variationValues: string[] = (Object as any).values(ColorVariation); /** An array of all non-default variations */ const nonDefaultVariations: string[] = variationValues.filter(v => v !== defaultVariation); function themify(options: ThemifyOptions) { /** Regex to get the value inside the themify parenthesis */ const themifyRegExp = /themify\(([^)]+)\)/gi; /** * Define the method of color execution */ const enum ExecutionMode { CSS_VAR = 'CSS_VAR', CSS_COLOR = 'CSS_COLOR', DYNAMIC_EXPRESSION = 'DYNAMIC_EXPRESSION' } options = buildOptions(options); return root => { // process fallback CSS, without mutating the rules if (options.screwIE11 === false) { processFallbackRules(root); } // mutate the existing rules processRules(root); }; /** * @example themify({"light": ["primary-0", 0.5], "dark": "primary-700"}) * @example themify({"light": "primary-0", "dark": "primary-700"}) * @example linear-gradient(themify({"color": "primary-200", "opacity": "1"}), themify({"color": "primary-300", "opacity": "1"})) * @example themify({"light": ["primary-100", "1"], "dark": ["primary-100", "1"]}) * @example 1px solid themify({"light": ["primary-200", "1"], "dark": ["primary-200", "1"]}) */ function getThemifyValue(propertyValue: string, execMode: ExecutionMode): { [variation: string]: string } { /** Remove the start and end ticks **/ propertyValue = propertyValue.replace(/'/g, ''); const colorVariations = {}; function normalize(value, variationName) { let parsedValue; try { parsedValue = JSON.parse(value); } catch (ex) { throw new Error(`fail to parse the following expression: ${value}.`); } const currentValue = parsedValue[variationName]; /** For example: background-color: themify((light: primary-100)); */ if (!currentValue) { throw new Error(`${value} has one variation.`); } // convert to array if (!Array.isArray(currentValue)) { // color, alpha parsedValue[variationName] = [currentValue, 1]; } else if (!currentValue.length || !currentValue[0]) { throw new Error('Oops. Received an empty color!'); } if (options.palette) return parsedValue[variationName]; } // iterate through all variations variationValues.forEach(variationName => { // replace all 'themify' tokens with the right string colorVariations[variationName] = propertyValue.replace(themifyRegExp, (occurrence, value) => { // parse and normalize the color const parsedColor = normalize(value, variationName); // convert it to the right format return translateColor(parsedColor, variationName, execMode); }); }); return colorVariations; } /** * Get the underline color, according to the execution mode * @param colorArr two sized array with the color and the alpha * @param variationName the name of the variation. e.g. light / dark * @param execMode */ function translateColor(colorArr: [string, string], variationName: string, execMode: ExecutionMode) { const [colorVar, alpha] = colorArr; // returns the real color representation const underlineColor = options.palette[variationName][colorVar]; if (!underlineColor) { // variable is not mandatory in non-default variations if (variationName !== defaultVariation) { return null; } throw new Error(`The variable name '${colorVar}' doesn't exists in your palette.`); } switch (execMode) { case ExecutionMode.CSS_COLOR: // with default alpha - just returns the color if (alpha === '1') { return underlineColor; } // with custom alpha, convert it to rgba const rgbaColorArr = getRgbaNumbers(underlineColor); return `rgba(${rgbaColorArr}, ${alpha})`; case ExecutionMode.DYNAMIC_EXPRESSION: // returns it in a unique pattern, so it will be easy to replace it in runtime return `%[${variationName}, ${colorVar}, ${alpha}]%`; default: // return an rgba with the CSS variable name return `rgba(var(--${colorVar}), ${alpha})`; } } /** * Walk through all rules, and replace each themify occurrence with the corresponding CSS variable. * @example background-color: themify(primary-300, 0.5) => background-color: rgba(var(--primary-300),0.6) * @param root */ function processRules(root) { root.walkRules(rule => { if (!hasThemify(rule.toString())) { return; } let aggragatedSelectorsMap = {}; let aggragatedSelectors: string[] = []; let createdRules: any[] = []; const variationRules = { [defaultVariation]: rule }; rule.walkDecls(decl => { const propertyValue = decl.value; if (!hasThemify(propertyValue)) return; const property = decl.prop; const variationValueMap = getThemifyValue(propertyValue, ExecutionMode.CSS_VAR); const defaultVariationValue = variationValueMap[defaultVariation]; decl.value = defaultVariationValue; // indicate if we have a global rule, that cannot be nested const createNonDefaultVariationRules = isAtRule(rule); // don't create extra CSS for global rules if (createNonDefaultVariationRules) { return; } // create a new declaration and append it to each rule nonDefaultVariations.forEach(variationName => { const currentValue = variationValueMap[variationName]; // variable for non-default variation is optional if (!currentValue || currentValue === 'null') { return; } // when the declaration is the same as the default variation, // we just need to concatenate our selector to the default rule if (currentValue === defaultVariationValue) { const selector = getSelectorName(rule, variationName); // append the selector once if (!aggragatedSelectorsMap[variationName]) { aggragatedSelectorsMap[variationName] = true; aggragatedSelectors.push(selector); } } else { // creating the rule for the first time if (!variationRules[variationName]) { const clonedRule = createRuleWithVariation(rule, variationName); variationRules[variationName] = clonedRule; // append the new rule to the array, so we can append it later createdRules.push(clonedRule); } const variationDecl = createDecl(property, variationValueMap[variationName]); variationRules[variationName].append(variationDecl); } }); }); if (aggragatedSelectors.length) { rule.selectors = [...rule.selectors, ...aggragatedSelectors]; } // append each created rule if (createdRules.length) { createdRules.forEach(r => root.append(r)); } }); } /** * indicate if we have a global rule, that cannot be nested * @param rule * @return {boolean} */ function isAtRule(rule) { return rule.parent && rule.parent.type === 'atrule'; } /** * Walk through all rules, and generate a CSS fallback for legacy browsers. * Two files shall be created for full compatibility: * 1. A CSS file, contains all the rules with the original color representation. * 2. A JSON with the themify rules, in the following form: * themify(primary-100, 0.5) => %[light,primary-100,0.5)% * @param root */ function processFallbackRules(root) { // an output for each execution mode const output = { [ExecutionMode.CSS_COLOR]: [], [ExecutionMode.DYNAMIC_EXPRESSION]: {} }; // initialize DYNAMIC_EXPRESSION with all existing variations variationValues.forEach(variation => (output[ExecutionMode.DYNAMIC_EXPRESSION][variation] = [])); // define which modes need to be processed const execModes = [ExecutionMode.CSS_COLOR, ExecutionMode.DYNAMIC_EXPRESSION]; walkFallbackAtRules(root, execModes, output); walkFallbackRules(root, execModes, output); writeFallbackCSS(output); } function writeFallbackCSS(output) { // write the CSS & JSON to external files if (output[ExecutionMode.CSS_COLOR].length) { // write CSS fallback; const fallbackCss = output[ExecutionMode.CSS_COLOR].join(''); writeToFile(options.fallback.cssPath as string, minifyCSS(fallbackCss)); // creating a JSON for the dynamic expressions const jsonOutput = {}; variationValues.forEach(variationName => { jsonOutput[variationName] = output[ExecutionMode.DYNAMIC_EXPRESSION][variationName] || []; jsonOutput[variationName] = minifyJSON(jsonOutput[variationName].join('')); // minify the CSS output jsonOutput[variationName] = minifyCSS(jsonOutput[variationName]); }); // stringify and save const dynamicCss = JSON.stringify(jsonOutput); writeToFile(options.fallback.dynamicPath as string, dynamicCss); } } function walkFallbackAtRules(root, execModes, output) { root.walkAtRules(atRule => { if (atRule.nodes && hasThemify(atRule.toString())) { execModes.forEach(mode => { const clonedAtRule = atRule.clone(); clonedAtRule.nodes.forEach(rule => { rule.walkDecls(decl => { const propertyValue = decl.value; // replace the themify token, if exists if (hasThemify(propertyValue)) { const colorMap = getThemifyValue(propertyValue, mode); decl.value = colorMap[defaultVariation]; } }); }); let rulesOutput = mode === ExecutionMode.DYNAMIC_EXPRESSION ? output[mode][defaultVariation] : output[mode]; rulesOutput.push(clonedAtRule); }); } }); } function walkFallbackRules(root, execModes, output) { root.walkRules(rule => { if (isAtRule(rule) || !hasThemify(rule.toString())) { return; } const ruleModeMap = {}; rule.walkDecls(decl => { const propertyValue = decl.value; if (!hasThemify(propertyValue)) return; const property = decl.prop; execModes.forEach(mode => { const colorMap = getThemifyValue(propertyValue, mode); // lazily creating a new rule for each variation, for the specific mode if (!ruleModeMap.hasOwnProperty(mode)) { ruleModeMap[mode] = {}; variationValues.forEach(variationName => { let newRule; if (variationName === defaultVariation) { newRule = cloneEmptyRule(rule); } else { newRule = createRuleWithVariation(rule, variationName); } // push the new rule into the right place, // so we can write them later to external file let rulesOutput = mode === ExecutionMode.DYNAMIC_EXPRESSION ? output[mode][variationName] : output[mode]; rulesOutput.push(newRule); ruleModeMap[mode][variationName] = newRule; }); } // create and append a new declaration variationValues.forEach(variationName => { const underlineColor = colorMap[variationName]; if (underlineColor && underlineColor !== 'null') { const newDecl = createDecl(property, colorMap[variationName]); ruleModeMap[mode][variationName].append(newDecl); } }); }); }); }); } function createDecl(prop, value) { return postcss.decl({ prop, value }); } /** * check if there's a themify keyword in this declaration * @param propertyValue */ function hasThemify(propertyValue) { return propertyValue.indexOf(THEMIFY) > -1; } /** * Create a new rule for the given variation, out of the original rule * @param rule * @param variationName */ function createRuleWithVariation(rule, variationName) { const selector = getSelectorName(rule, variationName); return postcss.rule({ selector }); } /** * Get a selector name for the given rule and variation * @param rule * @param variationName */ function getSelectorName(rule, variationName) { const selectorPrefix = `.${options.classPrefix || ''}${variationName}`; return rule.selectors .map(selector => { return `${selectorPrefix} ${selector}`; }) .join(','); } function cloneEmptyRule(rule, overrideConfig?) { const clonedRule = rule.clone(overrideConfig); // remove all the declaration from this rule clonedRule.removeAll(); return clonedRule; } } /** * Generating a SASS definition file with the palette map and the CSS variables. * This file should be injected into your bundle. */ function init(options) { options = buildOptions(options); return root => { const palette = options.palette; const css = generateVars(palette, options.classPrefix); const parsedCss = postcss.parse(css); root.prepend(parsedCss); }; /** * This function responsible for creating the CSS variable. * * The output should look like the following: * * .light { --primary-700: 255, 255, 255; --primary-600: 248, 248, 249; --primary-500: 242, 242, 244; * } * * .dark { --primary-700: 255, 255, 255; --primary-600: 248, 248, 249; --primary-500: 242, 242, 244; * } * */ function generateVars(palette, prefix) { let cssOutput = ''; prefix = prefix || ''; // iterate through the different variations Object.keys(palette).forEach(variationName => { const selector = variationName === ColorVariation.LIGHT ? ':root' : `.${prefix}${variationName}`; const variationColors = palette[variationName]; // make sure we got colors for this variation if (!variationColors) { throw new Error(`Expected map of colors for the variation name ${variationName}`); } const variationKeys = Object.keys(variationColors); // generate CSS variables const vars = variationKeys .map(varName => { return `--${varName}: ${getRgbaNumbers(variationColors[varName])};`; }) .join(' '); // concatenate the variables to the output const output = `${selector} {${vars}}`; cssOutput = `${cssOutput} ${output}`; }); // generate the $palette variable cssOutput += `$palette: ${JSToSass(palette)};`; return cssOutput; } } function hexToRgba(hex, alpha = 1): string { hex = hex.replace('#', ''); const r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16); const g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16); const b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16); return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')'; } module.exports = { initThemify: postcss.plugin('datoThemes', init), themify: postcss.plugin('datoThemes', themify) };
brandboxmarketplace/themify
__tests__/unmatch-palette.spec.ts
<filename>__tests__/unmatch-palette.spec.ts import {TestUtils} from "./test.util"; const options = { palette: TestUtils.unmatchPalette }; const plugins = [TestUtils.plugin.sass(), TestUtils.plugin.themify(options)]; TestUtils.run('Themify - Valid CSS with Unmatch Palette', '__tests__/unmatch-palette/*.input.spec.scss', plugins);
brandboxmarketplace/themify
__tests__/test.util.ts
<reponame>brandboxmarketplace/themify import {minifyCSS} from "../src/helpers/css.util"; const glob = require("glob"); const path = require('path'); const fs = require('fs'); const postcss = require('postcss'); const sass = require('@datorama/postcss-node-sass'); import {ProcessOptions} from "postcss"; import palette from './palettes/palette'; import tinyPalette from './palettes/tiny-palette'; import unmatchPalette from './palettes/unmatch-palette'; const {initThemify, themify} = require('../src/index'); export class TestUtils { static plugin = { initThemify, sass, themify }; static get defaultPalette() { return palette; } static get tinyPalette() { return tinyPalette; } static get unmatchPalette() { return unmatchPalette; } static run(suite: string, filesGlob: string, plugins: any[], withError = false) { const inputFiles = glob.sync(filesGlob); describe(suite, () => { inputFiles.forEach((inputFile) => { const testName = this.getTestName(inputFile); it(testName, () => { return this.testFile(inputFile, plugins, withError); }); }); }); } static testFile(inputFilename: string, plugins: any[], withError = false): any { const outputFile = `./${inputFilename.replace('input', 'output')}`; const expected = this.readFile(outputFile); const exp = expect(this.processFile(inputFilename, plugins)); if (withError) { return exp.rejects.toMatch(expected); } return exp.resolves.toEqual(this.minify(expected)); } static processFile(inputFilename: string, plugins: any[]) { const inputFile = `./${inputFilename}`; const outputFile = `./${inputFilename.replace('input', 'output')}`; const input = this.readFile(inputFile); const options: ProcessOptions = {}; options.from = inputFile; options.to = outputFile; return postcss(plugins) .process(input, options) .then(result => { return this.minify(result.css); }, error => { throw error.message; }); } static minify(css) { return minifyCSS(css); } static readFile(fileName) { return fs.readFileSync(fileName, 'utf8').toString(); } static getTestName(filePath) { const fileName = path.basename(filePath); const inputPos = fileName.indexOf(".input"); return fileName.substring(0, inputPos); } }
brandboxmarketplace/themify
src/utils.ts
let JSONFallbackCache; let _hasNativeSupport; export type Theme = { [name: string]: { [variable: string]: string; }; }; /** * * @param {string} path */ export function loadCSS(path: string, callback) { const head = document.getElementsByTagName('head')[0]; const style = document.createElement('link'); style.href = path; style.rel = 'stylesheet'; style.onload = callback; head.appendChild(style); } /** * * @param {string} style */ export function injectStyle(style: string) { /** Don't replace the style tag, otherwise you will remove the old changes */ if (hasNativeCSSProperties()) { inject(); } else { /** Use the same style tag as we replace all either way */ const styleTag = document.getElementById('themify') as HTMLLinkElement; if (!styleTag) { inject(); } else { styleTag.innerHTML = style; } } function inject() { let node = document.createElement('style'); node.id = 'themify'; node.innerHTML = style; document.head.appendChild(node); } } /** * * .dark { * --primary-100: 30, 24, 33; * } * * :root { * --primary-100: 22, 21, 22; * } * * @param customTheme * @returns {string} */ export function _generateNewVariables(customTheme: Theme) { // First, we need the variations [dark, light] const variations = Object.keys(customTheme); return variations.reduce((finalOutput, variation) => { // Next, we need the variation keys [primary-100, accent-100] const variationKeys = Object.keys(customTheme[variation]); const variationOutput = variationKeys.reduce((acc, variable) => { const value = normalizeColor(customTheme[variation][variable]); return (acc += `--${variable}: ${value};`); }, ''); return (finalOutput += `${variation === 'light' ? ':root' : '.' + variation}{${variationOutput}}`); }, ''); } /** * * @returns {boolean} */ export function hasNativeCSSProperties() { if (_hasNativeSupport != null) { return _hasNativeSupport; } _hasNativeSupport = (window as any).CSS && (window as any).CSS.supports && (window as any).CSS.supports('--fake-var', 0); return _hasNativeSupport; } /** * Load the CSS fallback file on load */ export function loadCSSVariablesFallback(path: string, cb) { if (!hasNativeCSSProperties()) { loadCSS(path, cb); } } function loadJSON(url, cb) { const req = new XMLHttpRequest(); req.overrideMimeType('application/json'); req.open('GET', url, true); req.onload = function() { cb(JSON.parse(req.responseText)); }; req.send(null); } /** * * @param customTheme */ export function replaceColors(fallbackJSONPath, customTheme, palette) { if (customTheme) { if (hasNativeCSSProperties()) { const newColors = _generateNewVariables(customTheme); injectStyle(newColors); } else { const replace = JSONFallback => { JSONFallbackCache = JSONFallback; _handleUnSupportedBrowsers(customTheme, palette, JSONFallbackCache); }; if (JSONFallbackCache) { replace(JSONFallbackCache); } else { loadJSON(fallbackJSONPath, replace); } } } } /** * * @param customTheme */ export function _handleUnSupportedBrowsers(customTheme, palette, JSONFallback) { const themifyRegExp = /%\[(.*?)\]%/gi; const merged = mergeDeep(palette, customTheme); let finalOutput = Object.keys(customTheme).reduce((acc, variation) => { let value = JSONFallback[variation].replace(themifyRegExp, (occurrence, value) => { const [variation, variable, opacity] = value.replace(/\s/g, '').split(','); const color = merged[variation][variable]; const normalized = hexToRGB(color, opacity); return normalized; }); return (acc += value); }, ''); injectStyle(finalOutput); return finalOutput; } /** * Omit the rgb and braces from rgb * rgb(235, 246, 244) => 235, 246, 244 * @param rgb * @returns {string} */ function normalizeRgb(rgb: string) { return rgb.replace('rgb(', '').replace(')', ''); } /** * * @param color * @returns {*} */ function normalizeColor(color: string) { if (isHex(color)) { return normalizeRgb(hexToRGB(color)); } if (isRgb(color)) { return normalizeRgb(color); } return color; } /** * * @param color * @returns {boolean} */ function isHex(color: string) { return color.indexOf('#') > -1; } /** * * @param color * @returns {boolean} */ function isRgb(color: string) { return color.indexOf('rgb') > -1; } /** * * @param hex * @param alpha * @returns {string} */ function hexToRGB(hex: string, alpha = false) { let c; if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) { c = hex.substring(1).split(''); if (c.length == 3) { c = [c[0], c[0], c[1], c[1], c[2], c[2]]; } c = '0x' + c.join(''); if (alpha) { return `rgba(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')}, ${alpha})`; } return `rgb(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')})`; } throw new Error('Bad Hex'); } /** * * @param target * @param sources * @returns {*} */ function mergeDeep(target, ...sources) { if (!sources.length) return target; const source = sources.shift(); if (isObject(target) && isObject(source)) { for (const key in source) { if (isObject(source[key])) { if (!target[key]) Object.assign(target, { [key]: {} }); mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } } } return mergeDeep(target, ...sources); } /** * * @param item * @returns {*|boolean} */ function isObject(value: any) { return Object.prototype.toString.call(value) === '[object Object]'; } module.exports = { replaceColors, loadCSSVariablesFallback, _handleUnSupportedBrowsers, _generateNewVariables };
brandboxmarketplace/themify
src/helpers/css.util.ts
const _cleanCSS = require('clean-css'); const cleanCSS = new _cleanCSS({}); export function minifyCSS(css): string { return cleanCSS.minify(css).styles; }
brandboxmarketplace/themify
__tests__/css-helpers.spec.ts
<filename>__tests__/css-helpers.spec.ts import {TestUtils} from "./test.util"; const options = { palette: TestUtils.tinyPalette }; const plugins = [TestUtils.plugin.initThemify(options), TestUtils.plugin.sass(), TestUtils.plugin.themify(options)]; TestUtils.run('Themify - CSS Helpers', '__tests__/theme-helpers/*.input.spec.scss', plugins);
brandboxmarketplace/themify
__tests__/invalid-css.spec.ts
import {TestUtils} from "./test.util"; const options = { palette: TestUtils.defaultPalette }; const plugins = [TestUtils.plugin.sass(), TestUtils.plugin.themify(options)]; TestUtils.run('Themify - Invalid CSS', '__tests__/invalid-css/*.input.spec.scss', plugins, true);
brandboxmarketplace/themify
__tests__/valid-css.spec.ts
<filename>__tests__/valid-css.spec.ts import {TestUtils} from "./test.util"; const options = { palette: TestUtils.defaultPalette }; const plugins = [TestUtils.plugin.sass(), TestUtils.plugin.themify(options)]; TestUtils.run('Themify - Valid CSS', '__tests__/valid-css/*.input.spec.scss', plugins);
ies-fe-sh/hire
promise-concurrency/src/index.ts
import { ConcurrencyResult } from './concurrency-result' export type Task<T> = () => Promise<T> export class PromiseConcurrencyController<T> { activeCount = 0 pendingCount = 0 constructor(public readonly size: number) {} run(...tasks: Task<T>[]): ConcurrencyResult<T> {} async stop(): Promise<void> {} resume() {} }
zhangCan112/stm_web_project
stmproject/src/utils/urls.ts
const prefix = '/v1' /// 用户信息 const USER = prefix + '/user/' ///登录 const LOGIN = prefix + '/user/login' ///注册 const LOGOUT = prefix + '/user/logout' /// 健康检查 const HEALTH = prefix + '/user/health' const URLS = { USER, LOGIN, LOGOUT, HEALTH, } export default URLS
zhangCan112/stm_web_project
stmproject/src/pages/login/login.tsx
import React, { Component } from 'react'; import { Form, Icon, Input, Button, Checkbox, message } from 'antd'; import css from './login.module.css'; import { FormComponentProps } from 'antd/lib/form/Form'; import { Link } from 'react-router-dom'; import { CheckboxChangeEvent } from 'antd/lib/checkbox'; import { GET, filterSuccessCode } from "../../utils/request"; import URLS from "../../utils/urls"; import { delay } from "../../utils/tools"; import history from '../../history' interface IProps extends FormComponentProps<any> { } class Login extends Component<IProps> { render() { const { getFieldDecorator } = this.props.form; return ( <Form onSubmit={this.handleSubmit}> <div className={css.login}> <p className={css.title}>STM登录</p> <Form.Item> {getFieldDecorator('username', { rules: [{ required: true, message: '请输入用户名!' }], })( <Input placeholder="用户名" prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} style={{ width: 340, height: 40, opacity: 0.85 }} /> )} </Form.Item> <Form.Item> {getFieldDecorator('password', { rules: [{ required: true, message: '请输入密码!' }], })( <Input.Password placeholder="密码" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} style={{ width: 340, height: 40, opacity: 0.85 }} /> )} </Form.Item> <Form.Item> <div className={css.buttonBox}> <Checkbox onChange={this.handleRemember} style={{ color: 'white' }}>记住登录信息</Checkbox> <Button type="primary" htmlType="submit" style={{ width: 340, height: 40, fontSize: 20 }}>登录</Button> <div className={css.help}> <Link to="/forget"> <p className={css.text}><span className={css.dot}>*</span>忘记密码</p></Link> <Link to="/register"> <p className={css.text}>注册新用户</p></Link> </div> </div> </Form.Item> </div> </Form> ); } handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { this.login(values) } }); } login = async (values: { [key: string]: any }) => { let hide = message.loading("登录中...", 0) let result = await GET(URLS.LOGIN, values) .then(filterSuccessCode) .catch((e: Error) => { return e }) await delay(1000) hide() if (result instanceof Error) { let err = result as Error message.error(err.message) return } message.success("登录成功!即将跳转到主页...", 0.75, ()=>{ history.replace('/') }) } handleRemember = (e: CheckboxChangeEvent) => { console.log(`checked = ${e.target.checked}`); } } export default Form.create({ name: 'login' })(Login);
zhangCan112/stm_web_project
stmproject/src/utils/tools.ts
<filename>stmproject/src/utils/tools.ts<gh_stars>0 /** * 延时毫秒执行 * @param millisecond 延时的毫秒数 */ export const delay = async (millisecond: number) => { await new Promise((resovle) => { setTimeout(()=>{ resovle() }, millisecond) }) } /** * 倒计时 * @param handler 每次间隔的回调 * @param count 总计时次数 * @param interval 计时间隔 * @returns 终止倒计时的执行函数(stop) */ export const countdown = (handler:(lefts: number)=>void, count: number, interval: number = 1000) => { let start = new Date().getTime() let end = new Date(start + (count * interval)).getTime() //立即开始 handler(Math.ceil(count)) let intervalHandler = setInterval(()=>{ let now = new Date().getTime() let lefts = end - now if ((lefts) < (interval * 0.5)) { //should end clearInterval(intervalHandler) handler(0) return } handler(Math.ceil(lefts/interval)) }, interval) return ()=>{clearInterval(intervalHandler)} }
zhangCan112/stm_web_project
stmproject/src/components/tomato/countdownButton.tsx
import React, { Component } from 'react'; import { Icon, Modal } from 'antd'; import { countdown } from "../../utils/tools"; import css from './tomato.module.css'; const { confirm } = Modal; enum CountdownStage { /** * 未开始 */ Normal, /** * 工作 */ Working, /** * 休息 */ Resting, } interface IProps { /** * 开始的标题内容 */ title: string, /** * 工作倒计时时长,单位分钟,默认25分钟 */ workMinutes: number, /** * 休息倒计时时长,单位分钟,默认5分钟 */ restMinutes: number, /** * 倒计时被终止时的回调 * @param stage 被终止时的状态阶段 */ onTerminated?: (stage: CountdownStage) => void, /** * 倒计时正常结束时的回调 * @param stage 被终止时的状态阶段 */ onEnd?: (stage: CountdownStage) => void, } interface IState { stage: CountdownStage, leftSeconds?: number, } export default class CountdownButton extends Component<IProps, IState> { /** * 计时器终止句柄 */ timeHandler?: () => void constructor(props: IProps) { super(props) this.state = { stage: CountdownStage.Normal, } } render() { let lefts = this.state.leftSeconds || 0 let totalTime = this.getTotalTime() let percent = 0; if (totalTime > 0) { percent = 1 - (lefts / totalTime) } let progressOverStyle = { backgroundColor: '#FFFFFF' } let progressClipStyle = { backgroundColor: '#FFFFFF' } as any if (this.state.stage === CountdownStage.Normal) { progressOverStyle = { backgroundColor: '#FFFFFF' } progressClipStyle = { backgroundColor: '#FFFFFF' } } else { progressOverStyle = { backgroundColor: '#FFFFFF' } progressClipStyle = { backgroundColor: '#4A90E2', width: `${percent * 100}%` } } return ( <div className={css.progressOver} style={progressOverStyle} onClick={this.onClick}> <div style={progressClipStyle}> <div className={css.button} > <Icon style={{ marginRight: 5 }} type={this.getButtonIcon()} /> {this.getButtonTitle()} </div> </div> </div> ) } onClick = () => { switch (this.state.stage) { case CountdownStage.Working: this.onWorking() break; case CountdownStage.Resting: this.terminateRest() break; default: this.startWork() break; } } onWorking = () => { if (this.state.leftSeconds && this.state.leftSeconds > 0) { confirm({ content: '您目前正在一个番茄工作时间中,要放弃这个番茄吗?', okText: '是的', cancelText: '取消', onOk: () => { this.terminateWork() }, onCancel: () => { }, }); } else { //记录当前工作弹窗 this.endWork() this.startRest() } } startWork = () => { this.timeHandler = countdown( (lefts: number) => { this.setState({ stage: CountdownStage.Working, leftSeconds: lefts }) }, this.props.workMinutes * 60, 1000) } endWork = () => { this.timeHandler && this.timeHandler() this.props.onEnd && this.props.onEnd(CountdownStage.Working) } terminateWork = () => { this.timeHandler && this.timeHandler() this.props.onTerminated && this.props.onTerminated(CountdownStage.Working) this.setState({ stage: CountdownStage.Normal, }) } startRest = () => { this.timeHandler = countdown( (resetLefts: number) => { this.setState({ stage: CountdownStage.Resting, leftSeconds: resetLefts }) }, this.props.restMinutes * 60, 1000) } endRest = () => { this.timeHandler && this.timeHandler() this.props.onEnd && this.props.onEnd(CountdownStage.Resting) this.setState({ stage: CountdownStage.Normal, }) } terminateRest = () => { this.timeHandler && this.timeHandler() this.props.onTerminated && this.props.onTerminated(CountdownStage.Resting) this.setState({ stage: CountdownStage.Normal, }) } showConfirm = () => { confirm({ title: 'Do you want to delete these items?', content: 'When clicked the OK button, this dialog will be closed after 1 second', onOk() { return new Promise((resolve, reject) => { setTimeout(Math.random() > 0.5 ? resolve : reject, 1000); }).catch(() => console.log('Oops errors!')); }, onCancel() { }, }); } getButtonTitle = () => { let btnTitle = `开始${this.props.title}` switch (this.state.stage) { case CountdownStage.Working: btnTitle = `处理${this.props.title}` break; case CountdownStage.Resting: btnTitle = `休息中` break; default: btnTitle = `开始${this.props.title}` break; } return btnTitle; } getButtonIcon = () => { switch (this.state.stage) { case CountdownStage.Working: return "loading"; case CountdownStage.Resting: return "clock-circle"; default: return "play-circle"; } } getTotalTime = () => { switch (this.state.stage) { case CountdownStage.Working: return this.props.workMinutes * 60; case CountdownStage.Resting: return this.props.restMinutes * 60; default: return 0; } } secondsToTime = (seconds: number) => { let mintinues = Math.floor(seconds / 60) let restSeconds = seconds % 60 return (mintinues === 0 ? '' : `${mintinues}分`) + (restSeconds === 0 ? '' : `${restSeconds}秒`) } }
zhangCan112/stm_web_project
stmproject/src/pages/register/register.tsx
import React, { Component } from 'react'; import { Form, Input, Tooltip, Icon, Button, message } from 'antd'; import { FormComponentProps } from 'antd/lib/form/Form'; import styles from './register.module.css'; import { POST, filterSuccessCode } from "../../utils/request"; import URLS from "../../utils/urls"; import { delay } from "../../utils/tools"; import history from '../../history' import { Link } from 'react-router-dom'; import * as Path from '../../utils/routepaths' const userNameKey = "userName" const emailKey = "email" const passwordKey = "password" const confirmKey = "confirm" interface Iprops extends FormComponentProps<any> { } class RegistrationForm extends Component<Iprops> { state = { confirmDirty: false, autoCompleteResult: [], }; render() { const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; return ( <div className={styles.container}> <p className={styles.title}>用户注册</p> <Form {...formItemLayout} onSubmit={this.handleSubmit}> <Form.Item label="邮箱"> {getFieldDecorator(emailKey, { rules: [ { type: 'email', message: '邮箱格式不正确!', }, { required: true, message: '请输入您的邮箱!', }, ], })(<Input style={{ width: 340, height: 40, opacity: 0.85 }} />)} </Form.Item> <Form.Item label={ <span> 用户名&nbsp; <Tooltip title="您可以使用自定义的用户名登录"> <Icon type="question-circle-o" /> </Tooltip> </span> } > {getFieldDecorator(userNameKey, { rules: [{ required: true, message: '请输入你的用户名!', whitespace: true }], })( <Input style={{ width: 340, height: 40, opacity: 0.85 }} onFocus={this.handleDefaultUserName} />)} </Form.Item> <Form.Item label="密码" hasFeedback> {getFieldDecorator(passwordKey, { rules: [ { required: true, message: '请设置密码!', }, { validator: this.validateToNextPassword, }, ], })(<Input.Password style={{ width: 340, height: 40, opacity: 0.85 }} />)} </Form.Item> <Form.Item label="确认密码" hasFeedback> {getFieldDecorator(confirmKey, { rules: [ { required: true, message: '请确认密码!', }, { validator: this.compareToFirstPassword, }, ], })(<Input.Password onBlur={this.handleConfirmBlur} style={{ width: 340, height: 40, opacity: 0.85 }} />)} </Form.Item> <Form.Item {...tailFormItemLayout}> <div className={styles.buttonBox}> <Button type="primary" htmlType="submit" style={{ width: 340, height: 40, fontSize: 20 }}>注册</Button> <Link to={Path.Login}> <p className={styles.text}>>返回登录</p></Link> </div> </Form.Item> </Form> </div> ); } handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); this.props.form.validateFieldsAndScroll((err, values) => { if (!err) { this.postRegisterInfo(values) } }); }; postRegisterInfo = async (values: { [key: string]: any }) => { let hide = message.loading("正在提交注册信息...", 0) let result = await POST(URLS.USER, values) .then(filterSuccessCode) .catch((e: Error) => { return e }) await delay(1000) hide() if (result instanceof Error) { let err = result as Error message.error(err.message) return } message.success("注册成功!即将跳转登录页面...", 2.5, ()=>{ history.replace(Path.Login) }) } handleConfirmBlur = (e: React.FocusEvent<HTMLInputElement>) => { const { value } = e.target; this.setState({ confirmDirty: this.state.confirmDirty || !!value }); }; compareToFirstPassword = (rule: any, value: any, callback: any) => { const { form } = this.props; if (value && value !== form.getFieldValue(passwordKey)) { callback('两次密码输入不一致,请检查!'); } else { callback(); } }; validateToNextPassword = (rule: any, value: any, callback: any) => { const { form } = this.props; if (value && this.state.confirmDirty) { form.validateFields([confirmKey], { force: true }); } callback(); }; handleDefaultUserName = (e: React.FocusEvent<HTMLInputElement>) => { // 如果用户名中已有值,则不需要生成默认的用户名 const { value } = e.target; if (value && value.length > 0) { return } const { form } = this.props; // 如果邮箱一栏信息校验错误,无法生成默认的用户名 let emailErr = form.getFieldError(emailKey) if (emailErr) { return } // 用email的前缀名做用户名 let email = form.getFieldValue(emailKey) if (email) { form.setFieldsValue({ userName: email.split('@')[0] }) } } } const WrappedRegistrationForm = Form.create({ name: 'register' })(RegistrationForm); export default WrappedRegistrationForm