commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
da2b484928642d4eb323f911db95eb3128d83747
|
src/RTMP.as
|
src/RTMP.as
|
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.net.NetStream;
import flash.events.*;
import flash.utils.setTimeout;
import org.osmf.containers.MediaContainer;
import org.osmf.elements.VideoElement;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.events.TimeEvent;
import org.osmf.events.BufferEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.events.LoadEvent;
import org.osmf.traits.MediaTraitType;
[SWF(width="640", height="360")]
public class RTMP extends Sprite {
private var playbackId:String;
private var mediaFactory:DefaultMediaFactory;
private var mediaContainer:MediaContainer;
private var mediaPlayer:MediaPlayer;
private var netStream:NetStream;
private var mediaElement:MediaElement;
private var netStreamLoadTrait:NetStreamLoadTrait;
private var playbackState:String = "IDLE";
public function RTMP() {
Security.allowDomain('*');
Security.allowInsecureDomain('*');
playbackId = this.root.loaderInfo.parameters.playbackId;
mediaFactory = new DefaultMediaFactory();
mediaContainer = new MediaContainer();
setupCallbacks();
setupGetters();
ExternalInterface.call('console.log', 'clappr rtmp 0.7-alpha');
_triggerEvent('flashready');
}
private function setupCallbacks():void {
ExternalInterface.addCallback("playerPlay", playerPlay);
ExternalInterface.addCallback("playerResume", playerPlay);
ExternalInterface.addCallback("playerPause", playerPause);
ExternalInterface.addCallback("playerStop", playerStop);
ExternalInterface.addCallback("playerSeek", playerSeek);
ExternalInterface.addCallback("playerVolume", playerVolume);
}
private function setupGetters():void {
ExternalInterface.addCallback("getState", getState);
ExternalInterface.addCallback("getPosition", getPosition);
ExternalInterface.addCallback("getDuration", getDuration);
}
private function onTraitAdd(event:MediaElementEvent):void {
if (mediaElement.hasTrait(MediaTraitType.LOAD)) {
netStreamLoadTrait = mediaElement.getTrait(MediaTraitType.LOAD) as NetStreamLoadTrait;
netStreamLoadTrait.addEventListener(LoadEvent.LOAD_STATE_CHANGE, onLoaded);
}
}
private function onLoaded(event:LoadEvent):void {
netStream = netStreamLoadTrait.netStream;
netStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
mediaPlayer.play();
}
private function netStatusHandler(event:NetStatusEvent):void {
ExternalInterface.call('console.log', '-> ' + event.info.code);
if (playbackState == "ENDED") {
return;
} else if (event.info.code == "NetStream.Buffer.Full") {
playbackState = "PLAYING";
_triggerEvent('statechanged');
} else if (event.info.code == "NetStream.Buffer.Empty" || event.info.code == "NetStream.Seek.Notify") {
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
}
}
private function playerPlay(url:String):void {
if (!mediaElement) {
ExternalInterface.call('console.log', 'player play, no mediaelement');
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
mediaElement = mediaFactory.createMediaElement(new URLResource(url));
mediaElement.addEventListener(MediaElementEvent.TRAIT_ADD, onTraitAdd);
mediaPlayer = new MediaPlayer(mediaElement);
mediaPlayer.autoPlay = false;
mediaPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.DURATION_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.COMPLETE, onFinish);
mediaContainer.addMediaElement(mediaElement);
addChild(mediaContainer);
} else {
ExternalInterface.call('console.log', 'playing with media element');
mediaPlayer.play();
}
}
private function playerPause():void {
ExternalInterface.call('console.log', 'player pause');
mediaPlayer.pause();
}
private function playerSeek(seconds:Number):void {
mediaPlayer.seek(seconds);
}
private function playerStop():void {
mediaPlayer.stop();
}
private function playerVolume(level:Number):void {
mediaPlayer.volume = level/100;
}
private function getState():String {
return playbackState;
}
private function getPosition():Number {
return mediaPlayer.currentTime;
}
private function getDuration():Number {
return mediaPlayer.duration;
}
private function onTimeUpdated(event:TimeEvent):void {
_triggerEvent('progress');
_triggerEvent('timeupdate');
}
private function onFinish(event:TimeEvent):void {
mediaPlayer.stop();
ExternalInterface.call('console.log', 'ended');
playbackState = 'ENDED';
_triggerEvent('statechanged');
}
private function _triggerEvent(name: String):void {
ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")');
}
}
}
|
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.net.NetStream;
import flash.events.*;
import flash.utils.setTimeout;
import org.osmf.containers.MediaContainer;
import org.osmf.elements.VideoElement;
import org.osmf.net.NetStreamLoadTrait;
import org.osmf.media.DefaultMediaFactory;
import org.osmf.media.MediaElement;
import org.osmf.media.MediaPlayer;
import org.osmf.media.URLResource;
import org.osmf.events.TimeEvent;
import org.osmf.events.BufferEvent;
import org.osmf.events.MediaElementEvent;
import org.osmf.events.LoadEvent;
import org.osmf.traits.MediaTraitType;
[SWF(width="640", height="360")]
public class RTMP extends Sprite {
private var playbackId:String;
private var mediaFactory:DefaultMediaFactory;
private var mediaContainer:MediaContainer;
private var mediaPlayer:MediaPlayer;
private var netStream:NetStream;
private var mediaElement:MediaElement;
private var netStreamLoadTrait:NetStreamLoadTrait;
private var playbackState:String = "IDLE";
public function RTMP() {
Security.allowDomain('*');
Security.allowInsecureDomain('*');
playbackId = this.root.loaderInfo.parameters.playbackId;
mediaFactory = new DefaultMediaFactory();
mediaContainer = new MediaContainer();
setupCallbacks();
setupGetters();
ExternalInterface.call('console.log', 'clappr rtmp 0.8-alpha');
_triggerEvent('flashready');
}
private function setupCallbacks():void {
ExternalInterface.addCallback("playerPlay", playerPlay);
ExternalInterface.addCallback("playerResume", playerPlay);
ExternalInterface.addCallback("playerPause", playerPause);
ExternalInterface.addCallback("playerStop", playerStop);
ExternalInterface.addCallback("playerSeek", playerSeek);
ExternalInterface.addCallback("playerVolume", playerVolume);
}
private function setupGetters():void {
ExternalInterface.addCallback("getState", getState);
ExternalInterface.addCallback("getPosition", getPosition);
ExternalInterface.addCallback("getDuration", getDuration);
}
private function onTraitAdd(event:MediaElementEvent):void {
if (mediaElement.hasTrait(MediaTraitType.LOAD)) {
netStreamLoadTrait = mediaElement.getTrait(MediaTraitType.LOAD) as NetStreamLoadTrait;
netStreamLoadTrait.addEventListener(LoadEvent.LOAD_STATE_CHANGE, onLoaded);
}
}
private function onLoaded(event:LoadEvent):void {
netStream = netStreamLoadTrait.netStream;
netStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
mediaPlayer.play();
}
private function netStatusHandler(event:NetStatusEvent):void {
if (playbackState == "ENDED") {
return;
} else if (event.info.code == "NetStream.Buffer.Full") {
playbackState = "PLAYING";
_triggerEvent('statechanged');
} else if (event.info.code == "NetStream.Buffer.Empty" || event.info.code == "NetStream.Seek.Notify") {
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
}
}
private function playerPlay(url:String=null):void {
if (!mediaElement) {
playbackState = "PLAYING_BUFFERING";
_triggerEvent('statechanged');
mediaElement = mediaFactory.createMediaElement(new URLResource(url));
mediaElement.addEventListener(MediaElementEvent.TRAIT_ADD, onTraitAdd);
mediaPlayer = new MediaPlayer(mediaElement);
mediaPlayer.autoPlay = false;
mediaPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.DURATION_CHANGE, onTimeUpdated);
mediaPlayer.addEventListener(TimeEvent.COMPLETE, onFinish);
mediaContainer.addMediaElement(mediaElement);
addChild(mediaContainer);
} else {
ExternalInterface.call('console.log', 'playing with media element');
mediaPlayer.play();
}
}
private function playerPause():void {
ExternalInterface.call('console.log', 'player pause');
mediaPlayer.pause();
playbackState = "PAUSED";
}
private function playerSeek(seconds:Number):void {
mediaPlayer.seek(seconds);
}
private function playerStop():void {
mediaPlayer.stop();
playbackState = "IDLE";
}
private function playerVolume(level:Number):void {
mediaPlayer.volume = level/100;
}
private function getState():String {
return playbackState;
}
private function getPosition():Number {
return mediaPlayer.currentTime;
}
private function getDuration():Number {
return mediaPlayer.duration;
}
private function onTimeUpdated(event:TimeEvent):void {
_triggerEvent('progress');
_triggerEvent('timeupdate');
}
private function onFinish(event:TimeEvent):void {
mediaPlayer.stop();
playbackState = 'ENDED';
_triggerEvent('statechanged');
}
private function _triggerEvent(name: String):void {
ExternalInterface.call('Clappr.Mediator.trigger("' + playbackId + ':' + name +'")');
}
}
}
|
change playbackState on pause/stop (fix #5)
|
RTMP.as: change playbackState on pause/stop (fix #5)
|
ActionScript
|
apache-2.0
|
hxl-dy/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,hxl-dy/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,eventials/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,video-dev/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,clappr/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin,flavioribeiro/clappr-rtmp-plugin
|
8aac78eb439af1c12be4079792839e44461e65f8
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.9.6";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.9.7";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
bump version 3.9.7
|
bump version 3.9.7
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
163f294d6f0f786ad49173581a5991cb4b16094d
|
src/aerys/minko/type/binding/DataBindings.as
|
src/aerys/minko/type/binding/DataBindings.as
|
package aerys.minko.type.binding
{
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
public final class DataBindings
{
private var _owner : ISceneNode;
private var _providers : Vector.<IDataProvider>;
private var _bindingNames : Vector.<String>;
private var _bindingNameToValue : Object;
private var _bindingNameToChangedSignal : Object;
private var _bindingNameToProvider : Object;
private var _providerToBindingNames : Dictionary;
public function get owner() : ISceneNode
{
return _owner;
}
public function get numProviders() : uint
{
return _providers.length;
}
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings(owner : ISceneNode)
{
_owner = owner;
_providers = new <IDataProvider>[];
_bindingNames = new <String>[];
_bindingNameToValue = {};
_bindingNameToChangedSignal = {};
_bindingNameToProvider = {};
_providerToBindingNames = new Dictionary(true);
}
public function contains(dataProvider : IDataProvider) : Boolean
{
return _providers.indexOf(dataProvider) != -1;
}
public function addProvider(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already bound.');
var dataDescriptor : Object = provider.dataDescriptor;
provider.propertyChanged.add(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.add(addBinding);
dynamicProvider.propertyRemoved.add(removeBinding);
}
_providerToBindingNames[provider] = new <String>[];
_providers.push(provider);
for (var propertyName : String in dataDescriptor)
addBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
private function addBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var providerBindingNames : Vector.<String> = _providerToBindingNames[provider];
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error(
'Another data provider is already declaring the \'' + bindingName
+ '\' property.'
);
_bindingNameToProvider[bindingName] = provider;
_bindingNameToValue[bindingName] = value;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, value);
}
public function removeProvider(provider : IDataProvider) : void
{
var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider];
if (providerBindingsNames == null)
throw new ArgumentError('Unknown provider.');
var numProviders : uint = _providers.length - 1;
provider.propertyChanged.remove(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.remove(addBinding);
dynamicProvider.propertyRemoved.remove(removeBinding);
}
_providers[_providers.indexOf(provider)] = _providers[numProviders];
_providers.length = numProviders;
delete _providerToBindingNames[provider];
var dataDescriptor : Object = provider.dataDescriptor;
for (var propertyName : String in dataDescriptor)
removeBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
public function removeBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var numBindings : uint = _bindingNames.length - 1;
var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal;
delete _bindingNameToValue[bindingName];
delete _bindingNameToProvider[bindingName];
_bindingNames[_bindingNames.indexOf(bindingName)] = _bindingNames[numBindings];
_bindingNames.length = numBindings;
if (changedSignal != null)
changedSignal.execute(this, bindingName, value, null);
}
public function removeAllProviders() : void
{
var numProviders : uint = this.numProviders;
for (var providerId : int = numProviders - 1; providerId >= 0; --providerId)
removeProvider(getProviderAt(providerId));
}
public function hasCallback(bindingName : String,
callback : Function) : Boolean
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
return signal != null && signal.hasCallback(callback);
}
public function addCallback(bindingName : String,
callback : Function) : void
{
_bindingNameToChangedSignal[bindingName] ||= new Signal(
'DataBindings.changed[' + bindingName + ']'
);
Signal(_bindingNameToChangedSignal[bindingName]).add(callback);
}
public function removeCallback(bindingName : String,
callback : Function) : void
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
if (!signal)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
signal.remove(callback);
if (signal.numCallbacks == 0)
delete _bindingNameToChangedSignal[bindingName];
}
public function getProviderAt(index : uint) : IDataProvider
{
return _providers[index];
}
public function getProviderByBindingName(bindingName : String) : IDataProvider
{
if (_bindingNameToProvider[bindingName] == null)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
return _bindingNameToProvider[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
if (_bindingNames.indexOf(bindingName) < 0)
throw new Error('The property \'' + bindingName + '\' does not exist.');
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
public function copySharedProvidersFrom(source : DataBindings) : void
{
var numProviders : uint = source._providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = source._providers[providerId];
if (provider.usage == DataProviderUsage.SHARED)
addProvider(provider);
}
}
private function propertyChangedHandler(source : IDataProvider,
attributeName : String) : void
{
if (attributeName == null)
throw new Error('DataProviders must change only one property at a time.');
var bindingName : String = source.dataDescriptor[attributeName];
var oldValue : Object = _bindingNameToValue[bindingName];
var newValue : Object = source[attributeName];
_bindingNameToValue[bindingName] = newValue;
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(
this,
bindingName,
oldValue,
newValue
);
}
}
}
|
package aerys.minko.type.binding
{
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
public final class DataBindings
{
private var _owner : ISceneNode;
private var _providers : Vector.<IDataProvider>;
private var _bindingNames : Vector.<String>;
private var _bindingNameToValue : Object;
private var _bindingNameToChangedSignal : Object;
private var _bindingNameToProvider : Object;
private var _providerToBindingNames : Dictionary;
public function get owner() : ISceneNode
{
return _owner;
}
public function get numProviders() : uint
{
return _providers.length;
}
public function get numProperties() : uint
{
return _bindingNames.length;
}
public function DataBindings(owner : ISceneNode)
{
_owner = owner;
_providers = new <IDataProvider>[];
_bindingNames = new <String>[];
_bindingNameToValue = {};
_bindingNameToChangedSignal = {};
_bindingNameToProvider = {};
_providerToBindingNames = new Dictionary(true);
}
public function contains(dataProvider : IDataProvider) : Boolean
{
return _providers.indexOf(dataProvider) != -1;
}
public function addProvider(provider : IDataProvider) : void
{
if (_providerToBindingNames[provider])
throw new Error('This provider is already bound.');
var dataDescriptor : Object = provider.dataDescriptor;
provider.propertyChanged.add(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.add(addBinding);
dynamicProvider.propertyRemoved.add(removeBinding);
}
_providerToBindingNames[provider] = new <String>[];
_providers.push(provider);
for (var propertyName : String in dataDescriptor)
addBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
private function addBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var providerBindingNames : Vector.<String> = _providerToBindingNames[provider];
if (_bindingNames.indexOf(bindingName) != -1)
throw new Error(
'Another data provider is already declaring the \'' + bindingName
+ '\' property.'
);
_bindingNameToProvider[bindingName] = provider;
_bindingNameToValue[bindingName] = value;
providerBindingNames.push(bindingName);
_bindingNames.push(bindingName);
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, value);
}
public function removeProvider(provider : IDataProvider) : void
{
var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider];
if (providerBindingsNames == null)
throw new ArgumentError('Unknown provider.');
var numProviders : uint = _providers.length - 1;
provider.propertyChanged.remove(propertyChangedHandler);
if (provider is IDynamicDataProvider)
{
var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider;
dynamicProvider.propertyAdded.remove(addBinding);
dynamicProvider.propertyRemoved.remove(removeBinding);
}
_providers[_providers.indexOf(provider)] = _providers[numProviders];
_providers.length = numProviders;
delete _providerToBindingNames[provider];
var dataDescriptor : Object = provider.dataDescriptor;
for (var propertyName : String in dataDescriptor)
removeBinding(
provider,
propertyName,
dataDescriptor[propertyName],
provider[propertyName]
);
}
public function removeBinding(provider : IDataProvider,
propertyName : String,
bindingName : String,
value : Object) : void
{
var numBindings : uint = _bindingNames.length - 1;
var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal;
delete _bindingNameToValue[bindingName];
delete _bindingNameToProvider[bindingName];
_bindingNames[_bindingNames.indexOf(bindingName)] = _bindingNames[numBindings];
_bindingNames.length = numBindings;
if (changedSignal != null)
changedSignal.execute(this, bindingName, value, null);
}
public function removeAllProviders() : void
{
var numProviders : uint = this.numProviders;
for (var providerId : int = numProviders - 1; providerId >= 0; --providerId)
removeProvider(getProviderAt(providerId));
}
public function hasCallback(bindingName : String,
callback : Function) : Boolean
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
return signal != null && signal.hasCallback(callback);
}
public function addCallback(bindingName : String,
callback : Function) : void
{
_bindingNameToChangedSignal[bindingName] ||= new Signal(
'DataBindings.changed[' + bindingName + ']'
);
Signal(_bindingNameToChangedSignal[bindingName]).add(callback);
}
public function removeCallback(bindingName : String,
callback : Function) : void
{
var signal : Signal = _bindingNameToChangedSignal[bindingName];
if (!signal)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
signal.remove(callback);
if (signal.numCallbacks == 0)
delete _bindingNameToChangedSignal[bindingName];
}
public function getProviderAt(index : uint) : IDataProvider
{
return _providers[index];
}
public function getProviderByBindingName(bindingName : String) : IDataProvider
{
if (_bindingNameToProvider[bindingName] == null)
throw new ArgumentError('Unkown property \'' + bindingName + '\'.');
return _bindingNameToProvider[bindingName];
}
public function propertyExists(bindingName : String) : Boolean
{
return _bindingNameToValue.hasOwnProperty(bindingName);
}
public function getProperty(bindingName : String) : *
{
if (_bindingNames.indexOf(bindingName) < 0)
throw new Error('The property \'' + bindingName + '\' does not exist.');
return _bindingNameToValue[bindingName];
}
public function getPropertyName(bindingIndex : uint) : String
{
if (bindingIndex > numProperties)
throw new ArgumentError('No such binding');
return _bindingNames[bindingIndex];
}
public function copySharedProvidersFrom(source : DataBindings) : void
{
var numProviders : uint = source._providers.length;
for (var providerId : uint = 0; providerId < numProviders; ++providerId)
{
var provider : IDataProvider = source._providers[providerId];
if (provider.usage == DataProviderUsage.SHARED)
addProvider(provider);
}
}
private function propertyChangedHandler(source : IDataProvider,
attributeName : String) : void
{
if (attributeName == null)
throw new Error('DataProviders must change only one property at a time.');
var bindingName : String = source.dataDescriptor[attributeName];
var oldValue : Object = _bindingNameToValue[bindingName];
var newValue : Object = source[attributeName];
_bindingNameToValue[bindingName] = newValue;
if (_bindingNameToChangedSignal[bindingName])
_bindingNameToChangedSignal[bindingName].execute(
this,
bindingName,
oldValue,
newValue
);
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
d172e24ba08b02864c5e59c16a47a9cf4015ac3e
|
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.as
|
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.as
|
/*
* Copyright 2017 FreshPlanet
* 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 com.freshplanet.ane.AirCapabilities {
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent;
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent;
import flash.display.BitmapData;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirCapabilities extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* Is the ANE supported on the current platform
*/
static public function get isSupported():Boolean {
return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
* If <code>true</code>, logs will be displayed at the ActionScript and native level.
*/
public function setLogging(value:Boolean):void {
_doLogging = value;
if (isSupported)
_extContext.call("setLogging", value);
}
public function get nativeLogger():ILogger {
return _logger;
}
/**
* AirCapabilities instance
*/
static public function get instance():AirCapabilities {
return _instance != null ? _instance : new AirCapabilities()
}
/**
* Is SMS available
* @return
*/
public function hasSmsEnabled():Boolean {
if (isSupported)
return _extContext.call("hasSMS");
return false;
}
/**
* Is Twitter available
* @return
*/
public function hasTwitterEnabled():Boolean {
if (isSupported)
return _extContext.call("hasTwitter");
return false;
}
/**
* Sends an SMS message
* @param message to send
* @param recipient phonenumber
*/
public function sendMsgWithSms(message:String, recipient:String = null):void {
if (isSupported)
_extContext.call("sendWithSms", message, recipient);
}
/**
* Sends a Twitter message
* @param message
*/
public function sendMsgWithTwitter(message:String):void {
if (isSupported)
_extContext.call("sendWithTwitter", message);
}
/**
* Redirect user to Rating page
* @param appId
* @param appName
*/
public function redirecToRating(appId:String, appName:String):void {
if (isSupported)
_extContext.call("redirectToRating", appId, appName);
}
/**
* Model of the device
* @return
*/
public function getDeviceModel():String {
if (isSupported)
return _extContext.call("getDeviceModel") as String;
return "";
}
/**
* Name of the machine
* @return
*/
public function getMachineName():String {
if (isSupported)
return _extContext.call("getMachineName") as String;
return "";
}
/**
* Opens the referral link URL
* @param url
*/
public function processReferralLink(url:String):void {
if (isSupported)
_extContext.call("processReferralLink", url);
}
/**
* Opens Facebook page
* @param pageId id of the facebook page
*/
public function redirectToPageId(pageId:String):void {
if (isSupported)
_extContext.call("redirectToPageId", pageId);
}
/**
* Opens Twitter account
* @param twitterAccount
*/
public function redirectToTwitterAccount(twitterAccount:String):void {
if (isSupported)
_extContext.call("redirectToTwitterAccount", twitterAccount);
}
/**
* Is posting pictures on Twitter enabled
* @return
*/
public function canPostPictureOnTwitter():Boolean {
if (isSupported)
return _extContext.call("canPostPictureOnTwitter");
return false;
}
/**
* Post new picture on Twitter
* @param message
* @param bitmapData
*/
public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void {
if (isSupported)
_extContext.call("postPictureOnTwitter", message, bitmapData);
}
/**
* Is Instagram enabled
* @return
*/
public function hasInstagramEnabled():Boolean {
if (isSupported)
return _extContext.call("hasInstagramEnabled");
return false;
}
/**
* Post new picture on Instagram
* @param message
* @param bitmapData
* @param x
* @param y
* @param width
* @param height
*/
public function postPictureOnInstagram(message:String, bitmapData:BitmapData,
x:int, y:int, width:int, height:int):void {
if (isSupported)
_extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height);
}
/**
* Open an application (if installed on the Device) or send the player to the appstore. iOS Only
* @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/
* @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?)
*/
public function openExternalApplication(schemes:Array, appStoreURL:String = null):void {
if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1)
_extContext.call("openExternalApplication", schemes, appStoreURL);
}
/**
* Is opening URLs available
* @param url
* @return
*/
public function canOpenURL(url:String):Boolean {
return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false;
}
/**
* Open URL
* @param url
*/
public function openURL(url:String):void {
if (canOpenURL(url))
_extContext.call("openURL", url);
}
/**
* Opens modal app store. Available on iOS only
* @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number)
*/
public function openModalAppStoreIOS(appStoreId:String):void {
if (Capabilities.manufacturer.indexOf("iOS") > -1)
_extContext.call("openModalAppStore", appStoreId);
}
/**
* Version of the operating system
* @return
*/
public function getOSVersion():String {
if (isSupported)
return _extContext.call("getOSVersion") as String;
return "";
}
/**
* @return current amount of RAM being used in bytes
*/
public function getCurrentMem():Number {
if (!isSupported)
return -1;
var ret:Object = _extContext.call("getCurrentMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return amount of RAM used by the VM
*/
public function getCurrentVirtualMem():Number {
if(!isSupported)
return -1;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return -1;
var ret:Object = _extContext.call("getCurrentVirtualMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return is requesting review available. Available on iOS only
*/
public function canRequestReview():Boolean {
if (!isSupported)
return false;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return false;
return _extContext.call("canRequestReview");
}
/**
* Request AppStore review. Available on iOS only
*/
public function requestReview():void {
if (!canRequestReview())
return;
_extContext.call("requestReview");
}
/**
* Generate haptic feedback - iOS only
*/
public function generateHapticFeedback(feedbackType:AirCapabilitiesHapticFeedbackType):void {
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return;
if(!feedbackType)
return
_extContext.call("generateHapticFeedback", feedbackType.value);
}
public function getNativeScale():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 1;
return _extContext.call("getNativeScale") as Number;
}
public function openAdSettings():void
{
if (Capabilities.manufacturer.indexOf("Android") < 0)
return;
_extContext.call("openAdSettings");
}
public function getTopInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getTopInset") as Number;
}
public function getBottomInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getBottomInset") as Number;
}
public function get iOSAppOnMac():Boolean
{
if(Capabilities.manufacturer.indexOf("iOS") < 0)
return false;
return _extContext.call("iOSAppOnMac") as Boolean;
}
public function switchToLandscape():void
{
if(Capabilities.manufacturer.indexOf("iOS") < 0)
return;
_extContext.call("switchToLandscape");
}
public function switchToPortrait():void
{
if(Capabilities.manufacturer.indexOf("iOS") < 0)
return;
_extContext.call("switchToPortrait");
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities";
static private var _instance:AirCapabilities = null;
private var _extContext:ExtensionContext = null;
private var _doLogging:Boolean = false;
private var _logger:ILogger;
/**
* "private" singleton constructor
*/
public function AirCapabilities() {
super();
if (_instance)
throw new Error("singleton class, use .instance");
_extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
_extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent);
if (isSupported)
_logger = new NativeLogger(_extContext);
else
_logger = new DefaultLogger();
_instance = this;
}
private function _handleStatusEvent(event:StatusEvent):void {
if (event.code == "log")
_doLogging && trace("[AirCapabilities] " + event.level);
else if (event.code == "OPEN_URL")
this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level));
else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) {
var memory:Number = Number(event.level);
this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory));
}
else
this.dispatchEvent(event);
}
}
}
|
/*
* Copyright 2017 FreshPlanet
* 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 com.freshplanet.ane.AirCapabilities {
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent;
import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent;
import flash.display.BitmapData;
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.system.Capabilities;
public class AirCapabilities extends EventDispatcher {
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
/**
* Is the ANE supported on the current platform
*/
static public function get isSupported():Boolean {
return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1;
}
/**
* If <code>true</code>, logs will be displayed at the ActionScript and native level.
*/
public function setLogging(value:Boolean):void {
_doLogging = value;
if (isSupported)
_extContext.call("setLogging", value);
}
public function get nativeLogger():ILogger {
return _logger;
}
/**
* AirCapabilities instance
*/
static public function get instance():AirCapabilities {
return _instance != null ? _instance : new AirCapabilities()
}
/**
* Is SMS available
* @return
*/
public function hasSmsEnabled():Boolean {
if (isSupported)
return _extContext.call("hasSMS");
return false;
}
/**
* Is Twitter available
* @return
*/
public function hasTwitterEnabled():Boolean {
if (isSupported)
return _extContext.call("hasTwitter");
return false;
}
/**
* Sends an SMS message
* @param message to send
* @param recipient phonenumber
*/
public function sendMsgWithSms(message:String, recipient:String = null):void {
if (isSupported)
_extContext.call("sendWithSms", message, recipient);
}
/**
* Sends a Twitter message
* @param message
*/
public function sendMsgWithTwitter(message:String):void {
if (isSupported)
_extContext.call("sendWithTwitter", message);
}
/**
* Redirect user to Rating page
* @param appId
* @param appName
*/
public function redirecToRating(appId:String, appName:String):void {
if (isSupported)
_extContext.call("redirectToRating", appId, appName);
}
/**
* Model of the device
* @return
*/
public function getDeviceModel():String {
if (isSupported)
return _extContext.call("getDeviceModel") as String;
return "";
}
/**
* Name of the machine
* @return
*/
public function getMachineName():String {
if (isSupported)
return _extContext.call("getMachineName") as String;
return "";
}
/**
* Opens the referral link URL
* @param url
*/
public function processReferralLink(url:String):void {
if (isSupported)
_extContext.call("processReferralLink", url);
}
/**
* Opens Facebook page
* @param pageId id of the facebook page
*/
public function redirectToPageId(pageId:String):void {
if (isSupported)
_extContext.call("redirectToPageId", pageId);
}
/**
* Opens Twitter account
* @param twitterAccount
*/
public function redirectToTwitterAccount(twitterAccount:String):void {
if (isSupported)
_extContext.call("redirectToTwitterAccount", twitterAccount);
}
/**
* Is posting pictures on Twitter enabled
* @return
*/
public function canPostPictureOnTwitter():Boolean {
if (isSupported)
return _extContext.call("canPostPictureOnTwitter");
return false;
}
/**
* Post new picture on Twitter
* @param message
* @param bitmapData
*/
public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void {
if (isSupported)
_extContext.call("postPictureOnTwitter", message, bitmapData);
}
/**
* Is Instagram enabled
* @return
*/
public function hasInstagramEnabled():Boolean {
if (isSupported)
return _extContext.call("hasInstagramEnabled");
return false;
}
/**
* Post new picture on Instagram
* @param message
* @param bitmapData
* @param x
* @param y
* @param width
* @param height
*/
public function postPictureOnInstagram(message:String, bitmapData:BitmapData,
x:int, y:int, width:int, height:int):void {
if (isSupported)
_extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height);
}
/**
* Open an application (if installed on the Device) or send the player to the appstore. iOS Only
* @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/
* @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?)
*/
public function openExternalApplication(schemes:Array, appStoreURL:String = null):void {
if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1)
_extContext.call("openExternalApplication", schemes, appStoreURL);
}
/**
* Is opening URLs available
* @param url
* @return
*/
public function canOpenURL(url:String):Boolean {
return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false;
}
/**
* Open URL
* @param url
*/
public function openURL(url:String):void {
if (canOpenURL(url))
_extContext.call("openURL", url);
}
/**
* Opens modal app store. Available on iOS only
* @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number)
*/
public function openModalAppStoreIOS(appStoreId:String):void {
if (Capabilities.manufacturer.indexOf("iOS") > -1)
_extContext.call("openModalAppStore", appStoreId);
}
/**
* Version of the operating system
* @return
*/
public function getOSVersion():String {
if (isSupported)
return _extContext.call("getOSVersion") as String;
return "";
}
/**
* @return current amount of RAM being used in bytes
*/
public function getCurrentMem():Number {
if (!isSupported)
return -1;
var ret:Object = _extContext.call("getCurrentMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return amount of RAM used by the VM
*/
public function getCurrentVirtualMem():Number {
if(!isSupported)
return -1;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return -1;
var ret:Object = _extContext.call("getCurrentVirtualMem");
if (ret is Error)
throw ret;
else
return ret ? ret as Number : 0;
}
/**
* @return is requesting review available. Available on iOS only
*/
public function canRequestReview():Boolean {
if (!isSupported)
return false;
if (Capabilities.manufacturer.indexOf("iOS") == -1)
return false;
return _extContext.call("canRequestReview");
}
/**
* Request AppStore review. Available on iOS only
*/
public function requestReview():void {
if (!canRequestReview())
return;
_extContext.call("requestReview");
}
/**
* Generate haptic feedback - iOS only
*/
public function generateHapticFeedback(feedbackType:AirCapabilitiesHapticFeedbackType):void {
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return;
if(!feedbackType)
return
_extContext.call("generateHapticFeedback", feedbackType.value);
}
public function getNativeScale():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 1;
return _extContext.call("getNativeScale") as Number;
}
public function openAdSettings():void
{
if (Capabilities.manufacturer.indexOf("Android") < 0)
return;
_extContext.call("openAdSettings");
}
public function getTopInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getTopInset") as Number;
}
public function getBottomInset():Number
{
if (Capabilities.manufacturer.indexOf("iOS") < 0)
return 0;
return _extContext.call("getBottomInset") as Number;
}
public function get iOSAppOnMac():Boolean
{
if(Capabilities.manufacturer.indexOf("iOS") < 0)
return false;
return _extContext.call("iOSAppOnMac") as Boolean;
}
public function switchToLandscape():void
{
if(Capabilities.manufacturer.indexOf("iOS") < 0)
return;
_extContext.call("switchToLandscape");
}
public function switchToPortrait():void
{
if(Capabilities.manufacturer.indexOf("iOS") < 0)
return;
_extContext.call("switchToPortrait");
}
/**
* MacOS only!
*/
public function forceFullscreen():void
{
if(Capabilities.os.indexOf("Mac OS") < 0)
return;
_extContext.call("forceFullscreen");
}
/**
* MacOS only!
*/
public function exitFullscreen():void
{
if(Capabilities.os.indexOf("Mac OS") < 0)
return;
_extContext.call("exitFullscreen");
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities";
static private var _instance:AirCapabilities = null;
private var _extContext:ExtensionContext = null;
private var _doLogging:Boolean = false;
private var _logger:ILogger;
/**
* "private" singleton constructor
*/
public function AirCapabilities() {
super();
if (_instance)
throw new Error("singleton class, use .instance");
_extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
_extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent);
if (isSupported)
_logger = new NativeLogger(_extContext);
else
_logger = new DefaultLogger();
_instance = this;
}
private function _handleStatusEvent(event:StatusEvent):void {
if (event.code == "log")
_doLogging && trace("[AirCapabilities] " + event.level);
else if (event.code == "OPEN_URL")
this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level));
else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) {
var memory:Number = Number(event.level);
this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory));
}
else
this.dispatchEvent(event);
}
}
}
|
add as3 side
|
add as3 side
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities
|
30cf6d4849e2a608519ffc31fc31360eb0945147
|
plugins/vastPlugin/src/com/kaltura/kdpfl/plugin/component/PersistentData.as
|
plugins/vastPlugin/src/com/kaltura/kdpfl/plugin/component/PersistentData.as
|
package com.kaltura.kdpfl.plugin.component
{
import flash.net.SharedObject;
import org.puremvc.as3.interfaces.IFacade;
public class PersistentData {
private var _soName:String = "kaltura/vast_";
public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;
/**
* the shared object used for storing data
*/
private var _so:SharedObject;
public function PersistentData(){}
public function init(facade:IFacade) :void {
var config:Object = facade.retrieveProxy("configProxy");
_so = SharedObject.getLocal(_soName + config.vo.kuiConf.id);
}
/**
* check if persistence data is from the last 24 hours
* @return true | false
*/
public function isPersistenceValid():Boolean {
var result:Boolean = true;
var pd:Object = _so.data;
if (pd.date == null) {
// no saved data
result = false;
}
else {
var date:Date = new Date();
var dif:Number = date.getTime() - pd.date.getTime();
if (dif > millisecondsPerDay) {
// more than 24 hours
result = false;
}
}
return result;
}
/**
* resets persistent data
*/
public function resetPersistenceData():void {
var pd:Object = _so.data;
pd.date = new Date();
// should reset to 1 and not 0 because the value would have been increased by now.
pd.prerollEntries = 1;
pd.prerollFirstShow = false;
pd.postrollEntries = 1;
pd.postrollFirstShow = false;
_so.flush();
}
/**
* match persistent data with plugin state
* */
public function updatePersistentData(o:Object):void {
var pd:Object = _so.data;
pd.prerollFirstShow = o.prerollFirstShow;
pd.prerollEntries = o.prerollEntries;
pd.postrollFirstShow = o.postrollFirstShow;
pd.postrollEntries = o.postrollEntries;
_so.flush();
}
/**
* saved data
*/
public function get data():Object {
return _so.data;
}
}
}
|
package com.kaltura.kdpfl.plugin.component
{
import flash.net.SharedObject;
import org.puremvc.as3.interfaces.IFacade;
public class PersistentData {
private var _soName:String = "kaltura/vast_";
public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;
/**
* the shared object used for storing data
*/
private var _so:SharedObject;
private var _config:Object
public function PersistentData(){}
public function init(facade:IFacade) :void {
_config = facade.retrieveProxy("configProxy");
_so = SharedObject.getLocal(_soName + _config.vo.kuiConf.id);
}
/**
* check if persistence data is from the last 24 hours
* @return true | false
*/
public function isPersistenceValid():Boolean {
var result:Boolean = true;
var pd:Object = _so.data;
if (pd.date == null) {
// no saved data
result = false;
}
else {
var date:Date = new Date();
var dif:Number = date.getTime() - pd.date.getTime();
if (dif > millisecondsPerDay) {
// more than 24 hours
result = false;
}
}
return result;
}
/**
* resets persistent data
*/
public function resetPersistenceData():void {
var pd:Object = _so.data;
pd.date = new Date();
// should reset to 1 and not 0 because the value would have been increased by now.
pd.prerollEntries = 1;
pd.prerollFirstShow = false;
pd.postrollEntries = 1;
pd.postrollFirstShow = false;
if (_config.vo.flashvars.allowCookies=="true")
_so.flush();
}
/**
* match persistent data with plugin state
* */
public function updatePersistentData(o:Object):void {
var pd:Object = _so.data;
pd.prerollFirstShow = o.prerollFirstShow;
pd.prerollEntries = o.prerollEntries;
pd.postrollFirstShow = o.postrollFirstShow;
pd.postrollEntries = o.postrollEntries;
if (_config.vo.flashvars.allowCookies=="true")
_so.flush();
}
/**
* saved data
*/
public function get data():Object {
return _so.data;
}
}
}
|
support in "allowCookies" flashvar
|
qnd: support in "allowCookies" flashvar
git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@85785 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp
|
0fa100918a00281b871d012a61d4e1be00af613a
|
flare/src/flare/animate/Scheduler.as
|
flare/src/flare/animate/Scheduler.as
|
package flare.animate
{
import flash.display.Shape;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* Scheduler that oversees animation and time-based processing. Uses an
* internal timer to regularly invoke the current set of scheduled
* objects. Typically, interaction with the scheduler is automatically
* handled by Transition classes. However, custom implmentations of
* the ISchedulable interface will need to be scheduled. Use the
* <tt>Scheduler.instance</tt> property, and not the constructor, to get
* a reference to the active scheduler.
*
* <p>By default, the Scheduler issues updates to all scheduled items each
* time the Flash Player advances to the next frame, as reported by the
* <code>Event.ENTER_FRAME</code> event. To instead set the update interval
* manually, see the <code>timerInterval</code> property.</p>
*/
public class Scheduler
{
private static const _instance:Scheduler = new Scheduler(_Lock);
/** The default Scheduler instance. */
public static function get instance():Scheduler { return _instance; }
private var _scheduled:Array; // list of all currently scheduled items
private var _ids:Object; // map of all named items
private var _timer:Timer; // timer for interval-based scheduling
private var _obj:Shape; // shape for getting ENTER_FRAME events
/**
* Sets the timer interval (in milliseconds) at which the scheduler
* should process events. If this value is greater than zero, a
* <code>Timer</code> instance will be used to trigger scheduler
* updates at the given interval. If this value is less than or equal
* to zero (the default), scheduler updates will be issued with each
* time the Flash Player advances to the next frame according to the
* <code>Event.ENTER_FRAME</code> event.
*/
public function get timerInterval():Number { return _timer.delay; }
public function set timerInterval(t:Number):void {
pause(); _timer.delay = (t>0 ? t : 0); play();
}
/**
* Creates a new Scheduler--this constructor should be not used;
* instead use the <code>instance</code> property.
* @param lock a lock object to emulate a private constructor
*/
public function Scheduler(lock:Class) {
if (lock == _Lock) {
_scheduled = [];
_ids = {};
_obj = new Shape();
_timer = new Timer(0);
_timer.addEventListener(TimerEvent.TIMER, tick);
} else {
throw new Error("Invalid constructor. Use Scheduler.instance.");
}
}
/**
* Plays the scheduler, allowing it to process events.
*/
private function play():void
{
if (timerInterval <= 0) {
if (!_obj.hasEventListener(Event.ENTER_FRAME))
_obj.addEventListener(Event.ENTER_FRAME, tick);
} else if (!_timer.running) {
_timer.start();
}
}
/**
* Pauses the scheduler, so that events are not processed.
*/
private function pause():void
{
if (timerInterval <= 0) {
_obj.removeEventListener(Event.ENTER_FRAME, tick);
} else {
_timer.stop();
}
}
/**
* Adds an object to the scheduling list.
* @param item a schedulable object to add
*/
public function add(item:ISchedulable) : void
{
if (item.id && _ids[item.id] != item) {
cancel(item.id);
_ids[item.id] = item;
}
_scheduled.push(item);
play();
}
/**
* Removes an object from the scheduling list.
* @param item the object to remove
* @return true if the object was found and removed, false otherwise
*/
public function remove(item:ISchedulable) : Boolean
{
var idx:int = _scheduled.indexOf(item);
if (idx >= 0) {
_scheduled.splice(idx,1);
if (item.id && _ids[item.id] == item) {
if (_scheduled.indexOf(item) < 0)
delete _ids[item.id];
}
}
return (idx >= 0);
}
/**
* Indicates if an object with the given id is currently in the
* scheduler queue.
* @param id the id to check for
* @return true if an object with that id is currently scheduled,
* false otherwise
*/
public function isScheduled(id:String) : Boolean
{
return _ids[id] != undefined;
}
/**
* Looks up the scheduled object indicated by the given id, if any.
* @param id the id to lookup
* @return the scheduled object with matching id, of null if none
*/
public function lookup(id:String) : ISchedulable
{
return id==null ? null : _ids[id];
}
/**
* Cancels any scheduled object with a matching id.
* @param id the id to cancel
* @return true if an object was found and cancelled, false otherwise
*/
public function cancel(id:String) : Boolean
{
var s:ISchedulable = _ids[id];
if (s != null) {
remove(s);
s.cancelled();
return true;
} else {
return false;
}
}
/**
* Frame/timer callback that invokes each scheduled object.
* @param event the event that triggered the callback
*/
public function tick(event:Event) : void
{
// all events will see the same timestamp
var time:Number = new Date().time;
for each (var s:ISchedulable in _scheduled) {
if (s.evaluate(time))
remove(s);
}
if (_scheduled.length == 0) {
pause();
}
}
} // end of class Scheduler
}
// scheduler lock class to enforce singleton pattern
class _Lock { }
|
package flare.animate
{
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* Scheduler that oversees animation and time-based processing. Uses an
* internal timer to regularly invoke the current set of scheduled
* objects. Typically, interaction with the scheduler is automatically
* handled by Transition classes. However, custom implmentations of
* the ISchedulable interface will need to be scheduled. Use the
* <tt>Scheduler.instance</tt> property, and not the constructor, to get
* a reference to the active scheduler.
*
* <p>By default, the Scheduler issues updates to all scheduled items each
* time the Flash Player advances to the next frame, as reported by the
* <code>Event.ENTER_FRAME</code> event. To instead set the update interval
* manually, see the <code>timerInterval</code> property.</p>
*/
public class Scheduler
{
private static const _instance:Scheduler = new Scheduler(_Lock);
/** The default Scheduler instance. */
public static function get instance():Scheduler { return _instance; }
private var _scheduled:Array; // list of all currently scheduled items
private var _ids:Object; // map of all named items
private var _timer:Timer; // timer for interval-based scheduling
/**
* Sets the timer interval (in milliseconds) at which the scheduler
* should process events.
*/
public function get timerInterval():Number { return _timer.delay; }
public function set timerInterval(t:Number):void {
pause(); _timer.delay = (t>0 ? t : 0); play();
}
/**
* Creates a new Scheduler--this constructor should be not used;
* instead use the <code>instance</code> property.
* @param lock a lock object to emulate a private constructor
*/
public function Scheduler(lock:Class) {
if (lock == _Lock) {
_scheduled = [];
_ids = {};
_timer = new Timer(0);
_timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true);
} else {
throw new Error("Invalid constructor. Use Scheduler.instance.");
}
}
/**
* Plays the scheduler, allowing it to process events.
*/
private function play():void
{
if (!_timer.running) {
_timer.start();
}
}
/**
* Pauses the scheduler, so that events are not processed.
*/
private function pause():void
{
_timer.stop();
}
/**
* Adds an object to the scheduling list.
* @param item a schedulable object to add
*/
public function add(item:ISchedulable) : void
{
if (item.id && _ids[item.id] != item) {
cancel(item.id);
_ids[item.id] = item;
}
_scheduled.push(item);
play();
}
/**
* Removes an object from the scheduling list.
* @param item the object to remove
* @return true if the object was found and removed, false otherwise
*/
public function remove(item:ISchedulable) : Boolean
{
var idx:int = _scheduled.indexOf(item);
if (idx >= 0) {
_scheduled.splice(idx,1);
if (item.id && _ids[item.id] == item) {
if (_scheduled.indexOf(item) < 0)
delete _ids[item.id];
}
}
return (idx >= 0);
}
/**
* Indicates if an object with the given id is currently in the
* scheduler queue.
* @param id the id to check for
* @return true if an object with that id is currently scheduled,
* false otherwise
*/
public function isScheduled(id:String) : Boolean
{
return _ids[id] != undefined;
}
/**
* Looks up the scheduled object indicated by the given id, if any.
* @param id the id to lookup
* @return the scheduled object with matching id, of null if none
*/
public function lookup(id:String) : ISchedulable
{
return id==null ? null : _ids[id];
}
/**
* Cancels any scheduled object with a matching id.
* @param id the id to cancel
* @return true if an object was found and cancelled, false otherwise
*/
public function cancel(id:String) : Boolean
{
var s:ISchedulable = _ids[id];
if (s != null) {
remove(s);
s.cancelled();
return true;
} else {
return false;
}
}
/**
* Frame/timer callback that invokes each scheduled object.
* @param event the event that triggered the callback
*/
public function tick(event:TimerEvent) : void
{
// all events will see the same timestamp
var time:Number = new Date().time;
for each (var s:ISchedulable in _scheduled) {
if (s.evaluate(time))
remove(s);
}
if (_scheduled.length == 0) {
pause();
}
// Defer rendering to the screen update (vertical blanking) period
event.updateAfterEvent();
}
} // end of class Scheduler
}
// scheduler lock class to enforce singleton pattern
class _Lock { }
|
Fix animation rendering issues by converting the Scheduler class to only use a Timer instance and deferring redraws to the screen update (vertical blanking) period.
|
Fix animation rendering issues by converting the Scheduler class to only use a Timer instance and deferring redraws to the screen update (vertical blanking) period.
|
ActionScript
|
bsd-3-clause
|
jonbuffington/flare_juicekit,jonbuffington/flare_juicekit
|
00b97eb45fd34008f166b9456f2dbef42157139d
|
frameworks/projects/Core/as/src/org/apache/flex/events/Event.as
|
frameworks/projects/Core/as/src/org/apache/flex/events/Event.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.events
{
COMPILE::AS3 {
import flash.events.Event;
}
COMPILE::JS {
import goog.events.Event;
}
/**
* This class simply wraps flash.events.Event so that
* no flash packages are needed on the JS side.
* At runtime, this class is not always the event object
* that is dispatched. In most cases we are dispatching
* DOMEvents instead, so as long as you don't actually
* check the typeof(event) it will work
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
COMPILE::AS3
public class Event extends flash.events.Event
{
//--------------------------------------
// Static Property
//--------------------------------------
static public const CHANGE:String = "change";
//--------------------------------------
// Constructor
//--------------------------------------
/**
* Constructor.
*
* @param type The name of the event.
* @param bubbles Whether the event bubbles.
* @param cancelable Whether the event can be canceled.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Event(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
//--------------------------------------
// Property
//--------------------------------------
//--------------------------------------
// Function
//--------------------------------------
/**
* @private
*/
public override function clone():flash.events.Event
{
return cloneEvent();
}
/**
* Create a copy/clone of the Event object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function cloneEvent():org.apache.flex.events.Event
{
return new org.apache.flex.events.Event(type, bubbles, cancelable);
}
}
COMPILE::JS
public class Event extends goog.events.Event {
public static const CHANGE:String = "change";
public function Event(type:String, target:Object = null) {
super(type, target);
}
public function init(type:String):void {
this.type = type;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.events
{
COMPILE::AS3 {
import flash.events.Event;
}
COMPILE::JS {
import goog.events.Event;
}
/**
* This class simply wraps flash.events.Event so that
* no flash packages are needed on the JS side.
* At runtime, this class is not always the event object
* that is dispatched. In most cases we are dispatching
* DOMEvents instead, so as long as you don't actually
* check the typeof(event) it will work
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
COMPILE::AS3
public class Event extends flash.events.Event
{
//--------------------------------------
// Static Property
//--------------------------------------
static public const CHANGE:String = "change";
//--------------------------------------
// Constructor
//--------------------------------------
/**
* Constructor.
*
* @param type The name of the event.
* @param bubbles Whether the event bubbles.
* @param cancelable Whether the event can be canceled.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Event(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
//--------------------------------------
// Property
//--------------------------------------
//--------------------------------------
// Function
//--------------------------------------
/**
* @private
*/
public override function clone():flash.events.Event
{
return cloneEvent();
}
/**
* Create a copy/clone of the Event object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function cloneEvent():org.apache.flex.events.Event
{
return new org.apache.flex.events.Event(type, bubbles, cancelable);
}
}
COMPILE::JS
public class Event extends goog.events.Event {
public static const CHANGE:String = "change";
public function Event(type:String, target:Object = null) {
super(type, target);
}
public function init(type:String):void {
this.type = type;
}
}
}
|
fix up imports per platform
|
fix up imports per platform
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
4ec288348d06b11d96439290a1ff9597dcd6b904
|
src/org/mangui/hls/model/Level.as
|
src/org/mangui/hls/model/Level.as
|
/* 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 org.mangui.hls.model {
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
import org.mangui.hls.utils.PTS;
/** HLS streaming quality level. **/
public class Level {
/** audio only Level ? **/
public var audio : Boolean;
/** AAC codec signaled ? **/
public var codec_aac : Boolean;
/** MP3 codec signaled ? **/
public var codec_mp3 : Boolean;
/** H264 codec signaled ? **/
public var codec_h264 : Boolean;
/** Level Bitrate. **/
public var bitrate : Number;
/** Level Name. **/
public var name : String;
/** level index **/
public var index : int = 0;
/** video width (from playlist) **/
public var width : int;
/** video height (from playlist) **/
public var height : int;
/** URL of this bitrate level (for M3U8). **/
public var url : String;
/** Level fragments **/
public var fragments : Vector.<Fragment>;
/** min sequence number from M3U8. **/
public var start_seqnum : int;
/** max sequence number from M3U8. **/
public var end_seqnum : int;
/** target fragment duration from M3U8 **/
public var targetduration : Number;
/** average fragment duration **/
public var averageduration : Number;
/** Total duration **/
public var duration : Number;
/** Audio Identifier **/
public var audio_stream_id : String;
/** Create the quality level. **/
public function Level() : void {
this.fragments = new Vector.<Fragment>();
};
/** Return the Fragment before a given time position. **/
public function getFragmentBeforePosition(position : Number) : Fragment {
if (fragments[0].data.valid && position < fragments[0].start_time)
return fragments[0];
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].start_time <= position && fragments[i].start_time + fragments[i].duration > position) {
return fragments[i];
}
}
return fragments[len - 1];
};
/** Return the sequence number from a given program date **/
public function getSeqNumFromProgramDate(program_date : Number) : int {
if (program_date < fragments[0].program_date)
return -1;
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].program_date <= program_date && fragments[i].program_date + 1000 * fragments[i].duration > program_date) {
return (start_seqnum + i);
}
}
return -1;
};
/** Return the sequence number nearest a PTS **/
public function getSeqNumNearestPTS(pts : Number, continuity : int) : Number {
if (fragments.length == 0)
return -1;
var firstIndex : Number = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1 || isNaN(fragments[firstIndex].data.pts_start_computed))
return -1;
var lastIndex : Number = getLastIndexfromContinuity(continuity);
for (var i : int = firstIndex; i <= lastIndex; i++) {
var frag : Fragment = fragments[i];
/* check nearest fragment */
if ( frag.data.valid && (frag.duration >= 0) && (Math.abs(frag.data.pts_start_computed - pts) < Math.abs(frag.data.pts_start_computed + 1000 * frag.duration - pts))) {
return frag.seqnum;
}
}
// requested PTS above max PTS of this level
return Number.POSITIVE_INFINITY;
};
public function getLevelstartPTS() : Number {
if (fragments.length)
return fragments[0].data.pts_start_computed;
else
return NaN;
}
/** Return the fragment index from fragment sequence number **/
public function getFragmentfromSeqNum(seqnum : Number) : Fragment {
var index : int = getIndexfromSeqNum(seqnum);
if (index != -1) {
return fragments[index];
} else {
return null;
}
}
/** Return the fragment index from fragment sequence number **/
private function getIndexfromSeqNum(seqnum : int) : int {
if (seqnum >= start_seqnum && seqnum <= end_seqnum) {
return (fragments.length - 1 - (end_seqnum - seqnum));
} else {
return -1;
}
}
/** Return the first index matching with given continuity counter **/
private function getFirstIndexfromContinuity(continuity : int) : int {
// look for first fragment matching with given continuity index
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
if (fragments[i].continuity == continuity)
return i;
}
return -1;
}
/** Return the first seqnum matching with given continuity counter **/
public function getFirstSeqNumfromContinuity(continuity : int) : Number {
var index : int = getFirstIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last seqnum matching with given continuity counter **/
public function getLastSeqNumfromContinuity(continuity : int) : Number {
var index : int = getLastIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last index matching with given continuity counter **/
private function getLastIndexfromContinuity(continuity : Number) : int {
var firstIndex : int = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1)
return -1;
var lastIndex : int = firstIndex;
// look for first fragment matching with given continuity index
for (var i : int = firstIndex; i < fragments.length; i++) {
if (fragments[i].continuity == continuity)
lastIndex = i;
else
break;
}
return lastIndex;
}
/** set Fragments **/
public function updateFragments(_fragments : Vector.<Fragment>) : void {
var idx_with_metrics : int = -1;
var len : int = _fragments.length;
var continuity_offset : int;
var frag : Fragment;
// update PTS from previous fragments
for (var i : int = 0; i < len; i++) {
frag = getFragmentfromSeqNum(_fragments[i].seqnum);
if (frag != null) {
continuity_offset = frag.continuity - _fragments[i].continuity;
_fragments[i].continuity
if(!isNaN(frag.data.pts_start)) {
_fragments[i].data = frag.data;
idx_with_metrics = i;
}
}
}
if(continuity_offset) {
CONFIG::LOGGING {
Log.debug("updateFragments: discontinuity sliding from live playlist,take into account discontinuity drift:" + continuity_offset);
}
for (i = 0; i < len; i++) {
_fragments[i].continuity+= continuity_offset;
}
}
updateFragmentsProgramDate(_fragments);
fragments = _fragments;
if (len > 0) {
start_seqnum = _fragments[0].seqnum;
end_seqnum = _fragments[len - 1].seqnum;
if (idx_with_metrics != -1) {
frag = fragments[idx_with_metrics];
// if at least one fragment contains PTS info, recompute PTS information for all fragments
CONFIG::LOGGING {
Log.debug("updateFragments: found PTS info from previous playlist,seqnum/PTS:" + frag.seqnum + "/" + frag.data.pts_start);
}
updateFragment(frag.seqnum, true, frag.data.pts_start, frag.data.pts_start + 1000 * frag.duration);
} else {
CONFIG::LOGGING {
Log.debug("updateFragments: unknown PTS info for this level");
}
duration = _fragments[len - 1].start_time + _fragments[len - 1].duration;
}
averageduration = duration / len;
} else {
duration = 0;
averageduration = 0;
}
}
private function updateFragmentsProgramDate(_fragments : Vector.<Fragment>) : void {
var len : int = _fragments.length;
var continuity : int;
var program_date : Number;
var frag : Fragment;
for (var i : int = 0; i < len; i++) {
frag = _fragments[i];
if (frag.continuity != continuity) {
continuity = frag.continuity;
program_date = 0;
}
if (frag.program_date) {
program_date = frag.program_date + 1000 * frag.duration;
} else if (program_date) {
frag.program_date = program_date;
}
}
}
private function _updatePTS(from_index : int, to_index : int) : void {
// CONFIG::LOGGING {
// Log.info("updateFragmentPTS from/to:" + from_index + "/" + to_index);
// }
var frag_from : Fragment = fragments[from_index];
var frag_to : Fragment = fragments[to_index];
if (frag_from.data.valid && frag_to.data.valid) {
if (!isNaN(frag_to.data.pts_start)) {
// we know PTS[to_index]
frag_to.data.pts_start_computed = frag_to.data.pts_start;
/* normalize computed PTS value based on known PTS value.
* this is to avoid computing wrong fragment duration in case of PTS looping */
var from_pts : Number = PTS.normalize(frag_to.data.pts_start, frag_from.data.pts_start_computed);
/* update fragment duration.
it helps to fix drifts between playlist reported duration and fragment real duration */
if (to_index > from_index) {
frag_from.duration = (frag_to.data.pts_start - from_pts) / 1000;
CONFIG::LOGGING {
if (frag_from.duration < 0) {
Log.error("negative duration computed for " + frag_from + ", there should be some duration drift between playlist and fragment!");
}
}
} else {
frag_to.duration = ( from_pts - frag_to.data.pts_start) / 1000;
CONFIG::LOGGING {
if (frag_to.duration < 0) {
Log.error("negative duration computed for " + frag_to + ", there should be some duration drift between playlist and fragment!");
}
}
}
} else {
// we dont know PTS[to_index]
if (to_index > from_index)
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed + 1000 * frag_from.duration;
else
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed - 1000 * frag_to.duration;
}
}
}
public function updateFragment(seqnum : Number, valid : Boolean, min_pts : Number = 0, max_pts : Number = 0) : void {
// CONFIG::LOGGING {
// Log.info("updatePTS : seqnum/min/max:" + seqnum + '/' + min_pts + '/' + max_pts);
// }
// get fragment from seqnum
var fragIdx : int = getIndexfromSeqNum(seqnum);
if (fragIdx != -1) {
var frag : Fragment = fragments[fragIdx];
// update fragment start PTS + duration
if (valid) {
frag.data.pts_start = min_pts;
frag.data.pts_start_computed = min_pts;
frag.duration = (max_pts - min_pts) / 1000;
} else {
frag.duration = 0;
}
frag.data.valid = valid;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[fragIdx].seqnum+"]:pts/duration:" + fragments[fragIdx].start_pts_computed + "/" + fragments[fragIdx].duration);
// }
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (var i : int = fragIdx; i > 0 && fragments[i - 1].continuity == frag.continuity; i--) {
_updatePTS(i, i - 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i-1].seqnum+"]:pts/duration:" + fragments[i-1].start_pts_computed + "/" + fragments[i-1].duration);
// }
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1 && fragments[i + 1].continuity == frag.continuity; i++) {
_updatePTS(i, i + 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i+1].seqnum+"]:pts/duration:" + fragments[i+1].start_pts_computed + "/" + fragments[i+1].duration);
// }
}
// second, adjust fragment offset
var start_time_offset : Number = fragments[0].start_time;
var len : int = fragments.length;
for (i = 0; i < len; i++) {
fragments[i].start_time = start_time_offset;
start_time_offset += fragments[i].duration;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i].seqnum+"]:start_time/continuity/pts/duration:" + fragments[i].start_time + "/" + fragments[i].continuity + "/"+ fragments[i].start_pts_computed + "/" + fragments[i].duration);
// }
}
duration = start_time_offset;
} else {
CONFIG::LOGGING {
Log.error("updateFragment:seqnum " + seqnum + " not found!");
}
}
}
}
}
|
/* 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 org.mangui.hls.model {
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
import org.mangui.hls.utils.PTS;
/** HLS streaming quality level. **/
public class Level {
/** audio only Level ? **/
public var audio : Boolean;
/** AAC codec signaled ? **/
public var codec_aac : Boolean;
/** MP3 codec signaled ? **/
public var codec_mp3 : Boolean;
/** H264 codec signaled ? **/
public var codec_h264 : Boolean;
/** Level Bitrate. **/
public var bitrate : Number;
/** Level Name. **/
public var name : String;
/** level index **/
public var index : int = 0;
/** video width (from playlist) **/
public var width : int;
/** video height (from playlist) **/
public var height : int;
/** URL of this bitrate level (for M3U8). **/
public var url : String;
/** Level fragments **/
public var fragments : Vector.<Fragment>;
/** min sequence number from M3U8. **/
public var start_seqnum : int;
/** max sequence number from M3U8. **/
public var end_seqnum : int;
/** target fragment duration from M3U8 **/
public var targetduration : Number;
/** average fragment duration **/
public var averageduration : Number;
/** Total duration **/
public var duration : Number;
/** Audio Identifier **/
public var audio_stream_id : String;
/** Create the quality level. **/
public function Level() : void {
this.fragments = new Vector.<Fragment>();
};
/** Return the Fragment before a given time position. **/
public function getFragmentBeforePosition(position : Number) : Fragment {
if (fragments[0].data.valid && position < fragments[0].start_time)
return fragments[0];
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].start_time <= position && fragments[i].start_time + fragments[i].duration > position) {
return fragments[i];
}
}
return fragments[len - 1];
};
/** Return the sequence number from a given program date **/
public function getSeqNumFromProgramDate(program_date : Number) : int {
if (program_date < fragments[0].program_date)
return -1;
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
/* check whether fragment contains current position */
if (fragments[i].data.valid && fragments[i].program_date <= program_date && fragments[i].program_date + 1000 * fragments[i].duration > program_date) {
return (start_seqnum + i);
}
}
return -1;
};
/** Return the sequence number nearest a PTS **/
public function getSeqNumNearestPTS(pts : Number, continuity : int) : Number {
if (fragments.length == 0)
return -1;
var firstIndex : Number = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1 || isNaN(fragments[firstIndex].data.pts_start_computed))
return -1;
var lastIndex : Number = getLastIndexfromContinuity(continuity);
for (var i : int = firstIndex; i <= lastIndex; i++) {
var frag : Fragment = fragments[i];
/* check nearest fragment */
if ( frag.data.valid && (frag.duration >= 0) && (Math.abs(frag.data.pts_start_computed - pts) < Math.abs(frag.data.pts_start_computed + 1000 * frag.duration - pts))) {
return frag.seqnum;
}
}
// requested PTS above max PTS of this level
return Number.POSITIVE_INFINITY;
};
public function getLevelstartPTS() : Number {
if (fragments.length)
return fragments[0].data.pts_start_computed;
else
return NaN;
}
/** Return the fragment index from fragment sequence number **/
public function getFragmentfromSeqNum(seqnum : Number) : Fragment {
var index : int = getIndexfromSeqNum(seqnum);
if (index != -1) {
return fragments[index];
} else {
return null;
}
}
/** Return the fragment index from fragment sequence number **/
private function getIndexfromSeqNum(seqnum : int) : int {
if (seqnum >= start_seqnum && seqnum <= end_seqnum) {
return (fragments.length - 1 - (end_seqnum - seqnum));
} else {
return -1;
}
}
/** Return the first index matching with given continuity counter **/
private function getFirstIndexfromContinuity(continuity : int) : int {
// look for first fragment matching with given continuity index
var len : int = fragments.length;
for (var i : int = 0; i < len; i++) {
if (fragments[i].continuity == continuity)
return i;
}
return -1;
}
/** Return the first seqnum matching with given continuity counter **/
public function getFirstSeqNumfromContinuity(continuity : int) : Number {
var index : int = getFirstIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last seqnum matching with given continuity counter **/
public function getLastSeqNumfromContinuity(continuity : int) : Number {
var index : int = getLastIndexfromContinuity(continuity);
if (index == -1) {
return Number.NEGATIVE_INFINITY;
}
return fragments[index].seqnum;
}
/** Return the last index matching with given continuity counter **/
private function getLastIndexfromContinuity(continuity : Number) : int {
var firstIndex : int = getFirstIndexfromContinuity(continuity);
if (firstIndex == -1)
return -1;
var lastIndex : int = firstIndex;
// look for first fragment matching with given continuity index
for (var i : int = firstIndex; i < fragments.length; i++) {
if (fragments[i].continuity == continuity)
lastIndex = i;
else
break;
}
return lastIndex;
}
/** set Fragments **/
public function updateFragments(_fragments : Vector.<Fragment>) : void {
var idx_with_metrics : int = -1;
var len : int = _fragments.length;
var continuity_offset : int;
var frag : Fragment;
// update PTS from previous fragments
for (var i : int = 0; i < len; i++) {
frag = getFragmentfromSeqNum(_fragments[i].seqnum);
if (frag != null) {
continuity_offset = frag.continuity - _fragments[i].continuity;
if(!isNaN(frag.data.pts_start)) {
_fragments[i].data = frag.data;
idx_with_metrics = i;
}
}
}
if(continuity_offset) {
CONFIG::LOGGING {
Log.debug("updateFragments: discontinuity sliding from live playlist,take into account discontinuity drift:" + continuity_offset);
}
for (i = 0; i < len; i++) {
_fragments[i].continuity+= continuity_offset;
}
}
updateFragmentsProgramDate(_fragments);
fragments = _fragments;
if (len > 0) {
start_seqnum = _fragments[0].seqnum;
end_seqnum = _fragments[len - 1].seqnum;
if (idx_with_metrics != -1) {
frag = fragments[idx_with_metrics];
// if at least one fragment contains PTS info, recompute PTS information for all fragments
CONFIG::LOGGING {
Log.debug("updateFragments: found PTS info from previous playlist,seqnum/PTS:" + frag.seqnum + "/" + frag.data.pts_start);
}
updateFragment(frag.seqnum, true, frag.data.pts_start, frag.data.pts_start + 1000 * frag.duration);
} else {
CONFIG::LOGGING {
Log.debug("updateFragments: unknown PTS info for this level");
}
duration = _fragments[len - 1].start_time + _fragments[len - 1].duration;
}
averageduration = duration / len;
} else {
duration = 0;
averageduration = 0;
}
}
private function updateFragmentsProgramDate(_fragments : Vector.<Fragment>) : void {
var len : int = _fragments.length;
var continuity : int;
var program_date : Number;
var frag : Fragment;
for (var i : int = 0; i < len; i++) {
frag = _fragments[i];
if (frag.continuity != continuity) {
continuity = frag.continuity;
program_date = 0;
}
if (frag.program_date) {
program_date = frag.program_date + 1000 * frag.duration;
} else if (program_date) {
frag.program_date = program_date;
}
}
}
private function _updatePTS(from_index : int, to_index : int) : void {
// CONFIG::LOGGING {
// Log.info("updateFragmentPTS from/to:" + from_index + "/" + to_index);
// }
var frag_from : Fragment = fragments[from_index];
var frag_to : Fragment = fragments[to_index];
if (frag_from.data.valid && frag_to.data.valid) {
if (!isNaN(frag_to.data.pts_start)) {
// we know PTS[to_index]
frag_to.data.pts_start_computed = frag_to.data.pts_start;
/* normalize computed PTS value based on known PTS value.
* this is to avoid computing wrong fragment duration in case of PTS looping */
var from_pts : Number = PTS.normalize(frag_to.data.pts_start, frag_from.data.pts_start_computed);
/* update fragment duration.
it helps to fix drifts between playlist reported duration and fragment real duration */
if (to_index > from_index) {
frag_from.duration = (frag_to.data.pts_start - from_pts) / 1000;
CONFIG::LOGGING {
if (frag_from.duration < 0) {
Log.error("negative duration computed for " + frag_from + ", there should be some duration drift between playlist and fragment!");
}
}
} else {
frag_to.duration = ( from_pts - frag_to.data.pts_start) / 1000;
CONFIG::LOGGING {
if (frag_to.duration < 0) {
Log.error("negative duration computed for " + frag_to + ", there should be some duration drift between playlist and fragment!");
}
}
}
} else {
// we dont know PTS[to_index]
if (to_index > from_index)
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed + 1000 * frag_from.duration;
else
frag_to.data.pts_start_computed = frag_from.data.pts_start_computed - 1000 * frag_to.duration;
}
}
}
public function updateFragment(seqnum : Number, valid : Boolean, min_pts : Number = 0, max_pts : Number = 0) : void {
// CONFIG::LOGGING {
// Log.info("updatePTS : seqnum/min/max:" + seqnum + '/' + min_pts + '/' + max_pts);
// }
// get fragment from seqnum
var fragIdx : int = getIndexfromSeqNum(seqnum);
if (fragIdx != -1) {
var frag : Fragment = fragments[fragIdx];
// update fragment start PTS + duration
if (valid) {
frag.data.pts_start = min_pts;
frag.data.pts_start_computed = min_pts;
frag.duration = (max_pts - min_pts) / 1000;
} else {
frag.duration = 0;
}
frag.data.valid = valid;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[fragIdx].seqnum+"]:pts/duration:" + fragments[fragIdx].start_pts_computed + "/" + fragments[fragIdx].duration);
// }
// adjust fragment PTS/duration from seqnum-1 to frag 0
for (var i : int = fragIdx; i > 0 && fragments[i - 1].continuity == frag.continuity; i--) {
_updatePTS(i, i - 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i-1].seqnum+"]:pts/duration:" + fragments[i-1].start_pts_computed + "/" + fragments[i-1].duration);
// }
}
// adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1 && fragments[i + 1].continuity == frag.continuity; i++) {
_updatePTS(i, i + 1);
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i+1].seqnum+"]:pts/duration:" + fragments[i+1].start_pts_computed + "/" + fragments[i+1].duration);
// }
}
// second, adjust fragment offset
var start_time_offset : Number = fragments[0].start_time;
var len : int = fragments.length;
for (i = 0; i < len; i++) {
fragments[i].start_time = start_time_offset;
start_time_offset += fragments[i].duration;
// CONFIG::LOGGING {
// Log.info("SN["+fragments[i].seqnum+"]:start_time/continuity/pts/duration:" + fragments[i].start_time + "/" + fragments[i].continuity + "/"+ fragments[i].start_pts_computed + "/" + fragments[i].duration);
// }
}
duration = start_time_offset;
} else {
CONFIG::LOGGING {
Log.error("updateFragment:seqnum " + seqnum + " not found!");
}
}
}
}
}
|
remove useless line
|
remove useless line
|
ActionScript
|
mpl-2.0
|
thdtjsdn/flashls,Corey600/flashls,clappr/flashls,jlacivita/flashls,vidible/vdb-flashls,codex-corp/flashls,neilrackett/flashls,aevange/flashls,suuhas/flashls,fixedmachine/flashls,dighan/flashls,Peer5/flashls,aevange/flashls,codex-corp/flashls,fixedmachine/flashls,dighan/flashls,Peer5/flashls,thdtjsdn/flashls,tedconf/flashls,hola/flashls,mangui/flashls,suuhas/flashls,JulianPena/flashls,hola/flashls,suuhas/flashls,Peer5/flashls,suuhas/flashls,Corey600/flashls,tedconf/flashls,NicolasSiver/flashls,loungelogic/flashls,Boxie5/flashls,neilrackett/flashls,loungelogic/flashls,aevange/flashls,aevange/flashls,Peer5/flashls,Boxie5/flashls,JulianPena/flashls,mangui/flashls,clappr/flashls,jlacivita/flashls,vidible/vdb-flashls,NicolasSiver/flashls
|
00555b01f04037bd72eabe75ffcb72c242ef3cf6
|
src/aerys/minko/Minko.as
|
src/aerys/minko/Minko.as
|
package aerys.minko
{
import aerys.minko.type.log.ILogger;
public final class Minko
{
private static const VERSION : String = "2.0b";
private static var _logger : ILogger = null;
private static var _debugLevel : uint = 0; // LogLevel.DISABLED;
public static function set logger(value : ILogger) : void
{
_logger = value;
}
public static function get debugLevel() : uint
{
return _debugLevel;
}
public static function set debugLevel(value : uint) : void
{
_debugLevel = value;
}
public static function log(type : uint, message : Object, target : Object = null) : void
{
if (_debugLevel & type)
{
if (_logger != null)
_logger.log(message);
else
trace(message);
}
}
}
}
|
package aerys.minko
{
import aerys.minko.type.log.ILogger;
public final class Minko
{
private static const VERSION : String = '2.0';
private static var _logger : ILogger = null;
private static var _debugLevel : uint = 0; // LogLevel.DISABLED;
public static function set logger(value : ILogger) : void
{
_logger = value;
}
public static function get debugLevel() : uint
{
return _debugLevel;
}
public static function set debugLevel(value : uint) : void
{
_debugLevel = value;
}
public static function log(type : uint, message : Object, target : Object = null) : void
{
if (_debugLevel & type)
{
if (_logger != null)
_logger.log(message);
else
trace(message);
}
}
}
}
|
set Minko.VERSION to 2.0
|
set Minko.VERSION to 2.0
|
ActionScript
|
mit
|
aerys/minko-as3
|
dfcebb60062732342856dc586e9780e1db867e4f
|
src/goplayer/Player.as
|
src/goplayer/Player.as
|
package goplayer
{
import flash.utils.getTimer
import streamio.Stat
public class Player
implements FlashNetConnectionListener, FlashNetStreamListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(1)
private const SMALL_BUFFER : Duration = Duration.seconds(5)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const SEEK_GRACE_TIME : Duration = Duration.seconds(2)
private const finishingListeners : Array = []
private var connection : FlashNetConnection
private var _movie : Movie
private var bitratePolicy : BitratePolicy
private var enableRTMP : Boolean
private var _started : Boolean = false
private var _finished : Boolean = false
private var triedStandardRTMP : Boolean = false
private var _usingRTMP : Boolean = false
private var measuredBandwidth : Bitrate = null
private var measuredLatency : Duration = null
private var stream : FlashNetStream = null
private var metadata : Object = null
private var _volume : Number = DEFAULT_VOLUME
private var savedVolume : Number = 0
private var _paused : Boolean = false
private var _buffering : Boolean = false
private var seekStopwatch : Stopwatch = new Stopwatch
public function Player
(connection : FlashNetConnection,
movie : Movie,
bitratePolicy : BitratePolicy,
enableRTMP : Boolean)
{
this.connection = connection
_movie = movie
this.bitratePolicy = bitratePolicy
this.enableRTMP = enableRTMP
Stat.view(movie.id)
connection.listener = this
}
public function get movie() : Movie
{ return _movie }
public function addFinishingListener
(value : PlayerFinishingListener) : void
{ finishingListeners.push(value) }
public function get started() : Boolean
{ return _started }
public function get running() : Boolean
{ return started && !finished }
public function get finished() : Boolean
{ return _finished }
// -----------------------------------------------------
public function start() : void
{
_started = true
if (enableRTMP && movie.rtmpURL != null)
connectUsingRTMP()
else
connectUsingHTTP()
Stat.play(movie.id)
}
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedStandardRTMP)
handleCustomRTMPUnavailable()
else
handleRTMPUnavailable()
}
private function handleCustomRTMPUnavailable() : void
{
debug("Trying to connect using default RTMP ports.")
connectUsingStandardRTMP()
}
private function handleRTMPUnavailable() : void
{
debug("Could not connect using RTMP; trying plain HTTP.")
connectUsingHTTP()
}
public function get usingRTMP() : Boolean
{ return _usingRTMP }
private function connectUsingRTMP() : void
{ connection.connect(movie.rtmpURL) }
private function connectUsingStandardRTMP() : void
{
triedStandardRTMP = true
connection.connect(movie.rtmpURL.withoutPort)
}
private function connectUsingHTTP() : void
{
_usingRTMP = false
connection.dontConnect()
startPlaying()
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
_usingRTMP = true
if (bandwidthDeterminationNeeded)
connection.determineBandwidth()
else
startPlaying()
}
private function get bandwidthDeterminationNeeded() : Boolean
{ return bitratePolicy == BitratePolicy.BEST }
public function handleBandwidthDetermined
(bandwidth : Bitrate, latency : Duration) : void
{
measuredBandwidth = bandwidth
measuredLatency = latency
startPlaying()
}
private function get bandwidthDetermined() : Boolean
{ return measuredBandwidth != null }
private function startPlaying() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.volume = volume
useStartBuffer()
if (usingRTMP)
playRTMPStream()
else
playHTTPStream()
if (paused)
stream.paused = true
}
private function playRTMPStream() : void
{ stream.playRTMP(streamPicker.first, streamPicker.all) }
private function playHTTPStream() : void
{ stream.playHTTP(movie.httpURL) }
private function get streamPicker() : RTMPStreamPicker
{
return new RTMPStreamPicker
(movie.rtmpStreams, bitratePolicy, measuredBandwidth)
}
// -----------------------------------------------------
public function handleNetStreamMetadata(data : Object) : void
{
metadata = data
if (!usingRTMP)
debug("Video file size: " + stream.httpFileSize)
}
public function handleStreamingStarted() : void
{
useStartBuffer()
_buffering = true
_finished = false
}
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
_buffering = false
// Give the backend a chance to resume playback before we go
// ahead and raise the buffer size further.
later($handleBufferingFinished)
}
private function $handleBufferingFinished() : void
{
// Make sure playback was not interrupted.
if (!buffering && !finished)
useLargeBuffer()
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
_finished = false
}
private function useStartBuffer() : void
{ stream.bufferTime = START_BUFFER }
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function get bufferingUnexpectedly() : Boolean
{ return buffering && !justSeeked }
private function get justSeeked() : Boolean
{ return seekStopwatch.within(SEEK_GRACE_TIME) }
public function handleStreamingStopped() : void
{
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
_finished = true
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
// Allow pausing before the stream has been created.
_paused = value
if (stream)
stream.paused = value
}
public function togglePaused() : void
{
// Forbid pausing before the stream has been created.
if (stream)
paused = !paused
}
// -----------------------------------------------------
public function get playheadPosition() : Duration
{
return stream != null && stream.playheadPosition != null
? stream.playheadPosition : Duration.ZERO
}
public function get playheadRatio() : Number
{ return getRatio(playheadPosition.seconds, streamLength.seconds) }
public function get bufferRatio() : Number
{ return getRatio(bufferPosition.seconds, streamLength.seconds) }
private function getRatio
(numerator : Number, denominator : Number) : Number
{ return Math.min(1, numerator / denominator) }
private function get bufferPosition() : Duration
{ return playheadPosition.plus(bufferLength) }
public function set playheadPosition(value : Duration) : void
{
if (stream)
$playheadPosition = value
}
private function set $playheadPosition(value : Duration) : void
{
_finished = false
seekStopwatch.start()
useStartBuffer()
stream.playheadPosition = value
}
public function set playheadRatio(value : Number) : void
{ playheadPosition = streamLength.scaledBy(value) }
public function seekBy(delta : Duration) : void
{ playheadPosition = playheadPosition.plus(delta) }
public function rewind() : void
{ playheadPosition = Duration.ZERO }
public function get playing() : Boolean
{ return stream != null && !paused && !finished }
// -----------------------------------------------------
public function get volume() : Number
{ return _volume }
public function set volume(value : Number) : void
{
_volume = Math.round(clamp(value, 0, 1) * 100) / 100
if (stream)
stream.volume = value
}
public function changeVolumeBy(delta : Number) : void
{ volume = volume + delta }
public function mute() : void
{
savedVolume = volume
volume = 0
}
public function unmute() : void
{ volume = savedVolume == 0 ? DEFAULT_VOLUME : savedVolume }
public function get muted() : Boolean
{ return volume == 0 }
// -----------------------------------------------------
public function get aspectRatio() : Number
{ return movie.aspectRatio }
public function get bufferTime() : Duration
{
return stream != null && stream.bufferTime != null
? stream.bufferTime : START_BUFFER
}
public function get bufferLength() : Duration
{
return stream != null && stream.bufferLength != null
? stream.bufferLength : Duration.ZERO
}
public function get bufferFillRatio() : Number
{ return getRatio(bufferLength.seconds, bufferTime.seconds) }
public function get streamLength() : Duration
{
return metadata != null
? Duration.seconds(metadata.duration)
: movie.duration
}
public function get currentBitrate() : Bitrate
{
return stream != null && stream.bitrate != null
? stream.bitrate : Bitrate.ZERO
}
public function get currentBandwidth() : Bitrate
{
return stream != null && stream.bandwidth != null
? stream.bandwidth : Bitrate.ZERO
}
public function get highQualityDimensions() : Dimensions
{
var result : Dimensions = Dimensions.ZERO
for each (var stream : RTMPStream in movie.rtmpStreams)
if (stream.dimensions.isGreaterThan(result))
result = stream.dimensions
return result
}
}
}
|
package goplayer
{
import flash.utils.getTimer
import streamio.Stat
public class Player
implements FlashNetConnectionListener, FlashNetStreamListener
{
private const DEFAULT_VOLUME : Number = .8
private const START_BUFFER : Duration = Duration.seconds(3)
private const SMALL_BUFFER : Duration = Duration.seconds(5)
private const LARGE_BUFFER : Duration = Duration.seconds(60)
private const SEEK_GRACE_TIME : Duration = Duration.seconds(2)
private const finishingListeners : Array = []
private var connection : FlashNetConnection
private var _movie : Movie
private var bitratePolicy : BitratePolicy
private var enableRTMP : Boolean
private var _started : Boolean = false
private var _finished : Boolean = false
private var triedStandardRTMP : Boolean = false
private var _usingRTMP : Boolean = false
private var measuredBandwidth : Bitrate = null
private var measuredLatency : Duration = null
private var stream : FlashNetStream = null
private var metadata : Object = null
private var _volume : Number = DEFAULT_VOLUME
private var savedVolume : Number = 0
private var _paused : Boolean = false
private var _buffering : Boolean = false
private var seekStopwatch : Stopwatch = new Stopwatch
public function Player
(connection : FlashNetConnection,
movie : Movie,
bitratePolicy : BitratePolicy,
enableRTMP : Boolean)
{
this.connection = connection
_movie = movie
this.bitratePolicy = bitratePolicy
this.enableRTMP = enableRTMP
Stat.view(movie.id)
connection.listener = this
}
public function get movie() : Movie
{ return _movie }
public function addFinishingListener
(value : PlayerFinishingListener) : void
{ finishingListeners.push(value) }
public function get started() : Boolean
{ return _started }
public function get running() : Boolean
{ return started && !finished }
public function get finished() : Boolean
{ return _finished }
// -----------------------------------------------------
public function start() : void
{
_started = true
if (enableRTMP && movie.rtmpURL != null)
connectUsingRTMP()
else
connectUsingHTTP()
Stat.play(movie.id)
}
public function handleConnectionFailed() : void
{
if (movie.rtmpURL.hasPort && !triedStandardRTMP)
handleCustomRTMPUnavailable()
else
handleRTMPUnavailable()
}
private function handleCustomRTMPUnavailable() : void
{
debug("Trying to connect using default RTMP ports.")
connectUsingStandardRTMP()
}
private function handleRTMPUnavailable() : void
{
debug("Could not connect using RTMP; trying plain HTTP.")
connectUsingHTTP()
}
public function get usingRTMP() : Boolean
{ return _usingRTMP }
private function connectUsingRTMP() : void
{ connection.connect(movie.rtmpURL) }
private function connectUsingStandardRTMP() : void
{
triedStandardRTMP = true
connection.connect(movie.rtmpURL.withoutPort)
}
private function connectUsingHTTP() : void
{
_usingRTMP = false
connection.dontConnect()
startPlaying()
}
public function handleConnectionClosed() : void
{}
// -----------------------------------------------------
public function handleConnectionEstablished() : void
{
_usingRTMP = true
if (bandwidthDeterminationNeeded)
connection.determineBandwidth()
else
startPlaying()
}
private function get bandwidthDeterminationNeeded() : Boolean
{ return bitratePolicy == BitratePolicy.BEST }
public function handleBandwidthDetermined
(bandwidth : Bitrate, latency : Duration) : void
{
measuredBandwidth = bandwidth
measuredLatency = latency
startPlaying()
}
private function get bandwidthDetermined() : Boolean
{ return measuredBandwidth != null }
private function startPlaying() : void
{
stream = connection.getNetStream()
stream.listener = this
stream.volume = volume
useStartBuffer()
if (usingRTMP)
playRTMPStream()
else
playHTTPStream()
if (paused)
stream.paused = true
}
private function playRTMPStream() : void
{ stream.playRTMP(streamPicker.first, streamPicker.all) }
private function playHTTPStream() : void
{ stream.playHTTP(movie.httpURL) }
private function get streamPicker() : RTMPStreamPicker
{
return new RTMPStreamPicker
(movie.rtmpStreams, bitratePolicy, measuredBandwidth)
}
// -----------------------------------------------------
public function handleNetStreamMetadata(data : Object) : void
{
metadata = data
if (!usingRTMP)
debug("Video file size: " + stream.httpFileSize)
}
public function handleStreamingStarted() : void
{
useStartBuffer()
_buffering = true
_finished = false
}
public function handleBufferFilled() : void
{ handleBufferingFinished() }
private function handleBufferingFinished() : void
{
_buffering = false
// Give the backend a chance to resume playback before we go
// ahead and raise the buffer size further.
later($handleBufferingFinished)
}
private function $handleBufferingFinished() : void
{
// Make sure playback was not interrupted.
if (!buffering && !finished)
useLargeBuffer()
}
public function handleBufferEmptied() : void
{
if (finishedPlaying)
handleFinishedPlaying()
else
handleBufferingStarted()
}
private function handleBufferingStarted() : void
{
useSmallBuffer()
_buffering = true
_finished = false
}
private function useStartBuffer() : void
{ stream.bufferTime = START_BUFFER }
private function useSmallBuffer() : void
{ stream.bufferTime = SMALL_BUFFER }
private function useLargeBuffer() : void
{ stream.bufferTime = LARGE_BUFFER }
public function get buffering() : Boolean
{ return _buffering }
public function get bufferingUnexpectedly() : Boolean
{ return buffering && !justSeeked }
private function get justSeeked() : Boolean
{ return seekStopwatch.within(SEEK_GRACE_TIME) }
public function handleStreamingStopped() : void
{
if (finishedPlaying)
handleFinishedPlaying()
}
private function handleFinishedPlaying() : void
{
debug("Finished playing.")
_finished = true
for each (var listener : PlayerFinishingListener in finishingListeners)
listener.handleMovieFinishedPlaying()
}
private function get finishedPlaying() : Boolean
{ return timeRemaining.seconds < 1 }
private function get timeRemaining() : Duration
{ return streamLength.minus(playheadPosition) }
// -----------------------------------------------------
public function get paused() : Boolean
{ return _paused }
public function set paused(value : Boolean) : void
{
// Allow pausing before the stream has been created.
_paused = value
if (stream)
stream.paused = value
}
public function togglePaused() : void
{
// Forbid pausing before the stream has been created.
if (stream)
paused = !paused
}
// -----------------------------------------------------
public function get playheadPosition() : Duration
{
return stream != null && stream.playheadPosition != null
? stream.playheadPosition : Duration.ZERO
}
public function get playheadRatio() : Number
{ return getRatio(playheadPosition.seconds, streamLength.seconds) }
public function get bufferRatio() : Number
{ return getRatio(bufferPosition.seconds, streamLength.seconds) }
private function getRatio
(numerator : Number, denominator : Number) : Number
{ return Math.min(1, numerator / denominator) }
private function get bufferPosition() : Duration
{ return playheadPosition.plus(bufferLength) }
public function set playheadPosition(value : Duration) : void
{
if (stream)
$playheadPosition = value
}
private function set $playheadPosition(value : Duration) : void
{
_finished = false
seekStopwatch.start()
useStartBuffer()
stream.playheadPosition = value
}
public function set playheadRatio(value : Number) : void
{ playheadPosition = streamLength.scaledBy(value) }
public function seekBy(delta : Duration) : void
{ playheadPosition = playheadPosition.plus(delta) }
public function rewind() : void
{ playheadPosition = Duration.ZERO }
public function get playing() : Boolean
{ return stream != null && !paused && !finished }
// -----------------------------------------------------
public function get volume() : Number
{ return _volume }
public function set volume(value : Number) : void
{
_volume = Math.round(clamp(value, 0, 1) * 100) / 100
if (stream)
stream.volume = value
}
public function changeVolumeBy(delta : Number) : void
{ volume = volume + delta }
public function mute() : void
{
savedVolume = volume
volume = 0
}
public function unmute() : void
{ volume = savedVolume == 0 ? DEFAULT_VOLUME : savedVolume }
public function get muted() : Boolean
{ return volume == 0 }
// -----------------------------------------------------
public function get aspectRatio() : Number
{ return movie.aspectRatio }
public function get bufferTime() : Duration
{
return stream != null && stream.bufferTime != null
? stream.bufferTime : START_BUFFER
}
public function get bufferLength() : Duration
{
return stream != null && stream.bufferLength != null
? stream.bufferLength : Duration.ZERO
}
public function get bufferFillRatio() : Number
{ return getRatio(bufferLength.seconds, bufferTime.seconds) }
public function get streamLength() : Duration
{
return metadata != null
? Duration.seconds(metadata.duration)
: movie.duration
}
public function get currentBitrate() : Bitrate
{
return stream != null && stream.bitrate != null
? stream.bitrate : Bitrate.ZERO
}
public function get currentBandwidth() : Bitrate
{
return stream != null && stream.bandwidth != null
? stream.bandwidth : Bitrate.ZERO
}
public function get highQualityDimensions() : Dimensions
{
var result : Dimensions = Dimensions.ZERO
for each (var stream : RTMPStream in movie.rtmpStreams)
if (stream.dimensions.isGreaterThan(result))
result = stream.dimensions
return result
}
}
}
|
Use a start buffer of 3s instead of 1s.
|
Use a start buffer of 3s instead of 1s.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
1f1c7276c83d1e6892de6107049bd4ac646c72ab
|
src/org/flintparticles/twoD/zones/DiscSectorZone.as
|
src/org/flintparticles/twoD/zones/DiscSectorZone.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* 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.flintparticles.twoD.zones
{
import org.flintparticles.twoD.particles.Particle2D;
import flash.geom.Point;
/**
* The DiscSectorZone zone defines a section of a Disc zone. The disc
* on which it's based have a hole in the middle, like a doughnut.
*/
public class DiscSectorZone implements Zone2D
{
private var _center:Point;
private var _innerRadius:Number;
private var _outerRadius:Number;
private var _innerSq:Number;
private var _outerSq:Number;
private var _minAngle:Number;
private var _maxAngle:Number;
private var _minAllowed:Number;
private var _minNormal:Point;
private var _maxNormal:Point;
private static var TWOPI:Number = Math.PI * 2;
/**
* The constructor defines a DiscSectorZone zone.
*
* @param center The centre of the disc.
* @param outerRadius The radius of the outer edge of the disc.
* @param innerRadius If set, this defines the radius of the inner
* edge of the disc. Points closer to the center than this inner radius
* are excluded from the zone. If this parameter is not set then all
* points inside the outer radius are included in the zone.
* @param minAngle The minimum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
* @param maxAngle The maximum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
*/
public function DiscSectorZone( center:Point = null, outerRadius:Number = 0, innerRadius:Number = 0, minAngle:Number = 0, maxAngle:Number = 0 )
{
if( outerRadius < innerRadius )
{
throw new Error( "The outerRadius (" + outerRadius + ") can't be smaller than the innerRadius (" + innerRadius + ") in your DiscSectorZone. N.B. the outerRadius is the second argument in the constructor and the innerRadius is the third argument." );
}
_center = center ? center.clone() : new Point( 0, 0 );
_innerRadius = innerRadius;
_outerRadius = outerRadius;
_innerSq = _innerRadius * _innerRadius;
_outerSq = _outerRadius * _outerRadius;
_minAngle = minAngle;
_maxAngle = maxAngle;
if( ! isNaN( _maxAngle ) )
{
while ( _maxAngle > TWOPI )
{
_maxAngle -= TWOPI;
}
while ( _maxAngle < 0 )
{
_maxAngle += TWOPI;
}
_minAllowed = _maxAngle - TWOPI;
if( ! isNaN( _minAngle ) )
{
if ( minAngle == maxAngle )
{
_minAngle = _maxAngle;
}
else
{
_minAngle = clamp( _minAngle );
}
}
calculateNormals();
}
}
private function clamp( angle:Number ):Number
{
if( ! isNaN( _maxAngle ) )
{
while ( angle > _maxAngle )
{
angle -= TWOPI;
}
while ( angle < _minAllowed )
{
angle += TWOPI;
}
}
return angle;
}
private function calculateNormals():void
{
if( ! isNaN( _minAngle ) )
{
_minNormal = new Point( Math.sin( _minAngle ), - Math.cos( _minAngle ) );
_minNormal.normalize( 1 );
}
if( ! isNaN( _maxAngle ) )
{
_maxNormal = new Point( - Math.sin( _maxAngle ), Math.cos( _maxAngle ) );
_maxNormal.normalize( 1 );
}
}
/**
* The centre of the disc.
*/
public function get center() : Point
{
return _center;
}
public function set center( value : Point ) : void
{
_center = value;
}
/**
* The x coordinate of the point that is the center of the disc.
*/
public function get centerX() : Number
{
return _center.x;
}
public function set centerX( value : Number ) : void
{
_center.x = value;
}
/**
* The y coordinate of the point that is the center of the disc.
*/
public function get centerY() : Number
{
return _center.y;
}
public function set centerY( value : Number ) : void
{
_center.y = value;
}
/**
* The radius of the inner edge of the disc.
*/
public function get innerRadius() : Number
{
return _innerRadius;
}
public function set innerRadius( value : Number ) : void
{
_innerRadius = value;
_innerSq = _innerRadius * _innerRadius;
}
/**
* The radius of the outer edge of the disc.
*/
public function get outerRadius() : Number
{
return _outerRadius;
}
public function set outerRadius( value : Number ) : void
{
_outerRadius = value;
_outerSq = _outerRadius * _outerRadius;
}
/**
* The minimum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
*/
public function get minAngle() : Number
{
return _minAngle;
}
public function set minAngle( value : Number ) : void
{
_minAngle = clamp( value );
calculateNormals();
}
/**
* The maximum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
*/
public function get maxAngle() : Number
{
return _maxAngle;
}
public function set maxAngle( value : Number ) : void
{
_maxAngle = value;
while ( _maxAngle > TWOPI )
{
_maxAngle -= TWOPI;
}
while ( _maxAngle < 0 )
{
_maxAngle += TWOPI;
}
_minAllowed = _maxAngle - TWOPI;
_minAngle = clamp( _minAngle );
calculateNormals();
}
/**
* The contains method determines whether a point is inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @param x The x coordinate of the location to test for.
* @param y The y coordinate of the location to test for.
* @return true if point is inside the zone, false if it is outside.
*/
public function contains( x:Number, y:Number ):Boolean
{
x -= _center.x;
y -= _center.y;
var distSq:Number = x * x + y * y;
if ( distSq > _outerSq || distSq < _innerSq )
{
return false;
}
var angle:Number = Math.atan2( y, x );
angle = clamp( angle );
return angle >= _minAngle;
}
/**
* The getLocation method returns a random point inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getLocation():Point
{
var rand:Number = Math.random();
var point:Point = Point.polar( _innerRadius + (1 - rand * rand ) * ( _outerRadius - _innerRadius ), _minAngle + Math.random() * ( _maxAngle - _minAngle ) );
point.x += _center.x;
point.y += _center.y;
return point;
}
/**
* The getArea method returns the size of the zone.
* This method is used by the MultiZone class. Usually,
* it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getArea():Number
{
return ( Math.PI * _outerSq - Math.PI * _innerSq );
}
/**
* Manages collisions between a particle and the zone. The particle will collide with the edges of
* the disc sector defined for this zone, from inside or outside the disc. In the interests of speed,
* these collisions do not take account of the collisionRadius of the particle.
*
* @param particle The particle to be tested for collision with the zone.
* @param bounce The coefficient of restitution for the collision.
*
* @return Whether a collision occured.
*/
public function collideParticle(particle:Particle2D, bounce:Number = 1):Boolean
{
// This is approximate, since accurate calculations would be quite complex and thus time consuming
var xNow:Number = particle.x - _center.x;
var yNow:Number = particle.y - _center.y;
var xThen:Number = particle.previousX - _center.x;
var yThen:Number = particle.previousY - _center.y;
var insideNow:Boolean = true;
var insideThen:Boolean = true;
var distThenSq:Number = xThen * xThen + yThen * yThen;
var distNowSq:Number = xNow * xNow + yNow * yNow;
if ( distThenSq > _outerSq || distThenSq < _innerSq )
{
insideThen = false;
}
if ( distNowSq > _outerSq || distNowSq < _innerSq )
{
insideNow = false;
}
if ( (! insideNow) && (! insideThen) )
{
return false;
}
var angleThen:Number = clamp( Math.atan2( yThen, xThen ) );
var angleNow:Number = clamp( Math.atan2( yNow, xNow ) );
insideThen = insideThen && angleThen >= minAngle;
insideNow = insideNow && angleNow >= _minAngle;
if ( insideNow == insideThen )
{
return false;
}
var adjustSpeed:Number;
var dotProduct:Number = particle.velX * xNow + particle.velY * yNow;
var factor:Number;
var normalSpeed:Number;
if( insideNow )
{
if( distThenSq > _outerSq )
{
// bounce off outer radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
else if( distThenSq < _innerSq )
{
// bounce off inner radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
if( angleThen < _minAngle )
{
if( angleThen < ( _minAllowed + _minAngle ) / 2 )
{
// bounce off max radius
normalSpeed = _maxNormal.x * particle.velX + _maxNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _maxNormal.x;
particle.velY -= factor * _maxNormal.y;
}
else
{
// bounce off min radius
normalSpeed = _minNormal.x * particle.velX + _minNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _minNormal.x;
particle.velY -= factor * _minNormal.y;
}
}
}
else // inside then
{
if( distNowSq > _outerSq )
{
// bounce off outer radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
else if( distNowSq < _innerSq )
{
// bounce off inner radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
if( angleNow < _minAngle )
{
if( angleNow < ( _minAllowed + _minAngle ) / 2 )
{
// bounce off max radius
normalSpeed = _maxNormal.x * particle.velX + _maxNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _maxNormal.x;
particle.velY -= factor * _maxNormal.y;
}
else
{
// bounce off min radius
normalSpeed = _minNormal.x * particle.velX + _minNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _minNormal.x;
particle.velY -= factor * _minNormal.y;
}
}
}
particle.x = particle.previousX;
particle.y = particle.previousY;
return true;
}
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* 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.flintparticles.twoD.zones
{
import org.flintparticles.twoD.particles.Particle2D;
import flash.geom.Point;
/**
* The DiscSectorZone zone defines a section of a Disc zone. The disc
* on which it's based have a hole in the middle, like a doughnut.
*/
public class DiscSectorZone implements Zone2D
{
private var _center:Point;
private var _innerRadius:Number;
private var _outerRadius:Number;
private var _innerSq:Number;
private var _outerSq:Number;
private var _minAngle:Number;
private var _maxAngle:Number;
private var _minAllowed:Number;
private var _minNormal:Point;
private var _maxNormal:Point;
private static var TWOPI:Number = Math.PI * 2;
/**
* The constructor defines a DiscSectorZone zone.
*
* @param center The centre of the disc.
* @param outerRadius The radius of the outer edge of the disc.
* @param innerRadius If set, this defines the radius of the inner
* edge of the disc. Points closer to the center than this inner radius
* are excluded from the zone. If this parameter is not set then all
* points inside the outer radius are included in the zone.
* @param minAngle The minimum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
* @param maxAngle The maximum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
*/
public function DiscSectorZone( center:Point = null, outerRadius:Number = 0, innerRadius:Number = 0, minAngle:Number = 0, maxAngle:Number = 0 )
{
if( outerRadius < innerRadius )
{
throw new Error( "The outerRadius (" + outerRadius + ") can't be smaller than the innerRadius (" + innerRadius + ") in your DiscSectorZone. N.B. the outerRadius is the second argument in the constructor and the innerRadius is the third argument." );
}
_center = center ? center.clone() : new Point( 0, 0 );
_innerRadius = innerRadius;
_outerRadius = outerRadius;
_innerSq = _innerRadius * _innerRadius;
_outerSq = _outerRadius * _outerRadius;
_minAngle = minAngle;
_maxAngle = maxAngle;
if( ! isNaN( _maxAngle ) )
{
while ( _maxAngle > TWOPI )
{
_maxAngle -= TWOPI;
}
while ( _maxAngle < 0 )
{
_maxAngle += TWOPI;
}
_minAllowed = _maxAngle - TWOPI;
if( ! isNaN( _minAngle ) )
{
if ( minAngle == maxAngle )
{
_minAngle = _maxAngle;
}
else
{
_minAngle = clamp( _minAngle );
}
}
calculateNormals();
}
}
private function clamp( angle:Number ):Number
{
if( ! isNaN( _maxAngle ) )
{
while ( angle > _maxAngle )
{
angle -= TWOPI;
}
while ( angle < _minAllowed )
{
angle += TWOPI;
}
}
return angle;
}
private function calculateNormals():void
{
if( ! isNaN( _minAngle ) )
{
_minNormal = new Point( Math.sin( _minAngle ), - Math.cos( _minAngle ) );
_minNormal.normalize( 1 );
}
if( ! isNaN( _maxAngle ) )
{
_maxNormal = new Point( - Math.sin( _maxAngle ), Math.cos( _maxAngle ) );
_maxNormal.normalize( 1 );
}
}
/**
* The centre of the disc.
*/
public function get center() : Point
{
return _center;
}
public function set center( value : Point ) : void
{
_center = value;
}
/**
* The x coordinate of the point that is the center of the disc.
*/
public function get centerX() : Number
{
return _center.x;
}
public function set centerX( value : Number ) : void
{
_center.x = value;
}
/**
* The y coordinate of the point that is the center of the disc.
*/
public function get centerY() : Number
{
return _center.y;
}
public function set centerY( value : Number ) : void
{
_center.y = value;
}
/**
* The radius of the inner edge of the disc.
*/
public function get innerRadius() : Number
{
return _innerRadius;
}
public function set innerRadius( value : Number ) : void
{
_innerRadius = value;
_innerSq = _innerRadius * _innerRadius;
}
/**
* The radius of the outer edge of the disc.
*/
public function get outerRadius() : Number
{
return _outerRadius;
}
public function set outerRadius( value : Number ) : void
{
_outerRadius = value;
_outerSq = _outerRadius * _outerRadius;
}
/**
* The minimum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
*/
public function get minAngle() : Number
{
return _minAngle;
}
public function set minAngle( value : Number ) : void
{
_minAngle = clamp( value );
calculateNormals();
}
/**
* The maximum angle, in radians, for points to be included in the zone.
* An angle of zero is horizontal and to the right. Positive angles are in a clockwise
* direction (towards the graphical y axis). Angles are converted to a value between 0
* and two times PI.
*/
public function get maxAngle() : Number
{
return _maxAngle;
}
public function set maxAngle( value : Number ) : void
{
_maxAngle = value;
while ( _maxAngle > TWOPI )
{
_maxAngle -= TWOPI;
}
while ( _maxAngle < 0 )
{
_maxAngle += TWOPI;
}
_minAllowed = _maxAngle - TWOPI;
_minAngle = clamp( _minAngle );
calculateNormals();
}
/**
* The contains method determines whether a point is inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @param x The x coordinate of the location to test for.
* @param y The y coordinate of the location to test for.
* @return true if point is inside the zone, false if it is outside.
*/
public function contains( x:Number, y:Number ):Boolean
{
x -= _center.x;
y -= _center.y;
var distSq:Number = x * x + y * y;
if ( distSq > _outerSq || distSq < _innerSq )
{
return false;
}
var angle:Number = Math.atan2( y, x );
angle = clamp( angle );
return angle >= _minAngle;
}
/**
* The getLocation method returns a random point inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getLocation():Point
{
var rand:Number = Math.random();
var point:Point = Point.polar( _innerRadius + (1 - rand * rand ) * ( _outerRadius - _innerRadius ), _minAngle + Math.random() * ( _maxAngle - _minAngle ) );
point.x += _center.x;
point.y += _center.y;
return point;
}
/**
* The getArea method returns the size of the zone.
* This method is used by the MultiZone class. Usually,
* it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getArea():Number
{
return ( _outerSq - _innerSq ) * ( _maxAngle - _minAngle ) * 0.5;
}
/**
* Manages collisions between a particle and the zone. The particle will collide with the edges of
* the disc sector defined for this zone, from inside or outside the disc. In the interests of speed,
* these collisions do not take account of the collisionRadius of the particle.
*
* @param particle The particle to be tested for collision with the zone.
* @param bounce The coefficient of restitution for the collision.
*
* @return Whether a collision occured.
*/
public function collideParticle(particle:Particle2D, bounce:Number = 1):Boolean
{
// This is approximate, since accurate calculations would be quite complex and thus time consuming
var xNow:Number = particle.x - _center.x;
var yNow:Number = particle.y - _center.y;
var xThen:Number = particle.previousX - _center.x;
var yThen:Number = particle.previousY - _center.y;
var insideNow:Boolean = true;
var insideThen:Boolean = true;
var distThenSq:Number = xThen * xThen + yThen * yThen;
var distNowSq:Number = xNow * xNow + yNow * yNow;
if ( distThenSq > _outerSq || distThenSq < _innerSq )
{
insideThen = false;
}
if ( distNowSq > _outerSq || distNowSq < _innerSq )
{
insideNow = false;
}
if ( (! insideNow) && (! insideThen) )
{
return false;
}
var angleThen:Number = clamp( Math.atan2( yThen, xThen ) );
var angleNow:Number = clamp( Math.atan2( yNow, xNow ) );
insideThen = insideThen && angleThen >= minAngle;
insideNow = insideNow && angleNow >= _minAngle;
if ( insideNow == insideThen )
{
return false;
}
var adjustSpeed:Number;
var dotProduct:Number = particle.velX * xNow + particle.velY * yNow;
var factor:Number;
var normalSpeed:Number;
if( insideNow )
{
if( distThenSq > _outerSq )
{
// bounce off outer radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
else if( distThenSq < _innerSq )
{
// bounce off inner radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
if( angleThen < _minAngle )
{
if( angleThen < ( _minAllowed + _minAngle ) / 2 )
{
// bounce off max radius
normalSpeed = _maxNormal.x * particle.velX + _maxNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _maxNormal.x;
particle.velY -= factor * _maxNormal.y;
}
else
{
// bounce off min radius
normalSpeed = _minNormal.x * particle.velX + _minNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _minNormal.x;
particle.velY -= factor * _minNormal.y;
}
}
}
else // inside then
{
if( distNowSq > _outerSq )
{
// bounce off outer radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
else if( distNowSq < _innerSq )
{
// bounce off inner radius
adjustSpeed = ( 1 + bounce ) * dotProduct / distNowSq;
particle.velX -= adjustSpeed * xNow;
particle.velY -= adjustSpeed * yNow;
}
if( angleNow < _minAngle )
{
if( angleNow < ( _minAllowed + _minAngle ) / 2 )
{
// bounce off max radius
normalSpeed = _maxNormal.x * particle.velX + _maxNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _maxNormal.x;
particle.velY -= factor * _maxNormal.y;
}
else
{
// bounce off min radius
normalSpeed = _minNormal.x * particle.velX + _minNormal.y * particle.velY;
factor = ( 1 + bounce ) * normalSpeed;
particle.velX -= factor * _minNormal.x;
particle.velY -= factor * _minNormal.y;
}
}
}
particle.x = particle.previousX;
particle.y = particle.previousY;
return true;
}
}
}
|
Fix error in getArea() on DiscSectorZone
|
Fix error in getArea() on DiscSectorZone
|
ActionScript
|
mit
|
richardlord/Flint
|
f7e3294e8c6fdf2d3eb97aa69e57dbc511339458
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : Vector.<uint> = null;
private var _usage : uint = 0;
private var _resource : IndexBuffer3DResource = null;
private var _length : uint = 0;
private var _changed : Signal = new Signal('IndexStream.changed');
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : Vector.<uint> = null,
length : uint = 0)
{
super();
initialize(data, length, usage);
}
minko_stream function invalidate() : void
{
_length = _data.length;
_changed.execute(this);
}
private function initialize(indices : Vector.<uint>,
length : uint,
usage : uint) : void
{
_usage = usage;
_resource = new IndexBuffer3DResource(this);
if (indices)
{
var numIndices : int = indices && length == 0
? indices.length
: Math.min(indices.length, length);
_data = new Vector.<uint>(numIndices);
for (var i : int = 0; i < numIndices; ++i)
_data[i] = indices[i];
}
else
{
_data = dummyData(length);
}
invalidate();
}
/*override flash_proxy function getProperty(name : *) : *
{
return _data[int(name)];
}
override flash_proxy function setProperty(name : *, value : *) : void
{
var index : int = int(name);
_data[index] = int(value);
invalidate();
}
override flash_proxy function nextNameIndex(index : int) : int
{
return index >= _data.length ? 0 : index + 1;
}
override flash_proxy function nextValue(index : int) : *
{
return _data[int(index - 1)];
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
var index : int = int(name);
var length : int = length;
if (index > length)
return false;
for (var i : int = index; i < length - 1; ++i)
_data[i] = _data[int(i + 1)];
_data.length = length - 1;
invalidate();
return true;
}*/
public function get(index : int) : uint
{
checkReadUsage(this);
return _data[index];
}
public function set(index : int, value : uint) : void
{
checkWriteUsage(this);
_data[index] = value;
}
public function deleteTriangleByIndex(index : int) : Vector.<uint>
{
checkWriteUsage(this);
var deletedIndices : Vector.<uint> = _data.splice(index, 3);
invalidate();
return deletedIndices;
}
public function getIndices(indices : Vector.<uint> = null) : Vector.<uint>
{
checkReadUsage(this);
var numIndices : int = length;
indices ||= new Vector.<uint>();
for (var i : int = 0; i < numIndices; ++i)
indices[i] = _data[i];
return indices;
}
public function setIndices(indices : Vector.<uint>) : void
{
checkWriteUsage(this);
var length : int = indices.length;
for (var i : int = 0; i < length; ++i)
_data[i] = indices[i];
_data.length = length;
invalidate();
}
public function clone() : IndexStream
{
return new IndexStream(_usage, _data, length);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
var numIndices : int = _data.length;
var toConcat : Vector.<uint> = indexStream._data;
count ||= toConcat.length;
for (var i : int = 0; i < count; ++i, ++numIndices)
_data[numIndices] = toConcat[int(firstIndex + i)] + offset;
invalidate();
return this;
}
public function push(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : void
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
for (var i : int = 0; i < count; ++i)
_data[int(numIndices++)] = indices[int(firstIndex + i)] + offset;
invalidate();
}
public function disposeLocalData() : void
{
if (length != resource.numIndices)
{
throw new Error(
"Unable to dispose local data: "
+ "some indices have not been uploaded."
);
}
_data = null;
_usage = StreamUsage.STATIC;
}
public function dispose() : void
{
_resource.dispose();
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage '
+ 'is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage '
+ 'is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint, offset : uint = 0) : Vector.<uint>
{
var indices : Vector.<uint> = new Vector.<uint>(size);
for (var i : int = 0; i < size; ++i)
indices[i] = i + offset;
return indices;
}
public static function fromByteArray(usage : uint,
data : ByteArray,
numIndices : int) : IndexStream
{
var indices : Vector.<uint> = new Vector.<uint>(numIndices, true);
var stream : IndexStream = new IndexStream(usage);
for (var i : int = 0; i < numIndices; ++i)
indices[i] = data.readInt();
stream._data = indices;
stream.invalidate();
return stream;
}
}
}
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : Vector.<uint> = null;
private var _usage : uint = 0;
private var _resource : IndexBuffer3DResource = null;
private var _length : uint = 0;
private var _changed : Signal = new Signal('IndexStream.changed');
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : Vector.<uint> = null,
length : uint = 0)
{
super();
initialize(data, length, usage);
}
minko_stream function invalidate() : void
{
_length = _data.length;
_changed.execute(this);
}
private function initialize(indices : Vector.<uint>,
length : uint,
usage : uint) : void
{
_usage = usage;
_resource = new IndexBuffer3DResource(this);
if (indices)
{
var numIndices : int = indices && length == 0
? indices.length
: Math.min(indices.length, length);
_data = new Vector.<uint>(numIndices);
for (var i : int = 0; i < numIndices; ++i)
_data[i] = indices[i];
}
else
{
_data = dummyData(length);
}
invalidate();
}
public function get(index : int) : uint
{
checkReadUsage(this);
return _data[index];
}
public function set(index : int, value : uint) : void
{
checkWriteUsage(this);
_data[index] = value;
}
public function deleteTriangleByIndex(index : int) : Vector.<uint>
{
checkWriteUsage(this);
var deletedIndices : Vector.<uint> = _data.splice(index, 3);
invalidate();
return deletedIndices;
}
public function getIndices(indices : Vector.<uint> = null) : Vector.<uint>
{
checkReadUsage(this);
var numIndices : int = length;
indices ||= new Vector.<uint>();
for (var i : int = 0; i < numIndices; ++i)
indices[i] = _data[i];
return indices;
}
public function setIndices(indices : Vector.<uint>) : void
{
checkWriteUsage(this);
var length : int = indices.length;
for (var i : int = 0; i < length; ++i)
_data[i] = indices[i];
_data.length = length;
invalidate();
}
public function clone() : IndexStream
{
return new IndexStream(_usage, _data, length);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
var numIndices : int = _data.length;
var toConcat : Vector.<uint> = indexStream._data;
count ||= toConcat.length;
for (var i : int = 0; i < count; ++i, ++numIndices)
_data[numIndices] = toConcat[int(firstIndex + i)] + offset;
invalidate();
return this;
}
public function push(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : void
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
for (var i : int = 0; i < count; ++i)
_data[int(numIndices++)] = indices[int(firstIndex + i)] + offset;
invalidate();
}
public function disposeLocalData() : void
{
if (length != resource.numIndices)
{
throw new Error(
"Unable to dispose local data: "
+ "some indices have not been uploaded."
);
}
_data = null;
_usage = StreamUsage.STATIC;
}
public function dispose() : void
{
_resource.dispose();
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage '
+ 'is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage '
+ 'is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint, offset : uint = 0) : Vector.<uint>
{
var indices : Vector.<uint> = new Vector.<uint>(size);
for (var i : int = 0; i < size; ++i)
indices[i] = i + offset;
return indices;
}
public static function fromByteArray(usage : uint,
data : ByteArray,
numIndices : int) : IndexStream
{
var indices : Vector.<uint> = new Vector.<uint>(numIndices, true);
var stream : IndexStream = new IndexStream(usage);
for (var i : int = 0; i < numIndices; ++i)
indices[i] = data.readInt();
stream._data = indices;
stream.invalidate();
return stream;
}
}
}
|
fix minor coding style issue in IndexStream.initialize()
|
fix minor coding style issue in IndexStream.initialize()
|
ActionScript
|
mit
|
aerys/minko-as3
|
e74a7b2d151c424cb77a7435cef5e139548e9930
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
import flash.utils.Endian;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : ByteArray;
minko_stream var _localDispose : Boolean;
private var _usage : uint;
private var _resource : IndexBuffer3DResource;
private var _length : uint;
private var _locked : Boolean;
private var _changed : Signal;
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value << 1;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : ByteArray = null,
length : uint = 0)
{
super();
initialize(data, length, usage);
}
minko_stream function invalidate() : void
{
_data.position = 0;
_length = _data.length >>> 1;
if (_length % 3 != 0)
throw new Error('Invalid size');
if (!_locked)
_changed.execute(this);
}
private function initialize(data : ByteArray,
length : uint,
usage : uint) : void
{
_changed = new Signal('IndexStream.changed');
_usage = usage;
_resource = new IndexBuffer3DResource(this);
_data = new ByteArray();
_data.endian = Endian.LITTLE_ENDIAN;
if (data)
{
if (data.endian != Endian.LITTLE_ENDIAN)
throw new Error('Endianness must be Endian.LITTLE_ENDIAN.');
if (length == 0)
length = data.bytesAvailable;
if (length % 6 != 0)
throw new Error('Invalid size');
data.readBytes(_data, 0, length);
}
else
{
_data = dummyData(length);
}
_data.position = 0;
invalidate();
}
public function get(index : uint) : uint
{
var value : uint = 0;
checkReadUsage(this);
_data.position = index << 1;
value = _data.readUnsignedShort();
_data.position = 0;
return value;
}
public function set(index : uint, value : uint) : void
{
checkWriteUsage(this);
_data.position = index << 1;
_data.writeShort(value);
_data.position = 0;
invalidate();
}
public function deleteTriangle(triangleIndex : uint) : void
{
checkWriteUsage(this);
_data.position = 0;
_data.writeBytes(_data, triangleIndex * 12, 12);
_data.length -= 12;
_data.position = 0;
invalidate();
}
public function clone(usage : uint = 0) : IndexStream
{
return new IndexStream(usage || _usage, _data);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
indexOffset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
pushBytes(indexStream._data, firstIndex, count, indexOffset);
indexStream._data.position = 0;
return this;
}
public function pushBytes(bytes : ByteArray,
firstIndex : uint = 0,
count : uint = 0,
indexOffset : uint = 0) : IndexStream
{
count ||= bytes.length >>> 1;
_data.position = _data.length;
if (indexOffset == 0)
_data.writeBytes(bytes, firstIndex << 1, count << 1);
else
{
bytes.position = firstIndex << 1;
for (var i : uint = 0; i < count; ++i)
_data.writeShort(bytes.readUnsignedShort() + indexOffset);
}
_data.position = 0;
bytes.position = (firstIndex + count) << 1;
invalidate();
return this;
}
public function pushVector(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
_data.position = _data.length;
for (var i : int = 0; i < count; ++i)
_data.writeShort(indices[int(firstIndex + i)] + offset);
_data.position = 0;
invalidate();
return this;
}
public function pushTriangle(index1 : uint, index2 : uint, index3 : uint) : IndexStream
{
return setTriangle(length * 3, index1, index2, index3);
}
public function setTriangle(triangleIndex : uint,
index1 : uint,
index2 : uint,
index3 : uint) : IndexStream
{
_data.position = triangleIndex << 1;
_data.writeShort(index1);
_data.writeShort(index2);
_data.writeShort(index3);
_data.position = 0;
invalidate();
return this;
}
public function disposeLocalData(waitForUpload : Boolean = true) : void
{
if (waitForUpload && _length != resource.numIndices)
_localDispose = true;
else
{
_data = null;
_usage = StreamUsage.STATIC;
}
}
public function dispose() : void
{
_resource.dispose();
}
public function lock() : ByteArray
{
checkReadUsage(this);
_data.position = 0;
_locked = true;
return _data;
}
public function unlock(hasChanged : Boolean = true) : void
{
_data.position = 0;
_locked = false;
if (hasChanged)
invalidate();
}
/**
* Clones the IndexStream by creating a new underlying ByteArray and applying an offset on the indices.
*
* @param indexStream The IndexStream to clone.
* @param offset The offset to apply on the indices.
*
* @return The offseted new IndexStream.
*
*/
public static function cloneWithOffset(indexStream : IndexStream,
offset : uint = 0) : IndexStream
{
if (!(indexStream.usage & StreamUsage.READ))
{
throw new Error('Unable to read from index stream: stream usage is not set to StreamUsage.READ.');
}
var newData : ByteArray = new ByteArray();
newData.endian = Endian.LITTLE_ENDIAN;
var oldData : ByteArray = indexStream._data;
oldData.position = 0;
while (oldData.bytesAvailable)
{
var index : uint = oldData.readUnsignedShort() + offset;
newData.writeShort(index);
}
newData.position = 0;
return new IndexStream(indexStream.usage, newData);
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint,
offset : uint = 0) : ByteArray
{
var indices : ByteArray = new ByteArray();
indices.endian = Endian.LITTLE_ENDIAN;
for (var i : int = 0; i < size; ++i)
indices.writeShort(i + offset);
indices.position = 0;
return indices;
}
public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream
{
var stream : IndexStream = new IndexStream(usage);
var numIndices : uint = data.length;
for (var i : uint = 0; i < numIndices; ++i)
stream._data.writeShort(data[i]);
stream._data.position = 0;
stream._length = numIndices;
return stream;
}
}
}
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
import flash.utils.Endian;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : ByteArray;
minko_stream var _localDispose : Boolean;
private var _usage : uint;
private var _resource : IndexBuffer3DResource;
private var _length : uint;
private var _locked : Boolean;
private var _changed : Signal;
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value << 1;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : ByteArray = null,
length : uint = 0)
{
super();
initialize(data, length, usage);
}
minko_stream function invalidate() : void
{
_data.position = 0;
_length = _data.length >>> 1;
if (_length % 3 != 0)
throw new Error('Invalid size');
if (!_locked)
_changed.execute(this);
}
private function initialize(data : ByteArray,
length : uint,
usage : uint) : void
{
_changed = new Signal('IndexStream.changed');
_usage = usage;
_resource = new IndexBuffer3DResource(this);
_data = new ByteArray();
_data.endian = Endian.LITTLE_ENDIAN;
if (data)
{
if (data.endian != Endian.LITTLE_ENDIAN)
throw new Error('Endianness must be Endian.LITTLE_ENDIAN.');
if (length == 0)
length = data.bytesAvailable;
if (length % 6 != 0)
throw new Error('Invalid size');
data.readBytes(_data, 0, length);
}
else
{
_data = dummyData(length);
}
_data.position = 0;
invalidate();
}
public function get(index : uint) : uint
{
var value : uint = 0;
checkReadUsage(this);
_data.position = index << 1;
value = _data.readUnsignedShort();
_data.position = 0;
return value;
}
public function set(index : uint, value : uint) : void
{
checkWriteUsage(this);
_data.position = index << 1;
_data.writeShort(value);
_data.position = 0;
invalidate();
}
public function deleteTriangle(triangleIndex : uint) : void
{
checkWriteUsage(this);
_data.position = _data.length - 6;
var v0 : uint = _data.readShort();
var v1 : uint = _data.readShort();
var v2 : uint = _data.readShort();
_data.position = triangleIndex * 12;
_data.writeShort(v0);
_data.writeShort(v1);
_data.writeShort(v2);
// _data.writeBytes(_data, triangleIndex * 12, 12);
_data.length -= 6;
_data.position = 0;
invalidate();
}
public function clone(usage : uint = 0) : IndexStream
{
return new IndexStream(usage || _usage, _data);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
indexOffset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
pushBytes(indexStream._data, firstIndex, count, indexOffset);
indexStream._data.position = 0;
return this;
}
public function pushBytes(bytes : ByteArray,
firstIndex : uint = 0,
count : uint = 0,
indexOffset : uint = 0) : IndexStream
{
count ||= bytes.length >>> 1;
_data.position = _data.length;
if (indexOffset == 0)
_data.writeBytes(bytes, firstIndex << 1, count << 1);
else
{
bytes.position = firstIndex << 1;
for (var i : uint = 0; i < count; ++i)
_data.writeShort(bytes.readUnsignedShort() + indexOffset);
}
_data.position = 0;
bytes.position = (firstIndex + count) << 1;
invalidate();
return this;
}
public function pushVector(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
_data.position = _data.length;
for (var i : int = 0; i < count; ++i)
_data.writeShort(indices[int(firstIndex + i)] + offset);
_data.position = 0;
invalidate();
return this;
}
public function pushTriangle(index1 : uint, index2 : uint, index3 : uint) : IndexStream
{
return setTriangle(length * 3, index1, index2, index3);
}
public function setTriangle(triangleIndex : uint,
index1 : uint,
index2 : uint,
index3 : uint) : IndexStream
{
_data.position = triangleIndex << 1;
_data.writeShort(index1);
_data.writeShort(index2);
_data.writeShort(index3);
_data.position = 0;
invalidate();
return this;
}
public function disposeLocalData(waitForUpload : Boolean = true) : void
{
if (waitForUpload && _length != resource.numIndices)
_localDispose = true;
else
{
_data = null;
_usage = StreamUsage.STATIC;
}
}
public function dispose() : void
{
_resource.dispose();
}
public function lock() : ByteArray
{
checkReadUsage(this);
_data.position = 0;
_locked = true;
return _data;
}
public function unlock(hasChanged : Boolean = true) : void
{
_data.position = 0;
_locked = false;
if (hasChanged)
invalidate();
}
/**
* Clones the IndexStream by creating a new underlying ByteArray and applying an offset on the indices.
*
* @param indexStream The IndexStream to clone.
* @param offset The offset to apply on the indices.
*
* @return The offseted new IndexStream.
*
*/
public static function cloneWithOffset(indexStream : IndexStream,
offset : uint = 0) : IndexStream
{
if (!(indexStream.usage & StreamUsage.READ))
{
throw new Error('Unable to read from index stream: stream usage is not set to StreamUsage.READ.');
}
var newData : ByteArray = new ByteArray();
newData.endian = Endian.LITTLE_ENDIAN;
var oldData : ByteArray = indexStream._data;
oldData.position = 0;
while (oldData.bytesAvailable)
{
var index : uint = oldData.readUnsignedShort() + offset;
newData.writeShort(index);
}
newData.position = 0;
return new IndexStream(indexStream.usage, newData);
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint,
offset : uint = 0) : ByteArray
{
var indices : ByteArray = new ByteArray();
indices.endian = Endian.LITTLE_ENDIAN;
for (var i : int = 0; i < size; ++i)
indices.writeShort(i + offset);
indices.position = 0;
return indices;
}
public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream
{
var stream : IndexStream = new IndexStream(usage);
var numIndices : uint = data.length;
for (var i : uint = 0; i < numIndices; ++i)
stream._data.writeShort(data[i]);
stream._data.position = 0;
stream._length = numIndices;
return stream;
}
}
}
|
Fix delete triangle function
|
Fix delete triangle function
|
ActionScript
|
mit
|
aerys/minko-as3
|
a658c4e0c55e024b0345d7f824c366cb4f1df1e9
|
src/flash/display/BitmapData.as
|
src/flash/display/BitmapData.as
|
package flash.display {
import Object;
import flash.display.IBitmapDrawable;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.filters.BitmapFilter;
import flash.utils.ByteArray;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
public class BitmapData implements IBitmapDrawable {
public function BitmapData(width:int, height:int, transparent:Boolean = true, fillColor:uint = 4294967295) {}
public native function clone():BitmapData;
public native function get width():int;
public native function get height():int;
public native function get transparent():Boolean;
public function get rect():Rectangle { notImplemented("rect"); }
public native function getPixel(x:int, y:int):uint;
public native function getPixel32(x:int, y:int):uint;
public native function setPixel(x:int, y:int, color:uint):void;
public native function setPixel32(x:int, y:int, color:uint):void;
public native function applyFilter(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, filter:BitmapFilter):void;
public native function colorTransform(rect:Rectangle, colorTransform:ColorTransform):void;
public native function compare(otherBitmapData:BitmapData):Object;
public native function copyChannel(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, sourceChannel:uint, destChannel:uint):void;
public native function copyPixels(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, alphaBitmapData:BitmapData = null, alphaPoint:Point = null, mergeAlpha:Boolean = false):void;
public native function dispose():void;
public native function draw(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false):void;
public native function drawWithQuality(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false, quality:String = null):void;
public native function fillRect(rect:Rectangle, color:uint):void;
public native function floodFill(x:int, y:int, color:uint):void;
public native function generateFilterRect(sourceRect:Rectangle, filter:BitmapFilter):Rectangle;
public native function getColorBoundsRect(mask:uint, color:uint, findColor:Boolean = true):Rectangle;
public native function getPixels(rect:Rectangle):ByteArray;
public native function copyPixelsToByteArray(rect:Rectangle, data:ByteArray):void;
public native function getVector(rect:Rectangle):Vector;
public native function hitTest(firstPoint:Point, firstAlphaThreshold:uint, secondObject:Object, secondBitmapDataPoint:Point = null, secondAlphaThreshold:uint = 1):Boolean;
public native function merge(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redMultiplier:uint, greenMultiplier:uint, blueMultiplier:uint, alphaMultiplier:uint):void;
public native function noise(randomSeed:int, low:uint = 0, high:uint = 255, channelOptions:uint = 7, grayScale:Boolean = false):void;
public native function paletteMap(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redArray:Array = null, greenArray:Array = null, blueArray:Array = null, alphaArray:Array = null):void;
public native function perlinNoise(baseX:Number, baseY:Number, numOctaves:uint, randomSeed:int, stitch:Boolean, fractalNoise:Boolean, channelOptions:uint = 7, grayScale:Boolean = false, offsets:Array = null):void;
public native function pixelDissolve(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, randomSeed:int = 0, numPixels:int = 0, fillColor:uint = 0):int;
public native function scroll(x:int, y:int):void;
public native function setPixels(rect:Rectangle, inputByteArray:ByteArray):void;
public native function setVector(rect:Rectangle, inputVector:Vector):void;
public native function threshold(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, operation:String, threshold:uint, color:uint = 0, mask:uint = 4294967295, copySource:Boolean = false):uint;
public native function lock():void;
public native function unlock(changeRect:Rectangle = null):void;
public native function histogram(hRect:Rectangle = null):Vector;
public native function encode(rect:Rectangle, compressor:Object, byteArray:ByteArray = null):ByteArray;
}
}
|
/*
* Copyright 2014 Mozilla Foundation
*
* 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
*totalMemory
* 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 flash.display {
import Object;
import flash.display.IBitmapDrawable;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.filters.BitmapFilter;
import flash.utils.ByteArray;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
[native(cls='BitmapData')]
public class BitmapData implements IBitmapDrawable {
public function BitmapData(width:int, height:int, transparent:Boolean = true, fillColor:uint = 4294967295) {}
public native function clone():BitmapData;
public native function get width():int;
public native function get height():int;
public native function get transparent():Boolean;
public function get rect():Rectangle { return new Rectangle (0, 0, width(), height()); }
public native function getPixel(x:int, y:int):uint;
public native function getPixel32(x:int, y:int):uint;
public native function setPixel(x:int, y:int, color:uint):void;
public native function setPixel32(x:int, y:int, color:uint):void;
public native function applyFilter(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, filter:BitmapFilter):void;
public native function colorTransform(rect:Rectangle, colorTransform:ColorTransform):void;
public native function compare(otherBitmapData:BitmapData):Object;
public native function copyChannel(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, sourceChannel:uint, destChannel:uint):void;
public native function copyPixels(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, alphaBitmapData:BitmapData = null, alphaPoint:Point = null, mergeAlpha:Boolean = false):void;
public native function dispose():void;
public native function draw(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false):void;
public native function drawWithQuality(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false, quality:String = null):void;
public native function fillRect(rect:Rectangle, color:uint):void;
public native function floodFill(x:int, y:int, color:uint):void;
public native function generateFilterRect(sourceRect:Rectangle, filter:BitmapFilter):Rectangle;
public native function getColorBoundsRect(mask:uint, color:uint, findColor:Boolean = true):Rectangle;
public native function getPixels(rect:Rectangle):ByteArray;
public native function copyPixelsToByteArray(rect:Rectangle, data:ByteArray):void;
public native function getVector(rect:Rectangle):Vector;
public native function hitTest(firstPoint:Point, firstAlphaThreshold:uint, secondObject:Object, secondBitmapDataPoint:Point = null, secondAlphaThreshold:uint = 1):Boolean;
public native function merge(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redMultiplier:uint, greenMultiplier:uint, blueMultiplier:uint, alphaMultiplier:uint):void;
public native function noise(randomSeed:int, low:uint = 0, high:uint = 255, channelOptions:uint = 7, grayScale:Boolean = false):void;
public native function paletteMap(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redArray:Array = null, greenArray:Array = null, blueArray:Array = null, alphaArray:Array = null):void;
public native function perlinNoise(baseX:Number, baseY:Number, numOctaves:uint, randomSeed:int, stitch:Boolean, fractalNoise:Boolean, channelOptions:uint = 7, grayScale:Boolean = false, offsets:Array = null):void;
public native function pixelDissolve(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, randomSeed:int = 0, numPixels:int = 0, fillColor:uint = 0):int;
public native function scroll(x:int, y:int):void;
public native function setPixels(rect:Rectangle, inputByteArray:ByteArray):void;
public native function setVector(rect:Rectangle, inputVector:Vector):void;
public native function threshold(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, operation:String, threshold:uint, color:uint = 0, mask:uint = 4294967295, copySource:Boolean = false):uint;
public native function lock():void;
public native function unlock(changeRect:Rectangle = null):void;
public native function histogram(hRect:Rectangle = null):Vector;
public native function encode(rect:Rectangle, compressor:Object, byteArray:ByteArray = null):ByteArray;
}
}
|
Implement BitmapData()
|
Implement BitmapData()
|
ActionScript
|
apache-2.0
|
mozilla/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway
|
676b003e42042ed1137442313595b6874cd8560a
|
common/actionscript/org/concord/sparks/JavaScript.as
|
common/actionscript/org/concord/sparks/JavaScript.as
|
package org.concord.sparks {
import flash.events.ErrorEvent;
import flash.external.ExternalInterface;
import org.concord.sparks.Activity;
// Interface with external JavaScript
public class JavaScript {
private static var _instance:JavaScript;
private static var _fromWithin:Boolean = false;
private var activity:Activity;
public static function instance() {
if (! _instance) {
_fromWithin = true;
_instance = new JavaScript();
_fromWithin = false;
}
return _instance;
}
public function JavaScript() {
if (! _fromWithin) {
throw new Error("Constructor JavaScript() is not supposed to be called from outside.");
}
this.activity = activity;
setupCallbacks();
}
public function setActivity(activity:Activity) {
this.activity = activity;
}
public function call(func:String, ... values) {
var args = values;
args.unshift(func);
ExternalInterface.call.apply(null, args);
}
public function sendEvent(name:String, ... values) {
var time = String(new Date().valueOf());
ExternalInterface.call('receiveEvent', name, values.join('|'), time);
}
private function setupCallbacks():void {
ExternalInterface.addCallback("sendMessageToFlash",
getMessageFromJavaScript);
}
private function parseParameter(parm) {
var tokens:Array = parm.split(':');
switch (tokens[1]) {
case "int":
return parseInt(tokens[0]);
default: //string
return tokens[0];
}
}
private function getMessageFromJavaScript(... Arguments):String {
try {
return activity.processMessageFromJavaScript(Arguments);
}
catch (e:ErrorEvent) {
return 'flash_error|' + e.toString();
}
catch (e:Error) {
return 'flash_error|' + e.name + '\n' + e.message + '\n' + e.getStackTrace();
}
return 'flash_error|this point should be unreachable';
}
}
}
|
package org.concord.sparks {
import flash.events.ErrorEvent;
import flash.external.ExternalInterface;
import org.concord.sparks.Activity;
// Interface with external JavaScript
public class JavaScript {
private static var _instance:JavaScript;
private static var _fromWithin:Boolean = false;
private var activity:Activity;
public static function instance() {
if (! _instance) {
_fromWithin = true;
_instance = new JavaScript();
_fromWithin = false;
}
return _instance;
}
public function JavaScript() {
if (! _fromWithin) {
throw new Error("Constructor JavaScript() is not supposed to be called from outside.");
}
this.activity = activity;
setupCallbacks();
}
public function setActivity(activity:Activity) {
this.activity = activity;
}
public function call(func:String, ... values) {
var args = values;
args.unshift(func);
if (ExternalInterface.available) {
ExternalInterface.call.apply(null, args);
}
else {
trace('ExternalInterface unavailable: tried to call ' + func + '(' + args + ')');
}
}
public function sendEvent(name:String, ... values) {
var time = String(new Date().valueOf());
if (ExternalInterface.available) {
ExternalInterface.call('receiveEvent', name, values.join('|'), time);
}
else {
trace('ExternalInterface unavailable: tried to call receiveEvent(' + name + ', ' + values.join('|') + ', ' + time + ')');
}
}
private function setupCallbacks():void {
if (ExternalInterface.available) {
ExternalInterface.addCallback("sendMessageToFlash",
getMessageFromJavaScript);
}
}
private function parseParameter(parm) {
var tokens:Array = parm.split(':');
switch (tokens[1]) {
case "int":
return parseInt(tokens[0]);
default: //string
return tokens[0];
}
}
private function getMessageFromJavaScript(... Arguments):String {
try {
return activity.processMessageFromJavaScript(Arguments);
}
catch (e:ErrorEvent) {
return 'flash_error|' + e.toString();
}
catch (e:Error) {
return 'flash_error|' + e.name + '\n' + e.message + '\n' + e.getStackTrace();
}
return 'flash_error|this point should be unreachable';
}
}
}
|
Check if ExternalInterface is available
|
Check if ExternalInterface is available
|
ActionScript
|
apache-2.0
|
concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks
|
7b402d32753ec8e63b2d18b52047a75bb8842cd0
|
lib/src/com/amanitadesign/steam/SteamConstants.as
|
lib/src/com/amanitadesign/steam/SteamConstants.as
|
/*
* SteamConstants.as
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class SteamConstants
{
/* response values */
public static const RESPONSE_OK:int = 0;
public static const RESPONSE_FAILED:int = 1;
/* response types */
public static const RESPONSE_OnUserStatsReceived:int = 0;
public static const RESPONSE_OnUserStatsStored:int = 1;
public static const RESPONSE_OnAchievementStored:int = 2;
public static const RESPONSE_OnGameOverlayActivated:int = 3;
public static const RESPONSE_OnFileShared:int = 4;
public static const RESPONSE_OnUGCDownload:int = 5;
public static const RESPONSE_OnPublishWorkshopFile:int = 6;
public static const RESPONSE_OnDeletePublishedFile:int = 7;
public static const RESPONSE_OnGetPublishedFileDetails:int = 8;
public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9;
public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10;
public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11;
public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12;
public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13;
public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14;
public static const RESPONSE_OnSubscribePublishedFile:int = 15;
public static const RESPONSE_OnUnsubscribePublishedFile:int = 16;
public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17;
public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18;
public static const RESPONSE_OnSetUserPublishedFileAction:int = 19;
}
}
|
/*
* SteamConstants.as
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class SteamConstants
{
/* response values */
public static const RESPONSE_OK:int = 0;
public static const RESPONSE_FAILED:int = 1;
/* response types */
public static const RESPONSE_OnUserStatsReceived:int = 0;
public static const RESPONSE_OnUserStatsStored:int = 1;
public static const RESPONSE_OnAchievementStored:int = 2;
public static const RESPONSE_OnGameOverlayActivated:int = 3;
public static const RESPONSE_OnFileShared:int = 4;
public static const RESPONSE_OnUGCDownload:int = 5;
public static const RESPONSE_OnPublishWorkshopFile:int = 6;
public static const RESPONSE_OnDeletePublishedFile:int = 7;
public static const RESPONSE_OnGetPublishedFileDetails:int = 8;
public static const RESPONSE_OnEnumerateUserPublishedFiles:int = 9;
public static const RESPONSE_OnEnumeratePublishedWorkshopFiles:int = 10;
public static const RESPONSE_OnEnumerateUserSubscribedFiles:int = 11;
public static const RESPONSE_OnEnumerateUserSharedWorkshopFiles:int = 12;
public static const RESPONSE_OnEnumeratePublishedFilesByUserAction:int = 13;
public static const RESPONSE_OnCommitPublishedFileUpdate:int = 14;
public static const RESPONSE_OnSubscribePublishedFile:int = 15;
public static const RESPONSE_OnUnsubscribePublishedFile:int = 16;
public static const RESPONSE_OnGetPublishedItemVoteDetails:int = 17;
public static const RESPONSE_OnUpdateUserPublishedItemVote:int = 18;
public static const RESPONSE_OnSetUserPublishedFileAction:int = 19;
public static const RESPONSE_OnDLCInstalled:int = 20;
}
}
|
Add OnDLCInstalled event id to SteamConstants
|
Add OnDLCInstalled event id to SteamConstants
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
f79d03f684f3a25ba50ced9dedd1ecc58ee98856
|
src/com/google/analytics/utils/Environment.as
|
src/com/google/analytics/utils/Environment.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* 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.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.utils
{
import core.strings.userAgent;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.external.HTMLDOM;
import flash.system.Capabilities;
import flash.system.Security;
import flash.system.System;
/**
* Environment provides informations for the local environment.
*/
public class Environment
{
private var _debug:DebugConfiguration;
private var _dom:HTMLDOM;
private var _protocol:Protocols;
private var _appName:String;
private var _appVersion:Version;
private var _userAgent:String;
private var _url:String;
/**
* Creates a new Environment instance.
* @param url The URL of the SWF.
* @param app The application name
* @param version The application version
* @param dom the HTMLDOM reference.
*/
public function Environment( url:String = "", app:String = "", version:String = "",
debug:DebugConfiguration = null, dom:HTMLDOM = null )
{
var v:Version;
if( app == "" )
{
if( isAIR() )
{
app = "AIR";
}
else
{
app = "Flash";
}
}
if( version == "" )
{
v = flashVersion;
}
else
{
v = Version.fromString( version );
}
_url = url;
_appName = app;
_appVersion = v;
_debug = debug;
_dom = dom;
}
/**
* @private
*/
private function _findProtocol():void
{
var p:Protocols = Protocols.none;
if(_url != "")
{
// file://
// http://
// https://
var URL:String = _url.toLowerCase();
var test:String = URL.substr(0,5);
switch( test )
{
case "file:":
{
p = Protocols.file;
break;
}
case "http:":
{
p = Protocols.HTTP;
break;
}
case "https":
{
if(URL.charAt(5) == ":")
{
p = Protocols.HTTPS;
}
break;
}
default:
{
_protocol = Protocols.none;
}
}
}
/*TODO:
if _url is not found (if someone forgot to add the tracker to the display list)
we could use the alternative to get the dom.location and find the protocol from that string
off course only if we have access to ExternalInterface
*/
var _proto:String = _dom.protocol;
var proto:String = (p.toString()+":").toLowerCase();
if( _proto && _proto != proto && _debug )
{
_debug.warning( "Protocol mismatch: SWF="+proto+", DOM="+_proto );
}
_protocol = p;
}
/**
* Indicates the name of the application.
*/
public function get appName():String
{
return _appName;
}
/**
* @private
*/
public function set appName( value:String ):void
{
_appName = value;
_defineUserAgent();
}
/**
* Indicates the version of the application.
*/
public function get appVersion():Version
{
return _appVersion;
}
/**
* @private
*/
public function set appVersion( value:Version ):void
{
_appVersion = value;
_defineUserAgent();
}
/**
* Sets the stage reference value of the application.
*/
ga_internal function set url( value:String ):void
{
_url = value;
}
/**
* Indicates the location of swf.
*/
public function get locationSWFPath():String
{
return _url;
}
/**
* Indicates the referrer value.
*/
public function get referrer():String
{
var _referrer:String = _dom.referrer;
if( _referrer )
{
return _referrer;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates the title of the document.
*/
public function get documentTitle():String
{
var _title:String = _dom.title;
if( _title )
{
return _title;
}
return "";
}
/**
* Indicates the local domain name value.
*/
public function get domainName():String
{
if( protocol == Protocols.HTTP ||
protocol == Protocols.HTTPS )
{
var URL:String = _url.toLowerCase();
var str:String;
var end:int;
if( protocol == Protocols.HTTP )
{
str = URL.split( "http://" ).join( "" );
}
else if( protocol == Protocols.HTTPS )
{
str = URL.split( "https://" ).join( "" );
}
end = str.indexOf( "/" );
if( end > -1 )
{
str = str.substring(0,end);
}
return str;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates if the application is running in AIR.
*/
public function isAIR():Boolean
{
//return (playerType == "Desktop") && (Security.sandboxType.toString() == "application");
return Security.sandboxType == "application";
}
/**
* Indicates if the SWF is embeded in an HTML page.
* @return <code class="prettyprint">true</code> if the SWF is embeded in an HTML page.
*/
public function isInHTML():Boolean
{
return Capabilities.playerType == "PlugIn" ;
}
/**
* Indicates the locationPath value.
*/
public function get locationPath():String
{
var _pathname:String = _dom.pathname;
if( _pathname )
{
return _pathname;
}
return "";
}
/**
* Indicates the locationSearch value.
*/
public function get locationSearch():String
{
var _search:String = _dom.search;
if( _search )
{
return _search;
}
return "";
}
/**
* Returns the flash version object representation of the application.
* <p>This object contains the attributes major, minor, build and revision :</p>
* <p><b>Example :</b></b>
* <pre class="prettyprint">
* import com.google.analytics.utils.Environment ;
*
* var info:Environment = new Environment( "http://www.domain.com" ) ;
* var version:Object = info.flashVersion ;
*
* trace( version.major ) ; // 9
* trace( version.minor ) ; // 0
* trace( version.build ) ; // 124
* trace( version.revision ) ; // 0
* </pre>
* @return the flash version object representation of the application.
*/
public function get flashVersion():Version
{
var v:Version = Version.fromString( Capabilities.version.split( " " )[1], "," ) ;
return v ;
}
/**
* Returns the language string as a lowercase two-letter language code from ISO 639-1.
* @see Capabilities.language
*/
public function get language():String
{
var _lang:String = _dom.language;
var lang:String = Capabilities.language;
if( _lang )
{
if( (_lang.length > lang.length) &&
(_lang.substr(0,lang.length) == lang) )
{
lang = _lang;
}
}
return lang;
}
/**
* Returns the internal character set used by the flash player
* <p>Logic : by default flash player use unicode internally so we return UTF-8.</p>
* <p>If the player use the system code page then we try to return the char set of the browser.</p>
* @return the internal character set used by the flash player
*/
public function get languageEncoding():String
{
if( System.useCodePage )
{
var _charset:String = _dom.characterSet;
if( _charset )
{
return _charset;
}
return "-"; //not found
}
//default
return "UTF-8" ;
}
/**
* Returns the operating system string.
* <p><b>Note:</b> The flash documentation indicate those strings</p>
* <li>"Windows XP"</li>
* <li>"Windows 2000"</li>
* <li>"Windows NT"</li>
* <li>"Windows 98/ME"</li>
* <li>"Windows 95"</li>
* <li>"Windows CE" (available only in Flash Player SDK, not in the desktop version)</li>
* <li>"Linux"</li>
* <li>"MacOS"</li>
* <p>Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")</p>
* @return the operating system string.
* @see Capabilities.os
*/
public function get operatingSystem():String
{
return Capabilities.os ;
}
/**
* Returns the player type.
* <p><b>Note :</b> The flash documentation indicate those strings.</p>
* <li><b>"ActiveX"</b> : for the Flash Player ActiveX control used by Microsoft Internet Explorer.</li>
* <li><b>"Desktop"</b> : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").</li>
* <li><b>"External"</b> : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).</li>
* <li><b>"StandAlone"</b> : for the stand-alone Flash Player.</li>
* @return the player type.
* @see Capabilities.playerType
*/
public function get playerType():String
{
return Capabilities.playerType;
}
/**
* Returns the platform, can be "Windows", "Macintosh" or "Linux"
* @see Capabilities.manufacturer
*/
public function get platform():String
{
var p:String = Capabilities.manufacturer;
return p.split( "Adobe " )[1];
}
/**
* Indicates the Protocols object of this local info.
*/
public function get protocol():Protocols
{
if(!_protocol)
{
_findProtocol();
}
return _protocol;
}
/**
* Indicates the height of the screen.
* @see Capabilities.screenResolutionY
*/
public function get screenHeight():Number
{
return Capabilities.screenResolutionY;
}
/**
* Indicates the width of the screen.
* @see Capabilities.screenResolutionX
*/
public function get screenWidth():Number
{
return Capabilities.screenResolutionX;
}
/**
* In AIR we can use flash.display.Screen to directly get the colorDepth property
* in flash player we can only access screenColor in flash.system.Capabilities.
* <p>Some ref : <a href="http://en.wikipedia.org/wiki/Color_depth">http://en.wikipedia.org/wiki/Color_depth</a></p>
* <li>"color" -> 16-bit or 24-bit or 32-bit</li>
* <li>"gray" -> 2-bit</li>
* <li>"bw" -> 1-bit</li>
*/
public function get screenColorDepth():String
{
var color:String;
switch( Capabilities.screenColor )
{
case "bw":
{
color = "1";
break;
}
case "gray":
{
color = "2";
break;
}
/* note:
as we have no way to know if
we are in 16-bit, 24-bit or 32-bit
we gives 24-bit by default
*/
case "color" :
default :
{
color = "24" ;
}
}
var _colorDepth:String = _dom.colorDepth;
if( _colorDepth )
{
color = _colorDepth;
}
return color;
}
private function _defineUserAgent():void
{
_userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
}
/**
* Defines a custom user agent.
* <p>For case where the user would want to define its own application name and version
* it is possible to change appName and appVersion which are in sync with
* applicationProduct and applicationVersion properties.</p>
*/
public function get userAgent():String
{
if( !_userAgent )
{
_defineUserAgent();
}
return _userAgent;
}
/**
* @private
*/
public function set userAgent( custom:String ):void
{
_userAgent = custom;
}
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* 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.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.utils
{
import core.strings.userAgent;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.external.HTMLDOM;
import flash.system.Capabilities;
import flash.system.Security;
import flash.system.System;
/**
* Environment provides informations for the local environment.
*/
public class Environment
{
private var _debug:DebugConfiguration;
private var _dom:HTMLDOM;
private var _protocol:Protocols;
private var _appName:String;
private var _appVersion:Version;
private var _userAgent:String;
private var _url:String;
/**
* Creates a new Environment instance.
* @param url The URL of the SWF.
* @param app The application name
* @param version The application version
* @param dom the HTMLDOM reference.
*/
public function Environment( url:String = "", app:String = "", version:String = "",
debug:DebugConfiguration = null, dom:HTMLDOM = null )
{
var v:Version;
if( app == "" )
{
if( isAIR() )
{
app = "AIR";
}
else
{
app = "Flash";
}
}
if( version == "" )
{
v = flashVersion;
}
else
{
v = Version.fromString( version );
}
_url = url;
_appName = app;
_appVersion = v;
_debug = debug;
_dom = dom;
}
/**
* @private
*/
private function _findProtocol():void
{
var p:Protocols = Protocols.none;
if(_url != "")
{
// file://
// http://
// https://
var URL:String = _url.toLowerCase();
var test:String = URL.substr(0,5);
switch( test )
{
case "file:":
{
p = Protocols.file;
break;
}
case "http:":
{
p = Protocols.HTTP;
break;
}
case "https":
{
if(URL.charAt(5) == ":")
{
p = Protocols.HTTPS;
}
break;
}
default:
{
_protocol = Protocols.none;
}
}
}
/*TODO:
if _url is not found (if someone forgot to add the tracker to the display list)
we could use the alternative to get the dom.location and find the protocol from that string
off course only if we have access to ExternalInterface
*/
var _proto:String = _dom.protocol;
var proto:String = (p.toString()+":").toLowerCase();
if( _proto && _proto != proto && _debug )
{
_debug.warning( "Protocol mismatch: SWF="+proto+", DOM="+_proto );
}
_protocol = p;
}
/**
* Indicates the name of the application.
*/
public function get appName():String
{
return _appName;
}
/**
* @private
*/
public function set appName( value:String ):void
{
_appName = value;
_defineUserAgent();
}
/**
* Indicates the version of the application.
*/
public function get appVersion():Version
{
return _appVersion;
}
/**
* @private
*/
public function set appVersion( value:Version ):void
{
_appVersion = value;
_defineUserAgent();
}
/**
* Sets the stage reference value of the application.
*/
ga_internal function set url( value:String ):void
{
_url = value;
}
/**
* Indicates the location of swf.
*/
public function get locationSWFPath():String
{
return _url;
}
/**
* Indicates the referrer value.
*/
public function get referrer():String
{
var _referrer:String = _dom.referrer;
if( _referrer )
{
return _referrer;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates the title of the document.
*/
public function get documentTitle():String
{
var _title:String = _dom.title;
if( _title )
{
return _title;
}
return "";
}
/**
* Indicates the local domain name value.
*/
public function get domainName():String
{
if( protocol == Protocols.HTTP ||
protocol == Protocols.HTTPS )
{
var URL:String = _url.toLowerCase();
var str:String;
var end:int;
if( protocol == Protocols.HTTP )
{
str = URL.split( "http://" ).join( "" );
}
else if( protocol == Protocols.HTTPS )
{
str = URL.split( "https://" ).join( "" );
}
end = str.indexOf( "/" );
if( end > -1 )
{
str = str.substring(0,end);
}
return str;
}
if( protocol == Protocols.file )
{
return "localhost";
}
return "";
}
/**
* Indicates if the application is running in AIR.
*/
public function isAIR():Boolean
{
//return (playerType == "Desktop") && (Security.sandboxType.toString() == "application");
return Security.sandboxType == "application";
}
/**
* Indicates if the SWF is embeded in an HTML page.
* @return <code class="prettyprint">true</code> if the SWF is embeded in an HTML page.
*/
public function isInHTML():Boolean
{
return Capabilities.playerType == "PlugIn" ;
}
/**
* Indicates the locationPath value.
*/
public function get locationPath():String
{
var _pathname:String = _dom.pathname;
if( _pathname )
{
return _pathname;
}
return "";
}
/**
* Indicates the locationSearch value.
*/
public function get locationSearch():String
{
var _search:String = _dom.search;
if( _search )
{
return _search;
}
return "";
}
/**
* Returns the flash version object representation of the application.
* <p>This object contains the attributes major, minor, build and revision :</p>
* <p><b>Example :</b></p>
* <pre class="prettyprint">
* import com.google.analytics.utils.Environment ;
*
* var info:Environment = new Environment( "http://www.domain.com" ) ;
* var version:Object = info.flashVersion ;
*
* trace( version.major ) ; // 9
* trace( version.minor ) ; // 0
* trace( version.build ) ; // 124
* trace( version.revision ) ; // 0
* </pre>
* @return the flash version object representation of the application.
*/
public function get flashVersion():Version
{
var v:Version = Version.fromString( Capabilities.version.split( " " )[1], "," ) ;
return v ;
}
/**
* Returns the language string as a lowercase two-letter language code from ISO 639-1.
* @see Capabilities.language
*/
public function get language():String
{
var _lang:String = _dom.language;
var lang:String = Capabilities.language;
if( _lang )
{
if( (_lang.length > lang.length) &&
(_lang.substr(0,lang.length) == lang) )
{
lang = _lang;
}
}
return lang;
}
/**
* Returns the internal character set used by the flash player
* <p>Logic : by default flash player use unicode internally so we return UTF-8.</p>
* <p>If the player use the system code page then we try to return the char set of the browser.</p>
* @return the internal character set used by the flash player
*/
public function get languageEncoding():String
{
if( System.useCodePage )
{
var _charset:String = _dom.characterSet;
if( _charset )
{
return _charset;
}
return "-"; //not found
}
//default
return "UTF-8" ;
}
/**
* Returns the operating system string.
* <p><b>Note:</b> The flash documentation indicate those strings</p>
* <li>"Windows XP"</li>
* <li>"Windows 2000"</li>
* <li>"Windows NT"</li>
* <li>"Windows 98/ME"</li>
* <li>"Windows 95"</li>
* <li>"Windows CE" (available only in Flash Player SDK, not in the desktop version)</li>
* <li>"Linux"</li>
* <li>"MacOS"</li>
* <p>Other strings we can obtain ( not documented : "Mac OS 10.5.4" , "Windows Vista")</p>
* @return the operating system string.
* @see Capabilities.os
*/
public function get operatingSystem():String
{
return Capabilities.os ;
}
/**
* Returns the player type.
* <p><b>Note :</b> The flash documentation indicate those strings.</p>
* <li><b>"ActiveX"</b> : for the Flash Player ActiveX control used by Microsoft Internet Explorer.</li>
* <li><b>"Desktop"</b> : for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which has Capabilities.playerType set to "PlugIn").</li>
* <li><b>"External"</b> : for the external Flash Player "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by an HTML page in an AIR application).</li>
* <li><b>"StandAlone"</b> : for the stand-alone Flash Player.</li>
* @return the player type.
* @see Capabilities.playerType
*/
public function get playerType():String
{
return Capabilities.playerType;
}
/**
* Returns the platform, can be "Windows", "Macintosh" or "Linux"
* @see Capabilities.manufacturer
*/
public function get platform():String
{
var p:String = Capabilities.manufacturer;
return p.split( "Adobe " )[1];
}
/**
* Indicates the Protocols object of this local info.
*/
public function get protocol():Protocols
{
if(!_protocol)
{
_findProtocol();
}
return _protocol;
}
/**
* Indicates the height of the screen.
* @see Capabilities.screenResolutionY
*/
public function get screenHeight():Number
{
return Capabilities.screenResolutionY;
}
/**
* Indicates the width of the screen.
* @see Capabilities.screenResolutionX
*/
public function get screenWidth():Number
{
return Capabilities.screenResolutionX;
}
/**
* In AIR we can use flash.display.Screen to directly get the colorDepth property
* in flash player we can only access screenColor in flash.system.Capabilities.
* <p>Some ref : <a href="http://en.wikipedia.org/wiki/Color_depth">http://en.wikipedia.org/wiki/Color_depth</a></p>
* <li>"color" -> 16-bit or 24-bit or 32-bit</li>
* <li>"gray" -> 2-bit</li>
* <li>"bw" -> 1-bit</li>
*/
public function get screenColorDepth():String
{
var color:String;
switch( Capabilities.screenColor )
{
case "bw":
{
color = "1";
break;
}
case "gray":
{
color = "2";
break;
}
/* note:
as we have no way to know if
we are in 16-bit, 24-bit or 32-bit
we gives 24-bit by default
*/
case "color" :
default :
{
color = "24" ;
}
}
var _colorDepth:String = _dom.colorDepth;
if( _colorDepth )
{
color = _colorDepth;
}
return color;
}
private function _defineUserAgent():void
{
_userAgent = core.strings.userAgent( appName + "/" + appVersion.toString(4) );
}
/**
* Defines a custom user agent.
* <p>For case where the user would want to define its own application name and version
* it is possible to change appName and appVersion which are in sync with
* applicationProduct and applicationVersion properties.</p>
*/
public function get userAgent():String
{
if( !_userAgent )
{
_defineUserAgent();
}
return _userAgent;
}
/**
* @private
*/
public function set userAgent( custom:String ):void
{
_userAgent = custom;
}
}
}
|
fix comment for asdoc
|
fix comment for asdoc
|
ActionScript
|
apache-2.0
|
minimedj/gaforflash,nsdevaraj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash
|
28e6d188ff8539eca58d61110c1fa960736f949c
|
src/aerys/minko/scene/controller/ScriptController.as
|
src/aerys/minko/scene/controller/ScriptController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import flash.display.BitmapData;
public class ScriptController extends EnterFrameController
{
private var _lastTime : Number;
private var _deltaTime : Number;
private var _currentTarget : ISceneNode;
private var _viewport : Viewport;
private var _scene : Scene;
protected function get deltaTime() : Number
{
return _deltaTime;
}
protected function get keyboard() : KeyboardManager
{
return _viewport.keyboardManager;
}
protected function get mouse() : MouseManager
{
return _viewport.mouseManager;
}
protected function get viewport() : Viewport
{
return _viewport;
}
protected function get scene() : Scene
{
return _scene;
}
public function ScriptController(targetType : Class = null)
{
super(targetType);
initialize();
}
private function initialize() : void
{
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
start(getTarget(i));
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = _lastTime - time;
_lastTime = time;
_scene = scene;
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
update(getTarget(i));
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetRemovedFromSceneHandler(target, scene);
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
stop(getTarget(i));
}
protected function start(target : ISceneNode) : void
{
// nothing
}
protected function update(target : ISceneNode) : void
{
// nothing
}
protected function stop(target : ISceneNode) : void
{
// nothing
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import flash.display.BitmapData;
public class ScriptController extends EnterFrameController
{
private var _lastTime : Number;
private var _deltaTime : Number;
private var _currentTarget : ISceneNode;
private var _viewport : Viewport;
protected function get deltaTime() : Number
{
return _deltaTime;
}
protected function get keyboard() : KeyboardManager
{
return _viewport.keyboardManager;
}
protected function get mouse() : MouseManager
{
return _viewport.mouseManager;
}
protected function get viewport() : Viewport
{
return _viewport;
}
public function ScriptController(targetType : Class = null)
{
super(targetType);
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
initialize(getTarget(i));
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
_viewport = viewport;
_deltaTime = _lastTime - time;
_lastTime = time;
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
{
var target : ISceneNode = getTarget(i);
if (target.scene)
update(target);
}
}
override protected function targetAddedToSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetAddedToSceneHandler(target, scene);
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
start(getTarget(i));
}
override protected function targetRemovedFromSceneHandler(target : ISceneNode,
scene : Scene) : void
{
super.targetRemovedFromSceneHandler(target, scene);
var numTargets : uint = this.numTargets;
for (var i : uint = 0; i < numTargets; ++i)
stop(getTarget(i));
}
protected function initialize(target : ISceneNode) : void
{
// nothing
}
protected function start(target : ISceneNode) : void
{
// nothing
}
protected function update(target : ISceneNode) : void
{
// nothing
}
protected function stop(target : ISceneNode) : void
{
// nothing
}
}
}
|
add ScriptController.initialize() fix ScriptController.start() that was never actually called
|
add ScriptController.initialize()
fix ScriptController.start() that was never actually called
|
ActionScript
|
mit
|
aerys/minko-as3
|
f11f8663e161cae63fcf4dce8404a73367f994af
|
src/as/com/threerings/ezgame/client/GameContainer.as
|
src/as/com/threerings/ezgame/client/GameContainer.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import mx.core.mx_internal;
import mx.core.IFlexDisplayObject;
import mx.core.IInvalidating;
import mx.containers.VBox;
import mx.managers.IFocusManagerComponent;
import mx.skins.ProgrammaticSkin;
import com.threerings.flash.MediaContainer;
// TODO: there are focus issues in here that need dealing with.
//
// 1) The focus rectangle is drawn at the wrong size in scrolling games
// 2) We can get focus without having the pink focus rectangle...
// 3) When the mouse leaves the flash player and returns, this
// damn thing doesn't seem to grip onto the focus.
//
public class GameContainer extends VBox
implements IFocusManagerComponent
{
public function GameContainer (url :String)
{
rawChildren.addChild(_game = new MediaContainer(url));
tabEnabled = true; // turned off by Container
// focusRect = true; // we need the focus rect
}
public function getMediaContainer () :MediaContainer
{
return _game;
}
// override public function setFocus () :void
// {
// if (stage) {
// try {
// stage.focus = this;
// } catch (e :Error) {
// trace("Apparently, this might happen: " + e)
// }
// }
// }
override protected function adjustFocusRect (obj :DisplayObject = null) :void
{
super.adjustFocusRect(obj);
// TODO: this is probably all wrong
var focusObj :IFlexDisplayObject =
IFlexDisplayObject(mx_internal::getFocusObject());
if (focusObj) {
var r :Rectangle = transform.pixelBounds;
focusObj.setActualSize(r.width - 2, r.height - 2);
focusObj.move(0, 0);
if (focusObj is IInvalidating) {
IInvalidating(focusObj).validateNow();
} else if (focusObj is ProgrammaticSkin) {
ProgrammaticSkin(focusObj).validateNow();
}
}
}
protected var _game :MediaContainer;
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import flash.text.TextField;
import mx.core.mx_internal;
import mx.core.IFlexDisplayObject;
import mx.core.IInvalidating;
import mx.containers.VBox;
import com.threerings.flash.MediaContainer;
// TODO: there are focus issues in here that need dealing with.
//
// 1) The focus rectangle is drawn at the wrong size in scrolling games
// 2) We can get focus without having the pink focus rectangle...
// 3) When the mouse leaves the flash player and returns, this
// damn thing doesn't seem to grip onto the focus.
//
public class GameContainer extends VBox
{
public function GameContainer (url :String)
{
rawChildren.addChild(_keyGrabber = new TextField());
_keyGrabber.selectable = false;
rawChildren.addChild(_game = new MediaContainer(url));
tabEnabled = true; // turned off by Container
// focusRect = true; // we need the focus rect
}
public function getMediaContainer () :MediaContainer
{
return _game;
}
override public function setActualSize (w :Number, h :Number) :void
{
super.setActualSize(w, h);
_keyGrabber.width = w;
_keyGrabber.height = h;
}
// override public function setFocus () :void
// {
// if (stage) {
// try {
// stage.focus = this;
// } catch (e :Error) {
// trace("Apparently, this might happen: " + e)
// }
// }
// }
// override protected function adjustFocusRect (obj :DisplayObject = null) :void
// {
// super.adjustFocusRect(obj);
//
// // TODO: this is probably all wrong
// var focusObj :IFlexDisplayObject =
// IFlexDisplayObject(mx_internal::getFocusObject());
// if (focusObj) {
// var r :Rectangle = transform.pixelBounds;
// focusObj.setActualSize(r.width - 2, r.height - 2);
// focusObj.move(0, 0);
//
// if (focusObj is IInvalidating) {
// IInvalidating(focusObj).validateNow();
//
// } else if (focusObj is ProgrammaticSkin) {
// ProgrammaticSkin(focusObj).validateNow();
// }
// }
// }
protected var _game :MediaContainer;
protected var _keyGrabber :TextField;
}
}
|
Use the TextField hack ourselves. - Flash seems to sketch out when key events go elsewhere - Whirled now does the handy thing of re-routing 'word' keypresses to the ChatControl, unless a TextField has focus. We want to automatically let games get any and all keypresses... - The damn focus stuff is broken anyway
|
Use the TextField hack ourselves.
- Flash seems to sketch out when key events go elsewhere
- Whirled now does the handy thing of re-routing 'word' keypresses
to the ChatControl, unless a TextField has focus. We want to automatically
let games get any and all keypresses...
- The damn focus stuff is broken anyway
Untested, Nathan will test.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@231 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
dfe12a263ecd832db6fdf6dfd0df315e98fff89f
|
krew-framework/krewfw/utils/as3/KrewSoundPlayer.as
|
krew-framework/krewfw/utils/as3/KrewSoundPlayer.as
|
package krewfw.utils.as3 {
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
import flash.utils.getDefinitionByName;
import krewfw.KrewConfig;
import krewfw.utils.krew;
public class KrewSoundPlayer {
private var _bgmChannel:SoundChannel;
private var _seChannel :SoundChannel;
private var _soundTransform:SoundTransform;
private var _bgmVolume:Number = 1.0; // master volume for BGM
private var _seVolume:Number = 1.0; // master volume for SE
private var _currentBgmId:String;
private var _currentBgm:Sound;
private var _pausePosition:int = 0;
/**
* BGM と SE の再生ユーティリティー。
* ToDo: 現状は非常にシンプルなもの。BGM は全てループ再生
* ToDO: 同じ SE 鳴らし過ぎちゃわない対応
*/
//------------------------------------------------------------
public function KrewSoundPlayer() {
_soundTransform = new SoundTransform();
_followDeviceMuteButton();
}
//------------------------------------------------------------
// accessors
//------------------------------------------------------------
public function get bgmVolume():Number { return _bgmVolume; }
public function set bgmVolume(vol:Number):void {
_bgmVolume = vol;
_bgmVolume = krew.within(_bgmVolume, 0, 1);
}
public function get seVolume():Number { return _seVolume; }
public function set seVolume(vol:Number):void {
_seVolume = vol;
_seVolume = krew.within(_seVolume, 0, 1);
}
//------------------------------------------------------------
// interfaces for BGM
//------------------------------------------------------------
/**
* 渡した Sound を BGM として再生。
* 前回渡した bgmId と同じものをすでに再生中の場合は、再生し直しを行わない。
* bgmId に null を渡した場合は常に再生し直す
*/
public function playBgm(sound:Sound, bgmId:String=null, vol:Number=NaN, startTime:Number=0):void
{
if (_bgmChannel) {
if (bgmId != null && bgmId == _currentBgmId) { return; }
_bgmChannel.stop();
}
_currentBgmId = bgmId;
_soundTransform.volume = (!isNaN(vol)) ? vol : _bgmVolume;
var loops:int = 1;
_bgmChannel = sound.play(startTime, loops, _soundTransform);
_currentBgm = sound;
_bgmChannel.addEventListener(Event.SOUND_COMPLETE, _onBgmComplete);
}
public function replayBgm(vol:Number=NaN, startTime:Number=0):void {
if (!_currentBgm) { return; }
playBgm(_currentBgm, _currentBgmId, vol, startTime);
}
public function pauseBgm():void {
if (!_bgmChannel) { return; }
_pausePosition = _bgmChannel.position;
_bgmChannel.stop();
}
public function resumeBgm():void {
if (!_bgmChannel) { return; }
playBgm(_currentBgm, _currentBgmId, NaN, _pausePosition);
}
public function stopBgm():void {
if (_bgmChannel) {
_bgmChannel.stop();
_bgmChannel = null;
}
}
//------------------------------------------------------------
// interfaces for SE
//------------------------------------------------------------
public function playSe(sound:Sound, pan:Number=0, loops:int=0,
vol:Number=NaN, startTime:Number=0):void
{
_soundTransform.pan = pan;
_soundTransform.volume = (!isNaN(vol)) ? vol : _seVolume;
_seChannel = sound.play(startTime, loops, _soundTransform);
}
public function stopSe():void {
if (_seChannel) {
_seChannel.stop();
_seChannel = null;
}
}
//------------------------------------------------------------
// interfaces for Entire Sound
//------------------------------------------------------------
public function stopAll():void {
stopBgm();
stopSe();
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
/**
* 端末のミュートボタンに従う。IS_AIR が true にセットされていなければ何もしない。
* クラスを動的に取得しているのは Flash にこのクラスが無いため
*/
private function _followDeviceMuteButton():void {
if (!KrewConfig.IS_AIR) { return; }
var AudioPlaybackMode:Class = getDefinitionByName("flash.media.AudioPlaybackMode") as Class;
SoundMixer.audioPlaybackMode = AudioPlaybackMode.AMBIENT;
}
/**
* pause & resume してしまうと、Sound.play() の loops に 2 以上の値を入れて
* ループさせた場合に、resume した位置から再生が再開されてしまうようだ。
* ひとまず再生終了のコールバックで 0 位置から再生し直すことでループ再生する
*/
private function _onBgmComplete(event:Event):void {
replayBgm();
}
}
}
|
package krewfw.utils.as3 {
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
import flash.utils.getDefinitionByName;
import krewfw.KrewConfig;
import krewfw.utils.krew;
public class KrewSoundPlayer {
private var _bgmChannel:SoundChannel;
private var _seChannel :SoundChannel;
private var _soundTransform:SoundTransform;
private var _bgmVolume:Number = 1.0; // master volume for BGM
private var _seVolume:Number = 1.0; // master volume for SE
private var _currentBgmId:String;
private var _currentBgm:Sound;
private var _pausePosition:int = 0;
/**
* BGM と SE の再生ユーティリティー。
* ToDo: 現状は非常にシンプルなもの。BGM は全てループ再生
* ToDO: 同じ SE 鳴らし過ぎちゃわない対応
*/
//------------------------------------------------------------
public function KrewSoundPlayer() {
_soundTransform = new SoundTransform();
_followDeviceMuteButton();
}
//------------------------------------------------------------
// accessors
//------------------------------------------------------------
public function get bgmVolume():Number { return _bgmVolume; }
public function set bgmVolume(vol:Number):void {
_bgmVolume = vol;
_bgmVolume = krew.within(_bgmVolume, 0, 1);
}
public function get seVolume():Number { return _seVolume; }
public function set seVolume(vol:Number):void {
_seVolume = vol;
_seVolume = krew.within(_seVolume, 0, 1);
}
//------------------------------------------------------------
// interfaces for BGM
//------------------------------------------------------------
/**
* 渡した Sound を BGM として再生。
* 前回渡した bgmId と同じものをすでに再生中の場合は、再生し直しを行わない。
* bgmId に null を渡した場合は常に再生し直す
*/
public function playBgm(sound:Sound, bgmId:String=null, vol:Number=NaN, startTime:Number=0):void
{
if (_bgmChannel) {
if (bgmId != null && bgmId == _currentBgmId) { return; }
_bgmChannel.stop();
}
_currentBgmId = bgmId;
_soundTransform.volume = (!isNaN(vol)) ? vol : _bgmVolume;
var loops:int = 1;
_bgmChannel = sound.play(startTime, loops, _soundTransform);
_currentBgm = sound;
_bgmChannel.addEventListener(Event.SOUND_COMPLETE, _onBgmComplete);
}
public function replayBgm(vol:Number=NaN, startTime:Number=0):void {
if (!_currentBgm) { return; }
playBgm(_currentBgm, _currentBgmId, vol, startTime);
}
public function pauseBgm():void {
if (!_bgmChannel) { return; }
_pausePosition = _bgmChannel.position;
_bgmChannel.stop();
}
public function resumeBgm():void {
if (!_bgmChannel) { return; }
stopBgm();
playBgm(_currentBgm, _currentBgmId, NaN, _pausePosition);
}
public function stopBgm():void {
if (_bgmChannel) {
_bgmChannel.stop();
_bgmChannel = null;
}
}
//------------------------------------------------------------
// interfaces for SE
//------------------------------------------------------------
public function playSe(sound:Sound, pan:Number=0, loops:int=0,
vol:Number=NaN, startTime:Number=0):void
{
_soundTransform.pan = pan;
_soundTransform.volume = (!isNaN(vol)) ? vol : _seVolume;
_seChannel = sound.play(startTime, loops, _soundTransform);
}
public function stopSe():void {
if (_seChannel) {
_seChannel.stop();
_seChannel = null;
}
}
//------------------------------------------------------------
// interfaces for Entire Sound
//------------------------------------------------------------
public function stopAll():void {
stopBgm();
stopSe();
}
//------------------------------------------------------------
// private
//------------------------------------------------------------
/**
* 端末のミュートボタンに従う。IS_AIR が true にセットされていなければ何もしない。
* クラスを動的に取得しているのは Flash にこのクラスが無いため
*/
private function _followDeviceMuteButton():void {
if (!KrewConfig.IS_AIR) { return; }
var AudioPlaybackMode:Class = getDefinitionByName("flash.media.AudioPlaybackMode") as Class;
SoundMixer.audioPlaybackMode = AudioPlaybackMode.AMBIENT;
}
/**
* pause & resume してしまうと、Sound.play() の loops に 2 以上の値を入れて
* ループさせた場合に、resume した位置から再生が再開されてしまうようだ。
* ひとまず再生終了のコールバックで 0 位置から再生し直すことでループ再生する
*/
private function _onBgmComplete(event:Event):void {
replayBgm();
}
}
}
|
Modify bug of sound player
|
Modify bug of sound player
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
a44134c04cf09b37e6c4654a5a3512a48ef0426b
|
com/segonquart/menuColourIdiomes.as
|
com/segonquart/menuColourIdiomes.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuColouridiomes extends MoviieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function menuColourIdiomes ():Void
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver():Void
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
}
private function mOut():Void
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class com.segonquart.menuColouridiomes extends MoviieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function menuColourIdiomes ():Void
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver():Void
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
}
private function mOut():Void
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
|
Update menuColourIdiomes.as
|
Update menuColourIdiomes.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
4b10a54213119a7166ce417af89338281602aff9
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.Animation;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose mesh");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
}
[Inline]
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
var reader:MafReader = new MafReader();
reader.execute(bytes);
var animations:Vector.<Animation> = reader.animations;
for each(var animation:Animation in animations){
result.push(animation.name);
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
// var name:String = asset.name;
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
var animation:String = list.selectedItem.toString();
log(this, "selectAnimationHandler", animation);
Miracle.currentScene.createAnimation(_name, animation)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}
private function imageAddedToStage(event:Event):void {
var target:MiracleDisplayObject = event.target as MiracleDisplayObject;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.animations.AnimationHelper;
import com.merlinds.miracle.display.MiracleDisplayObject;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose mesh");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
}
[Inline]
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
var reader:MafReader = new MafReader();
reader.execute(bytes);
var animations:Vector.<AnimationHelper> = reader.animations;
for each(var animation:AnimationHelper in animations){
result.push(animation.name);
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
// var name:String = asset.name;
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
//add animation to miracle
var animation:String = list.selectedItem.toString();
log(this, "selectAnimationHandler", animation);
Miracle.currentScene.createAnimation(_name, animation)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}
private function imageAddedToStage(event:Event):void {
var target:MiracleDisplayObject = event.target as MiracleDisplayObject;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
Add animations to scene
|
Add animations to scene
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
977e6f75231a0051bbd9564e9fb0a41b6364032c
|
kdp3Lib/src/com/kaltura/kdpfl/view/controls/BufferAnimationMediator.as
|
kdp3Lib/src/com/kaltura/kdpfl/view/controls/BufferAnimationMediator.as
|
package com.kaltura.kdpfl.view.controls
{
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import flash.events.TimerEvent;
import flash.geom.ColorTransform;
import flash.geom.Point;
import flash.utils.Timer;
import flash.utils.getQualifiedClassName;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
/**
* Mediator for the buffer indicator animation. Controls the appearance and removal of the animation from the display list.
* @author Hila
*
*/
public class BufferAnimationMediator extends Mediator
{
public static const NAME:String = "spinnerMediator";
public static const SPINNER_CLASS : String = "kspin";
public var applicationLoadStyleName:String = '';
public var bufferingStyleName:String = '';
private var zeroPoint : Point = new Point( 0 , 0);
/**
* flag indicating whether the active media has reached its end.
*/
private var _reachedEnd:Boolean=false;
private var _currConfig : ConfigProxy;
private var _notBuffering : Boolean = true;
private var _prevStatePaused:Boolean = true;
private var _lastPlayheadPos:Number;
/**
* indicate if "bufferChange" event was sent, we started buffering
*/
private var _bufferChangeStart:Boolean = false;
/**
* Constructor.
* @param viewComponent - the component controlled by the mediator.
*
*/
public function BufferAnimationMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
_currConfig = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
}
private var d:Date;
override public function handleNotification(note:INotification):void
{
var flashvars : Object = _currConfig.vo.flashvars;
var noteName : String = note.getName();
switch(noteName)
{
case NotificationType.SKIN_LOADED:
// spinner.swapLoadingWithAnimation( applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
fadeOutSpinner();
break;
case NotificationType.LAYOUT_READY:
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.KDP_READY:
case NotificationType.READY_TO_PLAY:
var spinnerColor:Number = -1;
if(flashvars.spinnerColorAttribute && flashvars[flashvars.spinnerColorAttribute] )
{
spinnerColor = flashvars[flashvars.spinnerColorAttribute]
}
if(flashvars.spinnerColor)
{
spinnerColor = flashvars.spinnerColor;
}
if(spinnerColor> -1 )
{
var color_transform:ColorTransform= new ColorTransform;
color_transform.color= spinnerColor ;
spinner.transform.colorTransform=color_transform;
}
if(flashvars.spinnerFadeTime)
_animationTime = Number(flashvars.spinnerFadeTime) * 1000;
fadeOutSpinner();
_reachedEnd = false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.PLAYER_STATE_CHANGE:
if( note.getBody() == MediaPlayerState.BUFFERING)
{
_notBuffering = false;
if(_reachedEnd)
{
fadeOutSpinner();
}
else if (!_prevStatePaused)
{
//fix OSMF bug: sometimes "buffering" was sent after player paused, the spinner shouldn't be visible in this case
fadeInSpinner();
}
}
else
{
//only relevant if not rtmp
/* if( note.getBody() == MediaPlayerState.READY ){
spinner.visible = false;
}
if(_flashvars.streamerType != StreamerType.RTMP){
spinner.visible = false;
} */
_notBuffering = true;
if( note.getBody() == MediaPlayerState.PLAYING)
{
_reachedEnd = false;
_prevStatePaused = false;
// spinner.visible = false;
}
if(note.getBody() == MediaPlayerState.PAUSED)
{
fadeOutSpinner();
_prevStatePaused = true;
}
if( note.getBody() == MediaPlayerState.READY)
{
fadeOutSpinner();
}
}
break;
/**
* Until OSMF for seeking in rtmp is fixed (buffering-wise)
* add a new case for update playhead notification
* */
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
//if _bufferChangeStart the next bufferChange event will make the spinner invisible
if(_notBuffering && !_bufferChangeStart)
{
fadeOutSpinner();
}
//fix another OSMF bug: we are buffering even though movie plays
else if (spinner.visible)
{
var updateIntervalInSeconds:Number = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentTimeUpdateInterval / 1000;
var curPos:Number = parseFloat(Number(note.getBody()).toFixed(2));
if ((curPos - _lastPlayheadPos)<=updateIntervalInSeconds)
{
fadeOutSpinner();
}
_lastPlayheadPos = curPos;
}
break;
case NotificationType.BUFFER_CHANGE:
_bufferChangeStart = note.getBody();
if(_bufferChangeStart)
{
fadeInSpinner()
}
if(!_bufferChangeStart)
{
fadeOutSpinner();
}
break;
case NotificationType.PLAYER_PLAY_END:
_reachedEnd=true;
fadeOutSpinner();
break;
case NotificationType.KDP_EMPTY:
case NotificationType.READY_TO_LOAD:
fadeOutSpinner();
_reachedEnd=false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.CHANGE_MEDIA:
//spinner.visible = true;
break;
//in case we are trying to connect to a live stream but it is not on air yet
case NotificationType.LIVE_ENTRY:
if (flashvars.hideSpinnerOnOffline=="true")
{
fadeOutSpinner();
}
else
{
fadeInSpinner();
}
break;
//in case the live stream we are trying to connect to was found to be on air
case LiveStreamCommand.LIVE_STREAM_READY:
fadeOutSpinner();
break;
case NotificationType.PRELOADER_LOADED:
var preObj:Object = note.getBody().preloader;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && preObj)
{
//save to flashvars, we might need it in the future
_currConfig.vo.flashvars["preloader"] = preObj;
spinner.setBufferingAnimation(getQualifiedClassName(preObj));
}
break;
}
}
private var _fadeInTimer:Timer;
private var _fadeOutTimer:Timer;
private var _animationTime:Number = 0;
private function fadeOutSpinner():void
{
_bufferChangeStart = true;
if (!spinner.visible)
return;
if(_animationTime == 0)
{
spinner.visible = false;
return;
}
//trace("^^^^^^^^^ fadeOutSpinner start >>>>>>>>>>");
spinner.visible = true;
spinner.alpha = 1;
_fadeOutTimer = new Timer(_animationTime/10,10);
_fadeOutTimer.addEventListener(TimerEvent.TIMER , onFadeOutTimer);
_fadeOutTimer.addEventListener(TimerEvent.TIMER_COMPLETE , onFadeOutComplete);
_fadeOutTimer.start();
}
private function onFadeOutTimer(event:TimerEvent):void
{
spinner.alpha -=0.1;
}
private function onFadeOutComplete(event:TimerEvent):void
{
//trace("^^^^^^^^^ fadeOutSpinner END >>>>>>>>>>");
_fadeOutTimer.removeEventListener(TimerEvent.TIMER , onFadeOutTimer);
_fadeOutTimer.removeEventListener(TimerEvent.TIMER_COMPLETE , onFadeOutComplete);
spinner.visible = false;
}
private function fadeInSpinner():void
{
if (spinner.visible)
return;
if(_animationTime == 0)
{
spinner.visible = true;
return;
}
spinner.alpha = 0;
spinner.visible = true;
_fadeInTimer = new Timer(_animationTime/10,10);
_fadeInTimer.addEventListener(TimerEvent.TIMER , onFadeInTimer);
_fadeInTimer.addEventListener(TimerEvent.TIMER_COMPLETE , onFadeInComplete);
_fadeInTimer.start();
}
private function onFadeInTimer(event:TimerEvent):void
{
spinner.alpha +=0.1;
}
private function onFadeInComplete(event:TimerEvent):void
{
_fadeInTimer.removeEventListener(TimerEvent.TIMER , onFadeInTimer);
_fadeInTimer.removeEventListener(TimerEvent.TIMER_COMPLETE , onFadeInComplete);
}
override public function listNotificationInterests():Array
{
return [
NotificationType.SKIN_LOADED,
NotificationType.PLAYER_STATE_CHANGE,
NotificationType.PLAYER_PLAYED,
NotificationType.PLAYER_UPDATE_PLAYHEAD, //TODO: REMOVE THIS WHEN I FIND A BETTER WORK AROUND TO THE BUG
NotificationType.ENTRY_FAILED,
NotificationType.CHANGE_MEDIA,
NotificationType.PLAYER_PLAY_END,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.LAYOUT_READY,
NotificationType.LIVE_ENTRY,
LiveStreamCommand.LIVE_STREAM_READY,
NotificationType.READY_TO_PLAY,
NotificationType.READY_TO_LOAD,
NotificationType.ROOT_RESIZE,
NotificationType.BUFFER_CHANGE,
NotificationType.PRELOADER_LOADED
];
}
/**
* the buffer indicator animation controlled by the mediator.
* @return
*
*/
public function get spinner():BufferAnimation
{
return viewComponent as BufferAnimation;
}
}
}
|
package com.kaltura.kdpfl.view.controls
{
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import flash.events.TimerEvent;
import flash.geom.ColorTransform;
import flash.geom.Point;
import flash.utils.Timer;
import flash.utils.getQualifiedClassName;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
/**
* Mediator for the buffer indicator animation. Controls the appearance and removal of the animation from the display list.
* @author Hila
*
*/
public class BufferAnimationMediator extends Mediator
{
public static const NAME:String = "spinnerMediator";
public static const SPINNER_CLASS : String = "kspin";
public var applicationLoadStyleName:String = '';
public var bufferingStyleName:String = '';
private var zeroPoint : Point = new Point( 0 , 0);
/**
* flag indicating whether the active media has reached its end.
*/
private var _reachedEnd:Boolean=false;
private var _currConfig : ConfigProxy;
private var _notBuffering : Boolean = true;
private var _prevStatePaused:Boolean = true;
private var _lastPlayheadPos:Number;
/**
* indicate if "bufferChange" event was sent, we started buffering
*/
private var _bufferChangeStart:Boolean = false;
/**
* Constructor.
* @param viewComponent - the component controlled by the mediator.
*
*/
public function BufferAnimationMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
_currConfig = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
}
private var d:Date;
override public function handleNotification(note:INotification):void
{
var flashvars : Object = _currConfig.vo.flashvars;
var noteName : String = note.getName();
switch(noteName)
{
case NotificationType.SKIN_LOADED:
// spinner.swapLoadingWithAnimation( applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
fadeOutSpinner();
break;
case NotificationType.LAYOUT_READY:
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.KDP_READY:
case NotificationType.READY_TO_PLAY:
var spinnerColor:Number = -1;
if(flashvars.spinnerColorAttribute && flashvars[flashvars.spinnerColorAttribute] )
{
spinnerColor = flashvars[flashvars.spinnerColorAttribute]
}
if(flashvars.spinnerColor)
{
spinnerColor = flashvars.spinnerColor;
}
if(spinnerColor> -1 )
{
var color_transform:ColorTransform= new ColorTransform;
color_transform.color= spinnerColor ;
spinner.transform.colorTransform=color_transform;
}
if(flashvars.spinnerFadeTime)
_animationTime = Number(flashvars.spinnerFadeTime) * 1000;
fadeOutSpinner();
_reachedEnd = false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.PLAYER_STATE_CHANGE:
if( note.getBody() == MediaPlayerState.BUFFERING)
{
_notBuffering = false;
if(_reachedEnd)
{
fadeOutSpinner();
}
else if (!_prevStatePaused)
{
//fix OSMF bug: sometimes "buffering" was sent after player paused, the spinner shouldn't be visible in this case
fadeInSpinner();
}
}
else
{
//only relevant if not rtmp
/* if( note.getBody() == MediaPlayerState.READY ){
spinner.visible = false;
}
if(_flashvars.streamerType != StreamerType.RTMP){
spinner.visible = false;
} */
_notBuffering = true;
if( note.getBody() == MediaPlayerState.PLAYING)
{
_reachedEnd = false;
_prevStatePaused = false;
// spinner.visible = false;
}
if(note.getBody() == MediaPlayerState.PAUSED)
{
fadeOutSpinner();
_prevStatePaused = true;
}
if( note.getBody() == MediaPlayerState.READY)
{
fadeOutSpinner();
}
}
break;
/**
* Until OSMF for seeking in rtmp is fixed (buffering-wise)
* add a new case for update playhead notification
* */
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
//if _bufferChangeStart the next bufferChange event will make the spinner invisible
if(_notBuffering && !_bufferChangeStart)
{
fadeOutSpinner();
}
//fix another OSMF bug: we are buffering even though movie plays
else if (spinner.visible)
{
var updateIntervalInSeconds:Number = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentTimeUpdateInterval / 1000;
var curPos:Number = parseFloat(Number(note.getBody()).toFixed(2));
if ((curPos - _lastPlayheadPos)<=updateIntervalInSeconds)
{
fadeOutSpinner();
}
_lastPlayheadPos = curPos;
}
break;
case NotificationType.BUFFER_CHANGE:
_bufferChangeStart = note.getBody();
if(_bufferChangeStart)
{
fadeInSpinner()
}
if(!_bufferChangeStart)
{
fadeOutSpinner();
}
break;
case NotificationType.PLAYER_PLAY_END:
_reachedEnd=true;
fadeOutSpinner();
break;
case NotificationType.KDP_EMPTY:
case NotificationType.READY_TO_LOAD:
fadeOutSpinner();
_reachedEnd=false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.CHANGE_MEDIA:
//spinner.visible = true;
break;
//in case we are trying to connect to a live stream but it is not on air yet
case NotificationType.LIVE_ENTRY:
if (flashvars.hideSpinnerOnOffline=="true")
{
fadeOutSpinner();
}
else
{
fadeInSpinner();
}
break;
//in case the live stream we are trying to connect to was found to be on air
case LiveStreamCommand.LIVE_STREAM_READY:
fadeOutSpinner();
break;
case NotificationType.PRELOADER_LOADED:
var preObj:Object = note.getBody().preloader;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && preObj)
{
//save to flashvars, we might need it in the future
_currConfig.vo.flashvars["preloader"] = preObj;
spinner.setBufferingAnimation(getQualifiedClassName(preObj));
}
break;
}
}
private var _fadeInTimer:Timer;
private var _fadeOutTimer:Timer;
private var _animationTime:Number = 0;
private function fadeOutSpinner():void
{
if (!spinner.visible)
return;
if(_animationTime == 0)
{
spinner.visible = false;
return;
}
//trace("^^^^^^^^^ fadeOutSpinner start >>>>>>>>>>");
spinner.visible = true;
spinner.alpha = 1;
_fadeOutTimer = new Timer(_animationTime/10,10);
_fadeOutTimer.addEventListener(TimerEvent.TIMER , onFadeOutTimer);
_fadeOutTimer.addEventListener(TimerEvent.TIMER_COMPLETE , onFadeOutComplete);
_fadeOutTimer.start();
}
private function onFadeOutTimer(event:TimerEvent):void
{
spinner.alpha -=0.1;
}
private function onFadeOutComplete(event:TimerEvent):void
{
//trace("^^^^^^^^^ fadeOutSpinner END >>>>>>>>>>");
_fadeOutTimer.removeEventListener(TimerEvent.TIMER , onFadeOutTimer);
_fadeOutTimer.removeEventListener(TimerEvent.TIMER_COMPLETE , onFadeOutComplete);
spinner.visible = false;
}
private function fadeInSpinner():void
{
if (spinner.visible)
return;
if(_animationTime == 0)
{
spinner.visible = true;
return;
}
spinner.alpha = 0;
spinner.visible = true;
_fadeInTimer = new Timer(_animationTime/10,10);
_fadeInTimer.addEventListener(TimerEvent.TIMER , onFadeInTimer);
_fadeInTimer.addEventListener(TimerEvent.TIMER_COMPLETE , onFadeInComplete);
_fadeInTimer.start();
}
private function onFadeInTimer(event:TimerEvent):void
{
spinner.alpha +=0.1;
}
private function onFadeInComplete(event:TimerEvent):void
{
_fadeInTimer.removeEventListener(TimerEvent.TIMER , onFadeInTimer);
_fadeInTimer.removeEventListener(TimerEvent.TIMER_COMPLETE , onFadeInComplete);
}
override public function listNotificationInterests():Array
{
return [
NotificationType.SKIN_LOADED,
NotificationType.PLAYER_STATE_CHANGE,
NotificationType.PLAYER_PLAYED,
NotificationType.PLAYER_UPDATE_PLAYHEAD, //TODO: REMOVE THIS WHEN I FIND A BETTER WORK AROUND TO THE BUG
NotificationType.ENTRY_FAILED,
NotificationType.CHANGE_MEDIA,
NotificationType.PLAYER_PLAY_END,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.LAYOUT_READY,
NotificationType.LIVE_ENTRY,
LiveStreamCommand.LIVE_STREAM_READY,
NotificationType.READY_TO_PLAY,
NotificationType.READY_TO_LOAD,
NotificationType.ROOT_RESIZE,
NotificationType.BUFFER_CHANGE,
NotificationType.PRELOADER_LOADED
];
}
/**
* the buffer indicator animation controlled by the mediator.
* @return
*
*/
public function get spinner():BufferAnimation
{
return viewComponent as BufferAnimation;
}
}
}
|
fix buffer animtation
|
fix buffer animtation
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
4efdd81d979cf5ac8206bd4302f2c0a2eb47e203
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/layouts/NonVirtualVerticalScrollingLayout.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/layouts/NonVirtualVerticalScrollingLayout.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads.layouts
{
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBorderModel;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IScrollBarModel;
import org.apache.flex.core.IScrollingLayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ScrollBar;
/**
* The NonVirtualVerticalScrollingLayout class is a layout
* bead that displays a set of children vertically in one row,
* separating them according to CSS layout rules for margin and
* vertical-align styles and lays out a vertical ScrollBar
* to the right of the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NonVirtualVerticalScrollingLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NonVirtualVerticalScrollingLayout()
{
}
private var vScrollBar:ScrollBar;
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("heightChanged", changeHandler);
IEventDispatcher(value).addEventListener("widthChanged", changeHandler);
IEventDispatcher(value).addEventListener("itemsCreated", changeHandler);
}
private function changeHandler(event:Event):void
{
var layoutParent:IScrollingLayoutParent =
_strand.getBeadByType(IScrollingLayoutParent) as IScrollingLayoutParent;
var contentView:IParentIUIBase = layoutParent.contentView as IParentIUIBase;
var border:Border = layoutParent.border;
var borderModel:IBorderModel = border.model as IBorderModel;
var ww:Number = layoutParent.resizableView.width;
var hh:Number = layoutParent.resizableView.height;
border.width = ww;
border.height = hh;
contentView.width = ww - borderModel.offsets.left - borderModel.offsets.right;
contentView.height = hh - borderModel.offsets.top - borderModel.offsets.bottom;
contentView.x = borderModel.offsets.left;
contentView.y = borderModel.offsets.top;
var n:int = contentView.numElements;
var yy:Number = 0;
for (var i:int = 0; i < n; i++)
{
var ir:IUIBase = contentView.getElementAt(i) as IUIBase;
ir.y = yy;
ir.width = contentView.width;
yy += ir.height;
}
if (yy > contentView.height)
{
vScrollBar = layoutParent.vScrollBar;
contentView.width -= vScrollBar.width;
IScrollBarModel(vScrollBar.model).maximum = yy;
IScrollBarModel(vScrollBar.model).pageSize = contentView.height;
IScrollBarModel(vScrollBar.model).pageStepSize = contentView.height;
vScrollBar.visible = true;
vScrollBar.height = contentView.height;
vScrollBar.y = contentView.y;
vScrollBar.x = contentView.width;
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
DisplayObject(contentView).scrollRect = new Rectangle(0, vpos, contentView.width, vpos + contentView.height);
vScrollBar.addEventListener("scroll", scrollHandler);
}
else if (vScrollBar)
{
DisplayObject(contentView).scrollRect = null;
vScrollBar.visible = false;
}
IEventDispatcher(_strand).dispatchEvent(new Event("layoutComplete"));
}
private function scrollHandler(event:Event):void
{
var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent.contentView;
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
DisplayObject(contentView).scrollRect = new Rectangle(0, vpos, contentView.width, vpos + contentView.height);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads.layouts
{
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBorderModel;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IScrollBarModel;
import org.apache.flex.core.IScrollingLayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ScrollBar;
/**
* The NonVirtualVerticalScrollingLayout class is a layout
* bead that displays a set of children vertically in one row,
* separating them according to CSS layout rules for margin and
* vertical-align styles and lays out a vertical ScrollBar
* to the right of the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NonVirtualVerticalScrollingLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NonVirtualVerticalScrollingLayout()
{
}
private var vScrollBar:ScrollBar;
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("heightChanged", changeHandler);
IEventDispatcher(value).addEventListener("widthChanged", changeHandler);
IEventDispatcher(value).addEventListener("itemsCreated", changeHandler);
}
private function changeHandler(event:Event):void
{
var layoutParent:IScrollingLayoutParent =
_strand.getBeadByType(IScrollingLayoutParent) as IScrollingLayoutParent;
var contentView:IParentIUIBase = layoutParent.contentView as IParentIUIBase;
var border:Border = layoutParent.border;
var borderModel:IBorderModel;
if (border)
borderModel = border.model as IBorderModel;
var ww:Number = layoutParent.resizableView.width;
var hh:Number = layoutParent.resizableView.height;
if (border)
{
border.width = ww;
border.height = hh;
}
contentView.width = ww - ((border) ? borderModel.offsets.left + borderModel.offsets.right : 0);
contentView.height = hh - ((border) ? borderModel.offsets.top - borderModel.offsets.bottom : 0);
contentView.x = (border) ? borderModel.offsets.left : 0;
contentView.y = (border) ? borderModel.offsets.top : 0;
var n:int = contentView.numElements;
var yy:Number = 0;
for (var i:int = 0; i < n; i++)
{
var ir:IUIBase = contentView.getElementAt(i) as IUIBase;
ir.y = yy;
ir.width = contentView.width;
yy += ir.height;
}
if (yy > contentView.height)
{
vScrollBar = layoutParent.vScrollBar;
contentView.width -= vScrollBar.width;
IScrollBarModel(vScrollBar.model).maximum = yy;
IScrollBarModel(vScrollBar.model).pageSize = contentView.height;
IScrollBarModel(vScrollBar.model).pageStepSize = contentView.height;
vScrollBar.visible = true;
vScrollBar.height = contentView.height;
vScrollBar.y = contentView.y;
vScrollBar.x = contentView.width;
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
DisplayObject(contentView).scrollRect = new Rectangle(0, vpos, contentView.width, vpos + contentView.height);
vScrollBar.addEventListener("scroll", scrollHandler);
}
else if (vScrollBar)
{
DisplayObject(contentView).scrollRect = null;
vScrollBar.visible = false;
}
IEventDispatcher(_strand).dispatchEvent(new Event("layoutComplete"));
}
private function scrollHandler(event:Event):void
{
var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent.contentView;
var vpos:Number = IScrollBarModel(vScrollBar.model).value;
DisplayObject(contentView).scrollRect = new Rectangle(0, vpos, contentView.width, vpos + contentView.height);
}
}
}
|
handle no border
|
handle no border
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
9a2cdb37a5bdbdad2a28d4d93a20769078ceeec7
|
src/stdio/BufferedStream.as
|
src/stdio/BufferedStream.as
|
package stdio {
internal class BufferedStream implements InputStream, OutputStream {
public var buffer: String = ""
public var closed: Boolean = false
public function get ready(): Boolean {
return ready_for({ gets: false })
}
public function read(callback: Function): void {
push({ callback: callback, gets: false })
}
public function gets(callback: Function): void {
push({ callback: callback, gets: true })
}
public function puts(value: *): void {
write(value + "\n")
}
public function write(value: *): void {
buffer += value; feed()
}
public function close(): void {
closed = true; feed()
}
//----------------------------------------------------------------
private const requests: Array = []
private function push(request: Object): void {
requests.push(request); feed()
}
private function feed(): void {
while (requests.length > 0 && ready_for(requests[0])) {
satisfy(requests.shift())
}
}
private function ready_for(request: Object): Boolean {
return closed || (
request.gets ? buffer.indexOf("\n") !== -1 : buffer !== ""
)
}
private function satisfy(request: Object): void {
if (closed && buffer.length === 0) {
(request.callback)(null)
} else if (request.gets) {
satisfy_gets(request.callback)
} else {
satisfy_read(request.callback)
}
}
private function satisfy_gets(callback: Function): void {
const next: int = buffer.indexOf("\n") === -1
? buffer.length : buffer.indexOf("\n") + 1
const line: String = buffer.slice(0, next)
buffer = buffer.slice(next)
callback(line.replace(/\n$/, ""))
}
private function satisfy_read(callback: Function): void {
const result: String = buffer
buffer = ""
callback(result)
}
}
}
|
package stdio {
public class BufferedStream implements InputStream, OutputStream {
public var buffer: String = ""
public var closed: Boolean = false
public function get ready(): Boolean {
return ready_for({ gets: false })
}
public function read(callback: Function): void {
push({ callback: callback, gets: false })
}
public function gets(callback: Function): void {
push({ callback: callback, gets: true })
}
public function puts(value: *): void {
write(value + "\n")
}
public function write(value: *): void {
buffer += value; feed()
}
public function close(): void {
closed = true; feed()
}
//----------------------------------------------------------------
private const requests: Array = []
private function push(request: Object): void {
requests.push(request); feed()
}
private function feed(): void {
while (requests.length > 0 && ready_for(requests[0])) {
satisfy(requests.shift())
}
}
private function ready_for(request: Object): Boolean {
return closed || (
request.gets ? buffer.indexOf("\n") !== -1 : buffer !== ""
)
}
private function satisfy(request: Object): void {
if (closed && buffer.length === 0) {
(request.callback)(null)
} else if (request.gets) {
satisfy_gets(request.callback)
} else {
satisfy_read(request.callback)
}
}
private function satisfy_gets(callback: Function): void {
const next: int = buffer.indexOf("\n") === -1
? buffer.length : buffer.indexOf("\n") + 1
const line: String = buffer.slice(0, next)
buffer = buffer.slice(next)
callback(line.replace(/\n$/, ""))
}
private function satisfy_read(callback: Function): void {
const result: String = buffer
buffer = ""
callback(result)
}
}
}
|
Make BufferedStream public.
|
Make BufferedStream public.
|
ActionScript
|
mit
|
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
|
14af0ae876362592e681410398e32f3e37b902ce
|
doc/tutorials/examples/actionscript/socket/flex/src/org/pyamf/examples/socket/PythonSocket.as
|
doc/tutorials/examples/actionscript/socket/flex/src/org/pyamf/examples/socket/PythonSocket.as
|
package org.pyamf.examples.socket
{
/**
* Copyright (c) 2007-2009 The PyAMF Project.
* See LICENSE.txt for details.
*/
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.ObjectEncoding;
import flash.net.Socket;
import flash.system.Capabilities;
[Event(name="connected", type="flash.events.Event")]
[Event(name="disconnected", type="flash.events.Event")]
[Event(name="logUpdate", type="flash.events.Event")]
/**
* Socket connection to read and write raw binary data.
*
* @see http://livedocs.adobe.com/flex/3/langref/flash/net/Socket.html
* @since 0.1.0
*/
public class PythonSocket extends Socket
{
private var _response : String;
private var _log : String;
private var _host : String;
private var _port : int;
public static const CONNECTED : String = "connected";
public static const DISCONNECTED: String = "disconnected";
public static const LOG_UPDATE : String = "logUpdate";
public function PythonSocket(host:String='localhost', port:int=8000)
{
super(host, port);
_host = host;
_port = port;
_log = "Using Flash Player " + Capabilities.version + "\n";
objectEncoding = ObjectEncoding.AMF0;
configureListeners();
logger("Connecting to socket server on " + _host + ":" + _port);
}
public function get log():String
{
return _log;
}
public function set log(val:String):void
{
_log = val;
}
private function configureListeners():void
{
addEventListener(Event.CLOSE, closeHandler);
addEventListener(Event.CONNECT, connectHandler);
addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
addEventListener(ProgressEvent.SOCKET_DATA, readResponse);
}
public function write(msg:String): void
{
sendRequest(msg);
}
private function writeln(str:String):void
{
str += "\n";
try {
writeUTFBytes(str);
}
catch(e:IOError) {
switch (e.errorID) {
case 2002:
// reconnect when connection timed out
if (!connected) {
logger("Reconnecting...");
connect( _host, _port );
}
break;
default:
logger(e.toString());
break;
}
}
}
private function sendRequest(str:String):void
{
logger("sendRequest: " + str);
_response = "";
writeln(str);
flush();
}
private function readResponse(event:ProgressEvent):void
{
var result:Object = this.readObject();
_response += result;
logger(result.toString());
}
private function logger(msg:String):void
{
var newMsg:String = msg + "\n";
_log += newMsg;
dispatchEvent(new Event(LOG_UPDATE));
}
private function connectHandler(event:Event):void
{
logger("Connected to server.\n");
dispatchEvent(new Event(CONNECTED));
}
private function closeHandler(event:Event):void
{
logger("Connection closed.");
dispatchEvent(new Event(DISCONNECTED));
}
private function ioErrorHandler(event:IOErrorEvent):void
{
logger("ioErrorHandler: " + event.text);
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
logger("securityErrorHandler: " + event.text);
}
}
}
|
package org.pyamf.examples.socket
{
/**
* Copyright (c) 2007-2009 The PyAMF Project.
* See LICENSE.txt for details.
*/
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.system.Capabilities;
[Event(name="connected", type="flash.events.Event")]
[Event(name="disconnected", type="flash.events.Event")]
[Event(name="logUpdate", type="flash.events.Event")]
/**
* Socket connection to read and write raw binary data.
*
* @see http://livedocs.adobe.com/flex/3/langref/flash/net/Socket.html
* @since 0.1.0
*/
public class PythonSocket extends Socket
{
private var _response : String;
private var _log : String;
private var _host : String;
private var _port : int;
public static const CONNECTED : String = "connected";
public static const DISCONNECTED: String = "disconnected";
public static const LOG_UPDATE : String = "logUpdate";
public function PythonSocket(host:String='localhost', port:int=8000)
{
super(host, port);
_host = host;
_port = port;
_log = "Using Flash Player " + Capabilities.version + "\n";
configureListeners();
logger("Connecting to socket server on " + _host + ":" + _port);
}
public function get log():String
{
return _log;
}
public function set log(val:String):void
{
_log = val;
}
private function configureListeners():void
{
addEventListener(Event.CLOSE, closeHandler);
addEventListener(Event.CONNECT, connectHandler);
addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
addEventListener(ProgressEvent.SOCKET_DATA, readResponse);
}
public function write(msg:String): void
{
sendRequest(msg);
}
private function writeln(str:String):void
{
str += "\n";
try {
writeUTFBytes(str);
}
catch(e:IOError) {
switch (e.errorID) {
case 2002:
// reconnect when connection timed out
if (!connected) {
logger("Reconnecting...");
connect( _host, _port );
}
break;
default:
logger(e.toString());
break;
}
}
}
private function sendRequest(str:String):void
{
logger("sendRequest: " + str);
_response = "";
writeln(str);
flush();
}
private function readResponse(event:ProgressEvent):void
{
var result:Object = this.readObject();
_response += result;
logger(result.toString());
}
private function logger(msg:String):void
{
var newMsg:String = msg + "\n";
_log += newMsg;
dispatchEvent(new Event(LOG_UPDATE));
}
private function connectHandler(event:Event):void
{
logger("Connected to server.\n");
dispatchEvent(new Event(CONNECTED));
}
private function closeHandler(event:Event):void
{
logger("Connection closed.");
dispatchEvent(new Event(DISCONNECTED));
}
private function ioErrorHandler(event:IOErrorEvent):void
{
logger("ioErrorHandler: " + event.text);
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
logger("securityErrorHandler: " + event.text);
}
}
}
|
fix the flex example to use AMF3 by default
|
fix the flex example to use AMF3 by default
|
ActionScript
|
mit
|
thijstriemstra/pyamf,thijstriemstra/pyamf,njoyce/pyamf,hydralabs/pyamf,hydralabs/pyamf,njoyce/pyamf
|
7bc9172221fa76a02003ad7f8e4921b9b84d9a12
|
exporter/src/main/as/flump/export/ExporterController.as
|
exporter/src/main/as/flump/export/ExporterController.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
import flash.desktop.NativeApplication;
import flash.display.NativeMenu;
import flash.display.NativeMenuItem;
import flash.display.NativeWindow;
import flash.display.Stage;
import flash.display.StageQuality;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.FileFilter;
import flash.utils.IDataOutput;
import flump.executor.Executor;
import flump.executor.Future;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import mx.events.PropertyChangeEvent;
import spark.components.DataGrid;
import spark.events.GridSelectionEvent;
import starling.display.Sprite;
public class ExporterController
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function ExporterController (win :ExporterWindow, configFile :File = null) {
Log.setLevel("", Log.INFO);
_win = win;
_errorsGrid = _win.errors;
_flashDocsGrid = _win.libraries;
_confFile = configFile;
if (_confFile != null) {
openConf();
}
var curSelection :DocStatus = null;
_flashDocsGrid.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _flashDocsGrid.selectedIndices);
updatePreviewAndExport();
if (curSelection != null) {
curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
var newSelection :DocStatus = _flashDocsGrid.selectedItem as DocStatus;
if (newSelection != null) {
newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
curSelection = newSelection;
});
_win.reload.addEventListener(MouseEvent.CLICK, F.callback(reloadNow));
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _flashDocsGrid.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_flashDocsGrid.selectedItem.lib);
});
_importChooser = new DirChooser(null, _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImportDirectory);
_exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(reloadNow);
_importChooser.changed.add(F.callback(updateWindowTitle, true));
_exportChooser.changed.add(F.callback(updateWindowTitle, true));
var editFormatsController :EditFormatsController = null;
_win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (editFormatsController == null || editFormatsController.closed) {
editFormatsController = new EditFormatsController(_conf);
editFormatsController.formatsChanged.add(updateUiFromConf);
} else {
editFormatsController.show();
}
});
updateUiFromConf();
updateWindowTitle(false);
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setupMenus () :void {
var fileMenuItem :NativeMenuItem;
if (NativeApplication.supportsMenu) {
// Grab the existing menu on macs. Use an index to get it as it's not going to be
// 'File' in all languages
fileMenuItem = NA.menu.getItemAt(1);
// Add a separator before the existing close command
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0);
} else {
_win.nativeWindow.menu = new NativeMenu();
fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File");
}
// Add save and save as by index to work with the existing items on Mac
// Mac menus have an existing "Close" item, so everything we add should go ahead of that
var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New Project"), 0);
newMenuItem.keyEquivalent = "n";
newMenuItem.addEventListener(Event.SELECT, function (..._) :void {
_confFile = null;
_conf = new FlumpConf();
setImportDirectory(null);
updateUiFromConf();
});
var openMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open Project..."), 1);
openMenuItem.keyEquivalent = "o";
openMenuItem.addEventListener(Event.SELECT, function (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
open(file);
});
file.browseForOpen("Open Flump Project", [
new FileFilter("Flump project (*.flump)", "*.flump") ]);
});
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2);
NA.addEventListener(InvokeEvent.INVOKE, function (event :InvokeEvent) :void {
if (event.arguments.length > 0) {
open(new File(event.arguments[0]));
}
});
const saveMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project"), 3);
saveMenuItem.keyEquivalent = "s";
function saveConf () :void {
Files.write(_confFile, function (out :IDataOutput) :void {
// Set directories relative to where this file is being saved. Fall back to absolute
// paths if relative paths aren't possible.
if (_importChooser.dir != null) {
_conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true);
if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath;
}
if (_exportChooser.dir != null) {
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath;
}
out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2));
updateWindowTitle(false);
});
};
function saveAs (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
// Ensure the filename ends with .flump
if (!StringUtil.endsWith(file.name.toLowerCase(), ".flump")) {
file = file.parent.resolvePath(file.name + ".flump");
}
_confFile = file;
saveConfFilePath();
saveConf();
});
file.browseForSave("Save Flump Configuration");
};
saveMenuItem.addEventListener(Event.SELECT, function (..._) :void {
if (_confFile == null) saveAs();
else saveConf();
});
const saveAsMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project As..."), 4);
saveAsMenuItem.keyEquivalent = "S";
saveAsMenuItem.addEventListener(Event.SELECT, saveAs);
}
protected function updateWindowTitle (modified :Boolean) :void {
var name :String = (_confFile != null) ? _confFile.name.replace(/\.flump$/i, "") : "Untitled Project";
if (modified) name += "*";
_win.title = name;
}
protected function openConf () :void {
try {
_conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile));
var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath;
setImportDirectory(new File(dir));
} catch (e :Error) {
log.warning("Unable to parse conf", e);
_errorsGrid.dataProvider.addItem(new ParseError(_confFile.nativePath,
ParseError.CRIT, "Unable to read configuration"));
_confFile = null;
}
}
protected function open (file :File) :void {
_confFile = file;
saveConfFilePath();
openConf();
updateUiFromConf();
updateWindowTitle(false);
}
protected function reloadNow () :void {
setImportDirectory(_importChooser.dir);
updatePreviewAndExport();
}
protected function updateUiFromConf (..._) :void {
if (_confFile != null) {
_importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null;
_exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null;
} else {
_importChooser.dir = null;
_exportChooser.dir = null;
}
var formatNames :Array = [];
for each (var export :ExportConf in _conf.exports) formatNames.push(export.description);
_win.formatOverview.text = formatNames.join(", ");
updateWindowTitle(true);
}
protected function updatePreviewAndExport (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _flashDocsGrid.selectionLength > 0 &&
_flashDocsGrid.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
var status :DocStatus = _flashDocsGrid.selectedItem as DocStatus;
_win.preview.enabled = status != null && status.isValid;
if (_exportChooser.dir == null) return;
_conf.exportDir = _confFile == null ? _exportChooser.dir.nativePath : _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
}
protected function createPublisher () :Publisher {
if (_exportChooser.dir == null || _conf.exports.length == 0) return null;
return new Publisher(_exportChooser.dir, _conf);
}
protected function saveConfFilePath () :void {
trace("Conf file is now " + _confFile.nativePath);
FlumpSettings.configFilePath = _confFile.nativePath;
}
protected function setImportDirectory (dir :File) :void {
_importDirectory = dir;
_flashDocsGrid.dataProvider.removeAll();
_errorsGrid.dataProvider.removeAll();
if (dir == null) {
return;
}
if (_docFinder != null) {
_docFinder.shutdownNow();
}
_docFinder = new Executor();
findFlashDocuments(dir, _docFinder, true);
_win.reload.enabled = true;
}
protected function showPreviewWindow (lib :XflLibrary) :void {
if (_previewController == null || _previewWindow.closed || _previewControls.closed) {
_previewWindow = new PreviewWindow();
_previewControls = new PreviewControlsWindow();
_previewWindow.started = function (container :Sprite) :void {
_previewController = new PreviewController(lib, container, _previewWindow,
_previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
_previewWindow.orderToFront();
_previewControls.orderToFront();
}
// Causes a window to be hidden, rather than closed, when its close box is clicked
protected static function preventWindowClose (window :NativeWindow) :void {
window.addEventListener(Event.CLOSING, function (e :Event) :void {
e.preventDefault();
window.visible = false;
});
}
protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void {
Files.list(base, exec).succeeded.add(function (files :Array) :void {
if (exec.isShutdown) return;
for each (var file :File in files) {
if (Files.hasExtension(file, "xfl")) {
if (ignoreXflAtBase) {
_errorsGrid.dataProvider.addItem(new ParseError(base.nativePath,
ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " +
base.parent.nativePath + "?"));
} else addFlashDocument(file);
return;
}
}
for each (file in files) {
if (StringUtil.startsWith(file.name, ".", "RECOVER_")) {
continue; // Ignore hidden VCS directories, and recovered backups created by Flash
}
if (file.isDirectory) findFlashDocuments(file, exec);
else addFlashDocument(file);
}
});
}
protected function exportFlashDocument (status :DocStatus) :void {
const stage :Stage = NA.activeWindow.stage;
const prevQuality :String = stage.quality;
stage.quality = StageQuality.BEST;
createPublisher().publish(status.lib);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function addFlashDocument (file :File) :void {
var importPathLen :int = _importDirectory.nativePath.length + 1;
var name :String = file.nativePath.substring(importPathLen).replace(
new RegExp("\\" + File.separator, "g"), "/");
var load :Future;
switch (Files.getExtension(file)) {
case "xfl":
name = name.substr(0, name.lastIndexOf("/"));
load = new XflLoader().load(name, file.parent);
break;
case "fla":
name = name.substr(0, name.lastIndexOf("."));
load = new FlaLoader().load(name, file);
break;
default:
// Unsupported file type, ignore
return;
}
const status :DocStatus = new DocStatus(name, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_flashDocsGrid.dataProvider.addItem(status);
load.succeeded.add(function (lib :XflLibrary) :void {
var pub :Publisher = createPublisher();
status.lib = lib;
status.updateModified(Ternary.of(pub == null || pub.modified(lib)));
for each (var err :ParseError in lib.getErrors()) _errorsGrid.dataProvider.addItem(err);
status.updateValid(Ternary.of(lib.valid));
});
load.failed.add(function (error :Error) :void {
trace("Failed to load " + file.nativePath + ": " + error);
status.updateValid(Ternary.FALSE);
throw error;
});
}
protected var _importDirectory :File;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _flashDocsGrid :DataGrid;
protected var _errorsGrid :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _conf :FlumpConf = new FlumpConf();
protected var _confFile :File;
protected var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
private static const log :Log = Log.getLog(ExporterController);
}
}
import flash.events.EventDispatcher;
import flump.export.Ternary;
import flump.xfl.XflLibrary;
import mx.core.IPropertyChangeNotifier;
import mx.events.PropertyChangeEvent;
class DocStatus extends EventDispatcher implements IPropertyChangeNotifier {
public var path :String;
public var modified :String;
public var valid :String = PENDING;
public var lib :XflLibrary;
public function DocStatus (path :String, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.lib = lib;
this.path = path;
_uid = path;
updateModified(modified);
updateValid(valid);
}
public function updateValid (newValid :Ternary) :void {
changeField("valid", function (..._) :void {
if (newValid == Ternary.TRUE) valid = YES;
else if (newValid == Ternary.FALSE) valid = ERROR;
else valid = PENDING;
});
}
public function get isValid () :Boolean { return valid == YES; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = YES;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = PENDING;
});
}
protected function changeField(fieldName :String, modifier :Function) :void {
const oldValue :Object = this[fieldName];
modifier();
const newValue :Object = this[fieldName];
dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue));
}
public function get uid () :String { return _uid; }
public function set uid (uid :String) :void { _uid = uid; }
protected var _uid :String;
protected static const PENDING :String = "...";
protected static const ERROR :String = "ERROR";
protected static const YES :String = "Yes";
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.export {
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.StringUtil;
import flash.desktop.NativeApplication;
import flash.display.NativeMenu;
import flash.display.NativeMenuItem;
import flash.display.NativeWindow;
import flash.display.Stage;
import flash.display.StageQuality;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.net.FileFilter;
import flash.utils.IDataOutput;
import flump.executor.Executor;
import flump.executor.Future;
import flump.xfl.ParseError;
import flump.xfl.XflLibrary;
import mx.events.PropertyChangeEvent;
import spark.components.DataGrid;
import spark.events.GridSelectionEvent;
import starling.display.Sprite;
public class ExporterController
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public function ExporterController (win :ExporterWindow, configFile :File = null) {
Log.setLevel("", Log.INFO);
_win = win;
_errorsGrid = _win.errors;
_flashDocsGrid = _win.libraries;
_confFile = configFile;
if (_confFile != null) {
openConf();
}
var curSelection :DocStatus = null;
_flashDocsGrid.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void {
log.info("Changed", "selected", _flashDocsGrid.selectedIndices);
updatePreviewAndExport();
if (curSelection != null) {
curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
var newSelection :DocStatus = _flashDocsGrid.selectedItem as DocStatus;
if (newSelection != null) {
newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport);
}
curSelection = newSelection;
});
_win.reload.addEventListener(MouseEvent.CLICK, F.callback(reloadNow));
_win.export.addEventListener(MouseEvent.CLICK, function (..._) :void {
for each (var status :DocStatus in _flashDocsGrid.selectedItems) {
exportFlashDocument(status);
}
});
_win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void {
showPreviewWindow(_flashDocsGrid.selectedItem.lib);
});
_importChooser = new DirChooser(null, _win.importRoot, _win.browseImport);
_importChooser.changed.add(setImportDirectory);
_exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport);
_exportChooser.changed.add(reloadNow);
_importChooser.changed.add(F.callback(updateWindowTitle, true));
_exportChooser.changed.add(F.callback(updateWindowTitle, true));
var editFormatsController :EditFormatsController = null;
_win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void {
if (editFormatsController == null || editFormatsController.closed) {
editFormatsController = new EditFormatsController(_conf);
editFormatsController.formatsChanged.add(updateUiFromConf);
} else {
editFormatsController.show();
}
});
updateUiFromConf();
updateWindowTitle(false);
_win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); });
}
protected function setupMenus () :void {
var fileMenuItem :NativeMenuItem;
if (NativeApplication.supportsMenu) {
// Grab the existing menu on macs. Use an index to get it as it's not going to be
// 'File' in all languages
fileMenuItem = NA.menu.getItemAt(1);
// Add a separator before the existing close command
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0);
} else {
_win.nativeWindow.menu = new NativeMenu();
fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File");
}
// Add save and save as by index to work with the existing items on Mac
// Mac menus have an existing "Close" item, so everything we add should go ahead of that
var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New Project"), 0);
newMenuItem.keyEquivalent = "n";
newMenuItem.addEventListener(Event.SELECT, function (..._) :void {
_confFile = null;
_conf = new FlumpConf();
setImportDirectory(null);
updateUiFromConf();
});
var openMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open Project..."), 1);
openMenuItem.keyEquivalent = "o";
openMenuItem.addEventListener(Event.SELECT, function (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
open(file);
});
file.browseForOpen("Open Flump Project", [
new FileFilter("Flump project (*.flump)", "*.flump") ]);
});
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2);
NA.addEventListener(InvokeEvent.INVOKE, function (event :InvokeEvent) :void {
if (event.arguments.length > 0) {
open(new File(event.arguments[0]));
}
});
const saveMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project"), 3);
saveMenuItem.keyEquivalent = "s";
saveMenuItem.addEventListener(Event.SELECT, function (..._) :void {
if (_confFile == null) saveConfAs();
else saveConf();
});
const saveAsMenuItem :NativeMenuItem =
fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project As..."), 4);
saveAsMenuItem.keyEquivalent = "S";
saveAsMenuItem.addEventListener(Event.SELECT, saveConfAs);
}
protected function updateWindowTitle (modified :Boolean) :void {
var name :String = (_confFile != null) ? _confFile.name.replace(/\.flump$/i, "") : "Untitled Project";
if (modified) name += "*";
_win.title = name;
}
protected function openConf () :void {
try {
_conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile));
var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath;
setImportDirectory(new File(dir));
} catch (e :Error) {
log.warning("Unable to parse conf", e);
_errorsGrid.dataProvider.addItem(new ParseError(_confFile.nativePath,
ParseError.CRIT, "Unable to read configuration"));
_confFile = null;
}
}
protected function saveConf () :void {
Files.write(_confFile, function (out :IDataOutput) :void {
// Set directories relative to where this file is being saved. Fall back to absolute
// paths if relative paths aren't possible.
if (_importChooser.dir != null) {
_conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true);
if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath;
}
if (_exportChooser.dir != null) {
_conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath;
}
out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2));
updateWindowTitle(false);
});
}
protected function saveConfAs (..._) :void {
var file :File = new File();
file.addEventListener(Event.SELECT, function (..._) :void {
// Ensure the filename ends with .flump
if (!StringUtil.endsWith(file.name.toLowerCase(), ".flump")) {
file = file.parent.resolvePath(file.name + ".flump");
}
_confFile = file;
saveConfFilePath();
saveConf();
});
file.browseForSave("Save Flump Configuration");
};
protected function open (file :File) :void {
_confFile = file;
saveConfFilePath();
openConf();
updateUiFromConf();
updateWindowTitle(false);
}
protected function reloadNow () :void {
setImportDirectory(_importChooser.dir);
updatePreviewAndExport();
}
protected function updateUiFromConf (..._) :void {
if (_confFile != null) {
_importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null;
_exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null;
} else {
_importChooser.dir = null;
_exportChooser.dir = null;
}
var formatNames :Array = [];
for each (var export :ExportConf in _conf.exports) formatNames.push(export.description);
_win.formatOverview.text = formatNames.join(", ");
updateWindowTitle(true);
}
protected function updatePreviewAndExport (..._) :void {
_win.export.enabled = _exportChooser.dir != null && _flashDocsGrid.selectionLength > 0 &&
_flashDocsGrid.selectedItems.some(function (status :DocStatus, ..._) :Boolean {
return status.isValid;
});
var status :DocStatus = _flashDocsGrid.selectedItem as DocStatus;
_win.preview.enabled = status != null && status.isValid;
if (_exportChooser.dir == null) return;
_conf.exportDir = _confFile == null ? _exportChooser.dir.nativePath : _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true);
}
protected function createPublisher () :Publisher {
if (_exportChooser.dir == null || _conf.exports.length == 0) return null;
return new Publisher(_exportChooser.dir, _conf);
}
protected function saveConfFilePath () :void {
trace("Conf file is now " + _confFile.nativePath);
FlumpSettings.configFilePath = _confFile.nativePath;
}
protected function setImportDirectory (dir :File) :void {
_importDirectory = dir;
_flashDocsGrid.dataProvider.removeAll();
_errorsGrid.dataProvider.removeAll();
if (dir == null) {
return;
}
if (_docFinder != null) {
_docFinder.shutdownNow();
}
_docFinder = new Executor();
findFlashDocuments(dir, _docFinder, true);
_win.reload.enabled = true;
}
protected function showPreviewWindow (lib :XflLibrary) :void {
if (_previewController == null || _previewWindow.closed || _previewControls.closed) {
_previewWindow = new PreviewWindow();
_previewControls = new PreviewControlsWindow();
_previewWindow.started = function (container :Sprite) :void {
_previewController = new PreviewController(lib, container, _previewWindow,
_previewControls);
}
_previewWindow.open();
_previewControls.open();
preventWindowClose(_previewWindow.nativeWindow);
preventWindowClose(_previewControls.nativeWindow);
} else {
_previewController.lib = lib;
_previewWindow.nativeWindow.visible = true;
_previewControls.nativeWindow.visible = true;
}
_previewWindow.orderToFront();
_previewControls.orderToFront();
}
// Causes a window to be hidden, rather than closed, when its close box is clicked
protected static function preventWindowClose (window :NativeWindow) :void {
window.addEventListener(Event.CLOSING, function (e :Event) :void {
e.preventDefault();
window.visible = false;
});
}
protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void {
Files.list(base, exec).succeeded.add(function (files :Array) :void {
if (exec.isShutdown) return;
for each (var file :File in files) {
if (Files.hasExtension(file, "xfl")) {
if (ignoreXflAtBase) {
_errorsGrid.dataProvider.addItem(new ParseError(base.nativePath,
ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " +
base.parent.nativePath + "?"));
} else addFlashDocument(file);
return;
}
}
for each (file in files) {
if (StringUtil.startsWith(file.name, ".", "RECOVER_")) {
continue; // Ignore hidden VCS directories, and recovered backups created by Flash
}
if (file.isDirectory) findFlashDocuments(file, exec);
else addFlashDocument(file);
}
});
}
protected function exportFlashDocument (status :DocStatus) :void {
const stage :Stage = NA.activeWindow.stage;
const prevQuality :String = stage.quality;
stage.quality = StageQuality.BEST;
createPublisher().publish(status.lib);
stage.quality = prevQuality;
status.updateModified(Ternary.FALSE);
}
protected function addFlashDocument (file :File) :void {
var importPathLen :int = _importDirectory.nativePath.length + 1;
var name :String = file.nativePath.substring(importPathLen).replace(
new RegExp("\\" + File.separator, "g"), "/");
var load :Future;
switch (Files.getExtension(file)) {
case "xfl":
name = name.substr(0, name.lastIndexOf("/"));
load = new XflLoader().load(name, file.parent);
break;
case "fla":
name = name.substr(0, name.lastIndexOf("."));
load = new FlaLoader().load(name, file);
break;
default:
// Unsupported file type, ignore
return;
}
const status :DocStatus = new DocStatus(name, Ternary.UNKNOWN, Ternary.UNKNOWN, null);
_flashDocsGrid.dataProvider.addItem(status);
load.succeeded.add(function (lib :XflLibrary) :void {
var pub :Publisher = createPublisher();
status.lib = lib;
status.updateModified(Ternary.of(pub == null || pub.modified(lib)));
for each (var err :ParseError in lib.getErrors()) _errorsGrid.dataProvider.addItem(err);
status.updateValid(Ternary.of(lib.valid));
});
load.failed.add(function (error :Error) :void {
trace("Failed to load " + file.nativePath + ": " + error);
status.updateValid(Ternary.FALSE);
throw error;
});
}
protected var _importDirectory :File;
protected var _docFinder :Executor;
protected var _win :ExporterWindow;
protected var _flashDocsGrid :DataGrid;
protected var _errorsGrid :DataGrid;
protected var _exportChooser :DirChooser;
protected var _importChooser :DirChooser;
protected var _conf :FlumpConf = new FlumpConf();
protected var _confFile :File;
protected var _previewController :PreviewController;
protected var _previewWindow :PreviewWindow;
protected var _previewControls :PreviewControlsWindow;
private static const log :Log = Log.getLog(ExporterController);
}
}
import flash.events.EventDispatcher;
import flump.export.Ternary;
import flump.xfl.XflLibrary;
import mx.core.IPropertyChangeNotifier;
import mx.events.PropertyChangeEvent;
class DocStatus extends EventDispatcher implements IPropertyChangeNotifier {
public var path :String;
public var modified :String;
public var valid :String = PENDING;
public var lib :XflLibrary;
public function DocStatus (path :String, modified :Ternary, valid :Ternary, lib :XflLibrary) {
this.lib = lib;
this.path = path;
_uid = path;
updateModified(modified);
updateValid(valid);
}
public function updateValid (newValid :Ternary) :void {
changeField("valid", function (..._) :void {
if (newValid == Ternary.TRUE) valid = YES;
else if (newValid == Ternary.FALSE) valid = ERROR;
else valid = PENDING;
});
}
public function get isValid () :Boolean { return valid == YES; }
public function updateModified (newModified :Ternary) :void {
changeField("modified", function (..._) :void {
if (newModified == Ternary.TRUE) modified = YES;
else if (newModified == Ternary.FALSE) modified = " ";
else modified = PENDING;
});
}
protected function changeField(fieldName :String, modifier :Function) :void {
const oldValue :Object = this[fieldName];
modifier();
const newValue :Object = this[fieldName];
dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue));
}
public function get uid () :String { return _uid; }
public function set uid (uid :String) :void { _uid = uid; }
protected var _uid :String;
protected static const PENDING :String = "...";
protected static const ERROR :String = "ERROR";
protected static const YES :String = "Yes";
}
|
Move save()/saveAs() into the class body
|
Move save()/saveAs() into the class body
|
ActionScript
|
mit
|
mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump
|
2b178fcd993ee505c471dbd0c1c21449d4c68199
|
src/goplayer/ConfigurationParser.as
|
src/goplayer/ConfigurationParser.as
|
package goplayer
{
public class ConfigurationParser
{
public static const DEFAULT_API_URL : String
= "http://staging.streamio.se/api"
public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array = [
"api", "tracker", "skin", "video", "bitrate",
"enablertmp", "autoplay", "loop",
"enablechrome", "enabletitle" ]
private const result : Configuration = new Configuration
private var parameters : Object
private var originalParameterNames : Object
public function ConfigurationParser
(parameters : Object, originalParameterNames : Object)
{
this.parameters = parameters
this.originalParameterNames = originalParameterNames
}
public function execute() : void
{
result.apiURL = getString("api", DEFAULT_API_URL)
result.trackerID = getString("tracker", DEFAULT_TRACKER_ID)
result.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getString("video", null)
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enablertmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("enablechrome", true)
result.enableTitle = getBoolean("enabletitle", true)
}
public static function parse(parameters : Object) : Configuration
{
const normalizedParameters : Object = {}
const originalParameterNames : Object = {}
for (var name : String in parameters)
if (VALID_PARAMETERS.indexOf(normalize(name)) == -1)
reportUnknownParameter(name)
else
normalizedParameters[normalize(name)] = parameters[name],
originalParameterNames[normalize(name)] = name
const parser : ConfigurationParser = new ConfigurationParser
(normalizedParameters, originalParameterNames)
parser.execute()
return parser.result
}
private static function normalize(name : String) : String
{ return name.toLowerCase().replace(/[^a-z]/g, "") }
private static function reportUnknownParameter(name : String) : void
{ debug("Error: Unknown parameter: " + name) }
// -----------------------------------------------------
private function getString(name : String, fallback : String) : String
{ return name in parameters ? parameters[name] : fallback }
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: " +
"“" + originalParameterNames[name] + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
package goplayer
{
public class ConfigurationParser
{
public static const DEFAULT_API_URL : String
= "http://staging.streamio.se/api"
public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf"
public static const DEFAULT_TRACKER_ID : String = "global"
public static const VALID_PARAMETERS : Array = [
"api", "tracker", "skin", "video", "bitrate",
"enablertmp", "autoplay", "loop",
"skin:showchrome", "skin:showtitle" ]
private const result : Configuration = new Configuration
private var parameters : Object
private var originalParameterNames : Object
public function ConfigurationParser
(parameters : Object, originalParameterNames : Object)
{
this.parameters = parameters
this.originalParameterNames = originalParameterNames
}
public function execute() : void
{
result.apiURL = getString("api", DEFAULT_API_URL)
result.trackerID = getString("tracker", DEFAULT_TRACKER_ID)
result.skinURL = getString("skin", DEFAULT_SKIN_URL)
result.movieID = getString("video", null)
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("enablertmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("skin:showchrome", true)
result.enableTitle = getBoolean("skin:showtitle", true)
}
public static function parse(parameters : Object) : Configuration
{
const normalizedParameters : Object = {}
const originalParameterNames : Object = {}
for (var name : String in parameters)
if (VALID_PARAMETERS.indexOf(normalize(name)) == -1)
reportUnknownParameter(name)
else
normalizedParameters[normalize(name)] = parameters[name],
originalParameterNames[normalize(name)] = name
const parser : ConfigurationParser = new ConfigurationParser
(normalizedParameters, originalParameterNames)
parser.execute()
return parser.result
}
private static function normalize(name : String) : String
{ return name.toLowerCase().replace(/[^a-z:]/g, "") }
private static function reportUnknownParameter(name : String) : void
{ debug("Error: Unknown parameter: " + name) }
// -----------------------------------------------------
private function getString(name : String, fallback : String) : String
{ return name in parameters ? parameters[name] : fallback }
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: " +
"“" + originalParameterNames[name] + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
Rename `enable-chrome' => `skin:show-chrome' and `enable-title' => `skin:show-title'.
|
Rename `enable-chrome' => `skin:show-chrome' and `enable-title' => `skin:show-title'.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
bb72ea7efd64ca6deaecf639959e1e6691a4e9bc
|
lib/src/com/amanitadesign/steam/WorkshopConstants.as
|
lib/src/com/amanitadesign/steam/WorkshopConstants.as
|
/*
* WorkshopConstants.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero> on 2013-04-24
* Copyright (c) 2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class WorkshopConstants
{
public static const FILETYPE_Community:int = 0;
public static const FILETYPE_Microtransaction:int = 1;
public static const FILETYPE_Collection:int = 2;
public static const FILETYPE_Art:int = 3;
public static const FILETYPE_Video:int = 4;
public static const FILETYPE_Screenshot:int = 5;
public static const FILETYPE_Game:int = 6;
public static const FILETYPE_Software:int = 7;
public static const FILETYPE_Concept:int = 8;
public static const FILETYPE_WebGuide:int = 9;
public static const FILETYPE_IntegratedGuide:int = 10;
public static const ENUMTYPE_RankedByVote:int = 0;
public static const ENUMTYPE_Recent:int = 1;
public static const ENUMTYPE_Trending:int = 2;
public static const ENUMTYPE_FavoritesOfFriends:int = 3;
public static const ENUMTYPE_VotedByFriends:int = 4;
public static const ENUMTYPE_ContentByFriends:int = 5;
public static const ENUMTYPE_RecentFromFollowedUsers:int = 6;
public static const FILEACTION_Played:int = 0;
public static const FILEACTION_Completed:int = 1;
public static const VISIBILITY_Public:int = 0;
public static const VISIBILITY_FriendsOnly:int = 1;
public static const VISIBILITY_Private:int = 2;
public static const FILEUPDATEHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
public static const UGCHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
}
}
|
/*
* WorkshopConstants.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero> on 2013-04-24
* Copyright (c) 2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class WorkshopConstants
{
public static const FILETYPE_Community:int = 0;
public static const FILETYPE_Microtransaction:int = 1;
public static const FILETYPE_Collection:int = 2;
public static const FILETYPE_Art:int = 3;
public static const FILETYPE_Video:int = 4;
public static const FILETYPE_Screenshot:int = 5;
public static const FILETYPE_Game:int = 6;
public static const FILETYPE_Software:int = 7;
public static const FILETYPE_Concept:int = 8;
public static const FILETYPE_WebGuide:int = 9;
public static const FILETYPE_IntegratedGuide:int = 10;
public static const ENUMTYPE_RankedByVote:int = 0;
public static const ENUMTYPE_Recent:int = 1;
public static const ENUMTYPE_Trending:int = 2;
public static const ENUMTYPE_FavoritesOfFriends:int = 3;
public static const ENUMTYPE_VotedByFriends:int = 4;
public static const ENUMTYPE_ContentByFriends:int = 5;
public static const ENUMTYPE_RecentFromFollowedUsers:int = 6;
public static const FILEACTION_Played:int = 0;
public static const FILEACTION_Completed:int = 1;
public static const VISIBILITY_Public:int = 0;
public static const VISIBILITY_FriendsOnly:int = 1;
public static const VISIBILITY_Private:int = 2;
public static const OVERLAYSTOREFLAG_None:int = 0;
public static const OVERLAYSTOREFLAG_AddToCart:int = 1;
public static const OVERLAYSTOREFLAG_AddToCartAndShow:int = 2;
public static const FILEUPDATEHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
public static const UGCHANDLE_Invalid:String = "18446744073709551615"; // 0xffffffffffffffffull
}
}
|
Add EOverlayToStoreFlags
|
Add EOverlayToStoreFlags
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
85702bb6de0af42a70cd4dccda70c5f4d6cd33fc
|
vivified/core/vivi_initialize.as
|
vivified/core/vivi_initialize.as
|
/* Vivified
* Copyright (C) 2007 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/*** general objects ***/
Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;
Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);
/*** breakpoints ***/
Breakpoint = function () extends Native.Breakpoint {
super ();
Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);
/*** information about the player ***/
Player = {};
Player.addProperty ("filename", Native.player_filename_get, Native.player_filename_set);
Player.addProperty ("frame", Native.player_frame_get, null);
Player.addProperty ("global", Native.player_global_get, null);
Player.addProperty ("variables", Native.player_variables_get, Native.player_variables_set);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onStartFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
Commands.where = function () {
var frame = Player.frame;
if (frame == undefined) {
Commands.print ("---");
return;
}
var i = 0;
while (frame) {
Commands.print (i++ + ": " + frame);
frame = frame.next;
}
};
Commands.backtrace = Commands.where;
Commands.bt = Commands.where;
|
/* Vivified
* Copyright (C) 2007 Benjamin Otte <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
/*** general objects ***/
Wrap = function () {};
Wrap.prototype = {};
Wrap.prototype.toString = Native.wrap_toString;
Frame = function () extends Wrap {};
Frame.prototype = new Wrap ();
Frame.prototype.addProperty ("code", Native.frame_code_get, null);
Frame.prototype.addProperty ("name", Native.frame_name_get, null);
Frame.prototype.addProperty ("next", Native.frame_next_get, null);
/*** breakpoints ***/
Breakpoint = function () extends Native.Breakpoint {
super ();
Breakpoint.list.push (this);
};
Breakpoint.list = new Array ();
Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set);
/*** information about the player ***/
Player = {};
Player.addProperty ("filename", Native.player_filename_get, Native.player_filename_set);
Player.addProperty ("frame", Native.player_frame_get, null);
Player.addProperty ("global", Native.player_global_get, null);
Player.addProperty ("variables", Native.player_variables_get, Native.player_variables_set);
/*** commands available for debugging ***/
Commands = new Object ();
Commands.print = Native.print;
Commands.error = Native.error;
Commands.r = Native.run;
Commands.run = Native.run;
Commands.halt = Native.stop;
Commands.stop = Native.stop;
Commands.s = Native.step;
Commands.step = Native.step;
Commands.reset = Native.reset;
Commands.restart = function () {
Commands.reset ();
Commands.run ();
};
Commands.quit = Native.quit;
/* can't use "break" as a function name, it's a keyword in JS */
Commands.add = function (name) {
if (name == undefined) {
Commands.error ("add command requires a function name");
return undefined;
}
var ret = new Breakpoint ();
ret.onStartFrame = function (frame) {
if (frame.name != name)
return false;
Commands.print ("Breakpoint: function " + name + " called");
Commands.print (" " + frame);
return true;
};
ret.toString = function () {
return "function call " + name;
};
return ret;
};
Commands.list = function () {
var a = Breakpoint.list;
var i;
for (i = 0; i < a.length; i++) {
Commands.print (i + ": " + a[i]);
}
};
Commands.del = function (id) {
var a = Breakpoint.list;
if (id == undefined) {
while (a[0])
Commands.del (0);
}
var b = a[id];
a.splice (id, 1);
b.active = false;
};
Commands.delete = Commands.del;
Commands.where = function () {
var frame = Player.frame;
if (frame == undefined) {
Commands.print ("---");
return;
}
var i = 0;
while (frame) {
Commands.print (i++ + ": " + frame);
frame = frame.next;
}
};
Commands.backtrace = Commands.where;
Commands.bt = Commands.where;
Commands.watch = function () {
var object;
var name;
if (arguments.length == 1) {
name = arguments[0];
} else if (arguments.length == 2) {
object = arguments[0];
name = arguments[1];
} else {
Commands.error ("usage: watch [object] name");
return;
}
var ret = new Breakpoint ();
ret.onSetVariable = function (o, variable, value) {
if (object && o != object)
return false;
if (variable != name)
return;
if (object) {
Commands.print ("Breakpoint: variable " + name + " on " + object);
} else {
Commands.print ("Breakpoint: variable " + name);
}
Commands.print (" " + Player.frame);
return true;
};
ret.toString = function () {
var s = "watch " + name;
if (object)
s += " on " + object;
return s;
};
return ret;
};
|
implement watch command
|
implement watch command
|
ActionScript
|
lgpl-2.1
|
freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,mltframework/swfdec
|
a5f4d6f3e8698c39f0a16c7ca48e2b52cb31d9d3
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(4, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const targetArrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(targetArrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(targetArrayCollection.length, 5);
assertEquals(targetArrayCollection.getItemAt(0), 1);
assertEquals(targetArrayCollection.getItemAt(1), 2);
assertEquals(targetArrayCollection.getItemAt(2), 3);
assertEquals(targetArrayCollection.getItemAt(3), 4);
assertEquals(targetArrayCollection.getItemAt(4), 5);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(4, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(arrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(arrayCollection.length, 5);
assertEquals(arrayCollection.getItemAt(0), 1);
assertEquals(arrayCollection.getItemAt(1), 2);
assertEquals(arrayCollection.getItemAt(2), 3);
assertEquals(arrayCollection.getItemAt(3), 4);
assertEquals(arrayCollection.getItemAt(4), 5);
}
}
}
|
Rename local method variable.
|
Rename local method variable.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
77762460949c20047525c644c1f2069bd249ff32
|
kdp3Lib/src/com/kaltura/kdpfl/view/controls/BufferAnimationMediator.as
|
kdp3Lib/src/com/kaltura/kdpfl/view/controls/BufferAnimationMediator.as
|
package com.kaltura.kdpfl.view.controls
{
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import flash.geom.Point;
import flash.utils.getQualifiedClassName;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
/**
* Mediator for the buffer indicator animation. Controls the appearance and removal of the animation from the display list.
* @author Hila
*
*/
public class BufferAnimationMediator extends Mediator
{
public static const NAME:String = "spinnerMediator";
public static const SPINNER_CLASS : String = "kspin";
public var applicationLoadStyleName:String = '';
public var bufferingStyleName:String = '';
private var zeroPoint : Point = new Point( 0 , 0);
/**
* flag indicating whether the active media has reached its end.
*/
private var _reachedEnd:Boolean=false;
private var _currConfig : ConfigProxy;
private var _notBuffering : Boolean = true;
private var _prevStatePaused:Boolean = true;
private var _lastPlayheadPos:Number;
/**
* indicate if "bufferChange" event was sent, we started buffering
*/
private var _bufferChangeStart:Boolean = false;
/**
* Constructor.
* @param viewComponent - the component controlled by the mediator.
*
*/
public function BufferAnimationMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
_currConfig = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
}
override public function handleNotification(note:INotification):void
{
var flashvars : Object = _currConfig.vo.flashvars;
var noteName : String = note.getName();
switch(noteName)
{
case NotificationType.SKIN_LOADED:
// spinner.swapLoadingWithAnimation( applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
spinner.visible = false;
break;
case NotificationType.LAYOUT_READY:
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.KDP_READY:
case NotificationType.READY_TO_PLAY:
spinner.visible = false;
_reachedEnd = false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.PLAYER_STATE_CHANGE:
if( note.getBody() == MediaPlayerState.BUFFERING)
{
_notBuffering = false;
if(_reachedEnd)
spinner.visible = false;
//fix OSMF bug: sometimes "buffering" was sent after player paused, the spinner shouldn't be visible in this case
else if (!_prevStatePaused)
spinner.visible = true;
}
else
{
//only relevant if not rtmp
/* if( note.getBody() == MediaPlayerState.READY ){
spinner.visible = false;
}
if(_flashvars.streamerType != StreamerType.RTMP){
spinner.visible = false;
} */
_notBuffering = true;
if( note.getBody() == MediaPlayerState.PLAYING)
{
_reachedEnd = false;
_prevStatePaused = false;
// spinner.visible = false;
}
if(note.getBody() == MediaPlayerState.PAUSED)
{
spinner.visible = false;
_prevStatePaused = true;
}
if( note.getBody() == MediaPlayerState.READY)
{
spinner.visible = false;
}
}
break;
/**
* Until OSMF for seeking in rtmp is fixed (buffering-wise)
* add a new case for update playhead notification
* */
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
//if _bufferChangeStart the next bufferChange event will make the spinner invisible
if(_notBuffering && !_bufferChangeStart)
{
spinner.visible = false;
}
//fix another OSMF bug: we are buffering even though movie plays
else if (spinner.visible)
{
var updateIntervalInSeconds:Number = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentTimeUpdateInterval / 1000;
var curPos:Number = parseFloat(Number(note.getBody()).toFixed(2));
if ((curPos - _lastPlayheadPos)<=updateIntervalInSeconds)
{
spinner.visible = false;
}
_lastPlayheadPos = curPos;
}
break;
case NotificationType.BUFFER_CHANGE:
_bufferChangeStart = note.getBody();
spinner.visible = _bufferChangeStart;
break;
case NotificationType.PLAYER_PLAY_END:
_reachedEnd=true;
spinner.visible = false;
break;
case NotificationType.KDP_EMPTY:
case NotificationType.READY_TO_LOAD:
spinner.visible = false;
_reachedEnd=false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.CHANGE_MEDIA:
//spinner.visible = true;
break;
//in case we are trying to connect to a live stream but it is not on air yet
case NotificationType.LIVE_ENTRY:
if (flashvars.hideSpinnerOnOffline=="true")
spinner.visible = false;
else
spinner.visible = true;
break;
//in case the live stream we are trying to connect to was found to be on air
case LiveStreamCommand.LIVE_STREAM_READY:
spinner.visible = false;
break;
case NotificationType.PRELOADER_LOADED:
var preObj:Object = note.getBody().preloader;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && preObj)
{
//save to flashvars, we might need it in the future
_currConfig.vo.flashvars["preloader"] = preObj;
spinner.setBufferingAnimation(getQualifiedClassName(preObj));
}
break;
}
}
override public function listNotificationInterests():Array
{
return [
NotificationType.SKIN_LOADED,
NotificationType.PLAYER_STATE_CHANGE,
NotificationType.PLAYER_PLAYED,
NotificationType.PLAYER_UPDATE_PLAYHEAD, //TODO: REMOVE THIS WHEN I FIND A BETTER WORK AROUND TO THE BUG
NotificationType.ENTRY_FAILED,
NotificationType.CHANGE_MEDIA,
NotificationType.PLAYER_PLAY_END,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.LAYOUT_READY,
NotificationType.LIVE_ENTRY,
LiveStreamCommand.LIVE_STREAM_READY,
NotificationType.READY_TO_PLAY,
NotificationType.READY_TO_LOAD,
NotificationType.ROOT_RESIZE,
NotificationType.BUFFER_CHANGE,
NotificationType.PRELOADER_LOADED
];
}
/**
* the buffer indicator animation controlled by the mediator.
* @return
*
*/
public function get spinner():BufferAnimation
{
return viewComponent as BufferAnimation;
}
}
}
|
package com.kaltura.kdpfl.view.controls
{
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import flash.geom.Point;
import flash.utils.getQualifiedClassName;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
/**
* Mediator for the buffer indicator animation. Controls the appearance and removal of the animation from the display list.
* @author Hila
*
*/
public class BufferAnimationMediator extends Mediator
{
public static const NAME:String = "spinnerMediator";
public static const SPINNER_CLASS : String = "kspin";
public var applicationLoadStyleName:String = '';
public var bufferingStyleName:String = '';
private var zeroPoint : Point = new Point( 0 , 0);
/**
* flag indicating whether the active media has reached its end.
*/
private var _reachedEnd:Boolean=false;
private var _currConfig : ConfigProxy;
private var _notBuffering : Boolean = true;
private var _prevStatePaused:Boolean = true;
private var _lastPlayheadPos:Number;
/**
* indicate if "bufferChange" event was sent, we started buffering
*/
private var _bufferChangeStart:Boolean = false;
/**
* Constructor.
* @param viewComponent - the component controlled by the mediator.
*
*/
public function BufferAnimationMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
_currConfig = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy;
}
override public function handleNotification(note:INotification):void
{
var flashvars : Object = _currConfig.vo.flashvars;
var noteName : String = note.getName();
switch(noteName)
{
case NotificationType.SKIN_LOADED:
// spinner.swapLoadingWithAnimation( applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
spinner.visible = false;
break;
case NotificationType.LAYOUT_READY:
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.KDP_READY:
case NotificationType.READY_TO_PLAY:
spinner.visible = false;
_reachedEnd = false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.PLAYER_STATE_CHANGE:
if( note.getBody() == MediaPlayerState.BUFFERING)
{
_notBuffering = false;
if(_reachedEnd)
spinner.visible = false;
//fix OSMF bug: sometimes "buffering" was sent after player paused, the spinner shouldn't be visible in this case
else if (!_prevStatePaused)
spinner.visible = true;
}
else
{
//only relevant if not rtmp
/* if( note.getBody() == MediaPlayerState.READY ){
spinner.visible = false;
}
if(_flashvars.streamerType != StreamerType.RTMP){
spinner.visible = false;
} */
_notBuffering = true;
if( note.getBody() == MediaPlayerState.PLAYING)
{
_reachedEnd = false;
_prevStatePaused = false;
// spinner.visible = false;
}
if(note.getBody() == MediaPlayerState.PAUSED)
{
spinner.visible = false;
_prevStatePaused = true;
}
if( note.getBody() == MediaPlayerState.READY)
{
spinner.visible = false;
}
}
break;
/**
* Until OSMF for seeking in rtmp is fixed (buffering-wise)
* add a new case for update playhead notification
* */
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
//if _bufferChangeStart the next bufferChange event will make the spinner invisible
if(_notBuffering && !_bufferChangeStart)
{
spinner.visible = false;
}
//fix another OSMF bug: we are buffering even though movie plays
else if (spinner.visible)
{
var updateIntervalInSeconds:Number = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentTimeUpdateInterval / 1000;
var curPos:Number = parseFloat(Number(note.getBody()).toFixed(2));
if ((curPos - _lastPlayheadPos)<=updateIntervalInSeconds)
{
spinner.visible = false;
}
_lastPlayheadPos = curPos;
}
break;
case NotificationType.BUFFER_CHANGE:
_bufferChangeStart = note.getBody();
//fix osmf bug: sometimes bufferChange was sent after playback complete
spinner.visible = _bufferChangeStart && !_reachedEnd;
break;
case NotificationType.PLAYER_PLAY_END:
_reachedEnd=true;
spinner.visible = false;
break;
case NotificationType.KDP_EMPTY:
case NotificationType.READY_TO_LOAD:
spinner.visible = false;
_reachedEnd=false;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && flashvars.preloader)
{
spinner.setBufferingAnimation(getQualifiedClassName(flashvars.preloader));
}
else
{
spinner.setBufferingAnimation(applicationLoadStyleName == '' ? SPINNER_CLASS : applicationLoadStyleName );
}
break;
case NotificationType.CHANGE_MEDIA:
//spinner.visible = true;
break;
//in case we are trying to connect to a live stream but it is not on air yet
case NotificationType.LIVE_ENTRY:
if (flashvars.hideSpinnerOnOffline=="true")
spinner.visible = false;
else
spinner.visible = true;
break;
//in case the live stream we are trying to connect to was found to be on air
case LiveStreamCommand.LIVE_STREAM_READY:
spinner.visible = false;
break;
case NotificationType.PRELOADER_LOADED:
var preObj:Object = note.getBody().preloader;
if (flashvars.usePreloaderBufferAnimation && flashvars.usePreloaderBufferAnimation=='true' && preObj)
{
//save to flashvars, we might need it in the future
_currConfig.vo.flashvars["preloader"] = preObj;
spinner.setBufferingAnimation(getQualifiedClassName(preObj));
}
break;
}
}
override public function listNotificationInterests():Array
{
return [
NotificationType.SKIN_LOADED,
NotificationType.PLAYER_STATE_CHANGE,
NotificationType.PLAYER_PLAYED,
NotificationType.PLAYER_UPDATE_PLAYHEAD, //TODO: REMOVE THIS WHEN I FIND A BETTER WORK AROUND TO THE BUG
NotificationType.ENTRY_FAILED,
NotificationType.CHANGE_MEDIA,
NotificationType.PLAYER_PLAY_END,
NotificationType.KDP_EMPTY,
NotificationType.KDP_READY,
NotificationType.LAYOUT_READY,
NotificationType.LIVE_ENTRY,
LiveStreamCommand.LIVE_STREAM_READY,
NotificationType.READY_TO_PLAY,
NotificationType.READY_TO_LOAD,
NotificationType.ROOT_RESIZE,
NotificationType.BUFFER_CHANGE,
NotificationType.PRELOADER_LOADED
];
}
/**
* the buffer indicator animation controlled by the mediator.
* @return
*
*/
public function get spinner():BufferAnimation
{
return viewComponent as BufferAnimation;
}
}
}
|
Fix OSMF bug: sometimes bufferChange events was sent after playback has finished.
|
qnd: Fix OSMF bug: sometimes bufferChange events was sent after playback
has finished.
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp
|
60ec297e24004ef5f50d8dae05c3313e99d3263a
|
src/stdio/Sprite.as
|
src/stdio/Sprite.as
|
package stdio {
import flash.display.*
import flash.utils.getQualifiedClassName
import flash.utils.setTimeout
public class Sprite extends flash.display.Sprite {
public function Sprite() {
stage.scaleMode = StageScaleMode.NO_SCALE
stage.align = StageAlign.TOP_LEFT
// Let the subclass constructor run first.
setTimeout(initialize, 0)
}
private function initialize(): void {
setup(loaderInfo, this, start)
}
private function start(): void {
if ("main" in this && this["main"].length === 0) {
this["main"]()
} else {
warn("Please write your main method like this:")
warn("public function main(): void {}")
process.exit(1)
}
}
private function warn(message: String): void {
process.warn(getQualifiedClassName(this) + ": " + message)
}
}
}
|
package stdio {
import flash.display.*
import flash.utils.getQualifiedClassName
import flash.utils.setTimeout
public class Sprite extends flash.display.Sprite {
public function Sprite() {
if (stage) {
stage.scaleMode = StageScaleMode.NO_SCALE
stage.align = StageAlign.TOP_LEFT
}
// Let the subclass constructor run first.
setTimeout(initialize, 0)
}
private function initialize(): void {
setup(loaderInfo, this, start)
}
private function start(): void {
if ("main" in this && this["main"].length === 0) {
this["main"]()
} else {
warn("Please write your main method like this:")
warn("public function main(): void {}")
process.exit(1)
}
}
private function warn(message: String): void {
process.warn(getQualifiedClassName(this) + ": " + message)
}
}
}
|
Fix bug preventing running processes recursively.
|
Fix bug preventing running processes recursively.
|
ActionScript
|
mit
|
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
|
a4205c30be2a021dbe43a28e40ba82a132fe6f22
|
src/aerys/minko/scene/controller/mesh/VisibilityController.as
|
src/aerys/minko/scene/controller/mesh/VisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.data.MeshVisibilityDataProvider;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class VisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _visibilityData : MeshVisibilityDataProvider;
public function get visible() : Boolean
{
return _visibilityData.visible;
}
public function set visible(value : Boolean) : void
{
_visibilityData.visible = value;
}
public function get frustumCulling() : uint
{
return _visibilityData.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibilityData.frustumCulling = value;
}
public function get insideFrustum() : Boolean
{
return _visibilityData.inFrustum;
}
public function VisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_visibilityData = new MeshVisibilityDataProvider();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : VisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.addedToScene.add(meshAddedToSceneHandler);
target.removedFromScene.add(meshRemovedFromSceneHandler);
target.bindings.addProvider(_visibilityData);
if (target.root is Scene)
meshAddedToSceneHandler(target, target.root as Scene);
}
private function targetRemovedHandler(ctrl : VisibilityController,
target : Mesh) : void
{
_mesh = null;
target.addedToScene.remove(meshAddedToSceneHandler);
target.removedFromScene.remove(meshRemovedFromSceneHandler);
target.bindings.removeProvider(_visibilityData);
if (target.root is Scene)
meshRemovedFromSceneHandler(target, target.root as Scene);
}
private function meshAddedToSceneHandler(mesh : Mesh,
scene : Scene) : void
{
scene.bindings.addCallback('worldToScreen', worldToViewChangedHandler);
mesh.localToWorld.changed.add(meshLocalToWorldChangedHandler);
}
private function meshRemovedFromSceneHandler(mesh : Mesh,
scene : Scene) : void
{
scene.bindings.removeCallback('worldToScreen', worldToViewChangedHandler);
mesh.localToWorld.changed.remove(meshLocalToWorldChangedHandler);
}
private function worldToViewChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _visibilityData.frustumCulling;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(
geom.boundingBox._vertices,
_boundingBox._vertices
);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE, TMP_VECTOR4);
_boundingSphere.update(
center,
geom.boundingSphere.radius * Math.max(scale.x, scale.y, scale.z)
);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _visibilityData.frustumCulling;
if (culling != FrustumCulling.DISABLED && _mesh.geometry.boundingBox)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.cameraData.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_visibilityData.inFrustum = true;
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_visibilityData.inFrustum = false;
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
var clone : VisibilityController = new VisibilityController();
clone._visibilityData = _visibilityData.clone() as MeshVisibilityDataProvider;
return clone;
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.data.MeshVisibilityDataProvider;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class VisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _visibilityData : MeshVisibilityDataProvider;
public function get visible() : Boolean
{
return _visibilityData.visible;
}
public function set visible(value : Boolean) : void
{
_visibilityData.visible = value;
}
public function get frustumCulling() : uint
{
return _visibilityData.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibilityData.frustumCulling = value;
}
public function get insideFrustum() : Boolean
{
return _visibilityData.inFrustum;
}
public function VisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_visibilityData = new MeshVisibilityDataProvider();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : VisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.addedToScene.add(meshAddedToSceneHandler);
target.removedFromScene.add(meshRemovedFromSceneHandler);
target.bindings.addProvider(_visibilityData);
if (target.root is Scene)
meshAddedToSceneHandler(target, target.root as Scene);
}
private function targetRemovedHandler(ctrl : VisibilityController,
target : Mesh) : void
{
_mesh = null;
target.addedToScene.remove(meshAddedToSceneHandler);
target.removedFromScene.remove(meshRemovedFromSceneHandler);
target.bindings.removeProvider(_visibilityData);
if (target.root is Scene)
meshRemovedFromSceneHandler(target, target.root as Scene);
}
private function meshAddedToSceneHandler(mesh : Mesh,
scene : Scene) : void
{
scene.bindings.addCallback('worldToScreen', worldToViewChangedHandler);
mesh.localToWorld.changed.add(meshLocalToWorldChangedHandler);
}
private function meshRemovedFromSceneHandler(mesh : Mesh,
scene : Scene) : void
{
scene.bindings.removeCallback('worldToScreen', worldToViewChangedHandler);
mesh.localToWorld.changed.remove(meshLocalToWorldChangedHandler);
}
private function worldToViewChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _visibilityData.frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(
geom.boundingBox._vertices,
_boundingBox._vertices
);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE, TMP_VECTOR4);
_boundingSphere.update(
center,
geom.boundingSphere.radius * Math.max(scale.x, scale.y, scale.z)
);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _visibilityData.frustumCulling;
if (culling != FrustumCulling.DISABLED && _mesh.geometry.boundingBox)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.cameraData.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_visibilityData.inFrustum = true;
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_visibilityData.inFrustum = false;
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
var clone : VisibilityController = new VisibilityController();
clone._visibilityData = _visibilityData.clone() as MeshVisibilityDataProvider;
return clone;
}
}
}
|
fix VisibilityController null pointer exception when Geometry.boundingSphere or Geometry.boundingBox is null
|
fix VisibilityController null pointer exception when Geometry.boundingSphere or Geometry.boundingBox is null
|
ActionScript
|
mit
|
aerys/minko-as3
|
3b4e2466cfdda4f02be34a2cf62e4ce1ca30ac48
|
src/aerys/minko/render/material/environment/EnvironmentMappingProperties.as
|
src/aerys/minko/render/material/environment/EnvironmentMappingProperties.as
|
package aerys.minko.render.material.environment
{
public final class EnvironmentMappingProperties
{
public static const ENVIRONMENT_MAP : String = 'environmentMappingEnvironmentMap';
public static const ENVIRONMENT_MAP_FILTERING : String = 'environmentMappingEnvironmentMapFiltering';
public static const ENVIRONMENT_MAP_MIPMAPPING : String = 'environmentMappingEnvironmentMapMipMapping';
public static const ENVIRONMENT_MAP_WRAPPING : String = 'environmentMappingEnvironmentMapWrapping';
public static const ENVIRONMENT_MAP_FORMAT : String = 'environmentMappingEnvironmentMapFormat';
public static const ENVIRONMENT_BLENDING : String = 'environmentMappingBlending';
public static const ENVIRONMENT_MAPPING_TYPE : String = 'environmentMappingType';
public static const REFLECTIVITY : String = 'environmentMappingReflectivity';
}
}
|
package aerys.minko.render.material.environment
{
public final class EnvironmentMappingProperties
{
public static const ENVIRONMENT_MAP : String = 'environmentMap';
public static const ENVIRONMENT_MAP_FILTERING : String = 'environmentMapFiltering';
public static const ENVIRONMENT_MAP_MIPMAPPING : String = 'environmentMapMipMapping';
public static const ENVIRONMENT_MAP_WRAPPING : String = 'environmentMapWrapping';
public static const ENVIRONMENT_MAP_FORMAT : String = 'environmentMapFormat';
public static const ENVIRONMENT_BLENDING : String = 'environmentMappingBlending';
public static const ENVIRONMENT_MAPPING_TYPE : String = 'environmentMappingType';
public static const REFLECTIVITY : String = 'environmentMappingReflectivity';
}
}
|
rename EnvironmentMappingProperties.environmentMappingEnvironmentMap to EnvironmentMappingProperties.environmentMap for consistency (and because it was really long to type...)
|
rename EnvironmentMappingProperties.environmentMappingEnvironmentMap to EnvironmentMappingProperties.environmentMap for consistency (and because it was really long to type...)
|
ActionScript
|
mit
|
aerys/minko-as3
|
d921b210f558f7258b5e659c219650111ca50925
|
src/stdio/StandardProcess.as
|
src/stdio/StandardProcess.as
|
package stdio {
import flash.display.*
import flash.events.*
import flash.utils.*
import flash.net.*
public class StandardProcess implements Process {
private const buffered_stdin: BufferedStream = new BufferedStream
private const stdin_socket: SocketStream = new SocketStream
private const readline_socket: SocketStream = new SocketStream
private const stdout_socket: SocketStream = new SocketStream
private const stderr_socket: SocketStream = new SocketStream
private var _env: Object
private var _prompt: String = "> "
public function StandardProcess(env: Object) {
_env = env
}
public function initialize(callback: Function): void {
if (available) {
connect(callback)
} else {
callback()
}
}
public function get available(): Boolean {
return env["stdio.enabled"]
}
private function get http_url(): String {
return env["stdio.http"]
}
private function get interactive(): Boolean {
return env["stdio.interactive"] === "true"
}
private function connect(callback: Function): void {
stdin_socket.onopen = onopen
readline_socket.onopen = onopen
stdout_socket.onopen = onopen
stderr_socket.onopen = onopen
var n: int = 0
function onopen(): void {
if (++n === 3) {
callback()
}
}
stdin_socket.ondata = buffered_stdin.write
stdin_socket.onclose = buffered_stdin.close
readline_socket.ondata = buffered_stdin.write
readline_socket.onclose = buffered_stdin.close
const stdin_port: int = get_int("stdio.in")
const readline_port: int = get_int("stdio.readline")
if (interactive) {
readline_socket.connect("localhost", readline_port)
} else {
stdin_socket.connect("localhost", stdin_port)
}
const stdout_port: int = get_int("stdio.out")
const stderr_port: int = get_int("stdio.err")
stdout_socket.connect("localhost", stdout_port)
stderr_socket.connect("localhost", stderr_port)
function get_int(name: String): int {
return parseInt(env[name])
}
}
//----------------------------------------------------------------
public function get env(): * {
return _env
}
public function get argv(): Array {
return env["stdio.argv"].split(" ").map(
function (argument: String, ...rest: Array): String {
return decodeURIComponent(argument)
}
)
}
public function puts(value: *): void {
if (available) {
if (interactive) {
readline_socket.puts("!" + value)
} else {
stdout.puts(value)
}
} else {
debug.show("puts: " + value)
}
}
public function warn(value: *): void {
if (available) {
stderr.puts(value)
} else {
debug.show("warn: " + value)
}
}
public function die(value: *): void {
if (available) {
warn(value); exit(-1)
} else {
throw new Error("fatal error: " + String(value))
}
}
public function style(styles: String, string: String): String {
const codes: Object = {
none: 0, bold: 1, italic: 3, underline: 4, inverse: 7,
black: 30, red: 31, green: 32, yellow: 33, blue: 34,
magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90
}
if (styles === "") {
return string
} else {
return styles.split(/\s+/).map(
function (style: String, ...rest: Array): String {
if (style in codes) {
return escape_sequence(codes[style])
} else {
throw new Error("style not supported: " + style)
}
}
).join("") + string + escape_sequence(0)
}
function escape_sequence(code: int): String {
return "\x1b[" + code + "m"
}
}
public function gets(callback: Function): void {
if (available) {
if (interactive) {
readline_socket.puts("?" + _prompt)
}
stdin.gets(callback)
} else {
callback(null)
}
}
public function set prompt(value: String): void {
_prompt = value
}
public function get stdin(): InputStream {
return buffered_stdin
}
public function get stdout(): OutputStream {
return stdout_socket
}
public function get stderr(): OutputStream {
return stderr_socket
}
public function handle(error: *): void {
if (error is UncaughtErrorEvent) {
UncaughtErrorEvent(error).preventDefault()
handle(UncaughtErrorEvent(error).error)
die("run-swf: uncaught error")
} else if (error is Error) {
// Important: Avoid the `Error(x)` casting syntax.
http_post("/error", (error as Error).getStackTrace())
} else if (error is ErrorEvent) {
http_post("/error", (error as ErrorEvent).text)
} else {
http_post("/error", String(error))
}
}
private function shell_quote(word: String): String {
if (/^[-=.,\w]+$/.test(word)) {
return word
} else {
return "'" + word.replace(/'/g, "'\\''") + "'"
}
}
public function shell(
command: *,
callback: Function,
errback: Function = null
): void {
if (available) {
if (command is Array) {
command = command.map(
function (word: String, ...rest: Array): String {
return shell_quote(word)
}
).join(" ")
}
http_post("/shell", command, function (data: String): void {
const result: XML = new XML(data)
const status: int = result.@status
const stdout: String = result.stdout.text()
const stderr: String = result.stderr.text()
if (status === 0) {
if (callback.length === 1) {
callback(stdout)
} else {
callback(stdout, stderr)
}
} else if (errback === null) {
warn(stderr)
} else if (errback.length === 1) {
errback(status)
} else if (errback.length === 2) {
errback(status, stderr)
} else {
errback(status, stderr, stdout)
}
})
} else {
throw new Error("cannot execute command: process not available")
}
}
public function exit(status: int = 0): void {
if (available) {
when_ready(function (): void {
http_post("/exit", String(status))
})
} else {
throw new Error("cannot exit: process not available")
}
}
//----------------------------------------------------------------
private var n_pending_requests: int = 0
private var ready_callbacks: Array = []
private function when_ready(callback: Function): void {
if (n_pending_requests === 0) {
callback()
} else {
ready_callbacks.push(callback)
}
}
private function handle_ready(): void {
for each (var callback: Function in ready_callbacks) {
callback()
}
ready_callbacks = []
}
private function http_post(
path: String, content: String, callback: Function = null
): void {
const request: URLRequest = new URLRequest(http_url + path)
request.method = "POST"
request.data = content
const loader: URLLoader = new URLLoader
++n_pending_requests
loader.addEventListener(
Event.COMPLETE,
function (event: Event): void {
if (callback !== null) {
callback(loader.data)
}
if (--n_pending_requests === 0) {
handle_ready()
}
}
)
loader.load(request)
}
}
}
|
package stdio {
import flash.display.*
import flash.events.*
import flash.utils.*
import flash.net.*
public class StandardProcess implements Process {
private const buffered_stdin: BufferedStream = new BufferedStream
private const stdin_socket: SocketStream = new SocketStream
private const readline_socket: SocketStream = new SocketStream
private const stdout_socket: SocketStream = new SocketStream
private const stderr_socket: SocketStream = new SocketStream
private var _env: Object
private var _prompt: String = "> "
public function StandardProcess(env: Object) {
_env = env
}
public function initialize(callback: Function): void {
if (available) {
connect(callback)
} else {
callback()
}
}
public function get available(): Boolean {
return env["stdio.enabled"]
}
private function get http_url(): String {
return env["stdio.http"]
}
private function get interactive(): Boolean {
return env["stdio.interactive"] === "true"
}
private function connect(callback: Function): void {
stdin_socket.onopen = onopen
readline_socket.onopen = onopen
stdout_socket.onopen = onopen
stderr_socket.onopen = onopen
var n: int = 0
function onopen(): void {
if (++n === 3) {
callback()
}
}
stdin_socket.ondata = buffered_stdin.write
stdin_socket.onclose = buffered_stdin.close
readline_socket.ondata = buffered_stdin.write
readline_socket.onclose = buffered_stdin.close
const stdin_port: int = get_int("stdio.in")
const readline_port: int = get_int("stdio.readline")
if (interactive) {
readline_socket.connect("localhost", readline_port)
} else {
stdin_socket.connect("localhost", stdin_port)
}
const stdout_port: int = get_int("stdio.out")
const stderr_port: int = get_int("stdio.err")
stdout_socket.connect("localhost", stdout_port)
stderr_socket.connect("localhost", stderr_port)
function get_int(name: String): int {
return parseInt(env[name])
}
}
//----------------------------------------------------------------
public function get env(): * {
return _env
}
public function get argv(): Array {
if (env["stdio.argv"] === "") {
return []
} else {
return env["stdio.argv"].split(" ").map(
function (argument: String, ...rest: Array): String {
return decodeURIComponent(argument)
}
)
}
}
public function puts(value: *): void {
if (available) {
if (interactive) {
readline_socket.puts("!" + value)
} else {
stdout.puts(value)
}
} else {
debug.show("puts: " + value)
}
}
public function warn(value: *): void {
if (available) {
stderr.puts(value)
} else {
debug.show("warn: " + value)
}
}
public function die(value: *): void {
if (available) {
warn(value); exit(-1)
} else {
throw new Error("fatal error: " + String(value))
}
}
public function style(styles: String, string: String): String {
const codes: Object = {
none: 0, bold: 1, italic: 3, underline: 4, inverse: 7,
black: 30, red: 31, green: 32, yellow: 33, blue: 34,
magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90
}
if (styles === "") {
return string
} else {
return styles.split(/\s+/).map(
function (style: String, ...rest: Array): String {
if (style in codes) {
return escape_sequence(codes[style])
} else {
throw new Error("style not supported: " + style)
}
}
).join("") + string + escape_sequence(0)
}
function escape_sequence(code: int): String {
return "\x1b[" + code + "m"
}
}
public function gets(callback: Function): void {
if (available) {
if (interactive) {
readline_socket.puts("?" + _prompt)
}
stdin.gets(callback)
} else {
callback(null)
}
}
public function set prompt(value: String): void {
_prompt = value
}
public function get stdin(): InputStream {
return buffered_stdin
}
public function get stdout(): OutputStream {
return stdout_socket
}
public function get stderr(): OutputStream {
return stderr_socket
}
public function handle(error: *): void {
if (error is UncaughtErrorEvent) {
UncaughtErrorEvent(error).preventDefault()
handle(UncaughtErrorEvent(error).error)
die("run-swf: uncaught error")
} else if (error is Error) {
// Important: Avoid the `Error(x)` casting syntax.
http_post("/error", (error as Error).getStackTrace())
} else if (error is ErrorEvent) {
http_post("/error", (error as ErrorEvent).text)
} else {
http_post("/error", String(error))
}
}
private function shell_quote(word: String): String {
if (/^[-=.,\w]+$/.test(word)) {
return word
} else {
return "'" + word.replace(/'/g, "'\\''") + "'"
}
}
public function shell(
command: *,
callback: Function,
errback: Function = null
): void {
if (available) {
if (command is Array) {
command = command.map(
function (word: String, ...rest: Array): String {
return shell_quote(word)
}
).join(" ")
}
http_post("/shell", command, function (data: String): void {
const result: XML = new XML(data)
const status: int = result.@status
const stdout: String = result.stdout.text()
const stderr: String = result.stderr.text()
if (status === 0) {
if (callback.length === 1) {
callback(stdout)
} else {
callback(stdout, stderr)
}
} else if (errback === null) {
warn(stderr)
} else if (errback.length === 1) {
errback(status)
} else if (errback.length === 2) {
errback(status, stderr)
} else {
errback(status, stderr, stdout)
}
})
} else {
throw new Error("cannot execute command: process not available")
}
}
public function exit(status: int = 0): void {
if (available) {
when_ready(function (): void {
http_post("/exit", String(status))
})
} else {
throw new Error("cannot exit: process not available")
}
}
//----------------------------------------------------------------
private var n_pending_requests: int = 0
private var ready_callbacks: Array = []
private function when_ready(callback: Function): void {
if (n_pending_requests === 0) {
callback()
} else {
ready_callbacks.push(callback)
}
}
private function handle_ready(): void {
for each (var callback: Function in ready_callbacks) {
callback()
}
ready_callbacks = []
}
private function http_post(
path: String, content: String, callback: Function = null
): void {
const request: URLRequest = new URLRequest(http_url + path)
request.method = "POST"
request.data = content
const loader: URLLoader = new URLLoader
++n_pending_requests
loader.addEventListener(
Event.COMPLETE,
function (event: Event): void {
if (callback !== null) {
callback(loader.data)
}
if (--n_pending_requests === 0) {
handle_ready()
}
}
)
loader.load(request)
}
}
}
|
Make `process.argv` be [] when no arguments are given.
|
Make `process.argv` be [] when no arguments are given.
|
ActionScript
|
mit
|
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
|
4c4ceb025238c142fa3377b618eb12314e75d739
|
src/aerys/minko/scene/node/camera/Camera.as
|
src/aerys/minko/scene/node/camera/Camera.as
|
package aerys.minko.scene.node.camera
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.data.CameraDataProvider;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
import aerys.minko.type.math.Vector4;
import flash.geom.Point;
use namespace minko_scene;
public class Camera extends AbstractCamera
{
public static const DEFAULT_FOV : Number = Math.PI * .25;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
public function get fieldOfView() : Number
{
return _cameraData.fieldOfView;
}
public function set fieldOfView(value : Number) : void
{
_cameraData.fieldOfView = value;
}
public function Camera(fieldOfView : Number = DEFAULT_FOV,
zNear : Number = AbstractCamera.DEFAULT_ZNEAR,
zFar : Number = AbstractCamera.DEFAULT_ZFAR)
{
super(zNear, zFar);
_cameraData.fieldOfView = fieldOfView;
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Camera = new Camera(fieldOfView, zNear, zFar);
clone.transform.copyFrom(this.transform);
return clone as AbstractSceneNode;
}
override public function unproject(x : Number, y : Number, out : Ray = null) : Ray
{
if (!(root is Scene))
throw new Error('Camera must be in the scene to unproject vectors.');
out ||= new Ray();
var sceneBindings : DataBindings = (root as Scene).bindings;
var zNear : Number = _cameraData.zNear;
var zFar : Number = _cameraData.zFar;
var fovDiv2 : Number = _cameraData.fieldOfView * 0.5;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var xPercent : Number = 2.0 * (x / width - 0.5);
var yPercent : Number = 2.0 * (y / height - 0.5);
var dx : Number = Math.tan(fovDiv2) * xPercent * (width / height);
var dy : Number = -Math.tan(fovDiv2) * yPercent;
out.origin.set(dx * zNear, dy * zNear, zNear);
out.direction.set(dx * zNear, dy * zNear, zNear).normalize();
localToWorld(out.origin, out.origin);
localToWorld(out.direction, out.direction, true);
return out;
}
override public function project(localToWorld : Matrix4x4, output : Point = null) : Point
{
output ||= new Point();
var sceneBindings : DataBindings = (root as Scene).bindings;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var translation : Vector4 = localToWorld.getTranslation();
var screenPosition : Vector4 = _cameraData.worldToScreen.projectVector(
translation, TMP_VECTOR4
);
output.x = width * ((screenPosition.x + 1.0) * .5);
output.y = height * ((1.0 - ((screenPosition.y + 1.0) * .5)));
return output;
}
}
}
|
package aerys.minko.scene.node.camera
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.data.CameraDataProvider;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
import aerys.minko.type.math.Vector4;
import flash.geom.Point;
use namespace minko_scene;
public class Camera extends AbstractCamera
{
public static const DEFAULT_FOV : Number = Math.PI * .25;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
public function get fieldOfView() : Number
{
return _cameraData.fieldOfView;
}
public function set fieldOfView(value : Number) : void
{
_cameraData.fieldOfView = value;
}
public function Camera(fieldOfView : Number = DEFAULT_FOV,
zNear : Number = AbstractCamera.DEFAULT_ZNEAR,
zFar : Number = AbstractCamera.DEFAULT_ZFAR)
{
super(zNear, zFar);
_cameraData.fieldOfView = fieldOfView;
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Camera = new Camera(fieldOfView, zNear, zFar);
clone.transform.copyFrom(this.transform);
return clone as AbstractSceneNode;
}
override public function unproject(x : Number, y : Number, out : Ray = null) : Ray
{
if (!(root is Scene))
throw new Error('Camera must be in the scene to unproject vectors.');
out ||= new Ray();
var sceneBindings : DataBindings = (root as Scene).bindings;
var zNear : Number = _cameraData.zNear;
var zFar : Number = _cameraData.zFar;
var fovDiv2 : Number = _cameraData.fieldOfView * 0.5;
var width : Number = sceneBindings.propertyExists('viewportWidth')
? sceneBindings.getProperty('viewportWidth')
: 0.;
var height : Number = sceneBindings.propertyExists('viewportHeight')
? sceneBindings.getProperty('viewportHeight')
: 0.;
var xPercent : Number = 2.0 * (x / width - 0.5);
var yPercent : Number = 2.0 * (y / height - 0.5);
var dx : Number = Math.tan(fovDiv2) * xPercent * (width / height);
var dy : Number = -Math.tan(fovDiv2) * yPercent;
out.origin.set(dx * zNear, dy * zNear, zNear);
out.direction.set(dx * zNear, dy * zNear, zNear).normalize();
localToWorld(out.origin, out.origin);
localToWorld(out.direction, out.direction, true);
return out;
}
override public function project(localToWorld : Matrix4x4, output : Point = null) : Point
{
output ||= new Point();
var sceneBindings : DataBindings = (root as Scene).bindings;
var width : Number = sceneBindings.getProperty('viewportWidth');
var height : Number = sceneBindings.getProperty('viewportHeight');
var translation : Vector4 = localToWorld.getTranslation();
var screenPosition : Vector4 = _cameraData.worldToScreen.projectVector(
translation, TMP_VECTOR4
);
output.x = width * ((screenPosition.x + 1.0) * .5);
output.y = height * ((1.0 - ((screenPosition.y + 1.0) * .5)));
return output;
}
}
}
|
use 0 as default value when viewportWidth/viewportHeight is not defined in the scene bindings
|
use 0 as default value when viewportWidth/viewportHeight is not defined in the scene bindings
|
ActionScript
|
mit
|
aerys/minko-as3
|
72188f8f12cafad938e45089e51d7b8ecf72d45c
|
src/aerys/minko/render/shader/Shader.as
|
src/aerys/minko/render/shader/Shader.as
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_render;
import aerys.minko.ns.minko_shader;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.shader.compiler.graph.ShaderGraph;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import flash.utils.getQualifiedClassName;
import aerys.minko.type.binding.Signature;
import aerys.minko.type.binding.ShaderDataBindingsProxy;
use namespace minko_shader;
/**
* The base class to extend in order to create ActionScript shaders
* and program the GPU using AS3.
*
* @author Jean-Marc Le Roux
* @author Romain Gilliotte
*
* @see aerys.minko.render.shader.ShaderPart
* @see aerys.minko.render.shader.ShaderInstance
* @see aerys.minko.render.shader.ShaderSignature
* @see aerys.minko.render.shader.ShaderDataBindings
*/
public class Shader extends ShaderPart
{
use namespace minko_shader;
use namespace minko_render;
minko_shader var _meshBindings : ShaderDataBindingsProxy = null;
minko_shader var _sceneBindings : ShaderDataBindingsProxy = null;
minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[];
private var _name : String = null;
private var _enabled : Boolean = true;
private var _defaultSettings : ShaderSettings = new ShaderSettings(null);
private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[];
private var _numActiveInstances : uint = 0;
private var _numRenderedInstances : uint = 0;
private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[];
private var _programs : Vector.<Program3DResource> = new <Program3DResource>[];
private var _begin : Signal = new Signal('Shader.begin');
private var _end : Signal = new Signal('Shader.end');
/**
* The name of the shader. Default value is the qualified name of the
* ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader").
*
* @return
*
*/
public function get name() : String
{
return _name;
}
public function set name(value : String) : void
{
_name = value;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very first time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get begin() : Signal
{
return _begin;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very last time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get end() : Signal
{
return _end;
}
/**
* Whether the shader (and all its forks) are enabled for rendering
* or not.
*
* @return
*
*/
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
/**
*
* @param priority Default value is 0.
* @param renderTarget Default value is null.
*
*/
public function Shader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(this);
_defaultSettings.renderTarget = renderTarget;
_defaultSettings.priority = priority;
_name = getQualifiedClassName(this);
}
public function fork(sceneBindings : DataBindings,
meshBindings : DataBindings) : ShaderInstance
{
var pass : ShaderInstance = findPass(sceneBindings, meshBindings);
if (pass == null)
{
var signature : Signature = new Signature();
var config : ShaderSettings = findOrCreateSettings(sceneBindings, meshBindings);
signature.mergeWith(config.signature);
var program : Program3DResource = null;
if (config.enabled)
{
program = findOrCreateProgram(sceneBindings, meshBindings);
signature.mergeWith(program.signature);
}
pass = new ShaderInstance(this, config, program, signature);
pass.retained.add(shaderInstanceRetainedHandler);
pass.released.add(shaderInstanceReleasedHandler);
_instances.push(pass);
}
return pass;
}
public function disposeUnusedResources() : void
{
var numInstances : uint = _instances.length;
var currentId : uint = 0;
for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId)
{
var passInstance : ShaderInstance = _instances[instanceId];
if (!passInstance.isDisposable)
_instances[currentId++] = passInstance;
}
_instances.length = currentId;
}
/**
* Override this method to initialize the settings
* - such as the blending operands or the triangle culling - of the shader.
* This values can be read from both the mesh and the scene bindings.
*
* @param settings
*
* @see aerys.minko.render.shader.ShaderSettings
*
*/
protected function initializeSettings(settings : ShaderSettings) : void
{
// nothing
}
/**
* The getVertexPosition() method is called to evaluate the vertex shader
* program that shall be executed on the GPU.
*
* @return The position of the vertex in clip space (normalized screen space).
*
*/
protected function getVertexPosition() : SFloat
{
throw new Error("The method 'getVertexPosition' must be implemented.");
}
/**
* The getPixelColor() method is called to evaluate the fragment shader
* program that shall be executed on the GPU.
*
* @return The color of the pixel on the screen.
*
*/
protected function getPixelColor() : SFloat
{
throw new Error("The method 'getPixelColor' must be implemented.");
}
private function findPass(sceneBindings : DataBindings,
meshBindings : DataBindings) : ShaderInstance
{
var numPasses : int = _instances.length;
for (var passId : uint = 0; passId < numPasses; ++passId)
if (_instances[passId].signature.isValid(sceneBindings, meshBindings))
return _instances[passId];
return null;
}
private function findOrCreateProgram(sceneBindings : DataBindings,
meshBindings : DataBindings) : Program3DResource
{
var numPrograms : int = _programs.length;
var program : Program3DResource;
for (var programId : uint = 0; programId < numPrograms; ++programId)
if (_programs[programId].signature.isValid(sceneBindings, meshBindings))
return _programs[programId];
var signature : Signature = new Signature();
_meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE);
var vertexPosition : AbstractNode = getVertexPosition()._node;
var pixelColor : AbstractNode = getPixelColor()._node;
var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills);
program = shaderGraph.generateProgram(_name, signature);
_meshBindings = null;
_sceneBindings = null;
_kills.length = 0;
_programs.push(program);
return program;
}
private function findOrCreateSettings(sceneBindings : DataBindings,
meshBindings : DataBindings) : ShaderSettings
{
var numConfigs : int = _settings.length;
var config : ShaderSettings = null;
for (var configId : int = 0; configId < numConfigs; ++configId)
if (_settings[configId].signature.isValid(sceneBindings, meshBindings))
return _settings[configId];
var signature : Signature = new Signature();
config = _defaultSettings.clone(signature);
_meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE);
initializeSettings(config);
_meshBindings = null;
_sceneBindings = null;
_settings.push(config);
return config;
}
private function shaderInstanceRetainedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 1)
{
++_numActiveInstances;
instance.begin.add(shaderInstanceBeginHandler);
instance.end.add(shaderInstanceEndHandler);
}
}
private function shaderInstanceReleasedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 0)
{
--_numActiveInstances;
instance.begin.remove(shaderInstanceBeginHandler);
instance.end.remove(shaderInstanceEndHandler);
}
}
private function shaderInstanceBeginHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
if (_numRenderedInstances == 0)
_begin.execute(this, context, backBuffer);
}
private function shaderInstanceEndHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
_numRenderedInstances++;
if (_numRenderedInstances == _numActiveInstances)
{
_numRenderedInstances = 0;
_end.execute(this, context, backBuffer);
}
}
}
}
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_render;
import aerys.minko.ns.minko_shader;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.shader.compiler.graph.ShaderGraph;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.part.ShaderPart;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import flash.utils.getQualifiedClassName;
import aerys.minko.type.binding.Signature;
import aerys.minko.type.binding.ShaderDataBindingsProxy;
use namespace minko_shader;
/**
* The base class to extend in order to create ActionScript shaders
* and program the GPU using AS3.
*
* @author Jean-Marc Le Roux
* @author Romain Gilliotte
*
* @see aerys.minko.render.shader.ShaderPart
* @see aerys.minko.render.shader.ShaderInstance
* @see aerys.minko.render.shader.ShaderSignature
* @see aerys.minko.render.shader.ShaderDataBindings
*/
public class Shader extends ShaderPart
{
use namespace minko_shader;
use namespace minko_render;
minko_shader var _meshBindings : ShaderDataBindingsProxy = null;
minko_shader var _sceneBindings : ShaderDataBindingsProxy = null;
minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[];
private var _name : String = null;
private var _enabled : Boolean = true;
private var _defaultSettings : ShaderSettings = new ShaderSettings(null);
private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[];
private var _numActiveInstances : uint = 0;
private var _numRenderedInstances : uint = 0;
private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[];
private var _programs : Vector.<Program3DResource> = new <Program3DResource>[];
private var _begin : Signal = new Signal('Shader.begin');
private var _end : Signal = new Signal('Shader.end');
/**
* The name of the shader. Default value is the qualified name of the
* ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader").
*
* @return
*
*/
public function get name() : String
{
return _name;
}
public function set name(value : String) : void
{
_name = value;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very first time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get begin() : Signal
{
return _begin;
}
/**
* The signal executed when the shader (one of its forks) is used
* for rendering for the very last time during the current frame.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>shader : Shader, the shader executing the signal</li>
* <li>context : Context3D, the context used for rendering</li>
* <li>backBuffer : RenderTarget, the render target used as the back-buffer</li>
* </ul>
*
* @return
*
*/
public function get end() : Signal
{
return _end;
}
/**
* Whether the shader (and all its forks) are enabled for rendering
* or not.
*
* @return
*
*/
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
}
/**
*
* @param priority Default value is 0.
* @param renderTarget Default value is null.
*
*/
public function Shader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(this);
_defaultSettings.renderTarget = renderTarget;
_defaultSettings.priority = priority;
_name = getQualifiedClassName(this);
}
public function fork(sceneBindings : DataBindings,
meshBindings : DataBindings) : ShaderInstance
{
var pass : ShaderInstance = findPass(sceneBindings, meshBindings);
if (!pass)
{
var signature : Signature = new Signature();
var config : ShaderSettings = findOrCreateSettings(
sceneBindings, meshBindings
);
signature.mergeWith(config.signature);
var program : Program3DResource = null;
if (config.enabled)
{
program = findOrCreateProgram(sceneBindings, meshBindings);
signature.mergeWith(program.signature);
}
pass = new ShaderInstance(this, config, program, signature);
pass.retained.add(shaderInstanceRetainedHandler);
pass.released.add(shaderInstanceReleasedHandler);
_instances.push(pass);
}
return pass;
}
public function disposeUnusedResources() : void
{
var numInstances : uint = _instances.length;
var currentId : uint = 0;
for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId)
{
var passInstance : ShaderInstance = _instances[instanceId];
if (!passInstance.isDisposable)
_instances[currentId++] = passInstance;
}
_instances.length = currentId;
}
/**
* Override this method to initialize the settings
* - such as the blending operands or the triangle culling - of the shader.
* This values can be read from both the mesh and the scene bindings.
*
* @param settings
*
* @see aerys.minko.render.shader.ShaderSettings
*
*/
protected function initializeSettings(settings : ShaderSettings) : void
{
// nothing
}
/**
* The getVertexPosition() method is called to evaluate the vertex shader
* program that shall be executed on the GPU.
*
* @return The position of the vertex in clip space (normalized screen space).
*
*/
protected function getVertexPosition() : SFloat
{
throw new Error("The method 'getVertexPosition' must be implemented.");
}
/**
* The getPixelColor() method is called to evaluate the fragment shader
* program that shall be executed on the GPU.
*
* @return The color of the pixel on the screen.
*
*/
protected function getPixelColor() : SFloat
{
throw new Error("The method 'getPixelColor' must be implemented.");
}
private function findPass(sceneBindings : DataBindings,
meshBindings : DataBindings) : ShaderInstance
{
var numPasses : int = _instances.length;
for (var passId : uint = 0; passId < numPasses; ++passId)
if (_instances[passId].signature.isValid(sceneBindings, meshBindings))
return _instances[passId];
return null;
}
private function findOrCreateProgram(sceneBindings : DataBindings,
meshBindings : DataBindings) : Program3DResource
{
var numPrograms : int = _programs.length;
var program : Program3DResource;
for (var programId : uint = 0; programId < numPrograms; ++programId)
if (_programs[programId].signature.isValid(sceneBindings, meshBindings))
return _programs[programId];
var signature : Signature = new Signature();
_meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE);
var vertexPosition : AbstractNode = getVertexPosition()._node;
var pixelColor : AbstractNode = getPixelColor()._node;
var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills);
program = shaderGraph.generateProgram(_name, signature);
_meshBindings = null;
_sceneBindings = null;
_kills.length = 0;
_programs.push(program);
return program;
}
private function findOrCreateSettings(sceneBindings : DataBindings,
meshBindings : DataBindings) : ShaderSettings
{
var numConfigs : int = _settings.length;
var config : ShaderSettings = null;
for (var configId : int = 0; configId < numConfigs; ++configId)
if (_settings[configId].signature.isValid(sceneBindings, meshBindings))
return _settings[configId];
var signature : Signature = new Signature();
config = _defaultSettings.clone(signature);
_meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH);
_sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE);
initializeSettings(config);
_meshBindings = null;
_sceneBindings = null;
_settings.push(config);
return config;
}
private function shaderInstanceRetainedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 1)
{
++_numActiveInstances;
instance.begin.add(shaderInstanceBeginHandler);
instance.end.add(shaderInstanceEndHandler);
}
}
private function shaderInstanceReleasedHandler(instance : ShaderInstance,
numUses : uint) : void
{
if (numUses == 0)
{
--_numActiveInstances;
instance.begin.remove(shaderInstanceBeginHandler);
instance.end.remove(shaderInstanceEndHandler);
}
}
private function shaderInstanceBeginHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
if (_numRenderedInstances == 0)
_begin.execute(this, context, backBuffer);
}
private function shaderInstanceEndHandler(instance : ShaderInstance,
context : Context3DResource,
backBuffer : RenderTarget) : void
{
_numRenderedInstances++;
if (_numRenderedInstances == _numActiveInstances)
{
_numRenderedInstances = 0;
_end.execute(this, context, backBuffer);
}
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
f135e411298bd1f83d71fef80cdfc0c7877e06a3
|
microphone/src/test/flex/TestApp.as
|
microphone/src/test/flex/TestApp.as
|
package {
import com.marstonstudio.crossusermedia.encoder.Encoder;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.utils.ByteArray;
import mx.core.ByteArrayAsset;
import mx.core.UIComponent;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertTrue;
import org.flexunit.async.Async;
import org.fluint.uiImpersonation.UIImpersonator;
public class TestApp {
public function TestApp() {}
[Embed(source="../resources/audio.pcm",mimeType="application/octet-stream")]
public var AudioPcm:Class;
public var container:DisplayObjectContainer;
[Before(async,ui)]
public function initialize():void {
trace("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
trace("test::start " + new Date().toLocaleString());
trace("");
container = new UIComponent();
Async.proceedOnEvent(this, container, Event.ADDED_TO_STAGE, 100);
UIImpersonator.addChild(container);
}
[Test(description="Load audio asset")]
public function testAudioLoad():void {
var audioPcmAsset:ByteArrayAsset = new AudioPcm();
assertTrue("embedded bytesAvailable", audioPcmAsset.bytesAvailable > 0);
assertNotNull(container.stage);
const sampleRate:int = 16000;
const format:String = 'f32be';
const bitRate:int = 32000;
var encoder:Encoder = new Encoder(container);
encoder.init(format, sampleRate, format, sampleRate, bitRate);
encoder.load(audioPcmAsset);
var output:ByteArray = encoder.flush();
assertTrue("outputSampleRate set to " + sampleRate, encoder.getOutputSampleRate() == sampleRate);
assertTrue("outputFormat set to " + format, encoder.getOutputFormat() == format);
assertTrue("outputLength = audioPcmAsset.length = " + audioPcmAsset.length, encoder.getOutputLength() == audioPcmAsset.length);
assertTrue("output.length = audioPcmAsset.length = " + audioPcmAsset.length, output.length == audioPcmAsset.length);
encoder.dispose(0);
}
[After]
public function finalize():void {
UIImpersonator.removeAllChildren();
container = null;
trace("");
trace("test::complete " + new Date().toLocaleString());
trace("=======================================================");
}
}
}
|
package {
import com.marstonstudio.crossusermedia.encoder.Encoder;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import mx.core.ByteArrayAsset;
import mx.core.UIComponent;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertTrue;
import org.flexunit.async.Async;
import org.fluint.uiImpersonation.UIImpersonator;
public class TestApp {
public function TestApp() {}
[Embed(source="../resources/audio.pcm",mimeType="application/octet-stream")]
public var AudioPcm:Class;
public var container:DisplayObjectContainer;
[Before(async,ui)]
public function initialize():void {
trace("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
trace("test::start " + new Date().toLocaleString());
trace("");
container = new UIComponent();
Async.proceedOnEvent(this, container, Event.ADDED_TO_STAGE, 100);
UIImpersonator.addChild(container);
}
[Test(description="Load audio asset")]
public function testAudioLoad():void {
var audioPcmAsset:ByteArrayAsset = new AudioPcm();
assertTrue("embedded bytesAvailable", audioPcmAsset.bytesAvailable > 0);
assertNotNull(container.stage);
const sampleRate:int = 16000;
const format:String = 'f32be';
const bitRate:int = 32000;
var encoder:Encoder = new Encoder(container);
encoder.init(format, sampleRate, format, sampleRate, bitRate);
encoder.load(audioPcmAsset);
var output:ByteArray = encoder.flush();
assertTrue("outputSampleRate set to " + sampleRate, encoder.getOutputSampleRate() == sampleRate);
assertTrue("outputFormat set to " + format, encoder.getOutputFormat() == format);
assertTrue("outputLength = audioPcmAsset.length = " + audioPcmAsset.length, encoder.getOutputLength() == audioPcmAsset.length);
assertTrue("output.length = audioPcmAsset.length = " + audioPcmAsset.length, output.length == audioPcmAsset.length);
//give stdout buffer a chance to catch up before terminating
sleep(1000);
encoder.dispose(0);
}
[After]
public function finalize():void {
UIImpersonator.removeAllChildren();
container = null;
trace("");
trace("test::complete " + new Date().toLocaleString());
trace("=======================================================");
}
private function sleep(ms:int):void {
var init:int = getTimer();
while(true) {
if(getTimer() - init >= ms) {
break;
}
}
}
}
}
|
add sleep to test for console output
|
add sleep to test for console output
|
ActionScript
|
mit
|
marstonstudio/crossUserMedia,marstonstudio/crossUserMedia,marstonstudio/crossUserMedia,marstonstudio/crossUserMedia,marstonstudio/crossUserMedia
|
a5fa3cbf800b5e133dd4582a31437b7a1d56816a
|
src/com/esri/builder/controllers/PortalController.as
|
src/com/esri/builder/controllers/PortalController.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 com.esri.builder.controllers
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.components.supportClasses.Credential;
import com.esri.ags.events.IdentityManagerEvent;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.supportClasses.URLUtil;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
public class PortalController
{
private static const LOG:ILogger = LogUtil.createLogger(PortalController);
private var lastUsedCultureCode:String;
private var portal:Portal = PortalModel.getInstance().portal;
public function PortalController()
{
AppEvent.addListener(AppEvent.SETTINGS_SAVED, settingsChangeHandler);
}
private function settingsChangeHandler(event:AppEvent):void
{
//optimization: AGO uses OAuth, so we register the OAuth info upfront
var portalModel:PortalModel = PortalModel.getInstance();
var portalURL:String = portalModel.portalURL;
if (portalModel.isAGO(portalURL))
{
portalModel.registerOAuthPortal(portalURL, Model.instance.cultureCode);
}
loadPortal(portalURL, Model.instance.cultureCode);
}
private function loadPortal(url:String, cultureCode:String):void
{
if (Log.isInfo())
{
LOG.info("Loading Portal");
}
if (url)
{
var hasPortalURLChanged:Boolean = (portal.url != url);
var hasCultureCodeChanged:Boolean = (lastUsedCultureCode != cultureCode);
if (hasPortalURLChanged || hasCultureCodeChanged)
{
if (Log.isDebug())
{
LOG.debug("Reloading Portal - URL: {0}, culture code: {1}", url, cultureCode);
}
if (hasPortalURLChanged)
{
portal.unload();
}
lastUsedCultureCode = cultureCode;
portal.culture = cultureCode;
portal.url = URLUtil.removeToken(url);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
portal.load();
}
}
else
{
unloadPortal();
dispatchPortalStatusUpdate();
}
}
private function identityManager_signInHandler(event:IdentityManagerEvent):void
{
if (PortalModel.getInstance().hasSameOrigin(event.credential.server)
&& !PortalModel.getInstance().portal.signedIn)
{
signIntoPortalInternally();
}
}
private function signIntoPortalInternally():void
{
AppEvent.removeListener(AppEvent.PORTAL_SIGN_IN, portalSignInHandler);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
portal.signIn();
}
private function portal_loadHandler(event:PortalEvent):void
{
if (Log.isDebug())
{
LOG.debug("Portal load success");
}
//do nothing, load successful
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
dispatchPortalStatusUpdate();
}
private function portal_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Portal load fault");
}
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
var fault:Fault = event.fault;
if (fault.faultCode == "403" && fault.faultString == "User not part of this account")
{
var credential:Credential = IdentityManager.instance.findCredential(portal.url);
if (credential)
{
credential.destroy();
}
AppEvent.dispatch(
AppEvent.SHOW_ERROR,
ResourceManager.getInstance().getString("BuilderStrings", "notOrgMember"));
}
else
{
dispatchPortalStatusUpdate();
}
}
private function unloadPortal():void
{
if (Log.isDebug())
{
LOG.debug("Unloading Portal");
}
portal.url = null;
portal.unload();
}
private function dispatchPortalStatusUpdate():void
{
updatePortalHandlersBasedOnStatus();
AppEvent.dispatch(AppEvent.PORTAL_STATUS_UPDATED);
}
private function updatePortalHandlersBasedOnStatus():void
{
if (portal.signedIn)
{
AppEvent.addListener(AppEvent.PORTAL_SIGN_OUT, portalSignOutHandler);
AppEvent.removeListener(AppEvent.PORTAL_SIGN_IN, portalSignInHandler);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
}
else
{
AppEvent.addListener(AppEvent.PORTAL_SIGN_IN, portalSignInHandler);
IdentityManager.instance.addEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
AppEvent.removeListener(AppEvent.PORTAL_SIGN_OUT, portalSignOutHandler);
}
}
private function portalSignOutHandler(event:AppEvent):void
{
if (Log.isInfo())
{
LOG.info("Portal sign out requested");
}
AppEvent.removeListener(AppEvent.PORTAL_SIGN_OUT, portalSignOutHandler);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
portal.signOut();
}
private function portalSignInHandler(event:AppEvent):void
{
if (Log.isInfo())
{
LOG.info("Portal sign in requested");
}
signIntoPortalInternally();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 com.esri.builder.controllers
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.components.supportClasses.Credential;
import com.esri.ags.events.IdentityManagerEvent;
import com.esri.ags.events.PortalEvent;
import com.esri.ags.portal.Portal;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.supportClasses.URLUtil;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.resources.ResourceManager;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;
public class PortalController
{
private static const LOG:ILogger = LogUtil.createLogger(PortalController);
private var lastUsedCultureCode:String;
private var portal:Portal = PortalModel.getInstance().portal;
public function PortalController()
{
AppEvent.addListener(AppEvent.SETTINGS_SAVED, settingsChangeHandler);
}
private function settingsChangeHandler(event:AppEvent):void
{
//optimization: AGO uses OAuth, so we register the OAuth info upfront
var portalModel:PortalModel = PortalModel.getInstance();
var portalURL:String = portalModel.portalURL;
var cultureCode:String = Model.instance.cultureCode;
if (portalModel.isAGO(portalURL))
{
portalModel.registerOAuthPortal(portalURL, cultureCode);
}
loadPortal(portalURL, cultureCode);
}
private function loadPortal(url:String, cultureCode:String):void
{
if (Log.isInfo())
{
LOG.info("Loading Portal");
}
if (url)
{
var hasPortalURLChanged:Boolean = (portal.url != url);
var hasCultureCodeChanged:Boolean = (lastUsedCultureCode != cultureCode);
if (hasPortalURLChanged || hasCultureCodeChanged)
{
if (Log.isDebug())
{
LOG.debug("Reloading Portal - URL: {0}, culture code: {1}", url, cultureCode);
}
if (hasPortalURLChanged)
{
portal.unload();
}
lastUsedCultureCode = cultureCode;
portal.culture = cultureCode;
portal.url = URLUtil.removeToken(url);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
portal.load();
}
}
else
{
unloadPortal();
dispatchPortalStatusUpdate();
}
}
private function identityManager_signInHandler(event:IdentityManagerEvent):void
{
if (PortalModel.getInstance().hasSameOrigin(event.credential.server)
&& !PortalModel.getInstance().portal.signedIn)
{
signIntoPortalInternally();
}
}
private function signIntoPortalInternally():void
{
AppEvent.removeListener(AppEvent.PORTAL_SIGN_IN, portalSignInHandler);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
portal.signIn();
}
private function portal_loadHandler(event:PortalEvent):void
{
if (Log.isDebug())
{
LOG.debug("Portal load success");
}
//do nothing, load successful
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
dispatchPortalStatusUpdate();
}
private function portal_faultHandler(event:FaultEvent):void
{
if (Log.isDebug())
{
LOG.debug("Portal load fault");
}
portal.removeEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.removeEventListener(FaultEvent.FAULT, portal_faultHandler);
var fault:Fault = event.fault;
if (fault.faultCode == "403" && fault.faultString == "User not part of this account")
{
var credential:Credential = IdentityManager.instance.findCredential(portal.url);
if (credential)
{
credential.destroy();
}
AppEvent.dispatch(
AppEvent.SHOW_ERROR,
ResourceManager.getInstance().getString("BuilderStrings", "notOrgMember"));
}
else
{
dispatchPortalStatusUpdate();
}
}
private function unloadPortal():void
{
if (Log.isDebug())
{
LOG.debug("Unloading Portal");
}
portal.url = null;
portal.unload();
}
private function dispatchPortalStatusUpdate():void
{
updatePortalHandlersBasedOnStatus();
AppEvent.dispatch(AppEvent.PORTAL_STATUS_UPDATED);
}
private function updatePortalHandlersBasedOnStatus():void
{
if (portal.signedIn)
{
AppEvent.addListener(AppEvent.PORTAL_SIGN_OUT, portalSignOutHandler);
AppEvent.removeListener(AppEvent.PORTAL_SIGN_IN, portalSignInHandler);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
}
else
{
AppEvent.addListener(AppEvent.PORTAL_SIGN_IN, portalSignInHandler);
IdentityManager.instance.addEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
AppEvent.removeListener(AppEvent.PORTAL_SIGN_OUT, portalSignOutHandler);
}
}
private function portalSignOutHandler(event:AppEvent):void
{
if (Log.isInfo())
{
LOG.info("Portal sign out requested");
}
AppEvent.removeListener(AppEvent.PORTAL_SIGN_OUT, portalSignOutHandler);
IdentityManager.instance.removeEventListener(IdentityManagerEvent.SIGN_IN, identityManager_signInHandler);
portal.addEventListener(PortalEvent.LOAD, portal_loadHandler);
portal.addEventListener(FaultEvent.FAULT, portal_faultHandler);
portal.signOut();
}
private function portalSignInHandler(event:AppEvent):void
{
if (Log.isInfo())
{
LOG.info("Portal sign in requested");
}
signIntoPortalInternally();
}
}
}
|
Clean up.
|
Clean up.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
c4d3c65d748ec3d4c1e461e8e2a8ea0bc672d588
|
src/org/mangui/hls/HLSJS.as
|
src/org/mangui/hls/HLSJS.as
|
package org.mangui.hls
{
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import org.hola.JSAPI;
import org.hola.HSettings;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.model.Level;
import org.mangui.hls.model.Fragment;
import flash.utils.setTimeout;
import flash.net.NetStreamAppendBytesAction;
public class HLSJS
{
private static var _inited: Boolean = false;
private static var _duration: Number;
private static var _bandwidth: Number = -1;
private static var _url: String;
private static var _currentFrag: String;
private static var _state: String;
private static var _hls: HLS;
private static var _silence: Boolean = false;
public static function init():void{
if (_inited || !ZExternalInterface.avail())
return;
_inited = true;
JSAPI.init();
ExternalInterface.addCallback("hola_version", hola_version);
ExternalInterface.addCallback("hola_hls_version", hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url",
hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position",
hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration",
hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec",
hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state",
hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_current_fragment",
hola_hls_get_current_fragment);
ExternalInterface.addCallback("hola_hls_get_levels",
hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_levels_async",
hola_hls_get_levels_async);
ExternalInterface.addCallback("hola_hls_get_segment_info",
hola_hls_get_segment_info);
ExternalInterface.addCallback("hola_hls_get_level",
hola_hls_get_level);
ExternalInterface.addCallback("hola_hls_get_bitrate",
hola_hls_get_bitrate);
ExternalInterface.addCallback("hola_hls_get_decoded_frames",
hola_hls_get_decoded_frames);
ExternalInterface.addCallback("hola_setBandwidth",
hola_setBandwidth);
ExternalInterface.addCallback("hola_hls_setBandwidth",
hola_setBandwidth);
ExternalInterface.addCallback("hola_hls_get_type",
hola_hls_get_type);
ExternalInterface.addCallback("hola_hls_load_fragment", hola_hls_load_fragment);
ExternalInterface.addCallback("hola_hls_abort_fragment", hola_hls_abort_fragment);
ExternalInterface.addCallback("hola_hls_load_level", hola_hls_load_level);
ExternalInterface.addCallback('hola_hls_flush_stream', hola_hls_flush_stream);
}
public static function HLSnew(hls:HLS):void{
_hls = hls;
_state = HLSPlayStates.IDLE;
// track duration events
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_playlist_duration_updated);
// track playlist-url/state
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_playback_state);
hls.addEventListener(HLSEvent.SEEK_STATE, on_seek_state);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_manifest_loaded);
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_manifest_loading);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_fragment_loading);
// notify js events
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_event);
hls.addEventListener(HLSEvent.MANIFEST_PARSED, on_event);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING_ABORTED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADED, on_level_loaded);
hls.addEventListener(HLSEvent.LEVEL_SWITCH, on_event);
hls.addEventListener(HLSEvent.LEVEL_ENDLIST, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED,
on_event);
hls.addEventListener(HLSEvent.FRAGMENT_PLAYING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_SKIPPED, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.TAGS_LOADED, on_event);
hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.WARNING, on_event);
hls.addEventListener(HLSEvent.ERROR, on_event);
hls.addEventListener(HLSEvent.MEDIA_TIME, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_event);
hls.addEventListener(HLSEvent.STREAM_TYPE_DID_CHANGE, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, on_event);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_event);
hls.addEventListener(HLSEvent.ID3_UPDATED, on_event);
hls.addEventListener(HLSEvent.FPS_DROP, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH,
on_event);
hls.addEventListener(HLSEvent.LIVE_LOADING_STALLED, on_event);
JSAPI.postMessage('flashls.hlsNew');
}
public static function HLSdispose(hls:HLS):void{
JSAPI.postMessage('flashls.hlsDispose');
_duration = 0;
_bandwidth = -1;
_url = null;
_state = HLSPlayStates.IDLE;
_hls = null;
}
public static function get bandwidth():Number{
return HSettings.gets('mode')=='adaptive' ? _bandwidth : -1;
}
private static function on_manifest_loaded(e:HLSEvent):void{
_duration = e.levels[_hls.startLevel].duration;
}
private static function on_playlist_duration_updated(e:HLSEvent):void{
_duration = e.duration;
}
private static function on_fragment_loading(e: HLSEvent): void
{
_currentFrag = e.url;
}
private static function on_manifest_loading(e:HLSEvent):void{
_url = e.url;
_state = "LOADING";
on_event(new HLSEvent(HLSEvent.PLAYBACK_STATE, _state));
}
private static function on_playback_state(e:HLSEvent):void{
_state = e.state;
}
private static function on_level_loaded(e: HLSEvent): void
{
JSAPI.postMessage('flashls.'+e.type, {level: level_to_object(_hls.levels[e.loadMetrics.level])});
}
private static function on_seek_state(e: HLSEvent): void
{
JSAPI.postMessage('flashls.'+e.type, {state: e.state, seek_pos: _hls.position, buffer: _hls.stream.bufferLength});
}
private static function on_event(e: HLSEvent): void
{
if (_silence)
return;
JSAPI.postMessage('flashls.'+e.type, {url: e.url, level: e.level,
duration: e.duration, levels: e.levels, error: e.error,
loadMetrics: e.loadMetrics, playMetrics: e.playMetrics,
mediatime: e.mediatime, state: e.state,
audioTrack: e.audioTrack, streamType: e.streamType});
}
private static function hola_version(): Object
{
return {
flashls_version: '0.4.4.20',
patch_version: '2.0.14'
};
}
private static function hola_hls_get_video_url(): String
{
return _url;
}
private static function hola_hls_get_position(): Number
{
return _hls.position;
}
private static function hola_hls_get_duration(): Number
{
return _duration;
}
private static function hola_hls_get_decoded_frames(): Number
{
return _hls.stream.decodedFrames;
}
private static function hola_hls_get_buffer_sec(): Number
{
return _hls.stream.bufferLength;
}
private static function hola_hls_get_state(): String
{
return _state;
}
private static function hola_hls_get_type(): String
{
return _hls.type;
}
private static function hola_hls_load_fragment(level: Number, frag: Number, url: String): Object
{
if (HSettings.gets('mode')!='hola_adaptive')
return 0;
return _hls.loadFragment(level, frag, url);
}
private static function hola_hls_flush_stream(): void
{
if (_hls.stream.decodedFrames === 0)
return;
_silence = true;
_hls.stream.close();
_hls.stream.play();
_hls.stream.pause();
_silence = false;
}
private static function hola_hls_abort_fragment(ldr_id: String): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
_hls.abortFragment(ldr_id);
}
private static function hola_hls_load_level(level: Number): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
if (!_hls.isStartLevelSet())
_hls.startLevel = level;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, level));
}
private static function level_to_object(l: Level): Object
{
var fragments: Array = [];
for (var i: int = 0; i<l.fragments.length; i++)
{
var fragment: Fragment = l.fragments[i];
fragments.push({url: fragment.url,
duration: fragment.duration, seqnum: fragment.seqnum});
}
return {url: l.url, bitrate: l.bitrate, fragments: fragments,
index: l.index, width: l.width, height: l.height, audio: l.audio};
}
private static function hola_hls_get_levels(): Object
{
var levels: Vector.<Object> = new Vector.<Object>(_hls.levels.length);
for (var i: int = 0; i<_hls.levels.length; i++)
{
var l: Level = _hls.levels[i];
// no fragments returned, use get_segment_info for fragm.info
levels[i] = Object({url: l.url, bitrate: l.bitrate,
index: l.index, fragments: []});
}
return levels;
}
private static function hola_hls_get_current_fragment(): String
{
return _currentFrag;
}
private static function hola_hls_get_levels_async(): void
{
setTimeout(function(): void
{
var levels: Array = [];
for (var i: int = 0; i<_hls.levels.length; i++)
levels.push(level_to_object(_hls.levels[i]));
JSAPI.postMessage('flashls.hlsAsyncMessage', {type: 'get_levels', msg: levels});
}, 0);
}
private static function hola_hls_get_segment_info(url: String): Object
{
for (var i: int = 0; i<_hls.levels.length; i++)
{
var l: Level = _hls.levels[i];
for (var j:int = 0; j<l.fragments.length; j++)
{
if (url==l.fragments[j].url)
{
return Object({fragment: l.fragments[j],
level: Object({url: l.url, bitrate: l.bitrate,
index: l.index})});
}
}
}
return undefined;
}
private static function hola_hls_get_bitrate(): Number
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].bitrate : 0;
}
private static function hola_hls_get_level(): String
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].url : undefined;
}
private static function hola_setBandwidth(bandwidth: Number): void
{
_bandwidth = bandwidth;
}
}
}
|
package org.mangui.hls
{
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import org.hola.JSAPI;
import org.hola.HSettings;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.model.Level;
import org.mangui.hls.model.Fragment;
import flash.utils.setTimeout;
import flash.net.NetStreamAppendBytesAction;
public class HLSJS
{
private static var _inited: Boolean = false;
private static var _duration: Number;
private static var _bandwidth: Number = -1;
private static var _url: String;
private static var _currentFrag: String;
private static var _state: String;
private static var _hls: HLS;
private static var _silence: Boolean = false;
public static function init():void{
if (_inited || !ZExternalInterface.avail())
return;
_inited = true;
JSAPI.init();
ExternalInterface.addCallback("hola_version", hola_version);
ExternalInterface.addCallback("hola_hls_version", hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url",
hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position",
hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration",
hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec",
hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state",
hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_current_fragment",
hola_hls_get_current_fragment);
ExternalInterface.addCallback("hola_hls_get_levels",
hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_levels_async",
hola_hls_get_levels_async);
ExternalInterface.addCallback("hola_hls_get_segment_info",
hola_hls_get_segment_info);
ExternalInterface.addCallback("hola_hls_get_level",
hola_hls_get_level);
ExternalInterface.addCallback("hola_hls_get_bitrate",
hola_hls_get_bitrate);
ExternalInterface.addCallback("hola_hls_get_decoded_frames",
hola_hls_get_decoded_frames);
ExternalInterface.addCallback("hola_setBandwidth",
hola_setBandwidth);
ExternalInterface.addCallback("hola_hls_setBandwidth",
hola_setBandwidth);
ExternalInterface.addCallback("hola_hls_get_type",
hola_hls_get_type);
ExternalInterface.addCallback("hola_hls_load_fragment", hola_hls_load_fragment);
ExternalInterface.addCallback("hola_hls_abort_fragment", hola_hls_abort_fragment);
ExternalInterface.addCallback("hola_hls_load_level", hola_hls_load_level);
ExternalInterface.addCallback('hola_hls_flush_stream', hola_hls_flush_stream);
}
public static function HLSnew(hls:HLS):void{
_hls = hls;
_state = HLSPlayStates.IDLE;
// track duration events
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_playlist_duration_updated);
// track playlist-url/state
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_playback_state);
hls.addEventListener(HLSEvent.SEEK_STATE, on_seek_state);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_manifest_loaded);
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_manifest_loading);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_fragment_loading);
// notify js events
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_event);
hls.addEventListener(HLSEvent.MANIFEST_PARSED, on_event);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING_ABORTED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADED, on_level_loaded);
hls.addEventListener(HLSEvent.LEVEL_SWITCH, on_event);
hls.addEventListener(HLSEvent.LEVEL_ENDLIST, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED,
on_event);
hls.addEventListener(HLSEvent.FRAGMENT_PLAYING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_SKIPPED, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.TAGS_LOADED, on_event);
hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.WARNING, on_event);
hls.addEventListener(HLSEvent.ERROR, on_event);
hls.addEventListener(HLSEvent.MEDIA_TIME, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_event);
hls.addEventListener(HLSEvent.STREAM_TYPE_DID_CHANGE, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, on_event);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_event);
hls.addEventListener(HLSEvent.ID3_UPDATED, on_event);
hls.addEventListener(HLSEvent.FPS_DROP, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH,
on_event);
hls.addEventListener(HLSEvent.LIVE_LOADING_STALLED, on_event);
JSAPI.postMessage('flashls.hlsNew');
}
public static function HLSdispose(hls:HLS):void{
JSAPI.postMessage('flashls.hlsDispose');
_duration = 0;
_bandwidth = -1;
_url = null;
_state = HLSPlayStates.IDLE;
_hls = null;
}
public static function get bandwidth():Number{
return HSettings.gets('mode')=='adaptive' ? _bandwidth : -1;
}
private static function on_manifest_loaded(e:HLSEvent):void{
_duration = e.levels[_hls.startLevel].duration;
}
private static function on_playlist_duration_updated(e:HLSEvent):void{
_duration = e.duration;
}
private static function on_fragment_loading(e: HLSEvent): void
{
_currentFrag = e.url;
}
private static function on_manifest_loading(e:HLSEvent):void{
_url = e.url;
_state = "LOADING";
on_event(new HLSEvent(HLSEvent.PLAYBACK_STATE, _state));
}
private static function on_playback_state(e:HLSEvent):void{
_state = e.state;
}
private static function on_level_loaded(e: HLSEvent): void
{
JSAPI.postMessage('flashls.'+e.type, {level: level_to_object(_hls.levels[e.loadMetrics.level])});
}
private static function on_seek_state(e: HLSEvent): void
{
JSAPI.postMessage('flashls.'+e.type, {state: e.state, seek_pos: _hls.position, buffer: _hls.stream.bufferLength});
}
private static function on_event(e: HLSEvent): void
{
if (_silence)
return;
JSAPI.postMessage('flashls.'+e.type, {url: e.url, level: e.level,
duration: e.duration, levels: e.levels, error: e.error,
loadMetrics: e.loadMetrics, playMetrics: e.playMetrics,
mediatime: e.mediatime, state: e.state,
audioTrack: e.audioTrack, streamType: e.streamType});
}
private static function hola_version(): Object
{
return {
flashls_version: '0.4.4.20',
patch_version: '2.0.14'
};
}
private static function hola_hls_get_video_url(): String
{
return _url;
}
private static function hola_hls_get_position(): Number
{
return _hls.position;
}
private static function hola_hls_get_duration(): Number
{
return _duration;
}
private static function hola_hls_get_decoded_frames(): Number
{
return _hls.stream.decodedFrames;
}
private static function hola_hls_get_buffer_sec(): Number
{
return _hls.stream.bufferLength;
}
private static function hola_hls_get_state(): String
{
return _state;
}
private static function hola_hls_get_type(): String
{
return _hls.type;
}
private static function hola_hls_load_fragment(level: Number, frag: Number, url: String): Object
{
if (HSettings.gets('mode')!='hola_adaptive')
return 0;
return _hls.loadFragment(level, frag, url);
}
private static function hola_hls_flush_stream(): void
{
if (_hls.stream.decodedFrames === 0)
return;
_silence = true;
_hls.stream.close();
_hls.stream.play();
_hls.stream.pause();
_silence = false;
}
private static function hola_hls_abort_fragment(ldr_id: String): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
_hls.abortFragment(ldr_id);
}
private static function hola_hls_load_level(level: Number): void
{
if (HSettings.gets('mode')!='hola_adaptive')
return;
if (!_hls.isStartLevelSet())
_hls.startLevel = level;
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, level));
}
private static function level_to_object(l: Level): Object
{
var fragments: Array = [];
for (var i: int = 0; i<l.fragments.length; i++)
{
var fragment: Fragment = l.fragments[i];
fragments.push({url: fragment.url,
duration: fragment.duration, seqnum: fragment.seqnum});
}
return {url: l.url, bitrate: l.bitrate, fragments: fragments,
index: l.index, width: l.width, height: l.height, audio: l.audio};
}
private static function hola_hls_get_levels(): Object
{
var levels: Vector.<Object> = new Vector.<Object>(_hls.levels.length);
for (var i: int = 0; i<_hls.levels.length; i++)
{
var l: Level = _hls.levels[i];
// no fragments returned, use get_segment_info for fragm.info
levels[i] = Object({url: l.url, bitrate: l.bitrate,
index: l.index, fragments: [], width: l.width,
height: l.height});
}
return levels;
}
private static function hola_hls_get_current_fragment(): String
{
return _currentFrag;
}
private static function hola_hls_get_levels_async(): void
{
setTimeout(function(): void
{
var levels: Array = [];
for (var i: int = 0; i<_hls.levels.length; i++)
levels.push(level_to_object(_hls.levels[i]));
JSAPI.postMessage('flashls.hlsAsyncMessage', {type: 'get_levels', msg: levels});
}, 0);
}
private static function hola_hls_get_segment_info(url: String): Object
{
for (var i: int = 0; i<_hls.levels.length; i++)
{
var l: Level = _hls.levels[i];
for (var j:int = 0; j<l.fragments.length; j++)
{
if (url==l.fragments[j].url)
{
return Object({fragment: l.fragments[j],
level: Object({url: l.url, bitrate: l.bitrate,
index: l.index})});
}
}
}
return undefined;
}
private static function hola_hls_get_bitrate(): Number
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].bitrate : 0;
}
private static function hola_hls_get_level(): String
{
return _hls.loadLevel<_hls.levels.length ? _hls.levels[_hls.loadLevel].url : undefined;
}
private static function hola_setBandwidth(bandwidth: Number): void
{
_bandwidth = bandwidth;
}
}
}
|
add width and height to level object
|
add width and height to level object
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls
|
0eb21c9c5d821d3579f821e4533deb385729ad22
|
bin/Data/Scripts/Spawn.as
|
bin/Data/Scripts/Spawn.as
|
class Spawn: ScriptObject
{
String SpawnItem;
String SpawnName;
Spawn()
{
SpawnItem = "";
SpawnName = "";
}
void DelayedStart()
{
log.Debug(node.name + " spawning...");
Node@ parent = node.parent;
if (SpawnItem != "")
{
Node@ newNode = parent.CreateChild(SpawnName);
log.Debug("Create new node");
newNode.position = node.position;
newNode.scale = node.scale;
newNode.rotation = node.rotation;
log.Debug("loc=" + newNode.position.ToString() + ", rot=" + newNode.rotation.ToString() + ", scale=" + newNode.scale.ToString());
log.Debug("loc=" + node.position.ToString() + ", rot=" + node.rotation.ToString() + ", scale=" + node.scale.ToString());
XMLFile@ xmlFile = cache.GetResource("XMLFile", SpawnItem);
newNode.LoadXML(xmlFile.root);
node.Remove();
log.Debug("Remove self");
}
}
void Save(Serializer& serializer)
{
serializer.WriteString(SpawnItem);
serializer.WriteString(SpawnName);
}
void Load(Deserializer& deserializer)
{
log.Debug("Deserializing");
SpawnItem = deserializer.ReadString();
log.Debug("SpawnItem: " + SpawnItem);
SpawnName = deserializer.ReadString();
log.Debug("SpawnName: " + SpawnName);
}
void Stop()
{
}
}
|
class Spawn: ScriptObject
{
String SpawnItem;
String SpawnName;
Spawn()
{
SpawnItem = "";
SpawnName = "";
}
void DelayedStart()
{
log.Debug(node.name + " spawning...");
Node@ parent = node.parent;
if (SpawnItem != "")
{
Node@ newNode = parent.CreateChild(SpawnName);
log.Debug("Create new node");
XMLFile@ xmlFile = cache.GetResource("XMLFile", SpawnItem);
newNode.LoadXML(xmlFile.root);
newNode.position = node.position;
newNode.scale = node.scale;
newNode.rotation = node.rotation;
log.Debug("loc=" + newNode.position.ToString() + ", rot=" + newNode.rotation.ToString() + ", scale=" + newNode.scale.ToString());
log.Debug("loc=" + node.position.ToString() + ", rot=" + node.rotation.ToString() + ", scale=" + node.scale.ToString());
node.Remove();
log.Debug("Remove self");
}
}
void Save(Serializer& serializer)
{
serializer.WriteString(SpawnItem);
serializer.WriteString(SpawnName);
}
void Load(Deserializer& deserializer)
{
log.Debug("Deserializing");
SpawnItem = deserializer.ReadString();
log.Debug("SpawnItem: " + SpawnItem);
SpawnName = deserializer.ReadString();
log.Debug("SpawnName: " + SpawnName);
}
void Stop()
{
}
}
|
Correct minor bug with spawning system
|
Correct minor bug with spawning system
|
ActionScript
|
mit
|
leyarotheconquerer/on-off
|
6b2b9ecbbb74ebdabe7e12d8a54370568aace811
|
src/as/com/threerings/ezgame/client/EZGameConfigurator.as
|
src/as/com/threerings/ezgame/client/EZGameConfigurator.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import mx.core.UIComponent;
import mx.controls.CheckBox;
import mx.controls.ComboBox;
import mx.controls.HSlider;
import mx.controls.Label;
import com.threerings.util.StringUtil;
import com.threerings.flex.LabeledSlider;
import com.threerings.parlor.game.client.FlexGameConfigurator;
import com.threerings.ezgame.data.EZGameConfig;
/**
* Adds custom configuration of options specified in XML.
*/
public class EZGameConfigurator extends FlexGameConfigurator
{
/**
* Set a String of configData, which is hopefully XML formatted with
* some game configuration options.
*/
public function setXMLConfig (config :XML) :void
{
var log :Log = Log.getLog(this);
for each (var param :XML in config..params.children()) {
if (StringUtil.isBlank(param.@ident)) {
log.warning("Bad configuration option: no 'ident' in " +
param + ", ignoring.");
continue;
}
switch (param.localName().toLowerCase()) {
case "range":
addRangeOption(param, log);
break;
case "choice":
addChoiceOption(param, log);
break;
case "toggle":
addToggleOption(param, log);
break;
default:
log.warning("Unknown XML configuration option: " + param +
", ignoring.");
break;
}
}
}
/**
* Add a control that came from parsing our custom option XML.
*/
protected function addXMLControl (spec :XML, control :UIComponent) :void
{
var ident :String = String(spec.@ident);
var name :String = String(spec.@name);
var tip :String = String(spec.@tip);
if (StringUtil.isBlank(name)) {
name = ident;
}
var lbl :Label = new Label();
lbl.text = name + ":";
lbl.toolTip = tip;
control.toolTip = tip;
addControl(lbl, control);
_customConfigs.push(ident, control);
}
/**
* Adds a 'range' option specified in XML
*/
protected function addRangeOption (spec :XML, log :Log) :void
{
var min :Number = Number(spec.@minimum);
var max :Number = Number(spec.@maximum);
var start :Number = Number(spec.@start);
if (isNaN(min) || isNaN(max) || isNaN(start)) {
log.warning("Unable to parse range specification. " +
"Required numeric values: minimum, maximum, start " +
"[xml=" + spec + "].");
return;
}
var slider :HSlider = new HSlider();
slider.minimum = min;
slider.maximum = max;
slider.value = start;
slider.liveDragging = true;
slider.snapInterval = 1;
addXMLControl(spec, new LabeledSlider(slider));
}
/**
* Adds a 'choice' option specified in XML
*/
protected function addChoiceOption (spec :XML, log :Log) :void
{
if ([email protected] == 0 || [email protected] == 0) {
log.warning("Unable to parse choice specification. " +
"Required 'choices' or 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var choiceString :String = String(spec.@choices);
var start :String = String(spec.@start);
var choices :Array = choiceString.split(",");
var startDex :int = choices.indexOf(start);
if (startDex == -1) {
log.warning("Choice start value does not appear in list of choices "+
"[xml=" + spec + "].");
return;
}
var box :ComboBox = new ComboBox();
box.dataProvider = choices;
box.selectedIndex = startDex;
addXMLControl(spec, box);
}
/**
* Adds a 'toggle' option specified in XML
*/
protected function addToggleOption (spec :XML, log :Log) :void
{
if ([email protected] == 0) {
log.warning("Unable to parse toggle specification. " +
"Required 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var startStr :String = String(spec.@start).toLowerCase();
var box :CheckBox = new CheckBox();
box.selected = ("true" == startStr);
addXMLControl(spec, box);
}
override protected function flushGameConfig () :void
{
super.flushGameConfig();
// if there were any custom XML configs, flush those as well.
if (_customConfigs.length > 0) {
var options :Object = {};
for (var ii :int = 0; ii < _customConfigs.length; ii += 2) {
var ident :String = String(_customConfigs[ii]);
var control :UIComponent = (_customConfigs[ii + 1] as UIComponent);
if (control is LabeledSlider) {
options[ident] = (control as LabeledSlider).slider.value;
} else if (control is CheckBox) {
options[ident] = (control as CheckBox).selected;
} else if (control is ComboBox) {
options[ident] = (control as ComboBox).value;
} else {
Log.getLog(this).warning("Unknow custom config type " + control);
}
}
(_config as EZGameConfig).customConfig = options;
}
}
/** Contains pairs of identString, control, identString, control.. */
protected var _customConfigs :Array = [];
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import mx.core.UIComponent;
import mx.controls.CheckBox;
import mx.controls.ComboBox;
import mx.controls.HSlider;
import mx.controls.Label;
import com.threerings.util.StringUtil;
import com.threerings.flex.LabeledSlider;
import com.threerings.parlor.game.client.FlexGameConfigurator;
import com.threerings.ezgame.data.EZGameConfig;
/**
* Adds custom configuration of options specified in XML.
*/
public class EZGameConfigurator extends FlexGameConfigurator
{
/**
* Set XML game configuration options.
*/
public function setXMLConfig (config :XML) :void
{
var log :Log = Log.getLog(this);
for each (var param :XML in config..params.children()) {
if (StringUtil.isBlank(param.@ident)) {
log.warning("Bad configuration option: no 'ident' in " +
param + ", ignoring.");
continue;
}
switch (param.localName().toLowerCase()) {
case "range":
addRangeOption(param, log);
break;
case "choice":
addChoiceOption(param, log);
break;
case "toggle":
addToggleOption(param, log);
break;
default:
log.warning("Unknown XML configuration option: " + param +
", ignoring.");
break;
}
}
}
/**
* Add a control that came from parsing our custom option XML.
*/
protected function addXMLControl (spec :XML, control :UIComponent) :void
{
var ident :String = String(spec.@ident);
var name :String = String(spec.@name);
var tip :String = String(spec.@tip);
if (StringUtil.isBlank(name)) {
name = ident;
}
var lbl :Label = new Label();
lbl.text = name + ":";
lbl.toolTip = tip;
control.toolTip = tip;
addControl(lbl, control);
_customConfigs.push(ident, control);
}
/**
* Adds a 'range' option specified in XML
*/
protected function addRangeOption (spec :XML, log :Log) :void
{
var min :Number = Number(spec.@minimum);
var max :Number = Number(spec.@maximum);
var start :Number = Number(spec.@start);
if (isNaN(min) || isNaN(max) || isNaN(start)) {
log.warning("Unable to parse range specification. " +
"Required numeric values: minimum, maximum, start " +
"[xml=" + spec + "].");
return;
}
var slider :HSlider = new HSlider();
slider.minimum = min;
slider.maximum = max;
slider.value = start;
slider.liveDragging = true;
slider.snapInterval = 1;
addXMLControl(spec, new LabeledSlider(slider));
}
/**
* Adds a 'choice' option specified in XML
*/
protected function addChoiceOption (spec :XML, log :Log) :void
{
if ([email protected] == 0 || [email protected] == 0) {
log.warning("Unable to parse choice specification. " +
"Required 'choices' or 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var choiceString :String = String(spec.@choices);
var start :String = String(spec.@start);
var choices :Array = choiceString.split(",");
var startDex :int = choices.indexOf(start);
if (startDex == -1) {
log.warning("Choice start value does not appear in list of choices "+
"[xml=" + spec + "].");
return;
}
var box :ComboBox = new ComboBox();
box.dataProvider = choices;
box.selectedIndex = startDex;
addXMLControl(spec, box);
}
/**
* Adds a 'toggle' option specified in XML
*/
protected function addToggleOption (spec :XML, log :Log) :void
{
if ([email protected] == 0) {
log.warning("Unable to parse toggle specification. " +
"Required 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var startStr :String = String(spec.@start).toLowerCase();
var box :CheckBox = new CheckBox();
box.selected = ("true" == startStr);
addXMLControl(spec, box);
}
override protected function flushGameConfig () :void
{
super.flushGameConfig();
// if there were any custom XML configs, flush those as well.
if (_customConfigs.length > 0) {
var options :Object = {};
for (var ii :int = 0; ii < _customConfigs.length; ii += 2) {
var ident :String = String(_customConfigs[ii]);
var control :UIComponent = (_customConfigs[ii + 1] as UIComponent);
if (control is LabeledSlider) {
options[ident] = (control as LabeledSlider).slider.value;
} else if (control is CheckBox) {
options[ident] = (control as CheckBox).selected;
} else if (control is ComboBox) {
options[ident] = (control as ComboBox).value;
} else {
Log.getLog(this).warning("Unknow custom config type " + control);
}
}
(_config as EZGameConfig).customConfig = options;
}
}
/** Contains pairs of identString, control, identString, control.. */
protected var _customConfigs :Array = [];
}
}
|
update comment
|
update comment
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@250 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
9064db50a55e9e8a397aa11a4aefe01501b1dbca
|
Makefile.as
|
Makefile.as
|
# Makefile to rebuild SM64 split image
################ Target Executable and Sources ###############
# TARGET is used to specify prefix in all build artifacts including
# output ROM is $(TARGET).z64
TARGET = sm64
# BUILD_DIR is location where all build artifacts are placed
BUILD_DIR = build
##################### Compiler Options #######################
CROSS = mips64-elf-
AS = $(CROSS)as
LD = $(CROSS)ld
OBJDUMP = $(CROSS)objdump
OBJCOPY = $(CROSS)objcopy
ASFLAGS = -mtune=vr4300 -march=vr4300
LDFLAGS = -T $(LD_SCRIPT) -Map $(BUILD_DIR)/sm64.map
####################### Other Tools #########################
# N64 tools
TOOLS_DIR = .
MIO0TOOL = $(TOOLS_DIR)/mio0
N64CKSUM = $(TOOLS_DIR)/n64cksum
N64GRAPHICS = $(TOOLS_DIR)/n64graphics
EMULATOR = mupen64plus
EMU_FLAGS = --noosd
LOADER = loader64
LOADER_FLAGS = -vwf
######################## Targets #############################
default: all
# file dependencies generated by splitter
MAKEFILE_GEN = gen/Makefile.gen
include $(MAKEFILE_GEN)
all: $(TARGET).gen.z64
clean:
rm -f $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).o $(BUILD_DIR)/$(TARGET).bin $(TARGET).v64
$(MIO0_DIR)/%.mio0: $(MIO0_DIR)/%.bin
$(MIO0TOOL) $< $@
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
$(BUILD_DIR)/$(TARGET).o: gen/$(TARGET).s Makefile.as $(MAKEFILE_GEN) $(MIO0_FILES) $(LEVEL_FILES) | $(BUILD_DIR)
$(AS) $(ASFLAGS) -o $@ $<
$(BUILD_DIR)/$(TARGET).elf: $(BUILD_DIR)/$(TARGET).o $(LD_SCRIPT)
$(LD) $(LDFLAGS) -o $@ $< $(LIBS)
$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
$(OBJCOPY) $< $@ -O binary
# final z64 updates checksum
$(TARGET).gen.z64: $(BUILD_DIR)/$(TARGET).bin
$(N64CKSUM) $< $@
$(BUILD_DIR)/$(TARGET).gen.hex: $(TARGET).gen.z64
xxd $< > $@
$(BUILD_DIR)/$(TARGET).objdump: $(BUILD_DIR)/$(TARGET).elf
$(OBJDUMP) -D $< > $@
diff: $(BUILD_DIR)/$(TARGET).gen.hex
diff sm64.hex $< | wc -l
test: $(TARGET).gen.z64
$(EMULATOR) $(EMU_FLAGS) $<
load: $(TARGET).gen.z64
$(LOADER) $(LOADER_FLAGS) $<
.PHONY: all clean default diff test
|
# Makefile to rebuild SM64 split image
################ Target Executable and Sources ###############
# TARGET is used to specify prefix in all build artifacts including
# output ROM is $(TARGET).z64
TARGET = sm64
# BUILD_DIR is location where all build artifacts are placed
BUILD_DIR = build
##################### Compiler Options #######################
CROSS = mips64-elf-
AS = $(CROSS)as
CC = $(CROSS)gcc
LD = $(CROSS)ld
OBJDUMP = $(CROSS)objdump
OBJCOPY = $(CROSS)objcopy
ASFLAGS = -mtune=vr4300 -march=vr4300
CFLAGS = -Wall -O2 -mtune=vr4300 -march=vr4300 -G 0 -c
LDFLAGS = -T $(LD_SCRIPT) -Map $(BUILD_DIR)/sm64.map
####################### Other Tools #########################
# N64 tools
TOOLS_DIR = .
MIO0TOOL = $(TOOLS_DIR)/mio0
N64CKSUM = $(TOOLS_DIR)/n64cksum
N64GRAPHICS = $(TOOLS_DIR)/n64graphics
EMULATOR = mupen64plus
EMU_FLAGS = --noosd
LOADER = loader64
LOADER_FLAGS = -vwf
######################## Targets #############################
default: all
# file dependencies generated by splitter
MAKEFILE_GEN = gen/Makefile.gen
include $(MAKEFILE_GEN)
all: $(TARGET).gen.z64
clean:
rm -f $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).o $(BUILD_DIR)/$(TARGET).bin $(TARGET).v64
$(MIO0_DIR)/%.mio0: $(MIO0_DIR)/%.bin
$(MIO0TOOL) $< $@
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
$(BUILD_DIR)/$(TARGET).o: gen/$(TARGET).s Makefile.as $(MAKEFILE_GEN) $(MIO0_FILES) $(LEVEL_FILES) | $(BUILD_DIR)
$(AS) $(ASFLAGS) -o $@ $<
$(BUILD_DIR)/%.o: gen/%.c Makefile.as | $(BUILD_DIR)
$(CC) $(CFLAGS) -o $@ $<
$(BUILD_DIR)/$(TARGET).elf: $(BUILD_DIR)/$(TARGET).o $(LD_SCRIPT)
$(LD) $(LDFLAGS) -o $@ $< $(LIBS)
$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
$(OBJCOPY) $< $@ -O binary
# final z64 updates checksum
$(TARGET).gen.z64: $(BUILD_DIR)/$(TARGET).bin
$(N64CKSUM) $< $@
$(BUILD_DIR)/$(TARGET).gen.hex: $(TARGET).gen.z64
xxd $< > $@
$(BUILD_DIR)/$(TARGET).objdump: $(BUILD_DIR)/$(TARGET).elf
$(OBJDUMP) -D $< > $@
diff: $(BUILD_DIR)/$(TARGET).gen.hex
diff sm64.hex $< | wc -l
test: $(TARGET).gen.z64
$(EMULATOR) $(EMU_FLAGS) $<
load: $(TARGET).gen.z64
$(LOADER) $(LOADER_FLAGS) $<
.PHONY: all clean default diff test
|
Add MIPS C compiler flags and target to Makefile
|
Add MIPS C compiler flags and target to Makefile
|
ActionScript
|
mit
|
queueRAM/sm64tools,queueRAM/sm64tools
|
b23a0063d24910f462e016b35c5a0d9f280d5248
|
examples/ChartExample/src/products/Product.as
|
examples/ChartExample/src/products/Product.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 products
{
public class Product
{
public function Product(id:String,title:String,detail:Number,sales2013:Number, sales2014 ,image:String)
{
this.id = id;
this.title = title;
this.detail = detail;
this.sales2013 = sales2013;
this.sales2014 = sales2014;
this.image = image;
}
public var id:String;
public var title:String;
public var detail:Number;
public var image:String;
public var sales2013:Number;
public var sales2014:Number;
public function toString():String
{
return title;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 products
{
public class Product
{
public function Product(id:String, title:String, detail:Number,sales2013:Number, sales2014:Number ,image:String)
{
this.id = id;
this.title = title;
this.detail = detail;
this.sales2013 = sales2013;
this.sales2014 = sales2014;
this.image = image;
}
public var id:String;
public var title:String;
public var detail:Number;
public var image:String;
public var sales2013:Number;
public var sales2014:Number;
public function toString():String
{
return title;
}
}
}
|
Add missing type in Product.as
|
Add missing type in Product.as
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
71c9c38b6865d532294e093dcba693e43ed55c7d
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import aerys.minko.type.stream.format.VertexComponent;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuse() : SFloat
{
var diffuseColor : SFloat = null;
if (meshBindings.propertyExists('diffuseMap'))
{
var diffuseMap : SFloat = meshBindings.getTextureParameter(
'diffuseMap',
meshBindings.getConstant('diffuseFiltering', SamplerFiltering.LINEAR),
meshBindings.getConstant('diffuseMipMapping', SamplerMipMapping.LINEAR),
meshBindings.getConstant('diffuseWrapping', SamplerWrapping.REPEAT)
);
diffuseColor = sampleTexture(diffuseMap,interpolate(vertexUV.xy));
}
else if (meshBindings.propertyExists('diffuseColor'))
{
diffuseColor = meshBindings.getParameter('diffuseColor', 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
// Apply HLSA modifiers
if (meshBindings.propertyExists('diffuseColorMatrix'))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter('diffuseColorMatrix', 16)
);
}
return diffuseColor;
}
}
}
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuse() : SFloat
{
var diffuseColor : SFloat = null;
if (meshBindings.propertyExists('diffuseMap'))
{
var uv : SFloat = vertexUV.xy;
var diffuseMap : SFloat = meshBindings.getTextureParameter(
'diffuseMap',
meshBindings.getConstant('diffuseFiltering', SamplerFiltering.LINEAR),
meshBindings.getConstant('diffuseMipMapping', SamplerMipMapping.LINEAR),
meshBindings.getConstant('diffuseWrapping', SamplerWrapping.REPEAT)
);
if (meshBindings.propertyExists('diffuseUVScale'))
uv.scaleBy(meshBindings.getParameter('diffuseUVScale', 2));
if (meshBindings.propertyExists('diffuseUVOffset'))
uv.incrementBy(meshBindings.getParameter('diffuseUVOffset', 2));
diffuseColor = sampleTexture(diffuseMap,interpolate(uv));
}
else if (meshBindings.propertyExists('diffuseColor'))
{
diffuseColor = meshBindings.getParameter('diffuseColor', 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
// Apply HLSA modifiers
if (meshBindings.propertyExists('diffuseColorMatrix'))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter('diffuseColorMatrix', 16)
);
}
return diffuseColor;
}
}
}
|
Add support for properties 'diffuseUVOffset' and 'diffuseUVScale'.
|
Add support for properties 'diffuseUVOffset' and 'diffuseUVScale'.
|
ActionScript
|
mit
|
aerys/minko-as3
|
53c40a2fd4e759a71893b474368ff474fd832813
|
test/src/FRESteamWorksTest.as
|
test/src/FRESteamWorksTest.as
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
Steamworks.addOverlayWorkaround(stage, true);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp());
log("getFileCount() == "+Steamworks.getFileCount());
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt'));
log("getDLCCount() == " + Steamworks.getDLCCount());
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private var id:String;
private var handle:String;
private function onSteamResponse(e:SteamEvent):void{
var apiCall:Boolean;
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++) {
id = result.publishedFileId[i];
apiCall = Steamworks.getPublishedFileDetails(result.publishedFileId[i]);
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ") - " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnGetPublishedFileDetails:
log("RESPONSE_OnGetPublishedFileDetails: " + e.response);
var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id);
log("Result for " + id + ": " + res);
if(res) {
log("File: " + res.fileName + ", handle: " + res.fileHandle);
handle = res.fileHandle;
apiCall = Steamworks.UGCDownload(res.fileHandle, 0);
log("UGCDownload(...) == " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnUGCDownload:
log("RESPONSE_OnUGCDownload: " + e.response);
var ugcResult:DownloadUGCResult = Steamworks.getUGCDownloadResult(handle);
log("Result for " + handle + ": " + ugcResult);
if(ugcResult) {
log("File: " + ugcResult.fileName + ", handle: " + ugcResult.fileHandle + ", size: " + ugcResult.size);
var ba:ByteArray = new ByteArray();
ba.length = ugcResult.size;
apiCall = Steamworks.UGCRead(ugcResult.fileHandle, ugcResult.size, 0, ba);
log("UGCRead(...) == " + apiCall);
if(apiCall) {
log("Result length: " + ba.position + "//" + ba.length);
log("Result: " + ba.readUTFBytes(ugcResult.size));
}
break;
}
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xccccccc);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
addButton("List shared files", enumerateSharedFiles);
addButton("List workshop files", enumerateWorkshopFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
Steamworks.addOverlayWorkaround(stage, true);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp());
log("getFileCount() == "+Steamworks.getFileCount());
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt'));
log("getDLCCount() == " + Steamworks.getDLCCount());
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function enumerateSharedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
var userID:String = Steamworks.getUserID();
var res:Boolean = Steamworks.enumerateUserSharedWorkshopFiles(userID, 0, [], []);
log("enumerateSharedFiles(" + userID + ", 0, [], []) == " + res);
}
private function enumerateWorkshopFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.enumeratePublishedWorkshopFiles(
WorkshopConstants.ENUMTYPE_RankedByVote, 0, 10, 0, [], []);
log("enumerateSharedFiles(...) == " + res);
}
private var id:String;
private var handle:String;
private function onSteamResponse(e:SteamEvent):void{
var apiCall:Boolean;
var i:int;
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var subRes:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + subRes.resultsReturned + "/" + subRes.totalResults);
for(i = 0; i < subRes.resultsReturned; i++) {
id = subRes.publishedFileId[i];
apiCall = Steamworks.getPublishedFileDetails(subRes.publishedFileId[i]);
log(i + ": " + subRes.publishedFileId[i] + " (" + subRes.timeSubscribed[i] + ") - " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnEnumerateUserSharedWorkshopFiles:
log("RESPONSE_OnEnumerateUserSharedWorkshopFiles: " + e.response);
var userRes:UserFilesResult = Steamworks.enumerateUserSharedWorkshopFilesResult();
log("User shared files: " + userRes.resultsReturned + "/" + userRes.totalResults);
for(i = 0; i < userRes.resultsReturned; i++) {
log(i + ": " + userRes.publishedFileId[i]);
}
break;
case SteamConstants.RESPONSE_OnEnumeratePublishedWorkshopFiles:
log("RESPONSE_OnEnumeratePublishedWorkshopFiles: " + e.response);
var fileRes:WorkshopFilesResult = Steamworks.enumeratePublishedWorkshopFilesResult();
log("Workshop files: " + fileRes.resultsReturned + "/" + fileRes.totalResults);
for(i = 0; i < fileRes.resultsReturned; i++) {
log(i + ": " + fileRes.publishedFileId[i] + " - " + fileRes.score[i]);
}
break;
case SteamConstants.RESPONSE_OnGetPublishedFileDetails:
log("RESPONSE_OnGetPublishedFileDetails: " + e.response);
var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id);
log("Result for " + id + ": " + res);
if(res) {
log("File: " + res.fileName + ", handle: " + res.fileHandle);
handle = res.fileHandle;
apiCall = Steamworks.UGCDownload(res.fileHandle, 0);
log("UGCDownload(...) == " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnUGCDownload:
log("RESPONSE_OnUGCDownload: " + e.response);
var ugcResult:DownloadUGCResult = Steamworks.getUGCDownloadResult(handle);
log("Result for " + handle + ": " + ugcResult);
if(ugcResult) {
log("File: " + ugcResult.fileName + ", handle: " + ugcResult.fileHandle + ", size: " + ugcResult.size);
var ba:ByteArray = new ByteArray();
ba.length = ugcResult.size;
apiCall = Steamworks.UGCRead(ugcResult.fileHandle, ugcResult.size, 0, ba);
log("UGCRead(...) == " + apiCall);
if(apiCall) {
log("Result length: " + ba.position + "//" + ba.length);
log("Result: " + ba.readUTFBytes(ugcResult.size));
}
}
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xccccccc);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
Add tests for Enumerate{UserShared,Workshop}Files
|
Add tests for Enumerate{UserShared,Workshop}Files
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
4a760182ae1e768be771a70bc85f36af9d70cb2d
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/SimpleCSSStyles.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/SimpleCSSStyles.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core
{
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
/**
* The SimpleCSSStyles class contains CSS style
* properties supported by SimpleCSSValuesImpl.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleCSSStyles
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleCSSStyles()
{
super();
}
private var _object:IStyleableObject;
/**
* The object to which these styles apply.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get object():IStyleableObject
{
return _object;
}
/**
* @private
*/
public function set object(value:IStyleableObject):void
{
if (_object != value)
{
_object = value;
}
}
public var top:*;
public var bottom:*;
public var left:*;
public var right:*;
public var padding:*;
public var paddingLeft:*;
public var paddingRight:*;
public var paddingTop:*;
public var paddingBottom:*;
public var horizontalCenter:*;
public var verticalCenter:*;
public var horizontalAlign:*;
public var verticalAlign:*;
public var fontFamily:*;
public var fontSize:*;
public var color:*;
public var fontWeight:*;
public var fontStyle:*;
public var backgroundAlpha:*;
public var backgroundColor:*;
public var backgroundImage:*;
public var borderColor:*;
public var borderStyle:*;
public var borderRadius:*;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.core
{
import org.apache.flex.events.Event;
import org.apache.flex.events.EventDispatcher;
/**
* The SimpleCSSStyles class contains CSS style
* properties supported by SimpleCSSValuesImpl.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SimpleCSSStyles
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SimpleCSSStyles()
{
super();
}
private var _object:IStyleableObject;
/**
* The object to which these styles apply.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get object():IStyleableObject
{
return _object;
}
/**
* @private
*/
public function set object(value:IStyleableObject):void
{
if (_object != value)
{
_object = value;
}
}
public var top:*;
public var bottom:*;
public var left:*;
public var right:*;
public var padding:*;
public var paddingLeft:*;
public var paddingRight:*;
public var paddingTop:*;
public var paddingBottom:*;
public var margin:*;
public var marginLeft:*;
public var marginRight:*;
public var marginTop:*;
public var marginBottom:*;
public var horizontalCenter:*;
public var verticalCenter:*;
public var horizontalAlign:*;
public var verticalAlign:*;
public var fontFamily:*;
public var fontSize:*;
public var color:*;
public var fontWeight:*;
public var fontStyle:*;
public var backgroundAlpha:*;
public var backgroundColor:*;
public var backgroundImage:*;
public var borderColor:*;
public var borderStyle:*;
public var borderRadius:*;
}
}
|
add margin styles
|
add margin styles
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
08f6fd45fcb3247ff96077e4011fa64b66aab20b
|
as3/com/netease/protobuf/SimpleWebRPC.as
|
as3/com/netease/protobuf/SimpleWebRPC.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo ([email protected])
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.net.*;
import flash.utils.*;
import flash.events.*;
public final class SimpleWebRPC {
private var urlPrefix:String
public function SimpleWebRPC(urlPrefix:String) {
this.urlPrefix = urlPrefix;
}
private static const REF:Dictionary = new Dictionary();
public function send(qualifiedMethodName:String,
input:IExternalizable,
rpcResult:Function,
outputType:Class):void {
const loader:URLLoader = new URLLoader
REF[loader] = true;
loader.dataFormat = URLLoaderDataFormat.BINARY
loader.addEventListener(Event.COMPLETE, function(event:Event):void {
delete REF[loader]
const output:IExternalizable = new outputType
output.readExternal(loader.data)
rpcResult(output)
})
function errorEventHandler(event:Event):void {
delete REF[loader]
rpcResult(event)
}
loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler)
loader.addEventListener(
SecurityErrorEvent.SECURITY_ERROR, errorEventHandler)
const request:URLRequest = new URLRequest(
urlPrefix + qualifiedMethodName.replace(/\./, "/"))
request.method = URLRequestMethod.POST
const requestContent:ByteArray = new ByteArray
input.writeExternal(requestContent)
request.data = requestContent
request.contentType = "application/x-protobuf"
loader.load(request)
}
}
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo ([email protected])
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.net.*;
import flash.utils.*;
import flash.events.*;
public final class SimpleWebRPC {
private var urlPrefix:String
public function SimpleWebRPC(urlPrefix:String) {
this.urlPrefix = urlPrefix;
}
private static const REF:Dictionary = new Dictionary();
public function send(qualifiedMethodName:String,
input:IExternalizable,
rpcResult:Function,
outputType:Class):void {
const loader:URLLoader = new URLLoader
REF[loader] = true;
loader.dataFormat = URLLoaderDataFormat.BINARY
loader.addEventListener(Event.COMPLETE, function(event:Event):void {
delete REF[loader]
const output:IExternalizable = new outputType
output.readExternal(loader.data)
rpcResult(output)
})
function errorEventHandler(event:Event):void {
delete REF[loader]
rpcResult(event)
}
loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler)
loader.addEventListener(
SecurityErrorEvent.SECURITY_ERROR, errorEventHandler)
const request:URLRequest = new URLRequest(
urlPrefix + qualifiedMethodName.replace(/\./g, "/"))
request.method = URLRequestMethod.POST
const requestContent:ByteArray = new ByteArray
input.writeExternal(requestContent)
request.data = requestContent
request.contentType = "application/x-protobuf"
loader.load(request)
}
}
}
|
替换掉所有的 \.
|
替换掉所有的 \.
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
869d1ca794884f80642cc32ef2c451cff1f32f24
|
src/aerys/minko/type/math/Vector4.as
|
src/aerys/minko/type/math/Vector4.as
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
public static const FORWARD : Vector4 = Z_AXIS;
public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.);
public static const LEFT : Vector4 = new Vector4(-1, 0., 0.);
public static const RIGHT : Vector4 = new Vector4(1, 0., 0.);
public static const UP : Vector4 = Y_AXIS;
public static const DOWN : Vector4 = new Vector4(0, -1., 0.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
};
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1.)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.incrementBy(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.decrementBy(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
return out;
}
public function compareTo(v : Vector4, allFour : Boolean = false) : Boolean
{
return _vector.x == v._vector.x
&& _vector.y == v._vector.y
&& _vector.z == v._vector.z
&& (!allFour || (_vector.w == v._vector.w));
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public function copyFrom(source : Vector4) : Vector4
{
return set(source.x, source.y, source.z, source.w);
}
public function incrementBy(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function decrementBy(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function lerp(target : Vector4, ratio : Number) : Vector4
{
if (ratio == 1.)
return copyFrom(target);
if (ratio != 0.)
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
var w : Number = _vector.w;
set(
x + (target._vector.x - x) * ratio,
y + (target._vector.y - y) * ratio,
z + (target._vector.z - z) * ratio,
w + (target._vector.w - w) * ratio
);
}
return this;
}
public function equals(v : Vector4, allFour : Boolean = false, tolerance : Number = 0.) : Boolean
{
return tolerance
? _vector.nearEquals(v._vector, tolerance, allFour)
: _vector.equals(v._vector, allFour);
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.setTo(x, y, z);
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
return this;
}
public function toString() : String
{
return '(' + _vector.x + ', ' + _vector.y + ', ' + _vector.z + ', ' + _vector.w + ')';
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(v._vector.x * s, v._vector.y * s, v._vector.z * s, v._vector.w * s);
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this);
}
public function clone() : Vector4
{
return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w);
}
}
}
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
public static const FORWARD : Vector4 = Z_AXIS;
public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.);
public static const LEFT : Vector4 = new Vector4(-1, 0., 0.);
public static const RIGHT : Vector4 = new Vector4(1, 0., 0.);
public static const UP : Vector4 = Y_AXIS;
public static const DOWN : Vector4 = new Vector4(0, -1., 0.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
};
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1.)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.incrementBy(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out ||= new Vector4();
out.copyFrom(u);
return out.decrementBy(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
return out;
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public function copyFrom(source : Vector4) : Vector4
{
return set(source.x, source.y, source.z, source.w);
}
public function incrementBy(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function decrementBy(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function lerp(target : Vector4, ratio : Number) : Vector4
{
if (ratio == 1.)
return copyFrom(target);
if (ratio != 0.)
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
var w : Number = _vector.w;
set(
x + (target._vector.x - x) * ratio,
y + (target._vector.y - y) * ratio,
z + (target._vector.z - z) * ratio,
w + (target._vector.w - w) * ratio
);
}
return this;
}
public function equals(v : Vector4, allFour : Boolean = false, tolerance : Number = 0.) : Boolean
{
return tolerance
? _vector.nearEquals(v._vector, tolerance, allFour)
: _vector.equals(v._vector, allFour);
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.setTo(x, y, z);
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
return this;
}
public function toString() : String
{
return '(' + _vector.x + ', ' + _vector.y + ', ' + _vector.z + ', ' + _vector.w + ')';
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(v._vector.x * s, v._vector.y * s, v._vector.z * s, v._vector.w * s);
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this);
}
public function clone() : Vector4
{
return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w);
}
}
}
|
remove duplicate Vector4.compareTo() method, use Vector4.equals() instead
|
remove duplicate Vector4.compareTo() method, use Vector4.equals() instead
|
ActionScript
|
mit
|
aerys/minko-as3
|
ad09bec805a67d98e57e79deaee6cc98dd59d14b
|
src/as/com/threerings/util/Config.as
|
src/as/com/threerings/util/Config.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.events.NetStatusEvent;
import flash.events.EventDispatcher;
import flash.net.SharedObject;
import flash.net.SharedObjectFlushStatus;
/**
* Dispatched when this Config object has a value set on it.
*
* @eventType com.threerings.util.ConfigValueSetEvent.CONFIG_VALUE_SET
*/
[Event(name="ConfigValSet", type="com.threerings.util.ConfigValueSetEvent")]
public class Config extends EventDispatcher
{
/**
* Constructs a new config object which will obtain configuration
* information from the specified path.
*/
public function Config (path :String)
{
setPath(path);
}
public function setPath (path :String) :void
{
_so = (path == null) ? null : SharedObject.getLocal("config_" + path, "/");
_data = (_so == null) ? {} : _so.data;
// dispatch events for all settings
for (var n :String in _data) {
dispatchEvent(new ConfigValueSetEvent(n, _data[n]));
}
}
/**
* Fetches and returns the value for the specified configuration property.
*/
public function getValue (name :String, defValue :Object) :Object
{
var val :* = _data[name];
return (val === undefined) ? defValue : val;
}
/**
* Returns the value specified.
*/
public function setValue (name :String, value :Object) :void
{
_data[name] = value;
if (_so != null) {
_so.flush(); // flushing is not strictly necessary
}
// dispatch an event corresponding
dispatchEvent(new ConfigValueSetEvent(name, value));
}
/**
* Remove any set value for the specified preference.
* This does not dispatch an event because this would only be done to remove an
* obsolete preference.
*/
public function remove (name :String) :void
{
delete _data[name];
if (_so != null) {
_so.flush(); // flushing is not strictly necessary
}
}
/**
* Ensure that we can store preferences up to the specified size.
* Note that calling this method may pop up a dialog to the user, asking
* them if it's ok to increase the capacity. The result listener may
* never be called if the user doesn't answer the pop-up.
*
* @param rl an optional listener that will be informed as to whether
* the request succeeded.
*/
public function ensureCapacity (kilobytes :int, rl :ResultListener) :void
{
if (_so == null) {
if (rl != null) {
rl.requestCompleted(this);
}
return;
}
// flush with the size, see if we're cool
var result :String = _so.flush(1024 * kilobytes);
if (rl == null) {
return;
}
// success
if (result == SharedObjectFlushStatus.FLUSHED) {
rl.requestCompleted(this);
return;
}
// otherwise we'll hear back in a sec
var thisConfig :Config = this;
var listener :Function = function (evt :NetStatusEvent) :void {
// TODO: There is a bug where the status is always
// "SharedObject.Flush.Failed", even on success, if the request
// was for a large enough storage that the player calls it
// "unlimited".
trace("================[" + evt.info.code + "]");
if ("SharedObject.Flush.Success" == evt.info.code) {
rl.requestCompleted(thisConfig);
} else {
rl.requestFailed(new Error(String(evt.info.code)));
}
_so.removeEventListener(NetStatusEvent.NET_STATUS, listener);
};
_so.addEventListener(NetStatusEvent.NET_STATUS, listener);
}
/** The shared object that contains our preferences. */
protected var _so :SharedObject;
/** The object in which we store things, usually _so.data. */
protected var _data :Object;
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.events.NetStatusEvent;
import flash.events.EventDispatcher;
import flash.net.SharedObject;
import flash.net.SharedObjectFlushStatus;
/**
* Dispatched when this Config object has a value set on it.
*
* @eventType com.threerings.util.ConfigValueSetEvent.CONFIG_VALUE_SET
*/
[Event(name="ConfigValSet", type="com.threerings.util.ConfigValueSetEvent")]
public class Config extends EventDispatcher
{
/**
* Constructs a new config object which will obtain configuration
* information from the specified path.
*/
public function Config (path :String)
{
setPath(path);
}
/**
* Set the path, if null then we aren't persisting settings.
*/
public function setPath (path :String) :void
{
_so = (path == null) ? null : SharedObject.getLocal("config_" + path, "/");
_data = (_so == null) ? {} : _so.data;
// dispatch events for all settings
for (var n :String in _data) {
dispatchEvent(new ConfigValueSetEvent(n, _data[n]));
}
}
/**
* Are we persisting settings?
*/
public function isPersisting () :Boolean
{
return (_so != null);
}
/**
* Fetches and returns the value for the specified configuration property.
*/
public function getValue (name :String, defValue :Object) :Object
{
var val :* = _data[name];
return (val === undefined) ? defValue : val;
}
/**
* Returns the value specified.
*/
public function setValue (name :String, value :Object) :void
{
_data[name] = value;
if (_so != null) {
_so.flush(); // flushing is not strictly necessary
}
// dispatch an event corresponding
dispatchEvent(new ConfigValueSetEvent(name, value));
}
/**
* Remove any set value for the specified preference.
* This does not dispatch an event because this would only be done to remove an
* obsolete preference.
*/
public function remove (name :String) :void
{
delete _data[name];
if (_so != null) {
_so.flush(); // flushing is not strictly necessary
}
}
/**
* Ensure that we can store preferences up to the specified size.
* Note that calling this method may pop up a dialog to the user, asking
* them if it's ok to increase the capacity. The result listener may
* never be called if the user doesn't answer the pop-up.
*
* @param rl an optional listener that will be informed as to whether
* the request succeeded.
*/
public function ensureCapacity (kilobytes :int, rl :ResultListener) :void
{
if (_so == null) {
if (rl != null) {
rl.requestCompleted(this);
}
return;
}
// flush with the size, see if we're cool
var result :String = _so.flush(1024 * kilobytes);
if (rl == null) {
return;
}
// success
if (result == SharedObjectFlushStatus.FLUSHED) {
rl.requestCompleted(this);
return;
}
// otherwise we'll hear back in a sec
var thisConfig :Config = this;
var listener :Function = function (evt :NetStatusEvent) :void {
// TODO: There is a bug where the status is always
// "SharedObject.Flush.Failed", even on success, if the request
// was for a large enough storage that the player calls it
// "unlimited".
trace("================[" + evt.info.code + "]");
if ("SharedObject.Flush.Success" == evt.info.code) {
rl.requestCompleted(thisConfig);
} else {
rl.requestFailed(new Error(String(evt.info.code)));
}
_so.removeEventListener(NetStatusEvent.NET_STATUS, listener);
};
_so.addEventListener(NetStatusEvent.NET_STATUS, listener);
}
/** The shared object that contains our preferences. */
protected var _so :SharedObject;
/** The object in which we store things, usually _so.data. */
protected var _data :Object;
}
}
|
Allow whether we're persisting to be queried.
|
Allow whether we're persisting to be queried.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5672 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
3c22779cd847c2f0a6d671e30d17dcb96d7111ab
|
src/aerys/minko/type/math/Vector4.as
|
src/aerys/minko/type/math/Vector4.as
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
public static const FORWARD : Vector4 = Z_AXIS;
public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.);
public static const LEFT : Vector4 = new Vector4(-1, 0., 0.);
public static const RIGHT : Vector4 = new Vector4(1, 0., 0.);
public static const UP : Vector4 = Y_AXIS;
public static const DOWN : Vector4 = new Vector4(0, -1., 0.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
}
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1.)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.incrementBy(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.decrementBy(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4) : Vector4
{
return new Vector4(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
}
public function compareTo(v : Vector4, allFour : Boolean = false) : Boolean
{
return _vector.x == v._vector.x
&& _vector.y == v._vector.y
&& _vector.z == v._vector.z
&& (!allFour || (_vector.w == v._vector.w));
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public static function copy(source : Vector4, target : Vector4 = null) : Vector4
{
target ||= FACTORY.create() as Vector4;
target.set(source.x, source.y, source.z, source.w);
return target;
}
public function incrementBy(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function decrementBy(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
return this;
}
public function toString() : String
{
return "(" + _vector.x + ", " + _vector.y + ", " + _vector.z + ", "
+ _vector.w + ")";
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out._vector.x = v._vector.x;
out._vector.y = v._vector.y;
out._vector.z = v._vector.z;
out._vector.w = v._vector.w;
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public static function normalize(v : Vector4, out : Vector4 = null) : Vector4
{
out = copy(v, out);
return out.normalize();
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this);
}
public function clone() : Vector4
{
return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w);
}
}
}
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
public static const FORWARD : Vector4 = Z_AXIS;
public static const BACKWARD : Vector4 = new Vector4(0., 0., -1.);
public static const LEFT : Vector4 = new Vector4(-1, 0., 0.);
public static const RIGHT : Vector4 = new Vector4(1, 0., 0.);
public static const UP : Vector4 = Y_AXIS;
public static const DOWN : Vector4 = new Vector4(0, -1., 0.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = 3; // UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
}
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1.)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.incrementBy(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.decrementBy(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4) : Vector4
{
return new Vector4(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
}
public function compareTo(v : Vector4, allFour : Boolean = false) : Boolean
{
return _vector.x == v._vector.x
&& _vector.y == v._vector.y
&& _vector.z == v._vector.z
&& (!allFour || (_vector.w == v._vector.w));
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public static function copy(source : Vector4, target : Vector4 = null) : Vector4
{
target ||= FACTORY.create() as Vector4;
target.set(source.x, source.y, source.z, source.w);
return target;
}
public function incrementBy(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function decrementBy(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this);
}
return this;
}
public function toString() : String
{
return "(" + _vector.x + ", " + _vector.y + ", " + _vector.z + ", "
+ _vector.w + ")";
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out.set(v._vector.x * s, v._vector.y * s, v._vector.z * s, v._vector.w * s);
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public static function normalize(v : Vector4, out : Vector4 = null) : Vector4
{
out = copy(v, out);
return out.normalize();
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this);
}
public function clone() : Vector4
{
return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w);
}
}
}
|
fix Vector4::scale()
|
fix Vector4::scale()
|
ActionScript
|
mit
|
aerys/minko-as3
|
a19e94e9a22efec0c077e02ccb839d1e89f3b1f8
|
mustella/tests/basicTests/shim/VBox.as
|
mustella/tests/basicTests/shim/VBox.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 shim
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import org.apache.flex.html.Container;
[DefaultProperty("mxmlContent")]
/**
* A VBox approximation.
*/
public class VBox extends Container
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VBox()
{
super();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 shim
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import org.apache.flex.html.Container;
import org.apache.flex.html.beads.layouts.NonVirtualVerticalLayout;
[DefaultProperty("mxmlContent")]
/**
* A VBox approximation.
*/
public class VBox extends Container
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VBox()
{
super();
addBead(new NonVirtualVerticalLayout());
}
}
}
|
put the v in the vbox
|
put the v in the vbox
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
9928c8e48b32c144e119776420a45abf59234bbb
|
src/aerys/minko/render/shader/part/environment/EnvironmentMappingShaderPart.as
|
src/aerys/minko/render/shader/part/environment/EnvironmentMappingShaderPart.as
|
package aerys.minko.render.shader.part.environment
{
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.BlendingShaderPart;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.render.shader.part.projection.BlinnNewellProjectionShaderPart;
import aerys.minko.render.shader.part.projection.ProbeProjectionShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.EnvironmentMappingType;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerFormat;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
import flash.geom.Rectangle;
public class EnvironmentMappingShaderPart extends LightAwareShaderPart
{
private var _blinnNewellProjectionPart : BlinnNewellProjectionShaderPart;
private var _probeProjectionPart : ProbeProjectionShaderPart;
private var _blending : BlendingShaderPart;
public function EnvironmentMappingShaderPart(main : Shader)
{
super(main);
_blinnNewellProjectionPart = new BlinnNewellProjectionShaderPart(main);
_probeProjectionPart = new ProbeProjectionShaderPart(main);
_blending = new BlendingShaderPart(main);
}
public function getEnvironmentColor() : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE)
|| !meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAP))
return float4(0, 0, 0, 0);
// compute reflected vector
var cWorldCameraPosition : SFloat = this.cameraPosition;
var vsWorldVertexToCamera : SFloat = normalize(subtract(cWorldCameraPosition, vsWorldPosition));
var reflected : SFloat = normalize(interpolate(reflect(vsWorldNormal.xyzz, vsWorldVertexToCamera.xyzz)));
var reflectionType : int = meshBindings.getProperty(
EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE
);
var reflectionMap : SFloat = getEnvironmentMap(reflectionType);
// retrieve reflection color from reflection map
var reflectionMapUV : SFloat;
var reflectionColor : SFloat;
switch (reflectionType)
{
case EnvironmentMappingType.NONE:
reflectionColor = float4(0, 0, 0, 0);
break;
case EnvironmentMappingType.PROBE:
reflectionMapUV = _probeProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.BLINN_NEWELL:
reflectionMapUV = _blinnNewellProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.CUBE:
reflectionColor = sampleTexture(reflectionMap, reflected);
break;
default:
throw new Error('Unsupported reflection type');
}
// modifify alpha color
if (meshBindings.propertyExists(EnvironmentMappingProperties.REFLECTIVITY))
{
var reflectivity : SFloat = meshBindings.getParameter(
EnvironmentMappingProperties.REFLECTIVITY, 1
);
reflectionColor = float4(reflectionColor.xyz, multiply(reflectionColor.w, reflectivity));
}
return reflectionColor;
}
public function getEnvironmentMap(environmentMappingType : uint = 0) : SFloat
{
if (!environmentMappingType)
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE);
return meshBindings.getTextureParameter(
EnvironmentMappingProperties.ENVIRONMENT_MAP,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, SamplerFiltering.NEAREST),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, SamplerMipMapping.DISABLE),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, SamplerWrapping.CLAMP),
environmentMappingType == EnvironmentMappingType.CUBE ? SamplerDimension.CUBE : SamplerDimension.FLAT,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, SamplerFormat.RGBA)
);
}
public function applyEnvironmentMapping(diffuse : SFloat) : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE))
return diffuse;
return _blending.blend(
getEnvironmentColor(),
diffuse,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, Blending.ALPHA)
);
}
}
}
|
package aerys.minko.render.shader.part.environment
{
import flash.geom.Rectangle;
import mx.messaging.SubscriptionInfo;
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.part.BlendingShaderPart;
import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
import aerys.minko.render.shader.part.projection.BlinnNewellProjectionShaderPart;
import aerys.minko.render.shader.part.projection.ProbeProjectionShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.EnvironmentMappingType;
import aerys.minko.type.enum.SamplerDimension;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerFormat;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class EnvironmentMappingShaderPart extends LightAwareShaderPart
{
private var _blinnNewellProjectionPart : BlinnNewellProjectionShaderPart;
private var _probeProjectionPart : ProbeProjectionShaderPart;
private var _blending : BlendingShaderPart;
public function EnvironmentMappingShaderPart(main : Shader)
{
super(main);
_blinnNewellProjectionPart = new BlinnNewellProjectionShaderPart(main);
_probeProjectionPart = new ProbeProjectionShaderPart(main);
_blending = new BlendingShaderPart(main);
}
public function getEnvironmentColor() : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE)
|| !meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAP))
return float4(0, 0, 0, 0);
// compute reflected vector
var cWorldCameraPosition : SFloat = this.cameraPosition;
var vsWorldVertexToCamera : SFloat = normalize(subtract(vsWorldPosition, cWorldCameraPosition));
var reflected : SFloat = normalize(interpolate(reflect(vsWorldVertexToCamera.xyzz, vsWorldNormal.xyzz)));
var reflectionType : int = meshBindings.getProperty(
EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE
);
var reflectionMap : SFloat = getEnvironmentMap(reflectionType);
// retrieve reflection color from reflection map
var reflectionMapUV : SFloat;
var reflectionColor : SFloat;
switch (reflectionType)
{
case EnvironmentMappingType.NONE:
reflectionColor = float4(0, 0, 0, 0);
break;
case EnvironmentMappingType.PROBE:
reflectionMapUV = _probeProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.BLINN_NEWELL:
reflectionMapUV = _blinnNewellProjectionPart.projectVector(reflected, new Rectangle(0, 0, 1, 1));
reflectionColor = sampleTexture(reflectionMap, reflectionMapUV);
break;
case EnvironmentMappingType.CUBE:
reflectionColor = sampleTexture(reflectionMap, reflected);
break;
default:
throw new Error('Unsupported reflection type');
}
// modifify alpha color
if (meshBindings.propertyExists(EnvironmentMappingProperties.REFLECTIVITY))
{
var reflectivity : SFloat = meshBindings.getParameter(
EnvironmentMappingProperties.REFLECTIVITY, 1
);
reflectionColor = float4(reflectionColor.xyz, multiply(reflectionColor.w, reflectivity));
}
return reflectionColor;
}
public function getEnvironmentMap(environmentMappingType : uint = 0) : SFloat
{
if (!environmentMappingType)
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE);
return meshBindings.getTextureParameter(
EnvironmentMappingProperties.ENVIRONMENT_MAP,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, SamplerFiltering.NEAREST),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, SamplerMipMapping.DISABLE),
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, SamplerWrapping.CLAMP),
environmentMappingType == EnvironmentMappingType.CUBE ? SamplerDimension.CUBE : SamplerDimension.FLAT,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, SamplerFormat.RGBA)
);
}
public function applyEnvironmentMapping(diffuse : SFloat) : SFloat
{
if (!meshBindings.propertyExists(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE))
return diffuse;
return _blending.blend(
getEnvironmentColor(),
diffuse,
meshBindings.getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, Blending.ALPHA)
);
}
}
}
|
Fix env map computation
|
Fix env map computation
|
ActionScript
|
mit
|
aerys/minko-as3
|
00efbc5fe5c574641a74f6d246712b81c1f29055
|
src/aerys/minko/type/math/Quaternion.as
|
src/aerys/minko/type/math/Quaternion.as
|
package aerys.minko.type.math
{
import aerys.minko.type.Factory;
public final class Quaternion
{
private static const FACTORY : Factory = Factory.getFactory(Quaternion);
private static const EPSILON : Number = 1e-6;
private static const TMP_QUATERNION : Quaternion = new Quaternion();
private var _r : Number = 1.;
private var _i : Number = 0.;
private var _j : Number = 0.;
private var _k : Number = 0.;
final public function get r() : Number
{
return _r;
}
final public function get i() : Number
{
return _i;
}
final public function get j() : Number
{
return _j;
}
final public function get k() : Number
{
return _k;
}
public function get length() : Number
{
return Math.sqrt(_r * _r + _i * _i + _j * _j + _k * _k);
}
public function get norm() : Number
{
return length;
}
public static function add(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q1)
return out.incrementBy(q2);
}
public static function subtract(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q1)
return out.decrementBy(q2);
}
public static function scale(q : Quaternion, f : Number, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q)
return out.scaleBy(f);
}
public static function multiply(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q1);
return out.multiplyBy(q2);
}
public static function divide(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
Quaternion.invert(q2, TMP_QUATERNION);
Quaternion.multiply(q1, TMP_QUATERNION, out);
return out;
}
public static function negate(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.negate();
}
public static function conjugate(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.conjugate();
}
public static function square(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.square();
}
public static function invert(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.invert();
}
public function Quaternion(r : Number = 0,
i : Number = 0,
j : Number = 0,
k : Number = 0)
{
_r = r;
_i = i;
_j = j;
_k = k;
}
public function set(r : Number,
i : Number,
j : Number,
k : Number) : Quaternion
{
_r = r;
_i = i;
_j = j;
_k = k;
return this;
}
public function copyFrom(q : Quaternion) : Quaternion
{
return set(q._r, q._i, q._j, q._k);
}
public function decrementBy(q : Quaternion) : Quaternion
{
_r += q._r;
_i += q._i;
_j += q._j;
_k += q._k;
return this;
}
public function incrementBy(q : Quaternion) : Quaternion
{
_r += q._r;
_i += q._i;
_j += q._j;
_k += q._k;
return this;
}
public function scaleBy(f : Number) : Quaternion
{
_r *= f;
_i *= f;
_j *= f;
_k *= f;
return this;
}
public function multiplyBy(q : Quaternion) : Quaternion
{
var t0 : Number = (_k - _j) * (q._j - q._k);
var t1 : Number = (_r + _i) * (q._r + q._i);
var t2 : Number = (_r - _i) * (q._j + q._k);
var t3 : Number = (_k + _j) * (q._r - q._i);
var t4 : Number = (_k - _i) * (q._i - q._j);
var t5 : Number = (_k + _i) * (q._i + q._j);
var t6 : Number = (_r + _j) * (q._r - q._k);
var t7 : Number = (_r - _j) * (q._r + q._k);
var t8 : Number = t5 + t6 + t7;
var t9 : Number = (t4 + t8) / 2;
_r = t0 + t9 - t5;
_i = t1 + t9 - t8;
_j = t2 + t9 - t7;
_k = t3 + t9 - t6;
return this;
}
public function normalize(q : Quaternion) : Quaternion
{
var l : Number = length;
if (l != 0.)
{
_r *= l;
_i *= l;
_j *= l;
_k *= l;
}
return this;
}
public function divide(q : Quaternion) : Quaternion
{
return Quaternion.divide(this, q, this);
}
public function negate() : Quaternion
{
return scaleBy(-1);
}
public function conjugate() : Quaternion
{
_i = -_i;
_j = -_j;
_k = -_k;
return this;
}
public function square() : Quaternion
{
var tmp : Number = 2 * _r;
_r = _r * _r - (_i * _i + _j * _j + _k * _k);
_i = tmp * _i;
_j = tmp * _j;
_k = tmp * _k;
return this;
}
public function invert() : Quaternion
{
var l : Number = length;
_r /= l;
_i /= -l;
_j /= -l;
_k /= -l;
return this;
}
public function equals(q : Quaternion) : Boolean
{
return _r == q._r && _i == q._i && _j == q._j && _k == q._k;
}
public function clone() : Quaternion
{
return Quaternion(FACTORY.create()).set(_r, _i, _j, _k);
}
public function toString() : String
{
return '[Quaternion r="' + _r + '" i="' + _i + '" j="' + _j + '" k="' + _k + '"]';
}
public static function fromRotationBetweenVectors(u : Vector4, v : Vector4) : Quaternion
{
u.normalize();
v.normalize();
var kCosTheta : Number = Vector4.dotProduct(u, v)
var k : Number = Math.sqrt(u.lengthSquared * v.lengthSquared);
if (Math.abs(kCosTheta / k + 1) < EPSILON)
{
// 180 degree rotation around any orthogonal vector
var other : Vector4 = (Math.abs(Vector4.dotProduct(u, Vector4.X_AXIS)) < 1.0) ? Vector4.X_AXIS : Vector4.Y_AXIS;
var axis : Vector4 = Vector4.crossProduct(u, other).normalize();
return fromRotationOnAxis(axis, Math.PI);
}
var c : Vector4 = Vector4.crossProduct(u, v);
var d : Number = Vector4.dotProduct(u, v);
var q : Quaternion = Quaternion(FACTORY.create()).set(d + k, c.x, c.y, c.z);
return q.scaleBy(1. / q.norm);
}
private static function fromRotationOnAxis(axis : Vector4, theta : Number) : Quaternion
{
theta *= .5;
axis.normalize();
var sine : Number = Math.sin(theta);
var out : Quaternion = Quaternion(FACTORY.create()).set(
Math.cos(theta),
axis.x * sine,
axis.y * sine,
axis.z * sine
);
return out;
}
}
}
|
package aerys.minko.type.math
{
import aerys.minko.type.Factory;
public final class Quaternion
{
private static const FACTORY : Factory = Factory.getFactory(Quaternion);
private static const EPSILON : Number = 1e-6;
private static const TMP_QUATERNION : Quaternion = new Quaternion();
private var _r : Number = 1.;
private var _i : Number = 0.;
private var _j : Number = 0.;
private var _k : Number = 0.;
final public function get r() : Number
{
return _r;
}
final public function get i() : Number
{
return _i;
}
final public function get j() : Number
{
return _j;
}
final public function get k() : Number
{
return _k;
}
public function get length() : Number
{
return Math.sqrt(_r * _r + _i * _i + _j * _j + _k * _k);
}
public function get norm() : Number
{
return length;
}
public static function add(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q1)
return out.incrementBy(q2);
}
public static function subtract(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q1)
return out.decrementBy(q2);
}
public static function scale(q : Quaternion, f : Number, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q)
return out.scaleBy(f);
}
public static function multiply(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q1);
return out.multiplyBy(q2);
}
public static function divide(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion
{
Quaternion.invert(q2, TMP_QUATERNION);
Quaternion.multiply(q1, TMP_QUATERNION, out);
return out;
}
public static function negate(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.negate();
}
public static function conjugate(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.conjugate();
}
public static function square(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.square();
}
public static function invert(q : Quaternion, out : Quaternion = null) : Quaternion
{
out ||= FACTORY.create() as Quaternion;
out.copyFrom(q);
return out.invert();
}
public function Quaternion(r : Number = 0,
i : Number = 0,
j : Number = 0,
k : Number = 0)
{
_r = r;
_i = i;
_j = j;
_k = k;
}
public function set(r : Number,
i : Number,
j : Number,
k : Number) : Quaternion
{
_r = r;
_i = i;
_j = j;
_k = k;
return this;
}
public function copyFrom(q : Quaternion) : Quaternion
{
return set(q._r, q._i, q._j, q._k);
}
public function decrementBy(q : Quaternion) : Quaternion
{
_r += q._r;
_i += q._i;
_j += q._j;
_k += q._k;
return this;
}
public function incrementBy(q : Quaternion) : Quaternion
{
_r += q._r;
_i += q._i;
_j += q._j;
_k += q._k;
return this;
}
public function scaleBy(f : Number) : Quaternion
{
_r *= f;
_i *= f;
_j *= f;
_k *= f;
return this;
}
public function multiplyBy(q : Quaternion) : Quaternion
{
var t0 : Number = (_k - _j) * (q._j - q._k);
var t1 : Number = (_r + _i) * (q._r + q._i);
var t2 : Number = (_r - _i) * (q._j + q._k);
var t3 : Number = (_k + _j) * (q._r - q._i);
var t4 : Number = (_k - _i) * (q._i - q._j);
var t5 : Number = (_k + _i) * (q._i + q._j);
var t6 : Number = (_r + _j) * (q._r - q._k);
var t7 : Number = (_r - _j) * (q._r + q._k);
var t8 : Number = t5 + t6 + t7;
var t9 : Number = (t4 + t8) / 2;
_r = t0 + t9 - t5;
_i = t1 + t9 - t8;
_j = t2 + t9 - t7;
_k = t3 + t9 - t6;
return this;
}
public function normalize() : Quaternion
{
var l : Number = length;
if (l != 0.)
{
_r *= l;
_i *= l;
_j *= l;
_k *= l;
}
return this;
}
public function divide(q : Quaternion) : Quaternion
{
return Quaternion.divide(this, q, this);
}
public function negate() : Quaternion
{
return scaleBy(-1);
}
public function conjugate() : Quaternion
{
_i = -_i;
_j = -_j;
_k = -_k;
return this;
}
public function square() : Quaternion
{
var tmp : Number = 2 * _r;
_r = _r * _r - (_i * _i + _j * _j + _k * _k);
_i = tmp * _i;
_j = tmp * _j;
_k = tmp * _k;
return this;
}
public function invert() : Quaternion
{
var l : Number = length;
_r /= l;
_i /= -l;
_j /= -l;
_k /= -l;
return this;
}
public function equals(q : Quaternion) : Boolean
{
return _r == q._r && _i == q._i && _j == q._j && _k == q._k;
}
public function clone() : Quaternion
{
return Quaternion(FACTORY.create()).set(_r, _i, _j, _k);
}
public function toString() : String
{
return '[Quaternion r="' + _r + '" i="' + _i + '" j="' + _j + '" k="' + _k + '"]';
}
public static function fromRotationBetweenVectors(u : Vector4, v : Vector4) : Quaternion
{
u.normalize();
v.normalize();
var kCosTheta : Number = Vector4.dotProduct(u, v)
var k : Number = Math.sqrt(u.lengthSquared * v.lengthSquared);
if (Math.abs(kCosTheta / k + 1) < EPSILON)
{
// 180 degree rotation around any orthogonal vector
var other : Vector4 = (Math.abs(Vector4.dotProduct(u, Vector4.X_AXIS)) < 1.0) ? Vector4.X_AXIS : Vector4.Y_AXIS;
var axis : Vector4 = Vector4.crossProduct(u, other).normalize();
return fromRotationOnAxis(axis, Math.PI);
}
var c : Vector4 = Vector4.crossProduct(u, v);
var d : Number = Vector4.dotProduct(u, v);
var q : Quaternion = Quaternion(FACTORY.create()).set(d + k, c.x, c.y, c.z);
return q.scaleBy(1. / q.norm);
}
private static function fromRotationOnAxis(axis : Vector4, theta : Number) : Quaternion
{
theta *= .5;
axis.normalize();
var sine : Number = Math.sin(theta);
var out : Quaternion = Quaternion(FACTORY.create()).set(
Math.cos(theta),
axis.x * sine,
axis.y * sine,
axis.z * sine
);
return out;
}
}
}
|
Remove unused argument to Quaternion.normalize().
|
Remove unused argument to Quaternion.normalize().
|
ActionScript
|
mit
|
aerys/minko-as3
|
94e2d3d67643f9960d18ac90c6405afa80b06e8c
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CloneableClass;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertTrue;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.core.not;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
const nestedCloneable:CloneableClass = new CloneableClass();
nestedCloneable.property1 = "property1 value";
nestedCloneable.writableField1 = "writableField1 value";
const nestedCompositeCloneable:CompositeCloneableClass = new CompositeCloneableClass();
nestedCompositeCloneable.compositeCloneable = compositeCloneableClass;
nestedCompositeCloneable.array = [1, 2, 3];
nestedCompositeCloneable.arrayList = new ArrayList([1, 2, 3]);
nestedCompositeCloneable.arrayCollection = new ArrayCollection([1, 2, 3]);
compositeCloneableClass.cloneable = nestedCloneable;
compositeCloneableClass.compositeCloneable = nestedCompositeCloneable;
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass.compositeCloneable =
compositeCloneableClass.compositeCloneable.compositeCloneable = null;
compositeCloneableClass.cloneable = null;
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(5, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(arrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(arrayCollection.length, 5);
assertEquals(arrayCollection.getItemAt(0), 1);
assertEquals(arrayCollection.getItemAt(1), 2);
assertEquals(arrayCollection.getItemAt(2), 3);
assertEquals(arrayCollection.getItemAt(3), 4);
assertEquals(arrayCollection.getItemAt(4), 5);
}
[Test]
public function cloningOfCloneableProperty():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const cloneable:CloneableClass = clone.cloneable;
assertNotNull(cloneable);
assertThat(cloneable, isA(CloneableClass));
assertEquals(cloneable.property1, "property1 value");
assertEquals(cloneable.writableField1, "writableField1 value");
assertThat(cloneable, not(compositeCloneableClass.cloneable));
}
[Test]
public function cloningOfCompositeCloneableClass():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const compositeCloneable:CompositeCloneableClass = clone.compositeCloneable;
assertNotNull(compositeCloneable);
assertThat(compositeCloneable, isA(CompositeCloneableClass));
assertNotNull(compositeCloneable.array);
assertThat(compositeCloneable.array, arrayWithSize(3));
assertThat(compositeCloneable.array, everyItem(isA(Number)));
assertThat(compositeCloneable.array, array(equalTo(1), equalTo(2), equalTo(3)));
assertNotNull(compositeCloneable.arrayList);
assertThat(compositeCloneable.arrayList, isA(ArrayList));
assertEquals(compositeCloneable.arrayList.length, 3);
assertEquals(compositeCloneable.arrayList.getItemAt(0), 1);
assertEquals(compositeCloneable.arrayList.getItemAt(1), 2);
assertEquals(compositeCloneable.arrayList.getItemAt(2), 3);
assertNotNull(compositeCloneable.arrayCollection);
assertThat(compositeCloneable.arrayCollection, isA(ArrayCollection));
assertEquals(compositeCloneable.arrayCollection.length, 3);
assertEquals(compositeCloneable.arrayCollection.getItemAt(0), 1);
assertEquals(compositeCloneable.arrayCollection.getItemAt(1), 2);
assertEquals(compositeCloneable.arrayCollection.getItemAt(2), 3);
assertNotNull(compositeCloneable.compositeCloneable);
assertThat(compositeCloneable.compositeCloneable, isA(CompositeCloneableClass));
assertEquals(clone, compositeCloneable.compositeCloneable);
assertEquals(clone.array, compositeCloneable.compositeCloneable.array);
assertEquals(clone.arrayList, compositeCloneable.compositeCloneable.arrayList);
assertEquals(clone.arrayCollection, compositeCloneable.compositeCloneable.arrayCollection);
assertEquals(clone.cloneable, compositeCloneable.compositeCloneable.cloneable);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CloneableClass;
import dolly.data.CompositeCloneableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.core.not;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CloningOfCompositeCloneableClassTest {
private var compositeCloneableClass:CompositeCloneableClass;
private var compositeCloneableClassType:Type;
[Before]
public function before():void {
compositeCloneableClass = new CompositeCloneableClass();
const nestedCloneable:CloneableClass = new CloneableClass();
nestedCloneable.property1 = "property1 value";
nestedCloneable.writableField1 = "writableField1 value";
const nestedCompositeCloneable:CompositeCloneableClass = new CompositeCloneableClass();
nestedCompositeCloneable.compositeCloneable = compositeCloneableClass;
nestedCompositeCloneable.array = [1, 2, 3];
nestedCompositeCloneable.arrayList = new ArrayList([1, 2, 3]);
nestedCompositeCloneable.arrayCollection = new ArrayCollection([1, 2, 3]);
compositeCloneableClass.cloneable = nestedCloneable;
compositeCloneableClass.compositeCloneable = nestedCompositeCloneable;
compositeCloneableClass.array = [1, 2, 3, 4, 5];
compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCloneableClassType = Type.forInstance(compositeCloneableClass);
}
[After]
public function after():void {
compositeCloneableClass.compositeCloneable =
compositeCloneableClass.compositeCloneable.compositeCloneable = null;
compositeCloneableClass.cloneable = null;
compositeCloneableClass = null;
compositeCloneableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType);
assertNotNull(writableFields);
assertEquals(5, writableFields.length);
}
[Test]
public function cloningOfArray():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
assertNotNull(clone.array);
assertThat(clone.array, arrayWithSize(5));
assertThat(clone.array, compositeCloneableClass.array);
assertFalse(clone.array == compositeCloneableClass.array);
assertThat(clone.array, everyItem(isA(Number)));
assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function cloningOfArrayList():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayList:ArrayList = clone.arrayList;
assertNotNull(arrayList);
assertFalse(clone.arrayList == compositeCloneableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
[Test]
public function cloningOfArrayCollection():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const arrayCollection:ArrayCollection = clone.arrayCollection;
assertNotNull(arrayCollection);
assertFalse(clone.arrayCollection == compositeCloneableClass.arrayCollection);
assertEquals(arrayCollection.length, 5);
assertEquals(arrayCollection.getItemAt(0), 1);
assertEquals(arrayCollection.getItemAt(1), 2);
assertEquals(arrayCollection.getItemAt(2), 3);
assertEquals(arrayCollection.getItemAt(3), 4);
assertEquals(arrayCollection.getItemAt(4), 5);
}
[Test]
public function cloningOfCloneableProperty():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const cloneable:CloneableClass = clone.cloneable;
assertNotNull(cloneable);
assertThat(cloneable, isA(CloneableClass));
assertEquals(cloneable.property1, "property1 value");
assertEquals(cloneable.writableField1, "writableField1 value");
assertThat(cloneable, not(compositeCloneableClass.cloneable));
}
[Test]
public function cloningOfCompositeCloneableClass():void {
const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass);
const compositeCloneable:CompositeCloneableClass = clone.compositeCloneable;
assertNotNull(compositeCloneable);
assertThat(compositeCloneable, isA(CompositeCloneableClass));
assertNotNull(compositeCloneable.array);
assertThat(compositeCloneable.array, arrayWithSize(3));
assertThat(compositeCloneable.array, everyItem(isA(Number)));
assertThat(compositeCloneable.array, array(equalTo(1), equalTo(2), equalTo(3)));
assertNotNull(compositeCloneable.arrayList);
assertThat(compositeCloneable.arrayList, isA(ArrayList));
assertEquals(compositeCloneable.arrayList.length, 3);
assertEquals(compositeCloneable.arrayList.getItemAt(0), 1);
assertEquals(compositeCloneable.arrayList.getItemAt(1), 2);
assertEquals(compositeCloneable.arrayList.getItemAt(2), 3);
assertNotNull(compositeCloneable.arrayCollection);
assertThat(compositeCloneable.arrayCollection, isA(ArrayCollection));
assertEquals(compositeCloneable.arrayCollection.length, 3);
assertEquals(compositeCloneable.arrayCollection.getItemAt(0), 1);
assertEquals(compositeCloneable.arrayCollection.getItemAt(1), 2);
assertEquals(compositeCloneable.arrayCollection.getItemAt(2), 3);
assertNotNull(compositeCloneable.compositeCloneable);
assertThat(compositeCloneable.compositeCloneable, isA(CompositeCloneableClass));
assertEquals(clone, compositeCloneable.compositeCloneable);
assertEquals(clone.array, compositeCloneable.compositeCloneable.array);
assertEquals(clone.arrayList, compositeCloneable.compositeCloneable.arrayList);
assertEquals(clone.arrayCollection, compositeCloneable.compositeCloneable.arrayCollection);
assertEquals(clone.cloneable, compositeCloneable.compositeCloneable.cloneable);
}
}
}
|
Optimize imports.
|
Optimize imports.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
d11d7b408bf5f5fbde6859ad93d74c908ed192ba
|
testSrc/com/kemsky/support/TestSupport.as
|
testSrc/com/kemsky/support/TestSupport.as
|
package com.kemsky.support
{
import avmplus.getQualifiedClassName;
import com.kemsky.Stream;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertTrue;
public class TestSupport
{
public function TestSupport()
{
}
[Test]
public function testTypeCache():void
{
var n:Number = 1.3;
var s:String = "test";
var a:Array = [1, 2, 3];
var b:Boolean = true;
var cls:Class = Item;
var d:Date = new Date(2000);
var x:XML = <t>test</t>;
var xl:XMLList = <t href="5">test</t>.@href;
var item:Item = new Item();
assertEquals(TypeCache.getQualifiedClassName(n), TypeCache.NUMBER);
assertEquals(TypeCache.getQualifiedClassName(s), TypeCache.STRING);
assertEquals(TypeCache.getQualifiedClassName(a), TypeCache.ARRAY);
assertEquals(TypeCache.getQualifiedClassName(b), TypeCache.BOOLEAN);
assertEquals(TypeCache.getQualifiedClassName(cls), "Item");
assertEquals(TypeCache.getQualifiedClassName(Class), "Class");
assertEquals(TypeCache.getQualifiedClassName(d), TypeCache.DATE);
assertEquals(TypeCache.getQualifiedClassName(x), TypeCache.XML_TYPE);
assertEquals(TypeCache.getQualifiedClassName(xl), TypeCache.XML_LIST);
assertEquals(TypeCache.getQualifiedClassName(undefined), TypeCache.UNDEFINED);
assertEquals(TypeCache.getQualifiedClassName(item), "Item");
assertEquals(TypeCache.getQualifiedClassName(n), getQualifiedClassName(n));
assertEquals(TypeCache.getQualifiedClassName(s), getQualifiedClassName(s));
assertEquals(TypeCache.getQualifiedClassName(a), getQualifiedClassName(a));
assertEquals(TypeCache.getQualifiedClassName(b), getQualifiedClassName(b));
assertEquals(TypeCache.getQualifiedClassName(cls), getQualifiedClassName(cls));
assertEquals(TypeCache.getQualifiedClassName(Class), getQualifiedClassName(Class));
assertEquals(TypeCache.getQualifiedClassName(d), getQualifiedClassName(d));
assertEquals(TypeCache.getQualifiedClassName(x), getQualifiedClassName(x));
assertEquals(TypeCache.getQualifiedClassName(xl), getQualifiedClassName(xl));
assertEquals(TypeCache.getQualifiedClassName(item), getQualifiedClassName(item));
assertEquals(TypeCache.getQualifiedClassName(undefined), getQualifiedClassName(undefined));
}
[Test]
public function testToValue():void
{
var date:Date = new Date(2000);
assertEquals(toValue(undefined, 1), 1);
assertEquals(toValue(undefined, "test"), "test");
assertEquals(toValue(undefined, date), date);
assertEquals(toValue(undefined, null), null);
assertTrue(toValue(undefined, undefined) === undefined);
assertTrue(toValue(1, undefined) === undefined);
assertTrue(toValue("test", undefined) === undefined);
assertTrue(toValue(date, undefined) === undefined);
assertTrue(toValue(null, undefined) === undefined);
var f:Function = function(value:*):*
{
return value;
};
assertEquals(toValue(1, f), 1);
assertEquals(toValue("test", f), "test");
assertEquals(toValue(date, f), date);
assertTrue(toValue(undefined, f) === undefined);
assertEquals(toValue(null, f), null);
}
[Test]
public function testCompare():void
{
var date:Date = new Date(2000);
assertEquals(Compare.compare(null, null), 0);
assertEquals(Compare.compare(null, 1), -1);
assertEquals(Compare.compare(null, 1, Stream.DESCENDING), 1);
assertEquals(Compare.compare(1, null), 1);
assertEquals(Compare.compare(1, 1, Stream.NUMERIC), 0);
assertEquals(Compare.compare(1, "1"), -1);
assertEquals(Compare.compare(new Date(), date), 1);
assertEquals(Compare.compare(date, date), 0);
assertEquals(Compare.compare(date, new Date()), -1);
assertEquals(Compare.compare(NaN, 1), -1);
assertEquals(Compare.compare(NaN, NaN), 0);
assertEquals(Compare.compare(1, NaN), 1);
assertEquals(Compare.compare("abc", "def"), -1);
assertEquals(Compare.compare("t", "t"), 0);
assertEquals(Compare.compare("def", "abc"), 1);
var xs1:XML = <a>123</a>;
var xs2:XML = <a>1</a>;
assertEquals(Compare.compare(xs1, xs2), 1);
assertEquals(Compare.compare(xs2, xs2), 0);
assertEquals(Compare.compare(xs2, xs1), -1);
assertEquals(Compare.compare(xs1, xs2, Stream.NUMERIC), 1);
assertEquals(Compare.compare(xs2, xs2, Stream.NUMERIC), 0);
assertEquals(Compare.compare(xs2, xs1, Stream.NUMERIC), -1);
try
{
Compare.compare(new Item(), new Item());
assertFalse(true);
}
catch (e:Error)
{
}
}
}
}
|
package com.kemsky.support
{
import avmplus.getQualifiedClassName;
import com.kemsky.Stream;
import com.kemsky.combine;
import com.kemsky.filters._;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertTrue;
public class TestSupport
{
public function TestSupport()
{
}
[Test]
public function testCombine():void
{
var lower:Function = function(value:String):String
{
return value.toLowerCase();
};
var first:Function = function(value:String):String
{
return value.charAt(0);
};
assertEquals(combine()(1), 1);
assertEquals(combine(_)(1), 1);
var c:Function = combine(first, lower);
assertEquals(c("ALEX"), "a");
}
[Test]
public function testTypeCache():void
{
var n:Number = 1.3;
var s:String = "test";
var a:Array = [1, 2, 3];
var b:Boolean = true;
var cls:Class = Item;
var d:Date = new Date(2000);
var x:XML = <t>test</t>;
var xl:XMLList = <t href="5">test</t>.@href;
var item:Item = new Item();
assertEquals(TypeCache.getQualifiedClassName(n), TypeCache.NUMBER);
assertEquals(TypeCache.getQualifiedClassName(s), TypeCache.STRING);
assertEquals(TypeCache.getQualifiedClassName(a), TypeCache.ARRAY);
assertEquals(TypeCache.getQualifiedClassName(b), TypeCache.BOOLEAN);
assertEquals(TypeCache.getQualifiedClassName(cls), "Item");
assertEquals(TypeCache.getQualifiedClassName(Class), "Class");
assertEquals(TypeCache.getQualifiedClassName(d), TypeCache.DATE);
assertEquals(TypeCache.getQualifiedClassName(x), TypeCache.XML_TYPE);
assertEquals(TypeCache.getQualifiedClassName(xl), TypeCache.XML_LIST);
assertEquals(TypeCache.getQualifiedClassName(undefined), TypeCache.UNDEFINED);
assertEquals(TypeCache.getQualifiedClassName(item), "Item");
assertEquals(TypeCache.getQualifiedClassName(n), getQualifiedClassName(n));
assertEquals(TypeCache.getQualifiedClassName(s), getQualifiedClassName(s));
assertEquals(TypeCache.getQualifiedClassName(a), getQualifiedClassName(a));
assertEquals(TypeCache.getQualifiedClassName(b), getQualifiedClassName(b));
assertEquals(TypeCache.getQualifiedClassName(cls), getQualifiedClassName(cls));
assertEquals(TypeCache.getQualifiedClassName(Class), getQualifiedClassName(Class));
assertEquals(TypeCache.getQualifiedClassName(d), getQualifiedClassName(d));
assertEquals(TypeCache.getQualifiedClassName(x), getQualifiedClassName(x));
assertEquals(TypeCache.getQualifiedClassName(xl), getQualifiedClassName(xl));
assertEquals(TypeCache.getQualifiedClassName(item), getQualifiedClassName(item));
assertEquals(TypeCache.getQualifiedClassName(undefined), getQualifiedClassName(undefined));
}
[Test]
public function testToValue():void
{
var date:Date = new Date(2000);
assertEquals(toValue(undefined, 1), 1);
assertEquals(toValue(undefined, "test"), "test");
assertEquals(toValue(undefined, date), date);
assertEquals(toValue(undefined, null), null);
assertTrue(toValue(undefined, undefined) === undefined);
assertTrue(toValue(1, undefined) === undefined);
assertTrue(toValue("test", undefined) === undefined);
assertTrue(toValue(date, undefined) === undefined);
assertTrue(toValue(null, undefined) === undefined);
var f:Function = function(value:*):*
{
return value;
};
assertEquals(toValue(1, f), 1);
assertEquals(toValue("test", f), "test");
assertEquals(toValue(date, f), date);
assertTrue(toValue(undefined, f) === undefined);
assertEquals(toValue(null, f), null);
}
[Test]
public function testCompare():void
{
var date:Date = new Date(2000);
assertEquals(Compare.compare(null, null), 0);
assertEquals(Compare.compare(null, 1), -1);
assertEquals(Compare.compare(null, 1, Stream.DESCENDING), 1);
assertEquals(Compare.compare(1, null), 1);
assertEquals(Compare.compare(1, 1, Stream.NUMERIC), 0);
assertEquals(Compare.compare(1, "1"), -1);
assertEquals(Compare.compare(new Date(), date), 1);
assertEquals(Compare.compare(date, date), 0);
assertEquals(Compare.compare(date, new Date()), -1);
assertEquals(Compare.compare(NaN, 1), -1);
assertEquals(Compare.compare(NaN, NaN), 0);
assertEquals(Compare.compare(1, NaN), 1);
assertEquals(Compare.compare("abc", "def"), -1);
assertEquals(Compare.compare("t", "t"), 0);
assertEquals(Compare.compare("def", "abc"), 1);
var xs1:XML = <a>123</a>;
var xs2:XML = <a>1</a>;
assertEquals(Compare.compare(xs1, xs2), 1);
assertEquals(Compare.compare(xs2, xs2), 0);
assertEquals(Compare.compare(xs2, xs1), -1);
assertEquals(Compare.compare(xs1, xs2, Stream.NUMERIC), 1);
assertEquals(Compare.compare(xs2, xs2, Stream.NUMERIC), 0);
assertEquals(Compare.compare(xs2, xs1, Stream.NUMERIC), -1);
try
{
Compare.compare(new Item(), new Item());
assertFalse(true);
}
catch (e:Error)
{
}
}
}
}
|
test combine
|
test combine
|
ActionScript
|
mit
|
kemsky/stream
|
d3bade48c317ffd4ad79b886d17b729678053187
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_frustumCulling = value;
if (_mesh && _mesh.root is Scene)
testCulling();
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider();
_data.setProperty('computedVisibility', false);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (culling != FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
return;
}
if (_mesh && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_frustumCulling = value;
if (_mesh && _mesh.root is Scene)
testCulling();
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : false },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (culling != FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
return;
}
if (_mesh && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
fix MeshVisibilityController to set its data provider usage to DataProviderUsage.EXCLUSIVE in order to make sure cloning the mesh nodes won't cause duplicate binding properties errors
|
fix MeshVisibilityController to set its data provider usage to DataProviderUsage.EXCLUSIVE in order to make sure cloning the mesh nodes won't cause duplicate binding properties errors
|
ActionScript
|
mit
|
aerys/minko-as3
|
91e8dc958bab70fc4fa99f9fc422421e0b6c9e70
|
src/as/com/threerings/media/Ticker.as
|
src/as/com/threerings/media/Ticker.as
|
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media {
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* Registers objects that wish to be sent a tick() call once per frame.
*/
public class Ticker
{
public function start () :void
{
_t.addEventListener(TimerEvent.TIMER, handleTimer);
_start = new Date().time;
_t.start();
}
public function stop () :void
{
_t.removeEventListener(TimerEvent.TIMER, handleTimer);
_t.stop();
}
public function handleTimer (event :TimerEvent) :void
{
tick(int(new Date().time - _start));
}
protected function tick (tickStamp :int) :void
{
for each (var tickable :Tickable in _tickables) {
tickable.tick(tickStamp);
}
}
public function registerTickable (tickable :Tickable) :void
{
_tickables.push(tickable);
}
public function removeTickable (tickable :Tickable) :void
{
_tickables.remove(tickable);
}
/** Everyone who wants to hear about our ticks. */
protected var _tickables :Array = [];
/** A timer that will fire every "frame". */
protected var _t :Timer = new Timer(1);
/** What time our ticker started running - tickStamps will be relative to this time. */
protected var _start :Number;
}
}
|
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media {
import flash.events.TimerEvent;
import flash.utils.Timer;
import com.threerings.util.ArrayUtil;
/**
* Registers objects that wish to be sent a tick() call once per frame.
*/
public class Ticker
{
public function start () :void
{
_t.addEventListener(TimerEvent.TIMER, handleTimer);
_start = new Date().time;
_t.start();
}
public function stop () :void
{
_t.removeEventListener(TimerEvent.TIMER, handleTimer);
_t.stop();
}
public function handleTimer (event :TimerEvent) :void
{
tick(int(new Date().time - _start));
}
protected function tick (tickStamp :int) :void
{
for each (var tickable :Tickable in _tickables) {
tickable.tick(tickStamp);
}
}
public function registerTickable (tickable :Tickable) :void
{
_tickables.push(tickable);
}
public function removeTickable (tickable :Tickable) :void
{
ArrayUtil.removeFirst(_tickables, tickable);
}
/** Everyone who wants to hear about our ticks. */
protected var _tickables :Array = [];
/** A timer that will fire every "frame". */
protected var _t :Timer = new Timer(1);
/** What time our ticker started running - tickStamps will be relative to this time. */
protected var _start :Number;
}
}
|
Make the proper call here - there's no remove() on arrays...
|
Make the proper call here - there's no remove() on arrays...
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@1002 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
d067f5b0f494c45fd91fe3e5055a529cba584b24
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
private var output_text:TextField;
// Socket to facilitator.
private var s_f:Socket;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var tor_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
private var output_text:TextField;
// Socket to facilitator.
private var s_f:Socket;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var fac_addr:Object;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main(fac_addr);
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main(fac_addr:Object):void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
Make fac_addr a local variable.
|
Make fac_addr a local variable.
|
ActionScript
|
mit
|
arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy
|
abffa4f45b2c132cc2607fc275aa47d2c0853b14
|
test/trace/trace_properties.as
|
test/trace/trace_properties.as
|
#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif
function new_empty_object () {
var hash = new Object ();
ASSetPropFlags (hash, null, 0, 7);
for (var prop in hash) {
hash[prop] = "to-be-deleted";
delete hash[prop];
}
return hash;
}
function hasOwnProperty (o, prop)
{
if (o.hasOwnProperty != undefined)
return o.hasOwnProperty (prop);
o.hasOwnProperty = ASnative (101, 5);
var result = o.hasOwnProperty (prop);
delete o.hasOwnProperty;
return result;
}
function new_info () {
return new_empty_object ();
}
function set_info (info, prop, id, value) {
info[prop + "_-_" + id] = value;
}
function get_info (info, prop, id) {
return info[prop + "_-_" + id];
}
function is_blaclisted (o, prop)
{
if (prop == "mySecretId" || prop == "globalSecretId")
return true;
if (o == _global.Camera && prop == "names")
return true;
if (o == _global.Microphone && prop == "names")
return true;
#if __SWF_VERSION__ < 6
if (prop == "__proto__" && o[prop] == undefined)
return true;
#endif
return false;
}
function trace_properties_recurse (o, prefix, identifier, level)
{
// to collect info about different properties
var info = new_info ();
// calculate indentation
var indentation = "";
for (var j = 0; j < level; j++) {
indentation = indentation + " ";
}
// mark the ones that are not hidden
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true)
set_info (info, prop, "hidden", false);
}
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
var hidden = new Array ();
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
if (get_info (info, prop, "hidden") != false) {
set_info (info, prop, "hidden", true);
hidden.push (prop);
}
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, hidden, 1, 0);
if (all.length == 0) {
trace (indentation + "no children");
return nextSecretId;
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
var old = o[prop];
var val = "hello " + o[prop];
o[prop] = val;
if (o[prop] != val)
{
set_info (info, prop, "constant", true);
// try changing value after removing constant propflag
ASSetPropFlags (o, prop, 0, 4);
o[prop] = val;
if (o[prop] != val) {
set_info (info, prop, "superconstant", true);
} else {
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
ASSetPropFlags (o, prop, 4);
}
else
{
set_info (info, prop, "constant", false);
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// remove constant flag
ASSetPropFlags (o, prop, 0, 4);
// try deleting
var old = o[prop];
delete o[prop];
if (hasOwnProperty (o, prop))
{
set_info (info, prop, "permanent", true);
}
else
{
set_info (info, prop, "permanent", false);
o[prop] = old;
}
// put constant flag back, if it was set
if (get_info (info, prop, "constant") == true)
ASSetPropFlags (o, prop, 4);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
// format propflags
var flags = "";
if (get_info (info, prop, "hidden") == true) {
flags += "h";
}
if (get_info (info, prop, "superpermanent") == true) {
flags += "P";
} else if (get_info (info, prop, "permanent") == true) {
flags += "p";
}
if (get_info (info, prop, "superconstant") == true) {
flags += "C";
} else if (get_info (info, prop, "constant") == true) {
flags += "c";
}
if (flags != "")
flags = " (" + flags + ")";
var value = "";
// add value depending on the type
if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
value += " : " + o[prop];
} else if (typeof (o[prop]) == "string") {
value += " : \"" + o[prop] + "\"";
}
// recurse if it's object or function and this is the place it has been
// named after
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
{
if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
o[prop]["mySecretId"])
{
trace (indentation + prop + flags + " = " + typeof (o[prop]));
trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop, level + 1);
}
else
{
trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
}
}
else
{
trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
}
}
}
function generate_names (o, prefix, identifier)
{
// mark the ones that are not hidden
var nothidden = new Array ();
for (var prop in o) {
nothidden.push (prop);
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
for (var prop in o)
{
if (is_blaclisted (o, prop) == false) {
// only get the ones that are not only in the __proto__
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, null, 1, 0);
ASSetPropFlags (o, nothidden, 0, 1);
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
if (hasOwnProperty (o[prop], "mySecretId")) {
all[i] = null; // don't recurse to it again
} else {
o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
identifier + "." + prop;
}
}
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (prop != null) {
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop);
}
}
}
function trace_properties (o, prefix, identifier)
{
_global["mySecretId"] = "_global";
_global.Object["mySecretId"] = "_global.Object";
_global.XMLNode["mySecretId"] = "_global.XMLNode";
generate_names (_global.Object, "_global", "Object");
generate_names (_global.XMLNode, "_global", "XMLNode");
generate_names (_global, "", "_global");
if (typeof (o) == "object" || typeof (o) == "function")
{
if (!o.hasOwnProperty ("mySecretId")) {
o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
generate_names (o, prefix, identifier);
}
if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o));
}
else
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
o["mySecretId"]);
}
trace_properties_recurse (o, prefix, identifier, 1);
}
else
{
var value = "";
if (typeof (o) == "number" || typeof (o) == "boolean") {
value += " : " + o;
} else if (typeof (o) == "string") {
value += " : \"" + o + "\"";
}
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o) + value);
}
}
|
#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif
function new_empty_object () {
var hash = new Object ();
ASSetPropFlags (hash, null, 0, 7);
for (var prop in hash) {
hash[prop] = "to-be-deleted";
delete hash[prop];
}
return hash;
}
function hasOwnProperty_inner (o, prop)
{
if (o.hasOwnProperty != undefined)
return o.hasOwnProperty (prop);
o.hasOwnProperty = ASnative (101, 5);
var result = o.hasOwnProperty (prop);
delete o.hasOwnProperty;
return result;
}
function hasOwnProperty (o, prop)
{
var result = hasOwnProperty_inner (o, prop);
#if __SWF_VERSION__ != 6
if (result == false) {
ASSetPropFlags (o, prop, 0, 256);
result = hasOwnProperty_inner (o, prop);
if (result)
ASSetPropFlags (o, prop, 256);
}
#endif
return result;
}
function new_info () {
return new_empty_object ();
}
function set_info (info, prop, id, value) {
info[prop + "_-_" + id] = value;
}
function get_info (info, prop, id) {
return info[prop + "_-_" + id];
}
function is_blaclisted (o, prop)
{
if (prop == "mySecretId" || prop == "globalSecretId")
return true;
if (o == _global.Camera && prop == "names")
return true;
if (o == _global.Microphone && prop == "names")
return true;
#if __SWF_VERSION__ < 6
if (prop == "__proto__" && o[prop] == undefined)
return true;
#endif
return false;
}
function trace_properties_recurse (o, prefix, identifier, level)
{
// to collect info about different properties
var info = new_info ();
// calculate indentation
var indentation = "";
for (var j = 0; j < level; j++) {
indentation = indentation + " ";
}
// mark the ones that are not hidden
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true)
set_info (info, prop, "hidden", false);
}
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
var hidden = new Array ();
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
if (get_info (info, prop, "hidden") != false) {
set_info (info, prop, "hidden", true);
hidden.push (prop);
}
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, hidden, 1, 0);
if (all.length == 0) {
trace (indentation + "no children");
return nextSecretId;
}
#if __SWF_VERSION__ != 6
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
if (!hasOwnProperty_inner(o, prop) && hasOwnProperty(o, prop))
{
set_info (info, prop, "not6", true);
}
else
{
set_info (info, prop, "not6", false);
}
}
#endif
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
var old = o[prop];
var val = "hello " + o[prop];
o[prop] = val;
if (o[prop] != val)
{
set_info (info, prop, "constant", true);
// try changing value after removing constant propflag
ASSetPropFlags (o, prop, 0, 4);
o[prop] = val;
if (o[prop] != val) {
set_info (info, prop, "superconstant", true);
} else {
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
ASSetPropFlags (o, prop, 4);
}
else
{
set_info (info, prop, "constant", false);
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// remove constant flag
ASSetPropFlags (o, prop, 0, 4);
// try deleting
var old = o[prop];
delete o[prop];
if (hasOwnProperty (o, prop))
{
set_info (info, prop, "permanent", true);
}
else
{
set_info (info, prop, "permanent", false);
o[prop] = old;
}
// put constant flag back, if it was set
if (get_info (info, prop, "constant") == true)
ASSetPropFlags (o, prop, 4);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
// format propflags
var flags = "";
if (get_info (info, prop, "hidden") == true) {
flags += "h";
}
if (get_info (info, prop, "superpermanent") == true) {
flags += "P";
} else if (get_info (info, prop, "permanent") == true) {
flags += "p";
}
if (get_info (info, prop, "superconstant") == true) {
flags += "C";
} else if (get_info (info, prop, "constant") == true) {
flags += "c";
}
if (get_info (info, prop, "not6") == true) {
flags += "6";
}
if (flags != "")
flags = " (" + flags + ")";
var value = "";
// add value depending on the type
if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
value += " : " + o[prop];
} else if (typeof (o[prop]) == "string") {
value += " : \"" + o[prop] + "\"";
}
// recurse if it's object or function and this is the place it has been
// named after
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
{
if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
o[prop]["mySecretId"])
{
trace (indentation + prop + flags + " = " + typeof (o[prop]));
trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop, level + 1);
}
else
{
trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
}
}
else
{
trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
}
}
}
function generate_names (o, prefix, identifier)
{
// mark the ones that are not hidden
var nothidden = new Array ();
for (var prop in o) {
nothidden.push (prop);
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
for (var prop in o)
{
if (is_blaclisted (o, prop) == false) {
// only get the ones that are not only in the __proto__
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, null, 1, 0);
ASSetPropFlags (o, nothidden, 0, 1);
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
if (hasOwnProperty (o[prop], "mySecretId")) {
all[i] = null; // don't recurse to it again
} else {
o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
identifier + "." + prop;
}
}
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (prop != null) {
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop);
}
}
}
function trace_properties (o, prefix, identifier)
{
_global["mySecretId"] = "_global";
_global.Object["mySecretId"] = "_global.Object";
_global.XMLNode["mySecretId"] = "_global.XMLNode";
generate_names (_global.Object, "_global", "Object");
generate_names (_global.XMLNode, "_global", "XMLNode");
generate_names (_global, "", "_global");
if (typeof (o) == "object" || typeof (o) == "function")
{
if (!o.hasOwnProperty ("mySecretId")) {
o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
generate_names (o, prefix, identifier);
}
if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o));
}
else
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
o["mySecretId"]);
}
trace_properties_recurse (o, prefix, identifier, 1);
}
else
{
var value = "";
if (typeof (o) == "number" || typeof (o) == "boolean") {
value += " : " + o;
} else if (typeof (o) == "string") {
value += " : \"" + o + "\"";
}
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o) + value);
}
}
|
Make trace_properties.as detect properties with "not 6" flag and mark it
|
Make trace_properties.as detect properties with "not 6" flag and mark it
This only works on versions other than 6
|
ActionScript
|
lgpl-2.1
|
freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
|
ea484fadee74d0bda68cd9f0bdbf38fad1fa54a7
|
as3/com/netease/protobuf/VarintWriter.as
|
as3/com/netease/protobuf/VarintWriter.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*
public final class VarintWriter extends ByteArray {
private var bitsLeft:uint = 0
public function end():void {
if (length == 1) {
this[0] &= 0x7F
} else {
for (var i:uint = length; i > 0; i--) {
const byte:uint = this[i - 1]
if (byte != 0x80) {
this[i - 1] = 0x7F & byte
length = i
return
}
}
}
}
public function write(number:uint, bits:uint):void {
if (bits <= bitsLeft) {
this[length - 1] |= number << (7 - bitsLeft)
bitsLeft -= bits
} else {
if (bitsLeft != 0) {
this[length - 1] |= number << (7 - bitsLeft)
bits -= bitsLeft
number >>>= bitsLeft
}
while (bits >= 7) {
writeByte(0x80 | number)
number >>>= 7
bits -= 7
}
writeByte(0x80 | number)
bitsLeft = 7 - bits
}
}
}
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*;
public final class VarintWriter extends ByteArray {
private var bitsLeft:uint = 0
public function end():void {
if (length == 1) {
this[0] &= 0x7F
} else {
for (var i:uint = length; i > 0;) {
const l:uint = i - 1
const byte:uint = this[l]
if (byte != 0x80) {
this[l] = byte & 0x7F
length = i
return
}
i = l
}
this[0] = 0
length = 1
}
}
public function write(number:uint, bits:uint):void {
if (bits <= bitsLeft) {
this[length - 1] |= number << (7 - bitsLeft)
bitsLeft -= bits
} else {
if (bitsLeft != 0) {
this[length - 1] |= number << (7 - bitsLeft)
bits -= bitsLeft
number >>>= bitsLeft
}
while (bits >= 7) {
writeByte(0x80 | number)
number >>>= 7
bits -= 7
}
writeByte(0x80 | number)
bitsLeft = 7 - bits
}
}
}
}
|
修复 Varint 大于 127 时组包错误的问题
|
修复 Varint 大于 127 时组包错误的问题
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
89e7d8c395cba68490c1af404d7039f9cf8aba9b
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/ButtonSkin.as
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/ButtonSkin.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.skins.ios7
{
import flash.display.DisplayObject;
import mx.core.DPIClassification;
import mx.core.mx_internal;
import mx.events.FlexEvent;
import spark.components.supportClasses.StyleableTextField;
import spark.skins.ios7.assets.Button_up;
import spark.skins.mobile.supportClasses.ButtonSkinBase;
use namespace mx_internal;
/**
* ActionScript-based skin for Button controls in mobile applications. The skin supports
* iconClass and labelPlacement. It uses FXG classes to
* implement the vector drawing.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class ButtonSkin extends ButtonSkinBase
{
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* An array of color distribution ratios.
* This is used in the chrome color fill.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
mx_internal static const CHROME_COLOR_RATIOS:Array = [0, 127.5];
/**
* An array of alpha values for the corresponding colors in the colors array.
* This is used in the chrome color fill.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
mx_internal static const CHROME_COLOR_ALPHAS:Array = [1, 1];
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function ButtonSkin()
{
super();
//In iOS7, buttons look like simple links, without any shape containing the text
//We still need to assign an asset to determine the size of the button
//Button_up is a simple transparent graphic object
upBorderSkin = spark.skins.ios7.assets.Button_up;
downBorderSkin = spark.skins.ios7.assets.Button_up;
layoutCornerEllipseSize = 0;
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
layoutGap = 20;
layoutPaddingLeft = 40;
layoutPaddingRight = 40;
layoutPaddingTop = 40;
layoutPaddingBottom = 40;
layoutBorderSize = 2;
measuredDefaultWidth = 128;
measuredDefaultHeight = 172;
break;
}
case DPIClassification.DPI_480:
{
layoutGap = 14;
layoutPaddingLeft = 30;
layoutPaddingRight = 30;
layoutPaddingTop = 30;
layoutPaddingBottom = 30;
layoutBorderSize = 2;
measuredDefaultWidth = 96;
measuredDefaultHeight = 130;
break;
}
case DPIClassification.DPI_320:
{
layoutGap = 10;
layoutPaddingLeft = 20;
layoutPaddingRight = 20;
layoutPaddingTop = 20;
layoutPaddingBottom = 20;
layoutBorderSize = 2;
measuredDefaultWidth = 64;
measuredDefaultHeight = 86;
break;
}
case DPIClassification.DPI_240:
{
layoutGap = 7;
layoutPaddingLeft = 15;
layoutPaddingRight = 15;
layoutPaddingTop = 15;
layoutPaddingBottom = 15;
layoutBorderSize = 1;
measuredDefaultWidth = 48;
measuredDefaultHeight = 65;
break;
}
case DPIClassification.DPI_120:
{
layoutGap = 4;
layoutPaddingLeft = 8;
layoutPaddingRight = 8;
layoutPaddingTop = 8;
layoutPaddingBottom = 8;
layoutBorderSize = 1;
measuredDefaultWidth = 24;
measuredDefaultHeight = 33;
break;
}
default:
{
layoutGap = 5;
layoutPaddingLeft = 10;
layoutPaddingRight = 10;
layoutPaddingTop = 10;
layoutPaddingBottom = 10;
layoutBorderSize = 1;
measuredDefaultWidth = 32;
measuredDefaultHeight = 43;
break;
}
}
}
//--------------------------------------------------------------------------
//
// Layout variables
//
//--------------------------------------------------------------------------
/**
* Defines the corner radius.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
protected var layoutCornerEllipseSize:uint;
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var _border:DisplayObject;
private var changeFXGSkin:Boolean = false;
private var borderClass:Class;
mx_internal var fillColorStyleName:String = "chromeColor";
/**
* Defines the shadow for the Button control's label.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var labelDisplayShadow:StyleableTextField;
/**
* Read-only button border graphic. Use getBorderClassForCurrentState()
* to specify a graphic per-state.
*
* @see #getBorderClassForCurrentState()
*/
protected function get border():DisplayObject
{
return _border;
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* Class to use for the border in the up state.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
* @default Button_up
*/
protected var upBorderSkin:Class;
/**
* Class to use for the border in the down state.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
* @default Button_down
*/
protected var downBorderSkin:Class;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
super.createChildren();
if (!labelDisplayShadow && labelDisplay)
{
labelDisplayShadow = StyleableTextField(createInFontContext(StyleableTextField));
labelDisplayShadow.styleName = this;
labelDisplayShadow.colorName = "textShadowColor";
labelDisplayShadow.useTightTextBounds = false;
// add shadow before display
addChildAt(labelDisplayShadow, getChildIndex(labelDisplay));
}
setStyle("textAlign", "center");
}
/**
* @private
*/
override protected function commitCurrentState():void
{
super.commitCurrentState();
borderClass = getBorderClassForCurrentState();
if (!(_border is borderClass))
changeFXGSkin = true;
// update borderClass and background
invalidateDisplayList();
}
/**
* @private
*/
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
// size the FXG background
if (changeFXGSkin)
{
changeFXGSkin = false;
if (_border)
{
removeChild(_border);
_border = null;
}
if (borderClass)
{
_border = new borderClass();
addChildAt(_border, 0);
}
}
layoutBorder(unscaledWidth, unscaledHeight);
// update label shadow
labelDisplayShadow.alpha = getStyle("textShadowAlpha");
labelDisplayShadow.commitStyles();
// don't use tightText positioning on shadow
setElementPosition(labelDisplayShadow, labelDisplay.x, labelDisplay.y + 1);
setElementSize(labelDisplayShadow, labelDisplay.width, labelDisplay.height);
// if labelDisplay is truncated, then push it down here as well.
// otherwise, it would have gotten pushed in the labelDisplay_valueCommitHandler()
if (labelDisplay.isTruncated)
labelDisplayShadow.text = labelDisplay.text;
}
/**
* Position the background of the skin. Override this function to re-position the background.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void
{
setElementSize(border, unscaledWidth, unscaledHeight);
setElementPosition(border, 0, 0);
}
/**
* Returns the borderClass to use based on the currentState.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
protected function getBorderClassForCurrentState():Class
{
if (currentState == "down")
return downBorderSkin;
else
return upBorderSkin;
}
//--------------------------------------------------------------------------
//
// Event Handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function labelDisplay_valueCommitHandler(event:FlexEvent):void
{
super.labelDisplay_valueCommitHandler(event);
labelDisplayShadow.text = labelDisplay.text;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.skins.ios7
{
import flash.display.DisplayObject;
import mx.core.DPIClassification;
import mx.core.mx_internal;
import mx.events.FlexEvent;
import spark.components.supportClasses.StyleableTextField;
import spark.skins.ios7.assets.Button_up;
import spark.skins.mobile.supportClasses.ButtonSkinBase;
use namespace mx_internal;
/**
* ActionScript-based skin for Button controls in mobile applications. The skin supports
* iconClass and labelPlacement. It uses FXG classes to
* implement the vector drawing.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class ButtonSkin extends ButtonSkinBase
{
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* An array of color distribution ratios.
* This is used in the chrome color fill.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
mx_internal static const CHROME_COLOR_RATIOS:Array = [0, 127.5];
/**
* An array of alpha values for the corresponding colors in the colors array.
* This is used in the chrome color fill.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
mx_internal static const CHROME_COLOR_ALPHAS:Array = [1, 1];
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function ButtonSkin()
{
super();
//In iOS7, buttons look like simple links, without any shape containing the text
//We still need to assign an asset to determine the size of the button
//Button_up is a simple transparent graphic object
upBorderSkin = spark.skins.ios7.assets.Button_up;
downBorderSkin = spark.skins.ios7.assets.Button_up;
layoutCornerEllipseSize = 0;
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
layoutGap = 20;
layoutPaddingLeft = 40;
layoutPaddingRight = 40;
layoutPaddingTop = 40;
layoutPaddingBottom = 40;
layoutBorderSize = 2;
measuredDefaultWidth = 128;
measuredDefaultHeight = 172;
break;
}
case DPIClassification.DPI_480:
{
layoutGap = 14;
layoutPaddingLeft = 30;
layoutPaddingRight = 30;
layoutPaddingTop = 30;
layoutPaddingBottom = 30;
layoutBorderSize = 2;
measuredDefaultWidth = 96;
measuredDefaultHeight = 130;
break;
}
case DPIClassification.DPI_320:
{
layoutGap = 10;
layoutPaddingLeft = 20;
layoutPaddingRight = 20;
layoutPaddingTop = 20;
layoutPaddingBottom = 20;
layoutBorderSize = 2;
measuredDefaultWidth = 64;
measuredDefaultHeight = 86;
break;
}
case DPIClassification.DPI_240:
{
layoutGap = 7;
layoutPaddingLeft = 15;
layoutPaddingRight = 15;
layoutPaddingTop = 15;
layoutPaddingBottom = 15;
layoutBorderSize = 1;
measuredDefaultWidth = 48;
measuredDefaultHeight = 65;
break;
}
case DPIClassification.DPI_120:
{
layoutGap = 4;
layoutPaddingLeft = 8;
layoutPaddingRight = 8;
layoutPaddingTop = 8;
layoutPaddingBottom = 8;
layoutBorderSize = 1;
measuredDefaultWidth = 24;
measuredDefaultHeight = 33;
break;
}
default:
{
layoutGap = 5;
layoutPaddingLeft = 10;
layoutPaddingRight = 10;
layoutPaddingTop = 10;
layoutPaddingBottom = 10;
layoutBorderSize = 1;
measuredDefaultWidth = 32;
measuredDefaultHeight = 43;
break;
}
}
}
//--------------------------------------------------------------------------
//
// Layout variables
//
//--------------------------------------------------------------------------
/**
* Defines the corner radius.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
protected var layoutCornerEllipseSize:uint;
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var _border:DisplayObject;
private var changeFXGSkin:Boolean = false;
private var borderClass:Class;
mx_internal var fillColorStyleName:String = "chromeColor";
/**
* Defines the shadow for the Button control's label.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var labelDisplayShadow:StyleableTextField;
/**
* Read-only button border graphic. Use getBorderClassForCurrentState()
* to specify a graphic per-state.
*
* @see #getBorderClassForCurrentState()
*/
protected function get border():DisplayObject
{
return _border;
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* Class to use for the border in the up state.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
* @default Button_up
*/
protected var upBorderSkin:Class;
/**
* Class to use for the border in the down state.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
* @default Button_down
*/
protected var downBorderSkin:Class;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
super.createChildren();
setStyle("textAlign", "center");
}
/**
* @private
*/
override protected function commitCurrentState():void
{
super.commitCurrentState();
borderClass = getBorderClassForCurrentState();
if (!(_border is borderClass))
changeFXGSkin = true;
// update borderClass and background
invalidateDisplayList();
}
/**
* @private
*/
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
// size the FXG background
if (changeFXGSkin)
{
changeFXGSkin = false;
if (_border)
{
removeChild(_border);
_border = null;
}
if (borderClass)
{
_border = new borderClass();
addChildAt(_border, 0);
}
}
layoutBorder(unscaledWidth, unscaledHeight);
}
/**
* Position the background of the skin. Override this function to re-position the background.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
mx_internal function layoutBorder(unscaledWidth:Number, unscaledHeight:Number):void
{
setElementSize(border, unscaledWidth, unscaledHeight);
setElementPosition(border, 0, 0);
}
/**
* Returns the borderClass to use based on the currentState.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
protected function getBorderClassForCurrentState():Class
{
if (currentState == "down")
return downBorderSkin;
else
return upBorderSkin;
}
//--------------------------------------------------------------------------
//
// Event Handlers
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function labelDisplay_valueCommitHandler(event:FlexEvent):void
{
super.labelDisplay_valueCommitHandler(event);
}
}
}
|
Remove labeldisplayshadow since it is not required
|
Remove labeldisplayshadow since it is not required
|
ActionScript
|
apache-2.0
|
shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk
|
a644190f6c8f02fedf079be37a53ee17c2c6d4ce
|
WeaveJS/src/weavejs/util/DateUtils.as
|
WeaveJS/src/weavejs/util/DateUtils.as
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This file is part of Weave.
*
* The Initial Developer of Weave is the Institute for Visualization
* and Perception Research at the University of Massachusetts Lowell.
* Portions created by the Initial Developer are Copyright (C) 2008-2015
* the Initial Developer. All Rights Reserved.
*
* 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/.
*
* ***** END LICENSE BLOCK ***** */
package weavejs.util
{
public class DateUtils
{
/**
* This must be set externally.
*/
public static var moment:Object;
public static function parse(date:Object, moment_fmt:String, force_utc:Boolean = false, force_local:Boolean = false):Date
{
if (moment_fmt)
return moment(date, moment_fmt, true).toDate();
return moment(date).toDate();
}
public static function format(date:Object, moment_fmt:String):String
{
return moment(date).format(moment_fmt);
}
public static function formatDuration(date:Object):String
{
return moment.duration(date).humanize();
}
public static function detectFormats(dates:Array/*/<string>/*/, moment_formats:Array/*/<string>/*/):Array/*/<string>/*/
{
var validFormatsSparse:Array = [].concat(moment_formats);
var fmt:String;
for each (var date:String in dates)
{
for (var fmtIdx:String in validFormatsSparse)
{
fmt = validFormatsSparse[fmtIdx];
if (!fmt)
continue;
var m:Object = new moment(date, fmt, true);
if (!m.isValid())
{
validFormatsSparse[fmtIdx] = null;
}
}
}
var validFormats:Array = [];
for each (fmt in validFormatsSparse)
{
if (fmt !== null)
{
validFormats.push(fmt);
}
}
return validFormats;
}
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This file is part of Weave.
*
* The Initial Developer of Weave is the Institute for Visualization
* and Perception Research at the University of Massachusetts Lowell.
* Portions created by the Initial Developer are Copyright (C) 2008-2015
* the Initial Developer. All Rights Reserved.
*
* 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/.
*
* ***** END LICENSE BLOCK ***** */
package weavejs.util
{
public class DateUtils
{
/**
* This must be set externally.
*/
public static var moment:Object;
public static function parse(date:Object, moment_fmt:String, force_utc:Boolean = false, force_local:Boolean = false):Date
{
if (moment_fmt)
return moment(date, moment_fmt, true).toDate();
return moment(date).toDate();
}
public static function format(date:Object, moment_fmt:String):String
{
return moment(date).format(moment_fmt);
}
public static function formatDuration(date:Object):String
{
return !isNaN(date as Number) ? moment.duration(date).humanize() : "";
}
public static function detectFormats(dates:Array/*/<string>/*/, moment_formats:Array/*/<string>/*/):Array/*/<string>/*/
{
var validFormatsSparse:Array = [].concat(moment_formats);
var fmt:String;
for each (var date:String in dates)
{
for (var fmtIdx:String in validFormatsSparse)
{
fmt = validFormatsSparse[fmtIdx];
if (!fmt)
continue;
var m:Object = new moment(date, fmt, true);
if (!m.isValid())
{
validFormatsSparse[fmtIdx] = null;
}
}
}
var validFormats:Array = [];
for each (fmt in validFormatsSparse)
{
if (fmt !== null)
{
validFormats.push(fmt);
}
}
return validFormats;
}
}
}
|
Add check for NaN in formatDuration. #WEAVE-616 Fixed Spent time 1h
|
Add check for NaN in formatDuration. #WEAVE-616 Fixed Spent time 1h
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
f25d002733718f152777521908fd210afa9df8c0
|
com/segonquart/menuIdiomes.as
|
com/segonquart/menuIdiomes.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class com.menuIdiomes extends MovieClip
{
public var fr:MovieClip;
public function menuIdiomes ()
{
this.onRollOver = this.over;
this.onRollOut = this.out;
this.onRelease =this.over;
}
private function over ()
{
fr.colorTo ("#95C60D", 0.3, "easeOutCirc");
}
private function out ()
{
fr.colorTo ("#010101", 0.3, "easeInCirc");
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuIdiomes extends MovieClip
{
public var fr:MovieClip;
public function menuIdiomes ()
{
this.onRollOver = this.over;
this.onRollOut = this.out;
this.onRelease =this.over;
}
private function over ()
{
fr.colorTo ("#95C60D", 0.3, "easeOutCirc");
}
private function out ()
{
fr.colorTo ("#010101", 0.3, "easeInCirc");
}
}
|
Update menuIdiomes.as
|
Update menuIdiomes.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
0e385a0e1aefd63c3cb300347e896355c01fce26
|
src/aerys/minko/render/shader/Shader.as
|
src/aerys/minko/render/shader/Shader.as
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko;
import aerys.minko.render.renderer.state.RendererState;
import aerys.minko.render.resource.ShaderResource;
import aerys.minko.render.resource.TextureResource;
import aerys.minko.render.shader.compiler.Compiler;
import aerys.minko.render.shader.compiler.allocator.ParameterAllocation;
import aerys.minko.render.shader.compiler.register.RegisterLimit;
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractParameter;
import aerys.minko.render.shader.node.leaf.StyleParameter;
import aerys.minko.render.shader.node.leaf.TransformParameter;
import aerys.minko.render.shader.node.leaf.WorldParameter;
import aerys.minko.scene.data.LocalData;
import aerys.minko.scene.data.StyleStack;
import aerys.minko.scene.data.ViewportData;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import aerys.minko.type.stream.format.VertexComponent;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
public class Shader
{
use namespace minko;
protected var _resource : ShaderResource;
protected var _lastFrameId : uint;
protected var _lastStyleStackVersion : uint;
protected var _lastTransformVersion : uint;
protected var _vsConstData : Vector.<Number>;
protected var _fsConstData : Vector.<Number>;
protected var _vsParams : Vector.<ParameterAllocation>;
protected var _fsParams : Vector.<ParameterAllocation>;
protected var _samplers : Vector.<int>;
public function get resource() : ShaderResource
{
return _resource;
}
public static function create(outputPosition : INode,
outputColor : INode) : Shader
{
var compiler : Compiler = new Compiler();
compiler.load(outputPosition, outputColor);
return compiler.compileShader();
}
public function Shader(vertexShader : ByteArray,
fragmentShader : ByteArray,
vertexInputComponents : Vector.<VertexComponent>,
vertexInputIndices : Vector.<uint>,
samplers : Vector.<int>,
vertexConstantData : Vector.<Number>,
fragmentConstantData : Vector.<Number>,
vertexParameters : Vector.<ParameterAllocation>,
fragmentParameters : Vector.<ParameterAllocation>)
{
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
_vsConstData = vertexConstantData;
_fsConstData = fragmentConstantData;
_vsParams = vertexParameters;
_fsParams = fragmentParameters;
_samplers = samplers;
_resource = new ShaderResource(vertexShader, fragmentShader, vertexInputComponents, vertexInputIndices);
}
public function fillRenderState(state : RendererState,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : Boolean
{
if (_lastFrameId != world[ViewportData].frameId)
{
_lastFrameId = world[ViewportData].frameId;
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
}
setTextures(state, styleStack, local, world);
setConstants(state, styleStack, local, world);
state.shader = _resource;
_lastStyleStackVersion = styleStack.version;
_lastTransformVersion = styleStack.version;
return true;
}
protected function setTextures(state : RendererState,
styleStack : StyleStack,
localData : LocalData,
worldData : Object) : void
{
var texture : TextureResource = null;
var samplerStyleId : int = 0;
var samplerCount : uint = _samplers.length;
for (var i : int = 0; i < samplerCount; ++i)
{
samplerStyleId = _samplers[i];
texture = styleStack.get(samplerStyleId) as TextureResource;
state.setTextureAt(i, texture);
}
}
protected function setConstants(state : RendererState,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : void
{
updateConstData(_vsConstData, _vsParams, styleStack, local, world);
updateConstData(_fsConstData, _fsParams, styleStack, local, world);
state.setVertexConstants(_vsConstData);
state.setFragmentConstants(_fsConstData);
}
protected function updateConstData(constData : Vector.<Number>,
paramsAllocs : Vector.<ParameterAllocation>,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : void
{
var paramLength : int = paramsAllocs.length;
for (var i : int = 0; i < paramLength; ++i)
{
var paramAlloc : ParameterAllocation = paramsAllocs[i];
var param : AbstractParameter = paramAlloc._parameter;
if ((param is StyleParameter && styleStack.version == _lastStyleStackVersion) ||
(param is TransformParameter && local.version == _lastTransformVersion))
continue;
var data : Object = getParameterData(param, styleStack, local, world);
loadParameterData(paramAlloc, constData, data);
}
}
private function getParameterData(param : AbstractParameter,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : Object
{
if (param is StyleParameter)
{
if (param._index != -1)
return styleStack.get(param._key as int).getItem(param._index)[param._field];
else if (param._field != null)
return styleStack.get(param._key as int)[param._field];
else
return styleStack.get(param._key as int, null);
}
else if (param is WorldParameter)
{
var paramClass : Class = WorldParameter(param)._class;
if (param._index != -1)
return world[paramClass].getItem(param._index)[param._field];
else if (param._field != null)
return world[paramClass][param._field];
else
return world[paramClass];
}
else if (param is TransformParameter)
{
return local[param._key];
}
else
throw new Error('Unknown parameter type');
}
private function loadParameterData(paramAlloc : ParameterAllocation,
constData : Vector.<Number>,
data : Object) : void
{
var offset : uint = paramAlloc._offset;
var size : uint = paramAlloc._parameter._size;
if (data is int)
{
var intData : int = data as int;
if (size == 1)
{
constData[offset] = intData;
}
else if (size == 2)
{
constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (intData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
}
}
else if (data is uint)
{
var uintData : uint = data as uint;
if (size == 1)
{
constData[offset] = uintData;
}
else if (size == 2)
{
constData[offset] = ((uintData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (uintData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((uintData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (uintData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((uintData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((uintData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((uintData & 0x000000FF)) / 255.;
}
}
else if (data is Number)
{
if (size != 1)
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'defined as size=' + size + ' but only a Number was found');
constData[offset] = data as Number;
}
else if (data is Vector4)
{
var vectorData : Vector4 = data as Vector4;
constData[offset] = vectorData.x;
size >= 2 && (constData[int(offset + 1)] = vectorData.y);
size >= 3 && (constData[int(offset + 2)] = vectorData.z);
size >= 4 && (constData[int(offset + 3)] = vectorData.w);
}
else if (data is Matrix4x4)
{
(data as Matrix4x4).getRawData(constData, offset, true);
}
else if (data is Vector.<Vector4>)
{
var vectorVectorData : Vector.<Vector4> = data as Vector.<Vector4>;
var vectorVectorDataLength : uint = vectorVectorData.length;
for (var j : uint = 0; j < vectorVectorDataLength; ++j)
{
vectorData = vectorVectorData[j];
constData[offset + 4 * j] = vectorData.x;
constData[int(offset + 4 * j + 1)] = vectorData.y;
constData[int(offset + 4 * j + 2)] = vectorData.z;
constData[int(offset + 4 * j + 3)] = vectorData.w;
}
}
else if (data is Vector.<Matrix4x4>)
{
var matrixVectorData : Vector.<Matrix4x4> = data as Vector.<Matrix4x4>;
var matrixVectorDataLength : uint = matrixVectorData.length;
for (var i : uint = 0; i < matrixVectorDataLength; ++i)
{
matrixVectorData[i].getRawData(constData, offset + i * 16, true);
}
}
else if (data == null)
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'null and required by automatic shader');
}
else
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'neither a int, a Number, a Vector4 or a Matrix4x4. Unable to ' +
'map it to a shader constant.');
}
}
}
}
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko;
import aerys.minko.render.renderer.state.RendererState;
import aerys.minko.render.resource.ShaderResource;
import aerys.minko.render.resource.TextureResource;
import aerys.minko.render.shader.compiler.Compiler;
import aerys.minko.render.shader.compiler.allocator.ParameterAllocation;
import aerys.minko.render.shader.compiler.register.RegisterLimit;
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractParameter;
import aerys.minko.render.shader.node.leaf.StyleParameter;
import aerys.minko.render.shader.node.leaf.TransformParameter;
import aerys.minko.render.shader.node.leaf.WorldParameter;
import aerys.minko.scene.data.LocalData;
import aerys.minko.scene.data.StyleStack;
import aerys.minko.scene.data.ViewportData;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import aerys.minko.type.stream.format.VertexComponent;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
public class Shader
{
use namespace minko;
protected var _resource : ShaderResource;
protected var _lastFrameId : uint;
protected var _lastStyleStackVersion : uint;
protected var _lastTransformVersion : uint;
protected var _vsConstData : Vector.<Number>;
protected var _fsConstData : Vector.<Number>;
protected var _vsParams : Vector.<ParameterAllocation>;
protected var _fsParams : Vector.<ParameterAllocation>;
protected var _samplers : Vector.<int>;
public function get resource() : ShaderResource
{
return _resource;
}
public static function create(outputPosition : INode,
outputColor : INode) : Shader
{
var compiler : Compiler = new Compiler();
compiler.load(outputPosition, outputColor);
return compiler.compileShader();
}
public function Shader(vertexShader : ByteArray,
fragmentShader : ByteArray,
vertexInputComponents : Vector.<VertexComponent>,
vertexInputIndices : Vector.<uint>,
samplers : Vector.<int>,
vertexConstantData : Vector.<Number>,
fragmentConstantData : Vector.<Number>,
vertexParameters : Vector.<ParameterAllocation>,
fragmentParameters : Vector.<ParameterAllocation>)
{
_lastFrameId = uint.MAX_VALUE;
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
_vsConstData = vertexConstantData;
_fsConstData = fragmentConstantData;
_vsParams = vertexParameters;
_fsParams = fragmentParameters;
_samplers = samplers;
_resource = new ShaderResource(vertexShader, fragmentShader, vertexInputComponents, vertexInputIndices);
}
public function fillRenderState(state : RendererState,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : Boolean
{
if (_lastFrameId != world[ViewportData].frameId)
{
_lastFrameId = world[ViewportData].frameId;
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
}
setTextures(state, styleStack, local, world);
setConstants(state, styleStack, local, world);
state.shader = _resource;
_lastStyleStackVersion = styleStack.version;
_lastTransformVersion = local.version;
return true;
}
protected function setTextures(state : RendererState,
styleStack : StyleStack,
localData : LocalData,
worldData : Object) : void
{
var texture : TextureResource = null;
var samplerStyleId : int = 0;
var samplerCount : uint = _samplers.length;
for (var i : int = 0; i < samplerCount; ++i)
{
samplerStyleId = _samplers[i];
texture = styleStack.get(samplerStyleId) as TextureResource;
state.setTextureAt(i, texture);
}
}
protected function setConstants(state : RendererState,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : void
{
updateConstData(_vsConstData, _vsParams, styleStack, local, world);
updateConstData(_fsConstData, _fsParams, styleStack, local, world);
state.setVertexConstants(_vsConstData);
state.setFragmentConstants(_fsConstData);
}
protected function updateConstData(constData : Vector.<Number>,
paramsAllocs : Vector.<ParameterAllocation>,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : void
{
var paramLength : int = paramsAllocs.length;
for (var i : int = 0; i < paramLength; ++i)
{
var paramAlloc : ParameterAllocation = paramsAllocs[i];
var param : AbstractParameter = paramAlloc._parameter;
if ((param is StyleParameter && styleStack.version == _lastStyleStackVersion) ||
(param is TransformParameter && local.version == _lastTransformVersion))
continue;
var data : Object = getParameterData(param, styleStack, local, world);
loadParameterData(paramAlloc, constData, data);
}
}
private function getParameterData(param : AbstractParameter,
styleStack : StyleStack,
local : LocalData,
world : Dictionary) : Object
{
if (param is StyleParameter)
{
if (param._index != -1)
return styleStack.get(param._key as int).getItem(param._index)[param._field];
else if (param._field != null)
return styleStack.get(param._key as int)[param._field];
else
return styleStack.get(param._key as int, null);
}
else if (param is WorldParameter)
{
var paramClass : Class = WorldParameter(param)._class;
if (param._index != -1)
return world[paramClass].getItem(param._index)[param._field];
else if (param._field != null)
return world[paramClass][param._field];
else
return world[paramClass];
}
else if (param is TransformParameter)
{
return local[param._key];
}
else
throw new Error('Unknown parameter type');
}
private function loadParameterData(paramAlloc : ParameterAllocation,
constData : Vector.<Number>,
data : Object) : void
{
var offset : uint = paramAlloc._offset;
var size : uint = paramAlloc._parameter._size;
if (data is int)
{
var intData : int = data as int;
if (size == 1)
{
constData[offset] = intData;
}
else if (size == 2)
{
constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (intData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
}
}
else if (data is uint)
{
var uintData : uint = data as uint;
if (size == 1)
{
constData[offset] = uintData;
}
else if (size == 2)
{
constData[offset] = ((uintData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (uintData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((uintData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (uintData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((uintData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((uintData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((uintData & 0x000000FF)) / 255.;
}
}
else if (data is Number)
{
if (size != 1)
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'defined as size=' + size + ' but only a Number was found');
constData[offset] = data as Number;
}
else if (data is Vector4)
{
var vectorData : Vector4 = data as Vector4;
constData[offset] = vectorData.x;
size >= 2 && (constData[int(offset + 1)] = vectorData.y);
size >= 3 && (constData[int(offset + 2)] = vectorData.z);
size >= 4 && (constData[int(offset + 3)] = vectorData.w);
}
else if (data is Matrix4x4)
{
(data as Matrix4x4).getRawData(constData, offset, true);
}
else if (data is Vector.<Vector4>)
{
var vectorVectorData : Vector.<Vector4> = data as Vector.<Vector4>;
var vectorVectorDataLength : uint = vectorVectorData.length;
for (var j : uint = 0; j < vectorVectorDataLength; ++j)
{
vectorData = vectorVectorData[j];
constData[offset + 4 * j] = vectorData.x;
constData[int(offset + 4 * j + 1)] = vectorData.y;
constData[int(offset + 4 * j + 2)] = vectorData.z;
constData[int(offset + 4 * j + 3)] = vectorData.w;
}
}
else if (data is Vector.<Matrix4x4>)
{
var matrixVectorData : Vector.<Matrix4x4> = data as Vector.<Matrix4x4>;
var matrixVectorDataLength : uint = matrixVectorData.length;
for (var i : uint = 0; i < matrixVectorDataLength; ++i)
{
matrixVectorData[i].getRawData(constData, offset + i * 16, true);
}
}
else if (data == null)
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'null and required by automatic shader');
}
else
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'neither a int, a Number, a Vector4 or a Matrix4x4. Unable to ' +
'map it to a shader constant.');
}
}
}
}
|
Fix minor bug in Shader
|
Fix minor bug in Shader
|
ActionScript
|
mit
|
aerys/minko-as3
|
812c315b7f7fb707852c9c620d38159331371db1
|
src/com/google/analytics/GATracker.as
|
src/com/google/analytics/GATracker.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* 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.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.Ecommerce;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.IdleTimer;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerCache;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.events.AnalyticsEvent;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import core.version;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
private var _idleTimer:IdleTimer;
private var _ecom:Ecommerce;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:core.version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
else
{
this.config = config;
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = new Buffer( config, debug, false );
_gifRequest = new GIFRequest( config, debug, _buffer, _env );
_idleTimer = new IdleTimer( config, debug, _display, _buffer );
_ecom = new Ecommerce ( _debug );
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _ecom );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* Indicates the account value of the tracking.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value ;
}
/**
* Indicates if the tracker use a visual debug.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* 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.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.Ecommerce;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerCache;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.events.AnalyticsEvent;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import core.version;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.EventDispatcher;
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
private var _ecom:Ecommerce;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:core.version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
else
{
this.config = config;
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = new Buffer( config, debug, false );
_gifRequest = new GIFRequest( config, debug, _buffer, _env );
_ecom = new Ecommerce ( _debug );
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _ecom );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* Indicates the account value of the tracking.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value ;
}
/**
* Indicates if the tracker use a visual debug.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
remove idle timer instanciation
|
remove idle timer instanciation
|
ActionScript
|
apache-2.0
|
nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash
|
1c3736590651b4fa6fdf586cb3aedee6846edff0
|
src/aerys/minko/type/binding/DataProvider.as
|
src/aerys/minko/type/binding/DataProvider.as
|
package aerys.minko.type.binding
{
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class DataProvider extends Proxy implements IDynamicDataProvider
{
private var _usage : uint;
private var _name : String;
private var _descriptor : Object;
private var _propertyChanged : Signal;
private var _propertyAdded : Signal;
private var _propertyRemoved : Signal;
private var _nameToProperty : Object;
private var _propertyToNames : Dictionary;
public function get usage() : uint
{
return _usage;
}
public function get dataDescriptor() : Object
{
return _descriptor;
}
public function get propertyChanged() : Signal
{
return _propertyChanged;
}
public function get propertyAdded() : Signal
{
return _propertyAdded;
}
public function get propertyRemoved() : Signal
{
return _propertyRemoved;
}
public function get name() : String
{
return _name;
}
public function set name(v : String) : void
{
_name = v;
}
public function DataProvider(properties : Object = null,
name : String = null,
usage : uint = 1)
{
_name = name;
_usage = usage;
initialize(properties);
}
private function initialize(properties : Object) : void
{
_descriptor = {};
_propertyChanged = new Signal('DataProvider.changed');
_propertyAdded = new Signal('DataProvider.propertyAdded');
_propertyRemoved = new Signal('DataProvider.propertyRemoved');
_nameToProperty = {};
_propertyToNames = new Dictionary();
var propertyName : String = null;
if (properties is DataProvider)
{
var provider : DataProvider = properties as DataProvider;
for each (propertyName in provider.dataDescriptor)
setProperty(propertyName, provider[propertyName]);
}
else if (properties is Object)
{
for (propertyName in properties)
setProperty(propertyName, properties[propertyName]);
}
}
override flash_proxy function getProperty(name : *) : *
{
return getProperty(String(name));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
setProperty(String(name), value);
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
removeProperty(String(name));
return true;
}
public function getProperty(name : String) : *
{
return _nameToProperty[name];
}
public function setProperty(name : String, newValue : Object) : DataProvider
{
var oldValue : Object = _nameToProperty[name];
var oldMonitoredValue : IWatchable = oldValue as IWatchable;
var newMonitoredValue : IWatchable = newValue as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue];
var newPropertyNames : Vector.<String> = _propertyToNames[newMonitoredValue];
if (oldMonitoredValue != null)
{
if (oldPropertyNames.length == 1)
{
oldMonitoredValue.changed.remove(propertyChangedHandler);
delete _propertyToNames[oldMonitoredValue];
}
else
oldPropertyNames.splice(oldPropertyNames.indexOf(name), 1);
}
if (newMonitoredValue != null)
watchProperty(name, newMonitoredValue);
var propertyAdded : Boolean = !_descriptor.hasOwnProperty(name);
_descriptor[name] = name;
_nameToProperty[name] = newValue;
if (propertyAdded)
_propertyAdded.execute(this, name, name, newValue);
else
_propertyChanged.execute(this, name);
return this;
}
public function setProperties(properties : Object) : DataProvider
{
for (var propertyName : String in properties)
setProperty(propertyName, properties[propertyName]);
return this;
}
protected function watchProperty(name : String, property : IWatchable) : void
{
if (property != null)
{
var newPropertyNames : Vector.<String> = _propertyToNames[property] as Vector.<String>;
if (newPropertyNames == null)
{
_propertyToNames[property] = newPropertyNames = new <String>[name];
property.changed.add(propertyChangedHandler);
}
else
newPropertyNames.push(name);
}
}
public function removeProperty(name : String) : DataProvider
{
if (_descriptor.hasOwnProperty(name))
{
var oldMonitoredValue : IWatchable = _nameToProperty[name] as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue];
var bindingName : String = _descriptor[name];
delete _descriptor[name];
delete _nameToProperty[name];
if (oldMonitoredValue != null)
{
if (oldPropertyNames.length == 1)
{
oldMonitoredValue.changed.remove(propertyChangedHandler);
delete _propertyToNames[oldMonitoredValue];
}
else
oldPropertyNames.splice(oldPropertyNames.indexOf(name), 1);
}
// _changed.execute(this, 'dataDescriptor');
_propertyRemoved.execute(this, name, bindingName, oldMonitoredValue);
}
return this;
}
public function removeAllProperties() : DataProvider
{
for (var propertyName : String in _nameToProperty)
removeProperty(propertyName);
return this;
}
public function propertyExists(name : String) : Boolean
{
return _descriptor.hasOwnProperty(name);
}
public function invalidate() : DataProvider
{
_propertyChanged.execute(this, null);
return this;
}
public function clone() : IDataProvider
{
switch (_usage)
{
case DataProviderUsage.EXCLUSIVE:
return new DataProvider(_nameToProperty, _name + '_cloned', _usage);
case DataProviderUsage.SHARED:
return this;
case DataProviderUsage.MANAGED:
throw new Error('This dataprovider is managed, and must not be cloned');
default:
throw new Error('Unkown usage value');
}
}
private function propertyChangedHandler(source : IWatchable) : void
{
var names : Vector.<String> = _propertyToNames[source];
var numNames : uint = names.length;
for (var nameId : uint = 0; nameId < numNames; ++nameId)
_propertyChanged.execute(this, names[nameId]);
}
}
}
|
package aerys.minko.type.binding
{
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class DataProvider extends Proxy implements IDynamicDataProvider
{
private var _usage : uint;
private var _name : String;
private var _descriptor : Object;
private var _propertyChanged : Signal;
private var _propertyAdded : Signal;
private var _propertyRemoved : Signal;
private var _nameToProperty : Object;
private var _propertyToNames : Dictionary;
public function get usage() : uint
{
return _usage;
}
public function get dataDescriptor() : Object
{
return _descriptor;
}
public function get propertyChanged() : Signal
{
return _propertyChanged;
}
public function get propertyAdded() : Signal
{
return _propertyAdded;
}
public function get propertyRemoved() : Signal
{
return _propertyRemoved;
}
public function get name() : String
{
return _name;
}
public function set name(v : String) : void
{
_name = v;
}
public function DataProvider(properties : Object = null,
name : String = null,
usage : uint = 1)
{
_name = name;
_usage = usage;
initialize(properties);
}
private function initialize(properties : Object) : void
{
_descriptor = {};
_propertyChanged = new Signal('DataProvider.changed');
_propertyAdded = new Signal('DataProvider.propertyAdded');
_propertyRemoved = new Signal('DataProvider.propertyRemoved');
_nameToProperty = {};
_propertyToNames = new Dictionary();
var propertyName : String = null;
if (properties is DataProvider)
{
var provider : DataProvider = properties as DataProvider;
for each (propertyName in provider.dataDescriptor)
setProperty(propertyName, provider[propertyName]);
}
else if (properties is Object)
{
for (propertyName in properties)
setProperty(propertyName, properties[propertyName]);
}
}
override flash_proxy function getProperty(name : *) : *
{
return getProperty(String(name));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
setProperty(String(name), value);
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
removeProperty(String(name));
return true;
}
public function getProperty(name : String) : *
{
return _nameToProperty[name];
}
public function setProperty(name : String, newValue : Object) : DataProvider
{
var oldValue : Object = _nameToProperty[name];
var oldWatchedValue : IWatchable = oldValue as IWatchable;
var newWatchedValue : IWatchable = newValue as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldWatchedValue];
var newPropertyNames : Vector.<String> = _propertyToNames[newWatchedValue];
if (newWatchedValue != oldWatchedValue)
{
if (oldWatchedValue != null)
unwatchProperty(name, oldWatchedValue);
if (newWatchedValue != null)
watchProperty(name, newWatchedValue);
}
var propertyAdded : Boolean = !_descriptor.hasOwnProperty(name);
_descriptor[name] = name;
_nameToProperty[name] = newValue;
if (propertyAdded)
_propertyAdded.execute(this, name, name, newValue);
else
_propertyChanged.execute(this, name);
return this;
}
public function setProperties(properties : Object) : DataProvider
{
for (var propertyName : String in properties)
setProperty(propertyName, properties[propertyName]);
return this;
}
protected function watchProperty(name : String, property : IWatchable) : void
{
if (property != null)
{
var newPropertyNames : Vector.<String> = _propertyToNames[property] as Vector.<String>;
if (newPropertyNames == null)
{
_propertyToNames[property] = newPropertyNames = new <String>[name];
property.changed.add(propertyChangedHandler);
}
else
newPropertyNames.push(name);
}
}
protected function unwatchProperty(name : String, property : IWatchable) : void
{
var oldPropertyNames : Vector.<String> = _propertyToNames[property];
if (oldPropertyNames.length == 1)
{
property.changed.remove(propertyChangedHandler);
delete _propertyToNames[property];
}
else
{
var numPropertyNames : uint = oldPropertyNames.length - 1;
oldPropertyNames[oldPropertyNames.indexOf(name)] = oldPropertyNames[numPropertyNames];
oldPropertyNames.length = numPropertyNames;
}
}
public function removeProperty(name : String) : DataProvider
{
if (_descriptor.hasOwnProperty(name))
{
var oldMonitoredValue : IWatchable = _nameToProperty[name] as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue];
var bindingName : String = _descriptor[name];
delete _descriptor[name];
delete _nameToProperty[name];
if (oldMonitoredValue != null)
unwatchProperty(name, oldMonitoredValue);
// _changed.execute(this, 'dataDescriptor');
_propertyRemoved.execute(this, name, bindingName, oldMonitoredValue);
}
return this;
}
public function removeAllProperties() : DataProvider
{
for (var propertyName : String in _nameToProperty)
removeProperty(propertyName);
return this;
}
public function propertyExists(name : String) : Boolean
{
return _descriptor.hasOwnProperty(name);
}
public function invalidate() : DataProvider
{
_propertyChanged.execute(this, null);
return this;
}
public function clone() : IDataProvider
{
switch (_usage)
{
case DataProviderUsage.EXCLUSIVE:
return new DataProvider(_nameToProperty, _name + '_cloned', _usage);
case DataProviderUsage.SHARED:
return this;
case DataProviderUsage.MANAGED:
throw new Error('This dataprovider is managed, and must not be cloned');
default:
throw new Error('Unkown usage value');
}
}
private function propertyChangedHandler(source : IWatchable) : void
{
var names : Vector.<String> = _propertyToNames[source];
var numNames : uint = names.length;
for (var nameId : uint = 0; nameId < numNames; ++nameId)
_propertyChanged.execute(this, names[nameId]);
}
}
}
|
add DataProvider.unwatchProperty() protected method to unwatch a property and refactor other methods to use it
|
add DataProvider.unwatchProperty() protected method to unwatch a property and refactor other methods to use it
|
ActionScript
|
mit
|
aerys/minko-as3
|
03be372ed926b1b41f0b392c4441468bd80f98d5
|
src/org/mangui/jwplayer/media/HLSProvider.as
|
src/org/mangui/jwplayer/media/HLSProvider.as
|
package org.mangui.jwplayer.media {
import org.mangui.HLS.parsing.Level;
import org.mangui.HLS.*;
import org.mangui.HLS.utils.Log;
import org.mangui.HLS.utils.ScaleVideo;
import com.longtailvideo.jwplayer.events.MediaEvent;
import com.longtailvideo.jwplayer.model.PlayerConfig;
import com.longtailvideo.jwplayer.model.PlaylistItem;
import com.longtailvideo.jwplayer.media.*;
import com.longtailvideo.jwplayer.player.PlayerState;
import com.longtailvideo.jwplayer.utils.RootReference;
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.media.StageVideo;
import flash.system.Capabilities;
import flash.events.Event;
/** JW Player provider for hls streaming. **/
public class HLSProvider extends MediaProvider {
/** Reference to the framework. **/
protected var _hls : HLS;
/** Current quality level. **/
protected var _level : Number;
/** Reference to the quality levels. **/
protected var _levels : Vector.<Level>;
/** Reference to the video object. **/
private var _video : Video;
/** Reference to the stage video element. **/
private var _stageVideo : StageVideo;
/** Whether or not StageVideo is enabled (not working with JW5) **/
protected var _stageEnabled : Boolean = false;
/** current position **/
protected var _media_position : Number;
/** Video Original size **/
private var _videoWidth : Number = 0;
private var _videoHeight : Number = 0;
private var _seekInLiveDurationThreshold : Number = 60;
public function HLSProvider() {
super('hls');
};
/** Forward completes from the framework. **/
private function _completeHandler(event : HLSEvent) : void {
complete();
};
/** Forward playback errors from the framework. **/
private function _errorHandler(event : HLSEvent) : void {
super.error(event.error.msg);
};
/** Forward QOS metrics on fragment load. **/
protected function _fragmentHandler(event : HLSEvent) : void {
_level = event.metrics.level;
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata:{bandwidth:Math.round(event.metrics.bandwidth / 1024), droppedFrames:_hls.stream.info.droppedFrames, currentLevel:(_level + 1) + ' of ' + _levels.length + ' (' + Math.round(_levels[_level].bitrate / 1024) + 'kbps, ' + _levels[_level].width + 'px)', width:_videoWidth}});
};
/** Update video A/R on manifest load. **/
private function _manifestHandler(event : HLSEvent) : void {
_levels = event.levels;
// only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold
if (_hls.type == HLSTypes.VOD || _levels[0].duration > _seekInLiveDurationThreshold) {
item.duration = _levels[0].duration;
} else {
item.duration = -1;
}
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {position:0, duration:item.duration});
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
/* start playback on manifest load */
if (item.start != 0) {
_hls.stream.seek(item.start);
} else {
_hls.stream.play();
}
};
/** Update playback position. **/
private function _mediaTimeHandler(event : HLSEvent) : void {
// only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold
if (_hls.type == HLSTypes.VOD || event.mediatime.duration > _seekInLiveDurationThreshold) {
item.duration = event.mediatime.duration;
_media_position = Math.max(0, event.mediatime.position);
var _bufferPercent : Number = 100 * (_media_position + event.mediatime.buffer) / event.mediatime.duration;
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {bufferPercent:_bufferPercent, offset:0, position:_media_position, duration:event.mediatime.duration});
}
var videoWidth : Number;
var videoHeight : Number;
if (_stageVideo) {
videoWidth = _stageVideo.videoWidth;
videoHeight = _stageVideo.videoHeight;
} else {
videoWidth = _video.videoWidth;
videoHeight = _video.videoHeight;
}
if (videoWidth && videoHeight) {
if (_videoWidth != videoWidth || _videoHeight != videoHeight) {
_videoHeight = videoHeight;
_videoWidth = videoWidth;
Log.info("video size changed to " + _videoWidth + "/" + _videoHeight);
// force resize to adjust video A/R
resize(videoWidth, _videoHeight);
}
}
};
/** Forward state changes from the framework. **/
private function _stateHandler(event : HLSEvent) : void {
switch(event.state) {
case HLSPlayStates.IDLE:
setState(PlayerState.IDLE);
break;
case HLSPlayStates.PLAYING_BUFFERING:
case HLSPlayStates.PAUSED_BUFFERING:
setState(PlayerState.BUFFERING);
break;
case HLSPlayStates.PLAYING:
_video.visible = true;
setState(PlayerState.PLAYING);
break;
case HLSPlayStates.PAUSED:
setState(PlayerState.PAUSED);
break;
}
};
private function _audioHandler(e : Event) : void {
media = null;
// sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED);
// dispatchEvent(new MediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED));
}
/** Set the volume on init. **/
override public function initializeMediaProvider(cfg : PlayerConfig) : void {
super.initializeMediaProvider(cfg);
_hls = new HLS();
_hls.stage = RootReference.stage;
_hls.stream.soundTransform = new SoundTransform(cfg.volume / 100);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.AUDIO_ONLY, _audioHandler);
// Allow stagevideo to be disabled by user config
if (cfg.hasOwnProperty('stagevideo') && cfg['stagevideo'].toString() == "false") {
_stageEnabled = false;
}
_video = new Video(320, 240);
_video.smoothing = true;
// Use stageVideo when available
if (_stageEnabled && RootReference.stage.stageVideos.length > 0) {
_stageVideo = RootReference.stage.stageVideos[0];
_stageVideo.viewPort = new Rectangle(0, 0, 320, 240);
_stageVideo.attachNetStream(_hls.stream);
Log.info("stage video enabled");
} else {
_video.attachNetStream(_hls.stream);
}
_level = 0;
var value : Object;
// parse configuration parameters
value = cfg.hls_debug;
if (value != null) {
Log.info("hls_debug:" + value);
Log.LOG_DEBUG_ENABLED = value as Boolean;
}
value = cfg.hls_debug2;
if (value != null) {
Log.info("hls_debug2:" + value);
Log.LOG_DEBUG2_ENABLED = value as Boolean;
}
value = cfg.hls_minbufferlength;
if (value != null) {
Log.info("hls_minbufferlength:" + value);
_hls.minBufferLength = value as Number;
}
value = cfg.hls_maxbufferlength;
if (value != null) {
Log.info("hls_maxbufferlength:" + value);
_hls.maxBufferLength = value as Number;
}
value = cfg.hls_lowbufferlength;
if (value != null) {
Log.info("hls_lowbufferlength:" + value);
_hls.lowBufferLength = value as Number;
}
value = cfg.hls_startfromlowestlevel;
if (value != null) {
Log.info("hls_startfromlowestlevel:" + value);
_hls.startFromLowestLevel = value as Boolean;
}
value = cfg.hls_seekfromlowestlevel;
if (value != null) {
Log.info("hls_seekfromlowestlevel:" + value);
_hls.seekFromLowestLevel = value as Boolean;
}
value = cfg.hls_live_flushurlcache;
if (value != null) {
Log.info("hls_live_flushurlcache:" + value);
_hls.flushLiveURLCache = value as Boolean;
}
value = cfg.hls_live_seekdurationthreshold;
if (value != null) {
Log.info("hls_live_seekdurationthreshold:" + value);
_seekInLiveDurationThreshold = value as Number;
}
value = cfg.hls_seekmode;
if (value != null) {
Log.info("hls_seekmode:" + value);
_hls.seekMode = value as String;
}
value = cfg.hls_fragmentloadmaxretry;
if (value != null) {
Log.info("hls_fragmentloadmaxretry:" + value);
_hls.fragmentLoadMaxRetry = value as Number;
}
value = cfg.hls_manifestloadmaxretry;
if (value != null) {
Log.info("hls_manifestloadmaxretry:" + value);
_hls.manifestLoadMaxRetry = value as Number;
}
value = cfg.hls_capleveltostage;
if (value != null) {
Log.info("hls_capleveltostage:" + value);
if (value as Boolean == true) {
_hls.capLeveltoStage = true;
}
}
mute(cfg.mute);
};
/** Check that Flash Player version is sufficient (10.1 or above) **/
private function _checkVersion() : Number {
var versionStr : String = Capabilities.version;
var verArray : Array = versionStr.split(/\s|,/);
var versionNum : Number = Number(String(verArray[1] + "." + verArray[2]));
return versionNum;
}
/** Load a new playlist item **/
override public function load(itm : PlaylistItem) : void {
// Check flash player version
var ver : Number = _checkVersion();
var minVersion : Number = 10.1;
if ( ver < minVersion ) {
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_ERROR, {message:"HLS streaming requires Flash Player 10.1 at mimimum"});
} else {
super.load(itm);
play();
}
};
/** Get the video object. **/
override public function get display() : DisplayObject {
return _video;
};
/** Resume playback of a paused item. **/
override public function play() : void {
if (state == PlayerState.PAUSED) {
_hls.stream.resume();
} else {
setState(PlayerState.BUFFERING);
_hls.load(item.file);
}
};
/** Pause a playing item. **/
override public function pause() : void {
_hls.stream.pause();
};
/** Do a resize on the video. **/
override public function resize(width : Number, height : Number) : void {
Log.info("resize video from [" + _videoWidth + "," + _videoHeight + "]" + "to [" + width + "," + height + "]");
_width = width;
_height = height;
if (_videoWidth && _videoHeight) {
var rect : Rectangle = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, width, height);
if (_stageVideo) {
_stageVideo.viewPort = rect;
} else {
_video.x = rect.x;
_video.y = rect.y;
_video.width = rect.width;
_video.height = rect.height;
}
}
};
/** Seek to a certain position in the item. **/
override public function seek(pos : Number) : void {
_hls.stream.seek(pos);
};
/** Change the playback volume of the item. **/
override public function setVolume(vol : Number) : void {
_hls.stream.soundTransform = new SoundTransform(vol / 100);
super.setVolume(vol);
};
/** Stop playback. **/
override public function stop() : void {
_hls.stream.close();
super.stop();
_hls.removeEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_level = 0;
};
}
}
|
package org.mangui.jwplayer.media {
import org.mangui.HLS.parsing.Level;
import org.mangui.HLS.*;
import org.mangui.HLS.utils.Log;
import org.mangui.HLS.utils.ScaleVideo;
import com.longtailvideo.jwplayer.events.MediaEvent;
import com.longtailvideo.jwplayer.model.PlayerConfig;
import com.longtailvideo.jwplayer.model.PlaylistItem;
import com.longtailvideo.jwplayer.media.*;
import com.longtailvideo.jwplayer.player.PlayerState;
import com.longtailvideo.jwplayer.utils.RootReference;
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import flash.media.SoundTransform;
import flash.media.Video;
import flash.media.StageVideo;
import flash.system.Capabilities;
import flash.events.Event;
/** JW Player provider for hls streaming. **/
public class HLSProvider extends MediaProvider {
/** Reference to the framework. **/
protected var _hls : HLS;
/** Current quality level. **/
protected var _level : Number;
/** Reference to the quality levels. **/
protected var _levels : Vector.<Level>;
/** Reference to the video object. **/
private var _video : Video;
/** Reference to the stage video element. **/
private var _stageVideo : StageVideo;
/** Whether or not StageVideo is enabled (not working with JW5) **/
protected var _stageEnabled : Boolean = false;
/** current position **/
protected var _media_position : Number;
/** Video Original size **/
private var _videoWidth : Number = 0;
private var _videoHeight : Number = 0;
private var _seekInLiveDurationThreshold : Number = 60;
public function HLSProvider() {
super('hls');
};
/** Forward completes from the framework. **/
private function _completeHandler(event : HLSEvent) : void {
complete();
};
/** Forward playback errors from the framework. **/
private function _errorHandler(event : HLSEvent) : void {
super.error(event.error.msg);
};
/** Forward QOS metrics on fragment load. **/
protected function _fragmentHandler(event : HLSEvent) : void {
_level = event.metrics.level;
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata:{bandwidth:Math.round(event.metrics.bandwidth / 1024), droppedFrames:_hls.stream.info.droppedFrames, currentLevel:(_level + 1) + ' of ' + _levels.length + ' (' + Math.round(_levels[_level].bitrate / 1024) + 'kbps, ' + _levels[_level].width + 'px)', width:_videoWidth}});
};
/** Update video A/R on manifest load. **/
private function _manifestHandler(event : HLSEvent) : void {
_levels = event.levels;
// only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold
if (_hls.type == HLSTypes.VOD || _levels[0].duration > _seekInLiveDurationThreshold) {
item.duration = _levels[0].duration;
} else {
item.duration = -1;
}
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {position:0, duration:item.duration});
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
/* start playback on manifest load */
if (item.start != 0) {
_hls.stream.seek(item.start);
} else {
_hls.stream.play();
}
};
/** Update playback position. **/
private function _mediaTimeHandler(event : HLSEvent) : void {
// only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold
if (_hls.type == HLSTypes.VOD || event.mediatime.duration > _seekInLiveDurationThreshold) {
item.duration = event.mediatime.duration;
_media_position = Math.max(0, event.mediatime.position);
var _bufferPercent : Number = 100 * (_media_position + event.mediatime.buffer) / event.mediatime.duration;
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {bufferPercent:_bufferPercent, offset:0, position:_media_position, duration:event.mediatime.duration});
}
var videoWidth : Number;
var videoHeight : Number;
if (_stageVideo) {
videoWidth = _stageVideo.videoWidth;
videoHeight = _stageVideo.videoHeight;
} else {
videoWidth = _video.videoWidth;
videoHeight = _video.videoHeight;
}
if (videoWidth && videoHeight) {
if (_videoWidth != videoWidth || _videoHeight != videoHeight) {
_videoHeight = videoHeight;
_videoWidth = videoWidth;
Log.info("video size changed to " + _videoWidth + "/" + _videoHeight);
// force resize to adjust video A/R
resize(videoWidth, _videoHeight);
}
}
};
/** Forward state changes from the framework. **/
private function _stateHandler(event : HLSEvent) : void {
switch(event.state) {
case HLSPlayStates.IDLE:
setState(PlayerState.IDLE);
break;
case HLSPlayStates.PLAYING_BUFFERING:
case HLSPlayStates.PAUSED_BUFFERING:
setState(PlayerState.BUFFERING);
break;
case HLSPlayStates.PLAYING:
_video.visible = true;
setState(PlayerState.PLAYING);
break;
case HLSPlayStates.PAUSED:
setState(PlayerState.PAUSED);
break;
}
};
private function _audioHandler(e : Event) : void {
media = null;
// sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED);
// dispatchEvent(new MediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED));
}
/** Set the volume on init. **/
override public function initializeMediaProvider(cfg : PlayerConfig) : void {
super.initializeMediaProvider(cfg);
_hls = new HLS();
_hls.stage = RootReference.stage;
_hls.stream.soundTransform = new SoundTransform(cfg.volume / 100);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.AUDIO_ONLY, _audioHandler);
// Allow stagevideo to be disabled by user config
if (cfg.hasOwnProperty('stagevideo') && cfg['stagevideo'].toString() == "false") {
_stageEnabled = false;
}
_video = new Video(320, 240);
_video.smoothing = true;
// Use stageVideo when available
if (_stageEnabled && RootReference.stage.stageVideos.length > 0) {
_stageVideo = RootReference.stage.stageVideos[0];
_stageVideo.viewPort = new Rectangle(0, 0, 320, 240);
_stageVideo.attachNetStream(_hls.stream);
Log.info("stage video enabled");
} else {
_video.attachNetStream(_hls.stream);
}
_level = 0;
var value : Object;
// parse configuration parameters
value = cfg.hls_debug;
if (value != null) {
Log.info("hls_debug:" + value);
Log.LOG_DEBUG_ENABLED = value as Boolean;
}
value = cfg.hls_debug2;
if (value != null) {
Log.info("hls_debug2:" + value);
Log.LOG_DEBUG2_ENABLED = value as Boolean;
}
value = cfg.hls_minbufferlength;
if (value != null) {
Log.info("hls_minbufferlength:" + value);
_hls.minBufferLength = value as Number;
}
value = cfg.hls_maxbufferlength;
if (value != null) {
Log.info("hls_maxbufferlength:" + value);
_hls.maxBufferLength = value as Number;
}
value = cfg.hls_lowbufferlength;
if (value != null) {
Log.info("hls_lowbufferlength:" + value);
_hls.lowBufferLength = value as Number;
}
value = cfg.hls_startfromlowestlevel;
if (value != null) {
Log.info("hls_startfromlowestlevel:" + value);
_hls.startFromLowestLevel = value as Boolean;
}
value = cfg.hls_seekfromlowestlevel;
if (value != null) {
Log.info("hls_seekfromlowestlevel:" + value);
_hls.seekFromLowestLevel = value as Boolean;
}
value = cfg.hls_live_flushurlcache;
if (value != null) {
Log.info("hls_live_flushurlcache:" + value);
_hls.flushLiveURLCache = value as Boolean;
}
value = cfg.hls_live_seekdurationthreshold;
if (value != null) {
Log.info("hls_live_seekdurationthreshold:" + value);
_seekInLiveDurationThreshold = value as Number;
}
value = cfg.hls_seekmode;
if (value != null) {
Log.info("hls_seekmode:" + value);
_hls.seekMode = value as String;
}
value = cfg.hls_fragmentloadmaxretry;
if (value != null) {
Log.info("hls_fragmentloadmaxretry:" + value);
_hls.fragmentLoadMaxRetry = value as Number;
}
value = cfg.hls_manifestloadmaxretry;
if (value != null) {
Log.info("hls_manifestloadmaxretry:" + value);
_hls.manifestLoadMaxRetry = value as Number;
}
value = cfg.hls_capleveltostage;
if (value != null) {
Log.info("hls_capleveltostage:" + value);
if (value as Boolean == true) {
_hls.capLeveltoStage = true;
}
}
mute(cfg.mute);
};
/** Check that Flash Player version is sufficient (10.1 or above) **/
private function _checkVersion() : Number {
var versionStr : String = Capabilities.version;
var verArray : Array = versionStr.split(/\s|,/);
var versionNum : Number = Number(String(verArray[1] + "." + verArray[2]));
return versionNum;
}
/** Load a new playlist item **/
override public function load(itm : PlaylistItem) : void {
// Check flash player version
var ver : Number = _checkVersion();
var minVersion : Number = 11.6;
if ( ver < minVersion ) {
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_ERROR, {message:"This application requires Flash Player 11.6 at mimimum"});
} else {
super.load(itm);
play();
}
};
/** Get the video object. **/
override public function get display() : DisplayObject {
return _video;
};
public override function getRawMedia():DisplayObject
{
return display;
}
/** Resume playback of a paused item. **/
override public function play() : void {
if (state == PlayerState.PAUSED) {
_hls.stream.resume();
} else {
setState(PlayerState.BUFFERING);
_hls.load(item.file);
}
};
/** Pause a playing item. **/
override public function pause() : void {
_hls.stream.pause();
};
/** Do a resize on the video. **/
override public function resize(width : Number, height : Number) : void {
Log.info("resize video from [" + _videoWidth + "," + _videoHeight + "]" + "to [" + width + "," + height + "]");
_width = width;
_height = height;
if (_videoWidth && _videoHeight) {
var rect : Rectangle = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, width, height);
if (_stageVideo) {
_stageVideo.viewPort = rect;
} else {
_video.x = rect.x;
_video.y = rect.y;
_video.width = rect.width;
_video.height = rect.height;
}
}
};
/** Seek to a certain position in the item. **/
override public function seek(pos : Number) : void {
_hls.stream.seek(pos);
};
/** Change the playback volume of the item. **/
override public function setVolume(vol : Number) : void {
_hls.stream.soundTransform = new SoundTransform(vol / 100);
super.setVolume(vol);
};
/** Stop playback. **/
override public function stop() : void {
_hls.stream.close();
super.stop();
_hls.removeEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_level = 0;
};
}
}
|
Add missing getRawMedia overriding super method.
|
Add missing getRawMedia overriding super method.
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
4a2249943284de2723c18d29d540e4790fd78fdd
|
src/aerys/minko/render/DrawCall.as
|
src/aerys/minko/render/DrawCall.as
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.VertexBuffer3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.binding.IBinder;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.ColorMask;
import aerys.minko.type.enum.TriangleCulling;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display3D.Context3DProgramType;
import flash.utils.Dictionary;
/**
* DrawCall objects contain all the shader constants and buffer settings required
* to perform drawing operations using the Stage3D API.
* @author Jean-Marc Le Roux
*
*/
public final class DrawCall
{
use namespace minko_render;
private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX;
private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT;
private static const NUM_TEXTURES : uint = 8;
private static const NUM_VERTEX_BUFFERS : uint = 8;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true);
private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true);
private var _bindings : Object = null;
private var _vsInputComponents : Vector.<VertexComponent> = null;
private var _vsInputIndices : Vector.<uint> = null;
private var _cpuConstants : Dictionary = null;
private var _vsConstants : Vector.<Number> = null;
private var _fsConstants : Vector.<Number> = null;
private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true);
// states
private var _indexBuffer : IndexBuffer3DResource = null;
private var _firstIndex : int = 0;
private var _numTriangles : int = -1;
private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true);
private var _numVertexComponents: uint = 0;
private var _offsets : Vector.<int> = new Vector.<int>(8, true);
private var _formats : Vector.<String> = new Vector.<String>(8, true);
private var _blending : uint = 0;
private var _blendingSource : String = null;
private var _blendingDest : String = null;
private var _triangleCulling : uint = 0;
private var _triangleCullingStr : String = null;
private var _colorMask : uint = 0;
private var _colorMaskR : Boolean = true;
private var _colorMaskG : Boolean = true;
private var _colorMaskB : Boolean = true;
private var _colorMaskA : Boolean = true;
private var _enabled : Boolean = true;
private var _depth : Number = 0.;
private var _center : Vector4 = null;
private var _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
private var _bindingsConsumer : DrawCallBindingsConsumer;
public function get vertexComponents() : Vector.<VertexComponent>
{
return _vsInputComponents;
}
public function get blending() : uint
{
return _blending;
}
public function set blending(value : uint) : void
{
_blending = value;
_blendingSource = Blending.STRINGS[int(value & 0xffff)];
_blendingDest = Blending.STRINGS[int(value >>> 16)]
}
public function get triangleCulling() : uint
{
return _triangleCulling;
}
public function set triangleCulling(value : uint) : void
{
_triangleCulling = value;
_triangleCullingStr = TriangleCulling.STRINGS[value];
}
public function get colorMask() : uint
{
return _colorMask;
}
public function set colorMask(value : uint) : void
{
_colorMask = value;
_colorMaskR = (value & ColorMask.RED) != 0;
_colorMaskG = (value & ColorMask.GREEN) != 0;
_colorMaskB = (value & ColorMask.BLUE) != 0;
_colorMaskA = (value & ColorMask.ALPHA) != 0;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
if (_bindingsConsumer)
_bindingsConsumer.enabled = value;
}
public function get depth() : Number
{
if (_invalidDepth && _enabled)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
var worldSpacePosition : Vector4 = _localToWorld.transformVector(
_center, TMP_VECTOR4
);
var screenSpacePosition : Vector4 = _worldToScreen.transformVector(
worldSpacePosition, TMP_VECTOR4
);
_depth = screenSpacePosition.z / screenSpacePosition.w;
}
}
return _depth;
}
public function configure(program : Program3DResource,
geometry : Geometry,
meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
meshBindings.removeConsumer(_bindingsConsumer);
sceneBindings.removeConsumer(_bindingsConsumer);
if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler))
sceneBindings.removeCallback('worldToScreen', transformChangedHandler);
if (meshBindings.hasCallback('localToWorld', transformChangedHandler))
meshBindings.removeCallback('localToWorld', transformChangedHandler);
}
private function setProgram(program : Program3DResource) : void
{
_cpuConstants = new Dictionary();
_vsConstants = program._vsConstants.slice();
_fsConstants = program._fsConstants.slice();
_fsTextures = program._fsTextures.slice();
_vsInputComponents = program._vertexInputComponents;
_vsInputIndices = program._vertexInputIndices;
_bindings = program._bindings;
_bindingsConsumer = new DrawCallBindingsConsumer(
_bindings,
_cpuConstants,
_vsConstants,
_fsConstants,
_fsTextures
);
_bindingsConsumer.enabled = _enabled;
triangleCulling = TriangleCulling.FRONT;
blending = Blending.NORMAL;
colorMask = ColorMask.RGBA;
}
/**
* Ask geometry to compute additional vertex data if needed for this drawcall.
*/
public function updateGeometry(geometry : Geometry) : void
{
var vertexFormat : VertexFormat = geometry.format;
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace();
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0
&& !vertexFormat.hasComponent(VertexComponent.NORMAL))
{
geometry.computeNormals();
}
}
/**
* Obtain a reference to each buffer and offset that apply() may possibly need.
*
*/
public function setGeometry(geometry : Geometry, frame : uint = 0) : void
{
if (!_vsInputComponents)
return ;
updateGeometry(geometry);
_center = geometry.boundingSphere
? geometry.boundingSphere.center
: Vector4.ZERO;
_numVertexComponents = _vsInputComponents.length;
_indexBuffer = geometry.indexStream.resource;
_firstIndex = geometry.firstIndex;
_numTriangles = geometry.numTriangles;
for (var i : uint = 0; i < _numVertexComponents; ++i)
{
var component : VertexComponent = _vsInputComponents[i];
var index : uint = _vsInputIndices[i];
if (component)
{
var vertexStream : IVertexStream = geometry.getVertexStream(index + frame);
var stream : VertexStream = vertexStream.getStreamByComponent(component);
if (stream == null)
{
throw new Error(
'Missing vertex component: \'' + component.toString() + '\'.'
);
}
_vertexBuffers[i] = stream.resource;
_formats[i] = component.nativeFormatString;
_offsets[i] = stream.format.getOffsetForComponent(component);
}
}
}
/**
* @fixme There is a bug here
* @fixme We splitted properties between scene and mesh
* @fixme it should be done on the compiler also to avoid this ugly hack
*/
private function setBindings(meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
meshBindings.addConsumer(_bindingsConsumer);
sceneBindings.addConsumer(_bindingsConsumer);
if (computeDepth)
{
_worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4;
_localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4;
sceneBindings.addCallback('worldToScreen', transformChangedHandler);
meshBindings.addCallback('localToWorld', transformChangedHandler);
_invalidDepth = true;
}
}
public function apply(context : Context3DResource, previous : DrawCall) : uint
{
if (!_enabled)
return 0;
context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA)
.setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants)
.setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants);
var numTextures : uint = _fsTextures.length;
var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES;
var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS;
var i : uint = 0;
// setup textures
for (i = 0; i < numTextures; ++i)
{
context.setTextureAt(
i,
(_fsTextures[i] as ITextureResource).getTexture(context)
);
}
while (i < maxTextures)
context.setTextureAt(i++, null);
// setup buffers
for (i = 0; i < _numVertexComponents; ++i)
{
context.setVertexBufferAt(
i,
(_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context),
_offsets[i],
_formats[i]
);
}
while (i < maxBuffers)
context.setVertexBufferAt(i++, null);
// draw triangles
context.drawTriangles(
_indexBuffer.getIndexBuffer3D(context),
_firstIndex,
_numTriangles
);
return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles;
}
public function setParameter(name : String, value : Object) : void
{
_bindingsConsumer.setProperty(name, value);
}
private function transformChangedHandler(bindings : DataBindings,
property : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
if (property == 'worldToScreen')
_worldToScreen = newValue;
else if (property == 'localToWorld')
_localToWorld = newValue;
_invalidDepth = true;
}
}
}
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.VertexBuffer3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.binding.IBinder;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.ColorMask;
import aerys.minko.type.enum.TriangleCulling;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display3D.Context3DProgramType;
import flash.utils.Dictionary;
/**
* DrawCall objects contain all the shader constants and buffer settings required
* to perform drawing operations using the Stage3D API.
* @author Jean-Marc Le Roux
*
*/
public final class DrawCall
{
use namespace minko_render;
private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX;
private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT;
private static const NUM_TEXTURES : uint = 8;
private static const NUM_VERTEX_BUFFERS : uint = 8;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true);
private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true);
private var _bindings : Object = null;
private var _vsInputComponents : Vector.<VertexComponent> = null;
private var _vsInputIndices : Vector.<uint> = null;
private var _cpuConstants : Dictionary = null;
private var _vsConstants : Vector.<Number> = null;
private var _fsConstants : Vector.<Number> = null;
private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true);
// states
private var _indexBuffer : IndexBuffer3DResource = null;
private var _firstIndex : int = 0;
private var _numTriangles : int = -1;
private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true);
private var _numVertexComponents: uint = 0;
private var _offsets : Vector.<int> = new Vector.<int>(8, true);
private var _formats : Vector.<String> = new Vector.<String>(8, true);
private var _blending : uint = 0;
private var _blendingSource : String = null;
private var _blendingDest : String = null;
private var _triangleCulling : uint = 0;
private var _triangleCullingStr : String = null;
private var _colorMask : uint = 0;
private var _colorMaskR : Boolean = true;
private var _colorMaskG : Boolean = true;
private var _colorMaskB : Boolean = true;
private var _colorMaskA : Boolean = true;
private var _enabled : Boolean = true;
private var _depth : Number = 0.;
private var _center : Vector4 = null;
private var _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
private var _bindingsConsumer : DrawCallBindingsConsumer;
public function get vertexComponents() : Vector.<VertexComponent>
{
return _vsInputComponents;
}
public function get blending() : uint
{
return _blending;
}
public function set blending(value : uint) : void
{
_blending = value;
_blendingSource = Blending.STRINGS[int(value & 0xffff)];
_blendingDest = Blending.STRINGS[int(value >>> 16)]
}
public function get triangleCulling() : uint
{
return _triangleCulling;
}
public function set triangleCulling(value : uint) : void
{
_triangleCulling = value;
_triangleCullingStr = TriangleCulling.STRINGS[value];
}
public function get colorMask() : uint
{
return _colorMask;
}
public function set colorMask(value : uint) : void
{
_colorMask = value;
_colorMaskR = (value & ColorMask.RED) != 0;
_colorMaskG = (value & ColorMask.GREEN) != 0;
_colorMaskB = (value & ColorMask.BLUE) != 0;
_colorMaskA = (value & ColorMask.ALPHA) != 0;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
if (_bindingsConsumer)
_bindingsConsumer.enabled = value;
}
public function get depth() : Number
{
if (_invalidDepth && _enabled)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
var worldSpacePosition : Vector4 = _localToWorld.transformVector(
_center, TMP_VECTOR4
);
var screenSpacePosition : Vector4 = _worldToScreen.transformVector(
worldSpacePosition, TMP_VECTOR4
);
_depth = screenSpacePosition.z / screenSpacePosition.w;
}
}
return _depth;
}
public function configure(program : Program3DResource,
geometry : Geometry,
meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
if (_bindingsConsumer != null)
{
meshBindings.removeConsumer(_bindingsConsumer);
sceneBindings.removeConsumer(_bindingsConsumer);
}
if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler))
sceneBindings.removeCallback('worldToScreen', transformChangedHandler);
if (meshBindings.hasCallback('localToWorld', transformChangedHandler))
meshBindings.removeCallback('localToWorld', transformChangedHandler);
}
private function setProgram(program : Program3DResource) : void
{
_cpuConstants = new Dictionary();
_vsConstants = program._vsConstants.slice();
_fsConstants = program._fsConstants.slice();
_fsTextures = program._fsTextures.slice();
_vsInputComponents = program._vertexInputComponents;
_vsInputIndices = program._vertexInputIndices;
_bindings = program._bindings;
_bindingsConsumer = new DrawCallBindingsConsumer(
_bindings,
_cpuConstants,
_vsConstants,
_fsConstants,
_fsTextures
);
_bindingsConsumer.enabled = _enabled;
triangleCulling = TriangleCulling.FRONT;
blending = Blending.NORMAL;
colorMask = ColorMask.RGBA;
}
/**
* Ask geometry to compute additional vertex data if needed for this drawcall.
*/
public function updateGeometry(geometry : Geometry) : void
{
var vertexFormat : VertexFormat = geometry.format;
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace();
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0
&& !vertexFormat.hasComponent(VertexComponent.NORMAL))
{
geometry.computeNormals();
}
}
/**
* Obtain a reference to each buffer and offset that apply() may possibly need.
*
*/
public function setGeometry(geometry : Geometry, frame : uint = 0) : void
{
if (!_vsInputComponents)
return ;
updateGeometry(geometry);
_center = geometry.boundingSphere
? geometry.boundingSphere.center
: Vector4.ZERO;
_numVertexComponents = _vsInputComponents.length;
_indexBuffer = geometry.indexStream.resource;
_firstIndex = geometry.firstIndex;
_numTriangles = geometry.numTriangles;
for (var i : uint = 0; i < _numVertexComponents; ++i)
{
var component : VertexComponent = _vsInputComponents[i];
var index : uint = _vsInputIndices[i];
if (component)
{
var vertexStream : IVertexStream = geometry.getVertexStream(index + frame);
var stream : VertexStream = vertexStream.getStreamByComponent(component);
if (stream == null)
{
throw new Error(
'Missing vertex component: \'' + component.toString() + '\'.'
);
}
_vertexBuffers[i] = stream.resource;
_formats[i] = component.nativeFormatString;
_offsets[i] = stream.format.getOffsetForComponent(component);
}
}
}
/**
* @fixme There is a bug here
* @fixme We splitted properties between scene and mesh
* @fixme it should be done on the compiler also to avoid this ugly hack
*/
private function setBindings(meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
meshBindings.addConsumer(_bindingsConsumer);
sceneBindings.addConsumer(_bindingsConsumer);
if (computeDepth)
{
_worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4;
_localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4;
sceneBindings.addCallback('worldToScreen', transformChangedHandler);
meshBindings.addCallback('localToWorld', transformChangedHandler);
_invalidDepth = true;
}
}
public function apply(context : Context3DResource, previous : DrawCall) : uint
{
if (!_enabled)
return 0;
context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA)
.setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants)
.setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants);
var numTextures : uint = _fsTextures.length;
var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES;
var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS;
var i : uint = 0;
// setup textures
for (i = 0; i < numTextures; ++i)
{
context.setTextureAt(
i,
(_fsTextures[i] as ITextureResource).getTexture(context)
);
}
while (i < maxTextures)
context.setTextureAt(i++, null);
// setup buffers
for (i = 0; i < _numVertexComponents; ++i)
{
context.setVertexBufferAt(
i,
(_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context),
_offsets[i],
_formats[i]
);
}
while (i < maxBuffers)
context.setVertexBufferAt(i++, null);
// draw triangles
context.drawTriangles(
_indexBuffer.getIndexBuffer3D(context),
_firstIndex,
_numTriangles
);
return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles;
}
public function setParameter(name : String, value : Object) : void
{
_bindingsConsumer.setProperty(name, value);
}
private function transformChangedHandler(bindings : DataBindings,
property : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
if (property == 'worldToScreen')
_worldToScreen = newValue;
else if (property == 'localToWorld')
_localToWorld = newValue;
_invalidDepth = true;
}
}
}
|
Fix for Bug #1232 bug in DrawCall.unsetBindings if _bindingsConsumer==null, the program is not created if enabled == false which is the expected behavior.
|
Fix for Bug #1232 bug in DrawCall.unsetBindings if _bindingsConsumer==null, the program is not created if enabled == false which is the expected behavior.
|
ActionScript
|
mit
|
aerys/minko-as3
|
bb4dab88212a5b732856daef7b9bf43bdd1b9fbc
|
plugins/vastPlugin/src/com/kaltura/kdpfl/plugin/component/VastMediator.as
|
plugins/vastPlugin/src/com/kaltura/kdpfl/plugin/component/VastMediator.as
|
package com.kaltura.kdpfl.plugin.component
{
import com.kaltura.kdpfl.ApplicationFacade;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.SequenceContextType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.puremvc.as3.patterns.mediator.SequenceMultiMediator;
import com.kaltura.types.KalturaAdProtocolType;
import com.kaltura.types.KalturaAdType;
import com.kaltura.vo.KalturaAdCuePoint;
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.puremvc.as3.interfaces.INotification;
public class VastMediator extends SequenceMultiMediator
{
public static const NAME : String = "vastMediator";
public static const VAST_AD_PROVIDER : String = "vast";
public var sequenceProxy : SequenceProxy;
private var _shouldPlayPreroll : Boolean = false;
private var _shouldPlayPostroll : Boolean = false;
private var _reached25:Boolean = false;
private var _reached50:Boolean = false;
private var _reached75:Boolean = false;
private var _loadedFirstOverlayVAST : Boolean = false;
private var _playedFirstMidroll : Boolean = false;
private var _pluginCode : vastPluginCode;
private var _adStarted:Boolean = false;
// private var _vastMidrollTimer : Timer;
/**
* @copy adContext
* */
private var _adContext:String;
/**
* @copy #isListening
*/
private var _isListening : Boolean = false;
/**
* Constructor.
* @param pluginCode
* @param viewComponent
*/
public function VastMediator(pluginCode : vastPluginCode, viewComponent:Object=null)
{
super(viewComponent);
_pluginCode = pluginCode;
}
override public function listNotificationInterests():Array
{
var interests : Array = [
NotificationType.PLAYER_UPDATE_PLAYHEAD,
NotificationType.SEQUENCE_ITEM_PLAY_END,
NotificationType.HAS_OPENED_FULL_SCREEN,
NotificationType.HAS_CLOSED_FULL_SCREEN,
NotificationType.ENTRY_READY,
"vastStartedPlaying",
NotificationType.PLAYER_PAUSED,
NotificationType.PLAYER_PLAYED,
NotificationType.AD_OPPORTUNITY,
NotificationType.CHANGE_MEDIA_PROCESS_STARTED,
NotificationType.ROOT_RESIZE,
NotificationType.SEQUENCE_SKIP_NEXT
];
return interests;
}
/**
* only use notification for stats, where the actual timing doesn't matter.<br/>
* <code>adStart</code> and <code>adClick</code> are sent from <code>VastLinearAdProxy</code>.
* @param notification
*/
override public function handleNotification(notification:INotification):void
{
if (!sequenceProxy)
sequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy;
switch (notification.getName()) {
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
if (_isListening) {
// only listen to notification while active.
handlePlayhead(notification.getBody());
}
else
{
if (!_loadedFirstOverlayVAST && _pluginCode.overlayStartAt >= Number(notification.getBody()))
{
_loadedFirstOverlayVAST = true;
_pluginCode.loadNonLinearAd();
if (_pluginCode.overlayInterval)
{
var overlayDisplayDuration : Number = _pluginCode["overlayDisplayDuration"] ? _pluginCode["overlayDisplayDuration"] : 5;
var overlayTimer : Timer = new Timer((_pluginCode["overlayInterval"] + overlayDisplayDuration)*1000 ,1);
overlayTimer.addEventListener(TimerEvent.TIMER_COMPLETE, loadOverlay );
overlayTimer.start();
}
}
if ( !_playedFirstMidroll && _pluginCode.showFirstMidrollAt && _pluginCode.showFirstMidrollAt <= Number(notification.getBody()) )
{
_playedFirstMidroll = true;
_pluginCode.midrollUrlArr.push( _pluginCode.midrollUrl );
/* if ( _pluginCode.midrollInterval )
{
_vastMidrollTimer = new Timer (_pluginCode.midrollInterval);
_vastMidrollTimer.start()
}*/
startVASTMidroll();
}
}
break;
case NotificationType.PLAYER_PLAYED:
// if (_playedFirstMidroll && _vastMidrollTimer)
// _vastMidrollTimer.start();
break;
case NotificationType.PLAYER_PAUSED:
// if (_playedFirstMidroll && _vastMidrollTimer)
// _vastMidrollTimer.stop();
break;
case "vastStartedPlaying":
isListening = true;
break;
case NotificationType.SEQUENCE_ITEM_PLAY_END:
if (isListening ) {
sendNotification("adEnd", {timeSlot:getTimeSlot()});
_pluginCode["playedPrerollsSingleEntry"] = 0;
_pluginCode["playedPostrollsSingleEntry"] = 0;
_pluginCode.finishLinearAd();
enableGUI(true)
}
// stop listening to notifications
isListening = false;
break;
case NotificationType.HAS_OPENED_FULL_SCREEN:
if (_isListening)
{
_pluginCode.sendLinearTrackEvent("trkFullScreenEvent");
}
break;
case NotificationType.HAS_CLOSED_FULL_SCREEN:
if (_isListening)
{
_pluginCode.sendLinearTrackEvent("trkExitFullScreenEvent");
}
break;
case NotificationType.ENTRY_READY :
if (!sequenceProxy.vo.isInSequence)
{
_loadedFirstOverlayVAST = false;
_playedFirstMidroll = false;
}
break;
case NotificationType.AD_OPPORTUNITY:
if (_pluginCode.trackCuePoints == "true")
{
var adContext : String = notification.getBody().context;
var cuePoint : KalturaAdCuePoint = notification.getBody().cuePoint as KalturaAdCuePoint;
if ( cuePoint.protocolType == KalturaAdProtocolType.VAST || cuePoint.protocolType == KalturaAdProtocolType.VAST_2_0)
{
switch ( adContext )
{
case SequenceContextType.PRE:
if (cuePoint.adType == KalturaAdType.VIDEO)
{
_pluginCode.prerollUrlArr.push( cuePoint.sourceUrl );
sequenceProxy.vo.preSequenceArr.push(_pluginCode);
}
break;
case SequenceContextType.POST:
if (cuePoint.adType == KalturaAdType.VIDEO)
{
_pluginCode.postrollUrlArr.push( cuePoint.sourceURL );
sequenceProxy.vo.postSequenceArr.push(_pluginCode);
}
break;
case SequenceContextType.MID:
resolveMidrollAd( cuePoint , sequenceProxy);
break;
}
}
}
break;
case NotificationType.CHANGE_MEDIA_PROCESS_STARTED:
// Restore previous situation (if existed at all)
if (_pluginCode.prerollUrl )
{
_pluginCode.prerollUrlArr = new Array( _pluginCode.prerollUrl );
}
if (_pluginCode.postrollUrl)
{
_pluginCode.postrollUrlArr = new Array(_pluginCode.postrollUrl);
}
break;
case NotificationType.SEQUENCE_SKIP_NEXT:
//if at least one vast ad played, most likely skip was for vast ad
if (_adStarted)
{
_pluginCode.sendLinearTrackEvent("trkSkipEvent");
}
break;
}
}
private function startVASTMidroll (e : TimerEvent = null) : void
{
sequenceProxy.vo.midCurrentIndex = 0;
sendNotification( NotificationType.DO_PAUSE );
sequenceProxy.playNextInSequence();
}
private function resolveMidrollAd( midrollObject : KalturaAdCuePoint , sequenceProxy: SequenceProxy) : void
{
if ( midrollObject.adType == KalturaAdType.VIDEO )
{
sendNotification( NotificationType.DO_PAUSE );
_pluginCode.midrollUrlArr.push( midrollObject.sourceUrl );
sequenceProxy.vo.midrollArr.push(_pluginCode);
}
else
{
sendNotification ("changeOverlayDisplayDuration" , {newDuration : ((midrollObject.endTime - midrollObject.startTime) / 1000)})
_pluginCode.loadNonLinearAd( midrollObject.sourceUrl );
}
}
private function loadOverlay ( e: TimerEvent) : void
{
_pluginCode.loadNonLinearAd();
(e.target as Timer).start();
}
/**
* @return statistics string for current ad context
*/
private function getTimeSlot():String {
var res:String;
switch (adContext) {
case "pre":
res = "preroll";
break;
case "mid":
res = "midroll";
break;
case "post":
res = "postroll";
break;
}
return res;
}
/**
* dispatch progress event if needed.
* @param o progress notification body
*/
private function handlePlayhead(o:Object):void {
var duration:Number = (facade.retrieveMediator("kMediaPlayerMediator"))["player"]["duration"];
var fraction:Number = (o as Number) / duration;
if (!_reached25 && fraction > 0.25) {
sendNotification("firstQuartileOfAd", {timeSlot:getTimeSlot()});
_reached25 = true;
}
else if (!_reached50 && fraction > 0.5){
sendNotification("midOfAd", {timeSlot:getTimeSlot()});
_reached50 = true;
}
else if (!_reached75 && fraction > 0.75){
sendNotification("ThirdQueartileOfAd", {timeSlot:getTimeSlot()});
_reached75 = true;
}
_pluginCode.checkLinearProgress(o as Number);
}
/**
* resets the "reached" variables.
* used when we have more than 1 ad.
*/
public function reset():void {
_reached25 = false;
_reached50 = false;
_reached75 = false;
}
public function get shouldPlayPreroll () : Boolean
{
return _shouldPlayPreroll;
}
public function get shouldPlayPostroll () : Boolean
{
return _shouldPlayPreroll;
}
public function enableGUI (enabled : Boolean) : void
{
sendNotification("enableGui", {guiEnabled : enabled, enableType : "full"});
}
/**
* indicates the mediator is listening to notifications.
*/
public function get isListening():Boolean {
return _isListening;
}
/**
* @private
*/
public function set isListening(value:Boolean):void {
if (_isListening != value) {
_isListening = value;
if (value) {
reset();
}
}
}
/**
* current ad context. <br/>
* possible values enumerated in <code>SequenceContextType</code>
*/
public function get adContext():String
{
return _adContext;
}
/**
* @private
*/
public function set adContext(value:String):void
{
_adContext = value;
}
}
}
|
package com.kaltura.kdpfl.plugin.component
{
import com.kaltura.kdpfl.ApplicationFacade;
import com.kaltura.kdpfl.model.SequenceProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.model.type.SequenceContextType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.puremvc.as3.patterns.mediator.SequenceMultiMediator;
import com.kaltura.types.KalturaAdProtocolType;
import com.kaltura.types.KalturaAdType;
import com.kaltura.vo.KalturaAdCuePoint;
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.puremvc.as3.interfaces.INotification;
public class VastMediator extends SequenceMultiMediator
{
public static const NAME : String = "vastMediator";
public static const VAST_AD_PROVIDER : String = "vast";
public var sequenceProxy : SequenceProxy;
private var _shouldPlayPreroll : Boolean = false;
private var _shouldPlayPostroll : Boolean = false;
private var _reached25:Boolean = false;
private var _reached50:Boolean = false;
private var _reached75:Boolean = false;
private var _loadedFirstOverlayVAST : Boolean = false;
private var _playedFirstMidroll : Boolean = false;
private var _pluginCode : vastPluginCode;
private var _adStarted:Boolean = false;
// private var _vastMidrollTimer : Timer;
/**
* @copy adContext
* */
private var _adContext:String;
/**
* @copy #isListening
*/
private var _isListening : Boolean = false;
/**
* Constructor.
* @param pluginCode
* @param viewComponent
*/
public function VastMediator(pluginCode : vastPluginCode, viewComponent:Object=null)
{
super(viewComponent);
_pluginCode = pluginCode;
}
override public function listNotificationInterests():Array
{
var interests : Array = [
NotificationType.PLAYER_UPDATE_PLAYHEAD,
NotificationType.SEQUENCE_ITEM_PLAY_END,
NotificationType.HAS_OPENED_FULL_SCREEN,
NotificationType.HAS_CLOSED_FULL_SCREEN,
NotificationType.ENTRY_READY,
"vastStartedPlaying",
NotificationType.PLAYER_PAUSED,
NotificationType.PLAYER_PLAYED,
NotificationType.AD_OPPORTUNITY,
NotificationType.CHANGE_MEDIA_PROCESS_STARTED,
NotificationType.ROOT_RESIZE,
NotificationType.SEQUENCE_SKIP_NEXT
];
return interests;
}
/**
* only use notification for stats, where the actual timing doesn't matter.<br/>
* <code>adStart</code> and <code>adClick</code> are sent from <code>VastLinearAdProxy</code>.
* @param notification
*/
override public function handleNotification(notification:INotification):void
{
if (!sequenceProxy)
sequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy;
switch (notification.getName()) {
case NotificationType.PLAYER_UPDATE_PLAYHEAD:
if (_isListening) {
// only listen to notification while active.
handlePlayhead(notification.getBody());
}
else
{
if (!_loadedFirstOverlayVAST && _pluginCode.overlayStartAt >= Number(notification.getBody()))
{
_loadedFirstOverlayVAST = true;
_pluginCode.loadNonLinearAd();
if (_pluginCode.overlayInterval)
{
var overlayDisplayDuration : Number = _pluginCode["overlayDisplayDuration"] ? _pluginCode["overlayDisplayDuration"] : 5;
var overlayTimer : Timer = new Timer((_pluginCode["overlayInterval"] + overlayDisplayDuration)*1000 ,1);
overlayTimer.addEventListener(TimerEvent.TIMER_COMPLETE, loadOverlay );
overlayTimer.start();
}
}
if ( !_playedFirstMidroll && _pluginCode.showFirstMidrollAt && _pluginCode.showFirstMidrollAt <= Number(notification.getBody()) )
{
_playedFirstMidroll = true;
_pluginCode.midrollUrlArr.push( _pluginCode.midrollUrl );
/* if ( _pluginCode.midrollInterval )
{
_vastMidrollTimer = new Timer (_pluginCode.midrollInterval);
_vastMidrollTimer.start()
}*/
startVASTMidroll();
}
}
break;
case NotificationType.PLAYER_PLAYED:
// if (_playedFirstMidroll && _vastMidrollTimer)
// _vastMidrollTimer.start();
break;
case NotificationType.PLAYER_PAUSED:
// if (_playedFirstMidroll && _vastMidrollTimer)
// _vastMidrollTimer.stop();
break;
case "vastStartedPlaying":
isListening = true;
_adStarted = true;
break;
case NotificationType.SEQUENCE_ITEM_PLAY_END:
if (isListening ) {
sendNotification("adEnd", {timeSlot:getTimeSlot()});
_pluginCode["playedPrerollsSingleEntry"] = 0;
_pluginCode["playedPostrollsSingleEntry"] = 0;
_pluginCode.finishLinearAd();
enableGUI(true)
}
// stop listening to notifications
isListening = false;
break;
case NotificationType.HAS_OPENED_FULL_SCREEN:
if (_isListening)
{
_pluginCode.sendLinearTrackEvent("trkFullScreenEvent");
}
break;
case NotificationType.HAS_CLOSED_FULL_SCREEN:
if (_isListening)
{
_pluginCode.sendLinearTrackEvent("trkExitFullScreenEvent");
}
break;
case NotificationType.ENTRY_READY :
if (!sequenceProxy.vo.isInSequence)
{
_loadedFirstOverlayVAST = false;
_playedFirstMidroll = false;
}
break;
case NotificationType.AD_OPPORTUNITY:
if (_pluginCode.trackCuePoints == "true")
{
var adContext : String = notification.getBody().context;
var cuePoint : KalturaAdCuePoint = notification.getBody().cuePoint as KalturaAdCuePoint;
if ( cuePoint.protocolType == KalturaAdProtocolType.VAST || cuePoint.protocolType == KalturaAdProtocolType.VAST_2_0)
{
switch ( adContext )
{
case SequenceContextType.PRE:
if (cuePoint.adType == KalturaAdType.VIDEO)
{
_pluginCode.prerollUrlArr.push( cuePoint.sourceUrl );
sequenceProxy.vo.preSequenceArr.push(_pluginCode);
}
break;
case SequenceContextType.POST:
if (cuePoint.adType == KalturaAdType.VIDEO)
{
_pluginCode.postrollUrlArr.push( cuePoint.sourceURL );
sequenceProxy.vo.postSequenceArr.push(_pluginCode);
}
break;
case SequenceContextType.MID:
resolveMidrollAd( cuePoint , sequenceProxy);
break;
}
}
}
break;
case NotificationType.CHANGE_MEDIA_PROCESS_STARTED:
// Restore previous situation (if existed at all)
if (_pluginCode.prerollUrl )
{
_pluginCode.prerollUrlArr = new Array( _pluginCode.prerollUrl );
}
if (_pluginCode.postrollUrl)
{
_pluginCode.postrollUrlArr = new Array(_pluginCode.postrollUrl);
}
break;
case NotificationType.SEQUENCE_SKIP_NEXT:
//if at least one vast ad played, most likely skip was for vast ad
if (_adStarted)
{
_pluginCode.sendLinearTrackEvent("trkSkipEvent");
}
break;
}
}
private function startVASTMidroll (e : TimerEvent = null) : void
{
sequenceProxy.vo.midCurrentIndex = 0;
sendNotification( NotificationType.DO_PAUSE );
sequenceProxy.playNextInSequence();
}
private function resolveMidrollAd( midrollObject : KalturaAdCuePoint , sequenceProxy: SequenceProxy) : void
{
if ( midrollObject.adType == KalturaAdType.VIDEO )
{
sendNotification( NotificationType.DO_PAUSE );
_pluginCode.midrollUrlArr.push( midrollObject.sourceUrl );
sequenceProxy.vo.midrollArr.push(_pluginCode);
}
else
{
sendNotification ("changeOverlayDisplayDuration" , {newDuration : ((midrollObject.endTime - midrollObject.startTime) / 1000)})
_pluginCode.loadNonLinearAd( midrollObject.sourceUrl );
}
}
private function loadOverlay ( e: TimerEvent) : void
{
_pluginCode.loadNonLinearAd();
(e.target as Timer).start();
}
/**
* @return statistics string for current ad context
*/
private function getTimeSlot():String {
var res:String;
switch (adContext) {
case "pre":
res = "preroll";
break;
case "mid":
res = "midroll";
break;
case "post":
res = "postroll";
break;
}
return res;
}
/**
* dispatch progress event if needed.
* @param o progress notification body
*/
private function handlePlayhead(o:Object):void {
var duration:Number = (facade.retrieveMediator("kMediaPlayerMediator"))["player"]["duration"];
var fraction:Number = (o as Number) / duration;
if (!_reached25 && fraction > 0.25) {
sendNotification("firstQuartileOfAd", {timeSlot:getTimeSlot()});
_reached25 = true;
}
else if (!_reached50 && fraction > 0.5){
sendNotification("midOfAd", {timeSlot:getTimeSlot()});
_reached50 = true;
}
else if (!_reached75 && fraction > 0.75){
sendNotification("ThirdQueartileOfAd", {timeSlot:getTimeSlot()});
_reached75 = true;
}
_pluginCode.checkLinearProgress(o as Number);
}
/**
* resets the "reached" variables.
* used when we have more than 1 ad.
*/
public function reset():void {
_reached25 = false;
_reached50 = false;
_reached75 = false;
}
public function get shouldPlayPreroll () : Boolean
{
return _shouldPlayPreroll;
}
public function get shouldPlayPostroll () : Boolean
{
return _shouldPlayPreroll;
}
public function enableGUI (enabled : Boolean) : void
{
sendNotification("enableGui", {guiEnabled : enabled, enableType : "full"});
}
/**
* indicates the mediator is listening to notifications.
*/
public function get isListening():Boolean {
return _isListening;
}
/**
* @private
*/
public function set isListening(value:Boolean):void {
if (_isListening != value) {
_isListening = value;
if (value) {
reset();
}
}
}
/**
* current ad context. <br/>
* possible values enumerated in <code>SequenceContextType</code>
*/
public function get adContext():String
{
return _adContext;
}
/**
* @private
*/
public function set adContext(value:String):void
{
_adContext = value;
}
}
}
|
fix skip statistics
|
vast: fix skip statistics
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp
|
2bf44cfc0c78e7eea0f54fdb78abd71b174e22c5
|
com/segonquart/Configuration.as
|
com/segonquart/Configuration.as
|
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class com.segonquart.Configuration extends MovieClip
{
public var addListener:Function;
public var addEventListener:Function;
public var removeEventListener:Function;
static var URLAPP:String = "http://www.talking-wear.com";
static var POLICY:String = "http://segonquart.net/crossdomain.xml";
public function Configuration ()
{
Stage.addListener (this);
mx.events.EventDispatcher.initialize (this);
}
public function init (m:MovieClip)
{
this.m = m;
m.config ();
}
static function config ():Void
{
System.security.allowDomain (URLAPP);
System.security.loadPolicyFile (POLICY);
Stage.showMenu = false;
Stage.scaleMode = "noScale";
_global.showRedrawRegions (false);
}
}
|
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class com.segonquart.Configuration extends MovieClip
{
public var addListener:Function;
public var addEventListener:Function;
public var removeEventListener:Function;
static var URLAPP:String = "http://www.talking-wear.com";
static var POLICY:String = "http://segonquart.net/crossdomain.xml";
public function Configuration ()
{
Stage.addListener (this);
mx.events.EventDispatcher.initialize (this);
}
public function init (m:MovieClip)
{
this.m = m;
m.config ();
}
static function config ()
{
System.security.allowDomain (URLAPP);
System.security.loadPolicyFile (POLICY);
Stage.showMenu = false;
Stage.scaleMode = "noScale";
_global.showRedrawRegions (false);
}
}
|
Update Configuration.as
|
Update Configuration.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
14e29c99fbaba25aace6714949c3cca398c89643
|
bin/Data/Scripts/Main.as
|
bin/Data/Scripts/Main.as
|
Scene@ newScene_;
Scene@ scene_;
Camera@ camera_;
void Start()
{
StartScene("Scenes/Level1.xml");
SubscribeToEvent("LevelComplete", "HandleLevelComplete");
}
void Stop()
{
}
void HandleLevelComplete(StringHash type, VariantMap& data)
{
log.Debug("Level Complete. I should be loading "+data["NextLevel"].GetString());
StartScene(data["NextLevel"].GetString());
}
void StartScene(String scene)
{
newScene_ = Scene();
newScene_.LoadAsyncXML(cache.GetFile(scene));
SubscribeToEvent("AsyncLoadFinished", "HandleAsyncLoadFinished");
}
void HandleAsyncLoadFinished(StringHash type, VariantMap& data)
{
UnsubscribeFromEvent("AsyncLoadFinished");
newScene_ = data["Scene"].GetPtr();
SubscribeToEvent("Update", "HandleDelayedStart");
}
void HandleDelayedStart(StringHash type, VariantMap& data)
{
UnsubscribeFromEvent("Update");
Node@ cameraNode = newScene_.GetChild("Camera", true);
Camera@ newCamera = cameraNode.CreateComponent("Camera");
Viewport@ viewport = Viewport(newScene_, cameraNode.GetComponent("Camera"));
renderer.viewports[0] = viewport;
scene_ = newScene_;
camera_ = newCamera;
newScene_ = null;
}
|
Scene@ newScene_;
Scene@ scene_;
Camera@ camera_;
Timer timer_;
void Start()
{
StartScene("Scenes/Level1.xml");
SubscribeToEvent("LevelComplete", "HandleLevelComplete");
}
void Stop()
{
}
void HandleLevelComplete(StringHash type, VariantMap& data)
{
log.Debug("Level Complete. I should be loading "+data["NextLevel"].GetString());
float timeTaken = timer_.GetMSec(false);
log.Debug("You took " + timeTaken / 1000.f + " seconds to solve the level");
StartScene(data["NextLevel"].GetString());
}
void StartScene(String scene)
{
newScene_ = Scene();
newScene_.LoadAsyncXML(cache.GetFile(scene));
SubscribeToEvent("AsyncLoadFinished", "HandleAsyncLoadFinished");
}
void HandleAsyncLoadFinished(StringHash type, VariantMap& data)
{
UnsubscribeFromEvent("AsyncLoadFinished");
newScene_ = data["Scene"].GetPtr();
SubscribeToEvent("Update", "HandleDelayedStart");
}
void HandleDelayedStart(StringHash type, VariantMap& data)
{
UnsubscribeFromEvent("Update");
Node@ cameraNode = newScene_.GetChild("Camera", true);
Camera@ newCamera = cameraNode.CreateComponent("Camera");
Viewport@ viewport = Viewport(newScene_, cameraNode.GetComponent("Camera"));
renderer.viewports[0] = viewport;
scene_ = newScene_;
camera_ = newCamera;
newScene_ = null;
timer_.Reset();
}
|
Add a level timer to the main procedure
|
Add a level timer to the main procedure
|
ActionScript
|
mit
|
leyarotheconquerer/on-off
|
5743bf1dba2e8f0e3b48752becab0153390475c0
|
shell/Domain.as
|
shell/Domain.as
|
/* ***** 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) 2004-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 ***** */
package avmplus {
import flash.utils.ByteArray
[native(cls="DomainClass", instance="DomainObject", methods="auto")]
public class Domain
{
private native function init(base:Domain):void;
public function Domain(base:Domain)
{
init(base);
}
public native function loadBytes(byteArray:ByteArray);
public native function getClass(className:String):Class;
public native static function get currentDomain():Domain;
public function load(filename:String)
{
return loadBytes(ByteArray.readFile(filename))
}
//#ifdef AVMPLUS_MOPS
/**
* Gets the minimum length of a ByteArray required to be used as
* ApplicationDomain.globalMemory
*
* @tiptext
* @playerversion Flash 10
* @langversion 3.0
*/
public native static function get MIN_DOMAIN_MEMORY_LENGTH():uint;
/**
* Gets and sets the ByteArray object on which global memory operations
* will operate within this ApplicationDomain
*
* @tiptext
* @playerversion Flash 10
* @langversion 3.0
*/
public native function get domainMemory():ByteArray;
public native function set domainMemory(mem:ByteArray);
//#endif AVMPLUS_MOPS
}
}
|
/* ***** 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) 2004-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 ***** */
package avmplus {
import flash.utils.ByteArray
[native(cls="DomainClass", instance="DomainObject", methods="auto")]
public class Domain
{
private native function init(base:Domain):void;
public function Domain(base:Domain)
{
init(base);
}
public native function loadBytes(byteArray:ByteArray);
public native function getClass(className:String):Class;
public native static function get currentDomain():Domain;
public function load(filename:String)
{
return loadBytes(ByteArray.readFile(filename))
}
/**
* Gets the minimum length of a ByteArray required to be used as
* ApplicationDomain.globalMemory
*
* @tiptext
* @playerversion Flash 10
* @langversion 3.0
*/
public native static function get MIN_DOMAIN_MEMORY_LENGTH():uint;
/**
* Gets and sets the ByteArray object on which global memory operations
* will operate within this ApplicationDomain
*
* @tiptext
* @playerversion Flash 10
* @langversion 3.0
*/
public native function get domainMemory():ByteArray;
public native function set domainMemory(mem:ByteArray);
}
}
|
remove one more commented out reference to AVMPLUS_MOPS (r=me)
|
remove one more commented out reference to AVMPLUS_MOPS (r=me)
|
ActionScript
|
mpl-2.0
|
pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux
|
e061cd8cef2affbdf7d2ed78e6907fe2a0320b43
|
WEB-INF/lps/lfc/kernel/swf9/LzLibrary.as
|
WEB-INF/lps/lfc/kernel/swf9/LzLibrary.as
|
/**
* LzLibrary.as
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic LZX
* @subtopic Syntax
*/
/**
* @lzxname import
* @initarg stage
*/
class LzLibrary extends LzNode {
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.ui.*;
import flash.geom.*;
import flash.utils.*;
import mx.controls.Button;
import flash.net.*;
import flash.utils.*;
import flash.system.*;
}#
/** @access private
* @modifiers override
*/
static var tagname = 'import';
/** @access private */
static var attributes = new LzInheritedHash(LzNode.attributes);
/** @access private */
var loaded = false;
/** @access private */
var loading = false;
/** @access private */
var sprite = null;
/**
* A reference to a target file whose content is treated as a
* loadable module.
*
* @keywords final
* @type string
* @access public
*/
var href;
/**
* When set to 'defer', the library will not be loaded until its
* load-method has been called. Otherwise, the library loads
* automatically.
*
* @keywords final
* @type string
* @lzxdefault "late"
* @access public
*/
var stage = "late";//"late|defer"
/**
* @access private
*/
function $lzc$set_stage(val) {
this.stage = val;
}
/**
* Sent when this library has finished loading.
*
* @lzxtype event
* @access public
*/
var onload = LzDeclaredEvent;
/** @access private
* @modifiers override
*/
function LzLibrary ( parent:LzNode? = null , attrs:Object? = null , children:Array? = null, instcall:Boolean = false) {
super(parent,attrs,children,instcall);
}
/**
* @access private
*/
function $lzc$set_href(val) {
this.href = val;
}
/**
* @access private
*/
override function construct (parent, args) {
this.stage = args.stage;
super.construct.apply(this, arguments);
LzLibrary.libraries[args.name] = this;
}
/**
* @access private
*/
override function init( ) {
super.init.apply(this, arguments);
if (this.stage == "late") {
this.load();
}
}
/**
* @access private
*/
override function destroy () {
if (this.sprite) {
this.sprite.destroy();
this.sprite = null;
}
super.destroy();
}
/** @access private */
static var libraries = {};
/**
* @access private
*/
static function findLibrary (libname){
return LzLibrary.libraries[libname];
}
/**
* @access private
*/
override function toString (){
return "Library " + this.href + " named " + this.name;
}
public var loader:Loader = null;
/**
* Loads this library dynamically at runtime. Must only be called
* when stage was set to 'defer'.
*
* @access public
*/
function load () {
if (this.loading || this.loaded) {
return;
}
this.loading = true;
var request:URLRequest = new URLRequest(this.href);
request.method = URLRequestMethod.GET;
this.loader = new Loader();
var info:LoaderInfo = loader.contentLoaderInfo;
info.addEventListener(Event.COMPLETE, handleLoadComplete);
trace('loader.load ', this.href);
this.loader.load(request);
}
public function handleLoadComplete(event:Event):void {
var library:Object = event.target.content;
library.exportClassDefs(null);
this.libapp = library;
}
var libapp;
/**
* Called by LzLibraryCleanup when this library has finished loading.
*
* @access private
*/
function loadfinished (){
this.loading = false;
if (this.onload.ready) this.onload.sendEvent(true);
}
/** @access private
*/
static function stripQueryString(str:String):String {
if (str.indexOf('?') > 0) {
str = str.substring(0,str.indexOf('?'));
}
return str;
}
/**
* Callback for runtime loaded libraries
* @access private
*/
static function __LZsnippetLoaded (url){
// find the lib with this url
// Strip out query string
url = LzLibrary.stripQueryString(url);
var lib = null;
var libs = LzLibrary.libraries;
for (var l in libs ) {
var libhref = LzLibrary.stripQueryString(libs[l].href);
if (libhref == url) {
lib = libs[l];
break;
}
}
if (lib == null) {
Debug.error("could not find library with href", url);
} else {
lib.loaded = true;
canvas.initiatorAddNode({attrs: {libname: lib.name}, "class": LzLibraryCleanup}, 1);
// Run the queue to instantiate all pending LzInstantiateView calls.
canvas.initDone();
}
}
}; // End of LzLibrary
lz[LzLibrary.tagname] = LzLibrary; //publish
|
/**
* LzLibrary.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic LZX
* @subtopic Syntax
*/
/**
* @lzxname import
* @initarg stage
*/
class LzLibrary extends LzNode {
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.ui.*;
import flash.geom.*;
import flash.utils.*;
import mx.controls.Button;
import flash.net.*;
import flash.utils.*;
import flash.system.*;
}#
/** @access private
* @modifiers override
*/
static var tagname = 'import';
/** @access private */
static var attributes = new LzInheritedHash(LzNode.attributes);
/** @access private */
var loaded = false;
/** @access private */
var loading = false;
/** @access private */
var sprite = null;
/**
* A reference to a target file whose content is treated as a
* loadable module.
*
* @keywords final
* @type string
* @access public
*/
var href;
/**
* When set to 'defer', the library will not be loaded until its
* load-method has been called. Otherwise, the library loads
* automatically.
*
* @keywords final
* @type string
* @lzxdefault "late"
* @access public
*/
var stage = "late";//"late|defer"
/**
* @access private
*/
function $lzc$set_stage(val) {
this.stage = val;
}
/**
* Sent when this library has finished loading.
*
* @lzxtype event
* @access public
*/
var onload = LzDeclaredEvent;
/** @access private
* @modifiers override
*/
function LzLibrary ( parent:LzNode? = null , attrs:Object? = null , children:Array? = null, instcall:Boolean = false) {
super(parent,attrs,children,instcall);
}
/**
* @access private
*/
function $lzc$set_href(val) {
this.href = val;
}
/**
* @access private
*/
override function construct (parent, args) {
this.stage = args.stage;
super.construct.apply(this, arguments);
LzLibrary.libraries[args.name] = this;
}
/**
* @access private
*/
override function init( ) {
super.init.apply(this, arguments);
if (this.stage == "late") {
this.load();
}
}
/**
* @access private
*/
override function destroy () {
if (this.sprite) {
this.sprite.destroy();
this.sprite = null;
}
super.destroy();
}
/** @access private */
static var libraries = {};
/**
* @access private
*/
static function findLibrary (libname){
return LzLibrary.libraries[libname];
}
/**
* @access private
*/
override function toString (){
return "Library " + this.href + " named " + this.name;
}
public var loader:Loader = null;
/**
* Loads this library dynamically at runtime. Must only be called
* when stage was set to 'defer'.
*
* @access public
*/
function load () {
if (this.loading || this.loaded) {
return;
}
this.loading = true;
var loadurl:LzURL = lz.Browser.getBaseURL();
loadurl.file = this.href;
var request:URLRequest = new URLRequest(loadurl.toString());
request.method = URLRequestMethod.GET;
this.loader = new Loader();
var info:LoaderInfo = loader.contentLoaderInfo;
info.addEventListener(Event.COMPLETE, handleLoadComplete);
this.loader.load(request);
}
public function handleLoadComplete(event:Event):void {
var library:Object = event.target.content;
library.exportClassDefs(null);
this.libapp = library;
}
var libapp;
/**
* Called by LzLibraryCleanup when this library has finished loading.
*
* @access private
*/
function loadfinished (){
this.loading = false;
if (this.onload.ready) this.onload.sendEvent(true);
}
/** @access private
*/
static function stripQueryString(str:String):String {
if (str.indexOf('?') > 0) {
str = str.substring(0,str.indexOf('?'));
}
return str;
}
/**
* Callback for runtime loaded libraries
* @access private
*/
static function __LZsnippetLoaded (url){
// find the lib with this url
// Strip out query string
url = LzLibrary.stripQueryString(url);
var lib = null;
var libs = LzLibrary.libraries;
for (var l in libs ) {
var libhref = LzLibrary.stripQueryString(libs[l].href);
if (libhref == url) {
lib = libs[l];
break;
}
}
if (lib == null) {
Debug.error("could not find library with href", url);
} else {
lib.loaded = true;
canvas.initiatorAddNode({attrs: {libname: lib.name}, "class": LzLibraryCleanup}, 1);
// Run the queue to instantiate all pending LzInstantiateView calls.
canvas.initDone();
}
}
}; // End of LzLibrary
lz[LzLibrary.tagname] = LzLibrary; //publish
|
Change 20090112-hqm-j by [email protected] on 2009-01-12 13:25:36 EST in /Users/hqm/openlaszlo/trunk5 for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20090112-hqm-j by [email protected] on 2009-01-12 13:25:36 EST
in /Users/hqm/openlaszlo/trunk5
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Allow snippets to load into app, when wrapper html file comes from different URL
New Features:
Bugs Fixed: LPP-7615
Technical Reviewer: ptw
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
+ When a snippet is compiled, the URL to load it from at runtime is
baked in as a relative path, like "build/myapp/mylib.lzx.swf".
The SWF9 library loader was creating a new URLRequest using that
relative URL, and when loaded, it would load relative to the current
HTML wrapper's URL, which could be in some place random.
The fix is to construct the library load URL by grabbing
lz.Browser.getBaseURL(), which, in swf9 anyway, seems URL that the app
swf code loaded from rather than the location of the HTML wrapper
page.
This change constructs the the snippet's load URL by appending
lz.Browser.getBaseURL() to the snippet's baked-in relative path.
+ The test case from the bug report may not work in SWF8 and DHTML
either, I haven't tested those runtimes yet. This is just a fix for
swf9.
Tests:
+ test case from bug report
+ regular tests in test/snippets in swf9
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12429 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
ca122661ebe79f3bce974ab8e618bc05df4166eb
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TEXTURE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose mesh");
var list:List = new List(_window, 0, 0, this.getTexture(asset.output));
_window.x = this.stage.stageWidth - _window.width >> 1;
_window.y = this.stage.stageHeight - _window.height >> 1;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
}
private function getTexture(bytes:ByteArray):Array {
var result:Array = [1, 2, 3];
return result;
}
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [1, 2, 3];
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
_assets.push(new Asset(_model.viewerInput.name, byteArray));
// var name:String = asset.name;
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
list.removeEventListener(event.type, this.selectAnimationHandler);
log(this, "selectAnimationHandler", list.selectedItem);
this.removeChild(_window);
_window = null;
//add animation to miracle
var name:String = list.selectedItem.toString();
Miracle.currentScene.createImage(name)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}
private function imageAddedToStage(event:Event):void {
var target:MiracleImage = event.target as MiracleImage;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MtfReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose mesh");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
}
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
// var name:String = asset.name;
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.currentScene.createImage(_name)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
log(this, "selectAnimationHandler", list.selectedItem);
//add animation to miracle
var name:String = list.selectedItem.toString();
}
private function imageAddedToStage(event:Event):void {
var target:MiracleImage = event.target as MiracleImage;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
change viewer
|
change viewer
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
2d42cf7f8590cee1c7521e62b1002f55b307f4c5
|
dolly-framework/src/test/actionscript/dolly/CopyingOfCompositeCopyableClassTest.as
|
dolly-framework/src/test/actionscript/dolly/CopyingOfCompositeCopyableClassTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CompositeCopyableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CopyingOfCompositeCopyableClassTest {
private var compositeCopyableClass:CompositeCopyableClass;
private var compositeCopyableClassType:Type;
[Before]
public function before():void {
compositeCopyableClass = new CompositeCopyableClass();
compositeCopyableClass.array = [1, 2, 3, 4, 5];
compositeCopyableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCopyableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCopyableClassType = Type.forInstance(compositeCopyableClass);
}
[After]
public function after():void {
compositeCopyableClass = null;
compositeCopyableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Copier.findCopyableFieldsForType(compositeCopyableClassType);
assertNotNull(writableFields);
assertEquals(4, writableFields.length);
}
[Test]
public function copyingOfArray():void {
const copy:CompositeCopyableClass = Copier.copy(compositeCopyableClass);
assertNotNull(copy.array);
assertThat(copy.array, arrayWithSize(5));
assertThat(copy.array, compositeCopyableClass.array);
assertFalse(copy.array == compositeCopyableClass.array);
assertThat(copy.array, everyItem(isA(Number)));
assertThat(copy.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.CompositeCopyableClass;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;
import org.hamcrest.assertThat;
import org.hamcrest.collection.array;
import org.hamcrest.collection.arrayWithSize;
import org.hamcrest.collection.everyItem;
import org.hamcrest.core.isA;
import org.hamcrest.object.equalTo;
use namespace dolly_internal;
public class CopyingOfCompositeCopyableClassTest {
private var compositeCopyableClass:CompositeCopyableClass;
private var compositeCopyableClassType:Type;
[Before]
public function before():void {
compositeCopyableClass = new CompositeCopyableClass();
compositeCopyableClass.array = [1, 2, 3, 4, 5];
compositeCopyableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
compositeCopyableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);
compositeCopyableClassType = Type.forInstance(compositeCopyableClass);
}
[After]
public function after():void {
compositeCopyableClass = null;
compositeCopyableClassType = null;
}
[Test]
public function findingAllWritableFieldsForType():void {
const writableFields:Vector.<Field> = Copier.findCopyableFieldsForType(compositeCopyableClassType);
assertNotNull(writableFields);
assertEquals(4, writableFields.length);
}
[Test]
public function copyingOfArray():void {
const copy:CompositeCopyableClass = Copier.copy(compositeCopyableClass);
assertNotNull(copy.array);
assertThat(copy.array, arrayWithSize(5));
assertThat(copy.array, compositeCopyableClass.array);
assertFalse(copy.array == compositeCopyableClass.array);
assertThat(copy.array, everyItem(isA(Number)));
assertThat(copy.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5)));
}
[Test]
public function copyingOfArrayList():void {
const copy:CompositeCopyableClass = Copier.copy(compositeCopyableClass);
const arrayList:ArrayList = copy.arrayList;
assertNotNull(arrayList);
assertFalse(copy.arrayList == compositeCopyableClass.arrayList);
assertEquals(arrayList.length, 5);
assertEquals(arrayList.getItemAt(0), 1);
assertEquals(arrayList.getItemAt(1), 2);
assertEquals(arrayList.getItemAt(2), 3);
assertEquals(arrayList.getItemAt(3), 4);
assertEquals(arrayList.getItemAt(4), 5);
}
}
}
|
Test for copying of ArrayList in CompositeCloneableClass.
|
Test for copying of ArrayList in CompositeCloneableClass.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
054e441316ab831684cb23b64fd9866e4ae43dbd
|
src/model/AnimationDataProxy.as
|
src/model/AnimationDataProxy.as
|
package model
{
import dragonBones.objects.AnimationData;
import dragonBones.objects.ArmatureData;
import dragonBones.objects.MovementBoneData;
import dragonBones.objects.MovementData;
import dragonBones.objects.XMLDataParser;
import dragonBones.utils.ConstValues;
import dragonBones.utils.dragonBones_internal;
import flash.events.Event;
import message.MessageDispatcher;
import mx.collections.XMLListCollection;
use namespace dragonBones_internal;
/**
* Manage selected animation data
*/
public class AnimationDataProxy
{
public var movementsMC:XMLListCollection;
private var _xml:XML;
private var _movementsXMLList:XMLList;
private var _movementXML:XML;
private var _movementBonesXMLList:XMLList;
private var _movementBoneXML:XML;
public function get animationName():String
{
return _xml?_xml.attribute(ConstValues.A_NAME):"";
}
public function get movementName():String
{
return _movementXML?_movementXML.attribute(ConstValues.A_NAME):"";
}
public function get boneName():String
{
return _movementBoneXML?_movementBoneXML.attribute(ConstValues.A_NAME):"";
}
public function get durationTo():Number
{
if(!_movementXML)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TO)) / ImportDataProxy.getInstance().frameRate;
}
public function set durationTo(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TO] = Math.round(value * ImportDataProxy.getInstance().frameRate);
updateMovement();
}
}
public function get durationTween():Number
{
if(_movementXML?int(_movementXML.attribute(ConstValues.A_DURATION)) == 1:true)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TWEEN)) / ImportDataProxy.getInstance().frameRate;
}
public function set durationTween(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TWEEN] = Math.round(value * ImportDataProxy.getInstance().frameRate);
updateMovement();
}
}
public function get loop():Boolean
{
return _movementXML?Boolean(int(_movementXML.attribute(ConstValues.A_LOOP)) == 1):false;
}
public function set loop(value:Boolean):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_LOOP] = value?1:0;
updateMovement();
}
}
public function get tweenEasing():Number
{
return _movementXML?Number(_movementXML.attribute(ConstValues.A_TWEEN_EASING)):-1.1;
}
public function set tweenEasing(value:Number):void
{
if(_movementXML)
{
if(value<-1)
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = NaN;
}
else
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = value;
}
updateMovement();
}
}
public function get boneScale():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_SCALE)) * 100;
}
public function set boneScale(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_SCALE] = value * 0.01;
updateMovementBone();
}
}
public function get boneDelay():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_DELAY))* 100;
}
public function set boneDelay(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_DELAY] = value * 0.01;
updateMovementBone();
}
}
public function AnimationDataProxy()
{
movementsMC = new XMLListCollection();
}
internal function setData(xml:XML):void
{
_xml = xml;
if(_xml)
{
_movementsXMLList = _xml.elements(ConstValues.MOVEMENT);
}
else
{
_movementsXMLList = null;
}
movementsMC.source = _movementsXMLList;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_ANIMATION_DATA, animationName);
changeMovement();
}
public function changeMovement(movementName:String = null, isChangedByArmature:Boolean = false):void
{
_movementXML = ImportDataProxy.getElementByName(_movementsXMLList, movementName, true);
if(_movementXML)
{
_movementBonesXMLList = _movementXML.elements(ConstValues.BONE);
}
else
{
_movementBonesXMLList = null;
}
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_DATA, this.movementName, isChangedByArmature);
changeMovementBone(ImportDataProxy.getInstance().armatureDataProxy.boneName);
}
public function changeMovementBone(boneName:String = null):void
{
var movementBoneXML:XML = ImportDataProxy.getElementByName(_movementBonesXMLList, boneName, true);
if(movementBoneXML == _movementBoneXML)
{
return;
}
_movementBoneXML = movementBoneXML;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_BONE_DATA , this.boneName);
}
internal function updateBoneParent(boneName:String):void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var armatureData:ArmatureData = ImportDataProxy.getInstance().skeletonData.getArmatureData(animationName);
XMLDataParser.parseAnimationData(_xml, animationData, armatureData);
}
private function updateMovement():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
movementData.durationTo = durationTo;
movementData.durationTween = durationTween;
movementData.loop = loop;
movementData.tweenEasing = tweenEasing;
if(!ImportDataProxy.getInstance().isExportedSource)
{
JSFLProxy.getInstance().changeMovement(animationName, movementName, _movementXML);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_DATA, movementName);
}
private function updateMovementBone():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
var movementBoneData:MovementBoneData = movementData.getMovementBoneData(boneName);
movementBoneData.scale = boneScale * 0.01;
movementBoneData.delay = boneDelay * 0.01;
if(movementBoneData.delay > 0)
{
movementBoneData.delay -= 1;
}
if(!ImportDataProxy.getInstance().isExportedSource)
{
var movementXMLCopy:XML = _movementXML.copy();
delete movementXMLCopy.elements(ConstValues.BONE).*;
delete movementXMLCopy[ConstValues.FRAME];
JSFLProxy.getInstance().changeMovement(animationName, movementName, movementXMLCopy);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_BONE_DATA, movementName);
}
}
}
|
package model
{
import dragonBones.objects.AnimationData;
import dragonBones.objects.ArmatureData;
import dragonBones.objects.MovementBoneData;
import dragonBones.objects.MovementData;
import dragonBones.objects.XMLDataParser;
import dragonBones.utils.ConstValues;
import dragonBones.utils.dragonBones_internal;
import flash.events.Event;
import message.MessageDispatcher;
import mx.collections.XMLListCollection;
use namespace dragonBones_internal;
/**
* Manage selected animation data
*/
public class AnimationDataProxy
{
public var movementsMC:XMLListCollection;
private var _xml:XML;
private var _movementsXMLList:XMLList;
private var _movementXML:XML;
private var _movementBonesXMLList:XMLList;
private var _movementBoneXML:XML;
public function get animationName():String
{
return _xml?_xml.attribute(ConstValues.A_NAME):"";
}
public function get movementName():String
{
return _movementXML?_movementXML.attribute(ConstValues.A_NAME):"";
}
public function get boneName():String
{
return _movementBoneXML?_movementBoneXML.attribute(ConstValues.A_NAME):"";
}
public function get durationTo():Number
{
if(!_movementXML)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TO)) / ImportDataProxy.getInstance().frameRate;
}
public function set durationTo(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TO] = Math.round(value * ImportDataProxy.getInstance().frameRate);
updateMovement();
}
}
public function get durationTween():Number
{
if(_movementXML?int(_movementXML.attribute(ConstValues.A_DURATION)) == 1:true)
{
return -1;
}
return int(_movementXML.attribute(ConstValues.A_DURATION_TWEEN)) / ImportDataProxy.getInstance().frameRate;
}
public function set durationTween(value:Number):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_DURATION_TWEEN] = Math.round(value * ImportDataProxy.getInstance().frameRate);
updateMovement();
}
}
public function get loop():Boolean
{
return _movementXML?Boolean(int(_movementXML.attribute(ConstValues.A_LOOP)) == 1):false;
}
public function set loop(value:Boolean):void
{
if(_movementXML)
{
_movementXML.@[ConstValues.A_LOOP] = value?1:0;
updateMovement();
}
}
public function get tweenEasing():Number
{
return _movementXML?Number(_movementXML.attribute(ConstValues.A_TWEEN_EASING)):-1.1;
}
public function set tweenEasing(value:Number):void
{
if(_movementXML)
{
if(value<-1)
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = NaN;
}
else
{
_movementXML.@[ConstValues.A_TWEEN_EASING] = value;
}
updateMovement();
}
}
public function get boneScale():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_SCALE)) * 100;
}
public function set boneScale(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_SCALE] = value * 0.01;
updateMovementBone();
}
}
public function get boneDelay():Number
{
if(!_movementBoneXML || int(_movementXML.attribute(ConstValues.A_DURATION)) < 2)
{
return NaN;
}
return Number(_movementBoneXML.attribute(ConstValues.A_MOVEMENT_DELAY))* 100;
}
public function set boneDelay(value:Number):void
{
if(_movementBoneXML)
{
_movementBoneXML.@[ConstValues.A_MOVEMENT_DELAY] = value * 0.01;
updateMovementBone();
}
}
public function AnimationDataProxy()
{
movementsMC = new XMLListCollection();
}
internal function setData(xml:XML):void
{
_xml = xml;
if(_xml)
{
_movementsXMLList = _xml.elements(ConstValues.MOVEMENT);
}
else
{
_movementsXMLList = null;
}
movementsMC.source = _movementsXMLList;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_ANIMATION_DATA, animationName);
changeMovement();
}
public function changeMovement(movementName:String = null, isChangedByArmature:Boolean = false):void
{
_movementXML = ImportDataProxy.getElementByName(_movementsXMLList, movementName, true);
if(_movementXML)
{
_movementBonesXMLList = _movementXML.elements(ConstValues.BONE);
}
else
{
_movementBonesXMLList = null;
}
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_DATA, this.movementName, isChangedByArmature);
changeMovementBone(ImportDataProxy.getInstance().armatureDataProxy.boneName);
}
public function changeMovementBone(boneName:String = null):void
{
var movementBoneXML:XML = ImportDataProxy.getElementByName(_movementBonesXMLList, boneName, true);
if(movementBoneXML == _movementBoneXML)
{
return;
}
_movementBoneXML = movementBoneXML;
MessageDispatcher.dispatchEvent(MessageDispatcher.CHANGE_MOVEMENT_BONE_DATA , this.boneName);
}
internal function updateBoneParent(boneName:String):void
{
if(_xml)
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var armatureData:ArmatureData = ImportDataProxy.getInstance().skeletonData.getArmatureData(animationName);
XMLDataParser.parseAnimationData(_xml, animationData, armatureData);
}
}
private function updateMovement():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
movementData.durationTo = durationTo;
movementData.durationTween = durationTween;
movementData.loop = loop;
movementData.tweenEasing = tweenEasing;
if(!ImportDataProxy.getInstance().isExportedSource)
{
JSFLProxy.getInstance().changeMovement(animationName, movementName, _movementXML);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_DATA, movementName);
}
private function updateMovementBone():void
{
var animationData:AnimationData = ImportDataProxy.getInstance().skeletonData.getAnimationData(animationName);
var movementData:MovementData = animationData.getMovementData(movementName);
var movementBoneData:MovementBoneData = movementData.getMovementBoneData(boneName);
movementBoneData.scale = boneScale * 0.01;
movementBoneData.delay = boneDelay * 0.01;
if(movementBoneData.delay > 0)
{
movementBoneData.delay -= 1;
}
if(!ImportDataProxy.getInstance().isExportedSource)
{
var movementXMLCopy:XML = _movementXML.copy();
delete movementXMLCopy.elements(ConstValues.BONE).*;
delete movementXMLCopy[ConstValues.FRAME];
JSFLProxy.getInstance().changeMovement(animationName, movementName, movementXMLCopy);
}
MessageDispatcher.dispatchEvent(MessageDispatcher.UPDATE_MOVEMENT_BONE_DATA, movementName);
}
}
}
|
fix bone parent change bug
|
fix bone parent change bug
|
ActionScript
|
mit
|
DragonBones/DesignPanel
|
c81aa637f8fd1fc716894d409997fdc15164ebcf
|
collect-client/src/main/flex/org/openforis/collect/presenter/CSVDataImportPresenter.as
|
collect-client/src/main/flex/org/openforis/collect/presenter/CSVDataImportPresenter.as
|
package org.openforis.collect.presenter
{
import flash.events.Event;
import flash.net.FileFilter;
import mx.collections.ArrayCollection;
import mx.collections.IList;
import mx.collections.ListCollectionView;
import mx.controls.Tree;
import mx.events.ListEvent;
import mx.rpc.AsyncResponder;
import mx.rpc.events.ResultEvent;
import org.openforis.collect.Application;
import org.openforis.collect.client.CSVDataImportClient;
import org.openforis.collect.client.ClientFactory;
import org.openforis.collect.event.UIEvent;
import org.openforis.collect.i18n.Message;
import org.openforis.collect.metamodel.proxy.AttributeDefinitionProxy;
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.metamodel.proxy.ModelVersionProxy;
import org.openforis.collect.metamodel.proxy.NodeDefinitionProxy;
import org.openforis.collect.model.CollectRecord$Step;
import org.openforis.collect.model.NodeItem;
import org.openforis.collect.ui.view.CSVDataImportView;
import org.openforis.collect.util.AlertUtil;
import org.openforis.collect.util.ArrayUtil;
import org.openforis.collect.util.CollectionUtil;
import org.openforis.collect.util.StringUtil;
import spark.components.DropDownList;
/**
*
* @author Ricci, Stefano
*
* */
public class CSVDataImportPresenter extends AbstractReferenceDataImportPresenter {
private static const ALL_STEPS_ITEM:Object = {label: Message.get('global.allItemsLabel')};
private static const ALLOWED_MULTIPLE_FILES_IMPORT_FILE_EXTENSIONS:Array = [".zip"];
private var _importClient:CSVDataImportClient;
public function CSVDataImportPresenter(view:CSVDataImportView) {
super(view, new MessageKeys());
_importClient = ClientFactory.csvDataImportClient;
}
override public function init():void {
super.init();
updateImportFileFormatInfoMessage();
}
override protected function initEventListeners():void {
super.initEventListeners();
view.entitySelectionTree.addEventListener(ListEvent.ITEM_CLICK, entityTreeItemSelectHandler);
view.importType.addEventListener(Event.CHANGE, importTypeChangeHandler);
}
override protected function createFileFilter():FileFilter {
switch(view.importType.selectedValue) {
case CSVDataImportView.INSERT_NEW_RECORDS_TYPE:
case CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE:
return new FileFilter("Excel documents", AbstractReferenceDataImportPresenter.ALLOWED_IMPORT_FILE_EXTENSIONS.join("; "));
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
return new FileFilter("Collect data export ZIP file", ALLOWED_MULTIPLE_FILES_IMPORT_FILE_EXTENSIONS.join("; "));
}
}
protected function importTypeChangeHandler(event:Event):void {
backToDefaultView();
view.stepDropDownList.selectedItem = CollectRecord$Step.ENTRY;
}
protected function entityTreeItemSelectHandler(event:ListEvent):void {
updateImportFileFormatInfoMessage();
}
protected function updateImportFileFormatInfoMessage():void {
var messageArgs:Array = [];
var tree:Tree = view.entitySelectionTree;
var selectedTreeItem:NodeItem = tree.selectedItem as NodeItem;
if ( selectedTreeItem == null ) {
view.importFileFormatInfo = Message.get("csvDataImport.alert.selectEntity");
} else {
var selectedNodeDefn:EntityDefinitionProxy = selectedTreeItem.nodeDefinition as EntityDefinitionProxy;
messageArgs[0] = StringUtil.concat(", ", getRecordKeyColumnNames(selectedNodeDefn));
messageArgs[1] = StringUtil.concat(", ", getAncestorKeyColumnNames(selectedNodeDefn));
messageArgs[2] = StringUtil.concat(", ", getExampleAttributeColumnNames(selectedNodeDefn));
view.importFileFormatInfo = Message.get(messageKeys.IMPORT_FILE_FORMAT_INFO, messageArgs);
}
}
private function getExampleAttributeColumnNames(selectedNodeDefn:EntityDefinitionProxy):Array {
var result:Array = new Array();
var children:ListCollectionView = selectedNodeDefn.childDefinitions;
for ( var i:int = 0; i < children.length && result.length <= 3; i++) {
var child:NodeDefinitionProxy = children.getItemAt(i) as NodeDefinitionProxy;
if ( child is AttributeDefinitionProxy &&
! CollectionUtil.contains(selectedNodeDefn.keyAttributeDefinitions, child, "id") ) {
result.push(child.name);
}
}
return result;
}
protected function getRecordKeyColumnNames(nodeDefn:EntityDefinitionProxy):Array {
var result:Array = new Array();
var rootEntityDefn:EntityDefinitionProxy = nodeDefn.rootEntity;
var keyDefns:IList = rootEntityDefn.keyAttributeDefinitions;
for each (var keyDefn:AttributeDefinitionProxy in keyDefns) {
result.push(rootEntityDefn.name + "_" + keyDefn.name);
}
return result;
}
protected function getAncestorKeyColumnNames(nodeDefn:EntityDefinitionProxy):Array {
var result:ArrayCollection = new ArrayCollection();
var currentParent:EntityDefinitionProxy = nodeDefn;
while ( currentParent != null && currentParent != nodeDefn.rootEntity ) {
var keyDefns:IList = currentParent.keyAttributeDefinitions;
if ( CollectionUtil.isEmpty(keyDefns) ) {
if ( currentParent.multiple ) {
result.addItemAt("_" + currentParent.name + "_position", 0);
} else {
//TODO consider it for naming following key definitions
}
} else {
var colNames:Array = new Array();
for each (var keyDefn:AttributeDefinitionProxy in keyDefns) {
var colName:String = "";
if ( currentParent != nodeDefn ) {
colName += currentParent.name + "_";
}
colName += keyDefn.name;
colNames.push(colName);
}
result.addAllAt(new ArrayCollection(colNames), 0);
}
currentParent = currentParent.parent;
}
return result.toArray();
}
public function getRequiredColumnNamesForSelectedEntity():Array {
var result:Array = new Array();
var selectedEntity:EntityDefinitionProxy = view.entitySelectionTree.selectedItem as EntityDefinitionProxy;
if ( selectedEntity != null ) {
ArrayUtil.addAll(result, getRecordKeyColumnNames(selectedEntity));
ArrayUtil.addAll(result, getAncestorKeyColumnNames(selectedEntity));
}
return result;
}
private function get view():CSVDataImportView {
return CSVDataImportView(_view);
}
private function get messageKeys():MessageKeys {
return MessageKeys(_messageKeys);
}
override protected function fileReferenceSelectHandler(event:Event):void {
switch(view.importType.selectedValue) {
case CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE:
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
confirmUploadStart(messageKeys.CONFIRM_IMPORT);
break;
default:
//when inserting new records, do not ask for confirmation
startUpload();
}
}
override protected function checkCanImport():Boolean {
//validate form
var importType:String = view.importType.selectedValue as String;
if ( importType == CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE ) {
if ( view.entitySelectionTree.selectedItem == null ) {
AlertUtil.showError("csvDataImport.alert.selectEntity");
return false;
} else if ( ! NodeItem(view.entitySelectionTree.selectedItem).nodeDefinition.multiple ) {
AlertUtil.showError("csvDataImport.alert.selectMultipleEntity");
return false;
} else {
return true;
}
} else if ( view.formVersionDropDownList.selectedItem == null && CollectionUtil.isNotEmpty(view.formVersionDropDownList.dataProvider) ) {
AlertUtil.showError("csvDataImport.alert.selectModelVersion");
return false;
} else {
return true;
}
}
override protected function performProcessStart():void {
var responder:AsyncResponder = new AsyncResponder(startResultHandler, faultHandler);
var transactional:Boolean = view.transactionalCheckBox.selected;
var validateRecords:Boolean = view.validateRecordsCheckBox.selected;
var deleteExistingEntities:Boolean = view.deleteExistingEntitiesCheckBox.selected;
var entityId:int;
var selectedStep:CollectRecord$Step = null;
var insertNewRecords:Boolean;
var newRecordModelVersion:String = null;
switch(view.importType.selectedValue) {
case CSVDataImportView.INSERT_NEW_RECORDS_TYPE:
//insert new records
insertNewRecords = true;
entityId = Application.activeRootEntity.id;
var version:ModelVersionProxy = view.formVersionDropDownList.selectedItem;
newRecordModelVersion = version == null ? null: version.name;
break;
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
insertNewRecords = true;
var version:ModelVersionProxy = view.formVersionDropDownList.selectedItem;
newRecordModelVersion = version == null ? null: version.name;
break;
default:
//update existing records
insertNewRecords = false;
entityId = NodeItem(view.entitySelectionTree.selectedItem).id;
var selectedStepItem:* = view.stepDropDownList.selectedItem;
selectedStep = selectedStepItem == ALL_STEPS_ITEM ? null: selectedStepItem as CollectRecord$Step;
}
_importClient.start(responder, _uploadedTempFileName, entityId, selectedStep, transactional, validateRecords, insertNewRecords, newRecordModelVersion, deleteExistingEntities);
}
override protected function performImportCancel():void {
var responder:AsyncResponder = new AsyncResponder(cancelResultHandler, faultHandler);
_importClient.cancel(responder);
}
override protected function performCancelThenClose():void {
var responder:AsyncResponder = new AsyncResponder(cancelResultHandler, faultHandler);
_importClient.cancel(responder);
function cancelResultHandler(event:ResultEvent, token:Object = null):void {
closePopUp();
}
}
override protected function updateStatus():void {
_importClient.getStatus(_getStatusResponder);
}
override protected function updateViewProcessComplete():void {
super.updateViewProcessComplete();
//reload record summaries
var uiEvent:UIEvent = new UIEvent(UIEvent.RELOAD_RECORD_SUMMARIES);
eventDispatcher.dispatchEvent(uiEvent);
}
override protected function loadInitialData():void {
initView();
updateStatus();
}
override protected function loadSummaries():void {
//do nothing
}
protected function initView():void {
initEntitiesTree();
initFormVersionsDropDown();
initStepsDropDown();
view.importType.selectedValue = CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE;
view.transactionalCheckBox.selected = true;
view.validateRecordsCheckBox.selected = true;
}
protected function initEntitiesTree():void {
var rootEntity:EntityDefinitionProxy = Application.activeRootEntity;
var rootNodeItem:NodeItem = NodeItem.fromNodeDef(rootEntity, true, false, false);
var tree:Tree = view.entitySelectionTree;
tree.dataProvider = new ArrayCollection([rootNodeItem]);
tree.callLater(function():void {
tree.expandItem(rootNodeItem, true);
});
}
protected function initFormVersionsDropDown():void {
Application.activeSurvey.versions;
var items:IList = new ArrayCollection(Application.activeSurvey.versions.toArray());
var dropDownList:DropDownList = view.formVersionDropDownList;
dropDownList.dataProvider = items;
//if only one model version is defined, select it
if ( items.length == 1 ) {
dropDownList.selectedIndex = 0;
}
}
protected function initStepsDropDown():void {
var steps:IList = new ArrayCollection(CollectRecord$Step.constants);
steps.addItemAt(ALL_STEPS_ITEM, 0);
var stepDropDownList:DropDownList = view.stepDropDownList;
stepDropDownList.dataProvider = steps;
stepDropDownList.callLater(function():void {
stepDropDownList.selectedIndex = 0;
});
}
override protected function backToDefaultView():void {
switch(view.importType.selectedValue) {
case CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE:
view.currentState = CSVDataImportView.STATE_UPDATE_EXISTING_RECORDS;
break;
case CSVDataImportView.INSERT_NEW_RECORDS_TYPE:
view.currentState = CSVDataImportView.STATE_INSERT_NEW_RECORDS;
break;
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
view.currentState = CSVDataImportView.STATE_IMPORT_MULTIPLE_FILES;
break;
}
}
}
}
import org.openforis.collect.presenter.ReferenceDataImportMessageKeys;
class MessageKeys extends ReferenceDataImportMessageKeys {
/*
override public function get CONFIRM_CLOSE_TITLE():String {
return "csvDataImport.confirmClose.title";
}
*/
public function get IMPORT_FILE_FORMAT_INFO():String {
return "csvDataImport.importFileFormatInfo";
}
override public function get CONFIRM_IMPORT():String {
return "csvDataImport.confirmImport.message";
}
}
|
package org.openforis.collect.presenter
{
import flash.events.Event;
import flash.net.FileFilter;
import mx.collections.ArrayCollection;
import mx.collections.IList;
import mx.collections.ListCollectionView;
import mx.controls.Tree;
import mx.events.ListEvent;
import mx.rpc.AsyncResponder;
import mx.rpc.events.ResultEvent;
import org.openforis.collect.Application;
import org.openforis.collect.client.CSVDataImportClient;
import org.openforis.collect.client.ClientFactory;
import org.openforis.collect.event.UIEvent;
import org.openforis.collect.i18n.Message;
import org.openforis.collect.metamodel.proxy.AttributeDefinitionProxy;
import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy;
import org.openforis.collect.metamodel.proxy.ModelVersionProxy;
import org.openforis.collect.metamodel.proxy.NodeDefinitionProxy;
import org.openforis.collect.model.CollectRecord$Step;
import org.openforis.collect.model.NodeItem;
import org.openforis.collect.ui.view.CSVDataImportView;
import org.openforis.collect.util.AlertUtil;
import org.openforis.collect.util.ArrayUtil;
import org.openforis.collect.util.CollectionUtil;
import org.openforis.collect.util.StringUtil;
import spark.components.DropDownList;
/**
*
* @author Ricci, Stefano
*
* */
public class CSVDataImportPresenter extends AbstractReferenceDataImportPresenter {
private static const ALL_STEPS_ITEM:Object = {label: Message.get('global.allItemsLabel')};
private static const ALLOWED_MULTIPLE_FILES_IMPORT_FILE_EXTENSIONS:Array = [".zip"];
private var _importClient:CSVDataImportClient;
public function CSVDataImportPresenter(view:CSVDataImportView) {
super(view, new MessageKeys());
_importClient = ClientFactory.csvDataImportClient;
}
override public function init():void {
super.init();
updateImportFileFormatInfoMessage();
}
override protected function initEventListeners():void {
super.initEventListeners();
view.entitySelectionTree.addEventListener(ListEvent.ITEM_CLICK, entityTreeItemSelectHandler);
view.importType.addEventListener(Event.CHANGE, importTypeChangeHandler);
}
override protected function createFileFilter():FileFilter {
switch(view.importType.selectedValue) {
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
return new FileFilter("Collect data export ZIP file", ALLOWED_MULTIPLE_FILES_IMPORT_FILE_EXTENSIONS.join("; "));
default:
return new FileFilter("Excel documents", AbstractReferenceDataImportPresenter.ALLOWED_IMPORT_FILE_EXTENSIONS.join("; "));
}
}
protected function importTypeChangeHandler(event:Event):void {
backToDefaultView();
view.stepDropDownList.selectedItem = CollectRecord$Step.ENTRY;
}
protected function entityTreeItemSelectHandler(event:ListEvent):void {
updateImportFileFormatInfoMessage();
}
protected function updateImportFileFormatInfoMessage():void {
var messageArgs:Array = [];
var tree:Tree = view.entitySelectionTree;
var selectedTreeItem:NodeItem = tree.selectedItem as NodeItem;
if ( selectedTreeItem == null ) {
view.importFileFormatInfo = Message.get("csvDataImport.alert.selectEntity");
} else {
var selectedNodeDefn:EntityDefinitionProxy = selectedTreeItem.nodeDefinition as EntityDefinitionProxy;
messageArgs[0] = StringUtil.concat(", ", getRecordKeyColumnNames(selectedNodeDefn));
messageArgs[1] = StringUtil.concat(", ", getAncestorKeyColumnNames(selectedNodeDefn));
messageArgs[2] = StringUtil.concat(", ", getExampleAttributeColumnNames(selectedNodeDefn));
view.importFileFormatInfo = Message.get(messageKeys.IMPORT_FILE_FORMAT_INFO, messageArgs);
}
}
private function getExampleAttributeColumnNames(selectedNodeDefn:EntityDefinitionProxy):Array {
var result:Array = new Array();
var children:ListCollectionView = selectedNodeDefn.childDefinitions;
for ( var i:int = 0; i < children.length && result.length <= 3; i++) {
var child:NodeDefinitionProxy = children.getItemAt(i) as NodeDefinitionProxy;
if ( child is AttributeDefinitionProxy &&
! CollectionUtil.contains(selectedNodeDefn.keyAttributeDefinitions, child, "id") ) {
result.push(child.name);
}
}
return result;
}
protected function getRecordKeyColumnNames(nodeDefn:EntityDefinitionProxy):Array {
var result:Array = new Array();
var rootEntityDefn:EntityDefinitionProxy = nodeDefn.rootEntity;
var keyDefns:IList = rootEntityDefn.keyAttributeDefinitions;
for each (var keyDefn:AttributeDefinitionProxy in keyDefns) {
result.push(rootEntityDefn.name + "_" + keyDefn.name);
}
return result;
}
protected function getAncestorKeyColumnNames(nodeDefn:EntityDefinitionProxy):Array {
var result:ArrayCollection = new ArrayCollection();
var currentParent:EntityDefinitionProxy = nodeDefn;
while ( currentParent != null && currentParent != nodeDefn.rootEntity ) {
var keyDefns:IList = currentParent.keyAttributeDefinitions;
if ( CollectionUtil.isEmpty(keyDefns) ) {
if ( currentParent.multiple ) {
result.addItemAt("_" + currentParent.name + "_position", 0);
} else {
//TODO consider it for naming following key definitions
}
} else {
var colNames:Array = new Array();
for each (var keyDefn:AttributeDefinitionProxy in keyDefns) {
var colName:String = "";
if ( currentParent != nodeDefn ) {
colName += currentParent.name + "_";
}
colName += keyDefn.name;
colNames.push(colName);
}
result.addAllAt(new ArrayCollection(colNames), 0);
}
currentParent = currentParent.parent;
}
return result.toArray();
}
public function getRequiredColumnNamesForSelectedEntity():Array {
var result:Array = new Array();
var selectedEntity:EntityDefinitionProxy = view.entitySelectionTree.selectedItem as EntityDefinitionProxy;
if ( selectedEntity != null ) {
ArrayUtil.addAll(result, getRecordKeyColumnNames(selectedEntity));
ArrayUtil.addAll(result, getAncestorKeyColumnNames(selectedEntity));
}
return result;
}
private function get view():CSVDataImportView {
return CSVDataImportView(_view);
}
private function get messageKeys():MessageKeys {
return MessageKeys(_messageKeys);
}
override protected function fileReferenceSelectHandler(event:Event):void {
switch(view.importType.selectedValue) {
case CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE:
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
confirmUploadStart(messageKeys.CONFIRM_IMPORT);
break;
default:
//when inserting new records, do not ask for confirmation
startUpload();
}
}
override protected function checkCanImport():Boolean {
//validate form
var importType:String = view.importType.selectedValue as String;
if ( importType == CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE ) {
if ( view.entitySelectionTree.selectedItem == null ) {
AlertUtil.showError("csvDataImport.alert.selectEntity");
return false;
} else if ( ! NodeItem(view.entitySelectionTree.selectedItem).nodeDefinition.multiple ) {
AlertUtil.showError("csvDataImport.alert.selectMultipleEntity");
return false;
} else {
return true;
}
} else if ( view.formVersionDropDownList.selectedItem == null && CollectionUtil.isNotEmpty(view.formVersionDropDownList.dataProvider) ) {
AlertUtil.showError("csvDataImport.alert.selectModelVersion");
return false;
} else {
return true;
}
}
override protected function performProcessStart():void {
var responder:AsyncResponder = new AsyncResponder(startResultHandler, faultHandler);
var transactional:Boolean = view.transactionalCheckBox.selected;
var validateRecords:Boolean = view.validateRecordsCheckBox.selected;
var deleteExistingEntities:Boolean = view.deleteExistingEntitiesCheckBox.selected;
var entityId:int;
var selectedStep:CollectRecord$Step = null;
var insertNewRecords:Boolean;
var newRecordModelVersion:String = null;
switch(view.importType.selectedValue) {
case CSVDataImportView.INSERT_NEW_RECORDS_TYPE:
//insert new records
insertNewRecords = true;
entityId = Application.activeRootEntity.id;
var version:ModelVersionProxy = view.formVersionDropDownList.selectedItem;
newRecordModelVersion = version == null ? null: version.name;
break;
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
insertNewRecords = true;
var version:ModelVersionProxy = view.formVersionDropDownList.selectedItem;
newRecordModelVersion = version == null ? null: version.name;
break;
default:
//update existing records
insertNewRecords = false;
entityId = NodeItem(view.entitySelectionTree.selectedItem).id;
var selectedStepItem:* = view.stepDropDownList.selectedItem;
selectedStep = selectedStepItem == ALL_STEPS_ITEM ? null: selectedStepItem as CollectRecord$Step;
}
_importClient.start(responder, _uploadedTempFileName, entityId, selectedStep, transactional, validateRecords, insertNewRecords, newRecordModelVersion, deleteExistingEntities);
}
override protected function performImportCancel():void {
var responder:AsyncResponder = new AsyncResponder(cancelResultHandler, faultHandler);
_importClient.cancel(responder);
}
override protected function performCancelThenClose():void {
var responder:AsyncResponder = new AsyncResponder(cancelResultHandler, faultHandler);
_importClient.cancel(responder);
function cancelResultHandler(event:ResultEvent, token:Object = null):void {
closePopUp();
}
}
override protected function updateStatus():void {
_importClient.getStatus(_getStatusResponder);
}
override protected function updateViewProcessComplete():void {
super.updateViewProcessComplete();
//reload record summaries
var uiEvent:UIEvent = new UIEvent(UIEvent.RELOAD_RECORD_SUMMARIES);
eventDispatcher.dispatchEvent(uiEvent);
}
override protected function loadInitialData():void {
initView();
updateStatus();
}
override protected function loadSummaries():void {
//do nothing
}
protected function initView():void {
initEntitiesTree();
initFormVersionsDropDown();
initStepsDropDown();
view.importType.selectedValue = CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE;
view.transactionalCheckBox.selected = true;
view.validateRecordsCheckBox.selected = true;
}
protected function initEntitiesTree():void {
var rootEntity:EntityDefinitionProxy = Application.activeRootEntity;
var rootNodeItem:NodeItem = NodeItem.fromNodeDef(rootEntity, true, false, false);
var tree:Tree = view.entitySelectionTree;
tree.dataProvider = new ArrayCollection([rootNodeItem]);
tree.callLater(function():void {
tree.expandItem(rootNodeItem, true);
});
}
protected function initFormVersionsDropDown():void {
Application.activeSurvey.versions;
var items:IList = new ArrayCollection(Application.activeSurvey.versions.toArray());
var dropDownList:DropDownList = view.formVersionDropDownList;
dropDownList.dataProvider = items;
//if only one model version is defined, select it
if ( items.length == 1 ) {
dropDownList.selectedIndex = 0;
}
}
protected function initStepsDropDown():void {
var steps:IList = new ArrayCollection(CollectRecord$Step.constants);
steps.addItemAt(ALL_STEPS_ITEM, 0);
var stepDropDownList:DropDownList = view.stepDropDownList;
stepDropDownList.dataProvider = steps;
stepDropDownList.callLater(function():void {
stepDropDownList.selectedIndex = 0;
});
}
override protected function backToDefaultView():void {
switch(view.importType.selectedValue) {
case CSVDataImportView.UPDATE_EXISTING_RECORDS_TYPE:
view.currentState = CSVDataImportView.STATE_UPDATE_EXISTING_RECORDS;
break;
case CSVDataImportView.INSERT_NEW_RECORDS_TYPE:
view.currentState = CSVDataImportView.STATE_INSERT_NEW_RECORDS;
break;
case CSVDataImportView.IMPORT_MULTIPLE_FILES_TYPE:
view.currentState = CSVDataImportView.STATE_IMPORT_MULTIPLE_FILES;
break;
}
}
}
}
import org.openforis.collect.presenter.ReferenceDataImportMessageKeys;
class MessageKeys extends ReferenceDataImportMessageKeys {
/*
override public function get CONFIRM_CLOSE_TITLE():String {
return "csvDataImport.confirmClose.title";
}
*/
public function get IMPORT_FILE_FORMAT_INFO():String {
return "csvDataImport.importFileFormatInfo";
}
override public function get CONFIRM_IMPORT():String {
return "csvDataImport.confirmImport.message";
}
}
|
Solve compilation problem
|
Solve compilation problem
|
ActionScript
|
mit
|
openforis/collect,openforis/collect,openforis/collect,openforis/collect
|
afd4b0c9fed667da1b6153ec88bdf503fbef4f4b
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ScrollingContainerView.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ScrollingContainerView.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads
{
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IScrollingLayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.html.Container;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ContainerContentArea;
import org.apache.flex.html.supportClasses.ScrollBar;
import org.apache.flex.html.beads.models.ScrollBarModel;
/**
* The ContainerView class is the default view for
* the org.apache.flex.html.Container class.
* It lets you use some CSS styles to manage the border, background
* and padding around the content area.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ScrollingContainerView extends BeadViewBase implements IBeadView, IScrollingLayoutParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ScrollingContainerView()
{
}
/**
* The actual parent that parents the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var actualParent:UIBase;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
var padding:Object = determinePadding();
if (contentAreaNeeded())
{
actualParent = new ContainerContentArea();
IParent(value).addElement(actualParent);
Container(value).setActualParent(actualParent);
actualParent.x = padding.paddingLeft;
actualParent.y = padding.paddingTop;
}
else
{
actualParent = value as UIBase;
}
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(value, "background-color");
var backgroundImage:Object = ValuesManager.valuesImpl.getValue(value, "background-image");
if (backgroundColor != null || backgroundImage != null)
{
if (value.getBeadByType(IBackgroundBead) == null)
value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBackgroundBead")) as IBead);
}
var borderStyle:String;
var borderStyles:Object = ValuesManager.valuesImpl.getValue(value, "border");
if (borderStyles is Array)
{
borderStyle = borderStyles[1];
}
if (borderStyle == null)
{
borderStyle = ValuesManager.valuesImpl.getValue(value, "border-style") as String;
}
if (borderStyle != null && borderStyle != "none")
{
if (value.getBeadByType(IBorderBead) == null)
value.addBead(new (ValuesManager.valuesImpl.getValue(value, "iBorderBead")) as IBead);
}
}
/**
* Determines the top and left padding values, if any, as set by
* padding style values. This includes "padding" for all padding values
* as well as "padding-left" and "padding-top".
*
* Returns an object with paddingLeft and paddingTop properties.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function determinePadding():Object
{
var paddingLeft:Object;
var paddingTop:Object;
var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding");
if (padding is Array)
{
if (padding.length == 1)
paddingLeft = paddingTop = padding[0];
else if (padding.length <= 3)
{
paddingLeft = padding[1];
paddingTop = padding[0];
}
else if (padding.length == 4)
{
paddingLeft = padding[3];
paddingTop = padding[0];
}
}
else if (padding == null)
{
paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left");
paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top");
}
else
{
paddingLeft = paddingTop = padding;
}
var pl:Number = Number(paddingLeft);
var pt:Number = Number(paddingTop);
return {paddingLeft:pl, paddingTop:pt};
}
/**
* Returns true if container to create a separate ContainerContentArea.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function contentAreaNeeded():Boolean
{
var padding:Object = determinePadding();
return (!isNaN(padding.paddingLeft) && padding.paddingLeft > 0 ||
!isNaN(padding.paddingTop) && padding.paddingTop > 0);
}
/**
* The parent of the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get contentView():IParentIUIBase
{
return actualParent;
}
/**
* The border.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get border():Border
{
return null;
}
/**
* The host component, which can resize to different slots.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get resizableView():IUIBase
{
return _strand as IUIBase;
}
private var _vScrollBar:ScrollBar;
/**
* The vertical ScrollBar, if it exists.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get vScrollBar():ScrollBar
{
if (!_vScrollBar)
_vScrollBar = createScrollBar();
return _vScrollBar;
}
/**
* The horizontal ScrollBar, if it exists.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get hScrollBar():ScrollBar
{
return null;
}
/**
* @private
*/
private function createScrollBar():ScrollBar
{
var vsb:ScrollBar;
vsb = new ScrollBar();
var vsbm:ScrollBarModel = new ScrollBarModel();
vsbm.maximum = 100;
vsbm.minimum = 0;
vsbm.pageSize = 10;
vsbm.pageStepSize = 10;
vsbm.snapInterval = 1;
vsbm.stepSize = 1;
vsbm.value = 0;
vsb.model = vsbm;
vsb.width = 16;
IParent(_strand).addElement(vsb);
return vsb;
}
/**
* The position of the vertical scrollbar
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get verticalScrollPosition():Number
{
return ScrollBarModel(vScrollBar.model).value;
}
/**
* @private
*/
public function set verticalScrollPosition(value:Number):void
{
ScrollBarModel(vScrollBar.model).value = value;
}
/**
* The maximum position of the vertical scrollbar
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxVerticalScrollPosition():Number
{
return ScrollBarModel(vScrollBar.model).maximum -
ScrollBarModel(vScrollBar.model).pageSize;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads
{
import org.apache.flex.core.BeadViewBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IScrollingLayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.html.Container;
import org.apache.flex.html.beads.models.ScrollBarModel;
import org.apache.flex.html.supportClasses.Border;
import org.apache.flex.html.supportClasses.ContainerContentArea;
import org.apache.flex.html.supportClasses.ScrollBar;
/**
* The ContainerView class is the default view for
* the org.apache.flex.html.Container class.
* It lets you use some CSS styles to manage the border, background
* and padding around the content area.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ScrollingContainerView extends BeadViewBase implements IBeadView, IScrollingLayoutParent
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ScrollingContainerView()
{
}
/**
* The actual parent that parents the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected var actualParent:UIBase;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function set strand(value:IStrand):void
{
super.strand = value;
var host:UIBase = value as UIBase;
if (host.numChildren > 0)
childHandler(null);
else
host.addEventListener("childrenAdded", childHandler);
}
private function childHandler(event:Event):void
{
var host:UIBase = _strand as UIBase;
if (host.numChildren > 0)
{
actualParent = host.getChildAt(0) as UIBase;
}
var backgroundColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color");
var backgroundImage:Object = ValuesManager.valuesImpl.getValue(host, "background-image");
if (backgroundColor != null || backgroundImage != null)
{
if (host.getBeadByType(IBackgroundBead) == null)
host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBackgroundBead")) as IBead);
}
var borderStyle:String;
var borderStyles:Object = ValuesManager.valuesImpl.getValue(host, "border");
if (borderStyles is Array)
{
borderStyle = borderStyles[1];
}
if (borderStyle == null)
{
borderStyle = ValuesManager.valuesImpl.getValue(host, "border-style") as String;
}
if (borderStyle != null && borderStyle != "none")
{
if (host.getBeadByType(IBorderBead) == null)
host.addBead(new (ValuesManager.valuesImpl.getValue(host, "iBorderBead")) as IBead);
}
}
/**
* The parent of the children.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get contentView():IParentIUIBase
{
return actualParent;
}
/**
* The border.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get border():Border
{
return null;
}
/**
* The host component, which can resize to different slots.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get resizableView():IUIBase
{
return _strand as IUIBase;
}
private var _vScrollBar:ScrollBar;
/**
* The vertical ScrollBar, if it exists.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get vScrollBar():ScrollBar
{
if (!_vScrollBar)
_vScrollBar = createScrollBar();
return _vScrollBar;
}
/**
* The horizontal ScrollBar, if it exists.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get hScrollBar():ScrollBar
{
return null;
}
/**
* @private
*/
private function createScrollBar():ScrollBar
{
var vsb:ScrollBar;
vsb = new ScrollBar();
var vsbm:ScrollBarModel = new ScrollBarModel();
vsbm.maximum = 100;
vsbm.minimum = 0;
vsbm.pageSize = 10;
vsbm.pageStepSize = 10;
vsbm.snapInterval = 1;
vsbm.stepSize = 1;
vsbm.value = 0;
vsb.model = vsbm;
vsb.width = 16;
IParent(_strand).addElement(vsb);
return vsb;
}
/**
* The position of the vertical scrollbar
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get verticalScrollPosition():Number
{
return ScrollBarModel(vScrollBar.model).value;
}
/**
* @private
*/
public function set verticalScrollPosition(value:Number):void
{
ScrollBarModel(vScrollBar.model).value = value;
}
/**
* The maximum position of the vertical scrollbar
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxVerticalScrollPosition():Number
{
return ScrollBarModel(vScrollBar.model).maximum -
ScrollBarModel(vScrollBar.model).pageSize;
}
}
}
|
rewrite to assume a single child as the content area
|
rewrite to assume a single child as the content area
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
719b3f9d5ad0ad777fbde9c3459b442db62b04c7
|
src/aerys/minko/render/shader/SFloat.as
|
src/aerys/minko/render/shader/SFloat.as
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_shader;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.type.math.Matrix4x4;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* SFloat (Shader Float) objects are GPU-side computed value proxies
* declared, defined and used in ActionScript shaders.
*
* <p>
* ActionScript shaders define what operations will be
* performed on the GPU. Those operations take arguments and return
* values that will be computed and accessible on the graphics hardware
* only. Those values are represented by SFloat objects.
* </p>
*
* <p>
* Because SFloat objects are just hardware memory proxies, it is not
* possible (and does not make sense to try) to read their actual value
* using CPU-side code. For the very same reason, most of the errors will
* be detected at runtime only. The only available property is the size
* (number of components) of the corresponding value (ie. 3D vector
* operations will return SFloat objects of size 3, dot-product will
* return a scalar SFloat object of size 1, ...).
* </p>
*
* <p>
* SFloat objects also provide OOP shader programming by encapsulating
* common operations (add, multiply, ...). They also allow the use of
* dynamic properties in order to read or write sub-components of
* non-scalar values. Example:
* </p>
*
* <pre>
* public function getOutputColor() : void
* {
* var diffuse : SFloat = sampleTexture(BasicStyle.DIFFUSE_MAP);
*
* // use the RGB components of the diffuse map but use a
* // fixed alpha = 0.5
* return combine(diffuse.rgb, 0.5);
* }
* </pre>
*
* <p>
* Each SFloat object wraps a shader graph node that will be evaluated
* by the compiler in order to create the corresponding AGAL bytecode.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public dynamic final class SFloat extends Proxy
{
use namespace minko_shader;
minko_shader var _node : AbstractNode = null;
public final function get size() : uint
{
return _node.size;
}
public function SFloat(value : Object)
{
_node = getNode(value);
}
public final function scaleBy(arg : Object) : SFloat
{
_node = new Instruction(Instruction.MUL, _node, getNode(arg));
return this;
}
public final function incrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.ADD, _node, getNode(value));
return this;
}
public final function decrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.SUB, _node, getNode(value));
return this;
}
public final function normalize() : SFloat
{
_node = new Instruction(Instruction.NRM, _node);
return this;
}
public final function negate() : SFloat
{
_node = new Instruction(Instruction.NEG, _node);
return this;
}
override flash_proxy function getProperty(name : *) : *
{
return new SFloat(new Extract(_node, Components.stringToComponent(name)));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
var propertyName : String = String(name);
var propertyComponent : uint = getPropertyWriteComponentMask(propertyName);
var propertyNode : AbstractNode = getNode(value);
var nodeComponent : uint = Components.createContinuous(0, 0, _node.size, _node.size);
propertyNode = new Overwriter(
new <AbstractNode>[propertyNode],
new <uint>[Components.createContinuous(0, 0, 4, propertyNode.size)]
);
_node = new Overwriter(
new <AbstractNode>[_node, propertyNode],
new <uint>[nodeComponent, propertyComponent]
);
}
public static function getPropertyWriteComponentMask(string : String) : uint
{
var result : uint = 0x04040404;
for (var i : uint = 0; i < 4; ++i)
if (i < string.length)
switch (string.charAt(i))
{
case 'x': case 'X': case 'r': case 'R':
result = (0xffffff00 & result) | i;
result |= i << (8 * 0);
break;
case 'y': case 'Y': case 'g': case 'G':
result = (0xffff00ff & result) | i << 8;
break;
case 'z': case 'Z': case 'b': case 'B':
result = (0xff00ffff & result) | i << 16;
break;
case 'w': case 'W': case 'a': case 'A':
result = (0x00ffffff & result) | i << 24;
break;
default:
throw new Error('Invalid string.');
}
return result;
}
private function getNode(value : Object) : AbstractNode
{
if (value is AbstractNode)
return value as AbstractNode;
if (value is SFloat)
return (value as SFloat)._node;
if (value is uint || value is int || value is Number)
return new Constant(new <Number>[Number(value)]);
if (value is Matrix4x4)
return new Constant(Matrix4x4(value).getRawData(null, 0, false));
throw new Error('This type cannot be casted to a shader value.');
}
}
}
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko_shader;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.type.math.Matrix4x4;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* SFloat (Shader Float) objects are GPU-side computed value proxies
* declared, defined and used in ActionScript shaders.
*
* <p>
* ActionScript shaders define what operations will be
* performed on the GPU. Those operations take arguments and return
* values that will be computed and accessible on the graphics hardware
* only. Those values are represented by SFloat objects.
* </p>
*
* <p>
* Because SFloat objects are just hardware memory proxies, it is not
* possible (and does not make sense to try) to read their actual value
* using CPU-side code. For the very same reason, most of the errors will
* be detected at runtime only. The only available property is the size
* (number of components) of the corresponding value (ie. 3D vector
* operations will return SFloat objects of size 3, dot-product will
* return a scalar SFloat object of size 1, ...).
* </p>
*
* <p>
* SFloat objects also provide OOP shader programming by encapsulating
* common operations (add, multiply, ...). They also allow the use of
* dynamic properties in order to read or write sub-components of
* non-scalar values. Example:
* </p>
*
* <pre>
* public function getOutputColor() : void
* {
* var diffuse : SFloat = sampleTexture(BasicStyle.DIFFUSE_MAP);
*
* // use the RGB components of the diffuse map but use a
* // fixed alpha = 0.5
* return combine(diffuse.rgb, 0.5);
* }
* </pre>
*
* <p>
* Each SFloat object wraps a shader graph node that will be evaluated
* by the compiler in order to create the corresponding AGAL bytecode.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public dynamic final class SFloat extends Proxy
{
use namespace minko_shader;
minko_shader var _node : AbstractNode = null;
public final function get size() : uint
{
return _node.size;
}
public function SFloat(value : Object)
{
_node = getNode(value);
}
public final function scaleBy(arg : Object) : SFloat
{
_node = new Instruction(Instruction.MUL, _node, getNode(arg));
return this;
}
public final function incrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.ADD, _node, getNode(value));
return this;
}
public final function decrementBy(value : Object) : SFloat
{
_node = new Instruction(Instruction.SUB, _node, getNode(value));
return this;
}
public final function normalize() : SFloat
{
_node = new Instruction(Instruction.NRM, _node);
return this;
}
public final function negate() : SFloat
{
_node = new Instruction(Instruction.NEG, _node);
return this;
}
override flash_proxy function getProperty(name : *) : *
{
return new SFloat(new Extract(_node, Components.stringToComponent(name)));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
var propertyName : String = String(name);
var propertyComponent : uint = getPropertyWriteComponentMask(propertyName);
var propertyNode : AbstractNode = getNode(value);
var nodeComponent : uint = Components.createContinuous(0, 0, _node.size, _node.size);
propertyNode = new Overwriter(
new <AbstractNode>[propertyNode],
new <uint>[Components.createContinuous(0, 0, 4, propertyNode.size)]
);
_node = new Overwriter(
new <AbstractNode>[_node, propertyNode],
new <uint>[nodeComponent, propertyComponent]
);
}
private function getPropertyWriteComponentMask(string : String) : uint
{
var result : uint = 0x04040404;
for (var i : uint = 0; i < 4; ++i)
if (i < string.length)
switch (string.charAt(i))
{
case 'x': case 'X': case 'r': case 'R':
result = (0xffffff00 & result) | i;
result |= i << (8 * 0);
break;
case 'y': case 'Y': case 'g': case 'G':
result = (0xffff00ff & result) | i << 8;
break;
case 'z': case 'Z': case 'b': case 'B':
result = (0xff00ffff & result) | i << 16;
break;
case 'w': case 'W': case 'a': case 'A':
result = (0x00ffffff & result) | i << 24;
break;
default:
throw new Error('Invalid string.');
}
return result;
}
private function getNode(value : Object) : AbstractNode
{
if (value is AbstractNode)
return value as AbstractNode;
if (value is SFloat)
return (value as SFloat)._node;
if (value is uint || value is int || value is Number)
return new Constant(new <Number>[Number(value)]);
if (value is Matrix4x4)
return new Constant(Matrix4x4(value).getRawData(null, 0, false));
throw new Error('This type cannot be casted to a shader value.');
}
}
}
|
set SFloat.getPropertyWriteComponentMask() to be private
|
set SFloat.getPropertyWriteComponentMask() to be private
|
ActionScript
|
mit
|
aerys/minko-as3
|
f30345e7109aa52f9d97eae757ce0ff298fddf03
|
src/aerys/minko/type/animation/Animation.as
|
src/aerys/minko/type/animation/Animation.as
|
package aerys.minko.type.animation
{
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.node.ITransformable;
import aerys.minko.scene.node.group.Group;
import aerys.minko.type.animation.timeline.ITimeline;
import flash.utils.getTimer;
public class Animation
{
private var _id : String;
private var _beginTime : uint;
private var _lastTime : uint;
private var _playingOn : IScene;
private var _timelines : Vector.<ITimeline>;
private var _duration : uint;
public function get id() : String { return _id; }
public function Animation(id : String,
timelines : Vector.<ITimeline>)
{
_id = id;
_timelines = timelines;
_lastTime = 0;
_duration = 0;
for each (var timeline : ITimeline in timelines)
if (_duration < timeline.duration)
_duration = timeline.duration;
}
public function tick() : void
{
var time : uint = (getTimer() - _beginTime) % _duration;
transformNodes(time);
}
public function step(deltaTime : uint = 80) : void
{
var time : uint = (_lastTime + deltaTime) % _duration;
transformNodes(time);
}
public function stepReverse(deltaTime : uint = 80) : void
{
var time : int = (_lastTime - deltaTime) % _duration;
if (time < 0)
time = time + _duration;
transformNodes(time);
}
private function transformNodes(time : uint) : void
{
_lastTime = time;
var timelinesCount : uint = _timelines.length;
for (var i : uint = 0; i < timelinesCount; ++i)
{
var timeline : ITimeline = _timelines[i];
var timelineTarget : String = timeline.target;
var target : ITransformable;
if (_playingOn.name == timelineTarget)
target = ITransformable(_playingOn);
else if (_playingOn is Group)
target = ITransformable(Group(_playingOn).getDescendantByName(timelineTarget));
if (!target)
continue;
timeline.updateAt(time, target);
}
}
public function playOn(node : IScene) : void
{
_beginTime = getTimer();
_playingOn = node;
_lastTime = 0;
}
public function stop() : void
{
_playingOn = null;
}
}
}
|
package aerys.minko.type.animation
{
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.node.ITransformable;
import aerys.minko.scene.node.group.Group;
import aerys.minko.type.animation.timeline.ITimeline;
import flash.utils.getTimer;
public class Animation
{
private var _id : String;
private var _beginTime : uint;
private var _lastTime : uint;
private var _playingOn : IScene;
private var _timelines : Vector.<ITimeline>;
private var _duration : uint;
public function get id() : String { return _id; }
public function Animation(id : String,
timelines : Vector.<ITimeline>)
{
_id = id;
_timelines = timelines;
_lastTime = 0;
_duration = 0;
for each (var timeline : ITimeline in timelines)
if (_duration < timeline.duration)
_duration = timeline.duration;
}
public function tick() : void
{
var time : uint = (getTimer() - _beginTime) % _duration;
transformNodes(time);
}
public function step(deltaTime : int = 80) : void
{
var time : int;
if (deltaTime > 0)
{
time = (_lastTime + deltaTime) % _duration;
}
else
{
time = (_lastTime + deltaTime) % _duration;
if (time < 0)
time = time + _duration;
}
transformNodes(time);
}
private function transformNodes(time : uint) : void
{
_lastTime = time;
var timelinesCount : uint = _timelines.length;
for (var i : uint = 0; i < timelinesCount; ++i)
{
var timeline : ITimeline = _timelines[i];
var timelineTarget : String = timeline.target;
var target : ITransformable;
if (_playingOn.name == timelineTarget)
target = ITransformable(_playingOn);
else if (_playingOn is Group)
target = ITransformable(Group(_playingOn).getDescendantByName(timelineTarget));
if (!target)
continue;
timeline.updateAt(time, target);
}
}
public function playOn(node : IScene) : void
{
_beginTime = getTimer();
_playingOn = node;
_lastTime = 0;
}
public function stop() : void
{
_playingOn = null;
}
}
}
|
Delete Animation::stepReverse method
|
Delete Animation::stepReverse method
|
ActionScript
|
mit
|
aerys/minko-as3
|
664b458430810ff0942b7c59d5aa25b4d3360b20
|
src/aerys/minko/scene/SceneIterator.as
|
src/aerys/minko/scene/SceneIterator.as
|
package aerys.minko.scene
{
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.binding.DataBindings;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.describeType;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
public dynamic class SceneIterator extends Proxy
{
private static const TYPE_CACHE : Dictionary = new Dictionary(true);
private static const OPERATORS : Vector.<String> = new <String>[
'//', '/', '[', ']', '..', '.', '~=', '?=', '=', '@', '*', '(', ')',
'>=', '>', '<=', '<', '==', '='
];
private static const REGEX_TRIM : RegExp = /^\s+|\s+$/;
private var _path : String = null;
private var _selection : Vector.<ISceneNode> = null;
private var _modifier : String = null;
public function get length() : uint
{
return _selection.length;
}
public function SceneIterator(path : String,
selection : Vector.<ISceneNode>,
modifier : String = "")
{
super();
_modifier = modifier;
initialize(path, selection);
}
public function toString() : String
{
return _selection.toString();
}
// override flash_proxy function setProperty(name : *, value : *):void
// {
// var propertyName : String = name;
//
// for each (var node : ISceneNode in _selection)
// getValueObject(node, _modifier)[propertyName] = value;
// }
override flash_proxy function getProperty(name : *) : *
{
var index : int = parseInt(name);
if (index == name)
return index < _selection.length ? _selection[index] : null;
else
{
throw new Error(
'Unable to get a property on a set of objects. '
+ 'You must use the [] operator to fetch one of the objects.'
);
}
}
override flash_proxy function nextNameIndex(index : int) : int
{
return index < _selection.length ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
return _selection[int(index - 1)];
}
// override flash_proxy function callProperty(name:*, ...parameters):*
// {
// var methodName : String = name;
//
// for each (var node : ISceneNode in _selection)
// {
// var method : Function = getValueObject(node, _modifier)[methodName];
//
// method.apply(null, parameters);
// }
//
// return this;
// }
private function initialize(path : String, selection : Vector.<ISceneNode>) : void
{
_path = path;
// update root
var token : String = getToken();
_selection = selection.slice();
if (token == "/")
{
selectRoots();
nextToken(token);
}
// parse
while ((token = getToken()) != null)
{
switch (token)
{
case '//' :
nextToken(token);
selectDescendants();
break ;
case '/' :
nextToken(token);
selectChildren();
break ;
default :
nextToken(token);
parseNodeType(token);
break ;
}
}
}
private function getToken(doNext : Boolean = false) : String
{
var token : String = null;
if (!_path)
return null;
_path = _path.replace(/^\s+/, '');
var nextOpIndex : int = int.MAX_VALUE;
for each (var op : String in OPERATORS)
{
var opIndex : int = _path.indexOf(op);
if (opIndex > 0 && opIndex < nextOpIndex)
nextOpIndex = opIndex;
if (opIndex == 0)
{
token = op;
break ;
}
}
if (!token)
token = _path.substring(0, nextOpIndex);
if (doNext)
nextToken(token);
return token;
}
private function getValueToken() : Object
{
var value : Object = null;
_path = _path.replace(/^\s+/, '');
if (_path.charAt(0) == "'")
{
var endOfStringIndex : int = _path.indexOf("'", 1);
if (endOfStringIndex < 0)
throw new Error("Unterminated string expression.");
var stringValue : String = _path.substring(1, endOfStringIndex);
_path = _path.substring(endOfStringIndex + 1);
value = stringValue;
}
else
{
var token : String = getToken(true);
if (token == 'true')
value = true;
else if (token == 'false')
value = false;
else if (token.indexOf('0x') == 0)
value = parseInt(token, 16);
}
return value;
}
private function nextToken(token : String) : void
{
_path = _path.substring(_path.indexOf(token) + token.length);
}
private function selectChildren(typeName : String = null) : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
if (typeName != null)
typeName = typeName.toLowerCase();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node is Group)
{
var group : Group = node as Group;
var numChildren : uint = group.numChildren;
for (var i : uint = 0; i < numChildren; ++i)
{
var child : ISceneNode = group.getChildAt(i);
var className : String = getQualifiedClassName(child)
var childType : String = className.substr(className.lastIndexOf(':') + 1);
if (typeName == null || childType.toLowerCase() == typeName)
_selection.push(child);
}
}
}
}
private function selectRoots() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
if (_selection.indexOf(node.root) < 0)
_selection.push(node);
}
private function selectDescendants() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
_selection.push(node);
if (node is Group)
(node as Group).getDescendantsByType(ISceneNode, _selection);
}
}
private function selectParents() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node.parent)
_selection.push(node.parent);
else
_selection.push(node);
}
}
private function parseNodeType(nodeType : String) : void
{
if (nodeType == '.')
{
// nothing
}
if (nodeType == '..')
selectParents();
else if (nodeType == '*')
selectChildren();
else
selectChildren(nodeType);
// apply predicates
var token : String = getToken();
while (token == '[')
{
nextToken(token);
parsePredicate();
token = getToken();
}
}
private function parsePredicate() : void
{
var propertyName : String = getToken(true);
var isBinding : Boolean = propertyName == '@';
if (isBinding)
propertyName = getToken(true);
var index : int = parseInt(propertyName);
if (propertyName == 'hasController')
filterOnController();
else if (propertyName == 'hasProperty')
filterOnProperty();
else if (propertyName == 'position')
filterOnPosition();
else if (propertyName == 'last')
filterLast();
else if (propertyName == 'first')
filterFirst();
else if (index.toString() == propertyName)
{
if (index < _selection.length)
{
_selection[0] = _selection[index];
_selection.length = 1;
}
else
_selection.length = 0;
}
else
filterOnValue(propertyName, isBinding);
checkNextToken(']');
}
private function filterLast() : void
{
checkNextToken('(');
checkNextToken(')');
_selection[0] = _selection[uint(_selection.length - 1)];
_selection.length = 1;
}
private function filterFirst() : void
{
checkNextToken('(');
checkNextToken(')');
_selection.length = 1;
}
private function filterOnValue(propertyName : String, isBinding : Boolean = false) : void
{
var operator : String = getToken(true);
var chunks : Array = [propertyName];
while (operator == '.')
{
chunks.push(getToken(true));
operator = getToken(true);
}
var value : Object = getValueToken();
var numNodes : uint = _selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = _selection[i];
var nodeValue : Object = null;
if (isBinding && (node['bindings'] is DataBindings))
nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName);
else
{
try
{
nodeValue = getValueObject(node, chunks);
if (!compare(operator, nodeValue, value))
removeFromSelection(i);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
}
private function compare(operator : String, a : Object, b : Object) : Boolean
{
switch (operator)
{
case '>' :
return a > b;
case '>=' :
return a >= b;
case '<' :
return a >= b;
case '<=' :
return a <= b;
case '=' :
case '==' :
return a == b;
case '~=' :
var matches : Array = String(a).match(b);
return matches && matches.length != 0;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
private function filterOnController() : Object
{
checkNextToken('(');
var controllerName : String = getToken(true);
checkNextToken(')');
var numNodes : uint = _selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = _selection[i];
var numControllers : uint = node.numControllers;
var keepSceneNode : Boolean = false;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
{
var controllerType : String = getQualifiedClassName(node.getController(controllerId));
controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1);
if (controllerType == controllerName)
{
keepSceneNode = true;
break;
}
}
if (!keepSceneNode)
removeFromSelection(i);
}
return null;
}
private function filterOnPosition() : void
{
checkNextToken('(');
checkNextToken(')');
var operator : String = getToken(true);
var value : uint = uint(parseInt(getToken(true)));
switch (operator)
{
case '>':
++value;
case '>=':
_selection = _selection.slice(value);
break;
case '<':
--value;
case '<=':
_selection = _selection.slice(0, value);
break;
case '=':
case '==':
_selection[0] = _selection[value];
_selection.length = 1;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
private function filterOnProperty() : void
{
checkNextToken('(');
var chunks : Array = [getToken(true)];
var operator : String = getToken(true);
while (operator == '.')
{
chunks.push(operator);
operator = getToken(true);
}
if (operator != ')')
throwParseError(')', operator);
var numNodes : uint = _selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
try
{
getValueObject(_selection[i], chunks);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
private function getValueObject(source : Object, chunks : Array) : Object
{
if (chunks)
for each (var chunk : String in chunks)
source = source[chunk];
return source;
}
private function removeFromSelection(index : uint) : void
{
var numNodes : uint = _selection.length - 1;
_selection[index] = _selection[numNodes];
_selection.length = numNodes;
}
private function checkNextToken(expected : String) : void
{
var token : String = getToken(true);
if (token != expected)
throwParseError(expected, token);
}
private function throwParseError(expected : String,
got : String) : void
{
throw new Error(
'Parse error: expected \'' + expected + '\', got \'' + got + '\'.'
);
}
}
}
|
package aerys.minko.scene
{
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.type.binding.DataBindings;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.describeType;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
public dynamic class SceneIterator extends Proxy
{
private static const TYPE_CACHE : Dictionary = new Dictionary(true);
private static const OPERATORS : Vector.<String> = new <String>[
'//', '/', '[', ']', '..', '.', '~=', '?=', '=', '@', '*', '(', ')',
'>=', '>', '<=', '<', '==', '='
];
private static const REGEX_TRIM : RegExp = /^\s+|\s+$/;
private var _path : String = null;
private var _selection : Vector.<ISceneNode> = null;
private var _modifier : String = null;
public function get length() : uint
{
return _selection.length;
}
public function SceneIterator(path : String,
selection : Vector.<ISceneNode>,
modifier : String = "")
{
super();
_modifier = modifier;
initialize(path, selection);
}
public function toString() : String
{
return _selection.toString();
}
// override flash_proxy function setProperty(name : *, value : *):void
// {
// var propertyName : String = name;
//
// for each (var node : ISceneNode in _selection)
// getValueObject(node, _modifier)[propertyName] = value;
// }
override flash_proxy function getProperty(name : *) : *
{
var index : int = parseInt(name);
if (index == name)
return index < _selection.length ? _selection[index] : null;
else
{
throw new Error(
'Unable to get a property on a set of objects. '
+ 'You must use the [] operator to fetch one of the objects.'
);
}
}
override flash_proxy function nextNameIndex(index : int) : int
{
return index < _selection.length ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
return _selection[int(index - 1)];
}
// override flash_proxy function callProperty(name:*, ...parameters):*
// {
// var methodName : String = name;
//
// for each (var node : ISceneNode in _selection)
// {
// var method : Function = getValueObject(node, _modifier)[methodName];
//
// method.apply(null, parameters);
// }
//
// return this;
// }
private function initialize(path : String, selection : Vector.<ISceneNode>) : void
{
_path = path;
// update root
var token : String = getToken();
_selection = selection.slice();
if (token == "/")
{
selectRoots();
nextToken(token);
}
// parse
while ((token = getToken()) != null)
{
switch (token)
{
case '//' :
nextToken(token);
selectDescendants();
break ;
case '/' :
nextToken(token);
selectChildren();
break ;
default :
nextToken(token);
parseNodeType(token);
break ;
}
}
}
private function getToken(doNext : Boolean = false) : String
{
var token : String = null;
if (!_path)
return null;
_path = _path.replace(/^\s+/, '');
var nextOpIndex : int = int.MAX_VALUE;
for each (var op : String in OPERATORS)
{
var opIndex : int = _path.indexOf(op);
if (opIndex > 0 && opIndex < nextOpIndex)
nextOpIndex = opIndex;
if (opIndex == 0)
{
token = op;
break ;
}
}
if (!token)
token = _path.substring(0, nextOpIndex);
if (doNext)
nextToken(token);
return token;
}
private function getValueToken() : Object
{
var value : Object = null;
_path = _path.replace(/^\s+/, '');
if (_path.charAt(0) == "'")
{
var endOfStringIndex : int = _path.indexOf("'", 1);
if (endOfStringIndex < 0)
throw new Error("Unterminated string expression.");
var stringValue : String = _path.substring(1, endOfStringIndex);
_path = _path.substring(endOfStringIndex + 1);
value = stringValue;
}
else
{
var token : String = getToken(true);
if (token == 'true')
value = true;
else if (token == 'false')
value = false;
else if (token.indexOf('0x') == 0)
value = parseInt(token, 16);
}
return value;
}
private function nextToken(token : String) : void
{
_path = _path.substring(_path.indexOf(token) + token.length);
}
private function selectChildren(typeName : String = null) : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
if (typeName != null)
typeName = typeName.toLowerCase();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node is Group)
{
var group : Group = node as Group;
var numChildren : uint = group.numChildren;
for (var i : uint = 0; i < numChildren; ++i)
{
var child : ISceneNode = group.getChildAt(i);
var className : String = getQualifiedClassName(child)
var childType : String = className.substr(className.lastIndexOf(':') + 1);
if (typeName == null || childType.toLowerCase() == typeName)
_selection.push(child);
}
}
}
}
private function selectRoots() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
if (_selection.indexOf(node.root) < 0)
_selection.push(node);
}
private function selectDescendants() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
_selection.push(node);
if (node is Group)
(node as Group).getDescendantsByType(ISceneNode, _selection);
}
}
private function selectParents() : void
{
var selection : Vector.<ISceneNode> = _selection.slice();
_selection.length = 0;
for each (var node : ISceneNode in selection)
{
if (node.parent)
_selection.push(node.parent);
else
_selection.push(node);
}
}
private function parseNodeType(nodeType : String) : void
{
if (nodeType == '.')
{
// nothing
}
if (nodeType == '..')
selectParents();
else if (nodeType == '*')
selectChildren();
else
selectChildren(nodeType);
// apply predicates
var token : String = getToken();
while (token == '[')
{
nextToken(token);
parsePredicate();
token = getToken();
}
}
private function parsePredicate() : void
{
var propertyName : String = getToken(true);
var isBinding : Boolean = propertyName == '@';
if (isBinding)
propertyName = getToken(true);
var index : int = parseInt(propertyName);
if (propertyName == 'hasController')
filterOnController();
else if (propertyName == 'hasProperty')
filterOnProperty();
else if (propertyName == 'position')
filterOnPosition();
else if (propertyName == 'last')
filterLast();
else if (propertyName == 'first')
filterFirst();
else if (index.toString() == propertyName)
{
if (index < _selection.length)
{
_selection[0] = _selection[index];
_selection.length = 1;
}
else
_selection.length = 0;
}
else
filterOnValue(propertyName, isBinding);
checkNextToken(']');
}
private function filterLast() : void
{
checkNextToken('(');
checkNextToken(')');
if (_selection.length)
{
_selection[0] = _selection[uint(_selection.length - 1)];
_selection.length = 1;
}
}
private function filterFirst() : void
{
checkNextToken('(');
checkNextToken(')');
_selection.length = 1;
}
private function filterOnValue(propertyName : String, isBinding : Boolean = false) : void
{
var operator : String = getToken(true);
var chunks : Array = [propertyName];
while (operator == '.')
{
chunks.push(getToken(true));
operator = getToken(true);
}
var value : Object = getValueToken();
var numNodes : uint = _selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = _selection[i];
var nodeValue : Object = null;
if (isBinding && (node['bindings'] is DataBindings))
nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName);
else
{
try
{
nodeValue = getValueObject(node, chunks);
if (!compare(operator, nodeValue, value))
removeFromSelection(i);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
}
private function compare(operator : String, a : Object, b : Object) : Boolean
{
switch (operator)
{
case '>' :
return a > b;
case '>=' :
return a >= b;
case '<' :
return a >= b;
case '<=' :
return a <= b;
case '=' :
case '==' :
return a == b;
case '~=' :
var matches : Array = String(a).match(b);
return matches && matches.length != 0;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
private function filterOnController() : Object
{
checkNextToken('(');
var controllerName : String = getToken(true);
checkNextToken(')');
var numNodes : uint = _selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
var node : ISceneNode = _selection[i];
var numControllers : uint = node.numControllers;
var keepSceneNode : Boolean = false;
for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId)
{
var controllerType : String = getQualifiedClassName(node.getController(controllerId));
controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1);
if (controllerType == controllerName)
{
keepSceneNode = true;
break;
}
}
if (!keepSceneNode)
removeFromSelection(i);
}
return null;
}
private function filterOnPosition() : void
{
checkNextToken('(');
checkNextToken(')');
var operator : String = getToken(true);
var value : uint = uint(parseInt(getToken(true)));
switch (operator)
{
case '>':
++value;
case '>=':
_selection = _selection.slice(value);
break;
case '<':
--value;
case '<=':
_selection = _selection.slice(0, value);
break;
case '=':
case '==':
_selection[0] = _selection[value];
_selection.length = 1;
default:
throw new Error('Unknown comparison operator \'' + operator + '\'');
}
}
private function filterOnProperty() : void
{
checkNextToken('(');
var chunks : Array = [getToken(true)];
var operator : String = getToken(true);
while (operator == '.')
{
chunks.push(operator);
operator = getToken(true);
}
if (operator != ')')
throwParseError(')', operator);
var numNodes : uint = _selection.length;
for (var i : int = numNodes - 1; i >= 0; --i)
{
try
{
getValueObject(_selection[i], chunks);
}
catch (e : Error)
{
removeFromSelection(i);
}
}
}
private function getValueObject(source : Object, chunks : Array) : Object
{
if (chunks)
for each (var chunk : String in chunks)
source = source[chunk];
return source;
}
private function removeFromSelection(index : uint) : void
{
var numNodes : uint = _selection.length - 1;
_selection[index] = _selection[numNodes];
_selection.length = numNodes;
}
private function checkNextToken(expected : String) : void
{
var token : String = getToken(true);
if (token != expected)
throwParseError(expected, token);
}
private function throwParseError(expected : String,
got : String) : void
{
throw new Error(
'Parse error: expected \'' + expected + '\', got \'' + got + '\'.'
);
}
}
}
|
fix 'last()' xpath special function 'out of bounds' exception when the selection set is empty
|
fix 'last()' xpath special function 'out of bounds' exception when the selection set is empty
|
ActionScript
|
mit
|
aerys/minko-as3
|
bb6bef718eb7bb9dbb2daa471fc860067bdf0bfc
|
src/org/mangui/hls/demux/Nalu.as
|
src/org/mangui/hls/demux/Nalu.as
|
/* 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 org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** H264 NAL unit names. **/
private static const NAMES : Array = ['Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
/* 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 org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
/** H264 NAL unit names. **/
const NAMES : Array = ['Unspecified',// 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
reduce release swf size
|
reduce release swf size
|
ActionScript
|
mpl-2.0
|
JulianPena/flashls,mangui/flashls,vidible/vdb-flashls,Boxie5/flashls,Corey600/flashls,loungelogic/flashls,tedconf/flashls,JulianPena/flashls,dighan/flashls,NicolasSiver/flashls,loungelogic/flashls,hola/flashls,codex-corp/flashls,tedconf/flashls,NicolasSiver/flashls,fixedmachine/flashls,clappr/flashls,fixedmachine/flashls,mangui/flashls,Corey600/flashls,neilrackett/flashls,jlacivita/flashls,jlacivita/flashls,codex-corp/flashls,dighan/flashls,thdtjsdn/flashls,thdtjsdn/flashls,vidible/vdb-flashls,hola/flashls,neilrackett/flashls,clappr/flashls,Boxie5/flashls
|
047d9f1e6b6bb2f547753a11a462faf1391c7956
|
src/org/mangui/osmf/plugins/HLSNetLoader.as
|
src/org/mangui/osmf/plugins/HLSNetLoader.as
|
package org.mangui.osmf.plugins
{
import flash.net.NetStream;
import flash.net.NetConnection;
import org.osmf.net.NetLoader;
import org.osmf.media.URLResource;
import org.mangui.HLS.HLS;
public class HLSNetLoader extends NetLoader
{
private var _hls:HLS;
public function HLSNetLoader(hls:HLS)
{
_hls = hls;
super();
}
override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream
{
return _hls.stream;
}
}
}
|
package org.mangui.osmf.plugins
{
import flash.net.NetStream;
import flash.net.NetConnection;
import org.osmf.net.NetLoader;
import org.osmf.media.URLResource;
import org.mangui.HLS.HLS;
public class HLSNetLoader extends NetLoader
{
private var _hls:HLS;
private var _connection:NetConnection;
private var _resource:URLResource;
public function HLSNetLoader(hls:HLS)
{
_hls = hls;
super();
}
override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream
{
_connection = connection;
_resource = resource;
return _hls.stream;
}
}
}
|
remove warnings
|
remove warnings
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
61191face972cd9876a78209b2b865afd95304ef
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/SolidBackgroundBead.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/SolidBackgroundBead.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads
{
import flash.display.Graphics;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The SolidBackgroundBead class draws a solid filled background.
* The color and opacity can be specified in CSS.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SolidBackgroundBead implements IBead, IBackgroundBead, IGraphicsDrawing
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SolidBackgroundBead()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("heightChanged", changeHandler);
IEventDispatcher(value).addEventListener("widthChanged", changeHandler);
var bgColor:Object = ValuesManager.valuesImpl.getValue(value, "background-color");
if( bgColor != null ) {
backgroundColor = uint(bgColor);
}
var bgAlpha:Object = ValuesManager.valuesImpl.getValue(value, "opacity");
if( bgAlpha != null ) {
opacity = Number(bgAlpha);
}
}
private var _backgroundColor:uint;
/**
* The background color
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get backgroundColor():uint
{
return _backgroundColor;
}
/**
* @private
*/
public function set backgroundColor(value:uint):void
{
_backgroundColor = value;
if (_strand)
changeHandler(null);
}
private var _opacity:Number = 1.0;
/**
* The opacity (alpha).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get opacity():Number
{
return _opacity;
}
/**
* @private
*/
public function set opacity(value:Number):void
{
_opacity = value;
if( _strand )
changeHandler(null);
}
private function changeHandler(event:Event):void
{
var host:UIBase = UIBase(_strand);
var g:Graphics = host.graphics;
var w:Number = host.width;
var h:Number = host.height;
var gd:IGraphicsDrawing = _strand.getBeadByType(IGraphicsDrawing) as IGraphicsDrawing;
if( this == gd ) g.clear();
g.beginFill(backgroundColor,opacity);
g.drawRect(0, 0, w, h);
g.endFill();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.html.beads
{
import flash.display.Sprite;
import flash.display.Graphics;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The SolidBackgroundBead class draws a solid filled background.
* The color and opacity can be specified in CSS.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class SolidBackgroundBead implements IBead, IBackgroundBead, IGraphicsDrawing
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function SolidBackgroundBead()
{
}
private var _strand:IStrand;
private var host:IUIBase;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
if (value is IUIBase)
host = IUIBase(value);
else if (value is IBeadView)
host = IUIBase(IBeadView(value).host);
IEventDispatcher(host).addEventListener("heightChanged", changeHandler);
IEventDispatcher(host).addEventListener("widthChanged", changeHandler);
var bgColor:Object = ValuesManager.valuesImpl.getValue(host, "background-color");
if( bgColor != null ) {
backgroundColor = ValuesManager.valuesImpl.convertColor(bgColor);
}
var bgAlpha:Object = ValuesManager.valuesImpl.getValue(host, "opacity");
if( bgAlpha != null ) {
opacity = Number(bgAlpha);
}
}
private var _backgroundColor:uint;
/**
* The background color
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get backgroundColor():uint
{
return _backgroundColor;
}
/**
* @private
*/
public function set backgroundColor(value:uint):void
{
_backgroundColor = value;
if (_strand)
changeHandler(null);
}
private var _opacity:Number = 1.0;
/**
* The opacity (alpha).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get opacity():Number
{
return _opacity;
}
/**
* @private
*/
public function set opacity(value:Number):void
{
_opacity = value;
if( _strand )
changeHandler(null);
}
private function changeHandler(event:Event):void
{
var g:Graphics = Sprite(host).graphics;
var w:Number = host.width;
var h:Number = host.height;
var gd:IGraphicsDrawing = _strand.getBeadByType(IGraphicsDrawing) as IGraphicsDrawing;
if( this == gd ) g.clear();
g.beginFill(backgroundColor,opacity);
g.drawRect(0, 0, w, h);
g.endFill();
}
}
}
|
allow as bead of view as well as component
|
allow as bead of view as well as component
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
4174e313f11f43e2cfc746d6408a57c43212afcf
|
src/aerys/minko/render/Viewport.as
|
src/aerys/minko/render/Viewport.as
|
package aerys.minko.render
{
import aerys.minko.Minko;
import aerys.minko.ns.minko;
import aerys.minko.render.effect.IEffect;
import aerys.minko.render.effect.basic.BasicEffect;
import aerys.minko.render.renderer.DefaultRenderer;
import aerys.minko.render.renderer.IRenderer;
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.visitor.ISceneVisitor;
import aerys.minko.scene.visitor.data.CameraData;
import aerys.minko.scene.visitor.data.LocalData;
import aerys.minko.scene.visitor.data.RenderingData;
import aerys.minko.scene.visitor.data.ViewportData;
import aerys.minko.scene.visitor.rendering.RenderingVisitor;
import aerys.minko.scene.visitor.rendering.WorldDataVisitor;
import aerys.minko.type.Factory;
import aerys.minko.type.IVersionnable;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display3D.Context3DRenderMode;
import flash.events.Event;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.system.Capabilities;
import flash.system.System;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* The viewport is the the display area used to render a 3D scene.
* It can be used to render any IScene3D object.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite implements IVersionnable
{
use namespace minko;
private static const ZERO2 : Point = new Point();
private var _version : uint = 0;
private var _width : Number = 0.;
private var _height : Number = 0.;
private var _autoResize : Boolean = false;
private var _antiAliasing : int = 0;
private var _visitors : Vector.<ISceneVisitor> = null;
private var _time : int = 0;
private var _sceneSize : uint = 0;
private var _drawTime : int = 0;
private var _stage3d : Stage3D = null;
private var _rendererClass : Class = null;
private var _renderer : IRenderer = null;
private var _defaultEffect : IEffect = new BasicEffect();
private var _backgroundColor : int = 0;
private var _viewportData : ViewportData = null;
public function get version() : uint
{
return _version;
}
override public function set x(value : Number) : void
{
super.x = value;
updateRectangle();
}
override public function set y(value : Number) : void
{
super.y = value;
updateRectangle();
}
/**
* Indicates the width of the viewport.
* @return The width of the viewport.
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
if (value != _width)
{
_width = value;
++_version;
resetStage3D();
}
}
public function get sceneSize() : uint
{
return _sceneSize;
}
/**
* Indicates the height of the viewport.
* @return The height of the viewport.
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
if (value != _height)
{
_height = value;
++_version;
resetStage3D();
}
}
/**
* The anti-aliasing value used to render the scene.
*
* @return
*
*/
public function get antiAliasing() : int
{
return _antiAliasing;
}
public function set antiAliasing(value : int) : void
{
if (value != _antiAliasing)
{
_antiAliasing = value;
++_version;
resetStage3D();
}
}
public function get defaultEffect() : IEffect
{
return _defaultEffect;
}
public function set defaultEffect(value : IEffect) : void
{
_defaultEffect = value;
}
/**
* The amount of triangle rendered durung the last call to the
* "render" method. Sometimes, the number of triangles is higher
* than the total amount of triangles in the scene because some
* triangles are renderer multiple times (multipass).
*
* @return
*
*/
public function get numTriangles() : uint
{
return _renderer ? _renderer.numTriangles : 0;
}
/**
* The time spent during the last call to the "render" method.
*
* This time includes:
* <ul>
* <li>updating the scene graph</li>
* <li>rendering the scene graph</li>
* <li>performing draw calls to the internal 3D APIs</li>
* </ul>
*
* @return
*
*/
public function get renderingTime() : uint
{
return _time;
}
public function get drawingTime() : int
{
return _drawTime;
}
public function get renderMode() : String
{
return _stage3d && _stage3d.context3D ? _stage3d.context3D.driverInfo : null;
}
public function get backgroundColor() : int
{
return _backgroundColor;
}
public function set backgroundColor(value : int) : void
{
_backgroundColor = value;
}
public function get visitors() : Vector.<ISceneVisitor>
{
return _visitors;
}
/**
* Creates a new Viewport object.
*
* @param width The width of the viewport.
* @param height The height of the viewport.
*/
public function Viewport(width : uint = 0,
height : uint = 0,
antiAliasing : int = 0,
rendererType : Class = null)
{
this.width = width;
this.height = height;
_autoResize = _width == 0 || _height == 0;
_antiAliasing = antiAliasing;
_rendererClass = rendererType || DefaultRenderer;
_viewportData = new ViewportData(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
addEventListener(Event.ADDED, addedHandler);
}
private function addedToStageHandler(event : Event) : void
{
var stageId : int = 0;
_stage3d = stage.stage3Ds[stageId];
while (_stage3d.willTrigger(Event.CONTEXT3D_CREATE))
_stage3d = stage.stage3Ds[int(++stageId)];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, resetStage3D);
_stage3d.requestContext3D(Context3DRenderMode.AUTO);
if (_autoResize)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, stageResizeHandler);
width = stage.stageWidth;
height = stage.stageHeight;
}
showLogo();
}
private function removedFromStage(event : Event) : void
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, resetStage3D);
_stage3d.context3D.dispose();
_stage3d = null;
}
private function addedHandler(event : Event) : void
{
updateRectangle();
}
private function stageResizeHandler(event : Event) : void
{
var stage : Stage = event.target as Stage;
if (stage.stageWidth)
width = stage.stageWidth;
if (stage.stageHeight)
height = stage.stageHeight;
resetStage3D();
showLogo();
}
private function resetStage3D(event : Event = null) : void
{
if (_stage3d && _stage3d.context3D)
{
updateRectangle();
_stage3d.context3D.configureBackBuffer(
Math.min(2048, _width),
Math.min(2048, _height),
_antiAliasing,
true
);
_renderer = new _rendererClass(this, _stage3d.context3D);
_visitors = Vector.<ISceneVisitor>([
new WorldDataVisitor(),
new RenderingVisitor()
]);
dispatchEvent(new Event(Event.INIT));
}
}
private function updateRectangle() : void
{
if (_stage3d)
{
var origin : Point = localToGlobal(ZERO2);
_stage3d.viewPort = new Rectangle(origin.x, origin.y, _width, _height);
}
}
/**
* Render the specified scene.
* @param scene
*/
public function render(scene : IScene) : void
{
if (_visitors && _visitors.length != 0)
{
var time : Number = getTimer();
// create the data sources the visitors are going to write and read from during render.
var localData : LocalData = new LocalData();
var worldData : Dictionary = new Dictionary();
var renderingData : RenderingData = new RenderingData();
// push viewport related data into the data sources
worldData[ViewportData] = _viewportData;
renderingData.effect = defaultEffect;
// execute all visitors
for each (var visitor : ISceneVisitor in _visitors)
visitor.processSceneGraph(scene, localData, worldData, renderingData, _renderer);
_sceneSize = visitors[0].numNodes;
_time = getTimer() - time;
_drawTime = _renderer.drawingTime;
}
else
{
_time = 0;
_drawTime = 0;
}
Factory.sweep();
showLogo();
}
public function showLogo() : void
{
var logo : Sprite = Minko.logo;
addChild(logo);
logo.x = 5;
logo.y = _height - logo.height - 5;
}
}
}
|
package aerys.minko.render
{
import aerys.minko.Minko;
import aerys.minko.ns.minko;
import aerys.minko.render.effect.IEffect;
import aerys.minko.render.effect.basic.BasicEffect;
import aerys.minko.render.renderer.DefaultRenderer;
import aerys.minko.render.renderer.IRenderer;
import aerys.minko.scene.node.IScene;
import aerys.minko.scene.visitor.ISceneVisitor;
import aerys.minko.scene.visitor.data.CameraData;
import aerys.minko.scene.visitor.data.LocalData;
import aerys.minko.scene.visitor.data.RenderingData;
import aerys.minko.scene.visitor.data.ViewportData;
import aerys.minko.scene.visitor.rendering.RenderingVisitor;
import aerys.minko.scene.visitor.rendering.WorldDataVisitor;
import aerys.minko.type.Factory;
import aerys.minko.type.IVersionnable;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display3D.Context3DRenderMode;
import flash.events.Event;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.system.Capabilities;
import flash.system.System;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* The viewport is the the display area used to render a 3D scene.
* It can be used to render any IScene3D object.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite implements IVersionnable
{
use namespace minko;
private static const ZERO2 : Point = new Point();
private var _version : uint = 0;
private var _width : Number = 0.;
private var _height : Number = 0.;
private var _autoResize : Boolean = false;
private var _antiAliasing : int = 0;
private var _visitors : Vector.<ISceneVisitor> = null;
private var _time : int = 0;
private var _sceneSize : uint = 0;
private var _drawTime : int = 0;
private var _stage3d : Stage3D = null;
private var _rendererClass : Class = null;
private var _renderer : IRenderer = null;
private var _defaultEffect : IEffect = new BasicEffect();
private var _backgroundColor : int = 0;
private var _viewportData : ViewportData = null;
public function get version() : uint
{
return _version;
}
override public function set x(value : Number) : void
{
super.x = value;
updateRectangle();
}
override public function set y(value : Number) : void
{
super.y = value;
updateRectangle();
}
/**
* Indicates the width of the viewport.
* @return The width of the viewport.
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
if (value != _width)
{
_width = value;
++_version;
resetStage3D();
}
}
public function get sceneSize() : uint
{
return _sceneSize;
}
/**
* Indicates the height of the viewport.
* @return The height of the viewport.
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
if (value != _height)
{
_height = value;
++_version;
resetStage3D();
}
}
/**
* The anti-aliasing value used to render the scene.
*
* @return
*
*/
public function get antiAliasing() : int
{
return _antiAliasing;
}
public function set antiAliasing(value : int) : void
{
if (value != _antiAliasing)
{
_antiAliasing = value;
++_version;
resetStage3D();
}
}
public function get defaultEffect() : IEffect
{
return _defaultEffect;
}
public function set defaultEffect(value : IEffect) : void
{
_defaultEffect = value;
}
/**
* The amount of triangle rendered durung the last call to the
* "render" method. Sometimes, the number of triangles is higher
* than the total amount of triangles in the scene because some
* triangles are renderer multiple times (multipass).
*
* @return
*
*/
public function get numTriangles() : uint
{
return _renderer ? _renderer.numTriangles : 0;
}
/**
* The time spent during the last call to the "render" method.
*
* This time includes:
* <ul>
* <li>updating the scene graph</li>
* <li>rendering the scene graph</li>
* <li>performing draw calls to the internal 3D APIs</li>
* </ul>
*
* @return
*
*/
public function get renderingTime() : uint
{
return _time;
}
public function get drawingTime() : int
{
return _drawTime;
}
public function get renderMode() : String
{
return _stage3d && _stage3d.context3D ? _stage3d.context3D.driverInfo : null;
}
public function get backgroundColor() : int
{
return _backgroundColor;
}
public function set backgroundColor(value : int) : void
{
_backgroundColor = value;
}
public function get visitors() : Vector.<ISceneVisitor>
{
return _visitors;
}
/**
* Creates a new Viewport object.
*
* @param width The width of the viewport.
* @param height The height of the viewport.
*/
public function Viewport(width : uint = 0,
height : uint = 0,
antiAliasing : int = 0,
rendererType : Class = null)
{
this.width = width;
this.height = height;
_autoResize = _width == 0 || _height == 0;
_antiAliasing = antiAliasing;
_rendererClass = rendererType || DefaultRenderer;
_viewportData = new ViewportData(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
addEventListener(Event.ADDED, addedHandler);
}
private function addedToStageHandler(event : Event) : void
{
var stageId : int = 0;
_stage3d = stage.stage3Ds[stageId];
while (_stage3d.willTrigger(Event.CONTEXT3D_CREATE))
_stage3d = stage.stage3Ds[int(++stageId)];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, resetStage3D);
_stage3d.requestContext3D(Context3DRenderMode.AUTO);
if (_autoResize)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, stageResizeHandler);
width = stage.stageWidth;
height = stage.stageHeight;
}
showLogo();
}
private function removedFromStage(event : Event) : void
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, resetStage3D);
_stage3d.context3D.dispose();
_stage3d = null;
}
private function addedHandler(event : Event) : void
{
updateRectangle();
}
private function stageResizeHandler(event : Event) : void
{
var stage : Stage = event.target as Stage;
if (stage.stageWidth)
width = stage.stageWidth;
if (stage.stageHeight)
height = stage.stageHeight;
resetStage3D();
showLogo();
}
private function resetStage3D(event : Event = null) : void
{
if (_stage3d && _stage3d.context3D)
{
updateRectangle();
_stage3d.context3D.configureBackBuffer(
Math.min(2048, _width),
Math.min(2048, _height),
_antiAliasing,
true
);
_renderer = new _rendererClass(this, _stage3d.context3D);
_visitors = Vector.<ISceneVisitor>([
new WorldDataVisitor(),
new RenderingVisitor()
]);
dispatchEvent(new Event(Event.INIT));
}
}
private function updateRectangle() : void
{
if (_stage3d)
{
var origin : Point = localToGlobal(ZERO2);
_stage3d.viewPort = new Rectangle(origin.x, origin.y, _width, _height);
}
}
/**
* Render the specified scene.
* @param scene
*/
public function render(scene : IScene) : void
{
showLogo();
if (_visitors && _visitors.length != 0)
{
var time : Number = getTimer();
// create the data sources the visitors are going to write and read from during render.
var localData : LocalData = new LocalData();
var worldData : Dictionary = new Dictionary();
var renderingData : RenderingData = new RenderingData();
// push viewport related data into the data sources
worldData[ViewportData] = _viewportData;
renderingData.effect = defaultEffect;
// execute all visitors
for each (var visitor : ISceneVisitor in _visitors)
visitor.processSceneGraph(scene, localData, worldData, renderingData, _renderer);
_sceneSize = visitors[0].numNodes;
_time = getTimer() - time;
_drawTime = _renderer.drawingTime;
}
else
{
_time = 0;
_drawTime = 0;
}
Factory.sweep();
}
public function showLogo() : void
{
var logo : Sprite = Minko.logo;
addChild(logo);
logo.x = 5;
logo.y = _height - logo.height - 5;
}
}
}
|
call showLogo() at the very begining of Viewport.render
|
call showLogo() at the very begining of Viewport.render
|
ActionScript
|
mit
|
aerys/minko-as3
|
7332ce81d2e17f64efe700e3db088bbb86ac1223
|
src/com/esri/viewer/utils/SymbolParser.as
|
src/com/esri/viewer/utils/SymbolParser.as
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 com.esri.viewer.utils
{
import com.esri.ags.symbols.PictureMarkerSymbol;
import com.esri.ags.symbols.SimpleFillSymbol;
import com.esri.ags.symbols.SimpleLineSymbol;
import com.esri.ags.symbols.SimpleMarkerSymbol;
import com.esri.ags.symbols.Symbol;
public class SymbolParser
{
public function parseSymbol(symbolXML:XML):Symbol
{
var symbol:Symbol;
if (symbolXML)
{
if (symbolXML.simplemarkersymbol[0])
{
symbol = parseSimpleMarkerSymbol(symbolXML.simplemarkersymbol[0]);
}
else if (symbolXML.picturemarkersymbol[0])
{
symbol = parsePictureMarkerSymbol(symbolXML.picturemarkersymbol[0]);
}
else if (symbolXML.simplelinesymbol[0])
{
symbol = parseSimpleLineSymbol(symbolXML.simplelinesymbol[0]);
}
else if (symbolXML.simplefillsymbol[0])
{
symbol = parseSimpleFillSymbol(symbolXML.simplefillsymbol[0]);
}
}
return symbol;
}
public function parseSimpleMarkerSymbol(smsXML:XML):SimpleMarkerSymbol
{
const simpleMarkerSymbol:SimpleMarkerSymbol = createDefaultPointSymbol();
const parsedColor:Number = parseInt(smsXML.@color[0]);
const parsedAlpha:Number = parseFloat(smsXML.@alpha[0]);
const parsedSize:Number = parseFloat(smsXML.@size[0]);
if (smsXML.@style[0])
{
simpleMarkerSymbol.style = smsXML.@style;
}
if (!isNaN(parsedAlpha))
{
simpleMarkerSymbol.alpha = parsedAlpha;
}
if (!isNaN(parsedColor))
{
simpleMarkerSymbol.color = parsedColor;
}
if (!isNaN(parsedSize))
{
simpleMarkerSymbol.size = parsedSize;
}
if (!simpleMarkerSymbol.outline)
{
simpleMarkerSymbol.outline = createDefaultOutlineSymbol();
}
const outlineSymbol:SimpleLineSymbol = simpleMarkerSymbol.outline;
const parsedOutlineColor:uint = parseInt(smsXML.outline.@color[0]);
const parsedOutlineWidth:Number = parseFloat(smsXML.outline.@width[0]);
if (smsXML.outline.@style[0])
{
outlineSymbol.style = smsXML.outline.@style
}
if (!isNaN(parsedOutlineColor))
{
outlineSymbol.color = parsedOutlineColor;
}
if (!isNaN(parsedOutlineWidth))
{
outlineSymbol.width = parsedOutlineWidth;
}
return simpleMarkerSymbol;
}
private var _defaultPointSymbol:SimpleMarkerSymbol;
public function get defaultPointSymbol():SimpleMarkerSymbol
{
return _defaultPointSymbol ||= new SimpleMarkerSymbol();
}
public function set defaultPointSymbol(value:SimpleMarkerSymbol):void
{
_defaultPointSymbol = value;
}
protected function createDefaultPointSymbol():SimpleMarkerSymbol
{
return defaultPointSymbol.clone() as SimpleMarkerSymbol;
}
private var _defaultOutlineSymbol:SimpleLineSymbol;
public function get defaultOutlineSymbol():SimpleLineSymbol
{
return _defaultOutlineSymbol ||= new SimpleLineSymbol();
}
public function set defaultOutlineSymbol(value:SimpleLineSymbol):void
{
_defaultOutlineSymbol = value;
}
protected function createDefaultOutlineSymbol():SimpleLineSymbol
{
return defaultOutlineSymbol.clone() as SimpleLineSymbol;
}
public function parsePictureMarkerSymbol(pmsXML:XML):PictureMarkerSymbol
{
const url:String = pmsXML.@url;
const parsedHeight:Number = parseFloat(pmsXML.@height[0]);
const parsedWidth:Number = parseFloat(pmsXML.@width[0]);
const parsedXOffset:Number = parseFloat(pmsXML.@xoffset[0]);
const parsedYOffset:Number = parseFloat(pmsXML.@yoffset[0]);
const parsedAngle:Number = parseFloat(pmsXML.@angle[0]);
const height:Number = !isNaN(parsedHeight) ? parsedHeight : 0;
const width:Number = !isNaN(parsedWidth) ? parsedWidth : 0;
const xOffset:Number = !isNaN(parsedXOffset) ? parsedXOffset : 0;
const yOffset:Number = !isNaN(parsedYOffset) ? parsedYOffset : 0;
const angle:Number = !isNaN(parsedAngle) ? parsedAngle : 0;
return new PictureMarkerSymbol(url, width, height, xOffset, yOffset, angle);
}
public function parseSimpleLineSymbol(slsXML:XML):SimpleLineSymbol
{
const simpleLineSymbol:SimpleLineSymbol = createDefaultPolylineSymbol();
const parsedAlpha:Number = parseFloat(slsXML.@alpha[0]);
const parsedOutlineColor:uint = parseInt(slsXML.@color[0]);
const parsedOutlineWidth:Number = parseFloat(slsXML.@width[0]);
if (slsXML.@style[0])
{
simpleLineSymbol.style = slsXML.@style;
}
if (!isNaN(parsedAlpha))
{
simpleLineSymbol.alpha = parsedAlpha;
}
if (!isNaN(parsedOutlineColor))
{
simpleLineSymbol.color = parsedOutlineColor;
}
if (!isNaN(parsedOutlineWidth))
{
simpleLineSymbol.width = parsedOutlineWidth;
}
return simpleLineSymbol;
}
private var _defaultPolylineSymbol:SimpleLineSymbol;
public function get defaultPolylineSymbol():SimpleLineSymbol
{
return _defaultPolylineSymbol ||= new SimpleLineSymbol();
}
public function set defaultPolylineSymbol(value:SimpleLineSymbol):void
{
_defaultPolylineSymbol = value;
}
protected function createDefaultPolylineSymbol():SimpleLineSymbol
{
return defaultPolylineSymbol.clone() as SimpleLineSymbol;
}
public function parseSimpleFillSymbol(sfsXML:XML):SimpleFillSymbol
{
const simpleFillSymbol:SimpleFillSymbol = createDefaultPolygonSymbol();
const parsedColor:Number = parseInt(sfsXML.@color[0]);
const parsedAlpha:Number = parseFloat(sfsXML.@alpha[0]);
if (sfsXML.@style[0])
{
simpleFillSymbol.style = sfsXML.@style;
}
if (!isNaN(parsedAlpha))
{
simpleFillSymbol.alpha = parsedAlpha;
}
if (!isNaN(parsedColor))
{
simpleFillSymbol.color = parsedColor;
}
if (!simpleFillSymbol.outline)
{
simpleFillSymbol.outline = createDefaultOutlineSymbol();
}
const outlineSymbol:SimpleLineSymbol = simpleFillSymbol.outline;
const parsedOutlineColor:uint = parseInt(sfsXML.outline.@color[0]);
const parsedOutlineWidth:Number = parseFloat(sfsXML.outline.@width[0]);
if (sfsXML.outline.@style[0])
{
outlineSymbol.style = sfsXML.outline.@style;
}
if (!isNaN(parsedOutlineColor))
{
outlineSymbol.color = parsedOutlineColor;
}
if (!isNaN(parsedOutlineWidth))
{
outlineSymbol.width = parsedOutlineWidth;
}
return simpleFillSymbol;
}
private var _defaultPolygonSymbol:SimpleFillSymbol;
public function get defaultPolygonSymbol():SimpleFillSymbol
{
return _defaultPolygonSymbol ||= new SimpleFillSymbol();
}
public function set defaultPolygonSymbol(value:SimpleFillSymbol):void
{
_defaultPolygonSymbol = value;
}
protected function createDefaultPolygonSymbol():SimpleFillSymbol
{
return defaultPolygonSymbol.clone() as SimpleFillSymbol;
}
}
}
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 com.esri.viewer.utils
{
import com.esri.ags.symbols.PictureMarkerSymbol;
import com.esri.ags.symbols.SimpleFillSymbol;
import com.esri.ags.symbols.SimpleLineSymbol;
import com.esri.ags.symbols.SimpleMarkerSymbol;
import com.esri.ags.symbols.Symbol;
import flash.utils.ByteArray;
import mx.utils.Base64Decoder;
public class SymbolParser
{
public function parseSymbol(symbolXML:XML):Symbol
{
var symbol:Symbol;
if (symbolXML)
{
if (symbolXML.simplemarkersymbol[0])
{
symbol = parseSimpleMarkerSymbol(symbolXML.simplemarkersymbol[0]);
}
else if (symbolXML.picturemarkersymbol[0])
{
symbol = parsePictureMarkerSymbol(symbolXML.picturemarkersymbol[0]);
}
else if (symbolXML.simplelinesymbol[0])
{
symbol = parseSimpleLineSymbol(symbolXML.simplelinesymbol[0]);
}
else if (symbolXML.simplefillsymbol[0])
{
symbol = parseSimpleFillSymbol(symbolXML.simplefillsymbol[0]);
}
}
return symbol;
}
public function parseSimpleMarkerSymbol(smsXML:XML):SimpleMarkerSymbol
{
const simpleMarkerSymbol:SimpleMarkerSymbol = createDefaultPointSymbol();
const parsedColor:Number = parseInt(smsXML.@color[0]);
const parsedAlpha:Number = parseFloat(smsXML.@alpha[0]);
const parsedSize:Number = parseFloat(smsXML.@size[0]);
if (smsXML.@style[0])
{
simpleMarkerSymbol.style = smsXML.@style;
}
if (!isNaN(parsedAlpha))
{
simpleMarkerSymbol.alpha = parsedAlpha;
}
if (!isNaN(parsedColor))
{
simpleMarkerSymbol.color = parsedColor;
}
if (!isNaN(parsedSize))
{
simpleMarkerSymbol.size = parsedSize;
}
if (!simpleMarkerSymbol.outline)
{
simpleMarkerSymbol.outline = createDefaultOutlineSymbol();
}
const outlineSymbol:SimpleLineSymbol = simpleMarkerSymbol.outline;
const parsedOutlineColor:uint = parseInt(smsXML.outline.@color[0]);
const parsedOutlineWidth:Number = parseFloat(smsXML.outline.@width[0]);
if (smsXML.outline.@style[0])
{
outlineSymbol.style = smsXML.outline.@style
}
if (!isNaN(parsedOutlineColor))
{
outlineSymbol.color = parsedOutlineColor;
}
if (!isNaN(parsedOutlineWidth))
{
outlineSymbol.width = parsedOutlineWidth;
}
return simpleMarkerSymbol;
}
private var _defaultPointSymbol:SimpleMarkerSymbol;
public function get defaultPointSymbol():SimpleMarkerSymbol
{
return _defaultPointSymbol ||= new SimpleMarkerSymbol();
}
public function set defaultPointSymbol(value:SimpleMarkerSymbol):void
{
_defaultPointSymbol = value;
}
protected function createDefaultPointSymbol():SimpleMarkerSymbol
{
return defaultPointSymbol.clone() as SimpleMarkerSymbol;
}
private var _defaultOutlineSymbol:SimpleLineSymbol;
public function get defaultOutlineSymbol():SimpleLineSymbol
{
return _defaultOutlineSymbol ||= new SimpleLineSymbol();
}
public function set defaultOutlineSymbol(value:SimpleLineSymbol):void
{
_defaultOutlineSymbol = value;
}
protected function createDefaultOutlineSymbol():SimpleLineSymbol
{
return defaultOutlineSymbol.clone() as SimpleLineSymbol;
}
public function parsePictureMarkerSymbol(pmsXML:XML):PictureMarkerSymbol
{
const url:String = pmsXML.@url[0];
const source:String = pmsXML.@source[0];
var sourceData:ByteArray;
if (source)
{
var decoder:Base64Decoder = new Base64Decoder();
decoder.decode(source);
sourceData = decoder.toByteArray();
}
const pictureSource:Object = sourceData ? sourceData : url;
const parsedHeight:Number = parseFloat(pmsXML.@height[0]);
const parsedWidth:Number = parseFloat(pmsXML.@width[0]);
const parsedXOffset:Number = parseFloat(pmsXML.@xoffset[0]);
const parsedYOffset:Number = parseFloat(pmsXML.@yoffset[0]);
const parsedAngle:Number = parseFloat(pmsXML.@angle[0]);
const height:Number = !isNaN(parsedHeight) ? parsedHeight : 0;
const width:Number = !isNaN(parsedWidth) ? parsedWidth : 0;
const xOffset:Number = !isNaN(parsedXOffset) ? parsedXOffset : 0;
const yOffset:Number = !isNaN(parsedYOffset) ? parsedYOffset : 0;
const angle:Number = !isNaN(parsedAngle) ? parsedAngle : 0;
return new PictureMarkerSymbol(pictureSource, width, height, xOffset, yOffset, angle);
}
public function parseSimpleLineSymbol(slsXML:XML):SimpleLineSymbol
{
const simpleLineSymbol:SimpleLineSymbol = createDefaultPolylineSymbol();
const parsedAlpha:Number = parseFloat(slsXML.@alpha[0]);
const parsedOutlineColor:uint = parseInt(slsXML.@color[0]);
const parsedOutlineWidth:Number = parseFloat(slsXML.@width[0]);
if (slsXML.@style[0])
{
simpleLineSymbol.style = slsXML.@style;
}
if (!isNaN(parsedAlpha))
{
simpleLineSymbol.alpha = parsedAlpha;
}
if (!isNaN(parsedOutlineColor))
{
simpleLineSymbol.color = parsedOutlineColor;
}
if (!isNaN(parsedOutlineWidth))
{
simpleLineSymbol.width = parsedOutlineWidth;
}
return simpleLineSymbol;
}
private var _defaultPolylineSymbol:SimpleLineSymbol;
public function get defaultPolylineSymbol():SimpleLineSymbol
{
return _defaultPolylineSymbol ||= new SimpleLineSymbol();
}
public function set defaultPolylineSymbol(value:SimpleLineSymbol):void
{
_defaultPolylineSymbol = value;
}
protected function createDefaultPolylineSymbol():SimpleLineSymbol
{
return defaultPolylineSymbol.clone() as SimpleLineSymbol;
}
public function parseSimpleFillSymbol(sfsXML:XML):SimpleFillSymbol
{
const simpleFillSymbol:SimpleFillSymbol = createDefaultPolygonSymbol();
const parsedColor:Number = parseInt(sfsXML.@color[0]);
const parsedAlpha:Number = parseFloat(sfsXML.@alpha[0]);
if (sfsXML.@style[0])
{
simpleFillSymbol.style = sfsXML.@style;
}
if (!isNaN(parsedAlpha))
{
simpleFillSymbol.alpha = parsedAlpha;
}
if (!isNaN(parsedColor))
{
simpleFillSymbol.color = parsedColor;
}
if (!simpleFillSymbol.outline)
{
simpleFillSymbol.outline = createDefaultOutlineSymbol();
}
const outlineSymbol:SimpleLineSymbol = simpleFillSymbol.outline;
const parsedOutlineColor:uint = parseInt(sfsXML.outline.@color[0]);
const parsedOutlineWidth:Number = parseFloat(sfsXML.outline.@width[0]);
if (sfsXML.outline.@style[0])
{
outlineSymbol.style = sfsXML.outline.@style;
}
if (!isNaN(parsedOutlineColor))
{
outlineSymbol.color = parsedOutlineColor;
}
if (!isNaN(parsedOutlineWidth))
{
outlineSymbol.width = parsedOutlineWidth;
}
return simpleFillSymbol;
}
private var _defaultPolygonSymbol:SimpleFillSymbol;
public function get defaultPolygonSymbol():SimpleFillSymbol
{
return _defaultPolygonSymbol ||= new SimpleFillSymbol();
}
public function set defaultPolygonSymbol(value:SimpleFillSymbol):void
{
_defaultPolygonSymbol = value;
}
protected function createDefaultPolygonSymbol():SimpleFillSymbol
{
return defaultPolygonSymbol.clone() as SimpleFillSymbol;
}
}
}
|
Add Base64 source property to <picturemarkersymbol/>.
|
Add Base64 source property to <picturemarkersymbol/>.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
557362b0fae5e42403e4c34ceef272c1763886c9
|
src/PlayState.as
|
src/PlayState.as
|
package
{
import flash.display.BlendMode;
import org.flixel.*;
import org.flixel.FlxPoint;
public class PlayState extends FlxState
{
// Tileset that works with AUTO mode (best for thin walls)
[Embed(source = 'auto_tiles.png')]private static var auto_tiles:Class;
// Tileset that works with ALT mode (best for thicker walls)
[Embed(source = 'alt_tiles.png')]private static var alt_tiles:Class;
// Tileset that works with OFF mode (do what you want mode)
[Embed(source = 'empty_tiles.png')]private static var empty_tiles:Class;
[Embed(source="player.png")] private static var ImgPlayer:Class;
[Embed(source="background.jpg")] private static var ImgBg:Class;
// Some static constants for the size of the tilemap tiles
private const TILE_WIDTH:uint = 24;
private const TILE_HEIGHT:uint = 24;
private const PLAYER_WIDTH:uint = 72;
private const PLAYER_HEIGHT:uint = 72;
// The dynamically generated FlxTilemap we're using.
private var collisionMap:FlxTilemap;
// Ledge controls, in tiles.
private var minLedgeSize:uint = 3;
private var maxLedgeSize:uint = 6;
private var minLedgeSpacing:FlxPoint = new FlxPoint(4, 2);
private var maxLedgeSpacing:FlxPoint = new FlxPoint(8, 4);
// Instance of custom player class.
private var player:Player;
private var fallChecking:Boolean;
private var bg:FlxSprite;
// Flixel Methods
// --------------
override public function create():void
{
// Globals.
FlxG.framerate = 50;
FlxG.flashFramerate = 50;
fallChecking = true;
// Start our setup chain.
setupPlatform();
// For now, we add things in order to get correct layering.
// TODO - offload to draw method?
add(bg);
add(collisionMap);
add(player);
}
override public function update():void
{
// Start our update chain.
updatePlatform();
super.update();
}
override public function draw():void
{
super.draw();
}
// Setup Routines
// --------------
// Since the observer pattern is too slow, we'll just name our functions to be like hooks.
// The platform is the first thing that gets set up.
private function setupPlatform():void
{
// Load our scenery.
bg = new FlxSprite(0, 0);
bg.loadGraphic(ImgBg);
// Generate our map string.
var mapData:String = '';
var rows:int = Math.round(Math.round(bg.height / TILE_HEIGHT)) ;
var cols:int = Math.round(Math.round(bg.width / TILE_WIDTH));
// Smarts of our algo.
var cStart:uint, cEnd:uint, facing:uint, rSize:int, rSpacing:int, sizeRange:uint, spacingRange:uint;
// Grunts of our algo.
var r:int, c:int, col:Array;
sizeRange = (maxLedgeSize - minLedgeSize);
spacingRange = (maxLedgeSpacing.y - minLedgeSpacing.y);
facing = FlxObject.RIGHT;
for (r = 0; r < rows; r++) {
col = [];
if (r >= rows - minLedgeSpacing.y) {
cStart = 0;
cEnd = 0;
}
if (r == rows-1) {
cStart = 0;
cEnd = cols;
rSpacing = 0;
} else {
if (rSpacing == 0) {
rSpacing = minLedgeSpacing.y + int(Math.random() * spacingRange);
rSize = minLedgeSize + uint(Math.random() * sizeRange);
if (facing == FlxObject.LEFT) {
cStart = 0;
cEnd = rSize;
facing = FlxObject.RIGHT;
} else if (facing == FlxObject.RIGHT) {
cStart = cols - rSize;
cEnd = cols;
facing = FlxObject.LEFT;
}
} else {
rSpacing--;
}
}
for (c = 0; c < cStart; c++) {
col.push('0');
}
for (c = cStart; c < cEnd; c++) {
col.push((rSpacing == 0) ? '1' : '0');
}
for (c = cEnd; c < cols; c++) {
col.push('0');
}
mapData += col.join(',')+"\n";
}
// Creates a new tilemap with no arguments.
collisionMap = new FlxTilemap();
// Initializes the map using the generated string, the tile images, and the tile size.
collisionMap.loadMap(mapData, auto_tiles, TILE_WIDTH, TILE_HEIGHT, FlxTilemap.AUTO);
setupPlatformAfter();
}
// Hooks.
private function setupPlatformAfter():void
{
// Draw player at the bottom.
var start:FlxPoint = new FlxPoint();
var floorHeight:Number = PLAYER_HEIGHT;
start.x = (FlxG.width - PLAYER_HEIGHT) / 2;
start.y = collisionMap.height - (PLAYER_HEIGHT + floorHeight);
setupPlayer(start);
// Move until we don't overlap.
while (collisionMap.overlaps(player)) {
if (player.x <= 0) {
player.x = FlxG.width;
}
player.x -= TILE_WIDTH;
}
setupPlatformAndPlayerAfter();
}
private function setupPlatformAndPlayerAfter():void
{
setupCamera();
}
// Hooked routines.
private function setupPlayer(start:FlxPoint):void
{
// Find start position for player.
player = new Player(start.x, start.y);
player.loadGraphic(ImgPlayer, true, true, 72);
// Bounding box tweaks.
player.height = 36;
player.offset.y = 36;
// Basic player physics.
player.drag.x = 900; // anti-friction
player.acceleration.y = 500; // gravity
player.maxVelocity.x = 300;
player.maxVelocity.y = 700;
// Player jump physics.
player.jumpVelocity.y = -420;
// Animations.
player.addAnimation('idle', [7]);
player.addAnimation('run', [0,1,2,3,4,5,6,7,8,9,10,11], 12);
player.addAnimation('jump', [3]);
}
private function setupCamera():void
{
FlxG.camera.follow(player);
collisionMap.follow();
}
// Update Routines
// ---------------
private function updatePlatform():void
{
updatePlatformAfter();
}
// Hooks.
private function updatePlatformAfter():void
{
// Tilemaps can be collided just like any other FlxObject, and flixel
// automatically collides each individual tile with the object.
FlxG.collide(player, collisionMap);
wrapToStage(player);
updatePlayer();
updatePlatformAndPlayerAfter();
}
private function updatePlatformAndPlayerAfter():void
{
updateCamera(player.justFell());
}
// Hooked routines.
private function updatePlayer():void
{
player.moveWithInput();
if (player.velocity.y != 0)
{
player.play('jump');
}
else if (player.velocity.x == 0)
{
player.play('idle');
}
else
{
player.play('run');
}
}
private function updateCamera(playerJustFell:Boolean):void
{
if (fallChecking && playerJustFell) {
FlxG.camera.shake(
0.01,
0.1, null, true,
FlxCamera.SHAKE_VERTICAL_ONLY
);
}
}
// Helpers
// -------
private function wrapToStage(obj:FlxObject):void
{
obj.x = Math.min(Math.max(obj.x, 0), (collisionMap.width - obj.width));
}
}
}
|
package
{
import flash.display.BlendMode;
import org.flixel.*;
import org.flixel.FlxPoint;
public class PlayState extends FlxState
{
// Tileset that works with AUTO mode (best for thin walls)
[Embed(source = 'auto_tiles.png')]private static var auto_tiles:Class;
// Tileset that works with ALT mode (best for thicker walls)
[Embed(source = 'alt_tiles.png')]private static var alt_tiles:Class;
// Tileset that works with OFF mode (do what you want mode)
[Embed(source = 'empty_tiles.png')]private static var empty_tiles:Class;
[Embed(source="player.png")] private static var ImgPlayer:Class;
[Embed(source="background.jpg")] private static var ImgBg:Class;
// Some static constants for the size of the tilemap tiles
private const TILE_WIDTH:uint = 24;
private const TILE_HEIGHT:uint = 24;
private const PLAYER_WIDTH:uint = 72;
private const PLAYER_HEIGHT:uint = 72;
// The dynamically generated FlxTilemap we're using.
private var collisionMap:FlxTilemap;
// Ledge controls, in tiles.
private var minLedgeSize:uint = 3;
private var maxLedgeSize:uint = 6;
private var minLedgeSpacing:FlxPoint = new FlxPoint(4, 2);
private var maxLedgeSpacing:FlxPoint = new FlxPoint(8, 4);
// Instance of custom player class.
private var player:Player;
private var fallChecking:Boolean;
private var bg:FlxSprite;
// Flixel Methods
// --------------
override public function create():void
{
// Globals.
FlxG.framerate = 50;
FlxG.flashFramerate = 50;
fallChecking = true;
// Start our setup chain.
setupPlatform();
// For now, we add things in order to get correct layering.
// TODO - offload to draw method?
add(bg);
add(collisionMap);
add(player);
}
override public function update():void
{
// Start our update chain.
updatePlatform();
super.update();
}
override public function draw():void
{
super.draw();
}
// Setup Routines
// --------------
// Since the observer pattern is too slow, we'll just name our functions to be like hooks.
// The platform is the first thing that gets set up.
private function setupPlatform():void
{
// Load our scenery.
bg = new FlxSprite(0, 0);
bg.loadGraphic(ImgBg);
// Generate our map string.
var mapData:String = '';
var rows:int = Math.round(Math.round(bg.height / TILE_HEIGHT)) ;
var cols:int = Math.round(Math.round(bg.width / TILE_WIDTH));
// Smarts of our algo.
var cStart:uint, cEnd:uint, facing:uint, rSize:int, rSpacing:int, sizeRange:uint, spacingRange:uint;
// Grunts of our algo.
var r:int, c:int, col:Array;
sizeRange = (maxLedgeSize - minLedgeSize);
spacingRange = (maxLedgeSpacing.y - minLedgeSpacing.y);
facing = FlxObject.RIGHT;
for (r = 0; r < rows; r++) {
col = [];
if (r >= rows - minLedgeSpacing.y) {
cStart = 0;
cEnd = 0;
}
if (r == rows-1) {
cStart = 0;
cEnd = cols;
rSpacing = 0;
} else {
if (rSpacing == 0) {
rSpacing = minLedgeSpacing.y + int(Math.random() * spacingRange);
rSize = minLedgeSize + uint(Math.random() * sizeRange);
if (facing == FlxObject.LEFT) {
cStart = 0;
cEnd = rSize;
facing = FlxObject.RIGHT;
} else if (facing == FlxObject.RIGHT) {
cStart = cols - rSize;
cEnd = cols;
facing = FlxObject.LEFT;
}
} else {
rSpacing--;
}
}
for (c = 0; c < cStart; c++) {
col.push('0');
}
for (c = cStart; c < cEnd; c++) {
col.push((rSpacing == 0) ? '1' : '0');
}
for (c = cEnd; c < cols; c++) {
col.push('0');
}
mapData += col.join(',')+"\n";
}
// Creates a new tilemap with no arguments.
collisionMap = new FlxTilemap();
// Initializes the map using the generated string, the tile images, and the tile size.
collisionMap.loadMap(mapData, auto_tiles, TILE_WIDTH, TILE_HEIGHT, FlxTilemap.AUTO);
setupPlatformAfter();
}
// Hooks.
private function setupPlatformAfter():void
{
// Draw player at the bottom.
var start:FlxPoint = new FlxPoint();
var floorHeight:Number = PLAYER_HEIGHT;
start.x = (FlxG.width - PLAYER_HEIGHT) / 2;
start.y = collisionMap.height - (PLAYER_HEIGHT + floorHeight);
setupPlayer(start);
// Move until we don't overlap.
while (collisionMap.overlaps(player)) {
if (player.x <= 0) {
player.x = FlxG.width;
}
player.x -= TILE_WIDTH;
}
setupPlatformAndPlayerAfter();
}
private function setupPlatformAndPlayerAfter():void
{
setupCamera();
}
// Hooked routines.
private function setupPlayer(start:FlxPoint):void
{
// Find start position for player.
player = new Player(start.x, start.y);
player.loadGraphic(ImgPlayer, true, true, 72);
// Bounding box tweaks.
player.height = 36;
player.offset.y = 36;
// Basic player physics.
player.drag.x = 900; // anti-friction
player.acceleration.y = 500; // gravity
player.maxVelocity.x = 300;
player.maxVelocity.y = 700;
// Player jump physics.
player.jumpVelocity.y = -420;
// Animations.
player.addAnimation('idle', [12,13,14], 12);
player.addAnimation('run', [0,1,2,3,4,5,6,7,8,9,10,11], 12);
player.addAnimation('jump', [3]);
}
private function setupCamera():void
{
FlxG.camera.follow(player);
collisionMap.follow();
}
// Update Routines
// ---------------
private function updatePlatform():void
{
updatePlatformAfter();
}
// Hooks.
private function updatePlatformAfter():void
{
// Tilemaps can be collided just like any other FlxObject, and flixel
// automatically collides each individual tile with the object.
FlxG.collide(player, collisionMap);
wrapToStage(player);
updatePlayer();
updatePlatformAndPlayerAfter();
}
private function updatePlatformAndPlayerAfter():void
{
updateCamera(player.justFell());
}
// Hooked routines.
private function updatePlayer():void
{
player.moveWithInput();
if (player.velocity.y != 0)
{
player.play('jump');
}
else if (player.velocity.x == 0)
{
player.play('idle');
}
else
{
player.play('run');
}
}
private function updateCamera(playerJustFell:Boolean):void
{
if (fallChecking && playerJustFell) {
FlxG.camera.shake(
0.01,
0.1, null, true,
FlxCamera.SHAKE_VERTICAL_ONLY
);
}
}
// Helpers
// -------
private function wrapToStage(obj:FlxObject):void
{
obj.x = Math.min(Math.max(obj.x, 0), (collisionMap.width - obj.width));
}
}
}
|
Add basic idle animation.
|
Add basic idle animation.
|
ActionScript
|
artistic-2.0
|
hlfcoding/morning-stroll
|
14e2977f5bd8e35a7e9018ae162459777403ffc1
|
www/demos/template.as
|
www/demos/template.as
|
;===============================================================================
;
; Empty template for new programs (replace with Title)
;
; Year Author <Email>
; Year Author <Email>
;
; Description
;
;============== Constants ======================================================
; Interrupt table (fe00h - feffh)
; Ends at feffh, but there are no devices connected to interrupts above fe0fh.
INT0_BTN EQU fe00h
INT1_BTN EQU fe01h
INT2_BTN EQU fe02h
; ...
INT14_BTN EQU fe02h
INT15_TIMER EQU fe0fh
; I/O addresses (ff00h - ffffh)
; Starts at ff00h, but there are no devices connected below fff0h.
DISP7SEG_0 EQU fff0h ; write
DISP7SEG_1 EQU fff1h ; write
DISP7SEG_2 EQU fff2h ; write
DISP7SEG_3 EQU fff3h ; write
LCD_CONTROL EQU fff4h ; write
LCD_WRITE EQU fff5h ; write
TIMER_VALUE EQU fff6h ; read/write
TIMER_CONTROL EQU fff7h ; read/write
LEDS EQU fff8h ; write
SWITCHES EQU fff9h ; read
INT_MASK EQU fffah ; read/write
TERM_CURSOR EQU fffch ; write
TERM_STATE EQU fffdh ; read
TERM_WRITE EQU fffeh ; write
TERM_READ EQU ffffh ; read
; Default values
STR_END EQU 0000h ; string terminator
SP_ADDRESS EQU fdffh ; starts at the last available address (fdffh)
INT_MASK_VALUE EQU ffffh ; ffffh = enable all
;============== Data Region (starting at address 8000h) =======================
ORIG 8000h
A_VARIABLE WORD 1010011010b
A_STRING STR 'A String', ' more words', '!', STR_END
A_BUFFER TAB 1337
;============== Code Region (starting at address 0000h) ========================
ORIG 0000h
JMP Main ; jump to main
;-------------- Routines -------------------------------------------------------
; a routine routine for INT0_BTN
Int0Routine: NOP
RTI
; a routine routine for INT1_BTN
Int1Routine: NOP
RTI
; a routine routine for INT2_BTN
Int2Routine: NOP
RTI
; a routine that does nothing
ARoutine: NOP
RET
; another routine that does nothing
AnotherRoutine: NOP
RET
;-------------- Main Program ---------------------------------------------------
Main: MOV R1, SP_ADDRESS
MOV SP, R1 ; set stack pointer
MOV R1, Int0Routine ; set routine for INT0
MOV M[INT0_BTN], R1
MOV R1, Int1Routine ; set routine for INT1
MOV M[INT1_BTN], R1
MOV R1, Int2Routine ; set routine for INT2
MOV M[INT2_BTN], R1
MOV R1, ffffh
MOV M[INT_MASK], R1 ; set interrupt mask
ENI ; enable interrupts
CALL ARoutine
CALL AnotherRoutine
NOP
NOP
NOP
TheEnd: BR TheEnd
;===============================================================================
|
;===============================================================================
;
; Empty template for new programs (replace with Title)
;
; Year Author <Email>
; Year Author <Email>
;
; Description
;
;===============================================================================
; Interrupt Vector Table addresses (fe00h to feffh)
INT0_BTN EQU fe00h
INT1_BTN EQU fe01h
INT2_BTN EQU fe02h
; ...
INT14_BTN EQU fe0eh
INT15_TIMER EQU fe0fh
; I/O addresses (ff00h to ffffh)
DISP7SEG_0 EQU fff0h
DISP7SEG_1 EQU fff1h
DISP7SEG_2 EQU fff2h
DISP7SEG_3 EQU fff3h
LCD_CONTROL EQU fff4h
LCD_WRITE EQU fff5h
TIMER_VALUE EQU fff6h
TIMER_CONTROL EQU fff7h
LEDS EQU fff8h
SWITCHES EQU fff9h
INT_MASK EQU fffah
TERM_CURSOR EQU fffch
TERM_STATE EQU fffdh
TERM_WRITE EQU fffeh
TERM_READ EQU ffffh
; Other constants
STR_END EQU 0000h
SP_ADDRESS EQU fdffh
INT_MASK_VALUE EQU ffffh
;============== Data Region (starting at address 8000h) ========================
ORIG 8000h
; allocate variables and data here (WORD, STR and TAB)
A_VARIABLE WORD 1010011010b
A_STRING STR 'A String', ' more words', '!', STR_END
A_BUFFER TAB 1337
;============== Code Region (starting at address 0000h) ========================
ORIG 0000h
JMP Main ; jump to main
;-------------- Routines -------------------------------------------------------
; put routines here
Int0Routine: NOP ; a routine routine for INT0
INC M[A_VARIABLE]
RTI
ARoutine: NOP ; a routine that does nothing
MOV R2, M[A_VARIABLE]
RET
;-------------- Main Program ---------------------------------------------------
Main: MOV R1, SP_ADDRESS
MOV SP, R1 ; set stack pointer
MOV R1, Int0Routine
MOV M[INT0_BTN], R1 ; set routine for INT0
MOV R1, INT_MASK_VALUE
MOV M[INT_MASK], R1 ; set interrupt mask
ENI ; enable interrupts
; start code here
CALL ARoutine
TheEnd: BR TheEnd
;===============================================================================
|
Clean 'template.as' demo
|
Clean 'template.as' demo
|
ActionScript
|
mit
|
goncalomb/p3js,goncalomb/p3js
|
93418afa4d9fe0346b4efa6181b95be53fe59a38
|
src/as/client/ClientApp.as
|
src/as/client/ClientApp.as
|
//
// $Id$
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.KeyboardEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.geom.Rectangle;
import flash.net.Socket;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.ui.Keyboard;
[SWF(frameRate="60", width=800, height=600, backgroundColor="#000000")]
public class ClientApp extends Sprite {
/**
* Creates a new client app.
*/
public function ClientApp ()
{
// initialize when we've got our dimensions
loaderInfo.addEventListener(Event.INIT, init);
}
/**
* Initializes the app.
*/
protected function init (event :Event) :void
{
// create and add the text field display
_field = new TextField();
addChild(_field);
_field.autoSize = TextFieldAutoSize.CENTER;
_field.textColor = 0x00FF00;
_field.text = " ";
_field.selectable = false;
_field.multiline = true;
var format :TextFormat = new TextFormat();
format.font = "_typewriter";
_field.setTextFormat(format);
// get the size of a character and use it to determine the char width/height
var bounds :Rectangle = _field.getCharBoundaries(0);
_width = loaderInfo.width / bounds.width;
_height = loaderInfo.height / bounds.height;
var line :String = "", text :String = "";
for (var ii :int = 0; ii < _width; ii++) {
line += " ";
}
line += '\n';
for (var jj :int = 0; jj < _height; jj++) {
text += line;
}
_field.text = text;
_field.setTextFormat(format);
_field.x = (loaderInfo.width - _field.width) / 2;
_field.y = (loaderInfo.height - _field.height) / 2;
// listen for key events
addEventListener(KeyboardEvent.KEY_DOWN, sendKeyMessage);
addEventListener(KeyboardEvent.KEY_UP, sendKeyMessage);
// create the socket
_socket = new Socket();
_socket.addEventListener(Event.CONNECT, function (event :Event) :void {
// write the magic number, version, screen dimensions
_socket.writeUnsignedInt(0x57544750);
_socket.writeUnsignedInt(0x00000001);
_socket.writeShort(_width);
_socket.writeShort(_height);
});
_socket.addEventListener(IOErrorEvent.IO_ERROR, function (event :IOErrorEvent) :void {
// TODO: display error
var str :String = "Connect error";
drawString(str, (_width - str.length) / 2, _height/2);
});
_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
function (event :SecurityErrorEvent) :void {
// we get this when we can't connect; ignore it
});
_socket.addEventListener(ProgressEvent.SOCKET_DATA, readMessages);
// attempt to connect to the server
var params :Object = loaderInfo.parameters;
_socket.connect(String(params["server_host"]), int(params["server_port"]));
}
/**
* Handles key events.
*/
protected function sendKeyMessage (event :KeyboardEvent) :void
{
if (!_socket.connected) {
return;
}
_socket.writeShort(6);
_socket.writeShort(event.type == KeyboardEvent.KEY_DOWN ? 0 : 1);
_socket.writeUnsignedInt(getQtKeyCode(event));
}
/**
* Handles incoming socket data.
*/
protected function readMessages (event :ProgressEvent) :void
{
}
/**
* Draws a string at the specified x and y positions.
*/
protected function drawString (str :String, x :int, y :int) :void
{
var begin :int = y*(_width + 1) + x;
_field.replaceText(begin, begin + str.length, str);
}
/**
* Converts an ActionScript key code to a Qt one.
*/
protected function getQtKeyCode (event :KeyboardEvent) :uint
{
switch (event.keyCode) {
case Keyboard.ESCAPE: return 0x01000000;
case Keyboard.F1: return 0x01000030;
case Keyboard.F2: return 0x01000031;
case Keyboard.F3: return 0x01000032;
case Keyboard.F4: return 0x01000033;
case Keyboard.F5: return 0x01000034;
case Keyboard.F6: return 0x01000035;
case Keyboard.F7: return 0x01000036;
case Keyboard.F8: return 0x01000037;
case Keyboard.F9: return 0x01000038;
case Keyboard.F10: return 0x01000039;
case Keyboard.F11: return 0x0100003a;
case Keyboard.F12: return 0x0100003b;
case Keyboard.F13: return 0x0100003c;
case Keyboard.F14: return 0x0100003d;
case Keyboard.F15: return 0x0100003e;
case Keyboard.PAUSE: return 0x01000008;
case Keyboard.BACKQUOTE: return 0x60;
case Keyboard.NUMBER_0: return 0x30;
case Keyboard.NUMBER_1: return 0x31;
case Keyboard.NUMBER_2: return 0x32;
case Keyboard.NUMBER_3: return 0x33;
case Keyboard.NUMBER_4: return 0x34;
case Keyboard.NUMBER_5: return 0x35;
case Keyboard.NUMBER_6: return 0x36;
case Keyboard.NUMBER_7: return 0x37;
case Keyboard.NUMBER_8: return 0x38;
case Keyboard.NUMBER_9: return 0x39;
case Keyboard.MINUS: return 0x2d;
case Keyboard.EQUAL: return 0x3d;
case Keyboard.BACKSPACE: return 0x01000003;
case Keyboard.INSERT: return 0x01000006;
case Keyboard.HOME: return 0x01000010;
case Keyboard.PAGE_UP: return 0x01000016;
case Keyboard.NUMPAD_DIVIDE: return 0x2f;
case Keyboard.NUMPAD_MULTIPLY: return 0x2a;
case Keyboard.NUMPAD_SUBTRACT: return 0x2d;
case Keyboard.TAB: return 0x01000001;
case Keyboard.Q: return 0x51;
case Keyboard.W: return 0x57;
case Keyboard.E: return 0x45;
case Keyboard.R: return 0x52;
case Keyboard.T: return 0x54;
case Keyboard.Y: return 0x59;
case Keyboard.U: return 0x55;
case Keyboard.I: return 0x49;
case Keyboard.O: return 0x4f;
case Keyboard.P: return 0x50;
case Keyboard.LEFTBRACKET: return 0x5b;
case Keyboard.RIGHTBRACKET: return 0x5d;
case Keyboard.BACKSLASH: return 0x5c;
case Keyboard.DELETE: return 0x01000007;
case Keyboard.END: return 0x01000011;
case Keyboard.PAGE_DOWN: return 0x01000017;
case Keyboard.NUMPAD_7: return 0x37;
case Keyboard.NUMPAD_8: return 0x38;
case Keyboard.NUMPAD_9: return 0x39;
case Keyboard.NUMPAD_ADD: return 0x2b;
case Keyboard.CAPS_LOCK: return 0x01000024;
case Keyboard.A: return 0x41;
case Keyboard.S: return 0x53;
case Keyboard.D: return 0x44;
case Keyboard.F: return 0x46;
case Keyboard.G: return 0x47;
case Keyboard.H: return 0x48;
case Keyboard.J: return 0x4a;
case Keyboard.K: return 0x4b;
case Keyboard.L: return 0x4c;
case Keyboard.SEMICOLON: return 0x3b;
case Keyboard.QUOTE: return 0x27;
case Keyboard.ENTER: return 0x01000004;
case Keyboard.NUMPAD_4: return 0x34;
case Keyboard.NUMPAD_5: return 0x35;
case Keyboard.NUMPAD_6: return 0x36;
case Keyboard.SHIFT: return 0x01000020;
case Keyboard.Z: return 0x5a;
case Keyboard.X: return 0x58;
case Keyboard.C: return 0x43;
case Keyboard.V: return 0x56;
case Keyboard.B: return 0x42;
case Keyboard.N: return 0x4e;
case Keyboard.M: return 0x4d;
case Keyboard.COMMA: return 0x2c;
case Keyboard.PERIOD: return 0x2e;
case Keyboard.SLASH: return 0x2f;
case Keyboard.UP: return 0x01000013;
case Keyboard.NUMPAD_1: return 0x31;
case Keyboard.NUMPAD_2: return 0x32;
case Keyboard.NUMPAD_3: return 0x33;
case Keyboard.NUMPAD_ENTER: return 0x01000005;
case Keyboard.CONTROL: return 0x01000021;
case Keyboard.COMMAND: return 0x01000021;
case Keyboard.ALTERNATE: return 0x01000023;
case Keyboard.SPACE: return 0x20;
case Keyboard.MENU: return 0x01000055;
case Keyboard.LEFT: return 0x01000012;
case Keyboard.DOWN: return 0x01000015;
case Keyboard.RIGHT: return 0x01000014;
case Keyboard.HELP: return 0x01000058;
default: return 0x01ffffff; // Key_unknown
}
}
/** Our gigantic text field. */
protected var _field :TextField;
/** The width and height of the display in characters. */
protected var _width :int, _height :int;
/** The socket via which we communicate with the server. */
protected var _socket :Socket;
}
}
|
//
// $Id$
package {
import flash.display.Sprite;
import flash.events.ContextMenuEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.KeyboardEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.geom.Rectangle;
import flash.net.SharedObject;
import flash.net.Socket;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;
import flash.ui.Keyboard;
/**
* The Witgap client application.
*/
[SWF(frameRate="60", width=800, height=600, backgroundColor="#000000")]
public class ClientApp extends Sprite {
/**
* Creates a new client app.
*/
public function ClientApp ()
{
// initialize when we've got our dimensions
loaderInfo.addEventListener(Event.INIT, init);
}
/**
* Initializes the app.
*/
protected function init (event :Event) :void
{
// create and add the text field display
_field = new TextField();
addChild(_field);
_field.autoSize = TextFieldAutoSize.CENTER;
_field.textColor = 0x00FF00;
_field.text = " ";
_field.selectable = false;
_field.multiline = true;
var format :TextFormat = new TextFormat();
format.font = "_typewriter";
_field.setTextFormat(format);
// get the size of a character and use it to determine the char width/height
var bounds :Rectangle = _field.getCharBoundaries(0);
_width = loaderInfo.width / bounds.width;
_height = loaderInfo.height / bounds.height;
var line :String = "", text :String = "";
for (var ii :int = 0; ii < _width; ii++) {
line += " ";
}
line += '\n';
for (var jj :int = 0; jj < _height; jj++) {
text += line;
}
_field.text = text;
_field.setTextFormat(format);
_field.x = (loaderInfo.width - _field.width) / 2;
_field.y = (loaderInfo.height - _field.height) / 2;
// get the preferences
_prefs = SharedObject.getLocal("prefs");
// add the context menu to change colors
contextMenu = new ContextMenu();
contextMenu.hideBuiltInItems();
contextMenu.customItems = [ ];
var captions :Array = [ "White", "Green", "Amber" ];
var colors :Array = [ 0xFFFFFF, 0x00FF00, 0xFFFF00 ];
var setColor :Function = function (caption :String) :void {
_prefs.setProperty("color", caption);
for (var kk :int = 0; kk < captions.length; kk++) {
if (captions[kk] == caption) {
_field.textColor = colors[kk];
contextMenu.customItems[kk].enabled = false;
} else {
contextMenu.customItems[kk].enabled = true;
}
}
};
var updateColor :Function = function (event :ContextMenuEvent) :void {
setColor(ContextMenuItem(event.target).caption);
};
for (var kk :int = 0; kk < captions.length; kk++) {
var item :ContextMenuItem = new ContextMenuItem(captions[kk]);
contextMenu.customItems.push(item);
item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, updateColor);
}
setColor(_prefs.data["color"] == undefined ? "Green" : _prefs.data["color"]);
// listen for key events
addEventListener(KeyboardEvent.KEY_DOWN, sendKeyMessage);
addEventListener(KeyboardEvent.KEY_UP, sendKeyMessage);
// create the socket
_socket = new Socket();
_socket.addEventListener(Event.CONNECT, function (event :Event) :void {
// write the magic number, version, screen dimensions
_socket.writeUnsignedInt(0x57544750);
_socket.writeUnsignedInt(0x00000001);
_socket.writeShort(_width);
_socket.writeShort(_height);
});
_socket.addEventListener(IOErrorEvent.IO_ERROR, function (event :IOErrorEvent) :void {
// TODO: display error
var str :String = "Connect error";
drawString(str, (_width - str.length) / 2, _height/2);
});
_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
function (event :SecurityErrorEvent) :void {
// we get this when we can't connect; ignore it
});
_socket.addEventListener(ProgressEvent.SOCKET_DATA, readMessages);
// attempt to connect to the server
var params :Object = loaderInfo.parameters;
_socket.connect(String(params["server_host"]), int(params["server_port"]));
}
/**
* Handles key events.
*/
protected function sendKeyMessage (event :KeyboardEvent) :void
{
if (!_socket.connected) {
return;
}
_socket.writeShort(6);
_socket.writeShort(event.type == KeyboardEvent.KEY_DOWN ? 0 : 1);
_socket.writeUnsignedInt(getQtKeyCode(event));
}
/**
* Handles incoming socket data.
*/
protected function readMessages (event :ProgressEvent) :void
{
}
/**
* Draws a string at the specified x and y positions.
*/
protected function drawString (str :String, x :int, y :int) :void
{
var begin :int = y*(_width + 1) + x;
_field.replaceText(begin, begin + str.length, str);
}
/**
* Converts an ActionScript key code to a Qt one.
*/
protected function getQtKeyCode (event :KeyboardEvent) :uint
{
switch (event.keyCode) {
case Keyboard.ESCAPE: return 0x01000000;
case Keyboard.F1: return 0x01000030;
case Keyboard.F2: return 0x01000031;
case Keyboard.F3: return 0x01000032;
case Keyboard.F4: return 0x01000033;
case Keyboard.F5: return 0x01000034;
case Keyboard.F6: return 0x01000035;
case Keyboard.F7: return 0x01000036;
case Keyboard.F8: return 0x01000037;
case Keyboard.F9: return 0x01000038;
case Keyboard.F10: return 0x01000039;
case Keyboard.F11: return 0x0100003a;
case Keyboard.F12: return 0x0100003b;
case Keyboard.F13: return 0x0100003c;
case Keyboard.F14: return 0x0100003d;
case Keyboard.F15: return 0x0100003e;
case Keyboard.PAUSE: return 0x01000008;
case Keyboard.BACKQUOTE: return 0x60;
case Keyboard.NUMBER_0: return 0x30;
case Keyboard.NUMBER_1: return 0x31;
case Keyboard.NUMBER_2: return 0x32;
case Keyboard.NUMBER_3: return 0x33;
case Keyboard.NUMBER_4: return 0x34;
case Keyboard.NUMBER_5: return 0x35;
case Keyboard.NUMBER_6: return 0x36;
case Keyboard.NUMBER_7: return 0x37;
case Keyboard.NUMBER_8: return 0x38;
case Keyboard.NUMBER_9: return 0x39;
case Keyboard.MINUS: return 0x2d;
case Keyboard.EQUAL: return 0x3d;
case Keyboard.BACKSPACE: return 0x01000003;
case Keyboard.INSERT: return 0x01000006;
case Keyboard.HOME: return 0x01000010;
case Keyboard.PAGE_UP: return 0x01000016;
case Keyboard.NUMPAD_DIVIDE: return 0x2f;
case Keyboard.NUMPAD_MULTIPLY: return 0x2a;
case Keyboard.NUMPAD_SUBTRACT: return 0x2d;
case Keyboard.TAB: return 0x01000001;
case Keyboard.Q: return 0x51;
case Keyboard.W: return 0x57;
case Keyboard.E: return 0x45;
case Keyboard.R: return 0x52;
case Keyboard.T: return 0x54;
case Keyboard.Y: return 0x59;
case Keyboard.U: return 0x55;
case Keyboard.I: return 0x49;
case Keyboard.O: return 0x4f;
case Keyboard.P: return 0x50;
case Keyboard.LEFTBRACKET: return 0x5b;
case Keyboard.RIGHTBRACKET: return 0x5d;
case Keyboard.BACKSLASH: return 0x5c;
case Keyboard.DELETE: return 0x01000007;
case Keyboard.END: return 0x01000011;
case Keyboard.PAGE_DOWN: return 0x01000017;
case Keyboard.NUMPAD_7: return 0x37;
case Keyboard.NUMPAD_8: return 0x38;
case Keyboard.NUMPAD_9: return 0x39;
case Keyboard.NUMPAD_ADD: return 0x2b;
case Keyboard.CAPS_LOCK: return 0x01000024;
case Keyboard.A: return 0x41;
case Keyboard.S: return 0x53;
case Keyboard.D: return 0x44;
case Keyboard.F: return 0x46;
case Keyboard.G: return 0x47;
case Keyboard.H: return 0x48;
case Keyboard.J: return 0x4a;
case Keyboard.K: return 0x4b;
case Keyboard.L: return 0x4c;
case Keyboard.SEMICOLON: return 0x3b;
case Keyboard.QUOTE: return 0x27;
case Keyboard.ENTER: return 0x01000004;
case Keyboard.NUMPAD_4: return 0x34;
case Keyboard.NUMPAD_5: return 0x35;
case Keyboard.NUMPAD_6: return 0x36;
case Keyboard.SHIFT: return 0x01000020;
case Keyboard.Z: return 0x5a;
case Keyboard.X: return 0x58;
case Keyboard.C: return 0x43;
case Keyboard.V: return 0x56;
case Keyboard.B: return 0x42;
case Keyboard.N: return 0x4e;
case Keyboard.M: return 0x4d;
case Keyboard.COMMA: return 0x2c;
case Keyboard.PERIOD: return 0x2e;
case Keyboard.SLASH: return 0x2f;
case Keyboard.UP: return 0x01000013;
case Keyboard.NUMPAD_1: return 0x31;
case Keyboard.NUMPAD_2: return 0x32;
case Keyboard.NUMPAD_3: return 0x33;
case Keyboard.NUMPAD_ENTER: return 0x01000005;
case Keyboard.CONTROL: return 0x01000021;
case Keyboard.COMMAND: return 0x01000021;
case Keyboard.ALTERNATE: return 0x01000023;
case Keyboard.SPACE: return 0x20;
case Keyboard.MENU: return 0x01000055;
case Keyboard.LEFT: return 0x01000012;
case Keyboard.DOWN: return 0x01000015;
case Keyboard.RIGHT: return 0x01000014;
case Keyboard.HELP: return 0x01000058;
default: return 0x01ffffff; // Key_unknown
}
}
/** Persistent preferences. */
protected var _prefs :SharedObject;
/** Our gigantic text field. */
protected var _field :TextField;
/** The width and height of the display in characters. */
protected var _width :int, _height :int;
/** The socket via which we communicate with the server. */
protected var _socket :Socket;
}
}
|
Allow customizing the text color, persist to preferences.
|
Allow customizing the text color, persist to preferences.
git-svn-id: 41360ad359616a519dfba9f2f48af1afe653c9f7@10 be230a1c-449f-4488-b524-6273046f66f0
|
ActionScript
|
bsd-2-clause
|
ey6es/witgap,ey6es/witgap,ey6es/witgap,ey6es/witgap
|
72f052749e74a3ae461bb20d0996df6896d368cd
|
src/org/hola/Base64.as
|
src/org/hola/Base64.as
|
package org.hola
{
import flash.utils.ByteArray;
public class Base64 extends Object
{
private static const _decodeChars:Vector.<int> = InitDecodeChar();
public function Base64()
{
super();
}
public static function decode(param1:String) : ByteArray
{
var _loc2_:* = 0;
var _loc3_:* = 0;
var _loc4_:* = 0;
var _loc5_:* = 0;
var _loc6_:* = 0;
var _loc7_:int = param1.length;
var _loc8_:ByteArray = new ByteArray();
_loc8_.writeUTFBytes(param1);
var _loc9_:* = 0;
while(_loc6_ < _loc7_)
{
_loc2_ = _decodeChars[int(_loc8_[_loc6_++])];
if(_loc2_ == -1)
{
break;
}
_loc3_ = _decodeChars[int(_loc8_[_loc6_++])];
if(_loc3_ == -1)
{
break;
}
_loc8_[int(_loc9_++)] = _loc2_ << 2 | (_loc3_ & 48) >> 4;
_loc4_ = _loc8_[int(_loc6_++)];
if(_loc4_ == 61)
{
_loc8_.length = _loc9_;
return _loc8_;
}
_loc4_ = _decodeChars[int(_loc4_)];
if(_loc4_ == -1)
{
break;
}
_loc8_[int(_loc9_++)] = (_loc3_ & 15) << 4 | (_loc4_ & 60) >> 2;
_loc5_ = _loc8_[int(_loc6_++)];
if(_loc5_ == 61)
{
_loc8_.length = _loc9_;
return _loc8_;
}
_loc5_ = _decodeChars[int(_loc5_)];
if(_loc5_ == -1)
{
break;
}
_loc8_[int(_loc9_++)] = (_loc4_ & 3) << 6 | _loc5_;
}
_loc8_.length = _loc9_;
return _loc8_;
}
public static function InitDecodeChar() : Vector.<int>
{
var _loc1_:Vector.<int> = new <int>[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];
return _loc1_;
}
}
}
|
package org.hola
{
import flash.utils.ByteArray;
public class Base64 extends Object
{
private static const _decodeChars:Vector.<int> = InitDecodeChar();
public static function decode(str : String) : ByteArray {
var c1 : int;
var c2 : int;
var c3 : int;
var c4 : int;
var i : int = 0;
var len : int = str.length;
var arr : ByteArray = new ByteArray();
arr.length = len/4*3;
var pos : int = 0;
while (i<len)
{
c1 = _decodeChars[int(str.charCodeAt(i++))];
if (c1 == -1)
break;
c2 = _decodeChars[int(str.charCodeAt(i++))];
if (c2 == -1)
break;
arr[int(pos++)] = (c1 << 2) | ((c2 & 0x30) >> 4);
c3 = int(str.charCodeAt(i++));
if (c3 == 61)
break;
c3 = _decodeChars[int(c3)];
if (c3 == -1)
break;
arr[int(pos++)] = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);
c4 = int(str.charCodeAt(i++));
if (c4 == 61)
break;
c4 = _decodeChars[int(c4)];
if (c4 == -1)
break;
arr[int(pos++)] = ((c3 & 0x03) << 6) | c4;
}
arr.length = pos;
return arr;
}
public static function InitDecodeChar() : Vector.<int>
{
var decodeChars : Vector.<int> = new <int>[
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
return decodeChars;
}
}
}
|
improve performance and readability of Base64.as
|
improve performance and readability of Base64.as
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls
|
e504f787edd833959a60209641b5690625d46e7f
|
src/org/jivesoftware/xiff/core/AbstractJID.as
|
src/org/jivesoftware/xiff/core/AbstractJID.as
|
package org.jivesoftware.xiff.core
{
public class AbstractJID
{
//TODO: this doesn't actually validate properly in some cases; need separate nodePrep, etc...
protected static var jidNodeValidator:RegExp = /^([\x29\x23-\x25\x28-\x2E\x30-\x39\x3B\x3D\x3F\x41-\x7E\xA0 \u1680\u202F\u205F\u3000\u2000-\u2009\u200A-\u200B\u06DD \u070F\u180E\u200C-\u200D\u2028-\u2029\u0080-\u009F \u2060-\u2063\u206A-\u206F\uFFF9-\uFFFC\uE000-\uF8FF\uFDD0-\uFDEF \uFFFE-\uFFFF\uD800-\uDFFF\uFFF9-\uFFFD\u2FF0-\u2FFB]{1,1023})/;
protected var _node:String = "";
protected var _domain:String = "";
protected var _resource:String = "";
public function AbstractJID(inJID:String, validate:Boolean=false):void {
if(validate)
{
if(!jidNodeValidator.test(inJID) || inJID.indexOf(" ") > -1)
{
trace("Invalid JID: %s", inJID);
throw "Invalid JID";
}
}
var separatorIndex:int = inJID.lastIndexOf("@");
var slashIndex:int = inJID.lastIndexOf("/");
if(slashIndex >= 0)
_resource = inJID.substring(slashIndex + 1);
if(separatorIndex >= 0)
_domain = inJID.substring(separatorIndex + 1, slashIndex >= 0 ? slashIndex : inJID.length);
if(separatorIndex >= 1)
_node = inJID.substring(0, separatorIndex);
}
//if we use the literal regexp notation, flex gets confused and thinks the quote starts a string
private static var quoteregex:RegExp = new RegExp('"', "g");
private static var quoteregex2:RegExp = new RegExp("'", "g");
protected function get escapedNode():String
{
var n:String = node;
n = n.replace(/\\/g, "\\5c");
n = n.replace(/@/g, "\\40");
n = n.replace(/ /g, "\\20");
n = n.replace(/&/g, "\\26");
n = n.replace(/>/g, "\\3e");
n = n.replace(/</g, "\\3c");
n = n.replace(/:/g, "\\3a");
n = n.replace(/\//g, "\\2f");
n = n.replace(quoteregex, "\\22");
n = n.replace(quoteregex2, "\\27");
trace(n);
return n;
}
protected function get unescapedNode():String
{
var n:String = node;
n = n.replace(/\40/g, "@");
n = n.replace(/\20/g, " ");
n = n.replace(/\26/g, "&");
n = n.replace(/\3e/g, ">");
n = n.replace(/\3c/g, "<");
n = n.replace(/\3a/g, ":");
n = n.replace(/\2f/g, "/");
n = n.replace(quoteregex, '"');
n = n.replace(quoteregex2, "'");
n = n.replace(/\5c/g, "\\");
return n;
}
public function toString():String
{
var j:String = "";
if(node)
j += node + "@";
j += domain;
if(resource)
j += "/" + resource;
return j;
}
public function get bareJID():String
{
var str:String = toString();
var slashIndex:int = str.lastIndexOf("/");
if(slashIndex > 0)
str = str.substring(0, slashIndex);
return str;
}
public function get resource():String
{
if(_resource.length > 0)
return _resource;
return null;
}
public function get node():String
{
if(_node.length > 0)
return _node;
return null;
}
public function get domain():String
{
return _domain;
}
}
}
|
package org.jivesoftware.xiff.core
{
public class AbstractJID
{
//TODO: this doesn't actually validate properly in some cases; need separate nodePrep, etc...
protected static var jidNodeValidator:RegExp = /^([\x29\x23-\x25\x28-\x2E\x30-\x39\x3B\x3D\x3F\x41-\x7E\xA0 \u1680\u202F\u205F\u3000\u2000-\u2009\u200A-\u200B\u06DD \u070F\u180E\u200C-\u200D\u2028-\u2029\u0080-\u009F \u2060-\u2063\u206A-\u206F\uFFF9-\uFFFC\uE000-\uF8FF\uFDD0-\uFDEF \uFFFE-\uFFFF\uD800-\uDFFF\uFFF9-\uFFFD\u2FF0-\u2FFB]{1,1023})/;
protected var _node:String = "";
protected var _domain:String = "";
protected var _resource:String = "";
public function AbstractJID(inJID:String, validate:Boolean=false):void {
if(validate)
{
if(!jidNodeValidator.test(inJID) || inJID.indexOf(" ") > -1)
{
trace("Invalid JID: %s", inJID);
throw "Invalid JID";
}
}
var separatorIndex:int = inJID.lastIndexOf("@");
var slashIndex:int = inJID.lastIndexOf("/");
if(slashIndex >= 0)
_resource = inJID.substring(slashIndex + 1);
_domain = inJID.substring(separatorIndex + 1, slashIndex >= 0 ? slashIndex : inJID.length);
if(separatorIndex >= 1)
_node = inJID.substring(0, separatorIndex);
}
//if we use the literal regexp notation, flex gets confused and thinks the quote starts a string
private static var quoteregex:RegExp = new RegExp('"', "g");
private static var quoteregex2:RegExp = new RegExp("'", "g");
protected function get escapedNode():String
{
var n:String = node;
n = n.replace(/\\/g, "\\5c");
n = n.replace(/@/g, "\\40");
n = n.replace(/ /g, "\\20");
n = n.replace(/&/g, "\\26");
n = n.replace(/>/g, "\\3e");
n = n.replace(/</g, "\\3c");
n = n.replace(/:/g, "\\3a");
n = n.replace(/\//g, "\\2f");
n = n.replace(quoteregex, "\\22");
n = n.replace(quoteregex2, "\\27");
trace(n);
return n;
}
protected function get unescapedNode():String
{
var n:String = node;
n = n.replace(/\40/g, "@");
n = n.replace(/\20/g, " ");
n = n.replace(/\26/g, "&");
n = n.replace(/\3e/g, ">");
n = n.replace(/\3c/g, "<");
n = n.replace(/\3a/g, ":");
n = n.replace(/\2f/g, "/");
n = n.replace(quoteregex, '"');
n = n.replace(quoteregex2, "'");
n = n.replace(/\5c/g, "\\");
return n;
}
public function toString():String
{
var j:String = "";
if(node)
j += node + "@";
j += domain;
if(resource)
j += "/" + resource;
return j;
}
public function get bareJID():String
{
var str:String = toString();
var slashIndex:int = str.lastIndexOf("/");
if(slashIndex > 0)
str = str.substring(0, slashIndex);
return str;
}
public function get resource():String
{
if(_resource.length > 0)
return _resource;
return null;
}
public function get node():String
{
if(_node.length > 0)
return _node;
return null;
}
public function get domain():String
{
return _domain;
}
}
}
|
Fix another NPE. r=Armando
|
Fix another NPE. r=Armando
|
ActionScript
|
apache-2.0
|
igniterealtime/XIFF
|
af202267f81b1ddde055ab4a8450e37ad946c799
|
com/segonquart/menuColourIdiomes.as
|
com/segonquart/menuColourIdiomes.as
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class com segonquart menuColouridiomes extends MoviieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function menuColourIdiomes ():Void
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver():Void
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
}
private function mOut():Void
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
|
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
class menuColouridiomes extends MoviieClip
{
public var cat, es, en ,fr:MovieClip;
public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr");
function menuColourIdiomes ():Void
{
this.onRollOver = this.mOver;
this.onRollOut = this.mOut;
this.onRelease =this.mOver;
}
private function mOver():Void
{
arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc");
}
private function mOut():Void
{
arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc");
}
}
|
Update menuColourIdiomes.as
|
Update menuColourIdiomes.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
f6060d95af24a17cc36d7ae9c150e8a11e76fd37
|
src/as/com/threerings/flash/FilterUtil.as
|
src/as/com/threerings/flash/FilterUtil.as
|
package com.threerings.flash {
import flash.display.DisplayObject;
import flash.filters.BevelFilter;
import flash.filters.BitmapFilter;
import flash.filters.BlurFilter;
import flash.filters.ColorMatrixFilter;
import flash.filters.ConvolutionFilter;
import flash.filters.DisplacementMapFilter;
import flash.filters.DropShadowFilter;
import flash.filters.GlowFilter;
import flash.filters.GradientBevelFilter;
import flash.filters.GradientGlowFilter;
import com.threerings.util.ArrayUtil;
import com.threerings.util.ClassUtil;
/**
* Useful utility methods that wouldn't be needed if the flash API were not so retarded.
*/
public class FilterUtil
{
/**
* Add the specified filter to the DisplayObject.
*/
public static function addFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts == null) {
filts = [];
}
filts.push(filter);
disp.filters = filts;
}
/**
* Remove the specified filter from the DisplayObject.
* Note that the filter set in the DisplayObject is a clone, so the values
* of the specified filter are used to find a match.
*/
public static function removeFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts != null) {
for (var ii :int = filts.length - 1; ii >= 0; ii--) {
var oldFilter :BitmapFilter = (filts[ii] as BitmapFilter);
if (equals(oldFilter, filter)) {
filts.splice(ii, 1);
if (filts.length == 0) {
filts = null;
}
disp.filters = filts;
return; // SUCCESS
}
}
}
}
/**
* Are the two filters equals?
*/
public static function equals (f1 :BitmapFilter, f2 :BitmapFilter) :Boolean
{
if (f1 === f2) { // catch same instance, or both null
return true;
} else if (f1 == null || f2 == null) { // otherwise nulls are no good
return false;
}
var c1 :Class = ClassUtil.getClass(f1);
if (c1 !== ClassUtil.getClass(f2)) {
return false;
}
// when we have two filters of the same class, figure it out by hand...
switch (c1) {
case BevelFilter:
var bf1 :BevelFilter = (f1 as BevelFilter);
var bf2 :BevelFilter = (f2 as BevelFilter);
return (bf1.angle == bf2.angle) && (bf1.blurX == bf2.blurX) &&
(bf1.blurY == bf2.blurY) && (bf1.distance == bf2.distance) &&
(bf1.highlightAlpha == bf2.highlightAlpha) &&
(bf1.highlightColor == bf2.highlightColor) && (bf1.knockout == bf2.knockout) &&
(bf1.quality == bf2.quality) && (bf1.shadowAlpha == bf2.shadowAlpha) &&
(bf1.shadowColor == bf2.shadowColor) && (bf1.strength == bf2.strength) &&
(bf1.type == bf2.type);
case BlurFilter:
var blur1 :BlurFilter = (f1 as BlurFilter);
var blur2 :BlurFilter = (f2 as BlurFilter);
return (blur1.blurX == blur2.blurX) && (blur1.blurY == blur2.blurY) &&
(blur1.quality == blur2.quality);
case ColorMatrixFilter:
var cmf1 :ColorMatrixFilter = (f1 as ColorMatrixFilter);
var cmf2 :ColorMatrixFilter = (f2 as ColorMatrixFilter);
return ArrayUtil.equals(cmf1.matrix, cmf2.matrix);
case ConvolutionFilter:
var cf1 :ConvolutionFilter = (f1 as ConvolutionFilter);
var cf2 :ConvolutionFilter = (f2 as ConvolutionFilter);
return (cf1.alpha == cf2.alpha) && (cf1.bias == cf2.bias) && (cf1.clamp == cf2.clamp) &&
(cf1.color == cf2.color) && (cf1.divisor == cf2.divisor) &&
ArrayUtil.equals(cf1.matrix, cf2.matrix) && (cf1.matrixX == cf2.matrixX) &&
(cf1.matrixY == cf2.matrixY) && (cf1.preserveAlpha == cf2.preserveAlpha);
case DisplacementMapFilter:
var dmf1 :DisplacementMapFilter = (f1 as DisplacementMapFilter);
var dmf2 :DisplacementMapFilter = (f2 as DisplacementMapFilter);
return (dmf1.alpha == dmf2.alpha) && (dmf1.color == dmf2.color) &&
(dmf1.componentX == dmf2.componentX) && (dmf1.componentY == dmf2.componentY) &&
(dmf1.mapBitmap == dmf2.mapBitmap) && dmf1.mapPoint.equals(dmf2.mapPoint) &&
(dmf1.mode == dmf2.mode) && (dmf1.scaleX == dmf2.scaleX) &&
(dmf1.scaleY == dmf2.scaleY);
case DropShadowFilter:
var dsf1 :DropShadowFilter = (f1 as DropShadowFilter);
var dsf2 :DropShadowFilter = (f2 as DropShadowFilter);
return (dsf1.alpha == dsf2.alpha) && (dsf1.angle = dsf2.angle) &&
(dsf1.blurX = dsf2.blurX) && (dsf1.blurY = dsf2.blurY) &&
(dsf1.color = dsf2.color) && (dsf1.distance = dsf2.distance) &&
(dsf1.hideObject = dsf2.hideObject) && (dsf1.inner = dsf2.inner) &&
(dsf1.knockout = dsf2.knockout) && (dsf1.quality = dsf2.quality) &&
(dsf1.strength = dsf2.strength);
case GlowFilter:
var gf1 :GlowFilter = (f1 as GlowFilter);
var gf2 :GlowFilter = (f2 as GlowFilter);
return (gf1.alpha == gf2.alpha) && (gf1.blurX == gf2.blurX) &&
(gf1.blurY == gf2.blurY) && (gf1.color == gf2.color) && (gf1.inner == gf2.inner) &&
(gf1.knockout == gf2.knockout) && (gf1.quality == gf2.quality) &&
(gf1.strength == gf2.strength);
case GradientBevelFilter:
var gbf1 :GradientBevelFilter = (f1 as GradientBevelFilter);
var gbf2 :GradientBevelFilter = (f2 as GradientBevelFilter);
return ArrayUtil.equals(gbf1.alphas, gbf2.alphas) && (gbf1.angle == gbf2.angle) &&
(gbf1.blurX == gbf2.blurX) && (gbf1.blurY == gbf2.blurY) &&
ArrayUtil.equals(gbf1.colors, gbf2.colors) && (gbf1.distance == gbf2.distance) &&
(gbf1.knockout == gbf2.knockout) && (gbf1.quality == gbf2.quality) &&
ArrayUtil.equals(gbf1.ratios, gbf2.ratios) && (gbf1.strength == gbf2.strength) &&
(gbf1.type == gbf2.type);
case GradientGlowFilter:
var ggf1 :GradientGlowFilter = (f1 as GradientGlowFilter);
var ggf2 :GradientGlowFilter = (f2 as GradientGlowFilter);
return ArrayUtil.equals(ggf1.alphas, ggf2.alphas) && (ggf1.angle == ggf2.angle) &&
(ggf1.blurX == ggf2.blurX) && (ggf1.blurY == ggf2.blurY) &&
ArrayUtil.equals(ggf1.colors, ggf2.colors) && (ggf1.distance == ggf2.distance) &&
(ggf1.knockout == ggf2.knockout) && (ggf1.quality == ggf2.quality) &&
ArrayUtil.equals(ggf1.ratios, ggf2.ratios) && (ggf1.strength == ggf2.strength) &&
(ggf1.type == ggf2.type);
default:
throw new ArgumentError("OMG! Unknown filter type: " + c1);
}
}
protected static function checkArgs (disp :DisplayObject, filter :BitmapFilter) :void
{
if (disp == null || filter == null) {
throw new ArgumentError("args may not be null");
}
}
}
}
|
package com.threerings.flash {
import flash.display.DisplayObject;
import flash.filters.BevelFilter;
import flash.filters.BitmapFilter;
import flash.filters.BlurFilter;
import flash.filters.ColorMatrixFilter;
import flash.filters.ConvolutionFilter;
import flash.filters.DisplacementMapFilter;
import flash.filters.DropShadowFilter;
import flash.filters.GlowFilter;
import flash.filters.GradientBevelFilter;
import flash.filters.GradientGlowFilter;
import com.threerings.util.ArrayUtil;
import com.threerings.util.ClassUtil;
/**
* Useful utility methods that wouldn't be needed if the flash API were not so retarded.
*/
public class FilterUtil
{
/**
* Add the specified filter to the DisplayObject.
*/
public static function addFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts == null) {
filts = [];
}
filts.push(filter);
disp.filters = filts;
}
/**
* Remove the specified filter from the DisplayObject.
* Note that the filter set in the DisplayObject is a clone, so the values
* of the specified filter are used to find a match.
*/
public static function removeFilter (disp :DisplayObject, filter :BitmapFilter) :void
{
checkArgs(disp, filter);
var filts :Array = disp.filters;
if (filts != null) {
for (var ii :int = filts.length - 1; ii >= 0; ii--) {
var oldFilter :BitmapFilter = (filts[ii] as BitmapFilter);
if (equals(oldFilter, filter)) {
filts.splice(ii, 1);
if (filts.length == 0) {
filts = null;
}
disp.filters = filts;
return; // SUCCESS
}
}
}
}
/**
* Are the two filters equals?
*/
public static function equals (f1 :BitmapFilter, f2 :BitmapFilter) :Boolean
{
if (f1 === f2) { // catch same instance, or both null
return true;
} else if (f1 == null || f2 == null) { // otherwise nulls are no good
return false;
}
var c1 :Class = ClassUtil.getClass(f1);
if (c1 !== ClassUtil.getClass(f2)) {
return false;
}
// when we have two filters of the same class, figure it out by hand...
switch (c1) {
case BevelFilter:
var bf1 :BevelFilter = (f1 as BevelFilter);
var bf2 :BevelFilter = (f2 as BevelFilter);
return (bf1.angle == bf2.angle) && (bf1.blurX == bf2.blurX) &&
(bf1.blurY == bf2.blurY) && (bf1.distance == bf2.distance) &&
(bf1.highlightAlpha == bf2.highlightAlpha) &&
(bf1.highlightColor == bf2.highlightColor) && (bf1.knockout == bf2.knockout) &&
(bf1.quality == bf2.quality) && (bf1.shadowAlpha == bf2.shadowAlpha) &&
(bf1.shadowColor == bf2.shadowColor) && (bf1.strength == bf2.strength) &&
(bf1.type == bf2.type);
case BlurFilter:
var blur1 :BlurFilter = (f1 as BlurFilter);
var blur2 :BlurFilter = (f2 as BlurFilter);
return (blur1.blurX == blur2.blurX) && (blur1.blurY == blur2.blurY) &&
(blur1.quality == blur2.quality);
case ColorMatrixFilter:
var cmf1 :ColorMatrixFilter = (f1 as ColorMatrixFilter);
var cmf2 :ColorMatrixFilter = (f2 as ColorMatrixFilter);
return ArrayUtil.equals(cmf1.matrix, cmf2.matrix);
case ConvolutionFilter:
var cf1 :ConvolutionFilter = (f1 as ConvolutionFilter);
var cf2 :ConvolutionFilter = (f2 as ConvolutionFilter);
return (cf1.alpha == cf2.alpha) && (cf1.bias == cf2.bias) && (cf1.clamp == cf2.clamp) &&
(cf1.color == cf2.color) && (cf1.divisor == cf2.divisor) &&
ArrayUtil.equals(cf1.matrix, cf2.matrix) && (cf1.matrixX == cf2.matrixX) &&
(cf1.matrixY == cf2.matrixY) && (cf1.preserveAlpha == cf2.preserveAlpha);
case DisplacementMapFilter:
var dmf1 :DisplacementMapFilter = (f1 as DisplacementMapFilter);
var dmf2 :DisplacementMapFilter = (f2 as DisplacementMapFilter);
return (dmf1.alpha == dmf2.alpha) && (dmf1.color == dmf2.color) &&
(dmf1.componentX == dmf2.componentX) && (dmf1.componentY == dmf2.componentY) &&
(dmf1.mapBitmap == dmf2.mapBitmap) && dmf1.mapPoint.equals(dmf2.mapPoint) &&
(dmf1.mode == dmf2.mode) && (dmf1.scaleX == dmf2.scaleX) &&
(dmf1.scaleY == dmf2.scaleY);
case DropShadowFilter:
var dsf1 :DropShadowFilter = (f1 as DropShadowFilter);
var dsf2 :DropShadowFilter = (f2 as DropShadowFilter);
return (dsf1.alpha == dsf2.alpha) && (dsf1.angle = dsf2.angle) &&
(dsf1.blurX = dsf2.blurX) && (dsf1.blurY = dsf2.blurY) &&
(dsf1.color = dsf2.color) && (dsf1.distance = dsf2.distance) &&
(dsf1.hideObject = dsf2.hideObject) && (dsf1.inner = dsf2.inner) &&
(dsf1.knockout = dsf2.knockout) && (dsf1.quality = dsf2.quality) &&
(dsf1.strength = dsf2.strength);
case GlowFilter:
var gf1 :GlowFilter = (f1 as GlowFilter);
var gf2 :GlowFilter = (f2 as GlowFilter);
return (gf1.alpha == gf2.alpha) && (gf1.blurX == gf2.blurX) &&
(gf1.blurY == gf2.blurY) && (gf1.color == gf2.color) && (gf1.inner == gf2.inner) &&
(gf1.knockout == gf2.knockout) && (gf1.quality == gf2.quality) &&
(gf1.strength == gf2.strength);
case GradientBevelFilter:
var gbf1 :GradientBevelFilter = (f1 as GradientBevelFilter);
var gbf2 :GradientBevelFilter = (f2 as GradientBevelFilter);
return ArrayUtil.equals(gbf1.alphas, gbf2.alphas) && (gbf1.angle == gbf2.angle) &&
(gbf1.blurX == gbf2.blurX) && (gbf1.blurY == gbf2.blurY) &&
ArrayUtil.equals(gbf1.colors, gbf2.colors) && (gbf1.distance == gbf2.distance) &&
(gbf1.knockout == gbf2.knockout) && (gbf1.quality == gbf2.quality) &&
ArrayUtil.equals(gbf1.ratios, gbf2.ratios) && (gbf1.strength == gbf2.strength) &&
(gbf1.type == gbf2.type);
case GradientGlowFilter:
var ggf1 :GradientGlowFilter = (f1 as GradientGlowFilter);
var ggf2 :GradientGlowFilter = (f2 as GradientGlowFilter);
return ArrayUtil.equals(ggf1.alphas, ggf2.alphas) && (ggf1.angle == ggf2.angle) &&
(ggf1.blurX == ggf2.blurX) && (ggf1.blurY == ggf2.blurY) &&
ArrayUtil.equals(ggf1.colors, ggf2.colors) && (ggf1.distance == ggf2.distance) &&
(ggf1.knockout == ggf2.knockout) && (ggf1.quality == ggf2.quality) &&
ArrayUtil.equals(ggf1.ratios, ggf2.ratios) && (ggf1.strength == ggf2.strength) &&
(ggf1.type == ggf2.type);
default:
throw new ArgumentError("OMG! Unknown filter type: " + c1);
}
}
/**
* Shift the color matrix filter by the given amount. This is adapted from the code found at
* http://www.kirupa.com/forum/showthread.php?t=230706
*/
public static function shiftHueBy (original :ColorMatrixFilter,
hueShift :int) :ColorMatrixFilter
{
var M1 :Array = [ 0.213, 0.715, 0.072,
0.213, 0.715, 0.072,
0.213, 0.715, 0.072 ];
var M2 :Array = [ 0.787, -0.715, -0.072,
-0.212, 0.285, -0.072,
-0.213, -0.715, 0.928 ];
var M3 :Array = [-0.213, -0.715, 0.928,
0.143, 0.140, -0.283,
-0.787, 0.715, 0.072 ];
var M4 :Array = add(M1, add(multiply(Math.cos(hueShift * Math.PI / 180), M2),
multiply(Math.sin(hueShift * Math.PI / 180), M3)));
var originalMatrix :Array = original.matrix;
if (originalMatrix == null) {
originalMatrix = original.matrix;
}
return new ColorMatrixFilter(concat(originalMatrix, [ M4[0], M4[1], M4[2], 0, 0,
M4[3], M4[4], M4[5], 0, 0,
M4[6], M4[7], M4[8], 0, 0,
0, 0, 0, 1, 0 ]));
}
protected static function checkArgs (disp :DisplayObject, filter :BitmapFilter) :void
{
if (disp == null || filter == null) {
throw new ArgumentError("args may not be null");
}
}
protected static function identity () :Array
{
return [ 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0 ];
}
protected static function add (A :Array, B :Array) :Array
{
var C :Array = [];
for(var ii :int = 0; ii < A.length; ii++)
{
C.push( A[ii] + B[ii] );
}
return C;
}
protected static function multiply(x :Number, B :Array) :Array
{
var A :Array = [];
for each (var n :Number in B)
{
A.push(x * n);
}
return A;
}
protected static function concat(A :Array, B :Array) :Array
{
var nM :Array = [];
nM[0] = (A[0] * B[0]) + (A[1] * B[5]) + (A[2] * B[10]) + (A[3] * B[15]);
nM[1] = (A[0] * B[1]) + (A[1] * B[6]) + (A[2] * B[11]) + (A[3] * B[16]);
nM[2] = (A[0] * B[2]) + (A[1] * B[7]) + (A[2] * B[12]) + (A[3] * B[17]);
nM[3] = (A[0] * B[3]) + (A[1] * B[8]) + (A[2] * B[13]) + (A[3] * B[18]);
nM[4] = (A[0] * B[4]) + (A[1] * B[9]) + (A[2] * B[14]) + (A[3] * B[19]) + A[4];
nM[5] = (A[5] * B[0]) + (A[6] * B[5]) + (A[7] * B[10]) + (A[8] * B[15]);
nM[6] = (A[5] * B[1]) + (A[6] * B[6]) + (A[7] * B[11]) + (A[8] * B[16]);
nM[7] = (A[5] * B[2]) + (A[6] * B[7]) + (A[7] * B[12]) + (A[8] * B[17]);
nM[8] = (A[5] * B[3]) + (A[6] * B[8]) + (A[7] * B[13]) + (A[8] * B[18]);
nM[9] = (A[5] * B[4]) + (A[6] * B[9]) + (A[7] * B[14]) + (A[8] * B[19]) + A[9];
nM[10] = (A[10] * B[0]) + (A[11] * B[5]) + (A[12] * B[10]) + (A[13] * B[15]);
nM[11] = (A[10] * B[1]) + (A[11] * B[6]) + (A[12] * B[11]) + (A[13] * B[16]);
nM[12] = (A[10] * B[2]) + (A[11] * B[7]) + (A[12] * B[12]) + (A[13] * B[17]);
nM[13] = (A[10] * B[3]) + (A[11] * B[8]) + (A[12] * B[13]) + (A[13] * B[18]);
nM[14] = (A[10] * B[4]) + (A[11] * B[9]) + (A[12] * B[14]) + (A[13] * B[19]) + A[14];
nM[15] = (A[15] * B[0]) + (A[16] * B[5]) + (A[17] * B[10]) + (A[18] * B[15]);
nM[16] = (A[15] * B[1]) + (A[16] * B[6]) + (A[17] * B[11]) + (A[18] * B[16]);
nM[17] = (A[15] * B[2]) + (A[16] * B[7]) + (A[17] * B[12]) + (A[18] * B[17]);
nM[18] = (A[15] * B[3]) + (A[16] * B[8]) + (A[17] * B[13]) + (A[18] * B[18]);
nM[19] = (A[15] * B[4]) + (A[16] * B[9]) + (A[17] * B[14]) + (A[18] * B[19]) + A[19];
return nM;
}
}
}
|
bring the functionality from UD's HueFilter into FilterUtil. I need to test this with UD to make sure it works, and then these matrix functions should probably be put into a separate lib class (perhaps a new narya com.threerings.util.Matrix?)
|
bring the functionality from UD's HueFilter into FilterUtil. I need to test this with UD to make
sure it works, and then these matrix functions should probably be put into a separate lib class
(perhaps a new narya com.threerings.util.Matrix?)
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@203 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
2a5d2c8cf2c382424f85e921a416ee471bef42df
|
WEB-INF/lps/lfc/kernel/swf9/LzHTTPLoader.as
|
WEB-INF/lps/lfc/kernel/swf9/LzHTTPLoader.as
|
/**
* LzHTTPLoader.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @affects lzloader
*/
public class LzHTTPLoader {
#passthrough (toplevel:true) {
import flash.events.*;
import flash.net.*;
import flash.utils.*;
import flash.xml.*;
}#
// holds list of outstanding data requests, to handle timeouts
static const activeRequests :Object = {};
static var loaderIDCounter :uint = 0;
const owner:*;
const __loaderid:uint;
var __abort:Boolean = false;
var __timeout:Boolean = false;
var gstart:Number;
var secure:Boolean;
var options:Object;
// Default infinite timeout
var timeout:Number = Infinity;
var requestheaders:Object;
var requestmethod:String;
var requesturl:String;
var responseText:String;
var responseXML:XML = null;
// The URLLoader object
var loader:URLLoader = null;
var dataRequest:LzDataRequest = null;
static const GET_METHOD:String = "GET";
static const POST_METHOD:String = "POST";
static const PUT_METHOD:String = "PUT";
static const DELETE_METHOD:String = "DELETE";
public function LzHTTPLoader (owner:*, proxied:Boolean) {
this.owner = owner;
this.options = {parsexml: true};
this.requestheaders = {};
this.requestmethod = LzHTTPLoader.GET_METHOD;
this.__loaderid = LzHTTPLoader.loaderIDCounter++;
}
// Default callback handlers
public var loadSuccess:Function = function (...data) { trace('loadSuccess callback not defined on', this); }
public var loadError:Function = function (...data) { trace('loadError callback not defined on', this); };
public var loadTimeout:Function = function (...data) { trace('loadTimeout callback not defined on', this); };
/* Returns the response as a string */
public function getResponse () :String {
return this.responseText;
}
/* Returns numeric status code (200, 404, 500, etc...) */
public function getResponseStatus () :int {
// nyi - only available in IE, see doc: flash.events.HTTPStatusEvent#status
return 0;
}
/* Returns an array of response headers */
public function getResponseHeaders () :Array {
// There seems to be no way to get response headers in the flash.net URLLoader API
// flash.events.HTTPStatusEvent docs say response headers are AIR-only
return null;
}
/* @param Object obj: A hash table of headers for the HTTP request
@access public
*/
public function setRequestHeaders (obj:Object) :void {
this.requestheaders = obj;
}
/* @param String key: HTTP request header name
@param String val: header value
@access public
*/
public function setRequestHeader (key:String, val:String) :void {
this.requestheaders[key] = val;
}
public function abort () :void {
if (this.loader) {
this.__abort = true;
this.loader.close();
this.loader = null;
this.removeTimeout(this);
}
}
/* @public */
public function setOption (key:String, val:*) :void {
this.options[key] = val;
}
/* @public */
public function setProxied (proxied:Boolean) :void {
this.setOption('proxied', proxied);
}
/* @public
*/
public function setQueryParams (qparams) :void {
}
/* @public
*/
public function setQueryString (qstring) :void {
}
/*
If queueRequests is true, subsequent requests will made sequentially
If queueRequests is false, subsequent requests will interrupt requests already in process
*/
public function setQueueing (queuing:Boolean) :void {
this.setOption('queuing', queuing);
// [todo hqm 2006-07] NYI
}
public function getResponseHeader (key:String) :String {
// There seems to be no way to get response headers in the flash.net URLLoader API
trace('getResponseHeader not implemented in swf9');
return null;
}
// headers can be a hashtable or null
public function open (method:String, url:String, username:String = null, password:String = null) :void {
if (this.loader) {
Debug.warn("pending request for id=%s", this.__loaderid);
}
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
this.__abort = false;
this.__timeout = false;
this.requesturl = url;
this.requestmethod = method;
}
// @access public
// @param String url: url, including query args
// @param String reqtype: 'POST' or 'GET'
// @param Object headers: hash table of HTTP request headers
public function makeProxiedURL( proxyurl:String,
url:String,
httpmethod:String,
lzt:String,
headers:Object,
postbody:String):String {
var params:Object = {
sendheaders: this.options.sendheaders,
trimwhitespace: this.options.trimwhitespace,
nsprefix: this.options.nsprefix,
timeout: this.timeout,
cache: this.options.cacheable,
ccache: this.options.ccache,
proxyurl: proxyurl,
url: url,
secure: this.secure,
postbody: postbody,
headers: headers,
httpmethod: httpmethod,
service: lzt
};
return lz.Browser.makeProxiedURL(params);
}
public function setTimeout (timeout:Number) :void {
this.timeout = timeout;
// [todo hqm 2006-07] Should we have an API method for setting LzLoader timeout?
}
// Set up a pending timeout for a loader.
/*
LzHTTPLoader.prototype.setupTimeout = function (obj, duration) {
var endtime = (new Date()).getTime() + duration;
LzHTTPLoader.activeRequests.push(obj, endtime);
setTimeout("LzHTTPLoader.__LZcheckXMLHTTPTimeouts()", duration);
}
*/
public function setupTimeout (obj:LzHTTPLoader, duration:Number) :void {
var endtime:Number = (new Date()).getTime() + duration;
//obj.__loaderid = LzHTTPLoader.loaderIDCounter++;//uncomment to give LzHTTPLoader-instance a new loader-id
var lid:uint = obj.__loaderid;
LzHTTPLoader.activeRequests[lid] = [obj, endtime];
var callback:Function = function () {
LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid);
}
var timeoutid:uint = flash.utils.setTimeout(callback, duration);
LzHTTPLoader.activeRequests[lid][2] = timeoutid;
}
// Remove a loader from the timeouts list.
public function removeTimeout (target:LzHTTPLoader) :void {
var lid:uint = target.__loaderid;
//Debug.write("remove timeout for id=%s", lid);
var reqarr:Array = LzHTTPLoader.activeRequests[lid];
if (reqarr && reqarr[0] === target) {
clearTimeout(reqarr[2]);
delete LzHTTPLoader.activeRequests[lid];
}
}
// Check if any outstanding requests have timed out.
static function __LZcheckXMLHTTPTimeouts (lid) :void {
var req:Array = LzHTTPLoader.activeRequests[lid];
if (req) {
var now:Number = (new Date()).getTime();
var httploader:LzHTTPLoader = req[0];
var dstimeout:Number = req[1];
//Debug.write("diff %d", now - dstimeout);
if (now >= dstimeout) {
//Debug.write("timeout for %s", lid);
delete LzHTTPLoader.activeRequests[lid];
httploader.__timeout = true;
httploader.abort();
httploader.loadTimeout(httploader, null);
} else {
// if it hasn't timed out, add it back to the list for the future
//Debug.write("recheck timeout");
var callback:Function = function () {
LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid);
}
var timeoutid:uint = flash.utils.setTimeout(callback, now - dstimeout);
req[2] = timeoutid;
}
}
}
public function getElapsedTime () :Number {
return ((new Date()).getTime() - this.gstart);
}
public function send (content:String = null) :void {
this.loadXMLDoc(/* method */ this.requestmethod,
/* url */ this.requesturl,
/* headers */ this.requestheaders,
/* postbody */ content,
/* ignorewhite */ true);
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void {
// trace("completeHandler: " + event + ", target = " + event.target);
if (event.target is URLLoader) {
// trace("completeHandler: " , this, loader);
//trace("completeHandler: bytesLoaded" , loader.bytesLoaded, 'bytesTotal', loader.bytesTotal);
//trace('typeof data:', typeof(loader.data), loader.data.length, 'parsexml=', options.parsexml);
responseText = loader.data;
var lzxdata:LzDataElementMixin = null;
removeTimeout(this);
// Parse data into flash native XML and then convert to LFC LzDataElement tree
try {
if (responseText != null && options.parsexml) {
// This is almost identical to LzXMLParser.parseXML()
// except ignoreWhitespace comes from options
XML.ignoreWhitespace = options.trimwhitespace;
this.responseXML = XML(responseText);
this.responseXML.normalize();
lzxdata = LzXMLTranslator.copyXML(this.responseXML,
options.trimwhitespace,
options.nsprefix);
}
} catch (err) {
trace("caught error parsing xml", err);
loader = null;
loadError(this, null);
return;
}
loader = null;
loadSuccess(this, lzxdata);
}
}
private function openHandler(event:Event):void {
trace("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
removeTimeout(this);
loader = null;
loadError(this, null);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
removeTimeout(this);
loader = null;
loadError(this, null);
}
// public
// parseXML flag : if true, translate native XML tree into LzDataNode tree,
// if false, don't attempt to translate the XML (if it exists)
public function loadXMLDoc (method:String, url:String, headers:Object, postbody:String, ignorewhite:Boolean) :void {
if (this.loader == null) {
// TODO [hqm 2008-01] wonder if we should be throwing an
// exception or returning some indication that the send
// did not execute? XMLHttpRequest doesn't return
// anything, but we could... or maybe at least a debugger
// message?
if ($debug) {
Debug.write("LzHTTPLoader.send, no request to send to, has open() been called?");
}
return;
}
configureListeners(this.loader);
var request:URLRequest = new URLRequest(url);
request.data = postbody;
request.method = (method == LzHTTPLoader.GET_METHOD) ? URLRequestMethod.GET : URLRequestMethod.POST;
var contentType:Boolean = false;
var rhArray:Array = new Array();
for (var k:String in headers) {
request.requestHeaders.push(new URLRequestHeader(k, headers[k]));
if (k.toLowerCase() == "content-type") {
contentType = true;
}
}
// If no content-type for POST was explicitly specified,
// use "application/x-www-form-urlencoded"
if ((method == "POST") && !contentType) {
request.requestHeaders.push(
new URLRequestHeader('Content-Type', 'application/x-www-form-urlencoded'));
}
try {
loader.load(request);
// Set up the timeout
if (isFinite(this.timeout)) {
this.setupTimeout(this, this.timeout);
}
} catch (error) {
// TODO [hqm 2008-01] make this send appropriate error event to listener,
// and abort the load.
trace("Unable to load requested document.", error);
}
}
}
////////////////////////////////////////////////////////////////
// swf-specific stuff
/*
Event Summary Defined By
complete
Dispatched after all the received data is decoded and placed in the data property of the URLLoader object.
httpStatus
Dispatched if a call to URLLoader.load() attempts to access data over HTTP and the current Flash Player environment is able to detect and return the status code for the request. URLLoader
ioError
Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download. URLLoader
open
Dispatched when the download operation commences following a call to the URLLoader.load() method. URLLoader
progress
Dispatched when data is received as the download operation progresses. URLLoader
securityError
Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox. URLLoader
*/
/*
URLLoaderDataFormat.TEXT
*/
|
/**
* LzHTTPLoader.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @affects lzloader
*/
public class LzHTTPLoader {
#passthrough (toplevel:true) {
import flash.events.*;
import flash.net.*;
import flash.utils.*;
import flash.xml.*;
}#
// holds list of outstanding data requests, to handle timeouts
static const activeRequests :Object = {};
static var loaderIDCounter :uint = 0;
const owner:*;
const __loaderid:uint;
var __abort:Boolean = false;
var __timeout:Boolean = false;
var gstart:Number;
var secure:Boolean;
var options:Object;
// Default infinite timeout
var timeout:Number = Infinity;
var requestheaders:Object;
var requestmethod:String;
var requesturl:String;
var responseText:String;
var responseXML:XML = null;
// The URLLoader object
var loader:URLLoader = null;
var dataRequest:LzDataRequest = null;
static const GET_METHOD:String = "GET";
static const POST_METHOD:String = "POST";
static const PUT_METHOD:String = "PUT";
static const DELETE_METHOD:String = "DELETE";
public function LzHTTPLoader (owner:*, proxied:Boolean) {
this.owner = owner;
this.options = {parsexml: true};
this.requestheaders = {};
this.requestmethod = LzHTTPLoader.GET_METHOD;
this.__loaderid = LzHTTPLoader.loaderIDCounter++;
}
// Default callback handlers
public var loadSuccess:Function = function (...data) { trace('loadSuccess callback not defined on', this); }
public var loadError:Function = function (...data) { trace('loadError callback not defined on', this); };
public var loadTimeout:Function = function (...data) { trace('loadTimeout callback not defined on', this); };
/* Returns the response as a string */
public function getResponse () :String {
return this.responseText;
}
/* Returns numeric status code (200, 404, 500, etc...) */
public function getResponseStatus () :int {
// nyi - only available in IE, see doc: flash.events.HTTPStatusEvent#status
return 0;
}
/* Returns an array of response headers */
public function getResponseHeaders () :Array {
// There seems to be no way to get response headers in the flash.net URLLoader API
// flash.events.HTTPStatusEvent docs say response headers are AIR-only
return null;
}
/* @param Object obj: A hash table of headers for the HTTP request
@access public
*/
public function setRequestHeaders (obj:Object) :void {
this.requestheaders = obj;
}
/* @param String key: HTTP request header name
@param String val: header value
@access public
*/
public function setRequestHeader (key:String, val:String) :void {
this.requestheaders[key] = val;
}
public function abort () :void {
if (this.loader) {
this.__abort = true;
this.loader.close();
this.loader = null;
this.removeTimeout(this);
}
}
/* @public */
public function setOption (key:String, val:*) :void {
this.options[key] = val;
}
/* @public */
public function setProxied (proxied:Boolean) :void {
this.setOption('proxied', proxied);
}
/* @public
*/
public function setQueryParams (qparams) :void {
}
/* @public
*/
public function setQueryString (qstring) :void {
}
/*
If queueRequests is true, subsequent requests will made sequentially
If queueRequests is false, subsequent requests will interrupt requests already in process
*/
public function setQueueing (queuing:Boolean) :void {
this.setOption('queuing', queuing);
// [todo hqm 2006-07] NYI
}
public function getResponseHeader (key:String) :String {
// There seems to be no way to get response headers in the flash.net URLLoader API
trace('getResponseHeader not implemented in swf9');
return null;
}
// headers can be a hashtable or null
public function open (method:String, url:String, username:String = null, password:String = null) :void {
if (this.loader) {
Debug.warn("pending request for id=%s", this.__loaderid);
}
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
this.__abort = false;
this.__timeout = false;
this.requesturl = url;
this.requestmethod = method;
}
// @access public
// @param String url: url, including query args
// @param String reqtype: 'POST' or 'GET'
// @param Object headers: hash table of HTTP request headers
public function makeProxiedURL( proxyurl:String,
url:String,
httpmethod:String,
lzt:String,
headers:Object,
postbody:String):String {
var params:Object = {
sendheaders: this.options.sendheaders,
trimwhitespace: this.options.trimwhitespace,
nsprefix: this.options.nsprefix,
timeout: this.timeout,
cache: this.options.cacheable,
ccache: this.options.ccache,
proxyurl: proxyurl,
url: url,
secure: this.secure,
postbody: postbody,
headers: headers,
httpmethod: httpmethod,
service: lzt
};
return lz.Browser.makeProxiedURL(params);
}
public function setTimeout (timeout:Number) :void {
this.timeout = timeout;
// [todo hqm 2006-07] Should we have an API method for setting LzLoader timeout?
}
// Set up a pending timeout for a loader.
/*
LzHTTPLoader.prototype.setupTimeout = function (obj, duration) {
var endtime = (new Date()).getTime() + duration;
LzHTTPLoader.activeRequests.push(obj, endtime);
setTimeout("LzHTTPLoader.__LZcheckXMLHTTPTimeouts()", duration);
}
*/
public function setupTimeout (obj:LzHTTPLoader, duration:Number) :void {
var endtime:Number = (new Date()).getTime() + duration;
//obj.__loaderid = LzHTTPLoader.loaderIDCounter++;//uncomment to give LzHTTPLoader-instance a new loader-id
var lid:uint = obj.__loaderid;
LzHTTPLoader.activeRequests[lid] = [obj, endtime];
var callback:Function = function () {
LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid);
}
var timeoutid:uint = flash.utils.setTimeout(callback, duration);
LzHTTPLoader.activeRequests[lid][2] = timeoutid;
}
// Remove a loader from the timeouts list.
public function removeTimeout (target:LzHTTPLoader) :void {
var lid:uint = target.__loaderid;
//Debug.write("remove timeout for id=%s", lid);
var reqarr:Array = LzHTTPLoader.activeRequests[lid];
if (reqarr && reqarr[0] === target) {
clearTimeout(reqarr[2]);
delete LzHTTPLoader.activeRequests[lid];
}
}
// Check if any outstanding requests have timed out.
static function __LZcheckXMLHTTPTimeouts (lid) :void {
var req:Array = LzHTTPLoader.activeRequests[lid];
if (req) {
var now:Number = (new Date()).getTime();
var httploader:LzHTTPLoader = req[0];
var dstimeout:Number = req[1];
//Debug.write("diff %d", now - dstimeout);
if (now >= dstimeout) {
//Debug.write("timeout for %s", lid);
delete LzHTTPLoader.activeRequests[lid];
httploader.__timeout = true;
httploader.abort();
httploader.loadTimeout(httploader, null);
} else {
// if it hasn't timed out, add it back to the list for the future
//Debug.write("recheck timeout");
var callback:Function = function () {
LzHTTPLoader.__LZcheckXMLHTTPTimeouts(lid);
}
var timeoutid:uint = flash.utils.setTimeout(callback, now - dstimeout);
req[2] = timeoutid;
}
}
}
public function getElapsedTime () :Number {
return ((new Date()).getTime() - this.gstart);
}
public function send (content:String = null) :void {
this.loadXMLDoc(/* method */ this.requestmethod,
/* url */ this.requesturl,
/* headers */ this.requestheaders,
/* postbody */ content,
/* ignorewhite */ true);
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void {
// trace("completeHandler: " + event + ", target = " + event.target);
if (event.target is URLLoader) {
// trace("completeHandler: " , this, loader);
//trace("completeHandler: bytesLoaded" , loader.bytesLoaded, 'bytesTotal', loader.bytesTotal);
//trace('typeof data:', typeof(loader.data), loader.data.length, 'parsexml=', options.parsexml);
responseText = loader.data;
var lzxdata:LzDataElementMixin = null;
removeTimeout(this);
// Parse data into flash native XML and then convert to LFC LzDataElement tree
try {
if (responseText != null && options.parsexml) {
// This is almost identical to LzXMLParser.parseXML()
// except ignoreWhitespace comes from options
XML.ignoreWhitespace = options.trimwhitespace;
this.responseXML = XML(responseText);
this.responseXML.normalize();
lzxdata = LzXMLTranslator.copyXML(this.responseXML,
options.trimwhitespace,
options.nsprefix);
}
} catch (err) {
trace("caught error parsing xml", err);
loader = null;
loadError(this, null);
return;
}
loader = null;
loadSuccess(this, lzxdata);
}
}
private function openHandler(event:Event):void {
trace("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
trace("securityErrorHandler: " + event);
removeTimeout(this);
loader = null;
loadError(this, null);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
removeTimeout(this);
loader = null;
loadError(this, null);
}
// public
// parseXML flag : if true, translate native XML tree into LzDataNode tree,
// if false, don't attempt to translate the XML (if it exists)
public function loadXMLDoc (method:String, url:String, headers:Object, postbody:String, ignorewhite:Boolean) :void {
var secure:Boolean = (url.indexOf("https:") == 0);
url = lz.Browser.toAbsoluteURL( url, secure );
if (this.loader == null) {
// TODO [hqm 2008-01] wonder if we should be throwing an
// exception or returning some indication that the send
// did not execute? XMLHttpRequest doesn't return
// anything, but we could... or maybe at least a debugger
// message?
if ($debug) {
Debug.write("LzHTTPLoader.send, no request to send to, has open() been called?");
}
return;
}
configureListeners(this.loader);
var request:URLRequest = new URLRequest(url);
request.data = postbody;
request.method = (method == LzHTTPLoader.GET_METHOD) ? URLRequestMethod.GET : URLRequestMethod.POST;
var contentType:Boolean = false;
var rhArray:Array = new Array();
for (var k:String in headers) {
request.requestHeaders.push(new URLRequestHeader(k, headers[k]));
if (k.toLowerCase() == "content-type") {
contentType = true;
}
}
// If no content-type for POST was explicitly specified,
// use "application/x-www-form-urlencoded"
if ((method == "POST") && !contentType) {
request.requestHeaders.push(
new URLRequestHeader('Content-Type', 'application/x-www-form-urlencoded'));
}
try {
loader.load(request);
// Set up the timeout
if (isFinite(this.timeout)) {
this.setupTimeout(this, this.timeout);
}
} catch (error) {
// TODO [hqm 2008-01] make this send appropriate error event to listener,
// and abort the load.
trace("Unable to load requested document.", error);
}
}
}
////////////////////////////////////////////////////////////////
// swf-specific stuff
/*
Event Summary Defined By
complete
Dispatched after all the received data is decoded and placed in the data property of the URLLoader object.
httpStatus
Dispatched if a call to URLLoader.load() attempts to access data over HTTP and the current Flash Player environment is able to detect and return the status code for the request. URLLoader
ioError
Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download. URLLoader
open
Dispatched when the download operation commences following a call to the URLLoader.load() method. URLLoader
progress
Dispatched when data is received as the download operation progresses. URLLoader
securityError
Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox. URLLoader
*/
/*
URLLoaderDataFormat.TEXT
*/
|
Change 20080714-hqm-V by [email protected] on 2008-07-14 21:40:34 EDT in /Users/hqm/openlaszlo/trunk4 for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080714-hqm-V by [email protected] on 2008-07-14 21:40:34 EDT
in /Users/hqm/openlaszlo/trunk4
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: ensure SOLO data loads are done with absolute URLs
New Features:
Bugs Fixed:
Technical Reviewer: pbr
QA Reviewer: max
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
+ when loading a data URL, use an absolute URL, as relative URLs will
confuse the Flash security rules
Tests:
test/lfc/data/alldata.lzx (fails in other way, but no longer reports
security errors in loading http)
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@10364 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
8745a94d0d6885db01aad1eb31df73b262612cf1
|
examples/LanguageTests/src/LanguageTests.as
|
examples/LanguageTests/src/LanguageTests.as
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
import flash.display.Sprite;
import classes.B;
import interfaces.IA;
import interfaces.IB;
import interfaces.IC;
import interfaces.ID;
import interfaces.IE;
import interfaces.IF;
public class LanguageTests extends Sprite implements IA, IE
{
public function LanguageTests()
{
var testResult:Boolean;
var testObject:Object;
var b:B = new B();
testResult = this instanceof Sprite;
trace('this instanceof Sprite - true: ' + testResult.toString());
testResult = this instanceof B;
trace('this instanceof classes.B - false: ' + testResult.toString());
testResult = b instanceof classes.B;
trace('b instanceof classes.B - true: ' + testResult.toString());
testResult = b instanceof classes.C;
trace('b instanceof classes.C - true: ' + testResult.toString());
testResult = b instanceof interfaces.IC;
trace('b instanceof interfaces.IC - false: ' + testResult.toString());
testResult = b instanceof interfaces.IF;
trace('b instanceof interfaces.IF - false: ' + testResult.toString());
testResult = this instanceof IA;
trace('this instanceof interfaces.IA - false: ' + testResult.toString());
testResult = this instanceof IB;
trace('this instanceof interfaces.IB - false: ' + testResult.toString());
testResult = this instanceof IC;
trace('this instanceof interfaces.IC - false: ' + testResult.toString());
testResult = this instanceof ID;
trace('this instanceof interfaces.ID - false: ' + testResult.toString());
testResult = this instanceof IE;
trace('this instanceof interfaces.IE - false: ' + testResult.toString());
trace();
testResult = this is Sprite;
trace('this is Sprite - true: ' + testResult.toString());
testResult = this is B;
trace('this is classes.B - false: ' + testResult.toString());
testResult = b is classes.B;
trace('b is classes.B - true: ' + testResult.toString());
testResult = b is classes.C;
trace('b is classes.C - true: ' + testResult.toString());
testResult = b is interfaces.IC;
trace('b is interfaces.IC - false: ' + testResult.toString());
testResult = b is interfaces.IF;
trace('b is interfaces.IF - true: ' + testResult.toString());
testResult = this is IA;
trace('this is interfaces.IA - true: ' + testResult.toString());
testResult = this is IB;
trace('this is interfaces.IB - false: ' + testResult.toString());
testResult = this is IC;
trace('this is interfaces.IC - true: ' + testResult.toString());
testResult = this is ID;
trace('this is interfaces.ID - true: ' + testResult.toString());
testResult = this is IE;
trace('this is interfaces.IE - true: ' + testResult.toString());
trace();
testObject = (this as Sprite) ? this as Sprite : 'null';
trace('this as Sprite - [object ...]: ' + testObject.toString());
testObject = (this as B) ? this as B : 'null';
trace('this as classes.B - null: ' + testObject.toString());
testObject = (b as classes.B) ? b as classes.B : 'null';
trace('b as classes.B - [object ...]: ' + testObject.toString());
testObject = (b as classes.C) ? b as classes.C : 'null';
trace('b as classes.C - [object ...]: ' + testObject.toString());
testObject = (b as interfaces.IC) ? b as interfaces.IC : 'null';
trace('b as interfaces.IC - null: ' + testObject.toString());
testObject = (b as interfaces.IF) ? b as interfaces.IF : 'null';
trace('b as interfaces.IF - [object ...]: ' + testObject.toString());
testObject = (this as IA) ? this as IA : 'null';
trace('this as interfaces.IA - [object ...]: ' + testObject.toString());
testObject = (this as IB) ? this as IB : 'null';
trace('this as interfaces.IB - null: ' + testObject.toString());
testObject = (this as IC) ? this as IC : 'null';
trace('this as interfaces.IC - [object ...]: ' + testObject.toString());
testObject = (this as ID) ? this as ID : 'null';
trace('this as interfaces.ID - [object ...]: ' + testObject.toString());
testObject = (this as IE) ? this as IE : 'null';
trace('this as interfaces.IE - [object ...]: ' + testObject.toString());
trace();
try {
testObject = Sprite(this);
trace('Sprite(this) - [object ...]: ' + testObject.toString());
} catch (e:Error)
{
trace("This shouldn't show!");
}
try {
testObject = B(this);
trace("This shouldn't show!");
} catch (e:Error)
{
trace('B(this) - exception expected: ' + e.message);
}
try {
testObject = interfaces.IC(b);
trace("This shouldn't show!");
} catch (e:Error)
{
trace('IC(b) - exception expected: ' + e.message);
}
try {
testObject = interfaces.IF(b);
trace('IF(b) - [object ...]: ' + testObject.toString());
} catch (e:Error)
{
trace("This shouldn't show!");
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
import flash.display.Sprite;
import classes.B;
import interfaces.IA;
import interfaces.IB;
import interfaces.IC;
import interfaces.ID;
import interfaces.IE;
import interfaces.IF;
public class LanguageTests extends Sprite implements IA, IE
{
public function LanguageTests()
{
var testResult:Boolean;
var testObject:Object;
var b:B = new B();
testResult = this is Sprite;
trace('this is Sprite - true: ' + testResult.toString());
testResult = this is B;
trace('this is classes.B - false: ' + testResult.toString());
testResult = b is classes.B;
trace('b is classes.B - true: ' + testResult.toString());
testResult = b is classes.C;
trace('b is classes.C - true: ' + testResult.toString());
testResult = b is interfaces.IC;
trace('b is interfaces.IC - false: ' + testResult.toString());
testResult = b is interfaces.IF;
trace('b is interfaces.IF - false: ' + testResult.toString());
testResult = this is IA;
trace('this is interfaces.IA - false: ' + testResult.toString());
testResult = this is IB;
trace('this is interfaces.IB - false: ' + testResult.toString());
testResult = this is IC;
trace('this is interfaces.IC - false: ' + testResult.toString());
testResult = this is ID;
trace('this is interfaces.ID - false: ' + testResult.toString());
testResult = this is IE;
trace('this is interfaces.IE - false: ' + testResult.toString());
trace();
testResult = this is Sprite;
trace('this is Sprite - true: ' + testResult.toString());
testResult = this is B;
trace('this is classes.B - false: ' + testResult.toString());
testResult = b is classes.B;
trace('b is classes.B - true: ' + testResult.toString());
testResult = b is classes.C;
trace('b is classes.C - true: ' + testResult.toString());
testResult = b is interfaces.IC;
trace('b is interfaces.IC - false: ' + testResult.toString());
testResult = b is interfaces.IF;
trace('b is interfaces.IF - true: ' + testResult.toString());
testResult = this is IA;
trace('this is interfaces.IA - true: ' + testResult.toString());
testResult = this is IB;
trace('this is interfaces.IB - false: ' + testResult.toString());
testResult = this is IC;
trace('this is interfaces.IC - true: ' + testResult.toString());
testResult = this is ID;
trace('this is interfaces.ID - true: ' + testResult.toString());
testResult = this is IE;
trace('this is interfaces.IE - true: ' + testResult.toString());
trace();
testObject = (this as Sprite) ? this as Sprite : 'null';
trace('this as Sprite - [object ...]: ' + testObject.toString());
testObject = (this as B) ? this as B : 'null';
trace('this as classes.B - null: ' + testObject.toString());
testObject = (b as classes.B) ? b as classes.B : 'null';
trace('b as classes.B - [object ...]: ' + testObject.toString());
testObject = (b as classes.C) ? b as classes.C : 'null';
trace('b as classes.C - [object ...]: ' + testObject.toString());
testObject = (b as interfaces.IC) ? b as interfaces.IC : 'null';
trace('b as interfaces.IC - null: ' + testObject.toString());
testObject = (b as interfaces.IF) ? b as interfaces.IF : 'null';
trace('b as interfaces.IF - [object ...]: ' + testObject.toString());
testObject = (this as IA) ? this as IA : 'null';
trace('this as interfaces.IA - [object ...]: ' + testObject.toString());
testObject = (this as IB) ? this as IB : 'null';
trace('this as interfaces.IB - null: ' + testObject.toString());
testObject = (this as IC) ? this as IC : 'null';
trace('this as interfaces.IC - [object ...]: ' + testObject.toString());
testObject = (this as ID) ? this as ID : 'null';
trace('this as interfaces.ID - [object ...]: ' + testObject.toString());
testObject = (this as IE) ? this as IE : 'null';
trace('this as interfaces.IE - [object ...]: ' + testObject.toString());
trace();
try {
testObject = Sprite(this);
trace('Sprite(this) - [object ...]: ' + testObject.toString());
} catch (e:Error)
{
trace("This shouldn't show!");
}
try {
testObject = B(this);
trace("This shouldn't show!");
} catch (e:Error)
{
trace('B(this) - exception expected: ' + e.message);
}
try {
testObject = interfaces.IC(b);
trace("This shouldn't show!");
} catch (e:Error)
{
trace('IC(b) - exception expected: ' + e.message);
}
try {
testObject = interfaces.IF(b);
trace('IF(b) - [object ...]: ' + testObject.toString());
} catch (e:Error)
{
trace("This shouldn't show!");
}
}
}
}
|
fix warnings in LanguageTest, changing 'insteadof' for 'is'
|
fix warnings in LanguageTest, changing 'insteadof' for 'is'
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
150865c3ee5ebcb158ceb7099972a18161c69148
|
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
|
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
|
// Editor debug icons
// to add new std debug icons just add IconType, IconsTypesMaterials and ComponentTypes items
enum IconsTypes
{
ICON_POINT_LIGHT = 0,
ICON_SPOT_LIGHT,
ICON_DIRECTIONAL_LIGHT,
ICON_CAMERA,
ICON_SOUND_SOURCE,
ICON_SOUND_SOURCE_3D,
ICON_SOUND_LISTENERS,
ICON_ZONE,
ICON_SPLINE_PATH,
ICON_TRIGGER,
ICON_CUSTOM_GEOMETRY,
ICON_PARTICLE_EMITTER,
ICON_COUNT
}
enum IconsColorType
{
ICON_COLOR_DEFAULT = 0,
ICON_COLOR_SPLINE_PATH_BEGIN,
ICON_COLOR_SPLINE_PATH_END
}
Array<Color> debugIconsColors = { Color(1,1,1) , Color(1,1,0), Color(0,1,0) };
Array<String> IconsTypesMaterials = {"DebugIconPointLight.xml",
"DebugIconSpotLight.xml",
"DebugIconLight.xml",
"DebugIconCamera.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundListener.xml",
"DebugIconZone.xml",
"DebugIconSplinePathPoint.xml",
"DebugIconCollisionTrigger.xml",
"DebugIconCustomGeometry.xml",
"DebugIconParticleEmitter.xml"};
Array<String> ComponentTypes = {"Light",
"Light",
"Light",
"Camera",
"SoundSource",
"SoundSource3D",
"SoundListener",
"Zone",
"SplinePath",
"RigidBody",
"CustomGeometry",
"ParticleEmitter"};
Array<BillboardSet@> debugIconsSet(ICON_COUNT);
Node@ debugIconsNode = null;
int stepDebugIconsUpdate = 100; //ms
int timeToNextDebugIconsUpdate = 0;
int stepDebugIconsUpdateSplinePath = 1000; //ms
int timeToNextDebugIconsUpdateSplinePath = 0;
const int splinePathResolution = 16;
const float splineStep = 1.0f / splinePathResolution;
bool debugIconsShow = true;
Vector2 debugIconsSize = Vector2(0.025, 0.025);
Vector2 debugIconsSizeSmall = debugIconsSize / 1.5;
Vector2 debugIconsSizeBig = debugIconsSize * 1.5;
Vector2 debugIconsMaxSize = debugIconsSize * 50;
VariantMap debugIconsPlacement;
const int debugIconsPlacementIndent = 1.0;
const float debugIconsOrthoDistance = 15.0f;
Vector2 Max(Vector2 a, Vector2 b)
{
return (a.length > b.length ? a : b);
}
Vector2 Clamp(Vector2 a, Vector2 b)
{
return Vector2((a.x > b.x ? b.x : a.x),(a.y > b.y ? b.y : a.y));
}
Vector2 ClampToIconMaxSize(Vector2 a)
{
return Clamp(a, debugIconsMaxSize);
}
void CreateDebugIcons(Node@ tempNode)
{
if (editorScene is null) return;
debugIconsSet.Resize(ICON_COUNT);
for (int i = 0; i < ICON_COUNT; i++)
{
debugIconsSet[i] = tempNode.CreateComponent("BillboardSet");
debugIconsSet[i].material = cache.GetResource("Material", "Materials/Editor/" + IconsTypesMaterials[i]);
debugIconsSet[i].sorted = true;
debugIconsSet[i].temporary = true;
debugIconsSet[i].viewMask = 0x80000000;
}
}
void UpdateViewDebugIcons()
{
if (editorScene is null || timeToNextDebugIconsUpdate > time.systemTime) return;
debugIconsNode = editorScene.GetChild("DebugIconsContainer", true);
if (debugIconsNode is null)
{
debugIconsNode = editorScene.CreateChild("DebugIconsContainer", LOCAL);
debugIconsNode.temporary = true;
}
// Checkout if debugIconsNode do not have any BBS component, add all at once
BillboardSet@ isBSExist = debugIconsNode.GetComponent("BillboardSet");
if (isBSExist is null) CreateDebugIcons(debugIconsNode);
if (debugIconsSet[ICON_POINT_LIGHT] !is null)
{
for(int i=0; i < ICON_COUNT; i++)
debugIconsSet[i].enabled = debugIconsShow;
}
if (debugIconsShow == false) return;
Vector3 camPos = activeViewport.cameraNode.worldPosition;
bool isOrthographic = activeViewport.camera.orthographic;
debugIconsPlacement.Clear();
for(int iconType=0; iconType<ICON_COUNT; iconType++)
{
if(debugIconsSet[iconType] !is null)
{
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH && timeToNextDebugIconsUpdateSplinePath > time.systemTime) continue;
Array<Node@> nodes = editorScene.GetChildrenWithComponent(ComponentTypes[iconType], true);
// Clear old data
if(iconType == ICON_SPLINE_PATH)
ClearCommit(ICON_SPLINE_PATH, ICON_SPLINE_PATH+1, nodes.length * splinePathResolution);
else if(iconType==ICON_POINT_LIGHT || iconType==ICON_SPOT_LIGHT || iconType==ICON_DIRECTIONAL_LIGHT)
ClearCommit(ICON_POINT_LIGHT, ICON_DIRECTIONAL_LIGHT+1, nodes.length);
else if(iconType==ICON_SOUND_SOURCE || iconType==ICON_SOUND_SOURCE_3D)
ClearCommit(ICON_SOUND_SOURCE, ICON_SOUND_SOURCE_3D+1, nodes.length);
else
ClearCommit(iconType, iconType+1, nodes.length);
if(nodes.length > 0)
{
// Fill with new data
for(int i=0;i<nodes.length; i++)
{
Component@ component = nodes[i].GetComponent(ComponentTypes[iconType]);
if (component is null) continue;
Billboard@ bb = null;
Color finalIconColor = debugIconsColors[ICON_COLOR_DEFAULT];
float distance = (camPos - nodes[i].worldPosition).length;
if (isOrthographic) distance = debugIconsOrthoDistance;
int iconsOffset = debugIconsPlacement[StringHash(nodes[i].id)].GetInt();
float iconsYPos = 0;
if(iconType==ICON_SPLINE_PATH)
{
SplinePath@ sp = cast<SplinePath>(component);
if(sp !is null)
if(sp.length > 0.01f)
{
for(int step=0; step < splinePathResolution; step++)
{
int index = (i * splinePathResolution) + step;
Vector3 splinePoint = sp.GetPoint(splineStep * step);
Billboard@ bb = debugIconsSet[ICON_SPLINE_PATH].billboards[index];
float stepDistance = (camPos - splinePoint).length;
if (isOrthographic) stepDistance = debugIconsOrthoDistance;
if(step == 0) // SplinePath start
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_BEGIN];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else if((step+1) >= (splinePathResolution - splineStep)) // SplinePath end
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_END];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else // SplinePath middle points
{
bb.color = finalIconColor;
bb.size = ClampToIconMaxSize(Max(debugIconsSizeSmall * stepDistance, debugIconsSizeSmall));
bb.position = splinePoint;
}
bb.enabled = sp.enabled;
// Blend Icon relatively by distance to it
bb.color = Color(bb.color.r, bb.color.g, bb.color.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
if (bb.color.a < 0.25f) bb.enabled = false;
}
}
}
else
{
bb = debugIconsSet[iconType].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
if(iconType==ICON_PARTICLE_EMITTER)
{
bb.size = ClampToIconMaxSize(Max(debugIconsSizeBig * distance, debugIconsSizeBig));
}
else if (iconType==ICON_TRIGGER)
{
RigidBody@ rigidbody = cast<RigidBody>(component);
if (rigidbody !is null)
{
if (rigidbody.trigger == false) continue;
}
}
else if (iconType==ICON_POINT_LIGHT || iconType==ICON_SPOT_LIGHT || iconType==ICON_DIRECTIONAL_LIGHT)
{
Light@ light = cast<Light>(component);
if(light !is null)
{
if(light.lightType == LIGHT_POINT)
bb = debugIconsSet[ICON_POINT_LIGHT].billboards[i];
else if(light.lightType == LIGHT_DIRECTIONAL)
bb = debugIconsSet[ICON_DIRECTIONAL_LIGHT].billboards[i];
else if(light.lightType == LIGHT_SPOT)
bb = debugIconsSet[ICON_SPOT_LIGHT].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
finalIconColor = light.effectiveColor;
}
}
bb.position = nodes[i].worldPosition;
// Blend Icon relatively by distance to it
bb.color = Color(finalIconColor.r, finalIconColor.g, finalIconColor.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
bb.enabled = component.enabled;
// Discard billboard if it almost transparent
if (bb.color.a < 0.25f) bb.enabled = false;
IncrementIconPlacement(bb.enabled, nodes[i], 1 );
}
}
Commit(iconType, iconType+1);
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH) timeToNextDebugIconsUpdateSplinePath = time.systemTime + stepDebugIconsUpdateSplinePath;
}
}
}
timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate;
}
void ClearCommit(int begin, int end, int newlength)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].numBillboards = 0;
debugIconsSet[i].Commit();
debugIconsSet[i].numBillboards = newlength;
}
}
void Commit(int begin, int end)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].Commit();
}
}
void IncrementIconPlacement(bool componentEnabled, Node@ node, int offset)
{
if(componentEnabled == true)
{
int oldPlacement = debugIconsPlacement[StringHash(node.id)].GetInt();
debugIconsPlacement[StringHash(node.id)] = Variant(oldPlacement + offset);
}
}
|
// Editor debug icons
// to add new std debug icons just add IconType, IconsTypesMaterials and ComponentTypes items
enum IconsTypes
{
ICON_POINT_LIGHT = 0,
ICON_SPOT_LIGHT,
ICON_DIRECTIONAL_LIGHT,
ICON_CAMERA,
ICON_SOUND_SOURCE,
ICON_SOUND_SOURCE_3D,
ICON_SOUND_LISTENERS,
ICON_ZONE,
ICON_SPLINE_PATH,
ICON_TRIGGER,
ICON_CUSTOM_GEOMETRY,
ICON_PARTICLE_EMITTER,
ICON_COUNT
}
enum IconsColorType
{
ICON_COLOR_DEFAULT = 0,
ICON_COLOR_SPLINE_PATH_BEGIN,
ICON_COLOR_SPLINE_PATH_END
}
Array<Color> debugIconsColors = { Color(1,1,1) , Color(1,1,0), Color(0,1,0) };
Array<String> IconsTypesMaterials = {"DebugIconPointLight.xml",
"DebugIconSpotLight.xml",
"DebugIconLight.xml",
"DebugIconCamera.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundSource.xml",
"DebugIconSoundListener.xml",
"DebugIconZone.xml",
"DebugIconSplinePathPoint.xml",
"DebugIconCollisionTrigger.xml",
"DebugIconCustomGeometry.xml",
"DebugIconParticleEmitter.xml"};
Array<String> ComponentTypes = {"Light",
"Light",
"Light",
"Camera",
"SoundSource",
"SoundSource3D",
"SoundListener",
"Zone",
"SplinePath",
"RigidBody",
"CustomGeometry",
"ParticleEmitter"};
Array<BillboardSet@> debugIconsSet(ICON_COUNT);
Node@ debugIconsNode = null;
int stepDebugIconsUpdate = 100; //ms
int timeToNextDebugIconsUpdate = 0;
int stepDebugIconsUpdateSplinePath = 1000; //ms
int timeToNextDebugIconsUpdateSplinePath = 0;
const int splinePathResolution = 16;
const float splineStep = 1.0f / splinePathResolution;
bool debugIconsShow = true;
Vector2 debugIconsSize = Vector2(0.015, 0.015);
Vector2 debugIconsSizeSmall = debugIconsSize / 1.5;
Vector2 debugIconsSizeBig = debugIconsSize * 1.5;
Vector2 debugIconsMaxSize = debugIconsSize * 50;
VariantMap debugIconsPlacement;
const int debugIconsPlacementIndent = 1.0;
const float debugIconsOrthoDistance = 15.0f;
Vector2 Max(Vector2 a, Vector2 b)
{
return (a.length > b.length ? a : b);
}
Vector2 Clamp(Vector2 a, Vector2 b)
{
return Vector2((a.x > b.x ? b.x : a.x),(a.y > b.y ? b.y : a.y));
}
Vector2 ClampToIconMaxSize(Vector2 a)
{
return Clamp(a, debugIconsMaxSize);
}
void CreateDebugIcons(Node@ tempNode)
{
if (editorScene is null) return;
debugIconsSet.Resize(ICON_COUNT);
for (int i = 0; i < ICON_COUNT; i++)
{
debugIconsSet[i] = tempNode.CreateComponent("BillboardSet");
debugIconsSet[i].material = cache.GetResource("Material", "Materials/Editor/" + IconsTypesMaterials[i]);
debugIconsSet[i].sorted = true;
debugIconsSet[i].temporary = true;
debugIconsSet[i].viewMask = 0x80000000;
}
}
void UpdateViewDebugIcons()
{
if (editorScene is null || timeToNextDebugIconsUpdate > time.systemTime) return;
debugIconsNode = editorScene.GetChild("DebugIconsContainer", true);
if (debugIconsNode is null)
{
debugIconsNode = editorScene.CreateChild("DebugIconsContainer", LOCAL);
debugIconsNode.temporary = true;
}
// Checkout if debugIconsNode do not have any BBS component, add all at once
BillboardSet@ isBSExist = debugIconsNode.GetComponent("BillboardSet");
if (isBSExist is null) CreateDebugIcons(debugIconsNode);
if (debugIconsSet[ICON_POINT_LIGHT] !is null)
{
for(int i=0; i < ICON_COUNT; i++)
debugIconsSet[i].enabled = debugIconsShow;
}
if (debugIconsShow == false) return;
Vector3 camPos = activeViewport.cameraNode.worldPosition;
bool isOrthographic = activeViewport.camera.orthographic;
debugIconsPlacement.Clear();
for(int iconType=0; iconType<ICON_COUNT; iconType++)
{
if(debugIconsSet[iconType] !is null)
{
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH && timeToNextDebugIconsUpdateSplinePath > time.systemTime) continue;
Array<Node@> nodes = editorScene.GetChildrenWithComponent(ComponentTypes[iconType], true);
// Clear old data
if(iconType == ICON_SPLINE_PATH)
ClearCommit(ICON_SPLINE_PATH, ICON_SPLINE_PATH+1, nodes.length * splinePathResolution);
else if(iconType==ICON_POINT_LIGHT || iconType==ICON_SPOT_LIGHT || iconType==ICON_DIRECTIONAL_LIGHT)
ClearCommit(ICON_POINT_LIGHT, ICON_DIRECTIONAL_LIGHT+1, nodes.length);
else if(iconType==ICON_SOUND_SOURCE || iconType==ICON_SOUND_SOURCE_3D)
ClearCommit(ICON_SOUND_SOURCE, ICON_SOUND_SOURCE_3D+1, nodes.length);
else
ClearCommit(iconType, iconType+1, nodes.length);
if(nodes.length > 0)
{
// Fill with new data
for(int i=0;i<nodes.length; i++)
{
Component@ component = nodes[i].GetComponent(ComponentTypes[iconType]);
if (component is null) continue;
Billboard@ bb = null;
Color finalIconColor = debugIconsColors[ICON_COLOR_DEFAULT];
float distance = (camPos - nodes[i].worldPosition).length;
if (isOrthographic) distance = debugIconsOrthoDistance;
int iconsOffset = debugIconsPlacement[StringHash(nodes[i].id)].GetInt();
float iconsYPos = 0;
if(iconType==ICON_SPLINE_PATH)
{
SplinePath@ sp = cast<SplinePath>(component);
if(sp !is null)
if(sp.length > 0.01f)
{
for(int step=0; step < splinePathResolution; step++)
{
int index = (i * splinePathResolution) + step;
Vector3 splinePoint = sp.GetPoint(splineStep * step);
Billboard@ bb = debugIconsSet[ICON_SPLINE_PATH].billboards[index];
float stepDistance = (camPos - splinePoint).length;
if (isOrthographic) stepDistance = debugIconsOrthoDistance;
if(step == 0) // SplinePath start
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_BEGIN];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else if((step+1) >= (splinePathResolution - splineStep)) // SplinePath end
{
bb.color = debugIconsColors[ICON_COLOR_SPLINE_PATH_END];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * stepDistance, debugIconsSize));
bb.position = splinePoint;
}
else // SplinePath middle points
{
bb.color = finalIconColor;
bb.size = ClampToIconMaxSize(Max(debugIconsSizeSmall * stepDistance, debugIconsSizeSmall));
bb.position = splinePoint;
}
bb.enabled = sp.enabled;
// Blend Icon relatively by distance to it
bb.color = Color(bb.color.r, bb.color.g, bb.color.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
if (bb.color.a < 0.25f) bb.enabled = false;
}
}
}
else
{
bb = debugIconsSet[iconType].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
if(iconType==ICON_PARTICLE_EMITTER)
{
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
}
else if (iconType==ICON_TRIGGER)
{
RigidBody@ rigidbody = cast<RigidBody>(component);
if (rigidbody !is null)
{
if (rigidbody.trigger == false) continue;
}
}
else if (iconType==ICON_POINT_LIGHT || iconType==ICON_SPOT_LIGHT || iconType==ICON_DIRECTIONAL_LIGHT)
{
Light@ light = cast<Light>(component);
if(light !is null)
{
if(light.lightType == LIGHT_POINT)
bb = debugIconsSet[ICON_POINT_LIGHT].billboards[i];
else if(light.lightType == LIGHT_DIRECTIONAL)
bb = debugIconsSet[ICON_DIRECTIONAL_LIGHT].billboards[i];
else if(light.lightType == LIGHT_SPOT)
bb = debugIconsSet[ICON_SPOT_LIGHT].billboards[i];
bb.size = ClampToIconMaxSize(Max(debugIconsSize * distance, debugIconsSize));
finalIconColor = light.effectiveColor;
}
}
bb.position = nodes[i].worldPosition;
// Blend Icon relatively by distance to it
bb.color = Color(finalIconColor.r, finalIconColor.g, finalIconColor.b, 1.2f - 1.0f / (debugIconsMaxSize.x / bb.size.x));
bb.enabled = component.enabled;
// Discard billboard if it almost transparent
if (bb.color.a < 0.25f) bb.enabled = false;
IncrementIconPlacement(bb.enabled, nodes[i], 1 );
}
}
Commit(iconType, iconType+1);
// SplinePath update resolution
if(iconType == ICON_SPLINE_PATH) timeToNextDebugIconsUpdateSplinePath = time.systemTime + stepDebugIconsUpdateSplinePath;
}
}
}
timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate;
}
void ClearCommit(int begin, int end, int newlength)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].numBillboards = 0;
debugIconsSet[i].Commit();
debugIconsSet[i].numBillboards = newlength;
}
}
void Commit(int begin, int end)
{
for(int i=begin;i<end;i++)
{
debugIconsSet[i].Commit();
}
}
void IncrementIconPlacement(bool componentEnabled, Node@ node, int offset)
{
if(componentEnabled == true)
{
int oldPlacement = debugIconsPlacement[StringHash(node.id)].GetInt();
debugIconsPlacement[StringHash(node.id)] = Variant(oldPlacement + offset);
}
}
|
change icons default size
|
change icons default size
|
ActionScript
|
mit
|
fire/Urho3D-1,PredatorMF/Urho3D,carnalis/Urho3D,codedash64/Urho3D,victorholt/Urho3D,MeshGeometry/Urho3D,c4augustus/Urho3D,c4augustus/Urho3D,kostik1337/Urho3D,victorholt/Urho3D,henu/Urho3D,tommy3/Urho3D,codemon66/Urho3D,rokups/Urho3D,abdllhbyrktr/Urho3D,SirNate0/Urho3D,urho3d/Urho3D,iainmerrick/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,MonkeyFirst/Urho3D,iainmerrick/Urho3D,299299/Urho3D,rokups/Urho3D,helingping/Urho3D,iainmerrick/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,helingping/Urho3D,cosmy1/Urho3D,abdllhbyrktr/Urho3D,codemon66/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,orefkov/Urho3D,PredatorMF/Urho3D,victorholt/Urho3D,kostik1337/Urho3D,codedash64/Urho3D,iainmerrick/Urho3D,luveti/Urho3D,fire/Urho3D-1,helingping/Urho3D,c4augustus/Urho3D,SirNate0/Urho3D,luveti/Urho3D,carnalis/Urho3D,carnalis/Urho3D,orefkov/Urho3D,xiliu98/Urho3D,MeshGeometry/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,MeshGeometry/Urho3D,PredatorMF/Urho3D,abdllhbyrktr/Urho3D,cosmy1/Urho3D,urho3d/Urho3D,helingping/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,luveti/Urho3D,iainmerrick/Urho3D,MonkeyFirst/Urho3D,henu/Urho3D,weitjong/Urho3D,urho3d/Urho3D,codemon66/Urho3D,urho3d/Urho3D,codemon66/Urho3D,SirNate0/Urho3D,299299/Urho3D,cosmy1/Urho3D,codedash64/Urho3D,codemon66/Urho3D,rokups/Urho3D,tommy3/Urho3D,weitjong/Urho3D,weitjong/Urho3D,SuperWangKai/Urho3D,abdllhbyrktr/Urho3D,tommy3/Urho3D,rokups/Urho3D,henu/Urho3D,helingping/Urho3D,abdllhbyrktr/Urho3D,299299/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,tommy3/Urho3D,xiliu98/Urho3D,299299/Urho3D,victorholt/Urho3D,eugeneko/Urho3D,victorholt/Urho3D,c4augustus/Urho3D,luveti/Urho3D,tommy3/Urho3D,bacsmar/Urho3D,299299/Urho3D,xiliu98/Urho3D,luveti/Urho3D,SuperWangKai/Urho3D,xiliu98/Urho3D,SirNate0/Urho3D,eugeneko/Urho3D,MonkeyFirst/Urho3D,MeshGeometry/Urho3D,weitjong/Urho3D,c4augustus/Urho3D,PredatorMF/Urho3D,fire/Urho3D-1,MeshGeometry/Urho3D,kostik1337/Urho3D,299299/Urho3D,eugeneko/Urho3D,weitjong/Urho3D,orefkov/Urho3D,eugeneko/Urho3D,henu/Urho3D,fire/Urho3D-1,bacsmar/Urho3D,carnalis/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,codedash64/Urho3D,henu/Urho3D,SirNate0/Urho3D
|
d3808c690f4215adb737c6ae622ef32b2f1141d6
|
actionscript/src/com/freshplanet/ane/AirDatePicker/AirDatePicker.as
|
actionscript/src/com/freshplanet/ane/AirDatePicker/AirDatePicker.as
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// 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 com.freshplanet.ane.AirDatePicker
{
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.geom.Rectangle;
import flash.system.Capabilities;
public class AirDatePicker extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const EVENT_CHANGE:String = "CHANGE";
public static const EVENT_UPDATE:String = "UPDATE";
/** AirDatePicker is supported on iOS and Android devices. */
public static function get isSupported() : Boolean
{
return Capabilities.manufacturer.indexOf("iOS") != -1 || Capabilities.manufacturer.indexOf("Android") != -1;
}
public function AirDatePicker()
{
if (!_instance)
{
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
{
throw Error("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
_instance = this;
}
else
{
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
}
}
public static function getInstance() : AirDatePicker
{
return _instance ? _instance : new AirDatePicker();
}
/**
* Display a Date (month, day, year) picker, using a Native implementation.<br><br>
*
* For Apple devices we rely on the iOS SDK's UIDatePicker. For Android, we rely on a DialogFragment
* containing a custom DatePickerDialog.<br><br>
*
* Android devices should define the DatePickerActivity's theme as @android:style/Theme.Holo.Dialog to
* present the Activity as a true Dialog. <br><br>
*
* @param date An AS3 Date object used to show a certain date by default in the picker.
* @param callback A callback function of the folllowing form:
* <code>function myCallback( selectedDate : String ): void</code>. The <code>selectedDate</code> parameter
* will contain the selected date in the following format: <code>yyyy-mm-dd</code>
* @param anchor (optional) On the iPad, the UIDatePicker is displayed in a popover that
* doesn't cover the whole screen. This parameter is the anchor from which the
* popover will be presented. For example, it could be the bounds of the button
* on which the user clicked to display the image picker. Note that you should
* use absolute stage coordinates. Example: <code>var anchor:Rectangle =
* myButton.getBounds(stage);</code>
*
* @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Date.html
* @see http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDatePicker_Class/Reference/UIDatePicker.html
* @see http://developer.apple.com/library/ios/#documentation/uikit/reference/UIPopoverController_class/Reference/Reference.html
* @see http://developer.android.com/reference/android/app/DatePickerDialog.html
* @see http://developer.android.com/guide/topics/ui/controls/pickers.html
* @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Date.html
*
**/
public function displayDatePicker( date : Date, callback : Function, anchor : Rectangle = null ) : void
{
if (!isSupported) return;
_callback = callback;
var month : Number = date.month + 1; // as3 date: january[0], ..., december[11]
if (anchor != null)
{
_context.call("AirDatePickerDisplayDatePicker", date.fullYear.toString(), month.toString(), date.date.toString(), anchor);
}
else
{
_context.call("AirDatePickerDisplayDatePicker", date.fullYear.toString(), month.toString(), date.date.toString());
}
}
/** Dismisses the DatePicker from the screen. */
public function removeDatePicker( ) : void
{
if (!isSupported) return;
_context.call("AirDatePickerRemoveDatePicker");
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID : String = "com.freshplanet.AirDatePicker";
private static var _instance : AirDatePicker;
private var _context : ExtensionContext;
private var _callback : Function = null;
private function onStatus( event : StatusEvent ) : void
{
if (event.code == EVENT_CHANGE)
{
if (_callback !== null)
{
var newDate : String = event.level as String;
trace("[AirDatePicker] new date from Native Extension : ",newDate);
_callback(newDate);
}
else
{
trace("Error: There is no callback, cannot return the picked date");
}
}
if(this.hasEventListener(StatusEvent.STATUS))
{
this.dispatchEvent(event);
}
}
}
}
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// 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 com.freshplanet.ane.AirDatePicker
{
import flash.events.EventDispatcher;
import flash.events.StatusEvent;
import flash.external.ExtensionContext;
import flash.geom.Rectangle;
import flash.system.Capabilities;
public class AirDatePicker extends EventDispatcher
{
// --------------------------------------------------------------------------------------//
// //
// PUBLIC API //
// //
// --------------------------------------------------------------------------------------//
public static const EVENT_CHANGE:String = "CHANGE";
public static const EVENT_UPDATE:String = "UPDATE";
private var _minimumDate:Date;
private var _maximumDate:Date;
/** AirDatePicker is supported on iOS and Android devices. */
public static function get isSupported() : Boolean
{
return Capabilities.manufacturer.indexOf("iOS") != -1 || Capabilities.manufacturer.indexOf("Android") != -1;
}
public function AirDatePicker()
{
if (!_instance)
{
_context = ExtensionContext.createExtensionContext(EXTENSION_ID, null);
if (!_context)
{
throw Error("ERROR - Extension context is null. Please check if extension.xml is setup correctly.");
return;
}
_context.addEventListener(StatusEvent.STATUS, onStatus);
_instance = this;
}
else
{
throw Error("This is a singleton, use getInstance(), do not call the constructor directly.");
}
}
public static function getInstance() : AirDatePicker
{
return _instance ? _instance : new AirDatePicker();
}
/**
* Display a Date (month, day, year) picker, using a Native implementation.<br><br>
*
* For Apple devices we rely on the iOS SDK's UIDatePicker. For Android, we rely on a DialogFragment
* containing a custom DatePickerDialog.<br><br>
*
* Android devices should define the DatePickerActivity's theme as @android:style/Theme.Holo.Dialog to
* present the Activity as a true Dialog. <br><br>
*
* @param date An AS3 Date object used to show a certain date by default in the picker.
* @param callback A callback function of the folllowing form:
* <code>function myCallback( selectedDate : String ): void</code>. The <code>selectedDate</code> parameter
* will contain the selected date in the following format: <code>yyyy-mm-dd</code>
* @param anchor (optional) On the iPad, the UIDatePicker is displayed in a popover that
* doesn't cover the whole screen. This parameter is the anchor from which the
* popover will be presented. For example, it could be the bounds of the button
* on which the user clicked to display the image picker. Note that you should
* use absolute stage coordinates. Example: <code>var anchor:Rectangle =
* myButton.getBounds(stage);</code>
*
* @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Date.html
* @see http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDatePicker_Class/Reference/UIDatePicker.html
* @see http://developer.apple.com/library/ios/#documentation/uikit/reference/UIPopoverController_class/Reference/Reference.html
* @see http://developer.android.com/reference/android/app/DatePickerDialog.html
* @see http://developer.android.com/guide/topics/ui/controls/pickers.html
* @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Date.html
*
**/
public function displayDatePicker( date : Date, callback : Function, anchor : Rectangle = null ) : void
{
if (!isSupported) return;
_callback = callback;
var month : Number = date.month + 1; // as3 date: january[0], ..., december[11]
if (anchor != null)
{
_context.call("AirDatePickerDisplayDatePicker", date.fullYear.toString(), month.toString(), date.date.toString(), anchor);
}
else
{
_context.call("AirDatePickerDisplayDatePicker", date.fullYear.toString(), month.toString(), date.date.toString());
}
}
public function setMinimumDate( date:Date ) : void
{
_context.call("setMinimumDate", date);
}
public function setMaximumDate( date:Date ) : void
{
_context.call("setMaximumDate", date);
}
/** Dismisses the DatePicker from the screen. */
public function removeDatePicker( ) : void
{
if (!isSupported) return;
_context.call("AirDatePickerRemoveDatePicker");
}
// --------------------------------------------------------------------------------------//
// //
// PRIVATE API //
// //
// --------------------------------------------------------------------------------------//
private static const EXTENSION_ID : String = "com.freshplanet.AirDatePicker";
private static var _instance : AirDatePicker;
private var _context : ExtensionContext;
private var _callback : Function = null;
private function onStatus( event : StatusEvent ) : void
{
if (event.code == EVENT_CHANGE)
{
if (_callback !== null)
{
var newDate : String = event.level as String;
trace("[AirDatePicker] new date from Native Extension : ",newDate);
_callback(newDate);
}
else
{
trace("Error: There is no callback, cannot return the picked date");
}
}
if(this.hasEventListener(StatusEvent.STATUS))
{
this.dispatchEvent(event);
}
}
}
}
|
add functions to as
|
add functions to as
|
ActionScript
|
apache-2.0
|
freshplanet/ANE-DatePicker,freshplanet/ANE-DatePicker,IngweLand/ANE-DatePicker,IngweLand/ANE-DatePicker
|
40515e3dfea91f745305c65b5d9f44a2731bde4c
|
src/swf2png.as
|
src/swf2png.as
|
package
{
import com.adobe.images.PNGEncoder;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var outfield:TextField;
private var outputDirPath:String;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
stage.addChild(outfield);
stage.frameRate = 12;
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
outfield.appendText("\nLoading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
loadedSwf = MovieClip(ev.target.content);
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
outfield.appendText("\nLoaded!");
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
totalFrames = loadedSwf.totalFrames;
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
//Called for every frame
private function step(ev:TimerEvent):void {
goToFrame(loadedSwf, counter);
saveFrame();
counter++;
if(counter > totalFrames) {
timer.stop();
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
bitmapData.draw(loader);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var outfileName:String = outputDirPath + File.separator + prefix + counter + ".png"
var file:File = new File(outfileName);
outfield.appendText("\nPrefix: " + prefix);
outfield.appendText("\nWriting: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matches:Array = inputFileName.match(/([a-zA-Z0-9_\-\+\.]*?)\.swf$/);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1];
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
outfield.appendText("\nInput file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
outfield.appendText("\ninpt: " + d.nativePath);
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
if(ev.arguments.length) {
d = new File(ev.arguments[0]);
d = d.resolvePath('..');
return d.nativePath;
}
else {
return File.desktopDirectory.nativePath;
}
}
else {
outfield.appendText("\ncwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
outfield.appendText("\nInput file: " + inputFilePath);
outfield.appendText("\nOutput directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
NativeApplication.nativeApplication.exit(code);
}
}
}
|
package
{
import com.adobe.images.PNGEncoder;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var outfield:TextField;
private var outputDirPath:String;
private var offsetMatrix:Matrix;
private var bBox:Rectangle;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
stage.addChild(outfield);
stage.frameRate = 12;
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
outfield.appendText("\nLoading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
loadedSwf = MovieClip(ev.target.content);
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
outfield.appendText("\nLoaded!");
totalFrames = loadedSwf.totalFrames;
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function calculateBBox():void {
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
var boundsArray:Object = {
"x" : new Array(),
"y" : new Array(),
"w" : new Array(),
"h" : new Array()
}
var r:Rectangle;
for(var currentFrame:int = 0; currentFrame < totalFrames; currentFrame++) {
goToFrame(loadedSwf, currentFrame);
r = loader.content.getRect(stage);
boundsArray.x.push(r.x);
boundsArray.y.push(r.y);
boundsArray.w.push(r.width);
boundsArray.h.push(r.height);
}
boundsArray.x.sort(Array.NUMERIC);
boundsArray.y.sort(Array.NUMERIC);
boundsArray.w.sort(Array.NUMERIC | Array.DESCENDING);
boundsArray.h.sort(Array.NUMERIC | Array.DESCENDING);
bBox = new Rectangle(
Math.floor(boundsArray.x[0]),
Math.floor(boundsArray.y[0]),
Math.ceil(boundsArray.w[0]),
Math.ceil(boundsArray.h[0])
);
outfield.appendText("\nBounding box: " + bBox)
outputWidth = bBox.width;
outputHeight = bBox.height;
offsetMatrix = new Matrix();
offsetMatrix.translate(bBox.x * -1, bBox.y * -1);
return;
}
//Called for every frame
private function step(ev:TimerEvent):void {
goToFrame(loadedSwf, counter);
saveFrame();
counter++;
if(counter > totalFrames) {
timer.stop();
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
bitmapData.draw(loader.content, offsetMatrix);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var outfileName:String = outputDirPath + File.separator + prefix + counter + ".png"
var file:File = new File(outfileName);
outfield.appendText("\nPrefix: " + prefix);
outfield.appendText("\nWriting: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matches:Array = inputFileName.match(/([a-zA-Z0-9_\-\+\.]*?)\.swf$/);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1];
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
outfield.appendText("\nInput file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
outfield.appendText("\ninpt: " + d.nativePath);
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
if(ev.arguments.length) {
d = new File(ev.arguments[0]);
d = d.resolvePath('..');
return d.nativePath;
}
else {
return File.desktopDirectory.nativePath;
}
}
else {
outfield.appendText("\ncwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
outfield.appendText("\nInput file: " + inputFilePath);
outfield.appendText("\nOutput directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
NativeApplication.nativeApplication.exit(code);
}
}
}
|
Adjust output size and positioning after content.
|
Adjust output size and positioning after content.
The output size is now adjusted after the content size, which stops content from being incorrectly cropped.
|
ActionScript
|
mit
|
mdahlstrand/swf2png
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.