CombinedText stringlengths 4 3.42M |
|---|
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2005-2007 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package mx.rpc
{
import flash.events.EventDispatcher;
import flash.utils.getQualifiedClassName;
import flash.events.Event;
import mx.core.mx_internal;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.messaging.errors.MessagingError;
import mx.messaging.events.MessageEvent;
import mx.messaging.events.MessageFaultEvent;
import mx.messaging.messages.AsyncMessage;
import mx.messaging.messages.IMessage;
import mx.resources.IResourceManager;
import mx.resources.ResourceManager;
import mx.rpc.events.AbstractEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.InvokeEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectProxy;
import mx.utils.StringUtil;
import mx.netmon.NetworkMonitor;
use namespace mx_internal;
[ResourceBundle("rpc")]
/**
* An invoker is an object that actually executes a remote procedure call (RPC).
* For example, RemoteObject, HTTPService, and WebService objects are invokers.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class AbstractInvoker extends EventDispatcher
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* @private
*/
public function AbstractInvoker()
{
super();
_log = Log.getLogger("mx.rpc.AbstractInvoker");
activeCalls = new ActiveCalls();
}
//-------------------------------------------------------------------------
//
// Variables
//
//-------------------------------------------------------------------------
/**
* @private
*/
private var resourceManager:IResourceManager =
ResourceManager.getInstance();
//-------------------------------------------------------------------------
//
// Properties
//
//-------------------------------------------------------------------------
[Bindable("resultForBinding")]
/**
* The result of the last invocation.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get lastResult():Object
{
return _result;
}
[Inspectable(defaultValue="true", category="General")]
/**
* When this value is true, anonymous objects returned are forced to bindable objects.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get makeObjectsBindable():Boolean
{
return _makeObjectsBindable;
}
public function set makeObjectsBindable(b:Boolean):void
{
_makeObjectsBindable = b;
}
/**
* This property is set usually by framework code which wants to modify the
* behavior of a service invocation without modifying the way in which the
* service is called externally. This allows you to add a "filter" step on
* the method call to ensure for example that you do not return duplicate
* instances for the same id or to insert parameters for performing on-demand
* paging.
*
* When this is set to a non-null value on the send call, the operationManager function
* is called instead. It returns the token that the caller uses to be notified
* of the result. Typically the called function will at some point clear this
* property temporarily, then invoke the operation again actually sending it to
* the server this time.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var operationManager:Function;
/**
* Specifies an optional return type for the operation. Used in situations where
* you want to coerce the over-the-wire information into a specific ActionScript class
* or to provide metadata for other services as to the return type of this operation.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var resultType:Class;
/**
* Like resultType, used to define the ActionScript class used by a given operation though
* this property only applies to operations which return a multi-valued result (e.g. an Array
* or ArrayCollection (IList)). This property specifies an ActionScript class for the members of the
* array or array collection. When you set resultElementType, you do not have to set
* resultType. In that case, the operation returns an Array if makeObjectsbindable is
* false and an ArrayCollection otherwise.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public var resultElementType:Class;
/**
* Event dispatched for binding when the <code>result</code> property
* changes.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal static const BINDING_RESULT:String = "resultForBinding";
//-------------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------------
/**
* Cancels the last service invocation or an invokation with the specified ID.
* Even though the network operation may still continue, no result or fault event
* is dispatched.
*
* @param id The messageId of the invocation to cancel. Optional. If omitted, the
* last service invocation is canceled.
*
* @return The AsyncToken associated with the call that is cancelled or null if no call was cancelled.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function cancel(id:String = null):AsyncToken
{
if (id != null)
return activeCalls.removeCall(id);
else
return activeCalls.cancelLast();
}
/**
* Sets the <code>result</code> property of the invoker to <code>null</code>.
* This is useful when the result is a large object that is no longer being
* used.
*
* @param fireBindingEvent Set to <code>true</code> if you want anything
* bound to the result to update. Otherwise, set to
* <code>false</code>.
* The default value is <code>true</code>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function clearResult(fireBindingEvent:Boolean = true):void
{
if (fireBindingEvent)
setResult(null);
else
_result = null;
}
/**
* This hook is exposed to update the lastResult property. Since lastResult
* is ordinarily updated automatically by the service, you do not typically
* call this. It is used by managed services that want to ensure lastResult
* always points to "the" managed instance for a given identity even if the
* the service returns a new copy of the same object.
*
* @param result The new value for the lastResult property.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function setResult(result:Object):void
{
_result = result;
dispatchEvent(new flash.events.Event(BINDING_RESULT));
}
//-------------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------------
/**
* This method is overridden in subclasses to redirect the event to another
* class.
*
* @private
*/
mx_internal function dispatchRpcEvent(event:AbstractEvent):void
{
event.callTokenResponders();
if (!event.isDefaultPrevented())
{
dispatchEvent(event);
}
}
/**
* Monitor an rpc event that is being dispatched
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal function monitorRpcEvent(event:AbstractEvent):void
{
if (NetworkMonitor.isMonitoring())
{
if (event is mx.rpc.events.ResultEvent)
{
NetworkMonitor.monitorResult(event.message, mx.rpc.events.ResultEvent(event).result);
}
else if (event is mx.rpc.events.FaultEvent)
{
//trace(" AbstractInvoker: MonitorFault - message:" + event.message);
NetworkMonitor.monitorFault(event.message, mx.rpc.events.FaultEvent(event).fault);
}
}
}
/**
* Take the MessageAckEvent and take the result, store it, and broadcast out
* appropriately.
*
* @private
*/
mx_internal function resultHandler(event:MessageEvent):void
{
var token:AsyncToken = preHandle(event);
//if the handler didn't give us something just bail
if (token == null)
return;
if (processResult(event.message, token))
{
dispatchEvent(new flash.events.Event(BINDING_RESULT));
var resultEvent:ResultEvent = ResultEvent.createEvent(_result, token, event.message);
resultEvent.headers = _responseHeaders;
dispatchRpcEvent(resultEvent);
}
//no else, we assume process would have dispatched the faults if necessary
}
/**
* Take the fault and convert it into a rpc.events.FaultEvent.
*
* @private
*/
mx_internal function faultHandler(event:MessageFaultEvent):void
{
var msgEvent:MessageEvent = MessageEvent.createEvent(MessageEvent.MESSAGE, event.message);
var token:AsyncToken = preHandle(msgEvent);
// continue only on a matching or empty correlationId
// empty correlationIds could be the result of de/serialization errors
if ((token == null) &&
(AsyncMessage(event.message).correlationId != null) &&
(AsyncMessage(event.message).correlationId != "") &&
(event.faultCode != "Client.Authentication"))
{
return;
}
if (processFault(event.message, token))
{
var fault:Fault = new Fault(event.faultCode, event.faultString, event.faultDetail);
fault.content = event.message.body;
fault.rootCause = event.rootCause;
var faultEvent:FaultEvent = FaultEvent.createEvent(fault, token, event.message);
faultEvent.headers = _responseHeaders;
dispatchRpcEvent(faultEvent);
}
}
/**
* Return the id for the NetworkMonitor.
* @private
*/
mx_internal function getNetmonId():String
{
return null;
}
/**
* @private
*/
mx_internal function invoke(message:IMessage, token:AsyncToken = null) : AsyncToken
{
if (token == null)
token = new AsyncToken(message);
else
token.setMessage(message);
activeCalls.addCall(message.messageId, token);
var fault:Fault;
try
{
//asyncRequest.invoke(message, new AsyncResponder(resultHandler, faultHandler, token));
asyncRequest.invoke(message, new Responder(resultHandler, faultHandler));
dispatchRpcEvent(InvokeEvent.createEvent(token, message));
}
catch(e:MessagingError)
{
_log.warn(e.toString());
var errorText:String = resourceManager.getString(
"rpc", "cannotConnectToDestination",
[ asyncRequest.destination ]);
fault = new Fault("InvokeFailed", e.toString(), errorText);
new AsyncDispatcher(dispatchRpcEvent, [FaultEvent.createEvent(fault, token, message)], 10);
}
catch(e2:Error)
{
_log.warn(e2.toString());
fault = new Fault("InvokeFailed", e2.message);
new AsyncDispatcher(dispatchRpcEvent, [FaultEvent.createEvent(fault, token, message)], 10);
}
return token;
}
/**
* Find the matching call object and pass it back.
*
* @private
*/
mx_internal function preHandle(event:MessageEvent):AsyncToken
{
return activeCalls.removeCall(AsyncMessage(event.message).correlationId);
}
/**
* @private
*/
mx_internal function processFault(message:IMessage, token:AsyncToken):Boolean
{
return true;
}
/**
* @private
*/
mx_internal function processResult(message:IMessage, token:AsyncToken):Boolean
{
var body:Object = message.body;
if (makeObjectsBindable && (body != null) && (getQualifiedClassName(body) == "Object"))
{
_result = new ObjectProxy(body);
}
else
{
_result = body;
}
return true;
}
/**
* @private
*/
mx_internal function get asyncRequest():AsyncRequest
{
if (_asyncRequest == null)
{
_asyncRequest = new AsyncRequest();
}
return _asyncRequest;
}
/**
* @private
*/
mx_internal function set asyncRequest(req:AsyncRequest):void
{
_asyncRequest = req;
}
/**
* @private
*/
mx_internal var activeCalls:ActiveCalls;
/**
* @private
*/
mx_internal var _responseHeaders:Array;
/**
* @private
*/
mx_internal var _result:Object;
/**
* @private
*/
mx_internal var _makeObjectsBindable:Boolean;
/**
* @private
*/
private var _asyncRequest:AsyncRequest;
/**
* @private
*/
private var _log:ILogger;
}
}
|
package dagd.caughman {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Boot extends MovieClip {
private var velocityX:Number = 0;
private var velocityY:Number = 0;
public var isDead:Boolean = false;
public var points:Number = 0;
public function Boot() {
x= -100;
y= Math.random()*500+50;
velocityX = Math.random()*2+2;
//velocityY = Math.random()*2-1;
addEventListener(MouseEvent.MOUSE_DOWN, click);
}//End compiler
private function click(e:MouseEvent):void{
isDead =true;//reference to the game that it should be removed from the game
points=-100;
}//End Click
public function update():void {
x++;
//euler integration
x+= velocityX;
//y+= velocityY;
if(x>800) isDead=true;//kills it off screne
}//End Update
public function dispose():void{
removeEventListener(MouseEvent.MOUSE_DOWN,click);
}//End Dispose
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.core
{
/*
import mx.managers.ILayoutManager;
import flash.display.InteractiveObject;
import flash.geom.Matrix;
use namespace mx_internal;
*/
import mx.core.mx_internal;
import org.apache.royale.geom.Matrix;
/**
* @private
*/
public class UIComponentGlobals
{
/**
* @private
* A reference to the sole instance of the LayoutManager
* used by all components.
*
* <p>This property is set in the constructor of the Application class.
* If you need to override or replace LayoutManager,
* set UIComponent.layoutManager in your application's constructor
* after calling super().</p>
*/
// mx_internal static var layoutManager:ILayoutManager;
/**
* @private
* When this variable is non-zero, no methods queued
* by the <code>callLater()</code> method get invoked.
* This is used to allow short effects to play without interruption.
* This counter is incremented by suspendBackgroundProcessing(),
* decremented by resumeBackgroundProcessing(), and checked by
* callLaterDispatcher().
*/
mx_internal static var callLaterSuspendCount:int = 0;
/**
* @private
* There is a bug (139390) where setting focus from within callLaterDispatcher
* screws up the ActiveX player. We defer focus until enterframe.
*/
mx_internal static var callLaterDispatcherCount:int = 0;
/**
* @private
* There is a bug (139390) where setting focus from within callLaterDispatcher
* screws up the ActiveX player. We defer focus until enterframe.
*/
// mx_internal static var nextFocusObject:InteractiveObject;
/**
* @private
* This single Matrix is used to pass information from the
* horizontalGradientMatrix() or verticalGradientMatrix()
* utility methods to the drawRoundRect() method.
* Each call to horizontalGradientMatrix() or verticalGradientMatrix()
* simply calls createGradientBox() to stuff this Matrix with new values.
* We can keep restuffing the same Matrix object because these utility
* methods are only used inside a call to drawRoundRect()
* and the Matrix isn't needed after drawRoundRect() returns.
*/
mx_internal static var tempMatrix:Matrix = new Matrix();
/**
* @private
* A global flag that can be read by any component to determine
* whether it is currently executing in the context of a design
* tool such as Flash Builder's design view. Most components will
* never need to check this flag, but if a component needs to
* have different behavior at design time than at runtime, then it
* can check this flag.
*/
mx_internal static var designTime:Boolean = false;
/**
* A global flag that can be read by any component to determine
* whether it is currently executing in the context of a design
* tool such as Flash Builder's design view. Most components will
* never need to check this flag, but if a component needs to
* have different behavior at design time than at runtime, then it
* can check this flag.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get designMode():Boolean
{
return false; //designTime;
}
/**
* @private
*/
public static function set designMode(value:Boolean):void
{
//designTime = value;
}
/**
* @private
*/
private static var _catchCallLaterExceptions:Boolean = false;
/**
* A global flag that can is used to catch unhandled exceptions
* during execution of methods executed via callLater
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static function get catchCallLaterExceptions():Boolean
{
return _catchCallLaterExceptions;
}
/**
* @private
*/
public static function set catchCallLaterExceptions(value:Boolean):void
{
_catchCallLaterExceptions = value;
}
}
}
|
package io.decagames.rotmg.dailyQuests.messages.incoming {
import flash.utils.IDataInput;
import io.decagames.rotmg.dailyQuests.messages.data.QuestData;
import kabam.rotmg.messaging.impl.incoming.IncomingMessage;
public class QuestFetchResponse extends IncomingMessage {
public function QuestFetchResponse(param1:uint, param2:Function) {
super(param1, param2);
this.nextRefreshPrice = -1;
}
public var quests:Vector.<QuestData>;
public var nextRefreshPrice:int;
override public function parseFromInput(param1:IDataInput):void {
var _loc2_:int = param1.readShort();
this.quests = new Vector.<QuestData>(_loc2_);
var _loc3_:int = 0;
while (_loc3_ < _loc2_) {
this.quests[_loc3_] = new QuestData();
this.quests[_loc3_].parseFromInput(param1);
_loc3_++;
}
this.nextRefreshPrice = param1.readShort();
}
override public function toString():String {
return formatToString("QUESTFETCHRESPONSE", "quests", "nextRefreshPrice");
}
}
}
|
package kabam.rotmg.pets.view.components {
import com.company.assembleegameclient.ui.tooltip.ToolTip;
import kabam.rotmg.core.signals.ShowTooltipSignal;
import robotlegs.bender.bundles.mvcs.Mediator;
public class PetAbilityDisplayMediator extends Mediator {
[Inject]
public var view:PetAbilityDisplay;
[Inject]
public var showToolTip:ShowTooltipSignal;
override public function initialize():void {
this.view.addToolTip.add(this.onAddToolTip);
}
override public function destroy():void {
this.view.destroy();
}
private function onAddToolTip(_arg1:ToolTip):void {
this.showToolTip.dispatch(_arg1);
}
}
}
|
package com.ankamagames.dofus.network.messages.game.context.roleplay.npc
{
import com.ankamagames.jerakine.network.CustomDataWrapper;
import com.ankamagames.jerakine.network.ICustomDataInput;
import com.ankamagames.jerakine.network.ICustomDataOutput;
import com.ankamagames.jerakine.network.INetworkMessage;
import com.ankamagames.jerakine.network.utils.FuncTree;
import flash.utils.ByteArray;
public class PortalDialogCreationMessage extends NpcDialogCreationMessage implements INetworkMessage
{
public static const protocolId:uint = 2812;
private var _isInitialized:Boolean = false;
public var type:uint = 0;
public function PortalDialogCreationMessage()
{
super();
}
override public function get isInitialized() : Boolean
{
return super.isInitialized && this._isInitialized;
}
override public function getMessageId() : uint
{
return 2812;
}
public function initPortalDialogCreationMessage(mapId:Number = 0, npcId:int = 0, type:uint = 0) : PortalDialogCreationMessage
{
super.initNpcDialogCreationMessage(mapId,npcId);
this.type = type;
this._isInitialized = true;
return this;
}
override public function reset() : void
{
super.reset();
this.type = 0;
this._isInitialized = false;
}
override public function pack(output:ICustomDataOutput) : void
{
var data:ByteArray = new ByteArray();
this.serialize(new CustomDataWrapper(data));
writePacket(output,this.getMessageId(),data);
}
override public function unpack(input:ICustomDataInput, length:uint) : void
{
this.deserialize(input);
}
override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree
{
var tree:FuncTree = new FuncTree();
tree.setRoot(input);
this.deserializeAsync(tree);
return tree;
}
override public function serialize(output:ICustomDataOutput) : void
{
this.serializeAs_PortalDialogCreationMessage(output);
}
public function serializeAs_PortalDialogCreationMessage(output:ICustomDataOutput) : void
{
super.serializeAs_NpcDialogCreationMessage(output);
output.writeInt(this.type);
}
override public function deserialize(input:ICustomDataInput) : void
{
this.deserializeAs_PortalDialogCreationMessage(input);
}
public function deserializeAs_PortalDialogCreationMessage(input:ICustomDataInput) : void
{
super.deserialize(input);
this._typeFunc(input);
}
override public function deserializeAsync(tree:FuncTree) : void
{
this.deserializeAsyncAs_PortalDialogCreationMessage(tree);
}
public function deserializeAsyncAs_PortalDialogCreationMessage(tree:FuncTree) : void
{
super.deserializeAsync(tree);
tree.addChild(this._typeFunc);
}
private function _typeFunc(input:ICustomDataInput) : void
{
this.type = input.readInt();
if(this.type < 0)
{
throw new Error("Forbidden value (" + this.type + ") on element of PortalDialogCreationMessage.type.");
}
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Assert;
// var SECTION = "Types: int";
// var VERSION = "as3";
// var TITLE = "x is int";
var testcases = getTestCases();
function getTestCases() {
var array = new Array();
var item = 0;
var c = 0;
array[item++] = Assert.expectEq( "var c=0;c is int",true, c is int );
array[item++] = Assert.expectEq( "0 is int",true, 0 is int );
var d = 1;
array[item++] = Assert.expectEq( "var d=1;d is int",true, d is int );
array[item++] = Assert.expectEq( "1 is int",true, 1 is int );
var e = uint.MAX_VALUE;
array[item++] = Assert.expectEq( "var e=uint.MAX_VALUE;e is int",false, e is int );
array[item++] = Assert.expectEq( "uint.MAX_VALUE is int",false, uint.MAX_VALUE is int );
array[item++] = Assert.expectEq( "4294967295 is int",false, 4294967295 is int );
var f:int = -1;
array[item++] = Assert.expectEq( "var f=-1;f is int",true, f is int );
array[item++] = Assert.expectEq( "-1 is int",true, -1 is int );
var g:int = int.MAX_VALUE;
array[item++] = Assert.expectEq( "var g=int.MAX_VALUE;g is int",true, g is int );
array[item++] = Assert.expectEq( "int.MAX_VALUE is int",true, int.MAX_VALUE is int );
array[item++] = Assert.expectEq( "2147483647 is int",true, 2147483647 is int );
return ( array );
}
/*function test() {
for ( tc = 0; tc < testcases.length; tc++ ) {
testcases[tc].passed = writeTestCaseResult(
testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+ testcases[tc].actual );
testcases[tc].reason += ( testcases[tc].passed ) ? "" : "delete should not be allowed "
}
stopTest();
return ( testcases );
}*/
|
package org.flexlite.domUI.components
{
import flash.events.Event;
import org.flexlite.domCore.dx_internal;
import org.flexlite.domUI.components.supportClasses.ToggleButtonBase;
import org.flexlite.domUI.events.UIEvent;
import org.flexlite.domUtils.SharedMap;
use namespace dx_internal;
[DXML(show="true")]
/**
* 单选按钮
* @author dom
*/
public class RadioButton extends ToggleButtonBase
{
/**
* 构造函数
*/
public function RadioButton()
{
super();
groupName = "radioGroup";
}
override protected function get hostComponentKey():Object
{
return RadioButton;
}
/**
* 在RadioButtonGroup中的索引
*/
dx_internal var indexNumber:int = 0;
/**
* 所属的RadioButtonGroup
*/
dx_internal var radioButtonGroup:RadioButtonGroup = null;
override public function get enabled():Boolean
{
if (!super.enabled)
return false;
return !radioButtonGroup ||
radioButtonGroup.enabled;
}
/**
* 存储根据groupName自动创建的RadioButtonGroup列表
*/
private static var automaticRadioButtonGroups:SharedMap;
private var _group:RadioButtonGroup;
/**
* 此单选按钮所属的组。同一个组的多个单选按钮之间互斥。
* 若不设置此属性,则根据groupName属性自动创建一个唯一的RadioButtonGroup。
*/
public function get group():RadioButtonGroup
{
if (!_group&&_groupName)
{
if(!automaticRadioButtonGroups)
automaticRadioButtonGroups = new SharedMap;
var g:RadioButtonGroup = automaticRadioButtonGroups.get(_groupName);
if (!g)
{
g = new RadioButtonGroup();
g.name = _groupName;
automaticRadioButtonGroups.set(_groupName,g);
}
_group = g;
}
return _group;
}
public function set group(value:RadioButtonGroup):void
{
if (_group == value)
return;
if(radioButtonGroup)
radioButtonGroup.removeInstance(this);
_group = value;
_groupName = value ? group.name : "radioGroup";
groupChanged = true;
invalidateProperties();
invalidateDisplayList();
}
private var groupChanged:Boolean = false;
private var _groupName:String = "radioGroup";
/**
* 所属组的名称,具有相同组名的多个单选按钮之间互斥。默认值:"radioGroup"。
* 可以把此属性当做设置组的一个简便方式,作用与设置group属性相同,。
*/
public function get groupName():String
{
return _groupName;
}
public function set groupName(value:String):void
{
if (!value || value == "")
return;
_groupName = value;
if(radioButtonGroup)
radioButtonGroup.removeInstance(this);
_group = null;
groupChanged = true;
invalidateProperties();
invalidateDisplayList();
}
/**
* @inheritDoc
*/
override public function set selected(value:Boolean):void
{
super.selected = value;
invalidateDisplayList();
}
private var _value:Object;
/**
* 与此单选按钮关联的自定义数据。
* 当被点击时,所属的RadioButtonGroup对象会把此属性赋值给ItemClickEvent.item属性并抛出事件。
*/
public function get value():Object
{
return _value;
}
public function set value(value:Object):void
{
if (_value == value)
return;
_value = value;
if (selected && group)
group.dispatchEvent(new UIEvent(UIEvent.VALUE_COMMIT));
}
/**
* @inheritDoc
*/
override protected function commitProperties():void
{
if (groupChanged)
{
addToGroup();
groupChanged = false;
}
super.commitProperties();
}
/**
* @inheritDoc
*/
override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if (group)
{
if (selected)
_group.selection = this;
else if (group.selection == this)
_group.selection = null;
}
}
/**
* @inheritDoc
*/
override protected function buttonReleased():void
{
if(!enabled || selected)
return;
if (!radioButtonGroup)
addToGroup();
super.buttonReleased();
group.setSelection(this);
}
/**
* 添此单选按钮加到组
*/
private function addToGroup():RadioButtonGroup
{
var g:RadioButtonGroup = group;
if (g)
g.addInstance(this);
return g;
}
}
}
|
/* -*- c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Utils;
// var SECTION = "5.5.2";
// var VERSION = "AS3";
// var TITLE = "Vector.<float4> access beyond vector length";
var vec:Vector.<float4> = new <float4> [float4(0, 0, 0, 0),
float4(1, 1, 1, 1),
float4(2, 2, 2, 2)];
for (var j:int = 0; j < vec.length; j++)
AddStrictTestCase("Global: read", float4(j, j, j, j), vec[j]);
Assert.expectError("Global: vector access beyond length", Utils.RANGEERROR+1125, function(){ vec[vec.length+1]; });
Assert.expectError("Global: vector access -1", Utils.RANGEERROR+1125, function(){ vec[-1]; });
function getValue(flt4:Vector.<float4>, index:int):float4 { return flt4[index]; }
for (var j:int = 0; j < vec.length; j++)
AddStrictTestCase("Function: read", float4(j, j, j, j), getValue(vec, j));
Assert.expectError("Function: vector access beyond length", Utils.RANGEERROR+1125, function(){ getValue(vec, vec.length+1); });
Assert.expectError("Function: vector access -1", Utils.RANGEERROR+1125, function(){ getValue(vec, -1); });
|
package com.axiomalaska.integratedlayers.views.test.timeline
{
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import mx.core.IFactory;
import spark.components.Group;
import spark.components.Label;
import spark.components.supportClasses.Skin;
import spark.components.supportClasses.SkinnableComponent;
import spark.effects.Animate;
import spark.effects.animation.MotionPath;
import spark.effects.animation.SimpleMotionPath;
import spark.effects.easing.Power;
import spark.primitives.Rect;
import com.axiomalaska.integratedlayers.views.test.timeline.AHLabelInstance;
/**
* The Ruler is a skinnable component that display a ruler.
*
*
* The Ruler takes an array of labels, a label distance and the number of subdivisions
* and draws the ruler based on this data.
*
* Associated is a ruler skin, where a graphic element is used to actually draw the ruler.
*
* The labels are drawn using a dynmaic skin part to add required label instances at rt.
*
* @TODO: clean up code, refactor, test.
*
* @author Andy Hulstkamp
*
*/
[Style(name="color", type="uint", format="Color", inherit="yes", theme="spark")]
public class AHRuler extends SkinnableComponent
{
public static var LABEL_PADDING:Number = 5;
public static var DEFAULT_LABEL_DISTANCE:Number = 186;
/**
* Dynamic skin part for a label.
* These are created at runtime based on the array of labels submitted
*/
[SkinPart("false")]
public var tickLineLabel:IFactory;
/**
* References to the labels created at rt
*/
public var tickLineLabelInstances:Array;
/**
* A SpriteVisualElement that draws the tick lines
*/
[SkinPart("true")]
public var ruler:DateBarGraphicElement;
[SkinPart("true")]
public var rulerGroup:Group;
/**
* Labels to display
*/
private var _labels:Array;
/**
* Flag to indicate label change
*/
private var _bLabelsChanged:Boolean;
/**
* Minimum date for timeline
*/
private var _startdate:Date;
/**
* Flag to indicate date range change
*/
private var _bStartDateRangeChange:Boolean;
/**
* Maximum date for timeline
*/
private var _enddate:Date;
/**
* Flag to indicate date range change
*/
private var _bEndDateRangeChange:Boolean;
/**
* Flag to indicate date range change
*/
private var _bDateRangeChange:Boolean;
/**
* Distance of labels
*/
private var _labelDistance:Number = DEFAULT_LABEL_DISTANCE;
private var _bLabelDistanceChanged:Boolean;
/**
* Number of subdivisions required
*/
private var _subdivisions:int = 2;
/**
* Flag to indicate that number of subdivision changed
*/
private var _bSubdivisionsChanged:Boolean;
/**
* Used for animation when scaling up or down
*/
private var animate:Animate;
public function AHRuler()
{
super();
}
/**
* Number of subdivisons to draw between labels
* @return
*
*/
public function get subdivisions():int
{
return _subdivisions;
}
public function set subdivisions(value:int):void
{
if(_subdivisions != value)
{
_subdivisions = value;
_bSubdivisionsChanged = true;
invalidateProperties();
invalidateDisplayList();
}
}
/**
* The distance between two labels
* @return
*
*/
public function get labelDistance():Number
{
return _labelDistance;
}
public function set labelDistance(value:Number):void
{
if (_labelDistance != value) {
_labelDistance = value;
_bLabelDistanceChanged = true;
invalidateProperties();
invalidateDisplayList();
}
}
/**
* An array of String values that hold the labels
* @param values
*
*/
public function set labels(values:Array):void
{
if (_labels != values)
{
_labels = values;
_bLabelsChanged = true;
//invalidateSize();
//invalidateProperties();
//invalidateDisplayList();
}
}
public function get startdate():Date{
return _startdate;
}
public function set startdate($startdate:Date):void{
if(!_startdate || _startdate.time != $startdate.time){
_startdate = $startdate;
_bStartDateRangeChange = true;
_bDateRangeChange = true;
_buildLabels();
invalidateSize();
invalidateProperties();
invalidateDisplayList();
}
}
public function get enddate():Date{
return _enddate;
}
public function set enddate($enddate:Date):void{
if(!_enddate || _enddate.time != $enddate.time){
_enddate = $enddate;
_bEndDateRangeChange = true;
_bDateRangeChange = true;
_buildLabels();
invalidateSize();
invalidateProperties();
invalidateDisplayList();
}
}
private function _buildLabels():void{
var arr:Array = [];
var minute:Number = 60*1000;
var hour:Number = 60*minute;
var day:Number = 24 * hour;
var week:Number = 7 * day;
var month:Number = 31 * day;
var year:Number = day * 365;
var altyear:Number = year * 2;
var decade:Number = year * 10;
var altdecade:Number = decade * 2;
var running:Number;
var starttime:Number = startdate.time;
var endtime:Number = enddate.time;
var diff:Number = Math.abs(starttime - endtime);
var mult:int;
var interval:Number;
var format:Function;
if(diff < day * 3){
interval = hour;
format = formatTime;
}else if(diff < month){
interval = week;
format = formatDay;
}else if(diff < year){
interval = month;
format = formatMonth;
}else if(diff < year * 5){
interval = month * 6;
format = formatMonth;
}else if(diff < decade){
interval = year;
format = formatYear;
}else if(diff < decade * 3){
interval = altyear;
format = formatYear;
}else{
interval = decade;
format = formatYear;
}
if(_bStartDateRangeChange){
running = Math.floor(endtime - interval/2);
while(running > starttime){
arr.push(format.call(null,new Date(running)));
running -= interval;
}
}else{
running = Math.floor(starttime + interval/2);
while(running < endtime){
arr.push(format.call(null,new Date(running)));
running += interval;
}
}
labels = arr;
}
private var _dayLabels:Array = ['Sun','Mon','Tues','Wed','Thurs','Fri','Sat']
private var _monthLabels:Array = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
private function _createLabelInstance($date:Date,$text:String):Object{
return {date:$date,text:$text};
}
private function formatYear($date:Date):Object{
var d:Date = new Date($date.fullYearUTC,0);
return _createLabelInstance(d,d.fullYear.toString());
}
private function formatMonth($date:Date):Object{
var d:Date = new Date($date.fullYearUTC,$date.monthUTC);
return _createLabelInstance(d,_monthLabels[d.getMonth()] + ' ' + d.getFullYear());
}
private function formatDay($date:Date):Object{
var d:Date = new Date($date.fullYearUTC,$date.monthUTC,$date.dateUTC);
return _createLabelInstance(d,_monthLabels[d.getMonth()] + ' ' + d.getDate());
}
private function formatTime($date:Date):Object{
return _createLabelInstance($date,_monthLabels[$date.getMonth()] + ' ' + $date.getDate() + ' ' + $date.getHours() + ':' + $date.getMinutes());
}
//--------------------------------------------------------------------
//
// Overriden functions and validation functions
//
//--------------------------------------------------------------------
/**
* Overriden. Add mouse listener to the entire skin
*/
override protected function attachSkin():void
{
super.attachSkin();
if (skin)
{
skin.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
}
}
override protected function detachSkin():void
{
if (skin)
{
skin.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
}
super.detachSkin();
}
//--------------------------------------------------------------------
//
// Validation methods
//
//--------------------------------------------------------------------
/**
* Take care of label changes and change in number of subdivisions
*/
override protected function commitProperties():void
{
super.commitProperties();
if(_bDateRangeChange){
_bDateRangeChange = false;
}
if (_bLabelsChanged) {
//Housekeeping, get rid of all former labels
if (tickLineLabelInstances)
{
var labelInstance:Label;
for (var i:int = 0; i< tickLineLabelInstances.length; i++)
{
labelInstance = tickLineLabelInstances[i];
//will call partRemoved, make sure to remove any event listeners there if any have been added
this.removeDynamicPartInstance("tickLineLabel", labelInstance);
//remove from skin manually (dynamic skin part are not added, removed by flex
rulerGroup.removeElement(labelInstance);
//explicit for readability, gc would get it anyway
labelInstance = null;
}
}
//create new array to hold label instances
tickLineLabelInstances = new Array();
//Add as many labels as needed to the skin using the dynamic skin part tickLineLabel
for (var k:int = 0; k < _labels.length; k++)
{
var label:AHLabelInstance = AHLabelInstance(this.createDynamicPartInstance("tickLineLabel"));
label.date = _labels[k].date;
label.text = _labels[k].text;
//label.text = _labels[k];
tickLineLabelInstances[k] = label;
rulerGroup.addElement(label);
}
//rulerGroup.width = _labels.length * labelDistance;
ruler.divisions = _labels.length;
_bLabelsChanged = false;
}
if (_bLabelDistanceChanged)
{
//rulerGroup.width = _labels.length * labelDistance;
_bLabelDistanceChanged = false;
}
if (_bSubdivisionsChanged)
{
//proxy value pass it down the skin part
_bSubdivisionsChanged = false;
ruler.subdivisions = _subdivisions;
}
}
/**
* Draw the skin and update the positions of the labels that have been added dynamically
*
* @param unscaledWidth
* @param unscaledHeight
*
*/
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
//update lables positions. See comment there
updatePositionOfLabels();
}
//--------------------------------------------------------------------
//
// Events and events handlers.
//
//--------------------------------------------------------------------
protected function onMouseClickHandler(event:MouseEvent):void
{
if (event.ctrlKey)
{
changeResolution(event.shiftKey);
}
}
protected function onMouseDownHandler(event:MouseEvent):void
{
/*
//down scale
if (event.ctrlKey)
{
changeResolution(false);
}
//up scale
else if (event.shiftKey)
{
changeResolution(true);
}
//move
else if (event.altKey)
{
doStartDrag(event);
}
*/
doStartDrag(event);
}
protected function doStartDrag(event:MouseEvent):void
{
var w:Number = this.getExplicitOrMeasuredWidth();
var bounds:Rectangle = rulerGroup.getBounds(rulerGroup);
bounds.bottom = bounds.top;
bounds.left = bounds.left - (bounds.width - w);
bounds.right = 0;
rulerGroup.startDrag(false, bounds);
this.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
this.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
}
protected function onMouseUpHandler (event:MouseEvent):void
{
rulerGroup.stopDrag();
this.removeEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
this.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
}
protected function changeResolution(upScale:Boolean):void
{
if (!animate || !animate.isPlaying){
if (labelDistance < DEFAULT_LABEL_DISTANCE / 2.5)
{
labelDistance = DEFAULT_LABEL_DISTANCE;
}
else if (labelDistance > DEFAULT_LABEL_DISTANCE * 2.5)
{
labelDistance = DEFAULT_LABEL_DISTANCE;
}
//reset any dragging
rulerGroup.x = 0;
createAndSetupAnimation(upScale);
animate.play();
}
}
//--------------------------------------------------------------------
//
// Drawing and animation
//
//--------------------------------------------------------------------
protected function createAndSetupAnimation(upScale:Boolean):Animate
{
//create or handle animate object if needed
if (!animate)
{
animate = createSimplePowerAnimate(this, "labelDistance");
}
else
{
animate.end();
}
//calculate and set motion path for animation
var smp:SimpleMotionPath
//get new distance based on up scale, down scale
var td:int = upScale ? labelDistance * 1.25 : labelDistance / 1.25;
//set start and end values for the motion
smp = SimpleMotionPath(animate.motionPaths[0]);
smp.valueFrom = labelDistance;
smp.valueTo = td;
return animate;
}
/**
* Update the positions of the labels.
* Note: This is actually bad practice, since it breaks Flex' separation of concerns.
* Might be better to place the label in a HGroup and let the layout object do the positioning
*
* We leave it here, since this is called multiple times during animation and keeping it here involves less overhead.
*/
protected function updatePositionOfLabels ():void
{
if (tickLineLabelInstances && tickLineLabelInstances.length)
{
var nLables:int = tickLineLabelInstances.length;
var _r:Number = Math.abs(enddate.time - startdate.time);
var _w:Number = this.width;
if(_bStartDateRangeChange){
for (var i:int = nLables - 1; i >= 0; i--)
{
tickLineLabelInstances[i].move(_w - (_w * (enddate.time - tickLineLabelInstances[i].date.time)) / _r, LABEL_PADDING);
}
}else{
for (var j:int = 0; j < nLables; j++)
{
tickLineLabelInstances[j].move((_w * (tickLineLabelInstances[j].date.time - startdate.time)) / _r, LABEL_PADDING);
}
}
}
_bStartDateRangeChange = false;
_bEndDateRangeChange = false;
}
/**
* create Animate instance. Refactor out to utils.
*
*/
public static function createSimplePowerAnimate (target:Object, property:String, duration:Number = 250, easeInFraction:Number = 0.5, exponent:Number = 2):Animate
{
var animate:Animate = new Animate(target);
animate.duration = duration;
var smp:SimpleMotionPath = new SimpleMotionPath(property, 0, 0);
var mp:Vector.<MotionPath> = new Vector.<MotionPath>();
mp[0] = smp;
animate.easer = new Power(easeInFraction, exponent);
animate.motionPaths = mp;
return animate;
}
}
}
|
class Arrow extends MovieClip {
//Create Instance Vars
var isPressed:Boolean = false;
var touchWasDown:Boolean = false;
var keyWasDown:Boolean = false;
//Check for Miss
function checkForArrow(){
//Problem Child, prevents cheating 1234 for high combos on hold
if(_root.game.speaker._currentFrame > 54 && _root.game.speaker._currentFrame < 76){
_root.game.speaker.gotoAndPlay(76);
}
//Animate Speaker BAD
if(_root.game.speaker._currentFrame < 36 || _root.game.speaker._currentFrame > 105){
_root.game.speaker.gotoAndPlay(76);
}
}
function onEnterFrame(){
if(!keyWasDown && !touchWasDown){
isPressed = false;
if(_currentFrame != 3){
this.gotoAndStop(1);
}
}
if(isPressed == true){
this.gotoAndStop(2);
}
}
} |
package
{
public class MyClass
{
public static function main():Void
{
var hash:Object = new Object();
var keys:Array = new Array("a", "b", "c");
var values:Array = new Array(1, 2, 3);
for (var i:int = 0; i < keys.length(); i++)
hash[keys[i]] = values[i];
}
}
}
|
//Created by Action Script Viewer - http://www.buraks.com/asv
package kabam.rotmg.ui.view.components {
import mx.core.ByteArrayAsset;
[Embed(source="MapBackground_EMBEDDED_BACKGROUNDMAP.dat", mimeType="application/octet-stream")]
public class MapBackground_EMBEDDED_BACKGROUNDMAP extends ByteArrayAsset {
}
}//package kabam.rotmg.ui.view.components
|
/*
* Copyright 2010-2012 Singapore Management University
* Developed under a grant from the Singapore-MIT GAMBIT Game Lab
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL was
* not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package sg.edu.smu.ksketch2.operators
{
import flash.geom.Matrix;
import flash.geom.Point;
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import sg.edu.smu.ksketch2.KSketch2;
import sg.edu.smu.ksketch2.events.KObjectEvent;
import sg.edu.smu.ksketch2.model.data_structures.IKeyFrame;
import sg.edu.smu.ksketch2.model.data_structures.ISpatialKeyFrame;
import sg.edu.smu.ksketch2.model.data_structures.KPath;
import sg.edu.smu.ksketch2.model.data_structures.KReferenceFrame;
import sg.edu.smu.ksketch2.model.data_structures.KSpatialKeyFrame;
import sg.edu.smu.ksketch2.model.data_structures.KTimedPoint;
import sg.edu.smu.ksketch2.model.objects.KObject;
import sg.edu.smu.ksketch2.operators.operations.KCompositeOperation;
import sg.edu.smu.ksketch2.operators.operations.KInsertKeyOperation;
import sg.edu.smu.ksketch2.operators.operations.KModifyPassthroughOperation;
import sg.edu.smu.ksketch2.operators.operations.KRemoveKeyOperation;
import sg.edu.smu.ksketch2.operators.operations.KReplacePathOperation;
import sg.edu.smu.ksketch2.utils.KPathProcessing;
import sg.edu.smu.ksketch2.utils.iterators.INumberIterator;
//Yay monster class! Good luck reading this
/**
* Serves as the transform interface for dealing with the
* single reference frame model.
*/
public class KSingleReferenceFrameOperator implements ITransformInterface
{
// ##########
// # Fields #
// ##########
// static variables
public static const TRANSLATE_THRESHOLD:Number = 3; // translation threshold
public static const ROTATE_THRESHOLD:Number = 0.3; // rotation threshold
public static const SCALE_THRESHOLD:Number = 0.1; // scaling threshold
public static const EPSILON:Number = 0.05; // epsilon threshold
public static const CONTROLPOINT:int = 2;
public static const KEYFRAME:int = 1;
private static const MAX_ROTATE_STEP:Number = Math.PI - 0.1;
public static var mode: int = KEYFRAME;
public static var always_allow_interpolate:Boolean = false; // always interpolate state flag
// miscellaneous state variables
protected var _object:KObject; // active object
protected var _refFrame:KReferenceFrame; // active reference frame
protected var _dirty:Boolean = true; // dirty state flag
protected var _lastQueryTime:Number; // previous query time
protected var _cachedMatrix:Matrix = new Matrix(); // cached matrix
// current transformation storage variables
protected var _interpolationKey:KSpatialKeyFrame; // Spatial key frame at the current time (to be interpolated)
protected var _nextInterpolationKey:KSpatialKeyFrame; // Holds the first interpolation (passthrough == false) spatial key frame after the current time (if any)
protected var _TStoredPath:KPath; // stored translation path for interpolation before current time
protected var _RStoredPath:KPath; // stored rotation path for interpolation before current time
protected var _SStoredPath:KPath; // stored scaling path for interpolation before current time
// params: type:int, keys:Vector.<KSpatialKeyFrame>, sourcePaths:Dictionary[KSpatialKeyFrame:KPath],
// targetPaths:Dictionary[KSpatialKeyFrame:KPath], startPoints:Dictionary[KSpatialKeyFrame:Point],
// sX:Number, sY:Number, eX:Number, eY:Number, dirty:Boolean
private var _stretchTransParams:Dictionary; // Parameters used for stretching translation paths before current time
private var _stretchRotParams:Dictionary; // Parameters used for stretching rotation paths before current time
private var _stretchScaleParams:Dictionary; // Parameters used for stretching scale paths before current time
private var _stretchTrans2Params:Dictionary; // Parameters used for stretching translation paths after current time
private var _stretchRot2Params:Dictionary; // Parameters used for stretching rotation paths after current time
private var _stretchScale2Params:Dictionary; // Parameters used for stretching scale paths after current time
// // subsequent transformation storage variables
// protected var _nextInterpolationKey:KSpatialKeyFrame; // First interpolation (passthrough == false) spatial key frame after the current time (if any)
// protected var _TStoredPath2:KPath; // stored translation path for interpolation after current time
// protected var _RStoredPath2:KPath; // stored rotation path for interpolation after current time
// protected var _SStoredPath2:KPath; // stored scaling path for interpolation after current time
// private var _stretchTransParams:Point; // Parameters used for stretching translation paths
// private var _stretchRotParams:Point; // Parameters used for stretching rotation paths
// private var _stretchScaleParams:Point; // Parameters used for stretching scale paths
// private var _stretchTransVector:Point; // Vector used for stretching translation paths
// private var _stretchRotVector:Point; // Vector used for stretching rotation paths
// private var _stretchScaleVector:Point; // Vector used for stretching scale paths
// transition time variables
protected var _startTime:Number; // starting time
protected var _startMatrix:Matrix; // starting matrix
protected var _inTransit:Boolean // in-transition state flag
protected var _transitionType:int; // transition state type
// transition space variables
protected var _transitionX:Number; // Current x difference from when interaction started.
protected var _transitionY:Number; // Current y difference from when interaction started.
protected var _transitionTheta:Number; // Current theta difference from when interaction started.
protected var _transitionSigma:Number; // Current sigma factor from when interaction started.
// magnitude variables
protected var _magX:Number; // The sum of all horizontal distance (x) changes (absolute value) since interaction started.
protected var _magY:Number; // The sum of all horizontal distance (x) changes (absolute value) since interaction started.
protected var _magTheta:Number; // The sum of all rotational (theta) changes (absolute value) since interaction started.
protected var _magSigma:Number; // The sum of all scaling (sigma) changes (absolute value) since interaction started.
// cache variables
protected var _cachedX:Number; // cache of x-vaue at the time interaction began
protected var _cachedY:Number; // cache of y-value at the time interaction began
protected var _cachedTheta:Number; // cache of rotation (theta) value at the time interaction began
protected var _cachedSigma:Number; // cache of scale (sigma) value at the time interaction began
// transformation state flag variables
public var hasTranslate:Boolean; // transition state flag
public var hasRotate:Boolean; // rotation state flag
public var hasScale:Boolean; // scaling state flag
public var tempArr: ArrayCollection = new ArrayCollection();
public var interpolationKeylist:ArrayCollection = new ArrayCollection(); // All interpolation spatial key frames after the current time.
// ###############
// # Constructor #
// ###############
/**
* The main constructor for the KSingleReferenceFrameOperator class.
*
* @param object The target object.
*/
public function KSingleReferenceFrameOperator(object:KObject)
{
// case: the given object is null
// throw an error
if(!object)
throw new Error("Transform interface says: Dude, no object given!");
// initialize the objects
_refFrame = new KReferenceFrame(); // initialize the active reference frame
_object = object; // initialize the active object
_inTransit = false; // initialize the in-transition flag
// set the initial transition information
_lastQueryTime = 0; // set the initial previous query time
_transitionX = 0; // set the initial transition x-position
_transitionY = 0; // set the initial transition y-position
_transitionTheta = 0; // set the initial transition's theta
_transitionSigma = 1; // set the initial transition's theta
// params: type:int, keys:Vector.<KSpatialKeyFrame>, sourcePaths:Dictionary[KSpatialKeyFrame:KPath],
// targetPaths:Dictionary[KSpatialKeyFrame:KPath], startPoints:Dictionary[KSpatialKeyFrame:Point],
// sX:Number, sY:Number, eX:Number, eY:Number
// Allocate temporary variables
_stretchTransParams = new Dictionary();
_stretchRotParams = new Dictionary();
_stretchScaleParams = new Dictionary();
_stretchTrans2Params = new Dictionary();
_stretchRot2Params = new Dictionary();
_stretchScale2Params = new Dictionary();
// _stretchTransParams = new Point();
// _stretchRotParams = new Point();
// _stretchScaleParams = new Point();
// _stretchTransVector = new Point();
// _stretchRotVector = new Point();
// _stretchScaleVector = new Point();
//
// _TStoredPathStart = new Point();
// _RStoredPathStart = new Point();
// _SStoredPathStart = new Point();
// _TStoredPath2Start = new Point();
// _RStoredPath2Start = new Point();
// _SStoredPath2Start = new Point();
}
// ##########################
// # Accessors and Mutators #
// ##########################
public function set dirty(value:Boolean):void
{
// set the dirty state flag to the given value
_dirty = value;
}
public function matrix(time:Number):Matrix
{
// case: the reference frame is in transition
if(_inTransit)
{
// case: the reference frame is being demonstrated
// return the transition matrix
if(_transitionType == KSketch2.TRANSITION_DEMONSTRATED)
return _transitionMatrix(time);
}
// case: the reference frame is clean and the given time matches the last queried time
// return the cached matrix
// sending the cached matrix is done to improve the interface's performance
if(!_dirty && _lastQueryTime == time)
return _cachedMatrix.clone();
// the reference frame is neither in transition nor cached,
// so calculate an extremely hardcoded matrix
// iterate through the key frame list and add up the rotation, scale, dx, and dy values,
// then pump these values into the matrix afterwards
var currentKey:KSpatialKeyFrame = _refFrame.head as KSpatialKeyFrame;
// case: the reference frame is null
// return a new matrix
if(!currentKey)
return new Matrix();
// set the initial key frame path values
var x:Number = 0;
var y:Number = 0;
var theta:Number = 0;
var sigma:Number = 1;
var point:KTimedPoint;
// iterate through each key frame
while(currentKey)
{
// case: the current key frame's is before the queried time
if(currentKey.startTime <= time)
{
// calculate the proportional value
var proportionKeyFrame:Number = currentKey.findProportion(time);
// locate the point in the current key frame's translated path at the proportional value
point = currentKey.translatePath.find_Point(proportionKeyFrame, currentKey);
// case: the located point is not null
// extract the located point's x- and y-positions
if(point)
{
x += point.x;
y += point.y;
}
// locate the point in the current key frame's rotated path at the proportional value
point = currentKey.rotatePath.find_Point(proportionKeyFrame, currentKey);
// case: the located point is not null
// increment the rotational value
if(point)
theta += point.x;
// locate the point in the current key frame's scaled path at the proportional value
point = currentKey.scalePath.find_Point(proportionKeyFrame, currentKey);
// case: the located point is not null
// multiply the scaling value
if(point)
sigma *= point.x;
}
// set the current key frame as the next key frame
currentKey = currentKey.next as KSpatialKeyFrame;
}
// create the resultant matrix from the extracted valued
var result:Matrix = new Matrix();
result.translate(-_object.center.x,-_object.center.y);
result.rotate(theta);
result.scale(sigma, sigma);
result.translate(_object.center.x, _object.center.y);
result.translate(x, y);
// set the cached matrix's states
_cachedMatrix = result.clone();
_lastQueryTime = time;
_dirty = false;
// return the resultant matrix
return result;
}
public function get firstKeyTime():Number
{
// case: the reference frame's head (i.e., first key frame) is non-null
// return the first key frame's time
if(_refFrame.head)
return _refFrame.head.time;
// case: the reference frame's head is null
// throw an error
else
throw new Error("Reference frame for "+_object.id.toString()+" doesn't have a key!");
}
public function get lastKeyTime():Number
{
// initialize the key frame as the reference frame's last key frame
var key:IKeyFrame = _refFrame.lastKey;
// case: the last key frame is non-null
// return the last key frame's time
if(key)
return _refFrame.lastKey.time;
// case: the reference frame's tail is null
// throw an error
else
throw new Error("Reference frame for "+_object.id.toString()+" doesn't have a key!");
}
public function getActiveKey(time:Number):IKeyFrame
{
var activeKey:IKeyFrame = _refFrame.getKeyAtTime(time);
if(!activeKey)
activeKey = _refFrame.getKeyAftertime(time);
return activeKey;
}
public function get transitionType():int
{
return _transitionType;
}
/**
* The matrix that is give during a performance operation
* Caches the values up till transition start time
* Will not incorporate a new transform value into the matrix
* unless it passes the threshold value
*/
private function _transitionMatrix(time:Number):Matrix
{
var x:Number = _transitionX;
var y:Number = _transitionY;
var theta:Number = _transitionTheta;
var sigma:Number = _transitionSigma;
var point:KTimedPoint;
var proportionKeyFrame:Number;
var computeTime:Number;
var currentKey:KSpatialKeyFrame = _refFrame.getKeyAftertime(_startTime) as KSpatialKeyFrame;
while(currentKey)
{
proportionKeyFrame = currentKey.findProportion(time);
if(!hasTranslate)
{
point = currentKey.translatePath.find_Point(proportionKeyFrame, currentKey);
if(Math.abs(_transitionX) <= EPSILON || Math.abs(_transitionY) <= EPSILON)
{
if(point)
{
x += point.x;
y += point.y;
}
}
else
{
if(point)
{
_cachedX += point.x;
_cachedY += point.y;
}
hasTranslate = true;
}
}
if(!hasRotate)
{
point = currentKey.rotatePath.find_Point(proportionKeyFrame, currentKey);
if(_magTheta <= EPSILON)
{
if(point)
theta += point.x;
}
else
{
if(point)
_cachedTheta += point.x;
hasRotate = true;
}
}
if(!hasScale)
{
point = currentKey.scalePath.find_Point(proportionKeyFrame, currentKey);
if(_magSigma <= EPSILON)
{
if(point)
sigma *= point.x;
}
else
{
if(point)
_cachedSigma *= point.x;
hasScale = true;
}
}
currentKey = currentKey.next as KSpatialKeyFrame;
}
var result:Matrix = new Matrix();
result.translate(-_object.center.x,-_object.center.y);
result.rotate(theta+_cachedTheta);
result.scale(sigma*_cachedSigma, sigma*_cachedSigma);
result.translate(_object.center.x, _object.center.y);
result.translate(x+_cachedX, y+_cachedY);
return result;
}
// ##############
// # Permitters #
// ##############
public function canInterpolate(time:Number):Boolean
{
// case: always allow interpolation flag is enabled
// return true
//if(always_allow_interpolate)
// return true;
// get the first active key frame after the time before the given time
var activeKey:ISpatialKeyFrame;
activeKey = _refFrame.getKeyAftertime(time-1) as ISpatialKeyFrame;
// case: the active key frame exists
if(activeKey)
{
// case: the active key frame's time matches the key frame after the time before the given time
if(activeKey.time == time)
return true;
// otherwese, return whether the active key frame has activity at that time
return activeKey.hasActivityAtTime();
}
// return false when all other possible true cases have failed
return false;
}
public function canInsertKeyFrame(time:Number):Boolean
{
// get the key frame at the given time and check if the extacted key frame exists
var hasKeyAtTime:Boolean = (_refFrame.getKeyAtTime(time) as KSpatialKeyFrame != null);
var canInsert:Boolean = true;
if(hasKeyAtTime)
if(!(_refFrame.getKeyAtTime(time) as KSpatialKeyFrame).passthrough)
canInsert = false;
// return whether the extracted key frame exists
return canInsert;
}
public function canInsertKey(time:Number):Boolean
{
// get the key frame at the given time and check if the extacted key frame exists
var hasKeyAtTime:Boolean = (_refFrame.getKeyAtTime(time) as KSpatialKeyFrame != null);
// return whether the extracted key frame exists
return !hasKeyAtTime;
}
public function canRemoveKey(time:Number):Boolean
{
// get the key frame at the given time
var key:IKeyFrame = _refFrame.getKeyAtTime(time);
// initially set the remove key frame check as false
var canRemove:Boolean = false;
// case: the key frame at the given time exists
if(key)
{
canRemove = true;
// case: the key frame either has no next key frame or is the head key frame
// set the remove key frame check as false false
if(!key.next)
{
if(key.passthrough)
canRemove = false;
}
if(key == _refFrame.head)
canRemove = false;
}
// return the remove key frame check
return canRemove;
}
public function canClearKeys(time:Number):Boolean
{
// get the key frame after the given time
var hasKeyAfterTime:Boolean = (_refFrame.getKeyAftertime(time) as KSpatialKeyFrame != null);
// return whether the key frame after the given time exists
return hasKeyAfterTime;
}
// ###############
// # Transitions #
// ###############
/**
* Preps the object for transition by checking for errors and
* inconsistencies, and complains if the object is not in the magical
* state. Note: the previous operation did not clean up the object.
*
* @param time The target time.
* @param transitionType The transition type.
* @param The corresponding composite operation.
*/
public function beginTransition(time:Number, transitionType:int, op:KCompositeOperation):void
{
_transitionType = transitionType;
_startTime = time;
//Initiate transition values and variables first
_transitionX = 0;
_transitionY = 0;
_transitionTheta = 0;
_transitionSigma = 1;
_magX = 0;
_magY = 0;
_magTheta = 0;
_magSigma = 0;
if(_transitionType == KSketch2.TRANSITION_DEMONSTRATED)
{
_TStoredPath = new KPath(KPath.TRANSLATE);
_TStoredPath.push(0,0,0);
_RStoredPath = new KPath(KPath.ROTATE);
_RStoredPath.push(0,0,0);
_SStoredPath = new KPath(KPath.SCALE);
_SStoredPath.push(1,0,0);
}
else
{
_beginTransition_process_interpolation(time, op);
}
//Because all transform values before start time will remain the same
//Cache them to avoid unnecessary computations
//Future matrix will only need to compute the active key's transforms
_cachedX = 0;
_cachedY = 0;
_cachedTheta = 0;
_cachedSigma = 1;
var currentProportion:Number = 1;
var point:KTimedPoint;
var currentKey:KSpatialKeyFrame = _refFrame.head as KSpatialKeyFrame;
while(currentKey)
{
if( _startTime < currentKey.time)
break;
point = currentKey.translatePath.find_Point(1, currentKey);
if(point)
{
_cachedX += point.x;
_cachedY += point.y;
}
point = currentKey.rotatePath.find_Point(1, currentKey);
if(point)
_cachedTheta += point.x;
point = currentKey.scalePath.find_Point(1, currentKey);
if(point)
_cachedSigma *= point.x;
currentKey = currentKey.next as KSpatialKeyFrame;
}
hasTranslate = false;
hasScale = false;
hasRotate = false;
_inTransit = true;
_dirty = true;
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_BEGIN, _object, time));
}
/**
* Updates the object during the transition.
*
* @param time The target time.
* @param dx The x-position displacement from when the interaction began.
* @param dy The y-position displacement from when the interaction began.
* @param dTheta The rotation displacement from when the interaction began.
* @param fScale The scaling factor from when the interaction began.
*/
public function updateTransition(time:Number, dx:Number, dy:Number, dTheta:Number, fScale:Number):void
{
var changeX:Number = dx - _transitionX;
var changeY:Number = dy - _transitionY;
var changeTheta:Number = dTheta - _transitionTheta;
var changeSigma:Number = fScale / _transitionSigma;
_magX += Math.abs(changeX);
_magY += Math.abs(changeY);
_magTheta += Math.abs(changeTheta);
_magSigma += Math.abs(1-changeSigma);
_transitionX = dx;
_transitionY = dy;
_transitionTheta = dTheta;
_transitionSigma = fScale;
if(_transitionType == KSketch2.TRANSITION_DEMONSTRATED)
{
var elapsedTime:Number;
//Just dump the new values in for demonstrated transitions
elapsedTime = time - _startTime;
if(elapsedTime != 0)
{
_TStoredPath.push(dx, dy, elapsedTime);
_RStoredPath.push(dTheta, 0, elapsedTime);
_SStoredPath.push(fScale, 0, elapsedTime);
}
}
else
{
if(!_interpolationKey)
throw new Error("No Keys to interpolate!");
//We need to interpolate the relevant keys during every update for interpolated transitions
//dx:Number, dy:Number, time:Number, params:Dictionary
if((Math.abs(_transitionX) > EPSILON) || (Math.abs(_transitionY) > EPSILON)) {
_stretch(_transitionX, _transitionY, time, _stretchTransParams);
//_interpolate(changeX, changeY, time, _stretchTransParams);
}
if(Math.abs(_transitionTheta) > EPSILON) {
//_stretch(_transitionTheta, 0, time, _stretchRotParams);
_interpolate(changeTheta, 0, time, _stretchRotParams);
}
if(Math.abs(_transitionSigma-1) > EPSILON) {
//_stretch(_transitionSigma, 0, time, _stretchScaleParams);
_interpolate(changeSigma, 0, time, _stretchScaleParams);
}
//if studymode kp2, then do Interpolation for next frame
if(mode == KEYFRAME)
{
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
// *****************************************************************
if (_nextInterpolationKey) {
if((Math.abs(_transitionX) > EPSILON) || (Math.abs(_transitionY) > EPSILON)) {
_stretch(-_transitionX, -_transitionY, time, _stretchTrans2Params);
//_interpolate(-changeX,-changeY, time, _stretchTrans2Params);
}
if(Math.abs(_transitionTheta) > EPSILON) {
//_stretch(-_transitionTheta, 0, time, _stretchRot2Params);
_interpolate(-changeTheta, 0, time, _stretchRot2Params);
}
if(Math.abs(_transitionSigma-1) > EPSILON) {
//_stretch(-_transitionSigma, 0, time, _stretchScale2Params);
_interpolate(1/changeSigma, 0, time, _stretchScale2Params);
}
}
// var interpolatePassthrough:Boolean = false;
// if(interpolationKeylist.length != 0)
// {
// for(var i:int = 0; i<interpolationKeylist.length; i++)
// {
// var tempKey:KSpatialKeyFrame = interpolationKeylist.getItemAt(i) as KSpatialKeyFrame;
// interpolatePassthrough = tempKey.passthrough;
//
// if(!interpolatePassthrough)
// {
// if((Math.abs(_transitionX) > EPSILON) || (Math.abs(_transitionY) > EPSILON)) {
// _interpolate(-changeX,-changeY, tempKey, KSketch2.TRANSFORM_TRANSLATION, tempKey.time);
// }
// if(Math.abs(_transitionTheta) > EPSILON) {
// _interpolate(-changeTheta, 0, tempKey, KSketch2.TRANSFORM_ROTATION, tempKey.time);
// }
// if(Math.abs(_transitionSigma) > EPSILON) {
// _interpolate(1/changeSigma, 0, tempKey, KSketch2.TRANSFORM_SCALE, tempKey.time);
// }
// break;
// }
// }
// }
}
else
{
if(_nextInterpolationKey)
{
if((Math.abs(_transitionX) > EPSILON) || (Math.abs(_transitionY) > EPSILON))
_interpolate(-changeX,-changeY, time, _stretchTrans2Params);
if(Math.abs(_transitionTheta) > EPSILON)
_interpolate(-changeTheta, 0, time, _stretchRot2Params);
if(Math.abs(_transitionSigma-1) > EPSILON)
_interpolate(1/changeSigma, 0, time, _stretchScale2Params);
}
}
}
_dirty = true;
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_CHANGED, _object, time));
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_UPDATING, _object, time));
}
/**
* Finalizes the object's transition.
*
* @param time The target time.
* @param op The corresponding composite operation.
*/
public function endTransition(time:Number, op:KCompositeOperation):void
{
_dirty = true;
_endTransition_process_ModeDI(time, op);
_inTransit = false;
_dirty = true;
// dispatch a transform finalised event
// application level components can listen to this event to do updates
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_ENDED, _object, time));
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_FINALISED, _object, time));
}
private function _beginTransition_process_interpolation(time:Number, op:KCompositeOperation):void
{
var tmpCurrent:KSpatialKeyFrame, tmpNext:KSpatialKeyFrame, tmpKeyVec:Vector.<KSpatialKeyFrame>, tmpDict:Dictionary;
var point:KTimedPoint, endKey:KSpatialKeyFrame, afterInerpTime:Boolean, key:Object;
var x:Number, y:Number, theta:Number, sigma:Number;
if(_transitionType == KSketch2.TRANSITION_INTERPOLATED)
{
//For interpolation, there will always be a key inserted at given time
//So we just insert a key at time, if there is a need to insert key
if(canInsertKey(time))
{
insertBlankKeyFrame(time, op, false);
}
//trace("_beginTransition_process_interpolation");
//trace(_refFrame);
//Then we grab that key
_interpolationKey = _refFrame.getKeyAtTime(time) as KSpatialKeyFrame;
//trace("_interpolationKey.time = " + _interpolationKey.time);
_TStoredPath = _interpolationKey.translatePath.clone();
_RStoredPath = _interpolationKey.rotatePath.clone();
_SStoredPath = _interpolationKey.scalePath.clone();
// params: type:int, keys:Vector.<KSpatialKeyFrame>, sourcePaths:Dictionary[KSpatialKeyFrame:KPath],
// targetPaths:Dictionary[KSpatialKeyFrame:KPath], startPoints:Dictionary[KSpatialKeyFrame:Point],
// sX:Number, sY:Number, eX:Number, eY:Number, dirty:Boolean
_stretchTransParams["type"] = KSketch2.TRANSFORM_TRANSLATION;
tmpKeyVec = new Vector.<KSpatialKeyFrame>();
tmpKeyVec.push(_interpolationKey);
_stretchTransParams["keys"] = tmpKeyVec;
tmpDict = new Dictionary();
tmpDict[_interpolationKey] = _TStoredPath;
_stretchTransParams["sourcePaths"] = tmpDict;
tmpDict = new Dictionary();
tmpDict[_interpolationKey] = _interpolationKey.translatePath;
_stretchTransParams["targetPaths"] = tmpDict;
_stretchTransParams["startPoints"] = new Dictionary();
_stretchTransParams["dirty"] = false;
_stretchRotParams["type"] = KSketch2.TRANSFORM_ROTATION;
tmpKeyVec = new Vector.<KSpatialKeyFrame>();
tmpKeyVec.push(_interpolationKey);
_stretchRotParams["keys"] = tmpKeyVec;
tmpDict = new Dictionary();
tmpDict[_interpolationKey] = _RStoredPath;
_stretchRotParams["sourcePaths"] = tmpDict;
tmpDict = new Dictionary();
tmpDict[_interpolationKey] = _interpolationKey.rotatePath;
_stretchRotParams["targetPaths"] = tmpDict;
_stretchRotParams["startPoints"] = new Dictionary();
_stretchRotParams["dirty"] = false;
_stretchScaleParams["type"] = KSketch2.TRANSFORM_SCALE;
tmpKeyVec = new Vector.<KSpatialKeyFrame>();
tmpKeyVec.push(_interpolationKey);
_stretchScaleParams["keys"] = tmpKeyVec;
tmpDict = new Dictionary();
tmpDict[_interpolationKey] = _SStoredPath;
_stretchScaleParams["sourcePaths"] = tmpDict;
tmpDict = new Dictionary();
tmpDict[_interpolationKey] = _interpolationKey.scalePath;
_stretchScaleParams["targetPaths"] = tmpDict;
_stretchScaleParams["startPoints"] = new Dictionary();
_stretchScaleParams["dirty"] = false;
_nextInterpolationKey = null;
interpolationKeylist.removeAll();
if(_interpolationKey.time == time)
{
//Then we deal with the interpolation
//Only if study mode is KP2, we need to get all the keys after the selected time
if(mode == KEYFRAME)
{
tmpCurrent = _interpolationKey;
tmpNext = tmpCurrent.next as KSpatialKeyFrame;
//trace("interpolationKeylist times");
while(tmpNext)
{
interpolationKeylist.addItem(tmpNext);
//trace(tmpNext.time);
if (!_nextInterpolationKey) {
if (!tmpNext.passthrough) {
_nextInterpolationKey = tmpNext;
}
}
tmpCurrent = tmpNext;
tmpNext = tmpCurrent.next as KSpatialKeyFrame;
}
}
_nextInterpolationKey ? trace("_nextInterpolationKey.time = " + _nextInterpolationKey.time): null;
}
if(_interpolationKey)
{
x = 0;
y = 0;
theta = 0;
sigma = 1;
afterInerpTime = false;
endKey = _nextInterpolationKey ? _nextInterpolationKey.next as KSpatialKeyFrame : _interpolationKey.next as KSpatialKeyFrame;
tmpCurrent = _refFrame.head as KSpatialKeyFrame;
// params: type:int, keys:Vector.<KSpatialKeyFrame>, sourcePaths:Dictionary[KSpatialKeyFrame:KPath],
// targetPaths:Dictionary[KSpatialKeyFrame:KPath], startPoints:Dictionary[KSpatialKeyFrame:Point],
// sX:Number, sY:Number, eX:Number, eY:Number, dirty:Boolean
while(tmpCurrent !== endKey) {
if (tmpCurrent === _interpolationKey) {
// When the first key is found, set the start times
_stretchTransParams["sX"] = x;
_stretchTransParams["sY"] = y;
tmpDict = _stretchTransParams["startPoints"] as Dictionary;
tmpDict[_interpolationKey] = new Point(x, y);
_stretchRotParams["sX"] = theta;
_stretchRotParams["sY"] = 0;
tmpDict = _stretchRotParams["startPoints"] as Dictionary;
tmpDict[_interpolationKey] = new Point(theta, 0);
_stretchScaleParams["sX"] = sigma;
_stretchScaleParams["sY"] = 0;
tmpDict = _stretchScaleParams["startPoints"] as Dictionary;
tmpDict[_interpolationKey] = new Point(sigma, 0);
afterInerpTime = true;
} else if (afterInerpTime) {
tmpKeyVec = _stretchTrans2Params["keys"] as Vector.<KSpatialKeyFrame>;
tmpKeyVec.push(tmpCurrent);
tmpKeyVec = _stretchRot2Params["keys"] as Vector.<KSpatialKeyFrame>;
tmpKeyVec.push(tmpCurrent);
tmpKeyVec = _stretchScale2Params["keys"] as Vector.<KSpatialKeyFrame>;
tmpKeyVec.push(tmpCurrent);
tmpDict = _stretchTrans2Params["sourcePaths"] as Dictionary;
tmpDict[tmpCurrent] = tmpCurrent.translatePath.clone();
tmpDict = _stretchRot2Params["sourcePaths"] as Dictionary;
tmpDict[tmpCurrent] = tmpCurrent.rotatePath.clone();
tmpDict = _stretchScale2Params["sourcePaths"] as Dictionary;
tmpDict[tmpCurrent] = tmpCurrent.scalePath.clone();
tmpDict = _stretchTrans2Params["targetPaths"] as Dictionary;
tmpDict[tmpCurrent] = tmpCurrent.translatePath;
tmpDict = _stretchRot2Params["targetPaths"] as Dictionary;
tmpDict[tmpCurrent] = tmpCurrent.rotatePath;
tmpDict = _stretchScale2Params["targetPaths"] as Dictionary;
tmpDict[tmpCurrent] = tmpCurrent.scalePath;
tmpDict = _stretchTrans2Params["startPoints"] as Dictionary;
tmpDict[tmpCurrent] = new Point(x, y);
tmpDict = _stretchRot2Params["startPoints"] as Dictionary;
tmpDict[tmpCurrent] = new Point(theta, 0);
tmpDict = _stretchScale2Params["startPoints"] as Dictionary;
tmpDict[tmpCurrent] = new Point(sigma, 0);
_stretchTrans2Params["dirty"] = false;
_stretchRot2Params["dirty"] = false;
_stretchScale2Params["dirty"] = false;
}
// Update the x, y, theta, and sigma accumulators.
point = tmpCurrent.translatePath.find_Point(1, tmpCurrent);
if(point) {
x += point.x;
y += point.y;
}
point = tmpCurrent.rotatePath.find_Point(1, tmpCurrent);
if(point) {
theta += point.x;
}
point = tmpCurrent.scalePath.find_Point(1, tmpCurrent);
if(point) {
sigma *= point.x;
}
if (tmpCurrent === _interpolationKey) {
// If this is the _interpolationKey, set end times for the stretch before the current time.
_stretchTransParams["eX"] = x;
_stretchTransParams["eY"] = y;
_stretchRotParams["eX"] = theta;
_stretchRotParams["eY"] = 0;
_stretchScaleParams["eX"] = sigma;
_stretchScaleParams["eY"] = 0;
if (_nextInterpolationKey) {
_stretchTrans2Params["type"] = KSketch2.TRANSFORM_TRANSLATION;
_stretchTrans2Params["keys"] = new Vector.<KSpatialKeyFrame>();
_stretchTrans2Params["sourcePaths"] = new Dictionary();
_stretchTrans2Params["targetPaths"] = new Dictionary();
_stretchTrans2Params["startPoints"] = new Dictionary();
_stretchTrans2Params["sX"] = x;
_stretchTrans2Params["sY"] = y;
_stretchRot2Params["type"] = KSketch2.TRANSFORM_ROTATION;
_stretchRot2Params["keys"] = new Vector.<KSpatialKeyFrame>();
_stretchRot2Params["sourcePaths"] = new Dictionary();
_stretchRot2Params["targetPaths"] = new Dictionary();
_stretchRot2Params["startPoints"] = new Dictionary();
_stretchRot2Params["sX"] = x;
_stretchRot2Params["sY"] = y;
_stretchScale2Params["type"] = KSketch2.TRANSFORM_SCALE;
_stretchScale2Params["keys"] = new Vector.<KSpatialKeyFrame>();
_stretchScale2Params["sourcePaths"] = new Dictionary();
_stretchScale2Params["targetPaths"] = new Dictionary();
_stretchScale2Params["startPoints"] = new Dictionary();
_stretchScale2Params["sX"] = x;
_stretchScale2Params["sY"] = y;
} else {
for (key in _stretchTrans2Params) delete _stretchTrans2Params[key];
for (key in _stretchRot2Params) delete _stretchRot2Params[key];
for (key in _stretchScale2Params) delete _stretchScale2Params[key];
}
} else if (afterInerpTime) {
if (tmpCurrent === _nextInterpolationKey) {
// If this is the _nextInterpolationKey, set end times for the stretch after the current time.
_stretchTrans2Params["eX"] = x;
_stretchTrans2Params["eY"] = y;
_stretchRot2Params["eX"] = theta;
_stretchRot2Params["eY"] = 0;
_stretchScale2Params["eX"] = sigma;
_stretchScale2Params["eY"] = 0;
}
}
tmpCurrent = tmpCurrent.next as KSpatialKeyFrame;
}
}
}
}
private function _endTransition_process_interpolation(time:Number, op:KCompositeOperation):void
{
var i:uint, keys:Vector.<KSpatialKeyFrame>, dict:Dictionary;
if(_transitionType == KSketch2.TRANSITION_INTERPOLATED)
{
//original implementation
if (_stretchTransParams["dirty"] as Boolean === true)
op.addOperation(new KReplacePathOperation(_interpolationKey, _interpolationKey.translatePath, _TStoredPath, KSketch2.TRANSFORM_TRANSLATION));
if (_stretchRotParams["dirty"] as Boolean === true)
op.addOperation(new KReplacePathOperation(_interpolationKey, _interpolationKey.rotatePath, _RStoredPath, KSketch2.TRANSFORM_ROTATION));
if (_stretchScaleParams["dirty"] as Boolean === true)
op.addOperation(new KReplacePathOperation(_interpolationKey, _interpolationKey.scalePath, _SStoredPath, KSketch2.TRANSFORM_SCALE));
if(_nextInterpolationKey)
{
if (_stretchTrans2Params["dirty"] as Boolean === true) {
keys = _stretchTrans2Params["keys"] as Vector.<KSpatialKeyFrame>;
for (i = 0; i < keys.length; i++) {
dict = _stretchTrans2Params["sourcePaths"] as Dictionary;
op.addOperation(new KReplacePathOperation(keys[i], keys[i].translatePath,
dict[keys[i]] as KPath, KSketch2.TRANSFORM_TRANSLATION));
}
}
if (_stretchRot2Params["dirty"] as Boolean === true) {
keys = _stretchRot2Params["keys"] as Vector.<KSpatialKeyFrame>;
for (i = 0; i < keys.length; i++) {
dict = _stretchRot2Params["sourcePaths"] as Dictionary;
op.addOperation(new KReplacePathOperation(keys[i], keys[i].rotatePath,
dict[keys[i]] as KPath, KSketch2.TRANSFORM_ROTATION));
}
}
if (_stretchScale2Params["dirty"] as Boolean === true) {
keys = _stretchScale2Params["keys"] as Vector.<KSpatialKeyFrame>;
for (i = 0; i < keys.length; i++) {
dict = _stretchScale2Params["sourcePaths"] as Dictionary;
op.addOperation(new KReplacePathOperation(keys[i], keys[i].scalePath,
dict[keys[i]] as KPath, KSketch2.TRANSFORM_SCALE));
}
}
}
}
}
private function _endTransition_process_ModeD(time:Number, op:KCompositeOperation):void
{
if(_transitionType == KSketch2.TRANSITION_DEMONSTRATED)
_demonstrate(time, op);
else
_endTransition_process_interpolation(time, op);
}
private function _endTransition_process_ModeDI(time:Number, op:KCompositeOperation):void
{
if(_transitionType == KSketch2.TRANSITION_DEMONSTRATED)
_demonstrate(time, op);
else
_endTransition_process_interpolation(time, op);
}
private function _demonstrate(time:Number, op:KCompositeOperation):void
{
//Process the paths here first
//Do w/e you want to the paths here!
// Spread out the times for these points.
// _TStoredPath.distributePathPointTimes();
// _RStoredPath.distributePathPointTimes();
// _SStoredPath.distributePathPointTimes();
//Make sure there is only one point at one frame
_TStoredPath.discardRedundantPathPoints();
_RStoredPath.discardRedundantPathPoints();
_SStoredPath.discardRedundantPathPoints();
// Make sure rotation doesn't move too fast, or the motion path won't render correctly.
KPathProcessing.limitSegmentLength(_RStoredPath, MAX_ROTATE_STEP);
if(KSketch2.discardTransitionTimings)
{
KPathProcessing.discardPathTimings(_TStoredPath);
KPathProcessing.discardPathTimings(_RStoredPath);
KPathProcessing.discardPathTimings(_SStoredPath);
}
//Path validity will be tested in _normaliseForOverwriting
//If path is valid, the object's future for that transform type will be discarded
_normaliseForOverwriting(_startTime, op);
//Then I need to put the usable paths into the object
if((TRANSLATE_THRESHOLD < _magX) || (TRANSLATE_THRESHOLD < _magY))
_replacePathOverTime(_TStoredPath, _startTime, time, KSketch2.TRANSFORM_TRANSLATION, op); //Optimise replace algo
if(ROTATE_THRESHOLD < _magTheta)
_replacePathOverTime(_RStoredPath, _startTime, time, KSketch2.TRANSFORM_ROTATION, op);
if(SCALE_THRESHOLD < _magSigma)
_replacePathOverTime(_SStoredPath, _startTime, time, KSketch2.TRANSFORM_SCALE, op);
_clearEmptyKeys(op);
}
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
//*********************************************************************************************************
// private function _updateStretchParameters(orig:KPath, dx:Number, dy:Number, transformType:int, params:Point, vec:Point):void
// {
// var vX1:Number, vY1:Number, vX2:Number, vY2:Number;
// var mag1:Number, mag2:Number, rot1:Number, rot2:Number;
// var m:Number, theta:Number, vX:Number, vY:Number;
//
// if (orig && 2 <= orig.length) {
// // 2 or more points. Return magnitude and rotation for stretching.
// switch(transformType)
// {
// case KSketch2.TRANSFORM_TRANSLATION:
// vX1 = orig.points[orig.length - 1].x;
// vY1 = orig.points[orig.length - 1].y;
// vX2 = vX1 + dx;
// vY2 = vY1 + dy;
// mag1 = Math.sqrt(vX1*vX1 + vY1*vY1);
// mag2 = Math.sqrt(vX2*vX2 + vY2*vY2);
// rot1 = Math.atan2(vY1, vX1);
// rot2 = Math.atan2(vY2, vX2);
//
// m = mag2 / mag1;
//
// theta = rot2 - rot1;
// if (Math.PI < theta)
// theta = -Math.PI + (theta - Math.PI);
// if (theta <= -Math.PI)
// theta = Math.PI + (theta + Math.PI);
//
// vX = vX2/mag2;
// vY = vY2/mag2;
//
// break;
// case KSketch2.TRANSFORM_ROTATION:
// case KSketch2.TRANSFORM_SCALE:
// mag1 = orig.points[orig.length - 1].x;
// mag2 = mag1 + dx;
//
// m = mag2 / mag1;
// theta = 0;
// vX = 1;
// vY = 0;
// break;
// default:
// throw new Error("Unable to replace path because an unknown transform type is given");
// }
// } else {
// // Less than 2 points. Set params to empty values and set vec to (dx, dy).
// m = 1;
// theta = 0;
// vX = dx;
// vY = dy;
// }
// trace("stretch parameters: mag=" + params.x + ", rot=" + params.y);
//
// params.x = m;
// params.y = theta;
// vec.x = vX;
// vec.y = vY;
// }
/**
* scales and rotates a path Adds a dx, dy interpolation to targetKey
* target key should be a key at or before time;
*/
private function _stretch(dx:Number, dy:Number, time:Number, params:Dictionary):void
{
// params: type:int, keys:Vector.<KSpatialKeyFrame>, sourcePaths:Dictionary[KSpatialKeyFrame:KPath],
// targetPaths:Dictionary[KSpatialKeyFrame:KPath], startPoints:Dictionary[KSpatialKeyFrame:Point],
// sX:Number, sY:Number, eX:Number, eY:Number
var vX1:Number, vY1:Number, vX2:Number, vY2:Number;
var mag1:Number, mag2:Number, rot1:Number, rot2:Number;
var mag:Number, theta:Number, vX:Number, vY:Number;
var i:uint, j:uint, ptX:Number, ptY:Number, projectionLen:Number, proportion:Number;
var targetKey:KSpatialKeyFrame, sourcePath:KPath, targetPath:KPath, startPoint:Point;
var type:int = params["type"] as int;
var targetKeys:Vector.<KSpatialKeyFrame> = params["keys"] as Vector.<KSpatialKeyFrame>;
var sourcePaths:Dictionary = params["sourcePaths"] as Dictionary;
var targetPaths:Dictionary = params["targetPaths"] as Dictionary;
var startPoints:Dictionary = params["startPoints"] as Dictionary;
var sX:Number = params["sX"] as Number;
var sY:Number = params["sY"] as Number;
var eX:Number = params["eX"] as Number;
var eY:Number = params["eY"] as Number;
var nonEmptyPaths:Boolean = false;
var startTime:int = 0;
var totalDuration:Number = 0;
// Check to make sure that some paths have points
for (j=0; j<targetKeys.length; j++) {
targetKey = targetKeys[j] as KSpatialKeyFrame;
sourcePath = sourcePaths[targetKey] as KPath;
if (sourcePath && 2 <= sourcePath.length) {
nonEmptyPaths = true;
break;
}
}
if (targetKeys.length > 0) {
totalDuration = targetKeys[targetKeys.length-1].time - targetKeys[0].startTime;
}
if (nonEmptyPaths) {
// 2 or more points. Return magnitude and rotation for stretching.
switch(type)
{
case KSketch2.TRANSFORM_TRANSLATION:
vX1 = eX - sX;
vY1 = eY - sY;
vX2 = vX1 + dx;
vY2 = vY1 + dy;
mag1 = Math.sqrt(vX1*vX1 + vY1*vY1);
mag2 = Math.sqrt(vX2*vX2 + vY2*vY2);
rot1 = Math.atan2(vY1, vX1);
rot2 = Math.atan2(vY2, vX2);
mag = mag2 / mag1;
theta = rot2 - rot1;
if (Math.PI < theta)
theta = -Math.PI + (theta - Math.PI);
if (theta <= -Math.PI)
theta = Math.PI + (theta + Math.PI);
vX = vX2/mag2;
vY = vY2/mag2;
break;
case KSketch2.TRANSFORM_ROTATION:
case KSketch2.TRANSFORM_SCALE:
mag1 = eX - sX;
mag2 = mag1 + dx;
mag = mag2 / mag1;
theta = 0;
vX = 1;
vY = 0;
break;
default:
throw new Error("Unable to replace path because an unknown transform type is given");
}
} else {
// Less than 2 points. Set params to empty values and set vec to (dx, dy).
mag = 1;
theta = 0;
vX = dx;
vY = dy;
}
//traceParams(params);
//trace(" mag:" + mag + " rot:" + theta + " vX:" + vX + " vY:" + vY);
for (j=0; j<targetKeys.length; j++) {
targetKey = targetKeys[j] as KSpatialKeyFrame;
sourcePath = sourcePaths[targetKey] as KPath;
targetPath = targetPaths[targetKey] as KPath;
startPoint = startPoints[targetKey] as Point;
proportion = (totalDuration === 0) ? 1 : (targetKey.time - targetKey.startTime)/totalDuration;
if((time > targetKey.time) && (KSketch2.studyMode != KSketch2.STUDYMODE_P))
throw new Error("Unable to stretch a key if the stretch time is greater than targetKey's time");
if(targetPath.length < 2) {
//Case 1: Key frames without transition paths of required type
if(targetPath.length != 0)
throw new Error("Someone created a path with 1 point somehow! Better check out the path functions");
//Provide the empty path with the positive interpolation first
targetPath.push(0,0,0);
targetPath.push(vX * proportion, vY * proportion, targetKey.duration);
} else if (sourcePath.length < 2) {
//Case 2: Empty sourcePath. Case 1 becomes this after the first update.
targetPath.points[targetPath.length - 1].x = vX * proportion;
targetPath.points[targetPath.length - 1].y = vY * proportion;
} else {
//Case 3: Transform sourcePath as indicated by params.
if(targetPath.length != sourcePath.length)
throw new Error("Target Path and SourcePath are not the same length!");
for (i=1; i < sourcePath.length; i++) {
// Set ptX and ptY, handling rotation, if any.
if (theta == 0) {
ptX = sourcePath.points[i].x;
ptY = sourcePath.points[i].y;
} else {
ptX = sourcePath.points[i].x*Math.cos(theta) - sourcePath.points[i].y*Math.sin(theta);
ptY = sourcePath.points[i].x*Math.sin(theta) + sourcePath.points[i].y*Math.cos(theta);
}
// Compute the length of the projection on the vector.
projectionLen = ptX * vX + ptY * vY;
ptX = ptX + (vX * projectionLen * (mag - 1));
ptY = ptY + (vY * projectionLen * (mag - 1));
targetPath.points[i].x = ptX;
targetPath.points[i].y = ptY;
}
}
// trace("Time=" + targetKey.time);
// trace("Source Path");
// sourcePath.debug();
// trace("Target Path");
// targetPath.debug();
}
params["dirty"] = true;
}
// params: type:int, keys:Vector.<KSpatialKeyFrame>, sourcePaths:Dictionary[KSpatialKeyFrame:KPath],
// targetPaths:Dictionary[KSpatialKeyFrame:KPath], startPoints:Dictionary[KSpatialKeyFrame:Point],
// sX:Number, sY:Number, eX:Number, eY:Number, dirty:Boolean
private function traceParams(params:Dictionary):void
{
var type:int = params["type"] as int;
var keys:Vector.<KSpatialKeyFrame> = params["keys"] as Vector.<KSpatialKeyFrame>;
var sourcePaths:Dictionary = params["sourcePaths"] as Dictionary;
var targetPaths:Dictionary = params["targetPaths"] as Dictionary;
var startPoints:Dictionary = params["startPoints"] as Dictionary;
var sX:Number = params["sX"] as Number;
var sY:Number = params["sY"] as Number;
var eX:Number = params["eX"] as Number;
var eY:Number = params["eY"] as Number;
var dirty:Boolean = params["dirty"] as Boolean;
var keyStrings:Array = new Array();
var i:uint, sourcePath:KPath, targetPath:KPath, startPoint:Point;
var typeString:String;
switch(type)
{
case KSketch2.TRANSFORM_TRANSLATION:
typeString = "Translation";
break;
case KSketch2.TRANSFORM_ROTATION:
typeString = "Rotation";
break;
case KSketch2.TRANSFORM_SCALE:
typeString = "Scale";
break;
default:
typeString = "Unknown";
}
//trace(typeString + " params dirty:" + (dirty ? "true " : "false ") + "sX:" + sX + " sY:" + sY + " eX:" + eX + " eY:" + eY);
for (i=0; i < keys.length; i++) {
sourcePath = sourcePaths[keys[i]] as KPath;
targetPath = targetPaths[keys[i]] as KPath;
startPoint = startPoints[keys[i]] as Point;
keyStrings.push(" [" + keys[i].time + " source:" + (sourcePath ? sourcePath.length + "pts " : "null ") +
"target:" + (targetPath ? targetPath.length + "pts " : "null ") +
"start:" + (startPoint ? startPoint.x + "," + startPoint.y: "null") + "]");
}
//trace(" ", keyStrings);
}
/**
* Adds a dx, dy interpolation to targetKey.
* Target key should be a key at or before time;
*
* @param dx The x displacement from when the interaction began.
* @param dy The y displacement from when the interaction began.
* @param time The target time.
* @param params Contains the original paths ("sourcePaths"), the new paths that will be used ("targetPaths"), "startPoints", "
*/
private function _interpolate(dx:Number, dy:Number, time:Number, params:Dictionary):void
{
// params: type:int, keys:Vector.<KSpatialKeyFrame>, sourcePaths:Dictionary[KSpatialKeyFrame:KPath],
// targetPaths:Dictionary[KSpatialKeyFrame:KPath], startPoints:Dictionary[KSpatialKeyFrame:Point],
// sX:Number, sY:Number, eX:Number, eY:Number
//traceParams(params);
var type:int = params["type"] as int;
var keys:Vector.<KSpatialKeyFrame> = params["keys"] as Vector.<KSpatialKeyFrame>;
var sourcePaths:Dictionary = params["sourcePaths"] as Dictionary;
var targetPaths:Dictionary = params["targetPaths"] as Dictionary;
var startPoints:Dictionary = params["startPoints"] as Dictionary;
var sX:Number = params["sX"] as Number;
var sY:Number = params["sY"] as Number;
var eX:Number = params["eX"] as Number;
var eY:Number = params["eY"] as Number;
var i:uint, targetKey:KSpatialKeyFrame, targetPath:KPath;
var totalDuration:Number, durationProportion:Number, proportionElapsed:Number;
var xFirst:Number, xInterp:Number, yInterp:Number, currScaleDiff:Number, prevScaleDiff:Number;
var currPartialScale:Number, prevPartialScale:Number;
if(keys.length === 0)
throw new Error("No Key to interpolate!");
totalDuration = keys[keys.length-1].time - keys[0].startTime;
prevScaleDiff = 0;
for (i=0; i<keys.length; i++) {
targetKey = keys[i];
targetPath = targetPaths[targetKey] as KPath;
durationProportion = totalDuration === 0 ? 1 : (targetKey.time - targetKey.startTime)/totalDuration;
if((time > targetKey.time) && (KSketch2.studyMode != KSketch2.STUDYMODE_P))
throw new Error("Unable to interpolate a key if the interpolation time is greater than targetKey's time");
switch(type)
{
case KSketch2.TRANSFORM_TRANSLATION:
targetPath = targetKey.translatePath;
break;
case KSketch2.TRANSFORM_ROTATION:
targetPath = targetKey.rotatePath;
break;
case KSketch2.TRANSFORM_SCALE:
targetPath = targetKey.scalePath;
break;
default:
throw new Error("Unable to replace path because an unknown transform type is given");
}
// if(targetKey.duration == 0) {
// proportionElapsed = 1;
// } else{
// proportionElapsed = (time-targetKey.startTime)/targetKey.duration;
//
// if(proportionElapsed > 1)
// proportionElapsed = 1;
// }
// RCDavis replaced this, because it we now always insert key frames at movement points.
proportionElapsed = 1;
if (type != KSketch2.TRANSFORM_SCALE)
{
// Translation or Rotation
xFirst = 0;
xInterp = dx * durationProportion;
yInterp = dy * durationProportion;
}
else
{
// Scale
xFirst = 1;
currScaleDiff = prevScaleDiff + (dx - 1) * durationProportion;
prevPartialScale = 1 + prevScaleDiff;
currPartialScale = 1 + currScaleDiff;
xInterp = currPartialScale / prevPartialScale;
yInterp = 0;
}
//var unInterpolate:Boolean = false;
//var oldPath:KPath = targetPath.clone();
//Case 1
//Key frames without transition paths of required type
if(targetPath.length < 2)
{
if(targetPath.length != 0)
throw new Error("Someone created a path with 1 point somehow! Better check out the path functions");
//Provide the empty path with the positive interpolation first
targetPath.push(xFirst,0,0);
targetPath.push(xInterp, yInterp, targetKey.duration * proportionElapsed);
//If the interpolation is performed in the middle of a key, "uninterpolate" it to 0 interpolation
// if(time != targetKey.time)
// {
// targetPath.push(dx, dy, targetKey.duration);
// }
//Should fill the paths with points here
//KPathProcessing.normalisePathDensity(targetPath);
}
else
{
// RCDavis replaced this with the immediately following code, since both cases are currently the same.
// if(targetKey.time == time) //Case 2:interpolate at key time
// KPathProcessing.interpolateSpan(targetPath, 0, proportionElapsed, xInterp, yInterp);
// else //case 3:interpolate between two keys
// KPathProcessing.interpolateSpan(targetPath, 0, proportionElapsed, xInterp, yInterp);
KPathProcessing.interpolateSpan(targetPath, 0, proportionElapsed, xInterp, yInterp);
if (targetPath == targetKey.rotatePath)
KPathProcessing.limitSegmentLength(targetPath, MAX_ROTATE_STEP);
}
//trace("Time=" + targetKey.time);
//trace("Target Path");
targetPath.debug();
prevScaleDiff = currScaleDiff;
}
params["dirty"] = true;
}
/**
* Make source path the transition path of type for this operator's key list.
* Will split the source path to fit the time range
* Replaces all current paths of given type
*/
protected function _replacePathOverTime(sourcePath:KPath, startTime:Number, endTime:Number, transformType:int, op:KCompositeOperation):void
{
if(sourcePath.length == 0)
return;
var sourceHeader:KSpatialKeyFrame = new KSpatialKeyFrame(startTime, _object.center);
var sourceKey:KSpatialKeyFrame = new KSpatialKeyFrame(endTime, _object.center);
sourceHeader.next = sourceKey;
sourceKey.previous = sourceHeader;
switch(transformType)
{
case KSketch2.TRANSFORM_TRANSLATION:
sourceKey.translatePath = sourcePath;
break;
case KSketch2.TRANSFORM_ROTATION:
sourceKey.rotatePath = sourcePath;
break;
case KSketch2.TRANSFORM_SCALE:
sourceKey.scalePath = sourcePath;
break;
default:
throw new Error("Wrong transform type given!");
}
var toMergeKey:KSpatialKeyFrame;
var currentKey:KSpatialKeyFrame = _refFrame.getKeyAftertime(startTime) as KSpatialKeyFrame;
var targetPath:KPath;
var oldPath:KPath;
while(currentKey && sourceKey != toMergeKey)
{
if(sourceKey.time < currentKey.time)
currentKey = _refFrame.split(currentKey,sourceKey.time, op) as KSpatialKeyFrame;
if(currentKey.time <= sourceKey.time)
{
if(currentKey.time < sourceKey.time)
toMergeKey = sourceKey.splitKey(currentKey.time, new KCompositeOperation()) as KSpatialKeyFrame;
else
toMergeKey = sourceKey;
switch(transformType)
{
case KSketch2.TRANSFORM_TRANSLATION:
targetPath = toMergeKey.translatePath;
oldPath = currentKey.translatePath;
currentKey.translatePath = targetPath;
break;
case KSketch2.TRANSFORM_ROTATION:
targetPath = toMergeKey.rotatePath;
oldPath = currentKey.rotatePath;
currentKey.rotatePath = targetPath;
break;
case KSketch2.TRANSFORM_SCALE:
targetPath = toMergeKey.scalePath;
oldPath = currentKey.scalePath;
currentKey.scalePath = targetPath;
break;
default:
throw new Error("Wrong transform type given!");
}
op.addOperation(new KReplacePathOperation(currentKey, targetPath, oldPath, transformType));
}
currentKey = currentKey.next as KSpatialKeyFrame;
}
if(sourceKey != toMergeKey)
{
_refFrame.insertKey(sourceKey);
op.addOperation(new KInsertKeyOperation(sourceKey.previous, sourceKey.next, sourceKey));
}
}
/**
* Makes sure the object/model is in a magical state in order for transition
* paths to be added to the model
*/
protected function _normaliseForOverwriting(time:Number, op:KCompositeOperation):void
{
var key:KSpatialKeyFrame = _refFrame.getKeyAtTime(time) as KSpatialKeyFrame;
//If there's a key there. Perfect! No need to do anything right now
//Else we need a key here some how
if(!key)
{
key = _refFrame.getKeyAftertime(time) as KSpatialKeyFrame;
//if there's a key after time, we need to split it
if(key)
key = _refFrame.split(key,time, op) as KSpatialKeyFrame;
else
{
key = new KSpatialKeyFrame(time, _object.center);
_refFrame.insertKey(key);
op.addOperation(new KInsertKeyOperation(key.previous, key.next, key));
}
}
if(!key)
throw new Error("Normaliser's magic is failing! Check if your object is available for demonstration!");
//FUTURE OVERWRITING IS DONE HERE
//IF YOU WANT TO CHANGE IMPLEMENTATION FOR FUTURE, DO IT HERE
var currentKey:KSpatialKeyFrame = key;
var oldPath:KPath;
var newPath:KPath;
var validTranslate:Boolean = (TRANSLATE_THRESHOLD < _magX) || (TRANSLATE_THRESHOLD < _magY);
var validRotate:Boolean = ROTATE_THRESHOLD < _magTheta;
var validScale:Boolean = SCALE_THRESHOLD < _magSigma;
while(currentKey.next)
{
currentKey = currentKey.next as KSpatialKeyFrame;
if(validTranslate)
{
//trace("_normaliseForOverwriting translate");
oldPath = currentKey.translatePath;
currentKey.translatePath = new KPath(KPath.TRANSLATE);
newPath = currentKey.translatePath;
op.addOperation(new KReplacePathOperation(currentKey, newPath, oldPath, KSketch2.TRANSFORM_TRANSLATION));
}
if(validRotate)
{
//trace("_normaliseForOverwriting rotate");
oldPath = currentKey.rotatePath;
currentKey.rotatePath = new KPath(KPath.ROTATE);
newPath = currentKey.rotatePath;
op.addOperation(new KReplacePathOperation(currentKey, newPath, oldPath, KSketch2.TRANSFORM_ROTATION));
}
if(validScale)
{
//trace("_normaliseForOverwriting scale");
oldPath = currentKey.scalePath;
currentKey.scalePath = new KPath(KPath.SCALE);
newPath = currentKey.scalePath;
op.addOperation(new KReplacePathOperation(currentKey, newPath, oldPath, KSketch2.TRANSFORM_SCALE));
}
}
}
//Cleans up the model after a transition.
//Splits key frames up if a key frame has a path that does not fill its time span fully.
//Removes empty key frames
protected function _clearEmptyKeys(op:KCompositeOperation):void
{
var currentKey:KSpatialKeyFrame = _refFrame.lastKey as KSpatialKeyFrame;
while(currentKey)
{
if(!currentKey.isUseful() && (currentKey != _refFrame.head))
{
var removeKeyOp:KRemoveKeyOperation = new KRemoveKeyOperation(currentKey.previous, currentKey.next, currentKey);
var nextCurrentKey:KSpatialKeyFrame = currentKey.previous as KSpatialKeyFrame;
_refFrame.removeKeyFrom(currentKey);
currentKey = nextCurrentKey;
op.addOperation(removeKeyOp);
}
else
currentKey = currentKey.previous as KSpatialKeyFrame;
}
}
// ############
// # Modifers #
// ############
public function moveCenter(dx:Number, dy:Number, time:Number):void
{
// set the new center of the object
_object.center = _object.center.add(new Point(dx, dy));
// enable the object's dirty state flag due to the object's changed center
_dirty = true;
// change the object's transform operation
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_CHANGED, _object, time));
// update the object's transform operation
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_UPDATING, _object, time));
}
public function insertBlankKeyFrame(time:Number, op:KCompositeOperation, keyframe:Boolean):void
{
var key:KSpatialKeyFrame = _refFrame.getKeyAftertime(time) as KSpatialKeyFrame;
// case: there exists a key frame after the given time
// need to split the key frame
if(key)
{
key = _refFrame.split(key,time, op) as KSpatialKeyFrame;
if(keyframe)
key.passthrough = false;
}
// case: there doesn't exist a key frame after the given time
else
{
// need to insert a key frame at the given time
key = new KSpatialKeyFrame(time, _object.center);
_refFrame.insertKey(key);
if(keyframe)
key.passthrough = false;
op.addOperation(new KInsertKeyOperation(key.previous, null, key));
}
// enable the dirty state flag due to the object's blank key frame insertion
_dirty = true;
// end the object's transform operation
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_ENDED, _object, time));
}
public function changeKeyPassthrough(time:Number, op:KCompositeOperation, value:Boolean):void
{
var key:KSpatialKeyFrame = _refFrame.getKeyAtTime(time) as KSpatialKeyFrame;
if(op && key.time == time)
{
key.passthrough = value;
var keyOp:KModifyPassthroughOperation = new KModifyPassthroughOperation(key);
op.addOperation(keyOp);
}
// enable the dirty state flag due to the object's blank key frame insertion
_dirty = true;
// end the object's transform operation
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_ENDED, _object, time));
}
public function removeKey(time:Number, op:KCompositeOperation):void
{
// get the key frame after the given time
var key:KSpatialKeyFrame = _refFrame.getKeyAtTime(time) as KSpatialKeyFrame;
//if this is the last key, check if it is a keyframe
if(!key.next)
{
//if key is a keyframe
if(!key.passthrough)
{
//change keyframe to control point
changeKeyPassthrough(time, op, true);
return;
}
}
removeKeyFrame(time, op);
}
private function removeKeyFrame(time:Number, op:KCompositeOperation):void
{
// get the key frame after the given time
var key:KSpatialKeyFrame = _refFrame.getKeyAtTime(time) as KSpatialKeyFrame;
// case: there exists a key frame after the given time
// split the key frame
// note: this method should never be called if the conditions are not correct
if(key)
{
var nextKey:KSpatialKeyFrame = key.next as KSpatialKeyFrame;
var oldPath:KPath = nextKey.translatePath.clone();
var proportionKeyFrame:Number = nextKey.findProportion(nextKey.time);
var point:KTimedPoint = nextKey.translatePath.find_Point(proportionKeyFrame, nextKey);
nextKey.translatePath = KPathProcessing.joinPaths(key.translatePath, nextKey.translatePath,key.duration, nextKey.duration);
op.addOperation(new KReplacePathOperation(nextKey, nextKey.translatePath, oldPath, KSketch2.TRANSFORM_TRANSLATION));
oldPath = nextKey.rotatePath.clone();
nextKey.rotatePath = KPathProcessing.joinPaths(key.rotatePath, nextKey.rotatePath,key.duration, nextKey.duration);
op.addOperation(new KReplacePathOperation(nextKey, nextKey.rotatePath, oldPath, KSketch2.TRANSFORM_ROTATION));
oldPath = nextKey.scalePath.clone();
nextKey.scalePath = KPathProcessing.joinPaths(key.scalePath, nextKey.scalePath,key.duration, nextKey.duration);
op.addOperation(new KReplacePathOperation(nextKey, nextKey.scalePath, oldPath, KSketch2.TRANSFORM_SCALE));
var removeKeyOp:KRemoveKeyOperation = new KRemoveKeyOperation(key.previous, key.next, key);
_refFrame.removeKeyFrame(key);
op.addOperation(removeKeyOp);
}
// case: there doesn't exist a key frame after the given time
// throw an error
else
{
throw new Error("There is no key at time! Cannot remove key");
}
// enable the dirty state flag due to the object's blank key frame insertion
_dirty = true;
// end the object's transform operation
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_ENDED, _object, time));
}
public function clearAllMotionsAfterTime(time:Number, op:KCompositeOperation):void
{
// case: there exists an active key frame at the given time
if(getActiveKey(time))
{
// case: can insert a key frame at the given time
// inserts a blank key frame at the given time
if(canInsertKey(time))
insertBlankKeyFrame(time, op, false);
// set the current key frame as the last key frame in the reference frame
var currentKey:KSpatialKeyFrame = _refFrame.lastKey as KSpatialKeyFrame;
// iterate backwards through the reference frame while the current key frame exists
while(currentKey)
{
// case: the given time is before the curret key frame's time and the current key frame is not the head key frame
// remove the current key frame
if(time < currentKey.time && (currentKey != _refFrame.head))
{
var removeKeyOp:KRemoveKeyOperation = new KRemoveKeyOperation(currentKey.previous, currentKey.next, currentKey);
var nextCurrentKey:KSpatialKeyFrame = currentKey.previous as KSpatialKeyFrame;
_refFrame.removeKeyFrom(currentKey);
currentKey = nextCurrentKey;
op.addOperation(removeKeyOp);
}
else
currentKey = currentKey.previous as KSpatialKeyFrame;
}
// enable the dirty state flag due to the object's blank key frame insertion
_dirty = true;
// end the object's transform operation
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_ENDED, _object, time));
}
}
// #################
// # Miscellaneous #
// #################
/**
* Return a list of headers for key frame linked lists
*/
public function getAllKeyFrames():Vector.<IKeyFrame>
{
var allKeys:Vector.<IKeyFrame> = new Vector.<IKeyFrame>();
allKeys.push(_refFrame.head);
return allKeys;
}
/**
* Merges the transform from the source object into this operator's key list's keys
*/
public function mergeTransform(sourceObject:KObject, stopMergeTime:Number, op:KCompositeOperation):void
{
var sourceInterface:KSingleReferenceFrameOperator = sourceObject.transformInterface.clone() as KSingleReferenceFrameOperator;
var oldInterface:KSingleReferenceFrameOperator = this.clone() as KSingleReferenceFrameOperator;
var toMergeRefFrame:KReferenceFrame = new KReferenceFrame();
var toModifyKey:KSpatialKeyFrame;
var currentKey:KSpatialKeyFrame = sourceInterface.getActiveKey(-1) as KSpatialKeyFrame;
var dummyOp:KCompositeOperation = new KCompositeOperation();
//Clone the source object's reference frame and modify the this operator's reference frame
//Such that it is the same as the source reference frame
//The following loop makes sure that this operator's reference frame
//Has keys at the key times of the source key list
while(currentKey)
{
//To Merge Ref Frame is a new reference frame
//This insert key op is basically adding a cloned key from the source into it
toMergeRefFrame.insertKey(currentKey.clone());
//To Modify key is a key from this operator's reference frame at the cloned key's time
toModifyKey = _refFrame.getKeyAtTime(currentKey.time) as KSpatialKeyFrame;
//If there is a key then we can move on to the next key
if(!toModifyKey)
{
//Else we need to split the next key at this time to make sure a key exists at this time
toModifyKey = _refFrame.getKeyAftertime(currentKey.time) as KSpatialKeyFrame;
if(toModifyKey)
_refFrame.split(toModifyKey,currentKey.time, dummyOp);
else
{
//Else we just insert a new one at time
toModifyKey = new KSpatialKeyFrame(currentKey.time, _object.center);
op.addOperation(new KInsertKeyOperation(_refFrame.getKeyAtBeforeTime(currentKey.time), null, toModifyKey));
_refFrame.insertKey(toModifyKey);
}
}
currentKey = currentKey.next as KSpatialKeyFrame;
}
currentKey = _refFrame.head as KSpatialKeyFrame;
//Modify the source key list to be the same as this operator's key list
while(currentKey)
{
toModifyKey = toMergeRefFrame.getKeyAtTime(currentKey.time) as KSpatialKeyFrame;
if(!toModifyKey)
{
toModifyKey = toMergeRefFrame.getKeyAftertime(currentKey.time) as KSpatialKeyFrame;
if(toModifyKey)
toModifyKey.splitKey(currentKey.time, dummyOp);
}
currentKey = currentKey.next as KSpatialKeyFrame;
}
//Merge the two key lists
currentKey = toMergeRefFrame.head as KSpatialKeyFrame;
var oldPath:KPath;
var keyStartTime:Number;
var currentTime:Number;
var oldMatrix:Matrix;
var newMatrix:Matrix;
var oldPosition:Point;
var newPosition:Point;
var difference:Point;
var centroid:Point = _object.center;
var centroidDiff:Point = sourceObject.center.subtract(_object.center);
var alteredTranslatePath:KPath;
var centroidPath:KPath;
while(currentKey && currentKey.time <= stopMergeTime)
{
toModifyKey = _refFrame.getKeyAtTime(currentKey.time) as KSpatialKeyFrame;
if(!toModifyKey)
{
toModifyKey = new KSpatialKeyFrame(currentKey.time, _object.center);
op.addOperation(new KInsertKeyOperation(_refFrame.getKeyAtBeforeTime(currentKey.time), null, toModifyKey));
_refFrame.insertKey(toModifyKey);
}
oldPath = toModifyKey.rotatePath.clone();
if(currentKey.rotatePath.points.length != 0)
toModifyKey.rotatePath.mergePath(currentKey.rotatePath, currentKey);
op.addOperation(new KReplacePathOperation(toModifyKey, toModifyKey.rotatePath, oldPath, KSketch2.TRANSFORM_ROTATION));
oldPath = toModifyKey.scalePath.clone();
if(currentKey.scalePath.points.length != 0)
toModifyKey.scalePath.mergePath(currentKey.scalePath, currentKey);
op.addOperation(new KReplacePathOperation(toModifyKey, toModifyKey.scalePath, oldPath, KSketch2.TRANSFORM_SCALE));
oldPath = toModifyKey.translatePath.clone();
keyStartTime = toModifyKey.startTime;
currentTime = toModifyKey.startTime;
alteredTranslatePath = new KPath(KPath.TRANSLATE);
alteredTranslatePath.push(0,0,0);
if(currentKey.duration == 0)
{
oldPosition = oldInterface.matrix(currentTime).transformPoint(centroid);
oldPosition = sourceInterface.matrix(currentTime).transformPoint(oldPosition);
newPosition = matrix(currentTime).transformPoint(centroid);
difference = oldPosition.subtract(newPosition);
alteredTranslatePath.push(difference.x, difference.y, currentTime-keyStartTime);
}
else
{
while(currentTime <= toModifyKey.time)
{
oldPosition = oldInterface.matrix(currentTime).transformPoint(centroid);
oldPosition = sourceInterface.matrix(currentTime).transformPoint(oldPosition);
newPosition = matrix(currentTime).transformPoint(centroid);
difference = oldPosition.subtract(newPosition);
alteredTranslatePath.push(difference.x, difference.y, currentTime-keyStartTime);
currentTime += KSketch2.ANIMATION_INTERVAL;
}
}
toModifyKey.translatePath.mergePath(alteredTranslatePath, toModifyKey);
op.addOperation(new KReplacePathOperation(toModifyKey, toModifyKey.translatePath, oldPath, KSketch2.TRANSFORM_TRANSLATION));
if(currentKey.time == stopMergeTime)
break;
currentKey = currentKey.next as KSpatialKeyFrame;
if(currentKey)
{
if(stopMergeTime < currentKey.time)
currentKey = currentKey.splitKey(stopMergeTime,op) as KSpatialKeyFrame;
}
}
dirty = true;//This guy is important if it isn't dirtied, the view wont update.
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_CHANGED, _object, stopMergeTime));
_object.dispatchEvent(new KObjectEvent(KObjectEvent.OBJECT_TRANSFORM_FINALISED, _object, stopMergeTime));
}
/**
* Returns an interator that gives the times of all translate events, in order from beginning to end.
*/
public function translateTimeIterator():INumberIterator
{
return _refFrame.translateTimeIterator();
}
/**
* Returns an interator that gives the times of all rotate events, in order from beginning to end.
*/
public function rotateTimeIterator():INumberIterator
{
return _refFrame.rotateTimeIterator();
}
/**
* Returns an interator that gives the times of all scale events, in order from beginning to end.
*/
public function scaleTimeIterator():INumberIterator
{
return _refFrame.scaleTimeIterator();
}
public function clone():ITransformInterface
{
var newTransformInterface:KSingleReferenceFrameOperator = new KSingleReferenceFrameOperator(_object);
var clonedKeys:KReferenceFrame = _refFrame.clone() as KReferenceFrame;
newTransformInterface._refFrame = clonedKeys;
return newTransformInterface;
}
public function serializeTransform():XML
{
var transformXML:XML = <transform type="single"/>;
var keyListXML:XML = _refFrame.serialize();
transformXML.appendChild(keyListXML);
return transformXML;
}
public function deserializeTransform(xml:XML):void
{
_refFrame = new KReferenceFrame();
var keyListXML:XMLList = xml.keylist.spatialkey;
var startScale:Number = 1;
for(var i:int = 0; i<keyListXML.length(); i++)
{
var currentKeyXML:XML = keyListXML[i];
var newCenter:Point = new Point();
var centerValues:Array = (currentKeyXML.@center.toString()).split(",");
newCenter.x = Number(centerValues[0]);
newCenter.y = Number(centerValues[1]);
var newKey:KSpatialKeyFrame = new KSpatialKeyFrame(new Number(currentKeyXML.@time), new Point());
newKey.deserialize(currentKeyXML, startScale);
startScale *= newKey.fSigma;
_refFrame.insertKey(newKey);
}
}
public function lastKeyWithTransform(targetKey:KSpatialKeyFrame):KSpatialKeyFrame
{
var targetPath:KPath;
//Loop through everything before time to find the correct key with a transform
while(targetKey)
{
if(targetKey.hasActivityAtTime())
return targetKey;
targetKey = targetKey.previous as KSpatialKeyFrame;
}
//Return the reference frame's header if there's nothing.
return _refFrame.head as KSpatialKeyFrame;
}
public function debug():void
{
_refFrame.debug();
}
}
} |
interface IMyInterface { void SomeFunc(); }
class MyBaseClass : IMyInterface { ~MyBaseClass(){ Print(); } void SomeFunc(){} }
class MyDerivedClass : MyBaseClass
{
IMyInterface@ m_obj;
MyDerivedClass(){}
void SetObj( IMyInterface@ obj ) { @m_obj = obj; }
void ClearObj(){ @m_obj = null; }
}
void SomeOtherFunction(){}
any@ GetClass(){
MyDerivedClass x;
any a( @x );
return a;
}
|
package com.playfab.ServerModels
{
import com.playfab.PlayFabUtil;
public class SubscriptionModel
{
public var Expiration:Date;
public var InitialSubscriptionTime:Date;
public var IsActive:Boolean;
public var Status:String;
public var SubscriptionId:String;
public var SubscriptionItemId:String;
public var SubscriptionProvider:String;
public function SubscriptionModel(data:Object=null)
{
if(data == null)
return;
Expiration = PlayFabUtil.parseDate(data.Expiration);
InitialSubscriptionTime = PlayFabUtil.parseDate(data.InitialSubscriptionTime);
IsActive = data.IsActive;
Status = data.Status;
SubscriptionId = data.SubscriptionId;
SubscriptionItemId = data.SubscriptionItemId;
SubscriptionProvider = data.SubscriptionProvider;
}
}
}
|
/*
* Temple Library for ActionScript 3.0
* Copyright © MediaMonks B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by MediaMonks B.V.
* 4. Neither the name of MediaMonks B.V. 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 MEDIAMONKS B.V. ''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 MEDIAMONKS B.V. 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.
*
*
* Note: This license does not apply to 3rd party classes inside the Temple
* repository with their own license!
*/
package temple.ui.behaviors
{
import temple.core.debug.IDebuggable;
import temple.ui.Dot;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
/**
* @eventType temple.ui.behaviors.ZoomBehaviorEvent.ZOOMING
*/
[Event(name = "ZoomBehaviorEvent.zooming", type = "temple.ui.behaviors.ZoomBehaviorEvent")]
/**
* @eventType temple.ui.behaviors.ZoomBehaviorEvent.ZOOM_START
*/
[Event(name = "ZoomBehaviorEvent.zoomStart", type = "temple.ui.behaviors.ZoomBehaviorEvent")]
/**
* @eventType temple.ui.behaviors.ZoomBehaviorEvent.ZOOM_STOP
*/
[Event(name = "ZoomBehaviorEvent.zoomStop", type = "temple.ui.behaviors.ZoomBehaviorEvent")]
/**
* The ZoomBehavior makes it possible to zoom in or out on a DisplayObject. The ZoomBehavior uses the decorator
* pattern, so you won't have to change the code of the DisplayObject. The DisplayObject can be zoomed by using code
* or the MouseWheel.
*
* <p>If you have a MovieClip called 'mcClip' add ZoomBehavior like:</p>
*
* @example
* <listing version="3.0">
* new ZoomBehavior(mcClip);
* </listing>
*
* <p>If you want to limit the zooming to a specific bounds, you can add a Rectangle. By adding the
* Reactangle you won't be able to zoom the DisplayObject outside the Rectangle:</p>
*
* @example
* <listing version="3.0">
* new ZoomBehavior(mcClip, new Reactangle(100, 100, 200, 200);
* </listing>
*
* <p>It is not nessessary to store a reference to the ZoomBehavior since the ZoomBehavior is automatically
* destructed if the DisplayObject is destructed.</p>
*
* @author Arjan van Wijk, Thijs Broerse
*/
public class ZoomBehavior extends BoundsBehavior implements IDebuggable
{
private var _zoomLevel:Number;
private var _minZoom:Number;
private var _maxZoom:Number;
private var _newScale:Number;
private var _newX:Number;
private var _newY:Number;
private var _running:Boolean;
private var _debug:Boolean;
private var _dot:Dot;
/**
* @param target The target to zoom
* @param minZoom Minimal zoom ratio (ie. 0.25)
* @param maxZoom Maximal zoom ratio (ie. 8)
*/
public function ZoomBehavior(target:DisplayObject, bounds:Rectangle = null, minZoom:Number = 1, maxZoom:Number = 4)
{
super(target, bounds);
_minZoom = minZoom;
_maxZoom = maxZoom;
_zoomLevel = 0;
_newScale = target.scaleX;
_newX = target.x;
_newY = target.y;
target.addEventListener(MouseEvent.MOUSE_WHEEL, handleMouseWheel);
_running = false;
// dispath ZoomBehaviorEvent on target
addEventListener(ZoomBehaviorEvent.ZOOM_START, target.dispatchEvent);
addEventListener(ZoomBehaviorEvent.ZOOM_STOP, target.dispatchEvent);
addEventListener(ZoomBehaviorEvent.ZOOMING, target.dispatchEvent);
}
/**
* Zooms to a specific zoom level
* @param zoom the level to zoom to
* @param center a point which is used as the center of the zooming, if null the center of the object is used.
*/
public function zoomTo(zoom:Number, point:Point = null):void
{
_zoomLevel = Math.log(zoom) / Math.log(2);
updateZoom(point || getCenter());
}
/**
* Stops the zooming
*/
public function stopZoom():void
{
if (_running)
{
_running = false;
displayObject.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
dispatchEvent(new ZoomBehaviorEvent(ZoomBehaviorEvent.ZOOM_STOP, this));
}
}
/**
* The minimal zoom
*/
public function get minZoom():Number
{
return _minZoom;
}
/**
* @private
*/
public function set minZoom(minZoom:Number):void
{
_minZoom = minZoom;
}
/**
* The maximal zoom
*/
public function get maxZoom():Number
{
return _maxZoom;
}
/**
* @private
*/
public function set maxZoom(maxZoom:Number):void
{
_maxZoom = maxZoom;
}
/**
* The current zoom
*/
public function get zoom():Number
{
return Math.pow(2, _zoomLevel);
}
/**
* @private
*/
public function set zoom(value:Number):void
{
_zoomLevel = Math.log(value) / Math.log(2);
updateZoom(getCenter());
}
/**
* The current zoomLevel
*/
public function get zoomLevel():Number
{
return _zoomLevel;
}
/**
* Recalculates the zoom based on the targets current scale.
*/
public function recalculateZoom():void
{
_zoomLevel = Math.log(displayObject.scaleX) / Math.log(2);
}
/**
* @inheritDoc
*/
public function get debug():Boolean
{
return _debug;
}
/**
* @inheritDoc
*/
public function set debug(value:Boolean):void
{
_debug = value;
}
/**
* @private
*/
protected function handleEnterFrame(event:Event):void
{
displayObject.scaleX = displayObject.scaleY += (_newScale - displayObject.scaleY) / 5;
displayObject.x += (_newX - displayObject.x) / 5;
displayObject.y += (_newY - displayObject.y) / 5;
dispatchEvent(new ZoomBehaviorEvent(ZoomBehaviorEvent.ZOOMING, this));
if (Math.abs(displayObject.scaleX - _newScale) < .01)
{
displayObject.scaleX = displayObject.scaleY = _newScale;
displayObject.x = _newX;
displayObject.y = _newY;
stopZoom();
}
keepInBounds();
}
/**
* @private
*/
protected function handleMouseWheel(event:MouseEvent):void
{
_zoomLevel += (event.delta / 3) / 4;
updateZoom(new Point((displayObject.mouseX * displayObject.scaleX) / displayObject.width, (displayObject.mouseY * displayObject.scaleY) / displayObject.height));
}
/**
* @private
*/
protected function updateZoom(point:Point):void
{
var prevW:Number = displayObject.width;
var prevH:Number = displayObject.height;
_newScale = Math.max(_minZoom, Math.min(_maxZoom, Math.pow(2, _zoomLevel)));
_zoomLevel = Math.log(_newScale) / Math.log(2);
_newX = displayObject.x + point.x * (prevW - (displayObject.width / displayObject.scaleX * _newScale));
_newY = displayObject.y + point.y * (prevH - (displayObject.height / displayObject.scaleY * _newScale));
if (_running == false)
{
_running = true;
displayObject.addEventListener(Event.ENTER_FRAME, handleEnterFrame, false, 0, true);
dispatchEvent(new ZoomBehaviorEvent(ZoomBehaviorEvent.ZOOM_START, this));
}
dispatchEvent(new Event(Event.CHANGE));
if (_debug)
{
_dot ||= new Dot();
DisplayObjectContainer(displayObject).addChild(_dot);
_dot.x = point.x * (displayObject.width / displayObject.scaleX);
_dot.y = point.y * (displayObject.height / displayObject.scaleY);
_dot.scaleX = 1 / displayObject.scaleX;
_dot.scaleY = 1 / displayObject.scaleY;
logDebug("Zoom: " + point.x + ", " + point.y);
}
else if (_dot && _dot.parent)
{
_dot.parent.removeChild(_dot);
}
}
private function getCenter():Point
{
var rect:Rectangle = displayObject.getRect(displayObject);
return new Point(rect.x/rect.width + .5, rect.y/rect.height + .5);
}
/**
* @inheritDoc
*/
override public function destruct():void
{
if (target) displayObject.removeEventListener(MouseEvent.MOUSE_WHEEL, handleMouseWheel);
if (_running) stopZoom();
super.destruct();
}
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2005-2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
var SECTION = "date-004";
var VERSION = "JS1_4";
var TITLE = "Date.prototype.getTime";
startTest();
writeHeaderToLog( SECTION + " "+ TITLE);
var testcases = getTestCases();
test();
function getTestCases() {
var array = new Array();
var item = 0;
var result = "Failed";
var exception = "No exception thrown";
var expect = "Passed";
try {
var MYDATE = new MyDate();
result = MYDATE.getTime();
} catch ( e ) {
result = expect;
exception = e.toString();
}finally{
array[item++] = new TestCase(
SECTION,
"MYDATE = new MyDate(); MYDATE.getTime()",
TYPEERROR+1034,
typeError( exception ) );
}
return array;
}
function MyDate( value ) {
this.value = value;
this.getTime = Date.prototype.getTime;
}
|
package sh.saqoo.util {
import flash.media.Sound;
import flash.utils.ByteArray;
/**
* @author Saqoosha
*/
public class SoundUtil {
/**
* @param sound Sound instance to extract.
* @param numSamples Number of samples.
* @param startPosition Start position in milliseconds.
* @param outData ByteArray to copy to. If not specified, allocated inside this method and returned.
*/
public static function extractLoop(sound:Sound, numSamples:int, startPosition:Number, outData:ByteArray = null):ByteArray {
outData ||= new ByteArray();
var n:int = sound.extract(outData, numSamples, startPosition);
if (numSamples - n > 0) {
sound.extract(outData, numSamples - n, 0);
}
return outData;
}
/**
* @param soundData Sound data represented by ByteArray.
* @param numSamples Number of samples to copy.
* @param startPosition Start position in samples.
* @param outData ByteArray to copy to. If not specified, allocated inside this method and returned.
*/
public static function copyLoopBytes(soundData:ByteArray, numSamples:int, startPosition:int, outData:ByteArray = null):ByteArray {
outData ||= new ByteArray();
var require:int = numSamples << 3;
var available:int = soundData.length - (soundData.position << 3);
available &= 0x7ffffff8;
if (require <= available) {
outData.writeBytes(soundData, startPosition << 3, require);
} else {
outData.writeBytes(soundData, startPosition << 3, available);
outData.writeBytes(soundData, 0, require - available);
}
return outData;
}
}
}
|
package test.yellcorp.lib.geom.Vector3
{
import org.yellcorp.lib.geom.Vector3;
public class TestMutators extends BaseVector3TestCase
{
public function TestMutators(testMethod:String = null)
{
super(testMethod);
}
public function testAdd():void
{
var u:Vector3 = new Vector3(1, 2, 3);
var v:Vector3 = u.clone();
var w:Vector3 = new Vector3(-3, -8, -1);
u.add(w);
assertVectorEqualsXYZ("add", v.x + w.x, v.y + w.y, v.z + w.z, u);
}
public function testSubtract():void
{
var u:Vector3 = new Vector3(-2, 7, 12);
var v:Vector3 = u.clone();
var w:Vector3 = new Vector3(1, -9, 9031);
u.subtract(w);
assertVectorEqualsXYZ("subtract", v.x - w.x, v.y - w.y, v.z - w.z, u);
}
public function testNegate():void
{
var u:Vector3 = new Vector3(1, -1, 2);
var v:Vector3 = u.clone();
u.negate();
assertVectorEqualsXYZ("negate", -v.x, -v.y, -v.z, u);
}
public function testScale():void
{
var u:Vector3 = new Vector3(5, -7, 19);
var v:Vector3 = u.clone();
var s:Number = 2;
u.scale(s);
assertVectorEqualsXYZ("scale", v.x * s, v.y * s, v.z* s, u);
}
public function testCross():void
{
var u:Vector3 = new Vector3(-2, 7, 12);
var v:Vector3 = u.clone();
var w:Vector3 = new Vector3(1, -9, 9031);
u.cross(w);
assertVectorEqualsXYZ("cross",
v.y * w.z - v.z * w.y,
v.z * w.x - v.x * w.z,
v.x * w.y - v.y * w.x,
u);
}
public function testNormalizeZero():void
{
var v:Vector3 = new Vector3(0,0,0);
v.normalize();
assertFalse("normalized zero vector is not finite", v.isfinite());
assertTrue(isNaN(v.x));
assertTrue(isNaN(v.y));
assertTrue(isNaN(v.z));
}
public function testNormalize():void
{
var testVectors:Array = makeCombinations([1, -1, 2, -2, Math.PI, -Math.PI]);
function testNormalizeSingle(v:Vector3):void
{
v.normalize();
assertEqualsFloat("normalize", 1, v.norm(), TEST_FLOAT_TOLERANCE);
}
for each (var v:Vector3 in testVectors)
{
testNormalizeSingle(v);
}
}
}
}
|
package cmodule.lua_wrapper
{
const __2E_str9266:int = gstaticInitter.alloc(5,1);
}
|
package im.chatFrame
{
import com.pickgliss.events.FrameEvent;
import com.pickgliss.ui.ComponentFactory;
import com.pickgliss.ui.controls.MinimizeFrame;
import com.pickgliss.ui.controls.SimpleBitmapButton;
import com.pickgliss.ui.image.ScaleBitmapImage;
import com.pickgliss.ui.text.FilterFrameText;
import com.pickgliss.ui.text.GradientText;
import com.pickgliss.ui.text.TextArea;
import com.pickgliss.utils.ObjectUtils;
import ddt.data.player.PlayerInfo;
import ddt.data.player.SelfInfo;
import ddt.manager.LanguageMgr;
import ddt.manager.MessageTipManager;
import ddt.manager.PlayerManager;
import ddt.manager.SocketManager;
import ddt.manager.SoundManager;
import ddt.utils.FilterWordManager;
import ddt.utils.PositionUtils;
import ddt.view.PlayerPortraitView;
import ddt.view.common.LevelIcon;
import flash.display.Bitmap;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import im.IMController;
import road7th.utils.StringHelper;
import vip.VipController;
public class PrivateChatFrame extends MinimizeFrame
{
private var _info:PlayerInfo;
private var _outputBG:ScaleBitmapImage;
private var _inputBG:ScaleBitmapImage;
private var _output:TextArea;
private var _input:TextArea;
private var _send:SimpleBitmapButton;
private var _record:SimpleBitmapButton;
private var _recordFrame:PrivateRecordFrame;
private var _show:Boolean = false;
private var _selfPortrait:PlayerPortraitView;
private var _selfLevelT:FilterFrameText;
private var _selfLevel:LevelIcon;
private var _selfName:FilterFrameText;
private var _selfVipName:GradientText;
private var _targetProtrait:PlayerPortraitView;
private var _targetLevelT:FilterFrameText;
private var _targetLevel:LevelIcon;
private var _targetName:FilterFrameText;
private var _targetVipName:GradientText;
private var _warningBg:Bitmap;
private var _warning:Bitmap;
private var _warningWord:FilterFrameText;
public function PrivateChatFrame()
{
super();
this.initView();
this.initEvent();
}
private function initView() : void
{
var _loc1_:SelfInfo = null;
this._selfPortrait = ComponentFactory.Instance.creatCustomObject("chatFrame.selfPortrait",["right"]);
this._selfLevelT = ComponentFactory.Instance.creatComponentByStylename("chatFrame.selflevel");
this._selfLevel = ComponentFactory.Instance.creatCustomObject("chatFrame.selfLevelIcon");
this._targetProtrait = ComponentFactory.Instance.creatCustomObject("chatFrame.targetPortrait",["right"]);
this._targetLevelT = ComponentFactory.Instance.creatComponentByStylename("chatFrame.targetlevel");
this._targetLevel = ComponentFactory.Instance.creatCustomObject("chatFrame.targetLevelIcon");
this._outputBG = ComponentFactory.Instance.creatComponentByStylename("chatFrame.outputBG");
this._inputBG = ComponentFactory.Instance.creatComponentByStylename("chatFrame.inputBG");
this._output = ComponentFactory.Instance.creatComponentByStylename("chatFrame.output");
this._input = ComponentFactory.Instance.creatComponentByStylename("chatFrame.input");
this._send = ComponentFactory.Instance.creatComponentByStylename("chatFrame.send");
this._record = ComponentFactory.Instance.creatComponentByStylename("chatFrame.record");
this._warningBg = ComponentFactory.Instance.creatBitmap("asset.chatFrame.worningbg");
this._warning = ComponentFactory.Instance.creatBitmap("asset.chatFrame.worning");
this._warningWord = ComponentFactory.Instance.creatComponentByStylename("chatFrame.warningword");
addToContent(this._selfPortrait);
addToContent(this._selfLevelT);
addToContent(this._selfLevel);
addToContent(this._targetProtrait);
addToContent(this._targetLevelT);
addToContent(this._targetLevel);
addToContent(this._outputBG);
addToContent(this._inputBG);
addToContent(this._output);
addToContent(this._input);
addToContent(this._send);
addToContent(this._record);
addToContent(this._warningBg);
addToContent(this._warningWord);
addToContent(this._warning);
this._input.textField.maxChars = 150;
this._send.tipStyle = "ddt.view.tips.OneLineTip";
this._send.tipDirctions = "0";
this._send.tipGapV = 5;
this._send.tipData = LanguageMgr.GetTranslation("IM.privateChatFrame.send.tipdata");
_loc1_ = PlayerManager.Instance.Self;
this._selfPortrait.info = _loc1_;
this._selfLevelT.text = LanguageMgr.GetTranslation("IM.ChatFrame.level");
this._selfLevel.setSize(LevelIcon.SIZE_SMALL);
this._selfLevel.setInfo(_loc1_.Grade,_loc1_.Repute,_loc1_.WinCount,_loc1_.TotalCount,_loc1_.FightPower,_loc1_.Offer,false,true);
this._selfLevel.mouseChildren = false;
this._selfLevel.mouseEnabled = false;
if(_loc1_.IsVIP)
{
this._selfVipName = VipController.instance.getVipNameTxt(84,_loc1_.typeVIP);
this._selfVipName.textSize = 14;
this._selfVipName.x = 16;
this._selfVipName.y = 303;
this._selfVipName.text = _loc1_.NickName;
addToContent(this._selfVipName);
}
else
{
this._selfName = ComponentFactory.Instance.creatComponentByStylename("chatFrame.selfName");
this._selfName.text = _loc1_.NickName;
addToContent(this._selfName);
}
this._targetLevelT.text = LanguageMgr.GetTranslation("IM.ChatFrame.level");
this._targetLevel.setSize(LevelIcon.SIZE_SMALL);
this._targetLevel.mouseChildren = false;
this._targetLevel.mouseEnabled = false;
this._warningWord.text = LanguageMgr.GetTranslation("IM.ChatFrame.warning");
}
public function set playerInfo(param1:PlayerInfo) : void
{
if(this._info != param1)
{
this._input.text = "";
this._output.htmlText = "";
this.closeRecordFrame();
}
this._info = param1;
this._targetProtrait.info = this._info;
this._targetLevel.setInfo(this._info.Grade,this._info.Repute,this._info.WinCount,this._info.TotalCount,this._info.FightPower,this._info.Offer,false,true);
if(this._info.IsVIP)
{
if(this._targetVipName == null)
{
this._targetVipName = VipController.instance.getVipNameTxt(84,this._info.typeVIP);
this._targetVipName.textSize = 14;
this._targetVipName.x = 16;
this._targetVipName.y = 136;
addToContent(this._targetVipName);
}
if(this._targetName)
{
this._targetName.visible = false;
}
this._targetVipName.visible = true;
this._targetVipName.text = this._info.NickName;
}
else
{
if(this._targetName == null)
{
this._targetName = ComponentFactory.Instance.creatComponentByStylename("chatFrame.targetName");
addToContent(this._targetName);
}
if(this._targetVipName)
{
this._targetVipName.visible = false;
}
this._targetName.visible = true;
this._targetName.text = this._info.NickName;
}
}
public function clearOutput() : void
{
this._output.htmlText = "";
}
public function addMessage(param1:String) : void
{
this._output.htmlText = this._output.htmlText + (param1 + "<br/>");
this._output.textField.setSelection(this._output.text.length - 1,this._output.text.length - 1);
this._output.upScrollArea();
}
public function addAllMessage(param1:Vector.<String>) : void
{
this._output.htmlText = "";
var _loc2_:int = 0;
while(_loc2_ < param1.length)
{
this._output.htmlText = this._output.htmlText + (param1[_loc2_] + "<br/>");
_loc2_++;
}
this._output.textField.setSelection(this._output.text.length - 1,this._output.text.length - 1);
this._output.upScrollArea();
}
public function get playerInfo() : PlayerInfo
{
return this._info;
}
private function initEvent() : void
{
addEventListener(FrameEvent.RESPONSE,this.__responseHandler);
this._send.addEventListener(MouseEvent.CLICK,this.__sendHandler);
this._record.addEventListener(MouseEvent.CLICK,this.__recordHandler);
this._input.addEventListener(KeyboardEvent.KEY_UP,this.__keyUpHandler);
this._input.addEventListener(KeyboardEvent.KEY_DOWN,this.__keyDownHandler);
this._input.addEventListener(FocusEvent.FOCUS_IN,this.__focusInHandler);
this._input.addEventListener(FocusEvent.FOCUS_OUT,this.__focusOutHandler);
addEventListener(Event.ADDED_TO_STAGE,this.__addToStageHandler);
}
private function removeEvent() : void
{
removeEventListener(FrameEvent.RESPONSE,this.__responseHandler);
this._send.removeEventListener(MouseEvent.CLICK,this.__sendHandler);
this._record.removeEventListener(MouseEvent.CLICK,this.__recordHandler);
this._input.removeEventListener(KeyboardEvent.KEY_UP,this.__keyUpHandler);
this._input.removeEventListener(KeyboardEvent.KEY_DOWN,this.__keyDownHandler);
this._input.removeEventListener(FocusEvent.FOCUS_IN,this.__focusInHandler);
this._input.removeEventListener(FocusEvent.FOCUS_OUT,this.__focusOutHandler);
removeEventListener(Event.ADDED_TO_STAGE,this.__addToStageHandler);
}
private function __keyDownHandler(param1:KeyboardEvent) : void
{
param1.stopImmediatePropagation();
param1.stopPropagation();
}
protected function __addToStageHandler(param1:Event) : void
{
this._input.textField.setFocus();
}
protected function __focusOutHandler(param1:FocusEvent) : void
{
IMController.Instance.privateChatFocus = false;
}
protected function __focusInHandler(param1:FocusEvent) : void
{
IMController.Instance.privateChatFocus = true;
}
protected function __keyUpHandler(param1:KeyboardEvent) : void
{
param1.stopImmediatePropagation();
param1.stopPropagation();
if(param1.keyCode == Keyboard.ENTER)
{
this.__sendHandler(null);
}
}
protected function __recordHandler(param1:MouseEvent) : void
{
SoundManager.instance.play("008");
if(this._recordFrame == null)
{
this._recordFrame = ComponentFactory.Instance.creatComponentByStylename("privateRecordFrame");
this._recordFrame.addEventListener(FrameEvent.RESPONSE,this.__recordResponseHandler);
this._recordFrame.addEventListener(PrivateRecordFrame.CLOSE,this.__recordCloseHandler);
PositionUtils.setPos(this._recordFrame,"recordFrame.pos");
}
if(!this._show)
{
addToContent(this._recordFrame);
this._recordFrame.playerId = this._info.ID;
this._show = true;
}
else
{
this.closeRecordFrame();
}
}
private function closeRecordFrame() : void
{
if(this._recordFrame && this._recordFrame.parent)
{
this._recordFrame.parent.removeChild(this._recordFrame);
}
this._show = false;
}
protected function __recordCloseHandler(param1:Event) : void
{
SoundManager.instance.play("008");
this._recordFrame.parent.removeChild(this._recordFrame);
this._show = false;
}
protected function __recordResponseHandler(param1:FrameEvent) : void
{
if(param1.responseCode == FrameEvent.CLOSE_CLICK)
{
SoundManager.instance.play("008");
this._recordFrame.parent.removeChild(this._recordFrame);
this._show = false;
}
}
protected function __sendHandler(param1:MouseEvent) : void
{
var _loc2_:String = null;
SoundManager.instance.play("008");
if(this._info.Grade < 5)
{
MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("IM.other.noEnough.five"));
return;
}
if(StringHelper.trim(this._input.text) != "")
{
_loc2_ = this._input.text.replace(/</g,"<").replace(/>/g,">");
_loc2_ = FilterWordManager.filterWrod(_loc2_);
SocketManager.Instance.out.sendOneOnOneTalk(this._info.ID,_loc2_);
this._input.text = "";
}
else
{
this._input.text = "";
}
this.__addToStageHandler(null);
}
private function checkHtmlTag(param1:String) : Boolean
{
if(param1.indexOf("<") != -1 || FilterWordManager.isGotForbiddenWords(param1))
{
MessageTipManager.getInstance().show(LanguageMgr.GetTranslation("IM.privateChatFrame.failWord"));
return false;
}
return true;
}
protected function __responseHandler(param1:FrameEvent) : void
{
SoundManager.instance.play("008");
switch(param1.responseCode)
{
case FrameEvent.ESC_CLICK:
case FrameEvent.CLOSE_CLICK:
IMController.Instance.disposePrivateFrame(this._info.ID);
this._output.htmlText = "";
break;
case FrameEvent.MINIMIZE_CLICK:
IMController.Instance.hidePrivateFrame(this._info.ID);
}
}
override public function dispose() : void
{
IMController.Instance.privateChatFocus = false;
this.removeEvent();
super.dispose();
if(this._recordFrame)
{
this._recordFrame.removeEventListener(FrameEvent.RESPONSE,this.__recordResponseHandler);
this._recordFrame.removeEventListener(PrivateRecordFrame.CLOSE,this.__recordCloseHandler);
this._recordFrame.dispose();
this._recordFrame = null;
}
this._info = null;
if(this._outputBG)
{
ObjectUtils.disposeObject(this._outputBG);
}
this._outputBG = null;
if(this._inputBG)
{
ObjectUtils.disposeObject(this._inputBG);
}
this._inputBG = null;
if(this._output)
{
ObjectUtils.disposeObject(this._output);
}
this._output = null;
if(this._input)
{
ObjectUtils.disposeObject(this._input);
}
this._input = null;
if(this._send)
{
ObjectUtils.disposeObject(this._send);
}
this._send = null;
if(this._record)
{
ObjectUtils.disposeObject(this._record);
}
this._record = null;
if(this._selfPortrait)
{
ObjectUtils.disposeObject(this._selfPortrait);
}
this._selfPortrait = null;
if(this._selfLevelT)
{
ObjectUtils.disposeObject(this._selfLevelT);
}
this._selfLevelT = null;
if(this._selfLevel)
{
ObjectUtils.disposeObject(this._selfLevel);
}
this._selfLevel = null;
if(this._selfName)
{
ObjectUtils.disposeObject(this._selfName);
}
this._selfName = null;
if(this._selfVipName)
{
ObjectUtils.disposeObject(this._selfVipName);
}
this._selfVipName = null;
if(this._targetProtrait)
{
ObjectUtils.disposeObject(this._targetProtrait);
}
this._targetProtrait = null;
if(this._targetLevelT)
{
ObjectUtils.disposeObject(this._targetLevelT);
}
this._targetLevelT = null;
if(this._targetLevel)
{
ObjectUtils.disposeObject(this._targetLevel);
}
this._targetLevel = null;
if(this._targetName)
{
ObjectUtils.disposeObject(this._targetName);
}
this._targetName = null;
if(this._targetVipName)
{
ObjectUtils.disposeObject(this._targetVipName);
}
this._targetVipName = null;
if(this._warningBg)
{
ObjectUtils.disposeObject(this._warningBg);
}
this._warningBg = null;
if(this._warning)
{
ObjectUtils.disposeObject(this._warning);
}
this._warning = null;
if(this._warningWord)
{
ObjectUtils.disposeObject(this._warningWord);
}
this._warningWord = null;
if(parent)
{
parent.removeChild(this);
}
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flexUnitTests.flexUnit4.suites.frameworkSuite.cases
{
import org.flexunit.Assert;
/**
* @private
*/
public class TestBeforeAfterOrder {
protected static var setupOrderArray:Array = new Array();
[Before]
public function beginNoOrder():void {
setupOrderArray.push( "beginNoOrder" );
}
[Before(order=1)]
public function beginOne():void {
setupOrderArray.push( "beginOne" );
}
[Before(order=70)]
public function beginSeventy():void {
setupOrderArray.push( "beginSeventy" );
}
[Before(order=2)]
public function beginTwo():void {
setupOrderArray.push( "beginTwo" );
}
[After]
public function afterNoOrder() : void {
setupOrderArray.push( "afterNoOrder" );
}
[After(order=1)]
public function afterOne():void {
setupOrderArray.push( "afterOne" );
}
[After(order=2)]
public function afterTwo():void {
setupOrderArray.push( "afterTwo" );
}
[After(order=8)]
public function afterEight():void {
setupOrderArray.push( "afterEight" );
}
[After(order=30)]
public function afterThirty():void {
setupOrderArray.push( "afterThirty" );
}
//This depends on the test order also working, so we should always run this test after the method order has been verified
[Test(order=1)]
public function checkingBeforeOrder() : void {
//4 begins
if ( setupOrderArray.length == 4 ) {
Assert.assertEquals( setupOrderArray[ 0 ], "beginNoOrder" );
Assert.assertEquals( setupOrderArray[ 1 ], "beginOne" );
Assert.assertEquals( setupOrderArray[ 2 ], "beginTwo" );
Assert.assertEquals( setupOrderArray[ 3 ], "beginSeventy" );
} else {
Assert.fail("Incorrect number of begin calls");
}
}
[Test(order=2)]
public function checkingAfterOrder() : void {
//4 begins
//5 afters
//4 more begins
if ( setupOrderArray.length == 13 ) {
Assert.assertEquals( setupOrderArray[ 4 ], "afterNoOrder" );
Assert.assertEquals( setupOrderArray[ 5 ], "afterOne" );
Assert.assertEquals( setupOrderArray[ 6 ], "afterTwo" );
Assert.assertEquals( setupOrderArray[ 7 ], "afterEight" );
Assert.assertEquals( setupOrderArray[ 8 ], "afterThirty" );
} else {
Assert.fail("Incorrect number of after calls");
}
}
}
} |
package com.playata.application.data.constants
{
import com.playata.framework.core.TypedObject;
import com.playata.framework.data.constants.ConstantsData;
public class CEventQuest extends ConstantsData
{
public static const CONSTANTS_KEY:String = "event_quests";
public static const ID_NAME:String = "event_identifier";
public function CEventQuest(param1:TypedObject)
{
super(param1);
}
public static function get constantsData() : *
{
return ConstantsData.getConstantsData("event_quests");
}
public static function get count() : int
{
return ConstantsData.getCount("event_quests");
}
public static function get ids() : Vector.<String>
{
return ConstantsData.getStringVectorIds("event_quests");
}
public static function exists(param1:String) : Boolean
{
return ConstantsData.getIdExists("event_quests",param1);
}
public static function fromId(param1:String) : CEventQuest
{
return ConstantsData.getConstantsDataObject(param1,CEventQuest) as CEventQuest;
}
public function get eventIdentifier() : String
{
return getString("event_identifier");
}
public function get startDate() : String
{
return getString("start_date");
}
public function get endDate() : String
{
return getString("end_date");
}
public function get reward1Type() : int
{
return getInt("reward1_type");
}
public function get reward1Factor() : int
{
return getInt("reward1_factor");
}
public function get reward1Flag() : String
{
return getString("reward1_flag");
}
public function get reward2Type() : int
{
return getInt("reward2_type");
}
public function get reward2Factor() : int
{
return getInt("reward2_factor");
}
public function get reward2Flag() : String
{
return getString("reward2_flag");
}
public function get rewardItem1Id() : String
{
return getString("reward_item1");
}
public function get rewardItem1() : CItemTemplate
{
return CItemTemplate.fromId(getId("reward_item1"));
}
public function get rewardItem2Id() : String
{
return getString("reward_item2");
}
public function get rewardItem2() : CItemTemplate
{
return CItemTemplate.fromId(getId("reward_item2"));
}
public function get rewardItem3Id() : String
{
return getString("reward_item3");
}
public function get rewardItem3() : CItemTemplate
{
return CItemTemplate.fromId(getId("reward_item3"));
}
public function get rewardItem1LevelPlus() : int
{
return getInt("reward_item1_level_plus");
}
public function get rewardItem2LevelPlus() : int
{
return getInt("reward_item2_level_plus");
}
public function get rewardItem3LevelPlus() : int
{
return getInt("reward_item3_level_plus");
}
public function get rewardTitleId() : String
{
return getString("reward_title");
}
public function get rewardTitle() : CTitle
{
return CTitle.fromId(getId("reward_title"));
}
public function get objectiveIds() : Vector.<String>
{
return getSubStringVectorIds("objectives");
}
public function hasObjectiveId(param1:String) : Boolean
{
return objectiveIds.indexOf(param1) != -1;
}
public function getObjective(param1:String) : CEventQuestObjective
{
return getSubData("objectives",eventIdentifier,param1,CEventQuestObjective) as CEventQuestObjective;
}
}
}
|
// Copyright (c) 2014 www.9miao.com All rights reserved.
package dUI
{
/**
* ...
* @author dym
*/
public class dUISuperTextUnderLineObj extends dUIImageBox
{
public var m_nUnderLineID:int = -1;
//public var m_rcBound:Rectangle;
public function dUISuperTextUnderLineObj( pFather:dUIImage )
{
super( pFather );
m_nObjType = dUISystem.GUIOBJ_TYPE_SUPERTEXTLINEOBJ;
SetHandleMouse( true );
//pFather.DrawTo( this , 0 , 0 , GetWidth() , GetHeight() , 0 , 0 , GetWidth() , GetHeight() );
//FillColor( 0x80FF0000 );
//FlashWindow( -1 , 500 , 0 , 0 );
/*useHandCursor = true;
buttonMode = true;
tabEnabled = false;*/
}
/*public function GetSuperTextFather():dUISuperText
{
return GetFather() as dUISuperText;
}
override public function OnLButtonDown( x:int , y:int ):void
{
if ( root && root.stage ) root.stage.focus = null;
super.OnLButtonDown( x , y );
GetSuperTextFather().OnUnderLineObjDown( this );
}
override public function OnMouseIn( x:int , y:int ):void
{
if ( !isRelease() )
{
super.OnMouseIn( x , y );
GetSuperTextFather().OnUnderLineObjMouseIn( this , x , y );
}
}
override public function OnMouseOut( x:int , y:int ):void
{
if ( !isRelease() )
{
super.OnMouseOut( x , y );
GetSuperTextFather().OnUnderLineObjMouseOut( this , x , y );
}
}*/
}
} |
package com.company.assembleegameclient.objects {
public class TextureDataFactory {
public function TextureDataFactory() {
super();
}
public function create(_arg_1:XML):TextureData {
return new TextureDataConcrete(_arg_1);
}
}
}
|
package cmodule.lua_wrapper
{
function AS3_FunctionT(param1:int, param2:int, param3:String, param4:String, param5:Boolean) : Function
{
var _loc6_:CTypemap = null;
_loc6_ = new CProcTypemap(CTypemap.getTypeByName(param3),CTypemap.getTypesByNames(param4),param5);
return AS3_Function(param1,_loc6_.fromC([param2]));
}
}
|
package org.shypl.common.loader {
import flash.display.BitmapData;
public interface ImageReceiver {
function receiveImage(image:BitmapData):void;
}
}
|
/**
* Created by max.rozdobudko@gmail.com on 2/24/18.
*/
package feathersx.mvvc.support {
import feathers.controls.ScreenNavigatorItem;
import feathers.controls.StackScreenNavigator;
import feathers.controls.StackScreenNavigatorItem;
import feathers.controls.StackScreenNavigatorItem;
import feathers.controls.StackScreenNavigatorItem;
import feathers.controls.supportClasses.IScreenNavigatorItem;
import feathers.events.FeathersEventType;
import feathersx.mvvc.NavigatorItem;
import starling.events.Event;
public class StackScreenNavigatorHolderHelper {
// Constructor
public function StackScreenNavigatorHolderHelper(navigator: StackScreenNavigator) {
super();
_navigator = navigator;
}
// Navigator
private var _navigator: StackScreenNavigator;
// MARK: Retrieve
public function getScreenWithId(id: String): StackScreenNavigatorItem {
return _navigator.getScreen(id);
}
public function hasScreenWithId(id: String): Boolean {
return _navigator.hasScreen(id);
}
// MARK: Add
public function addScreenWithId(id: String, screen: StackScreenNavigatorItem, completion: Function): void {
addScreensWithIds(new <String>[id], new <StackScreenNavigatorItem>[screen], completion);
}
public function addScreensWithIds(ids: Vector.<String>, screens: Vector.<StackScreenNavigatorItem>, completion: Function): void {
waitForTransitionCompleteIfNeeded(function (): void {
doAddScreensWithIds(ids, screens, completion);
});
}
protected function doAddScreensWithIds(ids: Vector.<String>, items: Vector.<StackScreenNavigatorItem>, completion: Function): void {
var result: Vector.<StackScreenNavigatorItem> = new Vector.<StackScreenNavigatorItem>();
for (var i: int = 0; i < ids.length; i++) {
var id: String = ids[i];
var item: StackScreenNavigatorItem = items[i];
if (_navigator.hasScreen(id)) {
_navigator.removeScreen(id);
}
_navigator.addScreen(id, item);
}
if (completion != null) {
completion();
}
}
// MARK: Remove
public function removeScreenWithId(id: String, completion: Function): void {
removeScreenWithIds(new <String>[id], completion);
}
public function removeScreenWithIds(ids: Vector.<String>, completion: Function): void {
var hasScreen: Boolean = ids.some(function(id: String, ...rest): Boolean {
return _navigator.hasScreen(id);
});
if (!hasScreen) {
if (completion != null) {
completion();
}
return;
}
waitForTransitionCompleteIfNeeded(function (): void {
doRemoveScreensWithIds(ids, completion);
});
}
protected function doRemoveScreensWithIds(ids: Vector.<String>, completion: Function): Vector.<StackScreenNavigatorItem> {
var result: Vector.<StackScreenNavigatorItem> = new Vector.<StackScreenNavigatorItem>();
for (var i: int = 0; i < ids.length; i++) {
var id: String = ids[i];
if (!_navigator.hasScreen(id)) {
result[i] = null;
continue;
}
result[i] = _navigator.removeScreen(id);
}
if (completion != null) {
completion();
}
return result;
}
// MARK: Push
public function pushScreenWithId(id: String, screen: StackScreenNavigatorItem, transition: Function, completion: Function): void {
addScreenWithId(id, screen, function(): void {
_navigator.pushScreen(id, screen, getPushTransition(id, transition));
if (completion != null) {
completion();
}
});
}
// MARK: Pop
public function popScreenWithId(id: String, transition: Function, completion: Function): void {
waitForTransitionCompleteIfNeeded(function(): void {
trackScreenTransitionComplete(function(): void {
removeScreenWithId(id, completion);
});
_navigator.popScreen(getPopTransition(id, transition));
});
}
public function popToRootScreenWithIds(ids: Vector.<String>, transition: Function, completion: Function): void {
waitForTransitionCompleteIfNeeded(function(): void {
trackScreenTransitionComplete(function(): void {
doRemoveScreensWithIds(ids, completion);
});
_navigator.popToRootScreen(getPopToRootTransition(transition));
});
}
// MARK: Root
public function setRootScreenWithId(id: String, screen: StackScreenNavigatorItem, completion: Function): void {
addScreenWithId(id, screen, function(): void {
_navigator.rootScreenID = id;
if (completion != null) {
completion();
}
});
}
// MARK: Replace
public function replaceScreenWithId(id: String, screen: StackScreenNavigatorItem, transition: Function, completion: Function): void {
addScreenWithId(id, screen, function(): void {
trackScreenTransitionComplete(completion);
_navigator.replaceScreen(id, transition);
});
}
// MARK: Transitions
protected function getPushTransition(id: String, transition: Function): Function {
if (transition == null) {
return null;
}
var screen: StackScreenNavigatorItem = _navigator.getScreen(id);
return screen.pushTransition || transition;
}
protected function getPopTransition(id: String, transition: Function): Function {
if (transition == null) {
return null;
}
var screen: StackScreenNavigatorItem = _navigator.getScreen(id);
return screen.popTransition || transition;
}
private function getPopToRootTransition(transition: Function): Function {
return getPopTransition(_navigator.rootScreenID, transition);
}
// MARK: Utils
private function trackScreenTransitionStart(handler: Function): void {
_navigator.addEventListener(FeathersEventType.TRANSITION_START, function(event: Event): void {
_navigator.removeEventListener(FeathersEventType.TRANSITION_START, arguments.callee);
if (handler != null) {
handler();
}
});
}
private function trackScreenTransitionComplete(handler: Function): void {
_navigator.addEventListener(FeathersEventType.TRANSITION_COMPLETE, function(event: Event): void {
_navigator.removeEventListener(FeathersEventType.TRANSITION_COMPLETE, arguments.callee);
if (handler != null) {
handler();
}
});
}
private function waitForTransitionCompleteIfNeeded(handler: Function): void {
if (_navigator.isTransitionActive) {
trackScreenTransitionComplete(handler);
} else {
if (handler != null) {
handler();
}
}
}
}
}
|
package vo
{
import common.debug.Debug;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import manager.MissionManager;
public class UserDeckData extends BaseData
{
private var _userDecks:Dictionary;
private var _deckCount:int = 0;
private var _shipsArr:Array;
private var _shipsDic:Dictionary;
private var _missionManager:MissionManager;
private var _combinedType:int = 0;
private var _combinedDeck:Array;
private var _autoUnCombinedDeck:int = 0;
public function UserDeckData()
{
_missionManager = new MissionManager();
super();
_shipsArr = [];
_combinedDeck = [];
}
public function get autoUnCombinedDeck() : int
{
return _autoUnCombinedDeck;
}
public function get deckCount() : int
{
return _deckCount;
}
public function get shipCount() : int
{
return _shipsArr.length;
}
public function get vacancyCount() : int
{
var _loc1_:int = DataFacade.getUserData().getMaxShipCount();
return _loc1_ - shipCount;
}
public function get missionManager() : MissionManager
{
return _missionManager;
}
public function setDeckData(param1:Array) : void
{
var _loc3_:int = 0;
var _loc2_:* = null;
_userDecks = new Dictionary();
_loc3_ = 0;
while(_loc3_ < param1.length)
{
_loc2_ = param1[_loc3_];
if(_loc2_ != null)
{
_userDecks[_loc2_.api_id] = _loc2_;
}
_loc3_++;
}
_deckCount = param1.length;
_missionManager.update(param1);
}
public function updateDeckData(param1:Array) : void
{
var _loc5_:int = 0;
var _loc3_:* = null;
_loc5_ = 0;
while(_loc5_ < param1.length)
{
_loc3_ = param1[_loc5_];
if(_loc3_ != null)
{
_userDecks[_loc3_.api_id] = _loc3_;
}
_loc5_++;
}
var _loc4_:Array = [];
var _loc7_:int = 0;
var _loc6_:* = _userDecks;
for each(var _loc2_ in _userDecks)
{
_loc4_.push(_loc2_);
}
_loc4_.sortOn("api_id");
_missionManager.update(_loc4_);
}
public function setShipData(param1:Array) : void
{
var _loc3_:int = 0;
var _loc2_:* = null;
_shipsDic = new Dictionary();
_shipsArr = param1;
_loc3_ = 0;
while(_loc3_ < param1.length)
{
if(param1[_loc3_] != null)
{
_loc2_ = new UserShipData(param1[_loc3_]);
_shipsDic[_loc2_.getShipID()] = _loc2_;
}
_loc3_++;
}
}
public function updateShipData(param1:Array) : void
{
var _loc6_:int = 0;
var _loc4_:* = null;
var _loc2_:int = 0;
var _loc5_:int = 0;
var _loc3_:Vector.<int> = new Vector.<int>();
_loc6_ = 0;
while(_loc6_ < param1.length)
{
if(param1[_loc6_] != null)
{
_loc4_ = new UserShipData(param1[_loc6_]);
_shipsDic[_loc4_.getShipID()] = _loc4_;
_loc3_.push(_loc4_.getShipID());
}
_loc6_++;
}
_loc6_ = 0;
while(_loc6_ < _shipsArr.length)
{
_loc5_ = _shipsArr[_loc6_]["api_id"];
_loc2_ = _loc3_.indexOf(_loc5_);
if(_loc2_ >= 0)
{
_shipsArr[_loc6_] = param1.splice(_loc2_,1)[0];
_loc3_.splice(_loc2_,1);
}
_loc6_++;
}
if(param1.length > 0)
{
_shipsArr.push(param1);
}
}
public function setShipDataOneShip(param1:Object) : void
{
var _loc3_:int = 0;
var _loc2_:UserShipData = new UserShipData(param1);
_shipsDic[_loc2_.getShipID()] = _loc2_;
_loc3_ = 0;
while(_loc3_ < _shipsArr.length)
{
if(_shipsArr[_loc3_]["api_id"] == _loc2_.getShipID())
{
_shipsArr[_loc3_] = param1;
}
_loc3_++;
}
}
public function setCombinedFlag(param1:int) : void
{
_combinedType = param1;
_autoUnCombinedDeck = 0;
if(param1 == 1)
{
Debug.log("====連合艦隊(機動部隊)====");
_combinedDeck = [1,2];
}
else if(param1 == 2)
{
Debug.log("====連合艦隊(水上部隊)====");
_combinedDeck = [1,2];
}
else if(param1 == 3)
{
Debug.log("====連合艦隊(輸送部隊)====");
_combinedDeck = [1,2];
}
else
{
Debug.log("====連合艦隊ではない====");
_combinedDeck = [];
if(param1 < 0)
{
_autoUnCombinedDeck = param1 * -1;
}
}
}
public function getCombinedType(param1:int = 1) : int
{
if(_combinedDeck.indexOf(param1) != -1)
{
return _combinedType;
}
return 0;
}
public function getCombinedMainDeckID(param1:int) : int
{
var _loc2_:int = _combinedDeck.indexOf(param1);
if(_loc2_ == -1)
{
return -1;
}
if(_loc2_ % 2 == 1)
{
return _combinedDeck[_loc2_ - 1];
}
return _combinedDeck[_loc2_];
}
public function getCombinedSubDeckID(param1:int) : int
{
var _loc2_:int = _combinedDeck.indexOf(param1);
if(_loc2_ == -1)
{
return -1;
}
if(_loc2_ % 2 == 0)
{
return _combinedDeck[_loc2_ + 1];
}
return _combinedDeck[_loc2_];
}
public function isExistDeck(param1:int) : Boolean
{
return _userDecks && _userDecks.hasOwnProperty(param1);
}
public function getName(param1:int) : String
{
if(isExistDeck(param1))
{
return _userDecks[param1]["api_name"];
}
Debug.log("UserDeckData::getName. deckID=" + param1 + " is no data");
return "";
}
public function getMissionList() : Array
{
var _loc3_:int = 0;
var _loc1_:int = 0;
var _loc2_:Array = [];
_loc3_ = 0;
while(_loc3_ < _deckCount)
{
_loc1_ = missionManager.getMissionID(_loc3_ + 1);
_loc2_.push(_loc1_);
_loc3_++;
}
return _loc2_;
}
public function getNameID(param1:int) : String
{
if(isExistDeck(param1))
{
return _userDecks[param1]["api_name_id"];
}
Debug.log("UserDeckData::getNameID. deckID=" + param1 + " is no data");
return "";
}
public function getAllShip() : Vector.<UserShipData>
{
var _loc2_:Vector.<UserShipData> = new Vector.<UserShipData>();
var _loc4_:int = 0;
var _loc3_:* = _shipsDic;
for each(var _loc1_ in _shipsDic)
{
_loc2_.push(_loc1_);
}
return _loc2_;
}
public function getShipData(param1:int) : UserShipData
{
if(_shipsDic.hasOwnProperty(param1))
{
return _shipsDic[param1];
}
return null;
}
public function getCharaIDList() : Array
{
var _loc3_:int = 0;
var _loc6_:* = null;
var _loc5_:int = 0;
var _loc1_:* = null;
var _loc4_:Array = [];
var _loc8_:int = 0;
var _loc7_:* = _userDecks;
for(var _loc2_ in _userDecks)
{
_loc3_ = parseInt(_loc2_);
_loc6_ = _getShipIDs(_loc3_);
_loc5_ = 0;
while(_loc5_ < _loc6_.length)
{
_loc1_ = getShipData(_loc6_[_loc5_]);
if(_loc1_ != null)
{
_loc4_.push(_loc1_.getCharaID());
}
_loc5_++;
}
}
return _loc4_;
}
public function getFlagShipData(param1:int) : UserShipData
{
var _loc3_:int = 0;
var _loc2_:Array = _getShipIDs(param1);
if(_loc2_.length > 0)
{
_loc3_ = _loc2_[0];
return getShipData(_loc3_);
}
return null;
}
public function getShipDataInDeck(param1:int) : Array
{
var _loc5_:int = 0;
var _loc2_:* = null;
var _loc4_:Array = _getShipIDs(param1);
var _loc3_:Array = [];
_loc5_ = 0;
while(_loc5_ < _loc4_.length)
{
_loc2_ = getShipData(_loc4_[_loc5_]);
_loc3_.push(_loc2_);
_loc5_++;
}
while(_loc3_.length < 6)
{
_loc3_.push(null);
}
return _loc3_;
}
public function getShipDataInCombinedDeck(param1:int) : Array
{
var _loc3_:int = getCombinedMainDeckID(param1);
if(_loc3_ == -1)
{
return getShipDataInDeck(param1);
}
var _loc2_:int = getCombinedSubDeckID(param1);
if(_loc2_ == -1)
{
return getShipDataInDeck(param1);
}
var _loc5_:Array = getShipDataInDeck(_loc3_);
var _loc4_:Array = getShipDataInDeck(_loc2_);
return _loc5_.concat(_loc4_);
}
public function getShipTypeCountInDeck(param1:int, param2:int) : int
{
var _loc7_:int = 0;
var _loc5_:* = null;
var _loc3_:int = 0;
var _loc4_:int = 0;
var _loc6_:Array = getShipDataInDeck(param1);
_loc7_ = 0;
while(_loc7_ < _loc6_.length)
{
if(_loc6_[_loc7_] != null)
{
_loc5_ = _loc6_[_loc7_];
_loc3_ = _loc5_.getShipType();
if(_loc3_ == param2)
{
_loc4_++;
}
}
_loc7_++;
}
return _loc4_;
}
function __setDeck(param1:int, param2:Array) : void
{
_userDecks[param1]["api_ship"] = param2;
}
function __getDeck(param1:int) : Array
{
return _userDecks[param1]["api_ship"];
}
public function getShipPos(param1:int, param2:int) : int
{
var _loc5_:int = 0;
var _loc3_:* = -1;
var _loc4_:Array = _userDecks[param1]["api_ship"];
_loc5_ = 0;
while(_loc5_ < 6)
{
if(param2 == _loc4_[_loc5_])
{
_loc3_ = _loc5_;
break;
}
_loc5_++;
}
return _loc3_;
}
public function getShipCountInDeck(param1:int, param2:Boolean = false) : int
{
var _loc7_:int = 0;
var _loc5_:* = null;
var _loc4_:int = 0;
var _loc6_:Array = getShipDataInDeck(param1);
var _loc3_:int = 0;
_loc7_ = 0;
while(_loc7_ < _loc6_.length)
{
_loc5_ = _loc6_[_loc7_] as UserShipData;
if(_loc5_ != null)
{
if(param2)
{
_loc4_ = _loc5_.getCondition();
if(_loc4_ != 0)
{
_loc3_++;
}
}
else
{
_loc3_++;
}
}
_loc7_++;
}
return _loc3_;
}
public function getDeckDataForBattle() : Object
{
var _loc5_:int = 0;
var _loc1_:* = null;
var _loc3_:* = null;
var _loc2_:Object = {
"decks":[],
"ships":getShipDataArrayForBattleALL()
};
var _loc7_:int = 0;
var _loc6_:* = _userDecks;
for(var _loc4_ in _userDecks)
{
_loc5_ = parseInt(_loc4_);
_loc1_ = _userDecks[_loc5_];
_loc3_ = new ByteArray();
_loc3_.writeObject(_loc1_);
_loc3_.position = 0;
_loc2_["decks"][_loc5_] = _loc3_.readObject();
}
return _loc2_;
}
public function getShipDataArrayForBattleALL() : Array
{
var _loc2_:int = 0;
var _loc3_:Array = [];
_loc2_ = 1;
while(_loc2_ <= deckCount)
{
_loc3_ = _loc3_.concat(getShipDataArrayForBattle(_loc2_));
_loc2_++;
}
var _loc1_:Array = [];
_loc2_ = 0;
while(_loc2_ < _loc3_.length)
{
if(_loc3_[_loc2_] != null)
{
_loc1_.push(_loc3_[_loc2_]);
}
_loc2_++;
}
return _loc1_;
}
public function getShipDataArrayForBattle(param1:int) : Array
{
var _loc6_:int = 0;
var _loc2_:* = null;
var _loc4_:* = null;
var _loc3_:Array = [];
var _loc5_:Array = getShipDataInDeck(param1);
_loc6_ = 0;
while(_loc6_ < _loc5_.length)
{
_loc2_ = _loc5_[_loc6_] as UserShipData;
if(_loc2_ != null)
{
_loc4_ = _loc2_.cloneOriginalObject();
_loc3_.push(_loc4_);
}
else
{
_loc3_.push(null);
}
_loc6_++;
}
return _loc3_;
}
public function getShipDataFromAllDeckForBattle() : Dictionary
{
var _loc3_:int = 0;
var _loc1_:Dictionary = new Dictionary();
var _loc5_:int = 0;
var _loc4_:* = _userDecks;
for(var _loc2_ in _userDecks)
{
_loc3_ = parseInt(_loc2_);
_loc1_[_loc3_] = getShipDataArrayForBattle(_loc3_);
}
return _loc1_;
}
public function getSortedShipList(param1:Boolean, param2:Boolean, param3:int, param4:Boolean = false, param5:Array = null) : Vector.<UserShipData>
{
var _loc11_:int = 0;
var _loc6_:* = 0;
var _loc9_:* = null;
var _loc7_:* = null;
var _loc10_:Boolean = false;
var _loc14_:Vector.<UserShipData> = new Vector.<UserShipData>();
var _loc12_:Array = _getSortedIndexList(param3,param4);
var _loc13_:Array = [];
var _loc8_:Array = [];
_loc11_ = 1;
while(_loc11_ <= 4)
{
if(isExistDeck(_loc11_))
{
_loc13_.push.apply(null,_getShipIDs(_loc11_));
}
_loc11_++;
}
_loc11_ = 0;
while(_loc11_ < _loc12_.length)
{
_loc6_ = uint(_loc12_[_loc11_]);
_loc9_ = _shipsArr[_loc6_];
_loc7_ = new UserShipData(_loc9_);
_loc10_ = false;
if(param1 && _loc13_.indexOf(_loc7_.getShipID()) != -1)
{
_loc10_ = true;
}
if(param2 && (_loc7_.isLocked() || _loc7_.isEquipLockedItem()))
{
_loc10_ = true;
}
if(param5 != null && param5.indexOf(_loc7_.getShipID()) != -1)
{
_loc10_ = true;
}
if(!_loc10_)
{
_loc14_.push(_loc7_);
}
_loc11_++;
}
return _loc14_;
}
private function _getDeckData(param1:int) : Object
{
if(isExistDeck(param1))
{
return _userDecks[param1];
}
return null;
}
private function _getShipIDs(param1:int) : Array
{
var _loc2_:Object = _getDeckData(param1);
if(_loc2_)
{
return _getArray(_loc2_,"api_ship",[]).concat();
}
Debug.log("UserDeckData::getShipIDs. deckID=" + param1 + " is no data.");
return [];
}
private function _getSortedIndexList(param1:int, param2:Boolean = false) : Array
{
var _loc3_:* = null;
var _loc4_:* = null;
switch(int(param1))
{
case 0:
_loc3_ = ["api_lv","api_sortno","api_id"];
if(param2)
{
_loc4_ = [16 | 2 | 8,16,16];
}
else
{
_loc4_ = [16 | 8,16 | 2,16 | 2];
}
break;
case 1:
_loc3_ = ["api_stype","api_sortno","api_lv","api_id"];
if(param2)
{
_loc4_ = [16 | 2 | 8,16,16 | 2,16];
}
else
{
_loc4_ = [16 | 8,16 | 2,16,16 | 2];
}
break;
default:
_loc3_ = ["api_id"];
if(param2)
{
_loc4_ = [16 | 2 | 8];
break;
}
_loc4_ = [16 | 8];
break;
case 3:
_loc3_ = ["hp_rate","api_sortno","api_id"];
if(param2)
{
_loc4_ = [16 | 8,16,16];
}
else
{
_loc4_ = [16 | 2 | 8,16 | 2,16 | 2];
}
}
return _shipsArr.sortOn(_loc3_,_loc4_);
}
function __addShip(param1:Object) : void
{
var _loc2_:UserShipData = new UserShipData(param1);
_shipsDic[_loc2_.getShipID()] = _loc2_;
_shipsArr.push(param1);
}
function __removeShip(param1:UserShipData) : void
{
var _loc2_:int = 0;
if(param1.isLocked() || param1.isEquipLockedItem() || param1.isInDeck() >= 0)
{
return;
}
_loc2_ = 0;
while(_loc2_ < _shipsArr.length)
{
if(_shipsArr[_loc2_]["api_id"] == param1.getShipID())
{
_shipsArr.splice(_loc2_,1);
break;
}
_loc2_++;
}
if(_shipsDic.hasOwnProperty(param1.getShipID()))
{
delete _shipsDic[param1.getShipID()];
}
}
function __setDeckName(param1:int, param2:String) : void
{
if(isExistDeck(param1))
{
_userDecks[param1]["api_name"] = param2;
}
}
}
}
|
package serverProto.ninjaexam
{
import com.netease.protobuf.Message;
import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_UINT32;
import com.netease.protobuf.WireType;
import com.netease.protobuf.WritingBuffer;
import com.netease.protobuf.WriteUtils;
import flash.utils.IDataInput;
import com.netease.protobuf.ReadUtils;
import flash.errors.IOError;
public final class ProtoNinjaExamInfo extends Message
{
public static const MAX_STAGE:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.ninjaexam.ProtoNinjaExamInfo.max_stage","maxStage",1 << 3 | WireType.VARINT);
public static const CURR_STAGE:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.ninjaexam.ProtoNinjaExamInfo.curr_stage","currStage",2 << 3 | WireType.VARINT);
public static const TOTAL_EXP:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.ninjaexam.ProtoNinjaExamInfo.total_exp","totalExp",3 << 3 | WireType.VARINT);
public static const FREE_COUNT:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.ninjaexam.ProtoNinjaExamInfo.free_count","freeCount",4 << 3 | WireType.VARINT);
public static const RAIDS_TIME:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.ninjaexam.ProtoNinjaExamInfo.raids_time","raidsTime",5 << 3 | WireType.VARINT);
public static const MY_RANK:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.ninjaexam.ProtoNinjaExamInfo.my_rank","myRank",6 << 3 | WireType.VARINT);
public static const TOTAL_MONEY:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.ninjaexam.ProtoNinjaExamInfo.total_money","totalMoney",7 << 3 | WireType.VARINT);
public var maxStage:uint;
public var currStage:uint;
public var totalExp:uint;
public var freeCount:uint;
private var raids_time$field:uint;
private var hasField$0:uint = 0;
private var my_rank$field:uint;
private var total_money$field:uint;
public function ProtoNinjaExamInfo()
{
super();
}
public function clearRaidsTime() : void
{
this.hasField$0 = this.hasField$0 & 4.294967294E9;
this.raids_time$field = new uint();
}
public function get hasRaidsTime() : Boolean
{
return (this.hasField$0 & 1) != 0;
}
public function set raidsTime(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 1;
this.raids_time$field = param1;
}
public function get raidsTime() : uint
{
return this.raids_time$field;
}
public function clearMyRank() : void
{
this.hasField$0 = this.hasField$0 & 4.294967293E9;
this.my_rank$field = new uint();
}
public function get hasMyRank() : Boolean
{
return (this.hasField$0 & 2) != 0;
}
public function set myRank(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 2;
this.my_rank$field = param1;
}
public function get myRank() : uint
{
return this.my_rank$field;
}
public function clearTotalMoney() : void
{
this.hasField$0 = this.hasField$0 & 4.294967291E9;
this.total_money$field = new uint();
}
public function get hasTotalMoney() : Boolean
{
return (this.hasField$0 & 4) != 0;
}
public function set totalMoney(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 4;
this.total_money$field = param1;
}
public function get totalMoney() : uint
{
return this.total_money$field;
}
override final function writeToBuffer(param1:WritingBuffer) : void
{
var _loc2_:* = undefined;
WriteUtils.writeTag(param1,WireType.VARINT,1);
WriteUtils.write$TYPE_UINT32(param1,this.maxStage);
WriteUtils.writeTag(param1,WireType.VARINT,2);
WriteUtils.write$TYPE_UINT32(param1,this.currStage);
WriteUtils.writeTag(param1,WireType.VARINT,3);
WriteUtils.write$TYPE_UINT32(param1,this.totalExp);
WriteUtils.writeTag(param1,WireType.VARINT,4);
WriteUtils.write$TYPE_UINT32(param1,this.freeCount);
if(this.hasRaidsTime)
{
WriteUtils.writeTag(param1,WireType.VARINT,5);
WriteUtils.write$TYPE_UINT32(param1,this.raids_time$field);
}
if(this.hasMyRank)
{
WriteUtils.writeTag(param1,WireType.VARINT,6);
WriteUtils.write$TYPE_UINT32(param1,this.my_rank$field);
}
if(this.hasTotalMoney)
{
WriteUtils.writeTag(param1,WireType.VARINT,7);
WriteUtils.write$TYPE_UINT32(param1,this.total_money$field);
}
for(_loc2_ in this)
{
super.writeUnknown(param1,_loc2_);
}
}
override final function readFromSlice(param1:IDataInput, param2:uint) : void
{
/*
* Decompilation error
* Code may be obfuscated
* Tip: You can try enabling "Automatic deobfuscation" in Settings
* Error type: IndexOutOfBoundsException (Index: 7, Size: 7)
*/
throw new flash.errors.IllegalOperationError("Not decompiled due to error");
}
}
}
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
function rightShift() {
var x:int = 10;
print(x >> 4);
}
rightShift();
|
package test {
public class Issue2701_1 {}
}
class A {
public function get foo():Number {
return 0;
}
public function set foo(value:Number):void {
return 0;
}
}
class B extends A {
override public function get foo():Number {
return super.foo;
}
override public function set foo(value:Number):void {
super.foo = value;
}
} |
package sk.yoz.ycanvas.map.demo
{
import starling.textures.Texture;
public class Assets
{
[Embed(source="/markers/green.png")]
private static const MARKER_GREEN_CLASS:Class;
private static var _MARKER_GREEN_TEXTURE:Texture;
public static function get MARKER_GREEN_TEXTURE():Texture
{
if(!_MARKER_GREEN_TEXTURE)
_MARKER_GREEN_TEXTURE = Texture.fromBitmap(new MARKER_GREEN_CLASS);
return _MARKER_GREEN_TEXTURE;
}
}
} |
/*
* Temple Library for ActionScript 3.0
* Copyright © MediaMonks B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by MediaMonks B.V.
* 4. Neither the name of MediaMonks B.V. 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 MEDIAMONKS B.V. ''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 MEDIAMONKS B.V. 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.
*
*
* Note: This license does not apply to 3rd party classes inside the Temple
* repository with their own license!
*/
package temple.facebook.data.vo
{
import temple.facebook.data.enum.FacebookObjectType;
import temple.facebook.data.facebook;
import temple.facebook.data.enum.FacebookConnection;
import temple.facebook.service.IFacebookService;
/**
* @private
*
* @author Thijs Broerse
*/
public class FacebookFriendListData extends FacebookObjectData implements IFacebookFriendListData
{
public static const FIELDS:FacebookFriendListFields = new FacebookFriendListFields();
public static const CONNECTIONS:Vector.<String> = Vector.<String>([FacebookConnection.MEMBERS]);
/**
* Used by Indexer
* @see temple.data.index.Indexer#INDEX_CLASS
*/
public static function get indexClass():Class
{
return IFacebookFriendListData;
}
public static function register(facebook:IFacebookService):void
{
facebook.registerVO(FacebookConnection.FRIENDLISTS, FacebookFriendListData);
}
facebook var list_type:String;
facebook var members:Vector.<IFacebookUserData>;
public function FacebookFriendListData(service:IFacebookService)
{
super(service, FacebookObjectType.FRIENDLIST, FacebookFriendListData.CONNECTIONS);
toStringProps.push("listType");
}
/**
* @inheritDoc
*/
override public function get fields():IFacebookFields
{
return FacebookFriendListData.FIELDS;
}
/**
* @inheritDoc
*/
public function get listType():String
{
return facebook::list_type;
}
/**
* @inheritDoc
*/
public function get members():Vector.<IFacebookUserData>
{
return facebook::members;
}
}
}
|
package kabam.rotmg.messaging.impl {
import com.company.assembleegameclient.util.TimeUtil;
import flash.display.Sprite;
import flash.events.Event;
import flash.filters.DropShadowFilter;
import kabam.rotmg.text.view.TextFieldDisplayConcrete;
import kabam.rotmg.text.view.stringBuilder.LineBuilder;
public class JitterWatcher extends Sprite {
private static const lineBuilder:LineBuilder = new LineBuilder();
private var text_:TextFieldDisplayConcrete = null;
private var lastRecord_:int = -1;
private var ticks_:Vector.<int>;
private var sum_:int;
public function JitterWatcher() {
ticks_ = new Vector.<int>();
super();
this.text_ = new TextFieldDisplayConcrete().setSize(14).setColor(16777215);
this.text_.setAutoSize("left");
this.text_.filters = [new DropShadowFilter(0,0,0)];
addChild(this.text_);
addEventListener("addedToStage",this.onAddedToStage);
addEventListener("removedFromStage",this.onRemovedFromStage);
}
public function record() : void {
var _loc3_:int = 0;
var _loc2_:int = TimeUtil.getTrueTime();
if(this.lastRecord_ == -1) {
this.lastRecord_ = _loc2_;
return;
}
var _loc1_:int = _loc2_ - this.lastRecord_;
this.ticks_.push(_loc1_);
this.sum_ = this.sum_ + _loc1_;
if(this.ticks_.length > 50) {
_loc3_ = this.ticks_.shift();
this.sum_ = this.sum_ - _loc3_;
}
this.lastRecord_ = _loc2_;
}
private function jitter() : Number {
var _loc2_:int = 0;
var _loc5_:int = this.ticks_.length;
if(_loc5_ == 0) {
return 0;
}
var _loc1_:Number = this.sum_ / _loc5_;
var _loc3_:* = 0;
var _loc6_:* = this.ticks_;
var _loc8_:int = 0;
var _loc7_:* = this.ticks_;
for each(_loc2_ in this.ticks_) {
_loc3_ = _loc3_ + (_loc2_ - _loc1_) * (_loc2_ - _loc1_);
}
return int(Math.sqrt(_loc3_ / _loc5_));
}
private function onAddedToStage(param1:Event) : void {
stage.addEventListener("enterFrame",this.onEnterFrame);
}
private function onRemovedFromStage(param1:Event) : void {
stage.removeEventListener("enterFrame",this.onEnterFrame);
}
private function onEnterFrame(param1:Event) : void {
this.text_.setStringBuilder(lineBuilder.setParams("JitterWatcher.desc",{"jitter":this.jitter()}));
}
}
}
|
/**
* User: booster
* Date: 19/11/14
* Time: 16:09
*/
package stork.nape.debug {
import flash.display.DisplayObject;
import flash.events.MouseEvent;
import flash.geom.Point;
import nape.constraint.PivotJoint;
import nape.geom.Vec2;
import nape.phys.Body;
import nape.phys.BodyList;
import nape.space.Space;
import stork.core.Node;
import stork.event.nape.NapeSpaceEvent;
import stork.nape.NapeSpaceNode;
public class NapeDebugDragNode extends Node {
private var _handJoint:PivotJoint;
private var _handDragX:Number;
private var _handDragY:Number;
private var _mouseDragTarget:DisplayObject;
private var _spaceNode:NapeSpaceNode;
private var _space:Space;
public function NapeDebugDragNode(name:String = "NapeDebugDrag") {
super(name);
}
// TODO: change this to allow passing the referenced path as a parameter
[LocalReference("@NapeSpaceNode")]
public function get spaceNode():NapeSpaceNode { return _spaceNode; }
public function set spaceNode(value:NapeSpaceNode):void {
if(_spaceNode != null) {
_space = null;
_handJoint.space = null;
_handJoint.body1 = null;
_handJoint.body2 = null;
_handJoint = null;
_spaceNode.removeEventListener(NapeSpaceEvent.PRE_UPDATE, onPreUpdate);
}
_spaceNode = value;
if(_spaceNode != null) {
_space = _spaceNode.space;
_handJoint = new PivotJoint(_space.world, null, Vec2.weak(), Vec2.weak());
_handJoint.space = _space;
_handJoint.active = false;
_handJoint.stiff = false;
_spaceNode.addEventListener(NapeSpaceEvent.PRE_UPDATE, onPreUpdate);
}
}
public function get mouseDragTarget():DisplayObject { return _mouseDragTarget; }
public function set mouseDragTarget(value:DisplayObject):void {
if(_mouseDragTarget != null) {
_mouseDragTarget.stage.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
_mouseDragTarget.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
_mouseDragTarget.stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
_mouseDragTarget = value;
if(_mouseDragTarget != null) {
_mouseDragTarget.stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
_mouseDragTarget.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
_mouseDragTarget.stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
}
/* TODO: implement
public function enableTouchDrag(eventTarget:starling.display.DisplayObject):void {
}
*/
private function onMouseDown(event:MouseEvent):void { beginDrag(event.stageX, event.stageY); }
private function onMouseUp(event:MouseEvent):void { finishDrag(); }
private function onMouseMove(event:MouseEvent):void {
if(! _handJoint.active)
return;
// TODO: use cached Points for better GC performance
var local:Point = _mouseDragTarget.globalToLocal(new Point(event.stageX, event.stageY));
_handDragX = local.x;
_handDragY = local.y;
}
private function beginDrag(x:Number, y:Number):void {
// TODO: use cached Points for better GC performance
var local:Point = _mouseDragTarget.globalToLocal(new Point(x, y));
// Allocate a Vec2 from object pool.
var location:Vec2 = Vec2.get(local.x, local.y);
// Determine the set of Body's which are intersecting mouse point.
// And search for any 'dynamic' type Body to begin dragging.
var bodies:BodyList = _space.bodiesUnderPoint(location);
var count:int = bodies.length;
for (var i:int = 0; i < count; i++) {
var body:Body = bodies.at(i);
if (! body.isDynamic())
continue;
// Configure hand joint to drag this body.
// We initialise the anchor point on this body so that
// constraint is satisfied.
//
// The second argument of worldPointToLocal means we get back
// a 'weak' Vec2 which will be automatically sent back to object
// pool when setting the handJoint's anchor2 property.
_handJoint.body2 = body;
_handJoint.anchor2.set(body.worldPointToLocal(location, true));
// Enable hand joint!
_handJoint.active = true;
_handDragX = local.x;
_handDragY = local.y;
break;
}
location.dispose();
}
private function finishDrag():void {
_handJoint.active = false;
}
private function onPreUpdate(event:NapeSpaceEvent):void {
if(_handJoint.active == false)
return;
_handJoint.anchor1.setxy(_handDragX, _handDragY);
}
}
}
|
package com.rockmatch.resourcemanager.events
{
import com.rockmatch.core.base.events.ContextEvent;
/**
*
* @author dkoloskov
*
*/
public class ResourceManagerEvent extends ContextEvent
{
static public const LOAD:String = "LOAD";
static public const PROGRESS:String = "PROGRESS";
static public const LOAD_COMPLETED:String = "LOAD_COMPLETED";
//==============================================================================
//{region PUBLIC METHODS
public function ResourceManagerEvent(type:String, body:* = null)
{
super(type, body);
}
//} endregion PUBLIC METHODS ===================================================
}
} |
package
{
import flash.display.DisplayObject;
import flash.display.Stage;
import view.Graphics;
import view.Image;
import view.Text;
public class Command
{
private var _input:CommandArray;
private var _pool:Object = {};
private var _stage:Stage;
public function Command(stage:Stage)
{
_stage = stage;
}
private function loadImage():void{
var src:String = _input.readString();
ImageLoader.jsLoad(src);
}
public function parse(data:String):void
{
if(!_input || _input.position >= _input.length){
_input = new CommandArray(data);
}
else{
_input.concat(data);
}
while(_input.position < _input.length){
var cmd:String = _input.readString();
this[cmd]();
}
}
public function resize():void
{
var w:int = _input.readInt();
var h:int = _input.readInt();
_stage.stageWidth = w;
_stage.stageHeight = h;
}
public function removeChild():void{
var pid:String = _input.readString();
var cid:String = _input.readString();
_pool[pid].remove(_pool[cid]);
}
public function addChild():void{
var pid:String = _input.readString();
var cid:String = _input.readString();
var index:int = _input.readInt();
_pool[pid].add(_pool[cid]);
_pool[cid].depth = index;
}
public function stageRemoveChild():void
{
var id:String = _input.readString();
_stage.removeChild(_pool[id]);
}
public function stageAddChild():void
{
var id:String = _input.readString();
_stage.addChild(_pool[id]);
}
public function create():void
{
var id:String = _input.readString();
var type:String = _input.readString();
var obj:DisplayObject;
switch(type){
case "Text":
obj = new Text(id);
break;
case "Graphics":
obj = new Graphics(id);
break;
default:
obj = new Image(id);
break;
}
_pool[id] = obj;
}
public function setImage():void
{
var id:String = _input.readString();
var src:String = _input.readString();
_pool[id].src = src;
}
public function setProp():void
{
var id:String = _input.readString()
var prop:String = _input.readString();
var value:* = _input.readValue();
if(value === "false" || value === "true"){
value = value === "true";
}
_pool[id][prop] = value;
}
public function setFps():void
{
var fps:Number = _input.readFloat();
_stage.frameRate = fps;
}
public function audio():void
{
Audio.executeCommand(_input);
}
public function graphicsDraw():void
{
var fid:String = _input.readString();
var commands:String = _input.readString();
_pool[fid].draw(commands);
}
public function release():void
{
var fid:String = _input.readString();
if(_pool[fid]){
if(_pool[fid].parent){
_pool[fid].parent.removeChild(_pool[fid]);
}
delete _pool[fid];
}
}
}
} |
/*
* Temple Library for ActionScript 3.0
* Copyright © MediaMonks B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by MediaMonks B.V.
* 4. Neither the name of MediaMonks B.V. 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 MEDIAMONKS B.V. ''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 MEDIAMONKS B.V. 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.
*
*
* Note: This license does not apply to 3rd party classes inside the Temple
* repository with their own license!
*/
package temple.ui.states.select
{
import temple.ui.states.BaseTimelineState;
/**
* Uses a timeline animation to display or hide the select state of his parent.
*
* @author Thijs Broerse
*/
public class SelectTimelineState extends BaseTimelineState implements ISelectState
{
public function SelectTimelineState()
{
super();
}
}
}
|
/*
Copyright (c) 2016 Bigpoint GmbH
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
import flash.events.Event;
import mx.controls.Alert;
import mx.events.CloseEvent;
import spark.events.IndexChangeEvent;
import mx.managers.PopUpManager;
public function onCreationComplete(e:Event):void
{
var persistentData:SharedObject = SharedObject.getLocal("persistentData");
if (persistentData)
{
drpLogging.selectedIndex = persistentData.data.IrisBuild_LoggerMaximumLevel;
}
}
public function onClose(e:CloseEvent):void
{
PopUpManager.removePopUp(this);
}
public function onBtnSaveClicked(e:Event):void
{
saveSettings();
PopUpManager.removePopUp(this);
}
public function onBtnCancelClicked(e:Event):void
{
PopUpManager.removePopUp(this);
}
public function onDrpLoggingChange(e:IndexChangeEvent):void
{
var persistentData:SharedObject = SharedObject.getLocal("persistentData");
if (!persistentData)
{
return;
}
persistentData.data.IrisBuild_LoggerMaximumLevel = e.currentTarget.selectedIndex;
} |
package websocket.hurlant.crypto.symmetric
{
import flash.utils.ByteArray;
public class PKCS5 implements IPad
{
private var blockSize:uint;
public function PKCS5(param1:uint = 0)
{
super();
this.blockSize = param1;
}
public function pad(param1:ByteArray) : void
{
var _loc3_:* = 0;
var _loc2_:uint = blockSize - param1.length % blockSize;
_loc3_ = uint(0);
while(_loc3_ < _loc2_)
{
param1[param1.length] = _loc2_;
_loc3_++;
}
}
public function unpad(param1:ByteArray) : void
{
var _loc4_:* = 0;
var _loc3_:* = 0;
var _loc2_:uint = param1.length % blockSize;
if(_loc2_ != 0)
{
throw new Error("PKCS#5::unpad: ByteArray.length isn\'t a multiple of the blockSize");
}
_loc2_ = param1[param1.length - 1];
_loc4_ = _loc2_;
while(_loc4_ > 0)
{
_loc3_ = uint(param1[param1.length - 1]);
param1.length--;
if(_loc2_ != _loc3_)
{
throw new Error("PKCS#5:unpad: Invalid padding value. expected [" + _loc2_ + "], found [" + _loc3_ + "]");
}
_loc4_--;
}
}
public function setBlockSize(param1:uint) : void
{
blockSize = param1;
}
}
}
|
package components.sequencer.events
{
public class ProjectEvent
{
public static const START_UPDATE : String = 'START_UPDATE';
public static const END_UPDATE : String = 'END_UPDATE';
}
} |
package com.unhurdle.spectrum
{
COMPILE::JS
{
import org.apache.royale.core.WrappedHTMLElement;
}
import com.unhurdle.spectrum.const.IconType;
public class TextArea extends TextFieldBase
{
public function TextArea()
{
super();
toggle(valueToSelector("multiline"),true);
textarea.addEventListener("input",checkValidation);
}
private var textarea:HTMLTextAreaElement;
public function get readonly():Boolean
{
return textarea.readOnly;
}
public function set readonly(value:Boolean):void
{
textarea.readOnly = value;
}
public function get placeholder():String
{
return textarea.placeholder;
}
public function set placeholder(value:String):void
{
//set the content in the textArea
textarea.placeholder = value;
}
// private var _multiline:Boolean;
// public function get multiline():Boolean
// {
// return _multiline;
// }
// public function set multiline(value:Boolean):void
// {
// if(value != !!_multiline){
// toggle(valueToSelector("multiline"),value);
// }
// _multiline = value;
// }
COMPILE::SWF
override public function get name():String
{
return super.name;
}
COMPILE::SWF
override public function set name(value:String):void
{
super.name = value;
}
COMPILE::JS
public function get name():String
{
return textarea.name;
}
COMPILE::JS
public function set name(value:String):void
{
textarea.name = value;
}
public function get text():String
{
return textarea.value;
}
public function set text(value:String):void
{
textarea.value = value;
checkValidation();
}
private var _maxLength:Number = Number.MAX_VALUE;
public function get maxLength():Number
{
return _maxLength;
}
public function set maxLength(value:Number):void
{
_maxLength = value;
if(text){
checkValidation();
}
}
private var _minLength:Number = Number.MIN_VALUE;
public function get minLength():Number
{
return _minLength;
}
public function set minLength(value:Number):void
{
_minLength = value;
if(text){
checkValidation();
}
}
//name???
//lang?????
override public function get disabled():Boolean
{
return super.disabled;
}
override public function set disabled(value:Boolean):void
{
if(value != !!super.disabled){
textarea.disabled = value;
}
super.disabled = value;
}
private var _required:Boolean;
public function get required():Boolean
{
return _required;
}
public function set required(value:Boolean):void
{
if(value != !!_required){
textarea.required = value;
}
_required = value;
}
private var validIcon:Icon;
private var invalidIcon:Icon;
override public function get valid():Boolean
{
return super.valid;
}
override public function set valid(value:Boolean):void
{
super.valid = value;
if(value){
if(!validIcon){
var type:String = IconType.CHECKMARK_MEDIUM;
validIcon = new Icon(Icon.getCSSTypeSelector(type));
validIcon.className = appendSelector("-validationIcon");
validIcon.type = type;
}
//if icon doesn't exist
if(getElementIndex(validIcon) == -1){
addElementAt(validIcon,0);
}
} else{
if(validIcon && getElementIndex(validIcon) != -1){
removeElement(validIcon);
}
}
}
override public function get invalid():Boolean
{
return super.invalid;
}
override public function set invalid(value:Boolean):void
{
super.invalid = value;
if(value){
if(!invalidIcon){
var type:String = IconType.ALERT_MEDIUM;
invalidIcon = new Icon(Icon.getCSSTypeSelector(type));
invalidIcon.className = appendSelector("-validationIcon");
invalidIcon.type = type;
invalidIcon.style = {'box-sizing': 'content-box'};
}
if(getElementIndex(invalidIcon) == -1){
addElementAt(invalidIcon,0);
}
} else{
if(invalidIcon && getElementIndex(invalidIcon) != -1){
removeElement(invalidIcon);
}
}
}
private function checkValidation():void
{
if(maxLength != Number.MAX_VALUE || minLength != Number.MIN_VALUE){
var len:Number = textarea.value.length;
if(len <= maxLength && len >= minLength){
valid = true;
} else{
invalid = true;
}
}
}
override public function get focusElement():HTMLElement{
return textarea;
}
COMPILE::JS
override protected function createElement():WrappedHTMLElement{
var elem:WrappedHTMLElement = super.createElement();
textarea = newElement("textarea",appendSelector("-input")) as HTMLTextAreaElement;
elem.appendChild(textarea);
return elem;
}
}
} |
/*
Copyright 2012-2013 Renaun Erickson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@author Renaun Erickson / renaun.com / @renaun
*/
package flash.ui
{
public class MultitouchInputMode
{
public static const GESTURE:String = "gesture";
public static const NONE:String = "none";
public static const TOUCH_POINT:String = "touchPoint";
public function MultitouchInputMode()
{
}
}
} |
#include "Scripts/Constants.as"
class KeyboardHandler : ScriptObject
{
NavigationMesh@ navMesh_;
void Start()
{
SubscribeToEvent("KeyDown", "HandleKeyDown");
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
}
void DelayedStart()
{
navMesh_ = scene.GetComponent("NavigationMesh");
navMesh_.Build();
}
void Stop()
{
}
void HandleKeyDown(StringHash type, VariantMap& data)
{
Viewport@ viewport = renderer.viewports[0];
float maxRayDistance_ = 50.0f;
PhysicsRaycastResult result = physicsWorld.RaycastSingle(
viewport.GetScreenRay(input.mousePosition.x, input.mousePosition.y),
maxRayDistance_,
MOVEMENT_LAYER
);
if (data["Key"] == KEY_ESCAPE)
{
engine.Exit();
}
else if (data["Key"] == KEY_B)
{
log.Debug("Sending purchase data");
VariantMap purchaseData;
purchaseData["Team"] = "player";
purchaseData["Type"] = "cuboid";
purchaseData["Target"] = result.position;
SendEvent("UnitPurchase", purchaseData);
}
else if (data["Key"] == KEY_T)
{
log.Debug("Sending upgrade data");
VariantMap upgradeData;
upgradeData["Team"] = "player";
upgradeData["Type"] = "cuboid";
SendEvent("UnitUpgrade", upgradeData);
}
}
void HandlePostRenderUpdate(StringHash type, VariantMap& data)
{
if (input.keyDown[KEY_N])
{
navMesh_.DrawDebugGeometry(debugRenderer, true);
}
}
} |
package de.dittner.siegmar.backend.op {
import de.dittner.async.CompositeCommand;
import de.dittner.async.IAsyncCommand;
import de.dittner.async.IAsyncOperation;
public class RemoveFileSQLOperation extends StorageOperation implements IAsyncCommand {
public function RemoveFileSQLOperation(fileWrapper:FileSQLWrapper) {
this.headerWrapper = fileWrapper;
}
private var headerWrapper:FileSQLWrapper;
public function execute():void {
var compositeOp:CompositeCommand = new CompositeCommand();
compositeOp.addCompleteCallback(compositeOpHandler);
try {
compositeOp.addOperation(SelectHeaderIDsToRemoveOperation, headerWrapper);
compositeOp.addOperation(RemoveFileHeadersAndBodiesPhaseOperation, headerWrapper);
compositeOp.execute();
}
catch (exc:Error) {
compositeOp.destroy();
dispatchError(exc.message);
}
}
private function compositeOpHandler(op:IAsyncOperation):void {
dispatchSuccess();
headerWrapper = null;
}
}
} |
package serverProto.guild
{
import com.netease.protobuf.Message;
import com.netease.protobuf.fieldDescriptors.FieldDescriptor$TYPE_UINT32;
import com.netease.protobuf.WireType;
import com.netease.protobuf.WritingBuffer;
import com.netease.protobuf.WriteUtils;
import flash.utils.IDataInput;
import com.netease.protobuf.ReadUtils;
import flash.errors.IOError;
public final class ProtoGuildActivityData extends Message
{
public static const TODAY_LUCKY_WHEEL_COUNT:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.guild.ProtoGuildActivityData.today_lucky_wheel_count","todayLuckyWheelCount",1 << 3 | WireType.VARINT);
public static const MAX_LUCKY_WHEEL_COUNT:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.guild.ProtoGuildActivityData.max_lucky_wheel_count","maxLuckyWheelCount",2 << 3 | WireType.VARINT);
public static const TODAY_ESCORT_COUNT:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.guild.ProtoGuildActivityData.today_escort_count","todayEscortCount",3 << 3 | WireType.VARINT);
public static const MAX_ESCORT_COUNT:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.guild.ProtoGuildActivityData.max_escort_count","maxEscortCount",4 << 3 | WireType.VARINT);
public static const TODAY_ROBERRY_COUNT:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.guild.ProtoGuildActivityData.today_roberry_count","todayRoberryCount",5 << 3 | WireType.VARINT);
public static const MAX_ROBERRY_COUNT:FieldDescriptor$TYPE_UINT32 = new FieldDescriptor$TYPE_UINT32("serverProto.guild.ProtoGuildActivityData.max_roberry_count","maxRoberryCount",6 << 3 | WireType.VARINT);
private var today_lucky_wheel_count$field:uint;
private var hasField$0:uint = 0;
private var max_lucky_wheel_count$field:uint;
private var today_escort_count$field:uint;
private var max_escort_count$field:uint;
private var today_roberry_count$field:uint;
private var max_roberry_count$field:uint;
public function ProtoGuildActivityData()
{
super();
}
public function clearTodayLuckyWheelCount() : void
{
this.hasField$0 = this.hasField$0 & 4.294967294E9;
this.today_lucky_wheel_count$field = new uint();
}
public function get hasTodayLuckyWheelCount() : Boolean
{
return (this.hasField$0 & 1) != 0;
}
public function set todayLuckyWheelCount(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 1;
this.today_lucky_wheel_count$field = param1;
}
public function get todayLuckyWheelCount() : uint
{
return this.today_lucky_wheel_count$field;
}
public function clearMaxLuckyWheelCount() : void
{
this.hasField$0 = this.hasField$0 & 4.294967293E9;
this.max_lucky_wheel_count$field = new uint();
}
public function get hasMaxLuckyWheelCount() : Boolean
{
return (this.hasField$0 & 2) != 0;
}
public function set maxLuckyWheelCount(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 2;
this.max_lucky_wheel_count$field = param1;
}
public function get maxLuckyWheelCount() : uint
{
return this.max_lucky_wheel_count$field;
}
public function clearTodayEscortCount() : void
{
this.hasField$0 = this.hasField$0 & 4.294967291E9;
this.today_escort_count$field = new uint();
}
public function get hasTodayEscortCount() : Boolean
{
return (this.hasField$0 & 4) != 0;
}
public function set todayEscortCount(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 4;
this.today_escort_count$field = param1;
}
public function get todayEscortCount() : uint
{
return this.today_escort_count$field;
}
public function clearMaxEscortCount() : void
{
this.hasField$0 = this.hasField$0 & 4.294967287E9;
this.max_escort_count$field = new uint();
}
public function get hasMaxEscortCount() : Boolean
{
return (this.hasField$0 & 8) != 0;
}
public function set maxEscortCount(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 8;
this.max_escort_count$field = param1;
}
public function get maxEscortCount() : uint
{
return this.max_escort_count$field;
}
public function clearTodayRoberryCount() : void
{
this.hasField$0 = this.hasField$0 & 4.294967279E9;
this.today_roberry_count$field = new uint();
}
public function get hasTodayRoberryCount() : Boolean
{
return (this.hasField$0 & 16) != 0;
}
public function set todayRoberryCount(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 16;
this.today_roberry_count$field = param1;
}
public function get todayRoberryCount() : uint
{
return this.today_roberry_count$field;
}
public function clearMaxRoberryCount() : void
{
this.hasField$0 = this.hasField$0 & 4.294967263E9;
this.max_roberry_count$field = new uint();
}
public function get hasMaxRoberryCount() : Boolean
{
return (this.hasField$0 & 32) != 0;
}
public function set maxRoberryCount(param1:uint) : void
{
this.hasField$0 = this.hasField$0 | 32;
this.max_roberry_count$field = param1;
}
public function get maxRoberryCount() : uint
{
return this.max_roberry_count$field;
}
override final function writeToBuffer(param1:WritingBuffer) : void
{
var _loc2_:* = undefined;
if(this.hasTodayLuckyWheelCount)
{
WriteUtils.writeTag(param1,WireType.VARINT,1);
WriteUtils.write$TYPE_UINT32(param1,this.today_lucky_wheel_count$field);
}
if(this.hasMaxLuckyWheelCount)
{
WriteUtils.writeTag(param1,WireType.VARINT,2);
WriteUtils.write$TYPE_UINT32(param1,this.max_lucky_wheel_count$field);
}
if(this.hasTodayEscortCount)
{
WriteUtils.writeTag(param1,WireType.VARINT,3);
WriteUtils.write$TYPE_UINT32(param1,this.today_escort_count$field);
}
if(this.hasMaxEscortCount)
{
WriteUtils.writeTag(param1,WireType.VARINT,4);
WriteUtils.write$TYPE_UINT32(param1,this.max_escort_count$field);
}
if(this.hasTodayRoberryCount)
{
WriteUtils.writeTag(param1,WireType.VARINT,5);
WriteUtils.write$TYPE_UINT32(param1,this.today_roberry_count$field);
}
if(this.hasMaxRoberryCount)
{
WriteUtils.writeTag(param1,WireType.VARINT,6);
WriteUtils.write$TYPE_UINT32(param1,this.max_roberry_count$field);
}
for(_loc2_ in this)
{
super.writeUnknown(param1,_loc2_);
}
}
override final function readFromSlice(param1:IDataInput, param2:uint) : void
{
/*
* Decompilation error
* Code may be obfuscated
* Tip: You can try enabling "Automatic deobfuscation" in Settings
* Error type: IndexOutOfBoundsException (Index: 6, Size: 6)
*/
throw new flash.errors.IllegalOperationError("Not decompiled due to error");
}
}
}
|
/**
* The DropdownMenu wraps the behavior of a button and a list. Clicking on this component opens a list that contains the elements to be selected. The DropdownMenu displays only the selected element in its idle state. It can be configured to use either the ScrollingList or the TileList, to which either a ScrollBar or ScrollIndicator can be paired with. The list is populated via an installed DataProvider. The DropdownMenu’s list element is populated via a DataProvider. The dataProvider is assigned via code, as shown in the example below:
<i>dropdownMenu.dataProvider = ["item1", "item2", "item3", "item4"];</i>
<b>Inspectable Properties</b>
The inspectable properties of the DropdownMenu component are:<ul>
<li><i>visible</i>: Hides the component if set to false.</li>
<li><i>disabled</i>: Disables the component if set to true.</li>
<li><i>dropdown</i>: Symbol name of the list component (ScrollingList or TileList) to use with the DropdownMenu component.</li>
<li><i>itemRenderer</i>: Symbol name of the list component's itemRenderer.</li>
<li><i>dropdownWidth</i>: Width of the dropdown list. If this value is -1, then the DropdownMenu will size the list to the component’s width.</li>
<li><i>itemRenderer</i>: Symbol name of the dropdown list’s item renderer. Created by the dropdown list instance.</li>
<li><i>scrollBar</i>: Symbol name of the dropdown list’s scroll bar. Created by the dropdown list instance. If value is empty, then the dropdown list will have no scroll bar.</li>
<li><i>margin</i>: The margin between the boundary of the list component and the list items created internally. This margin also affects the automatically generated scrollbar.</li>
<li><i>paddingTop:</i>Extra padding at the top for the list items. Does not affect the automatically generated scrollbar.</li>
<li><i>paddingBottom:</i>Extra padding at the bottom for the list items. Does not affect the automatically generated scrollbar.</li>
<li><i>paddingLeft:</i>Extra padding on the left side for the list items. Does not affect the automatically generated scrollbar.</li>
<li><i>paddingRight:</i>Extra padding on the right side for the list items. Does not affect the automatically generated scrollbar.</li>
<li><i>thumbOffsetTop:</i>Scrollbar thumb top offset. This property has no effect if the list does not automatically create a scrollbar instance.</li>
<li><i>thumbOffsetBottom:</i>Scrollbar thumb bottom offset. This property has no effect if the list does not automatically create a scrollbar instance.</li>
<li><i>thumbSizeFactor:</i>Page size factor for the scrollbar thumb. A value greater than 1.0 will increase the thumb size by the given factor. This value has no effect if a scrollbar is not attached to the list.</li>
<li><i>offsetX:</i>Horizontal offset of the dropdown list from the dropdown button position. A positive value moves the list to the right of the dropdown button horizontal position.</li>
<li><i>offsetY:</i>Vertical offset of the dropdown list from the dropdown button. A positive value moves the list away from the button.</li>
<li><i>extent:</i>An extra width offset that can be used in conjunction with offsetX. This value has no effect if the dropdownWidth property is set to a value other than -1.</li>
<li><i>direction:</i>The list open direction. Valid values are "up" and "down".</li>
<li><i>enableInitCallback</i>: If set to true, _global.CLIK_loadCallback() will be fired when a component is loaded and _global.CLIK_unloadCallback will be called when the component is unloaded. These methods receive the instance name, target path, and a reference the component as parameters. _global.CLIK_loadCallback and _global.CLIK_unloadCallback should be overriden from the game engine using GFx FunctionObjects.</li>
<li><i>soundMap</i>: Mapping between events and sound process. When an event is fired, the associated sound process will be fired via _global.gfxProcessSound, which should be overriden from the game engine using GFx FunctionObjects.</li></ul>
<b>States</b>
The DropdownMenu is toggled when opened, and therefore needs the same states as a ToggleButton or CheckBox that denote the selected state. These states include <ul>
<li>an up or default state.</li>
<li>an over state when the mouse cursor is over the component, or when it is focused.</li>
<li>a down state when the button is pressed.</li>
<li>a disabled state.</li>
<li>a selected_up or default state.</li>
<li>a selected_over state when the mouse cursor is over the component, or when it is focused.</li>
<li>a selected_down state when the button is pressed.</li>
<li>a selected_disabled state.</li></ul>
These are the minimal set of keyframes that should be in a DropdownMenu. The extended set of states and keyframes supported by the Button component, and consequently the DropdownMenu component, are described in the Getting Started with CLIK Buttons document.
<b>Events</b>
All event callbacks receive a single Object parameter that contains relevant information about the event. The following properties are common to all events. <ul>
<li><i>type</i>: The event type.</li>
<li><i>target</i>: The target that generated the event.</li></ul>
The events generated by the DropdownMenu component are listed below. They are the same as the Button component with the exception of the change event. The properties listed next to the event are provided in addition to the common properties.<ul>
<li><i>show</i>: The component's visible property has been set to true at runtime.</li>
<li><i>hide</i>: The component's visible property has been set to false at runtime.</li>
<li><i>focusIn</i>: The component has received focus.</li>
<li><i>focusOut</i>: The component has lost focus.</li>
<li><i>select</i>: The component's selected property has changed.<ul>
<li><i>selected</i>: The selected property of the Button. Boolean type.</li></ul></li>
<li><i>stateChange</i>: The button's state has changed.<ul>
<li><i>state</i>: The Button's new state. String type. Values "up", "over", "down", etc. </li></ul></li>
<li><i>rollOver</i>: The mouse cursor has rolled over the button.<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li>
<li><i>rollOut</i>: The mouse cursor has rolled out of the button.<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li>
<li><i>press</i>: The button has been pressed.<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li>
<li><i>doubleClick</i>: The button has been double clicked. Only fired when the {@link Button.doubleClickEnabled} property is set.<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li>
<li><i>click</i>: The button has been clicked.<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li>
<li><i>dragOver</i>: The mouse cursor has been dragged over the button (while the left mouse button is pressed).<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li>
<li><i>dragOut</i>: The mouse cursor has been dragged out of the button (while the left mouse button is pressed).<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li>
<li><i>releaseOutside</i>: The mouse cursor has been dragged out of the button and the left mouse button has been released.<ul>
<li><i>controllerIdx</i>: The index of the mouse cursor used to generate the event (applicable only for multi-mouse-cursor environments). Number type. Values 0 to 3.</li></ul></li></ul>
*/
import gfx.controls.Button;
import gfx.data.DataProvider;
import gfx.managers.PopUpManager;
import gfx.ui.InputDetails;
import gfx.ui.NavigationCode;
[InspectableList("disabled", "visible", "inspectableDropdown", "inspectableItemRenderer", "inspectableScrollBar", "dropdownWidth", "margin", "paddingTop", "paddingBottom", "paddingLeft", "paddingRight", "thumbOffsetBottom", "thumbOffsetTop", "thumbSizeFactor", "offsetX", "offsetY", "extent", "direction", "enableInitCallback", "soundMap")]
class gfx.controls.DropdownMenu extends Button
{
/* PUBLIC VARIABLES */
/** The current visible state of the {@code dropdown} component. When the dropdown is open, it will receive input from the user. */
public var isOpen: Boolean = false;
/** A reference to the currently selected item in the {@code dataProvider}. */
public var selectedItem: Object;
/** Direction the list opens. Valid values are "up" and "down". **/
[Inspectable(enumeration="up,down", defaultValue="down", verbose=1)]
public var direction: String = "down";
[Inspectable(type="Object", defaultValue="theme:default,focusIn:focusIn,focusOut:focusOut,select:select,rollOver:rollOver,rollOut:rollOut,press:press,doubleClick:doubleClick,click:click")]
public var soundMap: Object = { theme:"default", focusIn:"focusIn", focusOut:"focusOut", select:"select", rollOver:"rollOver", rollOut:"rollOut", press:"press", doubleClick:"doubleClick", click:"click" };
/* PRIVATE VARIABLES */
private var _dataProvider: Object;
private var _dropdownWidth: Number = -1;
private var _rowCount: Number = 5;
private var _labelField: String = "label";
private var _labelFunction: Function;
private var _selectedIndex: Number = -1;
[Inspectable(name="dropdown", type="String", defaultValue="ScrollingList")]
private var inspectableDropdown: Object;
[Inspectable(name="itemRenderer", type="String", defaultValue="ListItemRenderer")]
private var inspectableItemRenderer: Object;
[Inspectable(name="scrollBar", type="String")]
private var inspectableScrollBar: Object;
[Inspectable(defaultValue="1", verbose=1)]
private var margin: Number = 1;
[Inspectable(defaultValue="0", verbose=1)]
private var paddingTop: Number = 0;
[Inspectable(defaultValue="0", verbose=1)]
private var paddingBottom: Number = 0;
[Inspectable(defaultValue="0", verbose=1)]
private var paddingLeft: Number = 0;
[Inspectable(defaultValue="0", verbose=1)]
private var paddingRight: Number = 0;
[Inspectable(defaultValue="0", verbose=1)]
private var thumbOffsetTop: Number = 0;
[Inspectable(defaultValue="0", verbose=1)]
private var thumbOffsetBottom: Number = 0;
[Inspectable(defaultValue="1.0", verbose=1)]
private var thumbSizeFactor: Number = 1.0;
[Inspectable(defaultValue="0", verbose=1)]
private var offsetX: Number = 0;
[Inspectable(defaultValue="0", verbose=1)]
private var offsetY: Number = 0;
[Inspectable(defaultValue="0", verbose=1)]
private var extent: Number = 0;
/* STAGE ELEMENTS */
private var _dropdown: MovieClip = null;
/* INITIALIZATION */
/**
* The constructor is called when a DropdownMenu or a sub-class of DropdownMenu is instantiated on stage or by using {@code attachMovie()} in ActionScript. This component can <b>not</b> be instantiated using {@code new} syntax. When creating new components that extend DropdownMenu, ensure that a {@code super()} call is made first in the constructor.
*/
public function DropdownMenu()
{
super();
dataProvider = [];
}
/* PUBLIC FUNCTIONS */
/**
* Sets the class or instance to use as a dropdown. If a linkage ID is specified, it will be created using the {@code PopUpManager}. The dropdown property will return the persistent MovieClip instance created or referenced by the DropdownMenu so properties can be set on it directly.
* @see PopUpManager
*/
public function get dropdown(): Object
{
// Create the dropdown if not created yet
if (!_dropdown) {
createDropDown();
}
return _dropdown;
}
public function set dropdown(value: Object): Void
{
inspectableDropdown = value;
if (initialized) {
createDropDown();
}
}
/**
* Sets the linkage ID to use as the dropdown's item renderer, which will be created by the dropdown list component.
*/
public function get itemRenderer(): Object
{
return _dropdown.itemRenderer;
}
public function set itemRenderer(value: Object): Void
{
inspectableItemRenderer = value;
if (_dropdown) {
_dropdown.itemRenderer = inspectableItemRenderer;
}
}
/**
* Sets the class or instance to use as the dropdown's scrollbar. If a linkage ID is specified, it will be created by the dropdown list component. The scrollbar property will return the persistent MovieClip instance created or referenced by the DropdownMenu's list so properties can be set on it directly.
*/
public function get scrollBar(): Object
{
return _dropdown.scrollBar;
}
public function set scrollBar(value: Object): Void
{
inspectableScrollBar = value;
if (_dropdown) {
_dropdown.scrollBar = inspectableScrollBar;
}
}
/**
* The width of the dropdown.
<ul><li>When set to -1, the component will scale to match the width of the dropdownMenu.</li>
<li>When set to 0, the component will not scale at all, and will be left at its original size.</li>
<li>When set to a number greater than 0, the dropdown will be set to that size exactly.</li><ol>
Auto-sizing based on row contents is not supported.</li></ul>
*/
[Inspectable(defaultValue="-1")]
public function get dropdownWidth(): Number
{
return _dropdownWidth;
}
public function set dropdownWidth(value: Number): Void
{
_dropdownWidth = value;
}
/**
* The number of rows to display in the dropdown. The {@code autoRowCount} property on the dropdown determines how that property is applied. If the length of the {@code dataProvider} is less than the rowCount, only the number of items in the dataProvider will be displayed.
*/
public function get rowCount(): Number
{
return _rowCount;
}
public function set rowCount(value: Number): Void
{
_rowCount = value;
if (_dropdown != null && _dropdown.hasOwnProperty("rowCount")) {
_dropdown.rowCount = value;
}
}
/**
* The data model displayed in the component. The dataProvider can be an Array or any object exposing the appropriate API, defined in the {@code IDataProvider} interface. If an Array is set as the {@code dataProvider}, functionality will be mixed into it by the {@code DataProvider.initialize} method. When a new DataProvider is set, the {@code selectedIndex} property will be reset to 0.
* @see DataProvider
* @see IDataProvider
*/
public function get dataProvider(): Object
{
return _dataProvider;
}
public function set dataProvider(value: Object): Void
{
if (_dataProvider == value) {
return;
}
if (_dataProvider != null) {
_dataProvider.removeEventListener("change", this, "onDataChange");
}
_dataProvider = value;
DataProvider.initialize(_dataProvider);
_dataProvider.addEventListener("change", this, "onDataChange");
if (_dropdown != null) {
_dropdown.dataProvider = _dataProvider;
}
selectedIndex = 0;
updateSelectedItem();
}
/**
* The index of the item that is selected in a single-selection list. The DropdownMenu will always have a {@code selectedIndex} of 0 or greater, unless there is no data.
*/
public function get selectedIndex(): Number
{
return _selectedIndex;
}
public function set selectedIndex(value: Number): Void
{
_selectedIndex = value;
if (_dropdown != null) {
_dropdown.selectedIndex = value;
}
updateSelectedItem();
}
/**
* The name of the field in the {@code dataProvider} to be displayed as the label for the TextInput field. A {@code labelFunction} will be used over a {@code labelField} if it is defined.
* @see #itemToLabel()
*/
public function get labelField(): String
{
return _labelField;
}
public function set labelField(value: String): Void
{
_labelField = value;
if (_dropdown != null) {
_dropdown.labelField = _labelField;
}
updateLabel();
}
/**
* The function used to determine the label for an item. A {@code labelFunction} will override a {@code labelField} if it is defined.
* @see #itemToLabel()
*/
public function get labelFunction(): Function
{
return _labelFunction;
}
public function set labelFunction(value: Function): Void
{
_labelFunction = value;
if (_dropdown != null) {
_dropdown.labelFunction = _labelFunction;
}
updateLabel();
}
/**
* Convert an item to a label string using the {@code labelField} and {@code labelFunction}.
* @param item The item to convert to a label.
* @returns The converted label string.
* @see #labelField
* @see #labelFunction
*/
public function itemToLabel(item: Object): String
{
if (item == null) {
return "";
}
if (_labelFunction != null) {
return _labelFunction(item);
} else if (_labelField != null && item[_labelField] != null) {
return item[_labelField];
}
return item.toString();
}
/**
* Open the dropdown list. The {@code selected} and {@code isOpen} properties of the DropdownMenu are set to {@code true} when open. Input will be passed to the dropdown when it is open before it is handled by the DropdownMenu.
*/
public function open(): Void
{
if (!_dropdown) {
createDropDown();
if (!_dropdown) {
isOpen = false;
return;
}
}
openImpl();
}
/**
* Close the dropdown list. The list is not destroyed, the {@code visible} property is set to {@code false}. The {@code selected} property of the DropdownMenu is set to {@code false} when closed.
*/
public function close(): Void
{
if (!isOpen) {
return;
}
isOpen = false;
if (_dropdown == null) {
return;
}
_dropdown.visible = false;
Mouse.removeListener(this);
/*if (_dropdown.scrollBar != null && MovieClip(_dropdown.scrollBar)._parent != _dropdown) {
MovieClip(_dropdown.scrollBar)._visible = false;
}*/
selected = false;
}
/**
* The current data has become invalid, usually via a data change. The component requests a data update from the {@code dataProvider}.
*/
public function invalidateData(): Void
{
_dataProvider.requestItemAt(_selectedIndex, this, "populateText");
}
public function setSize(width: Number, height: Number): Void
{
super.setSize(width, height);
if (_dropdown != null && _dropdownWidth == -1) {
_dropdown.width = __width;
}
}
public function handleInput(details: InputDetails, pathToFocus: Array): Boolean
{
var handled: Boolean;
if (_dropdown != null && isOpen) {
handled = _dropdown.handleInput(details);
if (handled) {
return true;
}
}
// Let the Button also try and handle it.
handled = super.handleInput(details, pathToFocus);
var keyPress:Boolean = (details.value == "keyDown" || details.value == "keyHold");
switch (details.navEquivalent) {
case NavigationCode.ESCAPE:
if (isOpen) {
if (keyPress) {
close();
}
return true;
}
}
// Return the value the button handleInput returned.
return handled;
}
// Override in order to help out.
/** @exclude */
public function removeMovieClip(): Void
{
if (_dropdown) {
_dropdown.removeMovieClip();
}
super.removeMovieClip();
}
/** @exclude */
public function toString(): String
{
return "[Scaleform DropdownMenu " + _name + "]";
}
/* PRIVATE FUNCTIONS */
private function createDropDown(): Void
{
if (_dropdown == inspectableDropdown) {
return;
}
if (_dropdown != null) {
_dropdown.removeMovieClip();
}
// Create or cast the dropdown
if (typeof(inspectableDropdown) == "string") {
_dropdown = MovieClip(_parent[inspectableDropdown]);
if (_dropdown == null) {
_dropdown = PopUpManager.createPopUp(this, inspectableDropdown.toString(),
{itemRenderer:inspectableItemRenderer, paddingTop:paddingTop, paddingBottom:paddingBottom,
paddingLeft:paddingLeft, paddingRight:paddingRight, thumbOffsetTop:thumbOffsetTop,
thumbOffsetBottom:thumbOffsetBottom, thumbSizeFactor:thumbSizeFactor, margin:margin});
_dropdown.scrollBar = inspectableScrollBar;
}
} else if (inspectableDropdown instanceof MovieClip) {
_dropdown = MovieClip(_dropdown);
}
if (_dropdown == null) {
return;
}
// Initialize the dropdown
_dropdown.addEventListener("itemClick", this, "handleChange");
_dropdown.labelField = _labelField;
_dropdown.labelFunction = _labelFunction;
_dropdown.dataProvider = _dataProvider;
_dropdown.selectedIndex = _selectedIndex;
_dropdown.visible = false;
if (!_disableFocus) {
_dropdown.focusTarget = this;
}
if (_dropdown.wrapping != null) {
_dropdown.wrapping = "stick";
}
if (_dropdown.autoRowCount != null) {
_dropdown.autoRowCount = true;
}
if (_dropdown.rowCount != null) {
_dropdown.rowCount = Math.min(_dataProvider.length, _rowCount);
}
if (_dropdownWidth != 0) {
_dropdown.width = (_dropdownWidth == -1) ? (__width + extent) : _dropdownWidth;
}
}
private function openImpl(): Void
{
if (isOpen) {
return;
}
isOpen = true;
// Set the width *before* the rowCount, in case the width changes the rowCount.
if (_dropdownWidth != _dropdown.width) {
_dropdown.width = (_dropdownWidth == -1) ? (__width + extent) : _dropdownWidth;
}
if (_rowCount != _dropdown.rowCount) {
_dropdown.rowCount = Math.min(_dataProvider.length, _rowCount);
}
_dropdown.validateNow();
onMouseDown = handleStageClick;
Mouse.addListener(this);
selected = true; // Select the Button state.
_dropdown.selectedIndex = _selectedIndex;
_dropdown.scrollToIndex(_selectedIndex);
var oX:Number = offsetX * (100/_xscale);
var oY:Number = offsetY * (100/_yscale);
PopUpManager.movePopUp(this, MovieClip(_dropdown), this, oX,
(direction == "down") ? __height + oY : -_dropdown.height - oY);
_dropdown.visible = true;
}
private function configUI(): Void
{
super.configUI();
addEventListener("click", this, "toggleMenu");
toggle = false; // In case the developer doesn't know better.
}
private function changeFocus(): Void
{
super.changeFocus();
if (isOpen && _dropdown != null) {
close();
}
}
private function updateSelectedItem(): Void
{
invalidateData();
}
private function updateLabel(): Void
{
label = itemToLabel(selectedItem);
}
private function populateText(item: Object): Void
{
selectedItem = item;
updateLabel();
dispatchEvent({type:"change", index:_selectedIndex, data:item});
}
// The dropdown has been clicked/changed.
private function handleChange(event: Object): Void
{
var index: Number = _dropdown.selectedIndex;
_selectedIndex = index; // No need to trigger a selection change using selectedIndex instead
close();
updateSelectedItem();
}
private function onDataChange(event: Object): Void
{
updateSelectedItem();
}
private function toggleMenu(event: Object): Void
{
!_selected ? open() : close();
}
// Close the dropdown if the user clicks anywhere else in the application.
private function handleStageClick(event: Object): Void
{
if (hitTest(_root._xmouse, _root._ymouse, true)) {
return;
}
close();
}
// Overridden hitTest to account for dropdown list
private function hitTest(x: Number, y: Number, shapeFlag: Boolean): Boolean
{
return (super.hitTest(x, y, shapeFlag) || ((_dropdown && isOpen) ? _dropdown.hitTest(x, y, shapeFlag) : false));
}
}
|
package io.decagames.rotmg.dailyQuests.signal {
import io.decagames.rotmg.dailyQuests.messages.incoming.QuestFetchResponse;
import org.osflash.signals.Signal;
public class QuestFetchCompleteSignal extends Signal {
public function QuestFetchCompleteSignal() {
super(QuestFetchResponse);
}
}
}
|
package dragonBones.animation
{
import flash.geom.ColorTransform;
import flash.geom.Point;
import dragonBones.Armature;
import dragonBones.Bone;
import dragonBones.Slot;
import dragonBones.core.dragonBones_internal;
import dragonBones.objects.DBTransform;
import dragonBones.objects.Frame;
import dragonBones.objects.TimelineCached;
import dragonBones.objects.TransformFrame;
import dragonBones.objects.TransformTimeline;
import dragonBones.utils.TransformUtil;
use namespace dragonBones_internal;
/** @private */
public final class TimelineState
{
private static const HALF_PI:Number = Math.PI * 0.5;
private static const DOUBLE_PI:Number = Math.PI * 2;
private static var _pool:Vector.<TimelineState> = new Vector.<TimelineState>;
/** @private */
dragonBones_internal static function borrowObject():TimelineState
{
if(_pool.length == 0)
{
return new TimelineState();
}
return _pool.pop();
}
/** @private */
dragonBones_internal static function returnObject(timeline:TimelineState):void
{
if(_pool.indexOf(timeline) < 0)
{
_pool[_pool.length] = timeline;
}
timeline.clear();
}
/** @private */
dragonBones_internal static function clear():void
{
var i:int = _pool.length;
while(i --)
{
_pool[i].clear();
}
_pool.length = 0;
}
/** @private */
public static function getEaseValue(value:Number, easing:Number):Number
{
var valueEase:Number = 1;
if(easing > 1) //ease in out
{
valueEase = 0.5 * (1 - Math.cos(value * Math.PI));
easing -= 1;
}
else if (easing > 0) //ease out
{
valueEase = 1 - Math.pow(1-value,2);
}
else if (easing < 0) //ease in
{
easing *= -1;
valueEase = Math.pow(value,2);
}
return (valueEase - value) * easing + value;
}
/** @private */
dragonBones_internal var _transform:DBTransform;
/** @private */
dragonBones_internal var _pivot:Point;
/** @private */
dragonBones_internal var _blendEnabled:Boolean;
/** @private */
dragonBones_internal var _isComplete:Boolean;
private var _totalTime:int;
private var _currentTime:int;
private var _currentFrameIndex:int;
private var _currentFramePosition:int;
private var _currentFrameDuration:int;
private var _tweenEasing:Number;
private var _tweenTransform:Boolean;
private var _tweenScale:Boolean;
private var _tweenColor:Boolean;
private var _rawAnimationScale:Number;
private var _updateState:int;
private var _armature:Armature;
private var _animation:Animation;
private var _bone:Bone;
private var _animationState:AnimationState;
private var _timeline:TransformTimeline;
private var _originTransform:DBTransform;
private var _originPivot:Point;
private var _durationTransform:DBTransform;
private var _durationPivot:Point;
private var _durationColor:ColorTransform;
private var _name:String;
/**
* The name of the animation state.
*/
public function get name():String
{
return _name;
}
public function get layer():int
{
return _animationState.layer;
}
public function get weight():Number
{
return _animationState.fadeWeight * _animationState.weight;
}
public function TimelineState()
{
_transform = new DBTransform();
_pivot = new Point();
_durationTransform = new DBTransform();
_durationPivot = new Point();
_durationColor = new ColorTransform();
}
/** @private */
dragonBones_internal function fadeIn(bone:Bone, animationState:AnimationState, timeline:TransformTimeline):void
{
_bone = bone;
_armature = _bone.armature;
_animation = _armature.animation;
_animationState = animationState;
_timeline = timeline;
_originTransform = _timeline.originTransform;
_originPivot = _timeline.originPivot;
_name = _timeline.name;
_totalTime = _timeline.duration;
_rawAnimationScale = _animationState.clip.scale;
_currentFrameIndex = -1;
_currentTime = -1;
_isComplete = false;
_blendEnabled = false;
_tweenEasing = NaN;
_tweenTransform = false;
_tweenScale = false;
_tweenColor = false;
_transform.x = 0;
_transform.y = 0;
_transform.scaleX = 0;
_transform.scaleY = 0;
_transform.skewX = 0;
_transform.skewY = 0;
_pivot.x = 0;
_pivot.y = 0;
_durationTransform.x = 0;
_durationTransform.y = 0;
_durationTransform.scaleX = 0;
_durationTransform.scaleY = 0;
_durationTransform.skewX = 0;
_durationTransform.skewY = 0;
_durationPivot.x = 0;
_durationPivot.y = 0;
switch(_timeline.frameList.length)
{
case 0:
_updateState = 0;
break;
case 1:
_updateState = -1;
break;
default:
_updateState = 1;
break;
}
_bone.addState(this);
}
/** @private */
dragonBones_internal function fadeOut():void
{
_transform.skewX = TransformUtil.formatRadian(_transform.skewX);
_transform.skewY = TransformUtil.formatRadian(_transform.skewY);
}
/** @private */
dragonBones_internal function update(progress:Number):void
{
if(_updateState > 0)
{
updateMultipleFrame(progress);
}
else if(_updateState < 0)
{
_updateState = 0;
updateSingleFrame();
}
}
private function updateMultipleFrame(progress:Number):void
{
var currentPlayTimes:int = 0;
if(_timeline.scale == 0)
{
//normalizedTime [0, 1)
progress = 0.999999;
}
progress /= _timeline.scale;
progress += _timeline.offset;
var currentTime:int = _totalTime * progress;
var playTimes:int = _animationState.playTimes;
if(playTimes == 0)
{
_isComplete = false;
currentPlayTimes = Math.ceil(Math.abs(currentTime) / _totalTime) || 1;
//currentTime -= Math.floor(currentTime / _totalTime) * _totalTime;
currentTime -= int(currentTime / _totalTime) * _totalTime;
if(currentTime < 0)
{
currentTime += _totalTime;
}
}
else
{
var totalTimes:int = playTimes * _totalTime;
if(currentTime >= totalTimes)
{
currentTime = totalTimes;
_isComplete = true;
}
else if(currentTime <= -totalTimes)
{
currentTime = -totalTimes;
_isComplete = true;
}
else
{
_isComplete = false;
}
if(currentTime < 0)
{
currentTime += totalTimes;
}
currentPlayTimes = Math.ceil(currentTime / _totalTime) || 1;
if(_isComplete)
{
currentTime = _totalTime;
}
else
{
//currentTime -= Math.floor(currentTime / _totalTime) * _totalTime;
currentTime -= int(currentTime / _totalTime) * _totalTime;
}
}
if(_currentTime != currentTime)
{
_currentTime = currentTime;
var frameList:Vector.<Frame> = _timeline.frameList;
var prevFrame:TransformFrame;
var currentFrame:TransformFrame;
while(true)
{
if(_currentFrameIndex < 0)
{
_currentFrameIndex = 0;
currentFrame = frameList[_currentFrameIndex] as TransformFrame;
}
else if(_currentTime >= _currentFramePosition + _currentFrameDuration)
{
_currentFrameIndex ++;
if(_currentFrameIndex >= frameList.length)
{
if(_isComplete)
{
_currentFrameIndex --;
break;
}
else
{
_currentFrameIndex = 0;
}
}
currentFrame = frameList[_currentFrameIndex] as TransformFrame;
}
else if(_currentTime < _currentFramePosition)
{
_currentFrameIndex --;
if(_currentFrameIndex < 0)
{
_currentFrameIndex = frameList.length - 1;
}
currentFrame = frameList[_currentFrameIndex] as TransformFrame;
}
else
{
break;
}
if(prevFrame)
{
_bone.arriveAtFrame(prevFrame, this, _animationState, true);
}
_currentFrameDuration = currentFrame.duration;
_currentFramePosition = currentFrame.position;
}
if(currentFrame)
{
_bone.arriveAtFrame(currentFrame, this, _animationState, false);
_blendEnabled = currentFrame.displayIndex >= 0;
if(_blendEnabled)
{
updateToNextFrame(currentPlayTimes);
}
else
{
_tweenEasing = NaN;
_tweenTransform = false;
_tweenScale = false;
_tweenColor = false;
}
}
if(_blendEnabled)
{
updateTween();
}
}
}
private function updateToNextFrame(currentPlayTimes:int):void
{
var nextFrameIndex:int = _currentFrameIndex + 1;
if(nextFrameIndex >= _timeline.frameList.length)
{
nextFrameIndex = 0;
}
var currentFrame:TransformFrame = _timeline.frameList[_currentFrameIndex] as TransformFrame;
var nextFrame:TransformFrame = _timeline.frameList[nextFrameIndex] as TransformFrame;
var tweenEnabled:Boolean = false;
if(
nextFrameIndex == 0 &&
(
!_animationState.lastFrameAutoTween ||
(
_animationState.playTimes &&
_animationState.currentPlayTimes >= _animationState.playTimes &&
((_currentFramePosition + _currentFrameDuration) / _totalTime + currentPlayTimes - _timeline.offset) * _timeline.scale > 0.999999
)
)
)
{
_tweenEasing = NaN;
tweenEnabled = false;
}
else if(currentFrame.displayIndex < 0 || nextFrame.displayIndex < 0)
{
_tweenEasing = NaN;
tweenEnabled = false;
}
else if(_animationState.autoTween)
{
_tweenEasing = _animationState.clip.tweenEasing;
if(isNaN(_tweenEasing))
{
_tweenEasing = currentFrame.tweenEasing;
if(isNaN(_tweenEasing)) //frame no tween
{
tweenEnabled = false;
}
else
{
if(_tweenEasing == 10)
{
_tweenEasing = 0;
}
//_tweenEasing [-1, 0) 0 (0, 1] (1, 2]
tweenEnabled = true;
}
}
else //animationData overwrite tween
{
//_tweenEasing [-1, 0) 0 (0, 1] (1, 2]
tweenEnabled = true;
}
}
else
{
_tweenEasing = currentFrame.tweenEasing;
if(isNaN(_tweenEasing) || _tweenEasing == 10) //frame no tween
{
_tweenEasing = NaN;
tweenEnabled = false;
}
else
{
//_tweenEasing [-1, 0) 0 (0, 1] (1, 2]
tweenEnabled = true;
}
}
if(tweenEnabled)
{
//transform
_durationTransform.x = nextFrame.transform.x - currentFrame.transform.x;
_durationTransform.y = nextFrame.transform.y - currentFrame.transform.y;
_durationTransform.skewX = nextFrame.transform.skewX - currentFrame.transform.skewX;
_durationTransform.skewY = nextFrame.transform.skewY - currentFrame.transform.skewY;
/*
_durationTransform.scaleX = nextFrame.transform.scaleX - currentFrame.transform.scaleX;
_durationTransform.scaleY = nextFrame.transform.scaleY - currentFrame.transform.scaleY;
*/
_durationTransform.scaleX = nextFrame.transform.scaleX - currentFrame.transform.scaleX + nextFrame.scaleOffset.x;
_durationTransform.scaleY = nextFrame.transform.scaleY - currentFrame.transform.scaleY + nextFrame.scaleOffset.y;
if(nextFrameIndex == 0)
{
_durationTransform.skewX = TransformUtil.formatRadian(_durationTransform.skewX);
_durationTransform.skewY = TransformUtil.formatRadian(_durationTransform.skewY);
}
_durationPivot.x = nextFrame.pivot.x - currentFrame.pivot.x;
_durationPivot.y = nextFrame.pivot.y - currentFrame.pivot.y;
if(
_durationTransform.x ||
_durationTransform.y ||
_durationTransform.skewX ||
_durationTransform.skewY ||
_durationTransform.scaleX ||
_durationTransform.scaleY ||
_durationPivot.x ||
_durationPivot.y
)
{
_tweenTransform = true;
_tweenScale = currentFrame.tweenScale;
}
else
{
_tweenTransform = false;
_tweenScale = false;
}
//color
if(currentFrame.color && nextFrame.color)
{
_durationColor.alphaOffset = nextFrame.color.alphaOffset - currentFrame.color.alphaOffset;
_durationColor.redOffset = nextFrame.color.redOffset - currentFrame.color.redOffset;
_durationColor.greenOffset = nextFrame.color.greenOffset - currentFrame.color.greenOffset;
_durationColor.blueOffset = nextFrame.color.blueOffset - currentFrame.color.blueOffset;
_durationColor.alphaMultiplier = nextFrame.color.alphaMultiplier - currentFrame.color.alphaMultiplier;
_durationColor.redMultiplier = nextFrame.color.redMultiplier - currentFrame.color.redMultiplier;
_durationColor.greenMultiplier = nextFrame.color.greenMultiplier - currentFrame.color.greenMultiplier;
_durationColor.blueMultiplier = nextFrame.color.blueMultiplier - currentFrame.color.blueMultiplier;
if(
_durationColor.alphaOffset ||
_durationColor.redOffset ||
_durationColor.greenOffset ||
_durationColor.blueOffset ||
_durationColor.alphaMultiplier ||
_durationColor.redMultiplier ||
_durationColor.greenMultiplier ||
_durationColor.blueMultiplier
)
{
_tweenColor = true;
}
else
{
_tweenColor = false;
}
}
else if(currentFrame.color)
{
_tweenColor = true;
_durationColor.alphaOffset = -currentFrame.color.alphaOffset;
_durationColor.redOffset = -currentFrame.color.redOffset;
_durationColor.greenOffset = -currentFrame.color.greenOffset;
_durationColor.blueOffset = -currentFrame.color.blueOffset;
_durationColor.alphaMultiplier = 1 - currentFrame.color.alphaMultiplier;
_durationColor.redMultiplier = 1 - currentFrame.color.redMultiplier;
_durationColor.greenMultiplier = 1 - currentFrame.color.greenMultiplier;
_durationColor.blueMultiplier = 1 - currentFrame.color.blueMultiplier;
}
else if(nextFrame.color)
{
_tweenColor = true;
_durationColor.alphaOffset = nextFrame.color.alphaOffset;
_durationColor.redOffset = nextFrame.color.redOffset;
_durationColor.greenOffset = nextFrame.color.greenOffset;
_durationColor.blueOffset = nextFrame.color.blueOffset;
_durationColor.alphaMultiplier = nextFrame.color.alphaMultiplier - 1;
_durationColor.redMultiplier = nextFrame.color.redMultiplier - 1;
_durationColor.greenMultiplier = nextFrame.color.greenMultiplier - 1;
_durationColor.blueMultiplier = nextFrame.color.blueMultiplier - 1;
}
else
{
_tweenColor = false;
}
}
else
{
_tweenTransform = false;
_tweenScale = false;
_tweenColor = false;
}
if(!_tweenTransform)
{
if(!updateTimelineCached(true))
{
if(_animationState.additiveBlending)
{
_transform.x = currentFrame.transform.x;
_transform.y = currentFrame.transform.y;
_transform.skewX = currentFrame.transform.skewX;
_transform.skewY = currentFrame.transform.skewY;
_transform.scaleX = currentFrame.transform.scaleX;
_transform.scaleY = currentFrame.transform.scaleY;
_pivot.x = currentFrame.pivot.x;
_pivot.y = currentFrame.pivot.y;
}
else
{
_transform.x = _originTransform.x + currentFrame.transform.x;
_transform.y = _originTransform.y + currentFrame.transform.y;
_transform.skewX = _originTransform.skewX + currentFrame.transform.skewX;
_transform.skewY = _originTransform.skewY + currentFrame.transform.skewY;
_transform.scaleX = _originTransform.scaleX + currentFrame.transform.scaleX;
_transform.scaleY = _originTransform.scaleY + currentFrame.transform.scaleY;
_pivot.x = _originPivot.x + currentFrame.pivot.x;
_pivot.y = _originPivot.y + currentFrame.pivot.y;
}
}
_bone.invalidUpdate();
}
else if(!_tweenScale)
{
if(_animationState.additiveBlending)
{
_transform.scaleX = currentFrame.transform.scaleX;
_transform.scaleY = currentFrame.transform.scaleY;
}
else
{
_transform.scaleX = _originTransform.scaleX + currentFrame.transform.scaleX;
_transform.scaleY = _originTransform.scaleY + currentFrame.transform.scaleY;
}
}
if(!_tweenColor && _animationState.displayControl)
{
if(currentFrame.color)
{
_bone.updateColor(
currentFrame.color.alphaOffset,
currentFrame.color.redOffset,
currentFrame.color.greenOffset,
currentFrame.color.blueOffset,
currentFrame.color.alphaMultiplier,
currentFrame.color.redMultiplier,
currentFrame.color.greenMultiplier,
currentFrame.color.blueMultiplier,
true
);
}
else if(_bone._isColorChanged)
{
_bone.updateColor(0, 0, 0, 0, 1, 1, 1, 1, false);
}
}
}
private function updateTween():void
{
var progress:Number = (_currentTime - _currentFramePosition) / _currentFrameDuration;
if(_tweenEasing)
{
progress = getEaseValue(progress, _tweenEasing);
}
var currentFrame:TransformFrame = _timeline.frameList[_currentFrameIndex] as TransformFrame;
if(_tweenTransform)
{
if(!updateTimelineCached(false))
{
var currentTransform:DBTransform = currentFrame.transform;
var currentPivot:Point = currentFrame.pivot;
if(_animationState.additiveBlending)
{
//additive blending
_transform.x = currentTransform.x + _durationTransform.x * progress;
_transform.y = currentTransform.y + _durationTransform.y * progress;
_transform.skewX = currentTransform.skewX + _durationTransform.skewX * progress;
_transform.skewY = currentTransform.skewY + _durationTransform.skewY * progress;
if(_tweenScale)
{
_transform.scaleX = currentTransform.scaleX + _durationTransform.scaleX * progress;
_transform.scaleY = currentTransform.scaleY + _durationTransform.scaleY * progress;
}
_pivot.x = currentPivot.x + _durationPivot.x * progress;
_pivot.y = currentPivot.y + _durationPivot.y * progress;
}
else
{
//normal blending
_transform.x = _originTransform.x + currentTransform.x + _durationTransform.x * progress;
_transform.y = _originTransform.y + currentTransform.y + _durationTransform.y * progress;
_transform.skewX = _originTransform.skewX + currentTransform.skewX + _durationTransform.skewX * progress;
_transform.skewY = _originTransform.skewY + currentTransform.skewY + _durationTransform.skewY * progress;
if(_tweenScale)
{
_transform.scaleX = _originTransform.scaleX + currentTransform.scaleX + _durationTransform.scaleX * progress;
_transform.scaleY = _originTransform.scaleY + currentTransform.scaleY + _durationTransform.scaleY * progress;
}
_pivot.x = _originPivot.x + currentPivot.x + _durationPivot.x * progress;
_pivot.y = _originPivot.y + currentPivot.y + _durationPivot.y * progress;
}
}
_bone.invalidUpdate();
}
if(_tweenColor && _animationState.displayControl)
{
if(currentFrame.color)
{
_bone.updateColor(
currentFrame.color.alphaOffset + _durationColor.alphaOffset * progress,
currentFrame.color.redOffset + _durationColor.redOffset * progress,
currentFrame.color.greenOffset + _durationColor.greenOffset * progress,
currentFrame.color.blueOffset + _durationColor.blueOffset * progress,
currentFrame.color.alphaMultiplier + _durationColor.alphaMultiplier * progress,
currentFrame.color.redMultiplier + _durationColor.redMultiplier * progress,
currentFrame.color.greenMultiplier + _durationColor.greenMultiplier * progress,
currentFrame.color.blueMultiplier + _durationColor.blueMultiplier * progress,
true
);
}
else
{
_bone.updateColor(
_durationColor.alphaOffset * progress,
_durationColor.redOffset * progress,
_durationColor.greenOffset * progress,
_durationColor.blueOffset * progress,
1 + _durationColor.alphaMultiplier * progress,
1 + _durationColor.redMultiplier * progress,
1 + _durationColor.greenMultiplier * progress,
1 + _durationColor.blueMultiplier * progress,
true
);
}
}
}
private function updateTimelineCached(isNoTweenFrame:Boolean):Boolean
{
var slot:Slot;
var isCachedFrame:Boolean = false;
if(
_armature.cacheFrameRate > 0 &&
_animation._animationStateCount < 2 &&
!_animation._isFading
)
{
var timelineCached:TimelineCached = _timeline.timelineCached;
if(!_bone._timelineCached)
{
_bone._timelineCached = timelineCached;
for each(slot in _bone.getSlots(false))
{
slot._timelineCached = _timeline.getSlotTimelineCached(slot.name);
}
}
//Math.floor
var framePosition:int = (isNoTweenFrame?_currentFramePosition:_currentTime) * 0.001 * _rawAnimationScale * _armature.cacheFrameRate;
_bone._frameCachedPosition = framePosition;
if(timelineCached.getFrame(framePosition))
{
isCachedFrame = true;
_bone._frameCachedDuration = -1;
}
else
{
_bone._frameCachedDuration = isNoTweenFrame?(_currentFrameDuration * 0.001 * _rawAnimationScale * _armature.cacheFrameRate || 1):1;
}
}
else if(_bone._timelineCached)
{
_bone._timelineCached = null;
for each(slot in _bone.getSlots(false))
{
slot._timelineCached = null;
}
_bone._frameCachedPosition = -1;
_bone._frameCachedDuration = -1;
}
return isCachedFrame;
}
private function updateSingleFrame():void
{
var currentFrame:TransformFrame = _timeline.frameList[0] as TransformFrame;
_bone.arriveAtFrame(currentFrame, this, _animationState, false);
_isComplete = true;
_tweenEasing = NaN;
_tweenTransform = false;
_tweenScale = false;
_tweenColor = false;
_blendEnabled = currentFrame.displayIndex >= 0;
if(_blendEnabled)
{
/**
* 单帧的timeline,第一个关键帧的transform为0
* timeline.originTransform = firstFrame.transform;
* eachFrame.transform = eachFrame.transform - timeline.originTransform;
* firstFrame.transform == 0;
*/
if(_animationState.additiveBlending)
{
//additive blending
//singleFrame.transform (0)
_transform.x =
_transform.y =
_transform.skewX =
_transform.skewY =
_transform.scaleX =
_transform.scaleY = 0;
_pivot.x = 0;
_pivot.y = 0;
}
else
{
//normal blending
//timeline.originTransform + singleFrame.transform (0)
_transform.copy(_originTransform);
_pivot.x = _originPivot.x;
_pivot.y = _originPivot.y;
}
_bone.invalidUpdate();
if(_animationState.displayControl)
{
if(currentFrame.color)
{
_bone.updateColor(
currentFrame.color.alphaOffset,
currentFrame.color.redOffset,
currentFrame.color.greenOffset,
currentFrame.color.blueOffset,
currentFrame.color.alphaMultiplier,
currentFrame.color.redMultiplier,
currentFrame.color.greenMultiplier,
currentFrame.color.blueMultiplier,
true
);
}
else if(_bone._isColorChanged)
{
_bone.updateColor(0, 0, 0, 0, 1, 1, 1, 1, false);
}
}
}
}
private function clear():void
{
if(_bone)
{
_bone.removeState(this);
}
_bone = null;
_armature = null;
_animation = null;
_animationState = null;
_timeline = null;
_originTransform = null;
_originPivot = null;
}
}
}
|
// =================================================================================================
//
// CadetEngine Framework
// Copyright 2012 Unwrong Ltd. All Rights Reserved.
//
// This program is free software. You can redistribute and/or modify it
// in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================
package cadet2DBox2D.events
{
import flash.events.Event;
import flash.geom.Point;
import cadet2DBox2D.components.behaviours.RigidBodyBehaviour;
public class PhysicsCollisionEvent extends Event
{
public static const COLLISION :String = "collision";
public var behaviourA :RigidBodyBehaviour;
public var behaviourB :RigidBodyBehaviour;
public var position :Point; // In world space
public var normal :Point; // Points from A->B;
public var normalImpulse :Number; // In newtons
public var tangentImpulse :Number; // In newtons
public function PhysicsCollisionEvent(type:String, behaviourA:RigidBodyBehaviour, behaviourB:RigidBodyBehaviour, position:Point, normal:Point, normalImpulse:Number, tangentImpulse:Number)
{
super(type);
this.behaviourA = behaviourA;
this.behaviourB = behaviourB;
this.position = position;
this.normal = normal;
this.normalImpulse = normalImpulse;
this.tangentImpulse = tangentImpulse;
}
}
} |
package ui
{
import model.ServerSettings;
public interface IOwnServerSetupHandler
{
function onOwnServerSetupConnect(serverSettings:ServerSettings):void;
}
} |
/*
Feathers
Copyright 2012-2013 Joshua Tynjala. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
package feathers.dragDrop
{
import feathers.core.PopUpManager;
import feathers.events.DragDropEvent;
import feathers.utils.Substitute;
import flash.errors.IllegalOperationError;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.ui.Keyboard;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Stage;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
/**
* Handles drag and drop operations based on Starling touch events.
*
* @see IDragSource
* @see IDropTarget
* @see DragData
*/
public class DragDropManager
{
/**
* @private
*/
private static const HELPER_POINT:Point = new Point();
/**
* @private
*/
private static const HELPER_TOUCHES_VECTOR:Vector.<Touch> = new <Touch>[];
/**
* @private
*/
protected static var _touchPointID:int = -1;
/**
* The ID of the touch that initiated the current drag. Returns <code>-1</code>
* if there is not an active drag action. In multi-touch applications,
* knowing the touch ID is useful if additional actions need to happen
* using the same touch.
*/
public static function get touchPointID():int
{
return _touchPointID;
}
/**
* @private
*/
protected static var _dragSource:IDragSource;
/**
* The <code>IDragSource</code> that started the current drag.
*/
public static function get dragSource():IDragSource
{
return _dragSource;
}
/**
* @private
*/
protected static var _dragData:DragData;
/**
* Determines if the drag and drop manager is currently handling a drag.
* Only one drag may be active at a time.
*/
public static function get isDragging():Boolean
{
return _dragData != null;
}
/**
* The data associated with the current drag. Returns <code>null</code>
* if there is not a current drag.
*/
public static function get dragData():DragData
{
return _dragData;
}
/**
* @private
* The current target of the current drag.
*/
protected static var dropTarget:IDropTarget;
/**
* @private
* Indicates if the current drag has been accepted by the dropTarget.
*/
protected static var isAccepted:Boolean = false;
/**
* @private
* The avatar for the current drag data.
*/
protected static var avatar:DisplayObject;
/**
* @private
*/
protected static var avatarOffsetX:Number;
/**
* @private
*/
protected static var avatarOffsetY:Number;
/**
* @private
*/
protected static var dropTargetLocalX:Number;
/**
* @private
*/
protected static var dropTargetLocalY:Number;
/**
* @private
*/
protected static var avatarOldTouchable:Boolean;
/**
* Starts a new drag. If another drag is currently active, it is
* immediately cancelled. Includes an optional "avatar", a visual
* representation of the data that is being dragged.
*/
public static function startDrag(source:IDragSource, touch:Touch, data:DragData, dragAvatar:DisplayObject = null, dragAvatarOffsetX:Number = 0, dragAvatarOffsetY:Number = 0):void
{
if(isDragging)
{
cancelDrag();
}
if(!source)
{
throw new ArgumentError("Drag source cannot be null.");
}
if(!data)
{
throw new ArgumentError("Drag data cannot be null.");
}
_dragSource = source;
_dragData = data;
_touchPointID = touch.id;
avatar = dragAvatar;
avatarOffsetX = dragAvatarOffsetX;
avatarOffsetY = dragAvatarOffsetY;
touch.getLocation(Starling.current.stage, HELPER_POINT);
if(avatar)
{
avatarOldTouchable = avatar.touchable;
avatar.touchable = false;
avatar.x = HELPER_POINT.x + avatarOffsetX;
avatar.y = HELPER_POINT.y + avatarOffsetY;
PopUpManager.addPopUp(avatar, false, false);
}
Starling.current.stage.addEventListener(TouchEvent.TOUCH, stage_touchHandler);
Starling.current.nativeStage.addEventListener(KeyboardEvent.KEY_DOWN, nativeStage_keyDownHandler, false, 0, true);
_dragSource.dispatchEvent(new DragDropEvent(DragDropEvent.DRAG_START, data, false));
updateDropTarget(HELPER_POINT);
}
/**
* Tells the drag and drop manager if the target will accept the current
* drop. Meant to be called in a listener for the target's
* <code>DragDropEvent.DRAG_ENTER</code> event.
*/
public static function acceptDrag(target:IDropTarget):void
{
if(dropTarget != target)
{
throw new ArgumentError("Drop target cannot accept a drag at this time. Acceptance may only happen after the DragDropEvent.DRAG_ENTER event is dispatched and before the DragDropEvent.DRAG_EXIT event is dispatched.");
}
isAccepted = true;
}
/**
* Immediately cancels the current drag.
*/
public static function cancelDrag():void
{
if(!isDragging)
{
return;
}
completeDrag(false);
}
/**
* @private
*/
protected static function completeDrag(isDropped:Boolean):void
{
if(!isDragging)
{
throw new IllegalOperationError("Drag cannot be completed because none is currently active.");
}
if(dropTarget)
{
dropTarget.dispatchEvent(new DragDropEvent(DragDropEvent.DRAG_EXIT, _dragData, false, dropTargetLocalX, dropTargetLocalY));
dropTarget = null;
}
const source:IDragSource = _dragSource;
const data:DragData = _dragData;
cleanup();
source.dispatchEvent(new DragDropEvent(DragDropEvent.DRAG_COMPLETE, _dragData, isDropped));
}
/**
* @private
*/
protected static function cleanup():void
{
if(avatar)
{
//may have been removed from parent already in the drop listener
if(PopUpManager.isPopUp(avatar))
{
PopUpManager.removePopUp(avatar);
}
avatar.touchable = avatarOldTouchable;
avatar = null;
}
Starling.current.stage.removeEventListener(TouchEvent.TOUCH, stage_touchHandler);
Starling.current.nativeStage.removeEventListener(KeyboardEvent.KEY_DOWN, nativeStage_keyDownHandler);
_dragSource = null;
_dragData = null;
}
/**
* @private
*/
protected static function updateDropTarget(location:Point):void
{
var target:DisplayObject = Starling.current.stage.hitTest(location, true);
while(target && !(target is IDropTarget))
{
target = target.parent;
}
if(target)
{
target.globalToLocal(location, location);
}
if(target != dropTarget)
{
if(dropTarget)
{
//notice that we can reuse the previously saved location
dropTarget.dispatchEvent(new DragDropEvent(DragDropEvent.DRAG_EXIT, _dragData, false, dropTargetLocalX, dropTargetLocalY));
}
dropTarget = IDropTarget(target);
isAccepted = false;
if(dropTarget)
{
dropTargetLocalX = location.x;
dropTargetLocalY = location.y;
dropTarget.dispatchEvent(new DragDropEvent(DragDropEvent.DRAG_ENTER, _dragData, false, dropTargetLocalX, dropTargetLocalY));
}
}
else if(dropTarget)
{
dropTargetLocalX = location.x;
dropTargetLocalY = location.y;
dropTarget.dispatchEvent(new DragDropEvent(DragDropEvent.DRAG_MOVE, _dragData, false, dropTargetLocalX, dropTargetLocalY));
}
}
/**
* @private
*/
protected static function nativeStage_keyDownHandler(event:KeyboardEvent):void
{
if(event.keyCode == Substitute.KEYBOARD_BACK || event.keyCode == Keyboard.BACK)
{
event.preventDefault();
cancelDrag();
}
}
/**
* @private
*/
protected static function stage_touchHandler(event:TouchEvent):void
{
const stage:Stage = Starling.current.stage;
const touches:Vector.<Touch> = event.getTouches(stage, null, HELPER_TOUCHES_VECTOR);
if(touches.length == 0 || _touchPointID < 0)
{
HELPER_TOUCHES_VECTOR.length = 0;
return;
}
var touch:Touch;
for each(var currentTouch:Touch in touches)
{
if(currentTouch.id == _touchPointID)
{
touch = currentTouch;
break;
}
}
if(!touch)
{
HELPER_TOUCHES_VECTOR.length = 0;
return;
}
if(touch.phase == TouchPhase.MOVED)
{
touch.getLocation(stage, HELPER_POINT);
if(avatar)
{
avatar.x = HELPER_POINT.x + avatarOffsetX;
avatar.y = HELPER_POINT.y + avatarOffsetY;
}
updateDropTarget(HELPER_POINT);
}
else if(touch.phase == TouchPhase.ENDED)
{
_touchPointID = -1;
var isDropped:Boolean = false;
if(dropTarget && isAccepted)
{
dropTarget.dispatchEvent(new DragDropEvent(DragDropEvent.DRAG_DROP, _dragData, true, dropTargetLocalX, dropTargetLocalY));
isDropped = true;
}
dropTarget = null;
completeDrag(isDropped);
}
HELPER_TOUCHES_VECTOR.length = 0;
}
}
}
|
package org.fatlib.events
{
import flash.events.Event;
public class TextInputEvent extends Event
{
public static const TEXT_INPUT:String = 'onTextInput';
private var _text:String;
public function TextInputEvent(type:String, text:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
_text = text;
}
public override function clone():Event
{
return new TextInputEvent(type, _text, bubbles, cancelable);
}
public override function toString():String
{
return formatToString("TextInputEvent", "text", "type", "bubbles", "cancelable", "eventPhase");
}
public function get text():String { return _text; }
}
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package errors {
public class SuperInNamespace extends BaseClass {
override ns1 function foo(): String {
return super.foo() + " override";
}
}
}
|
package kabam.rotmg.protip.view {
import com.gskinner.motion.GTween;
import flash.display.Sprite;
import flash.filters.GlowFilter;
public class ProTipView extends Sprite {
private var text:ProTipText;
public function ProTipView() {
this.text = new ProTipText();
this.text.x = 300;
this.text.y = 125;
addChild(this.text);
filters = [new GlowFilter(0, 1, 3, 3, 2, 1)];
mouseEnabled = false;
mouseChildren = false;
}
public function setTip(_arg_1:String):void {
this.text.setTip(_arg_1);
var _local_2:GTween = new GTween(this, 5, {"alpha": 0});
_local_2.delay = 5;
_local_2.onComplete = this.removeSelf;
}
private function removeSelf(_arg_1:GTween):void {
((parent) && (parent.removeChild(this)));
}
}
}//package kabam.rotmg.protip.view
|
/**
* Ear clipping implementation - concave to convex polygon decomposition (Counterclockwise).
* NOTE: Should work only for SIMPLE polygons (not self-intersecting, without holes).
*
* Based on:
*
* @see http://www.box2d.org/forum/viewtopic.php?f=8&t=463&start=0 (JSFL - by mayobutter)
* @see http://www.ewjordan.com/earClip/ (Processing - by Eric Jordan)
* @see http://en.nicoptere.net/?p=16 (AS3 - by Nicolas Barradeau)
* @see http://blog.touchmypixel.com/2008/06/making-convex-polygons-from-concave-ones-ear-clipping/ (AS3 - by Tarwin Stroh-Spijer)
* @see http://headsoft.com.au/ (C# - by Ben Baker)
*
* @author azrafe7
*/
package as3GeomAlgo
{
import flash.geom.Point;
import as3GeomAlgo.PolyTools;
public class EarClipper
{
/**
* Triangulates a polygon.
*
* @param v Array of points defining the polygon.
* @return An array of Triangles resulting from the triangulation.
*/
public static function triangulate(v:Vector.<Point>):Vector.<Vector.<Point>>
{
if (v.length < 3)
return null;
var remList:Vector.<Point> = new Vector.<Point>().concat(v);
var resultList:Vector.<Vector.<Point>> = new Vector.<Vector.<Point>>();
while (remList.length > 3)
{
var earIndex:int = -1;
for (var i:int = 0; i < remList.length; i++)
{
if (isEar(remList, i))
{
earIndex = i;
break;
}
}
if (earIndex == -1)
return null;
var newList:Vector.<Point> = new Vector.<Point>().concat(remList);
newList.splice(earIndex, 1);
var under:int = (earIndex == 0 ? remList.length - 1 : earIndex - 1);
var over:int = (earIndex == remList.length - 1 ? 0 : earIndex + 1);
resultList.push(createCCWTri(remList[earIndex], remList[over], remList[under]));
remList = newList;
}
resultList.push(createCCWTri(remList[1], remList[2], remList[0]));
return resultList;
}
/**
* Merges triangles (defining a triangulated concave polygon) into a set of convex polygons.
*
* @param triangulation An array of triangles defining the concave polygon.
* @return An array of convex polygons being a decomposition of the original concave polygon.
*/
public static function polygonizeTriangles(triangulation:Vector.<Vector.<Point>>):Vector.<Vector.<Point>>
{
var polys:Vector.<Vector.<Point>> = new Vector.<Vector.<Point>>();
if (triangulation == null)
{
return null;
}
else
{
var covered:Vector.<Boolean> = new Vector.<Boolean>();
var i:int = 0;
for (i = 0; i < triangulation.length; i++) covered[i] = false;
var notDone:Boolean = true;
while (notDone)
{
var poly:Vector.<Point> = null;
var currTri:int = -1;
for (i = 0; i < triangulation.length; i++)
{
if (covered[i]) continue;
currTri = i;
break;
}
if (currTri == -1)
{
notDone = false;
}
else
{
/* mmh */
poly = triangulation[currTri];
covered[currTri] = true;
for (i = 0; i < triangulation.length; i++)
{
if (covered[i]) continue;
var newPoly:Vector.<Point> = addTriangle(poly, triangulation[i]);
if (newPoly == null) continue;
if (isConvex(newPoly))
{
poly = newPoly;
covered[i] = true;
}
}
polys.push(poly);
}
}
}
return polys;
}
/** Checks if vertex `i` is the tip of an ear. */
private static function isEar(v:Vector.<Point>, i:int):Boolean
{
var dx0:Number = 0., dy0:Number = 0., dx1:Number = 0., dy1:Number = 0.;
if (i >= v.length || i < 0 || v.length < 3)
return false;
var upper:int = i + 1;
var lower:int = i - 1;
if (i == 0)
{
dx0 = v[0].x - v[v.length - 1].x;
dy0 = v[0].y - v[v.length - 1].y;
dx1 = v[1].x - v[0].x;
dy1 = v[1].y - v[0].y;
lower = v.length - 1;
}
else if (i == v.length - 1)
{
dx0 = v[i].x - v[i - 1].x;
dy0 = v[i].y - v[i - 1].y;
dx1 = v[0].x - v[i].x;
dy1 = v[0].y - v[i].y;
upper = 0;
}
else
{
dx0 = v[i].x - v[i - 1].x;
dy0 = v[i].y - v[i - 1].y;
dx1 = v[i + 1].x - v[i].x;
dy1 = v[i + 1].y - v[i].y;
}
var cross:Number = (dx0 * dy1) - (dx1 * dy0);
if (cross > 0) return false;
var tri:Vector.<Point> = createCCWTri(v[i], v[upper], v[lower]);
for (var j:int = 0; j < v.length; j++)
{
if (!(j == i || j == lower || j == upper))
{
if (isPointInsideTri(v[j], tri))
return false;
}
}
return true;
}
/** Checks if `point` is inside the triangle. */
static public function isPointInsideTri(point:Point, tri:Vector.<Point>):Boolean
{
var vx2:Number = point.x - tri[0].x;
var vy2:Number = point.y - tri[0].y;
var vx1:Number = tri[1].x - tri[0].x;
var vy1:Number = tri[1].y - tri[0].y;
var vx0:Number = tri[2].x - tri[0].x;
var vy0:Number = tri[2].y - tri[0].y;
var dot00:Number = vx0 * vx0 + vy0 * vy0;
var dot01:Number = vx0 * vx1 + vy0 * vy1;
var dot02:Number = vx0 * vx2 + vy0 * vy2;
var dot11:Number = vx1 * vx1 + vy1 * vy1;
var dot12:Number = vx1 * vx2 + vy1 * vy2;
var invDenom:Number = 1.0 / (dot00 * dot11 - dot01 * dot01);
var u:Number = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v:Number = (dot00 * dot12 - dot01 * dot02) * invDenom;
return ((u > 0) && (v > 0) && (u + v < 1));
}
static public function createCCWTri(point1:Point, point2:Point, point3:Point):Vector.<Point>
{
var points:Vector.<Point> = new <Point>[point1, point2, point3];
PolyTools.makeCCW(points);
return points;
}
/** Assuming the polygon is simple, checks if it is convex. */
static public function isConvex(poly:Vector.<Point>):Boolean
{
var isPositive:Boolean = false;
for (var i:int = 0; i < poly.length; i++)
{
var lower:int = (i == 0 ? poly.length - 1 : i - 1);
var middle:int = i;
var upper:int = (i == poly.length - 1 ? 0 : i + 1);
var dx0:Number = poly[middle].x - poly[lower].x;
var dy0:Number = poly[middle].y - poly[lower].y;
var dx1:Number = poly[upper].x - poly[middle].x;
var dy1:Number = poly[upper].y - poly[middle].y;
var cross:Number = dx0 * dy1 - dx1 * dy0;
// cross product should have same sign
// for each vertex if poly is convex.
var newIsP:Boolean = (cross > 0 ? true : false);
if (i == 0)
isPositive = newIsP;
else if (isPositive != newIsP)
return false;
}
return true;
}
/**
* Tries to add a triangle to the polygon.
* Assumes bitwise equality of join vertices.
*
* @return null if it can't connect properly.
*/
static public function addTriangle(poly:Vector.<Point>, t:Vector.<Point>):Vector.<Point>
{
// first, find vertices that connect
var firstP:int = -1;
var firstT:int = -1;
var secondP:int = -1;
var secondT:int = -1;
var i:int = 0;
for (i = 0; i < poly.length; i++)
{
if (t[0].x == poly[i].x && t[0].y == poly[i].y)
{
if (firstP == -1)
{
firstP = i; firstT = 0;
}
else
{
secondP = i; secondT = 0;
}
}
else if (t[1].x == poly[i].x && t[1].y == poly[i].y)
{
if (firstP == -1)
{
firstP = i; firstT = 1;
}
else
{
secondP = i; secondT = 1;
}
}
else if (t[2].x == poly[i].x && t[2].y == poly[i].y)
{
if (firstP == -1)
{
firstP = i; firstT = 2;
}
else
{
secondP = i; secondT = 2;
}
}
else
{
//trace(t);
//trace(firstP, firstT, secondP, secondT);
}
}
// fix ordering if first should be last vertex of poly
if (firstP == 0 && secondP == poly.length - 1)
{
firstP = poly.length - 1;
secondP = 0;
}
// didn't find it
if (secondP == -1)
return null;
// find tip index on triangle
var tipT:int = 0;
if (tipT == firstT || tipT == secondT) tipT = 1;
if (tipT == firstT || tipT == secondT) tipT = 2;
var newPoints:Vector.<Point> = new Vector.<Point>();
for (i = 0; i < poly.length; i++)
{
newPoints.push(poly[i]);
if (i == firstP)
newPoints.push(t[tipT]);
}
return newPoints;
}
}
} |
package org.osflash.signals
{
import asunit.asserts.*;
import asunit4.async.addAsync;
public class SignalSplitInterfacesTest
{
// Notice the use of the ISignal interface, rather than Signal.
// This makes dispatch() inaccessible unless the ISignal is cast to IDispatcher or Signal.
public var completed:ISignal;
[Before]
public function setUp():void
{
completed = new Signal();
}
[After]
public function tearDown():void
{
Signal(completed).removeAll();
completed = null;
}
[Test]
public function cast_ISignal_to_IDispatcher_and_dispatch():void
{
completed.addOnce( addAsync(onCompleted, 10) );
IDispatcher(completed).dispatch();
}
private function onCompleted():void
{
assertEquals(0, arguments.length);
}
[Test]
public function cast_ISignal_to_Signal_and_dispatch():void
{
completed.addOnce( addAsync(onCompleted, 10) );
Signal(completed).dispatch();
}
}
}
|
// Decompiled by AS3 Sorcerer 6.08
// www.as3sorcerer.com
//kabam.lib.console.controller.RegisterConsoleActionCommand
package kabam.lib.console.controller
{
import kabam.lib.console.model.Console;
import kabam.lib.console.vo.ConsoleAction;
import org.osflash.signals.Signal;
public class RegisterConsoleActionCommand
{
[Inject]
public var console:Console;
[Inject]
public var action:ConsoleAction;
[Inject]
public var trigger:Signal;
public function execute():void
{
this.console.register(this.action, this.trigger);
}
}
}//package kabam.lib.console.controller
|
// =================================================================================================
//
// Starling Framework
// Copyright Gamua GmbH. All Rights Reserved.
//
// This program is free software. You can redistribute and/or modify it
// in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================
package starling.display
{
import starling.errors.AbstractClassError;
/** A class that provides constant values for the states of the Button class. */
public class ButtonState
{
/** @private */
public function ButtonState() { throw new AbstractClassError(); }
/** The button's default state. */
public static const UP:String = "up";
/** The button is pressed. */
public static const DOWN:String = "down";
/** The mouse hovers over the button. */
public static const OVER:String = "over";
/** The button was disabled altogether. */
public static const DISABLED:String = "disabled";
/** Indicates whether the given state string is valid. */
public static function isValid(state:String):Boolean
{
return state == UP || state == DOWN || state == OVER || state == DISABLED;
}
}
} |
/*
* Scratch Project Editor and Player
* Copyright (C) 2014 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// MotionAndPenPrims.as
// John Maloney, April 2010
//
// Scratch motion and pen primitives.
package primitives {
import flash.display.Graphics;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
import blocks.Block;
import interpreter.Interpreter;
import scratch.ScratchObj;
import scratch.ScratchSprite;
import scratch.ScratchStage;
internal class MotionAndPenPrims {
private var app:MBlock;
private var interp:Interpreter;
public function MotionAndPenPrims(app:MBlock, interpreter:Interpreter) {
this.app = app;
this.interp = interpreter;
}
public function addPrimsTo(primTable:Dictionary):void {
primTable["forward:"] = primMove;
primTable["turnRight:"] = primTurnRight;
primTable["turnLeft:"] = primTurnLeft;
primTable["heading:"] = primSetDirection;
primTable["pointTowards:"] = primPointTowards;
primTable["gotoX:y:"] = primGoTo;
primTable["gotoSpriteOrMouse:"] = primGoToSpriteOrMouse;
primTable["glideSecs:toX:y:elapsed:from:"] = primGlide;
primTable["changeXposBy:"] = primChangeX;
primTable["xpos:"] = primSetX;
primTable["changeYposBy:"] = primChangeY;
primTable["ypos:"] = primSetY;
primTable["bounceOffEdge"] = primBounceOffEdge;
primTable["xpos"] = primXPosition;
primTable["ypos"] = primYPosition;
primTable["heading"] = primDirection;
primTable["clearPenTrails"] = primClear;
primTable["putPenDown"] = primPenDown;
primTable["putPenUp"] = primPenUp;
primTable["penColor:"] = primSetPenColor;
primTable["setPenHueTo:"] = primSetPenHue;
primTable["changePenHueBy:"] = primChangePenHue;
primTable["setPenShadeTo:"] = primSetPenShade;
primTable["changePenShadeBy:"] = primChangePenShade;
primTable["penSize:"] = primSetPenSize;
primTable["changePenSizeBy:"] = primChangePenSize;
primTable["stampCostume"] = primStamp;
}
private function primMove(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
var radians:Number = (Math.PI * (90 - s.direction)) / 180;
var d:Number = interp.numarg(b, 0);
moveSpriteTo(s, s.scratchX + (d * Math.cos(radians)), s.scratchY + (d * Math.sin(radians)));
}
private function primTurnRight(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setDirection(s.direction + interp.numarg(b, 0));
if (s.visible) interp.redraw();
}
private function primTurnLeft(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setDirection(s.direction - interp.numarg(b, 0));
if (s.visible) interp.redraw();
}
private function primSetDirection(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setDirection(interp.numarg(b, 0));
if (s.visible) interp.redraw();
}
private function primPointTowards(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
var p:Point = mouseOrSpritePosition(interp.arg(b, 0));
if ((s == null) || (p == null)) return;
var dx:Number = p.x - s.scratchX;
var dy:Number = p.y - s.scratchY;
var angle:Number = 90 - ((Math.atan2(dy, dx) * 180) / Math.PI);
s.setDirection(angle);
if (s.visible) interp.redraw();
}
private function primGoTo(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) moveSpriteTo(s, interp.numarg(b, 0), interp.numarg(b, 1));
}
private function primGoToSpriteOrMouse(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
var p:Point = mouseOrSpritePosition(interp.arg(b, 0));
if ((s == null) || (p == null)) return;
moveSpriteTo(s, p.x, p.y);
}
private function primGlide(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
if (interp.activeThread.firstTime) {
var secs:Number = interp.numarg(b, 0);
var destX:Number = interp.numarg(b, 1);
var destY:Number = interp.numarg(b, 2);
if (secs <= 0) {
moveSpriteTo(s, destX, destY);
return;
}
// record state: [0]start msecs, [1]duration, [2]startX, [3]startY, [4]endX, [5]endY
interp.activeThread.tmpObj =
[interp.currentMSecs, 1000 * secs, s.scratchX, s.scratchY, destX, destY];
interp.startTimer(secs);
} else {
var state:Array = interp.activeThread.tmpObj;
if (!interp.checkTimer()) {
// in progress: move to intermediate position along path
var frac:Number = (interp.currentMSecs - state[0]) / state[1];
var newX:Number = state[2] + (frac * (state[4] - state[2]));
var newY:Number = state[3] + (frac * (state[5] - state[3]));
moveSpriteTo(s, newX, newY);
} else {
// finished: move to final position and clear state
moveSpriteTo(s, state[4], state[5]);
interp.activeThread.tmpObj = null;
}
}
}
private function mouseOrSpritePosition(arg:String):Point {
var targetSprite:ScratchSprite = interp.targetSprite();
var w:ScratchStage = app.stagePane;
var pt:Point;
switch(arg)
{
case "_mouse_":
pt = new Point(w.scratchMouseX(), w.scratchMouseY());
break;
case "rhp":
pt = new Point(w.width * (Math.random() - 0.5), targetSprite.scratchY);
break;
case "rvp":
pt = new Point(targetSprite.scratchX, w.height * (Math.random() - 0.5));
break;
case "rsp":
pt = new Point(w.width * (Math.random() - 0.5), w.height * (Math.random() - 0.5));
break;
default:
var s:ScratchSprite = app.stagePane.spriteNamed(arg);
if (s == null) return null;
pt = new Point(s.scratchX, s.scratchY);
}
return pt;
}
private function primChangeX(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) moveSpriteTo(s, s.scratchX + interp.numarg(b, 0), s.scratchY);
}
private function primSetX(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) moveSpriteTo(s, interp.numarg(b, 0), s.scratchY);
}
private function primChangeY(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) moveSpriteTo(s, s.scratchX, s.scratchY + interp.numarg(b, 0));
}
private function primSetY(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) moveSpriteTo(s, s.scratchX, interp.numarg(b, 0));
}
private function primBounceOffEdge(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s == null) return;
if (!turnAwayFromEdge(s)) return;
ensureOnStageOnBounce(s);
if (s.visible) interp.redraw();
}
private function primXPosition(b:Block):Number {
var s:ScratchSprite = interp.targetSprite();
return (s != null) ? snapToInteger(s.scratchX) : 0;
}
private function primYPosition(b:Block):Number {
var s:ScratchSprite = interp.targetSprite();
return (s != null) ? snapToInteger(s.scratchY) : 0;
}
private function primDirection(b:Block):Number {
var s:ScratchSprite = interp.targetSprite();
return (s != null) ? snapToInteger(s.direction) : 0;
}
private function snapToInteger(n:Number):Number {
var rounded:Number = Math.round(n);
var delta:Number = n - rounded;
if (delta < 0) delta = -delta;
return (delta < 1e-9) ? rounded : n;
}
private function primClear(b:Block):void {
app.stagePane.clearPenStrokes();
interp.redraw();
}
private function primPenDown(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.penIsDown = true;
stroke(s, s.scratchX, s.scratchY, s.scratchX + 0.2, s.scratchY + 0.2);
interp.redraw();
}
private function primPenUp(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.penIsDown = false;
}
private function primSetPenColor(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setPenColor(interp.numarg(b, 0));
}
private function primSetPenHue(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setPenHue(interp.numarg(b, 0));
}
private function primChangePenHue(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setPenHue(s.penHue + interp.numarg(b, 0));
}
private function primSetPenShade(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setPenShade(interp.numarg(b, 0));
}
private function primChangePenShade(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setPenShade(s.penShade + interp.numarg(b, 0));
}
private function primSetPenSize(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setPenSize(Math.max(1, Math.min(960, Math.round(interp.numarg(b, 0)))));
}
private function primChangePenSize(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
if (s != null) s.setPenSize(s.penWidth + interp.numarg(b, 0));
}
private function primStamp(b:Block):void {
var s:ScratchSprite = interp.targetSprite();
doStamp(s, s.img.transform.colorTransform.alphaMultiplier);
}
private function doStamp(s:ScratchSprite, stampAlpha:Number):void {
if (s == null) return;
app.stagePane.stampSprite(s, stampAlpha);
interp.redraw();
}
private function moveSpriteTo(s:ScratchSprite, newX:Number, newY:Number):void {
if (!(s.parent is ScratchStage)) return; // don't move while being dragged
var oldX:Number = s.scratchX;
var oldY:Number = s.scratchY;
s.setScratchXY(newX, newY);
s.keepOnStage();
if (s.penIsDown) stroke(s, oldX, oldY, s.scratchX, s.scratchY);
if ((s.penIsDown) || (s.visible)) interp.redraw();
}
private function stroke(s:ScratchSprite, oldX:Number, oldY:Number, newX:Number, newY:Number):void {
var g:Graphics = app.stagePane.newPenStrokes.graphics;
g.lineStyle(s.penWidth, s.penColorCache);
g.moveTo(240 + oldX, 180 - oldY);
g.lineTo(240 + newX, 180 - newY);
//trace('pen line('+oldX+', '+oldY+', '+newX+', '+newY+')');
app.stagePane.penActivity = true;
}
private function turnAwayFromEdge(s:ScratchSprite):Boolean {
// turn away from the nearest edge if it's close enough; otherwise do nothing
// Note: comparisions are in the stage coordinates, with origin (0, 0)
// use bounding rect of the sprite to account for costume rotation and scale
var r:Rectangle = s.getRect(app.stagePane);
// measure distance to edges
var d1:Number = Math.max(0, r.left);
var d2:Number = Math.max(0, r.top);
var d3:Number = Math.max(0, ScratchObj.STAGEW - r.right);
var d4:Number = Math.max(0, ScratchObj.STAGEH - r.bottom);
// find the nearest edge
var e:int = 0, minDist:Number = 100000;
if (d1 < minDist) { minDist = d1; e = 1 }
if (d2 < minDist) { minDist = d2; e = 2 }
if (d3 < minDist) { minDist = d3; e = 3 }
if (d4 < minDist) { minDist = d4; e = 4 }
if (minDist > 0) return false; // not touching to any edge
// point away from nearest edge
var radians:Number = ((90 - s.direction) * Math.PI) / 180;
var dx:Number = Math.cos(radians);
var dy:Number = -Math.sin(radians);
if (e == 1) { dx = Math.max(0.2, Math.abs(dx)) }
if (e == 2) { dy = Math.max(0.2, Math.abs(dy)) }
if (e == 3) { dx = 0 - Math.max(0.2, Math.abs(dx)) }
if (e == 4) { dy = 0 - Math.max(0.2, Math.abs(dy)) }
var newDir:Number = ((180 * Math.atan2(dy, dx)) / Math.PI) + 90;
s.setDirection(newDir);
return true;
}
private function ensureOnStageOnBounce(s:ScratchSprite):void {
var r:Rectangle = s.getRect(app.stagePane);
if (r.left < 0) moveSpriteTo(s, s.scratchX - r.left, s.scratchY);
if (r.top < 0) moveSpriteTo(s, s.scratchX, s.scratchY + r.top);
if (r.right > ScratchObj.STAGEW) {
moveSpriteTo(s, s.scratchX - (r.right - ScratchObj.STAGEW), s.scratchY);
}
if (r.bottom > ScratchObj.STAGEH) {
moveSpriteTo(s, s.scratchX, s.scratchY + (r.bottom - ScratchObj.STAGEH));
}
}
}}
|
/*
* Copyright 2010 Swiz Framework Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.swizframework.processors
{
import flash.events.IEventDispatcher;
import org.swizframework.core.Bean;
import org.swizframework.core.SwizConfig;
import org.swizframework.reflection.IMetadataTag;
import org.swizframework.reflection.MetadataArg;
/**
* Dispatcher Processor
*/
public class DispatcherProcessor extends BaseMetadataProcessor
{
// ========================================
// protected static constants
// ========================================
protected static const DISPATCHER:String = "Dispatcher";
// ========================================
// public properties
// ========================================
/**
*
*/
override public function get priority():int
{
return ProcessorPriority.DISPATCHER;
}
// ========================================
// constructor
// ========================================
/**
* Constructor
*/
public function DispatcherProcessor( metadataNames:Array = null )
{
super( ( metadataNames == null ) ? [ DISPATCHER ] : metadataNames );
}
// ========================================
// public methods
// ========================================
/**
* @inheritDoc
*/
override public function setUpMetadataTag( metadataTag:IMetadataTag, bean:Bean ):void
{
var scope:String;
if( metadataTag.hasArg( "scope" ) )
scope = metadataTag.getArg( "scope" ).value;
else if( metadataTag.args.length > 0 && MetadataArg(metadataTag.args[0]).key == "" )
scope = MetadataArg(metadataTag.args[0]).value;
var dispatcher:IEventDispatcher = null;
// if the mediate tag defines a scope, set proper dispatcher, else use defaults
if( scope == SwizConfig.GLOBAL_DISPATCHER )
dispatcher = swiz.globalDispatcher;
else if( scope == SwizConfig.LOCAL_DISPATCHER )
dispatcher = swiz.dispatcher;
else
dispatcher = swiz.config.defaultDispatcher == SwizConfig.LOCAL_DISPATCHER ? swiz.dispatcher : swiz.globalDispatcher;
bean.source[ metadataTag.host.name ] = dispatcher;
}
/**
* @inheritDoc
*/
override public function tearDownMetadataTag( metadataTag:IMetadataTag, bean:Bean ):void
{
bean.source[ metadataTag.host.name ] = null;
}
}
} |
/**
* VERSION: 2.21
* DATE: 2011-02-07
* AS3
* UPDATES AND DOCS AT: http://www.greensock.com
**/
package com.greensock.plugins {
import com.greensock.TweenLite;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.filters.BlurFilter;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.getDefinitionByName;
/**
* MotionBlurPlugin provides an easy way to apply a directional blur to a DisplayObject based on its velocity
* and angle of movement in 2D (x/y). This creates a much more realistic effect than a standard BlurFilter for
* several reasons:
* <ol>
* <li>A regular BlurFilter is limited to blurring horizontally and/or vertically whereas the motionBlur
* gets applied at the angle at which the object is moving.</li>
*
* <li>A BlurFilter tween has static start/end values whereas a motionBlur tween dynamically adjusts the
* values on-the-fly during the tween based on the velocity of the object. So if you use a <code>Strong.easeInOut</code>
* for example, the strength of the blur will start out low, then increase as the object moves faster, and
* reduce again towards the end of the tween.</li>
* </ol>
*
* motionBlur even works on bezier/bezierThrough tweens!<br /><br />
*
* To accomplish the effect, MotionBlurPlugin creates a Bitmap that it places over the original object, changing
* alpha of the original to [almost] zero during the course of the tween. The original DisplayObject still follows the
* course of the tween, so MouseEvents are properly dispatched. You shouldn't notice any loss of interactivity.
* The DisplayObject can also have animated contents - MotionBlurPlugin automatically updates on every frame.
* Be aware, however, that as with most filter effects, MotionBlurPlugin is somewhat CPU-intensive, so it is not
* recommended that you tween large quantities of objects simultaneously. You can activate <code>fastMode</code>
* to significantly speed up rendering if the object's contents and size/color doesn't need to change during the
* course of the tween. <br /><br />
*
* motionBlur recognizes the following properties:
* <ul>
* <li><b>strength : Number</b> - Determines the strength of the blur. The default is 1. For a more powerful
* blur, increase the number. Or reduce it to make the effect more subtle.</li>
*
* <li><b>fastMode : Boolean</b> - Setting fastMode to <code>true</code> will significantly improve rendering
* performance but it is only appropriate for situations when the target object's contents,
* size, color, filters, etc. do not need to change during the course of the tween. It works
* by essentially taking a BitmapData snapshot of the target object at the beginning of the
* tween and then reuses that throughout the tween, blurring it appropriately. The default
* value for <code>fastMode</code> is <code>false</code>.</li>
*
* <li><b>quality : int</b> - The lower the quality, the less CPU-intensive the effect will be. Options
* are 1, 2, or 3. The default is 2.</li>
*
* <li><b>padding : int</b> - padding controls the amount of space around the edges of the target object that is included
* in the BitmapData capture (the default is 10 pixels). If the target object has filters applied to
* it like a GlowFilter or DropShadowFilter that extend beyond the bounds of the object itself,
* you might need to increase the padding to accommodate the filters. </li>
*
* <li><b>containerClass : Class</b> - MotionBlurPlugin must add a container to the target's parent's display list
* to hold the blurred image during the tween (it gets removed when it's done). By default, a Sprite
* is used unless it senses the presense of the Flex framework (checking <code>getDefinitionByName("mx.managers.SystemManager")</code>)
* in which case it will use a UIComponent in order to comply with Flex requirements (if we
* addChild() a Sprite, Flex throws an error saying it requires a UIComponent). Typically the
* appropriate container class is automatically selected for you (Sprite or UIComponent) but there
* are some extremely rare circumstances under which it may be useful to define the class yourself.
* That's precisely what <code>containerClass</code> is for. Example: <code>containerClass:Sprite</code></li>
* </ul>
*
* You can optionally set motionBlur to the Boolean value of <code>true</code> in order to use the defaults. (see below for examples)<br /><br />
*
* Also note that due to a bug in Flash, if you apply motionBlur to an object that was masked in the Flash IDE it won't work
* properly - you must apply the mask via ActionScript instead (and set both the mask's and the masked object's cacheAsBitmap
* property to true). And another bug in Flash prevents motionBlur from working on objects that have 3D properties applied,
* like <code>z, rotationY, rotationX,</code> or <code>rotationZ</code>.<br /><br />
*
* <b>USAGE:</b><br /><br />
* <code>
* import com.greensock.~~; <br />
* import com.greensock.plugins.~~; <br />
* TweenPlugin.activate([MotionBlurPlugin]); //only do this once in your SWF to activate the plugin <br /><br />
*
* TweenMax.to(mc, 2, {x:400, y:300, motionBlur:{strength:1.5, fastMode:true, padding:15}}); <br /><br />
*
* //or to use the default values, you can simply pass in the Boolean "true" instead: <br />
* TweenMax.to(mc, 2, {x:400, y:300, motionBlur:true}); <br /><br />
* </code>
*
* MotionBlurPlugin is a <a href="http://www.greensock.com/club/">Club GreenSock</a> membership benefit.
* You must have a valid membership to use this class without violating the terms of use. Visit
* <a href="http://www.greensock.com/club/">http://www.greensock.com/club/</a> to sign up or get more details.<br /><br />
*
* <b>Copyright 2011, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
*
* @author Jack Doyle, jack@greensock.com
*/
public class MotionBlurPlugin extends TweenPlugin {
/** @private **/
public static const API:Number = 1.0; //If the API/Framework for plugins changes in the future, this number helps determine compatibility
/** @private **/
private static const _DEG2RAD:Number = Math.PI / 180; //precomputation for speed
/** @private **/
private static const _RAD2DEG:Number = 180 / Math.PI; //precomputation for speed;
/** @private **/
private static const _point:Point = new Point(0, 0);
/** @private **/
private static const _ct:ColorTransform = new ColorTransform();
/** @private **/
private static const _blankArray:Array = [];
/** @private **/
private static var _classInitted:Boolean;
/** @private **/
private static var _isFlex:Boolean;
/** @private **/
protected var _target:DisplayObject;
/** @private **/
protected var _time:Number;
/** @private **/
protected var _xCurrent:Number;
/** @private **/
protected var _yCurrent:Number;
/** @private **/
protected var _bd:BitmapData;
/** @private **/
protected var _bitmap:Bitmap;
/** @private **/
protected var _strength:Number = 0.05;
/** @private **/
protected var _tween:TweenLite;
/** @private **/
protected var _blur:BlurFilter = new BlurFilter(0, 0, 2);
/** @private **/
protected var _matrix:Matrix = new Matrix();
/** @private **/
protected var _sprite:Sprite;
/** @private **/
protected var _rect:Rectangle;
/** @private **/
protected var _angle:Number;
/** @private **/
protected var _alpha:Number;
/** @private **/
protected var _xRef:Number; //we keep recording this value every time the _target moves at least 2 pixels in either direction in order to accurately determine the angle (small measurements don't produce accurate results).
/** @private **/
protected var _yRef:Number;
/** @private **/
protected var _mask:DisplayObject;
/** @private **/
protected var _parentMask:DisplayObject;
/** @private **/
protected var _padding:int;
/** @private **/
protected var _bdCache:BitmapData;
/** @private **/
protected var _rectCache:Rectangle;
/** @private **/
protected var _cos:Number;
/** @private **/
protected var _sin:Number;
/** @private **/
protected var _smoothing:Boolean;
/** @private **/
protected var _xOffset:Number;
/** @private **/
protected var _yOffset:Number;
/** @private **/
protected var _cached:Boolean;
/** @private **/
protected var _fastMode:Boolean;
/** @private **/
public function MotionBlurPlugin() {
super();
this.propName = "motionBlur"; //name of the special property that the plugin should intercept/manage
this.overwriteProps = ["motionBlur"];
this.onComplete = disable;
this.onDisable = onTweenDisable;
this.priority = -2; //so that the x/y/alpha tweens occur BEFORE the motion blur is applied (we need to determine the angle at which it moved first)
this.activeDisable = true;
}
/** @private **/
override public function onInitTween(target:Object, value:*, tween:TweenLite):Boolean {
if (!(target is DisplayObject)) {
throw new Error("motionBlur tweens only work for DisplayObjects.");
return false;
} else if (value == false) {
_strength = 0;
} else if (typeof(value) == "object") {
_strength = (value.strength || 1) * 0.05;
_blur.quality = int(value.quality) || 2;
_fastMode = Boolean(value.fastMode == true);
}
if (!_classInitted) {
try {
_isFlex = Boolean(getDefinitionByName("mx.managers.SystemManager")); // SystemManager is the first display class created within a Flex application
} catch (e:Error) {
_isFlex = false;
}
_classInitted = true;
}
_target = target as DisplayObject;
_tween = tween;
_time = 0;
_padding = ("padding" in value) ? int(value.padding) : 10;
_smoothing = Boolean(_blur.quality > 1);
_xCurrent = _xRef = _target.x;
_yCurrent = _yRef = _target.y;
_alpha = _target.alpha;
if ("x" in _tween.propTweenLookup && "y" in _tween.propTweenLookup && !_tween.propTweenLookup.x.isPlugin && !_tween.propTweenLookup.y.isPlugin) { //if the tweens are plugins, like bezier or bezierThrough for example, we cannot assume the angle between the current _x/_y and the destination ones is what it should start at!
_angle = Math.PI - Math.atan2(_tween.propTweenLookup.y.change, _tween.propTweenLookup.x.change);
} else if (_tween.vars.x != null || _tween.vars.y != null) {
var x:Number = _tween.vars.x || _target.x;
var y:Number = _tween.vars.y || _target.y;
_angle = Math.PI - Math.atan2((y - _target.y), (x - _target.x));
} else {
_angle = 0;
}
_cos = Math.cos(_angle);
_sin = Math.sin(_angle);
_bd = new BitmapData(_target.width + _padding * 2, _target.height + _padding * 2, true, 0x00FFFFFF);
_bdCache = _bd.clone();
_bitmap = new Bitmap(_bd);
_bitmap.smoothing = _smoothing;
if (typeof(value) == "object" && value.containerClass is Class) {
_sprite = new value.containerClass();
} else if (_isFlex) {
_sprite = new (getDefinitionByName("mx.core.UIComponent"))()
} else {
_sprite = new Sprite();
}
_sprite.mouseEnabled = _sprite.mouseChildren = false;
_sprite.addChild(_bitmap);
_rectCache = new Rectangle(0, 0, _bd.width, _bd.height);
_rect = _rectCache.clone();
if (_target.mask) {
_mask = _target.mask;
}
if (_target.parent && _target.parent.mask) {
_parentMask = _target.parent.mask;
}
return true;
}
/** @private **/
private function disable():void {
if (_strength != 0) {
_target.alpha = _alpha;
}
if (_sprite.parent) {
if (_isFlex && _sprite.parent.hasOwnProperty("removeElement")) { //to accommodate Flex 4 API additions
(_sprite.parent as Object).removeElement(_sprite);
} else {
_sprite.parent.removeChild(_sprite);
}
}
if (_mask) {
_target.mask = _mask;
}
}
/** @private **/
private function onTweenDisable():void {
if (_tween.cachedTime != _tween.cachedDuration && _tween.cachedTime != 0) { //if the tween is on a TimelineLite/Max that eventually completes, another tween might have affected the target's alpha in which case we don't want to mess with it - only disable() if it's mid-tween. Also remember that from() tweens will complete at a value of 0, not 1.
disable();
}
}
/** @private **/
override public function set changeFactor(n:Number):void {
var time:Number = (_tween.cachedTime - _time);
if (time < 0) {
time = -time; //faster than Math.abs(_tween.cachedTime - _time)
}
if (time < 0.0000001) {
return; //number is too small - floating point errors will cause it to render incorrectly
}
var dx:Number = _target.x - _xCurrent;
var dy:Number = _target.y - _yCurrent;
var rx:Number = _target.x - _xRef;
var ry:Number = _target.y - _yRef;
_changeFactor = n;
if (rx > 2 || ry > 2 || rx < -2 || ry < -2) { //setting a tolerance of 2 pixels helps eliminate floating point error funkiness.
_angle = Math.PI - Math.atan2(ry, rx);
_cos = Math.cos(_angle);
_sin = Math.sin(_angle);
_xRef = _target.x;
_yRef = _target.y;
}
_blur.blurX = Math.sqrt(dx * dx + dy * dy) * _strength / time;
_xCurrent = _target.x;
_yCurrent = _target.y;
_time = _tween.cachedTime;
if (n == 0 || _target.parent == null) {
disable();
return;
}
if (_sprite.parent != _target.parent && _target.parent) {
if (_isFlex && _target.parent.hasOwnProperty("addElement")) { //to accommodate Flex 4 API additions
(_target.parent as Object).addElementAt(_sprite, (_target.parent as Object).getElementIndex(_target));
} else {
_target.parent.addChildAt(_sprite, _target.parent.getChildIndex(_target));
}
if (_mask) {
_sprite.mask = _mask;
}
}
if (!_fastMode || !_cached) {
var parentFilters:Array = _target.parent.filters;
if (parentFilters.length != 0) {
_target.parent.filters = _blankArray; //if the parent has filters, it will choke when we move the child object (_target) to x/y of 20,000/20,000.
}
_target.x = _target.y = 20000; //get it away from everything else;
var prevVisible:Boolean = _target.visible;
_target.visible = true;
var bounds:Rectangle = _target.getBounds(_target.parent);
if (bounds.width + _blur.blurX * 2 > 2870) { //in case it's too big and would exceed the 2880 maximum in Flash
_blur.blurX = (bounds.width >= 2870) ? 0 : (2870 - bounds.width) * 0.5;
}
_xOffset = 20000 - bounds.x + _padding;
_yOffset = 20000 - bounds.y + _padding;
bounds.width += _padding * 2;
bounds.height += _padding * 2;
if (bounds.height > _bdCache.height || bounds.width > _bdCache.width) {
_bdCache = new BitmapData(bounds.width, bounds.height, true, 0x00FFFFFF);
_rectCache = new Rectangle(0, 0, _bdCache.width, _bdCache.height);
}
_matrix.tx = _padding - bounds.x;
_matrix.ty = _padding - bounds.y;
_matrix.a = _matrix.d = 1;
_matrix.b = _matrix.c = 0;
bounds.x = bounds.y = 0;
if (_target.alpha == 0.00390625) {
_target.alpha = _alpha;
} else { //means the tween is affecting alpha, so respect it.
_alpha = _target.alpha;
}
if (_parentMask) {
_target.parent.mask = null; //otherwise the mask could interfere with draw()
}
_bdCache.fillRect(_rectCache, 0x00FFFFFF);
_bdCache.draw(_target.parent, _matrix, _ct, "normal", bounds, _smoothing);
if (_parentMask) {
_target.parent.mask = _parentMask;
}
_target.visible = prevVisible;
_target.x = _xCurrent;
_target.y = _yCurrent;
if (parentFilters.length != 0) {
_target.parent.filters = parentFilters;
}
_cached = true;
} else if (_target.alpha != 0.00390625) {
//means the tween is affecting alpha, so respect it.
_alpha = _target.alpha;
}
_target.alpha = 0.00390625; //use 0.00390625 instead of 0 so that we can identify if it was changed outside of this plugin next time through. We were running into trouble with tweens of alpha to 0 not being able to make the final value because of the conditional logic in this plugin.
_matrix.tx = _matrix.ty = 0;
_matrix.a = _cos;
_matrix.b = _sin;
_matrix.c = -_sin;
_matrix.d = _cos;
var width:Number, height:Number, val:Number;
if ((width = _matrix.a * _bdCache.width) < 0) {
_matrix.tx = -width;
width = -width;
}
if ((val = _matrix.c * _bdCache.height) < 0) {
_matrix.tx -= val;
width -= val;
} else {
width += val;
}
if ((height = _matrix.d * _bdCache.height) < 0) {
_matrix.ty = -height;
height = -height;
}
if ((val = _matrix.b * _bdCache.width) < 0) {
_matrix.ty -= val;
height -= val;
} else {
height += val;
}
width += _blur.blurX * 2;
_matrix.tx += _blur.blurX;
if (width > _bd.width || height > _bd.height) {
_bd = _bitmap.bitmapData = new BitmapData(width, height, true, 0x00FFFFFF);
_rect = new Rectangle(0, 0, _bd.width, _bd.height);
_bitmap.smoothing = _smoothing;
}
_bd.fillRect(_rect, 0x00FFFFFF);
_bd.draw(_bdCache, _matrix, _ct, "normal", _rect, _smoothing);
_bd.applyFilter(_bd, _rect, _point, _blur);
_bitmap.x = 0 - (_matrix.a * _xOffset + _matrix.c * _yOffset + _matrix.tx);
_bitmap.y = 0 - (_matrix.d * _yOffset + _matrix.b * _xOffset + _matrix.ty);
_matrix.b = -_sin;
_matrix.c = _sin;
_matrix.tx = _xCurrent;
_matrix.ty = _yCurrent;
_sprite.transform.matrix = _matrix;
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.automation.delegates.components
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import mx.automation.Automation;
import spark.components.Form;
[Mixin]
/**
*
* Defines the methods and properties required to perform instrumentation for the
* Form class.
*
* @see spark.components.Form
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public class SparkFormAutomationImpl extends SparkSkinnableContainerAutomationImpl
{
include "../../../core/Version.as";
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Registers the delegate class for a component class with automation manager.
*
* @param root The SystemManger of the application.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public static function init(root:DisplayObject):void
{
Automation.registerDelegateClass(spark.components.Form, SparkFormAutomationImpl);
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
* @param obj Form object to be automated.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function SparkFormAutomationImpl(obj:spark.components.Form)
{
super(obj);
recordClick = true;
}
/**
* @private
*/
private function get form():spark.components.Form
{
return uiComponent as spark.components.Form;
}
/**
* @private
*/
override protected function clickHandler(event:MouseEvent):void
{
if(isEventTargetApplicabale(event))
{
//var mouseEvent:MouseEvent = new MouseEvent(MouseEvent.CLICK);
recordAutomatableEvent(event);
}
}
/**
* @private
*/
private function isEventTargetApplicabale(event:Event):Boolean
{
// we decide to continue with the mouse events when they are
// on the same container group
return (event.target == form.skin || event.target == form.contentGroup);
}
}
} |
//------------------------------------------------------------------------------
// Copyright (c) 2009-2013 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
package robotlegs.bender.framework.impl
{
import robotlegs.bender.framework.api.IMatcher;
/**
* Robotlegs object processor
*
* @private
*/
public class ObjectProcessor
{
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private const _handlers:Array = [];
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
/**
* Add a handler to process objects that match a given matcher.
* @param matcher The matcher
* @param handler The handler function
*/
public function addObjectHandler(matcher:IMatcher, handler:Function):void
{
_handlers.push(new ObjectHandler(matcher, handler));
}
/**
* Process an object by running it through all registered handlers
* @param object The object instance to process.
*/
public function processObject(object:Object):void
{
for each (var handler:ObjectHandler in _handlers)
{
handler.handle(object);
}
}
}
}
import robotlegs.bender.framework.api.IMatcher;
class ObjectHandler
{
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private var _matcher:IMatcher;
private var _handler:Function;
/*============================================================================*/
/* Constructor */
/*============================================================================*/
/**
* @private
*/
public function ObjectHandler(matcher:IMatcher, handler:Function)
{
_matcher = matcher;
_handler = handler;
}
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
/**
* @private
*/
public function handle(object:Object):void
{
_matcher.matches(object) && _handler(object);
}
}
|
package com.gestureworks.cml.away3d.elements {
import away3d.lights.LightBase;
import com.gestureworks.cml.away3d.utils.StaticLightPickerMod;
import com.gestureworks.cml.core.CMLParser;
import com.gestureworks.cml.elements.State;
import com.gestureworks.cml.interfaces.ICSS;
import com.gestureworks.cml.interfaces.IObject;
import com.gestureworks.cml.interfaces.IState;
import com.gestureworks.cml.utils.ChildList;
import com.gestureworks.cml.utils.document;
import com.gestureworks.cml.utils.StateUtils;
import flash.utils.Dictionary;
/**
* This class creates a LightPicker. It extends the Away3D StaticLightPickerMod class to add CML support.
*/
public class LightPicker extends com.gestureworks.cml.away3d.utils.StaticLightPickerMod implements IObject, ICSS {
// IObject
private var _cmlIndex:int;
private var _childList:ChildList;
// ICSS
private var _className:String;
// 3D
private var _lref:XML;
/**
* @inheritDoc
*/
public function LightPicker(lights:Array=null) {
super(lights);
state = new Dictionary(false);
state[0] = new State(false);
_childList = new ChildList;
}
/**
* @inheritDoc
*/
public function init():void {
var larray:Array = [];
var lightp:Array = [];
var reg:RegExp = /[\s\r\n]*/gim;
if (lref) {
larray = String(lref).split(",");
}
for each(var l:String in larray) {
l = l.replace(reg, '');
if (l.charAt(0) == "#") {
l = l.substr(1);
}
var light:LightBase = document.getElementById(l);
lightp.push(light);
}
lights = lightp;
}
//////////////////////////////////////////////////////////////
// ICML
//////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public function parseCML(cml:XMLList):XMLList {
if (cml.@lights != undefined) {
cml.@lref = cml.@lights;
delete cml.@lights;
}
return CMLParser.parseCML(this, cml);
}
//////////////////////////////////////////////////////////////
// IOBJECT
//////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public var state:Dictionary;
/**
* @inheritDoc
*/
public function get cmlIndex():int { return _cmlIndex; }
public function set cmlIndex(value:int):void {
_cmlIndex = value;
}
/**
* @inheritDoc
*/
public function get childList():ChildList { return _childList; }
public function set childList(value:ChildList):void {
_childList = value;
}
/**
* @inheritDoc
*/
public function postparseCML(cml:XMLList):void {}
/**
* @inheritDoc
*/
public function updateProperties(state:*=0):void {
CMLParser.updateProperties(this, state);
}
/**
* @inheritDoc
*/
override public function dispose():void {
super.dispose();
}
//////////////////////////////////////////////////////////////
// ICSS
//////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public function get className():String { return _className; }
public function set className(value:String):void {
_className = value;
}
//////////////////////////////////////////////////////////////
// 3D
//////////////////////////////////////////////////////////////
public function get lref():XML { return _lref; }
public function set lref(value:XML):void {
_lref = value;
}
}
} |
package {
import flash.media.Sound;
public class Theme extends Sound {
public function Theme() {
// constructor code
}
}
}
|
/*
Copyright (c) 2012 Josh Tynjala
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
package feathers.controls
{
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.Timer;
import feathers.core.FeathersControl;
import feathers.core.PropertyProxy;
import feathers.utils.math.clamp;
import feathers.utils.math.roundToNearest;
import org.osflash.signals.ISignal;
import org.osflash.signals.Signal;
import starling.display.DisplayObject;
import starling.events.Event;
import starling.events.Touch;
import starling.events.TouchEvent;
import starling.events.TouchPhase;
/**
* Select a value between a minimum and a maximum by dragging a thumb over
* a physical range or by using step buttons.
*/
public class ScrollBar extends FeathersControl implements IScrollBar
{
/**
* @private
*/
private static const HELPER_POINT:Point = new Point();
/**
* The scroll bar's thumb may be dragged horizontally (on the x-axis).
*/
public static const DIRECTION_HORIZONTAL:String = "horizontal";
/**
* The scroll bar's thumb may be dragged vertically (on the y-axis).
*/
public static const DIRECTION_VERTICAL:String = "vertical";
/**
* The scroll bar has only one track, stretching to fill the full length
* of the scroll bar. In this layout mode, the minimum track is
* displayed and fills the entire length of the scroll bar. The maximum
* track will not exist.
*/
public static const TRACK_LAYOUT_MODE_SINGLE:String = "single";
/**
* The scroll bar's minimum and maximum track will by resized by
* changing their width and height values. Consider using a special
* display object such as a Scale9Image, Scale3Image or a TiledImage if
* the skins should be resizable.
*/
public static const TRACK_LAYOUT_MODE_STRETCH:String = "stretch";
/**
* The scroll bar's minimum and maximum tracks will be resized and
* cropped using a scrollRect to ensure that the skins maintain a static
* appearance without altering the aspect ratio.
*/
public static const TRACK_LAYOUT_MODE_SCROLL:String = "scroll";
/**
* The default value added to the <code>nameList</code> of the minimum
* track.
*/
public static const DEFAULT_CHILD_NAME_MINIMUM_TRACK:String = "feathers-scroll-bar-minimum-track";
/**
* The default value added to the <code>nameList</code> of the maximum
* track.
*/
public static const DEFAULT_CHILD_NAME_MAXIMUM_TRACK:String = "feathers-scroll-bar-maximum-track";
/**
* The default value added to the <code>nameList</code> of the thumb.
*/
public static const DEFAULT_CHILD_NAME_THUMB:String = "feathers-scroll-bar-thumb";
/**
* The default value added to the <code>nameList</code> of the decrement
* button.
*/
public static const DEFAULT_CHILD_NAME_DECREMENT_BUTTON:String = "feathers-scroll-bar-decrement-button";
/**
* The default value added to the <code>nameList</code> of the increment
* button.
*/
public static const DEFAULT_CHILD_NAME_INCREMENT_BUTTON:String = "feathers-scroll-bar-increment-button";
/**
* Constructor.
*/
public function ScrollBar()
{
this.addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
}
/**
* The value added to the <code>nameList</code> of the minimum track.
*/
protected var minimumTrackName:String = DEFAULT_CHILD_NAME_MINIMUM_TRACK;
/**
* The value added to the <code>nameList</code> of the maximum track.
*/
protected var maximumTrackName:String = DEFAULT_CHILD_NAME_MAXIMUM_TRACK;
/**
* The value added to the <code>nameList</code> of the thumb.
*/
protected var thumbName:String = DEFAULT_CHILD_NAME_THUMB;
/**
* The value added to the <code>nameList</code> of the decrement button.
*/
protected var decrementButtonName:String = DEFAULT_CHILD_NAME_DECREMENT_BUTTON;
/**
* The value added to the <code>nameList</code> of the increment button.
*/
protected var incrementButtonName:String = DEFAULT_CHILD_NAME_INCREMENT_BUTTON;
/**
* @private
*/
protected var thumbOriginalWidth:Number = NaN;
/**
* @private
*/
protected var thumbOriginalHeight:Number = NaN;
/**
* @private
*/
protected var minimumTrackOriginalWidth:Number = NaN;
/**
* @private
*/
protected var minimumTrackOriginalHeight:Number = NaN;
/**
* @private
*/
protected var maximumTrackOriginalWidth:Number = NaN;
/**
* @private
*/
protected var maximumTrackOriginalHeight:Number = NaN;
/**
* @private
*/
protected var decrementButton:Button;
/**
* @private
*/
protected var incrementButton:Button;
/**
* @private
*/
protected var thumb:Button;
/**
* @private
*/
protected var minimumTrack:Button;
/**
* @private
*/
protected var maximumTrack:Button;
/**
* @private
*/
protected var _direction:String = DIRECTION_HORIZONTAL;
/**
* Determines if the scroll bar's thumb can be dragged horizontally or
* vertically. When this value changes, the scroll bar's width and
* height values do not change automatically.
*/
public function get direction():String
{
return this._direction;
}
/**
* @private
*/
public function set direction(value:String):void
{
if(this._direction == value)
{
return;
}
this._direction = value;
this.invalidate(INVALIDATION_FLAG_DATA);
}
/**
* @private
*/
protected var _value:Number = 0;
/**
* @inheritDoc
*/
public function get value():Number
{
return this._value;
}
/**
* @private
*/
public function set value(newValue:Number):void
{
newValue = clamp(newValue, this._minimum, this._maximum);
if(this._value == newValue)
{
return;
}
this._value = newValue;
this.invalidate(INVALIDATION_FLAG_DATA);
if(this.liveDragging || !this.isDragging)
{
this._onChange.dispatch(this);
}
}
/**
* @private
*/
protected var _minimum:Number = 0;
/**
* @inheritDoc
*/
public function get minimum():Number
{
return this._minimum;
}
/**
* @private
*/
public function set minimum(value:Number):void
{
if(this._minimum == value)
{
return;
}
this._minimum = value;
this.invalidate(INVALIDATION_FLAG_DATA);
}
/**
* @private
*/
protected var _maximum:Number = 0;
/**
* @inheritDoc
*/
public function get maximum():Number
{
return this._maximum;
}
/**
* @private
*/
public function set maximum(value:Number):void
{
if(this._maximum == value)
{
return;
}
this._maximum = value;
this.invalidate(INVALIDATION_FLAG_DATA);
}
/**
* @private
*/
protected var _step:Number = 0;
/**
* @inheritDoc
*/
public function get step():Number
{
return this._step;
}
/**
* @private
*/
public function set step(value:Number):void
{
this._step = value;
}
/**
* @private
*/
private var _page:Number = 0;
/**
* @inheritDoc
*/
public function get page():Number
{
return this._page;
}
/**
* @private
*/
public function set page(value:Number):void
{
if(this._page == value)
{
return;
}
this._page = value;
this.invalidate(INVALIDATION_FLAG_DATA);
}
/**
* @private
*/
protected var _paddingTop:Number = 0;
/**
* The minimum space, in pixels, above the content, not
* including the track(s).
*/
public function get paddingTop():Number
{
return this._paddingTop;
}
/**
* @private
*/
public function set paddingTop(value:Number):void
{
if(this._paddingTop == value)
{
return;
}
this._paddingTop = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _paddingRight:Number = 0;
/**
* The minimum space, in pixels, to the right of the content, not
* including the track(s).
*/
public function get paddingRight():Number
{
return this._paddingRight;
}
/**
* @private
*/
public function set paddingRight(value:Number):void
{
if(this._paddingRight == value)
{
return;
}
this._paddingRight = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _paddingBottom:Number = 0;
/**
* The minimum space, in pixels, below the content, not
* including the track(s).
*/
public function get paddingBottom():Number
{
return this._paddingBottom;
}
/**
* @private
*/
public function set paddingBottom(value:Number):void
{
if(this._paddingBottom == value)
{
return;
}
this._paddingBottom = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var _paddingLeft:Number = 0;
/**
* The minimum space, in pixels, to the left of the content, not
* including the track(s).
*/
public function get paddingLeft():Number
{
return this._paddingLeft;
}
/**
* @private
*/
public function set paddingLeft(value:Number):void
{
if(this._paddingLeft == value)
{
return;
}
this._paddingLeft = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var currentRepeatAction:Function;
/**
* @private
*/
protected var _repeatDelay:Number = 0.05;
/**
* @private
*/
protected var _repeatTimer:Timer;
/**
* The time, in seconds, before actions are repeated. The first repeat
* happens five times longer than the others.
*/
public function get repeatDelay():Number
{
return this._repeatDelay;
}
/**
* @private
*/
public function set repeatDelay(value:Number):void
{
if(this._repeatDelay == value)
{
return;
}
this._repeatDelay = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected var isDragging:Boolean = false;
/**
* Determines if the scroll bar dispatches the <code>onChange</code>
* signal every time the thumb moves, or only once it stops moving.
*/
public var liveDragging:Boolean = true;
/**
* @private
*/
protected var _onChange:Signal = new Signal(ScrollBar);
/**
* Dispatched when the <code>value</code> property changes.
*/
public function get onChange():ISignal
{
return this._onChange;
}
/**
* @private
*/
protected var _onDragStart:Signal = new Signal(ScrollBar);
/**
* Dispatched when the user begins dragging the thumb.
*/
public function get onDragStart():ISignal
{
return this._onDragStart;
}
/**
* @private
*/
protected var _onDragEnd:Signal = new Signal(ScrollBar);
/**
* Dispatched when the user stops dragging the thumb.
*/
public function get onDragEnd():ISignal
{
return this._onDragEnd;
}
/**
* @private
*/
protected var _trackLayoutMode:String = TRACK_LAYOUT_MODE_SINGLE;
/**
* Determines how the minimum and maximum track skins are positioned and
* sized.
*/
public function get trackLayoutMode():String
{
return this._trackLayoutMode;
}
/**
* @private
*/
public function set trackLayoutMode(value:String):void
{
if(this._trackLayoutMode == value)
{
return;
}
this._trackLayoutMode = value;
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
private var _minimumTrackProperties:PropertyProxy;
/**
* A set of key/value pairs to be passed down to the scroll bar's
* minimum track sub-component. The minimum track is a
* <code>feathers.controls.Button</code> instance.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb of a <code>SimpleScrollBar</code>
* which is in a <code>Scroller</code> which is in a <code>List</code>,
* you can use the following syntax:</p>
* <pre>list.scrollerProperties.@verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* @see feathers.controls.Button
*/
public function get minimumTrackProperties():Object
{
if(!this._minimumTrackProperties)
{
this._minimumTrackProperties = new PropertyProxy(minimumTrackProperties_onChange);
}
return this._minimumTrackProperties;
}
/**
* @private
*/
public function set minimumTrackProperties(value:Object):void
{
if(this._minimumTrackProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
const newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._minimumTrackProperties)
{
this._minimumTrackProperties.onChange.remove(minimumTrackProperties_onChange);
}
this._minimumTrackProperties = PropertyProxy(value);
if(this._minimumTrackProperties)
{
this._minimumTrackProperties.onChange.add(minimumTrackProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
private var _maximumTrackProperties:PropertyProxy;
/**
* A set of key/value pairs to be passed down to the scroll bar's
* maximum track sub-component. The maximum track is a
* <code>feathers.controls.Button</code> instance.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb of a <code>SimpleScrollBar</code>
* which is in a <code>Scroller</code> which is in a <code>List</code>,
* you can use the following syntax:</p>
* <pre>list.scrollerProperties.@verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* @see feathers.controls.Button
*/
public function get maximumTrackProperties():Object
{
if(!this._maximumTrackProperties)
{
this._maximumTrackProperties = new PropertyProxy(maximumTrackProperties_onChange);
}
return this._maximumTrackProperties;
}
/**
* @private
*/
public function set maximumTrackProperties(value:Object):void
{
if(this._maximumTrackProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
const newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._maximumTrackProperties)
{
this._maximumTrackProperties.onChange.remove(maximumTrackProperties_onChange);
}
this._maximumTrackProperties = PropertyProxy(value);
if(this._maximumTrackProperties)
{
this._maximumTrackProperties.onChange.add(maximumTrackProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
private var _thumbProperties:PropertyProxy;
/**
* A set of key/value pairs to be passed down to the scroll bar's thumb
* sub-component. The thumb is a <code>feathers.controls.Button</code>
* instance.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb of a <code>SimpleScrollBar</code>
* which is in a <code>Scroller</code> which is in a <code>List</code>,
* you can use the following syntax:</p>
* <pre>list.scrollerProperties.@verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* @see feathers.controls.Button
*/
public function get thumbProperties():Object
{
if(!this._thumbProperties)
{
this._thumbProperties = new PropertyProxy(thumbProperties_onChange);
}
return this._thumbProperties;
}
/**
* @private
*/
public function set thumbProperties(value:Object):void
{
if(this._thumbProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
const newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._thumbProperties)
{
this._thumbProperties.onChange.remove(thumbProperties_onChange);
}
this._thumbProperties = PropertyProxy(value);
if(this._thumbProperties)
{
this._thumbProperties.onChange.add(thumbProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
private var _decrementButtonProperties:PropertyProxy;
/**
* A set of key/value pairs to be passed down to the scroll bar's
* decrement button sub-component. The decrement button is a
* <code>feathers.controls.Button</code> instance.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb of a <code>SimpleScrollBar</code>
* which is in a <code>Scroller</code> which is in a <code>List</code>,
* you can use the following syntax:</p>
* <pre>list.scrollerProperties.@verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* @see feathers.controls.Button
*/
public function get decrementButtonProperties():Object
{
if(!this._decrementButtonProperties)
{
this._decrementButtonProperties = new PropertyProxy(decrementButtonProperties_onChange);
}
return this._decrementButtonProperties;
}
/**
* @private
*/
public function set decrementButtonProperties(value:Object):void
{
if(this._decrementButtonProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
const newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._decrementButtonProperties)
{
this._decrementButtonProperties.onChange.remove(decrementButtonProperties_onChange);
}
this._decrementButtonProperties = PropertyProxy(value);
if(this._decrementButtonProperties)
{
this._decrementButtonProperties.onChange.add(decrementButtonProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
private var _incrementButtonProperties:PropertyProxy;
/**
* A set of key/value pairs to be passed down to the scroll bar's
* increment button sub-component. The increment button is a
* <code>feathers.controls.Button</code> instance.
*
* <p>If the subcomponent has its own subcomponents, their properties
* can be set too, using attribute <code>@</code> notation. For example,
* to set the skin on the thumb of a <code>SimpleScrollBar</code>
* which is in a <code>Scroller</code> which is in a <code>List</code>,
* you can use the following syntax:</p>
* <pre>list.scrollerProperties.@verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);</pre>
*
* @see feathers.controls.Button
*/
public function get incrementButtonProperties():Object
{
if(!this._incrementButtonProperties)
{
this._incrementButtonProperties = new PropertyProxy(incrementButtonProperties_onChange);
}
return this._incrementButtonProperties;
}
/**
* @private
*/
public function set incrementButtonProperties(value:Object):void
{
if(this._incrementButtonProperties == value)
{
return;
}
if(!value)
{
value = new PropertyProxy();
}
if(!(value is PropertyProxy))
{
const newValue:PropertyProxy = new PropertyProxy();
for(var propertyName:String in value)
{
newValue[propertyName] = value[propertyName];
}
value = newValue;
}
if(this._incrementButtonProperties)
{
this._incrementButtonProperties.onChange.remove(incrementButtonProperties_onChange);
}
this._incrementButtonProperties = PropertyProxy(value);
if(this._incrementButtonProperties)
{
this._incrementButtonProperties.onChange.add(incrementButtonProperties_onChange);
}
this.invalidate(INVALIDATION_FLAG_STYLES);
}
private var _touchPointID:int = -1;
private var _touchStartX:Number = NaN;
private var _touchStartY:Number = NaN;
private var _thumbStartX:Number = NaN;
private var _thumbStartY:Number = NaN;
private var _touchValue:Number;
/**
* @inheritDoc
*/
override public function dispose():void
{
this._onChange.removeAll();
this._onDragEnd.removeAll();
this._onDragStart.removeAll();
super.dispose();
}
/**
* @private
*/
override protected function initialize():void
{
if(!this.minimumTrack)
{
this.minimumTrack = new Button();
this.minimumTrack.nameList.add(this.minimumTrackName);
this.minimumTrack.label = "";
this.minimumTrack.addEventListener(TouchEvent.TOUCH, track_touchHandler);
this.addChild(this.minimumTrack);
}
if(!this.thumb)
{
this.thumb = new Button();
this.thumb.nameList.add(this.thumbName);
this.thumb.label = "";
this.thumb.keepDownStateOnRollOut = true;
this.thumb.addEventListener(TouchEvent.TOUCH, thumb_touchHandler);
this.addChild(this.thumb);
}
if(!this.decrementButton)
{
this.decrementButton = new Button();
this.decrementButton.nameList.add(this.decrementButtonName);
this.decrementButton.label = "";
this.decrementButton.onPress.add(decrementButton_onPress);
this.decrementButton.onRelease.add(decrementButton_onRelease);
this.addChild(this.decrementButton);
}
if(!this.incrementButton)
{
this.incrementButton = new Button();
this.incrementButton.nameList.add(this.incrementButtonName);
this.incrementButton.label = "";
this.incrementButton.onPress.add(incrementButton_onPress);
this.incrementButton.onRelease.add(incrementButton_onRelease);
this.addChild(this.incrementButton);
}
}
/**
* @private
*/
override protected function draw():void
{
const dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA);
const stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES);
var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE);
const stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE);
this.createOrDestroyMaximumTrackIfNeeded();
if(stylesInvalid)
{
this.refreshThumbStyles();
this.refreshMinimumTrackStyles();
this.refreshMaximumTrackStyles();
this.refreshDecrementButtonStyles();
this.refreshIncrementButtonStyles();
}
if(stateInvalid || dataInvalid)
{
const isEnabled:Boolean = this._isEnabled && this._maximum > this._minimum;
this.thumb.isEnabled = this.minimumTrack.isEnabled =
this.decrementButton.isEnabled = this.incrementButton.isEnabled = isEnabled;
if(this.maximumTrack)
{
this.maximumTrack.isEnabled = isEnabled;
}
}
sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid;
if(dataInvalid || stylesInvalid || sizeInvalid)
{
this.layout();
}
}
/**
* @private
*/
protected function autoSizeIfNeeded():Boolean
{
if(isNaN(this.minimumTrackOriginalWidth) || isNaN(this.minimumTrackOriginalHeight))
{
this.minimumTrack.validate();
this.minimumTrackOriginalWidth = this.minimumTrack.width;
this.minimumTrackOriginalHeight = this.minimumTrack.height;
}
if(this.maximumTrack)
{
if(isNaN(this.maximumTrackOriginalWidth) || isNaN(this.maximumTrackOriginalHeight))
{
this.maximumTrack.validate();
this.maximumTrackOriginalWidth = this.maximumTrack.width;
this.maximumTrackOriginalHeight = this.maximumTrack.height;
}
}
if(isNaN(this.thumbOriginalWidth) || isNaN(this.thumbOriginalHeight))
{
this.thumb.validate();
this.thumbOriginalWidth = this.thumb.width;
this.thumbOriginalHeight = this.thumb.height;
}
this.decrementButton.validate();
this.incrementButton.validate();
const needsWidth:Boolean = isNaN(this.explicitWidth);
const needsHeight:Boolean = isNaN(this.explicitHeight);
if(!needsWidth && !needsHeight)
{
return false;
}
var newWidth:Number = this.explicitWidth;
var newHeight:Number = this.explicitHeight;
if(needsWidth)
{
if(this._direction == DIRECTION_VERTICAL)
{
if(this.maximumTrack)
{
newWidth = Math.max(this.minimumTrackOriginalWidth, this.maximumTrackOriginalWidth);
}
else
{
newWidth = this.minimumTrackOriginalWidth;
}
}
else //horizontal
{
if(this.maximumTrack)
{
newWidth = Math.min(this.minimumTrackOriginalWidth, this.maximumTrackOriginalWidth) + this.thumb.width / 2;
}
else
{
newWidth = this.minimumTrackOriginalWidth;
}
}
}
if(needsHeight)
{
if(this._direction == DIRECTION_VERTICAL)
{
if(this.maximumTrack)
{
newHeight = Math.min(this.minimumTrackOriginalHeight, this.maximumTrackOriginalHeight) + this.thumb.height / 2;
}
else
{
newHeight = this.minimumTrackOriginalHeight;
}
}
else //horizontal
{
if(this.maximumTrack)
{
newHeight = Math.max(this.minimumTrackOriginalHeight, this.maximumTrackOriginalHeight);
}
else
{
newHeight = this.minimumTrackOriginalHeight;
}
}
}
return this.setSizeInternal(newWidth, newHeight, false);
}
/**
* @private
*/
protected function refreshThumbStyles():void
{
for(var propertyName:String in this._thumbProperties)
{
if(this.thumb.hasOwnProperty(propertyName))
{
var propertyValue:Object = this._thumbProperties[propertyName];
this.thumb[propertyName] = propertyValue;
}
}
}
/**
* @private
*/
protected function refreshMinimumTrackStyles():void
{
for(var propertyName:String in this._minimumTrackProperties)
{
if(this.minimumTrack.hasOwnProperty(propertyName))
{
var propertyValue:Object = this._minimumTrackProperties[propertyName];
this.minimumTrack[propertyName] = propertyValue;
}
}
}
/**
* @private
*/
protected function refreshMaximumTrackStyles():void
{
if(!this.maximumTrack)
{
return;
}
for(var propertyName:String in this._maximumTrackProperties)
{
if(this.maximumTrack.hasOwnProperty(propertyName))
{
var propertyValue:Object = this._maximumTrackProperties[propertyName];
this.maximumTrack[propertyName] = propertyValue;
}
}
}
/**
* @private
*/
protected function refreshDecrementButtonStyles():void
{
for(var propertyName:String in this._decrementButtonProperties)
{
if(this.decrementButton.hasOwnProperty(propertyName))
{
var propertyValue:Object = this._decrementButtonProperties[propertyName];
this.decrementButton[propertyName] = propertyValue;
}
}
}
/**
* @private
*/
protected function refreshIncrementButtonStyles():void
{
for(var propertyName:String in this._incrementButtonProperties)
{
if(this.incrementButton.hasOwnProperty(propertyName))
{
var propertyValue:Object = this._incrementButtonProperties[propertyName];
this.incrementButton[propertyName] = propertyValue;
}
}
}
/**
* @private
*/
protected function createOrDestroyMaximumTrackIfNeeded():void
{
if(this._trackLayoutMode == TRACK_LAYOUT_MODE_SCROLL || this._trackLayoutMode == TRACK_LAYOUT_MODE_STRETCH)
{
if(!this.maximumTrack)
{
this.maximumTrack = new Button();
this.maximumTrack.nameList.add(this.maximumTrackName);
this.maximumTrack.label = "";
this.maximumTrack.addEventListener(TouchEvent.TOUCH, track_touchHandler);
this.addChildAt(this.maximumTrack, 1);
}
}
else if(this.maximumTrack) //single
{
this.maximumTrack.removeFromParent(true);
this.maximumTrack = null;
}
}
/**
* @private
*/
protected function layout():void
{
this.layoutStepButtons();
this.layoutThumb();
if(this._trackLayoutMode == TRACK_LAYOUT_MODE_SCROLL)
{
this.layoutTrackWithScrollRect();
}
else if(this._trackLayoutMode == TRACK_LAYOUT_MODE_STRETCH)
{
this.layoutTrackWithStretch();
}
else //single
{
this.layoutTrackWithSingle();
}
}
/**
* @private
*/
protected function layoutStepButtons():void
{
if(this._direction == DIRECTION_VERTICAL)
{
this.decrementButton.x = (this.actualWidth - this.decrementButton.width) / 2;
this.decrementButton.y = 0;
this.incrementButton.x = (this.actualWidth - this.incrementButton.width) / 2;
this.incrementButton.y = this.actualHeight - this.incrementButton.height;
}
else
{
this.decrementButton.x = 0;
this.decrementButton.y = (this.actualHeight - this.decrementButton.height) / 2;
this.incrementButton.x = this.actualWidth - this.incrementButton.width;
this.incrementButton.y = (this.actualHeight - this.incrementButton.height) / 2;
}
}
/**
* @private
*/
protected function layoutThumb():void
{
const range:Number = this._maximum - this._minimum;
this.thumb.visible = range > 0;
if(!this.thumb.visible)
{
return;
}
//this will auto-size the thumb, if needed
this.thumb.validate();
var contentWidth:Number = this.actualWidth - this._paddingLeft - this._paddingRight;
var contentHeight:Number = this.actualHeight - this._paddingTop - this._paddingBottom;
const adjustedPageStep:Number = Math.min(range, this._page == 0 ? range : this._page);
var valueOffset:Number = 0;
if(this._value < this._minimum)
{
valueOffset = (this._minimum - this._value);
}
if(this._value > this._maximum)
{
valueOffset = (this._value - this._maximum);
}
if(this._direction == DIRECTION_VERTICAL)
{
contentHeight -= (this.decrementButton.height + this.incrementButton.height);
const thumbMinHeight:Number = this.thumb.minHeight > 0 ? this.thumb.minHeight : this.thumbOriginalHeight;
this.thumb.width = this.thumbOriginalWidth;
this.thumb.height = Math.max(thumbMinHeight, contentHeight * adjustedPageStep / range);
const trackScrollableHeight:Number = contentHeight - this.thumb.height;
this.thumb.x = (this.actualWidth - this.thumb.width) / 2;
this.thumb.y = this.decrementButton.height + this._paddingTop + Math.max(0, Math.min(trackScrollableHeight, trackScrollableHeight * (this._value - this._minimum) / range));
}
else //horizontal
{
contentWidth -= (this.decrementButton.width + this.decrementButton.width);
const thumbMinWidth:Number = this.thumb.minWidth > 0 ? this.thumb.minWidth : this.thumbOriginalWidth;
this.thumb.width = Math.max(thumbMinWidth, contentWidth * adjustedPageStep / range);
this.thumb.height = this.thumbOriginalHeight;
const trackScrollableWidth:Number = contentWidth - this.thumb.width;
this.thumb.x = this.decrementButton.width + this._paddingLeft + Math.max(0, Math.min(trackScrollableWidth, trackScrollableWidth * (this._value - this._minimum) / range));
this.thumb.y = (this.actualHeight - this.thumb.height) / 2;
}
}
/**
* @private
*/
protected function layoutTrackWithScrollRect():void
{
if(this._direction == DIRECTION_VERTICAL)
{
//we want to scale the skins to match the height of the slider,
//but we also want to keep the original aspect ratio.
const minimumTrackScaledHeight:Number = this.minimumTrackOriginalHeight * this.actualWidth / this.minimumTrackOriginalWidth;
const maximumTrackScaledHeight:Number = this.maximumTrackOriginalHeight * this.actualWidth / this.maximumTrackOriginalWidth;
this.minimumTrack.width = this.actualWidth;
this.minimumTrack.height = minimumTrackScaledHeight;
this.maximumTrack.width = this.actualWidth;
this.maximumTrack.height = maximumTrackScaledHeight;
var middleOfThumb:Number = this.thumb.y + this.thumb.height / 2;
this.minimumTrack.x = 0;
this.minimumTrack.y = 0;
var currentScrollRect:Rectangle = this.minimumTrack.scrollRect;
if(!currentScrollRect)
{
currentScrollRect = new Rectangle();
}
currentScrollRect.x = 0;
currentScrollRect.y = 0;
currentScrollRect.width = this.actualWidth;
currentScrollRect.height = Math.min(minimumTrackScaledHeight, middleOfThumb);
this.minimumTrack.scrollRect = currentScrollRect;
this.maximumTrack.x = 0;
this.maximumTrack.y = Math.max(this.actualHeight - maximumTrackOriginalHeight, middleOfThumb);
currentScrollRect = this.maximumTrack.scrollRect;
if(!currentScrollRect)
{
currentScrollRect = new Rectangle();
}
currentScrollRect.width = this.actualWidth;
currentScrollRect.height = Math.min(maximumTrackScaledHeight, this.actualHeight - middleOfThumb);
currentScrollRect.x = 0;
currentScrollRect.y = Math.max(0, maximumTrackScaledHeight - currentScrollRect.height);
this.maximumTrack.scrollRect = currentScrollRect;
}
else //horizontal
{
//we want to scale the skins to match the height of the slider,
//but we also want to keep the original aspect ratio.
const minimumTrackScaledWidth:Number = this.minimumTrackOriginalWidth * this.actualHeight / this.minimumTrackOriginalHeight;
const maximumTrackScaledWidth:Number = this.maximumTrackOriginalWidth * this.actualHeight / this.maximumTrackOriginalHeight;
this.minimumTrack.width = minimumTrackScaledWidth;
this.minimumTrack.height = this.actualHeight;
this.maximumTrack.width = maximumTrackScaledWidth;
this.maximumTrack.height = this.actualHeight;
middleOfThumb = this.thumb.x + this.thumb.width / 2;
this.minimumTrack.x = 0;
this.minimumTrack.y = 0;
currentScrollRect = this.minimumTrack.scrollRect;
if(!currentScrollRect)
{
currentScrollRect = new Rectangle();
}
currentScrollRect.x = 0;
currentScrollRect.y = 0;
currentScrollRect.width = Math.min(minimumTrackScaledWidth, middleOfThumb);
currentScrollRect.height = this.actualHeight;
this.minimumTrack.scrollRect = currentScrollRect;
this.maximumTrack.x = Math.max(this.actualWidth - maximumTrackScaledWidth, middleOfThumb);
this.maximumTrack.y = 0;
currentScrollRect = this.maximumTrack.scrollRect;
if(!currentScrollRect)
{
currentScrollRect = new Rectangle();
}
currentScrollRect.width = Math.min(maximumTrackScaledWidth, this.actualWidth - middleOfThumb);
currentScrollRect.height = this.actualHeight;
currentScrollRect.x = Math.max(0, maximumTrackScaledWidth - currentScrollRect.width);
currentScrollRect.y = 0;
this.maximumTrack.scrollRect = currentScrollRect;
}
}
/**
* @private
*/
protected function layoutTrackWithStretch():void
{
if(this.minimumTrack.scrollRect)
{
this.minimumTrack.scrollRect = null;
}
if(this.maximumTrack.scrollRect)
{
this.maximumTrack.scrollRect = null;
}
if(this._direction == DIRECTION_VERTICAL)
{
this.minimumTrack.x = 0;
this.minimumTrack.y = 0;
this.minimumTrack.width = this.actualWidth;
this.minimumTrack.height = (this.thumb.y + this.thumb.height / 2) - this.minimumTrack.y;
this.maximumTrack.x = 0;
this.maximumTrack.y = this.minimumTrack.y + this.minimumTrack.height;
this.maximumTrack.width = this.actualWidth;
this.maximumTrack.height = this.actualHeight - this.maximumTrack.y;
}
else //horizontal
{
this.minimumTrack.x = 0;
this.minimumTrack.y = 0;
this.minimumTrack.width = (this.thumb.x + this.thumb.width / 2) - this.minimumTrack.x;
this.minimumTrack.height = this.actualHeight;
this.maximumTrack.x = this.minimumTrack.x + this.minimumTrack.width;
this.maximumTrack.y = 0;
this.maximumTrack.width = this.actualWidth - this.maximumTrack.x;
this.maximumTrack.height = this.actualHeight;
}
}
/**
* @private
*/
protected function layoutTrackWithSingle():void
{
if(this.minimumTrack.scrollRect)
{
this.minimumTrack.scrollRect = null;
}
if(this._direction == DIRECTION_VERTICAL)
{
this.minimumTrack.x = 0;
this.minimumTrack.y = 0;
this.minimumTrack.width = this.actualWidth;
this.minimumTrack.height = this.actualHeight - this.minimumTrack.y;
}
else //horizontal
{
this.minimumTrack.x = 0;
this.minimumTrack.y = 0;
this.minimumTrack.width = this.actualWidth - this.minimumTrack.x;
this.minimumTrack.height = this.actualHeight;
}
}
/**
* @private
*/
protected function locationToValue(location:Point):Number
{
var percentage:Number;
if(this._direction == DIRECTION_VERTICAL)
{
const trackScrollableHeight:Number = this.actualHeight - this.thumb.height - this.decrementButton.height - this.incrementButton.height;
const yOffset:Number = location.y - this._touchStartY;
const yPosition:Number = Math.min(Math.max(0, this._thumbStartY + yOffset - this.decrementButton.height), trackScrollableHeight);
percentage = yPosition / trackScrollableHeight;
}
else //horizontal
{
const trackScrollableWidth:Number = this.actualWidth - this.thumb.width - this.decrementButton.width - this.incrementButton.width;
const xOffset:Number = location.x - this._touchStartX;
const xPosition:Number = Math.min(Math.max(0, this._thumbStartX + xOffset - this.decrementButton.width), trackScrollableWidth);
percentage = xPosition / trackScrollableWidth;
}
return this._minimum + percentage * (this._maximum - this._minimum);
}
/**
* @private
*/
protected function decrement():void
{
this.value -= this._step;
}
/**
* @private
*/
protected function increment():void
{
this.value += this._step;
}
/**
* @private
*/
protected function adjustPage():void
{
if(this._touchValue < this._value)
{
var newValue:Number = Math.max(this._touchValue, this._value - this._page);
if(this._step != 0)
{
newValue = roundToNearest(newValue, this._step);
}
this.value = newValue;
}
else if(this._touchValue > this._value)
{
newValue = Math.min(this._touchValue, this._value + this._page);
if(this._step != 0)
{
newValue = roundToNearest(newValue, this._step);
}
this.value = newValue;
}
}
/**
* @private
*/
protected function startRepeatTimer(action:Function):void
{
this.currentRepeatAction = action;
if(this._repeatDelay > 0)
{
if(!this._repeatTimer)
{
this._repeatTimer = new Timer(this._repeatDelay * 1000);
this._repeatTimer.addEventListener(TimerEvent.TIMER, repeatTimer_timerHandler);
}
else
{
this._repeatTimer.reset();
this._repeatTimer.delay = this._repeatDelay * 1000;
}
this._repeatTimer.start();
}
}
/**
* @private
*/
protected function thumbProperties_onChange(proxy:PropertyProxy, name:Object):void
{
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected function minimumTrackProperties_onChange(proxy:PropertyProxy, name:Object):void
{
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected function maximumTrackProperties_onChange(proxy:PropertyProxy, name:Object):void
{
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected function decrementButtonProperties_onChange(proxy:PropertyProxy, name:Object):void
{
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected function incrementButtonProperties_onChange(proxy:PropertyProxy, name:Object):void
{
this.invalidate(INVALIDATION_FLAG_STYLES);
}
/**
* @private
*/
protected function removedFromStageHandler(event:Event):void
{
this._touchPointID = -1;
if(this._repeatTimer)
{
this._repeatTimer.stop();
}
}
/**
* @private
*/
protected function track_touchHandler(event:TouchEvent):void
{
if(!this._isEnabled)
{
return;
}
const touches:Vector.<Touch> = event.getTouches(DisplayObject(event.currentTarget));
if(touches.length == 0)
{
return;
}
if(this._touchPointID >= 0)
{
var touch:Touch;
for each(var currentTouch:Touch in touches)
{
if(currentTouch.id == this._touchPointID)
{
touch = currentTouch;
break;
}
}
if(!touch)
{
return;
}
if(touch.phase == TouchPhase.ENDED)
{
this._touchPointID = -1;
this._repeatTimer.stop();
return;
}
}
else
{
for each(touch in touches)
{
if(touch.phase == TouchPhase.BEGAN)
{
this._touchPointID = touch.id;
touch.getLocation(this, HELPER_POINT);
this._touchStartX = HELPER_POINT.x;
this._touchStartY = HELPER_POINT.y;
this._thumbStartX = HELPER_POINT.x;
this._thumbStartY = HELPER_POINT.y;
this._touchValue = this.locationToValue(HELPER_POINT);
this.adjustPage();
this.startRepeatTimer(this.adjustPage);
return;
}
}
}
}
/**
* @private
*/
protected function thumb_touchHandler(event:TouchEvent):void
{
if(!this._isEnabled)
{
return;
}
const touches:Vector.<Touch> = event.getTouches(this.thumb);
if(touches.length == 0)
{
return;
}
if(this._touchPointID >= 0)
{
var touch:Touch;
for each(var currentTouch:Touch in touches)
{
if(currentTouch.id == this._touchPointID)
{
touch = currentTouch;
break;
}
}
if(!touch)
{
return;
}
if(touch.phase == TouchPhase.MOVED)
{
touch.getLocation(this, HELPER_POINT);
var newValue:Number = this.locationToValue(HELPER_POINT);
if(this._step != 0)
{
newValue = roundToNearest(newValue, this._step);
}
this.value = newValue;
return;
}
else if(touch.phase == TouchPhase.ENDED)
{
this._touchPointID = -1;
this.isDragging = false;
if(!this.liveDragging)
{
this._onChange.dispatch(this);
}
this._onDragEnd.dispatch(this);
return;
}
}
else
{
for each(touch in touches)
{
if(touch.phase == TouchPhase.BEGAN)
{
touch.getLocation(this, HELPER_POINT);
this._touchPointID = touch.id;
this._thumbStartX = this.thumb.x;
this._thumbStartY = this.thumb.y;
this._touchStartX = HELPER_POINT.x;
this._touchStartY = HELPER_POINT.y;
this.isDragging = true;
this._onDragStart.dispatch(this);
return;
}
}
}
}
/**
* @private
*/
protected function decrementButton_onPress(button:Button):void
{
this.decrement();
this.startRepeatTimer(this.decrement);
}
/**
* @private
*/
protected function decrementButton_onRelease(button:Button):void
{
this._repeatTimer.stop();
}
/**
* @private
*/
protected function incrementButton_onPress(button:Button):void
{
this.increment();
this.startRepeatTimer(this.increment);
}
/**
* @private
*/
protected function incrementButton_onRelease(button:Button):void
{
this._repeatTimer.stop();
}
/**
* @private
*/
protected function repeatTimer_timerHandler(event:TimerEvent):void
{
if(this._repeatTimer.currentCount < 5)
{
return;
}
this.currentRepeatAction();
}
}
}
|
package Ankama_Tooltips.ui
{
import com.ankamagames.berilia.components.Label;
import com.ankamagames.berilia.enums.UIEnum;
import com.ankamagames.berilia.types.graphic.GraphicContainer;
import com.ankamagames.dofus.internalDatacenter.items.WeaponWrapper;
import com.ankamagames.dofus.logic.game.common.spell.SpellModifier;
import com.ankamagames.dofus.logic.game.common.spell.SpellModifiers;
import com.ankamagames.dofus.logic.game.fight.managers.SpellModifiersManager;
import com.ankamagames.dofus.modules.utils.SpellTooltipSettings;
import com.ankamagames.dofus.uiApi.PlayedCharacterApi;
import com.ankamagames.dofus.uiApi.TooltipApi;
import com.ankamagames.jerakine.benchmark.BenchmarkTimer;
import com.ankamagames.jerakine.types.enums.DataStoreEnum;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
public class SpellBannerTooltipUi extends TooltipPinableBaseUi
{
private static var _shortcutColor:String;
[Api(name="TooltipApi")]
public var tooltipApi:TooltipApi;
[Api(name="PlayedCharacterApi")]
public var playerApi:PlayedCharacterApi;
public var lbl_content:Label;
private var _spellWrapper:Object;
private var _shortcutKey:String;
protected var _timerShowSpellTooltip:BenchmarkTimer;
public function SpellBannerTooltipUi()
{
super();
}
override public function main(oParam:Object = null) : void
{
if(!_shortcutColor)
{
_shortcutColor = sysApi.getConfigEntry("colors.shortcut");
_shortcutColor = _shortcutColor.replace("0x","#");
}
this._spellWrapper = oParam.data.spellWrapper;
this._shortcutKey = oParam.data.shortcutKey;
this.lbl_content.text = this._spellWrapper.name;
if(this._shortcutKey && this._shortcutKey != "")
{
this.lbl_content.text += " <font color=\'" + _shortcutColor + "\'>(" + this._shortcutKey + ")</font>";
}
this.lbl_content.multiline = false;
this.lbl_content.wordWrap = false;
this.lbl_content.fullWidthAndHeight();
backgroundCtr.width = this.lbl_content.textfield.width + 12;
backgroundCtr.height = this.lbl_content.textfield.height + 12;
this.tooltipApi.place(oParam.position,oParam.showDirectionalArrow,oParam.point,oParam.relativePoint,oParam.offset);
var delay:int = sysApi.getOption("largeTooltipDelay","dofus");
this._timerShowSpellTooltip = new BenchmarkTimer(delay,1,"SpellBannerTooltipUi._timerShowSpellTooltip");
this._timerShowSpellTooltip.addEventListener(TimerEvent.TIMER,this.onTimer);
this._timerShowSpellTooltip.start();
super.main(oParam);
}
public function unload() : void
{
this.removeTimer();
}
protected function onTimer(e:TimerEvent) : void
{
var cacheCode:String = null;
var setting:String = null;
var ref:GraphicContainer = null;
var weapon:WeaponWrapper = null;
var spellModifiersDict:Dictionary = null;
this.removeTimer();
var criticalMiss:int = this._spellWrapper.playerCriticalFailureRate;
if(this._spellWrapper.isSpellWeapon)
{
weapon = this.playerApi.getWeapon();
if(weapon)
{
cacheCode = "SpellBanner-" + this._spellWrapper.id + "#" + this.tooltipApi.getSpellTooltipCache() + "," + this._shortcutKey + "," + this._spellWrapper.playerCriticalRate + "," + criticalMiss + "," + weapon.objectUID + "," + weapon.setCount + "," + this._spellWrapper.versionNum;
}
else
{
cacheCode = "SpellBanner-" + this._spellWrapper.id + "#-" + this._shortcutKey + "," + this._shortcutKey + "," + this._spellWrapper.playerCriticalRate + "," + criticalMiss + "," + this._spellWrapper.versionNum;
}
}
else
{
cacheCode = "SpellBanner-" + this._spellWrapper.id + "," + this._spellWrapper.spellLevel + "#" + this.tooltipApi.getSpellTooltipCache() + "," + this._spellWrapper.playerCriticalRate + "," + this._spellWrapper.maximalRangeWithBoosts + "," + this._shortcutKey + "," + criticalMiss + "," + this._spellWrapper.versionNum;
}
var spellModifiersList:Vector.<SpellModifier> = null;
var spellModifier:SpellModifier = null;
var spellModifiers:SpellModifiers = SpellModifiersManager.getInstance().getSpellModifiers(this.playerApi.id(),this._spellWrapper.id);
if(spellModifiersDict !== null)
{
spellModifiersDict = spellModifiers.modifiers;
if(spellModifiersDict !== null)
{
spellModifiersList = new Vector.<SpellModifier>();
for each(spellModifier in spellModifiersDict)
{
spellModifiersList.push(spellModifier);
}
}
}
if(spellModifiersList !== null)
{
spellModifiersList.sort(function(spellModifierA:SpellModifier, spellModifierB:SpellModifier):Number
{
if(spellModifierA.id < spellModifierB.id)
{
return -1;
}
if(spellModifierA.id > spellModifierB.id)
{
return 1;
}
return 0;
});
for each(spellModifier in spellModifiersList)
{
cacheCode += "," + spellModifier.totalValue;
}
}
if(sysApi.getOption("useTheoreticalValuesInSpellTooltips","dofus"))
{
cacheCode += ",useTheoreticalValuesInSpellTooltips";
}
var spellTS:SpellTooltipSettings = sysApi.getData("spellTooltipSettings",DataStoreEnum.BIND_ACCOUNT) as SpellTooltipSettings;
if(!spellTS)
{
spellTS = this.tooltipApi.createSpellSettings();
sysApi.setData("spellTooltipSettings",spellTS,DataStoreEnum.BIND_ACCOUNT);
}
var settings:Object = {};
for each(setting in sysApi.getObjectVariables(spellTS))
{
if(setting == "header")
{
settings["name"] = spellTS[setting];
}
else
{
settings[setting] = spellTS[setting];
}
}
settings.smallSpell = true;
settings.contextual = true;
settings.noBg = false;
settings.shortcutKey = this._shortcutKey;
settings.isTheoretical = sysApi.getOption("useTheoreticalValuesInSpellTooltips","dofus");
ref = uiApi.getUi(UIEnum.BANNER).getElement(!!sysApi.isFightContext() ? "tooltipFightPlacer" : "tooltipRoleplayPlacer");
uiApi.showTooltip(this._spellWrapper,ref,false,"spellBanner",8,2,3,null,null,settings,cacheCode);
uiApi.hideTooltip(uiApi.me().name);
}
private function removeTimer() : void
{
if(this._timerShowSpellTooltip)
{
this._timerShowSpellTooltip.removeEventListener(TimerEvent.TIMER,this.onTimer);
this._timerShowSpellTooltip.stop();
this._timerShowSpellTooltip = null;
}
}
}
}
|
package kabam.rotmg.messaging.impl.data {
import flash.utils.IDataInput;
public class ObjectData {
public var objectType_:int;
public var status_:ObjectStatusData;
public function ObjectData() {
this.status_ = new ObjectStatusData();
super();
}
public function parseFromInput(param1:IDataInput) : void {
this.objectType_ = param1.readUnsignedShort();
this.status_.parseFromInput(param1);
}
public function toString() : String {
return "objectType_: " + this.objectType_ + " status_: " + this.status_;
}
}
}
|
package com.videojs.providers{
import com.videojs.VideoJSModel;
import com.videojs.Defaults;
import com.videojs.events.VideoPlaybackEvent;
import com.videojs.structs.ExternalErrorEventName;
import com.videojs.structs.ExternalEventName;
import com.videojs.structs.PlaybackType;
import flash.events.EventDispatcher;
import flash.events.NetStatusEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.media.Video;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.utils.getTimer;
public class RTMPVideoProvider extends EventDispatcher implements IProvider{
private var _nc:NetConnection;
private var _ns:NetStream;
private var _rtmpRetryTimer:Timer;
private var _ncRTMPRetryThreshold:int = 3;
private var _ncRTMPCurrentRetry:int = 0;
private var _throughputTimer:Timer;
private var _currentThroughput:int = 0; // in B/sec
private var _loadStartTimestamp:int;
private var _loadStarted:Boolean = false;
private var _loadCompleted:Boolean = false;
private var _loadErrored:Boolean = false;
private var _pauseOnStart:Boolean = false;
private var _pausePending:Boolean = false;
private var _bufferTime: Number = Defaults.BUFFER_TIME;
private var _bufferTimeMax: Number = Defaults.BUFFER_TIME_MAX;
private var _playerStats:Object = new Object();
private var _videoReference:Video;
private var _src:Object;
private var _metadata:Object;
private var _hasDuration:Boolean = false;
private var _isPlaying:Boolean = false;
private var _isPaused:Boolean = true;
private var _isBuffering:Boolean = false;
private var _isSeeking:Boolean = false;
private var _isLive:Boolean = false;
private var _canSeekAhead:Boolean = false;
private var _hasEnded:Boolean = false;
private var _reportEnded:Boolean = false;
private var _canPlayThrough:Boolean = false;
private var _loop:Boolean = false;
private var _model:VideoJSModel;
public function RTMPVideoProvider(){
_model = VideoJSModel.getInstance();
_metadata = {};
_rtmpRetryTimer = new Timer(25, 1);
_rtmpRetryTimer.addEventListener(TimerEvent.TIMER, onRTMPRetryTimerTick);
_throughputTimer = new Timer(250, 0);
_throughputTimer.addEventListener(TimerEvent.TIMER, onThroughputTimerTick);
}
public function get loop():Boolean{
return _loop;
}
public function set loop(pLoop:Boolean):void{
_loop = pLoop;
}
public function get time():Number{
if(_ns != null){
return _ns.time;
}
else{
return 0;
}
}
public function get bufferTime():Number{
if(_ns != null){
return _ns.bufferTime;
}
return _bufferTime;
}
public function set bufferTime(val:Number):void{
_bufferTime = val;
if(_ns != null){
_ns.bufferTime = _bufferTime;
}
}
public function get bufferTimeMax():Number{
if(_ns != null){
return _ns.bufferTimeMax;
}
return _bufferTimeMax;
}
public function set bufferTimeMax(val:Number):void{
_bufferTimeMax = val;
if(_ns != null){
_ns.bufferTimeMax = _bufferTimeMax;
}
}
public function get playerStats():Object{
if(_ns != null){
_playerStats["bufferTimeMax"] = _ns.bufferTimeMax;
_playerStats["bufferTime"] = _ns.bufferTime;
_playerStats["bufferLength"] = _ns.bufferLength;
_playerStats["bytesTotal"] = _ns.bytesTotal;
_playerStats["currentFPS"] = _ns.currentFPS;
_playerStats["dataReliable"] = _ns.dataReliable;
_playerStats["liveDelay"] = _ns.liveDelay;
_playerStats["maxPauseBufferTime"] = _ns.maxPauseBufferTime;
_playerStats["time"] = _ns.time;
_playerStats["info"] = _ns.info;
_playerStats["farID"] = _ns.farID;
_playerStats["farNonce"] = _ns.farNonce;
_playerStats["inBufferSeek"] = _ns.inBufferSeek;
_playerStats["backBufferTime"] = _ns.backBufferTime;
_playerStats["audioReliable"] = _ns.audioReliable;
_playerStats["backBufferLength"] = _ns.backBufferLength;
}
return _playerStats;
}
public function get duration():Number{
if(_metadata != null && _metadata.duration != undefined){
return Number(_metadata.duration);
}
else{
return 0;
}
}
public function get readyState():int{
// if we have metadata and a known duration
if(_metadata != null && _metadata.duration != undefined){
// if playback has begun
if(_isPlaying){
// if the asset can play through without rebuffering
if(_canPlayThrough){
return 4;
}
// if we don't know if the asset can play through without buffering
else{
// if the buffer is full, we assume we can seek a head at least a keyframe
if(_ns.bufferLength >= _ns.bufferTime){
return 3;
}
// otherwise, we can't be certain that seeking ahead will work
else{
return 2;
}
}
}
// if playback has not begun
else{
return 1;
}
}
// if we have no metadata
else{
return 0;
}
}
public function get networkState():int{
if(!_loadStarted){
return 0;
}
else{
if(_loadCompleted){
return 1;
}
else if(_loadErrored){
return 3;
}
else{
return 2;
}
}
}
public function appendBuffer(bytes:ByteArray):void{
throw "RTMPVideoProvider does not support appendBuffer";
}
public function endOfStream():void{
throw "RTMPVideoProvider does not support endOfStream";
}
public function abort():void{
throw "RTMPVideoProvider does not support abort";
}
public function discontinuity():void{
throw "RTMPVideoProvider does not support discontinuities";
}
public function get buffered():Array{
if(_metadata != null && _metadata.duration != undefined && _metadata.duration > 0){
return [[0, _metadata.duration]];
}
else{
return [];
}
}
public function get bufferedBytesEnd():int{
if(_loadStarted){
return _ns.bytesLoaded;
}
else{
return 0;
}
}
public function get bytesLoaded():int{
return 0;
}
public function get bytesTotal():int{
return 0;
}
public function get playing():Boolean{
return _isPlaying;
}
public function get paused():Boolean{
return _isPaused;
}
public function get ended():Boolean{
return _reportEnded;
}
public function get seeking():Boolean{
return _isSeeking;
}
public function get usesNetStream():Boolean{
return true;
}
public function get metadata():Object{
return _metadata;
}
public function get videoPlaybackQuality():Object{
if (_ns != null &&
_ns.hasOwnProperty('decodedFrames') &&
_ns.info.hasOwnProperty('droppedFrames')) {
return {
droppedVideoFrames: _ns.info.droppedFrames,
totalVideoFrames: _ns.decodedFrames + _ns.info.droppedFrames
};
}
return {};
}
public function set src(pSrc:Object):void{
_hasDuration = false;
if(_isPlaying){
_ns.close();
_loadErrored = false;
_loadStarted = false;
_loadCompleted = false;
_src = pSrc;
initNetConnection();
}
else{
init(pSrc, false);
}
}
public function get srcAsString():String{
if(_src != null){
return _src.url;
}
return "";
}
public function init(pSrc:Object, pAutoplay:Boolean):void{
_src = pSrc;
_loadErrored = false;
_loadStarted = false;
_loadCompleted = false;
// not need here
/*if(pAutoplay){
play();
}*/
}
public function load():void{
_pauseOnStart = true;
_isPlaying = false;
_isPaused = true;
initNetConnection();
}
public function play():void{
// if this is a fresh playback request
if(!_loadStarted){
_pauseOnStart = false;
_isPlaying = false;
_isPaused = false;
_metadata = {};
initNetConnection();
}
// if the asset is paused
else if(_isPaused && !_reportEnded){
_pausePending = false;
_ns.resume();
_isPaused = false;
_model.broadcastEventExternally(ExternalEventName.ON_RESUME);
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_STREAM_START, {}));
}
// video playback ended, seek to beginning
else if(_hasEnded){
_ns.seek(0);
_isPlaying = true;
_isPaused = false;
_hasEnded = false;
_reportEnded = false;
_isBuffering = true;
_model.broadcastEventExternally(ExternalEventName.ON_RESUME);
}
}
public function pause():void{
if(_isPlaying && !_isPaused){
_ns.pause();
_isPaused = true;
_model.broadcastEventExternally(ExternalEventName.ON_PAUSE);
if(_isBuffering){
_pausePending = true;
}
}
else if(_hasEnded && !_isPaused) {
_isPaused = true;
_model.broadcastEventExternally(ExternalEventName.ON_PAUSE);
}
}
public function resume():void{
if(_isPlaying && _isPaused){
_ns.resume();
_isPaused = false;
_model.broadcastEventExternally(ExternalEventName.ON_RESUME);
}
}
public function adjustCurrentTime(pValue:Number):void {
// no-op
}
public function seekBySeconds(pTime:Number):void{
if(_isPlaying){
_isSeeking = true;
_throughputTimer.stop();
_ns.seek(pTime);
_isBuffering = true;
}
else if(_hasEnded){
_ns.seek(pTime);
_isPaused = false;
_isPlaying = true;
_hasEnded = false;
_reportEnded = false;
_isBuffering = true;
_model.broadcastEventExternally(ExternalEventName.ON_RESUME);
}
}
public function seekByPercent(pPercent:Number):void{
if(_isPlaying && _metadata.duration != undefined){
_isSeeking = true;
if(pPercent < 0){
_ns.seek(0);
}
else if(pPercent > 1){
_throughputTimer.stop();
_ns.seek((pPercent / 100) * _metadata.duration);
}
else{
_throughputTimer.stop();
_ns.seek(pPercent * _metadata.duration);
}
}
}
public function stop():void{
if(_isPlaying){
_ns.close();
_isPlaying = false;
_hasEnded = true;
_reportEnded = true;
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_STREAM_CLOSE, {}));
_throughputTimer.stop();
_throughputTimer.reset();
}
}
public function attachVideo(pVideo:Video):void{
_videoReference = pVideo;
}
public function die():void{
if(_videoReference)
{
_videoReference.attachNetStream(null);
}
if( _ns )
{
try {
_ns.close();
_ns = null;
} catch( err: Error ) {
}
}
if( _nc )
{
try {
_nc.close();
_nc = null;
} catch( err: Error ) {
}
}
if(_throughputTimer)
{
try {
_throughputTimer.stop();
_throughputTimer = null;
} catch( err: Error ) {
}
}
if(_rtmpRetryTimer)
{
try {
_rtmpRetryTimer.stop();
_rtmpRetryTimer = null;
} catch( err: Error ) {
}
}
}
private function initNetConnection():void{
if(_nc == null){
_nc = new NetConnection();
_nc.proxyType = 'best'; // needed behind firewalls
_nc.client = this;
_nc.addEventListener(NetStatusEvent.NET_STATUS, onNetConnectionStatus);
}
// initiating an RTMP connection carries some overhead, so if we're already connected
// to a server, and that server is the same as the one that hosts whatever we're trying to
// play, we should skip straight to the playback
if(_nc.connected){
if(_src.connectionURL != _nc.uri){
_nc.connect(_src.connectionURL);
}
else{
initNetStream();
}
}
else{
_nc.connect(_src.connectionURL);
}
}
private function initNetStream():void{
if(_ns != null){
_ns.removeEventListener(NetStatusEvent.NET_STATUS, onNetStreamStatus);
_ns = null;
}
_ns = new NetStream(_nc);
_ns.bufferTime = _bufferTime;
_ns.backBufferTime = _bufferTime;
_ns.bufferTimeMax = _bufferTimeMax;
_ns.maxPauseBufferTime = _bufferTimeMax;
_ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStreamStatus);
_ns.client = this;
_ns.play(_src.streamURL);
_videoReference.attachNetStream(_ns);
_model.broadcastEventExternally(ExternalEventName.ON_LOAD_START);
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_STREAM_READY, {ns:_ns}));
}
private function calculateThroughput():void{
// if it's finished loading, we can kill the calculations and assume it can play through
if(_ns.bytesLoaded == _ns.bytesTotal){
_canPlayThrough = true;
_loadCompleted = true;
_throughputTimer.stop();
_throughputTimer.reset();
_model.broadcastEventExternally(ExternalEventName.ON_CAN_PLAY_THROUGH);
}
// if it's still loading, but we know its duration, we can check to see if the current transfer rate
// will sustain uninterrupted playback - this requires the duration to be known, which is currently
// only accessible via metadata, which isn't parsed until the Flash Player encounters the metadata atom
// in the file itself, which means that this logic will only work if the asset is playing - preload
// won't ever cause this logic to run :(
else if(_ns.bytesTotal > 0 && _metadata != null && _metadata.duration != undefined){
_currentThroughput = _ns.bytesLoaded / ((getTimer() - _loadStartTimestamp) / 1000);
var __estimatedTimeToLoad:Number = (_ns.bytesTotal - _ns.bytesLoaded) * _currentThroughput;
if(__estimatedTimeToLoad <= _metadata.duration){
_throughputTimer.stop();
_throughputTimer.reset();
_canPlayThrough = true;
_model.broadcastEventExternally(ExternalEventName.ON_CAN_PLAY_THROUGH);
}
}
}
private function onRTMPRetryTimerTick(e:TimerEvent):void{
initNetConnection();
}
private function onNetConnectionStatus(e:NetStatusEvent):void{
switch(e.info.code){
case "NetConnection.Connect.Success":
_model.broadcastEventExternally(ExternalEventName.ON_RTMP_CONNECT_SUCCESS);
_nc.call("FCSubscribe", null, _src.streamURL); // try to subscribe
initNetStream();
break;
case "NetConnection.Connect.Failed":
if(_ncRTMPCurrentRetry < _ncRTMPRetryThreshold){
_ncRTMPCurrentRetry++;
_model.broadcastErrorEventExternally(ExternalErrorEventName.RTMP_CONNECT_FAILURE);
_rtmpRetryTimer.start();
_model.broadcastEventExternally(ExternalEventName.ON_RTMP_RETRY);
}
break;
default:
if(e.info.level == "error"){
_model.broadcastErrorEventExternally(e.info.code);
_model.broadcastErrorEventExternally(e.info.description);
}
break;
}
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_NETCONNECTION_STATUS, {info:e.info}));
}
private function onNetStreamStatus(e:NetStatusEvent):void{
switch(e.info.code){
case "NetStream.Play.Reset":
break;
case "NetStream.Buffer.Flush":
break;
case "NetStream.Play.Start":
_canPlayThrough = false;
_hasEnded = false;
_reportEnded = false;
_isBuffering = true;
_currentThroughput = 0;
_loadStartTimestamp = getTimer();
_throughputTimer.reset();
_throughputTimer.start();
_model.broadcastEventExternally(ExternalEventName.ON_BUFFER_EMPTY);
if(_pauseOnStart && _loadStarted == false){
_ns.pause();
_isPaused = true;
}
else{
if (!_isPlaying) {
_model.broadcastEventExternally(ExternalEventName.ON_RESUME);
}
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_STREAM_START, {info:e.info}));
}
_loadStarted = true;
break;
case "NetStream.Buffer.Full":
// Sometimes bug on start NetStream: empty buffer
ExternalInterface.call("console.log", "[VIDEOJS-SWF] onNetStreamStatus: NetStream.Buffer.Full");
ExternalInterface.call("console.log", "[VIDEOJS-SWF] onNetStreamStatus: _ns.bufferTime = " + _ns.bufferTime);
ExternalInterface.call("console.log", "[VIDEOJS-SWF] onNetStreamStatus: _ns.bufferLength = " + _ns.bufferLength);
if(_ns.bufferLength < (_ns.bufferTime *0.8)){
ExternalInterface.call("console.log", "[VIDEOJS-SWF] onNetStreamStatus: _ns.pause()");
_ns.pause();
if(!_pausePending){
ExternalInterface.call("console.log", "[VIDEOJS-SWF] onNetStreamStatus: _ns.resume()");
_ns.resume();
}
}
_isBuffering = false;
_isPlaying = true;
_model.broadcastEventExternally(ExternalEventName.ON_BUFFER_FULL);
_model.broadcastEventExternally(ExternalEventName.ON_CAN_PLAY);
_model.broadcastEventExternally(ExternalEventName.ON_START);
if(_pausePending){
_pausePending = false;
_ns.pause();
_isPaused = true;
}
break;
case "NetStream.Buffer.Empty":
// playback is over
if (_hasEnded) {
if(!_loop){
_isPlaying = false;
_hasEnded = true;
_reportEnded = true;
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_STREAM_CLOSE, {info:e.info}));
_model.broadcastEventExternally(ExternalEventName.ON_PLAYBACK_COMPLETE);
}
else{
_ns.seek(0);
}
}
// other stream buffering
else {
_isBuffering = true;
_model.broadcastEventExternally(ExternalEventName.ON_BUFFER_EMPTY);
}
break;
case "NetStream.Play.Stop":
_hasEnded = true;
_throughputTimer.stop();
_throughputTimer.reset();
break;
case "NetStream.Seek.Notify":
_isPlaying = true;
_isSeeking = false;
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_STREAM_SEEK_COMPLETE, {info:e.info}));
_model.broadcastEventExternally(ExternalEventName.ON_SEEK_COMPLETE);
_model.broadcastEventExternally(ExternalEventName.ON_BUFFER_EMPTY);
_currentThroughput = 0;
_loadStartTimestamp = getTimer();
_throughputTimer.reset();
_throughputTimer.start();
break;
case "NetStream.Play.StreamNotFound":
_loadErrored = true;
_model.broadcastErrorEventExternally(ExternalErrorEventName.SRC_404);
break;
default:
if(e.info.level == "error"){
_model.broadcastErrorEventExternally(e.info.code);
_model.broadcastErrorEventExternally(e.info.description);
}
break;
}
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_NETSTREAM_STATUS, {info:e.info}));
}
private function onThroughputTimerTick(e:TimerEvent):void{
calculateThroughput();
}
public function onMetaData(pMetaData:Object):void{
_metadata = pMetaData;
if(pMetaData.duration != undefined){
_isLive = false;
_canSeekAhead = true;
if (!_hasDuration) {
_hasDuration = true;
_model.broadcastEventExternally(ExternalEventName.ON_DURATION_CHANGE, _metadata.duration);
}
}
else{
_isLive = true;
_canSeekAhead = false;
}
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_META_DATA, {metadata:_metadata}));
_model.broadcastEventExternally(ExternalEventName.ON_METADATA, _metadata);
}
public function onTextData(pTextData:Object):void {
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_TEXT_DATA, {textData:pTextData}));
_model.broadcastEventExternally(ExternalEventName.ON_TEXT_DATA, pTextData);
}
public function onCuePoint(pInfo:Object):void{
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_CUE_POINT, {cuepoint:pInfo}));
}
public function onXMPData(pInfo:Object):void{
_model.broadcastEvent(new VideoPlaybackEvent(VideoPlaybackEvent.ON_XMP_DATA, {cuepoint:pInfo}));
}
public function onPlayStatus(e:Object):void{
}
/**
* Called from FMS during bandwidth detection
*/
public function onBWCheck(... pRest):Number {
return 0;
}
/**
* Called from FMS when bandwidth detection is completed.
*/
public function onBWDone(... pRest):void {
// no op for now but needed by NetConnection
}
/**
* Called from FMS when subscribing to live streams.
*/
public function onFCSubscribe(pInfo:Object):void {
initNetStream();
}
/**
* Called from FMS when unsubscribing to live streams.
*/
public function onFCUnsubscribe(pInfo:Object):void {
// no op for now but needed by NetConnection
}
/**
* Called from FMS for NetStreams. Incorrectly used for NetConnections as well.
* This is here to prevent runtime errors.
*/
public function streamInfo(pObj:Object):void {}
}
}
|
class DashboardPadKeyboard : DashboardThing
{
DashboardPadKeyboard()
{
super();
}
void Render(CSceneVehicleVisState@ vis) override
{
float steerLeft = vis.InputSteer < 0 ? Math::Abs(vis.InputSteer) : 0.0f;
float steerRight = vis.InputSteer > 0 ? vis.InputSteer : 0.0f;
vec2 keySize = vec2((m_size.x - Setting_Keyboard_Spacing * 2) / 3, (m_size.y - Setting_Keyboard_Spacing) / 2);
vec2 sideKeySize = keySize;
vec2 upPos = vec2(keySize.x + Setting_Keyboard_Spacing, 0);
vec2 downPos = vec2(keySize.x + Setting_Keyboard_Spacing, keySize.y + Setting_Keyboard_Spacing);
vec2 leftPos = vec2(0, keySize.y + Setting_Keyboard_Spacing);
vec2 rightPos = vec2(keySize.x * 2 + Setting_Keyboard_Spacing * 2, keySize.y + Setting_Keyboard_Spacing);
if (Setting_Keyboard_Shape == KeyboardShape::Compact) {
sideKeySize.y = m_size.y;
leftPos.y = 0;
rightPos.y = 0;
}
RenderKey(upPos, keySize, Icons::AngleUp, vis.InputGasPedal);
RenderKey(downPos, keySize, Icons::AngleDown, vis.InputIsBraking ? 1.0f : vis.InputBrakePedal);
RenderKey(leftPos, sideKeySize, Icons::AngleLeft, steerLeft, -1);
RenderKey(rightPos, sideKeySize, Icons::AngleRight, steerRight, 1);
}
void RenderKey(const vec2 &in pos, const vec2 &in size, const string &in text, float value, int fillDir = 0)
{
vec4 borderColor = Setting_Keyboard_BorderColor;
if (fillDir == 0) {
borderColor.w *= Math::Abs(value) > 0.1f ? 1.0f : Setting_Keyboard_InactiveAlpha;
} else {
borderColor.w *= Math::Lerp(Setting_Keyboard_InactiveAlpha, 1.0f, value);
}
nvg::BeginPath();
nvg::StrokeWidth(Setting_Keyboard_BorderWidth);
switch (Setting_Keyboard_Shape) {
case KeyboardShape::Rectangle:
case KeyboardShape::Compact:
nvg::RoundedRect(pos.x, pos.y, size.x, size.y, Setting_Keyboard_BorderRadius);
break;
case KeyboardShape::Ellipse:
nvg::Ellipse(pos + size / 2, size.x / 2, size.y / 2);
break;
}
nvg::FillColor(Setting_Keyboard_EmptyFillColor);
nvg::Fill();
if (fillDir == 0) {
if (Math::Abs(value) > 0.1f) {
nvg::FillColor(Setting_Keyboard_FillColor);
nvg::Fill();
}
} else if (value > 0) {
if (fillDir == -1) {
float valueWidth = value * size.x;
nvg::Scissor(size.x - valueWidth, pos.y, valueWidth, size.y);
} else if (fillDir == 1) {
float valueWidth = value * size.x;
nvg::Scissor(pos.x, pos.y, valueWidth, size.y);
}
nvg::FillColor(Setting_Keyboard_FillColor);
nvg::Fill();
nvg::ResetScissor();
}
nvg::StrokeColor(borderColor);
nvg::Stroke();
nvg::BeginPath();
nvg::FontFace(g_font);
nvg::FontSize(size.x / 2);
nvg::FillColor(borderColor);
nvg::TextAlign(nvg::Align::Middle | nvg::Align::Center);
nvg::TextBox(pos.x, pos.y + size.y / 2, size.x, text);
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2007-2010 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package flashx.textLayout.formats
{
/**
* Defines values for setting the <code>textJustify</code> property of the TextLayoutFormat class.
* Default value is INTER_WORD, meaning that extra space in justification is added to the space characters.
* DISTRIBUTE specifies that extra space is added both to space characters and between individual
* letters. Use these values only when setting <code>justificationRule</code> to SPACE.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*
* @see TextLayoutFormat#textJustify
* @see TextLayoutFormat#justificationRule
*/
public final class TextJustify
{
/** Specifies that justification is to add space both to space characters and
* between individual letters.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const DISTRIBUTE:String = "distribute";
/** Specifies that justification is to add space to space characters.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public static const INTER_WORD:String = "interWord";
}
}
|
package com.tinyspeck.engine.view.ui.decorate
{
import com.tinyspeck.engine.control.TSFrontController;
import com.tinyspeck.engine.data.house.HouseExpandCosts;
import com.tinyspeck.engine.data.house.HouseExpandReq;
import com.tinyspeck.engine.data.item.Item;
import com.tinyspeck.engine.data.pc.PC;
import com.tinyspeck.engine.model.TSModelLocator;
import com.tinyspeck.engine.port.AssetManager;
import com.tinyspeck.engine.port.CSSManager;
import com.tinyspeck.engine.port.HouseExpandDialog;
import com.tinyspeck.engine.util.SpriteUtil;
import com.tinyspeck.engine.util.TFUtil;
import com.tinyspeck.engine.view.itemstack.ItemIconView;
import com.tinyspeck.engine.view.util.StaticFilters;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.text.TextField;
public class HouseExpandReqUI extends Sprite
{
private static const ICON_WH:uint = 55;
private var icon_holder:Sprite = new Sprite();
private var status_holder:Sprite = new Sprite();
private var checkmark:DisplayObject;
private var count_tf:TextField = new TextField();
private var name_tf:TextField = new TextField();
private var status_tf:TextField = new TextField();
private var current_req:HouseExpandReq;
private var current_item:Item;
private var rect:Rectangle;
private var status_bg_color:uint;
private var is_built:Boolean;
private var _has_material:Boolean;
public function HouseExpandReqUI(){}
private function buildBase():void {
addChild(icon_holder);
TFUtil.prepTF(count_tf, false);
count_tf.filters = StaticFilters.white3px_GlowA;
count_tf.htmlText = '<p class="house_expand_req_count">99x</p>';
count_tf.y = int(ICON_WH - count_tf.height/2 - 7);
addChild(count_tf);
TFUtil.prepTF(name_tf, false);
name_tf.htmlText = '<p class="house_expand_req_name">placeholder</p>';
name_tf.y = int(count_tf.y + count_tf.height - 8);
addChild(name_tf);
TFUtil.prepTF(status_tf, false);
status_tf.y = -2;
status_holder.addChild(status_tf);
addChild(status_holder);
//mouse
useHandCursor = buttonMode = true;
mouseChildren = false;
addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
//checkmark
checkmark = new AssetManager.instance.assets.expand_check();
status_holder.addChild(checkmark);
//color
status_bg_color = CSSManager.instance.getUintColorValueFromStyle('house_expand_req_need', 'backgroundColor', 0x8a3535);
is_built = true;
}
public function show(req:HouseExpandReq, type:String):void {
if(!is_built) buildBase();
current_req = req;
//show the count
count_tf.htmlText = '<p class="house_expand_req_count">'+req.count+'x</p>';
count_tf.x = int(ICON_WH/2 - count_tf.width/2);
//show the name
current_item = TSModelLocator.instance.worldModel.getItemByTsid(current_req.class_tsid);
name_tf.htmlText = '<p class="house_expand_req_name">'+(current_item ? current_item.label : current_req.class_tsid)+'</p>';
name_tf.x = int(ICON_WH/2 - name_tf.width/2);
//place the icon
showIcon();
//show the status
status_holder.visible = true;
status_holder.y = int(name_tf.y + name_tf.height + 2);
showStatus();
//we need to shift stuff?
jigger();
//clickable?
mouseEnabled = current_item != null;
}
private function showIcon():void {
SpriteUtil.clean(icon_holder);
//if we don't have a real item, show the broken sign
const iiv:ItemIconView = new ItemIconView(current_item ? current_item.tsid : 'broken_sign', ICON_WH);
icon_holder.addChild(iiv);
}
private function showStatus():void {
var need_num:int = current_req.count;
var status_txt:String = '<p class="house_expand_req_status">';
//do we gots the goods?
if(current_item){
const pc:PC = TSModelLocator.instance.worldModel.pc;
const has_how_many:int = pc.hasHowManyItems(current_item.tsid);
need_num -= has_how_many;
}
//we need to show the checkmark?
checkmark.visible = need_num <= 0;
if(need_num > 0){
status_txt += '<span class="house_expand_req_need">Need <b>'+need_num+'</b> more</span>';
}
else {
status_txt += 'Got ’em';
}
status_txt += '</p>';
status_tf.htmlText = status_txt;
status_tf.x = need_num > 0 ? 2 : checkmark.width;
const g:Graphics = status_holder.graphics;
g.clear();
if(need_num > 0){
g.beginFill(status_bg_color);
g.drawRoundRect(0, 0, int(status_tf.width + status_tf.x*2), 15, 6);
}
status_holder.x = int(ICON_WH/2 - status_holder.width/2);
//have enough?
_has_material = need_num <= 0;
}
private function jigger():void {
//I feel like there is a smarter way to do this, but for the life of me I can't remember
var i:int;
var total:int = numChildren;
rect = getBounds(this);
for(i; i < total; i++){
getChildAt(i).x -= rect.x;
}
}
private function onClick(event:MouseEvent):void {
if(!current_item) return;
//open the item info dialog
TSFrontController.instance.showItemInfo(current_item.tsid);
}
public function dispose():void {
//axe the listener
removeEventListener(MouseEvent.CLICK, onClick);
}
public function get has_material():Boolean { return _has_material; }
}
} |
table estOrientInfo
"Extra information on ESTs - calculated by polyInfo program"
(
string chrom; "Reference sequence chromosome or scaffold"
uint chromStart; "Start position in chromosome"
uint chromEnd; "End position in chromosome"
string name; "Accession of EST"
short intronOrientation; "Orientation of introns with respect to EST"
short sizePolyA; "Number of trailing A's"
short revSizePolyA; "Number of trailing A's on reverse strand"
short signalPos; "Position of start of polyA signal relative to end of EST or 0 if no signal"
short revSignalPos;"PolyA signal position on reverse strand if any"
)
|
package PathFinding.finders
{
import PathFinding.core.DiagonalMovement;
import PathFinding.core.Grid;
import PathFinding.core.Node;
/**
* ...
* @author ...
*/
public class JPFMoveDiagonallyIfAtMostOneObstacle extends JumpPointFinderBase
{
public function JPFMoveDiagonallyIfAtMostOneObstacle(opt:Object)
{
super(opt);
}
/**
* Search recursively in the direction (parent -> child), stopping only when a
* jump point is found.
* @protected
* @return {Array<Array<number>>} The x, y coordinate of the jump point
* found, or null if not found
*/
override public function _jump(x:int, y:int, px:int, py:int):Array
{
var grid:Grid = this.grid, dx:int = x - px, dy:int = y - py;
if (!grid.isWalkableAt(x, y))
{
return null;
}
if (this.trackJumpRecursion === true)
{
grid.getNodeAt(x, y).tested = true;
}
if (grid.getNodeAt(x, y) == this.endNode)
{
return [x, y];
}
// check for forced neighbors
// along the diagonal
if (dx !== 0 && dy !== 0)
{
if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy)))
{
return [x, y];
}
// when moving diagonally, must check for vertical/horizontal jump points
if (this._jump(x + dx, y, x, y) || this._jump(x, y + dy, x, y))
{
return [x, y];
}
}
// horizontally/vertically
else
{
if (dx !== 0)
{ // moving along x
if ((grid.isWalkableAt(x + dx, y + 1) && !grid.isWalkableAt(x, y + 1)) || (grid.isWalkableAt(x + dx, y - 1) && !grid.isWalkableAt(x, y - 1)))
{
return [x, y];
}
}
else
{
if ((grid.isWalkableAt(x + 1, y + dy) && !grid.isWalkableAt(x + 1, y)) || (grid.isWalkableAt(x - 1, y + dy) && !grid.isWalkableAt(x - 1, y)))
{
return [x, y];
}
}
}
// moving diagonally, must make sure one of the vertical/horizontal
// neighbors is open to allow the path
if (grid.isWalkableAt(x + dx, y) || grid.isWalkableAt(x, y + dy))
{
return this._jump(x + dx, y + dy, x, y);
}
else
{
return null;
}
}
/**
* Find the neighbors for the given node. If the node has a parent,
* prune the neighbors based on the jump point search algorithm, otherwise
* return all available neighbors.
* @return {Array<Array<number>>} The neighbors found.
*/
override public function _findNeighbors(node:Node):Array
{
var parent:Node = node.parent, x:int = node.x, y:int = node.y, grid:Grid = this.grid, px:int, py:int, nx:int, ny:int, dx:int, dy:int, neighbors:Array = [], neighborNodes:Array, neighborNode:Node, i:int, l:int;
// directed pruning: can ignore most neighbors, unless forced.
if (parent)
{
px = parent.x;
py = parent.y;
// get the normalized direction of travel
dx = (x - px) / Math.max(Math.abs(x - px), 1);
dy = (y - py) / Math.max(Math.abs(y - py), 1);
// search diagonally
if (dx !== 0 && dy !== 0)
{
if (grid.isWalkableAt(x, y + dy))
{
neighbors.push([x, y + dy]);
}
if (grid.isWalkableAt(x + dx, y))
{
neighbors.push([x + dx, y]);
}
if (grid.isWalkableAt(x, y + dy) || grid.isWalkableAt(x + dx, y))
{
neighbors.push([x + dx, y + dy]);
}
if (!grid.isWalkableAt(x - dx, y) && grid.isWalkableAt(x, y + dy))
{
neighbors.push([x - dx, y + dy]);
}
if (!grid.isWalkableAt(x, y - dy) && grid.isWalkableAt(x + dx, y))
{
neighbors.push([x + dx, y - dy]);
}
}
// search horizontally/vertically
else
{
if (dx === 0)
{
if (grid.isWalkableAt(x, y + dy))
{
neighbors.push([x, y + dy]);
if (!grid.isWalkableAt(x + 1, y))
{
neighbors.push([x + 1, y + dy]);
}
if (!grid.isWalkableAt(x - 1, y))
{
neighbors.push([x - 1, y + dy]);
}
}
}
else
{
if (grid.isWalkableAt(x + dx, y))
{
neighbors.push([x + dx, y]);
if (!grid.isWalkableAt(x, y + 1))
{
neighbors.push([x + dx, y + 1]);
}
if (!grid.isWalkableAt(x, y - 1))
{
neighbors.push([x + dx, y - 1]);
}
}
}
}
}
// return all neighbors
else
{
neighborNodes = grid.getNeighbors(node, DiagonalMovement.IfAtMostOneObstacle);
for (i = 0, l = neighborNodes.length; i < l; ++i)
{
neighborNode = neighborNodes[i];
neighbors.push([neighborNode.x, neighborNode.y]);
}
}
return neighbors;
}
}
} |
package com.illuzor.spinner {
import com.illuzor.spinner.controllers.AppController;
import com.illuzor.spinner.tools.ResizeManager;
import com.illuzor.spinner.tools.StorageManager;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Rectangle;
import starling.core.Starling;
import starling.events.Event;
/**
* ...
* @author illuzor // illuzor.com
*/
public class Main extends Sprite {
private var starling:Starling;
private var contextCreated:Boolean;
private var rootCreated:Boolean;
public function Main() {
if (stage) onAdded();
else addEventListener(flash.events.Event.ADDED_TO_STAGE, onAdded);
}
private function onAdded(e:flash.events.Event = null):void {
removeEventListener(flash.events.Event.ADDED_TO_STAGE, onAdded);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
init();
initStarling();
}
private function init():void {
StorageManager.init();
StorageManager.increaseRuns();
ResizeManager.init(stage);
}
private function initStarling():void {
starling = new Starling(Game, stage, new Rectangle(0, 0, stage.stageWidth, stage.stageHeight));
starling.antiAliasing = 16;
starling.start();
starling.addEventListener(starling.events.Event.ROOT_CREATED, onStarlingEvent);
starling.addEventListener(starling.events.Event.CONTEXT3D_CREATE, onStarlingEvent);
starling.addEventListener(starling.events.Event.FATAL_ERROR, onStarlingEvent);
//CONFIG::debug {
starling.showStats = true;
//}
}
private function onStarlingEvent(e:starling.events.Event):void {
switch (e.type) {
case starling.events.Event.CONTEXT3D_CREATE:
trace("[Main] Starling Context3D created");
contextCreated = true;
break;
case starling.events.Event.ROOT_CREATED:
trace("[Main] Starling root created");
rootCreated = true;
break;
case starling.events.Event.FATAL_ERROR:
trace("[Main] Starling Fatal Error");
break;
}
if (contextCreated && rootCreated) {
starling.removeEventListener(starling.events.Event.ROOT_CREATED, onStarlingEvent);
starling.removeEventListener(starling.events.Event.CONTEXT3D_CREATE, onStarlingEvent);
starling.removeEventListener(starling.events.Event.FATAL_ERROR, onStarlingEvent);
ResizeManager.addResize(resize);
AppController.start();
}
}
private function resize(stageWidth:uint, stageHeight:uint):void{
starling.viewPort = new Rectangle(0, 0, stageWidth, stageHeight);
starling.stage.stageWidth = stageWidth;
starling.stage.stageHeight = stageHeight;
}
}
} |
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageOrientation;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.system.Capabilities;
import feathers.examples.layoutExplorer.Main;
import starling.core.Starling;
[SWF(width="960",height="640",frameRate="60",backgroundColor="#2f2f2f")]
public class LayoutExplorer extends Sprite
{
public function LayoutExplorer()
{
if(this.stage)
{
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
}
this.mouseEnabled = this.mouseChildren = false;
this.loaderInfo.addEventListener(Event.COMPLETE, loaderInfo_completeHandler);
}
private var _starling:Starling;
private function loaderInfo_completeHandler(event:Event):void
{
Starling.handleLostContext = true;
Starling.multitouchEnabled = true;
this._starling = new Starling(Main, this.stage);
this._starling.enableErrorChecking = false;
//this._starling.showStats = true;
this._starling.start();
this.stage.addEventListener(Event.RESIZE, stage_resizeHandler, false, int.MAX_VALUE, true);
this.stage.addEventListener(Event.DEACTIVATE, stage_deactivateHandler, false, 0, true);
}
private function stage_resizeHandler(event:Event):void
{
this._starling.stage.stageWidth = this.stage.stageWidth;
this._starling.stage.stageHeight = this.stage.stageHeight;
const viewPort:Rectangle = this._starling.viewPort;
viewPort.width = this.stage.stageWidth;
viewPort.height = this.stage.stageHeight;
try
{
this._starling.viewPort = viewPort;
}
catch(error:Error) {}
}
private function stage_deactivateHandler(event:Event):void
{
this._starling.stop();
this.stage.addEventListener(Event.ACTIVATE, stage_activateHandler, false, 0, true);
}
private function stage_activateHandler(event:Event):void
{
this.stage.removeEventListener(Event.ACTIVATE, stage_activateHandler);
this._starling.start();
}
}
} |
package net.pixelmethod.engine {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import net.pixelmethod.engine.util.PMLog;
public class PMGame extends Sprite {
// PUBLIC PROPERTIES
public var gameLog:PMLog;
[ArrayElementType('net.pixelmethod.engine.PMRenderTarget')]
public var renderTargets:Array;
public var renderTimer:Timer;
public var renderPeriod:int;
public var lastUpdate:int;
public var lastRender:int;
// PRIVATE PROPERTIES
public function PMGame() {
super();
renderTargets = [];
renderPeriod = 25;
lastUpdate = 0;
lastRender = 0;
if (stage) { init(); }
else { addEventListener(Event.ADDED_TO_STAGE, init); }
}
// PUBLIC API
public function init( a_event:Event = null ):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
// Initialize Input Manager
stage.addEventListener(KeyboardEvent.KEY_UP, PMInputManager.instance.onKeyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, PMInputManager.instance.onKeyDown);
}
// HANDLERS
protected function render( a_event:TimerEvent ):void {
//
}
}
}
|
package com.codeazur.as3swf.data.abc.exporters.builders
{
import com.codeazur.as3swf.data.abc.bytecode.ABCClassInfo;
import com.codeazur.as3swf.data.abc.bytecode.ABCInstanceInfo;
import com.codeazur.as3swf.data.abc.bytecode.multiname.ABCQualifiedName;
/**
* @author Simon Richardson - simon@ustwo.co.uk
*/
public interface IABCClassBuilder extends IABCBuilder {
function get qname():ABCQualifiedName;
function set qname(value:ABCQualifiedName):void;
function get classInfo():ABCClassInfo;
function set classInfo(value:ABCClassInfo):void;
function get instanceInfo():ABCInstanceInfo;
function set instanceInfo(value:ABCInstanceInfo):void;
}
}
|
// Navigation example.
// This sample demonstrates:
// - Generating a navigation mesh into the scene
// - Performing path queries to the navigation mesh
// - Rebuilding the navigation mesh partially when adding or removing objects
// - Visualizing custom debug geometry
// - Raycasting drawable components
// - Making a node follow the Detour path
#include "Scripts/Utilities/Sample.as"
Vector3 endPos;
Array<Vector3> currentPath;
Node@ jackNode;
bool useStreaming = false;
// Used for streaming only
const int STREAMING_DISTANCE = 2;
Array<VectorBuffer> navigationTilesData;
Array<IntVector2> navigationTilesIdx;
Array<IntVector2> addedTiles;
void Start()
{
// Execute the common startup for samples
SampleStart();
// Create the scene content
CreateScene();
// Create the UI content
CreateUI();
// Setup the viewport for displaying the scene
SetupViewport();
// Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE);
// Hook up to the frame update and render post-update events
SubscribeToEvents();
}
void CreateScene()
{
scene_ = Scene();
// Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
// Also create a DebugRenderer component so that we can draw debug geometry
scene_.CreateComponent("Octree");
scene_.CreateComponent("DebugRenderer");
// Create scene node & StaticModel component for showing a static plane
Node@ planeNode = scene_.CreateChild("Plane");
planeNode.scale = Vector3(100.0f, 1.0f, 100.0f);
StaticModel@ planeObject = planeNode.CreateComponent("StaticModel");
planeObject.model = cache.GetResource("Model", "Models/Plane.mdl");
planeObject.material = cache.GetResource("Material", "Materials/StoneTiled.xml");
// Create a Zone component for ambient lighting & fog control
Node@ zoneNode = scene_.CreateChild("Zone");
Zone@ zone = zoneNode.CreateComponent("Zone");
zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
zone.fogColor = Color(0.5f, 0.5f, 0.7f);
zone.fogStart = 100.0f;
zone.fogEnd = 300.0f;
// Create a directional light to the world. Enable cascaded shadows on it
Node@ lightNode = scene_.CreateChild("DirectionalLight");
lightNode.direction = Vector3(0.6f, -1.0f, 0.8f);
Light@ light = lightNode.CreateComponent("Light");
light.lightType = LIGHT_DIRECTIONAL;
light.castShadows = true;
light.shadowBias = BiasParameters(0.00025f, 0.5f);
// Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
// Create some mushrooms
const uint NUM_MUSHROOMS = 100;
for (uint i = 0; i < NUM_MUSHROOMS; ++i)
CreateMushroom(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
// Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
// rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
const uint NUM_BOXES = 20;
for (uint i = 0; i < NUM_BOXES; ++i)
{
Node@ boxNode = scene_.CreateChild("Box");
float size = 1.0f + Random(10.0f);
boxNode.position = Vector3(Random(80.0f) - 40.0f, size * 0.5f, Random(80.0f) - 40.0f);
boxNode.SetScale(size);
StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
boxObject.material = cache.GetResource("Material", "Materials/Stone.xml");
boxObject.castShadows = true;
if (size >= 3.0f)
boxObject.occluder = true;
}
// Create Jack node that will follow the path
jackNode = scene_.CreateChild("Jack");
jackNode.position = Vector3(-5.0f, 0.0f, 20.0f);
AnimatedModel@ modelObject = jackNode.CreateComponent("AnimatedModel");
modelObject.model = cache.GetResource("Model", "Models/Jack.mdl");
modelObject.material = cache.GetResource("Material", "Materials/Jack.xml");
modelObject.castShadows = true;
// Create a NavigationMesh component to the scene root
NavigationMesh@ navMesh = scene_.CreateComponent("NavigationMesh");
// Set small tiles to show navigation mesh streaming
navMesh.tileSize = 32;
// Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
// navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
scene_.CreateComponent("Navigable");
// Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
// in the scene and still update the mesh correctly
navMesh.padding = Vector3(0.0f, 10.0f, 0.0f);
// Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
// physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
// it will use renderable geometry instead
navMesh.Build();
// Create the camera. Limit far clip distance to match the fog
cameraNode = scene_.CreateChild("Camera");
Camera@ camera = cameraNode.CreateComponent("Camera");
camera.farClip = 300.0f;
// Set an initial position for the camera scene node above the plane and looking down
cameraNode.position = Vector3(0.0f, 50.0f, 0.0f);
pitch = 80.0f;
cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
}
void CreateUI()
{
// Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
// control the camera, and when visible, it will point the raycast target
XMLFile@ style = cache.GetResource("XMLFile", "UI/DefaultStyle.xml");
Cursor@ cursor = Cursor();
cursor.SetStyleAuto(style);
ui.cursor = cursor;
// Set starting position of the cursor at the rendering window center
cursor.SetPosition(graphics.width / 2, graphics.height / 2);
// Construct new Text object, set string to display and font to use
Text@ instructionText = ui.root.CreateChild("Text");
instructionText.text =
"Use WASD keys to move, RMB to rotate view\n"
"LMB to set destination, SHIFT+LMB to teleport\n"
"MMB or O key to add or remove obstacles\n"
"Tab to toggle navigation mesh streaming\n"
"Space to toggle debug geometry";
instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
// The text has multiple rows. Center them in relation to each other
instructionText.textAlignment = HA_CENTER;
// Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER;
instructionText.verticalAlignment = VA_CENTER;
instructionText.SetPosition(0, ui.root.height / 4);
}
void SetupViewport()
{
// Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
renderer.viewports[0] = viewport;
}
void SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate");
// Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
// debug geometry
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate");
}
void MoveCamera(float timeStep)
{
input.mouseVisible = input.mouseMode != MM_RELATIVE;
bool mouseDown = input.mouseButtonDown[MOUSEB_RIGHT];
// Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI
input.mouseGrabbed = mouseDown;
// Right mouse button controls mouse cursor visibility: hide when pressed
ui.cursor.visible = !mouseDown;
// Do not move if the UI has a focused element (the console)
if (ui.focusElement !is null)
return;
// Movement speed as world units per second
const float MOVE_SPEED = 20.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
// Only move the camera when the cursor is hidden
if (!ui.cursor.visible)
{
IntVector2 mouseMove = input.mouseMove;
yaw += MOUSE_SENSITIVITY * mouseMove.x;
pitch += MOUSE_SENSITIVITY * mouseMove.y;
pitch = Clamp(pitch, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0f);
}
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input.keyDown[KEY_W])
cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input.keyDown[KEY_S])
cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
if (input.keyDown[KEY_A])
cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input.keyDown[KEY_D])
cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
// Set destination or teleport with left mouse button
if (input.mouseButtonPress[MOUSEB_LEFT])
SetPathPoint();
// Add or remove objects with middle mouse button, then rebuild navigation mesh partially
if (input.mouseButtonPress[MOUSEB_MIDDLE] || input.keyPress[KEY_O])
AddOrRemoveObject();
// Toggle debug geometry with space
if (input.keyPress[KEY_SPACE])
drawDebug = !drawDebug;
}
void SetPathPoint()
{
Vector3 hitPos;
Drawable@ hitDrawable;
NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
if (Raycast(250.0f, hitPos, hitDrawable))
{
Vector3 pathPos = navMesh.FindNearestPoint(hitPos, Vector3(1.0f, 1.0f, 1.0f));
if (input.qualifierDown[QUAL_SHIFT])
{
// Teleport
currentPath.Clear();
jackNode.LookAt(Vector3(pathPos.x, jackNode.position.y, pathPos.z), Vector3::UP);
jackNode.position = pathPos;
}
else
{
// Calculate path from Jack's current position to the end point
endPos = pathPos;
currentPath = navMesh.FindPath(jackNode.position, endPos);
}
}
}
void AddOrRemoveObject()
{
// Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
Vector3 hitPos;
Drawable@ hitDrawable;
if (!useStreaming && Raycast(250.0f, hitPos, hitDrawable))
{
// The part of the navigation mesh we must update, which is the world bounding box of the associated
// drawable component
BoundingBox updateBox;
Node@ hitNode = hitDrawable.node;
if (hitNode.name == "Mushroom")
{
updateBox = hitDrawable.worldBoundingBox;
hitNode.Remove();
}
else
{
Node@ newNode = CreateMushroom(hitPos);
StaticModel@ newObject = newNode.GetComponent("StaticModel");
updateBox = newObject.worldBoundingBox;
}
// Rebuild part of the navigation mesh, then rebuild the path if applicable
NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
navMesh.Build(updateBox);
if (currentPath.length > 0)
currentPath = navMesh.FindPath(jackNode.position, endPos);
}
}
Node@ CreateMushroom(const Vector3& pos)
{
Node@ mushroomNode = scene_.CreateChild("Mushroom");
mushroomNode.position = pos;
mushroomNode.rotation = Quaternion(0.0f, Random(360.0f), 0.0f);
mushroomNode.SetScale(2.0f + Random(0.5f));
StaticModel@ mushroomObject = mushroomNode.CreateComponent("StaticModel");
mushroomObject.model = cache.GetResource("Model", "Models/Mushroom.mdl");
mushroomObject.material = cache.GetResource("Material", "Materials/Mushroom.xml");
mushroomObject.castShadows = true;
return mushroomNode;
}
bool Raycast(float maxDistance, Vector3& hitPos, Drawable@& hitDrawable)
{
hitDrawable = null;
IntVector2 pos = ui.cursorPosition;
// Check the cursor is visible and there is no UI element in front of the cursor
if (!ui.cursor.visible || ui.GetElementAt(pos, true) !is null)
return false;
Camera@ camera = cameraNode.GetComponent("Camera");
Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height);
// Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
// Note the convenience accessor to scene's Octree component
RayQueryResult result = scene_.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY);
if (result.drawable !is null)
{
hitPos = result.position;
hitDrawable = result.drawable;
return true;
}
return false;
}
void FollowPath(float timeStep)
{
if (currentPath.length > 0)
{
Vector3 nextWaypoint = currentPath[0]; // NB: currentPath[0] is the next waypoint in order
// Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
float move = 5.0f * timeStep;
float distance = (jackNode.position - nextWaypoint).length;
if (move > distance)
move = distance;
jackNode.LookAt(nextWaypoint, Vector3::UP);
jackNode.Translate(Vector3::FORWARD * move);
// Remove waypoint if reached it
if (distance < 0.1)
currentPath.Erase(0);
}
}
void ToggleStreaming(bool enabled)
{
NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
if (enabled)
{
int maxTiles = (2 * STREAMING_DISTANCE + 1) * (2 * STREAMING_DISTANCE + 1);
BoundingBox boundingBox = navMesh.boundingBox;
SaveNavigationData();
navMesh.Allocate(boundingBox, maxTiles);
}
else
navMesh.Build();
}
void UpdateStreaming()
{
NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
// Center the navigation mesh at the jack
IntVector2 jackTile = navMesh.GetTileIndex(jackNode.worldPosition);
IntVector2 beginTile = VectorMax(IntVector2(0, 0), jackTile - IntVector2(1, 1) * STREAMING_DISTANCE);
IntVector2 endTile = VectorMin(jackTile + IntVector2(1, 1) * STREAMING_DISTANCE, navMesh.numTiles - IntVector2(1, 1));
// Remove tiles
for (uint i = 0; i < addedTiles.length;)
{
IntVector2 tileIdx = addedTiles[i];
if (beginTile.x <= tileIdx.x && tileIdx.x <= endTile.x && beginTile.y <= tileIdx.y && tileIdx.y <= endTile.y)
++i;
else
{
addedTiles.Erase(i);
navMesh.RemoveTile(tileIdx);
}
}
// Add tiles
for (int z = beginTile.y; z <= endTile.y; ++z)
for (int x = beginTile.x; x <= endTile.x; ++x)
{
const IntVector2 tileIdx(x, z);
int tileDataIdx = navigationTilesIdx.Find(tileIdx);
if (!navMesh.HasTile(tileIdx) && tileDataIdx != -1)
{
addedTiles.Push(tileIdx);
navMesh.AddTile(navigationTilesData[tileDataIdx]);
}
}
}
void SaveNavigationData()
{
NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
navigationTilesData.Clear();
navigationTilesIdx.Clear();
addedTiles.Clear();
IntVector2 numTiles = navMesh.numTiles;
for (int z = 0; z < numTiles.y; ++z)
for (int x = 0; x < numTiles.x; ++x)
{
IntVector2 idx(x, z);
navigationTilesData.Push(navMesh.GetTileData(idx));
navigationTilesIdx.Push(idx);
}
}
void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
// Take the frame time step, which is stored as a float
float timeStep = eventData["TimeStep"].GetFloat();
// Move the camera, scale movement with time step
MoveCamera(timeStep);
// Make Jack follow the Detour path
FollowPath(timeStep);
// Update streaming
if (input.keyPress[KEY_TAB])
{
useStreaming = !useStreaming;
ToggleStreaming(useStreaming);
}
if (useStreaming)
UpdateStreaming();
}
void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
{
// If draw debug mode is enabled, draw navigation mesh debug geometry
if (drawDebug)
{
NavigationMesh@ navMesh = scene_.GetComponent("NavigationMesh");
navMesh.DrawDebugGeometry(true);
}
if (currentPath.length > 0)
{
// Visualize the current calculated path
// Note the convenience accessor to the DebugRenderer component
DebugRenderer@ debug = scene_.debugRenderer;
debug.AddBoundingBox(BoundingBox(endPos - Vector3(0.1f, 0.1f, 0.1f), endPos + Vector3(0.1f, 0.1f, 0.1f)),
Color(1.0f, 1.0f, 1.0f));
// Draw the path with a small upward bias so that it does not clip into the surfaces
Vector3 bias(0.0f, 0.05f, 0.0f);
debug.AddLine(jackNode.position + bias, currentPath[0] + bias, Color(1.0f, 1.0f, 1.0f));
if (currentPath.length > 1)
{
for (uint i = 0; i < currentPath.length - 1; ++i)
debug.AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, Color(1.0f, 1.0f, 1.0f));
}
}
}
// Create XML patch instructions for screen joystick layout specific to this sample app
String patchInstructions =
"<patch>" +
" <add sel=\"/element\">" +
" <element type=\"Button\">" +
" <attribute name=\"Name\" value=\"Button3\" />" +
" <attribute name=\"Position\" value=\"-120 -120\" />" +
" <attribute name=\"Size\" value=\"96 96\" />" +
" <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
" <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
" <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
" <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
" <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
" <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"Label\" />" +
" <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
" <attribute name=\"Vert Alignment\" value=\"Center\" />" +
" <attribute name=\"Color\" value=\"0 0 0 1\" />" +
" <attribute name=\"Text\" value=\"Teleport\" />" +
" </element>" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"KeyBinding\" />" +
" <attribute name=\"Text\" value=\"LSHIFT\" />" +
" </element>" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
" <attribute name=\"Text\" value=\"LEFT\" />" +
" </element>" +
" </element>" +
" <element type=\"Button\">" +
" <attribute name=\"Name\" value=\"Button4\" />" +
" <attribute name=\"Position\" value=\"-120 -12\" />" +
" <attribute name=\"Size\" value=\"96 96\" />" +
" <attribute name=\"Horiz Alignment\" value=\"Right\" />" +
" <attribute name=\"Vert Alignment\" value=\"Bottom\" />" +
" <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" +
" <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" +
" <attribute name=\"Hover Image Offset\" value=\"0 0\" />" +
" <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"Label\" />" +
" <attribute name=\"Horiz Alignment\" value=\"Center\" />" +
" <attribute name=\"Vert Alignment\" value=\"Center\" />" +
" <attribute name=\"Color\" value=\"0 0 0 1\" />" +
" <attribute name=\"Text\" value=\"Obstacles\" />" +
" </element>" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
" <attribute name=\"Text\" value=\"MIDDLE\" />" +
" </element>" +
" </element>" +
" </add>" +
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" +
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" +
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"MouseButtonBinding\" />" +
" <attribute name=\"Text\" value=\"LEFT\" />" +
" </element>" +
" </add>" +
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" +
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" +
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" +
" <element type=\"Text\">" +
" <attribute name=\"Name\" value=\"KeyBinding\" />" +
" <attribute name=\"Text\" value=\"SPACE\" />" +
" </element>" +
" </add>" +
"</patch>";
|
/*
* =BEGIN CLOSED LICENSE
*
* Copyright (c) 2013-2014 Andras Csizmadia
* http://www.vpmedia.eu
*
* For information about the licensing and copyright please
* contact Andras Csizmadia at andras@vpmedia.eu
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* =END CLOSED LICENSE
*/
package hu.vpmedia.components.core {
import hu.vpmedia.framework.BaseConfig;
/**
* TBD
*/
public class BaseSkinConfig extends BaseConfig {
/**
* TBD
*/
public var backgroundStyleID:String;
/**
* TBD
*/
public var iconStyleID:String;
/**
* TBD
*/
public var labelStyleID:String;
/**
* TBD
*/
public var buttonStyleID:String;
//--------------------------------------
// Constructor
//--------------------------------------
/**
* TBD
*/
public function BaseSkinConfig(parameters:Object = null) {
backgroundStyleID = "background";
iconStyleID = "icon";
labelStyleID = "label";
buttonStyleID = "button";
super(parameters);
}
}
}
|
/*
* Copyright (C) 2003-2012 Igniterealtime Community Contributors
*
* Daniel Henninger
* Derrick Grigg <dgrigg@rogers.com>
* Juga Paazmaya <olavic@gmail.com>
* Nick Velloff <nick.velloff@gmail.com>
* Sean Treadway <seant@oncotype.dk>
* Sean Voisen <sean@voisen.org>
* Mark Walters <mark@yourpalmark.com>
* Michael McCarthy <mikeycmccarthy@gmail.com>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.igniterealtime.xiff.si
{
import flash.events.EventDispatcher;
import flash.utils.ByteArray;
import com.hurlant.util.Base64;
import com.hurlant.crypto.hash.MD5;
import org.igniterealtime.xiff.core.*;
import org.igniterealtime.xiff.data.*;
import org.igniterealtime.xiff.data.feature.FeatureNegotiationExtension;
import org.igniterealtime.xiff.data.forms.*;
import org.igniterealtime.xiff.data.forms.enum.*;
import org.igniterealtime.xiff.data.si.*;
import org.igniterealtime.xiff.data.stream.*;
import org.igniterealtime.xiff.data.message.*;
import org.igniterealtime.xiff.events.*;
/**
*
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.OUTGOING_FEATURE
*/
[Event(name="featureNegotiated", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
*
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.OUTGOING_OPEN
*/
[Event(name="outgoingOpen", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
* Recipient received the closing
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.OUTGOING_CLOSE
*/
[Event(name="outgoingClose", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
* Incoming stream method feature negotiation request
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.INCOMING_FEATURE
*/
[Event(name="incomingFeature", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
* Starting the incoming data stream.
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.INCOMING_OPEN
*/
[Event(name="incomingOpen", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
* Incoming data should be complete.
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.INCOMING_CLOSE
*/
[Event(name="incomingClose", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
* INCOMPLETE
*
* Manages Stream Initiation (XEP-0095) based File Transfer (XEP-0096),
* which uses In-Band Bytestreams (XEP-0047) as the transfer stream method.
*
* <p>You can have maximum of one outgoing and one incoming file
* transfer ongoing at the same time.</p>
*
* @see http://xmpp.org/extensions/xep-0095.html
* @see http://xmpp.org/extensions/xep-0096.html
* @see http://xmpp.org/extensions/xep-0047.html
*/
public class FileTransferManager extends EventDispatcher
{
private var _connection:IXMPPConnection;
private var _outGoingData:ByteArray;
private var _outGoingBase64:String;
private var _sequenceOut:uint = 0;
private var _inComingData:ByteArray;
private var _inComingBase64:String;
private var _sequenceIn:uint = 0;
private var _incomingMethodFieldName:String;
private var _chunkSize:uint = 4096;
private var _md5:MD5;
/**
* Set the out going data first.
* Then sendFile with all the relevant information.
*
* @param aConnection A reference to an XMPPConnection class instance
*/
public function FileTransferManager( aConnection:IXMPPConnection = null )
{
if ( aConnection != null )
{
connection = aConnection;
}
_md5 = new MD5();
}
/**
* Negotiate a suitable transfer protocol.
*
* <p><code>FileReferenceList.browse()</code> might be used to get the
* file and the relevant information.</p>
*
* <p>It seems that SOCKS5 Bytestreams (XEP-0065) would be the
* most preferred method, but it not implemented in XIFF.</p>
*
* <p>Negotiation the method for transferring files is done with
* the following extensions:</p>
* <ol>
* <li><code>FormExtension</code>, that contains a single
* <code>FormField</code> with possible methods listed</li>
* <li><code>FeatureNegotiationExtension</code> wraps the form</li>
* <li><code>FileTransferExtension</code> contains information
* about the file</li>
* <li>Both <code>FeatureNegotiationExtension</code> and
* <code>FileTransferExtension</code> are wrapped in
* <code>StreamInitiationExtension</code></li>
* <li>Finally <code>StreamInitiationExtension</code> is
* wrapped in <code>IQ</code></li>
* </ol>
*
* @see http://xmpp.org/extensions/xep-0065.html
* @see http://xmpp.org/extensions/xep-0095.html#usecase
* @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#load%28%29
*/
public function sendFile(to:EscapedJID, fileName:String, fileSize:uint, mimeType:String, modificationDate:Date = null):void
{
trace("sendFile. to: " + to.toString() + ", fileName: " + fileName + ", fileSize: " + fileSize + ", mimeType: " + mimeType);
var options:Array = [
{ label: "XEP-0047: In-Band Bytestreams", value: IBBExtension.NS } // Only supported method...
];
var field:FormField = new FormField(
FormFieldType.LIST_SINGLE,
"stream-method",
null,
options
);
var formExt:FormExtension = new FormExtension();
formExt.type = FormType.FORM;
formExt.fields = [field];
var featExt:FeatureNegotiationExtension = new FeatureNegotiationExtension();
featExt.addExtension(formExt);
var fileExt:FileTransferExtension = new FileTransferExtension();
fileExt.name = fileName;
fileExt.size = fileSize;
fileExt.date = modificationDate;
var hash:ByteArray = _md5.hash(_outGoingData);
hash.position = 0;
fileExt.hash = hash.readUTFBytes(hash.length);
var siExt:StreamInitiationExtension = new StreamInitiationExtension();
siExt.id = "letsdoit";
siExt.profile = FileTransferExtension.NS;
siExt.mimeType = mimeType;
siExt.addExtension(featExt);
siExt.addExtension(fileExt);
var iq:IQ = new IQ(to, IQ.TYPE_SET, null, sendFile_callback, sendFile_errorCallback);
iq.addExtension(siExt);
_connection.send(iq);
}
/**
* Called once the IQ stanza with the proper id is coming back
*/
private function sendFile_callback(iq:IQ):void
{
/*
<iq type='result' to='sender@jabber.org/resource' id='offer1'>
<si xmlns='http://jabber.org/protocol/si'>
<feature xmlns='http://jabber.org/protocol/feature-neg'>
<x xmlns='jabber:x:data' type='submit'>
<field var='stream-method'>
<value>http://jabber.org/protocol/bytestreams</value>
</field>
</x>
</feature>
</si>
</iq>
*/
var siExt:StreamInitiationExtension = iq.getAllExtensionsByNS(StreamInitiationExtension.NS)[0] as StreamInitiationExtension;
if (siExt != null)
{
var featExt:FeatureNegotiationExtension = siExt.getAllExtensionsByNS(FeatureNegotiationExtension.NS)[0] as FeatureNegotiationExtension;
var formExt:FormExtension = featExt.getAllExtensionsByNS(FormExtension.NS)[0] as FormExtension;
var field:FormField = formExt.getFormField("stream-method");
trace("sendFile_callback. field.value: " + field.value);
var event:FileTransferEvent = new FileTransferEvent(FileTransferEvent.OUTGOING_FEATURE);
event.extensions = [featExt];
dispatchEvent(event);
sendOpen(iq.from);
}
}
private function sendFile_errorCallback(iq:IQ):void
{
// fail....
}
/**
* Once the stream method has been negotiated, initiate the session.
*/
private function sendOpen(to:EscapedJID):void
{
var openExt:IBBOpenExtension = new IBBOpenExtension();
openExt.sid = "letsdoit";
openExt.blockSize = _chunkSize;
var iq:IQ = new IQ(to, IQ.TYPE_SET, null, sendOpen_callback, sendOpen_errorCallback);
iq.addExtension(openExt);
_connection.send(iq);
}
/**
* Called once the IQ stanza with the proper id is coming back
*/
private function sendOpen_callback(iq:IQ):void
{
var event:FileTransferEvent = new FileTransferEvent(FileTransferEvent.OUTGOING_OPEN);
dispatchEvent(event);
/*
<iq from='juliet@capulet.com/balcony'
id='jn3h8g65'
to='romeo@montague.net/orchard'
type='result'/>
*/
// Create Base64 version of the out going data
_outGoingData.position = 0;
_outGoingBase64 = Base64.encode( _outGoingData.readUTFBytes(_outGoingData.length) );
sendChunk(iq.from);
}
private function sendOpen_errorCallback(iq:IQ):void
{
// IBB not supported by the other party
/*
<iq from='juliet@capulet.com/balcony'
id='jn3h8g65'
to='romeo@montague.net/orchard'
type='error'>
<error type='cancel'>
<service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
</error>
</iq>
*/
}
private function sendChunk(to:EscapedJID):void
{
var iq:IQ = new IQ(to, IQ.TYPE_SET, null, sendChunk_callback, sendChunk_errorCallback);
var len:uint = Math.min(_outGoingBase64.length - _chunkSize * _sequenceOut, _sequenceOut);
if (len > 0)
{
var dataExt:IBBDataExtension = new IBBDataExtension();
dataExt.sid = "letsdoit";
dataExt.seq = _sequenceOut;
dataExt.data = _outGoingBase64.substr(_chunkSize * _sequenceOut, len);
iq.addExtension(dataExt);
++_sequenceOut;
}
else
{
iq.addExtension(new IBBCloseExtension());
}
_connection.send(iq);
}
private function sendChunk_callback(iq:IQ):void
{
if (_outGoingBase64.length - _chunkSize * _sequenceOut > 0)
{
sendChunk(iq.from);
}
else
{
var event:FileTransferEvent = new FileTransferEvent(FileTransferEvent.OUTGOING_CLOSE);
dispatchEvent(event);
}
}
private function sendChunk_errorCallback(iq:IQ):void
{
// fail....
}
/**
* This listener will catch any incoming requests.
*
* <p>Will dispatch an INCOMING_FEATURE event if suitable stream
* method is suggested.</p>
*/
private function onStreamInitiation(event:IQEvent):void
{
var iq:IQ;
/*
<si xmlns='http://jabber.org/protocol/si'
id='a0'
mime-type='text/plain'
profile='http://jabber.org/protocol/si/profile/file-transfer'>
<file xmlns='http://jabber.org/protocol/si/profile/file-transfer'
name='test.txt'
size='1022'>
<desc>This is info about the file.</desc>
</file>
<feature xmlns='http://jabber.org/protocol/feature-neg'>
<x xmlns='jabber:x:data' type='form'>
<field var='stream-method' type='list-single'>
<option><value>http://jabber.org/protocol/bytestreams</value></option>
<option><value>jabber:iq:oob</value></option>
<option><value>http://jabber.org/protocol/ibb</value></option>
</field>
</x>
</feature>
</si>
*/
var siExt:StreamInitiationExtension = event.data as StreamInitiationExtension;
if (siExt != null)
{
if (siExt.profile != FileTransferExtension.NS)
{
// Profile not understood
/*
<iq type='error' to='sender@jabber.org/resource' id='offer1'>
<error code='400' type='cancel'>
<bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
<bad-profile xmlns='http://jabber.org/protocol/si'/>
</error>
</iq>
*/
iq = new IQ(event.iq.from, IQ.TYPE_ERROR, event.iq.id);
iq.errorCondition = "bad-request";
iq.errorType = XMPPStanza.ERROR_MODIFY; // spec says modify, example cancel
// http://xmpp.org/extensions/xep-0095.html#def-error
// TODO: application specific error message..
//<bad-profile xmlns='http://jabber.org/protocol/si'/>
_connection.send(iq);
return;
}
var featExt:FeatureNegotiationExtension = siExt.getAllExtensionsByNS(FeatureNegotiationExtension.NS)[0] as FeatureNegotiationExtension;
var fileExt:FileTransferExtension = siExt.getAllExtensionsByNS(FileTransferExtension.NS)[0] as FileTransferExtension;
if (featExt != null && fileExt != null)
{
var formExt:FormExtension = featExt.getAllExtensionsByNS(FormExtension.NS)[0] as FormExtension;
if (formExt != null)
{
// Look for suitable stream method...
var fieldName:String;
var fields:Array = formExt.fields;
for each (var field:FormField in fields)
{
var index:int = field.values.indexOf(IBBExtension.NS);; // Only supported method...
if (index !== -1)
{
trace("field.varName: " + field.varName);
fieldName = field.varName;
}
}
if (fieldName != null)
{
_incomingMethodFieldName = fieldName;
var fileEvent:FileTransferEvent = new FileTransferEvent(FileTransferEvent.INCOMING_FEATURE);
fileEvent.iq = event.iq;
dispatchEvent(fileEvent);
}
else
{
// No Valid Streams
// Respond with an error
iq = new IQ(event.iq.from, IQ.TYPE_ERROR, event.iq.id);
iq.errorCondition = "bad-request";
iq.errorType = XMPPStanza.ERROR_CANCEL;
// TODO: application specific error message..
//<no-valid-streams xmlns='http://jabber.org/protocol/si'/>
_connection.send(iq);
}
}
}
}
}
/**
* Send feature request responce.
*/
public function acceptFile(originalIq:IQ):void
{
if (_incomingMethodFieldName == null || _incomingMethodFieldName == "")
{
throw new Error("Incoming method field name is not set.");
}
var field:FormField = new FormField();
field.varName = _incomingMethodFieldName;
field.value = IBBExtension.NS; // Only supported method...
var formExt:FormExtension = new FormExtension();
formExt.type = FormType.SUBMIT;
formExt.fields = [field];
var featExt:FeatureNegotiationExtension = new FeatureNegotiationExtension();
featExt.addExtension(formExt);
var siExt:StreamInitiationExtension = new StreamInitiationExtension();
siExt.addExtension(featExt);
var iq:IQ = new IQ(originalIq.from, IQ.TYPE_RESULT, originalIq.id);
iq.addExtension(siExt);
_connection.send(iq);
}
/**
* Reject the file, possible with an explanation
*/
public function rejectFile(originalIq:IQ, text:String = null):void
{
/*
<iq type='error' to='sender@jabber.org/resource' id='offer1'>
<error code='403' type='cancel'>
<forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
<text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>Offer Declined</text>
</error>
</iq>
*/
// Respond with an error
var iq:IQ = new IQ(originalIq.from, IQ.TYPE_ERROR, originalIq.id);
iq.errorCondition = "forbidden";
iq.errorType = XMPPStanza.ERROR_CANCEL;
iq.errorMessage = text;
_connection.send(iq);
}
/**
* Incoming In-Band Byte Stream listener.
*/
private function onInBandData(event:IQEvent):void
{
if (event.data != null)
{
if (event.data is IBBDataExtension)
{
var dataExt:IBBDataExtension = event.data as IBBDataExtension;
_sequenceIn = dataExt.seq;
_inComingBase64 += dataExt.data;
}
else if (event.data is IBBOpenExtension)
{
_inComingData = new ByteArray();
_inComingBase64 = "";
var openExt:IBBOpenExtension = event.data as IBBOpenExtension;
dispatchEvent(new FileTransferEvent(FileTransferEvent.INCOMING_OPEN));
}
else if (event.data is IBBCloseExtension)
{
_inComingData.writeUTFBytes(Base64.decode(_inComingBase64));
var closeExt:IBBCloseExtension = event.data as IBBCloseExtension;
dispatchEvent(new FileTransferEvent(FileTransferEvent.INCOMING_CLOSE));
}
// Send acknowledgement
var iq:IQ = new IQ(event.iq.from, IQ.TYPE_RESULT, event.iq.id);
_connection.send(iq);
}
}
/**
* Data that is sent to the recipient.
* This should be the raw data, possible Base64
* encoding is handled internally.
*/
public function get outGoingData():ByteArray
{
return _outGoingData;
}
public function set outGoingData( value:ByteArray ):void
{
_outGoingData = value;
}
/**
* Data that is received from the other party.
* This should be the raw data, possible Base64
* decoding is handled internally.
*
* <p>Read-only</p>
*/
public function get inComingData():ByteArray
{
return _inComingData;
}
/**
* The connection used for sending and receiving data.
*/
public function get connection():IXMPPConnection
{
return _connection;
}
public function set connection( value:IXMPPConnection ):void
{
if ( _connection != null )
{
_connection.removeEventListener(StreamInitiationExtension.NS, onStreamInitiation);
_connection.removeEventListener(IBBExtension.NS, onInBandData);
}
_connection = value;
_connection.addEventListener(StreamInitiationExtension.NS, onStreamInitiation);
_connection.addEventListener(IBBExtension.NS, onInBandData);
_connection.enableExtensions(
FileTransferExtension,
FormExtension,
StreamInitiationExtension,
FeatureNegotiationExtension,
OutOfBoundDataExtension,
IBBOpenExtension
);
}
}
}
|
package kabam.lib.net.api {
public interface MessageMap {
function map(_arg_1:int):MessageMapping;
function unmap(_arg_1:int):void;
}
}//package kabam.lib.net.api
|
table flagger
"Flagger for coverage-based reliable/unreliable analysis"
(
string chrom; "Genomic sequence name"
uint chromStart; "Start in genomic sequence"
uint chromEnd; "End in genomic sequence"
string name; "Name of repeat"
uint score; "always 0 place holder"
char[1] strand; "Relative orientation + or -"
uint thickStart; "Start of where display should be thick (start codon)"
uint thickEnd; "End of where display should be thick (stop codon)"
uint reserved; "color"
) |
package game.manager
{
import com.mobileLib.utils.ConverURL;
import com.singleton.Singleton;
import avmplus.getQualifiedClassName;
import starling.utils.AssetManager;
public class AssetMgr extends AssetManager
{
protected var _dict : Object = {}; // 去除重复加载
public static function get instance() : AssetMgr
{
return Singleton.getInstance(AssetMgr) as AssetMgr;
}
public function AssetMgr() : void
{
_dict = {};
}
override public function enqueueWithName(asset : Object, name : String = null) : String
{
if (ConverURL.update_dic[asset.name] != null)
{
asset = ConverURL.update_dic[asset.name];
}
if (getQualifiedClassName(asset) == "flash.filesystem::File")
asset = asset["url"];
if (name == null)
name = getName(asset);
log("Enqueuing '" + name + "'");
// 去除重复加载
if (_dict[asset])
{
return null;
}
else
{
_dict[asset] = true;
}
mQueue.push({name: name, asset: asset});
return name;
}
public function removeUi(name : String, home : String) : void
{
home += "/";
delete _dict[ConverURL.conver(home + name + ".atf").url];
delete _dict[ConverURL.conver(home + name + ".png").url];
delete _dict[ConverURL.conver(home + name + ".xml").url];
delete _dict[ConverURL.conver(home + name + ".axs").url];
removeXml(name);
removeByteArray(name);
removeTexture(name);
removeTextureAtlas(name);
}
}
} |
package a24.util
{
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.geom.Rectangle;
/**
*
*
* 基準点に関する便利なやつです。
* @author Atsushi Kaga
* @since 2012.02.14
*
*/
final public class Align24
{
/**
* 基準点を左上にするよう指定します。
*/
static public const TOP_LEFT:uint = 1;
/**
* 基準点をセンター上にするよう指定します。
*/
static public const TOP_CENTER:uint = 2;
/**
* 基準点を右上にするよう指定します。
*/
static public const TOP_RIGHT:uint = 3;
/**
* 基準点を左中央にするよう指定します。
*/
static public const MIDDLE_LEFT:uint = 4;
/**
* 基準点を中央にするよう指定します。
*/
static public const MIDDLE_CENTER:uint = 5;
/**
* 基準点を右中央にするよう指定します。
*/
static public const MIDDLE_RIGHT:uint = 6;
/**
* 基準点を左下にするよう指定します。
*/
static public const BOTTOM_LEFT:uint = 7;
/**
* 基準点をセンター下にするよう指定します。
*/
static public const BOTTOM_CENTER:uint = 8;
/**
* 基準点を右下にするよう指定します。
*/
static public const BOTTOM_RIGHT:uint = 9;
/**
* 基準点をデフォルトにするよう指定します。
*/
static public const DEFAULT:uint = 0;
/**
* 水平の基準点を左にするよう指定します。
*/
static public const LEFT:uint = 11;
/**
* 水平の基準点をセンターにするよう指定します。
*/
static public const CENTER:uint = 12;
/**
* 水平の基準点を右にするよう指定します。
*/
static public const RIGHT:uint = 13;
/**
* 垂直の基準点を上にするよう指定します。
*/
static public const TOP:uint = 14;
/**
* 垂直の基準点を中央にするよう指定します。
*/
static public const MIDDLE:uint = 15;
/**
* 垂直の基準点を下にするよう指定します。
*/
static public const BOTTOM:uint = 16;
/**
* 基準点を任意の点にするよう指定します。
*/
static public const SELECTED:uint = 100;
/**
* 基準点を左上にするよう指定します。
*/
public var topLeft:uint = TOP_LEFT;
/**
* 基準点をセンター上にするよう指定します。
*/
public var topCenter:uint = TOP_CENTER;
/**
* 基準点を右上にするよう指定します。
*/
public var topRight:uint = TOP_RIGHT;
/**
* 基準点を左中央にするよう指定します。
*/
public var middleLeft:uint = MIDDLE_LEFT;
/**
* 基準点を中央にするよう指定します。
*/
public var middleCenter:uint = MIDDLE_CENTER;
/**
* 基準点を右中央にするよう指定します。
*/
public var middleRight:uint = MIDDLE_RIGHT;
/**
* 基準点を左下にするよう指定します。
*/
public var bottomLeft:uint = BOTTOM_LEFT;
/**
* 基準点をセンター下にするよう指定します。
*/
public var bottomCenter:uint = BOTTOM_CENTER;
/**
* 基準点を右下にするよう指定します。
*/
public var bottomRight:uint = BOTTOM_RIGHT;
/**
* 基準点をデフォルトにするよう指定します。
*/
public var deautlt:uint = DEFAULT;
/**
* 水平の基準点を左にするよう指定します。
*/
public var left:uint = LEFT;
/**
* 水平の基準点をセンターにするよう指定します。
*/
public var center:uint = CENTER;
/**
* 水平の基準点を右にするよう指定します。
*/
public var right:uint = RIGHT;
/**
* 垂直の基準点を上にするよう指定します。
*/
public var top:uint = TOP;
/**
* 垂直の基準点を中央にするよう指定します。
*/
public var middle:uint = MIDDLE;
/**
* 垂直の基準点を下にするよう指定します。
*/
public var bottom:uint = BOTTOM;
/**
* 基準点を任意の点にするよう指定します。
*/
public var selected:uint = SELECTED;
/**
* @private
*/
public function Align24() {}
/**
* 整列値を元に、オブジェクトに対する座標を取得します。
* @param target ターゲット
* @param align 整列値
* @return Point
*/
static public function getAlignPoint(target:DisplayObject, align:uint):Point
{
var pt:Point = new Point();
var rect:Rectangle = target.getRect(target);
// rect.x *= target.scaleX;
// rect.y *= target.scaleY;
// rect.width *= target.scaleX;
// rect.height *= target.scaleY;
switch(align) {
case 1: case 4: case 7: case 11: pt.x = rect.left; break; // Left
case 2: case 5: case 8: case 12: pt.x = rect.left + (rect.width) / 2; break; // Center
case 3: case 6: case 9: case 13: pt.x = rect.right; break; // Right
}
switch(align) {
case 1: case 2: case 3: case 14: pt.y = rect.top; break; // Top
case 4: case 5: case 6: case 15: pt.y = rect.top + rect.height / 2; break; // Middle
case 7: case 8: case 9: case 16: pt.y = rect.bottom; break; // Bottom
}
return pt;
}
}
} |
package flexUnitTests.as3.mongo.db.collection
{
import as3.mongo.db.DB;
import as3.mongo.db.collection.Collection;
import as3.mongo.db.document.Document;
import mockolate.received;
import mockolate.runner.MockolateRule;
import org.flexunit.assertThat;
public class Collection_updateTests
{
[Rule]
public var mocks:MockolateRule = new MockolateRule();
[Mock(inject = "true", type = "nice")]
public var mockDB:DB;
private var _testCollectionName:String = "aCollectionName";
private var _collection:Collection;
[Before]
public function setUp():void
{
_collection = new Collection(_testCollectionName, mockDB);
}
[After]
public function tearDown():void
{
_collection = null;
}
[Test]
public function update_validInputs_updateInvokedOnDB():void
{
var selector:Document = new Document("selector:value");
var modifier:Document = new Document("selector:newValue");
_collection.update(selector, modifier);
assertThat(mockDB, received().method("update").args(_testCollectionName, selector, modifier).once());
}
[Test(expects = "as3.mongo.error.MongoError")]
public function update_invalidNullSelector_throwsError():void
{
_collection.update(null, new Document());
}
[Test(expects = "as3.mongo.error.MongoError")]
public function update_invalidNullModifier_throwsError():void
{
_collection.update(new Document(), null);
}
}
}
|
package Ankama_Admin.adminMenu.items
{
import Ankama_Admin.Api;
public class SeparatorItem extends BasicItem
{
private var _label:String;
public function SeparatorItem()
{
super();
}
override public function getContextMenuItem(replaceParam:Object) : Object
{
return Api.contextMod.createContextMenuSeparatorObject();
}
override public function get label() : String
{
return "";
}
override public function set label(l:String) : void
{
}
override protected function replace(txt:String, param:Object) : String
{
return "";
}
}
}
|
package away3d.loaders
{
import away3d.*;
import away3d.events.*;
import away3d.loaders.misc.*;
import away3d.loaders.parsers.*;
import flash.events.*;
import flash.net.*;
use namespace arcane;
/**
* Dispatched when any asset finishes parsing. Also see specific events for each
* individual asset type (meshes, materials et c.)
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="assetComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a full resource (including dependencies) finishes loading.
*
* @eventType away3d.events.LoaderEvent
*/
[Event(name="resourceComplete", type="away3d.events.LoaderEvent")]
/**
* Dispatched when a single dependency (which may be the main file of a resource)
* finishes loading.
*
* @eventType away3d.events.LoaderEvent
*/
[Event(name="dependencyComplete", type="away3d.events.LoaderEvent")]
/**
* Dispatched when an error occurs during loading. I
*
* @eventType away3d.events.LoaderEvent
*/
[Event(name="loadError", type="away3d.events.LoaderEvent")]
/**
* Dispatched when an error occurs during parsing.
*
* @eventType away3d.events.ParserEvent
*/
[Event(name="parseError", type="away3d.events.ParserEvent")]
/**
* Dispatched when a skybox asset has been costructed from a ressource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="skyboxComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a camera3d asset has been costructed from a ressource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="cameraComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a mesh asset has been costructed from a ressource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="meshComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a geometry asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="geometryComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a skeleton asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="skeletonComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a skeleton pose asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="skeletonPoseComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a container asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="containerComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a texture asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="textureComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a texture projector asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="textureProjectorComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a material asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="materialComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when a animator asset has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="animatorComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an animation set has been constructed from a group of animation state resources.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="animationSetComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an animation state has been constructed from a group of animation node resources.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="animationStateComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an animation node has been constructed from a resource.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="animationNodeComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an animation state transition has been constructed from a group of animation node resources.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="stateTransitionComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an light asset has been constructed from a resources.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="lightComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an light picker asset has been constructed from a resources.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="lightPickerComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an effect method asset has been constructed from a resources.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="effectMethodComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an shadow map method asset has been constructed from a resources.
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="shadowMapMethodComplete", type="away3d.events.AssetEvent")]
/**
* Dispatched when an image asset dimensions are not a power of 2
*
* @eventType away3d.events.AssetEvent
*/
[Event(name="textureSizeError", type="away3d.events.AssetEvent")]
/**
* AssetLoader can load any file format that Away3D supports (or for which a third-party parser
* has been plugged in) and it's dependencies. Events are dispatched when assets are encountered
* and for when the resource (or it's dependencies) have been loaded.
*
* The AssetLoader will not make assets available in any other way than through the dispatched
* events. To store assets and make them available at any point from any module in an application,
* use the AssetLibrary to load and manage assets.
*
* @see away3d.loading.Loader3D
* @see away3d.loading.AssetLibrary
*/
public class AssetLoader extends EventDispatcher
{
private var _context:AssetLoaderContext;
private var _token:AssetLoaderToken;
private var _uri:String;
private var _errorHandlers:Vector.<Function>;
private var _parseErrorHandlers:Vector.<Function>;
private var _stack:Vector.<ResourceDependency>;
private var _baseDependency:ResourceDependency;
private var _loadingDependency:ResourceDependency;
private var _namespace:String;
/**
* Returns the base dependency of the loader
*/
public function get baseDependency():ResourceDependency
{
return _baseDependency;
}
/**
* Create a new ResourceLoadSession object.
*/
public function AssetLoader()
{
_stack = new Vector.<ResourceDependency>();
_errorHandlers = new Vector.<Function>();
_parseErrorHandlers = new Vector.<Function>();
}
/**
* Enables a specific parser.
* When no specific parser is set for a loading/parsing opperation,
* loader3d can autoselect the correct parser to use.
* A parser must have been enabled, to be considered when autoselecting the parser.
*
* @param parserClass The parser class to enable.
*
* @see away3d.loaders.parsers.Parsers
*/
public static function enableParser(parserClass:Class):void
{
SingleFileLoader.enableParser(parserClass);
}
/**
* Enables a list of parsers.
* When no specific parser is set for a loading/parsing opperation,
* AssetLoader can autoselect the correct parser to use.
* A parser must have been enabled, to be considered when autoselecting the parser.
*
* @param parserClasses A Vector of parser classes to enable.
* @see away3d.loaders.parsers.Parsers
*/
public static function enableParsers(parserClasses:Vector.<Class>):void
{
SingleFileLoader.enableParsers(parserClasses);
}
/**
* Loads a file and (optionally) all of its dependencies.
*
* @param req The URLRequest object containing the URL of the file to be loaded.
* @param context An optional context object providing additional parameters for loading
* @param ns An optional namespace string under which the file is to be loaded, allowing the differentiation of two resources with identical assets
* @param parser An optional parser object for translating the loaded data into a usable resource. If not provided, AssetLoader will attempt to auto-detect the file type.
*/
public function load(req:URLRequest, context:AssetLoaderContext = null, ns:String = null, parser:ParserBase = null):AssetLoaderToken
{
if (!_token) {
_token = new AssetLoaderToken(this);
_uri = req.url = req.url.replace(/\\/g, "/");
_context = context;
_namespace = ns;
_baseDependency = new ResourceDependency('', req, null, null);
retrieveDependency(_baseDependency, parser);
return _token;
}
// TODO: Throw error (already loading)
return null;
}
/**
* Loads a resource from already loaded data.
*
* @param data The data object containing all resource information.
* @param context An optional context object providing additional parameters for loading
* @param ns An optional namespace string under which the file is to be loaded, allowing the differentiation of two resources with identical assets
* @param parser An optional parser object for translating the loaded data into a usable resource. If not provided, AssetLoader will attempt to auto-detect the file type.
*/
public function loadData(data:*, id:String, context:AssetLoaderContext = null, ns:String = null, parser:ParserBase = null):AssetLoaderToken
{
if (!_token) {
_token = new AssetLoaderToken(this);
_uri = id;
_context = context;
_namespace = ns;
_baseDependency = new ResourceDependency(id, null, data, null);
retrieveDependency(_baseDependency, parser);
return _token;
}
// TODO: Throw error (already loading)
return null;
}
/**
* Recursively retrieves the next to-be-loaded and parsed dependency on the stack, or pops the list off the
* stack when complete and continues on the top set.
* @param parser The parser that will translate the data into a usable resource.
*/
private function retrieveNext(parser:ParserBase = null):void
{
if (_loadingDependency.dependencies.length) {
var dep:ResourceDependency = _loadingDependency.dependencies.pop();
_stack.push(_loadingDependency);
retrieveDependency(dep);
} else if (_loadingDependency.loader.parser && _loadingDependency.loader.parser.parsingPaused) {
_loadingDependency.loader.parser.resumeParsingAfterDependencies();
_stack.pop();
} else if (_stack.length) {
var prev:ResourceDependency = _loadingDependency;
_loadingDependency = _stack.pop();
if (prev.success)
prev.resolve();
retrieveNext(parser);
} else
dispatchEvent(new LoaderEvent(LoaderEvent.RESOURCE_COMPLETE, _uri));
}
/**
* Retrieves a single dependency.
* @param parser The parser that will translate the data into a usable resource.
*/
private function retrieveDependency(dependency:ResourceDependency, parser:ParserBase = null):void
{
var data:*;
var matMode:uint = 0;
if (_context && _context.materialMode != 0)
matMode = _context.materialMode;
_loadingDependency = dependency;
_loadingDependency.loader = new SingleFileLoader(matMode);
addEventListeners(_loadingDependency.loader);
// Get already loaded (or mapped) data if available
data = _loadingDependency.data;
if (_context && _loadingDependency.request && _context.hasDataForUrl(_loadingDependency.request.url))
data = _context.getDataForUrl(_loadingDependency.request.url);
if (data) {
if (_loadingDependency.retrieveAsRawData) {
// No need to parse. The parent parser is expecting this
// to be raw data so it can be passed directly.
dispatchEvent(new LoaderEvent(LoaderEvent.DEPENDENCY_COMPLETE, _loadingDependency.request.url, true));
_loadingDependency.setData(data);
_loadingDependency.resolve();
// Move on to next dependency
retrieveNext();
} else
_loadingDependency.loader.parseData(data, parser, _loadingDependency.request);
} else {
// Resolve URL and start loading
dependency.request.url = resolveDependencyUrl(dependency);
_loadingDependency.loader.load(dependency.request, parser, _loadingDependency.retrieveAsRawData);
}
}
private function joinUrl(base:String, end:String):String
{
if (end.charAt(0) == '/')
end = end.substr(1);
if (base.length == 0)
return end;
if (base.charAt(base.length - 1) == '/')
base = base.substr(0, base.length - 1);
return base.concat('/', end);
}
private function resolveDependencyUrl(dependency:ResourceDependency):String
{
var scheme_re:RegExp;
var base:String;
var url:String = dependency.request.url;
// Has the user re-mapped this URL?
if (_context && _context.hasMappingForUrl(url))
return _context.getRemappedUrl(url);
// This is the "base" dependency, i.e. the actual requested asset.
// We will not try to resolve this since the user can probably be
// thrusted to know this URL better than our automatic resolver. :)
if (url == _uri)
return url;
// Absolute URL? Check if starts with slash or a URL
// scheme definition (e.g. ftp://, http://, file://)
scheme_re = new RegExp(/^[a-zA-Z]{3,4}:\/\//);
if (url.charAt(0) == '/') {
if (_context && _context.overrideAbsolutePaths)
return joinUrl(_context.dependencyBaseUrl, url);
else
return url;
} else if (scheme_re.test(url)) {
// If overriding full URLs, get rid of scheme (e.g. "http://")
// and replace with the dependencyBaseUrl defined by user.
if (_context && _context.overrideFullURLs) {
var noscheme_url:String;
noscheme_url = url.replace(scheme_re);
return joinUrl(_context.dependencyBaseUrl, noscheme_url);
}
}
// Since not absolute, just get rid of base file name to find it's
// folder and then concatenate dynamic URL
if (_context && _context.dependencyBaseUrl) {
base = _context.dependencyBaseUrl;
return joinUrl(base, url);
} else {
base = _uri.substring(0, _uri.lastIndexOf('/') + 1);
return joinUrl(base, url);
}
}
private function retrieveLoaderDependencies(loader:SingleFileLoader):void
{
if (!_loadingDependency) {
//loader.parser = null;
//loader = null;
return;
}
var i:int, len:int = loader.dependencies.length;
for (i = 0; i < len; i++)
_loadingDependency.dependencies[i] = loader.dependencies[i];
// Since more dependencies might be added eventually, empty this
// list so that the same dependency isn't retrieved more than once.
loader.dependencies.length = 0;
_stack.push(_loadingDependency);
retrieveNext();
}
/**
* Called when a single dependency loading failed, and pushes further dependencies onto the stack.
* @param event
*/
private function onRetrievalFailed(event:LoaderEvent):void
{
var handled:Boolean;
var isDependency:Boolean = (_loadingDependency != _baseDependency);
var loader:SingleFileLoader = SingleFileLoader(event.target);
removeEventListeners(loader);
event = new LoaderEvent(LoaderEvent.LOAD_ERROR, _uri, isDependency, event.message);
if (hasEventListener(LoaderEvent.LOAD_ERROR)) {
dispatchEvent(event);
handled = true;
} else {
// TODO: Consider not doing this even when AssetLoader does
// have it's own LOAD_ERROR listener
var i:uint, len:uint = _errorHandlers.length;
for (i = 0; i < len; i++) {
var handlerFunction:Function = _errorHandlers[i];
handled ||= Boolean(handlerFunction(event));
}
}
if (handled) {
if (isDependency && !event.isDefaultPrevented()) {
_loadingDependency.resolveFailure();
retrieveNext();
} else {
// Either this was the base file (last left in the stack) or
// default behavior was prevented by the handlers, and hence
// there is nothing more to do than clean up and bail.
dispose();
return;
}
} else {
// Error event was not handled by listeners directly on AssetLoader or
// on any of the subscribed loaders (in the list of error handlers.)
throw new Error(event.message);
}
}
/**
* Called when a dependency parsing failed, and dispatches a <code>ParserEvent.PARSE_ERROR</code>
* @param event
*/
private function onParserError(event:ParserEvent):void
{
var handled:Boolean;
var isDependency:Boolean = (_loadingDependency != _baseDependency);
var loader:SingleFileLoader = SingleFileLoader(event.target);
removeEventListeners(loader);
event = new ParserEvent(ParserEvent.PARSE_ERROR, event.message);
if (hasEventListener(ParserEvent.PARSE_ERROR)) {
dispatchEvent(event);
handled = true;
} else {
// TODO: Consider not doing this even when AssetLoader does
// have it's own LOAD_ERROR listener
var i:uint, len:uint = _parseErrorHandlers.length;
for (i = 0; i < len; i++) {
var handlerFunction:Function = _parseErrorHandlers[i];
handled ||= Boolean(handlerFunction(event));
}
}
if (handled) {
dispose();
return;
} else {
// Error event was not handled by listeners directly on AssetLoader or
// on any of the subscribed loaders (in the list of error handlers.)
throw new Error(event.message);
}
}
private function onAssetComplete(event:AssetEvent):void
{
// Event is dispatched twice per asset (once as generic ASSET_COMPLETE,
// and once as type-specific, e.g. MESH_COMPLETE.) Do this only once.
if (event.type == AssetEvent.ASSET_COMPLETE) {
// Add loaded asset to list of assets retrieved as part
// of the current dependency. This list will be inspected
// by the parent parser when dependency is resolved
if (_loadingDependency)
_loadingDependency.assets.push(event.asset);
event.asset.resetAssetPath(event.asset.name, _namespace);
}
if (!_loadingDependency.suppresAssetEvents)
dispatchEvent(event.clone());
}
private function onReadyForDependencies(event:ParserEvent):void
{
var loader:SingleFileLoader = SingleFileLoader(event.currentTarget);
if (_context && !_context.includeDependencies)
loader.parser.resumeParsingAfterDependencies();
else
retrieveLoaderDependencies(loader);
}
/**
* Called when a single dependency was parsed, and pushes further dependencies onto the stack.
* @param event
*/
private function onRetrievalComplete(event:LoaderEvent):void
{
var loader:SingleFileLoader = SingleFileLoader(event.target);
// Resolve this dependency
_loadingDependency.setData(loader.data);
_loadingDependency.success = true;
dispatchEvent(new LoaderEvent(LoaderEvent.DEPENDENCY_COMPLETE, event.url));
removeEventListeners(loader);
// Retrieve any last dependencies remaining on this loader, or
// if none exists, just move on.
if (loader.dependencies.length && (!_context || _context.includeDependencies)) { //context may be null
retrieveLoaderDependencies(loader);
} else
retrieveNext();
}
/**
* Called when an image is too large or it's dimensions are not a power of 2
* @param event
*/
private function onTextureSizeError(event:AssetEvent):void
{
event.asset.name = _loadingDependency.resolveName(event.asset);
dispatchEvent(event);
}
private function addEventListeners(loader:SingleFileLoader):void
{
loader.addEventListener(LoaderEvent.DEPENDENCY_COMPLETE, onRetrievalComplete);
loader.addEventListener(LoaderEvent.LOAD_ERROR, onRetrievalFailed);
loader.addEventListener(AssetEvent.TEXTURE_SIZE_ERROR, onTextureSizeError);
loader.addEventListener(AssetEvent.ASSET_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.ANIMATION_SET_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.ANIMATION_STATE_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.ANIMATION_NODE_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.STATE_TRANSITION_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.TEXTURE_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.CONTAINER_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.GEOMETRY_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.MATERIAL_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.MESH_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.ENTITY_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.SKELETON_COMPLETE, onAssetComplete);
loader.addEventListener(AssetEvent.SKELETON_POSE_COMPLETE, onAssetComplete);
loader.addEventListener(ParserEvent.READY_FOR_DEPENDENCIES, onReadyForDependencies);
loader.addEventListener(ParserEvent.PARSE_ERROR, onParserError);
}
private function removeEventListeners(loader:SingleFileLoader):void
{
loader.removeEventListener(ParserEvent.READY_FOR_DEPENDENCIES, onReadyForDependencies);
loader.removeEventListener(LoaderEvent.DEPENDENCY_COMPLETE, onRetrievalComplete);
loader.removeEventListener(LoaderEvent.LOAD_ERROR, onRetrievalFailed);
loader.removeEventListener(AssetEvent.TEXTURE_SIZE_ERROR, onTextureSizeError);
loader.removeEventListener(AssetEvent.ASSET_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.ANIMATION_SET_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.ANIMATION_STATE_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.ANIMATION_NODE_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.STATE_TRANSITION_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.TEXTURE_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.CONTAINER_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.GEOMETRY_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.MATERIAL_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.MESH_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.ENTITY_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.SKELETON_COMPLETE, onAssetComplete);
loader.removeEventListener(AssetEvent.SKELETON_POSE_COMPLETE, onAssetComplete);
loader.removeEventListener(ParserEvent.PARSE_ERROR, onParserError);
}
public function stop():void
{
dispose();
}
private function dispose():void
{
_errorHandlers = null;
_parseErrorHandlers = null;
_context = null;
_token = null;
_stack = null;
if (_loadingDependency && _loadingDependency.loader)
removeEventListeners(_loadingDependency.loader);
_loadingDependency = null;
}
/**
* @private
* This method is used by other loader classes (e.g. Loader3D and AssetLibraryBundle) to
* add error event listeners to the AssetLoader instance. This system is used instead of
* the regular EventDispatcher system so that the AssetLibrary error handler can be sure
* that if hasEventListener() returns true, it's client code that's listening for the
* event. Secondly, functions added as error handler through this custom method are
* expected to return a boolean value indicating whether the event was handled (i.e.
* whether they in turn had any client code listening for the event.) If no handlers
* return true, the AssetLoader knows that the event wasn't handled and will throw an RTE.
*/
arcane function addParseErrorHandler(handler:Function):void
{
if (_parseErrorHandlers.indexOf(handler) < 0)
_parseErrorHandlers.push(handler);
}
arcane function addErrorHandler(handler:Function):void
{
if (_errorHandlers.indexOf(handler) < 0)
_errorHandlers.push(handler);
}
}
}
|
/*
* Copyright (c) 2009 the original author or authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.swiftsuspenders.support.injectees
{
import org.swiftsuspenders.support.types.Clazz;
public class TwoParametersConstructorInjectee
{
private var m_dependency : Clazz;
private var m_dependency2 : String;
public function getDependency() : Clazz
{
return m_dependency;
}
public function getDependency2() : String
{
return m_dependency2;
}
public function TwoParametersConstructorInjectee(dependency:Clazz, dependency2:String)
{
m_dependency = dependency;
m_dependency2 = dependency2;
}
}
} |
/*
Adobe Systems Incorporated(r) Source Code License Agreement
Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved.
Please read this Source Code License Agreement carefully before using
the source code.
Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable copyright license, to reproduce,
prepare derivative works of, publicly display, publicly perform, and
distribute this source code and such derivative works in source or
object code form without any attribution requirements.
The name "Adobe Systems Incorporated" must not be used to endorse or promote products
derived from the source code without prior written permission.
You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and
against any loss, damage, claims or lawsuits, including attorney's
fees that arise or result from your use or distribution of the source
code.
THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT
ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF
NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA
OR ITS SUPPLIERS 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 SOURCE CODE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package adobe.webapis.events
{
import flash.events.Event;
/**
* Event class that contains data loaded from remote services.
*
* @author Mike Chambers
*/
public class ServiceEvent extends Event
{
private var _data:Object = new Object();;
/**
* Constructor for ServiceEvent class.
*
* @param type The type of event that the instance represents.
*/
public function ServiceEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
/**
* This object contains data loaded in response
* to remote service calls, and properties associated with that call.
*/
public function get data():Object
{
return _data;
}
public function set data(d:Object):void
{
_data = d;
}
}
} |
table wgEncodeCell
"Cell types used by ENCODE (2007-2012)"
(
uint id; "internal id"
string term; "public identifier"
string description; "descriptive phrase"
string tissue; "organ, anatomical site"
string type; "tissue, cell line, or differentiated"
string cancer; "cancer or normal"
string developmental; "cell lineage"
string sex; "M, F, or U for unknown"
string vendor; "name of vendor or lab provider"
string vendorId; "vendor product code or identifier"
string url; "order URL or protocol document"
string ontoTerm; "ontology term"
string btOntoTerm; "ontology term from Brenda Tissue Ontology"
string donor; "donor accession at encodeproject.org"
)
|
table txGraph
"A transcription graph. Includes alt-splicing info."
(
string tName; "name of target sequence, often a chrom."
int tStart; "First bac touched by graph."
int tEnd; "Start position in first bac."
string name; "Human readable name."
char[2] strand; "+ or - strand."
uint vertexCount; "Number of vertices in graph."
simple txVertex[vertexCount] vertices; "Splice sites and soft ends."
uint edgeCount; "Number of edges in graph."
object txEdge[edgeCount] edgeList; "Edges (introns and exons) in graph."
int sourceCount; "Number of sources of evidence."
simple txSource[sourceCount] sources; "Sources of evidence."
)
simple txVertex
"A vertex in a transcription graph - splice site or soft end"
(
int position; "Vertex position in genomic sequence."
ubyte type; "Vertex type - ggSoftStart, ggHardStart, etc."
)
object txEdge
"An edge in a transcription graph - exon or intron"
(
int startIx; "Index of start in vertex array"
int endIx; "Index of end in vertex array"
ubyte type; "Edge type"
int evCount; "Count of evidence"
object txEvidence[evCount] evList; "List of evidence"
)
object txEvidence
"Information on evidence for an edge."
(
int sourceId; "Id (index) in sources list"
int start; "Start position"
int end; "End position"
)
simple txSource
"Source of evidence in graph."
(
string type; "Type: refSeq, mrna, est, etc."
string accession; "GenBank accession. With type forms a key"
)
|
package feathers.tests
{
import feathers.controls.TabBar;
import feathers.controls.ToggleButton;
import feathers.data.ListCollection;
import org.flexunit.Assert;
import starling.display.Quad;
import starling.events.Event;
public class TabBarEmptyDataProviderTests
{
private var _tabBar:TabBar;
[Before]
public function prepare():void
{
this._tabBar = new TabBar();
this._tabBar.tabFactory = function():ToggleButton
{
var tab:ToggleButton = new ToggleButton();
tab.defaultSkin = new Quad(200, 200);
return tab;
}
TestFeathers.starlingRoot.addChild(this._tabBar);
this._tabBar.validate();
}
[After]
public function cleanup():void
{
this._tabBar.removeFromParent(true);
this._tabBar = null;
Assert.assertStrictlyEquals("Child not removed from Starling root on cleanup.", 0, TestFeathers.starlingRoot.numChildren);
}
[Test]
public function testNoSelection():void
{
Assert.assertStrictlyEquals("The selectedIndex property was not equal to -1",
-1, this._tabBar.selectedIndex);
Assert.assertStrictlyEquals("The selectedItem property was not equal to null",
null, this._tabBar.selectedItem);
}
[Test]
public function testSelectFirstItemOnSetDataProvider():void
{
var hasChanged:Boolean = false;
this._tabBar.addEventListener(Event.CHANGE, function(event:Event):void
{
hasChanged = true;
});
var dataProvider:ListCollection = new ListCollection(
[
{ label: "One" },
{ label: "Two" },
{ label: "Three" },
]);
this._tabBar.dataProvider = dataProvider;
Assert.assertTrue("Event.CHANGE was not dispatched", hasChanged);
Assert.assertStrictlyEquals("The selectedIndex property was not equal to 0",
0, this._tabBar.selectedIndex);
Assert.assertStrictlyEquals("The selectedItem property was not equal to the first item",
dataProvider.getItemAt(0), this._tabBar.selectedItem);
}
}
}
|
package freevana.view
{
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
import freevana.util.Utils;
import mx.core.UIComponent;
import org.flowplayer.view.*;
/*
* @author tirino
*/
public class FlowVideoPlayer extends EventDispatcher implements IVideoPlayer
{
public static const SUBTITLES_SMALL:String = 'SMALL';
public static const SUBTITLES_NORMAL:String = 'NORMAL';
public static const SUBTITLES_BIG:String = 'BIG';
public static const PLAYER_INITIALIZING:String = "VideoPlayerInitializing";
public static const PLAYER_READY:String = "VideoPlayerReady";
private var _flowplayerAppEvent:String = "FreevanaAppLoaded";
private var _videoComponent:UIComponent = null;
private var _preloader:* = null;
private var _flowLauncher:Launcher = null;
private var _flowPlayer:Flowplayer = null;
private var _movieIsLoading:Boolean = false;
private var _movieURL:String;
private var _subtitleURL:String;
private var _subtitleSize:int = 20;
private var _subtitleBoxSize:int = 50;
private var __prefix__:String = '';
private var __playerConfig__:String;
public function FlowVideoPlayer(movieURL:String, subtitleURL:String, playerConfig:String=null, prefix:String=null):void
{
if (prefix) {
this.__prefix__ = prefix;
}
if (playerConfig) {
this.__playerConfig__ = playerConfig;
}
setMovieURL(movieURL);
setSubtitleURL(subtitleURL);
}
public function setMovieURL(movieURL:String):void
{
_movieURL = movieURL;
}
public function setSubtitleURL(subtitleURL:String):void
{
_subtitleURL = subtitleURL;
}
public function setSubtitleSize(subsSize:String):void
{
if (subsSize == SUBTITLES_SMALL) {
_subtitleSize = 16;
_subtitleBoxSize = 46;
} else if (subsSize == SUBTITLES_BIG) {
_subtitleSize = 24;
_subtitleBoxSize = 60;
}
}
public function getUIComponent():UIComponent
{
return _videoComponent;
}
public function init():void
{
trace("[main] loading movie...");
// TODO: if _subtitleURL is null or empty, don't include subs configuration code
// Build the config string
// TODO: work-around for Linux bug
var captionsOpacity:String = '0.4';
if (Utils.isLinux()) {
captionsOpacity = '0.0';
}
var playerConfig:String = this.__playerConfig__;
if (this.__playerConfig__ == null) {
var captionsPlugins:String = '"captions":{"url":"{{prefix}}/videoplayers/flowplayer.captions-3.2.3.swf","captionTarget":"content", "button":{"width":23,"height":15,"right":5,"bottom":30,"label":"Sub","opacity":'+captionsOpacity+'}}';
captionsPlugins = captionsPlugins.replace('{{prefix}}',this.__prefix__);
var contentStyle:String = '"style":{"body":{"fontSize":"'+_subtitleSize+'","fontFamily":"Arial","textAlign":"center","color":"#FFFFFF"}}';
var contentPlugins:String = '"content":{"url":"{{prefix}}/videoplayers/flowplayer.content-3.2.0.swf","opacity":1.0,"bottom":30, "width":"90%","height":'+_subtitleBoxSize+',"backgroundColor":"transparent","backgroundGradient":"none","borderRadius":4,"border":0,"textDecoration":"outline",'+contentStyle+'}';
contentPlugins = contentPlugins.replace('{{prefix}}',this.__prefix__);
var plugins:String = '"plugins":{'+captionsPlugins+','+contentPlugins+'}';
if (_subtitleURL && _subtitleURL != '') {
playerConfig = '{"canvas":{"backgroundGradient":"none"},"clip":{"url":"'+_movieURL+'","captionUrl":"'+_subtitleURL+'","scaling":"fit","autoPlay":true,"autoBuffering":true},'+plugins+'}'
} else {
playerConfig = '{"canvas":{"backgroundGradient":"none"},"clip":{"url":"'+_movieURL+'","scaling":"fit","autoPlay":true,"autoBuffering":true},'+plugins+'}'
}
}
trace("[main] --> loading movie...");
var swfURL:String = '{{prefix}}/videoplayers/flowplayer-3.2.8.swf?config=' + escape(playerConfig);
swfURL = swfURL.replace('{{prefix}}',this.__prefix__);
trace(playerConfig);
trace('[main] --> '+swfURL);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, handleInit);
function handleInit(event:Event):void {
_preloader = event.target.loader.content;
if (_preloader.getAppObject()) {
_flowLauncher = (_preloader.getAppObject() as Launcher);
_flowPlayer = _flowLauncher.getFlowplayer();
_flowPlayer.config.getPlaylist().onError(function(ev:*):void {
trace("[onError!] " + ev.toString());
});
dispatchEvent(new Event(VideoPlayer.PLAYER_READY));
} else {
_preloader.addEventListener(_flowplayerAppEvent, handleFreevanaAppLoaded);
function handleFreevanaAppLoaded(ev:Event):void {
_flowLauncher = (_preloader.getAppObject() as Launcher);
_flowPlayer = _flowLauncher.getFlowplayer();
_flowPlayer.config.getPlaylist().onError(function(ev:*):void {
trace("[onError!] " + ev.toString());
});
dispatchEvent(new Event(VideoPlayer.PLAYER_READY));
}
}
var myComp:UIComponent = new UIComponent();
myComp.addChild(event.target.loader.content);
_videoComponent = myComp;
dispatchEvent(new Event(VideoPlayer.PLAYER_INITIALIZING));
}
function onPauseEv(ev:Event):void {
trace("[VideoPlaer] onPause! " + ev.toString());
}
// Load video player from external SWF
loader.load(new URLRequest(swfURL));
loader.addEventListener(IOErrorEvent.IO_ERROR,
function (event:IOErrorEvent):void {
trace('(@@@) !!!');
}
);
}
public function onAddedToStage():void {
// nothing
}
}
} |
package {
import flash.net.FileReference;
internal class FileItem
{
private static var file_id_sequence:Number = 0; // tracks the file id sequence
private var postObject:Object;
public var file_reference:FileReference;
public var id:String;
public var index:Number = -1;
public var file_status:int = 0;
private var js_object:Object;
public static var FILE_STATUS_QUEUED:int = -1;
public static var FILE_STATUS_IN_PROGRESS:int = -2;
public static var FILE_STATUS_ERROR:int = -3;
public static var FILE_STATUS_SUCCESS:int = -4;
public static var FILE_STATUS_CANCELLED:int = -5;
public static var FILE_STATUS_NEW:int = -6; // This file status should never be sent to JavaScript
public function FileItem(file_reference:FileReference, control_id:String, index:Number)
{
this.postObject = {};
this.file_reference = file_reference;
this.id = control_id + "_" + (FileItem.file_id_sequence++);
this.file_status = FileItem.FILE_STATUS_NEW;
this.index = index;
this.js_object = {
id: this.id,
index: this.index,
post: this.GetPostObject()
};
// Cleanly attempt to retrieve the FileReference info
// this can fail and so is wrapped in try..catch
try {
this.js_object.name = this.file_reference.name;
this.js_object.size = this.file_reference.size;
this.js_object.type = this.file_reference.type || "";
this.js_object.creationdate = this.file_reference.creationDate || new Date(0);
this.js_object.modificationdate = this.file_reference.modificationDate || new Date(0);
} catch (ex:Error) {
this.file_status = FileItem.FILE_STATUS_ERROR;
}
this.js_object.filestatus = this.file_status;
}
public function AddParam(name:String, value:String):void {
this.postObject[name] = value;
}
public function RemoveParam(name:String):void {
delete this.postObject[name];
}
public function GetPostObject(escape:Boolean = false):Object {
if (escape) {
var escapedPostObject:Object = { };
for (var k:String in this.postObject) {
if (this.postObject.hasOwnProperty(k)) {
var escapedName:String = FileItem.EscapeParamName(k);
escapedPostObject[escapedName] = this.postObject[k];
}
}
return escapedPostObject;
} else {
return this.postObject;
}
}
// Create the simply file object that is passed to the browser
public function ToJavaScriptObject():Object {
this.js_object.filestatus = this.file_status;
this.js_object.post = this.GetPostObject(true);
return this.js_object;
}
public function toString():String {
return "FileItem - ID: " + this.id;
}
/*
// The purpose of this function is to escape the property names so when Flash
// passes them back to javascript they can be interpretted correctly.
// ***They have to be unescaped again by JavaScript.**
//
// This works around a bug where Flash sends objects this way:
// object.parametername = "value";
// instead of
// object["parametername"] = "value";
// This can be a problem if the parameter name has characters that are not
// allowed in JavaScript identifiers:
// object.parameter.name! = "value";
// does not work but,
// object["parameter.name!"] = "value";
// would have worked.
*/
public static function EscapeParamName(name:String):String {
name = name.replace(/[^a-z0-9_]/gi, FileItem.EscapeCharacter);
name = name.replace(/^[0-9]/, FileItem.EscapeCharacter);
return name;
}
public static function EscapeCharacter():String {
return "$" + ("0000" + arguments[0].charCodeAt(0).toString(16)).substr(-4, 4);
}
}
} |
package
{
import com.core.Keyboard;
import com.module.ControllerRegister;
import com.xyzdl.components.Image;
import xyzdlcore.constants.CommonConstant;
import xyzdlcore.event.DispatchEvent;
import xyzdlcore.event.ModuleMessage;
import xyzdlcore.loader.LoaderBean;
import xyzdlcore.utils.AssetUtil;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.system.Security;
import test.Test4Client;
[SWF(width = 638, height = 425, frameRate = "30", backgroundColor = "#eeeeee")] //272822
public class Client extends Sprite
{
private static var _singleton:Client;
public static function get singleton():Client
{
_singleton ||= new Client();
return _singleton;
}
public function Client()
{
flash.system.Security.allowDomain("*");
flash.system.Security.allowInsecureDomain("*");
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event):void
{
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
Keyboard.init(stage); //初始化键盘响应事件
var lb:LoaderBean = new LoaderBean(); //顺序为先加载本地配置文件,再初始化配置类
lb.loadCompleteHandler = initApp;
// lb.loadCompleteHandler = testTemp;
lb.add(AssetUtil.CORE_CONFIG);
lb.add(AssetUtil.COMMON_CONFIG);
lb.add(AssetUtil.GENERAL_CONFIG);
lb.add(AssetUtil.LANGUAGE_PACKAGE);
lb.add(AssetUtil.DATA_CONFIG);
lb.start();
}
private function testTemp():void
{
new Test4Client();
}
private function initApp():void
{
//初始化的顺序十分重要,一定要注意
CoreConfig.initConf(); //第一:加载好核心配置文件后,初始化配置类
Config.initConf();
Lan.singleton;
DataConfig.singleton;
initView(); //第二:初始化基本界面
Security.loadPolicyFile("xmlsocket://" + Config.host + ":843");
ControllerRegister.singleton; //第三:初始化控制器,所有模块事件,都在控制器初始化过后
CSocket.singleton.connectToServer(); //第四:建立通信连接
}
private function initView():void
{
App.init(stage);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener(Event.RESIZE, resizeCom);
this.addChild(new Image(AssetUtil.RES + CommonConstant.IMG_BORDER));
Console.singleton.width = 638;
Console.singleton.height = 425;
this.addChild(Console.singleton);
Console.addMsg(Lan.val("1001") + (new Date()).toLocaleString());
Console.addMsg(Lan.val("1002") + Config.CLIENT_VERSION);
}
public function resizeCom(e:Event):void
{
if(stage)
DispatchEvent(ModuleMessage.VIEW_STAGE_RESIZE);
}
}
}
|
package laya.webgl.shader.d2.value {
import laya.resource.Bitmap;
import laya.resource.Texture;
import laya.webgl.WebGL;
import laya.webgl.shader.BaseShader;
import laya.webgl.shader.d2.skinAnishader.SkinSV;
import laya.webgl.WebGLContext;
import laya.webgl.canvas.DrawStyle;
import laya.webgl.shader.Shader;
import laya.webgl.shader.ShaderValue;
import laya.webgl.shader.d2.Shader2D;
import laya.webgl.shader.d2.Shader2X;
import laya.webgl.shader.d2.ShaderDefines2D;
import laya.webgl.utils.CONST3D2D;
import laya.webgl.utils.MatirxArray;
import laya.webgl.utils.RenderState2D;
public class Value2D extends ShaderValue
{
/*[DISABLE-ADD-VARIABLE-DEFAULT-VALUE]*/
public static var _POSITION:Array;
public static var _TEXCOORD:Array;
protected static var _cache:Array=[];
protected static var _typeClass:Object = [];
public static var TEMPMAT4_ARRAY:Array=/*[STATIC SAFE]*/ [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
private static function _initone(type:int, classT:*):void
{
_typeClass[type] = classT;
_cache[type] = [];
_cache[type]._length = 0;
}
public static function __init__():void
{
_POSITION = [2, WebGLContext.FLOAT, false, 4 * CONST3D2D.BYTES_PE, 0];
_TEXCOORD = [2, WebGLContext.FLOAT, false, 4 * CONST3D2D.BYTES_PE, 2 * CONST3D2D.BYTES_PE];
_initone(ShaderDefines2D.COLOR2D, Color2dSV);
_initone(ShaderDefines2D.PRIMITIVE, PrimitiveSV);
_initone(ShaderDefines2D.FILLTEXTURE, FillTextureSV);
_initone(ShaderDefines2D.SKINMESH, SkinSV);
_initone(ShaderDefines2D.TEXTURE2D, TextureSV);
_initone(ShaderDefines2D.TEXTURE2D | ShaderDefines2D.COLORADD,TextSV);
_initone(ShaderDefines2D.TEXTURE2D | ShaderDefines2D.FILTERGLOW, TextureSV);
}
public var defines:ShaderDefines2D = new ShaderDefines2D();
public var position:Array = _POSITION;
public var size:Array = [0, 0];
public var alpha:Number = 1.0;
public var mmat:Array;
public var ALPHA:Number = 1.0;
public var shader:Shader;
public var mainID:int;
public var subID:int=0;
public var filters:Array;
public var textureHost:Texture;
public var texture:*;
public var fillStyle:DrawStyle;
public var color:Array;
public var strokeStyle:DrawStyle;
public var colorAdd:Array;
public var glTexture:Bitmap;
/*[IF-FLASH]*/public var mul_mmat:Array;//存储两个矩阵相乘的值,mmat*ummat2
public var u_mmat2:Array;
private var _inClassCache:Array;
private var _cacheID:int = 0;
public function Value2D(mainID:int,subID:int)
{
this.mainID = mainID;
this.subID = subID;
this.textureHost = null;
this.texture = null;
this.fillStyle = null;
this.color = null;
this.strokeStyle = null;
this.colorAdd = null;
this.glTexture = null;
this.u_mmat2 = null;
/*[IF-FLASH]*/this.mul_mmat = null;
_cacheID = mainID|subID;
_inClassCache = _cache[_cacheID];
if (mainID>0 && !_inClassCache)
{
_inClassCache = _cache[_cacheID] = [];
_inClassCache._length = 0;
}
//_initDef=(_cacheID == (ShaderDefines2D.TEXTURE2D | ShaderDefines2D.COLORADD))?ShaderDefines2D.COLORADD:mainID;
clear();
}
public function setValue(value:Shader2D):void{}
//throw new Error("todo in subclass");
public function refresh():ShaderValue
{
var size:Array = this.size;
size[0] = RenderState2D.width;
size[1] = RenderState2D.height;
alpha = ALPHA * RenderState2D.worldAlpha;
mmat = RenderState2D.worldMatrix4;
return this;
}
private function _ShaderWithCompile():Shader2X
{
return Shader.withCompile2D(0, mainID, defines.toNameDic(), mainID | defines._value, Shader2X.create) as Shader2X;
}
private function _withWorldShaderDefines():Shader2X
{
var defs:ShaderDefines2D = RenderState2D.worldShaderDefines;
var sd:Shader2X = Shader.sharders[mainID | defines._value | defs.getValue()] as Shader2X;
if (!sd)
{
var def:Object = {};
var dic:Object;
var name:String;
dic = defines.toNameDic(); for (name in dic) def[name] = "";
dic = defs.toNameDic(); for (name in dic) def[name] = "";
sd=Shader.withCompile2D(0, mainID, def, mainID | defines._value| defs.getValue(), Shader2X.create) as Shader2X;
}
var worldFilters:Array = RenderState2D.worldFilters;
if (!worldFilters) return sd;
var n:int = worldFilters.length,f:*;
for (var i:int = 0; i < n; i++)
{
( (f= worldFilters[i])) && f.action.setValue(this);
}
return sd;
}
public function upload():void
{
var renderstate2d:*= RenderState2D;
alpha = ALPHA * renderstate2d.worldAlpha;
if ( RenderState2D.worldMatrix4 !== RenderState2D.TEMPMAT4_ARRAY) defines.add(ShaderDefines2D.WORLDMAT);
(WebGL.shaderHighPrecision) && (defines.add(ShaderDefines2D.SHADERDEFINE_FSHIGHPRECISION));
var sd:Shader2X = renderstate2d.worldShaderDefines?_withWorldShaderDefines():(Shader.sharders[mainID | defines._value] as Shader2X || _ShaderWithCompile());
var params:Array;
this.size[0] = renderstate2d.width, this.size[1] = renderstate2d.height;
mmat = renderstate2d.worldMatrix4;
/*[IF-FLASH]*/MatirxArray.ArrayMul(mmat, this.u_mmat2, TEMPMAT4_ARRAY);
/*[IF-FLASH]*/mul_mmat = TEMPMAT4_ARRAY;
if (BaseShader.activeShader!==sd)
{
if (sd._shaderValueWidth !== renderstate2d.width || sd._shaderValueHeight !== renderstate2d.height){
sd._shaderValueWidth = renderstate2d.width;
sd._shaderValueHeight = renderstate2d.height;
}
else{
params = sd._params2dQuick2 || sd._make2dQuick2();
}
sd.upload(this, params);
}
else
{
if (sd._shaderValueWidth !== renderstate2d.width || sd._shaderValueHeight !== renderstate2d.height){
sd._shaderValueWidth = renderstate2d.width;
sd._shaderValueHeight = renderstate2d.height;
}
else{
params = (sd._params2dQuick1) || sd._make2dQuick1();
}
sd.upload(this, params);
}
}
public function setFilters(value:Array):void
{
filters = value;
if (!value)
return;
var n:int = value.length, f:*;
for (var i:int = 0; i < n; i++)
{
f = value[i];
if (f)
{
defines.add(f.type);//搬到setValue中
f.action.setValue(this);
}
}
}
public function clear():void
{
defines.setValue(subID);
}
public function release():void
{
_inClassCache[_inClassCache._length++] = this;
this.fillStyle = null;
this.strokeStyle = null;
this.clear();
}
public static function create(mainType:int,subType:int):Value2D
{
var types:Array = _cache[mainType|subType];
if (types._length)
return types[--types._length];
else
return new _typeClass[mainType|subType](subType);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.